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