]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/Saml2Service.php
Cleaned some unused elements during testing
[bookstack] / app / Auth / Access / Saml2Service.php
1 <?php
2
3 namespace BookStack\Auth\Access;
4
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\User;
7 use BookStack\Exceptions\JsonDebugException;
8 use BookStack\Exceptions\SamlException;
9 use BookStack\Exceptions\StoppedAuthenticationException;
10 use BookStack\Exceptions\UserRegistrationException;
11 use BookStack\Facades\Activity;
12 use BookStack\Facades\Theme;
13 use BookStack\Theming\ThemeEvents;
14 use Exception;
15 use Illuminate\Support\Str;
16 use OneLogin\Saml2\Auth;
17 use OneLogin\Saml2\Error;
18 use OneLogin\Saml2\IdPMetadataParser;
19 use OneLogin\Saml2\ValidationError;
20
21 /**
22  * Class Saml2Service
23  * Handles any app-specific SAML tasks.
24  */
25 class Saml2Service extends ExternalAuthService
26 {
27     protected $config;
28     protected $registrationService;
29     protected $loginService;
30
31     /**
32      * Saml2Service constructor.
33      */
34     public function __construct(RegistrationService $registrationService, LoginService $loginService)
35     {
36         $this->config = config('saml2');
37         $this->registrationService = $registrationService;
38         $this->loginService = $loginService;
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     protected function getUserDetails(string $samlID, $samlAttributes): array
267     {
268         $emailAttr = $this->config['email_attribute'];
269         $externalId = $this->getExternalId($samlAttributes, $samlID);
270
271         $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
272         $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
273
274         return [
275             'external_id' => $externalId,
276             'name'        => $this->getUserDisplayName($samlAttributes, $externalId),
277             'email'       => $email,
278             'saml_id'     => $samlID,
279         ];
280     }
281
282     /**
283      * Get the groups a user is a part of from the SAML response.
284      */
285     public function getUserGroups(array $samlAttributes): array
286     {
287         $groupsAttr = $this->config['group_attribute'];
288         $userGroups = $samlAttributes[$groupsAttr] ?? null;
289
290         if (!is_array($userGroups)) {
291             $userGroups = [];
292         }
293
294         return $userGroups;
295     }
296
297     /**
298      *  For an array of strings, return a default for an empty array,
299      *  a string for an array with one element and the full array for
300      *  more than one element.
301      */
302     protected function simplifyValue(array $data, $defaultValue)
303     {
304         switch (count($data)) {
305             case 0:
306                 $data = $defaultValue;
307                 break;
308             case 1:
309                 $data = $data[0];
310                 break;
311         }
312
313         return $data;
314     }
315
316     /**
317      * Get a property from an SAML response.
318      * Handles properties potentially being an array.
319      */
320     protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
321     {
322         if (isset($samlAttributes[$propertyKey])) {
323             return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
324         }
325
326         return $defaultValue;
327     }
328
329     /**
330      * Get the user from the database for the specified details.
331      *
332      * @throws UserRegistrationException
333      */
334     protected function getOrRegisterUser(array $userDetails): ?User
335     {
336         $user = User::query()
337           ->where('external_auth_id', '=', $userDetails['external_id'])
338           ->first();
339
340         if (is_null($user)) {
341             $userData = [
342                 'name'             => $userDetails['name'],
343                 'email'            => $userDetails['email'],
344                 'password'         => Str::random(32),
345                 'external_auth_id' => $userDetails['external_id'],
346             ];
347
348             $user = $this->registrationService->registerUser($userData, null, false);
349         }
350
351         return $user;
352     }
353
354     /**
355      * Process the SAML response for a user. Login the user when
356      * they exist, optionally registering them automatically.
357      *
358      * @throws SamlException
359      * @throws JsonDebugException
360      * @throws UserRegistrationException
361      * @throws StoppedAuthenticationException
362      */
363     public function processLoginCallback(string $samlID, array $samlAttributes): User
364     {
365         $userDetails = $this->getUserDetails($samlID, $samlAttributes);
366         $isLoggedIn = auth()->check();
367
368         if ($this->config['dump_user_details']) {
369             throw new JsonDebugException([
370                 'id_from_idp'         => $samlID,
371                 'attrs_from_idp'      => $samlAttributes,
372                 'attrs_after_parsing' => $userDetails,
373             ]);
374         }
375
376         if ($userDetails['email'] === null) {
377             throw new SamlException(trans('errors.saml_no_email_address'));
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         $this->loginService->login($user, 'saml2');
395         return $user;
396     }
397 }