Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use IamCredentials endpoint for generating ID tokens outside GDU #581

Merged
merged 7 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
43 changes: 38 additions & 5 deletions src/Credentials/ServiceAccountCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@

namespace Google\Auth\Credentials;

use Firebase\JWT\JWT;
use Google\Auth\CredentialsLoader;
use Google\Auth\GetQuotaProjectInterface;
use Google\Auth\Iam;
use Google\Auth\OAuth2;
use Google\Auth\ProjectIdProviderInterface;
use Google\Auth\ServiceAccountSignerTrait;
Expand Down Expand Up @@ -71,6 +73,7 @@ class ServiceAccountCredentials extends CredentialsLoader implements
* @var string
*/
private const CRED_TYPE = 'sa';
private const IAM_SCOPE = 'https://www.googleapis.com/auth/iam';

/**
* The OAuth2 instance used to conduct authorization.
Expand Down Expand Up @@ -165,6 +168,7 @@ public function __construct(
'scope' => $scope,
'signingAlgorithm' => 'RS256',
'signingKey' => $jsonKey['private_key'],
'signingKeyId' => $jsonKey['private_key_id'] ?? null,
'sub' => $sub,
'tokenCredentialUri' => self::TOKEN_CREDENTIAL_URI,
'additionalClaims' => $additionalClaims,
Expand Down Expand Up @@ -213,9 +217,33 @@ public function fetchAuthToken(callable $httpHandler = null)

return $accessToken;
}
$authRequestType = empty($this->auth->getAdditionalClaims()['target_audience'])
? 'at' : 'it';
return $this->auth->fetchAuthToken($httpHandler, $this->applyTokenEndpointMetrics([], $authRequestType));

if ($this->isIdTokenRequest() && $this->getUniverseDomain() !== self::DEFAULT_UNIVERSE_DOMAIN) {
$now = time();
$jwt = Jwt::encode(
[
'iss' => $this->auth->getIssuer(),
'sub' => $this->auth->getIssuer(),
'scope' => self::IAM_SCOPE,
'exp' => ($now + $this->auth->getExpiry()),
'iat' => ($now - OAuth2::DEFAULT_SKEW_SECONDS),
],
$this->auth->getSigningKey(),
$this->auth->getSigningAlgorithm(),
$this->auth->getSigningKeyId()
);
// We create a new instance of Iam each time because the `$httpHandler` might change.
$idToken = (new Iam($httpHandler, $this->getUniverseDomain()))->generateIdToken(
$this->auth->getIssuer(),
$this->auth->getAdditionalClaims()['target_audience'],
$jwt
);
return ['id_token' => $idToken];
}
return $this->auth->fetchAuthToken(
$httpHandler,
$this->applyTokenEndpointMetrics([], $this->isIdTokenRequest() ? 'it' : 'at')
);
}

/**
Expand Down Expand Up @@ -399,8 +427,8 @@ private function useSelfSignedJwt()
return false;
}

// If claims are set, this call is for "id_tokens"
if ($this->auth->getAdditionalClaims()) {
// Do not use self-signed JWT for ID tokens
if ($this->isIdTokenRequest()) {
return false;
}

Expand All @@ -416,4 +444,9 @@ private function useSelfSignedJwt()

return is_null($this->auth->getScope());
}

private function isIdTokenRequest(): bool
{
return !empty($this->auth->getAdditionalClaims()['target_audience']);
}
}
47 changes: 45 additions & 2 deletions src/Iam.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class Iam
const SIGN_BLOB_PATH = '%s:signBlob?alt=json';
const SERVICE_ACCOUNT_NAME = 'projects/-/serviceAccounts/%s';
private const IAM_API_ROOT_TEMPLATE = 'https://iamcredentials.UNIVERSE_DOMAIN/v1';
private const GENERATE_ID_TOKEN_PATH = '%s:generateIdToken';

/**
* @var callable
Expand Down Expand Up @@ -73,7 +74,6 @@ public function __construct(
*/
public function signBlob($email, $accessToken, $stringToSign, array $delegates = [])
{
$httpHandler = $this->httpHandler;
$name = sprintf(self::SERVICE_ACCOUNT_NAME, $email);
$apiRoot = str_replace('UNIVERSE_DOMAIN', $this->universeDomain, self::IAM_API_ROOT_TEMPLATE);
$uri = $apiRoot . '/' . sprintf(self::SIGN_BLOB_PATH, $name);
Expand Down Expand Up @@ -102,9 +102,52 @@ public function signBlob($email, $accessToken, $stringToSign, array $delegates =
Utils::streamFor(json_encode($body))
);

$res = $httpHandler($request);
$res = ($this->httpHandler)($request);
$body = json_decode((string) $res->getBody(), true);

return $body['signedBlob'];
}

/**
* Sign a string using the IAM signBlob API.
*
* Note that signing using IAM requires your service account to have the
* `iam.serviceAccounts.signBlob` permission, part of the "Service Account
* Token Creator" IAM role.
*
* @param string $clientEmail The service account email.
* @param string $targetAudience The audience for the ID token.
* @param string $bearerToken The token to authenticate the IAM request.
*
* @return string The signed string, base64-encoded.
*/
public function generateIdToken(
string $clientEmail,
string $targetAudience,
string $bearerToken

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps there could be a fourth parameter array $headers = []. This way the calling class (e.g. ImpersonatedServiceAccountCredentials) could add a token endpoint metrics header. (The bearer token could stay as-is as it is required for the id token to be returned.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this feedback! Could you provide me an example of what that would look like? I assume it would look like adding the following in the call to Iam::generateIdToken:

            $idToken = (new Iam($httpHandler, $this->getUniverseDomain()))->generateIdToken(
                $this->auth->getIssuer(),
                $this->auth->getAdditionalClaims()['target_audience'],
                $jwt,
                $this->applyTokenEndpointMetrics([], 'it') // this is the new line
            );

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that is exactly what I had in mind. All requests I encountered getting an acces or id token send metrics headers, so it makes sense to add them here too. The implementation would be something like this.

    /**
     * @param array $headers Optional headers to send to the api, defaults to an empty array
     */
    public function generateIdToken(
        string $clientEmail,
        string $targetAudience,
        string $bearerToken,
        array $headers = [] // -> added optional parameter
): string {
        // ....
       // updated header assignment
       $headers['Authorization'] = 'Bearer ' . $bearerToken; 
        // ....

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has been added in 475bc74

): string {
$name = sprintf(self::SERVICE_ACCOUNT_NAME, $clientEmail);
$apiRoot = str_replace('UNIVERSE_DOMAIN', $this->universeDomain, self::IAM_API_ROOT_TEMPLATE);
$uri = $apiRoot . '/' . sprintf(self::GENERATE_ID_TOKEN_PATH, $name);

$headers = ['Authorization' => 'Bearer ' . $bearerToken];

$body = [
'audience' => $targetAudience,
'includeEmail' => true,
'useEmailAzp' => true,
];

$request = new Psr7\Request(
'POST',
$uri,
$headers,
Utils::streamFor(json_encode($body))
);

$res = ($this->httpHandler)($request);
$body = json_decode((string) $res->getBody(), true);

return $body['token'];
}
}
31 changes: 31 additions & 0 deletions tests/Credentials/ServiceAccountCredentialsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use Google\Auth\CredentialsLoader;
use Google\Auth\OAuth2;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Utils;
use InvalidArgumentException;
Expand Down Expand Up @@ -307,6 +308,36 @@ public function testShouldBeIdTokenWhenTargetAudienceIsSet()
$this->assertEquals(1, $timesCalled);
}

public function testShouldUseIamWhenTargetAudienceAndUniverseDomainIsSet()
{
$testJson = $this->createTestJson();
$testJson['universe_domain'] = 'abc.xyz';

$timesCalled = 0;
$httpHandler = function (Request $request) use (&$timesCalled) {
$timesCalled++;

// Verify Request
$this->assertStringContainsString(':generateIdToken', $request->getUri());
$json = json_decode($request->getBody(), true);
$this->assertArrayHasKey('audience', $json);
$this->assertEquals('a target audience', $json['audience']);

// Verify JWT Bearer Token
$jwt = str_replace('Bearer ', '', $request->getHeaderLine('Authorization'));
list($header, $payload, $sig) = explode('.', $jwt);
$jwtParams = json_decode(base64_decode($payload), true);
$this->assertArrayHasKey('iss', $jwtParams);
$this->assertEquals('test@example.com', $jwtParams['iss']);

// return expected IAM ID token response
return new Psr7\Response(200, [], json_encode(['token' => 'idtoken12345']));
};
$sa = new ServiceAccountCredentials(null, $testJson, null, 'a target audience');
$this->assertEquals('idtoken12345', $sa->fetchAuthToken($httpHandler)['id_token']);
$this->assertEquals(1, $timesCalled);
}

public function testShouldBeOAuthRequestWhenSubIsSet()
{
$testJson = $this->createTestJson();
Expand Down