From 3beb4c604df655653ff028f36fc4a9d1c9b56827 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amel=20Junuzovi=C4=87?= Date: Tue, 24 Nov 2026 13:11:43 +0100 Subject: [PATCH 1/8] feat(jwt): add opt-in token revocation --- docs/addons/jwt.md | 136 +++++++++- src/Authentication/Authenticators/JWT.php | 3 +- src/Authentication/JWTManager.php | 108 +++++++- src/Config/AuthJWT.php | 13 + ...26-11-24-000000_create_jwt_revocations.php | 49 ++++ src/Models/JWTRevocationModel.php | 74 ++++++ .../Authenticators/JWTAuthenticatorTest.php | 2 +- .../Authentication/Filters/JWTFilterTest.php | 36 +++ .../Authentication/JWT/JWTManagerTest.php | 235 ++++++++++++++++++ tests/Unit/JWTRevocationModelTest.php | 109 ++++++++ 10 files changed, 756 insertions(+), 9 deletions(-) create mode 100644 src/Database/Migrations/2026-11-24-000000_create_jwt_revocations.php create mode 100644 src/Models/JWTRevocationModel.php create mode 100644 tests/Unit/JWTRevocationModelTest.php diff --git a/docs/addons/jwt.md b/docs/addons/jwt.md index 0e3f4b8a6..3f1a66be3 100644 --- a/docs/addons/jwt.md +++ b/docs/addons/jwt.md @@ -141,6 +141,42 @@ 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. +### Enable JWT Revocation + +JWT revocation is disabled by default. To enable it, add these properties to +`Config\AuthJWT` in **app/Config/AuthJWT.php**. + +```php +public bool $revocationEnabled = true; +public string $revocationTable = 'auth_jwt_revocations'; +``` + +Set the table name before applying Shield's migrations. + +```console +php spark migrate --all +``` + +The store uses `Config\Auth::$DBGroup`. Every instance that verifies the same +JWTs must use the same revocation database and enable revocation. Coordinate +the migration and configuration rollout across those instances. A server with +revocation disabled can still accept a revoked JWT within its validity window. + +With revocation enabled, signed JWTs must contain a non-empty string issuer +(`iss`), a non-empty string token ID (`jti`), and an integer expiration time +(`exp`, in Unix seconds). Use a unique `jti` of at most 255 bytes for every +token issued under the same issuer. +`JWTManager::issue()` and `JWTManager::generateToken()` automatically add a +random `jti` when the caller omits it. Set a stable issuer in `$defaultClaims` +and let the manager set `exp` from the configured lifetime, or pass a valid +integer expiration claim when issuing a token. + +Legacy tokens with missing or invalid revocation claims are rejected after +revocation is enabled. To avoid interrupting existing clients, first issue +tokens with the required claims and let older tokens expire before enabling +revocation. Alternatively, enable revocation and require affected clients to +sign in again. + ## Issuing JWTs To use JWT Authentication, you need a controller that issues JWTs. @@ -286,6 +322,98 @@ 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`. 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. JWT revocation uses 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 @@ -370,8 +498,6 @@ you don't pass them. Login attempts are recorded in the `auth_token_logins` table, according to the configuration above. -When a failed login attempt is logged, the raw token value sent is saved in -the `identifier` column. - -When a successful login attempt is logged, the SHA256 hash value of the token -sent is saved in the `identifier` column. +For logged JWT attempts, the `identifier` column stores the SHA-256 digest of +the presented token with a `sha256:` prefix. Requests that omit the token record +an empty identifier if failure logging is enabled. diff --git a/src/Authentication/Authenticators/JWT.php b/src/Authentication/Authenticators/JWT.php index 441872c6f..c9100eb4a 100644 --- a/src/Authentication/Authenticators/JWT.php +++ b/src/Authentication/Authenticators/JWT.php @@ -82,9 +82,10 @@ public function attempt(array $credentials): Result if (! $result->isOK()) { if ($config->recordLoginAttempt >= Auth::RECORD_LOGIN_ATTEMPT_FAILURE) { // Record a failed login attempt. + $token = $credentials['token'] ?? ''; $this->tokenLoginModel->recordLoginAttempt( self::ID_TYPE_JWT, - $credentials['token'] ?? '', + $token === '' ? '' : 'sha256:' . hash('sha256', $token), false, $ipAddress, $userAgent, diff --git a/src/Authentication/JWTManager.php b/src/Authentication/JWTManager.php index ad0806465..976231a46 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,115 @@ public function issue( $keyset = 'default', ?array $headers = null, ): string { + if (config('AuthJWT')->revocationEnabled && ! 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); + + if (! config('AuthJWT')->revocationEnabled) { + 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 when revocation is enabled. + * + * @throws InvalidTokenException If the JWT is invalid or cannot be revoked. + * @throws RuntimeException If revocation is disabled or storage fails. + */ + public function revokeToken(string $encodedToken, string $keyset = 'default'): void + { + if (! config('AuthJWT')->revocationEnabled) { + throw new RuntimeException('JWT revocation is disabled.'); + } + + // 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/AuthJWT.php b/src/Config/AuthJWT.php index e44bf6d39..e3009ae2a 100644 --- a/src/Config/AuthJWT.php +++ b/src/Config/AuthJWT.php @@ -80,6 +80,19 @@ class AuthJWT extends BaseConfig */ public int $timeToLive = HOUR; + /** + * -------------------------------------------------------------------- + * Token Revocation + * -------------------------------------------------------------------- + * Check authenticated JWTs against the revocation table. + */ + public bool $revocationEnabled = false; + + /** + * The unprefixed revocation table name in the Auth database group. + */ + public string $revocationTable = 'auth_jwt_revocations'; + /** * -------------------------------------------------------------------- * Record Login Attempts 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..54a512b9b --- /dev/null +++ b/src/Database/Migrations/2026-11-24-000000_create_jwt_revocations.php @@ -0,0 +1,49 @@ + + * + * 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; + +class CreateJWTRevocations extends Migration +{ + private readonly string $table; + + public function __construct(?Forge $forge = null) + { + $this->DBGroup = config('Auth')->DBGroup; + + parent::__construct($forge); + + $this->table = config('AuthJWT')->revocationTable; + } + + 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..521f7f49c --- /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 = config('AuthJWT')->revocationTable; + } + + 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/Authenticators/JWTAuthenticatorTest.php b/tests/Authentication/Authenticators/JWTAuthenticatorTest.php index af0619fa7..ade3fe7b9 100644 --- a/tests/Authentication/Authenticators/JWTAuthenticatorTest.php +++ b/tests/Authentication/Authenticators/JWTAuthenticatorTest.php @@ -202,7 +202,7 @@ public function testAttemptBadSignatureToken(): void // A login attempt should have always been recorded $this->seeInDatabase('auth_token_logins', [ 'id_type' => JWT::ID_TYPE_JWT, - 'identifier' => self::BAD_JWT, + 'identifier' => 'sha256:' . hash('sha256', self::BAD_JWT), 'success' => 0, ]); } diff --git a/tests/Authentication/Filters/JWTFilterTest.php b/tests/Authentication/Filters/JWTFilterTest.php index 4477abf1c..cee784de0 100644 --- a/tests/Authentication/Filters/JWTFilterTest.php +++ b/tests/Authentication/Filters/JWTFilterTest.php @@ -17,6 +17,7 @@ use CodeIgniter\Shield\Authentication\Authenticators\JWT; use CodeIgniter\Shield\Authentication\JWTManager; use CodeIgniter\Shield\Config\Auth; +use CodeIgniter\Shield\Config\AuthJWT; use CodeIgniter\Shield\Entities\User; use CodeIgniter\Shield\Filters\JWTAuth; use CodeIgniter\Shield\Models\UserModel; @@ -92,4 +93,39 @@ public function testFilterSuccess(): void $this->assertSame($user->id, \auth('jwt')->id()); $this->assertSame($user->id, \auth('jwt')->user()->id); } + + public function testFilterRejectsOnlyTheRevokedToken(): void + { + /** @var AuthJWT $config */ + $config = config('AuthJWT'); + $config->revocationEnabled = true; + + /** @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' => 'sha256:' . hash('sha256', $firstToken), + 'success' => 0, + ]); + $this->dontSeeInDatabase('auth_token_logins', ['identifier' => $firstToken]); + } } diff --git a/tests/Unit/Authentication/JWT/JWTManagerTest.php b/tests/Unit/Authentication/JWT/JWTManagerTest.php index eed444244..fb841c801 100644 --- a/tests/Unit/Authentication/JWT/JWTManagerTest.php +++ b/tests/Unit/Authentication/JWT/JWTManagerTest.php @@ -14,10 +14,16 @@ 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\JWTManager; use CodeIgniter\Shield\Config\AuthJWT; +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; /** @@ -324,6 +330,235 @@ public function testParseCanDecodeWithAsymmetricKey(): void $this->assertSame('1', $payload->user_id); } + public function testDisabledRevocationDoesNotReadOrWriteTheStore(): void + { + $store = $this->createMock(JWTRevocationModel::class); + $store->expects($this->never())->method('isRevoked'); + $store->expects($this->never())->method('revoke'); + $manager = new JWTManager(revocationModel: $store); + + $token = $manager->issue(['sub' => '42']); + + $this->assertObjectNotHasProperty('jti', $manager->parse($token)); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('JWT revocation is disabled.'); + + $manager->revokeToken($token); + } + + public function testEnabledIssuanceGeneratesDistinctIdentifiersAndPreservesExplicitValues(): void + { + config('AuthJWT')->revocationEnabled = true; + $manager = $this->createJWTManager(); + $user = fake(UserModel::class, ['id' => 42], false); + + $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 + { + config('AuthJWT')->revocationEnabled = true; + $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 + { + config('AuthJWT')->revocationEnabled = true; + $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 + { + config('AuthJWT')->revocationEnabled = true; + $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 + { + config('AuthJWT')->revocationEnabled = true; + $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 'legacy token lacks jti' => [array_diff_key($claims, ['jti' => true])]; + + 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 'expiry missing' => [array_diff_key($claims, ['exp' => true])]; + + yield 'expiry not integer' => [['exp' => (string) $claims['exp']] + $claims]; + } + + public function testManagedExpiryIsStrictEvenWhenDecoderAcceptsTheToken(): void + { + config('AuthJWT')->revocationEnabled = true; + $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 + { + config('AuthJWT')->revocationEnabled = true; + $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 + { + config('AuthJWT')->revocationEnabled = true; + $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 + { + config('AuthJWT')->revocationEnabled = true; + $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..254dbce4a --- /dev/null +++ b/tests/Unit/JWTRevocationModelTest.php @@ -0,0 +1,109 @@ + + * + * 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\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 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('AuthJWT'); + $table = $config->revocationTable; + $dbDebug = new ReflectionProperty($this->db, 'DBDebug'); + $debugMode = $dbDebug->getValue($this->db); + + $this->expectException(DatabaseException::class); + + try { + $config->revocationTable = 'missing_jwt_revocations'; + $dbDebug->setValue($this->db, false); + + $query(new JWTRevocationModel()); + } finally { + $config->revocationTable = $table; + $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); + }]; + } +} From a92a08c89e8c99d77f384b5ff075258220732f8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amel=20Junuzovi=C4=87?= Date: Tue, 24 Nov 2026 13:14:06 +0100 Subject: [PATCH 2/8] fix(ci): bootstrap migrations config for Rector --- rector.php | 2 ++ 1 file changed, 2 insertions(+) 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', From c0a742e16b0c4a9c0254a7e378b8c83d33f67f38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amel=20Junuzovi=C4=87?= Date: Tue, 24 Nov 2026 13:26:06 +0100 Subject: [PATCH 3/8] refactor(jwt): remove the revocation feature flag --- docs/addons/jwt.md | 52 ++++++-------- src/Authentication/JWTManager.php | 13 ++-- src/Config/AuthJWT.php | 5 -- .../Authentication/Filters/JWTFilterTest.php | 5 -- .../Authentication/JWT/JWTManagerTest.php | 72 ++++++++++--------- 5 files changed, 67 insertions(+), 80 deletions(-) diff --git a/docs/addons/jwt.md b/docs/addons/jwt.md index 3f1a66be3..6802fb428 100644 --- a/docs/addons/jwt.md +++ b/docs/addons/jwt.md @@ -141,41 +141,34 @@ 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. -### Enable JWT Revocation +### Configure JWT Revocation -JWT revocation is disabled by default. To enable it, add these properties to -`Config\AuthJWT` in **app/Config/AuthJWT.php**. +Shield stores JWT revocations in `auth_jwt_revocations`. Set +`$revocationTable` in **app/Config/AuthJWT.php** before migrating if your +application uses a different table name. -```php -public bool $revocationEnabled = true; -public string $revocationTable = 'auth_jwt_revocations'; -``` - -Set the table name before applying Shield's migrations. +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 and enable revocation. Coordinate -the migration and configuration rollout across those instances. A server with -revocation disabled can still accept a revoked JWT within its validity window. - -With revocation enabled, signed JWTs must contain a non-empty string issuer -(`iss`), a non-empty string token ID (`jti`), and an integer expiration time -(`exp`, in Unix seconds). Use a unique `jti` of at most 255 bytes for every -token issued under the same issuer. -`JWTManager::issue()` and `JWTManager::generateToken()` automatically add a -random `jti` when the caller omits it. Set a stable issuer in `$defaultClaims` -and let the manager set `exp` from the configured lifetime, or pass a valid -integer expiration claim when issuing a token. +JWTs must use the same revocation database. Route requests to the logout +endpoint once all servers that verify these JWTs have been upgraded. -Legacy tokens with missing or invalid revocation claims are rejected after -revocation is enabled. To avoid interrupting existing clients, first issue -tokens with the required claims and let older tokens expire before enabling -revocation. Alternatively, enable revocation and require affected clients to -sign in again. +`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 @@ -395,8 +388,9 @@ curl -i -X POST https://api.example.com/api/logout \ 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`. If Shield cannot store the -revocation, the controller returns `503 Service Unavailable`. +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. @@ -404,7 +398,7 @@ 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. JWT revocation uses the signed `exp` as a strict cutoff without +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. diff --git a/src/Authentication/JWTManager.php b/src/Authentication/JWTManager.php index 976231a46..289ebe6b4 100644 --- a/src/Authentication/JWTManager.php +++ b/src/Authentication/JWTManager.php @@ -84,7 +84,7 @@ public function issue( $keyset = 'default', ?array $headers = null, ): string { - if (config('AuthJWT')->revocationEnabled && ! array_key_exists('jti', $claims)) { + if (! array_key_exists('jti', $claims)) { $claims['jti'] = bin2hex(random_bytes(16)); } @@ -100,7 +100,8 @@ public function parse(string $encodedToken, $keyset = 'default'): stdClass { $payload = $this->jwsDecoder->decode($encodedToken, $keyset); - if (! config('AuthJWT')->revocationEnabled) { + // Keep signed JWTs issued before token IDs were added usable. + if (! property_exists($payload, 'jti')) { return $payload; } @@ -124,17 +125,13 @@ public function parse(string $encodedToken, $keyset = 'default'): stdClass } /** - * Revokes a verified, unexpired JWT when revocation is enabled. + * Revokes a verified, unexpired JWT with a token ID. * * @throws InvalidTokenException If the JWT is invalid or cannot be revoked. - * @throws RuntimeException If revocation is disabled or storage fails. + * @throws RuntimeException If storage fails. */ public function revokeToken(string $encodedToken, string $keyset = 'default'): void { - if (! config('AuthJWT')->revocationEnabled) { - throw new RuntimeException('JWT revocation is disabled.'); - } - // Verify again without checking the revocation store so retries are safe. $payload = $this->jwsDecoder->decode($encodedToken, $keyset); [$identifier, $expiresAt] = $this->revocationIdentity($payload); diff --git a/src/Config/AuthJWT.php b/src/Config/AuthJWT.php index e3009ae2a..872ffd5bf 100644 --- a/src/Config/AuthJWT.php +++ b/src/Config/AuthJWT.php @@ -84,11 +84,6 @@ class AuthJWT extends BaseConfig * -------------------------------------------------------------------- * Token Revocation * -------------------------------------------------------------------- - * Check authenticated JWTs against the revocation table. - */ - public bool $revocationEnabled = false; - - /** * The unprefixed revocation table name in the Auth database group. */ public string $revocationTable = 'auth_jwt_revocations'; diff --git a/tests/Authentication/Filters/JWTFilterTest.php b/tests/Authentication/Filters/JWTFilterTest.php index cee784de0..c09093319 100644 --- a/tests/Authentication/Filters/JWTFilterTest.php +++ b/tests/Authentication/Filters/JWTFilterTest.php @@ -17,7 +17,6 @@ use CodeIgniter\Shield\Authentication\Authenticators\JWT; use CodeIgniter\Shield\Authentication\JWTManager; use CodeIgniter\Shield\Config\Auth; -use CodeIgniter\Shield\Config\AuthJWT; use CodeIgniter\Shield\Entities\User; use CodeIgniter\Shield\Filters\JWTAuth; use CodeIgniter\Shield\Models\UserModel; @@ -96,10 +95,6 @@ public function testFilterSuccess(): void public function testFilterRejectsOnlyTheRevokedToken(): void { - /** @var AuthJWT $config */ - $config = config('AuthJWT'); - $config->revocationEnabled = true; - /** @var User $user */ $user = \fake(UserModel::class); diff --git a/tests/Unit/Authentication/JWT/JWTManagerTest.php b/tests/Unit/Authentication/JWT/JWTManagerTest.php index fb841c801..91bba6ac6 100644 --- a/tests/Unit/Authentication/JWT/JWTManagerTest.php +++ b/tests/Unit/Authentication/JWT/JWTManagerTest.php @@ -16,6 +16,7 @@ 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\Exceptions\RuntimeException; @@ -33,7 +34,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 @@ -66,11 +70,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, ]; @@ -127,12 +134,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, ]; @@ -330,27 +340,29 @@ public function testParseCanDecodeWithAsymmetricKey(): void $this->assertSame('1', $payload->user_id); } - public function testDisabledRevocationDoesNotReadOrWriteTheStore(): void + 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); - $token = $manager->issue(['sub' => '42']); + // 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', $manager->parse($token)); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('JWT revocation is disabled.'); + $this->assertObjectNotHasProperty('jti', $payload); + $this->assertSame('42', $payload->sub); + $this->expectException(InvalidTokenException::class); + $this->expectExceptionMessage(lang('Auth.invalidJWT')); $manager->revokeToken($token); } - public function testEnabledIssuanceGeneratesDistinctIdentifiersAndPreservesExplicitValues(): void + public function testIssuanceGeneratesDistinctIdentifiersAndPreservesExplicitValues(): void { - config('AuthJWT')->revocationEnabled = true; - $manager = $this->createJWTManager(); - $user = fake(UserModel::class, ['id' => 42], false); + $manager = $this->createJWTManager(); + $user = fake(UserModel::class, ['id' => 42], false); $first = $this->decodeJWT($manager->issue(['sub' => '42']), 'payload'); $second = $this->decodeJWT($manager->generateToken($user), 'payload'); @@ -364,11 +376,10 @@ public function testEnabledIssuanceGeneratesDistinctIdentifiersAndPreservesExpli public function testRevocationUsesOnlyVerifiedIssuerAndIdentifier(): void { - config('AuthJWT')->revocationEnabled = true; - $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 = $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); @@ -380,8 +391,7 @@ public function testRevocationUsesOnlyVerifiedIssuerAndIdentifier(): void public function testRevocationDoesNotWriteForAnInvalidToken(): void { - config('AuthJWT')->revocationEnabled = true; - $store = $this->createMock(JWTRevocationModel::class); + $store = $this->createMock(JWTRevocationModel::class); $store->expects($this->never())->method('revoke'); $manager = new JWTManager(revocationModel: $store); @@ -392,8 +402,7 @@ public function testRevocationDoesNotWriteForAnInvalidToken(): void public function testParseRejectsRevokedTokenAndAllowsSeparateIssuer(): void { - config('AuthJWT')->revocationEnabled = true; - $store = $this->createMock(JWTRevocationModel::class); + $store = $this->createMock(JWTRevocationModel::class); $store->expects($this->exactly(2))->method('isRevoked') ->willReturnMap([ [hash('sha256', '1:abc'), false], @@ -415,8 +424,7 @@ public function testParseRejectsRevokedTokenAndAllowsSeparateIssuer(): void #[DataProvider('provideParseRejectsInvalidRevocationClaimsBeforeCheckingStorage')] public function testParseRejectsInvalidRevocationClaimsBeforeCheckingStorage(array $claims): void { - config('AuthJWT')->revocationEnabled = true; - $store = $this->createMock(JWTRevocationModel::class); + $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); @@ -435,7 +443,7 @@ public static function provideParseRejectsInvalidRevocationClaimsBeforeCheckingS { $claims = ['iss' => 'issuer', 'jti' => 'identifier', 'exp' => time() + DAY]; - yield 'legacy token lacks jti' => [array_diff_key($claims, ['jti' => true])]; + yield 'explicit null jti' => [['jti' => null] + $claims]; yield 'empty jti' => [['jti' => ''] + $claims]; @@ -447,6 +455,8 @@ public static function provideParseRejectsInvalidRevocationClaimsBeforeCheckingS 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]; @@ -454,9 +464,8 @@ public static function provideParseRejectsInvalidRevocationClaimsBeforeCheckingS public function testManagedExpiryIsStrictEvenWhenDecoderAcceptsTheToken(): void { - config('AuthJWT')->revocationEnabled = true; - $clock = Time::parse('2026-06-13 12:00:00', 'UTC'); - $store = $this->createMock(JWTRevocationModel::class); + $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) [ @@ -480,8 +489,7 @@ public function testManagedExpiryIsStrictEvenWhenDecoderAcceptsTheToken(): void public function testRevocationStoreReadFailureDoesNotAuthenticate(): void { - config('AuthJWT')->revocationEnabled = true; - $store = $this->createMock(JWTRevocationModel::class); + $store = $this->createMock(JWTRevocationModel::class); $store->expects($this->once())->method('isRevoked') ->willThrowException(new DatabaseException('private database detail')); $manager = new JWTManager(revocationModel: $store); @@ -497,10 +505,9 @@ public function testRevocationStoreReadFailureDoesNotAuthenticate(): void public function testExpiryIsRecheckedWhenARevocationRecordCanBePurgedDuringLookup(): void { - config('AuthJWT')->revocationEnabled = true; - $clock = Time::parse('2026-06-13 12:00:00', 'UTC'); - $expiry = $clock->addSeconds(1); - $store = $this->createMock(JWTRevocationModel::class); + $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); @@ -528,8 +535,7 @@ public function testExpiryIsRecheckedWhenARevocationRecordCanBePurgedDuringLooku public function testRevocationStoreWriteFailureIsSanitized(): void { - config('AuthJWT')->revocationEnabled = true; - $store = $this->createMock(JWTRevocationModel::class); + $store = $this->createMock(JWTRevocationModel::class); $store->expects($this->once())->method('revoke') ->willThrowException(new DatabaseException('private database detail')); $manager = new JWTManager(revocationModel: $store); From 86c5e37599620355d8358ea6396483c518faaf09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amel=20Junuzovi=C4=87?= Date: Tue, 24 Nov 2026 13:38:12 +0100 Subject: [PATCH 4/8] refactor(jwt): use the Shield table configuration --- docs/addons/jwt.md | 6 +-- docs/customization/table_names.md | 1 + src/Config/Auth.php | 2 + src/Config/AuthJWT.php | 8 ---- ...26-11-24-000000_create_jwt_revocations.php | 11 ++++- src/Models/JWTRevocationModel.php | 2 +- tests/Unit/JWTRevocationModelTest.php | 45 +++++++++++++++++-- 7 files changed, 57 insertions(+), 18 deletions(-) diff --git a/docs/addons/jwt.md b/docs/addons/jwt.md index 6802fb428..9b05c8b13 100644 --- a/docs/addons/jwt.md +++ b/docs/addons/jwt.md @@ -143,9 +143,9 @@ It means you log all requests. ### Configure JWT Revocation -Shield stores JWT revocations in `auth_jwt_revocations`. Set -`$revocationTable` in **app/Config/AuthJWT.php** before migrating if your -application uses a different table name. +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. 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/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/Config/AuthJWT.php b/src/Config/AuthJWT.php index 872ffd5bf..e44bf6d39 100644 --- a/src/Config/AuthJWT.php +++ b/src/Config/AuthJWT.php @@ -80,14 +80,6 @@ class AuthJWT extends BaseConfig */ public int $timeToLive = HOUR; - /** - * -------------------------------------------------------------------- - * Token Revocation - * -------------------------------------------------------------------- - * The unprefixed revocation table name in the Auth database group. - */ - public string $revocationTable = 'auth_jwt_revocations'; - /** * -------------------------------------------------------------------- * Record Login Attempts 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 index 54a512b9b..25122b912 100644 --- a/src/Database/Migrations/2026-11-24-000000_create_jwt_revocations.php +++ b/src/Database/Migrations/2026-11-24-000000_create_jwt_revocations.php @@ -15,6 +15,7 @@ use CodeIgniter\Database\Forge; use CodeIgniter\Database\Migration; +use CodeIgniter\Shield\Config\Auth; class CreateJWTRevocations extends Migration { @@ -22,11 +23,17 @@ class CreateJWTRevocations extends Migration public function __construct(?Forge $forge = null) { - $this->DBGroup = config('Auth')->DBGroup; + /** @var Auth $authConfig */ + $authConfig = config('Auth'); + + if ($authConfig->DBGroup !== null) { + $this->DBGroup = $authConfig->DBGroup; + } parent::__construct($forge); - $this->table = config('AuthJWT')->revocationTable; + // Older application configs may override the table map without this entry. + $this->table = $authConfig->tables['jwt_revocations'] ?? 'auth_jwt_revocations'; } public function up(): void diff --git a/src/Models/JWTRevocationModel.php b/src/Models/JWTRevocationModel.php index 521f7f49c..742afd4f3 100644 --- a/src/Models/JWTRevocationModel.php +++ b/src/Models/JWTRevocationModel.php @@ -26,7 +26,7 @@ protected function initialize(): void { parent::initialize(); - $this->table = config('AuthJWT')->revocationTable; + $this->table = $this->tables['jwt_revocations'] ?? 'auth_jwt_revocations'; } public function revoke(string $identifier, int $expiresAt): void diff --git a/tests/Unit/JWTRevocationModelTest.php b/tests/Unit/JWTRevocationModelTest.php index 254dbce4a..f5bcd46dc 100644 --- a/tests/Unit/JWTRevocationModelTest.php +++ b/tests/Unit/JWTRevocationModelTest.php @@ -14,6 +14,8 @@ 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; @@ -56,6 +58,42 @@ public function testDuplicateRevocationsKeepTheLaterExpiration(): void $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); @@ -69,20 +107,19 @@ public function testRawTokenIdentifiersAreRejected(): void #[DataProvider('provideDatabaseFailureThrowsWithDebugDisabled')] public function testDatabaseFailureThrowsWithDebugDisabled(Closure $query): void { - $config = config('AuthJWT'); - $table = $config->revocationTable; + $config = config('Auth'); $dbDebug = new ReflectionProperty($this->db, 'DBDebug'); $debugMode = $dbDebug->getValue($this->db); $this->expectException(DatabaseException::class); try { - $config->revocationTable = 'missing_jwt_revocations'; + $config->tables['jwt_revocations'] = 'missing_jwt_revocations'; $dbDebug->setValue($this->db, false); $query(new JWTRevocationModel()); } finally { - $config->revocationTable = $table; + $config->tables = $this->tables; $dbDebug->setValue($this->db, $debugMode); } } From eee1450d70e5c69f1b51a425c35f959a4dc3bae3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amel=20Junuzovi=C4=87?= Date: Tue, 24 Nov 2026 13:56:49 +0100 Subject: [PATCH 5/8] refactor(jwt): preserve failed login token logging --- docs/addons/jwt.md | 8 +++++--- src/Authentication/Authenticators/JWT.php | 3 +-- .../Authenticators/JWTAuthenticatorTest.php | 2 +- tests/Authentication/Filters/JWTFilterTest.php | 3 +-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/addons/jwt.md b/docs/addons/jwt.md index 9b05c8b13..2e5ecd189 100644 --- a/docs/addons/jwt.md +++ b/docs/addons/jwt.md @@ -492,6 +492,8 @@ you don't pass them. Login attempts are recorded in the `auth_token_logins` table, according to the configuration above. -For logged JWT attempts, the `identifier` column stores the SHA-256 digest of -the presented token with a `sha256:` prefix. Requests that omit the token record -an empty identifier if failure logging is enabled. +When a failed login attempt is logged, the raw token value sent is saved in +the `identifier` column. + +When a successful login attempt is logged, the SHA256 hash value of the token +sent is saved in the `identifier` column. diff --git a/src/Authentication/Authenticators/JWT.php b/src/Authentication/Authenticators/JWT.php index c9100eb4a..441872c6f 100644 --- a/src/Authentication/Authenticators/JWT.php +++ b/src/Authentication/Authenticators/JWT.php @@ -82,10 +82,9 @@ public function attempt(array $credentials): Result if (! $result->isOK()) { if ($config->recordLoginAttempt >= Auth::RECORD_LOGIN_ATTEMPT_FAILURE) { // Record a failed login attempt. - $token = $credentials['token'] ?? ''; $this->tokenLoginModel->recordLoginAttempt( self::ID_TYPE_JWT, - $token === '' ? '' : 'sha256:' . hash('sha256', $token), + $credentials['token'] ?? '', false, $ipAddress, $userAgent, diff --git a/tests/Authentication/Authenticators/JWTAuthenticatorTest.php b/tests/Authentication/Authenticators/JWTAuthenticatorTest.php index ade3fe7b9..af0619fa7 100644 --- a/tests/Authentication/Authenticators/JWTAuthenticatorTest.php +++ b/tests/Authentication/Authenticators/JWTAuthenticatorTest.php @@ -202,7 +202,7 @@ public function testAttemptBadSignatureToken(): void // A login attempt should have always been recorded $this->seeInDatabase('auth_token_logins', [ 'id_type' => JWT::ID_TYPE_JWT, - 'identifier' => 'sha256:' . hash('sha256', self::BAD_JWT), + 'identifier' => self::BAD_JWT, 'success' => 0, ]); } diff --git a/tests/Authentication/Filters/JWTFilterTest.php b/tests/Authentication/Filters/JWTFilterTest.php index c09093319..557c4310c 100644 --- a/tests/Authentication/Filters/JWTFilterTest.php +++ b/tests/Authentication/Filters/JWTFilterTest.php @@ -118,9 +118,8 @@ public function testFilterRejectsOnlyTheRevokedToken(): void $this->seeInDatabase('auth_token_logins', [ 'id_type' => JWT::ID_TYPE_JWT, - 'identifier' => 'sha256:' . hash('sha256', $firstToken), + 'identifier' => $firstToken, 'success' => 0, ]); - $this->dontSeeInDatabase('auth_token_logins', ['identifier' => $firstToken]); } } From b092c9ef951a7a37eb2b30d9c2e96650460c54c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amel=20Junuzovi=C4=87?= Date: Tue, 24 Nov 2026 14:49:26 +0100 Subject: [PATCH 6/8] docs(jwt): explain revocation checks and scheduled cleanup --- docs/addons/jwt.md | 48 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/docs/addons/jwt.md b/docs/addons/jwt.md index 2e5ecd189..f2b6366e5 100644 --- a/docs/addons/jwt.md +++ b/docs/addons/jwt.md @@ -157,6 +157,9 @@ 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 @@ -399,14 +402,51 @@ to end browser sessions or revoke refresh tokens. 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. +expiration leeway. Keep the clocks of verifying servers synchronized. + +Expired revocation records remain in the table until the application removes +them. Schedule `JWTManager::purgeExpiredRevocations()` to keep the table from +growing indefinitely. For example, create +**app/Commands/PurgeJWTRevocations.php**. ```php -$removed = service('jwtmanager')->purgeExpiredRevocations(); +purgeExpiredRevocations(); + CLI::write(sprintf('Removed %d expired JWT revocation records.', $removed)); + + return EXIT_SUCCESS; + } +} +``` + +Run the command manually to verify it. + +```console +php spark jwt:purge-revocations ``` -The method returns the number of records removed. +This example crontab entry runs cleanup daily at 03:00. Adjust the application +and PHP paths for your deployment. + +```crontab +0 3 * * * cd /path/to/app && /usr/bin/php spark jwt:purge-revocations +``` ## Method References From 9e5486da394bf8a447bb8fcf66018beff3f2bfb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amel=20Junuzovi=C4=87?= Date: Tue, 24 Nov 2026 14:51:08 +0100 Subject: [PATCH 7/8] docs(jwt): simplify revocation cleanup example --- docs/addons/jwt.md | 45 ++++----------------------------------------- 1 file changed, 4 insertions(+), 41 deletions(-) diff --git a/docs/addons/jwt.md b/docs/addons/jwt.md index f2b6366e5..4ddfd94bf 100644 --- a/docs/addons/jwt.md +++ b/docs/addons/jwt.md @@ -402,51 +402,14 @@ to end browser sessions or revoke refresh tokens. 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. - -Expired revocation records remain in the table until the application removes -them. Schedule `JWTManager::purgeExpiredRevocations()` to keep the table from -growing indefinitely. For example, create -**app/Commands/PurgeJWTRevocations.php**. +expiration leeway. Keep the clocks of verifying servers synchronized, and run +the following from a scheduled application task to remove expired records. ```php -purgeExpiredRevocations(); - CLI::write(sprintf('Removed %d expired JWT revocation records.', $removed)); - - return EXIT_SUCCESS; - } -} +$removed = service('jwtmanager')->purgeExpiredRevocations(); ``` -Run the command manually to verify it. - -```console -php spark jwt:purge-revocations -``` - -This example crontab entry runs cleanup daily at 03:00. Adjust the application -and PHP paths for your deployment. - -```crontab -0 3 * * * cd /path/to/app && /usr/bin/php spark jwt:purge-revocations -``` +The method returns the number of records removed. ## Method References From 3fc026c4993179e18eee33557c9aea37d0034e22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amel=20Junuzovi=C4=87?= Date: Tue, 24 Nov 2026 14:56:22 +0100 Subject: [PATCH 8/8] test(jwt): use a typed user fixture for token issuance --- tests/Unit/Authentication/JWT/JWTManagerTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Unit/Authentication/JWT/JWTManagerTest.php b/tests/Unit/Authentication/JWT/JWTManagerTest.php index 91bba6ac6..84e809190 100644 --- a/tests/Unit/Authentication/JWT/JWTManagerTest.php +++ b/tests/Unit/Authentication/JWT/JWTManagerTest.php @@ -19,6 +19,7 @@ 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; @@ -362,7 +363,7 @@ public function testLegacyTokenWithoutIdentifierParsesWithoutStorageAndCannotBeR public function testIssuanceGeneratesDistinctIdentifiersAndPreservesExplicitValues(): void { $manager = $this->createJWTManager(); - $user = fake(UserModel::class, ['id' => 42], false); + $user = new User(['id' => 42]); $first = $this->decodeJWT($manager->issue(['sub' => '42']), 'payload'); $second = $this->decodeJWT($manager->generateToken($user), 'payload');