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