Skip to content

Commit

Permalink
return default universe domain when MDS returns empty string
Browse files Browse the repository at this point in the history
  • Loading branch information
bshaffer committed Sep 12, 2023
1 parent 602e2fe commit 961e021
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/Credentials/GCECredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -552,19 +552,25 @@ public function getUniverseDomain(callable $httpHandler = null): string
return self::DEFAULT_UNIVERSE_DOMAIN;
}

// If we know the metadata server exists, but it returns a 404 for the universe domain, we
// can safely assume this is an older metadata server running in GCU, and so we can return
// the default universe domain.
try {
$this->universeDomain = $this->getFromMetadata(
$httpHandler,
self::getUniverseDomainUri()
);
} catch (ClientException $e) {
if ($e->hasResponse() && 404 == $e->getResponse()->getStatusCode()) {
return self::DEFAULT_UNIVERSE_DOMAIN;
// If the metadata server exists, but returns a 404 for the universe domain, the auth
// libraries should safely assume this is an older metadata server running in GCU, and
// should return the default universe domain.
if (!$e->hasResponse() || 404 != $e->getResponse()->getStatusCode()) {
throw $e;
}
throw $e;
$this->universeDomain = self::DEFAULT_UNIVERSE_DOMAIN;
}

// We expect in some cases the metadata server will return an empty string for the universe
// domain. In this case, the auth library MUST return the default universe domain.
if ('' === $this->universeDomain) {
$this->universeDomain = self::DEFAULT_UNIVERSE_DOMAIN;
}

return $this->universeDomain;
Expand Down
21 changes: 21 additions & 0 deletions tests/Credentials/GCECredentialsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,27 @@ public function testGetUniverseDomain()
$this->assertEquals($expected, $creds->getUniverseDomain($httpHandler));
}

public function testGetUniverseDomainEmptyStringReturnsDefault()
{
$creds = new GCECredentials();
$creds->setIsOnGce(true);

// Pretend we are on GCE and mock the MDS returning an empty string for the universe domain.
$httpHandler = function ($request) {
$this->assertEquals(
'/computeMetadata/v1/universe/universe_domain',
$request->getUri()->getPath()
);
return new Psr7\Response(200, [], Utils::streamFor(''));
};

// Assert the default universe domain is returned instead of the empty string.
$this->assertEquals(
GCECredentials::DEFAULT_UNIVERSE_DOMAIN,
$creds->getUniverseDomain($httpHandler)
);
}

public function testExplicitUniverseDomain()
{
$expected = 'example-universe.com';
Expand Down

0 comments on commit 961e021

Please sign in to comment.