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