Skip to content
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
16 changes: 15 additions & 1 deletion .github/workflows/php-cs-fixer.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,15 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Checkout branch
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
uses: actions/checkout@v6
with:
ref: ${{ github.head_ref || github.ref_name }}

- name: Checkout pull request merge ref
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository
uses: actions/checkout@v6

- name: Setup PHP
uses: shivammathur/setup-php@v2
Expand All @@ -34,9 +42,15 @@ jobs:
composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist

- name: Run PHP CS Fixer
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
run: ./vendor/bin/php-cs-fixer fix --allow-risky=yes

- name: Check PHP CS Fixer
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository
run: ./vendor/bin/php-cs-fixer fix --allow-risky=yes --dry-run --diff

- name: Commit Changes
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: 🪄 Code Style Fixes
Expand Down
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",
"guzzlehttp/promises": "^1.5 || ^2.0",
"guzzlehttp/psr7": "^2.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
19 changes: 12 additions & 7 deletions 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 @@ -81,15 +82,17 @@ public function getAuthorizationUrl(array $scopes = [], ?string $state = null, s
*/
public function getAccessToken(string $code, ?string $state = null, ?string $expectedState = null, bool $returnResponse = false, ?callable $requestModifier = null): OAuthAuthenticator|Response
{
$this->oauthConfig()->validate();
$oauthConfig = $this->oauthConfig();

$oauthConfig->validate();

if (! empty($state) && ! empty($expectedState) && $state !== $expectedState) {
throw new InvalidStateException;
}

$request = $this->resolveAccessTokenRequest($code, $this->oauthConfig());
$request = $this->resolveAccessTokenRequest($code, $oauthConfig);

$request = $this->oauthConfig()->invokeRequestModifier($request);
$request = $oauthConfig->invokeRequestModifier($request);

if (is_callable($requestModifier)) {
$requestModifier($request);
Expand Down Expand Up @@ -117,7 +120,9 @@ public function getAccessToken(string $code, ?string $state = null, ?string $exp
*/
public function refreshAccessToken(OAuthAuthenticator|string $refreshToken, bool $returnResponse = false, ?callable $requestModifier = null): OAuthAuthenticator|Response
{
$this->oauthConfig()->validate();
$oauthConfig = $this->oauthConfig();

$oauthConfig->validate();

if ($refreshToken instanceof OAuthAuthenticator) {
if ($refreshToken->isNotRefreshable()) {
Expand All @@ -127,9 +132,9 @@ public function refreshAccessToken(OAuthAuthenticator|string $refreshToken, bool
$refreshToken = $refreshToken->getRefreshToken();
}

$request = $this->resolveRefreshTokenRequest($this->oauthConfig(), $refreshToken);
$request = $this->resolveRefreshTokenRequest($oauthConfig, $refreshToken);

$request = $this->oauthConfig()->invokeRequestModifier($request);
$request = $oauthConfig->invokeRequestModifier($request);

if (is_callable($requestModifier)) {
$requestModifier($request);
Expand Down Expand Up @@ -159,7 +164,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
11 changes: 7 additions & 4 deletions 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 @@ -32,11 +33,13 @@ trait ClientCredentialsGrant
*/
public function getAccessToken(array $scopes = [], string $scopeSeparator = ' ', bool $returnResponse = false, ?callable $requestModifier = null): OAuthAuthenticator|Response
{
$this->oauthConfig()->validate(withRedirectUrl: false);
$oauthConfig = $this->oauthConfig();

$request = $this->resolveAccessTokenRequest($this->oauthConfig(), $scopes, $scopeSeparator);
$oauthConfig->validate(withRedirectUrl: false);

$request = $this->oauthConfig()->invokeRequestModifier($request);
$request = $this->resolveAccessTokenRequest($oauthConfig, $scopes, $scopeSeparator);

$request = $oauthConfig->invokeRequestModifier($request);

if (is_callable($requestModifier)) {
$requestModifier($request);
Expand Down Expand Up @@ -64,7 +67,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
Loading
Loading