]> BookStack Code Mirror - bookstack/blob - app/Access/Saml2Service.php
SAML2: Included parsed groups in dump data
[bookstack] / app / Access / Saml2Service.php
1 <?php
2
3 namespace BookStack\Access;
4
5 use BookStack\Exceptions\JsonDebugException;
6 use BookStack\Exceptions\SamlException;
7 use BookStack\Exceptions\StoppedAuthenticationException;
8 use BookStack\Exceptions\UserRegistrationException;
9 use BookStack\Users\Models\User;
10 use Exception;
11 use OneLogin\Saml2\Auth;
12 use OneLogin\Saml2\Constants;
13 use OneLogin\Saml2\Error;
14 use OneLogin\Saml2\IdPMetadataParser;
15 use OneLogin\Saml2\ValidationError;
16
17 /**
18  * Class Saml2Service
19  * Handles any app-specific SAML tasks.
20  */
21 class Saml2Service
22 {
23     protected array $config;
24
25     public function __construct(
26         protected RegistrationService $registrationService,
27         protected LoginService $loginService,
28         protected GroupSyncService $groupSyncService
29     ) {
30         $this->config = config('saml2');
31     }
32
33     /**
34      * Initiate a login flow.
35      *
36      * @throws Error
37      */
38     public function login(): array
39     {
40         $toolKit = $this->getToolkit();
41         $returnRoute = url('/saml2/acs');
42
43         return [
44             'url' => $toolKit->login($returnRoute, [], false, false, true),
45             'id'  => $toolKit->getLastRequestID(),
46         ];
47     }
48
49     /**
50      * Initiate a logout flow.
51      *
52      * @throws Error
53      */
54     public function logout(User $user): array
55     {
56         $toolKit = $this->getToolkit();
57         $returnRoute = url('/');
58
59         try {
60             $url = $toolKit->logout(
61                 $returnRoute,
62                 [],
63                 $user->email,
64                 session()->get('saml2_session_index'),
65                 true,
66                 Constants::NAMEID_EMAIL_ADDRESS
67             );
68             $id = $toolKit->getLastRequestID();
69         } catch (Error $error) {
70             if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
71                 throw $error;
72             }
73
74             $this->actionLogout();
75             $url = '/';
76             $id = null;
77         }
78
79         return ['url' => $url, 'id' => $id];
80     }
81
82     /**
83      * Process the ACS response from the idp and return the
84      * matching, or new if registration active, user matched to the idp.
85      * Returns null if not authenticated.
86      *
87      * @throws Error
88      * @throws SamlException
89      * @throws ValidationError
90      * @throws JsonDebugException
91      * @throws UserRegistrationException
92      */
93     public function processAcsResponse(?string $requestId, string $samlResponse): ?User
94     {
95         // The SAML2 toolkit expects the response to be within the $_POST superglobal
96         // so we need to manually put it back there at this point.
97         $_POST['SAMLResponse'] = $samlResponse;
98         $toolkit = $this->getToolkit();
99         $toolkit->processResponse($requestId);
100         $errors = $toolkit->getErrors();
101
102         if (!empty($errors)) {
103             $reason = $toolkit->getLastErrorReason();
104             $message = 'Invalid ACS Response; Errors: ' . implode(', ', $errors);
105             $message .= $reason ? "; Reason: {$reason}" : '';
106             throw new Error($message);
107         }
108
109         if (!$toolkit->isAuthenticated()) {
110             return null;
111         }
112
113         $attrs = $toolkit->getAttributes();
114         $id = $toolkit->getNameId();
115         session()->put('saml2_session_index', $toolkit->getSessionIndex());
116
117         return $this->processLoginCallback($id, $attrs);
118     }
119
120     /**
121      * Process a response for the single logout service.
122      *
123      * @throws Error
124      */
125     public function processSlsResponse(?string $requestId): ?string
126     {
127         $toolkit = $this->getToolkit();
128
129         // The $retrieveParametersFromServer in the call below will mean the library will take the query
130         // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
131         // value so that the exact encoding format is matched when checking the signature.
132         // This is primarily due to ADFS encoding query params with lowercase percent encoding while
133         // PHP (And most other sensible providers) standardise on uppercase.
134         $redirect = $toolkit->processSLO(true, $requestId, true, null, true);
135         $errors = $toolkit->getErrors();
136
137         if (!empty($errors)) {
138             throw new Error(
139                 'Invalid SLS Response: ' . implode(', ', $errors)
140             );
141         }
142
143         $this->actionLogout();
144
145         return $redirect;
146     }
147
148     /**
149      * Do the required actions to log a user out.
150      */
151     protected function actionLogout()
152     {
153         auth()->logout();
154         session()->invalidate();
155     }
156
157     /**
158      * Get the metadata for this service provider.
159      *
160      * @throws Error
161      */
162     public function metadata(): string
163     {
164         $toolKit = $this->getToolkit(true);
165         $settings = $toolKit->getSettings();
166         $metadata = $settings->getSPMetadata();
167         $errors = $settings->validateMetadata($metadata);
168
169         if (!empty($errors)) {
170             throw new Error(
171                 'Invalid SP metadata: ' . implode(', ', $errors),
172                 Error::METADATA_SP_INVALID
173             );
174         }
175
176         return $metadata;
177     }
178
179     /**
180      * Load the underlying Onelogin SAML2 toolkit.
181      *
182      * @throws Error
183      * @throws Exception
184      */
185     protected function getToolkit(bool $spOnly = false): Auth
186     {
187         $settings = $this->config['onelogin'];
188         $overrides = $this->config['onelogin_overrides'] ?? [];
189
190         if ($overrides && is_string($overrides)) {
191             $overrides = json_decode($overrides, true);
192         }
193
194         $metaDataSettings = [];
195         if (!$spOnly && $this->config['autoload_from_metadata']) {
196             $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
197         }
198
199         $spSettings = $this->loadOneloginServiceProviderDetails();
200         $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
201
202         return new Auth($settings, $spOnly);
203     }
204
205     /**
206      * Load dynamic service provider options required by the onelogin toolkit.
207      */
208     protected function loadOneloginServiceProviderDetails(): array
209     {
210         $spDetails = [
211             'entityId'                 => url('/saml2/metadata'),
212             'assertionConsumerService' => [
213                 'url' => url('/saml2/acs'),
214             ],
215             'singleLogoutService' => [
216                 'url' => url('/saml2/sls'),
217             ],
218         ];
219
220         return [
221             'baseurl' => url('/saml2'),
222             'sp'      => $spDetails,
223         ];
224     }
225
226     /**
227      * Check if groups should be synced.
228      */
229     protected function shouldSyncGroups(): bool
230     {
231         return $this->config['user_to_groups'] !== false;
232     }
233
234     /**
235      * Calculate the display name.
236      */
237     protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
238     {
239         $displayNameAttr = $this->config['display_name_attributes'];
240
241         $displayName = [];
242         foreach ($displayNameAttr as $dnAttr) {
243             $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
244             if ($dnComponent !== null) {
245                 $displayName[] = $dnComponent;
246             }
247         }
248
249         if (count($displayName) == 0) {
250             $displayName = $defaultValue;
251         } else {
252             $displayName = implode(' ', $displayName);
253         }
254
255         return $displayName;
256     }
257
258     /**
259      * Get the value to use as the external id saved in BookStack
260      * used to link the user to an existing BookStack DB user.
261      */
262     protected function getExternalId(array $samlAttributes, string $defaultValue)
263     {
264         $userNameAttr = $this->config['external_id_attribute'];
265         if ($userNameAttr === null) {
266             return $defaultValue;
267         }
268
269         return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
270     }
271
272     /**
273      * Extract the details of a user from a SAML response.
274      *
275      * @return array{external_id: string, name: string, email: string, saml_id: string}
276      */
277     protected function getUserDetails(string $samlID, $samlAttributes): array
278     {
279         $emailAttr = $this->config['email_attribute'];
280         $externalId = $this->getExternalId($samlAttributes, $samlID);
281
282         $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
283         $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
284
285         return [
286             'external_id' => $externalId,
287             'name'        => $this->getUserDisplayName($samlAttributes, $externalId),
288             'email'       => $email,
289             'saml_id'     => $samlID,
290         ];
291     }
292
293     /**
294      * Get the groups a user is a part of from the SAML response.
295      */
296     public function getUserGroups(array $samlAttributes): array
297     {
298         $groupsAttr = $this->config['group_attribute'];
299         $userGroups = $samlAttributes[$groupsAttr] ?? null;
300
301         if (!is_array($userGroups)) {
302             $userGroups = [];
303         }
304
305         return $userGroups;
306     }
307
308     /**
309      *  For an array of strings, return a default for an empty array,
310      *  a string for an array with one element and the full array for
311      *  more than one element.
312      */
313     protected function simplifyValue(array $data, $defaultValue)
314     {
315         switch (count($data)) {
316             case 0:
317                 $data = $defaultValue;
318                 break;
319             case 1:
320                 $data = $data[0];
321                 break;
322         }
323
324         return $data;
325     }
326
327     /**
328      * Get a property from an SAML response.
329      * Handles properties potentially being an array.
330      */
331     protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
332     {
333         if (isset($samlAttributes[$propertyKey])) {
334             return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
335         }
336
337         return $defaultValue;
338     }
339
340     /**
341      * Process the SAML response for a user. Login the user when
342      * they exist, optionally registering them automatically.
343      *
344      * @throws SamlException
345      * @throws JsonDebugException
346      * @throws UserRegistrationException
347      * @throws StoppedAuthenticationException
348      */
349     public function processLoginCallback(string $samlID, array $samlAttributes): User
350     {
351         $userDetails = $this->getUserDetails($samlID, $samlAttributes);
352         $isLoggedIn = auth()->check();
353
354         if ($this->shouldSyncGroups()) {
355             $userDetails['groups'] = $this->getUserGroups($samlAttributes);
356         }
357
358         if ($this->config['dump_user_details']) {
359             throw new JsonDebugException([
360                 'id_from_idp'         => $samlID,
361                 'attrs_from_idp'      => $samlAttributes,
362                 'attrs_after_parsing' => $userDetails,
363             ]);
364         }
365
366         if ($userDetails['email'] === null) {
367             throw new SamlException(trans('errors.saml_no_email_address'));
368         }
369
370         if ($isLoggedIn) {
371             throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
372         }
373
374         $user = $this->registrationService->findOrRegister(
375             $userDetails['name'],
376             $userDetails['email'],
377             $userDetails['external_id']
378         );
379
380         if ($this->shouldSyncGroups()) {
381             $this->groupSyncService->syncUserWithFoundGroups($user, $userDetails['groups'], $this->config['remove_from_groups']);
382         }
383
384         $this->loginService->login($user, 'saml2');
385
386         return $user;
387     }
388 }