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

decouple unique identifier generation #987

Open
wants to merge 5 commits into
base: master
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
30 changes: 23 additions & 7 deletions src/AuthorizationServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use League\Event\EmitterAwareTrait;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\GrantTypeInterface;
use League\OAuth2\Server\IdentifierGenerator\IdentifierGenerator;
use League\OAuth2\Server\IdentifierGenerator\IdentifierGeneratorInterface;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
Expand Down Expand Up @@ -79,23 +81,30 @@ class AuthorizationServer implements EmitterAwareInterface
*/
private $defaultScope = '';

/**
* @var IdentifierGeneratorInterface
*/
private $identifierGenerator;

/**
* New server instance.
*
* @param ClientRepositoryInterface $clientRepository
* @param AccessTokenRepositoryInterface $accessTokenRepository
* @param ScopeRepositoryInterface $scopeRepository
* @param CryptKey|string $privateKey
* @param string|Key $encryptionKey
* @param null|ResponseTypeInterface $responseType
* @param ClientRepositoryInterface $clientRepository
* @param AccessTokenRepositoryInterface $accessTokenRepository
* @param ScopeRepositoryInterface $scopeRepository
* @param CryptKey|string $privateKey
* @param string|Key $encryptionKey
* @param null|ResponseTypeInterface $responseType
* @param null|IdentifierGeneratorInterface $identifierGenerator
*/
public function __construct(
ClientRepositoryInterface $clientRepository,
AccessTokenRepositoryInterface $accessTokenRepository,
ScopeRepositoryInterface $scopeRepository,
$privateKey,
$encryptionKey,
ResponseTypeInterface $responseType = null
ResponseTypeInterface $responseType = null,
IdentifierGeneratorInterface $identifierGenerator = null
) {
$this->clientRepository = $clientRepository;
$this->accessTokenRepository = $accessTokenRepository;
Expand All @@ -115,6 +124,12 @@ public function __construct(
}

$this->responseType = $responseType;

if ($identifierGenerator === null) {
$identifierGenerator = new IdentifierGenerator();
}

$this->identifierGenerator = $identifierGenerator;
}

/**
Expand All @@ -136,6 +151,7 @@ public function enableGrantType(GrantTypeInterface $grantType, DateInterval $acc
$grantType->setPrivateKey($this->privateKey);
$grantType->setEmitter($this->getEmitter());
$grantType->setEncryptionKey($this->encryptionKey);
$grantType->setIdentifierGenerator($this->identifierGenerator);

$this->enabledGrantTypes[$grantType->getIdentifier()] = $grantType;
$this->grantTypeAccessTokenTTL[$grantType->getIdentifier()] = $accessTokenTTL;
Expand Down
48 changes: 17 additions & 31 deletions src/Grant/AbstractGrant.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@

use DateInterval;
use DateTime;
use Error;
use Exception;
use League\Event\EmitterAwareTrait;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\CryptTrait;
Expand All @@ -24,6 +22,7 @@
use League\OAuth2\Server\Entities\ScopeEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
use League\OAuth2\Server\IdentifierGenerator\IdentifierGeneratorInterface;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
Expand All @@ -34,7 +33,6 @@
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
use LogicException;
use Psr\Http\Message\ServerRequestInterface;
use TypeError;

/**
* Abstract grant class.
Expand Down Expand Up @@ -92,6 +90,11 @@ abstract class AbstractGrant implements GrantTypeInterface
*/
protected $defaultScope;

/**
* @var IdentifierGeneratorInterface
*/
protected $identifierGenerator;

/**
* @param ClientRepositoryInterface $clientRepository
*/
Expand Down Expand Up @@ -166,6 +169,14 @@ public function setDefaultScope($scope)
$this->defaultScope = $scope;
}

/**
* @param IdentifierGeneratorInterface $identifierGenerator
*/
public function setIdentifierGenerator(IdentifierGeneratorInterface $identifierGenerator)
{
$this->identifierGenerator = $identifierGenerator;
}

/**
* Validate the client.
*
Expand Down Expand Up @@ -403,7 +414,7 @@ protected function issueAccessToken(
}

while ($maxGenerationAttempts-- > 0) {
$accessToken->setIdentifier($this->generateUniqueIdentifier());
$accessToken->setIdentifier($this->identifierGenerator->generateUniqueIdentifier());
try {
$this->accessTokenRepository->persistNewAccessToken($accessToken);

Expand Down Expand Up @@ -453,7 +464,7 @@ protected function issueAuthCode(
}

while ($maxGenerationAttempts-- > 0) {
$authCode->setIdentifier($this->generateUniqueIdentifier());
$authCode->setIdentifier($this->identifierGenerator->generateUniqueIdentifier());
try {
$this->authCodeRepository->persistNewAuthCode($authCode);

Expand Down Expand Up @@ -483,7 +494,7 @@ protected function issueRefreshToken(AccessTokenEntityInterface $accessToken)
$refreshToken->setAccessToken($accessToken);

while ($maxGenerationAttempts-- > 0) {
$refreshToken->setIdentifier($this->generateUniqueIdentifier());
$refreshToken->setIdentifier($this->identifierGenerator->generateUniqueIdentifier());
try {
$this->refreshTokenRepository->persistNewRefreshToken($refreshToken);

Expand All @@ -496,31 +507,6 @@ protected function issueRefreshToken(AccessTokenEntityInterface $accessToken)
}
}

/**
* Generate a new unique identifier.
*
* @param int $length
*
* @throws OAuthServerException
*
* @return string
*/
protected function generateUniqueIdentifier($length = 40)
{
try {
return bin2hex(random_bytes($length));
// @codeCoverageIgnoreStart
} catch (TypeError $e) {
throw OAuthServerException::serverError('An unexpected error has occurred', $e);
} catch (Error $e) {
throw OAuthServerException::serverError('An unexpected error has occurred', $e);
} catch (Exception $e) {
// If you get this message, the CSPRNG failed hard.
throw OAuthServerException::serverError('Could not generate a random string', $e);
}
// @codeCoverageIgnoreEnd
}

/**
* {@inheritdoc}
*/
Expand Down
8 changes: 8 additions & 0 deletions src/Grant/GrantTypeInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Defuse\Crypto\Key;
use League\Event\EmitterAwareInterface;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\IdentifierGenerator\IdentifierGeneratorInterface;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
Expand Down Expand Up @@ -141,4 +142,11 @@ public function setPrivateKey(CryptKey $privateKey);
* @param string|Key|null $key
*/
public function setEncryptionKey($key = null);

/**
* Set the identifier generator
*
* @param IdentifierGeneratorInterface $identifierGenerator
*/
public function setIdentifierGenerator(IdentifierGeneratorInterface $identifierGenerator);
}
30 changes: 30 additions & 0 deletions src/IdentifierGenerator/IdentifierGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php declare(strict_types=1);

namespace League\OAuth2\Server\IdentifierGenerator;

use Error;
use Exception;
use League\OAuth2\Server\Exception\OAuthServerException;
use TypeError;

class IdentifierGenerator implements IdentifierGeneratorInterface
{
/**
* {@inheritdoc}
*/
public function generateUniqueIdentifier($length = 40)
{
try {
return bin2hex(random_bytes($length));
// @codeCoverageIgnoreStart
} catch (TypeError $e) {
throw OAuthServerException::serverError('An unexpected error has occurred', $e);
} catch (Error $e) {
throw OAuthServerException::serverError('An unexpected error has occurred', $e);
} catch (Exception $e) {
// If you get this message, the CSPRNG failed hard.
throw OAuthServerException::serverError('Could not generate a random string', $e);
}
// @codeCoverageIgnoreEnd
}
}
15 changes: 15 additions & 0 deletions src/IdentifierGenerator/IdentifierGeneratorInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php declare(strict_types=1);

namespace League\OAuth2\Server\IdentifierGenerator;

use League\OAuth2\Server\Exception\OAuthServerException;

interface IdentifierGeneratorInterface
{
/**
* Generate a new unique identifier.
*
* @throws OAuthServerException
*/
public function generateUniqueIdentifier();
}
24 changes: 13 additions & 11 deletions tests/Grant/AbstractGrantTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use League\OAuth2\Server\Entities\AuthCodeEntityInterface;
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
use League\OAuth2\Server\Grant\AbstractGrant;
use League\OAuth2\Server\IdentifierGenerator\IdentifierGeneratorInterface;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface;
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
Expand Down Expand Up @@ -330,10 +331,14 @@ public function testIssueRefreshToken()
->method('getNewRefreshToken')
->willReturn(new RefreshTokenEntity());

$identifierGeneratorMock = $this->getMockBuilder(IdentifierGeneratorInterface::class)->getMock();
$identifierGeneratorMock->expects($this->once())->method('generateUniqueIdentifier')->willReturn(uniqid());

/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setRefreshTokenTTL(new \DateInterval('PT1M'));
$grantMock->setRefreshTokenRepository($refreshTokenRepoMock);
$grantMock->setIdentifierGenerator($identifierGeneratorMock);

$abstractGrantReflection = new \ReflectionClass($grantMock);
$issueRefreshTokenMethod = $abstractGrantReflection->getMethod('issueRefreshToken');
Expand All @@ -351,9 +356,13 @@ public function testIssueAccessToken()
$accessTokenRepoMock = $this->getMockBuilder(AccessTokenRepositoryInterface::class)->getMock();
$accessTokenRepoMock->method('getNewToken')->willReturn(new AccessTokenEntity());

$identifierGeneratorMock = $this->getMockBuilder(IdentifierGeneratorInterface::class)->getMock();
$identifierGeneratorMock->expects($this->once())->method('generateUniqueIdentifier')->willReturn(uniqid());

/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setAccessTokenRepository($accessTokenRepoMock);
$grantMock->setIdentifierGenerator($identifierGeneratorMock);

$abstractGrantReflection = new \ReflectionClass($grantMock);
$issueAccessTokenMethod = $abstractGrantReflection->getMethod('issueAccessToken');
Expand All @@ -375,9 +384,13 @@ public function testIssueAuthCode()
$authCodeRepoMock = $this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock();
$authCodeRepoMock->expects($this->once())->method('getNewAuthCode')->willReturn(new AuthCodeEntity());

$identifierGeneratorMock = $this->getMockBuilder(IdentifierGeneratorInterface::class)->getMock();
$identifierGeneratorMock->expects($this->once())->method('generateUniqueIdentifier')->willReturn(uniqid());

/** @var AbstractGrant $grantMock */
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->setAuthCodeRepository($authCodeRepoMock);
$grantMock->setIdentifierGenerator($identifierGeneratorMock);

$abstractGrantReflection = new \ReflectionClass($grantMock);
$issueAuthCodeMethod = $abstractGrantReflection->getMethod('issueAuthCode');
Expand Down Expand Up @@ -460,17 +473,6 @@ public function testValidateScopesBadScope()
$grantMock->validateScopes('basic ');
}

public function testGenerateUniqueIdentifier()
{
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);

$abstractGrantReflection = new \ReflectionClass($grantMock);
$method = $abstractGrantReflection->getMethod('generateUniqueIdentifier');
$method->setAccessible(true);

$this->assertInternalType('string', $method->invoke($grantMock));
}

public function testCanRespondToAuthorizationRequest()
{
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
Expand Down
Loading