Skip to content

ImpersonatedServiceAccountCredentials incorrectly caches and retrieves user token instead of id token #622

@lykbl

Description

@lykbl

Environment details

  • OS: macOS Sequoia 15.5
  • PHP version: 8.3.16
  • Package name and version: googleapis/google-auth-library-php 1.47.1

Steps to reproduce

  1. login with a --impersonate-service-account
gcloud auth application-default login --impersonate-service-account=*@*.iam.gserviceaccount.com
Credentials saved to file: [~/.config/gcloud/application_default_credentials.json]
  1. Create ApplicationDefaultCredentials::getIdTokenMiddleware with $cacheConfig and $cache and credentials from step 1
  2. Send 2 requests to the same endpoint that has IAP configured
  3. Second request fails as getLastReceivedToken() calls OAuth2::getLastReceivedToken() which returns incorrect token
src/FetchAuthTokenCache.php
:268
if (!$cached && $token = $this->fetcher->getLastReceivedToken()) {
    $this->saveAuthTokenInCache($token, $authUri);
}

Example

putenv('GOOGLE_APPLICATION_CREDENTIALS=~/.config/gcloud/application_default_credentials.json');
$targetAudience = '$YOUR_AUDIENCE';
$baseUri = '$YOU_IAP_URL';
$url = '$YOUR_IAP_ENDPOINT';

$stack = HandlerStack::create();

$memoryCache = new MemoryCacheItemPool;
$cacheConfig = ['prefix' => 'your_cache_key'];
$middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($targetAudience, null, $cacheConfig, $memoryCache);
$stack->push($middleware);

$options = [
  'handler' => $stack,
  'auth' => 'google_auth',
  'base_uri' => $baseUri,
];
$client = new Client($options);
 
$res = $client->get($url);

// Will throw exception
$res = $client->get($url);

Example fix

src/Credentials/ImpersonatedServiceAccountCredentials.php
public function fetchAuthToken(?callable $httpHandler = null) {
...
        $token = match ($this->isIdTokenRequest()) {
            true => ['id_token' => $body['token']],
            false => [
                'access_token' => $body['accessToken'],
                'expires_at' => strtotime($body['expireTime']),
            ]
        };
        $this->lastReceivedToken = $token;

        return $token;
}

    public function getLastReceivedToken()
    {
        return $this->lastReceivedToken;
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions