]> BookStack Code Mirror - bookstack/blob - app/Access/Saml2Service.php
SAML: Set static type to pass static checks
[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      * Returns the SAML2 request ID, and the URL to redirect the user to.
52      *
53      * @throws Error
54      * @returns array{url: string, id: ?string}
55      */
56     public function logout(User $user): array
57     {
58         $toolKit = $this->getToolkit();
59         $sessionIndex = session()->get('saml2_session_index');
60         $returnUrl = url($this->loginService->logout());
61
62         try {
63             $url = $toolKit->logout(
64                 $returnUrl,
65                 [],
66                 $user->email,
67                 $sessionIndex,
68                 true,
69                 Constants::NAMEID_EMAIL_ADDRESS
70             );
71             $id = $toolKit->getLastRequestID();
72         } catch (Error $error) {
73             if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
74                 throw $error;
75             }
76
77             $url = $returnUrl;
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, string $samlResponse): ?User
96     {
97         // The SAML2 toolkit expects the response to be within the $_POST superglobal
98         // so we need to manually put it back there at this point.
99         $_POST['SAMLResponse'] = $samlResponse;
100         $toolkit = $this->getToolkit();
101         $toolkit->processResponse($requestId);
102         $errors = $toolkit->getErrors();
103
104         if (!empty($errors)) {
105             $reason = $toolkit->getLastErrorReason();
106             $message = 'Invalid ACS Response; Errors: ' . implode(', ', $errors);
107             $message .= $reason ? "; Reason: {$reason}" : '';
108             throw new Error($message);
109         }
110
111         if (!$toolkit->isAuthenticated()) {
112             return null;
113         }
114
115         $attrs = $toolkit->getAttributes();
116         $id = $toolkit->getNameId();
117         session()->put('saml2_session_index', $toolkit->getSessionIndex());
118
119         return $this->processLoginCallback($id, $attrs);
120     }
121
122     /**
123      * Process a response for the single logout service.
124      *
125      * @throws Error
126      */
127     public function processSlsResponse(?string $requestId): string
128     {
129         $toolkit = $this->getToolkit();
130
131         // The $retrieveParametersFromServer in the call below will mean the library will take the query
132         // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
133         // value so that the exact encoding format is matched when checking the signature.
134         // This is primarily due to ADFS encoding query params with lowercase percent encoding while
135         // PHP (And most other sensible providers) standardise on uppercase.
136         /** @var ?string $samlRedirect */
137         $samlRedirect = $toolkit->processSLO(true, $requestId, true, null, true);
138         $errors = $toolkit->getErrors();
139
140         if (!empty($errors)) {
141             throw new Error(
142                 'Invalid SLS Response: ' . implode(', ', $errors)
143             );
144         }
145
146         $defaultBookStackRedirect = $this->loginService->logout();
147
148         return $samlRedirect ?? $defaultBookStackRedirect;
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(true);
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(bool $spOnly = false): 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 (!$spOnly && $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, $spOnly);
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->shouldSyncGroups()) {
349             $userDetails['groups'] = $this->getUserGroups($samlAttributes);
350         }
351
352         if ($this->config['dump_user_details']) {
353             throw new JsonDebugException([
354                 'id_from_idp'         => $samlID,
355                 'attrs_from_idp'      => $samlAttributes,
356                 'attrs_after_parsing' => $userDetails,
357             ]);
358         }
359
360         if ($userDetails['email'] === null) {
361             throw new SamlException(trans('errors.saml_no_email_address'));
362         }
363
364         if ($isLoggedIn) {
365             throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
366         }
367
368         $user = $this->registrationService->findOrRegister(
369             $userDetails['name'],
370             $userDetails['email'],
371             $userDetails['external_id']
372         );
373
374         if ($this->shouldSyncGroups()) {
375             $this->groupSyncService->syncUserWithFoundGroups($user, $userDetails['groups'], $this->config['remove_from_groups']);
376         }
377
378         $this->loginService->login($user, 'saml2');
379
380         return $user;
381     }
382 }