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