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 $url = $this->loginService->logout();
78 return ['url' => $url, 'id' => $id];
82 * Process the ACS response from the idp and return the
83 * matching, or new if registration active, user matched to the idp.
84 * Returns null if not authenticated.
87 * @throws SamlException
88 * @throws ValidationError
89 * @throws JsonDebugException
90 * @throws UserRegistrationException
92 public function processAcsResponse(?string $requestId, string $samlResponse): ?User
94 // The SAML2 toolkit expects the response to be within the $_POST superglobal
95 // so we need to manually put it back there at this point.
96 $_POST['SAMLResponse'] = $samlResponse;
97 $toolkit = $this->getToolkit();
98 $toolkit->processResponse($requestId);
99 $errors = $toolkit->getErrors();
101 if (!empty($errors)) {
102 $reason = $toolkit->getLastErrorReason();
103 $message = 'Invalid ACS Response; Errors: ' . implode(', ', $errors);
104 $message .= $reason ? "; Reason: {$reason}" : '';
105 throw new Error($message);
108 if (!$toolkit->isAuthenticated()) {
112 $attrs = $toolkit->getAttributes();
113 $id = $toolkit->getNameId();
114 session()->put('saml2_session_index', $toolkit->getSessionIndex());
116 return $this->processLoginCallback($id, $attrs);
120 * Process a response for the single logout service.
124 public function processSlsResponse(?string $requestId): ?string
126 $toolkit = $this->getToolkit();
128 // The $retrieveParametersFromServer in the call below will mean the library will take the query
129 // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
130 // value so that the exact encoding format is matched when checking the signature.
131 // This is primarily due to ADFS encoding query params with lowercase percent encoding while
132 // PHP (And most other sensible providers) standardise on uppercase.
133 $redirect = $toolkit->processSLO(true, $requestId, true, null, true);
134 $errors = $toolkit->getErrors();
136 if (!empty($errors)) {
138 'Invalid SLS Response: ' . implode(', ', $errors)
142 $this->loginService->logout();
148 * Get the metadata for this service provider.
152 public function metadata(): string
154 $toolKit = $this->getToolkit(true);
155 $settings = $toolKit->getSettings();
156 $metadata = $settings->getSPMetadata();
157 $errors = $settings->validateMetadata($metadata);
159 if (!empty($errors)) {
161 'Invalid SP metadata: ' . implode(', ', $errors),
162 Error::METADATA_SP_INVALID
170 * Load the underlying Onelogin SAML2 toolkit.
175 protected function getToolkit(bool $spOnly = false): Auth
177 $settings = $this->config['onelogin'];
178 $overrides = $this->config['onelogin_overrides'] ?? [];
180 if ($overrides && is_string($overrides)) {
181 $overrides = json_decode($overrides, true);
184 $metaDataSettings = [];
185 if (!$spOnly && $this->config['autoload_from_metadata']) {
186 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
189 $spSettings = $this->loadOneloginServiceProviderDetails();
190 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
192 return new Auth($settings, $spOnly);
196 * Load dynamic service provider options required by the onelogin toolkit.
198 protected function loadOneloginServiceProviderDetails(): array
201 'entityId' => url('/saml2/metadata'),
202 'assertionConsumerService' => [
203 'url' => url('/saml2/acs'),
205 'singleLogoutService' => [
206 'url' => url('/saml2/sls'),
211 'baseurl' => url('/saml2'),
217 * Check if groups should be synced.
219 protected function shouldSyncGroups(): bool
221 return $this->config['user_to_groups'] !== false;
225 * Calculate the display name.
227 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
229 $displayNameAttr = $this->config['display_name_attributes'];
232 foreach ($displayNameAttr as $dnAttr) {
233 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
234 if ($dnComponent !== null) {
235 $displayName[] = $dnComponent;
239 if (count($displayName) == 0) {
240 $displayName = $defaultValue;
242 $displayName = implode(' ', $displayName);
249 * Get the value to use as the external id saved in BookStack
250 * used to link the user to an existing BookStack DB user.
252 protected function getExternalId(array $samlAttributes, string $defaultValue)
254 $userNameAttr = $this->config['external_id_attribute'];
255 if ($userNameAttr === null) {
256 return $defaultValue;
259 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
263 * Extract the details of a user from a SAML response.
265 * @return array{external_id: string, name: string, email: string, saml_id: string}
267 protected function getUserDetails(string $samlID, $samlAttributes): array
269 $emailAttr = $this->config['email_attribute'];
270 $externalId = $this->getExternalId($samlAttributes, $samlID);
272 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
273 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
276 'external_id' => $externalId,
277 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
279 'saml_id' => $samlID,
284 * Get the groups a user is a part of from the SAML response.
286 public function getUserGroups(array $samlAttributes): array
288 $groupsAttr = $this->config['group_attribute'];
289 $userGroups = $samlAttributes[$groupsAttr] ?? null;
291 if (!is_array($userGroups)) {
299 * For an array of strings, return a default for an empty array,
300 * a string for an array with one element and the full array for
301 * more than one element.
303 protected function simplifyValue(array $data, $defaultValue)
305 switch (count($data)) {
307 $data = $defaultValue;
318 * Get a property from an SAML response.
319 * Handles properties potentially being an array.
321 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
323 if (isset($samlAttributes[$propertyKey])) {
324 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
327 return $defaultValue;
331 * Process the SAML response for a user. Login the user when
332 * they exist, optionally registering them automatically.
334 * @throws SamlException
335 * @throws JsonDebugException
336 * @throws UserRegistrationException
337 * @throws StoppedAuthenticationException
339 public function processLoginCallback(string $samlID, array $samlAttributes): User
341 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
342 $isLoggedIn = auth()->check();
344 if ($this->shouldSyncGroups()) {
345 $userDetails['groups'] = $this->getUserGroups($samlAttributes);
348 if ($this->config['dump_user_details']) {
349 throw new JsonDebugException([
350 'id_from_idp' => $samlID,
351 'attrs_from_idp' => $samlAttributes,
352 'attrs_after_parsing' => $userDetails,
356 if ($userDetails['email'] === null) {
357 throw new SamlException(trans('errors.saml_no_email_address'));
361 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
364 $user = $this->registrationService->findOrRegister(
365 $userDetails['name'],
366 $userDetails['email'],
367 $userDetails['external_id']
370 if ($this->shouldSyncGroups()) {
371 $this->groupSyncService->syncUserWithFoundGroups($user, $userDetails['groups'], $this->config['remove_from_groups']);
374 $this->loginService->login($user, 'saml2');