3 namespace BookStack\Access;
5 use BookStack\Exceptions\JsonDebugException;
6 use BookStack\Exceptions\SamlException;
7 use BookStack\Exceptions\StoppedAuthenticationException;
8 use BookStack\Exceptions\UserRegistrationException;
9 use BookStack\Users\Models\User;
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;
19 * Handles any app-specific SAML tasks.
23 protected array $config;
25 public function __construct(
26 protected RegistrationService $registrationService,
27 protected LoginService $loginService,
28 protected GroupSyncService $groupSyncService
30 $this->config = config('saml2');
34 * Initiate a login flow.
38 public function login(): array
40 $toolKit = $this->getToolkit();
41 $returnRoute = url('/saml2/acs');
44 'url' => $toolKit->login($returnRoute, [], false, false, true),
45 'id' => $toolKit->getLastRequestID(),
50 * Initiate a logout flow.
54 public function logout(User $user): array
56 $toolKit = $this->getToolkit();
57 $returnRoute = url('/');
60 $url = $toolKit->logout(
64 session()->get('saml2_session_index'),
66 Constants::NAMEID_EMAIL_ADDRESS
68 $id = $toolKit->getLastRequestID();
69 } catch (Error $error) {
70 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
74 $this->actionLogout();
79 return ['url' => $url, 'id' => $id];
83 * Process the ACS response from the idp and return the
84 * matching, or new if registration active, user matched to the idp.
85 * Returns null if not authenticated.
88 * @throws SamlException
89 * @throws ValidationError
90 * @throws JsonDebugException
91 * @throws UserRegistrationException
93 public function processAcsResponse(?string $requestId, string $samlResponse): ?User
95 // The SAML2 toolkit expects the response to be within the $_POST superglobal
96 // so we need to manually put it back there at this point.
97 $_POST['SAMLResponse'] = $samlResponse;
98 $toolkit = $this->getToolkit();
99 $toolkit->processResponse($requestId);
100 $errors = $toolkit->getErrors();
102 if (!empty($errors)) {
103 $reason = $toolkit->getLastErrorReason();
104 $message = 'Invalid ACS Response; Errors: ' . implode(', ', $errors);
105 $message .= $reason ? "; Reason: {$reason}" : '';
106 throw new Error($message);
109 if (!$toolkit->isAuthenticated()) {
113 $attrs = $toolkit->getAttributes();
114 $id = $toolkit->getNameId();
115 session()->put('saml2_session_index', $toolkit->getSessionIndex());
117 return $this->processLoginCallback($id, $attrs);
121 * Process a response for the single logout service.
125 public function processSlsResponse(?string $requestId): ?string
127 $toolkit = $this->getToolkit();
129 // The $retrieveParametersFromServer in the call below will mean the library will take the query
130 // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
131 // value so that the exact encoding format is matched when checking the signature.
132 // This is primarily due to ADFS encoding query params with lowercase percent encoding while
133 // PHP (And most other sensible providers) standardise on uppercase.
134 $redirect = $toolkit->processSLO(true, $requestId, true, null, true);
135 $errors = $toolkit->getErrors();
137 if (!empty($errors)) {
139 'Invalid SLS Response: ' . implode(', ', $errors)
143 $this->actionLogout();
149 * Do the required actions to log a user out.
151 protected function actionLogout()
154 session()->invalidate();
158 * Get the metadata for this service provider.
162 public function metadata(): string
164 $toolKit = $this->getToolkit(true);
165 $settings = $toolKit->getSettings();
166 $metadata = $settings->getSPMetadata();
167 $errors = $settings->validateMetadata($metadata);
169 if (!empty($errors)) {
171 'Invalid SP metadata: ' . implode(', ', $errors),
172 Error::METADATA_SP_INVALID
180 * Load the underlying Onelogin SAML2 toolkit.
185 protected function getToolkit(bool $spOnly = false): Auth
187 $settings = $this->config['onelogin'];
188 $overrides = $this->config['onelogin_overrides'] ?? [];
190 if ($overrides && is_string($overrides)) {
191 $overrides = json_decode($overrides, true);
194 $metaDataSettings = [];
195 if (!$spOnly && $this->config['autoload_from_metadata']) {
196 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
199 $spSettings = $this->loadOneloginServiceProviderDetails();
200 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
202 return new Auth($settings, $spOnly);
206 * Load dynamic service provider options required by the onelogin toolkit.
208 protected function loadOneloginServiceProviderDetails(): array
211 'entityId' => url('/saml2/metadata'),
212 'assertionConsumerService' => [
213 'url' => url('/saml2/acs'),
215 'singleLogoutService' => [
216 'url' => url('/saml2/sls'),
221 'baseurl' => url('/saml2'),
227 * Check if groups should be synced.
229 protected function shouldSyncGroups(): bool
231 return $this->config['user_to_groups'] !== false;
235 * Calculate the display name.
237 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
239 $displayNameAttr = $this->config['display_name_attributes'];
242 foreach ($displayNameAttr as $dnAttr) {
243 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
244 if ($dnComponent !== null) {
245 $displayName[] = $dnComponent;
249 if (count($displayName) == 0) {
250 $displayName = $defaultValue;
252 $displayName = implode(' ', $displayName);
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.
262 protected function getExternalId(array $samlAttributes, string $defaultValue)
264 $userNameAttr = $this->config['external_id_attribute'];
265 if ($userNameAttr === null) {
266 return $defaultValue;
269 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
273 * Extract the details of a user from a SAML response.
275 * @return array{external_id: string, name: string, email: string, saml_id: string}
277 protected function getUserDetails(string $samlID, $samlAttributes): array
279 $emailAttr = $this->config['email_attribute'];
280 $externalId = $this->getExternalId($samlAttributes, $samlID);
282 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
283 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
286 'external_id' => $externalId,
287 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
289 'saml_id' => $samlID,
294 * Get the groups a user is a part of from the SAML response.
296 public function getUserGroups(array $samlAttributes): array
298 $groupsAttr = $this->config['group_attribute'];
299 $userGroups = $samlAttributes[$groupsAttr] ?? null;
301 if (!is_array($userGroups)) {
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.
313 protected function simplifyValue(array $data, $defaultValue)
315 switch (count($data)) {
317 $data = $defaultValue;
328 * Get a property from an SAML response.
329 * Handles properties potentially being an array.
331 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
333 if (isset($samlAttributes[$propertyKey])) {
334 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
337 return $defaultValue;
341 * Process the SAML response for a user. Login the user when
342 * they exist, optionally registering them automatically.
344 * @throws SamlException
345 * @throws JsonDebugException
346 * @throws UserRegistrationException
347 * @throws StoppedAuthenticationException
349 public function processLoginCallback(string $samlID, array $samlAttributes): User
351 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
352 $isLoggedIn = auth()->check();
354 if ($this->shouldSyncGroups()) {
355 $userDetails['groups'] = $this->getUserGroups($samlAttributes);
358 if ($this->config['dump_user_details']) {
359 throw new JsonDebugException([
360 'id_from_idp' => $samlID,
361 'attrs_from_idp' => $samlAttributes,
362 'attrs_after_parsing' => $userDetails,
366 if ($userDetails['email'] === null) {
367 throw new SamlException(trans('errors.saml_no_email_address'));
371 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
374 $user = $this->registrationService->findOrRegister(
375 $userDetails['name'],
376 $userDetails['email'],
377 $userDetails['external_id']
380 if ($this->shouldSyncGroups()) {
381 $this->groupSyncService->syncUserWithFoundGroups($user, $userDetails['groups'], $this->config['remove_from_groups']);
384 $this->loginService->login($user, 'saml2');