]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
5a73484c1ee1ccb411bcdee1eb9b35f728c34431
[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 validate failed with error: {$exception->getMessage()}");
198         }
199
200         $userDetails = OidcUserDetails::fromToken(
201             $idToken,
202             $this->config()['external_id_claim'],
203             $this->config()['display_name_claims'] ?? '',
204             $this->config()['groups_claim'] ?? ''
205         );
206
207         // TODO - This should not affect id token validation
208         if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) {
209             $provider = $this->getProvider($settings);
210             $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
211             $response = $provider->getParsedResponse($request);
212             // TODO - Ensure response content-type is "application/json" before using in this way (5.3.2)
213             // TODO - The sub Claim in the UserInfo Response MUST be verified to exactly match the sub Claim in the ID Token; if they do not match, the UserInfo Response values MUST NOT be used. (5.3.2)
214             // TODO - Response validation (5.3.4)
215             // TODO - Verify that the OP that responded was the intended OP through a TLS server certificate check, per RFC 6125 [RFC6125].
216             // TODO - If the Client has provided a userinfo_encrypted_response_alg parameter during Registration, decrypt the UserInfo Response using the keys specified during Registration.
217             // TODO - If the response was signed, the Client SHOULD validate the signature according to JWS [JWS].
218             $claims = $idToken->getAllClaims();
219             foreach ($response as $key => $value) {
220                 $claims[$key] = $value;
221             }
222             // TODO - Should maybe remain separate from IdToken completely
223             $idToken->replaceClaims($claims);
224         }
225
226         if (empty($userDetails->email)) {
227             throw new OidcException(trans('errors.oidc_no_email_address'));
228         }
229
230         $isLoggedIn = auth()->check();
231         if ($isLoggedIn) {
232             throw new OidcException(trans('errors.oidc_already_logged_in'));
233         }
234
235         try {
236             $user = $this->registrationService->findOrRegister(
237                 $userDetails->name,
238                 $userDetails->email,
239                 $userDetails->externalId
240             );
241         } catch (UserRegistrationException $exception) {
242             throw new OidcException($exception->getMessage());
243         }
244
245         if ($this->shouldSyncGroups()) {
246             $detachExisting = $this->config()['remove_from_groups'];
247             $this->groupService->syncUserWithFoundGroups($user, $userDetails->groups ?? [], $detachExisting);
248         }
249
250         $this->loginService->login($user, 'oidc');
251
252         return $user;
253     }
254
255     /**
256      * Get the OIDC config from the application.
257      */
258     protected function config(): array
259     {
260         return config('oidc');
261     }
262
263     /**
264      * Check if groups should be synced.
265      */
266     protected function shouldSyncGroups(): bool
267     {
268         return $this->config()['user_to_groups'] !== false;
269     }
270
271     /**
272      * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
273      * Returns a post-app-logout redirect URL.
274      * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
275      * @throws OidcException
276      */
277     public function logout(): string
278     {
279         $oidcToken = session()->pull("oidc_id_token");
280         $defaultLogoutUrl = url($this->loginService->logout());
281         $oidcSettings = $this->getProviderSettings();
282
283         if (!$oidcSettings->endSessionEndpoint) {
284             return $defaultLogoutUrl;
285         }
286
287         $endpointParams = [
288             'id_token_hint' => $oidcToken,
289             'post_logout_redirect_uri' => $defaultLogoutUrl,
290         ];
291
292         $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
293
294         return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);
295     }
296 }