123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521 |
- <?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;
- use PHPUnit\Framework\TestCase;
-
- // 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 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 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 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 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 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->assertInternalType('callable', $update_metadata);
-
- $actual_metadata = call_user_func($update_metadata,
- $metadata = array('foo' => 'bar'),
- $authUri = null,
- $httpHandler);
- $this->assertArrayHasKey(
- CredentialsLoader::AUTH_METADATA_KEY,
- $actual_metadata
- );
- $this->assertEquals(
- $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY],
- array('Bearer ' . $access_token));
- }
- }
-
- class SACJwtAccessTest extends 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->assertInternalType('callable', $update_metadata);
-
- $actual_metadata = call_user_func($update_metadata,
- $metadata = array('foo' => 'bar'),
- $authUri = null);
- $this->assertArrayNotHasKey(
- CredentialsLoader::AUTH_METADATA_KEY,
- $actual_metadata
- );
- }
-
- public function testUpdateMetadataFunc()
- {
- $testJson = $this->createTestJson();
- $sa = new ServiceAccountJwtAccessCredentials(
- $testJson
- );
- $this->assertNotNull($sa);
-
- $update_metadata = $sa->getUpdateMetadataFunc();
- $this->assertInternalType('callable', $update_metadata);
-
- $actual_metadata = call_user_func($update_metadata,
- $metadata = array('foo' => 'bar'),
- $authUri = 'https://example.com/service');
- $this->assertArrayHasKey(
- CredentialsLoader::AUTH_METADATA_KEY,
- $actual_metadata
- );
-
- $authorization = $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY];
- $this->assertInternalType('array', $authorization);
-
- $bearer_token = current($authorization);
- $this->assertInternalType('string', $bearer_token);
- $this->assertEquals(0, strpos($bearer_token, 'Bearer '));
- $this->assertGreaterThan(30, strlen($bearer_token));
-
- $actual_metadata2 = call_user_func($update_metadata,
- $metadata = array('foo' => 'bar'),
- $authUri = 'https://example.com/anotherService');
- $this->assertArrayHasKey(
- CredentialsLoader::AUTH_METADATA_KEY,
- $actual_metadata2
- );
-
- $authorization2 = $actual_metadata2[CredentialsLoader::AUTH_METADATA_KEY];
- $this->assertInternalType('array', $authorization2);
-
- $bearer_token2 = current($authorization2);
- $this->assertInternalType('string', $bearer_token2);
- $this->assertEquals(0, strpos($bearer_token2, 'Bearer '));
- $this->assertGreaterThan(30, strlen($bearer_token2));
- $this->assertNotEquals($bearer_token2, $bearer_token);
- }
- }
-
- class SACJwtAccessComboTest extends 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->assertInternalType('callable', $update_metadata);
-
- $actual_metadata = call_user_func($update_metadata,
- $metadata = array('foo' => 'bar'),
- $authUri = 'https://example.com/service');
- $this->assertArrayHasKey(
- CredentialsLoader::AUTH_METADATA_KEY,
- $actual_metadata
- );
-
- $authorization = $actual_metadata[CredentialsLoader::AUTH_METADATA_KEY];
- $this->assertInternalType('array', $authorization);
-
- $bearer_token = current($authorization);
- $this->assertInternalType('string', $bearer_token);
- $this->assertEquals(0, strpos($bearer_token, 'Bearer '));
- $this->assertGreaterThan(30, strlen($bearer_token));
- }
-
- 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->assertInternalType('callable', $update_metadata);
-
- $actual_metadata = call_user_func($update_metadata,
- $metadata = array('foo' => 'bar'),
- $authUri = null);
- // no access_token is added to the metadata hash
- // but also, no error should be thrown
- $this->assertInternalType('array', $actual_metadata);
- $this->assertArrayNotHasKey(
- CredentialsLoader::AUTH_METADATA_KEY,
- $actual_metadata
- );
- }
- }
|