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