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.
51 * Returns the SAML2 request ID, and the URL to redirect the user to.
54 * @returns array{url: string, id: ?string}
56 public function logout(User $user): array
58 $toolKit = $this->getToolkit();
59 $sessionIndex = session()->get('saml2_session_index');
60 $returnUrl = url($this->loginService->logout());
63 $url = $toolKit->logout(
69 Constants::NAMEID_EMAIL_ADDRESS
71 $id = $toolKit->getLastRequestID();
72 } catch (Error $error) {
73 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
81 return ['url' => $url, 'id' => $id];
85 * Process the ACS response from the idp and return the
86 * matching, or new if registration active, user matched to the idp.
87 * Returns null if not authenticated.
90 * @throws SamlException
91 * @throws ValidationError
92 * @throws JsonDebugException
93 * @throws UserRegistrationException
95 public function processAcsResponse(?string $requestId, string $samlResponse): ?User
97 // The SAML2 toolkit expects the response to be within the $_POST superglobal
98 // so we need to manually put it back there at this point.
99 $_POST['SAMLResponse'] = $samlResponse;
100 $toolkit = $this->getToolkit();
101 $toolkit->processResponse($requestId);
102 $errors = $toolkit->getErrors();
104 if (!empty($errors)) {
105 $reason = $toolkit->getLastErrorReason();
106 $message = 'Invalid ACS Response; Errors: ' . implode(', ', $errors);
107 $message .= $reason ? "; Reason: {$reason}" : '';
108 throw new Error($message);
111 if (!$toolkit->isAuthenticated()) {
115 $attrs = $toolkit->getAttributes();
116 $id = $toolkit->getNameId();
117 session()->put('saml2_session_index', $toolkit->getSessionIndex());
119 return $this->processLoginCallback($id, $attrs);
123 * Process a response for the single logout service.
127 public function processSlsResponse(?string $requestId): string
129 $toolkit = $this->getToolkit();
131 // The $retrieveParametersFromServer in the call below will mean the library will take the query
132 // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
133 // value so that the exact encoding format is matched when checking the signature.
134 // This is primarily due to ADFS encoding query params with lowercase percent encoding while
135 // PHP (And most other sensible providers) standardise on uppercase.
136 /** @var ?string $samlRedirect */
137 $samlRedirect = $toolkit->processSLO(true, $requestId, true, null, true);
138 $errors = $toolkit->getErrors();
140 if (!empty($errors)) {
142 'Invalid SLS Response: ' . implode(', ', $errors)
146 $defaultBookStackRedirect = $this->loginService->logout();
148 return $samlRedirect ?? $defaultBookStackRedirect;
152 * Get the metadata for this service provider.
156 public function metadata(): string
158 $toolKit = $this->getToolkit(true);
159 $settings = $toolKit->getSettings();
160 $metadata = $settings->getSPMetadata();
161 $errors = $settings->validateMetadata($metadata);
163 if (!empty($errors)) {
165 'Invalid SP metadata: ' . implode(', ', $errors),
166 Error::METADATA_SP_INVALID
174 * Load the underlying Onelogin SAML2 toolkit.
179 protected function getToolkit(bool $spOnly = false): Auth
181 $settings = $this->config['onelogin'];
182 $overrides = $this->config['onelogin_overrides'] ?? [];
184 if ($overrides && is_string($overrides)) {
185 $overrides = json_decode($overrides, true);
188 $metaDataSettings = [];
189 if (!$spOnly && $this->config['autoload_from_metadata']) {
190 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
193 $spSettings = $this->loadOneloginServiceProviderDetails();
194 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
196 return new Auth($settings, $spOnly);
200 * Load dynamic service provider options required by the onelogin toolkit.
202 protected function loadOneloginServiceProviderDetails(): array
205 'entityId' => url('/saml2/metadata'),
206 'assertionConsumerService' => [
207 'url' => url('/saml2/acs'),
209 'singleLogoutService' => [
210 'url' => url('/saml2/sls'),
215 'baseurl' => url('/saml2'),
221 * Check if groups should be synced.
223 protected function shouldSyncGroups(): bool
225 return $this->config['user_to_groups'] !== false;
229 * Calculate the display name.
231 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
233 $displayNameAttr = $this->config['display_name_attributes'];
236 foreach ($displayNameAttr as $dnAttr) {
237 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
238 if ($dnComponent !== null) {
239 $displayName[] = $dnComponent;
243 if (count($displayName) == 0) {
244 $displayName = $defaultValue;
246 $displayName = implode(' ', $displayName);
253 * Get the value to use as the external id saved in BookStack
254 * used to link the user to an existing BookStack DB user.
256 protected function getExternalId(array $samlAttributes, string $defaultValue)
258 $userNameAttr = $this->config['external_id_attribute'];
259 if ($userNameAttr === null) {
260 return $defaultValue;
263 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
267 * Extract the details of a user from a SAML response.
269 * @return array{external_id: string, name: string, email: string, saml_id: string}
271 protected function getUserDetails(string $samlID, $samlAttributes): array
273 $emailAttr = $this->config['email_attribute'];
274 $externalId = $this->getExternalId($samlAttributes, $samlID);
276 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
277 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
280 'external_id' => $externalId,
281 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
283 'saml_id' => $samlID,
288 * Get the groups a user is a part of from the SAML response.
290 public function getUserGroups(array $samlAttributes): array
292 $groupsAttr = $this->config['group_attribute'];
293 $userGroups = $samlAttributes[$groupsAttr] ?? null;
295 if (!is_array($userGroups)) {
303 * For an array of strings, return a default for an empty array,
304 * a string for an array with one element and the full array for
305 * more than one element.
307 protected function simplifyValue(array $data, $defaultValue)
309 switch (count($data)) {
311 $data = $defaultValue;
322 * Get a property from an SAML response.
323 * Handles properties potentially being an array.
325 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
327 if (isset($samlAttributes[$propertyKey])) {
328 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
331 return $defaultValue;
335 * Process the SAML response for a user. Login the user when
336 * they exist, optionally registering them automatically.
338 * @throws SamlException
339 * @throws JsonDebugException
340 * @throws UserRegistrationException
341 * @throws StoppedAuthenticationException
343 public function processLoginCallback(string $samlID, array $samlAttributes): User
345 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
346 $isLoggedIn = auth()->check();
348 if ($this->shouldSyncGroups()) {
349 $userDetails['groups'] = $this->getUserGroups($samlAttributes);
352 if ($this->config['dump_user_details']) {
353 throw new JsonDebugException([
354 'id_from_idp' => $samlID,
355 'attrs_from_idp' => $samlAttributes,
356 'attrs_after_parsing' => $userDetails,
360 if ($userDetails['email'] === null) {
361 throw new SamlException(trans('errors.saml_no_email_address'));
365 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
368 $user = $this->registrationService->findOrRegister(
369 $userDetails['name'],
370 $userDetails['email'],
371 $userDetails['external_id']
374 if ($this->shouldSyncGroups()) {
375 $this->groupSyncService->syncUserWithFoundGroups($user, $userDetails['groups'], $this->config['remove_from_groups']);
378 $this->loginService->login($user, 'saml2');