]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
Merge branch 'development' into lukeshu/oidc-development
[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             'redirectUri'           => url('/oidc/callback'),
95             'authorizationEndpoint' => $config['authorization_endpoint'],
96             'tokenEndpoint'         => $config['token_endpoint'],
97             'endSessionEndpoint'    => is_string($config['end_session_endpoint']) ? $config['end_session_endpoint'] : null,
98             'userinfoEndpoint'      => $config['userinfo_endpoint'],
99         ]);
100
101         // Use keys if configured
102         if (!empty($config['jwt_public_key'])) {
103             $settings->keys = [$config['jwt_public_key']];
104         }
105
106         // Run discovery
107         if ($config['discover'] ?? false) {
108             try {
109                 $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
110             } catch (OidcIssuerDiscoveryException $exception) {
111                 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
112             }
113         }
114
115         // Prevent use of RP-initiated logout if specifically disabled
116         // Or force use of a URL if specifically set.
117         if ($config['end_session_endpoint'] === false) {
118             $settings->endSessionEndpoint = null;
119         } else if (is_string($config['end_session_endpoint'])) {
120             $settings->endSessionEndpoint = $config['end_session_endpoint'];
121         }
122
123         $settings->validate();
124
125         return $settings;
126     }
127
128     /**
129      * Load the underlying OpenID Connect Provider.
130      */
131     protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
132     {
133         $provider = new OidcOAuthProvider($settings->arrayForProvider(), [
134             'httpClient'     => $this->http->buildClient(5),
135             'optionProvider' => new HttpBasicAuthOptionProvider(),
136         ]);
137
138         foreach ($this->getAdditionalScopes() as $scope) {
139             $provider->addScope($scope);
140         }
141
142         return $provider;
143     }
144
145     /**
146      * Get any user-defined addition/custom scopes to apply to the authentication request.
147      *
148      * @return string[]
149      */
150     protected function getAdditionalScopes(): array
151     {
152         $scopeConfig = $this->config()['additional_scopes'] ?: '';
153
154         $scopeArr = explode(',', $scopeConfig);
155         $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
156
157         return array_filter($scopeArr);
158     }
159
160     /**
161      * Calculate the display name.
162      */
163     protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
164     {
165         $displayNameAttrString = $this->config()['display_name_claims'] ?? '';
166         $displayNameAttrs = explode('|', $displayNameAttrString);
167
168         $displayName = [];
169         foreach ($displayNameAttrs as $dnAttr) {
170             $dnComponent = $token->getClaim($dnAttr) ?? '';
171             if ($dnComponent !== '') {
172                 $displayName[] = $dnComponent;
173             }
174         }
175
176         if (count($displayName) == 0) {
177             $displayName[] = $defaultValue;
178         }
179
180         return implode(' ', $displayName);
181     }
182
183     /**
184      * Extract the assigned groups from the id token.
185      *
186      * @return string[]
187      */
188     protected function getUserGroups(OidcIdToken $token): array
189     {
190         $groupsAttr = $this->config()['groups_claim'];
191         if (empty($groupsAttr)) {
192             return [];
193         }
194
195         $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
196         if (!is_array($groupsList)) {
197             return [];
198         }
199
200         return array_values(array_filter($groupsList, function ($val) {
201             return is_string($val);
202         }));
203     }
204
205     /**
206      * Extract the details of a user from an ID token.
207      *
208      * @return array{name: string, email: string, external_id: string, groups: string[]}
209      */
210     protected function getUserDetails(OidcIdToken $token): array
211     {
212         $idClaim = $this->config()['external_id_claim'];
213         $id = $token->getClaim($idClaim);
214
215         return [
216             'external_id' => $id,
217             'email'       => $token->getClaim('email'),
218             'name'        => $this->getUserDisplayName($token, $id),
219             'groups'      => $this->getUserGroups($token),
220         ];
221     }
222
223     /**
224      * Processes a received access token for a user. Login the user when
225      * they exist, optionally registering them automatically.
226      *
227      * @throws OidcException
228      * @throws JsonDebugException
229      * @throws StoppedAuthenticationException
230      */
231     protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
232     {
233         $idTokenText = $accessToken->getIdToken();
234         $idToken = new OidcIdToken(
235             $idTokenText,
236             $settings->issuer,
237             $settings->keys,
238         );
239
240         session()->put("oidc_id_token", $idTokenText);
241
242         if (!empty($settings->userinfoEndpoint)) {
243             $provider = $this->getProvider($settings);
244             $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
245             $response = $provider->getParsedResponse($request);
246             $claims = $idToken->getAllClaims();
247             foreach ($response as $key => $value) {
248                 $claims[$key] = $value;
249             }
250             $idToken->replaceClaims($claims);
251         }
252
253         $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
254             'access_token' => $accessToken->getToken(),
255             'expires_in' => $accessToken->getExpires(),
256             'refresh_token' => $accessToken->getRefreshToken(),
257         ]);
258
259         if (!is_null($returnClaims)) {
260             $idToken->replaceClaims($returnClaims);
261         }
262
263         if ($this->config()['dump_user_details']) {
264             throw new JsonDebugException($idToken->getAllClaims());
265         }
266
267         try {
268             $idToken->validate($settings->clientId);
269         } catch (OidcInvalidTokenException $exception) {
270             throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
271         }
272
273         $userDetails = $this->getUserDetails($idToken);
274         $isLoggedIn = auth()->check();
275
276         if (empty($userDetails['email'])) {
277             throw new OidcException(trans('errors.oidc_no_email_address'));
278         }
279
280         if ($isLoggedIn) {
281             throw new OidcException(trans('errors.oidc_already_logged_in'));
282         }
283
284         try {
285             $user = $this->registrationService->findOrRegister(
286                 $userDetails['name'],
287                 $userDetails['email'],
288                 $userDetails['external_id']
289             );
290         } catch (UserRegistrationException $exception) {
291             throw new OidcException($exception->getMessage());
292         }
293
294         if ($this->shouldSyncGroups()) {
295             $groups = $userDetails['groups'];
296             $detachExisting = $this->config()['remove_from_groups'];
297             $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
298         }
299
300         $this->loginService->login($user, 'oidc');
301
302         return $user;
303     }
304
305     /**
306      * Get the OIDC config from the application.
307      */
308     protected function config(): array
309     {
310         return config('oidc');
311     }
312
313     /**
314      * Check if groups should be synced.
315      */
316     protected function shouldSyncGroups(): bool
317     {
318         return $this->config()['user_to_groups'] !== false;
319     }
320
321     /**
322      * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
323      * Returns a post-app-logout redirect URL.
324      * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
325      * @throws OidcException
326      */
327     public function logout(): string
328     {
329         $oidcToken = session()->pull("oidc_id_token");
330         $defaultLogoutUrl = url($this->loginService->logout());
331         $oidcSettings = $this->getProviderSettings();
332
333         if (!$oidcSettings->endSessionEndpoint) {
334             return $defaultLogoutUrl;
335         }
336
337         $endpointParams = [
338             'id_token_hint' => $oidcToken,
339             'post_logout_redirect_uri' => $defaultLogoutUrl,
340         ];
341
342         $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
343
344         return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);
345     }
346 }