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