diff --git a/docs/addons/jwt.md b/docs/addons/jwt.md index 0e3f4b8a6..4ddfd94bf 100644 --- a/docs/addons/jwt.md +++ b/docs/addons/jwt.md @@ -141,6 +141,38 @@ If you don't want any logs, set it to `Auth::RECORD_LOGIN_ATTEMPT_NONE`. If you want to log all login attempts, set it to `Auth::RECORD_LOGIN_ATTEMPT_ALL`. It means you log all requests. +### Configure JWT Revocation + +Shield stores JWT revocations in `auth_jwt_revocations`. To use a different +table name, set the `jwt_revocations` entry in `Config\Auth::$tables` in +**app/Config/Auth.php** before running the migration. + +Run Shield's migrations from the new release before it starts verifying JWTs. + +```console +php spark migrate --all +``` + +The store uses `Config\Auth::$DBGroup`. Every instance that verifies the same +JWTs must use the same revocation database. Route requests to the logout +endpoint once all servers that verify these JWTs have been upgraded. + +Each protected request with a JWT that has a `jti` adds one database lookup +for revocation after the signature and revocation claims pass validation. + +`JWTManager::issue()` and `JWTManager::generateToken()` automatically add a +random token ID (`jti`) when the caller omits it. Signed JWTs with a `jti` +require a non-empty string issuer (`iss`), a non-empty string `jti` of at most +255 bytes, and an integer expiration time (`exp`, in Unix seconds). If you +supply a `jti`, use a unique value for every token issued under the same +issuer. Set a stable issuer in `$defaultClaims` and let the manager set +`exp` from the configured lifetime, or pass an integer expiration claim +when issuing a token. + +Legacy JWTs without a `jti` can still authenticate under the prior signature +and time checks. Clients using these JWTs must obtain a newly issued JWT to +use API logout. + ## Issuing JWTs To use JWT Authentication, you need a controller that issues JWTs. @@ -286,6 +318,99 @@ that has the JWT. It then validates the token. If the token is valid, it can determine the correct user, which will then be available through an `auth()->user()` call. +## Revoking the Current API Token + +Register the application-owned POST route in **app/Config/Routes.php**. + +```php +$routes->post('api/logout', '\App\Controllers\Auth\JwtLogoutController::logout'); +``` + +Apply the `jwt` filter to your protected API routes and keep this route outside +that filter. If you currently apply `jwt` to all `api/*` paths, move the filter +to the protected routes or a group that excludes this route. The logout +controller verifies the bearer token through `JWTManager::revokeToken()`, so +a repeat request with the same unexpired token can complete successfully. + +Create **app/Controllers/Auth/JwtLogoutController.php**. + +```php +request->getHeaderLine(config('AuthJWT')->authenticatorHeader); + $bearer = '/\ABearer[ \t]+([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\z/i'; + if (preg_match($bearer, $header, $matches) !== 1) { + return $this->unauthorized(); + } + + /** @var JWTManager $manager */ + $manager = service('jwtmanager'); + + try { + $manager->revokeToken($matches[1]); + } catch (InvalidTokenException) { + return $this->unauthorized(); + } catch (RuntimeException) { + return $this->response->setStatusCode(ResponseInterface::HTTP_SERVICE_UNAVAILABLE); + } + + return $this->response->setStatusCode(ResponseInterface::HTTP_NO_CONTENT)->setBody(''); + } + + private function unauthorized(): ResponseInterface + { + return $this->response + ->setHeader('WWW-Authenticate', 'Bearer') + ->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED); + } +} +``` + +For tokens issued with a custom key group, pass the trusted key group name as +the second argument to `revokeToken()`. + +```bash +curl -i -X POST https://api.example.com/api/logout \ + -H "Authorization: Bearer $JWT" +``` + +Success returns `204 No Content`, including repeat requests made before the +same token expires. Subsequent requests with that token fail verification in +the `jwt` filter or `JWTManager::parse()`. Missing, malformed, invalid, and +expired bearer tokens receive `401 Unauthorized`, as do signed JWTs without a +`jti`. If Shield cannot store the revocation, the controller returns +`503 Service Unavailable`. + +This operation revokes the presented JWT. Use the application's existing flows +to end browser sessions or revoke refresh tokens. + +### Clean Up Expired Revocations + +The database stores a digest of the issuer and token ID with the expiration +timestamp. JWTs with a `jti` use the signed `exp` as a strict cutoff without +expiration leeway. Keep the clocks of verifying servers synchronized, and run +the following from a scheduled application task to remove expired records. + +```php +$removed = service('jwtmanager')->purgeExpiredRevocations(); +``` + +The method returns the number of records removed. + ## Method References ### Generating Signed JWTs diff --git a/docs/customization/table_names.md b/docs/customization/table_names.md index daad7d7f8..999a4a496 100644 --- a/docs/customization/table_names.md +++ b/docs/customization/table_names.md @@ -9,6 +9,7 @@ public array $tables = [ 'identities' => 'auth_identities', 'logins' => 'auth_logins', 'token_logins' => 'auth_token_logins', + 'jwt_revocations' => 'auth_jwt_revocations', 'remember_tokens' => 'auth_remember_tokens', 'groups_users' => 'auth_groups_users', 'permissions_users' => 'auth_permissions_users', diff --git a/rector.php b/rector.php index ca31f2cde..bf4e96fa6 100644 --- a/rector.php +++ b/rector.php @@ -49,6 +49,8 @@ ]) ->withBootstrapFiles([ realpath(getcwd()) . '/vendor/codeigniter4/framework/system/Test/bootstrap.php', + // Load Config\Migrations before PHPStan's reflection can intercept its autoload. + realpath(getcwd()) . '/vendor/codeigniter4/framework/app/Config/Migrations.php', ]) ->withPHPStanConfigs([ __DIR__ . '/phpstan.dist.neon', diff --git a/src/Authentication/JWTManager.php b/src/Authentication/JWTManager.php index ad0806465..289ebe6b4 100644 --- a/src/Authentication/JWTManager.php +++ b/src/Authentication/JWTManager.php @@ -14,9 +14,13 @@ namespace CodeIgniter\Shield\Authentication; use CodeIgniter\I18n\Time; +use CodeIgniter\Shield\Authentication\JWT\Exceptions\InvalidTokenException; use CodeIgniter\Shield\Authentication\JWT\JWSDecoder; use CodeIgniter\Shield\Authentication\JWT\JWSEncoder; use CodeIgniter\Shield\Entities\User; +use CodeIgniter\Shield\Exceptions\RuntimeException; +use CodeIgniter\Shield\Models\JWTRevocationModel; +use RuntimeException as NativeRuntimeException; use stdClass; /** @@ -32,6 +36,7 @@ public function __construct( ?Time $clock = null, ?JWSEncoder $jwsEncoder = null, ?JWSDecoder $jwsDecoder = null, + private readonly ?JWTRevocationModel $revocationModel = null, ) { $this->clock = $clock ?? new Time(); $this->jwsEncoder = $jwsEncoder ?? new JWSEncoder(null, $this->clock); @@ -79,16 +84,112 @@ public function issue( $keyset = 'default', ?array $headers = null, ): string { + if (! array_key_exists('jti', $claims)) { + $claims['jti'] = bin2hex(random_bytes(16)); + } + return $this->jwsEncoder->encode($claims, $ttl, $keyset, $headers); } /** - * Returns payload of the JWT + * Verifies the JWT and returns its payload unless it has been revoked. * * @param string $keyset The key group. The array key of Config\AuthJWT::$keys. */ public function parse(string $encodedToken, $keyset = 'default'): stdClass { - return $this->jwsDecoder->decode($encodedToken, $keyset); + $payload = $this->jwsDecoder->decode($encodedToken, $keyset); + + // Keep signed JWTs issued before token IDs were added usable. + if (! property_exists($payload, 'jti')) { + return $payload; + } + + [$identifier, $expiresAt] = $this->revocationIdentity($payload); + + try { + $revoked = $this->revocations()->isRevoked($identifier); + } catch (NativeRuntimeException) { + log_message('error', '[Shield] JWT revocation lookup failed.'); + $revoked = true; + } + + if ($revoked) { + throw new InvalidTokenException(lang('Auth.invalidJWT'), InvalidTokenException::INVALID_TOKEN); + } + + // An expired revocation record could have been removed during the lookup. + $this->enforceExpiry($expiresAt); + + return $payload; + } + + /** + * Revokes a verified, unexpired JWT with a token ID. + * + * @throws InvalidTokenException If the JWT is invalid or cannot be revoked. + * @throws RuntimeException If storage fails. + */ + public function revokeToken(string $encodedToken, string $keyset = 'default'): void + { + // Verify again without checking the revocation store so retries are safe. + $payload = $this->jwsDecoder->decode($encodedToken, $keyset); + [$identifier, $expiresAt] = $this->revocationIdentity($payload); + + try { + $this->revocations()->revoke($identifier, $expiresAt); + } catch (NativeRuntimeException) { + throw new RuntimeException('JWT revocation could not be stored.'); + } + } + + /** + * Removes revocation records whose signed JWTs have expired. + * + * @return int The number of removed records. + * + * @throws RuntimeException If the revocation records cannot be removed. + */ + public function purgeExpiredRevocations(): int + { + try { + return $this->revocations()->purgeExpired($this->clock::now()->getTimestamp()); + } catch (NativeRuntimeException) { + throw new RuntimeException('Expired JWT revocations could not be purged.'); + } + } + + /** + * @return array{string, int} The issuer-scoped digest and expiry. + */ + private function revocationIdentity(stdClass $payload): array + { + $issuer = $payload->iss ?? null; + $jti = $payload->jti ?? null; + $expiresAt = $payload->exp ?? null; + + if (! is_string($issuer) || $issuer === '' + || ! is_string($jti) || $jti === '' || strlen($jti) > 255 + || ! is_int($expiresAt) + ) { + throw new InvalidTokenException(lang('Auth.invalidJWT'), InvalidTokenException::INVALID_TOKEN); + } + + $this->enforceExpiry($expiresAt); + + return [hash('sha256', strlen($issuer) . ':' . $issuer . $jti), $expiresAt]; + } + + private function enforceExpiry(int $expiresAt): void + { + // The revocation store can remove this record at exp, so ignore decoder leeway here. + if ($expiresAt <= $this->clock::now()->getTimestamp()) { + throw new InvalidTokenException(lang('Auth.expiredJWT'), InvalidTokenException::EXPIRED_TOKEN); + } + } + + private function revocations(): JWTRevocationModel + { + return $this->revocationModel ?? model(JWTRevocationModel::class); } } diff --git a/src/Config/Auth.php b/src/Config/Auth.php index e8d779905..99f675fa7 100644 --- a/src/Config/Auth.php +++ b/src/Config/Auth.php @@ -415,6 +415,7 @@ class Auth extends BaseConfig * - auth_identities Auth Identities Table, Used for storage of passwords, access tokens, social login identities, etc. * - auth_logins Auth Login Attempts, Table records login attempts. * - auth_token_logins Auth Token Login Attempts Table, Records Bearer Token type login attempts. + * - auth_jwt_revocations Revoked JWTs Table. * - auth_remember_tokens Auth Remember Tokens (remember-me) Table. * - auth_groups_users Groups Users Table. * - auth_permissions_users Users Permissions Table. @@ -426,6 +427,7 @@ class Auth extends BaseConfig 'identities' => 'auth_identities', 'logins' => 'auth_logins', 'token_logins' => 'auth_token_logins', + 'jwt_revocations' => 'auth_jwt_revocations', 'remember_tokens' => 'auth_remember_tokens', 'groups_users' => 'auth_groups_users', 'permissions_users' => 'auth_permissions_users', diff --git a/src/Database/Migrations/2026-11-24-000000_create_jwt_revocations.php b/src/Database/Migrations/2026-11-24-000000_create_jwt_revocations.php new file mode 100644 index 000000000..25122b912 --- /dev/null +++ b/src/Database/Migrations/2026-11-24-000000_create_jwt_revocations.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Shield\Database\Migrations; + +use CodeIgniter\Database\Forge; +use CodeIgniter\Database\Migration; +use CodeIgniter\Shield\Config\Auth; + +class CreateJWTRevocations extends Migration +{ + private readonly string $table; + + public function __construct(?Forge $forge = null) + { + /** @var Auth $authConfig */ + $authConfig = config('Auth'); + + if ($authConfig->DBGroup !== null) { + $this->DBGroup = $authConfig->DBGroup; + } + + parent::__construct($forge); + + // Older application configs may override the table map without this entry. + $this->table = $authConfig->tables['jwt_revocations'] ?? 'auth_jwt_revocations'; + } + + public function up(): void + { + $this->forge->addField([ + 'identifier' => ['type' => 'varchar', 'constraint' => 64], + 'expires_at' => ['type' => 'bigint'], + ]); + $this->forge->addPrimaryKey('identifier'); + $this->forge->addKey('expires_at'); + + $attributes = $this->db->getPlatform() === 'MySQLi' ? ['ENGINE' => 'InnoDB'] : []; + $this->forge->createTable($this->table, false, $attributes); + } + + public function down(): void + { + $this->forge->dropTable($this->table, true); + } +} diff --git a/src/Models/JWTRevocationModel.php b/src/Models/JWTRevocationModel.php new file mode 100644 index 000000000..742afd4f3 --- /dev/null +++ b/src/Models/JWTRevocationModel.php @@ -0,0 +1,74 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Shield\Models; + +use CodeIgniter\Database\RawSql; +use CodeIgniter\Shield\Exceptions\InvalidArgumentException; + +class JWTRevocationModel extends BaseModel +{ + protected $primaryKey = 'identifier'; + protected $useAutoIncrement = false; + protected $allowedFields = ['identifier', 'expires_at']; + + protected function initialize(): void + { + parent::initialize(); + + $this->table = $this->tables['jwt_revocations'] ?? 'auth_jwt_revocations'; + } + + public function revoke(string $identifier, int $expiresAt): void + { + if (preg_match('/\A[0-9a-f]{64}\z/', $identifier) !== 1) { + throw new InvalidArgumentException('Expected a SHA-256 digest for the JWT revocation identifier.'); + } + + $expiration = $this->db->protectIdentifiers($this->table . '.expires_at'); + $later = new RawSql("CASE WHEN {$expiration} < {$expiresAt} THEN {$expiresAt} ELSE {$expiration} END"); + + // Execute the compiled upsert directly to observe write failures even when DBDebug is false. + $sql = $this->db->table($this->table) + ->onConstraint('identifier') + ->set(['identifier' => $identifier, 'expires_at' => $expiresAt]) + ->updateFields(['expires_at' => $later]) + ->getCompiledUpsert(); + + $this->checkQueryReturn($this->db->query($sql, null, false) !== false); + } + + public function isRevoked(string $identifier): bool + { + $result = $this->builder() + ->select('identifier') + ->where('identifier', $identifier) + ->get(); + + if ($result === false) { + throw new DatabaseException('Could not read the JWT revocation table.'); + } + + return $result->getRowArray() !== null; + } + + public function purgeExpired(int $now): int + { + $deleted = $this->builder() + ->where('expires_at <=', $now) + ->delete(); + $this->checkQueryReturn($deleted); + + return $this->db->affectedRows(); + } +} diff --git a/tests/Authentication/Filters/JWTFilterTest.php b/tests/Authentication/Filters/JWTFilterTest.php index 4477abf1c..557c4310c 100644 --- a/tests/Authentication/Filters/JWTFilterTest.php +++ b/tests/Authentication/Filters/JWTFilterTest.php @@ -92,4 +92,34 @@ public function testFilterSuccess(): void $this->assertSame($user->id, \auth('jwt')->id()); $this->assertSame($user->id, \auth('jwt')->user()->id); } + + public function testFilterRejectsOnlyTheRevokedToken(): void + { + /** @var User $user */ + $user = \fake(UserModel::class); + + $generator = new JWTManager(); + $firstToken = $generator->generateToken($user); + $otherToken = $generator->generateToken($user); + + $this->withHeaders(['Authorization' => 'Bearer ' . $firstToken]) + ->get('protected-route') + ->assertStatus(200); + + $generator->revokeToken($firstToken); + + $this->withHeaders(['Authorization' => 'Bearer ' . $firstToken]) + ->get('protected-route') + ->assertStatus(401); + + $this->withHeaders(['Authorization' => 'Bearer ' . $otherToken]) + ->get('protected-route') + ->assertStatus(200); + + $this->seeInDatabase('auth_token_logins', [ + 'id_type' => JWT::ID_TYPE_JWT, + 'identifier' => $firstToken, + 'success' => 0, + ]); + } } diff --git a/tests/Unit/Authentication/JWT/JWTManagerTest.php b/tests/Unit/Authentication/JWT/JWTManagerTest.php index eed444244..84e809190 100644 --- a/tests/Unit/Authentication/JWT/JWTManagerTest.php +++ b/tests/Unit/Authentication/JWT/JWTManagerTest.php @@ -14,10 +14,18 @@ namespace CodeIgniter\Shield\Tests\Unit\Authentication\JWT; use CodeIgniter\I18n\Time; +use CodeIgniter\Shield\Authentication\JWT\Exceptions\InvalidTokenException; +use CodeIgniter\Shield\Authentication\JWT\JWSDecoder; +use CodeIgniter\Shield\Authentication\JWT\JWSEncoder; use CodeIgniter\Shield\Authentication\JWTManager; use CodeIgniter\Shield\Config\AuthJWT; +use CodeIgniter\Shield\Entities\User; +use CodeIgniter\Shield\Exceptions\RuntimeException; +use CodeIgniter\Shield\Models\DatabaseException; +use CodeIgniter\Shield\Models\JWTRevocationModel; use CodeIgniter\Shield\Models\UserModel; use CodeIgniter\Shield\Tests\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Depends; /** @@ -27,7 +35,10 @@ final class JWTManagerTest extends TestCase { private function createJWTManager(?Time $clock = null): JWTManager { - return $clock instanceof Time ? new JWTManager($clock) : new JWTManager(); + $store = $this->createStub(JWTRevocationModel::class); + $store->method('isRevoked')->willReturn(false); + + return new JWTManager($clock, revocationModel: $store); } public function testGenerateToken(): array @@ -60,11 +71,14 @@ public function testGenerateTokenPayload(array $data): void $manager = $this->createJWTManager(); $payload = $manager->parse($token); + $this->assertMatchesRegularExpression('/\A[a-f0-9]{32}\z/', $payload->jti); + /** @var AuthJWT $config */ $config = config('AuthJWT'); $expected = [ 'iss' => $config->defaultClaims['iss'], 'sub' => '1', + 'jti' => $payload->jti, 'iat' => $currentTime->getTimestamp(), 'exp' => $currentTime->getTimestamp() + $config->timeToLive, ]; @@ -121,12 +135,15 @@ public function testIssuePayload(array $data): void $manager = $this->createJWTManager(); $payload = $manager->parse($token); + $this->assertMatchesRegularExpression('/\A[a-f0-9]{32}\z/', $payload->jti); + /** @var AuthJWT $config */ $config = config('AuthJWT'); $expected = [ 'iss' => $config->defaultClaims['iss'], 'user_id' => '1', 'email' => 'admin@example.jp', + 'jti' => $payload->jti, 'iat' => $currentTime->getTimestamp(), 'exp' => $currentTime->getTimestamp() + DAY, ]; @@ -324,6 +341,231 @@ public function testParseCanDecodeWithAsymmetricKey(): void $this->assertSame('1', $payload->user_id); } + public function testLegacyTokenWithoutIdentifierParsesWithoutStorageAndCannotBeRevoked(): void + { + $store = $this->createMock(JWTRevocationModel::class); + $store->expects($this->never())->method('isRevoked'); + $store->expects($this->never())->method('revoke'); + $manager = new JWTManager(revocationModel: $store); + + // Before JWTManager automatically added an identifier, it delegated directly to the encoder. + $token = (new JWSEncoder())->encode(['sub' => '42']); + $payload = $manager->parse($token); + + $this->assertObjectNotHasProperty('jti', $payload); + $this->assertSame('42', $payload->sub); + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage(lang('Auth.invalidJWT')); + + $manager->revokeToken($token); + } + + public function testIssuanceGeneratesDistinctIdentifiersAndPreservesExplicitValues(): void + { + $manager = $this->createJWTManager(); + $user = new User(['id' => 42]); + + $first = $this->decodeJWT($manager->issue(['sub' => '42']), 'payload'); + $second = $this->decodeJWT($manager->generateToken($user), 'payload'); + + $this->assertMatchesRegularExpression('/\A[a-f0-9]{32}\z/', $first['jti']); + $this->assertMatchesRegularExpression('/\A[a-f0-9]{32}\z/', $second['jti']); + $this->assertNotSame($first['jti'], $second['jti']); + $this->assertSame('explicit', $this->decodeJWT($manager->issue(['jti' => 'explicit']), 'payload')['jti']); + $this->assertNull($this->decodeJWT($manager->issue(['jti' => null]), 'payload')['jti']); + } + + public function testRevocationUsesOnlyVerifiedIssuerAndIdentifier(): void + { + $store = $this->createMock(JWTRevocationModel::class); + $manager = new JWTManager(revocationModel: $store); + $expiresAt = Time::now()->getTimestamp() + MINUTE; + $token = $manager->issue(['iss' => 'issuer', 'jti' => 'identifier', 'exp' => $expiresAt]); + + $store->expects($this->exactly(2))->method('revoke') + ->with(hash('sha256', '6:issueridentifier'), $expiresAt); + $store->expects($this->never())->method('isRevoked'); + + $manager->revokeToken($token); + $manager->revokeToken($token); + } + + public function testRevocationDoesNotWriteForAnInvalidToken(): void + { + $store = $this->createMock(JWTRevocationModel::class); + $store->expects($this->never())->method('revoke'); + $manager = new JWTManager(revocationModel: $store); + + $this->expectException(InvalidTokenException::class); + + $manager->revokeToken('invalid-token'); + } + + public function testParseRejectsRevokedTokenAndAllowsSeparateIssuer(): void + { + $store = $this->createMock(JWTRevocationModel::class); + $store->expects($this->exactly(2))->method('isRevoked') + ->willReturnMap([ + [hash('sha256', '1:abc'), false], + [hash('sha256', '2:abc'), true], + ]); + $manager = new JWTManager(revocationModel: $store); + + $this->assertSame('a', $manager->parse($manager->issue(['iss' => 'a', 'jti' => 'bc']))->iss); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage(lang('Auth.invalidJWT')); + + $manager->parse($manager->issue(['iss' => 'ab', 'jti' => 'c'])); + } + + /** + * @param array $claims + */ + #[DataProvider('provideParseRejectsInvalidRevocationClaimsBeforeCheckingStorage')] + public function testParseRejectsInvalidRevocationClaimsBeforeCheckingStorage(array $claims): void + { + $store = $this->createMock(JWTRevocationModel::class); + $store->expects($this->never())->method('isRevoked'); + $decoder = $this->createMock(JWSDecoder::class); + $decoder->expects($this->once())->method('decode')->willReturn((object) $claims); + $manager = new JWTManager(jwsDecoder: $decoder, revocationModel: $store); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage(lang('Auth.invalidJWT')); + + $manager->parse('verified-by-mock'); + } + + /** + * @return iterable}> + */ + public static function provideParseRejectsInvalidRevocationClaimsBeforeCheckingStorage(): iterable + { + $claims = ['iss' => 'issuer', 'jti' => 'identifier', 'exp' => time() + DAY]; + + yield 'explicit null jti' => [['jti' => null] + $claims]; + + yield 'empty jti' => [['jti' => ''] + $claims]; + + yield 'numeric jti' => [['jti' => 42] + $claims]; + + yield 'long jti' => [['jti' => str_repeat('a', 256)] + $claims]; + + yield 'empty issuer' => [['iss' => ''] + $claims]; + + yield 'invalid issuer' => [['iss' => ['issuer']] + $claims]; + + yield 'issuer missing' => [array_diff_key($claims, ['iss' => true])]; + + yield 'expiry missing' => [array_diff_key($claims, ['exp' => true])]; + + yield 'expiry not integer' => [['exp' => (string) $claims['exp']] + $claims]; + } + + public function testManagedExpiryIsStrictEvenWhenDecoderAcceptsTheToken(): void + { + $clock = Time::parse('2026-06-13 12:00:00', 'UTC'); + $store = $this->createMock(JWTRevocationModel::class); + $store->expects($this->never())->method('isRevoked'); + $decoder = $this->createMock(JWSDecoder::class); + $decoder->expects($this->once())->method('decode')->willReturn((object) [ + 'iss' => 'issuer', + 'jti' => 'identifier', + 'exp' => $clock->getTimestamp(), + ]); + $manager = new JWTManager($clock, jwsDecoder: $decoder, revocationModel: $store); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage(lang('Auth.expiredJWT')); + + Time::setTestNow($clock); + + try { + $manager->parse('verified-by-mock'); + } finally { + Time::setTestNow(); + } + } + + public function testRevocationStoreReadFailureDoesNotAuthenticate(): void + { + $store = $this->createMock(JWTRevocationModel::class); + $store->expects($this->once())->method('isRevoked') + ->willThrowException(new DatabaseException('private database detail')); + $manager = new JWTManager(revocationModel: $store); + + try { + $manager->parse($manager->issue(['sub' => '42'])); + $this->fail('Revocation store failure allowed the token.'); + } catch (InvalidTokenException $exception) { + $this->assertSame(lang('Auth.invalidJWT'), $exception->getMessage()); + $this->assertNull($exception->getPrevious()); + } + } + + public function testExpiryIsRecheckedWhenARevocationRecordCanBePurgedDuringLookup(): void + { + $clock = Time::parse('2026-06-13 12:00:00', 'UTC'); + $expiry = $clock->addSeconds(1); + $store = $this->createMock(JWTRevocationModel::class); + $store->expects($this->once())->method('isRevoked')->willReturnCallback(static function () use ($expiry): bool { + Time::setTestNow($expiry); + + return false; + }); + $decoder = $this->createMock(JWSDecoder::class); + $decoder->expects($this->once())->method('decode')->willReturn((object) [ + 'iss' => 'issuer', + 'jti' => 'identifier', + 'exp' => $expiry->getTimestamp(), + ]); + $manager = new JWTManager($clock, jwsDecoder: $decoder, revocationModel: $store); + + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage(lang('Auth.expiredJWT')); + + Time::setTestNow($clock); + + try { + $manager->parse('verified-by-mock'); + } finally { + Time::setTestNow(); + } + } + + public function testRevocationStoreWriteFailureIsSanitized(): void + { + $store = $this->createMock(JWTRevocationModel::class); + $store->expects($this->once())->method('revoke') + ->willThrowException(new DatabaseException('private database detail')); + $manager = new JWTManager(revocationModel: $store); + + try { + $manager->revokeToken($manager->issue(['sub' => '42'])); + $this->fail('A failed write was reported as successful.'); + } catch (RuntimeException $exception) { + $this->assertSame('JWT revocation could not be stored.', $exception->getMessage()); + $this->assertNull($exception->getPrevious()); + } + } + + public function testPurgeUsesTheCurrentTimeAndReturnsTheRemovedCount(): void + { + $clock = Time::parse('2026-06-13 12:00:00', 'UTC'); + $store = $this->createMock(JWTRevocationModel::class); + $store->expects($this->once())->method('purgeExpired')->with($clock->getTimestamp())->willReturn(2); + $manager = new JWTManager($clock, revocationModel: $store); + + Time::setTestNow($clock); + + try { + $this->assertSame(2, $manager->purgeExpiredRevocations()); + } finally { + Time::setTestNow(); + } + } + private function generateJWTWithAsymmetricKey(): string { $manager = $this->createJWTManager(); diff --git a/tests/Unit/JWTRevocationModelTest.php b/tests/Unit/JWTRevocationModelTest.php new file mode 100644 index 000000000..f5bcd46dc --- /dev/null +++ b/tests/Unit/JWTRevocationModelTest.php @@ -0,0 +1,146 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Shield\Tests\Unit; + +use Closure; +use CodeIgniter\Database\Config as Database; +use CodeIgniter\Shield\Database\Migrations\CreateJWTRevocations; +use CodeIgniter\Shield\Exceptions\InvalidArgumentException; +use CodeIgniter\Shield\Models\DatabaseException; +use CodeIgniter\Shield\Models\JWTRevocationModel; +use CodeIgniter\Shield\Tests\DatabaseTestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use ReflectionProperty; + +/** + * @internal + */ +final class JWTRevocationModelTest extends DatabaseTestCase +{ + protected $refresh = true; + + public function testRevocationIsVisibleToAnotherModel(): void + { + $writer = new JWTRevocationModel(); + $identifier = hash('sha256', 'issuer and token identifier'); + + $this->assertFalse($writer->isRevoked($identifier)); + + $writer->revoke($identifier, 2_200_000_000); + + $this->assertTrue((new JWTRevocationModel())->isRevoked($identifier)); + } + + public function testDuplicateRevocationsKeepTheLaterExpiration(): void + { + $revocations = new JWTRevocationModel(); + $identifier = hash('sha256', 'issuer and token identifier'); + + $revocations->revoke($identifier, 1_900_000_000); + $revocations->revoke($identifier, 2_200_000_000); + $revocations->revoke($identifier, 2_200_000_000); + $revocations->revoke($identifier, 1_900_000_000); + + $this->assertSame(0, $revocations->purgeExpired(1_900_000_000)); + $this->assertTrue($revocations->isRevoked($identifier)); + $this->assertSame(1, $revocations->purgeExpired(2_200_000_000)); + $this->assertFalse($revocations->isRevoked($identifier)); + } + + public function testMigrationAndModelUseConfiguredTableName(): void + { + $config = config('Auth'); + $table = 'custom_jwt_revocations'; + $config->tables['jwt_revocations'] = $table; + $migration = new CreateJWTRevocations(Database::forge($this->db)); + $identifier = hash('sha256', 'issuer and token identifier'); + + try { + $migration->up(); + (new JWTRevocationModel())->revoke($identifier, 2_200_000_000); + + $this->seeInDatabase($table, ['identifier' => $identifier]); + $this->dontSeeInDatabase($this->tables['jwt_revocations'], ['identifier' => $identifier]); + } finally { + $config->tables = $this->tables; + $migration->down(); + } + } + + public function testModelUsesDefaultTableWhenLegacyConfigOmitsTheKey(): void + { + $config = config('Auth'); + $identifier = hash('sha256', 'issuer and token identifier'); + + try { + unset($config->tables['jwt_revocations']); + + (new JWTRevocationModel())->revoke($identifier, 2_200_000_000); + + $this->seeInDatabase($this->tables['jwt_revocations'], ['identifier' => $identifier]); + } finally { + $config->tables = $this->tables; + } + } + + public function testRawTokenIdentifiersAreRejected(): void + { + $this->expectException(InvalidArgumentException::class); + + (new JWTRevocationModel())->revoke('raw token identifier', 2_200_000_000); + } + + /** + * @param Closure(JWTRevocationModel): void $query + */ + #[DataProvider('provideDatabaseFailureThrowsWithDebugDisabled')] + public function testDatabaseFailureThrowsWithDebugDisabled(Closure $query): void + { + $config = config('Auth'); + $dbDebug = new ReflectionProperty($this->db, 'DBDebug'); + $debugMode = $dbDebug->getValue($this->db); + + $this->expectException(DatabaseException::class); + + try { + $config->tables['jwt_revocations'] = 'missing_jwt_revocations'; + $dbDebug->setValue($this->db, false); + + $query(new JWTRevocationModel()); + } finally { + $config->tables = $this->tables; + $dbDebug->setValue($this->db, $debugMode); + } + } + + /** + * @return iterable + */ + public static function provideDatabaseFailureThrowsWithDebugDisabled(): iterable + { + $identifier = hash('sha256', 'issuer and token identifier'); + + yield 'read' => [static function (JWTRevocationModel $revocations) use ($identifier): void { + $revocations->isRevoked($identifier); + }]; + + yield 'write' => [static function (JWTRevocationModel $revocations) use ($identifier): void { + $revocations->revoke($identifier, 2_200_000_000); + }]; + + yield 'purge' => [static function (JWTRevocationModel $revocations): void { + $revocations->purgeExpired(2_200_000_000); + }]; + } +}