]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
Vectors: Added command to regenerate for all
[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\Facades\Cache;
16 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
17 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
18
19 /**
20  * Class OpenIdConnectService
21  * Handles any app-specific OIDC tasks.
22  */
23 class OidcService
24 {
25     public function __construct(
26         protected RegistrationService $registrationService,
27         protected LoginService $loginService,
28         protected HttpRequestService $http,
29         protected GroupSyncService $groupService
30     ) {
31     }
32
33     /**
34      * Initiate an authorization flow.
35      * Provides back an authorize redirect URL, in addition to other
36      * details which may be required for the auth flow.
37      *
38      * @throws OidcException
39      *
40      * @return array{url: string, state: string}
41      */
42     public function login(): array
43     {
44         $settings = $this->getProviderSettings();
45         $provider = $this->getProvider($settings);
46
47         $url = $provider->getAuthorizationUrl();
48         session()->put('oidc_pkce_code', $provider->getPkceCode() ?? '');
49
50         return [
51             'url'   => $url,
52             'state' => $provider->getState(),
53         ];
54     }
55
56     /**
57      * Process the Authorization response from the authorization server and
58      * return the matching, or new if registration active, user matched to the
59      * authorization server. Throws if the user cannot be auth if not authenticated.
60      *
61      * @throws JsonDebugException
62      * @throws OidcException
63      * @throws StoppedAuthenticationException
64      * @throws IdentityProviderException
65      */
66     public function processAuthorizeResponse(?string $authorizationCode): User
67     {
68         $settings = $this->getProviderSettings();
69         $provider = $this->getProvider($settings);
70
71         // Set PKCE code flashed at login
72         $pkceCode = session()->pull('oidc_pkce_code', '');
73         $provider->setPkceCode($pkceCode);
74
75         // Try to exchange authorization code for access token
76         $accessToken = $provider->getAccessToken('authorization_code', [
77             'code' => $authorizationCode,
78         ]);
79
80         return $this->processAccessTokenCallback($accessToken, $settings);
81     }
82
83     /**
84      * @throws OidcException
85      */
86     protected function getProviderSettings(): OidcProviderSettings
87     {
88         $config = $this->config();
89         $settings = new OidcProviderSettings([
90             'issuer'                => $config['issuer'],
91             'clientId'              => $config['client_id'],
92             'clientSecret'          => $config['client_secret'],
93             'authorizationEndpoint' => $config['authorization_endpoint'],
94             'tokenEndpoint'         => $config['token_endpoint'],
95             'endSessionEndpoint'    => is_string($config['end_session_endpoint']) ? $config['end_session_endpoint'] : null,
96             'userinfoEndpoint'      => $config['userinfo_endpoint'],
97         ]);
98
99         // Use keys if configured
100         if (!empty($config['jwt_public_key'])) {
101             $settings->keys = [$config['jwt_public_key']];
102         }
103
104         // Run discovery
105         if ($config['discover'] ?? false) {
106             try {
107                 $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
108             } catch (OidcIssuerDiscoveryException $exception) {
109                 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
110             }
111         }
112
113         // Prevent use of RP-initiated logout if specifically disabled
114         // Or force use of a URL if specifically set.
115         if ($config['end_session_endpoint'] === false) {
116             $settings->endSessionEndpoint = null;
117         } else if (is_string($config['end_session_endpoint'])) {
118             $settings->endSessionEndpoint = $config['end_session_endpoint'];
119         }
120
121         $settings->validate();
122
123         return $settings;
124     }
125
126     /**
127      * Load the underlying OpenID Connect Provider.
128      */
129     protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
130     {
131         $provider = new OidcOAuthProvider([
132             ...$settings->arrayForOAuthProvider(),
133             'redirectUri' => url('/oidc/callback'),
134         ], [
135             'httpClient'     => $this->http->buildClient(5),
136             'optionProvider' => new HttpBasicAuthOptionProvider(),
137         ]);
138
139         foreach ($this->getAdditionalScopes() as $scope) {
140             $provider->addScope($scope);
141         }
142
143         return $provider;
144     }
145
146     /**
147      * Get any user-defined addition/custom scopes to apply to the authentication request.
148      *
149      * @return string[]
150      */
151     protected function getAdditionalScopes(): array
152     {
153         $scopeConfig = $this->config()['additional_scopes'] ?: '';
154
155         $scopeArr = explode(',', $scopeConfig);
156         $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
157
158         return array_filter($scopeArr);
159     }
160
161     /**
162      * Processes a received access token for a user. Login the user when
163      * they exist, optionally registering them automatically.
164      *
165      * @throws OidcException
166      * @throws JsonDebugException
167      * @throws StoppedAuthenticationException
168      */
169     protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
170     {
171         $idTokenText = $accessToken->getIdToken();
172         $idToken = new OidcIdToken(
173             $idTokenText,
174             $settings->issuer,
175             $settings->keys,
176         );
177
178         session()->put("oidc_id_token", $idTokenText);
179
180         $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
181             'access_token' => $accessToken->getToken(),
182             'expires_in' => $accessToken->getExpires(),
183             'refresh_token' => $accessToken->getRefreshToken(),
184         ]);
185
186         if (!is_null($returnClaims)) {
187             $idToken->replaceClaims($returnClaims);
188         }
189
190         if ($this->config()['dump_user_details']) {
191             throw new JsonDebugException($idToken->getAllClaims());
192         }
193
194         try {
195             $idToken->validate($settings->clientId);
196         } catch (OidcInvalidTokenException $exception) {
197             throw new OidcException("ID token validation failed with error: {$exception->getMessage()}");
198         }
199
200         $userDetails = $this->getUserDetailsFromToken($idToken, $accessToken, $settings);
201         if (empty($userDetails->email)) {
202             throw new OidcException(trans('errors.oidc_no_email_address'));
203         }
204         if (empty($userDetails->name)) {
205             $userDetails->name = $userDetails->externalId;
206         }
207
208         $isLoggedIn = auth()->check();
209         if ($isLoggedIn) {
210             throw new OidcException(trans('errors.oidc_already_logged_in'));
211         }
212
213         try {
214             $user = $this->registrationService->findOrRegister(
215                 $userDetails->name,
216                 $userDetails->email,
217                 $userDetails->externalId
218             );
219         } catch (UserRegistrationException $exception) {
220             throw new OidcException($exception->getMessage());
221         }
222
223         if ($this->shouldSyncGroups()) {
224             $detachExisting = $this->config()['remove_from_groups'];
225             $this->groupService->syncUserWithFoundGroups($user, $userDetails->groups ?? [], $detachExisting);
226         }
227
228         $this->loginService->login($user, 'oidc');
229
230         return $user;
231     }
232
233     /**
234      * @throws OidcException
235      */
236     protected function getUserDetailsFromToken(OidcIdToken $idToken, OidcAccessToken $accessToken, OidcProviderSettings $settings): OidcUserDetails
237     {
238         $userDetails = new OidcUserDetails();
239         $userDetails->populate(
240             $idToken,
241             $this->config()['external_id_claim'],
242             $this->config()['display_name_claims'] ?? '',
243             $this->config()['groups_claim'] ?? ''
244         );
245
246         if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) {
247             $provider = $this->getProvider($settings);
248             $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
249             $response = new OidcUserinfoResponse(
250                 $provider->getResponse($request),
251                 $settings->issuer,
252                 $settings->keys,
253             );
254
255             try {
256                 $response->validate($idToken->getClaim('sub'), $settings->clientId);
257             } catch (OidcInvalidTokenException $exception) {
258                 throw new OidcException("Userinfo endpoint response validation failed with error: {$exception->getMessage()}");
259             }
260
261             $userDetails->populate(
262                 $response,
263                 $this->config()['external_id_claim'],
264                 $this->config()['display_name_claims'] ?? '',
265                 $this->config()['groups_claim'] ?? ''
266             );
267         }
268
269         return $userDetails;
270     }
271
272     /**
273      * Get the OIDC config from the application.
274      */
275     protected function config(): array
276     {
277         return config('oidc');
278     }
279
280     /**
281      * Check if groups should be synced.
282      */
283     protected function shouldSyncGroups(): bool
284     {
285         return $this->config()['user_to_groups'] !== false;
286     }
287
288     /**
289      * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
290      * Returns a post-app-logout redirect URL.
291      * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
292      * @throws OidcException
293      */
294     public function logout(): string
295     {
296         $oidcToken = session()->pull("oidc_id_token");
297         $defaultLogoutUrl = url($this->loginService->logout());
298         $oidcSettings = $this->getProviderSettings();
299
300         if (!$oidcSettings->endSessionEndpoint) {
301             return $defaultLogoutUrl;
302         }
303
304         $endpointParams = [
305             'id_token_hint' => $oidcToken,
306             'post_logout_redirect_uri' => $defaultLogoutUrl,
307         ];
308
309         $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
310
311         return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);
312     }
313 }