Skip to content

Commit 0056791

Browse files
committed
Almost all tests working for GoogleAuth
1 parent d009494 commit 0056791

7 files changed

Lines changed: 239 additions & 318 deletions

File tree

UPGRADING.md

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -305,8 +305,6 @@ A trait is a better fit as it's a utility class.
305305
<td><code>Credentials\GCECredentials</code>
306306
<p>
307307
=> <code>Credentials\ComputeCredentials</code>
308-
<p>
309-
=> <code>Credentials\MetadataCredentials</code>
310308
</td>
311309
<td>"Compute" represents a suite of products (App Engine, Compute Engine, Cloud Functions, Cloud Run) which all have a metadata server, and so use these credentials.
312310
<p>
@@ -637,6 +635,18 @@ Proper caching should make this unnecessary
637635
Proper caching should make this unnecessary
638636
</td>
639637
</tr>
638+
<tr>
639+
<td><code>GCECredentials</code>
640+
<p>
641+
<code>:: getTokenUri</code>
642+
<p>
643+
<code>:: getClientNameUri</code>
644+
</td>
645+
<td><strong>not needed</strong>
646+
<p>
647+
The URIs used to call the metadata server is implementation detail, and does not need to be public
648+
</td>
649+
</tr>
640650
<tr>
641651
<td><code>SignBlobInterface</code>
642652
<p>

src/Auth/Credentials/ComputeCredentials.php

Lines changed: 13 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -89,21 +89,6 @@ class ComputeCredentials implements
8989
*/
9090
private const FLAVOR_HEADER = 'Metadata-Flavor';
9191

92-
/**
93-
* Flag used to ensure that the onGCE test is only done once;.
94-
*
95-
* @var bool
96-
*/
97-
private $hasCheckedOnGce = false;
98-
99-
/**
100-
* Flag that stores the value of the onGCE check.
101-
*
102-
* @var bool
103-
*/
104-
private $isOnGce = false;
105-
106-
10792
/**
10893
* @var string|null
10994
*/
@@ -168,15 +153,7 @@ public function __construct(array $options = [])
168153
);
169154
}
170155

171-
$tokenUri = self::getTokenUri($options['serviceAccountIdentity']);
172-
if ($options['scope']) {
173-
if (is_string($options['scope'])) {
174-
$options['scope'] = explode(' ', $options['scope']);
175-
}
176-
177-
$options['scope'] = implode(',', $options['scope']);
178-
$tokenUri = $tokenUri . '?scopes='. $options['scope'];
179-
} elseif ($options['targetAudience']) {
156+
if ($options['targetAudience']) {
180157
$tokenUri = self::getIdTokenUri($options['serviceAccountIdentity']);
181158
$tokenUri = sprintf(
182159
'http://%s/computeMetadata/%s?audience=%s',
@@ -185,6 +162,16 @@ public function __construct(array $options = [])
185162
$options['targetAudience']
186163
);
187164
$this->targetAudience = $options['targetAudience'];
165+
} else {
166+
$tokenUri = self::getAccessTokenUri($options['serviceAccountIdentity']);
167+
if ($options['scope']) {
168+
if (is_string($options['scope'])) {
169+
$options['scope'] = explode(' ', $options['scope']);
170+
}
171+
172+
$options['scope'] = implode(',', $options['scope']);
173+
$tokenUri = $tokenUri . '?scopes='. $options['scope'];
174+
}
188175
}
189176

190177
$this->tokenUri = $tokenUri;
@@ -202,7 +189,7 @@ public function __construct(array $options = [])
202189
* @return string
203190
*/
204191

205-
public static function getTokenUri(
192+
private static function getAccessTokenUri(
206193
string $serviceAccountIdentity = null
207194
): string {
208195
$base = 'http://' . self::METADATA_IP . '/computeMetadata/';
@@ -301,10 +288,6 @@ public static function onCompute(ClientInterface $httpClient): bool
301288
*/
302289
public function fetchAuthToken(): array
303290
{
304-
if (!$this->isOnGce($this->httpClient)) {
305-
return []; // return an empty array with no access token
306-
}
307-
308291
$response = $this->getFromMetadata($this->tokenUri);
309292

310293
if ($this->targetAudience) {
@@ -336,10 +319,6 @@ public function getClientEmail(): string
336319
return $this->clientEmail;
337320
}
338321

339-
if (!$this->isOnGce($this->httpClient)) {
340-
return '';
341-
}
342-
343322
return $this->clientEmail = $this->getFromMetadata(
344323
self::getClientEmailUri($this->serviceAccountIdentity)
345324
);
@@ -380,10 +359,6 @@ public function getProjectId(): ?string
380359
return $this->projectId;
381360
}
382361

383-
if (!$this->isOnGce($this->httpClient)) {
384-
return null;
385-
}
386-
387362
return $this->projectId = $this->getFromMetadata(
388363
self::getProjectIdUri()
389364
);
@@ -399,16 +374,6 @@ public function getQuotaProject(): ?string
399374
return $this->quotaProject;
400375
}
401376

402-
private function isOnGce(): bool
403-
{
404-
if (!$this->hasCheckedOnGce) {
405-
$this->isOnGce = self::onGce($this->httpClient);
406-
$this->hasCheckedOnGce = true;
407-
}
408-
409-
return $this->isOnGce;
410-
}
411-
412377
/**
413378
* Fetch the value of a GCE metadata server URI.
414379
*
@@ -417,8 +382,7 @@ private function isOnGce(): bool
417382
*/
418383
private function getFromMetadata($uri)
419384
{
420-
$httpClient = $this->httpClient;
421-
$resp = $httpClient(
385+
$resp = $this->httpClient->send(
422386
new Request(
423387
'GET',
424388
$uri,

src/Auth/Credentials/ServiceAccountCredentials.php

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ class ServiceAccountCredentials implements
6262
CredentialsInterface,
6363
SignBlobInterface
6464
{
65-
use CredentialsTrait;
65+
use CredentialsTrait {
66+
CredentialsTrait::getRequestMetadata as traitGetRequestMetadata;
67+
}
6668
use PrivateKeySignBlobTrait;
6769
use ServiceAccountApiSignBlobTrait;
6870

@@ -170,11 +172,7 @@ public function __construct($jsonKey, array $options = [])
170172
*/
171173
public function fetchAuthToken(): array
172174
{
173-
// If self-signed JWTs are being used, fetch the last received token
174-
// from memory. Else, fetch it from OAuth2
175-
return $this->useSelfSignedJwt()
176-
? $this->lastReceivedJwtAccessToken
177-
: $this->oauth2->getLastReceivedToken();
175+
return $this->oauth2->fetchAuthToken();
178176
}
179177

180178
/**
@@ -190,31 +188,27 @@ public function getProjectId(): ?string
190188
}
191189

192190
/**
193-
* Updates metadata with the authorization token.
191+
* Returns request metadata with the authorization token.
194192
*
195-
* @param array $metadata metadata hashmap
196-
* @param string $authUri optional auth uri
197193
* @param callable $httpHandler callback which delivers psr7 request
198-
* @return array updated metadata hashmap
194+
* @return array metadata hashmap for request headers
199195
*/
200-
public function updateMetadata(
201-
$metadata,
202-
$authUri = null,
203-
callable $httpHandler = null
204-
) {
196+
public function getRequestMetadata(
197+
ClientInterface $httpHandler = null
198+
): array {
205199
// scope exists. use oauth implementation
206200
if (!$this->useSelfSignedJwt()) {
207-
return parent::updateMetadata($metadata, $authUri, $httpHandler);
201+
return $this->traitGetRequestMetadata($httpHandler);
208202
}
209203

210204
// no scope found. create jwt with the auth uri
211205
$credJson = array(
212-
'private_key' => $this->auth->getSigningKey(),
213-
'client_email' => $this->auth->getIssuer(),
206+
'private_key' => $this->oauth2->getSigningKey(),
207+
'client_email' => $this->oauth2->getIssuer(),
214208
);
215209
$jwtCreds = new ServiceAccountJwtAccessCredentials($credJson);
216210

217-
$updatedMetadata = $jwtCreds->updateMetadata($metadata, $authUri, $httpHandler);
211+
$updatedMetadata = $jwtCreds->getRequestMetadata($httpHandler);
218212

219213
if ($lastReceivedToken = $jwtCreds->getLastReceivedToken()) {
220214
// Keep self-signed JWTs in memory as the last received token
@@ -230,7 +224,7 @@ public function updateMetadata(
230224
*/
231225
public function setSub($sub)
232226
{
233-
$this->auth->setSub($sub);
227+
$this->oauth2->setSub($sub);
234228
}
235229

236230
/**
@@ -274,7 +268,7 @@ public function getClientEmail(): string
274268

275269
private function useSelfSignedJwt()
276270
{
277-
return is_null($this->auth->getScope());
271+
return is_null($this->oauth2->getScope());
278272
}
279273

280274
/**

src/Auth/GoogleAuth.php

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,13 @@
2424
use Google\Auth\Credentials\ServiceAccountCredentials;
2525
use Google\Auth\Credentials\ServiceAccountJwtAccessCredentials;
2626
use Google\Auth\Credentials\CredentialsInterface;
27+
use Google\Auth\Credentials\UserRefreshCredentials;
2728
use Google\Auth\Http\ClientFactory;
2829
use Google\Cache\MemoryCacheItemPool;
2930
use GuzzleHttp\Psr7\Request;
3031
use InvalidArgumentException;
3132
use Psr\Cache\CacheItemPoolInterface;
33+
use RuntimeException;
3234

3335
/**
3436
* GoogleAuth obtains the default credentials for
@@ -110,10 +112,9 @@ public function __construct(array $options = [])
110112
'cacheLifetime' => 1500,
111113
'cachePrefix' => '',
112114
];
113-
114115
$this->httpClient = $options['httpClient'] ?: ClientFactory::build();
115116
$this->cache = $options['cache'] ?: new MemoryCacheItemPool();
116-
$this->cacheLifetme = $options['cacheLifetime'];
117+
$this->cacheLifetime = $options['cacheLifetime'];
117118
$this->cachePrefix = $options['cachePrefix'];
118119
}
119120

@@ -131,8 +132,11 @@ public function __construct(array $options = [])
131132
* @type string $targetAudience The audience for the ID token.
132133
* @type string $audience
133134
* @type string $quotaProject specifies a project to bill for access
134-
* charges associated with the request.
135+
* charges associated with the request.
135136
* @type string $subject
137+
* @type string|array $defaultScope The default scope to use if no
138+
* user-defined scopes exist, expressed either as an Array or as
139+
* a space-delimited string.
136140
* }
137141
* @return CredentialsInterface
138142
* @throws DomainException if no implementation can be obtained.
@@ -146,7 +150,9 @@ public function makeCredentials(array $options = []): CredentialsInterface
146150
'quotaProject' => null,
147151
'subject' => null,
148152
'credentialsFile' => null,
153+
'defaultScope' => null,
149154
];
155+
$anyScope = $options['scope'] ?: $options['defaultScope'];
150156
if (is_null($options['credentialsFile'])) {
151157
$jsonKey = $this->fromEnv() ?: $this->fromWellKnownFile();
152158
} else {
@@ -165,7 +171,7 @@ public function makeCredentials(array $options = []): CredentialsInterface
165171

166172
// Set quota project on jsonKey if passed in
167173
if (isset($options['quotaProject'])) {
168-
$jsonKey['quota_project'] = $options['quotaProject'];
174+
$jsonKey['quota_project_id'] = $options['quotaProject'];
169175
}
170176

171177
switch ($jsonKey['type']) {
@@ -194,7 +200,8 @@ public function makeCredentials(array $options = []): CredentialsInterface
194200
);
195201
}
196202
$creds = new UserRefreshCredentials($jsonKey, [
197-
'scope' => $options['scope'],
203+
'scope' => $anyScope,
204+
'httpClient' => $this->httpClient,
198205
]);
199206
break;
200207
default:
@@ -204,9 +211,10 @@ public function makeCredentials(array $options = []): CredentialsInterface
204211
}
205212
} elseif ($this->onCompute()) {
206213
$creds = new ComputeCredentials([
207-
'scope' => $options['scope'],
214+
'scope' => $anyScope,
208215
'quotaProject' => $options['quotaProject'],
209216
'httpClient' => $this->httpClient,
217+
'targetAudience' => $options['targetAudience'],
210218
]);
211219
}
212220

@@ -229,14 +237,15 @@ public function makeCredentials(array $options = []): CredentialsInterface
229237
*/
230238
public function onCompute(): bool
231239
{
232-
$cacheItem = $this->cache->getItem(self::ON_COMPUTE_CACHE_KEY);
240+
$cacheItem = $this->cache->getItem(
241+
$this->cachePrefix . self::ON_COMPUTE_CACHE_KEY
242+
);
233243

234244
if ($cacheItem->isHit()) {
235245
return $cacheItem->get();
236246
}
237247

238248
$onCompute = ComputeCredentials::onCompute($this->httpClient);
239-
240249
$cacheItem->set($onCompute);
241250
$cacheItem->expiresAfter($this->cacheLifetime);
242251
$this->cache->save($cacheItem);
@@ -283,13 +292,13 @@ private function getCerts(string $location, string $cacheKey): array {
283292

284293
$gotNewCerts = false;
285294
if (!$certs) {
286-
$certs = $this->retrieveCertsFromLocation($location, $options);
295+
$certs = $this->retrieveCertsFromLocation($location);
287296

288297
$gotNewCerts = true;
289298
}
290299

291300
if (!isset($certs['keys'])) {
292-
if ($location !== self::IAP_CERT_URL) {
301+
if ($location !== self::IAP_JWK_URI) {
293302
throw new InvalidArgumentException(
294303
'federated sign-on certs expects "keys" to be set'
295304
);
@@ -353,7 +362,7 @@ private function retrieveCertsFromLocation(string $url): array
353362
*/
354363
private function getCacheKeyFromCertLocation($certsLocation)
355364
{
356-
$key = $certsLocation === self::FEDERATED_SIGNON_CERT_URL
365+
$key = $certsLocation === self::OIDC_CERT_URI
357366
? 'federated_signon_certs_v3'
358367
: sha1($certsLocation);
359368

0 commit comments

Comments
 (0)