]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
a7f31e56bf1498b40be0d725ba416c36acb4b6ec
[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      * Provides back an authorize redirect URL, in addition to other
37      * details which may be required for the auth flow.
38      *
39      * @throws OidcException
40      *
41      * @return array{url: string, state: string}
42      */
43     public function login(): array
44     {
45         $settings = $this->getProviderSettings();
46         $provider = $this->getProvider($settings);
47
48         $url = $provider->getAuthorizationUrl();
49         session()->put('oidc_pkce_code', $provider->getPkceCode() ?? '');
50
51         return [
52             'url'   => $url,
53             'state' => $provider->getState(),
54         ];
55     }
56
57     /**
58      * Process the Authorization response from the authorization server and
59      * return the matching, or new if registration active, user matched to the
60      * authorization server. Throws if the user cannot be auth if not authenticated.
61      *
62      * @throws JsonDebugException
63      * @throws OidcException
64      * @throws StoppedAuthenticationException
65      * @throws IdentityProviderException
66      */
67     public function processAuthorizeResponse(?string $authorizationCode): User
68     {
69         $settings = $this->getProviderSettings();
70         $provider = $this->getProvider($settings);
71
72         // Set PKCE code flashed at login
73         $pkceCode = session()->pull('oidc_pkce_code', '');
74         $provider->setPkceCode($pkceCode);
75
76         // Try to exchange authorization code for access token
77         $accessToken = $provider->getAccessToken('authorization_code', [
78             'code' => $authorizationCode,
79         ]);
80
81         return $this->processAccessTokenCallback($accessToken, $settings);
82     }
83
84     /**
85      * @throws OidcException
86      */
87     protected function getProviderSettings(): OidcProviderSettings
88     {
89         $config = $this->config();
90         $settings = new OidcProviderSettings([
91             'issuer'                => $config['issuer'],
92             'clientId'              => $config['client_id'],
93             'clientSecret'          => $config['client_secret'],
94             'authorizationEndpoint' => $config['authorization_endpoint'],
95             'tokenEndpoint'         => $config['token_endpoint'],
96             'endSessionEndpoint'    => is_string($config['end_session_endpoint']) ? $config['end_session_endpoint'] : null,
97             'userinfoEndpoint'      => $config['userinfo_endpoint'],
98         ]);
99
100         // Use keys if configured
101         if (!empty($config['jwt_public_key'])) {
102             $settings->keys = [$config['jwt_public_key']];
103         }
104
105         // Run discovery
106         if ($config['discover'] ?? false) {
107             try {
108                 $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
109             } catch (OidcIssuerDiscoveryException $exception) {
110                 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
111             }
112         }
113
114         // Prevent use of RP-initiated logout if specifically disabled
115         // Or force use of a URL if specifically set.
116         if ($config['end_session_endpoint'] === false) {
117             $settings->endSessionEndpoint = null;
118         } else if (is_string($config['end_session_endpoint'])) {
119             $settings->endSessionEndpoint = $config['end_session_endpoint'];
120         }
121
122         $settings->validate();
123
124         return $settings;
125     }
126
127     /**
128      * Load the underlying OpenID Connect Provider.
129      */
130     protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
131     {
132         $provider = new OidcOAuthProvider([
133             ...$settings->arrayForOAuthProvider(),
134             'redirectUri' => url('/oidc/callback'),
135         ], [
136             'httpClient'     => $this->http->buildClient(5),
137             'optionProvider' => new HttpBasicAuthOptionProvider(),
138         ]);
139
140         foreach ($this->getAdditionalScopes() as $scope) {
141             $provider->addScope($scope);
142         }
143
144         return $provider;
145     }
146
147     /**
148      * Get any user-defined addition/custom scopes to apply to the authentication request.
149      *
150      * @return string[]
151      */
152     protected function getAdditionalScopes(): array
153     {
154         $scopeConfig = $this->config()['additional_scopes'] ?: '';
155
156         $scopeArr = explode(',', $scopeConfig);
157         $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
158
159         return array_filter($scopeArr);
160     }
161
162     /**
163      * Calculate the display name.
164      */
165     protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
166     {
167         $displayNameAttrString = $this->config()['display_name_claims'] ?? '';
168         $displayNameAttrs = explode('|', $displayNameAttrString);
169
170         $displayName = [];
171         foreach ($displayNameAttrs as $dnAttr) {
172             $dnComponent = $token->getClaim($dnAttr) ?? '';
173             if ($dnComponent !== '') {
174                 $displayName[] = $dnComponent;
175             }
176         }
177
178         if (count($displayName) == 0) {
179             $displayName[] = $defaultValue;
180         }
181
182         return implode(' ', $displayName);
183     }
184
185     /**
186      * Extract the assigned groups from the id token.
187      *
188      * @return string[]
189      */
190     protected function getUserGroups(OidcIdToken $token): array
191     {
192         $groupsAttr = $this->config()['groups_claim'];
193         if (empty($groupsAttr)) {
194             return [];
195         }
196
197         $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
198         if (!is_array($groupsList)) {
199             return [];
200         }
201
202         return array_values(array_filter($groupsList, function ($val) {
203             return is_string($val);
204         }));
205     }
206
207     /**
208      * Extract the details of a user from an ID token.
209      *
210      * @return array{name: string, email: string, external_id: string, groups: string[]}
211      */
212     protected function getUserDetails(OidcIdToken $token): array
213     {
214         $idClaim = $this->config()['external_id_claim'];
215         $id = $token->getClaim($idClaim);
216
217         return [
218             'external_id' => $id,
219             'email'       => $token->getClaim('email'),
220             'name'        => $this->getUserDisplayName($token, $id),
221             'groups'      => $this->getUserGroups($token),
222         ];
223     }
224
225     /**
226      * Processes a received access token for a user. Login the user when
227      * they exist, optionally registering them automatically.
228      *
229      * @throws OidcException
230      * @throws JsonDebugException
231      * @throws StoppedAuthenticationException
232      */
233     protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
234     {
235         $idTokenText = $accessToken->getIdToken();
236         $idToken = new OidcIdToken(
237             $idTokenText,
238             $settings->issuer,
239             $settings->keys,
240         );
241
242         session()->put("oidc_id_token", $idTokenText);
243
244         // TODO - This should not affect id token validation
245         // TODO - Should only call if we're missing properties
246         if (!empty($settings->userinfoEndpoint)) {
247             $provider = $this->getProvider($settings);
248             $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
249             $response = $provider->getParsedResponse($request);
250             // TODO - Ensure response content-type is "application/json" before using in this way (5.3.2)
251             // TODO - The sub Claim in the UserInfo Response MUST be verified to exactly match the sub Claim in the ID Token; if they do not match, the UserInfo Response values MUST NOT be used. (5.3.2)
252             // TODO - Response validation (5.3.4)
253                // TODO - Verify that the OP that responded was the intended OP through a TLS server certificate check, per RFC 6125 [RFC6125].
254                // TODO - If the Client has provided a userinfo_encrypted_response_alg parameter during Registration, decrypt the UserInfo Response using the keys specified during Registration.
255                // TODO - If the response was signed, the Client SHOULD validate the signature according to JWS [JWS].
256             $claims = $idToken->getAllClaims();
257             foreach ($response as $key => $value) {
258                 $claims[$key] = $value;
259             }
260             // TODO - Should maybe remain separate from IdToken completely
261             $idToken->replaceClaims($claims);
262         }
263
264         $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
265             'access_token' => $accessToken->getToken(),
266             'expires_in' => $accessToken->getExpires(),
267             'refresh_token' => $accessToken->getRefreshToken(),
268         ]);
269
270         if (!is_null($returnClaims)) {
271             $idToken->replaceClaims($returnClaims);
272         }
273
274         if ($this->config()['dump_user_details']) {
275             throw new JsonDebugException($idToken->getAllClaims());
276         }
277
278         try {
279             $idToken->validate($settings->clientId);
280         } catch (OidcInvalidTokenException $exception) {
281             throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
282         }
283
284         $userDetails = $this->getUserDetails($idToken);
285         $isLoggedIn = auth()->check();
286
287         if (empty($userDetails['email'])) {
288             throw new OidcException(trans('errors.oidc_no_email_address'));
289         }
290
291         if ($isLoggedIn) {
292             throw new OidcException(trans('errors.oidc_already_logged_in'));
293         }
294
295         try {
296             $user = $this->registrationService->findOrRegister(
297                 $userDetails['name'],
298                 $userDetails['email'],
299                 $userDetails['external_id']
300             );
301         } catch (UserRegistrationException $exception) {
302             throw new OidcException($exception->getMessage());
303         }
304
305         if ($this->shouldSyncGroups()) {
306             $groups = $userDetails['groups'];
307             $detachExisting = $this->config()['remove_from_groups'];
308             $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
309         }
310
311         $this->loginService->login($user, 'oidc');
312
313         return $user;
314     }
315
316     /**
317      * Get the OIDC config from the application.
318      */
319     protected function config(): array
320     {
321         return config('oidc');
322     }
323
324     /**
325      * Check if groups should be synced.
326      */
327     protected function shouldSyncGroups(): bool
328     {
329         return $this->config()['user_to_groups'] !== false;
330     }
331
332     /**
333      * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
334      * Returns a post-app-logout redirect URL.
335      * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
336      * @throws OidcException
337      */
338     public function logout(): string
339     {
340         $oidcToken = session()->pull("oidc_id_token");
341         $defaultLogoutUrl = url($this->loginService->logout());
342         $oidcSettings = $this->getProviderSettings();
343
344         if (!$oidcSettings->endSessionEndpoint) {
345             return $defaultLogoutUrl;
346         }
347
348         $endpointParams = [
349             'id_token_hint' => $oidcToken,
350             'post_logout_redirect_uri' => $defaultLogoutUrl,
351         ];
352
353         $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
354
355         return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);
356     }
357 }