Skip to content

Commit

Permalink
Fix tests and improve code coverate
Browse files Browse the repository at this point in the history
  • Loading branch information
alexbilbie committed Apr 10, 2016
1 parent 7a6d9a4 commit 5969082
Show file tree
Hide file tree
Showing 10 changed files with 209 additions and 51 deletions.
1 change: 1 addition & 0 deletions src/Entities/Traits/ClientTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ trait ClientTrait
* Get the client's name.
*
* @return string
* @codeCoverageIgnore
*/
public function getName()
{
Expand Down
2 changes: 2 additions & 0 deletions src/Exception/OAuthServerException.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ public static function invalidCredentials()
* @param $hint
*
* @return static
*
* @codeCoverageIgnore
*/
public static function serverError($hint)
{
Expand Down
1 change: 1 addition & 0 deletions src/Grant/AuthCodeGrant.php
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ public function completeAuthorizationRequest(AuthorizationRequest $authorization
]
)
);
$redirectPayload['state'] = $authorizationRequest->getState();

$response = new RedirectResponse();
$response->setRedirectUri(
Expand Down
1 change: 1 addition & 0 deletions src/RequestEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public function __construct($name, ServerRequestInterface $request)

/**
* @return ServerRequestInterface
* @codeCoverageIgnore
*/
public function getRequest()
{
Expand Down
8 changes: 8 additions & 0 deletions tests/CryptTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,12 @@ public function testBadPublicKey()
$this->cryptStub->setPublicKey(new CryptKey(__DIR__ . '/Stubs/private.key'));
$this->cryptStub->doDecrypt('');
}

/**
* @expectedException \LogicException
*/
public function testNonExistentKey()
{
new CryptKey('foo/bar');
}
}
25 changes: 25 additions & 0 deletions tests/Grant/AbstractGrantTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use League\OAuth2\Server\Repositories\ClientRepositoryInterface;
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
use LeagueTests\Stubs\AccessTokenEntity;
use LeagueTests\Stubs\AuthCodeEntity;
use LeagueTests\Stubs\ClientEntity;
Expand Down Expand Up @@ -402,4 +403,28 @@ public function testGenerateUniqueIdentifier()

$this->assertTrue(is_string($method->invoke($grantMock)));
}

public function testCanRespondToAuthorizationRequest()
{
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$this->assertFalse($grantMock->canRespondToAuthorizationRequest(new ServerRequest()));
}

/**
* @expectedException \LogicException
*/
public function testValidateAuthorizationRequest()
{
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->validateAuthorizationRequest(new ServerRequest());
}

/**
* @expectedException \LogicException
*/
public function testCompleteAuthorizationRequest()
{
$grantMock = $this->getMockForAbstractClass(AbstractGrant::class);
$grantMock->completeAuthorizationRequest(new AuthorizationRequest());
}
}
1 change: 0 additions & 1 deletion tests/Grant/AuthCodeGrantTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
use LeagueTests\Stubs\ScopeEntity;
use LeagueTests\Stubs\StubResponseType;
use LeagueTests\Stubs\UserEntity;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;

Expand Down
21 changes: 20 additions & 1 deletion tests/Middleware/AuthenticationServerMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace LeagueTests\Middleware;

use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\ClientCredentialsGrant;
use League\OAuth2\Server\Middleware\AuthenticationServerMiddleware;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
Expand Down Expand Up @@ -36,7 +37,7 @@ public function testValidResponse()
new StubResponseType()
);

$server->enableGrantType(new ClientCredentialsGrant(), new \DateInterval('PT1M'));
$server->enableGrantType(new ClientCredentialsGrant());

$_POST['grant_type'] = 'client_credentials';
$_POST['client_id'] = 'foo';
Expand Down Expand Up @@ -89,4 +90,22 @@ function () {

$this->assertEquals(401, $response->getStatusCode());
}

public function testOAuthErrorResponseRedirectUri()
{
$exception = OAuthServerException::invalidScope('test', 'http://foo/bar');
$response = $exception->generateHttpResponse(new Response());

$this->assertEquals(302, $response->getStatusCode());
$this->assertEquals('http://foo/bar?error=invalid_scope&message=The+requested+scope+is+invalid%2C+unknown%2C+or+malformed&hint=Check+the+%60test%60+scope', $response->getHeader('location')[0]);
}

public function testOAuthErrorResponseRedirectUriFragment()
{
$exception = OAuthServerException::invalidScope('test', 'http://foo/bar');
$response = $exception->generateHttpResponse(new Response(), true);

$this->assertEquals(302, $response->getStatusCode());
$this->assertEquals('http://foo/bar#error=invalid_scope&message=The+requested+scope+is+invalid%2C+unknown%2C+or+malformed&hint=Check+the+%60test%60+scope', $response->getHeader('location')[0]);
}
}
41 changes: 41 additions & 0 deletions tests/Middleware/ResourceServerMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,47 @@ function () {
$this->assertEquals(200, $response->getStatusCode());
}

public function testValidResponseExpiredToken()
{
$clientRepository = $this->getMock(ClientRepositoryInterface::class);

$server = new Server(
$clientRepository,
$this->getMock(AccessTokenRepositoryInterface::class),
$this->getMock(ScopeRepositoryInterface::class),
'file://' . __DIR__ . '/../Stubs/private.key',
'file://' . __DIR__ . '/../Stubs/public.key',
new StubResponseType()
);

$client = new ClientEntity();
$client->setIdentifier('clientName');

$accessToken = new AccessTokenEntity();
$accessToken->setIdentifier('test');
$accessToken->setUserIdentifier(123);
$accessToken->setExpiryDateTime((new \DateTime())->sub(new \DateInterval('PT1H')));
$accessToken->setClient($client);

$token = $accessToken->convertToJWT(new CryptKey('file://' . __DIR__ . '/../Stubs/private.key'));

$request = new ServerRequest();
$request = $request->withHeader('authorization', sprintf('Bearer %s', $token));

$middleware = new ResourceServerMiddleware($server);
$response = $middleware->__invoke(
$request,
new Response(),
function () {
$this->assertEquals('test', func_get_args()[0]->getAttribute('oauth_access_token_id'));

return func_get_args()[1];
}
);

$this->assertEquals(401, $response->getStatusCode());
}

public function testErrorResponse()
{
$clientRepository = $this->getMock(ClientRepositoryInterface::class);
Expand Down
159 changes: 110 additions & 49 deletions tests/ServerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace LeagueTests;

use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\AuthCodeGrant;
use League\OAuth2\Server\Grant\ClientCredentialsGrant;
Expand All @@ -11,6 +12,7 @@
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
use League\OAuth2\Server\Repositories\ScopeRepositoryInterface;
use League\OAuth2\Server\Repositories\UserRepositoryInterface;
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
use League\OAuth2\Server\ResponseTypes\BearerTokenResponse;
use League\OAuth2\Server\Server;
use LeagueTests\Stubs\AccessTokenEntity;
Expand All @@ -20,6 +22,7 @@
use LeagueTests\Stubs\UserEntity;
use Psr\Http\Message\ResponseInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\ServerRequestFactory;

class ServerTest extends \PHPUnit_Framework_TestCase
Expand Down Expand Up @@ -74,58 +77,45 @@ public function testRespondToRequest()
$this->assertEquals(200, $response->getStatusCode());
}

public function testRespondToRequestPsrResponse()
public function testGetResponseType()
{
$client = new ClientEntity();
$client->setIdentifier('foo');
$client->setIdentifier('http://bar.com');

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

$scopeRepositoryMock = $this->getMockBuilder(ScopeRepositoryInterface::class)->getMock();
$scopeRepositoryMock->method('finalizeScopes')->willReturnArgument(0);

$server = new Server(
$clientRepository,
$this->getMock(AccessTokenRepositoryInterface::class),
$scopeRepositoryMock,
$this->getMock(ScopeRepositoryInterface::class),
'file://' . __DIR__ . '/Stubs/private.key',
'file://' . __DIR__ . '/Stubs/public.key',
new StubResponseType()
'file://' . __DIR__ . '/Stubs/public.key'
);

$userRepository = $this->getMock(UserRepositoryInterface::class);
$userRepository->method('getUserEntityByUserCredentials')->willReturn(new UserEntity());
$abstractGrantReflection = new \ReflectionClass($server);
$method = $abstractGrantReflection->getMethod('getResponseType');
$method->setAccessible(true);

$authCodeRepoMock = $this->getMock(AuthCodeRepositoryInterface::class);
$authCodeRepoMock->expects($this->once())->method('getNewAuthCode')->willReturn(new AuthCodeEntity());
$this->assertTrue($method->invoke($server) instanceof BearerTokenResponse);
}

$server->enableGrantType(
new AuthCodeGrant(
$authCodeRepoMock,
$this->getMock(RefreshTokenRepositoryInterface::class),
$userRepository,
new \DateInterval('PT1H')
),
new \DateInterval('PT1M')
public function testValidateAuthenticatedRequest()
{
$clientRepository = $this->getMock(ClientRepositoryInterface::class);

$server = new Server(
$clientRepository,
$this->getMock(AccessTokenRepositoryInterface::class),
$this->getMock(ScopeRepositoryInterface::class),
'file://' . __DIR__ . '/Stubs/private.key',
'file://' . __DIR__ . '/Stubs/public.key'
);

$_SERVER['HTTP_HOST'] = 'http://auth.com';
$_SERVER['REQUEST_URI'] = '/auth';
$_GET['response_type'] = 'code';
$_GET['client_id'] = $client->getIdentifier();
$_GET['redirect_uri'] = $client->getRedirectUri();
$_POST['action'] = 'approve';
$_POST['username'] = 'user';
$_POST['password'] = 'pass';
$response = $server->respondToAccessTokenRequest(ServerRequestFactory::fromGlobals(), new Response);
$this->assertTrue($response instanceof ResponseInterface);
$this->assertEquals(302, $response->getStatusCode());
$this->assertTrue(strstr($response->getHeaderLine('location'), 'code=') !== false);
try {
$server->validateAuthenticatedRequest(ServerRequestFactory::fromGlobals());
} catch (OAuthServerException $e) {
$this->assertEquals('Missing "Authorization" header', $e->getHint());
}
}

public function testGetResponseType()
public function testCompleteAuthorizationRequest()
{
$clientRepository = $this->getMock(ClientRepositoryInterface::class);

Expand All @@ -137,29 +127,100 @@ public function testGetResponseType()
'file://' . __DIR__ . '/Stubs/public.key'
);

$abstractGrantReflection = new \ReflectionClass($server);
$method = $abstractGrantReflection->getMethod('getResponseType');
$method->setAccessible(true);
$authCodeRepository = $this->getMockBuilder(AuthCodeRepositoryInterface::class)->getMock();
$authCodeRepository->method('getNewAuthCode')->willReturn(new AuthCodeEntity());

$this->assertTrue($method->invoke($server) instanceof BearerTokenResponse);
$grant = new AuthCodeGrant(
$authCodeRepository,
$this->getMock(RefreshTokenRepositoryInterface::class),
$this->getMock(UserRepositoryInterface::class),
new \DateInterval('PT10M')
);

$grant->setPrivateKey(new CryptKey('file://' . __DIR__ . '/Stubs/private.key'));
$grant->setPublicKey(new CryptKey('file://' . __DIR__ . '/Stubs/public.key'));

$server->enableGrantType($grant);

$authRequest = new AuthorizationRequest();
$authRequest->setAuthorizationApproved(true);
$authRequest->setClient(new ClientEntity());
$authRequest->setGrantTypeId('authorization_code');
$authRequest->setUser(new UserEntity());

$this->assertTrue(
$server->completeAuthorizationRequest($authRequest, new Response) instanceof ResponseInterface
);
}

public function testValidateRequest()
public function testValidateAuthorizationRequest()
{
$clientRepository = $this->getMock(ClientRepositoryInterface::class);
$client = new ClientEntity();
$clientRepositoryMock = $this->getMockBuilder(ClientRepositoryInterface::class)->getMock();
$clientRepositoryMock->method('getClientEntity')->willReturn($client);

$grant = new AuthCodeGrant(
$this->getMock(AuthCodeRepositoryInterface::class),
$this->getMock(RefreshTokenRepositoryInterface::class),
$this->getMock(UserRepositoryInterface::class),
new \DateInterval('PT10M')
);
$grant->setClientRepository($clientRepositoryMock);

$server = new Server(
$clientRepository,
$clientRepositoryMock,
$this->getMock(AccessTokenRepositoryInterface::class),
$this->getMock(ScopeRepositoryInterface::class),
'file://' . __DIR__ . '/Stubs/private.key',
'file://' . __DIR__ . '/Stubs/public.key'
);
$server->enableGrantType($grant);

$request = new ServerRequest(
[],
[],
null,
null,
'php://input',
$headers = [],
$cookies = [],
$queryParams = [
'response_type' => 'code',
'client_id' => 'foo',
]
);

try {
$server->validateAuthenticatedRequest(ServerRequestFactory::fromGlobals());
} catch (OAuthServerException $e) {
$this->assertEquals('Missing "Authorization" header', $e->getHint());
}
$this->assertTrue($server->validateAuthorizationRequest($request) instanceof AuthorizationRequest);
}

/**
* @expectedException \League\OAuth2\Server\Exception\OAuthServerException
* @expectedExceptionCode 2
*/
public function testValidateAuthorizationRequestUnregistered()
{
$server = new Server(
$this->getMock(ClientRepositoryInterface::class),
$this->getMock(AccessTokenRepositoryInterface::class),
$this->getMock(ScopeRepositoryInterface::class),
'file://' . __DIR__ . '/Stubs/private.key',
'file://' . __DIR__ . '/Stubs/public.key'
);

$request = new ServerRequest(
[],
[],
null,
null,
'php://input',
$headers = [],
$cookies = [],
$queryParams = [
'response_type' => 'code',
'client_id' => 'foo',
]
);

$server->validateAuthorizationRequest($request);
}
}

0 comments on commit 5969082

Please sign in to comment.