diff --git a/src/SDK/Resource/Detectors/Host.php b/src/SDK/Resource/Detectors/Host.php index 6024c44e2..c58488302 100644 --- a/src/SDK/Resource/Detectors/Host.php +++ b/src/SDK/Resource/Detectors/Host.php @@ -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)); } } @@ -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; } diff --git a/tests/Unit/SDK/Resource/Detectors/HostTest.php b/tests/Unit/SDK/Resource/Detectors/HostTest.php index dfc0b199d..1d86b6aa9 100644 --- a/tests/Unit/SDK/Resource/Detectors/HostTest.php +++ b/tests/Unit/SDK/Resource/Detectors/HostTest.php @@ -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; @@ -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], + ]; + } }