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