From df40f8fc303cc0fb5b254590dd9b60b04c3bd957 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Sat, 7 Nov 2026 17:31:52 +0100 Subject: [PATCH] Centralize access token verification --- api/components/Tokens/Component.php | 99 ++++++++++++++--- .../Tokens/InvalidTokenException.php | 10 ++ .../Tokens/TokenExpiredException.php | 12 +++ .../Tokens/TokenRevokedException.php | 12 +++ api/components/User/JwtIdentity.php | 63 ++--------- .../authserver/models/RefreshTokenForm.php | 14 +-- .../validators/AccessTokenValidator.php | 20 ++-- api/modules/oauth/models/OauthProcess.php | 20 ++-- .../functional/_steps/AuthserverSteps.php | 14 +++ .../functional/authserver/RefreshCest.php | 15 +++ .../functional/authserver/ValidateCest.php | 14 +++ .../unit/components/Tokens/ComponentTest.php | 100 ++++++++++-------- .../OAuth2/Grants/RefreshTokenGrant.php | 33 ++---- 13 files changed, 259 insertions(+), 167 deletions(-) create mode 100644 api/components/Tokens/InvalidTokenException.php create mode 100644 api/components/Tokens/TokenExpiredException.php create mode 100644 api/components/Tokens/TokenRevokedException.php diff --git a/api/components/Tokens/Component.php b/api/components/Tokens/Component.php index 5b7a853..a69dd53 100644 --- a/api/components/Tokens/Component.php +++ b/api/components/Tokens/Component.php @@ -4,6 +4,9 @@ declare(strict_types=1); namespace api\components\Tokens; use Carbon\Carbon; +use common\models\OauthClient; +use common\models\OauthSession; +use DateTimeImmutable; use Exception; use InvalidArgumentException; use Lcobucci\JWT\Encoding\ChainedFormatter; @@ -18,6 +21,7 @@ use Lcobucci\JWT\Validation\Validator; use ParagonIE\ConstantTime\Base64UrlSafe; use RangeException; use SodiumException; +use Throwable; use Webmozart\Assert\Assert; use yii\base\Component as BaseComponent; @@ -114,22 +118,40 @@ class Component extends BaseComponent { } /** - * @param string $jwt + * The single place where the access tokens are verified: the signature, the lifetime and the revocation. + * The account's state (deleted, banned, etc.) is intentionally not checked here: some endpoints must accept + * the tokens of banned/deleted accounts, so it's the caller's (or RBAC's) responsibility. * - * @return Token - * @throws InvalidArgumentException + * @throws TokenExpiredException + * @throws TokenRevokedException + * @throws InvalidTokenException */ - public function parse(string $jwt): Token { - return (new Parser(new JoseEncoder()))->parse($jwt); - } - - public function verify(Token $token): bool { + public function verifyAccessToken(string $jwt, bool $verifyExpiration = true): UnencryptedToken { try { - $algorithm = $this->getAlgorithmManager()->get($token->headers()->get('alg')); - return (new Validator())->validate($token, new SignedWith($algorithm->getSigner(), $algorithm->getPublicKey())); - } catch (Exception) { - return false; + $token = $this->parse($jwt); + } catch (Throwable $e) { + throw new InvalidTokenException('Cannot parse the token', previous: $e); } + + if (!$token instanceof UnencryptedToken || !$this->verify($token)) { + throw new InvalidTokenException('Invalid signature'); + } + + $now = Carbon::now(); + if ($verifyExpiration && $token->isExpired($now)) { + throw new TokenExpiredException(); + } + + // Unlike the expiration, these are checked always: the revocation relies on the iat claim + if (!$token->hasBeenIssuedBefore($now) || !$token->isMinimumTimeBefore($now)) { + throw new InvalidTokenException('The token cannot be used yet'); + } + + if ($this->isRevoked($token)) { + throw new TokenRevokedException(); + } + + return $token; } public function encryptValue(string $rawValue): string { @@ -183,6 +205,25 @@ class Component extends BaseComponent { ]; } + /** + * @param string $jwt + * + * @return Token + * @throws InvalidArgumentException + */ + private function parse(string $jwt): Token { + return (new Parser(new JoseEncoder()))->parse($jwt); + } + + private function verify(Token $token): bool { + try { + $algorithm = $this->getAlgorithmManager()->get($token->headers()->get('alg')); + return (new Validator())->validate($token, new SignedWith($algorithm->getSigner(), $algorithm->getPublicKey())); + } catch (Exception) { + return false; + } + } + private function getAlgorithmManager(): AlgorithmsManager { if ($this->algorithmManager === null) { $this->algorithmManager = new AlgorithmsManager([ @@ -193,6 +234,40 @@ class Component extends BaseComponent { return $this->algorithmManager; } + private function isRevoked(UnencryptedToken $token): bool { + $reader = new TokenReader($token); + $accountId = $reader->getAccountId(); + // The client_credentials tokens aren't related to any account, so there is no session to check + if ($accountId === null) { + return false; + } + + $clientIds = []; + if ($reader->getMinecraftClientToken() !== null) { + $clientIds[] = OauthClient::UNAUTHORIZED_MINECRAFT_GAME_LAUNCHER; + } + + if ($reader->getClientId() !== null) { + $clientIds[] = $reader->getClientId(); + } + + /** @var DateTimeImmutable $iat */ + $iat = $token->claims()->get(RegisteredClaims::ISSUED_AT); + foreach ($clientIds as $clientId) { + $session = OauthSession::findOne(['account_id' => $accountId, 'client_id' => $clientId]); + // The session is always created when the token is issued, so its absence means that it was revoked + if ($session === null) { + return true; + } + + if ($session->isRevokedForTokenIssuedAt($iat)) { + return true; + } + } + + return false; + } + private function prepareValue(EncryptedValue|string|bool $value): string|bool { if ($value instanceof EncryptedValue) { return $this->encryptValue($value->value); diff --git a/api/components/Tokens/InvalidTokenException.php b/api/components/Tokens/InvalidTokenException.php new file mode 100644 index 0000000..4177e44 --- /dev/null +++ b/api/components/Tokens/InvalidTokenException.php @@ -0,0 +1,10 @@ +tokens->parse($token); - } catch (Exception $e) { - Yii::error($e); - throw new UnauthorizedHttpException('Incorrect token'); - } - - if (!Yii::$app->tokens->verify($parsedToken)) { - throw new UnauthorizedHttpException('Incorrect token'); - } - - $now = Carbon::now(); - if ($parsedToken->isExpired($now)) { - throw new UnauthorizedHttpException('Token expired'); - } - - if (!(new Validator())->validate($parsedToken, new LooseValidAt(FactoryImmutable::getDefaultInstance()))) { - throw new UnauthorizedHttpException('Incorrect token'); - } - - $tokenReader = new TokenReader($parsedToken); - $accountId = $tokenReader->getAccountId(); - if ($accountId !== null) { - /** @var DateTimeImmutable $iat */ - $iat = $parsedToken->claims()->get('iat'); - if ($tokenReader->getMinecraftClientToken() !== null - && self::isRevoked($accountId, OauthClient::UNAUTHORIZED_MINECRAFT_GAME_LAUNCHER, $iat) - ) { - throw new UnauthorizedHttpException('Token has been revoked'); - } - - if ($tokenReader->getClientId() !== null - && self::isRevoked($accountId, $tokenReader->getClientId(), $iat) - ) { - throw new UnauthorizedHttpException('Token has been revoked'); - } + $parsedToken = Yii::$app->tokens->verifyAccessToken($token); + } catch (TokenExpiredException $e) { + throw new UnauthorizedHttpException('Token expired', previous: $e); + } catch (TokenRevokedException $e) { + throw new UnauthorizedHttpException('Token has been revoked', previous: $e); + } catch (InvalidTokenException $e) { + throw new UnauthorizedHttpException('Incorrect token', previous: $e); } return new self($parsedToken); @@ -102,15 +68,6 @@ class JwtIdentity implements IdentityInterface { throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); } - private static function isRevoked(int $accountId, string $clientId, DateTimeInterface $iat): bool { - $session = OauthSession::findOne(['account_id' => $accountId, 'client_id' => $clientId]); - if ($session === null) { - return true; - } - - return $session->isRevokedForTokenIssuedAt($iat); - } - /** @codeCoverageIgnoreEnd */ private function getReader(): TokenReader { if ($this->reader === null) { diff --git a/api/modules/authserver/models/RefreshTokenForm.php b/api/modules/authserver/models/RefreshTokenForm.php index f2b521b..42707c5 100644 --- a/api/modules/authserver/models/RefreshTokenForm.php +++ b/api/modules/authserver/models/RefreshTokenForm.php @@ -8,7 +8,6 @@ use api\models\base\ApiForm; use api\modules\authserver\exceptions\ForbiddenOperationException; use api\modules\authserver\validators\AccessTokenValidator; use api\modules\authserver\validators\RequiredValidator; -use common\components\OAuth2\Repositories\PublicScopeRepository; use common\models\Account; use common\models\OauthClient; use common\models\OauthSession; @@ -47,7 +46,8 @@ class RefreshTokenForm extends ApiForm { */ public function refresh(): AuthenticateData { $this->validate(); - $token = Yii::$app->tokens->parse($this->accessToken); + // The token has already been verified by the validation above, so this is just to read its claims + $token = Yii::$app->tokens->verifyAccessToken($this->accessToken, verifyExpiration: false); $tokenReader = new TokenReader($token); if ($tokenReader->getMinecraftClientToken() !== $this->clientToken) { throw new ForbiddenOperationException('Invalid token.'); @@ -58,18 +58,12 @@ class RefreshTokenForm extends ApiForm { throw new ForbiddenOperationException('Invalid token.'); } - // TODO: This behavior duplicates with the AuthenticationForm. Need to find a way to avoid duplication. /** @var OauthSession|null $minecraftOauthSession */ $minecraftOauthSession = $account->getOauthSessions() ->andWhere(['client_id' => OauthClient::UNAUTHORIZED_MINECRAFT_GAME_LAUNCHER]) ->one(); - if ($minecraftOauthSession === null) { - $minecraftOauthSession = new OauthSession(); - $minecraftOauthSession->account_id = $account->id; - $minecraftOauthSession->client_id = OauthClient::UNAUTHORIZED_MINECRAFT_GAME_LAUNCHER; - $minecraftOauthSession->scopes = [PublicScopeRepository::MINECRAFT_SERVER_SESSION]; - } - + // The token's verification has already ensured that the session exists and isn't revoked + Assert::notNull($minecraftOauthSession); $minecraftOauthSession->last_used_at = time(); Assert::true($minecraftOauthSession->save()); diff --git a/api/modules/authserver/validators/AccessTokenValidator.php b/api/modules/authserver/validators/AccessTokenValidator.php index 99f08ff..a219754 100644 --- a/api/modules/authserver/validators/AccessTokenValidator.php +++ b/api/modules/authserver/validators/AccessTokenValidator.php @@ -3,11 +3,11 @@ declare(strict_types=1); namespace api\modules\authserver\validators; +use api\components\Tokens\InvalidTokenException; +use api\components\Tokens\TokenExpiredException; use api\components\Tokens\TokenReader; use api\modules\authserver\exceptions\ForbiddenOperationException; -use Carbon\Carbon; use common\models\Account; -use Exception; use Yii; use yii\validators\Validator; @@ -26,17 +26,11 @@ class AccessTokenValidator extends Validator { */ protected function validateValue($value): ?array { try { - $token = Yii::$app->tokens->parse($value); - } catch (Exception) { - throw new ForbiddenOperationException(self::INVALID_TOKEN); - } - - if (!Yii::$app->tokens->verify($token)) { - throw new ForbiddenOperationException(self::INVALID_TOKEN); - } - - if ($this->verifyExpiration && $token->isExpired(Carbon::now())) { - throw new ForbiddenOperationException(self::TOKEN_EXPIRED); + $token = Yii::$app->tokens->verifyAccessToken($value, verifyExpiration: $this->verifyExpiration); + } catch (TokenExpiredException $e) { + throw new ForbiddenOperationException(self::TOKEN_EXPIRED, previous: $e); + } catch (InvalidTokenException $e) { + throw new ForbiddenOperationException(self::INVALID_TOKEN, previous: $e); } if ($this->verifyAccount && !$this->validateAccount((new TokenReader($token))->getAccountId())) { diff --git a/api/modules/oauth/models/OauthProcess.php b/api/modules/oauth/models/OauthProcess.php index 76b9fcc..32a372a 100644 --- a/api/modules/oauth/models/OauthProcess.php +++ b/api/modules/oauth/models/OauthProcess.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace api\modules\oauth\models; +use api\components\Tokens\InvalidTokenException; use api\components\Tokens\TokenReader; use common\components\OAuth2\Entities\UserEntity; use common\components\OAuth2\Events\RequestedRefreshToken; @@ -14,8 +15,6 @@ use common\models\OauthClient; use common\models\OauthSession; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Uri; -use InvalidArgumentException; -use Lcobucci\JWT\UnencryptedToken; use League\OAuth2\Server\AuthorizationServer; use League\OAuth2\Server\Entities\ScopeEntityInterface; use League\OAuth2\Server\Exception\OAuthServerException; @@ -276,12 +275,10 @@ final readonly class OauthProcess { */ private function revokeTokensByToken(string $jwt, string $clientId): void { try { - $token = Yii::$app->tokens->parse($jwt); - } catch (InvalidArgumentException) { - return; - } - - if (!$token instanceof UnencryptedToken || !Yii::$app->tokens->verify($token)) { + // The expired tokens still can be revoked. The already revoked token mustn't revoke + // the tokens issued after its revocation, so it's ignored too + $token = Yii::$app->tokens->verifyAccessToken($jwt, verifyExpiration: false); + } catch (InvalidTokenException) { return; } @@ -294,12 +291,9 @@ final readonly class OauthProcess { /** @var \DateTimeImmutable $iat */ $iat = $token->claims()->get('iat'); - /** @var OauthSession|null $session */ $session = OauthSession::findOne(['account_id' => $accountId, 'client_id' => $clientId]); - // The already revoked token mustn't revoke the tokens issued after its revocation - if ($session === null || $session->isRevokedForTokenIssuedAt($iat)) { - return; - } + // The token's verification has already ensured that the session exists and isn't revoked + Assert::notNull($session); // The revocation is checked with the seconds precision, so the token issued in the same second // as the revocation won't be considered as revoked. Ensure that at least the passed token is revoked diff --git a/api/tests/functional/_steps/AuthserverSteps.php b/api/tests/functional/_steps/AuthserverSteps.php index d656417..16f3280 100644 --- a/api/tests/functional/_steps/AuthserverSteps.php +++ b/api/tests/functional/_steps/AuthserverSteps.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace api\tests\functional\_steps; use api\tests\FunctionalTester; +use common\models\OauthClient; +use common\models\OauthSession; use Ramsey\Uuid\Uuid; class AuthserverSteps extends FunctionalTester { @@ -21,4 +23,16 @@ class AuthserverSteps extends FunctionalTester { return [$accessToken, $clientToken]; } + /** + * Emulates the sessions termination (e.g. on password change) for the tokens issued before the current second + */ + public function haveMinecraftSessionsRevoked(int $accountId = 1): void { + // The revocation is compared with the seconds precision, so the tokens issued in the current second + // wouldn't be considered as revoked if the time() value is used + OauthSession::updateAll(['revoked_at' => time() + 1], [ + 'account_id' => $accountId, + 'client_id' => OauthClient::UNAUTHORIZED_MINECRAFT_GAME_LAUNCHER, + ]); + } + } diff --git a/api/tests/functional/authserver/RefreshCest.php b/api/tests/functional/authserver/RefreshCest.php index ad51916..b391bb4 100644 --- a/api/tests/functional/authserver/RefreshCest.php +++ b/api/tests/functional/authserver/RefreshCest.php @@ -46,6 +46,21 @@ class RefreshCest { $this->assertSuccessResponse($I, false); } + public function refreshRevokedToken(AuthserverSteps $I): void { + $I->wantTo('get error on refreshing the revoked accessToken'); + [$accessToken, $clientToken] = $I->amAuthenticated(); + $I->haveMinecraftSessionsRevoked(); + $I->sendPOST('/api/authserver/authentication/refresh', [ + 'accessToken' => $accessToken, + 'clientToken' => $clientToken, + ]); + $I->canSeeResponseCodeIs(401); + $I->canSeeResponseContainsJson([ + 'error' => 'ForbiddenOperationException', + 'errorMessage' => 'Invalid token.', + ]); + } + public function wrongArguments(AuthserverSteps $I): void { $I->wantTo('get error on wrong amount of arguments'); $I->sendPOST('/api/authserver/authentication/refresh', [ diff --git a/api/tests/functional/authserver/ValidateCest.php b/api/tests/functional/authserver/ValidateCest.php index 875fdad..4a3a405 100644 --- a/api/tests/functional/authserver/ValidateCest.php +++ b/api/tests/functional/authserver/ValidateCest.php @@ -57,6 +57,20 @@ class ValidateCest { ]); } + public function revokedAccessToken(AuthserverSteps $I): void { + $I->wantTo('get error on revoked accessToken'); + [$accessToken] = $I->amAuthenticated(); + $I->haveMinecraftSessionsRevoked(); + $I->sendPOST('/api/authserver/authentication/validate', [ + 'accessToken' => $accessToken, + ]); + $I->canSeeResponseCodeIs(401); + $I->canSeeResponseContainsJson([ + 'error' => 'ForbiddenOperationException', + 'errorMessage' => 'Invalid token.', + ]); + } + public function credentialsFromBannedAccount(AuthserverSteps $I): void { $I->wantTo('get error on expired legacy accessToken'); $I->sendPOST('/api/authserver/authentication/validate', [ diff --git a/api/tests/unit/components/Tokens/ComponentTest.php b/api/tests/unit/components/Tokens/ComponentTest.php index 3a4e326..576470e 100644 --- a/api/tests/unit/components/Tokens/ComponentTest.php +++ b/api/tests/unit/components/Tokens/ComponentTest.php @@ -4,13 +4,15 @@ declare(strict_types=1); namespace api\tests\unit\components\Tokens; use api\components\Tokens\Component; +use api\components\Tokens\InvalidTokenException; +use api\components\Tokens\TokenExpiredException; +use api\components\Tokens\TokenRevokedException; use api\tests\unit\TestCase; +use Carbon\Carbon; +use common\tests\fixtures\AccountFixture; +use common\tests\fixtures\OauthClientFixture; +use common\tests\fixtures\OauthSessionFixture; use DateTimeImmutable; -use Generator; -use Lcobucci\JWT\Encoding\JoseEncoder; -use Lcobucci\JWT\Token; -use Lcobucci\JWT\Token\Parser; -use Lcobucci\JWT\UnencryptedToken; use Yii; class ComponentTest extends TestCase { @@ -20,6 +22,14 @@ class ComponentTest extends TestCase { */ private Component $component; + public function _fixtures(): array { + return [ + 'accounts' => AccountFixture::class, + 'oauthClients' => OauthClientFixture::class, + 'oauthSessions' => OauthSessionFixture::class, + ]; + } + public function testCreate(): void { // Run without any arguments $token = $this->component->create(); @@ -61,42 +71,55 @@ class ComponentTest extends TestCase { ], $this->component->getJwks()); } - public function testParse(): void { - /*TODO fix - // Valid token signed with ES256 - $token = $this->component->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.M8Kam9bv0BXui3k7Posq_vc0I95Kb_Tw7L2vPdEPlwsHqh1VJHoWtlQc32_SlsotttL7j6RYbffBkRFX2wDGFQ'); - $this->assertValidParsedToken($token, 'ES256'); + /** + * @param class-string|null $expectedException + * @dataProvider getVerifyAccessTokenCases + */ + public function testVerifyAccessToken(string $jwt, bool $verifyExpiration, ?string $expectedException): void { + Carbon::setTestNow(Carbon::create(2019, 8, 1, 1, 2, 22, 'Europe/Minsk')); + $exception = null; + try { + $token = $this->component->verifyAccessToken($jwt, verifyExpiration: $verifyExpiration); + $this->assertSame($jwt, $token->toString()); + } catch (InvalidTokenException $e) { + $exception = $e; + } - // Valid token signed with ES256, but the signature is invalid - $token = $this->component->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.xxx'); - $this->assertValidParsedToken($token, 'ES256'); - - // Completely invalid token - $this->expectException(CannotDecodeContent::class); - $this->component->parse('How do you tame a horse in Minecraft?');*/ + $this->assertSame($expectedException, $exception === null ? null : $exception::class); } /** - * @dataProvider getVerifyCases + * @return iterable|null}> */ - public function testVerify(Token $token, bool $shouldBeValid): void { - $this->assertSame($shouldBeValid, $this->component->verify($token)); - } + public static function getVerifyAccessTokenCases(): iterable { + $valid = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.4Oidvuo4spvUf9hkpHR72eeqZUh2Zbxh_L8Od3vcgTj--0iOrcOEp6zwmEW6vF7BTHtjz2b3mXce61bqsCjXjQ'; + $expired = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MDMzNDIsImV4cCI6MTU2NDYwNjk0Miwic3ViIjoiZWx5fDEifQ.36cDWyiXRArv-lgK_S5dyC5m_Ddytwkb78tMrxcPcbWEpoeg2VtwPC7zr6NI0cd0CuLw6InC2hZ9Ey95SSOsHw'; + $iatFromFuture = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTc3NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ._6hj6XUSmSLibgT9ZE1Pokf4oI9r-d6tEc1z2J-fBlr1710Qiso5yNcXqb3Z_xy7Qtemyq8jOlOZA8DvmkVBrg'; + $revokedByOauthClient = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudF9pbmZvLG1pbmVjcmFmdF9zZXJ2ZXJfc2Vzc2lvbiIsImlhdCI6MTU2NDYxMDUwMCwic3ViIjoiZWx5fDEiLCJjbGllbnRfaWQiOiJ0bGF1bmNoZXIifQ.qmiPOjI8jGAQdP5LoAVHO8L75Ly7fRcrTB_iYsUgQ4azgsPnLEhvG7dUnQ9utEd3RK5swDpaZ0bXf90vRbvnmg'; + $revokedMinecraft = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoibWluZWNyYWZ0X3NlcnZlcl9zZXNzaW9uIiwiZWx5LWNsaWVudC10b2tlbiI6IllBTVhneTBBcEI5Z2dUX1VYNjNJaTdKcGtNd2ZwTmxaaE8yVVVEeEZ3YTFmZ2g4dksyN0RtV25vN2xqbk1pWWJwQ1VuS09YVnR2V1YtVVg1dWRQVVFsLU4xY3BBZlJBX2EtZW1BZyIsImlhdCI6MTU2NDYxMDUwMCwic3ViIjoiZWx5fDEifQ.LtE9cQJ4z5dGVkDZl50M2HZH6kOYHgGz2RIycS_lzU9YLhosQ3ux7i2KI7qGI7BNuxO5zJ1OkxF2r9Qc240EpA'; + $invalidSignature = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ2MTA1NDIsImV4cCI6MTU2NDYxNDE0Miwic3ViIjoiZWx5fDEifQ.yth31f2PyhUkYSfBlizzUXWIgOvxxk8gNP-js0z8g1OT5rig40FPTIkgsZRctAwAAlj6QoIWW7-hxLTcSb2vmw'; - public static function getVerifyCases(): Generator { - $parser = new Parser(new JoseEncoder()); - yield 'ES256' => [ - $parser->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.M8Kam9bv0BXui3k7Posq_vc0I95Kb_Tw7L2vPdEPlwsHqh1VJHoWtlQc32_SlsotttL7j6RYbffBkRFX2wDGFQ'), - true, - ]; - /* TODO fix yield 'ES256 with an invalid signature' => [ - $parser->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.xxx'), + yield 'valid' => [$valid, true, null]; + yield 'expired' => [$expired, true, TokenExpiredException::class]; + yield 'expired without expiration verification' => [$expired, false, null]; + yield 'iat from future' => [$iatFromFuture, true, InvalidTokenException::class]; + yield 'iat from future without expiration verification' => [$iatFromFuture, false, InvalidTokenException::class]; + yield 'revoked by oauth client' => [$revokedByOauthClient, true, TokenRevokedException::class]; + yield 'revoked by unauthorized minecraft launcher' => [$revokedMinecraft, true, TokenRevokedException::class]; + yield 'revoked by unauthorized minecraft launcher without expiration verification' => [$revokedMinecraft, false, TokenRevokedException::class]; + yield 'invalid signature' => [$invalidSignature, true, InvalidTokenException::class]; + yield 'empty token' => ['', true, InvalidTokenException::class]; + yield 'not a jwt' => ['How do you tame a horse in Minecraft?', true, InvalidTokenException::class]; + yield 'malformed signature' => [ + 'eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.xxx', false, + InvalidTokenException::class, ]; - yield 'RS256 (unsupported)' => [ - $parser->parse('eyJhbGciOiJSUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.t3c68OMaoWWXxNFuz6SW-RfNmCOwAagyPSedbzJ1K3gR3bY5C8PRP6IEyE-OQvAcSFQcake0brsa4caXAmVlU0c3jQxpjk0bl4fBMd-InpGCoo42G89lgAY-dqWeJqokRORCpUL5Mzptbm5fNDlCrnNhI_6EmQygL3WXh1uorCbcxxO-Lb2Nr7Sge7GV0t24-I61I7ErrFL2ZC9ybSi6V8pdhFZlfO6MSUM0ASyRN994sVmcQEZHDiQFP7zj79zoAFamfYe8JBFAGtC-p4LeVYjrw052VahNXyRuGLxW7y1gX-znpyx0T-7lgKSWVxhJ6k3qt5qT33utdC76w1vihEdYinpEE3VbTMN01bxAFpyDbK11R49FCwCKStPjw_wdoLZChx_zob95yVU6IUCJwPYVc4SBtrAPV0uVe3mL3Gzgtr6MkhJAF3diFevTLGfnOOCAWwhdjVs10VWqcajBwvfFlm_Yw5MYZnetEECqumqFEr_u6CdRxtx0gCiPReDG8XwYHt0EqEw-LoRqxGWp5zqfud7f0DWv6cXlLbnKsB8XQh8EqnKblvNCFilXJIgfknCZ34PAob1pUkXO1geMLw4b8NUnKta1D3ad3AxGW5CEmOjWzEhzMOxIgnouU2ZVtWFDrPVs12Q4494BxTvGKXrG2cT6TK18-XY26DllglY'), + yield 'unsupported algorithm' => [ + 'eyJhbGciOiJSUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.t3c68OMaoWWXxNFuz6SW-RfNmCOwAagyPSedbzJ1K3gR3bY5C8PRP6IEyE-OQvAcSFQcake0brsa4caXAmVlU0c3jQxpjk0bl4fBMd-InpGCoo42G89lgAY-dqWeJqokRORCpUL5Mzptbm5fNDlCrnNhI_6EmQygL3WXh1uorCbcxxO-Lb2Nr7Sge7GV0t24-I61I7ErrFL2ZC9ybSi6V8pdhFZlfO6MSUM0ASyRN994sVmcQEZHDiQFP7zj79zoAFamfYe8JBFAGtC-p4LeVYjrw052VahNXyRuGLxW7y1gX-znpyx0T-7lgKSWVxhJ6k3qt5qT33utdC76w1vihEdYinpEE3VbTMN01bxAFpyDbK11R49FCwCKStPjw_wdoLZChx_zob95yVU6IUCJwPYVc4SBtrAPV0uVe3mL3Gzgtr6MkhJAF3diFevTLGfnOOCAWwhdjVs10VWqcajBwvfFlm_Yw5MYZnetEECqumqFEr_u6CdRxtx0gCiPReDG8XwYHt0EqEw-LoRqxGWp5zqfud7f0DWv6cXlLbnKsB8XQh8EqnKblvNCFilXJIgfknCZ34PAob1pUkXO1geMLw4b8NUnKta1D3ad3AxGW5CEmOjWzEhzMOxIgnouU2ZVtWFDrPVs12Q4494BxTvGKXrG2cT6TK18-XY26DllglY', false, - ];*/ + InvalidTokenException::class, + ]; } protected function _setUp(): void { @@ -104,16 +127,9 @@ class ComponentTest extends TestCase { $this->component = Yii::$app->tokens; } - /** - * @phpstan-ignore method.unused (will become used once tests be fixed) - */ - private function assertValidParsedToken(UnencryptedToken $token, string $expectedAlg): void { - $this->assertSame($expectedAlg, $token->headers()->get('alg')); - $this->assertSame(1564527476, $token->claims()->get('iat')->getTimestamp()); - $this->assertSame(1564531076, $token->claims()->get('exp')->getTimestamp()); - $this->assertSame('ely|1', $token->claims()->get('sub')); - $this->assertSame(3069592, (int)$token->claims()->get('jti')); - $this->assertSame('accounts_web_user', $token->claims()->get('ely-scopes')); + protected function _tearDown(): void { + Carbon::setTestNow(); + parent::_tearDown(); } } diff --git a/common/components/OAuth2/Grants/RefreshTokenGrant.php b/common/components/OAuth2/Grants/RefreshTokenGrant.php index 1278873..e9e64b3 100644 --- a/common/components/OAuth2/Grants/RefreshTokenGrant.php +++ b/common/components/OAuth2/Grants/RefreshTokenGrant.php @@ -3,16 +3,14 @@ declare(strict_types=1); namespace common\components\OAuth2\Grants; +use api\components\Tokens\InvalidTokenException; +use api\components\Tokens\TokenExpiredException; use api\components\Tokens\TokenReader; -use Carbon\FactoryImmutable; +use api\components\Tokens\TokenRevokedException; use common\components\OAuth2\CryptTrait; use common\components\OAuth2\Repositories\PublicScopeRepository; use common\components\OAuth2\ScopesMapper; use common\models\OauthSession; -use DateTimeImmutable; -use InvalidArgumentException; -use Lcobucci\JWT\Validation\Constraint\LooseValidAt; -use Lcobucci\JWT\Validation\Validator; use League\OAuth2\Server\Entities\AccessTokenEntityInterface; use League\OAuth2\Server\Entities\RefreshTokenEntityInterface; use League\OAuth2\Server\Exception\OAuthServerException; @@ -107,19 +105,15 @@ final class RefreshTokenGrant extends BaseRefreshTokenGrant { */ private function validateAccessToken(string $jwt, string $clientId): array { try { - $token = Yii::$app->tokens->parse($jwt); - } catch (InvalidArgumentException $e) { + $token = Yii::$app->tokens->verifyAccessToken($jwt); + } catch (TokenExpiredException $e) { + throw OAuthServerException::invalidRefreshToken('Token has expired', $e); + } catch (TokenRevokedException $e) { + throw OAuthServerException::invalidRefreshToken('Token has been revoked', $e); + } catch (InvalidTokenException $e) { throw OAuthServerException::invalidRefreshToken('Cannot decrypt the refresh token', $e); } - if (!Yii::$app->tokens->verify($token)) { - throw OAuthServerException::invalidRefreshToken('Cannot decrypt the refresh token'); - } - - if (!(new Validator())->validate($token, new LooseValidAt(FactoryImmutable::getDefaultInstance()))) { - throw OAuthServerException::invalidRefreshToken('Token has expired'); - } - $reader = new TokenReader($token); $tokenClientId = $reader->getClientId(); $accountId = $reader->getAccountId(); @@ -137,15 +131,6 @@ final class RefreshTokenGrant extends BaseRefreshTokenGrant { throw OAuthServerException::invalidRefreshToken('Token is not a refresh token'); } - /** @var DateTimeImmutable $iat */ - $iat = $token->claims()->get('iat'); - /** @var OauthSession|null $session */ - $session = OauthSession::findOne(['account_id' => $accountId, 'client_id' => $clientId]); - // Session is always created when the user grants access, so its absence means that it was revoked - if ($session === null || $session->isRevokedForTokenIssuedAt($iat)) { - throw OAuthServerException::invalidRefreshToken('Token has been revoked'); - } - return [ 'client_id' => $tokenClientId, 'refresh_token_id' => '', // This value used only to invalidate old token