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