A free open source IT asset/license management system
Added Ubuntu Landscape adapter
snipeb965c851ea7a
diff --git a/app/SyncAdapters/Landscape/LandscapeAdapter.php b/app/SyncAdapters/Landscape/LandscapeAdapter.phpnew file mode 100644index 0000000000..ea822076c9--- /dev/null+++ b/app/SyncAdapters/Landscape/LandscapeAdapter.php@@ -0,0 +1,173 @@+<?php++namespace App\SyncAdapters\Landscape;++use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\SyncAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;++/**+ * Landscape adapter. Pulls computer inventory from a Canonical+ * Landscape instance (SaaS or self-hosted) and normalizes it into+ * HostInventoryRecord objects.+ *+ * Authentication is a bearer JWT the admin obtains once by POSTing+ * credentials to /api/v2/login on their Landscape instance. Landscape+ * has no UI for issuing static API tokens, so admins paste the JWT+ * returned by that call. The token's expiry_minutes at login time+ * controls how long the paste stays valid.+ *+ * Push (Snipe-IT -> Landscape) is not wired. Landscape's v2 API+ * only exposes specialized action endpoints on a computer (restart,+ * archive, sanitize, delete). It has no PATCH endpoint for the+ * writable metadata fields the admin UI can edit (comment, title,+ * tags, access_group). The `comment` field would be an obvious+ * composed-notes target if Canonical ever publishes a generic+ * update endpoint.+ */+class LandscapeAdapter extends SyncAdapter+{+ public static function typeLabel(): string+ {+ return 'Landscape';+ }++ public static function typeSlug(): string+ {+ return 'landscape';+ }++ public static function docsUrl(): ?string+ {+ return 'https://ubuntu.com/landscape/docs/reference/api/';+ }++ public function settingsSchema(): array+ {+ return [+ [+ 'key' => 'token',+ 'label' => trans('admin/settings/sync_adapters.label_bearer_token'),+ 'secret' => true,+ 'help' => trans('admin/settings/sync_adapters.landscape_token_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ return [+ 'landscape_tags' => ['label_key' => 'admin/settings/sync_adapters.extra_tags'],+ 'landscape_access_group' => ['label_key' => 'admin/settings/sync_adapters.extra_group'],+ 'landscape_distribution' => ['label_key' => 'admin/settings/sync_adapters.extra_distribution'],+ 'landscape_reboot_required' => [+ 'label_key' => 'admin/settings/sync_adapters.extra_reboot_required',+ 'type' => 'boolean',+ ],+ 'landscape_ubuntu_pro' => ['label_key' => 'admin/settings/sync_adapters.extra_ubuntu_pro'],+ ];+ }++ public function canPush(): bool+ {+ return false;+ }++ public function supportsGroupScoping(): bool+ {+ // Landscape has access groups but the v2 API does not+ // publish a list-access-groups endpoint we can enumerate+ // from. Leaving group scoping off until we either find that+ // endpoint or add a manual "type in group names" flow.+ return false;+ }++ public function pull(): iterable+ {+ $client = new LandscapeClient(+ baseUrl: $this->url(),+ token: $this->credential('token'),+ );++ foreach ($client->computers() as $computer) {+ yield $this->normalize($computer);+ }+ }++ /**+ * Convert a Landscape computer payload into the normalized record+ * shape. Landscape's numeric `id` is the stable per-computer key+ * for asset_external_sources.+ *+ * Assigned-user extraction is null in v1: Landscape does not+ * natively track a primary user on the computer record. Installs+ * that populate a custom field via a run-once script can surface+ * that through the vendor-custom-fields extras path instead.+ *+ * @param array<string, mixed> $computer+ */+ private function normalize(array $computer): HostInventoryRecord+ {+ $system = $this->firstHardwareRecord($computer, 'system');+ $network = $this->firstHardwareRecord($computer, 'network');++ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($computer, 'id'),+ hostname: Arr::get($computer, 'hostname') ?? Arr::get($computer, 'title'),+ hardwareSerial: Arr::get($system, 'serial') ?? Arr::get($system, 'serial_number'),+ hardwareModel: Arr::get($system, 'product') ?? Arr::get($system, 'product_name'),+ manufacturer: Arr::get($system, 'vendor') ?? Arr::get($system, 'manufacturer'),+ primaryMac: Arr::get($network, 'mac') ?? Arr::get($network, 'mac_address'),+ primaryIp: Arr::get($network, 'ip') ?? Arr::get($network, 'ip_address'),+ os: 'Ubuntu',+ osVersion: Arr::get($computer, 'distribution'),+ lastSeen: $this->parseTimestamp(Arr::get($computer, 'last_ping_time')),+ assignedUserEmail: null,+ assignedUserName: null,+ vendorGroupId: null,+ extra: [+ 'landscape_tags' => Arr::get($computer, 'tags'),+ 'landscape_access_group' => Arr::get($computer, 'access_group'),+ 'landscape_distribution' => Arr::get($computer, 'distribution'),+ 'landscape_reboot_required' => (bool) Arr::get($computer, 'reboot_required_flag'),+ 'landscape_ubuntu_pro' => Arr::get($computer, 'ubuntu_pro_info'),+ ],+ );+ }++ /**+ * Landscape's grouped_hardware entries may come back as either a+ * flat object (single system, single primary NIC) or a list of+ * objects, depending on the install and category. Return the+ * first record in either shape.+ *+ * @param array<string, mixed> $computer+ * @return array<string, mixed>|null+ */+ private function firstHardwareRecord(array $computer, string $category): ?array+ {+ $entry = Arr::get($computer, 'grouped_hardware.' . $category);+ if (!is_array($entry) || $entry === []) {+ return null;+ }++ if (array_is_list($entry)) {+ $first = $entry[0] ?? null;++ return is_array($first) ? $first : null;+ }++ return $entry;+ }++ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }+}diff --git a/app/SyncAdapters/Landscape/LandscapeClient.php b/app/SyncAdapters/Landscape/LandscapeClient.phpnew file mode 100644index 0000000000..bc5b141aba--- /dev/null+++ b/app/SyncAdapters/Landscape/LandscapeClient.php@@ -0,0 +1,67 @@+<?php++namespace App\SyncAdapters\Landscape;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Landscape v2 REST API. Owns pagination over+ * the computers endpoint and yields raw decoded JSON, normalization is+ * the adapter's job.+ *+ * Landscape API reference: https://ubuntu.com/landscape/docs/reference/api/+ */+class LandscapeClient+{+ public function __construct(+ private readonly string $baseUrl,+ private readonly string $token,+ ) {+ }++ /**+ * Stream every computer in the account, one page at a time.+ * Requests grouped hardware so downstream normalization can+ * extract serial, vendor, and model from the same call rather+ * than paying an N+1 detail-fetch per host.+ *+ * @return iterable<array<string, mixed>>+ */+ public function computers(int $perPage = 500): iterable+ {+ $offset = 0;++ do {+ $response = $this->request()+ ->get('/api/v2/computers', [+ 'limit' => $perPage,+ 'offset' => $offset,+ 'with_grouped_hardware' => 'true',+ ])+ ->throw()+ ->json();++ $results = $response['results'] ?? [];+ foreach ($results as $computer) {+ yield $computer;+ }++ // Landscape returns a `next` URL on paginated responses+ // and null once the caller has walked the full list. Prefer+ // that signal over offset arithmetic so we stop as soon as+ // the server says we are done.+ $hasNext = !empty($response['next'] ?? null);+ $offset += $perPage;+ } while ($hasNext);+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/'))+ ->withOptions(['allow_redirects' => false])+ ->withToken($this->token)+ ->acceptJson()+ ->timeout(60);+ }+}diff --git a/phpstan-baseline.neon b/phpstan-baseline.neonindex 256ac5dab0..9342e96b06 100644--- a/phpstan-baseline.neon+++ b/phpstan-baseline.neon@@ -3672,6 +3672,12 @@ parameters:count: 2path: app/Http/Transformers/AssetModelsTransformer.php+ -+ message: '#^Access to an undefined property App\\Models\\AssetModel\:\:\$remaining\.$#'+ identifier: property.notFound+ count: 1+ path: app/Http/Transformers/AssetModelsTransformer.php+-message: '#^Access to an undefined property App\\Models\\AccessoryCheckout\:\:\$deleted_at\.$#'identifier: property.notFounddiff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex 5a766aa575..db2a7d68c2 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -186,6 +186,7 @@ return ['jamf_platform_client_id_help' => 'Create an integration in Jamf Account under API integrations, then grant it the capabilities for Devices (read) and Blueprints (read) on your Platform environment. Copy the Client ID from the integration detail page.','jamf_platform_client_secret_help' => 'Paired with the Client ID above. Jamf shows the secret once at integration creation time.','jamf_platform_environment_id_help' => 'UUID of the Platform environment the integration is scoped to. Copy from Jamf Account under Environments, or from the URL of your environment console. Sent as the X-Environment-Id header on every request.',+ 'landscape_token_help' => 'Landscape does not have a UI for API tokens. Obtain one by POSTing your credentials to <code>/api/v2/login</code> on your Landscape instance and copying the <code>token</code> field from the JSON response. Pass an <code>expiry_minutes</code> value on that call to control how long the token stays valid (defaults to 24h). The account behind the token needs read access to computers.',// Custom HTTP adapter'custom_auth_method_help' => 'How the adapter authenticates against your API. <code>Bearer</code> sends a Bearer token in the <code>Authorization</code> header. <code>Basic</code> sends username + password. <code>API Key</code> sends the value in a custom header. <code>None</code> sends no auth headers.',@@ -287,6 +288,9 @@ return ['extra_applecare_description' => 'AppleCare Description','extra_applecare_is_canceled' => 'AppleCare Is Canceled','extra_applecare_is_renewable' => 'AppleCare Is Renewable',+ 'extra_distribution' => ':vendor Distribution',+ 'extra_reboot_required' => ':vendor Reboot Required',+ 'extra_ubuntu_pro' => 'Ubuntu Pro','extra_osquery_version' => 'osquery Version',// Shared label strings for adapter settings schemas. Adaptersdiff --git a/tests/Feature/SyncAdapters/Landscape/LandscapeAdapterTest.php b/tests/Feature/SyncAdapters/Landscape/LandscapeAdapterTest.phpnew file mode 100644index 0000000000..e9773312b8--- /dev/null+++ b/tests/Feature/SyncAdapters/Landscape/LandscapeAdapterTest.php@@ -0,0 +1,290 @@+<?php++namespace Tests\Feature\SyncAdapters\Landscape;++use App\Models\Asset;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\SyncAdapters\Landscape\LandscapeAdapter;+use App\SyncAdapters\SyncAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;++/**+ * End-to-end coverage for the Landscape adapter through SyncAdapter.+ * Mocks Landscape's /api/v2/computers endpoint, asserts assets ++ * asset_external_sources rows land correctly, exercises the+ * grouped_hardware normalization for both flat and list shapes, and+ * verifies the `next` URL pagination loop terminates.+ */+class LandscapeAdapterTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();++ Statuslabel::factory()->rtd()->create();+ }++ public function test_pulls_computers_from_landscape_and_creates_assets()+ {+ $adapter = $this->configuredLandscapeAdapter();++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push($this->landscapeComputersResponse([+ $this->landscapeComputer(id: 42, hostname: 'ubuntu-01', product: 'PowerEdge R450', mac: 'aa:bb:cc:00:00:42'),+ $this->landscapeComputer(id: 99, hostname: 'ubuntu-02', product: 'ThinkSystem SR630', mac: 'aa:bb:cc:00:00:99'),+ ])),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('asset_external_sources', 2);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'landscape', 'external_id' => '42']);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'landscape', 'external_id' => '99']);+ $this->assertDatabaseHas('assets', ['name' => 'ubuntu-01']);+ $this->assertDatabaseHas('assets', ['name' => 'ubuntu-02']);+ }++ public function test_re_running_updates_existing_assets_instead_of_duplicating()+ {+ $adapter = $this->configuredLandscapeAdapter();++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push($this->landscapeComputersResponse([+ $this->landscapeComputer(id: 42, hostname: 'ubuntu-01', product: 'PowerEdge'),+ ]))+ ->push($this->landscapeComputersResponse([+ $this->landscapeComputer(id: 42, hostname: 'ubuntu-01-renamed', product: 'PowerEdge', ip: '10.0.0.42'),+ ])),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('asset_external_sources', 1);+ $this->assertDatabaseCount('assets', 1);+ $originalAssetId = Asset::where('name', 'ubuntu-01')->firstOrFail()->id;++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('asset_external_sources', 1);+ $this->assertDatabaseCount('assets', 1);++ $this->assertSame('ubuntu-01-renamed', Asset::find($originalAssetId)->name);+ $this->assertSame('10.0.0.42', DB::table('asset_external_sources')->where('asset_id', $originalAssetId)->value('primary_ip'));+ }++ public function test_normalized_record_carries_expected_fields()+ {+ $adapter = $this->configuredLandscapeAdapter();++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push($this->landscapeComputersResponse([+ $this->landscapeComputer(+ id: 7,+ hostname: 'ubuntu-server',+ product: 'PowerEdge R750',+ vendor: 'Dell',+ serial: 'DELL-ABC-123',+ mac: 'aa:bb:cc:dd:ee:ff',+ ip: '192.168.1.7',+ distribution: '24.04',+ last_ping_time: '2026-01-15T10:00:00Z',+ tags: ['prod', 'db'],+ access_group: 'engineering',+ reboot_required: true,+ ),+ ])),+ ]);++ $records = iterator_to_array($adapter->pull());+ $this->assertCount(1, $records);++ $record = $records[0];+ $this->assertSame('landscape', $record->sourceKey);+ $this->assertSame('7', $record->sourceId);+ $this->assertSame('ubuntu-server', $record->hostname);+ $this->assertSame('PowerEdge R750', $record->hardwareModel);+ $this->assertSame('DELL-ABC-123', $record->hardwareSerial);+ $this->assertSame('Dell', $record->manufacturer);+ $this->assertSame('aa:bb:cc:dd:ee:ff', $record->primaryMac);+ $this->assertSame('192.168.1.7', $record->primaryIp);+ $this->assertSame('Ubuntu', $record->os);+ $this->assertSame('24.04', $record->osVersion);+ $this->assertNotNull($record->lastSeen);++ $this->assertSame(['prod', 'db'], $record->extra['landscape_tags']);+ $this->assertSame('engineering', $record->extra['landscape_access_group']);+ $this->assertSame('24.04', $record->extra['landscape_distribution']);+ $this->assertTrue($record->extra['landscape_reboot_required']);+ }++ public function test_hostname_falls_back_to_title_when_hostname_missing()+ {+ // Some Landscape installs populate `title` (the display name in+ // the admin UI) but not `hostname` (the OS-reported name).+ // Normalize falls back to title so the asset row still has a+ // useful name column.+ $adapter = $this->configuredLandscapeAdapter();++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push($this->landscapeComputersResponse([+ ['id' => 1, 'title' => 'title-only', 'grouped_hardware' => []],+ ])),+ ]);++ $record = iterator_to_array($adapter->pull())[0];+ $this->assertSame('title-only', $record->hostname);+ }++ public function test_grouped_hardware_tolerates_list_shape_for_system()+ {+ // Landscape's grouped_hardware.system comes back as a flat+ // object on some responses and as a single-element list on+ // others. firstHardwareRecord() unwraps both to the same+ // shape so serial/vendor/product extraction is stable.+ $adapter = $this->configuredLandscapeAdapter();++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push($this->landscapeComputersResponse([+ [+ 'id' => 1,+ 'hostname' => 'list-shape',+ 'grouped_hardware' => [+ 'system' => [+ ['serial' => 'LIST-SN', 'vendor' => 'Dell', 'product' => 'PowerEdge'],+ ],+ 'network' => [+ ['mac' => 'aa:bb:cc:00:00:01', 'ip' => '10.0.0.1'],+ ],+ ],+ ],+ ])),+ ]);++ $record = iterator_to_array($adapter->pull())[0];+ $this->assertSame('LIST-SN', $record->hardwareSerial);+ $this->assertSame('Dell', $record->manufacturer);+ $this->assertSame('PowerEdge', $record->hardwareModel);+ }++ public function test_pagination_stops_when_next_url_is_null()+ {+ // Landscape returns `next: null` on the final page. The pull+ // loop must terminate rather than hammering the endpoint+ // forever. Multi-page fake with the second page marking end.+ $adapter = $this->configuredLandscapeAdapter();++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push([+ 'results' => [$this->landscapeComputer(id: 1, hostname: 'page1-host', product: 'P1')],+ 'next' => 'https://landscape.example.test/api/v2/computers?offset=500',+ ])+ ->push([+ 'results' => [$this->landscapeComputer(id: 2, hostname: 'page2-host', product: 'P2')],+ 'next' => null,+ ]),+ ]);++ $records = iterator_to_array($adapter->pull());+ $this->assertCount(2, $records);+ $this->assertSame('page1-host', $records[0]->hostname);+ $this->assertSame('page2-host', $records[1]->hostname);+ }++ public function test_bearer_token_is_sent_on_every_request()+ {+ $adapter = $this->configuredLandscapeAdapter();++ Http::fake([+ '*/api/v2/computers*' => Http::sequence()+ ->push($this->landscapeComputersResponse([])),+ ]);++ iterator_to_array($adapter->pull());++ Http::assertSent(function ($request) {+ return str_contains($request->url(), '/api/v2/computers')+ && $request->hasHeader('Authorization', 'Bearer fake-token');+ });+ }++ private function configuredLandscapeAdapter(): LandscapeAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'landscape')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://landscape.example.test');+ SyncAdapterConfig::put($instance->id, 'token', Crypt::encrypt('fake-token'));++ return new LandscapeAdapter($instance->fresh());+ }++ /**+ * Wraps a set of computer objects in the top-level shape+ * Landscape's list endpoint returns.+ *+ * @param array<int, array<string, mixed>> $computers+ * @return array<string, mixed>+ */+ private function landscapeComputersResponse(array $computers): array+ {+ return [+ 'results' => $computers,+ 'next' => null,+ ];+ }++ /**+ * @param array<int, string> $tags+ * @return array<string, mixed>+ */+ private function landscapeComputer(+ int $id,+ string $hostname = 'ubuntu-host',+ string $product = 'Generic Server',+ ?string $vendor = null,+ ?string $serial = null,+ ?string $mac = null,+ ?string $ip = null,+ ?string $distribution = null,+ ?string $last_ping_time = null,+ array $tags = [],+ ?string $access_group = null,+ bool $reboot_required = false,+ ): array {+ return [+ 'id' => $id,+ 'hostname' => $hostname,+ 'title' => $hostname,+ 'distribution' => $distribution,+ 'last_ping_time' => $last_ping_time,+ 'tags' => $tags,+ 'access_group' => $access_group,+ 'reboot_required_flag' => $reboot_required,+ 'grouped_hardware' => [+ 'system' => [+ 'serial' => $serial,+ 'vendor' => $vendor,+ 'product' => $product,+ ],+ 'network' => [+ ['mac' => $mac, 'ip' => $ip],+ ],+ ],+ ];+ }+}