5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\Role;
7 use BookStack\Auth\User;
8 use GuzzleHttp\Psr7\Request;
9 use GuzzleHttp\Psr7\Response;
10 use Illuminate\Testing\TestResponse;
11 use Tests\Helpers\OidcJwtHelper;
14 class OidcTest extends TestCase
16 protected string $keyFilePath;
19 protected function setUp(): void
22 // Set default config for OpenID Connect
24 $this->keyFile = tmpfile();
25 $this->keyFilePath = 'file://' . stream_get_meta_data($this->keyFile)['uri'];
26 file_put_contents($this->keyFilePath, OidcJwtHelper::publicPemKey());
29 'auth.method' => 'oidc',
30 'auth.defaults.guard' => 'oidc',
31 'oidc.name' => 'SingleSignOn-Testing',
32 'oidc.display_name_claims' => ['name'],
33 'oidc.client_id' => OidcJwtHelper::defaultClientId(),
34 'oidc.client_secret' => 'testpass',
35 'oidc.jwt_public_key' => $this->keyFilePath,
36 'oidc.issuer' => OidcJwtHelper::defaultIssuer(),
37 'oidc.authorization_endpoint' => 'https://oidc.local/auth',
38 'oidc.token_endpoint' => 'https://oidc.local/token',
39 'oidc.discover' => false,
40 'oidc.dump_user_details' => false,
41 'oidc.additional_scopes' => '',
42 'oidc.user_to_groups' => false,
43 'oidc.group_attribute' => 'group',
44 'oidc.remove_from_groups' => false,
48 protected function tearDown(): void
51 if (file_exists($this->keyFilePath)) {
52 unlink($this->keyFilePath);
56 public function test_login_option_shows_on_login_page()
58 $req = $this->get('/login');
59 $req->assertSeeText('SingleSignOn-Testing');
60 $this->withHtml($req)->assertElementExists('form[action$="/oidc/login"][method=POST] button');
63 public function test_oidc_routes_are_only_active_if_oidc_enabled()
65 config()->set(['auth.method' => 'standard']);
66 $routes = ['/login' => 'post', '/callback' => 'get'];
67 foreach ($routes as $uri => $method) {
68 $req = $this->call($method, '/oidc' . $uri);
69 $this->assertPermissionError($req);
73 public function test_forgot_password_routes_inaccessible()
75 $resp = $this->get('/password/email');
76 $this->assertPermissionError($resp);
78 $resp = $this->post('/password/email');
79 $this->assertPermissionError($resp);
81 $resp = $this->get('/password/reset/abc123');
82 $this->assertPermissionError($resp);
84 $resp = $this->post('/password/reset');
85 $this->assertPermissionError($resp);
88 public function test_standard_login_routes_inaccessible()
90 $resp = $this->post('/login');
91 $this->assertPermissionError($resp);
94 public function test_logout_route_functions()
96 $this->actingAs($this->getEditor());
97 $this->post('/logout');
98 $this->assertFalse(auth()->check());
101 public function test_user_invite_routes_inaccessible()
103 $resp = $this->get('/register/invite/abc123');
104 $this->assertPermissionError($resp);
106 $resp = $this->post('/register/invite/abc123');
107 $this->assertPermissionError($resp);
110 public function test_user_register_routes_inaccessible()
112 $resp = $this->get('/register');
113 $this->assertPermissionError($resp);
115 $resp = $this->post('/register');
116 $this->assertPermissionError($resp);
119 public function test_login()
121 $req = $this->post('/oidc/login');
122 $redirect = $req->headers->get('location');
124 $this->assertStringStartsWith('https://oidc.local/auth', $redirect, 'Login redirects to SSO location');
125 $this->assertFalse($this->isAuthenticated());
126 $this->assertStringContainsString('scope=openid%20profile%20email', $redirect);
127 $this->assertStringContainsString('client_id=' . OidcJwtHelper::defaultClientId(), $redirect);
128 $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $redirect);
131 public function test_login_success_flow()
134 $this->post('/oidc/login');
135 $state = session()->get('oidc_state');
137 $transactions = &$this->mockHttpClient([$this->getMockAuthorizationResponse([
139 'sub' => 'benny1010101',
142 // Callback from auth provider
143 // App calls token endpoint to get id token
144 $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
145 $resp->assertRedirect('/');
146 $this->assertCount(1, $transactions);
147 /** @var Request $tokenRequest */
148 $tokenRequest = $transactions[0]['request'];
149 $this->assertEquals('https://oidc.local/token', (string) $tokenRequest->getUri());
150 $this->assertEquals('POST', $tokenRequest->getMethod());
151 $this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]);
152 $this->assertStringContainsString('grant_type=authorization_code', $tokenRequest->getBody());
153 $this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody());
154 $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody());
156 $this->assertTrue(auth()->check());
157 $this->assertDatabaseHas('users', [
159 'external_auth_id' => 'benny1010101',
160 'email_confirmed' => false,
164 $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, "oidc; ({$user->id}) Barry Scott");
167 public function test_login_uses_custom_additional_scopes_if_defined()
170 'oidc.additional_scopes' => 'groups, badgers',
173 $redirect = $this->post('/oidc/login')->headers->get('location');
175 $this->assertStringContainsString('scope=openid%20profile%20email%20groups%20badgers', $redirect);
178 public function test_callback_fails_if_no_state_present_or_matching()
180 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
181 $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
183 $this->post('/oidc/login');
184 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
185 $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
188 public function test_dump_user_details_option_outputs_as_expected()
190 config()->set('oidc.dump_user_details', true);
192 $resp = $this->runLogin([
197 $resp->assertStatus(200);
201 'iss' => OidcJwtHelper::defaultIssuer(),
202 'aud' => OidcJwtHelper::defaultClientId(),
204 $this->assertFalse(auth()->check());
207 public function test_auth_fails_if_no_email_exists_in_user_data()
214 $this->assertSessionError('Could not find an email address, for this user, in the data provided by the external authentication system');
217 public function test_auth_fails_if_already_logged_in()
226 $this->assertSessionError('Already logged in');
229 public function test_auth_login_as_existing_user()
231 $editor = $this->getEditor();
232 $editor->external_auth_id = 'benny505';
235 $this->assertFalse(auth()->check());
242 $this->assertTrue(auth()->check());
243 $this->assertEquals($editor->id, auth()->user()->id);
246 public function test_auth_login_as_existing_user_email_with_different_auth_id_fails()
248 $editor = $this->getEditor();
249 $editor->external_auth_id = 'editor101';
252 $this->assertFalse(auth()->check());
254 $resp = $this->runLogin([
255 'email' => $editor->email,
258 $resp = $this->followRedirects($resp);
260 $resp->assertSeeText('A user with the email ' . $editor->email . ' already exists but with different credentials.');
261 $this->assertFalse(auth()->check());
264 public function test_auth_login_with_invalid_token_fails()
266 $resp = $this->runLogin([
269 $resp = $this->followRedirects($resp);
271 $resp->assertSeeText('ID token validate failed with error: Missing token subject value');
272 $this->assertFalse(auth()->check());
275 public function test_auth_login_with_autodiscovery()
277 $this->withAutodiscovery();
279 $transactions = &$this->mockHttpClient([
280 $this->getAutoDiscoveryResponse(),
281 $this->getJwksResponse(),
284 $this->assertFalse(auth()->check());
288 $this->assertTrue(auth()->check());
289 /** @var Request $discoverRequest */
290 $discoverRequest = $transactions[0]['request'];
291 /** @var Request $discoverRequest */
292 $keysRequest = $transactions[1]['request'];
294 $this->assertEquals('GET', $keysRequest->getMethod());
295 $this->assertEquals('GET', $discoverRequest->getMethod());
296 $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri());
297 $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/oidc/keys', $keysRequest->getUri());
300 public function test_auth_fails_if_autodiscovery_fails()
302 $this->withAutodiscovery();
303 $this->mockHttpClient([
304 new Response(404, [], 'Not found'),
307 $resp = $this->followRedirects($this->runLogin());
308 $this->assertFalse(auth()->check());
309 $resp->assertSeeText('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
312 public function test_autodiscovery_calls_are_cached()
314 $this->withAutodiscovery();
316 $transactions = &$this->mockHttpClient([
317 $this->getAutoDiscoveryResponse(),
318 $this->getJwksResponse(),
319 $this->getAutoDiscoveryResponse([
320 'issuer' => 'https://auto.example.com',
322 $this->getJwksResponse(),
326 $this->post('/oidc/login');
327 $this->assertCount(2, $transactions);
328 // Second run, hits cache
329 $this->post('/oidc/login');
330 $this->assertCount(2, $transactions);
332 // Third run, different issuer, new cache key
333 config()->set(['oidc.issuer' => 'https://auto.example.com']);
334 $this->post('/oidc/login');
335 $this->assertCount(4, $transactions);
338 public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_alg_property()
340 $this->withAutodiscovery();
342 $keyArray = OidcJwtHelper::publicJwkKeyArray();
343 unset($keyArray['alg']);
345 $this->mockHttpClient([
346 $this->getAutoDiscoveryResponse(),
348 'Content-Type' => 'application/json',
349 'Cache-Control' => 'no-cache, no-store',
350 'Pragma' => 'no-cache',
358 $this->assertFalse(auth()->check());
360 $this->assertTrue(auth()->check());
363 public function test_login_group_sync()
366 'oidc.user_to_groups' => true,
367 'oidc.group_attribute' => 'groups',
368 'oidc.remove_from_groups' => false,
370 $roleA = Role::factory()->create(['display_name' => 'Wizards']);
371 $roleB = Role::factory()->create(['display_name' => 'ZooFolks', 'external_auth_id' => 'zookeepers']);
372 $roleC = Role::factory()->create(['display_name' => 'Another Role']);
374 $resp = $this->runLogin([
376 'sub' => 'benny1010101',
377 'groups' => ['Wizards', 'Zookeepers']
379 $resp->assertRedirect('/');
381 /** @var User $user */
384 $this->assertTrue($user->hasRole($roleA->id));
385 $this->assertTrue($user->hasRole($roleB->id));
386 $this->assertFalse($user->hasRole($roleC->id));
389 public function test_login_group_sync_with_nested_groups_in_token()
392 'oidc.user_to_groups' => true,
393 'oidc.group_attribute' => 'my.custom.groups.attr',
394 'oidc.remove_from_groups' => false,
396 $roleA = Role::factory()->create(['display_name' => 'Wizards']);
398 $resp = $this->runLogin([
400 'sub' => 'benny1010101',
404 'attr' => ['Wizards']
409 $resp->assertRedirect('/');
411 /** @var User $user */
413 $this->assertTrue($user->hasRole($roleA->id));
416 protected function withAutodiscovery()
419 'oidc.issuer' => OidcJwtHelper::defaultIssuer(),
420 'oidc.discover' => true,
421 'oidc.authorization_endpoint' => null,
422 'oidc.token_endpoint' => null,
423 'oidc.jwt_public_key' => null,
427 protected function runLogin($claimOverrides = []): TestResponse
429 $this->post('/oidc/login');
430 $state = session()->get('oidc_state');
431 $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides)]);
433 return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
436 protected function getAutoDiscoveryResponse($responseOverrides = []): Response
438 return new Response(200, [
439 'Content-Type' => 'application/json',
440 'Cache-Control' => 'no-cache, no-store',
441 'Pragma' => 'no-cache',
442 ], json_encode(array_merge([
443 'token_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/token',
444 'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
445 'jwks_uri' => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
446 'issuer' => OidcJwtHelper::defaultIssuer(),
447 ], $responseOverrides)));
450 protected function getJwksResponse(): Response
452 return new Response(200, [
453 'Content-Type' => 'application/json',
454 'Cache-Control' => 'no-cache, no-store',
455 'Pragma' => 'no-cache',
458 OidcJwtHelper::publicJwkKeyArray(),
463 protected function getMockAuthorizationResponse($claimOverrides = []): Response
465 return new Response(200, [
466 'Content-Type' => 'application/json',
467 'Cache-Control' => 'no-cache, no-store',
468 'Pragma' => 'no-cache',
470 'access_token' => 'abc123',
471 'token_type' => 'Bearer',
472 'expires_in' => 3600,
473 'id_token' => OidcJwtHelper::idToken($claimOverrides),