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: Change getCacheKey implementation for more unique keys #560

Merged
merged 17 commits into from
Jul 10, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
33 changes: 32 additions & 1 deletion src/Credentials/ExternalAccountCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ class ExternalAccountCredentials implements
private ?string $projectId;
private string $universeDomain;

/**
* Used to calculate the Cache Key for caching
*
* @var array<mixed>
*/
private array $jsonKey;

/**
* @param string|string[] $scope The scope of the access request, expressed either as an array
* or as a space-delimited string.
Expand Down Expand Up @@ -122,6 +129,8 @@ public function __construct(
'workforce_pool_user_project should not be set for non-workforce pool credentials.'
);
}

$this->jsonKey = $jsonKey;
Hectorhammett marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down Expand Up @@ -278,7 +287,7 @@ public function fetchAuthToken(callable $httpHandler = null)

public function getCacheKey()
{
return $this->auth->getCacheKey();
return implode(':', $this->flattenJsonKey($this->jsonKey)) . ':' . $this->auth->getFormattedScopeOrAudience();
}

public function getLastReceivedToken()
Expand Down Expand Up @@ -359,4 +368,26 @@ private function isWorkforcePool(): bool
$regex = '#//iam\.googleapis\.com/locations/[^/]+/workforcePools/#';
return preg_match($regex, $this->auth->getAudience()) === 1;
}

/**
* @param array<mixed> $arr
*
* @return array<string>
*/
private function flattenJsonKey(array $arr): array
{
$result = [];

foreach($arr as $key => $val) {
if (is_array($val)) {
$result = array_merge($result, $this->flattenJsonKey($val));
} elseif ($val === '') {
continue;
} else {
array_push($result, $val);
}
}

return $result;
}
}
2 changes: 1 addition & 1 deletion src/Credentials/GCECredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,7 @@ public function fetchAuthToken(callable $httpHandler = null)
*/
public function getCacheKey()
{
return self::cacheKey;
return $this->tokenUri;
Hectorhammett marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/Credentials/ServiceAccountCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,8 @@ public function fetchAuthToken(callable $httpHandler = null)
*/
public function getCacheKey()
{
$key = $this->auth->getIssuer() . ':' . $this->auth->getCacheKey();
$key = $this->auth->getIssuer() . ':' . $this->auth->getFormattedScopeOrAudience();

if ($sub = $this->auth->getSub()) {
$key .= ':' . $sub;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Credentials/ServiceAccountJwtAccessCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public function fetchAuthToken(callable $httpHandler = null)
*/
public function getCacheKey()
{
return $this->auth->getCacheKey();
return $this->auth->getIssuer() . ':' . $this->auth->getFormattedScopeOrAudience();
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Credentials/UserRefreshCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public function fetchAuthToken(callable $httpHandler = null, array $metricsHeade
*/
public function getCacheKey()
{
return $this->auth->getClientId() . ':' . $this->auth->getCacheKey();
return $this->auth->getClientId() . ':' . $this->auth->getFormattedScopeOrAudience();
}

/**
Expand Down
20 changes: 20 additions & 0 deletions src/OAuth2.php
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,26 @@ public function getCacheKey()
return null;
}

/**
* Obtains the scope or the Audience and formats it for external classes to use
* in generating a cache key.
*
* @return ?string a key that may be used to cache the auth token.
*/
public function getFormattedScopeOrAudience()
Hectorhammett marked this conversation as resolved.
Show resolved Hide resolved
{
if (is_array($this->scope)) {
return implode(':', $this->scope);
}

if ($this->audience) {
return $this->audience;
}

// If scope has not set, return null to indicate no caching.
return null;
}

/**
* Parses the fetched tokens.
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Credentials/ExternalAccountCredentialsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,18 @@ public function testFetchAuthTokenWithWorkforcePoolCredentials()
$this->assertEquals(strtotime($expiry), $authToken['expires_at']);
}

public function testCacheKeyFormat()
{
$credentials = new ExternalAccountCredentials('scope1', $this->baseCreds);
$cacheKey = $credentials->getCacheKey();

// I decided to hand craft this manually to avoid reusing the flattenJsonKey method
// inside the ExternalAccountCredentials class and make
// sure the flat function works properly
$expectedKey = 'external_account:token-url.com:sts-url.com:scope1';
$this->assertEquals($expectedKey, $cacheKey);
}

/**
* @runInSeparateProcess
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -480,8 +480,10 @@ public function testShouldBeTheSameAsOAuth2WithTheSameScope()
{
$testJson = $this->createTestJson();
$scope = ['scope/1', 'scope/2'];
$sa = new ServiceAccountJwtAccessCredentials($testJson);
$this->assertNull($sa->getCacheKey());
$sa = new ServiceAccountJwtAccessCredentials($testJson, $scope);

$expectedKey = $testJson['client_email'] . ':' . implode(':', $scope);
$this->assertEquals($expectedKey, $sa->getCacheKey());
}

public function testReturnsClientEmail()
Expand Down