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

Fix including interval in response of device authorization request #1410

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Added
- Support for PHP 8.4 (PR #1454)

### Fixed
- Fixed bug on setting interval visibility of device authorization grant (PR #1410)
hafezdivandari marked this conversation as resolved.
Show resolved Hide resolved

## [9.0.1] - released 2024-10-14
### Fixed
- Auto-generated event emitter is now persisted. Previously, a new emitter was generated every time (PR #1428)
Expand Down
4 changes: 3 additions & 1 deletion examples/src/Repositories/DeviceCodeRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function persistDeviceCode(DeviceCodeEntityInterface $deviceCodeEntity):
/**
* {@inheritdoc}
*/
public function getDeviceCodeEntityByDeviceCode($deviceCode): ?DeviceCodeEntityInterface
public function getDeviceCodeEntityByDeviceCode(string $deviceCode): ?DeviceCodeEntityInterface
{
$clientEntity = new ClientEntity();
$clientEntity->setIdentifier('myawesomeapp');
Expand All @@ -49,6 +49,8 @@ public function getDeviceCodeEntityByDeviceCode($deviceCode): ?DeviceCodeEntityI
$deviceCodeEntity->setIdentifier($deviceCode);
$deviceCodeEntity->setExpiryDateTime(new DateTimeImmutable('now +1 hour'));
$deviceCodeEntity->setClient($clientEntity);
$deviceCodeEntity->setLastPolledAt(new DateTimeImmutable('now -5 second'));
$deviceCodeEntity->setInterval(5);

// The user identifier should be set when the user authenticates on the
// OAuth server, along with whether they approved the request
Expand Down
32 changes: 25 additions & 7 deletions src/Exception/OAuthServerException.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
class OAuthServerException extends Exception
{
/**
* @var array<string, string>
* @var array<string, string|int>
*/
private array $payload;

Expand All @@ -49,7 +49,7 @@ final public function __construct(string $message, int $code, private string $er
/**
* Returns the current payload.
*
* @return array<string, string>
* @return array<string, string|int>
*/
public function getPayload(): array
{
Expand All @@ -59,7 +59,7 @@ public function getPayload(): array
/**
* Updates the current payload.
*
* @param array<string, string> $payload
* @param array<string, string|int> $payload
*/
public function setPayload(array $payload): void
{
Expand Down Expand Up @@ -215,9 +215,9 @@ public static function expiredToken(?string $hint = null, ?Throwable $previous =
return new static($errorMessage, 11, 'expired_token', 400, $hint, null, $previous);
}

public static function authorizationPending(string $hint = '', ?Throwable $previous = null): static
public static function authorizationPending(?int $interval = null, string $hint = '', ?Throwable $previous = null): static
hafezdivandari marked this conversation as resolved.
Show resolved Hide resolved
{
return new static(
$exception = new static(
'The authorization request is still pending as the end user ' .
'hasn\'t yet completed the user interaction steps. The client ' .
'SHOULD repeat the Access Token Request to the token endpoint',
Expand All @@ -228,6 +228,15 @@ public static function authorizationPending(string $hint = '', ?Throwable $previ
null,
$previous
);

if (!is_null($interval)) {
$exception->setPayload([
...$exception->getPayload(),
'interval' => $interval,
]);
}

return $exception;
}

/**
Expand All @@ -236,9 +245,9 @@ public static function authorizationPending(string $hint = '', ?Throwable $previ
*
* @return static
*/
public static function slowDown(string $hint = '', ?Throwable $previous = null): static
public static function slowDown(?int $interval = null, string $hint = '', ?Throwable $previous = null): static
hafezdivandari marked this conversation as resolved.
Show resolved Hide resolved
{
return new static(
$exception = new static(
'The authorization request is still pending and polling should ' .
'continue, but the interval MUST be increased ' .
'by 5 seconds for this and all subsequent requests.',
Expand All @@ -249,6 +258,15 @@ public static function slowDown(string $hint = '', ?Throwable $previous = null):
null,
$previous
);

if (!is_null($interval)) {
$exception->setPayload([
...$exception->getPayload(),
'interval' => $interval,
]);
}

return $exception;
}

/**
Expand Down
47 changes: 31 additions & 16 deletions src/Grant/DeviceCodeGrant.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public function __construct(
RefreshTokenRepositoryInterface $refreshTokenRepository,
private DateInterval $deviceCodeTTL,
string $verificationUri,
private int $retryInterval = 5
private readonly int $defaultInterval = 5
) {
$this->setDeviceCodeRepository($deviceCodeRepository);
$this->setRefreshTokenRepository($refreshTokenRepository);
Expand Down Expand Up @@ -101,6 +101,10 @@ public function respondToDeviceAuthorizationRequest(ServerRequestInterface $requ
$response->includeVerificationUriComplete();
}

if ($this->intervalVisibility === true) {
$response->includeInterval();
}

$response->setDeviceCodeEntity($deviceCodeEntity);

return $response;
Expand Down Expand Up @@ -140,12 +144,28 @@ public function respondToAccessTokenRequest(
$scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
$deviceCodeEntity = $this->validateDeviceCode($request, $client);

$deviceCodeEntity->setLastPolledAt(new DateTimeImmutable());
$this->deviceCodeRepository->persistDeviceCode($deviceCodeEntity);

// If device code has no user associated, respond with pending
// If device code has no user associated, respond with pending or slow down
if (is_null($deviceCodeEntity->getUserIdentifier())) {
throw OAuthServerException::authorizationPending();
$shouldSlowDown = false;

if ($this->deviceCodePolledTooSoon($deviceCodeEntity) === true) {
$deviceCodeEntity->setInterval($deviceCodeEntity->getInterval() + 5);
hafezdivandari marked this conversation as resolved.
Show resolved Hide resolved

$shouldSlowDown = true;
}

$deviceCodeEntity->setLastPolledAt(new DateTimeImmutable());
$this->deviceCodeRepository->persistDeviceCode($deviceCodeEntity);

if ($shouldSlowDown) {
throw OAuthServerException::slowDown(
$this->intervalVisibility ? $deviceCodeEntity->getInterval() : null
);
}

throw OAuthServerException::authorizationPending(
$this->intervalVisibility ? $deviceCodeEntity->getInterval() : null
);
}

if ($deviceCodeEntity->getUserApproved() === false) {
Expand Down Expand Up @@ -206,16 +226,14 @@ protected function validateDeviceCode(ServerRequestInterface $request, ClientEnt
throw OAuthServerException::invalidRequest('device_code', 'Device code was not issued to this client');
}

if ($this->deviceCodePolledTooSoon($deviceCodeEntity->getLastPolledAt()) === true) {
throw OAuthServerException::slowDown();
}

return $deviceCodeEntity;
}

private function deviceCodePolledTooSoon(?DateTimeImmutable $lastPoll): bool
private function deviceCodePolledTooSoon(DeviceCodeEntityInterface $deviceCodeEntity): bool
{
return $lastPoll !== null && $lastPoll->getTimestamp() + $this->retryInterval > time();
$lastPoll = $deviceCodeEntity->getLastPolledAt();

return $lastPoll !== null && $lastPoll->getTimestamp() + $deviceCodeEntity->getInterval() > time();
}

/**
Expand Down Expand Up @@ -259,10 +277,7 @@ protected function issueDeviceCode(
$deviceCode->setExpiryDateTime((new DateTimeImmutable())->add($deviceCodeTTL));
$deviceCode->setClient($client);
$deviceCode->setVerificationUri($verificationUri);

if ($this->getIntervalVisibility() === true) {
$deviceCode->setInterval($this->retryInterval);
}
$deviceCode->setInterval($this->defaultInterval);

foreach ($scopes as $scope) {
$deviceCode->addScope($scope);
Expand Down
2 changes: 1 addition & 1 deletion src/Repositories/DeviceCodeRepositoryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function persistDeviceCode(DeviceCodeEntityInterface $deviceCodeEntity):
* Get a device code entity.
*/
public function getDeviceCodeEntityByDeviceCode(
string $deviceCodeEntity
string $deviceCode
): ?DeviceCodeEntityInterface;

/**
Expand Down
9 changes: 7 additions & 2 deletions src/ResponseTypes/DeviceCodeResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class DeviceCodeResponse extends AbstractResponseType
{
protected DeviceCodeEntityInterface $deviceCodeEntity;
private bool $includeVerificationUriComplete = false;
private const DEFAULT_INTERVAL = 5;
private bool $includeInterval = false;

/**
* {@inheritdoc}
Expand All @@ -45,7 +45,7 @@ public function generateHttpResponse(ResponseInterface $response): ResponseInter
$responseParams['verification_uri_complete'] = $this->deviceCodeEntity->getVerificationUriComplete();
}

if ($this->deviceCodeEntity->getInterval() !== self::DEFAULT_INTERVAL) {
if ($this->includeInterval === true) {
$responseParams['interval'] = $this->deviceCodeEntity->getInterval();
}

Expand Down Expand Up @@ -79,6 +79,11 @@ public function includeVerificationUriComplete(): void
$this->includeVerificationUriComplete = true;
}

public function includeInterval(): void
{
$this->includeInterval = true;
}

/**
* Add custom fields to your Bearer Token response here, then override
* AuthorizationServer::getResponseType() to pull in your version of
Expand Down
45 changes: 45 additions & 0 deletions tests/Grant/DeviceCodeGrantTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,51 @@ public function testSettingDeviceCodeIntervalRate(): void
$this::assertEquals(self::INTERVAL_RATE, $deviceCode->interval);
}

public function testSettingInternalVisibility(): void
{
$client = new ClientEntity();
$client->setIdentifier('foo');

$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);

$deviceCode = new DeviceCodeEntity();

$deviceCodeRepository = $this->getMockBuilder(DeviceCodeRepositoryInterface::class)->getMock();
$deviceCodeRepository->method('getNewDeviceCode')->willReturn($deviceCode);

$scope = new ScopeEntity();
$scope->setIdentifier('basic');
$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('getScopeEntityByIdentifier')->willReturn($scope);

$grant = new DeviceCodeGrant(
$deviceCodeRepository,
$this->getMockBuilder(RefreshTokenRepositoryInterface::class)->getMock(),
new DateInterval('PT10M'),
'http://foo/bar',
);

$grant->setClientRepository($clientRepositoryMock);
$grant->setDefaultScope(self::DEFAULT_SCOPE);
$grant->setScopeRepository($scopeRepositoryMock);
$grant->setIntervalVisibility(true);

$request = (new ServerRequest())->withParsedBody([
'client_id' => 'foo',
'scope' => 'basic',
]);

$deviceCodeResponse = $grant
->respondToDeviceAuthorizationRequest($request)
->generateHttpResponse(new Response());

$deviceCode = json_decode((string) $deviceCodeResponse->getBody());

$this::assertObjectHasProperty('interval', $deviceCode);
$this::assertEquals(5, $deviceCode->interval);
}

public function testIssueAccessDeniedError(): void
{
$client = new ClientEntity();
Expand Down