]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/Saml2Service.php
Added examples, updated docs for image gallery api endpoints
[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\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                 null,
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
122         return $this->processLoginCallback($id, $attrs);
123     }
124
125     /**
126      * Process a response for the single logout service.
127      *
128      * @throws Error
129      */
130     public function processSlsResponse(?string $requestId): ?string
131     {
132         $toolkit = $this->getToolkit();
133
134         // The $retrieveParametersFromServer in the call below will mean the library will take the query
135         // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
136         // value so that the exact encoding format is matched when checking the signature.
137         // This is primarily due to ADFS encoding query params with lowercase percent encoding while
138         // PHP (And most other sensible providers) standardise on uppercase.
139         $redirect = $toolkit->processSLO(true, $requestId, true, null, true);
140         $errors = $toolkit->getErrors();
141
142         if (!empty($errors)) {
143             throw new Error(
144                 'Invalid SLS Response: ' . implode(', ', $errors)
145             );
146         }
147
148         $this->actionLogout();
149
150         return $redirect;
151     }
152
153     /**
154      * Do the required actions to log a user out.
155      */
156     protected function actionLogout()
157     {
158         auth()->logout();
159         session()->invalidate();
160     }
161
162     /**
163      * Get the metadata for this service provider.
164      *
165      * @throws Error
166      */
167     public function metadata(): string
168     {
169         $toolKit = $this->getToolkit(true);
170         $settings = $toolKit->getSettings();
171         $metadata = $settings->getSPMetadata();
172         $errors = $settings->validateMetadata($metadata);
173
174         if (!empty($errors)) {
175             throw new Error(
176                 'Invalid SP metadata: ' . implode(', ', $errors),
177                 Error::METADATA_SP_INVALID
178             );
179         }
180
181         return $metadata;
182     }
183
184     /**
185      * Load the underlying Onelogin SAML2 toolkit.
186      *
187      * @throws Error
188      * @throws Exception
189      */
190     protected function getToolkit(bool $spOnly = false): Auth
191     {
192         $settings = $this->config['onelogin'];
193         $overrides = $this->config['onelogin_overrides'] ?? [];
194
195         if ($overrides && is_string($overrides)) {
196             $overrides = json_decode($overrides, true);
197         }
198
199         $metaDataSettings = [];
200         if (!$spOnly && $this->config['autoload_from_metadata']) {
201             $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
202         }
203
204         $spSettings = $this->loadOneloginServiceProviderDetails();
205         $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
206
207         return new Auth($settings, $spOnly);
208     }
209
210     /**
211      * Load dynamic service provider options required by the onelogin toolkit.
212      */
213     protected function loadOneloginServiceProviderDetails(): array
214     {
215         $spDetails = [
216             'entityId'                 => url('/saml2/metadata'),
217             'assertionConsumerService' => [
218                 'url' => url('/saml2/acs'),
219             ],
220             'singleLogoutService' => [
221                 'url' => url('/saml2/sls'),
222             ],
223         ];
224
225         return [
226             'baseurl' => url('/saml2'),
227             'sp'      => $spDetails,
228         ];
229     }
230
231     /**
232      * Check if groups should be synced.
233      */
234     protected function shouldSyncGroups(): bool
235     {
236         return $this->config['user_to_groups'] !== false;
237     }
238
239     /**
240      * Calculate the display name.
241      */
242     protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
243     {
244         $displayNameAttr = $this->config['display_name_attributes'];
245
246         $displayName = [];
247         foreach ($displayNameAttr as $dnAttr) {
248             $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
249             if ($dnComponent !== null) {
250                 $displayName[] = $dnComponent;
251             }
252         }
253
254         if (count($displayName) == 0) {
255             $displayName = $defaultValue;
256         } else {
257             $displayName = implode(' ', $displayName);
258         }
259
260         return $displayName;
261     }
262
263     /**
264      * Get the value to use as the external id saved in BookStack
265      * used to link the user to an existing BookStack DB user.
266      */
267     protected function getExternalId(array $samlAttributes, string $defaultValue)
268     {
269         $userNameAttr = $this->config['external_id_attribute'];
270         if ($userNameAttr === null) {
271             return $defaultValue;
272         }
273
274         return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
275     }
276
277     /**
278      * Extract the details of a user from a SAML response.
279      *
280      * @return array{external_id: string, name: string, email: string, saml_id: string}
281      */
282     protected function getUserDetails(string $samlID, $samlAttributes): array
283     {
284         $emailAttr = $this->config['email_attribute'];
285         $externalId = $this->getExternalId($samlAttributes, $samlID);
286
287         $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
288         $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
289
290         return [
291             'external_id' => $externalId,
292             'name'        => $this->getUserDisplayName($samlAttributes, $externalId),
293             'email'       => $email,
294             'saml_id'     => $samlID,
295         ];
296     }
297
298     /**
299      * Get the groups a user is a part of from the SAML response.
300      */
301     public function getUserGroups(array $samlAttributes): array
302     {
303         $groupsAttr = $this->config['group_attribute'];
304         $userGroups = $samlAttributes[$groupsAttr] ?? null;
305
306         if (!is_array($userGroups)) {
307             $userGroups = [];
308         }
309
310         return $userGroups;
311     }
312
313     /**
314      *  For an array of strings, return a default for an empty array,
315      *  a string for an array with one element and the full array for
316      *  more than one element.
317      */
318     protected function simplifyValue(array $data, $defaultValue)
319     {
320         switch (count($data)) {
321             case 0:
322                 $data = $defaultValue;
323                 break;
324             case 1:
325                 $data = $data[0];
326                 break;
327         }
328
329         return $data;
330     }
331
332     /**
333      * Get a property from an SAML response.
334      * Handles properties potentially being an array.
335      */
336     protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
337     {
338         if (isset($samlAttributes[$propertyKey])) {
339             return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
340         }
341
342         return $defaultValue;
343     }
344
345     /**
346      * Process the SAML response for a user. Login the user when
347      * they exist, optionally registering them automatically.
348      *
349      * @throws SamlException
350      * @throws JsonDebugException
351      * @throws UserRegistrationException
352      * @throws StoppedAuthenticationException
353      */
354     public function processLoginCallback(string $samlID, array $samlAttributes): User
355     {
356         $userDetails = $this->getUserDetails($samlID, $samlAttributes);
357         $isLoggedIn = auth()->check();
358
359         if ($this->config['dump_user_details']) {
360             throw new JsonDebugException([
361                 'id_from_idp'         => $samlID,
362                 'attrs_from_idp'      => $samlAttributes,
363                 'attrs_after_parsing' => $userDetails,
364             ]);
365         }
366
367         if ($userDetails['email'] === null) {
368             throw new SamlException(trans('errors.saml_no_email_address'));
369         }
370
371         if ($isLoggedIn) {
372             throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
373         }
374
375         $user = $this->registrationService->findOrRegister(
376             $userDetails['name'],
377             $userDetails['email'],
378             $userDetails['external_id']
379         );
380
381         if ($user === null) {
382             throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
383         }
384
385         if ($this->shouldSyncGroups()) {
386             $groups = $this->getUserGroups($samlAttributes);
387             $this->groupSyncService->syncUserWithFoundGroups($user, $groups, $this->config['remove_from_groups']);
388         }
389
390         $this->loginService->login($user, 'saml2');
391
392         return $user;
393     }
394 }