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