<?php
namespace Google\Auth\Credentials;
use Google\Auth\CacheTrait;
use Google\Auth\CredentialsLoader;
use Google\Auth\FetchAuthTokenInterface;
use Google\Auth\GetUniverseDomainInterface;
use Google\Auth\HttpHandler\HttpClientCache;
use Google\Auth\HttpHandler\HttpHandlerFactory;
use Google\Auth\IamSignerTrait;
use Google\Auth\SignBlobInterface;
use GuzzleHttp\Psr7\Request;
use InvalidArgumentException;
use LogicException;
class ImpersonatedServiceAccountCredentials extends CredentialsLoader implements
SignBlobInterface,
GetUniverseDomainInterface
{
use CacheTrait;
use IamSignerTrait;
private const CRED_TYPE = 'imp';
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';
protected $impersonatedServiceAccountName;
protected FetchAuthTokenInterface $sourceCredentials;
private string $serviceAccountImpersonationUrl;
private array $delegates;
private string|array $targetScope;
private int $lifetime;
public function __construct(
string|array|null $scope,
string|array $jsonKey,
private ?string $targetAudience = null,
string|array|null $defaultScope = null,
) {
if (is_string($jsonKey)) {
if (!file_exists($jsonKey)) {
throw new InvalidArgumentException('file does not exist');
}
$json = file_get_contents($jsonKey);
if (!$jsonKey = json_decode((string) $json, true)) {
throw new LogicException('invalid json for auth config');
}
}
if (!array_key_exists('service_account_impersonation_url', $jsonKey)) {
throw new LogicException(
'json key is missing the service_account_impersonation_url field'
);
}
if (!array_key_exists('source_credentials', $jsonKey)) {
throw new LogicException('json key is missing the source_credentials field');
}
$jsonKeyScope = $jsonKey['scopes'] ?? null;
$scope = $scope ?: $jsonKeyScope ?: $defaultScope;
if ($scope && $targetAudience) {
throw new InvalidArgumentException(
'Scope and targetAudience cannot both be supplied'
);
}
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 (
$targetAudience !== null
&& $jsonKey['source_credentials']['type'] === 'service_account'
) {
$scope = self::IAM_SCOPE;
}
$jsonKey['source_credentials'] = match ($jsonKey['source_credentials']['type'] ?? null) {
'service_account' => new ServiceAccountCredentials($scope, $jsonKey['source_credentials']),
'authorized_user' => new UserRefreshCredentials($scope, $jsonKey['source_credentials']),
'external_account' => new ExternalAccountCredentials($scope, $jsonKey['source_credentials']),
default => throw new \InvalidArgumentException('invalid value in the type field'),
};
}
$this->targetScope = $scope ?? [];
$this->lifetime = $jsonKey['lifetime'] ?? 3600;
$this->delegates = $jsonKey['delegates'] ?? [];
$this->serviceAccountImpersonationUrl = $jsonKey['service_account_impersonation_url'];
$this->impersonatedServiceAccountName = $this->getImpersonatedServiceAccountNameFromUrl(
$this->serviceAccountImpersonationUrl
);
$this->sourceCredentials = $jsonKey['source_credentials'];
}
private function getImpersonatedServiceAccountNameFromUrl(
string $serviceAccountImpersonationUrl
): string {
$fields = explode('/', $serviceAccountImpersonationUrl);
$lastField = end($fields);
$splitter = explode(':', $lastField);
return $splitter[0];
}
public function getClientName(?callable $unusedHttpHandler = null)
{
return $this->impersonatedServiceAccountName;
}
public function fetchAuthToken(?callable $httpHandler = null)
{
$httpHandler = $httpHandler ?? HttpHandlerFactory::build(HttpClientCache::getHttpClient());
$authToken = $this->sourceCredentials->fetchAuthToken(
$httpHandler,
$this->applyTokenEndpointMetrics([], 'at')
);
$headers = $this->applyTokenEndpointMetrics([
'Content-Type' => 'application/json',
'Cache-Control' => 'no-store',
'Authorization' => sprintf('Bearer %s', $authToken['access_token'] ?? $authToken['id_token']),
], $this->isIdTokenRequest() ? 'it' : 'at');
$body = match ($this->isIdTokenRequest()) {
true => [
'audience' => $this->targetAudience,
'includeEmail' => true,
],
false => [
'scope' => $this->targetScope,
'delegates' => $this->delegates,
'lifetime' => sprintf('%ss', $this->lifetime),
]
};
$url = $this->serviceAccountImpersonationUrl;
if ($this->isIdTokenRequest()) {
$regex = '/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/';
if (!preg_match($regex, $url, $matches)) {
throw new InvalidArgumentException(
'Invalid service account impersonation URL - unable to parse service account email'
);
}
$url = str_replace(
'UNIVERSE_DOMAIN',
$this->getUniverseDomain(),
sprintf(self::ID_TOKEN_IMPERSONATION_URL, $matches['email'])
);
}
$request = new Request(
'POST',
$url,
$headers,
(string) json_encode($body)
);
$response = $httpHandler($request);
$body = json_decode((string) $response->getBody(), true);
return match ($this->isIdTokenRequest()) {
true => ['id_token' => $body['token']],
false => [
'access_token' => $body['accessToken'],
'expires_at' => strtotime($body['expireTime']),
]
};
}
public function getCacheKey()
{
return $this->getFullCacheKey(
$this->serviceAccountImpersonationUrl . $this->sourceCredentials->getCacheKey()
);
}
public function getLastReceivedToken()
{
return $this->sourceCredentials->getLastReceivedToken();
}
protected function getCredType(): string
{
return self::CRED_TYPE;
}
private function isIdTokenRequest(): bool
{
return !is_null($this->targetAudience);
}
public function getUniverseDomain(): string
{
return $this->sourceCredentials instanceof GetUniverseDomainInterface
? $this->sourceCredentials->getUniverseDomain()
: self::DEFAULT_UNIVERSE_DOMAIN;
}
}