1
0
mirror of https://github.com/BookStackApp/BookStack.git synced 2025-10-13 11:47:56 +03:00

Merge branch 'oidc'

This commit is contained in:
Dan Brown
2021-10-16 15:50:50 +01:00
39 changed files with 2068 additions and 72 deletions

View File

@@ -334,6 +334,7 @@ class AuthTest extends TestCase
$this->assertTrue(auth()->check());
$this->assertTrue(auth('ldap')->check());
$this->assertTrue(auth('saml2')->check());
$this->assertTrue(auth('oidc')->check());
}
public function test_login_authenticates_nonadmins_on_default_guard_only()
@@ -346,6 +347,7 @@ class AuthTest extends TestCase
$this->assertTrue(auth()->check());
$this->assertFalse(auth('ldap')->check());
$this->assertFalse(auth('saml2')->check());
$this->assertFalse(auth('oidc')->check());
}
public function test_failed_logins_are_logged_when_message_configured()

381
tests/Auth/OidcTest.php Normal file
View File

@@ -0,0 +1,381 @@
<?php namespace Tests\Auth;
use BookStack\Actions\ActivityType;
use BookStack\Auth\Access\Oidc\OidcService;
use BookStack\Auth\User;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Illuminate\Filesystem\Cache;
use Tests\Helpers\OidcJwtHelper;
use Tests\TestCase;
use Tests\TestResponse;
class OidcTest extends TestCase
{
protected $keyFilePath;
protected $keyFile;
public function setUp(): void
{
parent::setUp();
// Set default config for OpenID Connect
$this->keyFile = tmpfile();
$this->keyFilePath = 'file://' . stream_get_meta_data($this->keyFile)['uri'];
file_put_contents($this->keyFilePath, OidcJwtHelper::publicPemKey());
config()->set([
'auth.method' => 'oidc',
'auth.defaults.guard' => 'oidc',
'oidc.name' => 'SingleSignOn-Testing',
'oidc.display_name_claims' => ['name'],
'oidc.client_id' => OidcJwtHelper::defaultClientId(),
'oidc.client_secret' => 'testpass',
'oidc.jwt_public_key' => $this->keyFilePath,
'oidc.issuer' => OidcJwtHelper::defaultIssuer(),
'oidc.authorization_endpoint' => 'https://oidc.local/auth',
'oidc.token_endpoint' => 'https://oidc.local/token',
'oidc.discover' => false,
'oidc.dump_user_details' => false,
]);
}
public function tearDown(): void
{
parent::tearDown();
if (file_exists($this->keyFilePath)) {
unlink($this->keyFilePath);
}
}
public function test_login_option_shows_on_login_page()
{
$req = $this->get('/login');
$req->assertSeeText('SingleSignOn-Testing');
$req->assertElementExists('form[action$="/oidc/login"][method=POST] button');
}
public function test_oidc_routes_are_only_active_if_oidc_enabled()
{
config()->set(['auth.method' => 'standard']);
$routes = ['/login' => 'post', '/callback' => 'get'];
foreach ($routes as $uri => $method) {
$req = $this->call($method, '/oidc' . $uri);
$this->assertPermissionError($req);
}
}
public function test_forgot_password_routes_inaccessible()
{
$resp = $this->get('/password/email');
$this->assertPermissionError($resp);
$resp = $this->post('/password/email');
$this->assertPermissionError($resp);
$resp = $this->get('/password/reset/abc123');
$this->assertPermissionError($resp);
$resp = $this->post('/password/reset');
$this->assertPermissionError($resp);
}
public function test_standard_login_routes_inaccessible()
{
$resp = $this->post('/login');
$this->assertPermissionError($resp);
}
public function test_logout_route_functions()
{
$this->actingAs($this->getEditor());
$this->get('/logout');
$this->assertFalse(auth()->check());
}
public function test_user_invite_routes_inaccessible()
{
$resp = $this->get('/register/invite/abc123');
$this->assertPermissionError($resp);
$resp = $this->post('/register/invite/abc123');
$this->assertPermissionError($resp);
}
public function test_user_register_routes_inaccessible()
{
$resp = $this->get('/register');
$this->assertPermissionError($resp);
$resp = $this->post('/register');
$this->assertPermissionError($resp);
}
public function test_login()
{
$req = $this->post('/oidc/login');
$redirect = $req->headers->get('location');
$this->assertStringStartsWith('https://oidc.local/auth', $redirect, 'Login redirects to SSO location');
$this->assertFalse($this->isAuthenticated());
$this->assertStringContainsString('scope=openid%20profile%20email', $redirect);
$this->assertStringContainsString('client_id=' . OidcJwtHelper::defaultClientId(), $redirect);
$this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $redirect);
}
public function test_login_success_flow()
{
// Start auth
$this->post('/oidc/login');
$state = session()->get('oidc_state');
$transactions = &$this->mockHttpClient([$this->getMockAuthorizationResponse([
'email' => 'benny@example.com',
'sub' => 'benny1010101'
])]);
// Callback from auth provider
// 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('https://oidc.local/token', (string) $tokenRequest->getUri());
$this->assertEquals('POST', $tokenRequest->getMethod());
$this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]);
$this->assertStringContainsString('grant_type=authorization_code', $tokenRequest->getBody());
$this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody());
$this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody());
$this->assertTrue(auth()->check());
$this->assertDatabaseHas('users', [
'email' => 'benny@example.com',
'external_auth_id' => 'benny1010101',
'email_confirmed' => false,
]);
$user = User::query()->where('email', '=', 'benny@example.com')->first();
$this->assertActivityExists(ActivityType::AUTH_LOGIN, null, "oidc; ({$user->id}) Barry Scott");
}
public function test_callback_fails_if_no_state_present_or_matching()
{
$this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
$this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
$this->post('/oidc/login');
$this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
$this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
}
public function test_dump_user_details_option_outputs_as_expected()
{
config()->set('oidc.dump_user_details', true);
$resp = $this->runLogin([
'email' => 'benny@example.com',
'sub' => 'benny505'
]);
$resp->assertStatus(200);
$resp->assertJson([
'email' => 'benny@example.com',
'sub' => 'benny505',
"iss" => OidcJwtHelper::defaultIssuer(),
"aud" => OidcJwtHelper::defaultClientId(),
]);
$this->assertFalse(auth()->check());
}
public function test_auth_fails_if_no_email_exists_in_user_data()
{
$this->runLogin([
'email' => '',
'sub' => 'benny505'
]);
$this->assertSessionError('Could not find an email address, for this user, in the data provided by the external authentication system');
}
public function test_auth_fails_if_already_logged_in()
{
$this->asEditor();
$this->runLogin([
'email' => 'benny@example.com',
'sub' => 'benny505'
]);
$this->assertSessionError('Already logged in');
}
public function test_auth_login_as_existing_user()
{
$editor = $this->getEditor();
$editor->external_auth_id = 'benny505';
$editor->save();
$this->assertFalse(auth()->check());
$this->runLogin([
'email' => 'benny@example.com',
'sub' => 'benny505'
]);
$this->assertTrue(auth()->check());
$this->assertEquals($editor->id, auth()->user()->id);
}
public function test_auth_login_as_existing_user_email_with_different_auth_id_fails()
{
$editor = $this->getEditor();
$editor->external_auth_id = 'editor101';
$editor->save();
$this->assertFalse(auth()->check());
$this->runLogin([
'email' => $editor->email,
'sub' => 'benny505'
]);
$this->assertSessionError('A user with the email ' . $editor->email . ' already exists but with different credentials.');
$this->assertFalse(auth()->check());
}
public function test_auth_login_with_invalid_token_fails()
{
$this->runLogin([
'sub' => null,
]);
$this->assertSessionError('ID token validate failed with error: Missing token subject value');
$this->assertFalse(auth()->check());
}
public function test_auth_login_with_autodiscovery()
{
$this->withAutodiscovery();
$transactions = &$this->mockHttpClient([
$this->getAutoDiscoveryResponse(),
$this->getJwksResponse(),
]);
$this->assertFalse(auth()->check());
$this->runLogin();
$this->assertTrue(auth()->check());
/** @var Request $discoverRequest */
$discoverRequest = $transactions[0]['request'];
/** @var Request $discoverRequest */
$keysRequest = $transactions[1]['request'];
$this->assertEquals('GET', $keysRequest->getMethod());
$this->assertEquals('GET', $discoverRequest->getMethod());
$this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri());
$this->assertEquals(OidcJwtHelper::defaultIssuer() . '/oidc/keys', $keysRequest->getUri());
}
public function test_auth_fails_if_autodiscovery_fails()
{
$this->withAutodiscovery();
$this->mockHttpClient([
new Response(404, [], 'Not found'),
]);
$this->runLogin();
$this->assertFalse(auth()->check());
$this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
}
public function test_autodiscovery_calls_are_cached()
{
$this->withAutodiscovery();
$transactions = &$this->mockHttpClient([
$this->getAutoDiscoveryResponse(),
$this->getJwksResponse(),
$this->getAutoDiscoveryResponse([
'issuer' => 'https://auto.example.com'
]),
$this->getJwksResponse(),
]);
// Initial run
$this->post('/oidc/login');
$this->assertCount(2, $transactions);
// Second run, hits cache
$this->post('/oidc/login');
$this->assertCount(2, $transactions);
// Third run, different issuer, new cache key
config()->set(['oidc.issuer' => 'https://auto.example.com']);
$this->post('/oidc/login');
$this->assertCount(4, $transactions);
}
protected function withAutodiscovery()
{
config()->set([
'oidc.issuer' => OidcJwtHelper::defaultIssuer(),
'oidc.discover' => true,
'oidc.authorization_endpoint' => null,
'oidc.token_endpoint' => null,
'oidc.jwt_public_key' => null,
]);
}
protected function runLogin($claimOverrides = []): TestResponse
{
$this->post('/oidc/login');
$state = session()->get('oidc_state');
$this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides)]);
return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
}
protected function getAutoDiscoveryResponse($responseOverrides = []): Response
{
return new Response(200, [
'Content-Type' => 'application/json',
'Cache-Control' => 'no-cache, no-store',
'Pragma' => 'no-cache'
], json_encode(array_merge([
'token_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/token',
'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
'jwks_uri' => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
'issuer' => OidcJwtHelper::defaultIssuer()
], $responseOverrides)));
}
protected function getJwksResponse(): Response
{
return new Response(200, [
'Content-Type' => 'application/json',
'Cache-Control' => 'no-cache, no-store',
'Pragma' => 'no-cache'
], json_encode([
'keys' => [
OidcJwtHelper::publicJwkKeyArray()
]
]));
}
protected function getMockAuthorizationResponse($claimOverrides = []): Response
{
return new Response(200, [
'Content-Type' => 'application/json',
'Cache-Control' => 'no-cache, no-store',
'Pragma' => 'no-cache'
], json_encode([
'access_token' => 'abc123',
'token_type' => 'Bearer',
'expires_in' => 3600,
'id_token' => OidcJwtHelper::idToken($claimOverrides)
]));
}
}

View File

@@ -0,0 +1,132 @@
<?php
namespace Tests\Helpers;
use phpseclib3\Crypt\RSA;
/**
* A collection of functions to help with OIDC JWT testing.
* By default, unless overridden, content is provided in a correct working state.
*/
class OidcJwtHelper
{
public static function defaultIssuer(): string
{
return "https://auth.example.com";
}
public static function defaultClientId(): string
{
return "xxyyzz.aaa.bbccdd.123";
}
public static function defaultPayload(): array
{
return [
"sub" => "abc1234def",
"name" => "Barry Scott",
"email" => "bscott@example.com",
"ver" => 1,
"iss" => static::defaultIssuer(),
"aud" => static::defaultClientId(),
"iat" => time(),
"exp" => time() + 720,
"jti" => "ID.AaaBBBbbCCCcccDDddddddEEEeeeeee",
"amr" => ["pwd"],
"idp" => "fghfghgfh546456dfgdfg",
"preferred_username" => "xXBazzaXx",
"auth_time" => time(),
"at_hash" => "sT4jbsdSGy9w12pq3iNYDA",
];
}
public static function idToken($payloadOverrides = [], $headerOverrides = []): string
{
$payload = array_merge(static::defaultPayload(), $payloadOverrides);
$header = array_merge([
'kid' => 'xyz456',
'alg' => 'RS256',
], $headerOverrides);
$top = implode('.', [
static::base64UrlEncode(json_encode($header)),
static::base64UrlEncode(json_encode($payload)),
]);
$privateKey = static::privateKeyInstance();
$signature = $privateKey->sign($top);
return $top . '.' . static::base64UrlEncode($signature);
}
public static function privateKeyInstance()
{
static $key;
if (is_null($key)) {
$key = RSA::loadPrivateKey(static::privatePemKey())->withPadding(RSA::SIGNATURE_PKCS1);
}
return $key;
}
public static function base64UrlEncode(string $decoded): string
{
return strtr(base64_encode($decoded), '+/', '-_');
}
public static function publicPemKey(): string
{
return "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqo1OmfNKec5S2zQC4SP9
DrHuUR0VgCi6oqcGERz7zqO36hqk3A3R3aCgJkEjfnbnMuszRRKs45NbXoOp9pvm
zXL16c93Obn7G8x8A3ao6yN5qKO5S5+CETqOZfKN/g75Xlz7VsC3igOhgsXnPx6i
iM6sbYbk0U/XpFaT84LXKI8VTIPUo7gTeZN1pTET//i9FlzAOzX+xfWBKdOqlEzl
+zihMHCZUUvQu99P+o0MDR0lMUT+vPJ6SJeRfnoHexwt6bZFiNnsZIEL03bX4QNk
WvsLta1+jNUee+8IPVhzCO8bvM86NzLaKUJ4k6NZ5IVrmdCFpFsjCWByOrDG8wdw
3wIDAQAB
-----END PUBLIC KEY-----";
}
public static function privatePemKey(): string
{
return "-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCqjU6Z80p5zlLb
NALhI/0Ose5RHRWAKLqipwYRHPvOo7fqGqTcDdHdoKAmQSN+ducy6zNFEqzjk1te
g6n2m+bNcvXpz3c5ufsbzHwDdqjrI3moo7lLn4IROo5l8o3+DvleXPtWwLeKA6GC
xec/HqKIzqxthuTRT9ekVpPzgtcojxVMg9SjuBN5k3WlMRP/+L0WXMA7Nf7F9YEp
06qUTOX7OKEwcJlRS9C730/6jQwNHSUxRP688npIl5F+egd7HC3ptkWI2exkgQvT
dtfhA2Ra+wu1rX6M1R577wg9WHMI7xu8zzo3MtopQniTo1nkhWuZ0IWkWyMJYHI6
sMbzB3DfAgMBAAECggEADm7K2ghWoxwsstQh8j+DaLzx9/dIHIJV2PHdd5FGVeRQ
6gS7MswQmHrBUrtsb4VMZ2iz/AJqkw+jScpGldH3pCc4XELsSfxNHbseO4TNIqjr
4LOKOLYU4bRc3I+8KGXIAI5JzrucTJemEVUCDrte8cjbmqExt+zTyNpyxsapworF
v+vnSdv40d62f+cS1xvwB+ymLK/B/wZ/DemDCi8jsi7ou/M7l5xNCzjH4iMSLtOW
fgEhejIBG9miMJWPiVpTXE3tMdNuN3OsWc4XXm2t4VRovlZdu30Fax1xWB+Locsv
HlHKLOFc8g+jZh0TL2KCNjPffMcC7kHhW3afshpIsQKBgQDhyWUnkqd6FzbwIX70
SnaMgKoUv5W/K5T+Sv/PA2CyN8Gu8ih/OsoNZSnI0uqe3XQIvvgN/Fq3wO1ttLzf
z5B6ZC7REfTgcR0190gihk6f5rtcj7d6Fy/oG2CE8sDSXgPnpEaBjvJVgN5v/U2s
HpVaidmHTyGLCfEszoeoy8jyrQKBgQDBX8caGylmzQLc6XNntZChlt3e18Nj8MPA
DxWLcoqgdDoofLDQAmLl+vPKyDmhQjos5eas1jgmVVEM4ge+MysaVezvuLBsSnOh
ihc0i63USU6i7YDE83DrCewCthpFHi/wW1S5FoCAzpVy8y99vwcqO4kOXcmf4O6Y
uW6sMsjvOwKBgQDbFtqB+MtsLCSSBF61W6AHHD5tna4H75lG2623yXZF2NanFLF5
K6muL9DI3ujtOMQETJJUt9+rWJjLEEsJ/dYa/SV0l7D/LKOEnyuu3JZkkLaTzZzi
6qcA2bfhqdCzEKlHV99WjkfV8hNlpex9rLuOPB8JLh7FVONicBGxF/UojQKBgDXs
IlYaSuI6utilVKQP0kPtEPOKERc2VS+iRSy8hQGXR3xwwNFQSQm+f+sFCGT6VcSd
W0TI+6Fc2xwPj38vP465dTentbKM1E+wdSYW6SMwSfhO6ECDbfJsst5Sr2Kkt1N7
9FUkfDLu6GfEfnK/KR1SurZB2u51R7NYyg7EnplvAoGAT0aTtOcck0oYN30g5mdf
efqXPwg2wAPYeiec49EbfnteQQKAkqNfJ9K69yE2naf6bw3/5mCBsq/cXeuaBMII
ylysUIRBqt2J0kWm2yCpFWR7H+Ilhdx9A7ZLCqYVt8e+vjO/BOI3cQDe2VPOLPSl
q/1PY4iJviGKddtmfClH3v4=
-----END PRIVATE KEY-----";
}
public static function publicJwkKeyArray(): array
{
return [
'kty' => 'RSA',
'alg' => 'RS256',
'kid' => '066e52af-8884-4926-801d-032a276f9f2a',
'use' => 'sig',
'e' => 'AQAB',
'n' => 'qo1OmfNKec5S2zQC4SP9DrHuUR0VgCi6oqcGERz7zqO36hqk3A3R3aCgJkEjfnbnMuszRRKs45NbXoOp9pvmzXL16c93Obn7G8x8A3ao6yN5qKO5S5-CETqOZfKN_g75Xlz7VsC3igOhgsXnPx6iiM6sbYbk0U_XpFaT84LXKI8VTIPUo7gTeZN1pTET__i9FlzAOzX-xfWBKdOqlEzl-zihMHCZUUvQu99P-o0MDR0lMUT-vPJ6SJeRfnoHexwt6bZFiNnsZIEL03bX4QNkWvsLta1-jNUee-8IPVhzCO8bvM86NzLaKUJ4k6NZ5IVrmdCFpFsjCWByOrDG8wdw3w',
];
}
}

View File

@@ -18,6 +18,10 @@ use BookStack\Entities\Repos\ChapterRepo;
use BookStack\Entities\Repos\PageRepo;
use BookStack\Settings\SettingService;
use BookStack\Uploads\HttpFetcher;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Illuminate\Foundation\Testing\Assert as PHPUnit;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Env;
@@ -25,6 +29,7 @@ use Illuminate\Support\Facades\Log;
use Mockery;
use Monolog\Handler\TestHandler;
use Monolog\Logger;
use Psr\Http\Client\ClientInterface;
trait SharedTestHelpers
{
@@ -244,6 +249,22 @@ trait SharedTestHelpers
->andReturn($returnData);
}
/**
* Mock the http client used in BookStack.
* Returns a reference to the container which holds all history of http transactions.
* @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
*/
protected function &mockHttpClient(array $responses = []): array
{
$container = [];
$history = Middleware::history($container);
$mock = new MockHandler($responses);
$handlerStack = new HandlerStack($mock);
$handlerStack->push($history);
$this->app[ClientInterface::class] = new Client(['handler' => $handlerStack]);
return $container;
}
/**
* Run a set test with the given env variable.
* Remembers the original and resets the value after test.
@@ -323,6 +344,15 @@ trait SharedTestHelpers
);
}
/**
* Assert that the session has a particular error notification message set.
*/
protected function assertSessionError(string $message)
{
$error = session()->get('error');
PHPUnit::assertTrue($error === $message, "Failed asserting the session contains an error. \nFound: {$error}\nExpecting: {$message}");
}
/**
* Set a test handler as the logging interface for the application.
* Allows capture of logs for checking against during tests.

View File

@@ -0,0 +1,164 @@
<?php
namespace Tests\Unit;
use BookStack\Auth\Access\Oidc\OidcInvalidTokenException;
use BookStack\Auth\Access\Oidc\OidcIdToken;
use Tests\Helpers\OidcJwtHelper;
use Tests\TestCase;
class OidcIdTokenTest extends TestCase
{
public function test_valid_token_passes_validation()
{
$token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [
OidcJwtHelper::publicJwkKeyArray()
]);
$this->assertTrue($token->validate('xxyyzz.aaa.bbccdd.123'));
}
public function test_get_claim_returns_value_if_existing()
{
$token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), []);
$this->assertEquals('bscott@example.com', $token->getClaim('email'));
}
public function test_get_claim_returns_null_if_not_existing()
{
$token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), []);
$this->assertEquals(null, $token->getClaim('emails'));
}
public function test_get_all_claims_returns_all_payload_claims()
{
$defaultPayload = OidcJwtHelper::defaultPayload();
$token = new OidcIdToken(OidcJwtHelper::idToken($defaultPayload), OidcJwtHelper::defaultIssuer(), []);
$this->assertEquals($defaultPayload, $token->getAllClaims());
}
public function test_token_structure_error_cases()
{
$idToken = OidcJwtHelper::idToken();
$idTokenExploded = explode('.', $idToken);
$messagesAndTokenValues = [
['Could not parse out a valid header within the provided token', ''],
['Could not parse out a valid header within the provided token', 'cat'],
['Could not parse out a valid payload within the provided token', $idTokenExploded[0]],
['Could not parse out a valid payload within the provided token', $idTokenExploded[0] . '.' . 'dog'],
['Could not parse out a valid signature within the provided token', $idTokenExploded[0] . '.' . $idTokenExploded[1]],
['Could not parse out a valid signature within the provided token', $idTokenExploded[0] . '.' . $idTokenExploded[1] . '.' . '@$%'],
];
foreach ($messagesAndTokenValues as [$message, $tokenValue]) {
$token = new OidcIdToken($tokenValue, OidcJwtHelper::defaultIssuer(), []);
$err = null;
try {
$token->validate('abc');
} catch (\Exception $exception) {
$err = $exception;
}
$this->assertInstanceOf(OidcInvalidTokenException::class, $err, $message);
$this->assertEquals($message, $err->getMessage());
}
}
public function test_error_thrown_if_token_signature_not_validated_from_no_keys()
{
$token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), []);
$this->expectException(OidcInvalidTokenException::class);
$this->expectExceptionMessage('Token signature could not be validated using the provided keys');
$token->validate('abc');
}
public function test_error_thrown_if_token_signature_not_validated_from_non_matching_key()
{
$token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [
array_merge(OidcJwtHelper::publicJwkKeyArray(), [
'n' => 'iqK-1QkICMf_cusNLpeNnN-bhT0-9WLBvzgwKLALRbrevhdi5ttrLHIQshaSL0DklzfyG2HWRmAnJ9Q7sweEjuRiiqRcSUZbYu8cIv2hLWYu7K_NH67D2WUjl0EnoHEuiVLsZhQe1CmdyLdx087j5nWkd64K49kXRSdxFQUlj8W3NeK3CjMEUdRQ3H4RZzJ4b7uuMiFA29S2ZhMNG20NPbkUVsFL-jiwTd10KSsPT8yBYipI9O7mWsUWt_8KZs1y_vpM_k3SyYihnWpssdzDm1uOZ8U3mzFr1xsLAO718GNUSXk6npSDzLl59HEqa6zs4O9awO2qnSHvcmyELNk31w'
])
]);
$this->expectException(OidcInvalidTokenException::class);
$this->expectExceptionMessage('Token signature could not be validated using the provided keys');
$token->validate('abc');
}
public function test_error_thrown_if_invalid_key_provided()
{
$token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), ['url://example.com']);
$this->expectException(OidcInvalidTokenException::class);
$this->expectExceptionMessage('Unexpected type of key value provided');
$token->validate('abc');
}
public function test_error_thrown_if_token_algorithm_is_not_rs256()
{
$token = new OidcIdToken(OidcJwtHelper::idToken([], ['alg' => 'HS256']), OidcJwtHelper::defaultIssuer(), []);
$this->expectException(OidcInvalidTokenException::class);
$this->expectExceptionMessage("Only RS256 signature validation is supported. Token reports using HS256");
$token->validate('abc');
}
public function test_token_claim_error_cases()
{
/** @var array<array{0: string: 1: array}> $claimOverridesByErrorMessage */
$claimOverridesByErrorMessage = [
// 1. iss claim present
['Missing or non-matching token issuer value', ['iss' => null]],
// 1. iss claim matches provided issuer
['Missing or non-matching token issuer value', ['iss' => 'https://auth.example.co.uk']],
// 2. aud claim present
['Missing token audience value', ['aud' => null]],
// 2. aud claim validates all values against those expected (Only expect single)
['Token audience value has 2 values, Expected 1', ['aud' => ['abc', 'def']]],
// 2. aud claim matches client id
['Token audience value did not match the expected client_id', ['aud' => 'xxyyzz.aaa.bbccdd.456']],
// 4. azp claim matches client id if present
['Token authorized party exists but does not match the expected client_id', ['azp' => 'xxyyzz.aaa.bbccdd.456']],
// 5. exp claim present
['Missing token expiration time value', ['exp' => null]],
// 5. exp claim not expired
['Token has expired', ['exp' => time() - 360]],
// 6. iat claim present
['Missing token issued at time value', ['iat' => null]],
// 6. iat claim too far in the future
['Token issue at time is not recent or is invalid', ['iat' => time() + 600]],
// 6. iat claim too far in the past
['Token issue at time is not recent or is invalid', ['iat' => time() - 172800]],
// Custom: sub is present
['Missing token subject value', ['sub' => null]],
];
foreach ($claimOverridesByErrorMessage as [$message, $overrides]) {
$token = new OidcIdToken(OidcJwtHelper::idToken($overrides), OidcJwtHelper::defaultIssuer(), [
OidcJwtHelper::publicJwkKeyArray()
]);
$err = null;
try {
$token->validate('xxyyzz.aaa.bbccdd.123');
} catch (\Exception $exception) {
$err = $exception;
}
$this->assertInstanceOf(OidcInvalidTokenException::class, $err, $message);
$this->assertEquals($message, $err->getMessage());
}
}
public function test_keys_can_be_a_local_file_reference_to_pem_key()
{
$file = tmpfile();
$testFilePath = 'file://' . stream_get_meta_data($file)['uri'];
file_put_contents($testFilePath, OidcJwtHelper::publicPemKey());
$token = new OidcIdToken(OidcJwtHelper::idToken(), OidcJwtHelper::defaultIssuer(), [
$testFilePath
]);
$this->assertTrue($token->validate('xxyyzz.aaa.bbccdd.123'));
unlink($testFilePath);
}
}