]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
Text: Tweaks to EN text for consistency/readability
[bookstack] / app / Access / Oidc / OidcService.php
1 <?php
2
3 namespace BookStack\Access\Oidc;
4
5 use BookStack\Access\GroupSyncService;
6 use BookStack\Access\LoginService;
7 use BookStack\Access\RegistrationService;
8 use BookStack\Exceptions\JsonDebugException;
9 use BookStack\Exceptions\StoppedAuthenticationException;
10 use BookStack\Exceptions\UserRegistrationException;
11 use BookStack\Facades\Theme;
12 use BookStack\Http\HttpRequestService;
13 use BookStack\Theming\ThemeEvents;
14 use BookStack\Users\Models\User;
15 use Illuminate\Support\Arr;
16 use Illuminate\Support\Facades\Cache;
17 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
18 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
19
20 /**
21  * Class OpenIdConnectService
22  * Handles any app-specific OIDC tasks.
23  */
24 class OidcService
25 {
26     public function __construct(
27         protected RegistrationService $registrationService,
28         protected LoginService $loginService,
29         protected HttpRequestService $http,
30         protected GroupSyncService $groupService
31     ) {
32     }
33
34     /**
35      * Initiate an authorization flow.
36      *
37      * @throws OidcException
38      *
39      * @return array{url: string, state: string}
40      */
41     public function login(): array
42     {
43         $settings = $this->getProviderSettings();
44         $provider = $this->getProvider($settings);
45         return [
46             'url'   => $provider->getAuthorizationUrl(),
47             'state' => $provider->getState(),
48         ];
49     }
50
51     /**
52      * Process the Authorization response from the authorization server and
53      * return the matching, or new if registration active, user matched to the
54      * authorization server. Throws if the user cannot be auth if not authenticated.
55      *
56      * @throws JsonDebugException
57      * @throws OidcException
58      * @throws StoppedAuthenticationException
59      * @throws IdentityProviderException
60      */
61     public function processAuthorizeResponse(?string $authorizationCode): User
62     {
63         $settings = $this->getProviderSettings();
64         $provider = $this->getProvider($settings);
65
66         // Try to exchange authorization code for access token
67         $accessToken = $provider->getAccessToken('authorization_code', [
68             'code' => $authorizationCode,
69         ]);
70
71         return $this->processAccessTokenCallback($accessToken, $settings);
72     }
73
74     /**
75      * @throws OidcException
76      */
77     protected function getProviderSettings(): OidcProviderSettings
78     {
79         $config = $this->config();
80         $settings = new OidcProviderSettings([
81             'issuer'                => $config['issuer'],
82             'clientId'              => $config['client_id'],
83             'clientSecret'          => $config['client_secret'],
84             'redirectUri'           => url('/oidc/callback'),
85             'authorizationEndpoint' => $config['authorization_endpoint'],
86             'tokenEndpoint'         => $config['token_endpoint'],
87             'endSessionEndpoint'    => is_string($config['end_session_endpoint']) ? $config['end_session_endpoint'] : null,
88         ]);
89
90         // Use keys if configured
91         if (!empty($config['jwt_public_key'])) {
92             $settings->keys = [$config['jwt_public_key']];
93         }
94
95         // Run discovery
96         if ($config['discover'] ?? false) {
97             try {
98                 $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
99             } catch (OidcIssuerDiscoveryException $exception) {
100                 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
101             }
102         }
103
104         // Prevent use of RP-initiated logout if specifically disabled
105         // Or force use of a URL if specifically set.
106         if ($config['end_session_endpoint'] === false) {
107             $settings->endSessionEndpoint = null;
108         } else if (is_string($config['end_session_endpoint'])) {
109             $settings->endSessionEndpoint = $config['end_session_endpoint'];
110         }
111
112         $settings->validate();
113
114         return $settings;
115     }
116
117     /**
118      * Load the underlying OpenID Connect Provider.
119      */
120     protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
121     {
122         $provider = new OidcOAuthProvider($settings->arrayForProvider(), [
123             'httpClient'     => $this->http->buildClient(5),
124             'optionProvider' => new HttpBasicAuthOptionProvider(),
125         ]);
126
127         foreach ($this->getAdditionalScopes() as $scope) {
128             $provider->addScope($scope);
129         }
130
131         return $provider;
132     }
133
134     /**
135      * Get any user-defined addition/custom scopes to apply to the authentication request.
136      *
137      * @return string[]
138      */
139     protected function getAdditionalScopes(): array
140     {
141         $scopeConfig = $this->config()['additional_scopes'] ?: '';
142
143         $scopeArr = explode(',', $scopeConfig);
144         $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
145
146         return array_filter($scopeArr);
147     }
148
149     /**
150      * Calculate the display name.
151      */
152     protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
153     {
154         $displayNameAttrString = $this->config()['display_name_claims'] ?? '';
155         $displayNameAttrs = explode('|', $displayNameAttrString);
156
157         $displayName = [];
158         foreach ($displayNameAttrs as $dnAttr) {
159             $dnComponent = $token->getClaim($dnAttr) ?? '';
160             if ($dnComponent !== '') {
161                 $displayName[] = $dnComponent;
162             }
163         }
164
165         if (count($displayName) == 0) {
166             $displayName[] = $defaultValue;
167         }
168
169         return implode(' ', $displayName);
170     }
171
172     /**
173      * Extract the assigned groups from the id token.
174      *
175      * @return string[]
176      */
177     protected function getUserGroups(OidcIdToken $token): array
178     {
179         $groupsAttr = $this->config()['groups_claim'];
180         if (empty($groupsAttr)) {
181             return [];
182         }
183
184         $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
185         if (!is_array($groupsList)) {
186             return [];
187         }
188
189         return array_values(array_filter($groupsList, function ($val) {
190             return is_string($val);
191         }));
192     }
193
194     /**
195      * Extract the details of a user from an ID token.
196      *
197      * @return array{name: string, email: string, external_id: string, groups: string[]}
198      */
199     protected function getUserDetails(OidcIdToken $token): array
200     {
201         $idClaim = $this->config()['external_id_claim'];
202         $id = $token->getClaim($idClaim);
203
204         return [
205             'external_id' => $id,
206             'email'       => $token->getClaim('email'),
207             'name'        => $this->getUserDisplayName($token, $id),
208             'groups'      => $this->getUserGroups($token),
209         ];
210     }
211
212     /**
213      * Processes a received access token for a user. Login the user when
214      * they exist, optionally registering them automatically.
215      *
216      * @throws OidcException
217      * @throws JsonDebugException
218      * @throws StoppedAuthenticationException
219      */
220     protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
221     {
222         $idTokenText = $accessToken->getIdToken();
223         $idToken = new OidcIdToken(
224             $idTokenText,
225             $settings->issuer,
226             $settings->keys,
227         );
228
229         session()->put("oidc_id_token", $idTokenText);
230
231         $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
232             'access_token' => $accessToken->getToken(),
233             'expires_in' => $accessToken->getExpires(),
234             'refresh_token' => $accessToken->getRefreshToken(),
235         ]);
236
237         if (!is_null($returnClaims)) {
238             $idToken->replaceClaims($returnClaims);
239         }
240
241         if ($this->config()['dump_user_details']) {
242             throw new JsonDebugException($idToken->getAllClaims());
243         }
244
245         try {
246             $idToken->validate($settings->clientId);
247         } catch (OidcInvalidTokenException $exception) {
248             throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
249         }
250
251         $userDetails = $this->getUserDetails($idToken);
252         $isLoggedIn = auth()->check();
253
254         if (empty($userDetails['email'])) {
255             throw new OidcException(trans('errors.oidc_no_email_address'));
256         }
257
258         if ($isLoggedIn) {
259             throw new OidcException(trans('errors.oidc_already_logged_in'));
260         }
261
262         try {
263             $user = $this->registrationService->findOrRegister(
264                 $userDetails['name'],
265                 $userDetails['email'],
266                 $userDetails['external_id']
267             );
268         } catch (UserRegistrationException $exception) {
269             throw new OidcException($exception->getMessage());
270         }
271
272         if ($this->shouldSyncGroups()) {
273             $groups = $userDetails['groups'];
274             $detachExisting = $this->config()['remove_from_groups'];
275             $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
276         }
277
278         $this->loginService->login($user, 'oidc');
279
280         return $user;
281     }
282
283     /**
284      * Get the OIDC config from the application.
285      */
286     protected function config(): array
287     {
288         return config('oidc');
289     }
290
291     /**
292      * Check if groups should be synced.
293      */
294     protected function shouldSyncGroups(): bool
295     {
296         return $this->config()['user_to_groups'] !== false;
297     }
298
299     /**
300      * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
301      * Returns a post-app-logout redirect URL.
302      * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
303      * @throws OidcException
304      */
305     public function logout(): string
306     {
307         $oidcToken = session()->pull("oidc_id_token");
308         $defaultLogoutUrl = url($this->loginService->logout());
309         $oidcSettings = $this->getProviderSettings();
310
311         if (!$oidcSettings->endSessionEndpoint) {
312             return $defaultLogoutUrl;
313         }
314
315         $endpointParams = [
316             'id_token_hint' => $oidcToken,
317             'post_logout_redirect_uri' => $defaultLogoutUrl,
318         ];
319
320         $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
321
322         return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);
323     }
324 }