diff --git a/src/Credentials/ExternalAccountCredentials.php b/src/Credentials/ExternalAccountCredentials.php index 478063be12..c0306ee807 100644 --- a/src/Credentials/ExternalAccountCredentials.php +++ b/src/Credentials/ExternalAccountCredentials.php @@ -52,6 +52,8 @@ class ExternalAccountCredentials implements private ?string $serviceAccountImpersonationUrl; private ?string $workforcePoolUserProject; private ?string $projectId; + /** @var array */ + private ?array $lastImpersonatedAccessToken; private string $universeDomain; /** @@ -270,7 +272,10 @@ public function fetchAuthToken(?callable $httpHandler = null, array $headers = [ $stsToken = $this->auth->fetchAuthToken($httpHandler, $headers); if (isset($this->serviceAccountImpersonationUrl)) { - return $this->getImpersonatedAccessToken($stsToken['access_token'], $httpHandler); + return $this->lastImpersonatedAccessToken = $this->getImpersonatedAccessToken( + $stsToken['access_token'], + $httpHandler + ); } return $stsToken; @@ -301,7 +306,7 @@ public function getCacheKey(): ?string public function getLastReceivedToken() { - return $this->auth->getLastReceivedToken(); + return $this->lastImpersonatedAccessToken ?? $this->auth->getLastReceivedToken(); } /** diff --git a/tests/Credentials/ExternalAccountCredentialsTest.php b/tests/Credentials/ExternalAccountCredentialsTest.php index 4d1f8ae0ed..3cade03037 100644 --- a/tests/Credentials/ExternalAccountCredentialsTest.php +++ b/tests/Credentials/ExternalAccountCredentialsTest.php @@ -293,7 +293,7 @@ public function testFetchAuthTokenWithImpersonation() $this->assertEquals('service-account-impersonation-url.com', (string) $request->getUri()); $requestBody = json_decode((string) $request->getBody(), true); $this->assertEquals(['a-scope'], $requestBody['scope']); - $responseBody = json_encode(['accessToken' => 'def', 'expireTime' => $expiry]); + $responseBody = json_encode(['accessToken' => 'ghi', 'expireTime' => $expiry]); break; } @@ -311,8 +311,11 @@ public function testFetchAuthTokenWithImpersonation() $authToken = $creds->fetchAuthToken($httpHandler); $this->assertArrayHasKey('access_token', $authToken); - $this->assertEquals('def', $authToken['access_token']); + $this->assertEquals('ghi', $authToken['access_token']); $this->assertEquals(strtotime($expiry), $authToken['expires_at']); + + // test that getLastReceivedToken() returns the correct token + $this->assertEquals($authToken, $creds->getLastReceivedToken()); } public function testGetQuotaProject()