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