Skip to content
Merged
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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"guzzlehttp/guzzle": "^7.6 || ^8.0",
"guzzlehttp/promises": "^1.5 || ^2.0 || ^3.0",
"guzzlehttp/psr7": "^2.0 || ^3.0",
"psr/clock": "^1.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.1 || ^2.0"
},
Expand Down
31 changes: 31 additions & 0 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

namespace Saloon;

use DateTimeImmutable;
use Saloon\Enums\PipeOrder;
use Saloon\Contracts\Sender;
use Psr\Clock\ClockInterface;
use Saloon\Http\PendingRequest;
use Saloon\Http\Senders\GuzzleSender;
use Saloon\Helpers\MiddlewarePipeline;
Expand Down Expand Up @@ -52,6 +54,11 @@ final class Config
*/
private static bool $preventStrayRequests = false;

/**
* Global clock used by built-in time-aware features.
*/
private static ?ClockInterface $clock = null;

/**
* Write a custom sender resolver
*/
Expand All @@ -70,6 +77,30 @@ public static function getDefaultSender(): Sender
return is_callable($senderResolver) ? $senderResolver() : new self::$defaultSender;
}

/**
* Set the global package clock.
*/
public static function setClock(?ClockInterface $clock): void
{
self::$clock = $clock;
}

/**
* Get the global package clock.
*/
public static function getClock(): ?ClockInterface
{
return self::$clock;
}

/**
* Resolve the current time.
*/
public static function now(): DateTimeImmutable
{
return self::$clock?->now() ?? new DateTimeImmutable;
}

/**
* Update global middleware
*/
Expand Down
3 changes: 2 additions & 1 deletion src/Http/Auth/AccessTokenAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Saloon\Http\Auth;

use Saloon\Config;
use DateTimeImmutable;
use Saloon\Http\PendingRequest;
use Saloon\Contracts\OAuthAuthenticator;
Expand Down Expand Up @@ -38,7 +39,7 @@ public function hasExpired(): bool
return false;
}

return $this->expiresAt->getTimestamp() <= (new DateTimeImmutable)->getTimestamp();
return $this->expiresAt->getTimestamp() <= Config::now()->getTimestamp();
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/Traits/OAuth2/AuthorizationCodeGrant.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Saloon\Traits\OAuth2;

use DateInterval;
use Saloon\Config;
use DateTimeImmutable;
use Saloon\Http\Request;
use Saloon\Http\Response;
Expand Down Expand Up @@ -159,7 +160,7 @@ protected function createOAuthAuthenticatorFromResponse(Response $response, ?str
$expiresAt = null;

if (isset($responseData->expires_in) && is_numeric($responseData->expires_in)) {
$expiresAt = (new DateTimeImmutable)->add(
$expiresAt = Config::now()->add(
DateInterval::createFromDateString((int)$responseData->expires_in . ' seconds')
);
}
Expand Down
3 changes: 2 additions & 1 deletion src/Traits/OAuth2/ClientCredentialsGrant.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Saloon\Traits\OAuth2;

use DateInterval;
use Saloon\Config;
use DateTimeImmutable;
use Saloon\Http\Request;
use Saloon\Http\Response;
Expand Down Expand Up @@ -64,7 +65,7 @@ protected function createOAuthAuthenticatorFromResponse(Response $response): OAu
$expiresAt = null;

if (isset($responseData->expires_in) && is_numeric($responseData->expires_in)) {
$expiresAt = (new DateTimeImmutable)->add(
$expiresAt = Config::now()->add(
DateInterval::createFromDateString((int)$responseData->expires_in . ' seconds')
);
}
Expand Down
40 changes: 40 additions & 0 deletions tests/Feature/Oauth2/AuthCodeFlowConnectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

declare(strict_types=1);

use Saloon\Config;
use Saloon\Http\Request;
use Saloon\Http\Response;
use Saloon\Tests\Helpers\Date;
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use Saloon\Http\OAuth2\GetUserRequest;
use Saloon\Tests\Fixtures\Clock\FixedClock;
use Saloon\Exceptions\InvalidStateException;
use Saloon\Http\OAuth2\GetAccessTokenRequest;
use Saloon\Http\Auth\AccessTokenAuthenticator;
Expand All @@ -22,6 +24,10 @@
use Saloon\Tests\Fixtures\Connectors\CustomResponseOAuth2Connector;
use Saloon\Tests\Fixtures\Requests\OAuth\CustomRefreshTokenRequest;

afterEach(function () {
Config::setClock(null);
});

test('you can get the redirect url from a connector', function () {
$connector = new OAuth2Connector;

Expand Down Expand Up @@ -109,6 +115,40 @@
expect($authenticator->getExpiresAt())->toBeInstanceOf(DateTimeImmutable::class);
});

test('oauth access tokens derive expiry from the global clock', function () {
$now = new DateTimeImmutable('2026-01-01T00:00:00+00:00');
$mockClient = new MockClient([
MockResponse::make(['access_token' => 'access', 'refresh_token' => 'refresh', 'expires_in' => 3600], 200),
]);

Config::setClock(new FixedClock($now));

$connector = new OAuth2Connector;
$connector->withMockClient($mockClient);

$authenticator = $connector->getAccessToken('code');

expect($authenticator->getExpiresAt())->toEqual($now->modify('+3600 seconds'));
});

test('custom oauth authenticators use the global clock for expiry semantics', function () {
$now = new DateTimeImmutable('2026-01-01T00:00:00+00:00');
$mockClient = new MockClient([
MockResponse::make(['access_token' => 'access', 'refresh_token' => 'refresh', 'expires_in' => 3600], 200),
]);

Config::setClock(new FixedClock($now));

$connector = new CustomResponseOAuth2Connector('hello');
$connector->withMockClient($mockClient);

$authenticator = $connector->getAccessToken('code');

expect($authenticator)->toBeInstanceOf(CustomOAuthAuthenticator::class);
expect($authenticator->getExpiresAt())->toEqual($now->modify('+3600 seconds'));
expect($authenticator->hasExpired())->toBeFalse();
});

test('you can tap into the access token request and modify it', function () {
$mockClient = new MockClient([
MockResponse::make(['access_token' => 'access', 'refresh_token' => 'refresh', 'expires_in' => 3600], 200),
Expand Down
22 changes: 22 additions & 0 deletions tests/Feature/Oauth2/ClientCredentialsFlowConnectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

declare(strict_types=1);

use Saloon\Config;
use Saloon\Http\Request;
use Saloon\Http\Response;
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use Saloon\Tests\Fixtures\Clock\FixedClock;
use Saloon\Http\Auth\AccessTokenAuthenticator;
use Saloon\Exceptions\OAuthConfigValidationException;
use Saloon\Tests\Fixtures\Connectors\ClientCredentialsConnector;
Expand All @@ -14,6 +16,10 @@
use Saloon\Tests\Fixtures\Connectors\CustomRequestClientCredentialsConnector;
use Saloon\Tests\Fixtures\Requests\OAuth\CustomClientCredentialsAccessTokenRequest;

afterEach(function () {
Config::setClock(null);
});

test('you can get the authenticator from the connector', function () {
$mockClient = new MockClient([
MockResponse::make(['access_token' => 'access', 'expires_in' => 3600], 200),
Expand All @@ -40,6 +46,22 @@
]);
});

test('client credentials tokens derive expiry from the global clock', function () {
$now = new DateTimeImmutable('2026-01-01T00:00:00+00:00');
$mockClient = new MockClient([
MockResponse::make(['access_token' => 'access', 'expires_in' => 3600], 200),
]);

Config::setClock(new FixedClock($now));

$connector = new ClientCredentialsConnector;
$connector->withMockClient($mockClient);

$authenticator = $connector->getAccessToken();

expect($authenticator->getExpiresAt())->toEqual($now->modify('+3600 seconds'));
});

test('you can get the response instead of the authenticator', function () {
$mockClient = new MockClient([
MockResponse::make(['access_token' => 'access', 'expires_in' => 3600], 200),
Expand Down
27 changes: 27 additions & 0 deletions tests/Fixtures/Clock/FixedClock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace Saloon\Tests\Fixtures\Clock;

use DateTimeImmutable;
use Psr\Clock\ClockInterface;

final class FixedClock implements ClockInterface
{
/**
* Constructor
*/
public function __construct(protected DateTimeImmutable $now)
{
//
}

/**
* Get the current time.
*/
public function now(): DateTimeImmutable
{
return $this->now;
}
}
18 changes: 18 additions & 0 deletions tests/Unit/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use Saloon\Http\Senders\GuzzleSender;
use Saloon\Tests\Fixtures\Clock\FixedClock;
use Saloon\Exceptions\StrayRequestException;
use Saloon\Tests\Fixtures\Senders\ArraySender;
use Saloon\Tests\Fixtures\Requests\UserRequest;
Expand All @@ -16,6 +17,9 @@
afterEach(function () {
Config::clearGlobalMiddleware();
Config::$defaultSender = GuzzleSender::class;
Config::setSenderResolver(null);
Config::setClock(null);
Config::allowStrayRequests();
});

test('the config can specify global middleware', function () {
Expand Down Expand Up @@ -74,6 +78,20 @@
expect($sender)->toBeInstanceOf(GuzzleSender::class);
});

test('you can configure a global clock and resolve now', function () {
$now = new DateTimeImmutable('2026-01-01T00:00:00+00:00');
$clock = new FixedClock($now);

Config::setClock($clock);

expect(Config::getClock())->toBe($clock);
expect(Config::now())->toEqual($now);

Config::setClock(null);

expect(Config::getClock())->toBeNull();
});

test('you can prevent stray api requests', function () {
Config::preventStrayRequests();

Expand Down
17 changes: 17 additions & 0 deletions tests/Unit/Oauth2/AccessTokenAuthenticatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@

declare(strict_types=1);

use Saloon\Config;
use Saloon\Tests\Helpers\Date;
use Saloon\Tests\Fixtures\Clock\FixedClock;
use Saloon\Http\Auth\AccessTokenAuthenticator;

afterEach(function () {
Config::setClock(null);
});

it('can return if it has expired or not', function () {
$accessToken = 'access';
$refreshToken = 'refresh';
Expand Down Expand Up @@ -44,3 +50,14 @@
expect($authenticator->isRefreshable())->toBeTrue();
expect($authenticator->isNotRefreshable())->toBeFalse();
});

test('it can use the global clock for expiry checks', function () {
$expiresAt = new DateTimeImmutable('2026-01-01T01:00:00+00:00');

Config::setClock(new FixedClock(new DateTimeImmutable('2026-01-01T02:00:00+00:00')));

$authenticator = new AccessTokenAuthenticator('access', 'refresh', $expiresAt);

expect($authenticator->hasExpired())->toBeTrue();
expect($authenticator->hasNotExpired())->toBeFalse();
});
Loading