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,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);
}
}