diff --git a/Auth/src/Credentials/ExternalAccountAuthorizedUserCredentials.php b/Auth/src/Credentials/ExternalAccountAuthorizedUserCredentials.php index a3f3346b7c2d..ffc927e463e9 100644 --- a/Auth/src/Credentials/ExternalAccountAuthorizedUserCredentials.php +++ b/Auth/src/Credentials/ExternalAccountAuthorizedUserCredentials.php @@ -147,7 +147,9 @@ public function updateMetadata( ) { $metadata = $this->traitUpdateMetadata($metadata, $authUri, $httpHandler); - if ($this->enableRegionalAccessBoundary) { + if ($this->enableRegionalAccessBoundary + && $this->getUniverseDomain() === GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN + ) { $metadata = $this->updateRegionalAccessBoundaryMetadata( $metadata, $this->buildRegionalAccessBoundaryLookupUrl(), diff --git a/Auth/src/Credentials/ExternalAccountCredentials.php b/Auth/src/Credentials/ExternalAccountCredentials.php index a3d932b7e6c9..dc4bcf282159 100644 --- a/Auth/src/Credentials/ExternalAccountCredentials.php +++ b/Auth/src/Credentials/ExternalAccountCredentials.php @@ -62,6 +62,17 @@ class ExternalAccountCredentials implements private const EXTERNAL_ACCOUNT_TYPE = 'external_account'; private const CLOUD_RESOURCE_MANAGER_URL = 'https://cloudresourcemanager.UNIVERSE_DOMAIN/v1/projects/%s'; + private const DEFAULT_IAM_HOSTS = [ + 'iam.googleapis.com', + ]; + private const DEFAULT_IAM_CREDENTIALS_HOSTS = [ + 'iamcredentials.googleapis.com', + 'iamcredentials.mtls.googleapis.com', + ]; + private const DEFAULT_STS_HOSTS = [ + 'sts.googleapis.com', + 'sts.mtls.googleapis.com', + ]; private OAuth2 $auth; private ?string $quotaProject; @@ -335,10 +346,33 @@ public function updateMetadata( ) { $metadata = $this->traitUpdateMetadata($metadata, $authUri, $httpHandler); - if ($this->enableRegionalAccessBoundary) { - $clientName = $this->serviceAccountImpersonationUrl - ? self::getServiceAccountImpersonationEmail($this->serviceAccountImpersonationUrl) - : null; + if ($this->enableRegionalAccessBoundary + && $this->getUniverseDomain() === GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN + && $this->hasAllowedRegionalAccessBoundaryHost( + (string) $this->auth->getTokenCredentialUri(), + self::DEFAULT_STS_HOSTS + ) + ) { + if ($this->serviceAccountImpersonationUrl) { + if (!$this->hasAllowedRegionalAccessBoundaryHost( + $this->serviceAccountImpersonationUrl, + self::DEFAULT_IAM_CREDENTIALS_HOSTS + )) { + return $metadata; + } + $clientName = self::getServiceAccountImpersonationEmail($this->serviceAccountImpersonationUrl); + if (null === $clientName) { + return $metadata; + } + } else { + if (!$this->hasAllowedRegionalAccessBoundaryHost( + (string) $this->auth->getAudience(), + self::DEFAULT_IAM_HOSTS + )) { + return $metadata; + } + $clientName = null; + } $metadata = $this->updateRegionalAccessBoundaryMetadata( $metadata, diff --git a/Auth/src/Credentials/GCECredentials.php b/Auth/src/Credentials/GCECredentials.php index 334c002eaf9e..b3f64465badb 100644 --- a/Auth/src/Credentials/GCECredentials.php +++ b/Auth/src/Credentials/GCECredentials.php @@ -202,10 +202,12 @@ class GCECredentials extends CredentialsLoader implements private $serviceAccountIdentity; /** - * @var string + * @var string|null */ private ?string $universeDomain; + private bool $hasExplicitUniverseDomain = false; + /** * @param Iam|null $iam [optional] An IAM instance. * @param string|string[] $scope [optional] the scope of the access request, @@ -255,6 +257,7 @@ public function __construct( $this->quotaProject = $quotaProject; $this->serviceAccountIdentity = $serviceAccountIdentity; $this->universeDomain = $universeDomain; + $this->hasExplicitUniverseDomain = null !== $universeDomain && '' !== $universeDomain; $this->enableRegionalAccessBoundary = $enableRegionalAccessBoundary; } @@ -626,6 +629,7 @@ public function getUniverseDomain(?callable $httpHandler = null): string $httpHandler, self::getUniverseDomainUri() ); + $this->hasExplicitUniverseDomain = '' !== $this->universeDomain; } catch (ClientException $e) { // If the metadata server exists, but returns a 404 for the universe domain, the auth // libraries should safely assume this is an older metadata server running in GCU, and @@ -634,6 +638,7 @@ public function getUniverseDomain(?callable $httpHandler = null): string throw $e; } $this->universeDomain = self::DEFAULT_UNIVERSE_DOMAIN; + $this->hasExplicitUniverseDomain = false; } // We expect in some cases the metadata server will return an empty string for the universe @@ -660,7 +665,10 @@ public function updateMetadata( ) { $metadata = parent::updateMetadata($metadata, $authUri, $httpHandler); - if ($this->enableRegionalAccessBoundary) { + if ($this->enableRegionalAccessBoundary + && $this->getUniverseDomain($httpHandler) === self::DEFAULT_UNIVERSE_DOMAIN + && $this->hasExplicitUniverseDomain + ) { $serviceAccountEmail = $this->getClientName($httpHandler); if (preg_match('/^[^@]+@[^@]+\.[^@]+$/', $serviceAccountEmail)) { $metadata = $this->updateRegionalAccessBoundaryMetadata( diff --git a/Auth/src/Credentials/ImpersonatedServiceAccountCredentials.php b/Auth/src/Credentials/ImpersonatedServiceAccountCredentials.php index a6560bf8cdf6..ea01262cebc5 100644 --- a/Auth/src/Credentials/ImpersonatedServiceAccountCredentials.php +++ b/Auth/src/Credentials/ImpersonatedServiceAccountCredentials.php @@ -20,6 +20,7 @@ use Google\Auth\CacheTrait; use Google\Auth\CredentialsLoader; +use Google\Auth\FetchAuthTokenCache; use Google\Auth\FetchAuthTokenInterface; use Google\Auth\GetUniverseDomainInterface; use Google\Auth\HttpHandler\HttpClientCache; @@ -55,6 +56,10 @@ class ImpersonatedServiceAccountCredentials extends CredentialsLoader implements private const IAM_SCOPE = 'https://www.googleapis.com/auth/iam'; private const ID_TOKEN_IMPERSONATION_URL = 'https://iamcredentials.UNIVERSE_DOMAIN/v1/projects/-/serviceAccounts/%s:generateIdToken'; + private const DEFAULT_IAM_CREDENTIALS_HOSTS = [ + 'iamcredentials.googleapis.com', + 'iamcredentials.mtls.googleapis.com', + ]; /** * @var string @@ -77,6 +82,8 @@ class ImpersonatedServiceAccountCredentials extends CredentialsLoader implements private int $lifetime; + private ?string $universeDomain = null; + /** * @var array|null */ @@ -132,10 +139,28 @@ public function __construct( 'Scope and targetAudience cannot both be supplied' ); } + if (isset($jsonKey['universe_domain'])) { + $this->universeDomain = (string) $jsonKey['universe_domain']; + } if (is_array($jsonKey['source_credentials'])) { if (!array_key_exists('type', $jsonKey['source_credentials'])) { throw new InvalidArgumentException('json key source credentials are missing the type field'); } + if (null !== $this->universeDomain) { + if (isset($jsonKey['source_credentials']['universe_domain'])) { + $sourceUniverseDomain = (string) $jsonKey['source_credentials']['universe_domain']; + if ($sourceUniverseDomain !== $this->universeDomain) { + throw new InvalidArgumentException(sprintf( + 'Universe domain %s in source credentials does not match ' + . '%s universe domain set for impersonated credentials.', + $sourceUniverseDomain, + $this->universeDomain + )); + } + } else { + $jsonKey['source_credentials']['universe_domain'] = $this->universeDomain; + } + } if ($targetAudience !== null && $jsonKey['source_credentials']['type'] === 'service_account' ) { @@ -153,6 +178,24 @@ public function __construct( 'external_account' => new ExternalAccountCredentials($scope, $jsonKey['source_credentials']), default => throw new \InvalidArgumentException('invalid value in the type field'), }; + } elseif (null !== $this->universeDomain + && $jsonKey['source_credentials'] instanceof GetUniverseDomainInterface + ) { + $unwrapped = $jsonKey['source_credentials']; + while ($unwrapped instanceof FetchAuthTokenCache) { + $unwrapped = $unwrapped->getFetcher(); + } + if (!$unwrapped instanceof GCECredentials) { + $sourceUniverseDomain = $jsonKey['source_credentials']->getUniverseDomain(); + if ($sourceUniverseDomain !== $this->universeDomain) { + throw new InvalidArgumentException(sprintf( + 'Universe domain %s in source credentials does not match ' + . '%s universe domain set for impersonated credentials.', + $sourceUniverseDomain, + $this->universeDomain + )); + } + } } $this->targetScope = $scope ?? []; @@ -308,6 +351,10 @@ private function isIdTokenRequest(): bool public function getUniverseDomain(): string { + if (null !== $this->universeDomain) { + return $this->universeDomain; + } + return $this->sourceCredentials instanceof GetUniverseDomainInterface ? $this->sourceCredentials->getUniverseDomain() : self::DEFAULT_UNIVERSE_DOMAIN; @@ -326,17 +373,32 @@ public function updateMetadata( $authUri = null, ?callable $httpHandler = null ) { - $metatadata = parent::updateMetadata($metadata, $authUri, $httpHandler); - - $metatadata = $this->updateRegionalAccessBoundaryMetadata( - $metatadata, - $this->buildRegionalAccessBoundaryLookupUrl( - serviceAccountEmail: $this->impersonatedServiceAccountName - ), - $this->getUniverseDomain(), - $httpHandler, - ); + $metadata = parent::updateMetadata($metadata, $authUri, $httpHandler); + + if ($this->enableRegionalAccessBoundary + && $this->getUniverseDomain() === self::DEFAULT_UNIVERSE_DOMAIN + && $this->hasAllowedRegionalAccessBoundaryHost( + $this->serviceAccountImpersonationUrl, + self::DEFAULT_IAM_CREDENTIALS_HOSTS + ) + ) { + $sourceUniverse = $this->sourceCredentials instanceof GCECredentials + ? $this->sourceCredentials->getUniverseDomain($httpHandler) + : ($this->sourceCredentials instanceof GetUniverseDomainInterface + ? $this->sourceCredentials->getUniverseDomain() + : self::DEFAULT_UNIVERSE_DOMAIN); + if ($sourceUniverse === self::DEFAULT_UNIVERSE_DOMAIN) { + $metadata = $this->updateRegionalAccessBoundaryMetadata( + $metadata, + $this->buildRegionalAccessBoundaryLookupUrl( + serviceAccountEmail: $this->impersonatedServiceAccountName + ), + $this->getUniverseDomain(), + $httpHandler, + ); + } + } - return $metatadata; + return $metadata; } } diff --git a/Auth/src/Credentials/RegionalAccessBoundaryTrait.php b/Auth/src/Credentials/RegionalAccessBoundaryTrait.php index ed568909708b..e0a10e200df6 100644 --- a/Auth/src/Credentials/RegionalAccessBoundaryTrait.php +++ b/Auth/src/Credentials/RegionalAccessBoundaryTrait.php @@ -189,6 +189,22 @@ private function lookupRegionalAccessBoundary( return $regionalAccessBoundary; } + /** + * Check whether a URL's host matches one of the allowed default-universe hosts. + * + * @param string $url + * @param array $allowedHosts Lowercase hostnames without trailing dots. + */ + private function hasAllowedRegionalAccessBoundaryHost(string $url, array $allowedHosts): bool + { + $host = parse_url($url, PHP_URL_HOST); + if (!is_string($host) || '' === $host) { + return false; + } + + return in_array(strtolower(rtrim($host, '.')), $allowedHosts, true); + } + private function initiateCooldown(): void { $cooldownKey = $this->getCacheKey() . ':rab:cooldown'; diff --git a/Auth/src/Credentials/ServiceAccountCredentials.php b/Auth/src/Credentials/ServiceAccountCredentials.php index 7f28234307a5..b63aca658796 100644 --- a/Auth/src/Credentials/ServiceAccountCredentials.php +++ b/Auth/src/Credentials/ServiceAccountCredentials.php @@ -79,6 +79,12 @@ class ServiceAccountCredentials extends CredentialsLoader implements */ private const CRED_TYPE = 'sa'; private const IAM_SCOPE = 'https://www.googleapis.com/auth/iam'; + private const DEFAULT_TOKEN_HOSTS = [ + 'oauth2.googleapis.com', + 'oauth2.mtls.googleapis.com', + 'accounts.google.com', + 'www.googleapis.com', + ]; /** * The OAuth2 instance used to conduct authorization. @@ -119,6 +125,10 @@ class ServiceAccountCredentials extends CredentialsLoader implements */ private string $universeDomain; + private bool $hasExplicitUniverseDomain = false; + + private ?string $tokenUri = null; + /** * Whether this is an ID token request or an access token request. Used when * building the metric header. @@ -190,6 +200,9 @@ public function __construct( $this->projectId = $jsonKey['project_id'] ?? null; $this->universeDomain = $jsonKey['universe_domain'] ?? self::DEFAULT_UNIVERSE_DOMAIN; + $this->hasExplicitUniverseDomain = isset($jsonKey['universe_domain']) + && '' !== (string) $jsonKey['universe_domain']; + $this->tokenUri = isset($jsonKey['token_uri']) ? (string) $jsonKey['token_uri'] : null; $this->enableRegionalAccessBoundary = $enableRegionalAccessBoundary; } @@ -331,14 +344,23 @@ public function updateMetadata( ? $this->updateMetadataSelfSignedJwt($metadata, $authUri, $httpHandler) : parent::updateMetadata($metadata, $authUri, $httpHandler); - $metadata = $this->updateRegionalAccessBoundaryMetadata( - $metadata, - $this->buildRegionalAccessBoundaryLookupUrl( - serviceAccountEmail: $this->auth->getIssuer() - ), - $this->getUniverseDomain(), - $httpHandler, - ); + if ($this->enableRegionalAccessBoundary + && $this->getUniverseDomain() === self::DEFAULT_UNIVERSE_DOMAIN + && ( + (null !== $this->tokenUri + && $this->hasAllowedRegionalAccessBoundaryHost($this->tokenUri, self::DEFAULT_TOKEN_HOSTS)) + || ($this->hasExplicitUniverseDomain && null === $this->tokenUri) + ) + ) { + $metadata = $this->updateRegionalAccessBoundaryMetadata( + $metadata, + $this->buildRegionalAccessBoundaryLookupUrl( + serviceAccountEmail: $this->auth->getIssuer() + ), + $this->getUniverseDomain(), + $httpHandler, + ); + } return $metadata; } diff --git a/Auth/tests/Unit/ApplicationDefaultCredentialsTest.php b/Auth/tests/Unit/ApplicationDefaultCredentialsTest.php index 6a78107c141c..65c1ee73b7fc 100644 --- a/Auth/tests/Unit/ApplicationDefaultCredentialsTest.php +++ b/Auth/tests/Unit/ApplicationDefaultCredentialsTest.php @@ -864,6 +864,29 @@ public function testUniverseDomainInKeyFile() 'example-universe2.com' ); $this->assertEquals(CredentialsLoader::DEFAULT_UNIVERSE_DOMAIN, $creds3->getUniverseDomain()); + + // Test passing in universe domain applies to "impersonated_service_account" + $tmpFile = tempnam(sys_get_temp_dir(), 'impersonated-'); + file_put_contents($tmpFile, json_encode([ + 'type' => 'impersonated_service_account', + 'service_account_impersonation_url' => 'https://iamcredentials.example-universe.com/v1/' + . 'projects/-/serviceAccounts/test@example.com:generateAccessToken', + 'source_credentials' => [ + 'type' => 'service_account', + 'client_email' => 'source@example.com', + 'private_key' => file_get_contents(__DIR__ . '/fixtures/fixtures1/private.pem'), + ], + ])); + try { + putenv(ServiceAccountCredentials::ENV_VAR . '=' . $tmpFile); + $creds4 = ApplicationDefaultCredentials::getCredentials( + universeDomain: 'example-universe.com', + enableRegionalAccessBoundary: true + ); + $this->assertEquals('example-universe.com', $creds4->getUniverseDomain()); + } finally { + @unlink($tmpFile); + } } /** @runInSeparateProcess */ diff --git a/Auth/tests/Unit/Credentials/ExternalAccountCredentialsTest.php b/Auth/tests/Unit/Credentials/ExternalAccountCredentialsTest.php index ab547b2e525b..3284ce37ed95 100644 --- a/Auth/tests/Unit/Credentials/ExternalAccountCredentialsTest.php +++ b/Auth/tests/Unit/Credentials/ExternalAccountCredentialsTest.php @@ -754,4 +754,151 @@ public function testRegionalAccessBoundaryWithImpersonationUsesServiceAccountEma $this->assertArrayHasKey('x-allowed-locations', $metadata); $this->assertEquals('foo', $metadata['x-allowed-locations']); } + + public function testRegionalAccessBoundarySuppressedWithUniverseDomain() + { + $requestCount = 0; + $httpHandler = function () use (&$requestCount) { + $requestCount++; + return new Response(200, [], '{"access_token": "source-token", "expires_in": 3600}'); + }; + $tokenFile = tempnam(sys_get_temp_dir(), 'token'); + try { + $jsonKey = [ + 'type' => 'external_account', + 'audience' => 'custom-audience', + 'subject_token_type' => 'urn:ietf:params:oauth:token-type:jwt', + 'token_url' => 'https://sts.example.com/v1/token', + 'universe_domain' => 'example.com', + 'credential_source' => ['file' => $tokenFile], + ]; + $creds = new ExternalAccountCredentials('a-scope', $jsonKey, enableRegionalAccessBoundary: true); + + $metadata = $creds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(1, $requestCount); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } finally { + @unlink($tokenFile); + } + } + + public function testRegionalAccessBoundarySuppressedWithNonDefaultTokenUrlHost() + { + $requestCount = 0; + $httpHandler = function () use (&$requestCount) { + $requestCount++; + return new Response(200, [], '{"access_token": "source-token", "expires_in": 3600}'); + }; + $tokenFile = tempnam(sys_get_temp_dir(), 'token'); + try { + $jsonKey = [ + 'type' => 'external_account', + 'audience' => '//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/' + . 'workloadIdentityPools/POOL_ID/providers/PROJECT_ID', + 'subject_token_type' => 'urn:ietf:params:oauth:token-type:jwt', + 'token_url' => 'https://sts.example.com/v1/token', + 'credential_source' => ['file' => $tokenFile], + ]; + $creds = new ExternalAccountCredentials('a-scope', $jsonKey, enableRegionalAccessBoundary: true); + + $metadata = $creds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(1, $requestCount); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } finally { + @unlink($tokenFile); + } + } + + public function testRegionalAccessBoundarySuppressedWithNonDefaultImpersonationUrlHost() + { + $count = 0; + $httpHandler = function () use (&$count) { + return match ($count++) { + 0 => new Response(200, [], '{"access_token": "source-token", "expires_in": 3600}'), + 1 => new Response(200, [], '{"accessToken": "access-token", "expireTime": "2026-01-01"}'), + }; + }; + $tokenFile = tempnam(sys_get_temp_dir(), 'token'); + try { + $jsonKey = [ + 'type' => 'external_account', + 'audience' => '//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/' + . 'workloadIdentityPools/POOL_ID/providers/PROJECT_ID', + 'subject_token_type' => 'urn:ietf:params:oauth:token-type:jwt', + 'token_url' => 'https://sts.googleapis.com/v1/token', + 'credential_source' => ['file' => $tokenFile], + 'service_account_impersonation_url' => 'https://iamcredentials.example.com/v1/' + . 'projects/-/serviceAccounts/test@example.com:generateAccessToken', + ]; + $creds = new ExternalAccountCredentials('a-scope', $jsonKey, enableRegionalAccessBoundary: true); + + $metadata = $creds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(2, $count); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } finally { + @unlink($tokenFile); + } + } + + public function testRegionalAccessBoundarySuppressedWithNonDefaultAudienceHost() + { + $requestCount = 0; + $httpHandler = function () use (&$requestCount) { + $requestCount++; + return new Response(200, [], '{"access_token": "source-token", "expires_in": 3600}'); + }; + $tokenFile = tempnam(sys_get_temp_dir(), 'token'); + try { + $jsonKey = [ + 'type' => 'external_account', + 'audience' => '//iam.example.com/projects/PROJECT_NUMBER/locations/global/' + . 'workloadIdentityPools/POOL_ID/providers/PROJECT_ID', + 'subject_token_type' => 'urn:ietf:params:oauth:token-type:jwt', + 'token_url' => 'https://sts.googleapis.com/v1/token', + 'credential_source' => ['file' => $tokenFile], + ]; + $creds = new ExternalAccountCredentials('a-scope', $jsonKey, enableRegionalAccessBoundary: true); + + $metadata = $creds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(1, $requestCount); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } finally { + @unlink($tokenFile); + } + } + + public function testRegionalAccessBoundarySuppressedWithUnparseableImpersonationUrl() + { + $count = 0; + $httpHandler = function () use (&$count) { + return match ($count++) { + 0 => new Response(200, [], '{"access_token": "source-token", "expires_in": 3600}'), + 1 => new Response(200, [], '{"accessToken": "access-token", "expireTime": "2026-01-01"}'), + }; + }; + $tokenFile = tempnam(sys_get_temp_dir(), 'token'); + try { + $jsonKey = [ + 'type' => 'external_account', + 'audience' => '//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/' + . 'workloadIdentityPools/POOL_ID/providers/PROJECT_ID', + 'subject_token_type' => 'urn:ietf:params:oauth:token-type:jwt', + 'token_url' => 'https://sts.googleapis.com/v1/token', + 'credential_source' => ['file' => $tokenFile], + 'service_account_impersonation_url' => 'https://iamcredentials.googleapis.com/v1/invalid', + ]; + $creds = new ExternalAccountCredentials('a-scope', $jsonKey, enableRegionalAccessBoundary: true); + + $metadata = $creds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(2, $count); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } finally { + @unlink($tokenFile); + } + } } diff --git a/Auth/tests/Unit/Credentials/GCECredentialsTest.php b/Auth/tests/Unit/Credentials/GCECredentialsTest.php index f0041d64a1e0..8c631f92f034 100644 --- a/Auth/tests/Unit/Credentials/GCECredentialsTest.php +++ b/Auth/tests/Unit/Credentials/GCECredentialsTest.php @@ -829,4 +829,87 @@ public function testUpdateMetadataWithInvalidEmailBypassesRegionalAccessBoundary $this->assertArrayNotHasKey('x-allowed-locations', $metadata); } + + public function testUpdateMetadataWithRegionalAccessBoundarySuppressedWithMdsUniverseDomain() + { + $timesCalled = 0; + $httpHandler = function () use (&$timesCalled) { + return match (++$timesCalled) { + 1 => new Response(200, [GCECredentials::FLAVOR_HEADER => 'Google']), + 2 => new Response(200, [], '{"access_token": "abc", "expires_in": 57}'), + 3 => new Response(200, [], 'example.com'), + }; + }; + + $gceCreds = new GCECredentials( + enableRegionalAccessBoundary: true, + ); + + $metadata = $gceCreds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(3, $timesCalled); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } + + public function testUpdateMetadataWithRegionalAccessBoundaryRunsWithExplicitMdsDefaultUniverse() + { + $timesCalled = 0; + $httpHandler = function () use (&$timesCalled) { + return match (++$timesCalled) { + 1 => new Response(200, [GCECredentials::FLAVOR_HEADER => 'Google']), + 2 => new Response(200, [], '{"access_token": "abc", "expires_in": 57}'), + 3 => new Response(200, [], 'googleapis.com'), + 4 => new Response(200, [], '1234567890-compute@developer.gserviceaccount.com'), + 5 => new Response(200, [], '{"locations": [], "encodedLocations": "foo"}'), + }; + }; + + $gceCreds = new GCECredentials( + enableRegionalAccessBoundary: true, + ); + + $metadata = $gceCreds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(5, $timesCalled); + $this->assertEquals('foo', $metadata['x-allowed-locations']); + } + + public function testUpdateMetadataWithRegionalAccessBoundarySuppressedOnMdsUniverseNotFound() + { + $httpHandler = $this->getHandler([ + new Response(200, [GCECredentials::FLAVOR_HEADER => 'Google']), + new Response(200, [], '{"access_token": "abc", "expires_in": 57}'), + new Response(404), + ]); + + $gceCreds = new GCECredentials( + enableRegionalAccessBoundary: true, + ); + + $metadata = $gceCreds->updateMetadata([], null, $httpHandler); + + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + $this->assertSame(GCECredentials::DEFAULT_UNIVERSE_DOMAIN, $gceCreds->getUniverseDomain($httpHandler)); + } + + public function testUpdateMetadataWithRegionalAccessBoundarySuppressedOnEmptyMdsUniverse() + { + $timesCalled = 0; + $httpHandler = function () use (&$timesCalled) { + return match (++$timesCalled) { + 1 => new Response(200, [GCECredentials::FLAVOR_HEADER => 'Google']), + 2 => new Response(200, [], '{"access_token": "abc", "expires_in": 57}'), + 3 => new Response(200, [], ''), + }; + }; + + $gceCreds = new GCECredentials( + enableRegionalAccessBoundary: true, + ); + + $metadata = $gceCreds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(3, $timesCalled); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } } diff --git a/Auth/tests/Unit/Credentials/ImpersonatedServiceAccountCredentialsTest.php b/Auth/tests/Unit/Credentials/ImpersonatedServiceAccountCredentialsTest.php index f7e85fe63c7b..da3136eca036 100644 --- a/Auth/tests/Unit/Credentials/ImpersonatedServiceAccountCredentialsTest.php +++ b/Auth/tests/Unit/Credentials/ImpersonatedServiceAccountCredentialsTest.php @@ -19,8 +19,10 @@ namespace Google\Auth\Tests\Credentials; use Google\Auth\Credentials\ExternalAccountCredentials; +use Google\Auth\Credentials\GCECredentials; use Google\Auth\Credentials\ImpersonatedServiceAccountCredentials; use Google\Auth\Credentials\ServiceAccountCredentials; +use Google\Auth\Credentials\StaticCredentials; use Google\Auth\Credentials\UserRefreshCredentials; use Google\Auth\FetchAuthTokenInterface; use Google\Auth\GetUniverseDomainInterface; @@ -640,4 +642,202 @@ public function testUpdateMetadataWithRegionalAccessBoundarySuppressedWithUniver $this->assertArrayNotHasKey('x-allowed-locations', $metadata); } + + public function testUpdateMetadataWithRegionalAccessBoundarySuppressedWithTopLevelUniverseDomain() + { + $requestCount = 0; + $httpHandler = function () use (&$requestCount) { + $requestCount++; + return new Response(200, [], '{"accessToken": "impersonated-token", "expireTime": "2026-01-01"}'); + }; + + $jsonKey = [ + 'service_account_impersonation_url' => 'https://iamcredentials.foo.com/v1/' + . 'projects/-/serviceAccounts/test@example.com:generateAccessToken', + 'universe_domain' => 'foo.com', + 'source_credentials' => [ + 'type' => 'service_account', + 'private_key' => file_get_contents(__DIR__ . '/../fixtures/fixtures1/private.pem'), + 'client_email' => 'test@example.com', + ], + ]; + $impersonatedCreds = new ImpersonatedServiceAccountCredentials( + 'a-scope', + $jsonKey, + enableRegionalAccessBoundary: true + ); + + $this->assertEquals('foo.com', $impersonatedCreds->getUniverseDomain()); + + $metadata = $impersonatedCreds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(1, $requestCount); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } + + public function testUpdateMetadataWithRegionalAccessBoundarySuppressedWithStaticSourceAndTopLevelUniverseDomain() + { + $requestCount = 0; + $httpHandler = function () use (&$requestCount) { + $requestCount++; + return new Response(200, [], '{"accessToken": "impersonated-token", "expireTime": "2026-01-01"}'); + }; + + $jsonKey = [ + 'service_account_impersonation_url' => 'https://iamcredentials.googleapis.com/v1/' + . 'projects/-/serviceAccounts/test@example.com:generateAccessToken', + 'universe_domain' => 'foo.com', + 'source_credentials' => new StaticCredentials('source-token'), + ]; + $impersonatedCreds = new ImpersonatedServiceAccountCredentials( + 'a-scope', + $jsonKey, + enableRegionalAccessBoundary: true + ); + + $this->assertEquals('foo.com', $impersonatedCreds->getUniverseDomain()); + + $metadata = $impersonatedCreds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(1, $requestCount); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } + + public function testUpdateMetadataWithRegionalAccessBoundarySuppressedWithNonDefaultImpersonationHost() + { + $requestCount = 0; + $httpHandler = function () use (&$requestCount) { + $requestCount++; + return new Response(200, [], '{"accessToken": "impersonated-token", "expireTime": "2026-01-01"}'); + }; + + $jsonKey = [ + 'service_account_impersonation_url' => 'https://iamcredentials.example.com/v1/' + . 'projects/-/serviceAccounts/test@example.com:generateAccessToken', + 'source_credentials' => new StaticCredentials('source-token'), + ]; + $impersonatedCreds = new ImpersonatedServiceAccountCredentials( + 'a-scope', + $jsonKey, + enableRegionalAccessBoundary: true + ); + + $metadata = $impersonatedCreds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(1, $requestCount); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } + + public function testConstructorThrowsOnMismatchedSourceUniverseDomainArray() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Universe domain foo.com in source credentials does not match ' + . 'googleapis.com universe domain set for impersonated credentials.' + ); + + $jsonKey = [ + 'service_account_impersonation_url' => 'https://iamcredentials.googleapis.com/v1/' + . 'projects/-/serviceAccounts/test@example.com:generateAccessToken', + 'universe_domain' => 'googleapis.com', + 'source_credentials' => [ + 'type' => 'service_account', + 'private_key' => file_get_contents(__DIR__ . '/../fixtures/fixtures1/private.pem'), + 'client_email' => 'test@example.com', + 'universe_domain' => 'foo.com', + ], + ]; + new ImpersonatedServiceAccountCredentials('a-scope', $jsonKey); + } + + public function testConstructorThrowsOnMismatchedSourceUniverseDomainObject() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Universe domain foo.com in source credentials does not match ' + . 'googleapis.com universe domain set for impersonated credentials.' + ); + + $sourceCreds = new ServiceAccountCredentials('a-scope', [ + 'type' => 'service_account', + 'private_key' => file_get_contents(__DIR__ . '/../fixtures/fixtures1/private.pem'), + 'client_email' => 'test@example.com', + 'universe_domain' => 'foo.com', + ]); + new ImpersonatedServiceAccountCredentials('a-scope', [ + 'service_account_impersonation_url' => 'https://iamcredentials.googleapis.com/v1/' + . 'projects/-/serviceAccounts/test@example.com:generateAccessToken', + 'universe_domain' => 'googleapis.com', + 'source_credentials' => $sourceCreds, + ]); + } + + public function testConstructorAllowsMatchingTopLevelAndSourceUniverseDomain() + { + $impersonatedCreds = new ImpersonatedServiceAccountCredentials('a-scope', [ + 'service_account_impersonation_url' => 'https://iamcredentials.foo.com/v1/' + . 'projects/-/serviceAccounts/test@example.com:generateAccessToken', + 'universe_domain' => 'foo.com', + 'source_credentials' => [ + 'type' => 'service_account', + 'private_key' => file_get_contents(__DIR__ . '/../fixtures/fixtures1/private.pem'), + 'client_email' => 'test@example.com', + 'universe_domain' => 'foo.com', + ], + ]); + + $this->assertSame('foo.com', $impersonatedCreds->getUniverseDomain()); + } + + public function testUpdateMetadataWithRegionalAccessBoundarySuppressedWithMismatchedGceSource() + { + $timesCalled = 0; + $httpHandler = function () use (&$timesCalled) { + return match (++$timesCalled) { + 1 => new Response(200, [GCECredentials::FLAVOR_HEADER => 'Google']), + 2 => new Response(200, [], '{"access_token": "source-token", "expires_in": 57}'), + 3 => new Response(200, [], '{"accessToken": "impersonated-token", "expireTime": "2026-01-01"}'), + }; + }; + + $impersonatedCreds = new ImpersonatedServiceAccountCredentials( + 'a-scope', + [ + 'service_account_impersonation_url' => 'https://iamcredentials.googleapis.com/v1/' + . 'projects/-/serviceAccounts/test@example.com:generateAccessToken', + 'universe_domain' => 'googleapis.com', + 'source_credentials' => new GCECredentials(universeDomain: 'foo.com'), + ], + enableRegionalAccessBoundary: true + ); + + $metadata = $impersonatedCreds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(3, $timesCalled); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } + + public function testUpdateMetadataWithRegionalAccessBoundaryWithMtlsImpersonationHost() + { + $httpHandler = $this->getHandler([ + new Response(200, [], '{"accessToken": "impersonated-token", "expireTime": "2026-01-01"}'), + new Response(200, [], '{"locations": [], "encodedLocations": "foo"}'), + ]); + + $jsonKey = [ + 'service_account_impersonation_url' => 'https://iamcredentials.mtls.googleapis.com/v1/' + . 'projects/-/serviceAccounts/test@example.com:generateAccessToken', + 'source_credentials' => new StaticCredentials('source-token'), + ]; + $impersonatedCreds = new ImpersonatedServiceAccountCredentials( + 'a-scope', + $jsonKey, + enableRegionalAccessBoundary: true + ); + + $metadata = $impersonatedCreds->updateMetadata([], null, $httpHandler); + + $this->assertArrayHasKey('x-allowed-locations', $metadata); + $this->assertEquals('foo', $metadata['x-allowed-locations']); + } } diff --git a/Auth/tests/Unit/Credentials/RegionalAccessBoundaryTraitTest.php b/Auth/tests/Unit/Credentials/RegionalAccessBoundaryTraitTest.php index 9a3dc3724a78..bd0e0ebec3ba 100644 --- a/Auth/tests/Unit/Credentials/RegionalAccessBoundaryTraitTest.php +++ b/Auth/tests/Unit/Credentials/RegionalAccessBoundaryTraitTest.php @@ -395,6 +395,33 @@ public function testMalformedResponseFromAllowLocationsLookup(int $statusCode, s $this->assertTrue($this->impl->cooldownIsActive()); } + /** + * @dataProvider provideHasAllowedRegionalAccessBoundaryHost + */ + public function testHasAllowedRegionalAccessBoundaryHost(string $url, array $allowedHosts, bool $expected) + { + $this->assertSame($expected, $this->impl->hasAllowedRegionalAccessBoundaryHost($url, $allowedHosts)); + } + + public function provideHasAllowedRegionalAccessBoundaryHost(): array + { + $iamCredsHosts = ['iamcredentials.googleapis.com', 'iamcredentials.mtls.googleapis.com']; + return [ + 'exact match' => ['https://iamcredentials.googleapis.com/v1/foo', $iamCredsHosts, true], + 'mtls match' => ['https://iamcredentials.mtls.googleapis.com/v1/foo', $iamCredsHosts, true], + 'with port' => ['https://iamcredentials.googleapis.com:443/v1/foo', $iamCredsHosts, true], + 'uppercase host' => ['https://IAMCREDENTIALS.GOOGLEAPIS.COM/v1/foo', $iamCredsHosts, true], + 'trailing dot' => ['https://iamcredentials.googleapis.com./v1/foo', $iamCredsHosts, true], + 'schemeless audience match' => ['//iam.googleapis.com/projects/123', ['iam.googleapis.com'], true], + 'non-default host' => ['https://iamcredentials.example.com/v1/foo', $iamCredsHosts, false], + 'non-default audience' => ['//iam.example.com/projects/123', ['iam.googleapis.com'], false], + 'sandbox host' => ['https://iamcredentials.sandbox.googleapis.com/v1/foo', $iamCredsHosts, false], + 'suffix spoof' => ['https://iamcredentials.googleapis.com.evil.com/v1/foo', $iamCredsHosts, false], + 'unparseable url' => ['not-a-url', $iamCredsHosts, false], + 'empty string' => ['', $iamCredsHosts, false], + ]; + } + private function getRegionalAccessBoundaryTraitImpl(array $config = []) { return new class($config) { @@ -402,6 +429,7 @@ private function getRegionalAccessBoundaryTraitImpl(array $config = []) buildRegionalAccessBoundaryLookupUrl as public; lookupRegionalAccessBoundary as public; getRegionalAccessBoundary as public; + hasAllowedRegionalAccessBoundaryHost as public; } private $cache; diff --git a/Auth/tests/Unit/Credentials/ServiceAccountCredentialsTest.php b/Auth/tests/Unit/Credentials/ServiceAccountCredentialsTest.php index c3600fd7701c..1b0082ff0e87 100644 --- a/Auth/tests/Unit/Credentials/ServiceAccountCredentialsTest.php +++ b/Auth/tests/Unit/Credentials/ServiceAccountCredentialsTest.php @@ -439,6 +439,7 @@ public function testUpdateMetadataWithRegionalAccessBoundary() 'type' => 'service_account', 'private_key' => file_get_contents(__DIR__ . '/../fixtures/fixtures1/private.pem'), 'client_email' => 'test@example.com', + 'universe_domain' => 'googleapis.com', ]; $serviceAccountCreds = new ServiceAccountCredentials( 'a-scope', @@ -470,4 +471,110 @@ public function testUpdateMetadataWithRegionalAccessBoundarySuppressedWithUniver $this->assertArrayNotHasKey('x-allowed-locations', $metadata); } + + public function testUpdateMetadataWithRegionalAccessBoundarySuppressedWithNonDefaultTokenUriHost() + { + $requestCount = 0; + $httpHandler = function () use (&$requestCount) { + $requestCount++; + return new Response(200, [], '{"access_token": "source-token", "expires_in": 3600}'); + }; + + $jsonKey = [ + 'type' => 'service_account', + 'private_key' => file_get_contents(__DIR__ . '/../fixtures/fixtures1/private.pem'), + 'client_email' => 'test@example.com', + 'token_uri' => 'https://oauth2.example.com/token', + ]; + $serviceAccountCreds = new ServiceAccountCredentials( + 'a-scope', + $jsonKey, + enableRegionalAccessBoundary: true + ); + $serviceAccountCreds->useJwtAccessWithScope(); + + $metadata = $serviceAccountCreds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(0, $requestCount); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } + + public function testUpdateMetadataWithRegionalAccessBoundaryWithDefaultTokenUriHost() + { + $httpHandler = $this->getHandler([ + new Response(200, [], '{"access_token": "source-token", "expires_in": 3600}'), + new Response(200, [], '{"locations": [], "encodedLocations": "foo"}'), + ]); + + $jsonKey = [ + 'type' => 'service_account', + 'private_key' => file_get_contents(__DIR__ . '/../fixtures/fixtures1/private.pem'), + 'client_email' => 'test@example.com', + 'token_uri' => 'https://oauth2.googleapis.com/token', + ]; + $serviceAccountCreds = new ServiceAccountCredentials( + 'a-scope', + $jsonKey, + enableRegionalAccessBoundary: true + ); + + $metadata = $serviceAccountCreds->updateMetadata([], null, $httpHandler); + + $this->assertArrayHasKey('x-allowed-locations', $metadata); + $this->assertEquals('foo', $metadata['x-allowed-locations']); + } + + public function testUpdateMetadataWithRegionalAccessBoundarySuppressedWithoutUniverseDomainOrTokenUri() + { + $requestCount = 0; + $httpHandler = function () use (&$requestCount) { + $requestCount++; + return new Response(200, [], '{"access_token": "source-token", "expires_in": 3600}'); + }; + + $jsonKey = [ + 'type' => 'service_account', + 'private_key' => file_get_contents(__DIR__ . '/../fixtures/fixtures1/private.pem'), + 'client_email' => 'test@example.com', + ]; + $serviceAccountCreds = new ServiceAccountCredentials( + 'a-scope', + $jsonKey, + enableRegionalAccessBoundary: true + ); + $serviceAccountCreds->useJwtAccessWithScope(); + + $metadata = $serviceAccountCreds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(0, $requestCount); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } + + public function testUpdateMetadataWithRegionalAccessBoundarySuppressedWithDefaultUniverseAndNonDefaultTokenUri() + { + $requestCount = 0; + $httpHandler = function () use (&$requestCount) { + $requestCount++; + return new Response(200, [], '{"access_token": "source-token", "expires_in": 3600}'); + }; + + $jsonKey = [ + 'type' => 'service_account', + 'private_key' => file_get_contents(__DIR__ . '/../fixtures/fixtures1/private.pem'), + 'client_email' => 'test@example.com', + 'universe_domain' => 'googleapis.com', + 'token_uri' => 'https://oauth2.example.com/token', + ]; + $serviceAccountCreds = new ServiceAccountCredentials( + 'a-scope', + $jsonKey, + enableRegionalAccessBoundary: true + ); + $serviceAccountCreds->useJwtAccessWithScope(); + + $metadata = $serviceAccountCreds->updateMetadata([], null, $httpHandler); + + $this->assertEquals(0, $requestCount); + $this->assertArrayNotHasKey('x-allowed-locations', $metadata); + } } diff --git a/Auth/tests/Unit/Credentials/ServiceAccountJwtAccessCredentialsTest.php b/Auth/tests/Unit/Credentials/ServiceAccountJwtAccessCredentialsTest.php index 92182b205e9b..50560f351acb 100644 --- a/Auth/tests/Unit/Credentials/ServiceAccountJwtAccessCredentialsTest.php +++ b/Auth/tests/Unit/Credentials/ServiceAccountJwtAccessCredentialsTest.php @@ -566,6 +566,7 @@ public function testUpdateMetadataWithRegionalAccessBoundary() 'type' => 'service_account', 'private_key' => file_get_contents(__DIR__ . '/../fixtures/fixtures1/private.pem'), 'client_email' => 'test@example.com', + 'universe_domain' => 'googleapis.com', ]; $serviceAccountCreds = new ServiceAccountCredentials( 'a-scope', diff --git a/Gax/src/ClientOptionsTrait.php b/Gax/src/ClientOptionsTrait.php index f5fbafdd4d23..a2cbcb743f42 100644 --- a/Gax/src/ClientOptionsTrait.php +++ b/Gax/src/ClientOptionsTrait.php @@ -331,6 +331,7 @@ private function createCredentialsWrapper($credentials, array $credentialsConfig } if ($credentials instanceof CredentialsWrapper) { + CredentialsWrapper::validateRegionalAccessBoundaryUniverseDomain($credentials, $universeDomain); return $credentials; } diff --git a/Gax/src/CredentialsWrapper.php b/Gax/src/CredentialsWrapper.php index ff9ccc9c24d7..29b3f3fa3409 100644 --- a/Gax/src/CredentialsWrapper.php +++ b/Gax/src/CredentialsWrapper.php @@ -60,6 +60,8 @@ class CredentialsWrapper implements HeaderCredentialsInterface, ProjectIdProvide private bool $hasCheckedUniverse = false; + private string $universeDomain = GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN; + /** @var int */ private static int $eagerRefreshThresholdSeconds = 10; @@ -75,13 +77,14 @@ class CredentialsWrapper implements HeaderCredentialsInterface, ProjectIdProvide public function __construct( FetchAuthTokenInterface $credentialsFetcher, ?callable $authHttpHandler = null, - private string $universeDomain = GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN, + string $universeDomain = GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN, ) { $this->credentialsFetcher = $credentialsFetcher; $this->authHttpHandler = $authHttpHandler; if (empty($universeDomain)) { throw new ValidationException('The universe domain cannot be empty'); } + $this->universeDomain = $universeDomain; } /** @@ -140,6 +143,9 @@ public static function build( 'enableRegionalAccessBoundary' => false, ]; + $enableRegionalAccessBoundary = $args['enableRegionalAccessBoundary'] === true + && $universeDomain === GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN; + $keyFile = $args['keyFile']; if (is_null($keyFile)) { @@ -150,7 +156,7 @@ public static function build( $args['authCache'], $args['quotaProject'], $args['defaultScopes'], - $args['enableRegionalAccessBoundary'], + $enableRegionalAccessBoundary, ); if ($loader instanceof FetchAuthTokenCache) { $loader = $loader->getFetcher(); @@ -171,7 +177,7 @@ public static function build( $args['scopes'], $keyFile, $args['defaultScopes'], - $args['enableRegionalAccessBoundary'], + $enableRegionalAccessBoundary, ); } @@ -278,9 +284,12 @@ public function getAuthorizationHeaderCallback($audience = null): ?callable public function checkUniverseDomain(): void { if (false === $this->hasCheckedUniverse && $this->shouldCheckUniverseDomain()) { - $credentialsUniverse = $this->credentialsFetcher instanceof GetUniverseDomainInterface - ? $this->credentialsFetcher->getUniverseDomain() - : GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN; + $fetcher = $this->unwrapCredentialsFetcher(); + $credentialsUniverse = $fetcher instanceof GCECredentials && null !== $this->authHttpHandler + ? $fetcher->getUniverseDomain($this->authHttpHandler) + : ($this->credentialsFetcher instanceof GetUniverseDomainInterface + ? $this->credentialsFetcher->getUniverseDomain() + : GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN); if ($credentialsUniverse !== $this->universeDomain) { throw new ValidationException(sprintf( 'The configured universe domain (%s) does not match the credential universe domain (%s)', @@ -293,23 +302,76 @@ public function checkUniverseDomain(): void } /** - * Skip universe domain check for Metadata server (e.g. GCE) credentials. + * Validate that a pre-built wrapper's configured universe domain matches the + * client's universe domain when Regional Access Boundary lookups are enabled. + * + * @internal + * @throws ValidationException + */ + public static function validateRegionalAccessBoundaryUniverseDomain( + self $wrapper, + string $universeDomain + ): void { + if (self::hasRegionalAccessBoundaryEnabled($wrapper->credentialsFetcher) + && $wrapper->universeDomain !== $universeDomain + ) { + throw new ValidationException(sprintf( + 'The configured universe domain (%s) does not match the credential universe domain (%s)', + $universeDomain, + $wrapper->universeDomain + )); + } + } + + /** + * Skip universe domain check for Metadata server (e.g. GCE) credentials + * unless Regional Access Boundary lookups are enabled. * * @return bool */ private function shouldCheckUniverseDomain(): bool { - $fetcher = $this->credentialsFetcher instanceof FetchAuthTokenCache - ? $this->credentialsFetcher->getFetcher() - : $this->credentialsFetcher; + $fetcher = $this->unwrapCredentialsFetcher(); if ($fetcher instanceof GCECredentials) { - return false; + return self::hasRegionalAccessBoundaryEnabled($fetcher); } return true; } + private static function hasRegionalAccessBoundaryEnabled(?FetchAuthTokenInterface $fetcher): bool + { + while ($fetcher instanceof FetchAuthTokenCache) { + $fetcher = $fetcher->getFetcher(); + } + if (null === $fetcher) { + return false; + } + + $reflection = new \ReflectionObject($fetcher); + while ($reflection !== false) { + if ($reflection->hasProperty('enableRegionalAccessBoundary')) { + $property = $reflection->getProperty('enableRegionalAccessBoundary'); + return $property->isInitialized($fetcher) + && $property->getValue($fetcher) === true; + } + $reflection = $reflection->getParentClass(); + } + + return false; + } + + private function unwrapCredentialsFetcher(): ?FetchAuthTokenInterface + { + $fetcher = $this->credentialsFetcher; + while ($fetcher instanceof FetchAuthTokenCache) { + $fetcher = $fetcher->getFetcher(); + } + + return $fetcher; + } + /** * @param array $scopes * @param callable $authHttpHandler @@ -327,7 +389,7 @@ private static function buildApplicationDefaultCredentials( ?CacheItemPoolInterface $authCache = null, $quotaProject = null, ?array $defaultScopes = null, - bool $enableRegionalAccessBoundary = true, + bool $enableRegionalAccessBoundary = false, ) { try { return ApplicationDefaultCredentials::getCredentials( diff --git a/Gax/src/GapicClientTrait.php b/Gax/src/GapicClientTrait.php index 77a20e4be2d6..88665709c951 100644 --- a/Gax/src/GapicClientTrait.php +++ b/Gax/src/GapicClientTrait.php @@ -50,6 +50,7 @@ use Google\ApiCore\Transport\RestTransport; use Google\ApiCore\Transport\TransportInterface; use Google\Auth\FetchAuthTokenInterface; +use Google\Auth\GetUniverseDomainInterface; use Google\LongRunning\Client\OperationsClient; use Google\LongRunning\Operation; use Google\Protobuf\Internal\Message; @@ -362,12 +363,20 @@ private function setClientOptions(array $options) getenv('GOOGLE_AUTH_TRUST_BOUNDARY_ENABLE_EXPERIMENT'), FILTER_VALIDATE_BOOLEAN ); - $isRegional = str_ends_with($options['apiEndpoint'], '.rep.googleapis.com') - || str_ends_with($options['apiEndpoint'], '.rep.sandbox.googleapis.com'); + $apiEndpoint = (string) $options['apiEndpoint']; + $endpointHost = str_contains($apiEndpoint, '://') + ? (string) parse_url($apiEndpoint, PHP_URL_HOST) + : explode(':', $apiEndpoint, 2)[0]; + $endpointHost = strtolower(rtrim($endpointHost, '.')); + $isRegional = str_ends_with($endpointHost, '.rep.googleapis.com') + || str_ends_with($endpointHost, '.rep.sandbox.googleapis.com'); + $isDefaultUniverse = $options['universeDomain'] === GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN; $this->credentialsWrapper = $this->createCredentialsWrapper( $options['credentials'], $options['credentialsConfig'] + [ - 'enableRegionalAccessBoundary' => $enableRegionalAccessBoundary && !$isRegional + 'enableRegionalAccessBoundary' => $enableRegionalAccessBoundary + && !$isRegional + && $isDefaultUniverse, ], $options['universeDomain'], ); diff --git a/Gax/tests/Unit/ClientOptionsTraitTest.php b/Gax/tests/Unit/ClientOptionsTraitTest.php index a5c9d964a57f..76b71b7e09e1 100644 --- a/Gax/tests/Unit/ClientOptionsTraitTest.php +++ b/Gax/tests/Unit/ClientOptionsTraitTest.php @@ -36,6 +36,7 @@ use Google\ApiCore\CredentialsWrapper; use Google\ApiCore\Options\ClientOptions; use Google\ApiCore\ValidationException; +use Google\Auth\Credentials\ServiceAccountCredentials; use Google\Auth\CredentialsLoader; use Google\Auth\FetchAuthTokenInterface; use Google\Auth\GetUniverseDomainInterface; @@ -747,4 +748,38 @@ public function testExceptionIsRaisedIfOptionsIsInvalid() ]; $this->clientStub->buildClientOptions($optionsArray); } + + public function testCreateCredentialsWrapperWithMismatchedUniverseDomainAndRegionalAccessBoundaryThrows() + { + $this->expectException(ValidationException::class); + $this->expectExceptionMessage( + 'The configured universe domain (example.com) does not match ' + . 'the credential universe domain (googleapis.com)' + ); + + $wrapper = CredentialsWrapper::build([ + 'keyFile' => [ + 'type' => 'service_account', + 'client_email' => 'test@example.com', + 'private_key' => 'fake-key', + ], + 'enableRegionalAccessBoundary' => true, + ]); + + $this->clientStub->createCredentialsWrapper($wrapper, [], 'example.com'); + } + + public function testCreateCredentialsWrapperWithMismatchedUniverseDomainWithoutRegionalAccessBoundaryAllowed() + { + $wrapper = new CredentialsWrapper(new ServiceAccountCredentials(null, [ + 'type' => 'service_account', + 'client_email' => 'test@example.com', + 'private_key' => 'fake-key', + ])); + + $this->assertSame( + $wrapper, + $this->clientStub->createCredentialsWrapper($wrapper, [], 'example.com') + ); + } } diff --git a/Gax/tests/Unit/CredentialsWrapperTest.php b/Gax/tests/Unit/CredentialsWrapperTest.php index 428957daf1b1..955b7e0edfdc 100644 --- a/Gax/tests/Unit/CredentialsWrapperTest.php +++ b/Gax/tests/Unit/CredentialsWrapperTest.php @@ -643,6 +643,113 @@ public function testSerializeCredentialsWrapper() $this->assertIsString($serialized); } + public function testBuildDisablesRegionalAccessBoundaryOutsideDefaultUniverseDomain() + { + $serviceAccountKey = [ + 'type' => 'service_account', + 'client_email' => 'test@example.com', + 'private_key' => 'fake-key', + ]; + $expectedKeyCreds = new ServiceAccountCredentials( + null, + $serviceAccountKey, + enableRegionalAccessBoundary: false + ); + $expectedKeyCreds->useJwtAccessWithScope(); + $this->assertEquals( + new CredentialsWrapper( + new FetchAuthTokenCache($expectedKeyCreds, [], new MemoryCacheItemPool()), + null, + 'example.com' + ), + CredentialsWrapper::build( + [ + 'keyFile' => $serviceAccountKey, + 'enableRegionalAccessBoundary' => true, + ], + 'example.com' + ) + ); + + $previousEnv = getenv('GOOGLE_APPLICATION_CREDENTIALS'); + $tmpKeyFile = tempnam(sys_get_temp_dir(), 'sa-key-'); + file_put_contents($tmpKeyFile, json_encode($serviceAccountKey)); + try { + $this->setEnv('GOOGLE_APPLICATION_CREDENTIALS', $tmpKeyFile); + $wrapper = CredentialsWrapper::build( + ['enableRegionalAccessBoundary' => true, 'enableCaching' => false], + 'example.com' + ); + $this->assertEquals( + new CredentialsWrapper($expectedKeyCreds, null, 'example.com'), + $wrapper + ); + } finally { + $this->setEnv('GOOGLE_APPLICATION_CREDENTIALS', $previousEnv === false ? null : $previousEnv); + @unlink($tmpKeyFile); + } + } + + public function testBuildRequiresStrictBooleanForEnableRegionalAccessBoundary() + { + $serviceAccountKey = [ + 'type' => 'service_account', + 'client_email' => 'test@example.com', + 'private_key' => 'fake-key', + ]; + $expectedKeyCreds = new ServiceAccountCredentials( + null, + $serviceAccountKey, + enableRegionalAccessBoundary: false + ); + $expectedKeyCreds->useJwtAccessWithScope(); + + foreach (['false', 'true', '1', 1] as $nonBoolValue) { + $this->assertEquals( + new CredentialsWrapper( + new FetchAuthTokenCache($expectedKeyCreds, [], new MemoryCacheItemPool()), + null + ), + CredentialsWrapper::build([ + 'keyFile' => $serviceAccountKey, + 'enableRegionalAccessBoundary' => $nonBoolValue, + ]) + ); + } + } + + public function testCheckUniverseDomainOnGceCredentialsChecksWhenRegionalAccessBoundaryEnabled() + { + $this->expectException(ValidationException::class); + $this->expectExceptionMessage( + 'The configured universe domain (example.com) does not match ' + . 'the credential universe domain (googleapis.com)' + ); + + $fetcher = new GCECredentials( + universeDomain: 'googleapis.com', + enableRegionalAccessBoundary: true + ); + $wrapper = new CredentialsWrapper( + new FetchAuthTokenCache($fetcher, [], new MemoryCacheItemPool()), + null, + 'example.com' + ); + + $wrapper->checkUniverseDomain(); + } + + public function testCheckUniverseDomainOnGceCredentialsUsesAuthHttpHandlerWhenRegionalAccessBoundaryEnabled() + { + $fetcher = new GCECredentials(enableRegionalAccessBoundary: true); + $fetcher->setIsOnGce(true); + $httpHandler = fn () => new \GuzzleHttp\Psr7\Response(200, [], 'example.com'); + $wrapper = new CredentialsWrapper($fetcher, $httpHandler, 'example.com'); + + $wrapper->checkUniverseDomain(); + $this->assertSame('example.com', $fetcher->getUniverseDomain($httpHandler)); + } + private function setEnv(string $env, ?string $value = null) { if ($value === null) { diff --git a/Gax/tests/Unit/GapicClientTraitTest.php b/Gax/tests/Unit/GapicClientTraitTest.php index 85153e5cb316..c62ddc4e77a0 100644 --- a/Gax/tests/Unit/GapicClientTraitTest.php +++ b/Gax/tests/Unit/GapicClientTraitTest.php @@ -983,8 +983,12 @@ public function setClientOptionsData() * @runInSeparateProcess * @preserveGlobalState disabled */ - public function testBuildClientOptionsRegionalEndpoint(?string $apiEndpoint, ?string $envVarValue, bool $rabEnabled) - { + public function testBuildClientOptionsRegionalEndpoint( + ?string $apiEndpoint, + ?string $envVarValue, + bool $rabEnabled, + ?string $universeDomain = null + ) { if ($envVarValue !== null) { putenv('GOOGLE_AUTH_TRUST_BOUNDARY_ENABLE_EXPERIMENT=' . $envVarValue); } @@ -999,9 +1003,14 @@ public function createCredentialsWrapper($credentials, array $credentialsConfig, } }; - $clientOptions = $client->buildClientOptions( - $apiEndpoint !== null ? ['apiEndpoint' => $apiEndpoint] : [] - ); + $options = []; + if ($apiEndpoint !== null) { + $options['apiEndpoint'] = $apiEndpoint; + } + if ($universeDomain !== null) { + $options['universeDomain'] = $universeDomain; + } + $clientOptions = $client->buildClientOptions($options); $client->setClientOptions($clientOptions); $this->assertEquals( @@ -1015,11 +1024,16 @@ public function buildClientOptionsRegionalEndpointData() return [ ['test.googleapis.com', 'true', true], ['test.rep.googleapis.com', 'true', false], + ['test.rep.googleapis.com:443', 'true', false], ['test.rep.sandbox.googleapis.com', 'true', false], + ['test.rep.sandbox.googleapis.com:443', 'true', false], ['test.googleapis.com', 'false', false], ['test.googleapis.com', null, false], ['', 'true', true], // Empty endpoint case [null, 'true', true], // Unset endpoint case + ['test.googleapis.com', 'true', false, 'example.com'], + [null, 'true', false, 'example.com'], + [null, 'true', true, 'googleapis.com'], ]; } diff --git a/Spanner/src/OpenTelemetry/OtlpMetricsExporter.php b/Spanner/src/OpenTelemetry/OtlpMetricsExporter.php index 5e0dc0f71e5c..fc78f9b38f2d 100644 --- a/Spanner/src/OpenTelemetry/OtlpMetricsExporter.php +++ b/Spanner/src/OpenTelemetry/OtlpMetricsExporter.php @@ -33,6 +33,10 @@ namespace Google\Cloud\Spanner\OpenTelemetry; use Google\ApiCore\CredentialsWrapper; +use Google\Auth\Credentials\GCECredentials; +use Google\Auth\FetchAuthTokenCache; +use Google\Auth\FetchAuthTokenInterface; +use Google\Auth\GetUniverseDomainInterface; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\HandlerStack; use OpenTelemetry\Contrib\Otlp\MetricExporter as OtlpMetricExporter; @@ -43,6 +47,7 @@ use OpenTelemetry\SDK\Metrics\MetricMetadataInterface; use OpenTelemetry\SDK\Metrics\PushMetricExporterInterface; use Psr\Http\Message\RequestInterface; +use ReflectionProperty; use Throwable; /** @@ -55,7 +60,12 @@ class OtlpMetricsExporter implements PushMetricExporterInterface, AggregationTem { private const DEFAULT_ENDPOINT = 'https://telemetry.googleapis.com/v1/metrics'; - private PushMetricExporterInterface $otlpExporter; + private ?PushMetricExporterInterface $otlpExporter = null; + + private ?GCECredentials $gceCredentials = null; + + /** @var callable|null */ + private $authHttpHandler = null; /** * @param CredentialsWrapper $credentials The credentials wrapper for metric export. @@ -69,6 +79,16 @@ public function __construct( array $options = [], ?PushMetricExporterInterface $otlpExporter = null ) { + if (!$this->isDefaultUniverseDomain($credentials, $options)) { + return; + } + + $fetcher = $this->unwrapCredentialsFetcher($credentials); + if ($fetcher instanceof GCECredentials) { + $this->gceCredentials = $fetcher; + $this->authHttpHandler = $this->getAuthHttpHandler($credentials); + } + if ($otlpExporter !== null) { $this->otlpExporter = $otlpExporter; return; @@ -112,7 +132,18 @@ public function __construct( */ public function export(iterable $batch): bool { + if ($this->otlpExporter === null) { + return false; + } + try { + if ($this->gceCredentials !== null + && $this->gceCredentials->getUniverseDomain($this->authHttpHandler) + !== GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN + ) { + return false; + } + return $this->otlpExporter->export($batch); } catch (Throwable $e) { return false; @@ -126,6 +157,10 @@ public function export(iterable $batch): bool */ public function forceFlush(): bool { + if ($this->otlpExporter === null) { + return false; + } + try { return $this->otlpExporter->forceFlush(); } catch (Throwable $e) { @@ -140,6 +175,10 @@ public function forceFlush(): bool */ public function shutdown(): bool { + if ($this->otlpExporter === null) { + return false; + } + try { return $this->otlpExporter->shutdown(); } catch (Throwable $e) { @@ -157,4 +196,55 @@ public function temporality(MetricMetadataInterface $metric): Temporality|string { return Temporality::CUMULATIVE; } + + private function isDefaultUniverseDomain(CredentialsWrapper $credentials, array $options): bool + { + $universeDomain = $options['universeDomain'] ?? GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN; + if ($universeDomain !== GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN) { + return false; + } + + $wrapperUniverseProp = new ReflectionProperty(CredentialsWrapper::class, 'universeDomain'); + if ($wrapperUniverseProp->isInitialized($credentials) + && $wrapperUniverseProp->getValue($credentials) !== GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN + ) { + return false; + } + + $fetcher = $this->unwrapCredentialsFetcher($credentials); + if ($fetcher instanceof GetUniverseDomainInterface + && !$fetcher instanceof GCECredentials + && $fetcher->getUniverseDomain() !== GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN + ) { + return false; + } + + return true; + } + + private function unwrapCredentialsFetcher(CredentialsWrapper $credentials): ?FetchAuthTokenInterface + { + $fetcherProp = new ReflectionProperty(CredentialsWrapper::class, 'credentialsFetcher'); + if (!$fetcherProp->isInitialized($credentials)) { + return null; + } + + $fetcher = $fetcherProp->getValue($credentials); + while ($fetcher instanceof FetchAuthTokenCache) { + $fetcher = $fetcher->getFetcher(); + } + + return $fetcher instanceof FetchAuthTokenInterface ? $fetcher : null; + } + + private function getAuthHttpHandler(CredentialsWrapper $credentials): ?callable + { + $handlerProp = new ReflectionProperty(CredentialsWrapper::class, 'authHttpHandler'); + if (!$handlerProp->isInitialized($credentials)) { + return null; + } + + $handler = $handlerProp->getValue($credentials); + return is_callable($handler) ? $handler : null; + } } diff --git a/Spanner/src/SpannerClient.php b/Spanner/src/SpannerClient.php index 596191b98f55..3e690db02b96 100644 --- a/Spanner/src/SpannerClient.php +++ b/Spanner/src/SpannerClient.php @@ -1066,7 +1066,12 @@ private function configureMetrics( ): void { $timeoutMillis = $this->pluck('metricsTimeoutMillis', $options, false) ?? 100; - if (!$this->pluck('enableBuiltInMetrics', $options, false)) { + if ($this->pluck('enableBuiltInMetrics', $options, false) !== true) { + return; + } + + $universeDomain = $options['universeDomain'] ?? GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN; + if ($universeDomain !== GetUniverseDomainInterface::DEFAULT_UNIVERSE_DOMAIN) { return; } diff --git a/Spanner/tests/Unit/OpenTelemetry/OtlpMetricsExporterTest.php b/Spanner/tests/Unit/OpenTelemetry/OtlpMetricsExporterTest.php index 7909e4d25997..f52cf28f3174 100644 --- a/Spanner/tests/Unit/OpenTelemetry/OtlpMetricsExporterTest.php +++ b/Spanner/tests/Unit/OpenTelemetry/OtlpMetricsExporterTest.php @@ -188,4 +188,91 @@ public function testExportFailureReturnsFalse() $result = $exporter->export([$metric]); $this->assertFalse($result); } + + public function testDisabledWithNonDefaultUniverseDomainOption() + { + $mockCredentials = $this->prophesize(\Google\ApiCore\CredentialsWrapper::class); + $mockOtlpExporter = $this->prophesize(PushMetricExporterInterface::class); + $mockOtlpExporter->export(Argument::any())->shouldNotBeCalled(); + $mockOtlpExporter->forceFlush()->shouldNotBeCalled(); + $mockOtlpExporter->shutdown()->shouldNotBeCalled(); + + $exporter = new OtlpMetricsExporter( + $mockCredentials->reveal(), + 100, + ['universeDomain' => 'example.com'], + $mockOtlpExporter->reveal() + ); + + $this->assertFalse($exporter->export([])); + $this->assertFalse($exporter->forceFlush()); + $this->assertFalse($exporter->shutdown()); + } + + public function testDisabledWithNonDefaultCredentialsWrapperUniverseDomain() + { + $creds = new \Google\Auth\Credentials\GCECredentials(universeDomain: 'example.com'); + $wrapper = new \Google\ApiCore\CredentialsWrapper($creds, null, 'example.com'); + $mockOtlpExporter = $this->prophesize(PushMetricExporterInterface::class); + $mockOtlpExporter->export(Argument::any())->shouldNotBeCalled(); + + $exporter = new OtlpMetricsExporter( + $wrapper, + 100, + [], + $mockOtlpExporter->reveal() + ); + + $this->assertFalse($exporter->export([])); + $this->assertFalse($exporter->forceFlush()); + $this->assertFalse($exporter->shutdown()); + } + + public function testDisabledWithNonDefaultFetcherUniverseDomain() + { + $fetcher = new \Google\Auth\Credentials\ServiceAccountCredentials(null, [ + 'type' => 'service_account', + 'client_email' => 'test@example.com', + 'private_key' => 'fake-key', + 'universe_domain' => 'example.com', + ]); + $wrapper = new \Google\ApiCore\CredentialsWrapper($fetcher); + $mockOtlpExporter = $this->prophesize(PushMetricExporterInterface::class); + $mockOtlpExporter->export(Argument::any())->shouldNotBeCalled(); + + $exporter = new OtlpMetricsExporter( + $wrapper, + 100, + [], + $mockOtlpExporter->reveal() + ); + + $this->assertFalse($exporter->export([])); + } + + public function testGuzzleMiddlewareSkipsExportForNonDefaultGceCredentials() + { + $gce = new \Google\Auth\Credentials\GCECredentials(universeDomain: 'example.com'); + $wrapper = new \Google\ApiCore\CredentialsWrapper($gce); + + $mockHandler = new \GuzzleHttp\Handler\MockHandler([ + new \GuzzleHttp\Psr7\Response(200, [], ''), + ]); + $handlerStack = \GuzzleHttp\HandlerStack::create($mockHandler); + + $exporter = new OtlpMetricsExporter( + $wrapper, + 100, + ['handlerStack' => $handlerStack] + ); + + $scope = new InstrumentationScope('google-cloud-spanner', '1.0.0', null, Attributes::create([])); + $resource = ResourceInfo::create(Attributes::create([])); + $point = new NumberDataPoint(1, Attributes::create([]), 1000, 2000); + $sum = new Sum([$point], Temporality::CUMULATIVE, true); + $metric = new OTelMetric($scope, $resource, 'attempt_count', '1', 'desc', $sum); + + $this->assertFalse($exporter->export([$metric])); + $this->assertNull($mockHandler->getLastRequest()); + } } diff --git a/Spanner/tests/Unit/SpannerClientTest.php b/Spanner/tests/Unit/SpannerClientTest.php index 62e231cac99b..79c15c6930a1 100644 --- a/Spanner/tests/Unit/SpannerClientTest.php +++ b/Spanner/tests/Unit/SpannerClientTest.php @@ -920,4 +920,57 @@ public function testSpannerClientInstantiatesWithoutDelayWhenMetricsDisabled() // If it probed the GCE metadata server without a mock, it would take ~1.5s to time out. $this->assertLessThan(1.0, $end - $start); } + + public function testBuiltInMetricsDisabledOutsideDefaultUniverseDomain() + { + $gapicSpannerClient = $this->prophesize(GapicSpannerClient::class); + $gapicSpannerClient->prependMiddleware(Argument::any()) + ->shouldBeCalledTimes(1); + $gapicSpannerClient->addMiddleware(Argument::any()) + ->shouldBeCalledTimes(1); + + new SpannerClient([ + 'projectId' => self::PROJECT, + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'gapicSpannerClient' => $gapicSpannerClient->reveal(), + 'enableBuiltInMetrics' => true, + 'universeDomain' => 'example.com', + ]); + } + + public function testBuiltInMetricsRequiresStrictBoolean() + { + $gapicSpannerClient = $this->prophesize(GapicSpannerClient::class); + $gapicSpannerClient->prependMiddleware(Argument::any()) + ->shouldBeCalledTimes(1); + $gapicSpannerClient->addMiddleware(Argument::any()) + ->shouldBeCalledTimes(1); + + new SpannerClient([ + 'projectId' => self::PROJECT, + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'gapicSpannerClient' => $gapicSpannerClient->reveal(), + 'enableBuiltInMetrics' => 'false', + ]); + } + + /** + * @runInSeparateProcess + */ + public function testBuiltInMetricsDisabledWhenUniverseDomainEnvVarSet() + { + putenv('GOOGLE_CLOUD_UNIVERSE_DOMAIN=example.com'); + $gapicSpannerClient = $this->prophesize(GapicSpannerClient::class); + $gapicSpannerClient->prependMiddleware(Argument::any()) + ->shouldBeCalledTimes(1); + $gapicSpannerClient->addMiddleware(Argument::any()) + ->shouldBeCalledTimes(1); + + new SpannerClient([ + 'projectId' => self::PROJECT, + 'credentials' => Fixtures::KEYFILE_STUB_FIXTURE(), + 'gapicSpannerClient' => $gapicSpannerClient->reveal(), + 'enableBuiltInMetrics' => true, + ]); + } }