]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
fba6dc9a8f34bc5189a2dbce0b3b19c13dc17868
[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
205         $isLoggedIn = auth()->check();
206         if ($isLoggedIn) {
207             throw new OidcException(trans('errors.oidc_already_logged_in'));
208         }
209
210         try {
211             $user = $this->registrationService->findOrRegister(
212                 $userDetails->name,
213                 $userDetails->email,
214                 $userDetails->externalId
215             );
216         } catch (UserRegistrationException $exception) {
217             throw new OidcException($exception->getMessage());
218         }
219
220         if ($this->shouldSyncGroups()) {
221             $detachExisting = $this->config()['remove_from_groups'];
222             $this->groupService->syncUserWithFoundGroups($user, $userDetails->groups ?? [], $detachExisting);
223         }
224
225         $this->loginService->login($user, 'oidc');
226
227         return $user;
228     }
229
230     /**
231      * @throws OidcException
232      */
233     protected function getUserDetailsFromToken(OidcIdToken $idToken, OidcAccessToken $accessToken, OidcProviderSettings $settings): OidcUserDetails
234     {
235         $userDetails = new OidcUserDetails();
236         $userDetails->populate(
237             $idToken,
238             $this->config()['external_id_claim'],
239             $this->config()['display_name_claims'] ?? '',
240             $this->config()['groups_claim'] ?? ''
241         );
242
243         if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) {
244             $provider = $this->getProvider($settings);
245             $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
246             $response = new OidcUserinfoResponse($provider->getResponse($request));
247
248             try {
249                 $response->validate($idToken->getClaim('sub'));
250             } catch (OidcInvalidTokenException $exception) {
251                 throw new OidcException("Userinfo endpoint response validation failed with error: {$exception->getMessage()}");
252             }
253
254             $userDetails->populate(
255                 $response,
256                 $this->config()['external_id_claim'],
257                 $this->config()['display_name_claims'] ?? '',
258                 $this->config()['groups_claim'] ?? ''
259             );
260         }
261
262         return $userDetails;
263     }
264
265     /**
266      * Get the OIDC config from the application.
267      */
268     protected function config(): array
269     {
270         return config('oidc');
271     }
272
273     /**
274      * Check if groups should be synced.
275      */
276     protected function shouldSyncGroups(): bool
277     {
278         return $this->config()['user_to_groups'] !== false;
279     }
280
281     /**
282      * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
283      * Returns a post-app-logout redirect URL.
284      * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
285      * @throws OidcException
286      */
287     public function logout(): string
288     {
289         $oidcToken = session()->pull("oidc_id_token");
290         $defaultLogoutUrl = url($this->loginService->logout());
291         $oidcSettings = $this->getProviderSettings();
292
293         if (!$oidcSettings->endSessionEndpoint) {
294             return $defaultLogoutUrl;
295         }
296
297         $endpointParams = [
298             'id_token_hint' => $oidcToken,
299             'post_logout_redirect_uri' => $defaultLogoutUrl,
300         ];
301
302         $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
303
304         return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);
305     }
306 }