Skip to content

Commit

Permalink
Use and apply beste/php-cs-fixer-config:^3.1
Browse files Browse the repository at this point in the history
  • Loading branch information
jeromegamez committed Jul 26, 2024
1 parent 8ecc3a2 commit 61a6d74
Show file tree
Hide file tree
Showing 12 changed files with 85 additions and 63 deletions.
25 changes: 6 additions & 19 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,10 @@

declare(strict_types=1);

$finder = PhpCsFixer\Finder::create()->in(__DIR__);
use Beste\PhpCsFixer\Config;

return (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setRules([
'@PER-CS2.0' => true,
'final_class' => true,
'no_unused_imports' => true,
'ordered_imports' => [
'imports_order' => [
'class',
'function',
'const',
],
'sort_algorithm' => 'alpha',
],
'php_unit_internal_class' => true,
'php_unit_test_class_requires_covers' => true,
])
->setFinder($finder);
$config = Config\Factory::fromRuleSet(new Config\RuleSet\Php81());

$config->getFinder()->in(__DIR__);

return $config;
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"require": {
"php": "~8.1.0 || ~8.2.0 || ~8.3.0",
"azjezz/psl": "^2.9",
"beste/in-memory-cache": "^1.0",
"beste/in-memory-cache": "^1.2",
"lcobucci/jwt": "^5.2",
"php-http/discovery": "^1.19.2",
"psr/cache": "^2.0 || ^3.0",
Expand All @@ -23,6 +23,7 @@
},
"require-dev": {
"beste/clock": "^3.0",
"beste/php-cs-fixer-config": "^3.1",
"friendsofphp/php-cs-fixer": "^3.45.0",
"google/auth": "^1.33",
"nyholm/psr7": "^1.8.1",
Expand Down
4 changes: 2 additions & 2 deletions src/FirebaseJwtFacade.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ private function idTokenVerifier(): IdTokenVerifier
$this->client,
$this->requestFactory,
$this->cache,
)
),
);
}

Expand Down Expand Up @@ -131,7 +131,7 @@ private function sessionCookieVerifier(): SessionCookieVerifier
$this->client,
$this->requestFactory,
$this->cache,
)
),
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Signer/GooglePublicKeys.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ private function getResponseExpiry(ResponseInterface $response): ?DateInterval
$match = Regex\first_match(
$response->getHeaderLine('Cache-Control'),
'/max-age=(?P<max_age>\d+)/i',
Regex\capture_groups(['max_age'])
Regex\capture_groups(['max_age']),
);

return $match === null ? null : new DateInterval(Str\format('PT%dM', $match['max_age']));
Expand Down
2 changes: 1 addition & 1 deletion tests/Environment/EnvironmentVariablesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function testItAcceptsValidCredentials(): void
Env\set_var(self::ENV_VAR, Json\encode([
'project_id' => $projectId,
'client_email' => $clientEmail,
'private_key' => $privateKey
'private_key' => $privateKey,
]));

$variables = EnvironmentVariables::fromEnvironment(self::ENV_VAR);
Expand Down
10 changes: 6 additions & 4 deletions tests/FirebaseJwtFacadeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ public function testItRejectsAnExpiredIdToken(): void
$customToken = self::customTokenBuilder()
->forUser('uid')
->expiresAfter(new \DateInterval('PT10M'))
->getToken();
->getToken()
;

$idToken = self::customTokenExchanger()->exchangeCustomTokenForIdToken($customToken);

Expand All @@ -131,7 +132,8 @@ public function testItAcceptsAnExpiredIdTokenWithLeeway(): void
$customToken = self::customTokenBuilder()
->forUser('uid')
->expiresAfter(new \DateInterval('PT10M'))
->getToken();
->getToken()
;

$idToken = self::customTokenExchanger()->exchangeCustomTokenForIdToken($customToken);

Expand Down Expand Up @@ -168,7 +170,7 @@ public function testItRejectsAnExpiredSessionCookie(): void
$customToken = self::customTokenBuilder()->forUser('uid')->getToken();
$sessionCookie = self::customTokenExchanger()->exchangeCustomTokenForSessionCookie(
customToken: $customToken,
idTokenExpiresAfter: new \DateInterval('PT10M')
idTokenExpiresAfter: new \DateInterval('PT10M'),
);

$clock = FrozenClock::fromUTC();
Expand All @@ -192,7 +194,7 @@ public function testItAcceptsAnExpiredSessionCookieWithLeeway(): void
$customToken = self::customTokenBuilder()->forUser('uid')->getToken();
$sessionCookie = self::customTokenExchanger()->exchangeCustomTokenForSessionCookie(
customToken: $customToken,
idTokenExpiresAfter: new \DateInterval('PT10M')
idTokenExpiresAfter: new \DateInterval('PT10M'),
);

$facade = new FirebaseJwtFacade(
Expand Down
49 changes: 32 additions & 17 deletions tests/Signer/GooglePublicKeysTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ public function testItHandlesClientExceptions(): void
$this->mockedClient
->method('sendRequest')
->withAnyParameters()
->willThrowException(new $exception(__FUNCTION__));
->willThrowException(new $exception(__FUNCTION__))
;

$this->expectException(KeySetError::class);

Expand All @@ -63,12 +64,14 @@ public function testItHandlesJsonErrors(): void
{
$keySet = $this->keySetWithMockedClient();
$response = $this->responseFactory->createResponse(code: 200)
->withBody($this->streamFactory->createStream('{'));
->withBody($this->streamFactory->createStream('{'))
;

$this->mockedClient
->method('sendRequest')
->withAnyParameters()
->willReturn($response);
->willReturn($response)
;

$this->expectException(KeySetError::class);

Expand All @@ -79,12 +82,14 @@ public function testItHandlesJsonWithoutAnArrayOfKeys(): void
{
$keySet = $this->keySetWithMockedClient();
$response = $this->responseFactory->createResponse(code: 200)
->withBody($this->streamFactory->createStream('"not an object"'));
->withBody($this->streamFactory->createStream('"not an object"'))
;

$this->mockedClient
->method('sendRequest')
->withAnyParameters()
->willReturn($response);
->willReturn($response)
;

$this->expectException(KeySetError::class);

Expand All @@ -96,12 +101,14 @@ public function testItFindsAKey(): void
{
$keySet = $this->keySetWithMockedClient();
$response = $this->responseFactory->createResponse(code: 200)
->withBody($this->streamFactory->createStream(Json\encode(['foo' => '-----BEGIN CERTIFICATE-----'])));
->withBody($this->streamFactory->createStream(Json\encode(['foo' => '-----BEGIN CERTIFICATE-----'])))
;

$this->mockedClient
->method('sendRequest')
->withAnyParameters()
->willReturn($response);
->willReturn($response)
;

$keySet->findKeyById('foo');
}
Expand All @@ -110,12 +117,14 @@ public function testItDoesNotFindAKey(): void
{
$keySet = $this->keySetWithMockedClient();
$response = $this->responseFactory->createResponse(code: 200)
->withBody($this->streamFactory->createStream(Json\encode(['kid' => 'key'])));
->withBody($this->streamFactory->createStream(Json\encode(['kid' => 'key'])))
;

$this->mockedClient
->method('sendRequest')
->withAnyParameters()
->willReturn($response);
->willReturn($response)
;

$this->expectException(KeyNotFound::class);
$keySet->findKeyById('bar');
Expand All @@ -126,12 +135,14 @@ public function testItHandlesUnsuccessfulResponses(): void
$keySet = $this->keySetWithMockedClient();

$response = $this->responseFactory->createResponse(code: 500)
->withBody($this->streamFactory->createStream('Error'));
->withBody($this->streamFactory->createStream('Error'))
;

$this->mockedClient
->method('sendRequest')
->withAnyParameters()
->willReturn($response);
->willReturn($response)
;

$this->expectException(KeySetError::class);
$keySet->findKeyById('foo');
Expand All @@ -143,13 +154,15 @@ public function testItReturnsACachedKey(): void

$response = $this->responseFactory->createResponse(code: 200)
->withBody($this->streamFactory->createStream(Json\encode(['kid' => 'key'])))
->withHeader('Cache-Control', 'max-age=60');
->withHeader('Cache-Control', 'max-age=60')
;

$this->mockedClient
->expects(self::once())
->method('sendRequest')
->withAnyParameters()
->willReturn($response);
->willReturn($response)
;

$keySet->findKeyById('kid');
$keySet->findKeyById('kid');
Expand All @@ -161,12 +174,14 @@ public function testItCachesKeysAsLongAsTheResponseSaysTo(): void

$response = $this->responseFactory->createResponse(code: 200)
->withBody($this->streamFactory->createStream(Json\encode(['kid' => 'key'])))
->withHeader('Cache-Control', 'max-age=60');
->withHeader('Cache-Control', 'max-age=60')
;

$this->mockedClient
->method('sendRequest')
->withAnyParameters()
->willReturn($response);
->willReturn($response)
;

$keySet->findKeyById('kid');

Expand Down Expand Up @@ -194,11 +209,11 @@ private function keySetWithMockedClient(string $cacheKeyPrefix = 'test'): Google
public static function invalidKeys(): iterable
{
yield "empty key" => [
["" => '-----BEGIN CERTIFICATE-----']
["" => '-----BEGIN CERTIFICATE-----'],
];

yield "unexpected value" => [
["key_id" => 'not a certificate']
["key_id" => 'not a certificate'],
];
}
}
8 changes: 5 additions & 3 deletions tests/Support/TokenExchanger.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ public function exchangeCustomTokenForIdToken(UnencryptedToken $customToken): st
$request = $this->requestFactory
->createRequest('POST', 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken')
->withBody($this->streamFactory->createStream($json))
->withHeader('Accept', 'application/json');
->withHeader('Accept', 'application/json')
;

$response = $this->client->sendRequest($request);
assert($response->getStatusCode() === 200);
Expand Down Expand Up @@ -100,7 +101,8 @@ public function exchangeIdTokenForSessionCookie(Token $idToken, ?string $tenantI
$request = $this->requestFactory
->createRequest('POST', $url)
->withBody($this->streamFactory->createStream($json))
->withHeader('Accept', 'application/json');
->withHeader('Accept', 'application/json')
;

$response = $this->client->sendRequest($request);
assert($response->getStatusCode() === 200);
Expand All @@ -126,7 +128,7 @@ public function exchangeCustomTokenForSessionCookie(UnencryptedToken $customToke
return $this->exchangeIdTokenForSessionCookie(
idToken: $this->parser->parse($idToken),
tenantId: $tenantId,
expiresAfter: $idTokenExpiresAfter
expiresAfter: $idTokenExpiresAfter,
);
}
}
5 changes: 4 additions & 1 deletion tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
use PHPUnit\Framework\TestCase as PHPUnitTestCase;
use Psl\Env;

/**
* @internal
*/
abstract class TestCase extends PHPUnitTestCase
{
private static ?Variables $variables = null;
Expand Down Expand Up @@ -63,7 +66,7 @@ protected static function customTokenExchanger(): TokenExchanger
$client = new Client([
'handler' => $stack,
'http_errors' => false,
'auth' => 'google_auth' // authorize all requests
'auth' => 'google_auth', // authorize all requests
]);
$requestFactory = Psr17FactoryDiscovery::findRequestFactory();
$streamFactory = Psr17FactoryDiscovery::findStreamFactory();
Expand Down
3 changes: 2 additions & 1 deletion tests/Token/CustomTokenBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ public function testItCanOnlyBeUsedAfterTheGivenDuration(): void

$token = $this->builder()
->expiresAfter($expiresAfter)
->getToken();
->getToken()
;

$parsed = $this->parse($token);
$claims = $parsed->claims();
Expand Down
20 changes: 13 additions & 7 deletions tests/Token/SecureIdTokenVerifierTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ public function testItVerifiesAValidIdToken(): void
$customToken = self::customTokenBuilder()->forUser($uid = 'uid')->getToken();

$idToken = self::customTokenExchanger()
->exchangeCustomTokenForIdToken($customToken);
->exchangeCustomTokenForIdToken($customToken)
;

$verified = $this->verifier()->verify($idToken);

Expand All @@ -43,21 +44,24 @@ public function testItVerifiesATenant(): void
$customToken = self::customTokenBuilder()
->forUser('uid')
->forTenant($tenantId)
->getToken();
->getToken()
;

$idToken = self::customTokenExchanger()->exchangeCustomTokenForIdToken($customToken);

$this->verifier()
->withExpectedTenantId($tenantId)
->verify($idToken);
->verify($idToken)
;
}

public function testItRejectsAnExpiredIdToken(): void
{
$customToken = self::customTokenBuilder()
->forUser('uid')
->expiresAfter(new \DateInterval('PT10M'))
->getToken();
->getToken()
;

$idToken = self::customTokenExchanger()->exchangeCustomTokenForIdToken($customToken);

Expand All @@ -79,14 +83,16 @@ public function testItAcceptsAnExpiredIdTokenWithLeeway(): void
$customToken = self::customTokenBuilder($correctClock)

Check failure on line 83 in tests/Token/SecureIdTokenVerifierTest.php

View workflow job for this annotation

GitHub Actions / PHP 8.2

Static method Beste\Firebase\JWT\Tests\TestCase::customTokenBuilder() invoked with 1 parameter, 0 required.

Check failure on line 83 in tests/Token/SecureIdTokenVerifierTest.php

View workflow job for this annotation

GitHub Actions / PHP 8.3

Static method Beste\Firebase\JWT\Tests\TestCase::customTokenBuilder() invoked with 1 parameter, 0 required.
->forUser('uid')
->expiresAfter(new \DateInterval('PT10M'))
->getToken();
->getToken()
;

$idToken = self::customTokenExchanger()->exchangeCustomTokenForIdToken($customToken);

// It is one hour later, but the token expired after 10 minutes, so 50 minutes ago
$this->verifier($futureClock)
->withLeeway(new \DateInterval('PT51M'))
->verify($idToken);
->verify($idToken)
;
}

private function verifier(?ClockInterface $clock = null): SecureIdTokenVerifier
Expand All @@ -101,7 +107,7 @@ private function verifier(?ClockInterface $clock = null): SecureIdTokenVerifier
Psr18ClientDiscovery::find(),
Psr17FactoryDiscovery::findRequestFactory(),
new InMemoryCache($clock),
)
),
);
}
}
Loading

0 comments on commit 61a6d74

Please sign in to comment.