]> BookStack Code Mirror - bookstack/blobdiff - tests/Auth/OidcTest.php
Dev: Fixed flaky OIDC test, updated dev version
[bookstack] / tests / Auth / OidcTest.php
index aa2c99a36dbf92268ec77dfc45f834fe6e7c82d7..228c75e9eade8f29e5daf3adfa08e1d725f23c78 100644 (file)
@@ -2,9 +2,11 @@
 
 namespace Tests\Auth;
 
-use BookStack\Actions\ActivityType;
-use BookStack\Auth\User;
-use GuzzleHttp\Psr7\Request;
+use BookStack\Activity\ActivityType;
+use BookStack\Facades\Theme;
+use BookStack\Theming\ThemeEvents;
+use BookStack\Users\Models\Role;
+use BookStack\Users\Models\User;
 use GuzzleHttp\Psr7\Response;
 use Illuminate\Testing\TestResponse;
 use Tests\Helpers\OidcJwtHelper;
@@ -28,7 +30,7 @@ class OidcTest extends TestCase
             'auth.method'                 => 'oidc',
             'auth.defaults.guard'         => 'oidc',
             'oidc.name'                   => 'SingleSignOn-Testing',
-            'oidc.display_name_claims'    => ['name'],
+            'oidc.display_name_claims'    => 'name',
             'oidc.client_id'              => OidcJwtHelper::defaultClientId(),
             'oidc.client_secret'          => 'testpass',
             'oidc.jwt_public_key'         => $this->keyFilePath,
@@ -37,6 +39,12 @@ class OidcTest extends TestCase
             'oidc.token_endpoint'         => 'https://oidc.local/token',
             'oidc.discover'               => false,
             'oidc.dump_user_details'      => false,
+            'oidc.additional_scopes'      => '',
+            'oidc.user_to_groups'         => false,
+            'oidc.groups_claim'           => 'group',
+            'oidc.remove_from_groups'     => false,
+            'oidc.external_id_claim'      => 'sub',
+            'oidc.end_session_endpoint'   => false,
         ]);
     }
 
@@ -88,7 +96,7 @@ class OidcTest extends TestCase
 
     public function test_logout_route_functions()
     {
-        $this->actingAs($this->getEditor());
+        $this->actingAs($this->users->editor());
         $this->post('/logout');
         $this->assertFalse(auth()->check());
     }
@@ -129,7 +137,7 @@ class OidcTest extends TestCase
         $this->post('/oidc/login');
         $state = session()->get('oidc_state');
 
-        $transactions = &$this->mockHttpClient([$this->getMockAuthorizationResponse([
+        $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
             'email' => '[email protected]',
             'sub'   => 'benny1010101',
         ])]);
@@ -138,9 +146,8 @@ class OidcTest extends TestCase
         // App calls token endpoint to get id token
         $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
         $resp->assertRedirect('/');
-        $this->assertCount(1, $transactions);
-        /** @var Request $tokenRequest */
-        $tokenRequest = $transactions[0]['request'];
+        $this->assertEquals(1, $transactions->requestCount());
+        $tokenRequest = $transactions->latestRequest();
         $this->assertEquals('https://oidc.local/token', (string) $tokenRequest->getUri());
         $this->assertEquals('POST', $tokenRequest->getMethod());
         $this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]);
@@ -159,6 +166,17 @@ class OidcTest extends TestCase
         $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, "oidc; ({$user->id}) Barry Scott");
     }
 
+    public function test_login_uses_custom_additional_scopes_if_defined()
+    {
+        config()->set([
+            'oidc.additional_scopes' => 'groups, badgers',
+        ]);
+
+        $redirect = $this->post('/oidc/login')->headers->get('location');
+
+        $this->assertStringContainsString('scope=openid%20profile%20email%20groups%20badgers', $redirect);
+    }
+
     public function test_callback_fails_if_no_state_present_or_matching()
     {
         $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
@@ -212,7 +230,7 @@ class OidcTest extends TestCase
 
     public function test_auth_login_as_existing_user()
     {
-        $editor = $this->getEditor();
+        $editor = $this->users->editor();
         $editor->external_auth_id = 'benny505';
         $editor->save();
 
@@ -229,7 +247,7 @@ class OidcTest extends TestCase
 
     public function test_auth_login_as_existing_user_email_with_different_auth_id_fails()
     {
-        $editor = $this->getEditor();
+        $editor = $this->users->editor();
         $editor->external_auth_id = 'editor101';
         $editor->save();
 
@@ -260,7 +278,7 @@ class OidcTest extends TestCase
     {
         $this->withAutodiscovery();
 
-        $transactions = &$this->mockHttpClient([
+        $transactions = $this->mockHttpClient([
             $this->getAutoDiscoveryResponse(),
             $this->getJwksResponse(),
         ]);
@@ -270,11 +288,9 @@ class OidcTest extends TestCase
         $this->runLogin();
 
         $this->assertTrue(auth()->check());
-        /** @var Request $discoverRequest */
-        $discoverRequest = $transactions[0]['request'];
-        /** @var Request $discoverRequest */
-        $keysRequest = $transactions[1]['request'];
 
+        $discoverRequest = $transactions->requestAt(0);
+        $keysRequest = $transactions->requestAt(1);
         $this->assertEquals('GET', $keysRequest->getMethod());
         $this->assertEquals('GET', $discoverRequest->getMethod());
         $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri());
@@ -297,7 +313,7 @@ class OidcTest extends TestCase
     {
         $this->withAutodiscovery();
 
-        $transactions = &$this->mockHttpClient([
+        $transactions = $this->mockHttpClient([
             $this->getAutoDiscoveryResponse(),
             $this->getJwksResponse(),
             $this->getAutoDiscoveryResponse([
@@ -308,15 +324,15 @@ class OidcTest extends TestCase
 
         // Initial run
         $this->post('/oidc/login');
-        $this->assertCount(2, $transactions);
+        $this->assertEquals(2, $transactions->requestCount());
         // Second run, hits cache
         $this->post('/oidc/login');
-        $this->assertCount(2, $transactions);
+        $this->assertEquals(2, $transactions->requestCount());
 
         // Third run, different issuer, new cache key
         config()->set(['oidc.issuer' => 'https://auto.example.com']);
         $this->post('/oidc/login');
-        $this->assertCount(4, $transactions);
+        $this->assertEquals(4, $transactions->requestCount());
     }
 
     public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_alg_property()
@@ -344,6 +360,335 @@ class OidcTest extends TestCase
         $this->assertTrue(auth()->check());
     }
 
+    public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_use_property()
+    {
+        // Based on reading the OIDC discovery spec:
+        // > This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also
+        // > contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When
+        // > both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all
+        // > keys in the referenced JWK Set to indicate each key's intended usage.
+        // We can assume that keys without use are intended for signing.
+        $this->withAutodiscovery();
+
+        $keyArray = OidcJwtHelper::publicJwkKeyArray();
+        unset($keyArray['use']);
+
+        $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(),
+            new Response(200, [
+                'Content-Type'  => 'application/json',
+                'Cache-Control' => 'no-cache, no-store',
+                'Pragma'        => 'no-cache',
+            ], json_encode([
+                'keys' => [
+                    $keyArray,
+                ],
+            ])),
+        ]);
+
+        $this->assertFalse(auth()->check());
+        $this->runLogin();
+        $this->assertTrue(auth()->check());
+    }
+
+    public function test_auth_uses_configured_external_id_claim_option()
+    {
+        config()->set([
+            'oidc.external_id_claim' => 'super_awesome_id',
+        ]);
+
+        $resp = $this->runLogin([
+            'email'            => '[email protected]',
+            'sub'              => 'benny1010101',
+            'super_awesome_id' => 'xXBennyTheGeezXx',
+        ]);
+        $resp->assertRedirect('/');
+
+        /** @var User $user */
+        $user = User::query()->where('email', '=', '[email protected]')->first();
+        $this->assertEquals('xXBennyTheGeezXx', $user->external_auth_id);
+    }
+
+    public function test_auth_uses_mulitple_display_name_claims_if_configured()
+    {
+        config()->set(['oidc.display_name_claims' => 'first_name|last_name']);
+
+        $this->runLogin([
+            'email'      => '[email protected]',
+            'sub'        => 'benny1010101',
+            'first_name' => 'Benny',
+            'last_name'  => 'Jenkins'
+        ]);
+
+        $this->assertDatabaseHas('users', [
+            'name' => 'Benny Jenkins',
+            'email' => '[email protected]',
+        ]);
+    }
+
+    public function test_login_group_sync()
+    {
+        config()->set([
+            'oidc.user_to_groups'     => true,
+            'oidc.groups_claim'       => 'groups',
+            'oidc.remove_from_groups' => false,
+        ]);
+        $roleA = Role::factory()->create(['display_name' => 'Wizards']);
+        $roleB = Role::factory()->create(['display_name' => 'ZooFolks', 'external_auth_id' => 'zookeepers']);
+        $roleC = Role::factory()->create(['display_name' => 'Another Role']);
+
+        $resp = $this->runLogin([
+            'email'  => '[email protected]',
+            'sub'    => 'benny1010101',
+            'groups' => ['Wizards', 'Zookeepers'],
+        ]);
+        $resp->assertRedirect('/');
+
+        /** @var User $user */
+        $user = User::query()->where('email', '=', '[email protected]')->first();
+
+        $this->assertTrue($user->hasRole($roleA->id));
+        $this->assertTrue($user->hasRole($roleB->id));
+        $this->assertFalse($user->hasRole($roleC->id));
+    }
+
+    public function test_login_group_sync_with_nested_groups_in_token()
+    {
+        config()->set([
+            'oidc.user_to_groups'     => true,
+            'oidc.groups_claim'       => 'my.custom.groups.attr',
+            'oidc.remove_from_groups' => false,
+        ]);
+        $roleA = Role::factory()->create(['display_name' => 'Wizards']);
+
+        $resp = $this->runLogin([
+            'email'  => '[email protected]',
+            'sub'    => 'benny1010101',
+            'my'     => [
+                'custom' => [
+                    'groups' => [
+                        'attr' => ['Wizards'],
+                    ],
+                ],
+            ],
+        ]);
+        $resp->assertRedirect('/');
+
+        /** @var User $user */
+        $user = User::query()->where('email', '=', '[email protected]')->first();
+        $this->assertTrue($user->hasRole($roleA->id));
+    }
+
+    public function test_oidc_logout_form_active_when_oidc_active()
+    {
+        $this->runLogin();
+
+        $resp = $this->get('/');
+        $this->withHtml($resp)->assertElementExists('header form[action$="/oidc/logout"] button');
+    }
+    public function test_logout_with_autodiscovery_with_oidc_logout_enabled()
+    {
+        config()->set(['oidc.end_session_endpoint' => true]);
+        $this->withAutodiscovery();
+
+        $transactions = $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(),
+            $this->getJwksResponse(),
+        ]);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode(url('/')));
+
+        $this->assertEquals(2, $transactions->requestCount());
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_with_autodiscovery_with_oidc_logout_disabled()
+    {
+        $this->withAutodiscovery();
+        config()->set(['oidc.end_session_endpoint' => false]);
+
+        $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(),
+            $this->getJwksResponse(),
+        ]);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('/');
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_without_autodiscovery_but_with_endpoint_configured()
+    {
+        config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('https://example.com/logout?post_logout_redirect_uri=' . urlencode(url('/')));
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_without_autodiscovery_with_configured_endpoint_adds_to_query_if_existing()
+    {
+        config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout?a=b']);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('https://example.com/logout?a=b&post_logout_redirect_uri=' . urlencode(url('/')));
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_with_autodiscovery_and_auto_initiate_returns_to_auto_prevented_login()
+    {
+        $this->withAutodiscovery();
+        config()->set([
+            'auth.auto_initiate' => true,
+            'services.google.client_id' => false,
+            'services.github.client_id' => false,
+            'oidc.end_session_endpoint' => true,
+        ]);
+
+        $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(),
+            $this->getJwksResponse(),
+        ]);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+
+        $redirectUrl = url('/login?prevent_auto_init=true');
+        $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode($redirectUrl));
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_endpoint_url_overrides_autodiscovery_endpoint()
+    {
+        config()->set(['oidc.end_session_endpoint' => 'https://a.example.com']);
+        $this->withAutodiscovery();
+
+        $transactions = $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(),
+            $this->getJwksResponse(),
+        ]);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('https://a.example.com?post_logout_redirect_uri=' . urlencode(url('/')));
+
+        $this->assertEquals(2, $transactions->requestCount());
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_with_autodiscovery_does_not_use_rp_logout_if_no_url_via_autodiscovery()
+    {
+        config()->set(['oidc.end_session_endpoint' => true]);
+        $this->withAutodiscovery();
+
+        $this->mockHttpClient([
+            $this->getAutoDiscoveryResponse(['end_session_endpoint' => null]),
+            $this->getJwksResponse(),
+        ]);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $resp->assertRedirect('/');
+        $this->assertFalse(auth()->check());
+    }
+
+    public function test_logout_redirect_contains_id_token_hint_if_existing()
+    {
+        config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
+
+        // Fix times so our token is predictable
+        $claimOverrides = [
+            'iat' => time(),
+            'exp' => time() + 720,
+            'auth_time' => time()
+        ];
+        $this->runLogin($claimOverrides);
+
+        $resp = $this->asEditor()->post('/oidc/logout');
+        $query = 'id_token_hint=' . urlencode(OidcJwtHelper::idToken($claimOverrides)) .  '&post_logout_redirect_uri=' . urlencode(url('/'));
+        $resp->assertRedirect('https://example.com/logout?' . $query);
+    }
+
+    public function test_oidc_id_token_pre_validate_theme_event_without_return()
+    {
+        $args = [];
+        $callback = function (...$eventArgs) use (&$args) {
+            $args = $eventArgs;
+        };
+        Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
+
+        $resp = $this->runLogin([
+            'email' => '[email protected]',
+            'sub'   => 'benny1010101',
+            'name'  => 'Benny',
+        ]);
+        $resp->assertRedirect('/');
+
+        $this->assertDatabaseHas('users', [
+            'external_auth_id' => 'benny1010101',
+        ]);
+
+        $this->assertArrayHasKey('iss', $args[0]);
+        $this->assertArrayHasKey('sub', $args[0]);
+        $this->assertEquals('Benny', $args[0]['name']);
+        $this->assertEquals('benny1010101', $args[0]['sub']);
+
+        $this->assertArrayHasKey('access_token', $args[1]);
+        $this->assertArrayHasKey('expires_in', $args[1]);
+        $this->assertArrayHasKey('refresh_token', $args[1]);
+    }
+
+    public function test_oidc_id_token_pre_validate_theme_event_with_return()
+    {
+        $callback = function (...$eventArgs) {
+            return array_merge($eventArgs[0], [
+                'email' => '[email protected]',
+                'sub' => 'lenny1010101',
+                'name' => 'Lenny',
+            ]);
+        };
+        Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
+
+        $resp = $this->runLogin([
+            'email' => '[email protected]',
+            'sub'   => 'benny1010101',
+            'name'  => 'Benny',
+        ]);
+        $resp->assertRedirect('/');
+
+        $this->assertDatabaseHas('users', [
+            'email' => '[email protected]',
+            'external_auth_id' => 'lenny1010101',
+            'name' => 'Lenny',
+        ]);
+    }
+
+    public function test_pkce_used_on_authorize_and_access()
+    {
+        // Start auth
+        $resp = $this->post('/oidc/login');
+        $state = session()->get('oidc_state');
+
+        $pkceCode = session()->get('oidc_pkce_code');
+        $this->assertGreaterThan(30, strlen($pkceCode));
+
+        $expectedCodeChallenge = trim(strtr(base64_encode(hash('sha256', $pkceCode, true)), '+/', '-_'), '=');
+        $redirect = $resp->headers->get('Location');
+        $redirectParams = [];
+        parse_str(parse_url($redirect, PHP_URL_QUERY), $redirectParams);
+        $this->assertEquals($expectedCodeChallenge, $redirectParams['code_challenge']);
+        $this->assertEquals('S256', $redirectParams['code_challenge_method']);
+
+        $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
+            'email' => '[email protected]',
+            'sub'   => 'benny1010101',
+        ])]);
+
+        $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
+        $tokenRequest = $transactions->latestRequest();
+        $bodyParams = [];
+        parse_str($tokenRequest->getBody(), $bodyParams);
+        $this->assertEquals($pkceCode, $bodyParams['code_verifier']);
+    }
+
     protected function withAutodiscovery()
     {
         config()->set([
@@ -375,6 +720,7 @@ class OidcTest extends TestCase
             'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
             'jwks_uri'               => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
             'issuer'                 => OidcJwtHelper::defaultIssuer(),
+            'end_session_endpoint'   => OidcJwtHelper::defaultIssuer() . '/oidc/logout',
         ], $responseOverrides)));
     }