]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
38eecdff35c8b4f4df3a17d97e5b310173bea2ab
[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\Uploads\UserAvatars;
15 use BookStack\Users\Models\User;
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         protected UserAvatars $userAvatars
32     ) {
33     }
34
35     /**
36      * Initiate an authorization flow.
37      * Provides back an authorize redirect URL, in addition to other
38      * details which may be required for the auth flow.
39      *
40      * @throws OidcException
41      *
42      * @return array{url: string, state: string}
43      */
44     public function login(): array
45     {
46         $settings = $this->getProviderSettings();
47         $provider = $this->getProvider($settings);
48
49         $url = $provider->getAuthorizationUrl();
50         session()->put('oidc_pkce_code', $provider->getPkceCode() ?? '');
51
52         return [
53             'url'   => $url,
54             'state' => $provider->getState(),
55         ];
56     }
57
58     /**
59      * Process the Authorization response from the authorization server and
60      * return the matching, or new if registration active, user matched to the
61      * authorization server. Throws if the user cannot be auth if not authenticated.
62      *
63      * @throws JsonDebugException
64      * @throws OidcException
65      * @throws StoppedAuthenticationException
66      * @throws IdentityProviderException
67      */
68     public function processAuthorizeResponse(?string $authorizationCode): User
69     {
70         $settings = $this->getProviderSettings();
71         $provider = $this->getProvider($settings);
72
73         // Set PKCE code flashed at login
74         $pkceCode = session()->pull('oidc_pkce_code', '');
75         $provider->setPkceCode($pkceCode);
76
77         // Try to exchange authorization code for access token
78         $accessToken = $provider->getAccessToken('authorization_code', [
79             'code' => $authorizationCode,
80         ]);
81
82         return $this->processAccessTokenCallback($accessToken, $settings);
83     }
84
85     /**
86      * @throws OidcException
87      */
88     protected function getProviderSettings(): OidcProviderSettings
89     {
90         $config = $this->config();
91         $settings = new OidcProviderSettings([
92             'issuer'                => $config['issuer'],
93             'clientId'              => $config['client_id'],
94             'clientSecret'          => $config['client_secret'],
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([
134             ...$settings->arrayForOAuthProvider(),
135             'redirectUri' => url('/oidc/callback'),
136         ], [
137             'httpClient'     => $this->http->buildClient(5),
138             'optionProvider' => new HttpBasicAuthOptionProvider(),
139         ]);
140
141         foreach ($this->getAdditionalScopes() as $scope) {
142             $provider->addScope($scope);
143         }
144
145         return $provider;
146     }
147
148     /**
149      * Get any user-defined addition/custom scopes to apply to the authentication request.
150      *
151      * @return string[]
152      */
153     protected function getAdditionalScopes(): array
154     {
155         $scopeConfig = $this->config()['additional_scopes'] ?: '';
156
157         $scopeArr = explode(',', $scopeConfig);
158         $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
159
160         return array_filter($scopeArr);
161     }
162
163     /**
164      * Processes a received access token for a user. Login the user when
165      * they exist, optionally registering them automatically.
166      *
167      * @throws OidcException
168      * @throws JsonDebugException
169      * @throws StoppedAuthenticationException
170      */
171     protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
172     {
173         $idTokenText = $accessToken->getIdToken();
174         $idToken = new OidcIdToken(
175             $idTokenText,
176             $settings->issuer,
177             $settings->keys,
178         );
179
180         session()->put("oidc_id_token", $idTokenText);
181
182         $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
183             'access_token' => $accessToken->getToken(),
184             'expires_in' => $accessToken->getExpires(),
185             'refresh_token' => $accessToken->getRefreshToken(),
186         ]);
187
188         if (!is_null($returnClaims)) {
189             $idToken->replaceClaims($returnClaims);
190         }
191
192         if ($this->config()['dump_user_details']) {
193             throw new JsonDebugException($idToken->getAllClaims());
194         }
195
196         try {
197             $idToken->validate($settings->clientId);
198         } catch (OidcInvalidTokenException $exception) {
199             throw new OidcException("ID token validation failed with error: {$exception->getMessage()}");
200         }
201
202         $userDetails = $this->getUserDetailsFromToken($idToken, $accessToken, $settings);
203         if (empty($userDetails->email)) {
204             throw new OidcException(trans('errors.oidc_no_email_address'));
205         }
206         if (empty($userDetails->name)) {
207             $userDetails->name = $userDetails->externalId;
208         }
209
210         $isLoggedIn = auth()->check();
211         if ($isLoggedIn) {
212             throw new OidcException(trans('errors.oidc_already_logged_in'));
213         }
214
215         try {
216             $user = $this->registrationService->findOrRegister(
217                 $userDetails->name,
218                 $userDetails->email,
219                 $userDetails->externalId
220             );
221         } catch (UserRegistrationException $exception) {
222             throw new OidcException($exception->getMessage());
223         }
224
225         // TODO - Update this (and tests and config option comments) to actually align with LDAP system
226         //  which syncs whenever on login or registration, where there's no existing avatar.
227         if ($this->config()['fetch_avatar'] && $user->wasRecentlyCreated && $userDetails->picture) {
228             $this->userAvatars->assignToUserFromUrl($user, $userDetails->picture);
229         }
230
231         if ($this->shouldSyncGroups()) {
232             $detachExisting = $this->config()['remove_from_groups'];
233             $this->groupService->syncUserWithFoundGroups($user, $userDetails->groups ?? [], $detachExisting);
234         }
235
236         $this->loginService->login($user, 'oidc');
237
238         return $user;
239     }
240
241     /**
242      * @throws OidcException
243      */
244     protected function getUserDetailsFromToken(OidcIdToken $idToken, OidcAccessToken $accessToken, OidcProviderSettings $settings): OidcUserDetails
245     {
246         $userDetails = new OidcUserDetails();
247         $userDetails->populate(
248             $idToken,
249             $this->config()['external_id_claim'],
250             $this->config()['display_name_claims'] ?? '',
251             $this->config()['groups_claim'] ?? ''
252         );
253
254         if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) {
255             $provider = $this->getProvider($settings);
256             $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
257             $response = new OidcUserinfoResponse(
258                 $provider->getResponse($request),
259                 $settings->issuer,
260                 $settings->keys,
261             );
262
263             try {
264                 $response->validate($idToken->getClaim('sub'), $settings->clientId);
265             } catch (OidcInvalidTokenException $exception) {
266                 throw new OidcException("Userinfo endpoint response validation failed with error: {$exception->getMessage()}");
267             }
268
269             $userDetails->populate(
270                 $response,
271                 $this->config()['external_id_claim'],
272                 $this->config()['display_name_claims'] ?? '',
273                 $this->config()['groups_claim'] ?? ''
274             );
275         }
276
277         return $userDetails;
278     }
279
280     /**
281      * Get the OIDC config from the application.
282      */
283     protected function config(): array
284     {
285         return config('oidc');
286     }
287
288     /**
289      * Check if groups should be synced.
290      */
291     protected function shouldSyncGroups(): bool
292     {
293         return $this->config()['user_to_groups'] !== false;
294     }
295
296     /**
297      * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
298      * Returns a post-app-logout redirect URL.
299      * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
300      * @throws OidcException
301      */
302     public function logout(): string
303     {
304         $oidcToken = session()->pull("oidc_id_token");
305         $defaultLogoutUrl = url($this->loginService->logout());
306         $oidcSettings = $this->getProviderSettings();
307
308         if (!$oidcSettings->endSessionEndpoint) {
309             return $defaultLogoutUrl;
310         }
311
312         $endpointParams = [
313             'id_token_hint' => $oidcToken,
314             'post_logout_redirect_uri' => $defaultLogoutUrl,
315         ];
316
317         $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
318
319         return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);
320     }
321 }