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