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