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