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