Skip to content

Commit

Permalink
check for readable host id files before read
Browse files Browse the repository at this point in the history
  • Loading branch information
brettmc committed Oct 13, 2024
1 parent cd8c0e3 commit 5a65747
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/SDK/Resource/Detectors/Host.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,9 @@ private function getLinuxId(): ?string
$paths = [self::PATH_ETC_MACHINEID, self::PATH_VAR_LIB_DBUS_MACHINEID];

foreach ($paths as $path) {
if (file_exists($this->dir . $path)) {
return trim(file_get_contents($this->dir . $path));
$file = $this->dir . $path;
if (file_exists($file) && is_readable($file)) {
return trim(file_get_contents($file));
}
}

Expand All @@ -62,13 +63,14 @@ private function getLinuxId(): ?string

private function getBsdId(): ?string
{
if (file_exists($this->dir . self::PATH_ETC_HOSTID)) {
return trim(file_get_contents($this->dir . self::PATH_ETC_HOSTID));
$file = $this->dir . self::PATH_ETC_HOSTID;
if (file_exists($file) && is_readable($file)) {
return trim(file_get_contents($file));
}

$out = exec('kenv -q smbios.system.uuid');
$out = exec('which kenv && kenv -q smbios.system.uuid');

if ($out !== false) {
if ($out) {
return $out;
}

Expand Down
32 changes: 32 additions & 0 deletions tests/Unit/SDK/Resource/Detectors/HostTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use OpenTelemetry\SDK\Resource\Detectors\Host;
use OpenTelemetry\SemConv\ResourceAttributes;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -72,4 +73,35 @@ public static function hostIdData(): array
['BSD', $etc_hostid, '1234567890'],
];
}

/**
* @dataProvider nonReadableFileProvider
*/
public function test_file_not_readable(string $os, vfsStreamDirectory $root): void
{
$resourceDetector = new Host($root->url(), $os);
$resource = $resourceDetector->getResource();

$hostId = $resource->getAttributes()->get(ResourceAttributes::HOST_ID);
$this->assertNull($hostId);
}

public static function nonReadableFileProvider(): array
{
$root = vfsStream::setup('/');
$etc = vfsStream::newDirectory('etc')->at($root);
vfsStream::newFile('machine-id')
->at($etc)
->setContent('you-cant-see-me')
->chmod(0);
vfsStream::newFile('hostid')
->at($etc)
->setContent('you-cant-see-me')
->chmod(0222);

return [
['Linux', $root],
['BSD', $root],
];
}
}

0 comments on commit 5a65747

Please sign in to comment.