Initial commit

This commit is contained in:
Caribana
2017-05-26 11:41:26 +02:00
commit 61c24500af
6264 changed files with 645934 additions and 0 deletions

View File

@@ -0,0 +1,299 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\Credentials\GCECredentials;
use Google\Auth\Credentials\ServiceAccountCredentials;
use GuzzleHttp\Psr7;
class ADCGetTest extends \PHPUnit_Framework_TestCase
{
private $originalHome;
protected function setUp()
{
$this->originalHome = getenv('HOME');
}
protected function tearDown()
{
if ($this->originalHome != getenv('HOME')) {
putenv('HOME=' . $this->originalHome);
}
putenv(ServiceAccountCredentials::ENV_VAR); // removes it from
}
/**
* @expectedException DomainException
*/
public function testIsFailsEnvSpecifiesNonExistentFile()
{
$keyFile = __DIR__ . '/fixtures' . '/does-not-exist-private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
ApplicationDefaultCredentials::getCredentials('a scope');
}
public function testLoadsOKIfEnvSpecifiedIsValid()
{
$keyFile = __DIR__ . '/fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$this->assertNotNull(
ApplicationDefaultCredentials::getCredentials('a scope')
);
}
public function testLoadsDefaultFileIfPresentAndEnvVarIsNotSet()
{
putenv('HOME=' . __DIR__ . '/fixtures');
$this->assertNotNull(
ApplicationDefaultCredentials::getCredentials('a scope')
);
}
/**
* @expectedException DomainException
*/
public function testFailsIfNotOnGceAndNoDefaultFileFound()
{
putenv('HOME=' . __DIR__ . '/not_exist_fixtures');
// simulate not being GCE by return 500
$httpHandler = getHandler([
buildResponse(500),
]);
ApplicationDefaultCredentials::getCredentials('a scope', $httpHandler);
}
public function testSuccedsIfNoDefaultFilesButIsOnGCE()
{
$wantedTokens = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'token_type' => 'Bearer',
];
$jsonTokens = json_encode($wantedTokens);
// simulate the response from GCE.
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for($jsonTokens)),
]);
$this->assertNotNull(
ApplicationDefaultCredentials::getCredentials('a scope', $httpHandler)
);
}
}
class ADCGetMiddlewareTest extends \PHPUnit_Framework_TestCase
{
private $originalHome;
protected function setUp()
{
$this->originalHome = getenv('HOME');
}
protected function tearDown()
{
if ($this->originalHome != getenv('HOME')) {
putenv('HOME=' . $this->originalHome);
}
putenv(ServiceAccountCredentials::ENV_VAR); // removes it if assigned
}
/**
* @expectedException DomainException
*/
public function testIsFailsEnvSpecifiesNonExistentFile()
{
$keyFile = __DIR__ . '/fixtures' . '/does-not-exist-private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
ApplicationDefaultCredentials::getMiddleware('a scope');
}
public function testLoadsOKIfEnvSpecifiedIsValid()
{
$keyFile = __DIR__ . '/fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$this->assertNotNull(ApplicationDefaultCredentials::getMiddleware('a scope'));
}
public function testLoadsDefaultFileIfPresentAndEnvVarIsNotSet()
{
putenv('HOME=' . __DIR__ . '/fixtures');
$this->assertNotNull(ApplicationDefaultCredentials::getMiddleware('a scope'));
}
/**
* @expectedException DomainException
*/
public function testFailsIfNotOnGceAndNoDefaultFileFound()
{
putenv('HOME=' . __DIR__ . '/not_exist_fixtures');
// simulate not being GCE by return 500
$httpHandler = getHandler([
buildResponse(500),
]);
ApplicationDefaultCredentials::getMiddleware('a scope', $httpHandler);
}
public function testSuccedsIfNoDefaultFilesButIsOnGCE()
{
$wantedTokens = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'token_type' => 'Bearer',
];
$jsonTokens = json_encode($wantedTokens);
// simulate the response from GCE.
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for($jsonTokens)),
]);
$this->assertNotNull(ApplicationDefaultCredentials::getMiddleware('a scope', $httpHandler));
}
}
class ADCGetCredentialsAppEngineTest extends BaseTest
{
private $originalHome;
private $originalServiceAccount;
protected function setUp()
{
// set home to be somewhere else
$this->originalHome = getenv('HOME');
putenv('HOME=' . __DIR__ . '/not_exist_fixtures');
// remove service account path
$this->originalServiceAccount = getenv(ServiceAccountCredentials::ENV_VAR);
putenv(ServiceAccountCredentials::ENV_VAR);
}
protected function tearDown()
{
// removes it if assigned
putenv('HOME=' . $this->originalHome);
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $this->originalServiceAccount);
}
public function testAppEngineStandard()
{
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
$this->assertInstanceOf(
'Google\Auth\Credentials\AppIdentityCredentials',
ApplicationDefaultCredentials::getCredentials()
);
}
public function testAppEngineFlexible()
{
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
$_SERVER['GAE_VM'] = 'true';
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
]);
$this->assertInstanceOf(
'Google\Auth\Credentials\GCECredentials',
ApplicationDefaultCredentials::getCredentials(null, $httpHandler)
);
}
}
// @todo consider a way to DRY this and above class up
class ADCGetSubscriberTest extends BaseTest
{
private $originalHome;
protected function setUp()
{
$this->onlyGuzzle5();
$this->originalHome = getenv('HOME');
}
protected function tearDown()
{
if ($this->originalHome != getenv('HOME')) {
putenv('HOME=' . $this->originalHome);
}
putenv(ServiceAccountCredentials::ENV_VAR); // removes it if assigned
}
/**
* @expectedException DomainException
*/
public function testIsFailsEnvSpecifiesNonExistentFile()
{
$keyFile = __DIR__ . '/fixtures' . '/does-not-exist-private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
ApplicationDefaultCredentials::getSubscriber('a scope');
}
public function testLoadsOKIfEnvSpecifiedIsValid()
{
$keyFile = __DIR__ . '/fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$this->assertNotNull(ApplicationDefaultCredentials::getSubscriber('a scope'));
}
public function testLoadsDefaultFileIfPresentAndEnvVarIsNotSet()
{
putenv('HOME=' . __DIR__ . '/fixtures');
$this->assertNotNull(ApplicationDefaultCredentials::getSubscriber('a scope'));
}
/**
* @expectedException DomainException
*/
public function testFailsIfNotOnGceAndNoDefaultFileFound()
{
putenv('HOME=' . __DIR__ . '/not_exist_fixtures');
// simulate not being GCE by return 500
$httpHandler = getHandler([
buildResponse(500),
]);
ApplicationDefaultCredentials::getSubscriber('a scope', $httpHandler);
}
public function testSuccedsIfNoDefaultFilesButIsOnGCE()
{
$wantedTokens = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'token_type' => 'Bearer',
];
$jsonTokens = json_encode($wantedTokens);
// simulate the response from GCE.
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for($jsonTokens)),
]);
$this->assertNotNull(ApplicationDefaultCredentials::getSubscriber('a scope', $httpHandler));
}
}

32
vendor/google/auth/tests/BaseTest.php vendored Normal file
View File

@@ -0,0 +1,32 @@
<?php
namespace Google\Auth\tests;
use GuzzleHttp\ClientInterface;
abstract class BaseTest extends \PHPUnit_Framework_TestCase
{
public function onlyGuzzle6()
{
$version = ClientInterface::VERSION;
if ('6' !== $version[0]) {
$this->markTestSkipped('Guzzle 6 only');
}
}
public function onlyGuzzle5()
{
$version = ClientInterface::VERSION;
if ('5' !== $version[0]) {
$this->markTestSkipped('Guzzle 5 only');
}
}
/**
* @see Google\Auth\$this->getValidKeyName
*/
public function getValidKeyName($key)
{
return preg_replace('|[^a-zA-Z0-9_\.! ]|', '', $key);
}
}

View File

@@ -0,0 +1,125 @@
<?php
/*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\Cache\Item;
class ItemTest extends \PHPUnit_Framework_TestCase
{
public function getItem($key)
{
return new Item($key);
}
public function testGetsKey()
{
$key = 'item';
$this->assertEquals($key, $this->getItem($key)->getKey());
}
public function testGetsNull()
{
$item = $this->getItem('item');
$this->assertNull($item->get());
$this->assertFalse($item->isHit());
}
public function testGetsValue()
{
$value = 'value';
$item = $this->getItem('item');
$item->set($value);
$this->assertEquals('value', $item->get());
}
/**
* @dataProvider values
*/
public function testSetsValue($value)
{
$item = $this->getItem('item');
$item->set($value);
$this->assertEquals($value, $item->get());
}
public function values()
{
return [
[1],
[1.5],
[true],
[null],
[new \DateTime()],
[['test']],
['value']
];
}
public function testIsHit()
{
$item = $this->getItem('item');
$this->assertFalse($item->isHit());
$item->set('value');
$this->assertTrue($item->isHit());
}
public function testExpiresAt()
{
$item = $this->getItem('item');
$item->set('value');
$item->expiresAt(new \DateTime('now + 1 hour'));
$this->assertTrue($item->isHit());
$item->expiresAt(null);
$this->assertTrue($item->isHit());
$item->expiresAt(new \DateTime('yesterday'));
$this->assertFalse($item->isHit());
}
public function testExpiresAfter()
{
$item = $this->getItem('item');
$item->set('value');
$item->expiresAfter(30);
$this->assertTrue($item->isHit());
$item->expiresAfter(0);
$this->assertFalse($item->isHit());
$item->expiresAfter(new \DateInterval('PT30S'));
$this->assertTrue($item->isHit());
$item->expiresAfter(null);
$this->assertTrue($item->isHit());
}
}

View File

@@ -0,0 +1,189 @@
<?php
/*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\Cache\MemoryCacheItemPool;
use Psr\Cache\InvalidArgumentException;
class MemoryCacheItemPoolTest extends \PHPUnit_Framework_TestCase
{
private $pool;
public function setUp()
{
$this->pool = new MemoryCacheItemPool();
}
public function saveItem($key, $value)
{
$item = $this->pool->getItem($key);
$item->set($value);
$this->assertTrue($this->pool->save($item));
return $item;
}
public function testGetsFreshItem()
{
$item = $this->pool->getItem('item');
$this->assertInstanceOf('Google\Auth\Cache\Item', $item);
$this->assertNull($item->get());
$this->assertFalse($item->isHit());
}
public function testGetsExistingItem()
{
$key = 'item';
$value = 'value';
$this->saveItem($key, $value);
$item = $this->pool->getItem($key);
$this->assertInstanceOf('Google\Auth\Cache\Item', $item);
$this->assertEquals($value, $item->get());
$this->assertTrue($item->isHit());
}
public function testGetsMultipleItems()
{
$keys = ['item1', 'item2'];
$items = $this->pool->getItems($keys);
$this->assertEquals($keys, array_keys($items));
$this->assertContainsOnlyInstancesOf('Google\Auth\Cache\Item', $items);
}
public function testHasItem()
{
$existsKey = 'does-exist';
$this->saveItem($existsKey, 'value');
$this->assertTrue($this->pool->hasItem($existsKey));
$this->assertFalse($this->pool->hasItem('does-not-exist'));
}
public function testClear()
{
$key = 'item';
$this->saveItem($key, 'value');
$this->assertTrue($this->pool->hasItem($key));
$this->assertTrue($this->pool->clear());
$this->assertFalse($this->pool->hasItem($key));
}
public function testDeletesItem()
{
$key = 'item';
$this->saveItem($key, 'value');
$this->assertTrue($this->pool->deleteItem($key));
$this->assertFalse($this->pool->hasItem($key));
}
public function testDeletesItems()
{
$keys = ['item1', 'item2'];
foreach ($keys as $key) {
$this->saveItem($key, 'value');
}
$this->assertTrue($this->pool->deleteItems($keys));
$this->assertFalse($this->pool->hasItem($keys[0]));
$this->assertFalse($this->pool->hasItem($keys[1]));
}
public function testDoesNotDeleteItemsWithInvalidKey()
{
$keys = ['item1', '{item2}', 'item3'];
$value = 'value';
$this->saveItem($keys[0], $value);
$this->saveItem($keys[2], $value);
try {
$this->pool->deleteItems($keys);
} catch (InvalidArgumentException $ex) {
// continue execution
}
$this->assertTrue($this->pool->hasItem($keys[0]));
$this->assertTrue($this->pool->hasItem($keys[2]));
}
public function testSavesItem()
{
$key = 'item';
$this->saveItem($key, 'value');
$this->assertTrue($this->pool->hasItem($key));
}
public function testSavesDeferredItem()
{
$item = $this->pool->getItem('item');
$this->assertTrue($this->pool->saveDeferred($item));
}
public function testCommitsDeferredItems()
{
$keys = ['item1', 'item2'];
foreach ($keys as $key) {
$item = $this->pool->getItem($key);
$item->set('value');
$this->pool->saveDeferred($item);
}
$this->assertTrue($this->pool->commit());
$this->assertTrue($this->pool->hasItem($keys[0]));
$this->assertTrue($this->pool->hasItem($keys[1]));
}
/**
* @expectedException \Psr\Cache\InvalidArgumentException
* @dataProvider invalidKeys
*/
public function testCheckInvalidKeys($key)
{
$this->pool->getItem($key);
$this->pool->getItems([$key]);
$this->pool->hasItem($key);
$this->pool->deleteItem($key);
$this->pool->deleteItems([$key]);
}
public function invalidKeys()
{
return [
[1],
[true],
[null],
[new \DateTime()],
['{'],
['}'],
['('],
[')'],
['/'],
['\\'],
['@'],
[':'],
[[]]
];
}
}

View File

@@ -0,0 +1,151 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\CacheTrait;
class CacheTraitTest extends \PHPUnit_Framework_TestCase
{
private $mockFetcher;
private $mockCacheItem;
private $mockCache;
public function setUp()
{
$this->mockFetcher =
$this
->getMockBuilder('Google\Auth\FetchAuthTokenInterface')
->getMock();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
}
public function testSuccessfullyPullsFromCache()
{
$expectedValue = '1234';
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($expectedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->will($this->returnValue($this->mockCacheItem));
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
]);
$cachedValue = $implementation->gCachedValue();
$this->assertEquals($expectedValue, $cachedValue);
}
public function testFailsPullFromCacheWithNoCache()
{
$implementation = new CacheTraitImplementation();
$cachedValue = $implementation->gCachedValue();
$this->assertEquals(null, $cachedValue);
}
public function testFailsPullFromCacheWithoutKey()
{
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
'key' => null,
]);
$cachedValue = $implementation->gCachedValue();
}
public function testSuccessfullySetsToCache()
{
$value = '1234';
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($value);
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo('key'))
->will($this->returnValue($this->mockCacheItem));
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
]);
$implementation->sCachedValue($value);
}
public function testFailsSetToCacheWithNoCache()
{
$implementation = new CacheTraitImplementation();
$implementation->sCachedValue('1234');
$cachedValue = $implementation->sCachedValue('1234');
$this->assertNull($cachedValue);
}
public function testFailsSetToCacheWithoutKey()
{
$implementation = new CacheTraitImplementation([
'cache' => $this->mockCache,
'key' => null,
]);
$cachedValue = $implementation->sCachedValue('1234');
$this->assertNull($cachedValue);
}
}
class CacheTraitImplementation
{
use CacheTrait;
private $cache;
private $cacheConfig;
public function __construct(array $config = [])
{
$this->key = array_key_exists('key', $config) ? $config['key'] : 'key';
$this->cache = isset($config['cache']) ? $config['cache'] : null;
$this->cacheConfig = [
'prefix' => '',
'lifetime' => 1000,
];
}
// allows us to keep trait methods private
public function gCachedValue()
{
return $this->getCachedValue($this->key);
}
public function sCachedValue($v)
{
$this->setCachedValue($this->key, $v);
}
}

View File

@@ -0,0 +1,104 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use google\appengine\api\app_identity\AppIdentityService;
// included from tests\mocks\AppIdentityService.php
use Google\Auth\Credentials\AppIdentityCredentials;
class AppIdentityCredentialsOnAppEngineTest extends \PHPUnit_Framework_TestCase
{
public function testIsFalseByDefault()
{
$this->assertFalse(AppIdentityCredentials::onAppEngine());
}
public function testIsTrueWhenServerSoftwareIsGoogleAppEngine()
{
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
$this->assertTrue(AppIdentityCredentials::onAppEngine());
}
}
class AppIdentityCredentialsGetCacheKeyTest extends \PHPUnit_Framework_TestCase
{
public function testShouldBeEmpty()
{
$g = new AppIdentityCredentials();
$this->assertEmpty($g->getCacheKey());
}
}
class AppIdentityCredentialsFetchAuthTokenTest extends \PHPUnit_Framework_TestCase
{
public function testShouldBeEmptyIfNotOnAppEngine()
{
$g = new AppIdentityCredentials();
$this->assertEquals(array(), $g->fetchAuthToken());
}
/* @expectedException */
public function testThrowsExceptionIfClassDoesntExist()
{
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
$g = new AppIdentityCredentials();
}
public function testReturnsExpectedToken()
{
// include the mock AppIdentityService class
require_once __DIR__ . '/../mocks/AppIdentityService.php';
$wantedToken = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'token_type' => 'Bearer',
];
AppIdentityService::$accessToken = $wantedToken;
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
$g = new AppIdentityCredentials();
$this->assertEquals($wantedToken, $g->fetchAuthToken());
}
public function testScopeIsAlwaysArray()
{
// include the mock AppIdentityService class
require_once __DIR__ . '/../mocks/AppIdentityService.php';
$scope1 = ['scopeA', 'scopeB'];
$scope2 = 'scopeA scopeB';
$scope3 = 'scopeA';
$_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
$g = new AppIdentityCredentials($scope1);
$g->fetchAuthToken();
$this->assertEquals($scope1, AppIdentityService::$scope);
$g = new AppIdentityCredentials($scope2);
$g->fetchAuthToken();
$this->assertEquals(explode(' ', $scope2), AppIdentityService::$scope);
$g = new AppIdentityCredentials($scope3);
$g->fetchAuthToken();
$this->assertEquals([$scope3], AppIdentityService::$scope);
}
}

View File

@@ -0,0 +1,124 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\Credentials\GCECredentials;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Response;
class GCECredentialsOnGCETest extends \PHPUnit_Framework_TestCase
{
public function testIsFalseOnClientErrorStatus()
{
$httpHandler = getHandler([
buildResponse(400),
]);
$this->assertFalse(GCECredentials::onGCE($httpHandler));
}
public function testIsFalseOnServerErrorStatus()
{
$httpHandler = getHandler([
buildResponse(500),
]);
$this->assertFalse(GCECredentials::onGCE($httpHandler));
}
public function testIsFalseOnOkStatusWithoutExpectedHeader()
{
$httpHandler = getHandler([
buildResponse(200),
]);
$this->assertFalse(GCECredentials::onGCE($httpHandler));
}
public function testIsOkIfGoogleIsTheFlavor()
{
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
]);
$this->assertTrue(GCECredentials::onGCE($httpHandler));
}
}
class GCECredentialsOnAppEngineFlexibleTest extends \PHPUnit_Framework_TestCase
{
public function testIsFalseByDefault()
{
$this->assertFalse(GCECredentials::onAppEngineFlexible());
}
public function testIsTrueWhenGaeVmIsTrue()
{
$_SERVER['GAE_VM'] = 'true';
$this->assertTrue(GCECredentials::onAppEngineFlexible());
}
}
class GCECredentialsGetCacheKeyTest extends \PHPUnit_Framework_TestCase
{
public function testShouldNotBeEmpty()
{
$g = new GCECredentials();
$this->assertNotEmpty($g->getCacheKey());
}
}
class GCECredentialsFetchAuthTokenTest extends \PHPUnit_Framework_TestCase
{
public function testShouldBeEmptyIfNotOnGCE()
{
$httpHandler = getHandler([
buildResponse(500),
]);
$g = new GCECredentials();
$this->assertEquals(array(), $g->fetchAuthToken($httpHandler));
}
/**
* @expectedException Exception
* @expectedExceptionMessage Invalid JSON response
*/
public function testShouldFailIfResponseIsNotJson()
{
$notJson = '{"foo": , this is cannot be passed as json" "bar"}';
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], $notJson),
]);
$g = new GCECredentials();
$g->fetchAuthToken($httpHandler);
}
public function testShouldReturnTokenInfo()
{
$wantedTokens = [
'access_token' => '1/abdef1234567890',
'expires_in' => '57',
'token_type' => 'Bearer',
];
$jsonTokens = json_encode($wantedTokens);
$httpHandler = getHandler([
buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']),
buildResponse(200, [], Psr7\stream_for($jsonTokens)),
]);
$g = new GCECredentials();
$this->assertEquals($wantedTokens, $g->fetchAuthToken($httpHandler));
$this->assertEquals(time() + 57, $g->getLastReceivedToken()['expires_at']);
}
}

View File

@@ -0,0 +1,83 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\Credentials\IAMCredentials;
class IAMConstructorTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfSelectorIsNotString()
{
$notAString = new \stdClass();
$iam = new IAMCredentials(
$notAString,
''
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfTokenIsNotString()
{
$notAString = new \stdClass();
$iam = new IAMCredentials(
'',
$notAString
);
}
public function testInitializeSuccess()
{
$this->assertNotNull(
new IAMCredentials('iam-selector', 'iam-token')
);
}
}
class IAMUpdateMetadataCallbackTest extends \PHPUnit_Framework_TestCase
{
public function testUpdateMetadataFunc()
{
$selector = 'iam-selector';
$token = 'iam-token';
$iam = new IAMCredentials(
$selector,
$token
);
$update_metadata = $iam->getUpdateMetadataFunc();
$this->assertTrue(is_callable($update_metadata));
$actual_metadata = call_user_func($update_metadata,
$metadata = array('foo' => 'bar'));
$this->assertTrue(
isset($actual_metadata[IAMCredentials::SELECTOR_KEY]));
$this->assertEquals(
$actual_metadata[IAMCredentials::SELECTOR_KEY],
$selector);
$this->assertTrue(
isset($actual_metadata[IAMCredentials::TOKEN_KEY]));
$this->assertEquals(
$actual_metadata[IAMCredentials::TOKEN_KEY],
$token);
}
}

View File

@@ -0,0 +1,508 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Credentials\ServiceAccountJwtAccessCredentials;
use Google\Auth\CredentialsLoader;
use Google\Auth\OAuth2;
use GuzzleHttp\Psr7;
// Creates a standard JSON auth object for testing.
function createTestJson()
{
return [
'private_key_id' => 'key123',
'private_key' => 'privatekey',
'client_email' => 'test@example.com',
'client_id' => 'client123',
'type' => 'service_account',
];
}
class SACGetCacheKeyTest extends \PHPUnit_Framework_TestCase
{
public function testShouldBeTheSameAsOAuth2WithTheSameScope()
{
$testJson = createTestJson();
$scope = ['scope/1', 'scope/2'];
$sa = new ServiceAccountCredentials(
$scope,
$testJson);
$o = new OAuth2(['scope' => $scope]);
$this->assertSame(
$testJson['client_email'] . ':' . $o->getCacheKey(),
$sa->getCacheKey()
);
}
public function testShouldBeTheSameAsOAuth2WithTheSameScopeWithSub()
{
$testJson = createTestJson();
$scope = ['scope/1', 'scope/2'];
$sub = 'sub123';
$sa = new ServiceAccountCredentials(
$scope,
$testJson,
$sub);
$o = new OAuth2(['scope' => $scope]);
$this->assertSame(
$testJson['client_email'] . ':' . $o->getCacheKey() . ':' . $sub,
$sa->getCacheKey()
);
}
public function testShouldBeTheSameAsOAuth2WithTheSameScopeWithSubAddedLater()
{
$testJson = createTestJson();
$scope = ['scope/1', 'scope/2'];
$sub = 'sub123';
$sa = new ServiceAccountCredentials(
$scope,
$testJson,
null);
$sa->setSub($sub);
$o = new OAuth2(['scope' => $scope]);
$this->assertSame(
$testJson['client_email'] . ':' . $o->getCacheKey() . ':' . $sub,
$sa->getCacheKey()
);
}
}
class SACConstructorTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfScopeIsNotAValidType()
{
$testJson = createTestJson();
$notAnArrayOrString = new \stdClass();
$sa = new ServiceAccountCredentials(
$notAnArrayOrString,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfJsonDoesNotHaveClientEmail()
{
$testJson = createTestJson();
unset($testJson['client_email']);
$scope = ['scope/1', 'scope/2'];
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfJsonDoesNotHavePrivateKey()
{
$testJson = createTestJson();
unset($testJson['private_key']);
$scope = ['scope/1', 'scope/2'];
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsToInitalizeFromANonExistentFile()
{
$keyFile = __DIR__ . '/../fixtures' . '/does-not-exist-private.json';
new ServiceAccountCredentials('scope/1', $keyFile);
}
public function testInitalizeFromAFile()
{
$keyFile = __DIR__ . '/../fixtures' . '/private.json';
$this->assertNotNull(
new ServiceAccountCredentials('scope/1', $keyFile)
);
}
}
class SACFromEnvTest extends \PHPUnit_Framework_TestCase
{
protected function tearDown()
{
putenv(ServiceAccountCredentials::ENV_VAR); // removes it from
}
public function testIsNullIfEnvVarIsNotSet()
{
$this->assertNull(ServiceAccountCredentials::fromEnv());
}
/**
* @expectedException DomainException
*/
public function testFailsIfEnvSpecifiesNonExistentFile()
{
$keyFile = __DIR__ . '/../fixtures' . '/does-not-exist-private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
ApplicationDefaultCredentials::getCredentials('a scope');
}
public function testSucceedIfFileExists()
{
$keyFile = __DIR__ . '/../fixtures' . '/private.json';
putenv(ServiceAccountCredentials::ENV_VAR . '=' . $keyFile);
$this->assertNotNull(ApplicationDefaultCredentials::getCredentials('a scope'));
}
}
class SACFromWellKnownFileTest extends \PHPUnit_Framework_TestCase
{
private $originalHome;
protected function setUp()
{
$this->originalHome = getenv('HOME');
}
protected function tearDown()
{
if ($this->originalHome != getenv('HOME')) {
putenv('HOME=' . $this->originalHome);
}
}
public function testIsNullIfFileDoesNotExist()
{
putenv('HOME=' . __DIR__ . '/../not_exists_fixtures');
$this->assertNull(
ServiceAccountCredentials::fromWellKnownFile()
);
}
public function testSucceedIfFileIsPresent()
{
putenv('HOME=' . __DIR__ . '/../fixtures');
$this->assertNotNull(
ApplicationDefaultCredentials::getCredentials('a scope')
);
}
}
class SACFetchAuthTokenTest extends \PHPUnit_Framework_TestCase
{
private $privateKey;
public function setUp()
{
$this->privateKey =
file_get_contents(__DIR__ . '/../fixtures' . '/private.pem');
}
private function createTestJson()
{
$testJson = createTestJson();
$testJson['private_key'] = $this->privateKey;
return $testJson;
}
/**
* @expectedException GuzzleHttp\Exception\ClientException
*/
public function testFailsOnClientErrors()
{
$testJson = $this->createTestJson();
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(400),
]);
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$sa->fetchAuthToken($httpHandler);
}
/**
* @expectedException GuzzleHttp\Exception\ServerException
*/
public function testFailsOnServerErrors()
{
$testJson = $this->createTestJson();
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(500),
]);
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$sa->fetchAuthToken($httpHandler);
}
public function testCanFetchCredsOK()
{
$testJson = $this->createTestJson();
$testJsonText = json_encode($testJson);
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($testJsonText)),
]);
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$tokens = $sa->fetchAuthToken($httpHandler);
$this->assertEquals($testJson, $tokens);
}
public function testUpdateMetadataFunc()
{
$testJson = $this->createTestJson();
$scope = ['scope/1', 'scope/2'];
$access_token = 'accessToken123';
$responseText = json_encode(array('access_token' => $access_token));
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($responseText)),
]);
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertTrue(is_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->assertEquals(
$actual_metadata[CredentialsLoader::AUTH_METADATA_KEY],
array('Bearer ' . $access_token));
}
}
class SACJwtAccessTest extends \PHPUnit_Framework_TestCase
{
private $privateKey;
public function setUp()
{
$this->privateKey =
file_get_contents(__DIR__ . '/../fixtures' . '/private.pem');
}
private function createTestJson()
{
$testJson = createTestJson();
$testJson['private_key'] = $this->privateKey;
return $testJson;
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsOnMissingClientEmail()
{
$testJson = $this->createTestJson();
unset($testJson['client_email']);
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsOnMissingPrivateKey()
{
$testJson = $this->createTestJson();
unset($testJson['private_key']);
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
}
public function testCanInitializeFromJson()
{
$testJson = $this->createTestJson();
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
$this->assertNotNull($sa);
}
public function testNoOpOnFetchAuthToken()
{
$testJson = $this->createTestJson();
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
$this->assertNotNull($sa);
$httpHandler = getHandler([
buildResponse(200),
]);
$result = $sa->fetchAuthToken($httpHandler); // authUri has not been set
$this->assertNull($result);
}
public function testAuthUriIsNotSet()
{
$testJson = $this->createTestJson();
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertTrue(is_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]));
}
public function testUpdateMetadataFunc()
{
$testJson = $this->createTestJson();
$sa = new ServiceAccountJwtAccessCredentials(
$testJson
);
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertTrue(is_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]));
$authorization = $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY];
$this->assertTrue(is_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);
$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]));
$authorization2 = $actual_metadata2[CredentialsLoader::AUTH_METADATA_KEY];
$this->assertTrue(is_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);
}
}
class SACJwtAccessComboTest extends \PHPUnit_Framework_TestCase
{
private $privateKey;
public function setUp()
{
$this->privateKey =
file_get_contents(__DIR__ . '/../fixtures' . '/private.pem');
}
private function createTestJson()
{
$testJson = createTestJson();
$testJson['private_key'] = $this->privateKey;
return $testJson;
}
public function testNoScopeUseJwtAccess()
{
$testJson = $this->createTestJson();
// no scope, jwt access should be used, no outbound
// call should be made
$scope = null;
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertTrue(is_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]));
$authorization = $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY];
$this->assertTrue(is_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);
}
public function testNoScopeAndNoAuthUri()
{
$testJson = $this->createTestJson();
// no scope, jwt access should be used, no outbound
// call should be made
$scope = null;
$sa = new ServiceAccountCredentials(
$scope,
$testJson
);
$this->assertNotNull($sa);
$update_metadata = $sa->getUpdateMetadataFunc();
$this->assertTrue(is_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]));
}
}

View File

@@ -0,0 +1,228 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\Credentials\UserRefreshCredentials;
use Google\Auth\OAuth2;
use GuzzleHttp\Psr7;
// Creates a standard JSON auth object for testing.
function createURCTestJson()
{
return [
'client_id' => 'client123',
'client_secret' => 'clientSecret123',
'refresh_token' => 'refreshToken123',
'type' => 'authorized_user',
];
}
class URCGetCacheKeyTest extends \PHPUnit_Framework_TestCase
{
public function testShouldBeTheSameAsOAuth2WithTheSameScope()
{
$testJson = createURCTestJson();
$scope = ['scope/1', 'scope/2'];
$sa = new UserRefreshCredentials(
$scope,
$testJson);
$o = new OAuth2(['scope' => $scope]);
$this->assertSame(
$testJson['client_id'] . ':' . $o->getCacheKey(),
$sa->getCacheKey()
);
}
}
class URCConstructorTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfScopeIsNotAValidType()
{
$testJson = createURCTestJson();
$notAnArrayOrString = new \stdClass();
$sa = new UserRefreshCredentials(
$notAnArrayOrString,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfJsonDoesNotHaveClientSecret()
{
$testJson = createURCTestJson();
unset($testJson['client_secret']);
$scope = ['scope/1', 'scope/2'];
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testShouldFailIfJsonDoesNotHaveRefreshToken()
{
$testJson = createURCTestJson();
unset($testJson['refresh_token']);
$scope = ['scope/1', 'scope/2'];
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsToInitalizeFromANonExistentFile()
{
$keyFile = __DIR__ . '/../fixtures' . '/does-not-exist-private.json';
new UserRefreshCredentials('scope/1', $keyFile);
}
public function testInitalizeFromAFile()
{
$keyFile = __DIR__ . '/../fixtures2' . '/private.json';
$this->assertNotNull(
new UserRefreshCredentials('scope/1', $keyFile)
);
}
}
class URCFromEnvTest extends \PHPUnit_Framework_TestCase
{
protected function tearDown()
{
putenv(UserRefreshCredentials::ENV_VAR); // removes it from
}
public function testIsNullIfEnvVarIsNotSet()
{
$this->assertNull(UserRefreshCredentials::fromEnv('a scope'));
}
/**
* @expectedException DomainException
*/
public function testFailsIfEnvSpecifiesNonExistentFile()
{
$keyFile = __DIR__ . '/../fixtures' . '/does-not-exist-private.json';
putenv(UserRefreshCredentials::ENV_VAR . '=' . $keyFile);
UserRefreshCredentials::fromEnv('a scope');
}
public function testSucceedIfFileExists()
{
$keyFile = __DIR__ . '/../fixtures2' . '/private.json';
putenv(UserRefreshCredentials::ENV_VAR . '=' . $keyFile);
$this->assertNotNull(ApplicationDefaultCredentials::getCredentials('a scope'));
}
}
class URCFromWellKnownFileTest extends \PHPUnit_Framework_TestCase
{
private $originalHome;
protected function setUp()
{
$this->originalHome = getenv('HOME');
}
protected function tearDown()
{
if ($this->originalHome != getenv('HOME')) {
putenv('HOME=' . $this->originalHome);
}
}
public function testIsNullIfFileDoesNotExist()
{
putenv('HOME=' . __DIR__ . '/../not_exist_fixtures');
$this->assertNull(
UserRefreshCredentials::fromWellKnownFile('a scope')
);
}
public function testSucceedIfFileIsPresent()
{
putenv('HOME=' . __DIR__ . '/../fixtures2');
$this->assertNotNull(
ApplicationDefaultCredentials::getCredentials('a scope')
);
}
}
class URCFetchAuthTokenTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException GuzzleHttp\Exception\ClientException
*/
public function testFailsOnClientErrors()
{
$testJson = createURCTestJson();
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(400),
]);
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
$sa->fetchAuthToken($httpHandler);
}
/**
* @expectedException GuzzleHttp\Exception\ServerException
*/
public function testFailsOnServerErrors()
{
$testJson = createURCTestJson();
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(500),
]);
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
$sa->fetchAuthToken($httpHandler);
}
public function testCanFetchCredsOK()
{
$testJson = createURCTestJson();
$testJsonText = json_encode($testJson);
$scope = ['scope/1', 'scope/2'];
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($testJsonText)),
]);
$sa = new UserRefreshCredentials(
$scope,
$testJson
);
$tokens = $sa->fetchAuthToken($httpHandler);
$this->assertEquals($testJson, $tokens);
}
}

View File

@@ -0,0 +1,146 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\tests;
use Google\Auth\FetchAuthTokenCache;
class FetchAuthTokenCacheTest extends BaseTest
{
protected function setUp()
{
$this->mockFetcher =
$this
->getMockBuilder('Google\Auth\FetchAuthTokenInterface')
->getMock();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
}
public function testUsesCachedAuthToken()
{
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
null,
$this->mockCache
);
$accessToken = $cachedFetcher->fetchAuthToken();
$this->assertEquals($accessToken, ['access_token' => $cachedValue]);
}
public function testGetsCachedAuthTokenUsingCachePrefix()
{
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
// Run the test
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix],
$this->mockCache
);
$accessToken = $cachedFetcher->fetchAuthToken();
$this->assertEquals($accessToken, ['access_token' => $cachedValue]);
}
public function testShouldSaveValueInCacheWithCacheOptions()
{
$prefix = 'test_prefix_';
$lifetime = '70707';
$cacheKey = 'myKey';
$token = '1/abcdef1234567890';
$authResult = ['access_token' => $token];
$this->mockCacheItem
->expects($this->any())
->method('get')
->will($this->returnValue(null));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('expiresAfter')
->with($this->equalTo($lifetime));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
// Run the test
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix, 'lifetime' => $lifetime],
$this->mockCache
);
$accessToken = $cachedFetcher->fetchAuthToken();
$this->assertEquals($accessToken, ['access_token' => $token]);
}
}

View File

@@ -0,0 +1,170 @@
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\tests;
use Google\Auth\Credentials\AppIdentityCredentials;
use Google\Auth\Credentials\GCECredentials;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Credentials\ServiceAccountJwtAccessCredentials;
use Google\Auth\Credentials\UserRefreshCredentials;
use Google\Auth\CredentialsLoader;
use Google\Auth\FetchAuthTokenInterface;
use Google\Auth\OAuth2;
class FetchAuthTokenTest extends BaseTest
{
/** @dataProvider provideAuthTokenFetcher */
public function testGetLastReceivedToken(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']);
}
public function provideAuthTokenFetcher()
{
$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()],
];
}
private function getAppIdentityCredentials()
{
$class = new \ReflectionClass(
'Google\Auth\Credentials\AppIdentityCredentials'
);
$property = $class->getProperty('lastReceivedToken');
$property->setAccessible(true);
$credentials = new AppIdentityCredentials();
$property->setValue($credentials, [
'access_token' => 'xyz',
'expiration_time' => strtotime('2001'),
]);
return $credentials;
}
private function getGCECredentials()
{
$class = new \ReflectionClass(
'Google\Auth\Credentials\GCECredentials'
);
$property = $class->getProperty('lastReceivedToken');
$property->setAccessible(true);
$credentials = new GCECredentials();
$property->setValue($credentials, [
'access_token' => 'xyz',
'expires_at' => strtotime('2001'),
]);
return $credentials;
}
private function getServiceAccountCredentials($scopes, $jsonPath)
{
$class = new \ReflectionClass(
'Google\Auth\Credentials\ServiceAccountCredentials'
);
$property = $class->getProperty('auth');
$property->setAccessible(true);
$credentials = new ServiceAccountCredentials($scopes, $jsonPath);
$property->setValue($credentials, $this->getOAuth2Mock());
return $credentials;
}
private function getServiceAccountJwtAccessCredentials($jsonPath)
{
$class = new \ReflectionClass(
'Google\Auth\Credentials\ServiceAccountJwtAccessCredentials'
);
$property = $class->getProperty('auth');
$property->setAccessible(true);
$credentials = new ServiceAccountJwtAccessCredentials($jsonPath);
$property->setValue($credentials, $this->getOAuth2Mock());
return $credentials;
}
private function getUserRefreshCredentials($scopes, $jsonPath)
{
$class = new \ReflectionClass(
'Google\Auth\Credentials\UserRefreshCredentials'
);
$property = $class->getProperty('auth');
$property->setAccessible(true);
$credentials = new UserRefreshCredentials($scopes, $jsonPath);
$property->setValue($credentials, $this->getOAuth2Mock());
return $credentials;
}
private function getOAuth2()
{
$oauth = new OAuth2([
'access_token' => 'xyz',
'expires_at' => strtotime('2001'),
]);
return $oauth;
}
private function getOAuth2Mock()
{
$mock = $this->getMockBuilder('Google\Auth\OAuth2')
->disableOriginalConstructor()
->getMock();
$mock
->expects($this->once())
->method('getLastReceivedToken')
->will($this->returnValue([
'access_token' => 'xyz',
'expires_at' => strtotime('2001'),
]));
return $mock;
}
}

View File

@@ -0,0 +1,59 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\HttpHandler\Guzzle5HttpHandler;
use GuzzleHttp\Message\Response;
class Guzzle5HttpHandlerTest extends BaseTest
{
public function setUp()
{
$this->onlyGuzzle5();
$this->mockPsr7Request =
$this
->getMockBuilder('Psr\Http\Message\RequestInterface')
->getMock();
$this->mockRequest =
$this
->getMockBuilder('GuzzleHttp\Message\RequestInterface')
->getMock();
$this->mockClient =
$this
->getMockBuilder('GuzzleHttp\Client')
->disableOriginalConstructor()
->getMock();
}
public function testSuccessfullySendsRequest()
{
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue(new Response(200)));
$this->mockClient
->expects($this->any())
->method('createRequest')
->will($this->returnValue($this->mockRequest));
$handler = new Guzzle5HttpHandler($this->mockClient);
$response = $handler($this->mockPsr7Request);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
}
}

View File

@@ -0,0 +1,50 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\HttpHandler\Guzzle6HttpHandler;
use GuzzleHttp\Psr7\Response;
class Guzzle6HttpHandlerTest extends BaseTest
{
public function setUp()
{
$this->onlyGuzzle6();
$this->mockRequest =
$this
->getMockBuilder('Psr\Http\Message\RequestInterface')
->getMock();
$this->mockClient =
$this
->getMockBuilder('GuzzleHttp\Client')
->getMock();
}
public function testSuccessfullySendsRequest()
{
$this->mockClient
->expects($this->any())
->method('send')
->will($this->returnValue(new Response(200)));
$handler = new Guzzle6HttpHandler($this->mockClient);
$response = $handler($this->mockRequest);
$this->assertInstanceOf('Psr\Http\Message\ResponseInterface', $response);
}
}

View File

@@ -0,0 +1,39 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\HttpHandler\HttpHandlerFactory;
class HttpHandlerFactoryTest extends BaseTest
{
public function testBuildsGuzzle5Handler()
{
$this->onlyGuzzle5();
$handler = HttpHandlerFactory::build();
$this->assertInstanceOf('Google\Auth\HttpHandler\Guzzle5HttpHandler', $handler);
}
public function testBuildsGuzzle6Handler()
{
$this->onlyGuzzle6();
$handler = HttpHandlerFactory::build();
$this->assertInstanceOf('Google\Auth\HttpHandler\Guzzle6HttpHandler', $handler);
}
}

View File

@@ -0,0 +1,336 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\FetchAuthTokenCache;
use Google\Auth\Middleware\AuthTokenMiddleware;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Psr7\Response;
class AuthTokenMiddlewareTest extends BaseTest
{
private $mockFetcher;
private $mockCacheItem;
private $mockCache;
private $mockRequest;
protected function setUp()
{
$this->onlyGuzzle6();
$this->mockFetcher =
$this
->getMockBuilder('Google\Auth\FetchAuthTokenInterface')
->getMock();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
$this->mockRequest =
$this
->getMockBuilder('GuzzleHttp\Psr7\Request')
->disableOriginalConstructor()
->getMock();
}
public function testOnlyTouchesWhenAuthConfigScoped()
{
$this->mockFetcher
->expects($this->any())
->method('fetchAuthToken')
->will($this->returnValue([]));
$this->mockRequest
->expects($this->never())
->method('withHeader');
$middleware = new AuthTokenMiddleware($this->mockFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'not_google_auth']);
}
public function testAddsTheTokenAsAnAuthorizationHeader()
{
$authResult = ['access_token' => '1/abcdef1234567890'];
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $authResult['access_token'])
->will($this->returnValue($this->mockRequest));
// Run the test.
$middleware = new AuthTokenMiddleware($this->mockFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
}
public function testDoesNotAddAnAuthorizationHeaderOnNoAccessToken()
{
$authResult = ['not_access_token' => '1/abcdef1234567890'];
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ')
->will($this->returnValue($this->mockRequest));
// Run the test.
$middleware = new AuthTokenMiddleware($this->mockFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
}
public function testUsesCachedAuthToken()
{
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
null,
$this->mockCache
);
$middleware = new AuthTokenMiddleware($cachedFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
}
public function testGetsCachedAuthTokenUsingCacheOptions()
{
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix],
$this->mockCache
);
$middleware = new AuthTokenMiddleware($cachedFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
}
public function testShouldSaveValueInCacheWithSpecifiedPrefix()
{
$prefix = 'test_prefix_';
$lifetime = '70707';
$cacheKey = 'myKey';
$token = '1/abcdef1234567890';
$authResult = ['access_token' => $token];
$this->mockCacheItem
->expects($this->any())
->method('get')
->will($this->returnValue(null));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('expiresAfter')
->with($this->equalTo($lifetime));
$this->mockCache
->expects($this->any())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix, 'lifetime' => $lifetime],
$this->mockCache
);
$middleware = new AuthTokenMiddleware($cachedFetcher);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
}
/** @dataProvider provideShouldNotifyTokenCallback */
public function testShouldNotifyTokenCallback(callable $tokenCallback)
{
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$token = '1/abcdef1234567890';
$authResult = ['access_token' => $token];
$this->mockCacheItem
->expects($this->any())
->method('get')
->will($this->returnValue(null));
$this->mockCache
->expects($this->any())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->will($this->returnValue($this->mockRequest));
MiddlewareCallback::$expectedKey = $this->getValidKeyName($prefix . $cacheKey);
MiddlewareCallback::$expectedValue = $token;
MiddlewareCallback::$called = false;
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix],
$this->mockCache
);
$middleware = new AuthTokenMiddleware(
$cachedFetcher,
null,
$tokenCallback
);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'google_auth']);
$this->assertTrue(MiddlewareCallback::$called);
}
public function provideShouldNotifyTokenCallback()
{
MiddlewareCallback::$phpunit = $this;
$anonymousFunc = function ($key, $value) {
MiddlewareCallback::staticInvoke($key, $value);
};
return [
['Google\Auth\Tests\MiddlewareCallbackFunction'],
['Google\Auth\Tests\MiddlewareCallback::staticInvoke'],
[['Google\Auth\Tests\MiddlewareCallback', 'staticInvoke']],
[$anonymousFunc],
[[new MiddlewareCallback, 'staticInvoke']],
[[new MiddlewareCallback, 'methodInvoke']],
[new MiddlewareCallback],
];
}
}
class MiddlewareCallback
{
public static $phpunit;
public static $expectedKey;
public static $expectedValue;
public static $called = false;
public function __invoke($key, $value)
{
self::$phpunit->assertEquals(self::$expectedKey, $key);
self::$phpunit->assertEquals(self::$expectedValue, $value);
self::$called = true;
}
public function methodInvoke($key, $value)
{
return $this($key, $value);
}
public static function staticInvoke($key, $value)
{
$instance = new self();
return $instance($key, $value);
}
}
function MiddlewareCallbackFunction($key, $value)
{
return MiddlewareCallback::staticInvoke($key, $value);
}

View File

@@ -0,0 +1,245 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\Middleware\ScopedAccessTokenMiddleware;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Psr7\Response;
class ScopedAccessTokenMiddlewareTest extends BaseTest
{
const TEST_SCOPE = 'https://www.googleapis.com/auth/cloud-taskqueue';
private $mockCacheItem;
private $mockCache;
private $mockRequest;
protected function setUp()
{
$this->onlyGuzzle6();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
$this->mockRequest =
$this
->getMockBuilder('GuzzleHttp\Psr7\Request')
->disableOriginalConstructor()
->getMock();
}
/**
* @expectedException InvalidArgumentException
*/
public function testRequiresScopeAsAStringOrArray()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
new ScopedAccessTokenMiddleware($fakeAuthFunc, new \stdClass());
}
public function testAddsTheTokenAsAnAuthorizationHeader()
{
$token = '1/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) use ($token) {
return $token;
};
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test
$middleware = new ScopedAccessTokenMiddleware($fakeAuthFunc, self::TEST_SCOPE);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'scoped']);
}
public function testUsesCachedAuthToken()
{
$cachedValue = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($this->getValidKeyName(self::TEST_SCOPE)))
->will($this->returnValue($this->mockCacheItem));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test
$middleware = new ScopedAccessTokenMiddleware(
$fakeAuthFunc,
self::TEST_SCOPE,
[],
$this->mockCache
);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'scoped']);
}
public function testGetsCachedAuthTokenUsingCachePrefix()
{
$prefix = 'test_prefix_';
$cachedValue = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($prefix . $this->getValidKeyName(self::TEST_SCOPE)))
->will($this->returnValue($this->mockCacheItem));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $cachedValue)
->will($this->returnValue($this->mockRequest));
// Run the test
$middleware = new ScopedAccessTokenMiddleware(
$fakeAuthFunc,
self::TEST_SCOPE,
['prefix' => $prefix],
$this->mockCache
);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'scoped']);
}
public function testShouldSaveValueInCache()
{
$token = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) use ($token) {
return $token;
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($this->equalTo($this->getValidKeyName(self::TEST_SCOPE)))
->will($this->returnValue($this->mockCacheItem));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test
$middleware = new ScopedAccessTokenMiddleware(
$fakeAuthFunc,
self::TEST_SCOPE,
[],
$this->mockCache
);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'scoped']);
}
public function testShouldSaveValueInCacheWithCacheOptions()
{
$token = '2/abcdef1234567890';
$prefix = 'test_prefix_';
$lifetime = '70707';
$fakeAuthFunc = function ($unused_scopes) use ($token) {
return $token;
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('expiresAfter')
->with($this->equalTo($lifetime));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($this->equalTo($prefix . $this->getValidKeyName(self::TEST_SCOPE)))
->will($this->returnValue($this->mockCacheItem));
$this->mockRequest
->expects($this->once())
->method('withHeader')
->with('Authorization', 'Bearer ' . $token)
->will($this->returnValue($this->mockRequest));
// Run the test
$middleware = new ScopedAccessTokenMiddleware(
$fakeAuthFunc,
self::TEST_SCOPE,
['prefix' => $prefix, 'lifetime' => $lifetime],
$this->mockCache
);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'scoped']);
}
public function testOnlyTouchesWhenAuthConfigScoped()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
$this->mockRequest
->expects($this->never())
->method('withHeader');
// Run the test
$middleware = new ScopedAccessTokenMiddleware($fakeAuthFunc, self::TEST_SCOPE);
$mock = new MockHandler([new Response(200)]);
$callable = $middleware($mock);
$callable($this->mockRequest, ['auth' => 'not_scoped']);
}
}

View File

@@ -0,0 +1,41 @@
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
class SimpleMiddlewareTest extends BaseTest
{
private $mockRequest;
/**
* @todo finish
*/
protected function setUp()
{
$this->onlyGuzzle6();
$this->mockRequest =
$this
->getMockBuilder('GuzzleHttp\Psr7\Request')
->disableOriginalConstructor()
->getMock();
}
public function testTest()
{
}
}

858
vendor/google/auth/tests/OAuth2Test.php vendored Normal file
View File

@@ -0,0 +1,858 @@
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\OAuth2;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Response;
class OAuth2AuthorizationUriTest extends \PHPUnit_Framework_TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
'clientId' => 'aClientID',
];
/**
* @expectedException InvalidArgumentException
*/
public function testIsNullIfAuthorizationUriIsNull()
{
$o = new OAuth2([]);
$this->assertNull($o->buildFullAuthorizationUri());
}
/**
* @expectedException InvalidArgumentException
*/
public function testRequiresTheClientId()
{
$o = new OAuth2([
'authorizationUri' => 'https://accounts.test.org/auth/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
]);
$o->buildFullAuthorizationUri();
}
/**
* @expectedException InvalidArgumentException
*/
public function testRequiresTheRedirectUri()
{
$o = new OAuth2([
'authorizationUri' => 'https://accounts.test.org/auth/url',
'clientId' => 'aClientID',
]);
$o->buildFullAuthorizationUri();
}
/**
* @expectedException InvalidArgumentException
*/
public function testCannotHavePromptAndApprovalPrompt()
{
$o = new OAuth2([
'authorizationUri' => 'https://accounts.test.org/auth/url',
'clientId' => 'aClientID',
]);
$o->buildFullAuthorizationUri([
'approval_prompt' => 'an approval prompt',
'prompt' => 'a prompt',
]);
}
/**
* @expectedException InvalidArgumentException
*/
public function testCannotHaveInsecureAuthorizationUri()
{
$o = new OAuth2([
'authorizationUri' => 'http://accounts.test.org/insecure/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
'clientId' => 'aClientID',
]);
$o->buildFullAuthorizationUri();
}
/**
* @expectedException InvalidArgumentException
*/
public function testCannotHaveRelativeRedirectUri()
{
$o = new OAuth2([
'authorizationUri' => 'http://accounts.test.org/insecure/url',
'redirectUri' => '/redirect/url',
'clientId' => 'aClientID',
]);
$o->buildFullAuthorizationUri();
}
public function testHasDefaultXXXTypeParams()
{
$o = new OAuth2($this->minimal);
$q = Psr7\parse_query($o->buildFullAuthorizationUri()->getQuery());
$this->assertEquals('code', $q['response_type']);
$this->assertEquals('offline', $q['access_type']);
}
public function testCanBeUrlObject()
{
$config = array_merge($this->minimal, [
'authorizationUri' => Psr7\uri_for('https://another/uri'),
]);
$o = new OAuth2($config);
$this->assertEquals('/uri', $o->buildFullAuthorizationUri()->getPath());
}
public function testCanOverrideParams()
{
$overrides = [
'access_type' => 'o_access_type',
'client_id' => 'o_client_id',
'redirect_uri' => 'o_redirect_uri',
'response_type' => 'o_response_type',
'state' => 'o_state',
];
$config = array_merge($this->minimal, ['state' => 'the_state']);
$o = new OAuth2($config);
$q = Psr7\parse_query($o->buildFullAuthorizationUri($overrides)->getQuery());
$this->assertEquals('o_access_type', $q['access_type']);
$this->assertEquals('o_client_id', $q['client_id']);
$this->assertEquals('o_redirect_uri', $q['redirect_uri']);
$this->assertEquals('o_response_type', $q['response_type']);
$this->assertEquals('o_state', $q['state']);
}
public function testIncludesTheScope()
{
$with_strings = array_merge($this->minimal, ['scope' => 'scope1 scope2']);
$o = new OAuth2($with_strings);
$q = Psr7\parse_query($o->buildFullAuthorizationUri()->getQuery());
$this->assertEquals('scope1 scope2', $q['scope']);
$with_array = array_merge($this->minimal, [
'scope' => ['scope1', 'scope2'],
]);
$o = new OAuth2($with_array);
$q = Psr7\parse_query($o->buildFullAuthorizationUri()->getQuery());
$this->assertEquals('scope1 scope2', $q['scope']);
}
public function testRedirectUriPostmessageIsAllowed()
{
$o = new OAuth2([
'authorizationUri' => 'https://accounts.test.org/insecure/url',
'redirectUri' => 'postmessage',
'clientId' => 'aClientID',
]);
$this->assertEquals('postmessage', $o->getRedirectUri());
$url = $o->buildFullAuthorizationUri();
$parts = parse_url((string)$url);
parse_str($parts['query'], $query);
$this->assertArrayHasKey('redirect_uri', $query);
$this->assertEquals('postmessage', $query['redirect_uri']);
}
}
class OAuth2GrantTypeTest extends \PHPUnit_Framework_TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
'clientId' => 'aClientID',
];
public function testReturnsNullIfCannotBeInferred()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getGrantType());
}
public function testInfersAuthorizationCode()
{
$o = new OAuth2($this->minimal);
$o->setCode('an auth code');
$this->assertEquals('authorization_code', $o->getGrantType());
}
public function testInfersRefreshToken()
{
$o = new OAuth2($this->minimal);
$o->setRefreshToken('a refresh token');
$this->assertEquals('refresh_token', $o->getGrantType());
}
public function testInfersPassword()
{
$o = new OAuth2($this->minimal);
$o->setPassword('a password');
$o->setUsername('a username');
$this->assertEquals('password', $o->getGrantType());
}
public function testInfersJwtBearer()
{
$o = new OAuth2($this->minimal);
$o->setIssuer('an issuer');
$o->setSigningKey('a key');
$this->assertEquals('urn:ietf:params:oauth:grant-type:jwt-bearer',
$o->getGrantType());
}
public function testSetsKnownTypes()
{
$o = new OAuth2($this->minimal);
foreach (OAuth2::$knownGrantTypes as $t) {
$o->setGrantType($t);
$this->assertEquals($t, $o->getGrantType());
}
}
public function testSetsUrlAsGrantType()
{
$o = new OAuth2($this->minimal);
$o->setGrantType('http://a/grant/url');
$this->assertEquals('http://a/grant/url', $o->getGrantType());
}
}
class OAuth2GetCacheKeyTest extends \PHPUnit_Framework_TestCase
{
private $minimal = [
'clientID' => 'aClientID',
];
public function testIsNullWithNoScopes()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getCacheKey());
}
public function testIsScopeIfSingleScope()
{
$o = new OAuth2($this->minimal);
$o->setScope('test/scope/1');
$this->assertEquals('test/scope/1', $o->getCacheKey());
}
public function testIsAllScopesWhenScopeIsArray()
{
$o = new OAuth2($this->minimal);
$o->setScope(['test/scope/1', 'test/scope/2']);
$this->assertEquals('test/scope/1:test/scope/2', $o->getCacheKey());
}
}
class OAuth2TimingTest extends \PHPUnit_Framework_TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
'clientId' => 'aClientID',
];
public function testIssuedAtDefaultsToNull()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getIssuedAt());
}
public function testExpiresAtDefaultsToNull()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getExpiresAt());
}
public function testExpiresInDefaultsToNull()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getExpiresIn());
}
public function testSettingExpiresInSetsIssuedAt()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getIssuedAt());
$aShortWhile = 5;
$o->setExpiresIn($aShortWhile);
$this->assertEquals($aShortWhile, $o->getExpiresIn());
$this->assertNotNull($o->getIssuedAt());
}
public function testSettingExpiresInSetsExpireAt()
{
$o = new OAuth2($this->minimal);
$this->assertNull($o->getExpiresAt());
$aShortWhile = 5;
$o->setExpiresIn($aShortWhile);
$this->assertNotNull($o->getExpiresAt());
$this->assertEquals($aShortWhile, $o->getExpiresAt() - $o->getIssuedAt());
}
public function testIsNotExpiredByDefault()
{
$o = new OAuth2($this->minimal);
$this->assertFalse($o->isExpired());
}
public function testIsNotExpiredIfExpiresAtIsOld()
{
$o = new OAuth2($this->minimal);
$o->setExpiresAt(time() - 2);
$this->assertTrue($o->isExpired());
}
}
class OAuth2GeneralTest extends \PHPUnit_Framework_TestCase
{
private $minimal = [
'authorizationUri' => 'https://accounts.test.org/insecure/url',
'redirectUri' => 'https://accounts.test.org/redirect/url',
'clientId' => 'aClientID',
];
/**
* @expectedException InvalidArgumentException
*/
public function testFailsOnUnknownSigningAlgorithm()
{
$o = new OAuth2($this->minimal);
$o->setSigningAlgorithm('this is definitely not an algorithm name');
}
public function testAllowsKnownSigningAlgorithms()
{
$o = new OAuth2($this->minimal);
foreach (OAuth2::$knownSigningAlgorithms as $a) {
$o->setSigningAlgorithm($a);
$this->assertEquals($a, $o->getSigningAlgorithm());
}
}
/**
* @expectedException InvalidArgumentException
*/
public function testFailsOnRelativeRedirectUri()
{
$o = new OAuth2($this->minimal);
$o->setRedirectUri('/relative/url');
}
public function testAllowsUrnRedirectUri()
{
$urn = 'urn:ietf:wg:oauth:2.0:oob';
$o = new OAuth2($this->minimal);
$o->setRedirectUri($urn);
$this->assertEquals($urn, $o->getRedirectUri());
}
}
class OAuth2JwtTest extends \PHPUnit_Framework_TestCase
{
private $signingMinimal = [
'signingKey' => 'example_key',
'signingAlgorithm' => 'HS256',
'scope' => 'https://www.googleapis.com/auth/userinfo.profile',
'issuer' => 'app@example.com',
'audience' => 'accounts.google.com',
'clientId' => 'aClientID',
];
/**
* @expectedException DomainException
*/
public function testFailsWithMissingAudience()
{
$testConfig = $this->signingMinimal;
unset($testConfig['audience']);
$o = new OAuth2($testConfig);
$o->toJwt();
}
/**
* @expectedException DomainException
*/
public function testFailsWithMissingIssuer()
{
$testConfig = $this->signingMinimal;
unset($testConfig['issuer']);
$o = new OAuth2($testConfig);
$o->toJwt();
}
/**
*/
public function testCanHaveNoScope()
{
$testConfig = $this->signingMinimal;
unset($testConfig['scope']);
$o = new OAuth2($testConfig);
$o->toJwt();
}
/**
* @expectedException DomainException
*/
public function testFailsWithMissingSigningKey()
{
$testConfig = $this->signingMinimal;
unset($testConfig['signingKey']);
$o = new OAuth2($testConfig);
$o->toJwt();
}
/**
* @expectedException DomainException
*/
public function testFailsWithMissingSigningAlgorithm()
{
$testConfig = $this->signingMinimal;
unset($testConfig['signingAlgorithm']);
$o = new OAuth2($testConfig);
$o->toJwt();
}
public function testCanHS256EncodeAValidPayload()
{
$testConfig = $this->signingMinimal;
$o = new OAuth2($testConfig);
$payload = $o->toJwt();
$roundTrip = $this->jwtDecode($payload, $testConfig['signingKey'], array('HS256'));
$this->assertEquals($roundTrip->iss, $testConfig['issuer']);
$this->assertEquals($roundTrip->aud, $testConfig['audience']);
$this->assertEquals($roundTrip->scope, $testConfig['scope']);
}
public function testCanRS256EncodeAValidPayload()
{
$publicKey = file_get_contents(__DIR__ . '/fixtures' . '/public.pem');
$privateKey = file_get_contents(__DIR__ . '/fixtures' . '/private.pem');
$testConfig = $this->signingMinimal;
$o = new OAuth2($testConfig);
$o->setSigningAlgorithm('RS256');
$o->setSigningKey($privateKey);
$payload = $o->toJwt();
$roundTrip = $this->jwtDecode($payload, $publicKey, array('RS256'));
$this->assertEquals($roundTrip->iss, $testConfig['issuer']);
$this->assertEquals($roundTrip->aud, $testConfig['audience']);
$this->assertEquals($roundTrip->scope, $testConfig['scope']);
}
private function jwtDecode()
{
$args = func_get_args();
$class = 'JWT';
if (class_exists('Firebase\JWT\JWT')) {
$class = 'Firebase\JWT\JWT';
}
return call_user_func_array("$class::decode", $args);
}
}
class OAuth2GenerateAccessTokenRequestTest extends \PHPUnit_Framework_TestCase
{
private $tokenRequestMinimal = [
'tokenCredentialUri' => 'https://tokens_r_us/test',
'scope' => 'https://www.googleapis.com/auth/userinfo.profile',
'issuer' => 'app@example.com',
'audience' => 'accounts.google.com',
'clientId' => 'aClientID',
];
/**
* @expectedException DomainException
*/
public function testFailsIfNoTokenCredentialUri()
{
$testConfig = $this->tokenRequestMinimal;
unset($testConfig['tokenCredentialUri']);
$o = new OAuth2($testConfig);
$o->generateCredentialsRequest();
}
/**
* @expectedException DomainException
*/
public function testFailsIfAuthorizationCodeIsMissing()
{
$testConfig = $this->tokenRequestMinimal;
$testConfig['redirectUri'] = 'https://has/redirect/uri';
$o = new OAuth2($testConfig);
$o->generateCredentialsRequest();
}
public function testGeneratesAuthorizationCodeRequests()
{
$testConfig = $this->tokenRequestMinimal;
$testConfig['redirectUri'] = 'https://has/redirect/uri';
$o = new OAuth2($testConfig);
$o->setCode('an_auth_code');
// Generate the request and confirm that it's correct.
$req = $o->generateCredentialsRequest();
$this->assertInstanceOf('Psr\Http\Message\RequestInterface', $req);
$this->assertEquals('POST', $req->getMethod());
$fields = Psr7\parse_query((string)$req->getBody());
$this->assertEquals('authorization_code', $fields['grant_type']);
$this->assertEquals('an_auth_code', $fields['code']);
}
public function testGeneratesPasswordRequests()
{
$testConfig = $this->tokenRequestMinimal;
$o = new OAuth2($testConfig);
$o->setUsername('a_username');
$o->setPassword('a_password');
// Generate the request and confirm that it's correct.
$req = $o->generateCredentialsRequest();
$this->assertInstanceOf('Psr\Http\Message\RequestInterface', $req);
$this->assertEquals('POST', $req->getMethod());
$fields = Psr7\parse_query((string)$req->getBody());
$this->assertEquals('password', $fields['grant_type']);
$this->assertEquals('a_password', $fields['password']);
$this->assertEquals('a_username', $fields['username']);
}
public function testGeneratesRefreshTokenRequests()
{
$testConfig = $this->tokenRequestMinimal;
$o = new OAuth2($testConfig);
$o->setRefreshToken('a_refresh_token');
// Generate the request and confirm that it's correct.
$req = $o->generateCredentialsRequest();
$this->assertInstanceOf('Psr\Http\Message\RequestInterface', $req);
$this->assertEquals('POST', $req->getMethod());
$fields = Psr7\parse_query((string)$req->getBody());
$this->assertEquals('refresh_token', $fields['grant_type']);
$this->assertEquals('a_refresh_token', $fields['refresh_token']);
}
public function testClientSecretAddedIfSetForAuthorizationCodeRequests()
{
$testConfig = $this->tokenRequestMinimal;
$testConfig['clientSecret'] = 'a_client_secret';
$testConfig['redirectUri'] = 'https://has/redirect/uri';
$o = new OAuth2($testConfig);
$o->setCode('an_auth_code');
$request = $o->generateCredentialsRequest();
$fields = Psr7\parse_query((string)$request->getBody());
$this->assertEquals('a_client_secret', $fields['client_secret']);
}
public function testClientSecretAddedIfSetForRefreshTokenRequests()
{
$testConfig = $this->tokenRequestMinimal;
$testConfig['clientSecret'] = 'a_client_secret';
$o = new OAuth2($testConfig);
$o->setRefreshToken('a_refresh_token');
$request = $o->generateCredentialsRequest();
$fields = Psr7\parse_query((string)$request->getBody());
$this->assertEquals('a_client_secret', $fields['client_secret']);
}
public function testClientSecretAddedIfSetForPasswordRequests()
{
$testConfig = $this->tokenRequestMinimal;
$testConfig['clientSecret'] = 'a_client_secret';
$o = new OAuth2($testConfig);
$o->setUsername('a_username');
$o->setPassword('a_password');
$request = $o->generateCredentialsRequest();
$fields = Psr7\parse_query((string)$request->getBody());
$this->assertEquals('a_client_secret', $fields['client_secret']);
}
public function testGeneratesAssertionRequests()
{
$testConfig = $this->tokenRequestMinimal;
$o = new OAuth2($testConfig);
$o->setSigningKey('a_key');
$o->setSigningAlgorithm('HS256');
// Generate the request and confirm that it's correct.
$req = $o->generateCredentialsRequest();
$this->assertInstanceOf('Psr\Http\Message\RequestInterface', $req);
$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));
}
public function testGeneratesExtendedRequests()
{
$testConfig = $this->tokenRequestMinimal;
$o = new OAuth2($testConfig);
$o->setGrantType('urn:my_test_grant_type');
$o->setExtensionParams(['my_param' => 'my_value']);
// Generate the request and confirm that it's correct.
$req = $o->generateCredentialsRequest();
$this->assertInstanceOf('Psr\Http\Message\RequestInterface', $req);
$this->assertEquals('POST', $req->getMethod());
$fields = Psr7\parse_query((string)$req->getBody());
$this->assertEquals('my_value', $fields['my_param']);
$this->assertEquals('urn:my_test_grant_type', $fields['grant_type']);
}
}
class OAuth2FetchAuthTokenTest extends \PHPUnit_Framework_TestCase
{
private $fetchAuthTokenMinimal = [
'tokenCredentialUri' => 'https://tokens_r_us/test',
'scope' => 'https://www.googleapis.com/auth/userinfo.profile',
'signingKey' => 'example_key',
'signingAlgorithm' => 'HS256',
'issuer' => 'app@example.com',
'audience' => 'accounts.google.com',
'clientId' => 'aClientID',
];
/**
* @expectedException GuzzleHttp\Exception\ClientException
*/
public function testFailsOn400()
{
$testConfig = $this->fetchAuthTokenMinimal;
$httpHandler = getHandler([
buildResponse(400),
]);
$o = new OAuth2($testConfig);
$o->fetchAuthToken($httpHandler);
}
/**
* @expectedException GuzzleHttp\Exception\ServerException
*/
public function testFailsOn500()
{
$testConfig = $this->fetchAuthTokenMinimal;
$httpHandler = getHandler([
buildResponse(500),
]);
$o = new OAuth2($testConfig);
$o->fetchAuthToken($httpHandler);
}
/**
* @expectedException Exception
* @expectedExceptionMessage Invalid JSON response
*/
public function testFailsOnNoContentTypeIfResponseIsNotJSON()
{
$testConfig = $this->fetchAuthTokenMinimal;
$notJson = '{"foo": , this is cannot be passed as json" "bar"}';
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($notJson)),
]);
$o = new OAuth2($testConfig);
$o->fetchAuthToken($httpHandler);
}
public function testFetchesJsonResponseOnNoContentTypeOK()
{
$testConfig = $this->fetchAuthTokenMinimal;
$json = '{"foo": "bar"}';
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($json)),
]);
$o = new OAuth2($testConfig);
$tokens = $o->fetchAuthToken($httpHandler);
$this->assertEquals($tokens['foo'], 'bar');
}
public function testFetchesFromFormEncodedResponseOK()
{
$testConfig = $this->fetchAuthTokenMinimal;
$json = 'foo=bar&spice=nice';
$httpHandler = getHandler([
buildResponse(
200,
['Content-Type' => 'application/x-www-form-urlencoded'],
Psr7\stream_for($json)
),
]);
$o = new OAuth2($testConfig);
$tokens = $o->fetchAuthToken($httpHandler);
$this->assertEquals($tokens['foo'], 'bar');
$this->assertEquals($tokens['spice'], 'nice');
}
public function testUpdatesTokenFieldsOnFetch()
{
$testConfig = $this->fetchAuthTokenMinimal;
$wanted_updates = [
'expires_at' => '1',
'expires_in' => '57',
'issued_at' => '2',
'access_token' => 'an_access_token',
'id_token' => 'an_id_token',
'refresh_token' => 'a_refresh_token',
];
$json = json_encode($wanted_updates);
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($json)),
]);
$o = new OAuth2($testConfig);
$this->assertNull($o->getExpiresAt());
$this->assertNull($o->getExpiresIn());
$this->assertNull($o->getIssuedAt());
$this->assertNull($o->getAccessToken());
$this->assertNull($o->getIdToken());
$this->assertNull($o->getRefreshToken());
$tokens = $o->fetchAuthToken($httpHandler);
$this->assertEquals(1, $o->getExpiresAt());
$this->assertEquals(57, $o->getExpiresIn());
$this->assertEquals(2, $o->getIssuedAt());
$this->assertEquals('an_access_token', $o->getAccessToken());
$this->assertEquals('an_id_token', $o->getIdToken());
$this->assertEquals('a_refresh_token', $o->getRefreshToken());
}
public function testUpdatesTokenFieldsOnFetchMissingRefreshToken()
{
$testConfig = $this->fetchAuthTokenMinimal;
$testConfig['refresh_token'] = 'a_refresh_token';
$wanted_updates = [
'expires_at' => '1',
'expires_in' => '57',
'issued_at' => '2',
'access_token' => 'an_access_token',
'id_token' => 'an_id_token',
];
$json = json_encode($wanted_updates);
$httpHandler = getHandler([
buildResponse(200, [], Psr7\stream_for($json)),
]);
$o = new OAuth2($testConfig);
$this->assertNull($o->getExpiresAt());
$this->assertNull($o->getExpiresIn());
$this->assertNull($o->getIssuedAt());
$this->assertNull($o->getAccessToken());
$this->assertNull($o->getIdToken());
$this->assertEquals('a_refresh_token', $o->getRefreshToken());
$tokens = $o->fetchAuthToken($httpHandler);
$this->assertEquals(1, $o->getExpiresAt());
$this->assertEquals(57, $o->getExpiresIn());
$this->assertEquals(2, $o->getIssuedAt());
$this->assertEquals('an_access_token', $o->getAccessToken());
$this->assertEquals('an_id_token', $o->getIdToken());
$this->assertEquals('a_refresh_token', $o->getRefreshToken());
}
}
class OAuth2VerifyIdTokenTest extends \PHPUnit_Framework_TestCase
{
private $publicKey;
private $privateKey;
private $verifyIdTokenMinimal = [
'scope' => 'https://www.googleapis.com/auth/userinfo.profile',
'audience' => 'myaccount.on.host.issuer.com',
'issuer' => 'an.issuer.com',
'clientId' => 'myaccount.on.host.issuer.com',
];
public function setUp()
{
$this->publicKey =
file_get_contents(__DIR__ . '/fixtures' . '/public.pem');
$this->privateKey =
file_get_contents(__DIR__ . '/fixtures' . '/private.pem');
}
/**
* @expectedException UnexpectedValueException
*/
public function testFailsIfIdTokenIsInvalid()
{
$testConfig = $this->verifyIdTokenMinimal;
$not_a_jwt = 'not a jot';
$o = new OAuth2($testConfig);
$o->setIdToken($not_a_jwt);
$o->verifyIdToken($this->publicKey);
}
/**
* @expectedException DomainException
*/
public function testFailsIfAudienceIsMissing()
{
$testConfig = $this->verifyIdTokenMinimal;
$now = time();
$origIdToken = [
'issuer' => $testConfig['issuer'],
'exp' => $now + 65, // arbitrary
'iat' => $now,
];
$o = new OAuth2($testConfig);
$jwtIdToken = $this->jwtEncode($origIdToken, $this->privateKey, 'RS256');
$o->setIdToken($jwtIdToken);
$o->verifyIdToken($this->publicKey, ['RS256']);
}
/**
* @expectedException DomainException
*/
public function testFailsIfAudienceIsWrong()
{
$now = time();
$testConfig = $this->verifyIdTokenMinimal;
$origIdToken = [
'aud' => 'a different audience',
'iss' => $testConfig['issuer'],
'exp' => $now + 65, // arbitrary
'iat' => $now,
];
$o = new OAuth2($testConfig);
$jwtIdToken = $this->jwtEncode($origIdToken, $this->privateKey, 'RS256');
$o->setIdToken($jwtIdToken);
$o->verifyIdToken($this->publicKey, ['RS256']);
}
public function testShouldReturnAValidIdToken()
{
$testConfig = $this->verifyIdTokenMinimal;
$now = time();
$origIdToken = [
'aud' => $testConfig['audience'],
'iss' => $testConfig['issuer'],
'exp' => $now + 65, // arbitrary
'iat' => $now,
];
$o = new OAuth2($testConfig);
$alg = 'RS256';
$jwtIdToken = $this->jwtEncode($origIdToken, $this->privateKey, $alg);
$o->setIdToken($jwtIdToken);
$roundTrip = $o->verifyIdToken($this->publicKey, array($alg));
$this->assertEquals($origIdToken['aud'], $roundTrip->aud);
}
private function jwtEncode()
{
$args = func_get_args();
$class = 'JWT';
if (class_exists('Firebase\JWT\JWT')) {
$class = 'Firebase\JWT\JWT';
}
return call_user_func_array("$class::encode", $args);
}
}

View File

@@ -0,0 +1,325 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\FetchAuthTokenCache;
use Google\Auth\Subscriber\AuthTokenSubscriber;
use GuzzleHttp\Client;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Transaction;
class AuthTokenSubscriberTest extends BaseTest
{
private $mockFetcher;
private $mockCacheItem;
private $mockCache;
protected function setUp()
{
$this->onlyGuzzle5();
$this->mockFetcher =
$this
->getMockBuilder('Google\Auth\FetchAuthTokenInterface')
->getMock();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
}
public function testSubscribesToEvents()
{
$a = new AuthTokenSubscriber($this->mockFetcher);
$this->assertArrayHasKey('before', $a->getEvents());
}
public function testOnlyTouchesWhenAuthConfigScoped()
{
$s = new AuthTokenSubscriber($this->mockFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'not_google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame($request->getHeader('Authorization'), '');
}
public function testAddsTheTokenAsAnAuthorizationHeader()
{
$authResult = ['access_token' => '1/abcdef1234567890'];
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
// Run the test.
$a = new AuthTokenSubscriber($this->mockFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('Authorization'),
'Bearer 1/abcdef1234567890');
}
public function testDoesNotAddAnAuthorizationHeaderOnNoAccessToken()
{
$authResult = ['not_access_token' => '1/abcdef1234567890'];
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
// Run the test.
$a = new AuthTokenSubscriber($this->mockFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('Authorization'), '');
}
public function testUsesCachedAuthToken()
{
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
// Run the test.
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
null,
$this->mockCache
);
$a = new AuthTokenSubscriber($cachedFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('Authorization'),
'Bearer 2/abcdef1234567890');
}
public function testGetsCachedAuthTokenUsingCachePrefix()
{
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$cachedValue = '2/abcdef1234567890';
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->never())
->method('fetchAuthToken');
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
// Run the test
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix],
$this->mockCache
);
$a = new AuthTokenSubscriber($cachedFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('Authorization'),
'Bearer 2/abcdef1234567890');
}
public function testShouldSaveValueInCacheWithCacheOptions()
{
$prefix = 'test_prefix_';
$lifetime = '70707';
$cacheKey = 'myKey';
$token = '1/abcdef1234567890';
$authResult = ['access_token' => $token];
$this->mockCacheItem
->expects($this->any())
->method('get')
->will($this->returnValue(null));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('expiresAfter')
->with($this->equalTo($lifetime));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
// Run the test
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix, 'lifetime' => $lifetime],
$this->mockCache
);
$a = new AuthTokenSubscriber($cachedFetcher);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertSame($request->getHeader('Authorization'),
'Bearer 1/abcdef1234567890');
}
/** @dataProvider provideShouldNotifyTokenCallback */
public function testShouldNotifyTokenCallback(callable $tokenCallback)
{
$prefix = 'test_prefix_';
$cacheKey = 'myKey';
$token = '1/abcdef1234567890';
$authResult = ['access_token' => $token];
$this->mockCacheItem
->expects($this->any())
->method('get')
->will($this->returnValue(null));
$this->mockCache
->expects($this->any())
->method('getItem')
->with($this->equalTo($prefix . $cacheKey))
->will($this->returnValue($this->mockCacheItem));
$this->mockFetcher
->expects($this->any())
->method('getCacheKey')
->will($this->returnValue($cacheKey));
$this->mockFetcher
->expects($this->once())
->method('fetchAuthToken')
->will($this->returnValue($authResult));
SubscriberCallback::$expectedKey = $this->getValidKeyName($prefix . $cacheKey);
SubscriberCallback::$expectedValue = $token;
SubscriberCallback::$called = false;
// Run the test
$cachedFetcher = new FetchAuthTokenCache(
$this->mockFetcher,
['prefix' => $prefix],
$this->mockCache
);
$a = new AuthTokenSubscriber(
$cachedFetcher,
null,
$tokenCallback
);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'google_auth']);
$before = new BeforeEvent(new Transaction($client, $request));
$a->onBefore($before);
$this->assertTrue(SubscriberCallback::$called);
}
public function provideShouldNotifyTokenCallback()
{
SubscriberCallback::$phpunit = $this;
$anonymousFunc = function ($key, $value) {
SubscriberCallback::staticInvoke($key, $value);
};
return [
['Google\Auth\Tests\SubscriberCallbackFunction'],
['Google\Auth\Tests\SubscriberCallback::staticInvoke'],
[['Google\Auth\Tests\SubscriberCallback', 'staticInvoke']],
[$anonymousFunc],
[[new SubscriberCallback, 'staticInvoke']],
[[new SubscriberCallback, 'methodInvoke']],
[new SubscriberCallback],
];
}
}
class SubscriberCallback
{
public static $phpunit;
public static $expectedKey;
public static $expectedValue;
public static $called = false;
public function __invoke($key, $value)
{
self::$phpunit->assertEquals(self::$expectedKey, $key);
self::$phpunit->assertEquals(self::$expectedValue, $value);
self::$called = true;
}
public function methodInvoke($key, $value)
{
return $this($key, $value);
}
public static function staticInvoke($key, $value)
{
$instance = new self();
return $instance($key, $value);
}
}
function SubscriberCallbackFunction($key, $value)
{
return SubscriberCallback::staticInvoke($key, $value);
}

View File

@@ -0,0 +1,238 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\Subscriber\ScopedAccessTokenSubscriber;
use GuzzleHttp\Client;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Transaction;
class ScopedAccessTokenSubscriberTest extends BaseTest
{
const TEST_SCOPE = 'https://www.googleapis.com/auth/cloud-taskqueue';
private $mockCacheItem;
private $mockCache;
private $mockRequest;
protected function setUp()
{
$this->onlyGuzzle5();
$this->mockCacheItem =
$this
->getMockBuilder('Psr\Cache\CacheItemInterface')
->getMock();
$this->mockCache =
$this
->getMockBuilder('Psr\Cache\CacheItemPoolInterface')
->getMock();
$this->mockRequest =
$this
->getMockBuilder('GuzzleHttp\Psr7\Request')
->disableOriginalConstructor()
->getMock();
}
/**
* @expectedException InvalidArgumentException
*/
public function testRequiresScopeAsAStringOrArray()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
new ScopedAccessTokenSubscriber($fakeAuthFunc, new \stdClass(), array());
}
public function testSubscribesToEvents()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array());
$this->assertArrayHasKey('before', $s->getEvents());
}
public function testAddsTheTokenAsAnAuthorizationHeader()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array());
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'scoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame(
'Bearer 1/abcdef1234567890',
$request->getHeader('Authorization')
);
}
public function testUsesCachedAuthToken()
{
$cachedValue = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($this->getValidKeyName(self::TEST_SCOPE))
->will($this->returnValue($this->mockCacheItem));
// Run the test
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array(),
$this->mockCache);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'scoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('Authorization')
);
}
public function testGetsCachedAuthTokenUsingCachePrefix()
{
$prefix = 'test_prefix_';
$cachedValue = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) {
return '';
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue($cachedValue));
$this->mockCache
->expects($this->once())
->method('getItem')
->with($prefix . $this->getValidKeyName(self::TEST_SCOPE))
->will($this->returnValue($this->mockCacheItem));
// Run the test
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE,
['prefix' => $prefix],
$this->mockCache);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'scoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('Authorization')
);
}
public function testShouldSaveValueInCache()
{
$token = '2/abcdef1234567890';
$fakeAuthFunc = function ($unused_scopes) {
return '2/abcdef1234567890';
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token))
->will($this->returnValue(false));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($this->getValidKeyName(self::TEST_SCOPE))
->will($this->returnValue($this->mockCacheItem));
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array(),
$this->mockCache);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'scoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('Authorization')
);
}
public function testShouldSaveValueInCacheWithCacheOptions()
{
$token = '2/abcdef1234567890';
$prefix = 'test_prefix_';
$lifetime = '70707';
$fakeAuthFunc = function ($unused_scopes) {
return '2/abcdef1234567890';
};
$this->mockCacheItem
->expects($this->once())
->method('get')
->will($this->returnValue(false));
$this->mockCacheItem
->expects($this->once())
->method('set')
->with($this->equalTo($token));
$this->mockCacheItem
->expects($this->once())
->method('expiresAfter')
->with($this->equalTo($lifetime));
$this->mockCache
->expects($this->exactly(2))
->method('getItem')
->with($prefix . $this->getValidKeyName(self::TEST_SCOPE))
->will($this->returnValue($this->mockCacheItem));
// Run the test
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE,
['prefix' => $prefix, 'lifetime' => $lifetime],
$this->mockCache);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'scoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame(
'Bearer 2/abcdef1234567890',
$request->getHeader('Authorization')
);
}
public function testOnlyTouchesWhenAuthConfigScoped()
{
$fakeAuthFunc = function ($unused_scopes) {
return '1/abcdef1234567890';
};
$s = new ScopedAccessTokenSubscriber($fakeAuthFunc, self::TEST_SCOPE, array());
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'notscoped']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertSame('', $request->getHeader('Authorization'));
}
}

View File

@@ -0,0 +1,69 @@
<?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Auth\Tests;
use Google\Auth\Subscriber\SimpleSubscriber;
use GuzzleHttp\Client;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Transaction;
class SimpleSubscriberTest extends BaseTest
{
protected function setUp()
{
$this->onlyGuzzle5();
}
/**
* @expectedException InvalidArgumentException
*/
public function testRequiresADeveloperKey()
{
new SimpleSubscriber(['not_key' => 'a test key']);
}
public function testSubscribesToEvents()
{
$events = (new SimpleSubscriber(['key' => 'a test key']))->getEvents();
$this->assertArrayHasKey('before', $events);
}
public function testAddsTheKeyToTheQuery()
{
$s = new SimpleSubscriber(['key' => 'test_key']);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'simple']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertCount(1, $request->getQuery());
$this->assertTrue($request->getQuery()->hasKey('key'));
$this->assertSame($request->getQuery()->get('key'), 'test_key');
}
public function testOnlyTouchesWhenAuthConfigIsSimple()
{
$s = new SimpleSubscriber(['key' => 'test_key']);
$client = new Client();
$request = $client->createRequest('GET', 'http://testing.org',
['auth' => 'notsimple']);
$before = new BeforeEvent(new Transaction($client, $request));
$s->onBefore($before);
$this->assertCount(0, $request->getQuery());
}
}

55
vendor/google/auth/tests/bootstrap.php vendored Normal file
View File

@@ -0,0 +1,55 @@
<?php
/*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
error_reporting(E_ALL | E_STRICT);
require dirname(__DIR__) . '/vendor/autoload.php';
date_default_timezone_set('UTC');
// autoload base test
require_once __DIR__ . '/BaseTest.php';
function buildResponse($code, array $headers = [], $body = null)
{
if (class_exists('GuzzleHttp\HandlerStack')) {
return new \GuzzleHttp\Psr7\Response($code, $headers, $body);
}
return new \GuzzleHttp\Message\Response(
$code,
$headers,
\GuzzleHttp\Stream\Stream::factory((string)$body)
);
}
function getHandler(array $mockResponses = [])
{
if (class_exists('GuzzleHttp\HandlerStack')) {
$mock = new \GuzzleHttp\Handler\MockHandler($mockResponses);
$handler = \GuzzleHttp\HandlerStack::create($mock);
$client = new \GuzzleHttp\Client(['handler' => $handler]);
return new \Google\Auth\HttpHandler\Guzzle6HttpHandler($client);
}
$client = new \GuzzleHttp\Client();
$client->getEmitter()->attach(
new \GuzzleHttp\Subscriber\Mock($mockResponses)
);
return new \Google\Auth\HttpHandler\Guzzle5HttpHandler($client);
}

View File

@@ -0,0 +1,7 @@
{
"private_key_id": "key123",
"private_key": "privatekey",
"client_email": "hello@youarecool.com",
"client_id": "client123",
"type": "service_account"
}

View File

@@ -0,0 +1,7 @@
{
"private_key_id": "key123",
"private_key": "privatekey",
"client_email": "hello@youarecool.com",
"client_id": "client123",
"type": "service_account"
}

View File

@@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDzU+jLTzW6154Joezxrd2+5pCNYP0HcaMoYqEyXfNRpkNE7wrQ
UEG830o4Qcaae2BhqZoujwSW7RkR6h0Fkd0WTR8h5J8rSGNHv/1jJoUUjP9iZ/5S
FAyIIyEYfDPqtnA4iF1QWO2lXWlEFSuZjwM/8jBmeGzoiw17akNThIw8NwIDAQAB
AoGATpboVloEAY/IdFX/QGOmfhTb1T3hG3lheBa695iOkO2BRo9qT7PMN6NqxlbA
PX7ht0lfCfCZS+HSOg4CR50/6WXHMSmwlvcjGuDIDKWjviQTTYE77MlVBQHw9WzY
PfiRBbtouyPGQtO4rk42zkIILC6exBZ1vKpRPOmTAnxrjCECQQD+56r6hYcS6GNp
NOWyv0eVFMBX4iNWAsRf9JVVvGDz2rVuhnkNiN73vfffDWvSXkCydL1jFmalgdQD
gm77UZQHAkEA9F+CauU0aZsJ1SthQ6H0sDQ+eNRUgnz4itnkSC2C20fZ3DaSpCMC
0go81CcZOhftNO730ILqiS67C3d3rqLqUQJBAP10ROHMmz4Fq7MUUcClyPtHIuk/
hXskTTZL76DMKmrN8NDxDLSUf38+eJRkt+z4osPOp/E6eN3gdXr32nox50kCQCl8
hXGMU+eR0IuF/88xkY7Qb8KnmWlFuhQohZ7TSyHbAttl0GNZJkNuRYFm2duI8FZK
M3wMnbCIZGy/7WuScOECQQCV+0yrf5dL1M2GHjJfwuTb00wRKalKQEH1v/kvE5vS
FmdN7BPK5Ra50MaecMNoYqu9rmtyWRBn93dcvKrL57nY
-----END RSA PRIVATE KEY-----

View File

@@ -0,0 +1,6 @@
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDzU+jLTzW6154Joezxrd2+5pCN
YP0HcaMoYqEyXfNRpkNE7wrQUEG830o4Qcaae2BhqZoujwSW7RkR6h0Fkd0WTR8h
5J8rSGNHv/1jJoUUjP9iZ/5SFAyIIyEYfDPqtnA4iF1QWO2lXWlEFSuZjwM/8jBm
eGzoiw17akNThIw8NwIDAQAB
-----END PUBLIC KEY-----

View File

@@ -0,0 +1,6 @@
{
"client_id": "client123",
"client_secret": "clientSecret123",
"refresh_token": "refreshToken123",
"type": "authorized_user"
}

View File

@@ -0,0 +1,6 @@
{
"client_id": "client123",
"client_secret": "clientSecret123",
"refresh_token": "refreshToken123",
"type": "authorized_user"
}

View File

@@ -0,0 +1,19 @@
<?php
namespace google\appengine\api\app_identity;
class AppIdentityService
{
public static $scope;
public static $accessToken = array(
'access_token' => 'xyz',
'expiration_time' => '2147483646',
);
public static function getAccessToken($scope)
{
self::$scope = $scope;
return self::$accessToken;
}
}