]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
Opensearch: Fixed XML declaration when php short tags enabled
[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         if ($this->config()['fetch_avatar'] && !$user->avatar()->exists() && $userDetails->picture) {
226             $this->userAvatars->assignToUserFromUrl($user, $userDetails->picture);
227         }
228
229         if ($this->shouldSyncGroups()) {
230             $detachExisting = $this->config()['remove_from_groups'];
231             $this->groupService->syncUserWithFoundGroups($user, $userDetails->groups ?? [], $detachExisting);
232         }
233
234         $this->loginService->login($user, 'oidc');
235
236         return $user;
237     }
238
239     /**
240      * @throws OidcException
241      */
242     protected function getUserDetailsFromToken(OidcIdToken $idToken, OidcAccessToken $accessToken, OidcProviderSettings $settings): OidcUserDetails
243     {
244         $userDetails = new OidcUserDetails();
245         $userDetails->populate(
246             $idToken,
247             $this->config()['external_id_claim'],
248             $this->config()['display_name_claims'] ?? '',
249             $this->config()['groups_claim'] ?? ''
250         );
251
252         if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) {
253             $provider = $this->getProvider($settings);
254             $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
255             $response = new OidcUserinfoResponse(
256                 $provider->getResponse($request),
257                 $settings->issuer,
258                 $settings->keys,
259             );
260
261             try {
262                 $response->validate($idToken->getClaim('sub'), $settings->clientId);
263             } catch (OidcInvalidTokenException $exception) {
264                 throw new OidcException("Userinfo endpoint response validation failed with error: {$exception->getMessage()}");
265             }
266
267             $userDetails->populate(
268                 $response,
269                 $this->config()['external_id_claim'],
270                 $this->config()['display_name_claims'] ?? '',
271                 $this->config()['groups_claim'] ?? ''
272             );
273         }
274
275         return $userDetails;
276     }
277
278     /**
279      * Get the OIDC config from the application.
280      */
281     protected function config(): array
282     {
283         return config('oidc');
284     }
285
286     /**
287      * Check if groups should be synced.
288      */
289     protected function shouldSyncGroups(): bool
290     {
291         return $this->config()['user_to_groups'] !== false;
292     }
293
294     /**
295      * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
296      * Returns a post-app-logout redirect URL.
297      * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
298      * @throws OidcException
299      */
300     public function logout(): string
301     {
302         $oidcToken = session()->pull("oidc_id_token");
303         $defaultLogoutUrl = url($this->loginService->logout());
304         $oidcSettings = $this->getProviderSettings();
305
306         if (!$oidcSettings->endSessionEndpoint) {
307             return $defaultLogoutUrl;
308         }
309
310         $endpointParams = [
311             'id_token_hint' => $oidcToken,
312             'post_logout_redirect_uri' => $defaultLogoutUrl,
313         ];
314
315         $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
316
317         return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);
318     }
319 }