Mise à jour des librairies vendor

This commit is contained in:
Caribana
2018-05-01 14:43:32 +02:00
parent b67375ae8e
commit d776be73fc
5211 changed files with 59115 additions and 25863 deletions

View File

@@ -10,18 +10,19 @@ php:
- 5.5
- 5.6
- 7.0
- hhvm
- 7.1
- 7.2
env:
- COMPOSER_CMD="composer install"
- COMPOSER_CMD="composer update --prefer-lowest"
-
- COMPOSER_ARGS="--prefer-lowest"
matrix:
include:
- php: "7.0"
env: RUN_CS_FIXER=true COMPOSER_CMD="composer install"
- php: "7.2"
env: RUN_CS_FIXER=true
before_script:
- $(echo $COMPOSER_CMD)
- composer update $COMPOSER_ARGS
script:
- if [ "${RUN_CS_FIXER}" = "true" ]; then

View File

@@ -1,3 +1,48 @@
## 1.3.0 (06/04/2018)
### Changes
* Fixes usage of deprecated env var for GAE Flex (#189)
* fix - guzzlehttp/psr7 dependency version definition (#190)
* Added SystemV shared memory based CacheItemPool (#191)
## 1.2.1 (24/01/2018)
### Changes
* Fixes array merging bug in Guzzle5HttpHandler (#186)
* Fixes constructor argument bug in Subscriber & Middleware (#184)
## 1.2.0 (6/12/2017)
### Changes
* Adds async method to HTTP handlers (#176)
* Misc bug fixes and improvements (#177, #175, #178)
## 1.1.0 (10/10/2017)
### Changes
* Supports additional claims in JWT tokens (#171)
* Adds makeHttpClient for creating authorized Guzzle clients (#162)
* Misc bug fixes/improvements (#168, #161, #167, #170, #143)
## 1.0.1 (31/07/2017)
### Changes
* Adds support for Firebase 5.0 (#159)
## 1.0.0 (12/06/2017)
### Changes
* Adds hashing and shortening to enforce max key length ([@bshaffer])
* Fix for better PSR-6 compliance - verifies a hit before getting the cache item ([@bshaffer])
* README fixes ([@bshaffer])
* Change authorization header key to lowercase ([@stanley-cheung])
## 0.4.0 (23/04/2015)
### Changes
@@ -5,4 +50,5 @@
* Export callback function to update auth metadata ([@stanley-cheung][])
* Adds an implementation of User Refresh Token auth ([@stanley-cheung][])
[@bshaffer]: https://github.com/bshaffer
[@stanley-cheung]: https://github.com/stanley-cheung

View File

@@ -95,7 +95,7 @@ $stack->push($middleware);
// create the HTTP client
$client = new Client([
'handler' => $stack,
'base_url' => 'https://www.googleapis.com',
'base_uri' => 'https://www.googleapis.com',
'auth' => 'google_auth' // authorize all requests
]);

View File

@@ -7,20 +7,19 @@
"license": "Apache-2.0",
"require": {
"php": ">=5.4",
"firebase/php-jwt": "~2.0|~3.0|~4.0",
"guzzlehttp/guzzle": "~5.3|~6.0",
"guzzlehttp/psr7": "~1.2",
"firebase/php-jwt": "~2.0|~3.0|~4.0|~5.0",
"guzzlehttp/guzzle": "~5.3.1|~6.0",
"guzzlehttp/psr7": "^1.2",
"psr/http-message": "^1.0",
"psr/cache": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "3.7.*",
"friendsofphp/php-cs-fixer": "^1.11"
"guzzlehttp/promises": "0.1.1|^1.3",
"friendsofphp/php-cs-fixer": "^1.11",
"phpunit/phpunit": "^4.8.36|^5.7",
"sebastian/comparator": ">=1.2.3"
},
"autoload": {
"classmap": [
"src/"
],
"psr-4": {
"Google\\Auth\\": "src"
}

View File

@@ -86,7 +86,7 @@ class ApplicationDefaultCredentials
) {
$creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache);
return new AuthTokenSubscriber($creds, $cacheConfig);
return new AuthTokenSubscriber($creds, $httpHandler);
}
/**
@@ -114,7 +114,7 @@ class ApplicationDefaultCredentials
) {
$creds = self::getCredentials($scope, $httpHandler, $cacheConfig, $cache);
return new AuthTokenMiddleware($creds, $cacheConfig);
return new AuthTokenMiddleware($creds, $httpHandler);
}
/**

View File

@@ -134,7 +134,7 @@ final class Item implements CacheItemInterface
} else {
$message = 'Argument 1 passed to %s::expiresAfter() must be an ' .
'instance of DateInterval or of the type integer, %s given';
$error = sprintf($message, get_class($this), gettype($expiration));
$error = sprintf($message, get_class($this), gettype($time));
$this->handleError($error);
}

View File

@@ -51,7 +51,6 @@ final class MemoryCacheItemPool implements CacheItemPoolInterface
$items = [];
foreach ($keys as $key) {
$this->isValidKey($key);
$items[$key] = $this->hasItem($key) ? clone $this->items[$key] : new Item($key);
}
@@ -74,7 +73,7 @@ final class MemoryCacheItemPool implements CacheItemPoolInterface
public function clear()
{
$this->items = [];
$this->deferred = [];
$this->deferredItems = [];
return true;
}

View File

@@ -19,6 +19,8 @@ namespace Google\Auth;
trait CacheTrait
{
private $maxKeyLength = 64;
/**
* Gets the cached value if it is present in the cache when that is
* available.
@@ -35,7 +37,9 @@ trait CacheTrait
}
$cacheItem = $this->cache->getItem($key);
return $cacheItem->get();
if ($cacheItem->isHit()) {
return $cacheItem->get();
}
}
/**
@@ -67,6 +71,13 @@ trait CacheTrait
$key = $this->cacheConfig['prefix'] . $key;
// ensure we do not have illegal characters
return preg_replace('|[^a-zA-Z0-9_\.!]|', '', $key);
$key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $key);
// Hash keys if they exceed $maxKeyLength (defaults to 64)
if ($this->maxKeyLength && strlen($key) > $this->maxKeyLength) {
$key = substr(hash('sha256', $key), 0, $this->maxKeyLength);
}
return $key;
}
}

View File

@@ -69,15 +69,25 @@ class AppIdentityCredentials extends CredentialsLoader
}
/**
* Determines if this an App Engine instance, by accessing the SERVER_SOFTWARE
* environment variable.
* Determines if this an App Engine instance, by accessing the
* SERVER_SOFTWARE environment variable (prod) or the APPENGINE_RUNTIME
* environment variable (dev).
*
* @return true if this an App Engine Instance, false otherwise
*/
public static function onAppEngine()
{
return isset($_SERVER['SERVER_SOFTWARE']) &&
strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false;
$appEngineProduction = isset($_SERVER['SERVER_SOFTWARE']) &&
0 === strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine');
if ($appEngineProduction) {
return true;
}
$appEngineDevAppServer = isset($_SERVER['APPENGINE_RUNTIME']) &&
$_SERVER['APPENGINE_RUNTIME'] == 'php';
if ($appEngineDevAppServer) {
return true;
}
return false;
}
/**

View File

@@ -102,13 +102,13 @@ class GCECredentials extends CredentialsLoader
/**
* Determines if this an App Engine Flexible instance, by accessing the
* GAE_VM environment variable.
* GAE_INSTANCE environment variable.
*
* @return true if this an App Engine Flexible Instance, false otherwise
*/
public static function onAppEngineFlexible()
{
return isset($_SERVER['GAE_VM']) && 'true' === $_SERVER['GAE_VM'];
return substr(getenv('GAE_INSTANCE'), 0, 4) === 'aef-';
}
/**

View File

@@ -30,7 +30,7 @@ abstract class CredentialsLoader implements FetchAuthTokenInterface
const ENV_VAR = 'GOOGLE_APPLICATION_CREDENTIALS';
const WELL_KNOWN_PATH = 'gcloud/application_default_credentials.json';
const NON_WINDOWS_WELL_KNOWN_PATH_BASE = '.config';
const AUTH_METADATA_KEY = 'Authorization';
const AUTH_METADATA_KEY = 'authorization';
/**
* @param string $cause
@@ -106,7 +106,7 @@ abstract class CredentialsLoader implements FetchAuthTokenInterface
/**
* Create a new Credentials instance.
*
* @param string|array scope the scope of the access request, expressed
* @param string|array $scope the scope of the access request, expressed
* either as an Array or as a space-delimited String.
* @param array $jsonKey the JSON credentials.
*
@@ -127,6 +127,53 @@ abstract class CredentialsLoader implements FetchAuthTokenInterface
}
}
/**
* Create an authorized HTTP Client from an instance of FetchAuthTokenInterface.
*
* @param FetchAuthTokenInterface $fetcher is used to fetch the auth token
* @param array $httpClientOptoins (optional) Array of request options to apply.
* @param callable $httpHandler (optional) http client to fetch the token.
* @param callable $tokenCallback (optional) function to be called when a new token is fetched.
*
* @return \GuzzleHttp\Client
*/
public static function makeHttpClient(
FetchAuthTokenInterface $fetcher,
array $httpClientOptions = [],
callable $httpHandler = null,
callable $tokenCallback = null
) {
$version = \GuzzleHttp\ClientInterface::VERSION;
switch ($version[0]) {
case '5':
$client = new \GuzzleHttp\Client($httpClientOptions);
$client->setDefaultOption('auth', 'google_auth');
$subscriber = new Subscriber\AuthTokenSubscriber(
$fetcher,
$httpHandler,
$tokenCallback
);
$client->getEmitter()->attach($subscriber);
return $client;
case '6':
$middleware = new Middleware\AuthTokenMiddleware(
$fetcher,
$httpHandler,
$tokenCallback
);
$stack = \GuzzleHttp\HandlerStack::create();
$stack->push($middleware);
return new \GuzzleHttp\Client([
'handler' => $stack,
'auth' => 'google_auth',
] + $httpClientOptions);
default:
throw new \Exception('Version not supported');
}
}
/**
* export a callback function which updates runtime metadata.
*

View File

@@ -16,7 +16,11 @@
*/
namespace Google\Auth\HttpHandler;
use Exception;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Message\ResponseInterface as Guzzle5ResponseInterface;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\RejectedPromise;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
@@ -46,17 +50,73 @@ class Guzzle5HttpHandler
*/
public function __invoke(RequestInterface $request, array $options = [])
{
$request = $this->client->createRequest(
$response = $this->client->send(
$this->createGuzzle5Request($request, $options)
);
return $this->createPsr7Response($response);
}
/**
* Accepts a PSR-7 request and an array of options and returns a PromiseInterface
*
* @param RequestInterface $request
* @param array $options
*
* @return Promise
*/
public function async(RequestInterface $request, array $options = [])
{
if (!class_exists('GuzzleHttp\Promise\Promise')) {
throw new Exception('Install guzzlehttp/promises to use async with Guzzle 5');
}
$futureResponse = $this->client->send(
$this->createGuzzle5Request(
$request,
['future' => true] + $options
)
);
$promise = new Promise(
function () use ($futureResponse) {
try {
$futureResponse->wait();
} catch (Exception $e) {
// The promise is already delivered when the exception is
// thrown, so don't rethrow it.
}
},
[$futureResponse, 'cancel']
);
$futureResponse->then([$promise, 'resolve'], [$promise, 'reject']);
return $promise->then(
function (Guzzle5ResponseInterface $response) {
// Adapt the Guzzle 5 Response to a PSR-7 Response.
return $this->createPsr7Response($response);
},
function (Exception $e) {
return new RejectedPromise($e);
}
);
}
private function createGuzzle5Request(RequestInterface $request, array $options)
{
return $this->client->createRequest(
$request->getMethod(),
$request->getUri(),
array_merge([
array_merge_recursive([
'headers' => $request->getHeaders(),
'body' => $request->getBody(),
], $options)
);
}
$response = $this->client->send($request);
private function createPsr7Response(Guzzle5ResponseInterface $response)
{
return new Response(
$response->getStatusCode(),
$response->getHeaders() ?: [],

View File

@@ -33,4 +33,17 @@ class Guzzle6HttpHandler
{
return $this->client->send($request, $options);
}
/**
* Accepts a PSR-7 request and an array of options and returns a PromiseInterface
*
* @param RequestInterface $request
* @param array $options
*
* @return \GuzzleHttp\Promise\Promise
*/
public function async(RequestInterface $request, array $options = [])
{
return $this->client->sendAsync($request, $options);
}
}

View File

@@ -29,7 +29,7 @@ use Psr\Http\Message\RequestInterface;
*
* Requests will be accessed with the authorization header:
*
* 'Authorization' 'Bearer <value of auth_token>'
* 'authorization' 'Bearer <value of auth_token>'
*/
class AuthTokenMiddleware
{
@@ -99,7 +99,7 @@ class AuthTokenMiddleware
return $handler($request, $options);
}
$request = $request->withHeader('Authorization', 'Bearer ' . $this->fetchToken());
$request = $request->withHeader('authorization', 'Bearer ' . $this->fetchToken());
return $handler($request, $options);
};

View File

@@ -31,7 +31,7 @@ use Psr\Http\Message\RequestInterface;
*
* Requests will be accessed with the authorization header:
*
* 'Authorization' 'Bearer <value of auth_token>'
* 'authorization' 'Bearer <value of auth_token>'
*/
class ScopedAccessTokenMiddleware
{
@@ -113,7 +113,7 @@ class ScopedAccessTokenMiddleware
* $client = new Client([
* 'handler' => $stack,
* 'base_url' => 'https://www.googleapis.com/taskqueue/v1beta2/projects/',
* 'auth' => 'google_auth' // authorize all requests
* 'auth' => 'scoped' // authorize all requests
* ]);
*
* $res = $client->get('myproject/taskqueues/myqueue');
@@ -130,7 +130,7 @@ class ScopedAccessTokenMiddleware
return $handler($request, $options);
}
$request = $request->withHeader('Authorization', 'Bearer ' . $this->fetchToken());
$request = $request->withHeader('authorization', 'Bearer ' . $this->fetchToken());
return $handler($request, $options);
};

View File

@@ -238,6 +238,12 @@ class OAuth2 implements FetchAuthTokenInterface
*/
private $extensionParams;
/**
* When using the toJwt function, these claims will be added to the JWT
* payload.
*/
private $additionalClaims;
/**
* Create a new OAuthCredentials.
*
@@ -322,6 +328,7 @@ class OAuth2 implements FetchAuthTokenInterface
'signingKey' => null,
'signingAlgorithm' => null,
'scope' => null,
'additionalClaims' => [],
], $config);
$this->setAuthorizationUri($opts['authorizationUri']);
@@ -340,6 +347,7 @@ class OAuth2 implements FetchAuthTokenInterface
$this->setSigningAlgorithm($opts['signingAlgorithm']);
$this->setScope($opts['scope']);
$this->setExtensionParams($opts['extensionParams']);
$this->setAdditionalClaims($opts['additionalClaims']);
$this->updateToken($opts);
}
@@ -413,6 +421,7 @@ class OAuth2 implements FetchAuthTokenInterface
if (!(is_null($this->getSub()))) {
$assertion['sub'] = $this->getSub();
}
$assertion += $this->getAdditionalClaims();
return $this->jwtEncode($assertion, $this->getSigningKey(),
$this->getSigningAlgorithm());
@@ -1212,6 +1221,26 @@ class OAuth2 implements FetchAuthTokenInterface
$this->refreshToken = $refreshToken;
}
/**
* Sets additional claims to be included in the JWT token
*
* @param array $additionalClaims
*/
public function setAdditionalClaims(array $additionalClaims)
{
$this->additionalClaims = $additionalClaims;
}
/**
* Gets the additional claims to be included in the JWT token.
*
* @return array
*/
public function getAdditionalClaims()
{
return $this->additionalClaims;
}
/**
* The expiration of the last received token.
*

View File

@@ -31,7 +31,7 @@ use GuzzleHttp\Event\SubscriberInterface;
*
* Requests will be accessed with the authorization header:
*
* 'Authorization' 'Bearer <value of auth_token>'
* 'authorization' 'Bearer <value of auth_token>'
*/
class AuthTokenSubscriber implements SubscriberInterface
{
@@ -107,7 +107,7 @@ class AuthTokenSubscriber implements SubscriberInterface
// Fetch the auth token.
$auth_tokens = $this->fetcher->fetchAuthToken($this->httpHandler);
if (array_key_exists('access_token', $auth_tokens)) {
$request->setHeader('Authorization', 'Bearer ' . $auth_tokens['access_token']);
$request->setHeader('authorization', 'Bearer ' . $auth_tokens['access_token']);
// notify the callback if applicable
if ($this->tokenCallback) {

View File

@@ -33,7 +33,7 @@ use Psr\Cache\CacheItemPoolInterface;
*
* Requests will be accessed with the authorization header:
*
* 'Authorization' 'Bearer <access token obtained from the closure>'
* 'authorization' 'Bearer <access token obtained from the closure>'
*/
class ScopedAccessTokenSubscriber implements SubscriberInterface
{
@@ -135,7 +135,7 @@ class ScopedAccessTokenSubscriber implements SubscriberInterface
return;
}
$auth_header = 'Bearer ' . $this->fetchToken();
$request->setHeader('Authorization', $auth_header);
$request->setHeader('authorization', $auth_header);
}
/**

View File

@@ -21,8 +21,9 @@ use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\Credentials\GCECredentials;
use Google\Auth\Credentials\ServiceAccountCredentials;
use GuzzleHttp\Psr7;
use PHPUnit\Framework\TestCase;
class ADCGetTest extends \PHPUnit_Framework_TestCase
class ADCGetTest extends TestCase
{
private $originalHome;
@@ -101,7 +102,7 @@ class ADCGetTest extends \PHPUnit_Framework_TestCase
}
}
class ADCGetMiddlewareTest extends \PHPUnit_Framework_TestCase
class ADCGetMiddlewareTest extends TestCase
{
private $originalHome;
@@ -156,6 +157,26 @@ class ADCGetMiddlewareTest extends \PHPUnit_Framework_TestCase
ApplicationDefaultCredentials::getMiddleware('a scope', $httpHandler);
}
public function testWithCacheOptions()
{
$keyFile = __DIR__ . '/fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$httpHandler = getHandler([
buildResponse(200),
]);
$cacheOptions = [];
$cachePool = $this->getMock('Psr\Cache\CacheItemPoolInterface');
$middleware = ApplicationDefaultCredentials::getMiddleware(
'a scope',
$httpHandler,
$cacheOptions,
$cachePool
);
}
public function testSuccedsIfNoDefaultFilesButIsOnGCE()
{
$wantedTokens = [
@@ -196,6 +217,7 @@ class ADCGetCredentialsAppEngineTest extends BaseTest
// removes it if assigned
putenv('HOME=' . $this->originalHome);
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $this->originalServiceAccount);
putenv('GAE_INSTANCE');
}
public function testAppEngineStandard()
@@ -210,7 +232,7 @@ class ADCGetCredentialsAppEngineTest extends BaseTest
public function testAppEngineFlexible()
{
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
$_SERVER['GAE_VM'] = 'true';
putenv('GAE_INSTANCE=aef-default-20180313t154438');
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
]);
@@ -279,6 +301,26 @@ class ADCGetSubscriberTest extends BaseTest
ApplicationDefaultCredentials::getSubscriber('a scope', $httpHandler);
}
public function testWithCacheOptions()
{
$keyFile = __DIR__ . '/fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$httpHandler = getHandler([
buildResponse(200),
]);
$cacheOptions = [];
$cachePool = $this->getMock('Psr\Cache\CacheItemPoolInterface');
$subscriber = ApplicationDefaultCredentials::getSubscriber(
'a scope',
$httpHandler,
$cacheOptions,
$cachePool
);
}
public function testSuccedsIfNoDefaultFilesButIsOnGCE()
{
$wantedTokens = [

View File

@@ -3,8 +3,9 @@
namespace Google\Auth\tests;
use GuzzleHttp\ClientInterface;
use PHPUnit\Framework\TestCase;
abstract class BaseTest extends \PHPUnit_Framework_TestCase
abstract class BaseTest extends TestCase
{
public function onlyGuzzle6()
{

View File

@@ -18,8 +18,9 @@
namespace Google\Auth\Tests;
use Google\Auth\Cache\Item;
use PHPUnit\Framework\TestCase;
class ItemTest extends \PHPUnit_Framework_TestCase
class ItemTest extends TestCase
{
public function getItem($key)
{

View File

@@ -18,9 +18,10 @@
namespace Google\Auth\Tests;
use Google\Auth\Cache\MemoryCacheItemPool;
use PHPUnit\Framework\TestCase;
use Psr\Cache\InvalidArgumentException;
class MemoryCacheItemPoolTest extends \PHPUnit_Framework_TestCase
class MemoryCacheItemPoolTest extends TestCase
{
private $pool;
@@ -159,12 +160,44 @@ class MemoryCacheItemPoolTest extends \PHPUnit_Framework_TestCase
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeys($key)
public function testCheckInvalidKeysOnGetItem($key)
{
$this->pool->getItem($key);
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeysOnGetItems($key)
{
$this->pool->getItems([$key]);
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeysOnHasItem($key)
{
$this->pool->hasItem($key);
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeysOnDeleteItem($key)
{
$this->pool->deleteItem($key);
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeysOnDeleteItems($key)
{
$this->pool->deleteItems([$key]);
}

View File

@@ -18,8 +18,9 @@
namespace Google\Auth\Tests;
use Google\Auth\CacheTrait;
use PHPUnit\Framework\TestCase;
class CacheTraitTest extends \PHPUnit_Framework_TestCase
class CacheTraitTest extends TestCase
{
private $mockFetcher;
private $mockCacheItem;
@@ -44,6 +45,10 @@ class CacheTraitTest extends \PHPUnit_Framework_TestCase
public function testSuccessfullyPullsFromCache()
{
$expectedValue = '1234';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
@@ -61,6 +66,64 @@ class CacheTraitTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($expectedValue, $cachedValue);
}
public function testSuccessfullyPullsFromCacheWithInvalidKey()
{
$key = 'this-key-has-@-illegal-characters';
$expectedKey = 'thiskeyhasillegalcharacters';
$expectedValue = '1234';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($expectedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($expectedKey)
->will($this->returnValue($this->mockCacheItem));
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
'key' => $key,
]);
$cachedValue = $implementation->gCachedValue();
$this->assertEquals($expectedValue, $cachedValue);
}
public function testSuccessfullyPullsFromCacheWithLongKey()
{
$key = 'this-key-is-over-64-characters-and-it-will-still-work'
. '-but-it-will-be-hashed-and-shortened';
$expectedKey = str_replace('-', '', $key);
$expectedKey = substr(hash('sha256', $expectedKey), 0, 64);
$expectedValue = '1234';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($expectedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($expectedKey)
->will($this->returnValue($this->mockCacheItem));
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
'key' => $key
]);
$cachedValue = $implementation->gCachedValue();
$this->assertEquals($expectedValue, $cachedValue);
}
public function testFailsPullFromCacheWithNoCache()
{
$implementation = new CacheTraitImplementation();

View File

@@ -20,8 +20,9 @@ namespace Google\Auth\Tests;
use google\appengine\api\app_identity\AppIdentityService;
// included from tests\mocks\AppIdentityService.php
use Google\Auth\Credentials\AppIdentityCredentials;
use PHPUnit\Framework\TestCase;
class AppIdentityCredentialsOnAppEngineTest extends \PHPUnit_Framework_TestCase
class AppIdentityCredentialsOnAppEngineTest extends TestCase
{
public function testIsFalseByDefault()
{
@@ -33,9 +34,15 @@ class AppIdentityCredentialsOnAppEngineTest extends \PHPUnit_Framework_TestCase
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
$this->assertTrue(AppIdentityCredentials::onAppEngine());
}
public function testIsTrueWhenAppEngineRuntimeIsPhp()
{
$_SERVER['APPENGINE_RUNTIME'] = 'php';
$this->assertTrue(AppIdentityCredentials::onAppEngine());
}
}
class AppIdentityCredentialsGetCacheKeyTest extends \PHPUnit_Framework_TestCase
class AppIdentityCredentialsGetCacheKeyTest extends TestCase
{
public function testShouldBeEmpty()
{
@@ -44,7 +51,7 @@ class AppIdentityCredentialsGetCacheKeyTest extends \PHPUnit_Framework_TestCase
}
}
class AppIdentityCredentialsFetchAuthTokenTest extends \PHPUnit_Framework_TestCase
class AppIdentityCredentialsFetchAuthTokenTest extends TestCase
{
public function testShouldBeEmptyIfNotOnAppEngine()
{

View File

@@ -20,8 +20,9 @@ namespace Google\Auth\Tests;
use Google\Auth\Credentials\GCECredentials;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
class GCECredentialsOnGCETest extends \PHPUnit_Framework_TestCase
class GCECredentialsOnGCETest extends TestCase
{
public function testIsFalseOnClientErrorStatus()
{
@@ -56,21 +57,27 @@ class GCECredentialsOnGCETest extends \PHPUnit_Framework_TestCase
}
}
class GCECredentialsOnAppEngineFlexibleTest extends \PHPUnit_Framework_TestCase
class GCECredentialsOnAppEngineFlexibleTest extends TestCase
{
public function testIsFalseByDefault()
{
$this->assertFalse(GCECredentials::onAppEngineFlexible());
}
public function testIsTrueWhenGaeVmIsTrue()
public function testIsTrueWhenGaeInstanceHasAefPrefix()
{
$_SERVER['GAE_VM'] = 'true';
putenv('GAE_INSTANCE=aef-default-20180313t154438');
$this->assertTrue(GCECredentials::onAppEngineFlexible());
}
protected function tearDown()
{
// removes it if assigned
putenv('GAE_INSTANCE');
}
}
class GCECredentialsGetCacheKeyTest extends \PHPUnit_Framework_TestCase
class GCECredentialsGetCacheKeyTest extends TestCase
{
public function testShouldNotBeEmpty()
{
@@ -79,7 +86,7 @@ class GCECredentialsGetCacheKeyTest extends \PHPUnit_Framework_TestCase
}
}
class GCECredentialsFetchAuthTokenTest extends \PHPUnit_Framework_TestCase
class GCECredentialsFetchAuthTokenTest extends TestCase
{
public function testShouldBeEmptyIfNotOnGCE()
{

View File

@@ -18,8 +18,9 @@
namespace Google\Auth\Tests;
use Google\Auth\Credentials\IAMCredentials;
use PHPUnit\Framework\TestCase;
class IAMConstructorTest extends \PHPUnit_Framework_TestCase
class IAMConstructorTest extends TestCase
{
/**
* @expectedException InvalidArgumentException
@@ -53,7 +54,7 @@ class IAMConstructorTest extends \PHPUnit_Framework_TestCase
}
}
class IAMUpdateMetadataCallbackTest extends \PHPUnit_Framework_TestCase
class IAMUpdateMetadataCallbackTest extends TestCase
{
public function testUpdateMetadataFunc()
{
@@ -65,17 +66,15 @@ class IAMUpdateMetadataCallbackTest extends \PHPUnit_Framework_TestCase
);
$update_metadata = $iam->getUpdateMetadataFunc();
$this->assertTrue(is_callable($update_metadata));
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'));
$this->assertTrue(
isset($actual_metadata[IAMCredentials::SELECTOR_KEY]));
$this->assertArrayHasKey(IAMCredentials::SELECTOR_KEY, $actual_metadata);
$this->assertEquals(
$actual_metadata[IAMCredentials::SELECTOR_KEY],
$selector);
$this->assertTrue(
isset($actual_metadata[IAMCredentials::TOKEN_KEY]));
$this->assertArrayHasKey(IAMCredentials::TOKEN_KEY, $actual_metadata);
$this->assertEquals(
$actual_metadata[IAMCredentials::TOKEN_KEY],
$token);

View File

@@ -23,6 +23,7 @@ use Google\Auth\Credentials\ServiceAccountJwtAccessCredentials;
use Google\Auth\CredentialsLoader;
use Google\Auth\OAuth2;
use GuzzleHttp\Psr7;
use PHPUnit\Framework\TestCase;
// Creates a standard JSON auth object for testing.
function createTestJson()
@@ -36,7 +37,7 @@ function createTestJson()
];
}
class SACGetCacheKeyTest extends \PHPUnit_Framework_TestCase
class SACGetCacheKeyTest extends TestCase
{
public function testShouldBeTheSameAsOAuth2WithTheSameScope()
{
@@ -87,7 +88,7 @@ class SACGetCacheKeyTest extends \PHPUnit_Framework_TestCase
}
}
class SACConstructorTest extends \PHPUnit_Framework_TestCase
class SACConstructorTest extends TestCase
{
/**
* @expectedException InvalidArgumentException
@@ -148,7 +149,7 @@ class SACConstructorTest extends \PHPUnit_Framework_TestCase
}
}
class SACFromEnvTest extends \PHPUnit_Framework_TestCase
class SACFromEnvTest extends TestCase
{
protected function tearDown()
{
@@ -178,7 +179,7 @@ class SACFromEnvTest extends \PHPUnit_Framework_TestCase
}
}
class SACFromWellKnownFileTest extends \PHPUnit_Framework_TestCase
class SACFromWellKnownFileTest extends TestCase
{
private $originalHome;
@@ -211,7 +212,7 @@ class SACFromWellKnownFileTest extends \PHPUnit_Framework_TestCase
}
}
class SACFetchAuthTokenTest extends \PHPUnit_Framework_TestCase
class SACFetchAuthTokenTest extends TestCase
{
private $privateKey;
@@ -293,21 +294,23 @@ class SACFetchAuthTokenTest extends \PHPUnit_Framework_TestCase
$testJson
);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertTrue(is_callable($update_metadata));
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = null,
$httpHandler);
$this->assertTrue(
isset($actual_metadata[CredentialsLoader::AUTH_METADATA_KEY]));
$this->assertArrayHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata
);
$this->assertEquals(
$actual_metadata[CredentialsLoader::AUTH_METADATA_KEY],
array('Bearer ' . $access_token));
}
}
class SACJwtAccessTest extends \PHPUnit_Framework_TestCase
class SACJwtAccessTest extends TestCase
{
private $privateKey;
@@ -382,13 +385,15 @@ class SACJwtAccessTest extends \PHPUnit_Framework_TestCase
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertTrue(is_callable($update_metadata));
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = null);
$this->assertTrue(
!isset($actual_metadata[CredentialsLoader::AUTH_METADATA_KEY]));
$this->assertArrayNotHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata
);
}
public function testUpdateMetadataFunc()
@@ -400,40 +405,44 @@ class SACJwtAccessTest extends \PHPUnit_Framework_TestCase
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertTrue(is_callable($update_metadata));
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = 'https://example.com/service');
$this->assertTrue(
isset($actual_metadata[CredentialsLoader::AUTH_METADATA_KEY]));
$this->assertArrayHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata
);
$authorization = $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY];
$this->assertTrue(is_array($authorization));
$this->assertInternalType('array', $authorization);
$bearer_token = current($authorization);
$this->assertTrue(is_string($bearer_token));
$this->assertTrue(strpos($bearer_token, 'Bearer ') == 0);
$this->assertTrue(strlen($bearer_token) > 30);
$this->assertInternalType('string', $bearer_token);
$this->assertEquals(0, strpos($bearer_token, 'Bearer '));
$this->assertGreaterThan(30, strlen($bearer_token));
$actual_metadata2 = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = 'https://example.com/anotherService');
$this->assertTrue(
isset($actual_metadata2[CredentialsLoader::AUTH_METADATA_KEY]));
$this->assertArrayHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata2
);
$authorization2 = $actual_metadata2[CredentialsLoader::AUTH_METADATA_KEY];
$this->assertTrue(is_array($authorization2));
$this->assertInternalType('array', $authorization2);
$bearer_token2 = current($authorization2);
$this->assertTrue(is_string($bearer_token2));
$this->assertTrue(strpos($bearer_token2, 'Bearer ') == 0);
$this->assertTrue(strlen($bearer_token2) > 30);
$this->assertTrue($bearer_token != $bearer_token2);
$this->assertInternalType('string', $bearer_token2);
$this->assertEquals(0, strpos($bearer_token2, 'Bearer '));
$this->assertGreaterThan(30, strlen($bearer_token2));
$this->assertNotEquals($bearer_token2, $bearer_token);
}
}
class SACJwtAccessComboTest extends \PHPUnit_Framework_TestCase
class SACJwtAccessComboTest extends TestCase
{
private $privateKey;
@@ -464,21 +473,23 @@ class SACJwtAccessComboTest extends \PHPUnit_Framework_TestCase
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertTrue(is_callable($update_metadata));
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = 'https://example.com/service');
$this->assertTrue(
isset($actual_metadata[CredentialsLoader::AUTH_METADATA_KEY]));
$this->assertArrayHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata
);
$authorization = $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY];
$this->assertTrue(is_array($authorization));
$this->assertInternalType('array', $authorization);
$bearer_token = current($authorization);
$this->assertTrue(is_string($bearer_token));
$this->assertTrue(strpos($bearer_token, 'Bearer ') == 0);
$this->assertTrue(strlen($bearer_token) > 30);
$this->assertInternalType('string', $bearer_token);
$this->assertEquals(0, strpos($bearer_token, 'Bearer '));
$this->assertGreaterThan(30, strlen($bearer_token));
}
public function testNoScopeAndNoAuthUri()
@@ -494,15 +505,17 @@ class SACJwtAccessComboTest extends \PHPUnit_Framework_TestCase
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertTrue(is_callable($update_metadata));
$this->assertInternalType('callable', $update_metadata);
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'),
$authUri = null);
// no access_token is added to the metadata hash
// but also, no error should be thrown
$this->assertTrue(is_array($actual_metadata));
$this->assertTrue(
!isset($actual_metadata[CredentialsLoader::AUTH_METADATA_KEY]));
$this->assertInternalType('array', $actual_metadata);
$this->assertArrayNotHasKey(
CredentialsLoader::AUTH_METADATA_KEY,
$actual_metadata
);
}
}

View File

@@ -21,6 +21,7 @@ use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\Credentials\UserRefreshCredentials;
use Google\Auth\OAuth2;
use GuzzleHttp\Psr7;
use PHPUnit\Framework\TestCase;
// Creates a standard JSON auth object for testing.
function createURCTestJson()
@@ -33,7 +34,7 @@ function createURCTestJson()
];
}
class URCGetCacheKeyTest extends \PHPUnit_Framework_TestCase
class URCGetCacheKeyTest extends TestCase
{
public function testShouldBeTheSameAsOAuth2WithTheSameScope()
{
@@ -50,7 +51,7 @@ class URCGetCacheKeyTest extends \PHPUnit_Framework_TestCase
}
}
class URCConstructorTest extends \PHPUnit_Framework_TestCase
class URCConstructorTest extends TestCase
{
/**
* @expectedException InvalidArgumentException
@@ -111,7 +112,7 @@ class URCConstructorTest extends \PHPUnit_Framework_TestCase
}
}
class URCFromEnvTest extends \PHPUnit_Framework_TestCase
class URCFromEnvTest extends TestCase
{
protected function tearDown()
{
@@ -141,7 +142,7 @@ class URCFromEnvTest extends \PHPUnit_Framework_TestCase
}
}
class URCFromWellKnownFileTest extends \PHPUnit_Framework_TestCase
class URCFromWellKnownFileTest extends TestCase
{
private $originalHome;
@@ -174,7 +175,7 @@ class URCFromWellKnownFileTest extends \PHPUnit_Framework_TestCase
}
}
class URCFetchAuthTokenTest extends \PHPUnit_Framework_TestCase
class URCFetchAuthTokenTest extends TestCase
{
/**
* @expectedException GuzzleHttp\Exception\ClientException

View File

@@ -41,6 +41,10 @@ class FetchAuthTokenCacheTest extends BaseTest
{
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
@@ -73,6 +77,10 @@ class FetchAuthTokenCacheTest extends BaseTest
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')

View File

@@ -28,44 +28,68 @@ use Google\Auth\OAuth2;
class FetchAuthTokenTest extends BaseTest
{
/** @dataProvider provideAuthTokenFetcher */
public function testGetLastReceivedToken(FetchAuthTokenInterface $fetcher)
private $scopes = ['https://www.googleapis.com/auth/drive.readonly'];
/** @dataProvider provideMakeHttpClient */
public function testMakeHttpClient($fetcherClass)
{
$accessToken = $fetcher->getLastReceivedToken();
$mockFetcher = $this->getMockBuilder($fetcherClass)
->disableOriginalConstructor()
->getMock();
$this->assertNotNull($accessToken);
$this->assertArrayHasKey('access_token', $accessToken);
$this->assertArrayHasKey('expires_at', $accessToken);
$mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnCallback(function ($httpHandler) {
return $httpHandler();
}));
$this->assertEquals('xyz', $accessToken['access_token']);
$this->assertEquals(strtotime('2001'), $accessToken['expires_at']);
$httpHandlerCalled = false;
$httpHandler = function () use (&$httpHandlerCalled) {
$httpHandlerCalled = true;
return ['access_token' => 'xyz'];
};
$tokenCallbackCalled = false;
$tokenCallback = function ($cacheKey, $accessToken) use (&$tokenCallbackCalled) {
$tokenCallbackCalled = true;
$this->assertEquals('xyz', $accessToken);
};
$client = CredentialsLoader::makeHttpClient(
$mockFetcher,
[
'base_url' => 'https://www.googleapis.com/books/v1/',
'base_uri' => 'https://www.googleapis.com/books/v1/',
'exceptions' => false,
'defaults' => ['exceptions' => false]
],
$httpHandler,
$tokenCallback
);
$response = $client->get(
'volumes?q=Henry+David+Thoreau&country=US'
);
$this->assertEquals(401, $response->getStatusCode());
$this->assertTrue($httpHandlerCalled);
$this->assertTrue($tokenCallbackCalled);
}
public function provideAuthTokenFetcher()
public function provideMakeHttpClient()
{
$scopes = ['https://www.googleapis.com/auth/drive.readonly'];
$jsonPath = sprintf(
'%s/fixtures/.config/%s',
__DIR__,
CredentialsLoader::WELL_KNOWN_PATH
);
$jsonPath2 = sprintf(
'%s/fixtures2/.config/%s',
__DIR__,
CredentialsLoader::WELL_KNOWN_PATH
);
return [
[$this->getAppIdentityCredentials()],
[$this->getGCECredentials()],
[$this->getServiceAccountCredentials($scopes, $jsonPath)],
[$this->getServiceAccountJwtAccessCredentials($jsonPath)],
[$this->getUserRefreshCredentials($scopes, $jsonPath2)],
[$this->getOAuth2()],
['Google\Auth\Credentials\AppIdentityCredentials'],
['Google\Auth\Credentials\GCECredentials'],
['Google\Auth\Credentials\ServiceAccountCredentials'],
['Google\Auth\Credentials\ServiceAccountJwtAccessCredentials'],
['Google\Auth\Credentials\UserRefreshCredentials'],
['Google\Auth\OAuth2'],
];
}
private function getAppIdentityCredentials()
public function testAppIdentityCredentialsGetLastReceivedToken()
{
$class = new \ReflectionClass(
'Google\Auth\Credentials\AppIdentityCredentials'
@@ -79,10 +103,10 @@ class FetchAuthTokenTest extends BaseTest
'expiration_time' => strtotime('2001'),
]);
return $credentials;
$this->assertGetLastReceivedToken($credentials);
}
private function getGCECredentials()
public function testGCECredentialsGetLastReceivedToken()
{
$class = new \ReflectionClass(
'Google\Auth\Credentials\GCECredentials'
@@ -96,25 +120,37 @@ class FetchAuthTokenTest extends BaseTest
'expires_at' => strtotime('2001'),
]);
return $credentials;
$this->assertGetLastReceivedToken($credentials);
}
private function getServiceAccountCredentials($scopes, $jsonPath)
public function testServiceAccountCredentialsGetLastReceivedToken()
{
$jsonPath = sprintf(
'%s/fixtures/.config/%s',
__DIR__,
CredentialsLoader::WELL_KNOWN_PATH
);
$class = new \ReflectionClass(
'Google\Auth\Credentials\ServiceAccountCredentials'
);
$property = $class->getProperty('auth');
$property->setAccessible(true);
$credentials = new ServiceAccountCredentials($scopes, $jsonPath);
$credentials = new ServiceAccountCredentials($this->scopes, $jsonPath);
$property->setValue($credentials, $this->getOAuth2Mock());
return $credentials;
$this->assertGetLastReceivedToken($credentials);
}
private function getServiceAccountJwtAccessCredentials($jsonPath)
public function testServiceAccountJwtAccessCredentialsGetLastReceivedToken()
{
$jsonPath = sprintf(
'%s/fixtures/.config/%s',
__DIR__,
CredentialsLoader::WELL_KNOWN_PATH
);
$class = new \ReflectionClass(
'Google\Auth\Credentials\ServiceAccountJwtAccessCredentials'
);
@@ -124,21 +160,27 @@ class FetchAuthTokenTest extends BaseTest
$credentials = new ServiceAccountJwtAccessCredentials($jsonPath);
$property->setValue($credentials, $this->getOAuth2Mock());
return $credentials;
$this->assertGetLastReceivedToken($credentials);
}
private function getUserRefreshCredentials($scopes, $jsonPath)
public function testUserRefreshCredentialsGetLastReceivedToken()
{
$jsonPath = sprintf(
'%s/fixtures2/.config/%s',
__DIR__,
CredentialsLoader::WELL_KNOWN_PATH
);
$class = new \ReflectionClass(
'Google\Auth\Credentials\UserRefreshCredentials'
);
$property = $class->getProperty('auth');
$property->setAccessible(true);
$credentials = new UserRefreshCredentials($scopes, $jsonPath);
$credentials = new UserRefreshCredentials($this->scopes, $jsonPath);
$property->setValue($credentials, $this->getOAuth2Mock());
return $credentials;
$this->assertGetLastReceivedToken($credentials);
}
private function getOAuth2()
@@ -148,7 +190,7 @@ class FetchAuthTokenTest extends BaseTest
'expires_at' => strtotime('2001'),
]);
return $oauth;
$this->assertGetLastReceivedToken($oauth);
}
private function getOAuth2Mock()
@@ -167,4 +209,16 @@ class FetchAuthTokenTest extends BaseTest
return $mock;
}
private function assertGetLastReceivedToken(FetchAuthTokenInterface $fetcher)
{
$accessToken = $fetcher->getLastReceivedToken();
$this->assertNotNull($accessToken);
$this->assertArrayHasKey('access_token', $accessToken);
$this->assertArrayHasKey('expires_at', $accessToken);
$this->assertEquals('xyz', $accessToken['access_token']);
$this->assertEquals(strtotime('2001'), $accessToken['expires_at']);
}
}

View File

@@ -17,8 +17,13 @@
namespace Google\Auth\Tests;
use Composer\Autoload\ClassLoader;
use Exception;
use Google\Auth\HttpHandler\Guzzle5HttpHandler;
use GuzzleHttp\Message\FutureResponse;
use GuzzleHttp\Message\Response;
use GuzzleHttp\Ring\Future\CompletedFutureValue;
use GuzzleHttp\Stream\Stream;
class Guzzle5HttpHandlerTest extends BaseTest
{
@@ -39,14 +44,37 @@ class Guzzle5HttpHandlerTest extends BaseTest
->getMockBuilder('GuzzleHttp\Client')
->disableOriginalConstructor()
->getMock();
$this->mockFuture =
$this
->getMockBuilder('GuzzleHttp\Ring\Future\FutureInterface')
->disableOriginalConstructor()
->getMock();
}
public function testSuccessfullySendsRequest()
public function testSuccessfullySendsRealRequest()
{
$request = new \GuzzleHttp\Psr7\Request('get', 'http://httpbin.org/get');
$client = new \GuzzleHttp\Client();
$handler = new Guzzle5HttpHandler($client);
$response = $handler($request);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
$this->assertEquals(200, $response->getStatusCode());
$json = json_decode((string) $response->getBody(), true);
$this->assertArrayHasKey('url', $json);
$this->assertEquals($request->getUri(), $json['url']);
}
public function testSuccessfullySendsMockRequest()
{
$response = new Response(
200,
[],
Stream::factory('Body Text')
);
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue(new Response(200)));
->will($this->returnValue($response));
$this->mockClient
->expects($this->any())
->method('createRequest')
@@ -55,5 +83,135 @@ class Guzzle5HttpHandlerTest extends BaseTest
$handler = new Guzzle5HttpHandler($this->mockClient);
$response = $handler($this->mockPsr7Request);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Body Text', (string) $response->getBody());
}
public function testAsyncWithoutGuzzlePromiseThrowsException()
{
// Pretend the promise library doesn't exist
foreach (spl_autoload_functions() as $function) {
if ($function[0] instanceof ClassLoader) {
$newAutoloader = clone $function[0];
$newAutoloader->setPsr4('GuzzleHttp\\Promise\\', '/tmp');
spl_autoload_register($newAutoloadFunc = [$newAutoloader, 'loadClass']);
spl_autoload_unregister($previousAutoloadFunc = $function);
}
}
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue(new FutureResponse($this->mockFuture)));
$this->mockClient
->expects($this->any())
->method('createRequest')
->will($this->returnValue($this->mockRequest));
$handler = new Guzzle5HttpHandler($this->mockClient);
$errorThrown = false;
try {
$handler->async($this->mockPsr7Request);
} catch (Exception $e) {
$this->assertEquals(
'Install guzzlehttp/promises to use async with Guzzle 5',
$e->getMessage()
);
$errorThrown = true;
}
// Restore autoloader before assertion (in case it fails)
spl_autoload_register($previousAutoloadFunc);
spl_autoload_unregister($newAutoloadFunc);
$this->assertTrue($errorThrown);
}
public function testSuccessfullySendsRequestAsync()
{
$response = new Response(
200,
[],
Stream::factory('Body Text')
);
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue(new FutureResponse(
new CompletedFutureValue($response)
)));
$this->mockClient
->expects($this->any())
->method('createRequest')
->will($this->returnValue($this->mockRequest));
$handler = new Guzzle5HttpHandler($this->mockClient);
$promise = $handler->async($this->mockPsr7Request);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $promise->wait());
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Body Text', (string) $response->getBody());
}
/**
* @expectedException Exception
* @expectedExceptionMessage This is a test rejection message
*/
public function testPromiseHandlesException()
{
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue(new FutureResponse(
(new CompletedFutureValue(new Response(200)))
->then(function () {
throw new Exception('This is a test rejection message');
})
)));
$this->mockClient
->expects($this->any())
->method('createRequest')
->will($this->returnValue($this->mockRequest));
$handler = new Guzzle5HttpHandler($this->mockClient);
$promise = $handler->async($this->mockPsr7Request);
$promise->wait();
}
public function testCreateGuzzle5Request()
{
$requestHeaders = [
'header1' => 'value1',
'header2' => 'value2',
];
$this->mockPsr7Request
->expects($this->once())
->method('getHeaders')
->will($this->returnValue($requestHeaders));
$mockBody = $this->getMock('Psr\Http\Message\StreamInterface');
$this->mockPsr7Request
->expects($this->once())
->method('getBody')
->will($this->returnValue($mockBody));
$this->mockClient
->expects($this->once())
->method('createRequest')
->with(null, null, [
'headers' => $requestHeaders + ['header3' => 'value3'],
'body' => $mockBody,
])
->will($this->returnValue(
$this->getMock('GuzzleHttp\Message\RequestInterface')
));
$this->mockClient
->expects($this->once())
->method('send')
->will($this->returnValue(
$this->getMock('GuzzleHttp\Message\ResponseInterface')
));
$handler = new Guzzle5HttpHandler($this->mockClient);
$handler($this->mockPsr7Request, [
'headers' => [
'header3' => 'value3'
]
]);
}
}

View File

@@ -18,6 +18,7 @@
namespace Google\Auth\Tests;
use Google\Auth\HttpHandler\Guzzle6HttpHandler;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Psr7\Response;
class Guzzle6HttpHandlerTest extends BaseTest
@@ -47,4 +48,21 @@ class Guzzle6HttpHandlerTest extends BaseTest
$response = $handler($this->mockRequest);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
}
public function testSuccessfullySendsRequestAsync()
{
$this->mockClient
->expects($this->any())
->method('sendAsync')
->will($this->returnValue(new Promise(function () use (&$promise) {
return $promise->resolve(new Response(200, [], 'Body Text'));
})));
$handler = new Guzzle6HttpHandler($this->mockClient);
$promise = $handler->async($this->mockRequest);
$response = $promise->wait();
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('Body Text', (string) $response->getBody());
}
}

View File

@@ -78,7 +78,7 @@ class AuthTokenMiddlewareTest extends BaseTest
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $authResult['access_token'])
->with('authorization', 'Bearer ' . $authResult['access_token'])
->will($this->returnValue($this->mockRequest));
// Run the test.
@@ -98,7 +98,7 @@ class AuthTokenMiddlewareTest extends BaseTest
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ')
->with('authorization', 'Bearer ')
->will($this->returnValue($this->mockRequest));
// Run the test.
@@ -112,6 +112,10 @@ class AuthTokenMiddlewareTest extends BaseTest
{
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
@@ -131,7 +135,7 @@ class AuthTokenMiddlewareTest extends BaseTest
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $cachedValue)
->with('authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test.
@@ -151,6 +155,10 @@ class AuthTokenMiddlewareTest extends BaseTest
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
@@ -170,7 +178,7 @@ class AuthTokenMiddlewareTest extends BaseTest
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $cachedValue)
->with('authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test.
@@ -221,7 +229,7 @@ class AuthTokenMiddlewareTest extends BaseTest
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $token)
->with('authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test.

View File

@@ -68,7 +68,7 @@ class ScopedAccessTokenMiddlewareTest extends BaseTest
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $token)
->with('authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test
@@ -84,6 +84,10 @@ class ScopedAccessTokenMiddlewareTest extends BaseTest
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
@@ -96,7 +100,7 @@ class ScopedAccessTokenMiddlewareTest extends BaseTest
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $cachedValue)
->with('authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test
@@ -118,6 +122,10 @@ class ScopedAccessTokenMiddlewareTest extends BaseTest
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
@@ -130,7 +138,7 @@ class ScopedAccessTokenMiddlewareTest extends BaseTest
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $cachedValue)
->with('authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test
@@ -153,7 +161,7 @@ class ScopedAccessTokenMiddlewareTest extends BaseTest
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->method('isHit')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
@@ -168,7 +176,7 @@ class ScopedAccessTokenMiddlewareTest extends BaseTest
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $token)
->with('authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test
@@ -193,7 +201,7 @@ class ScopedAccessTokenMiddlewareTest extends BaseTest
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->method('isHit')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
@@ -212,7 +220,7 @@ class ScopedAccessTokenMiddlewareTest extends BaseTest
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $token)
->with('authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test

View File

@@ -20,8 +20,9 @@ namespace Google\Auth\Tests;
use Google\Auth\OAuth2;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
class OAuth2AuthorizationUriTest extends \PHPUnit_Framework_TestCase
class OAuth2AuthorizationUriTest extends TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
@@ -170,7 +171,7 @@ class OAuth2AuthorizationUriTest extends \PHPUnit_Framework_TestCase
}
}
class OAuth2GrantTypeTest extends \PHPUnit_Framework_TestCase
class OAuth2GrantTypeTest extends TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
@@ -232,7 +233,7 @@ class OAuth2GrantTypeTest extends \PHPUnit_Framework_TestCase
}
}
class OAuth2GetCacheKeyTest extends \PHPUnit_Framework_TestCase
class OAuth2GetCacheKeyTest extends TestCase
{
private $minimal = [
'clientID' => 'aClientID',
@@ -259,7 +260,7 @@ class OAuth2GetCacheKeyTest extends \PHPUnit_Framework_TestCase
}
}
class OAuth2TimingTest extends \PHPUnit_Framework_TestCase
class OAuth2TimingTest extends TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
@@ -319,7 +320,7 @@ class OAuth2TimingTest extends \PHPUnit_Framework_TestCase
}
}
class OAuth2GeneralTest extends \PHPUnit_Framework_TestCase
class OAuth2GeneralTest extends TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
@@ -363,7 +364,7 @@ class OAuth2GeneralTest extends \PHPUnit_Framework_TestCase
}
}
class OAuth2JwtTest extends \PHPUnit_Framework_TestCase
class OAuth2JwtTest extends TestCase
{
private $signingMinimal = [
'signingKey' => 'example_key',
@@ -454,6 +455,21 @@ class OAuth2JwtTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($roundTrip->scope, $testConfig['scope']);
}
public function testCanHaveAdditionalClaims()
{
$publicKey = file_get_contents(__DIR__ . '/fixtures' . '/public.pem');
$privateKey = file_get_contents(__DIR__ . '/fixtures' . '/private.pem');
$testConfig = $this->signingMinimal;
$targetAud = '123@456.com';
$testConfig['additionalClaims'] = ['target_audience' => $targetAud];
$o = new OAuth2($testConfig);
$o->setSigningAlgorithm('RS256');
$o->setSigningKey($privateKey);
$payload = $o->toJwt();
$roundTrip = $this->jwtDecode($payload, $publicKey, array('RS256'));
$this->assertEquals($roundTrip->target_audience, $targetAud);
}
private function jwtDecode()
{
$args = func_get_args();
@@ -466,7 +482,7 @@ class OAuth2JwtTest extends \PHPUnit_Framework_TestCase
}
}
class OAuth2GenerateAccessTokenRequestTest extends \PHPUnit_Framework_TestCase
class OAuth2GenerateAccessTokenRequestTest extends TestCase
{
private $tokenRequestMinimal = [
'tokenCredentialUri' => 'https://tokens_r_us/test',
@@ -594,7 +610,7 @@ class OAuth2GenerateAccessTokenRequestTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('POST', $req->getMethod());
$fields = Psr7\parse_query((string)$req->getBody());
$this->assertEquals(OAuth2::JWT_URN, $fields['grant_type']);
$this->assertTrue(array_key_exists('assertion', $fields));
$this->assertArrayHasKey('assertion', $fields);
}
public function testGeneratesExtendedRequests()
@@ -614,7 +630,7 @@ class OAuth2GenerateAccessTokenRequestTest extends \PHPUnit_Framework_TestCase
}
}
class OAuth2FetchAuthTokenTest extends \PHPUnit_Framework_TestCase
class OAuth2FetchAuthTokenTest extends TestCase
{
private $fetchAuthTokenMinimal = [
'tokenCredentialUri' => 'https://tokens_r_us/test',
@@ -759,7 +775,7 @@ class OAuth2FetchAuthTokenTest extends \PHPUnit_Framework_TestCase
}
}
class OAuth2VerifyIdTokenTest extends \PHPUnit_Framework_TestCase
class OAuth2VerifyIdTokenTest extends TestCase
{
private $publicKey;
private $privateKey;

View File

@@ -61,7 +61,7 @@ class AuthTokenSubscriberTest extends BaseTest
['auth' => 'not_google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame($request->getHeader('Authorization'), '');
$this->assertSame($request->getHeader('authorization'), '');
}
public function testAddsTheTokenAsAnAuthorizationHeader()
@@ -79,7 +79,7 @@ class AuthTokenSubscriberTest extends BaseTest
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('Authorization'),
$this->assertSame($request->getHeader('authorization'),
'Bearer 1/abcdef1234567890');
}
@@ -98,13 +98,17 @@ class AuthTokenSubscriberTest extends BaseTest
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('Authorization'), '');
$this->assertSame($request->getHeader('authorization'), '');
}
public function testUsesCachedAuthToken()
{
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
@@ -134,7 +138,7 @@ class AuthTokenSubscriberTest extends BaseTest
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('Authorization'),
$this->assertSame($request->getHeader('authorization'),
'Bearer 2/abcdef1234567890');
}
@@ -143,6 +147,10 @@ class AuthTokenSubscriberTest extends BaseTest
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
@@ -172,7 +180,7 @@ class AuthTokenSubscriberTest extends BaseTest
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('Authorization'),
$this->assertSame($request->getHeader('authorization'),
'Bearer 2/abcdef1234567890');
}
@@ -222,7 +230,7 @@ class AuthTokenSubscriberTest extends BaseTest
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('Authorization'),
$this->assertSame($request->getHeader('authorization'),
'Bearer 1/abcdef1234567890');
}

View File

@@ -82,7 +82,7 @@ class ScopedAccessTokenSubscriberTest extends BaseTest
$s->onBefore($before);
$this->assertSame(
'Bearer 1/abcdef1234567890',
$request->getHeader('Authorization')
$request->getHeader('authorization')
);
}
@@ -92,6 +92,10 @@ class ScopedAccessTokenSubscriberTest extends BaseTest
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
@@ -112,7 +116,7 @@ class ScopedAccessTokenSubscriberTest extends BaseTest
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('Authorization')
$request->getHeader('authorization')
);
}
@@ -123,6 +127,10 @@ class ScopedAccessTokenSubscriberTest extends BaseTest
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('isHit')
->will($this->returnValue(true));
$this->mockCacheItem
->expects($this->once())
->method('get')
@@ -144,7 +152,7 @@ class ScopedAccessTokenSubscriberTest extends BaseTest
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('Authorization')
$request->getHeader('authorization')
);
}
@@ -156,7 +164,7 @@ class ScopedAccessTokenSubscriberTest extends BaseTest
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->method('isHit')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
@@ -177,7 +185,7 @@ class ScopedAccessTokenSubscriberTest extends BaseTest
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('Authorization')
$request->getHeader('authorization')
);
}
@@ -191,7 +199,7 @@ class ScopedAccessTokenSubscriberTest extends BaseTest
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->method('isHit')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
@@ -218,7 +226,7 @@ class ScopedAccessTokenSubscriberTest extends BaseTest
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('Authorization')
$request->getHeader('authorization')
);
}
@@ -233,6 +241,6 @@ class ScopedAccessTokenSubscriberTest extends BaseTest
['auth' => 'notscoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame('', $request->getHeader('Authorization'));
$this->assertSame('', $request->getHeader('authorization'));
}
}