Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
42 changes: 38 additions & 4 deletions Auth/src/Credentials/ExternalAccountCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
12 changes: 10 additions & 2 deletions Auth/src/Credentials/GCECredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -255,6 +257,7 @@ public function __construct(
$this->quotaProject = $quotaProject;
$this->serviceAccountIdentity = $serviceAccountIdentity;
$this->universeDomain = $universeDomain;
$this->hasExplicitUniverseDomain = null !== $universeDomain && '' !== $universeDomain;
$this->enableRegionalAccessBoundary = $enableRegionalAccessBoundary;
}

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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(
Expand Down
84 changes: 73 additions & 11 deletions Auth/src/Credentials/ImpersonatedServiceAccountCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -77,6 +82,8 @@ class ImpersonatedServiceAccountCredentials extends CredentialsLoader implements

private int $lifetime;

private ?string $universeDomain = null;

/**
* @var array<mixed>|null
*/
Expand Down Expand Up @@ -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'
) {
Expand All @@ -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 ?? [];
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}
}
16 changes: 16 additions & 0 deletions Auth/src/Credentials/RegionalAccessBoundaryTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> $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';
Expand Down
38 changes: 30 additions & 8 deletions Auth/src/Credentials/ServiceAccountCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;
}
Expand Down
23 changes: 23 additions & 0 deletions Auth/tests/Unit/ApplicationDefaultCredentialsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down
Loading
Loading