Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use symfony/clock component when available instead of non-testable time() #1204

Open
wants to merge 3 commits into
base: 2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Command/GenerateTokenCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Lexik\Bundle\JWTAuthenticationBundle\Command;

use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\Clock\Clock;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
Expand Down Expand Up @@ -95,7 +96,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int
if (null !== $input->getOption('ttl') && ((int) $input->getOption('ttl')) == 0) {
$payload['exp'] = 0;
} elseif (null !== $input->getOption('ttl') && ((int) $input->getOption('ttl')) > 0) {
$payload['exp'] = time() + $input->getOption('ttl');
if (class_exists(Clock::class)) {
$now = Clock::get()->now()->getTimestamp();
} else {
$now = time();
}
$payload['exp'] = $now + $input->getOption('ttl');
}

$token = $this->tokenManager->createFromPayload($user, $payload);
Expand Down
8 changes: 7 additions & 1 deletion Security/Http/Cookie/JWTCookieProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Cookie;

use Lexik\Bundle\JWTAuthenticationBundle\Helper\JWTSplitter;
use Symfony\Component\Clock\Clock;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Kernel;

Expand Down Expand Up @@ -62,7 +63,12 @@ public function createCookie(string $jwt, ?string $name = null, $expiresAt = nul
$jwt = $jwtParts->getParts($split ?: $this->defaultSplit);

if (null === $expiresAt) {
$expiresAt = 0 === $this->defaultLifetime ? 0 : (time() + $this->defaultLifetime);
if (class_exists(Clock::class)) {
$now = Clock::get()->now()->getTimestamp();
} else {
$now = time();
}
$expiresAt = 0 === $this->defaultLifetime ? 0 : ($now + $this->defaultLifetime);
}

return Cookie::create(
Expand Down
11 changes: 9 additions & 2 deletions Services/JWSProvider/DefaultJWSProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Lexik\Bundle\JWTAuthenticationBundle\Signature\CreatedJWS;
use Lexik\Bundle\JWTAuthenticationBundle\Signature\LoadedJWS;
use Namshi\JOSE\JWS;
use Symfony\Component\Clock\Clock;

/**
* JWS Provider, Namshi\JOSE library integration.
Expand Down Expand Up @@ -82,13 +83,19 @@ public function __construct(KeyLoaderInterface $keyLoader, $cryptoEngine, $signa
*/
public function create(array $payload, array $header = [])
{
if (class_exists(Clock::class)) {
$now = Clock::get()->now()->getTimestamp();
} else {
$now = time();
}

$header['alg'] = $this->signatureAlgorithm;

$jws = new JWS($header, $this->cryptoEngine);
$claims = ['iat' => time()];
$claims = ['iat' => $now];

if (null !== $this->ttl && !isset($payload['exp'])) {
$claims['exp'] = time() + $this->ttl;
$claims['exp'] = $now + $this->ttl;
}

$jws->setPayload($payload + $claims);
Expand Down
11 changes: 8 additions & 3 deletions Services/JWSProvider/LcobucciJWSProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Lexik\Bundle\JWTAuthenticationBundle\Services\JWSProvider;

use Lcobucci\Clock\Clock;
use Lcobucci\Clock\SystemClock;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Encoding\ChainedFormatter;
Expand Down Expand Up @@ -30,6 +29,8 @@
use Lexik\Bundle\JWTAuthenticationBundle\Services\KeyLoader\RawKeyLoader;
use Lexik\Bundle\JWTAuthenticationBundle\Signature\CreatedJWS;
use Lexik\Bundle\JWTAuthenticationBundle\Signature\LoadedJWS;
use Symfony\Component\Clock\Clock as SymfonyClock;
use Psr\Clock\ClockInterface as Clock;

/**
* @final
Expand Down Expand Up @@ -77,7 +78,11 @@ public function __construct(KeyLoaderInterface $keyLoader, string $cryptoEngine,
throw new \InvalidArgumentException(sprintf('The %s provider supports only "openssl" as crypto engine.', self::class));
}
if (null === $clock) {
$clock = new SystemClock(new \DateTimeZone('UTC'));
if (class_exists(SymfonyClock::class)) {
$clock = SymfonyClock::get();
} else {
$clock = new SystemClock(new \DateTimeZone('UTC'));
}
}

$this->keyLoader = $keyLoader;
Expand All @@ -103,7 +108,7 @@ public function create(array $payload, array $header = [])
$jws = $jws->withHeader($k, $v);
}

$now = time();
$now = $this->clock->now()->getTimestamp();

$issuedAt = $payload['iat'] ?? $now;
unset($payload['iat']);
Expand Down
17 changes: 15 additions & 2 deletions Signature/LoadedJWS.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Lexik\Bundle\JWTAuthenticationBundle\Signature;

use Symfony\Component\Clock\Clock;

/**
* Object representation of a JSON Web Signature loaded from an
* existing JSON Web Token.
Expand Down Expand Up @@ -74,7 +76,13 @@ private function checkExpiration(): void
return;
}

if ($this->clockSkew <= time() - $this->payload['exp']) {
if (class_exists(Clock::class)) {
$now = Clock::get()->now()->getTimestamp();
} else {
$now = time();
}

if ($this->clockSkew <= $now - $this->payload['exp']) {
$this->state = self::EXPIRED;
}
}
Expand All @@ -84,7 +92,12 @@ private function checkExpiration(): void
*/
private function checkIssuedAt()
{
if (isset($this->payload['iat']) && (int) $this->payload['iat'] - $this->clockSkew > time()) {
if (class_exists(Clock::class)) {
$now = Clock::get()->now()->getTimestamp();
} else {
$now = time();
}
if (isset($this->payload['iat']) && (int) $this->payload['iat'] - $this->clockSkew > $now) {
return $this->state = self::INVALID;
}
}
Expand Down
13 changes: 10 additions & 3 deletions Subscriber/AdditionalAccessTokenClaimsAndHeaderSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTCreatedEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Events;
use Symfony\Component\Clock\Clock;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

final class AdditionalAccessTokenClaimsAndHeaderSubscriber implements EventSubscriberInterface
Expand All @@ -29,14 +30,20 @@ public static function getSubscribedEvents(): array

public function addClaims(JWTCreatedEvent $event): void
{
if (class_exists(Clock::class)) {
$now = Clock::get()->now()->getTimestamp();
} else {
$now = time();
}

$claims = [
'jti' => uniqid('', true),
'iat' => time(),
'nbf' => time(),
'iat' => $now,
'nbf' => $now,
];
$data = $event->getData();
if (!array_key_exists('exp', $data) && $this->ttl > 0) {
$claims['exp'] = time() + $this->ttl;
$claims['exp'] = $now + $this->ttl;
}
$event->setData(array_merge($claims, $data));
}
Expand Down
8 changes: 7 additions & 1 deletion Tests/Signature/LoadedJWSTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use Lexik\Bundle\JWTAuthenticationBundle\Tests\ForwardCompatTestCaseTrait;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ClockMock;
use Symfony\Component\Clock\Clock;
use Symfony\Component\Clock\MockClock;

/**
* Tests the CreatedJWS model class.
Expand Down Expand Up @@ -128,7 +130,11 @@ public function testIsNotExpiredDaySavingTransition()
{
// 2020-10-25 00:16:13 UTC+0
$timestamp = 1603584973;
ClockMock::withClockMock($timestamp);
if (class_exists(Clock::class)) {
Clock::set(new MockClock("@$timestamp"));
} else {
ClockMock::withClockMock($timestamp);
}

$dstPayload = [
'username' => 'test',
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@
},
"suggest": {
"gesdinet/jwt-refresh-token-bundle": "Implements a refresh token system over Json Web Tokens in Symfony",
"spomky-labs/lexik-jose-bridge": "Provides a JWT Token encoder with encryption support"
"spomky-labs/lexik-jose-bridge": "Provides a JWT Token encoder with encryption support",
"symfony/clock": "Allow to test JWT with a shared and expectable clock"
},
"autoload": {
"psr-4": {
Expand Down
Loading