Skip to content

Commit

Permalink
feat: check product name file on linux for gce
Browse files Browse the repository at this point in the history
  • Loading branch information
bshaffer committed Aug 15, 2023
1 parent dfd1439 commit b163b42
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Credentials/GCECredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ class GCECredentials extends CredentialsLoader implements
*/
const FLAVOR_HEADER = 'Metadata-Flavor';

/**
* The Linux file which contains the product name.
*/
private const GKE_PRODUCT_NAME_FILE = '/sys/class/dmi/id/product_name';

/**
* Note: the explicit `timeout` and `tries` below is a workaround. The underlying
* issue is that resolving an unknown host on some networks will take
Expand Down Expand Up @@ -340,6 +345,22 @@ public static function onGce(callable $httpHandler = null)
} catch (ConnectException $e) {
}
}

if (PHP_OS === 'Windows') {
// @TODO: implement GCE residency detection on Windows
return false;
}

// Detect GCE residency on Linux
return self::detectResidencyLinux(self::GKE_PRODUCT_NAME_FILE);
}

private static function detectResidencyLinux(string $productNameFile): bool
{
if (file_exists($productNameFile)) {
$productName = trim(file_get_contents($productNameFile));

Check failure on line 361 in src/Credentials/GCECredentials.php

View workflow job for this annotation

GitHub Actions / PHPStan Static Analysis

Parameter #1 $string of function trim expects string, string|false given.
return 0 === strpos($productName, 'Google');
}
return false;
}

Expand Down
17 changes: 17 additions & 0 deletions tests/Credentials/GCECredentialsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,23 @@ public function testOnGCEIsFalseOnServerErrorStatus()
$this->assertFalse(GCECredentials::onGCE($httpHandler));
}

public function testCheckProductNameFile()
{
$tmpFile = tempnam(sys_get_temp_dir(), 'gce-test-product-name');

$method = (new \ReflectionClass(GCECredentials::class))
->getMethod('detectResidencyLinux');
$method->setAccessible(true);

$this->assertFalse($method->invoke(null, '/nonexistant/file'));

file_put_contents($tmpFile, 'Google');
$this->assertTrue($method->invoke(null, $tmpFile));

file_put_contents($tmpFile, 'Not Google');
$this->assertFalse($method->invoke(null, $tmpFile));
}

public function testOnGCEIsFalseOnOkStatusWithoutExpectedHeader()
{
$httpHandler = getHandler([
Expand Down

0 comments on commit b163b42

Please sign in to comment.