Skip to content

A free open source IT asset/license management system

Sync Adapters: Added level.io

snipeafb2b42a6740
diff --git a/app/SyncAdapters/Levelio/LevelioAdapter.php b/app/SyncAdapters/Levelio/LevelioAdapter.php
new file mode 100644
index 0000000000..d73aca7cf8
--- /dev/null
+++ b/app/SyncAdapters/Levelio/LevelioAdapter.php
@@ -0,0 +1,416 @@
+<?php
+
+namespace App\SyncAdapters\Levelio;
+
+use App\Models\Asset;
+use App\SyncAdapters\HostInventoryRecord;
+use App\SyncAdapters\PushableSyncAdapter;
+use App\SyncAdapters\Traits\UsesAppleDbEnrichment;
+use Carbon\Carbon;
+use Illuminate\Support\Arr;
+
+/**
+ * Level.io adapter. Pulls managed-device inventory from a Level.io
+ * tenant via the v2 REST API and normalizes it into
+ * HostInventoryRecord objects. Also pushes Snipe-IT-authoritative
+ * values back to Level.io when the admin configures a composed notes
+ * template.
+ *
+ * Auth is a long-lived API key issued from the Level.io dashboard
+ * (Settings -> API Keys). The key goes on the Authorization header
+ * verbatim, no Bearer prefix.
+ *
+ * Push surface is small. Level.io's PATCH /v2/devices/{id} only
+ * accepts `name`, `notes`, and `group_id`. Snipe-IT's composed notes
+ * template is routed to `notes`. Pushing `name` would rename the
+ * device from Level's view (devices self-report hostname), so that
+ * field stays read-only here.
+ *
+ * Level.io API reference: https://developers.level.io/
+ */
+class LevelioAdapter extends PushableSyncAdapter
+{
+ use UsesAppleDbEnrichment;
+
+ public static function typeLabel(): string
+ {
+ return 'Level.io';
+ }
+
+ public static function typeSlug(): string
+ {
+ return 'levelio';
+ }
+
+ public static function docsUrl(): ?string
+ {
+ return 'https://developers.level.io/';
+ }
+
+ public function baseUrlPlaceholder(): ?string
+ {
+ return 'https://api.level.io';
+ }
+
+ public function baseUrlHelp(): ?string
+ {
+ return trans('admin/settings/sync_adapters.levelio_base_url_help');
+ }
+
+ public function settingsSchema(): array
+ {
+ return [
+ [
+ 'key' => 'api_key',
+ 'label' => trans('admin/settings/sync_adapters.label_api_key'),
+ 'secret' => true,
+ 'help' => trans('admin/settings/sync_adapters.levelio_api_key_help'),
+ ],
+ $this->appleDbSettingsField(),
+ ];
+ }
+
+ public function extraFields(): array
+ {
+ return [
+ ...$this->appleDbExtraFieldsDeclaration(),
+ 'levelio_online' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_online', 'type' => 'boolean'],
+ 'levelio_role' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_role'],
+ 'levelio_tags' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_tags'],
+ 'levelio_security_score' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_security_score'],
+ 'levelio_security_risk' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_security_risk'],
+ 'levelio_cpu_model' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_cpu_model'],
+ 'levelio_cpu_cores' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_cpu_cores'],
+ 'levelio_total_memory_gb' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_total_memory_gb'],
+ 'levelio_disk_total_gb' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_disk_total_gb'],
+ 'levelio_disk_free_gb' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_disk_free_gb'],
+ 'levelio_notes' => ['label_key' => 'admin/settings/sync_adapters.levelio_extra_notes'],
+ ];
+ }
+
+ public function supportsGroupScoping(): bool
+ {
+ return true;
+ }
+
+ public function vendorGroupLabel(): string
+ {
+ return trans('admin/settings/sync_adapters.vendor_group_levelio_group');
+ }
+
+ public function fetchGroups(): array
+ {
+ $client = $this->client();
+
+ return array_map(
+ fn (array $group) => [
+ 'id' => (string) ($group['id'] ?? ''),
+ 'label' => (string) ($group['name'] ?? $group['id'] ?? '?'),
+ ],
+ $client->groups(),
+ );
+ }
+
+ public function pull(): iterable
+ {
+ $client = $this->client();
+ $enrichmentEnabled = $this->appleDbEnrichmentEnabled();
+ $enrichmentHandled = [];
+
+ foreach ($client->devices() as $device) {
+ $record = $this->normalize($device);
+ if ($enrichmentEnabled) {
+ $enrichmentHandled = $this->enrichFromAppleDb($record, $enrichmentHandled);
+ }
+ yield $record;
+ }
+ }
+
+ /**
+ * Level.io's device payload exposes the marketing-shape model
+ * string on the top-level `model` field, but no AppleDB-shape
+ * hardware identifier. Enrichment therefore falls back to the
+ * name-only AppleDB lookup path, which the trait handles when the
+ * caller passes a null productType.
+ *
+ * @param array<string, bool> $handled
+ * @return array<string, bool>
+ */
+ private function enrichFromAppleDb(HostInventoryRecord $record, array $handled): array
+ {
+ $modelName = $record->hardwareModel;
+ if (! is_string($modelName) || $modelName === '') {
+ return $handled;
+ }
+
+ return $this->enrichModelFromAppleDb($modelName, null, null, $handled);
+ }
+
+ /**
+ * Convert a Level.io device payload into the normalized record
+ * shape. Level.io's `id` is stable per enrolled device and is
+ * what we key asset_external_sources on.
+ *
+ * Falls back to motherboard.manufacturer / motherboard.model
+ * when the top-level `manufacturer` / `model` fields are empty.
+ * Level sources both from DMI on Windows and from
+ * I/O Registry on macOS, but one side is sometimes blank
+ * depending on how the Level agent harvested the host.
+ *
+ * @param array<string, mixed> $device
+ */
+ private function normalize(array $device): HostInventoryRecord
+ {
+ $modelName = Arr::get($device, 'model') ?: Arr::get($device, 'motherboard.model');
+ $manufacturer = Arr::get($device, 'manufacturer') ?: Arr::get($device, 'motherboard.manufacturer');
+ $canonical = $this->canonicalIdentityFor(null, $modelName);
+ $appleDbExtras = $this->appleDbExtrasFor(null, $modelName);
+
+ $osName = Arr::get($device, 'operating_system.full_operating_system')
+ ?: Arr::get($device, 'platform');
+ // `minor_version` carries the fully-qualified version string
+ // ("10.0.19045.5247"), while `major_version` is the shorter
+ // "10.0" form. Prefer minor and fall back only when the
+ // vendor response does not include it.
+ $osVersion = Arr::get($device, 'operating_system.minor_version')
+ ?: Arr::get($device, 'operating_system.major_version');
+
+ $interface = $this->primaryInterface(Arr::get($device, 'network_interfaces', []));
+ $primaryMac = $interface['mac_address'] ?? null;
+ $primaryIp = $this->firstIp(Arr::get($interface, 'ip_addresses', []));
+
+ $tags = Arr::get($device, 'tags', []);
+ $tagNames = is_array($tags)
+ ? array_values(array_filter(array_map(
+ fn ($tag) => is_array($tag) ? ($tag['name'] ?? null) : (is_string($tag) ? $tag : null),
+ $tags,
+ )))
+ : [];
+
+ return new HostInventoryRecord(
+ sourceKey: $this->name(),
+ sourceId: (string) Arr::get($device, 'id'),
+ hostname: Arr::get($device, 'hostname') ?: Arr::get($device, 'nickname'),
+ hardwareSerial: Arr::get($device, 'serial_number'),
+ hardwareModel: $modelName,
+ manufacturer: $manufacturer,
+ primaryMac: $primaryMac,
+ primaryIp: $primaryIp,
+ os: $osName,
+ osVersion: $osVersion,
+ lastSeen: $this->parseTimestamp(Arr::get($device, 'last_seen_at')),
+ assetTag: null,
+ assignedUserEmail: null,
+ assignedUserName: Arr::get($device, 'last_logged_in_user'),
+ vendorGroupId: Arr::has($device, 'group_id') ? (string) Arr::get($device, 'group_id') : null,
+ extra: [
+ ...$appleDbExtras,
+ 'levelio_online' => Arr::get($device, 'online'),
+ 'levelio_role' => Arr::get($device, 'role'),
+ 'levelio_tags' => $tagNames !== [] ? implode(', ', $tagNames) : null,
+ 'levelio_security_score' => Arr::get($device, 'security.score'),
+ 'levelio_security_risk' => Arr::get($device, 'security.risk'),
+ 'levelio_cpu_model' => Arr::get($device, 'cpus.0.model'),
+ 'levelio_cpu_cores' => Arr::get($device, 'cpu_cores') ?? Arr::get($device, 'cpus.0.cores'),
+ 'levelio_total_memory_gb' => $this->bytesToGb(Arr::get($device, 'total_memory')),
+ 'levelio_disk_total_gb' => $this->bytesToGb($this->sumBytes(Arr::get($device, 'disks', []), 'size')),
+ 'levelio_disk_free_gb' => $this->bytesToGb($this->sumBytes(Arr::get($device, 'disk_partitions', []), 'free_space')),
+ 'levelio_notes' => Arr::get($device, 'notes'),
+ ],
+ canonicalMarketingName: $canonical['canonicalMarketingName'],
+ canonicalModelNumber: $canonical['canonicalModelNumber'],
+ );
+ }
+
+ /**
+ * Pick the interface that's most likely to be the primary one. Level
+ * returns every NIC the host reports, including virtual, loopback,
+ * and VPN adapters. First preference: an interface with a non-empty
+ * mac_address AND an IPv4 address, since those two together exclude
+ * most virtual adapters. Falls back to the first interface with any
+ * mac_address so we at least have the hardware-level identifier even
+ * when the host has no live link.
+ *
+ * @param array<int, array<string, mixed>>|mixed $interfaces
+ * @return array<string, mixed>
+ */
+ private function primaryInterface(mixed $interfaces): array
+ {
+ if (! is_array($interfaces)) {
+ return [];
+ }
+
+ foreach ($interfaces as $interface) {
+ if (! is_array($interface)) {
+ continue;
+ }
+ $mac = $interface['mac_address'] ?? null;
+ $ips = $interface['ip_addresses'] ?? [];
+ if (is_string($mac) && $mac !== '' && is_array($ips) && $this->firstIp($ips) !== null) {
+ return $interface;
+ }
+ }
+
+ foreach ($interfaces as $interface) {
+ if (! is_array($interface)) {
+ continue;
+ }
+ $mac = $interface['mac_address'] ?? null;
+ if (is_string($mac) && $mac !== '') {
+ return $interface;
+ }
+ }
+
+ return [];
+ }
+
+ /**
+ * Extract the first usable IP from Level's ip_addresses array.
+ * The array can contain plain strings or objects shaped
+ * {address: ..., family: v4|v6}, depending on how the agent
+ * reported the interface. Prefer v4 so dashboards don't show a
+ * link-local v6 when a routable v4 is available.
+ *
+ * @param array<int, mixed> $ips
+ */
+ private function firstIp(array $ips): ?string
+ {
+ $fallback = null;
+ foreach ($ips as $ip) {
+ if (is_string($ip) && $ip !== '') {
+ if ($fallback === null) {
+ $fallback = $ip;
+ }
+ if (str_contains($ip, '.')) {
+ return $ip;
+ }
+
+ continue;
+ }
+ if (is_array($ip)) {
+ $address = $ip['address'] ?? null;
+ $family = $ip['family'] ?? null;
+ if (is_string($address) && $address !== '') {
+ if ($family === 'v4' || str_contains($address, '.')) {
+ return $address;
+ }
+ $fallback ??= $address;
+ }
+ }
+ }
+
+ return $fallback;
+ }
+
+ /**
+ * Convert a byte count to a one-decimal GB string, or null on
+ * null / zero input. Admins mapping the memory / disk extras to
+ * custom fields expect human-readable GB rather than raw bytes.
+ * Uses 1024-based GB (gibibyte) to match how OS vendors advertise
+ * installed memory and disk capacity.
+ */
+ private function bytesToGb(mixed $bytes): ?string
+ {
+ if (! is_numeric($bytes) || (int) $bytes <= 0) {
+ return null;
+ }
+
+ return number_format((int) $bytes / 1024 ** 3, 1, '.', '');
+ }
+
+ /**
+ * Sum a given byte-size field across a Level.io hardware array
+ * (`disks[]`, `memory[]`). Entries missing the field or carrying
+ * non-numeric values skip rather than poison the sum.
+ *
+ * @param array<int, mixed> $items
+ */
+ private function sumBytes(array $items, string $sizeField): int
+ {
+ $total = 0;
+ foreach ($items as $item) {
+ if (! is_array($item)) {
+ continue;
+ }
+ $value = $item[$sizeField] ?? null;
+ if (is_numeric($value)) {
+ $total += (int) $value;
+ }
+ }
+
+ return $total;
+ }
+
+ private function parseTimestamp(mixed $value): ?Carbon
+ {
+ if ($value === null || $value === '') {
+ return null;
+ }
+
+ return Carbon::parse($value);
+ }
+
+ /**
+ * Level.io's device PATCH endpoint accepts any valid API key, so
+ * push is always available on a configured instance (no per-tier
+ * push gate like Fleet's Teams edition).
+ */
+ public function canPush(): bool
+ {
+ return true;
+ }
+
+ /**
+ * Level.io exposes a freeform `notes` field on each device. The
+ * composed notes template rendered by composeNotesForPush() is
+ * routed here so a Snipe-IT asset's tag + status + assigned user
+ * surfaces on the Level device page.
+ */
+ public function notesFieldTarget(): ?string
+ {
+ return 'notes';
+ }
+
+ public function supportsComposedNotesPush(): bool
+ {
+ return true;
+ }
+
+ /**
+ * Delegates to the base template, which handles the dry-run
+ * branch, splices composed notes into the payload at notesFieldTarget,
+ * and writes the success log line. Level.io's narrow PATCH surface
+ * (`name` / `notes` / `group_id`) means the per-field payload is
+ * always empty and composed notes carries the push.
+ *
+ * @param array<int, string> $changedFields
+ */
+ public function push(Asset $asset, array $changedFields = []): bool
+ {
+ return $this->pushViaSinglePayload($asset, $changedFields);
+ }
+
+ /**
+ * @return array{0: array<string, mixed>, 1: array<int, string>}
+ */
+ protected function buildPushPayload(Asset $asset): array
+ {
+ return [[], []];
+ }
+
+ /**
+ * @param array<string, mixed> $payload
+ */
+ protected function dispatchPush(\App\Models\AssetExternalSource $externalSource, array $payload): void
+ {
+ $this->client()->updateDevice($externalSource->external_id, $payload);
+ }
+
+ private function client(): LevelioClient
+ {
+ return new LevelioClient(
+ baseUrl: $this->url(),
+ apiKey: $this->credential('api_key'),
+ );
+ }
+}
diff --git a/app/SyncAdapters/Levelio/LevelioClient.php b/app/SyncAdapters/Levelio/LevelioClient.php
new file mode 100644
index 0000000000..52af25e6d6
--- /dev/null
+++ b/app/SyncAdapters/Levelio/LevelioClient.php
@@ -0,0 +1,150 @@
+<?php
+
+namespace App\SyncAdapters\Levelio;
+
+use App\SyncAdapters\Traits\RetriesTransientHttpErrors;
+use Illuminate\Http\Client\PendingRequest;
+use Illuminate\Support\Facades\Http;
+
+/**
+ * Thin wrapper around the Level.io v2 REST API. Owns auth and
+ * cursor pagination for the endpoints the sync adapter uses. Yields
+ * raw decoded JSON, no normalization (that's the adapter's job).
+ *
+ * Level.io API reference: https://developers.level.io/
+ */
+class LevelioClient
+{
+ use RetriesTransientHttpErrors;
+
+ public function __construct(
+ private readonly string $baseUrl,
+ private readonly string $apiKey,
+ ) {}
+
+ /**
+ * Iterate every device in the Level.io tenant, one page at a time.
+ * Returns a generator so callers stream through large fleets without
+ * holding the whole list in memory. Level.io caps `limit` at 100
+ * and uses cursor pagination keyed on `starting_after`.
+ *
+ * Every include_* flag maps to data the adapter surfaces either
+ * as a standard HostInventoryRecord field or as an admin-mappable
+ * extra. Toggles kept to the exact set the normalizer reads so a
+ * big-fleet pull does not spend bandwidth on sections nothing
+ * routes to.
+ *
+ * @return iterable<array<string, mixed>>
+ */
+ public function devices(int $limit = 100): iterable
+ {
+ $cursor = null;
+
+ do {
+ $query = [
+ 'limit' => $limit,
+ 'include_operating_system' => 'true',
+ 'include_network_interfaces' => 'true',
+ 'include_motherboard' => 'true',
+ 'include_cpus' => 'true',
+ 'include_memory' => 'true',
+ 'include_disks' => 'true',
+ 'include_security' => 'true',
+ ];
+ if ($cursor !== null) {
+ $query['starting_after'] = $cursor;
+ }
+
+ $response = $this->request()
+ ->get('/v2/devices', $query)
+ ->throw()
+ ->throwIfNotJson()
+ ->json();
+
+ $devices = is_array($response['data'] ?? null) ? $response['data'] : [];
+ foreach ($devices as $device) {
+ yield $device;
+ }
+
+ $hasMore = (bool) ($response['has_more'] ?? false);
+ $cursor = $hasMore && ! empty($devices)
+ ? ($devices[count($devices) - 1]['id'] ?? null)
+ : null;
+ } while ($cursor !== null);
+ }
+
+ /**
+ * List every group in the Level.io tenant. Used by the adapter's
+ * fetchGroups() so admins can map Level groups to Snipe-IT
+ * companies. Level.io's groups endpoint uses the same cursor
+ * pagination style as devices.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public function groups(int $limit = 100): array
+ {
+ $groups = [];
+ $cursor = null;
+
+ do {
+ $query = ['limit' => $limit];
+ if ($cursor !== null) {
+ $query['starting_after'] = $cursor;
+ }
+
+ $response = $this->request()
+ ->get('/v2/groups', $query)
+ ->throw()
+ ->throwIfNotJson()
+ ->json();
+
+ $batch = is_array($response['data'] ?? null) ? $response['data'] : [];
+ foreach ($batch as $group) {
+ $groups[] = $group;
+ }
+
+ $hasMore = (bool) ($response['has_more'] ?? false);
+ $cursor = $hasMore && ! empty($batch)
+ ? ($batch[count($batch) - 1]['id'] ?? null)
+ : null;
+ } while ($cursor !== null);
+
+ return $groups;
+ }
+
+ /**
+ * Update a device's writable fields on Level.io. The vendor
+ * exposes `name`, `notes`, and `group_id` on this endpoint, which
+ * is a narrow push surface compared to full-featured RMMs. Fields
+ * the caller does not include stay untouched.
+ *
+ * @param array<string, scalar|null> $fields
+ */
+ public function updateDevice(string $deviceId, array $fields): void
+ {
+ Http::baseUrl(rtrim($this->baseUrl, '/'))
+ ->withOptions(['allow_redirects' => false])
+ ->withHeaders(['Authorization' => $this->apiKey])
+ ->acceptJson()
+ ->asJson()
+ ->timeout(30)
+ ->patch('/v2/devices/'.rawurlencode($deviceId), $fields)
+ ->throw();
+ }
+
+ /**
+ * Level.io auth is a raw `Authorization: <api_key>` header. No
+ * Bearer prefix, no OAuth exchange, so withToken() is not usable
+ * here (it would prepend "Bearer " and 401 on every call).
+ */
+ private function request(): PendingRequest
+ {
+ return $this->withTransientRetry(
+ Http::baseUrl(rtrim($this->baseUrl, '/'))
+ ->withOptions(['allow_redirects' => false])
+ ->withHeaders(['Authorization' => $this->apiKey])
+ ->acceptJson()
+ ->timeout(30)
+ );
+ }
+}
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index 0233f3be0f..773e55e58b 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -307,6 +307,19 @@ return [
'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.',
+ 'levelio_api_key_help' => 'Generate an API key under Settings -> API Keys in your Level.io dashboard. The key goes on the Authorization header verbatim (no Bearer prefix). The account behind the key needs read access to Devices and Groups, plus write access to Devices if you want push to populate the device notes from a Snipe-IT composed-notes template.',
+ 'levelio_base_url_help' => 'Level.io\'s API URL is <code>https://api.level.io</code> for all tenants. Leave as the default unless you are testing against a staging environment Level has pointed you at.',
+ 'levelio_extra_online' => 'Level.io Online',
+ 'levelio_extra_role' => 'Level.io Role',
+ 'levelio_extra_tags' => 'Level.io Tags',
+ 'levelio_extra_security_score' => 'Level.io Security Score',
+ 'levelio_extra_security_risk' => 'Level.io Security Risk',
+ 'levelio_extra_cpu_model' => 'Level.io CPU Model',
+ 'levelio_extra_cpu_cores' => 'Level.io CPU Cores',
+ 'levelio_extra_total_memory_gb' => 'Level.io Memory (GB)',
+ 'levelio_extra_disk_total_gb' => 'Level.io Disk Capacity (GB)',
+ 'levelio_extra_disk_free_gb' => 'Level.io Disk Free (GB)',
+ 'levelio_extra_notes' => 'Level.io Notes',
'sophos_client_id_help' => 'Create a credential in Sophos Central under Global Settings -> API Credentials Management, with the Service Principal Read-Only role. Copy the Client ID from the credential page. Only tenant-level credentials are supported.',
'sophos_client_secret_help' => 'Paired with the Client ID above. Sophos Central shows the secret once, when the credential is created. Credentials expire eventually and can\'t be renewed, so create a new one when that happens.',
'sophos_endpoint_types_help' => 'Only sync these Sophos endpoint types. Sophos lists every Linux device as a server, laptops included.',
@@ -507,6 +520,7 @@ return [
'vendor_group_jamf_platform_blueprint' => 'Jamf Platform Blueprint',
'vendor_group_kaseya_organization' => 'Kaseya Organization',
'vendor_group_google_workspace_org_unit' => 'Google Organizational Unit',
+ 'vendor_group_levelio_group' => 'Level.io Group',
// Kaseya-specific label prefix for tenant-defined custom fields
// captured by the "Refresh custom fields" button. Rendered in the
diff --git a/tests/Feature/SyncAdapters/Levelio/LevelioAdapterTest.php b/tests/Feature/SyncAdapters/Levelio/LevelioAdapterTest.php
new file mode 100644
index 0000000000..ef3b7411db
--- /dev/null
+++ b/tests/Feature/SyncAdapters/Levelio/LevelioAdapterTest.php
@@ -0,0 +1,326 @@
+<?php
+
+namespace Tests\Feature\SyncAdapters\Levelio;
+
+use App\Models\Statuslabel;
+use App\Models\SyncAdapterConfig;
+use App\Models\SyncAdapterInstance;
+use App\SyncAdapters\Levelio\LevelioAdapter;
+use App\SyncAdapters\SyncAdapter;
+use Illuminate\Support\Facades\Crypt;
+use Illuminate\Support\Facades\Http;
+use Tests\TestCase;
+
+/**
+ * End-to-end coverage for the Level.io adapter through SyncAdapter.
+ * Mocks the Level.io v2 REST API, asserts assets + asset_external_sources
+ * land correctly, and that cursor pagination terminates on `has_more=false`.
+ */
+class LevelioAdapterTest extends TestCase
+{
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ Statuslabel::factory()->rtd()->create();
+ }
+
+ public function test_pulls_devices_from_level_and_creates_assets(): void
+ {
+ $adapter = $this->configuredLevelio();
+
+ Http::fake([
+ '*/v2/devices*' => Http::sequence()
+ ->push([
+ 'data' => [
+ $this->levelDevice(id: 'dev-aaa', hostname: 'workstation-01', model: 'MacBook Pro'),
+ $this->levelDevice(id: 'dev-bbb', hostname: 'workstation-02', model: 'MacBook Air'),
+ ],
+ 'has_more' => false,
+ ]),
+ ]);
+
+ foreach ($adapter->pull() as $record) {
+ SyncAdapter::syncFromRecord($record);
+ }
+
+ $this->assertDatabaseCount('asset_external_sources', 2);
+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'levelio', 'external_id' => 'dev-aaa']);
+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'levelio', 'external_id' => 'dev-bbb']);
+ $this->assertDatabaseHas('assets', ['name' => 'workstation-01']);
+ }
+
+ public function test_normalized_record_carries_expected_fields(): void
+ {
+ $adapter = $this->configuredLevelio();
+
+ Http::fake([
+ '*/v2/devices*' => Http::sequence()
+ ->push([
+ 'data' => [
+ $this->levelDevice(
+ id: 'dev-ccc',
+ hostname: 'design-mbp',
+ model: 'MacBook Pro (16-inch, M3)',
+ serial_number: 'ABC123',
+ manufacturer: 'Apple Inc.',
+ platform: 'Mac',
+ operating_system: [
+ 'full_operating_system' => 'macOS 14.2.1 (23C71)',
+ 'major_version' => '14.0',
+ 'minor_version' => '14.2.1',
+ ],
+ network_interfaces: [
+ ['mac_address' => '00:11:22:33:44:55', 'ip_addresses' => ['192.168.1.10']],
+ ],
+ last_seen_at: '2026-01-15T10:00:00.000Z',
+ last_logged_in_user: 'jane.doe',
+ group_id: 'grp-eng',
+ tags: ['Engineering', 'Laptops'],
+ ),
+ ],
+ 'has_more' => false,
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $this->assertCount(1, $records);
+
+ $record = $records[0];
+ $this->assertSame('levelio', $record->sourceKey);
+ $this->assertSame('dev-ccc', $record->sourceId);
+ $this->assertSame('design-mbp', $record->hostname);
+ $this->assertSame('MacBook Pro (16-inch, M3)', $record->hardwareModel);
+ $this->assertSame('ABC123', $record->hardwareSerial);
+ $this->assertSame('Apple Inc.', $record->manufacturer);
+ $this->assertSame('macOS 14.2.1 (23C71)', $record->os);
+ $this->assertSame('14.2.1', $record->osVersion);
+ $this->assertSame('00:11:22:33:44:55', $record->primaryMac);
+ $this->assertSame('192.168.1.10', $record->primaryIp);
+ $this->assertSame('jane.doe', $record->assignedUserName);
+ $this->assertSame('grp-eng', $record->vendorGroupId);
+ $this->assertSame('Engineering, Laptops', $record->extra['levelio_tags']);
+ $this->assertNotNull($record->lastSeen);
+ }
+
+ public function test_follows_cursor_pagination_until_has_more_false(): void
+ {
+ $adapter = $this->configuredLevelio();
+
+ Http::fake([
+ '*/v2/devices*' => Http::sequence()
+ ->push([
+ 'data' => [
+ $this->levelDevice(id: 'page1-a', hostname: 'host-a'),
+ $this->levelDevice(id: 'page1-b', hostname: 'host-b'),
+ ],
+ 'has_more' => true,
+ ])
+ ->push([
+ 'data' => [
+ $this->levelDevice(id: 'page2-a', hostname: 'host-c'),
+ ],
+ 'has_more' => false,
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+
+ $this->assertCount(3, $records);
+ $this->assertSame(['page1-a', 'page1-b', 'page2-a'], array_map(fn ($r) => $r->sourceId, $records));
+
+ // Second request carried the cursor from the tail of the first page.
+ Http::assertSent(function ($request) {
+ return str_contains($request->url(), '/v2/devices')
+ && str_contains($request->url(), 'starting_after=page1-b');
+ });
+ }
+
+ public function test_falls_back_to_motherboard_fields_when_root_manufacturer_and_model_are_blank(): void
+ {
+ // Level.io's agent sources the top-level `manufacturer` and
+ // `model` from either DMI or I/O Registry depending on the
+ // platform, and one is sometimes empty on a given host. The
+ // motherboard section carries the fallback pair so the
+ // normalized record still has something to seed the AssetModel
+ // from.
+ $adapter = $this->configuredLevelio();
+
+ Http::fake([
+ '*/v2/devices*' => Http::response([
+ 'data' => [
+ [
+ 'id' => 'mb-fallback',
+ 'hostname' => 'desktop-01',
+ 'serial_number' => 'MB-SN-1',
+ 'manufacturer' => null,
+ 'model' => null,
+ 'motherboard' => [
+ 'manufacturer' => 'Dell Inc.',
+ 'model' => 'OptiPlex 7090',
+ ],
+ ],
+ ],
+ 'has_more' => false,
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+
+ $this->assertSame('Dell Inc.', $records[0]->manufacturer);
+ $this->assertSame('OptiPlex 7090', $records[0]->hardwareModel);
+ }
+
+ public function test_picks_interface_with_mac_and_ip_over_virtual_adapters(): void
+ {
+ // Level reports every NIC the host enumerates, including
+ // virtual, VPN, and loopback adapters. The primary pick skips
+ // interfaces without a usable IP so dashboards show the
+ // real wired / wireless adapter rather than a Hyper-V vSwitch
+ // or TAP interface that happens to come first in the list.
+ $adapter = $this->configuredLevelio();
+
+ Http::fake([
+ '*/v2/devices*' => Http::response([
+ 'data' => [
+ $this->levelDevice(
+ id: 'nic-pick',
+ hostname: 'vm-host',
+ network_interfaces: [
+ ['mac_address' => 'aa:aa:aa:aa:aa:aa', 'ip_addresses' => []],
+ ['mac_address' => 'bb:bb:bb:bb:bb:bb', 'ip_addresses' => ['10.0.0.5']],
+ ],
+ ),
+ ],
+ 'has_more' => false,
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+
+ $this->assertSame('bb:bb:bb:bb:bb:bb', $records[0]->primaryMac);
+ $this->assertSame('10.0.0.5', $records[0]->primaryIp);
+ }
+
+ public function test_hardware_and_security_extras_populate_from_include_sections(): void
+ {
+ // Vendor payload mirrors the live Level.io v2 shape with
+ // include_cpus / include_memory / include_disks /
+ // include_security turned on. Verifies the adapter's hardware
+ // extras pull from the expected spots so admins mapping them
+ // to Snipe-IT custom fields see populated values rather than
+ // null.
+ $adapter = $this->configuredLevelio();
+
+ Http::fake([
+ '*/v2/devices*' => Http::response([
+ 'data' => [
+ [
+ 'id' => 'hw-1',
+ 'hostname' => 'hw-host',
+ 'serial_number' => 'HW-SN-1',
+ 'manufacturer' => 'Dell',
+ 'model' => 'OptiPlex 5070',
+ 'platform' => 'Windows',
+ 'total_memory' => 17179869184,
+ 'cpu_cores' => 6,
+ 'cpus' => [
+ [
+ 'model' => 'Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz',
+ 'clock_speed' => 3000,
+ 'cores' => 6,
+ ],
+ ],
+ 'disks' => [
+ ['disk_type' => 'SSD', 'size' => 274877906944],
+ ['disk_type' => 'SSD', 'size' => 549755813888],
+ ],
+ 'disk_partitions' => [
+ ['mount_point' => 'C:', 'size' => 274877906944, 'free_space' => 107374182400],
+ ],
+ 'security' => [
+ 'score' => 90,
+ 'risk' => 'low_risk',
+ 'firewall_enabled' => true,
+ ],
+ ],
+ ],
+ 'has_more' => false,
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $extras = $records[0]->extra;
+
+ $this->assertSame('Intel(R) Core(TM) i5-9500 CPU @ 3.00GHz', $extras['levelio_cpu_model']);
+ $this->assertSame(6, $extras['levelio_cpu_cores']);
+ $this->assertSame('16.0', $extras['levelio_total_memory_gb']);
+ $this->assertSame('768.0', $extras['levelio_disk_total_gb']);
+ $this->assertSame('100.0', $extras['levelio_disk_free_gb']);
+ $this->assertSame(90, $extras['levelio_security_score']);
+ $this->assertSame('low_risk', $extras['levelio_security_risk']);
+ }
+
+ public function test_sends_api_key_on_authorization_header_without_bearer_prefix(): void
+ {
+ $adapter = $this->configuredLevelio();
+
+ Http::fake([
+ '*/v2/devices*' => Http::response(['data' => [], 'has_more' => false]),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ Http::assertSent(function ($request) {
+ return $request->hasHeader('Authorization', 'fake-level-api-key');
+ });
+ }
+
+ private function configuredLevelio(): LevelioAdapter
+ {
+ $instance = SyncAdapterInstance::where('slug', 'levelio')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'url', 'https://api.level.io');
+ SyncAdapterConfig::put($instance->id, 'api_key', Crypt::encrypt('fake-level-api-key'));
+
+ return new LevelioAdapter($instance->fresh());
+ }
+
+ /**
+ * @param array<string, mixed>|null $operating_system
+ * @param array<int, array<string, mixed>>|null $network_interfaces
+ * @param array<int, array<string, mixed>>|null $tags
+ * @return array<string, mixed>
+ */
+ private function levelDevice(
+ string $id,
+ string $hostname = 'host',
+ string $model = 'MacBook',
+ ?string $serial_number = null,
+ ?string $manufacturer = 'Apple Inc.',
+ ?string $platform = 'Mac',
+ ?array $operating_system = null,
+ ?array $network_interfaces = null,
+ ?string $last_seen_at = null,
+ ?string $last_logged_in_user = null,
+ ?string $group_id = null,
+ ?array $tags = null,
+ ): array {
+ return [
+ 'id' => $id,
+ 'hostname' => $hostname,
+ 'serial_number' => $serial_number,
+ 'manufacturer' => $manufacturer,
+ 'model' => $model,
+ 'platform' => $platform,
+ 'operating_system' => $operating_system,
+ 'network_interfaces' => $network_interfaces ?? [],
+ 'last_seen_at' => $last_seen_at,
+ 'last_logged_in_user' => $last_logged_in_user,
+ 'group_id' => $group_id,
+ 'tags' => $tags ?? [],
+ 'notes' => null,
+ 'role' => 'workstation',
+ 'online' => true,
+ ];
+ }
+}
diff --git a/tests/Feature/SyncAdapters/Levelio/LevelioPushTest.php b/tests/Feature/SyncAdapters/Levelio/LevelioPushTest.php
new file mode 100644
index 0000000000..65a80ba6d3
--- /dev/null
+++ b/tests/Feature/SyncAdapters/Levelio/LevelioPushTest.php
@@ -0,0 +1,156 @@
+<?php
+
+namespace Tests\Feature\SyncAdapters\Levelio;
+
+use App\Models\Asset;
+use App\Models\AssetExternalSource;
+use App\Models\Statuslabel;
+use App\Models\SyncAdapterConfig;
+use App\Models\SyncAdapterInstance;
+use App\SyncAdapters\Levelio\LevelioAdapter;
+use App\SyncAdapters\PushableSyncAdapter;
+use App\SyncAdapters\SyncAdapter;
+use Illuminate\Support\Facades\Crypt;
+use Illuminate\Support\Facades\Http;
+use Tests\TestCase;
+
+/**
+ * End-to-end coverage for the Level.io push path. Level's PATCH
+ * /v2/devices/{id} only accepts `name`, `notes`, and `group_id`, and
+ * the adapter routes Snipe-IT's composed notes template to `notes`.
+ */
+class LevelioPushTest extends TestCase
+{
+ protected function setUp(): void
+ {
+ parent::setUp();
+ Statuslabel::factory()->rtd()->create();
+ }
+
+ public function test_adapter_implements_pushable_interface(): void
+ {
+ $this->assertInstanceOf(PushableSyncAdapter::class, $this->configuredLevelio());
+ }
+
+ public function test_composed_notes_push_sends_patch_to_level(): void
+ {
+ $adapter = $this->configuredLevelio();
+ $instance = SyncAdapterInstance::where('slug', 'levelio')->firstOrFail();
+
+ // Compose template renders the asset tag so the push payload
+ // has a non-empty notes body to send.
+ SyncAdapterConfig::put($instance->id, 'push_notes_template', 'Snipe-IT: {{asset_tag}}');
+
+ // Seed via sync so the asset + external-source rows exist.
+ Http::fake([
+ '*/v2/devices*' => Http::response([
+ 'data' => [
+ $this->levelDevice(id: 'lvl-uuid-1', hostname: 'notes-host'),
+ ],
+ 'has_more' => false,
+ ]),
+ ]);
+ foreach ($adapter->pull() as $record) {
+ SyncAdapter::syncFromRecord($record);
+ }
+
+ $asset = Asset::where('name', 'notes-host')->firstOrFail();
+ $asset->asset_tag = 'SNIPE-TAG-42';
+ $asset->save();
+
+ Http::fake([
+ 'PATCH */v2/devices/lvl-uuid-1' => Http::response(['ok' => true]),
+ ]);
+
+ $this->assertTrue($adapter->push($asset));
+
+ Http::assertSent(function ($request) {
+ return $request->method() === 'PATCH'
+ && str_contains($request->url(), '/v2/devices/lvl-uuid-1')
+ && str_contains((string) $request['notes'], 'SNIPE-TAG-42');
+ });
+ }
+
+ public function test_push_skipped_when_no_composed_notes_template_configured(): void
+ {
+ $adapter = $this->configuredLevelio();
+ $this->seedExternalSource($adapter, 'lvl-uuid-2');
+
+ Http::fake();
+
+ $adapter->push(Asset::first());
+
+ Http::assertNothingSent();
+ }
+
+ public function test_push_skipped_when_asset_has_no_external_source_for_this_instance(): void
+ {
+ $adapter = $this->configuredLevelio();
+ $instance = SyncAdapterInstance::where('slug', 'levelio')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'push_notes_template', 'Snipe-IT: {{asset_tag}}');
+
+ // Asset with no asset_external_sources row for this instance.
+ $asset = Asset::factory()->create();
+
+ Http::fake();
+
+ $adapter->push($asset);
+
+ Http::assertNothingSent();
+ }
+
+ public function test_push_sends_api_key_on_authorization_header(): void
+ {
+ $adapter = $this->configuredLevelio();
+ $instance = SyncAdapterInstance::where('slug', 'levelio')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'push_notes_template', 'Snipe-IT: {{asset_tag}}');
+
+ $this->seedExternalSource($adapter, 'lvl-uuid-3');
+ $asset = Asset::first();
+ $asset->asset_tag = 'SNIPE-TAG-99';
+ $asset->save();
+
+ Http::fake(['*' => Http::response(['ok' => true])]);
+
+ $adapter->push($asset);
+
+ Http::assertSent(function ($request) {
+ return $request->method() === 'PATCH'
+ && $request->hasHeader('Authorization', 'fake-level-api-key');
+ });
+ }
+
+ private function configuredLevelio(): LevelioAdapter
+ {
+ $instance = SyncAdapterInstance::where('slug', 'levelio')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'url', 'https://api.level.io');
+ SyncAdapterConfig::put($instance->id, 'api_key', Crypt::encrypt('fake-level-api-key'));
+
+ return new LevelioAdapter($instance->fresh());
+ }
+
+ private function seedExternalSource(LevelioAdapter $adapter, string $externalId): void
+ {
+ $asset = Asset::factory()->create();
+ AssetExternalSource::create([
+ 'asset_id' => $asset->id,
+ 'source' => $adapter->name(),
+ 'external_id' => $externalId,
+ ]);
+ }
+
+ /**
+ * @return array<string, mixed>
+ */
+ private function levelDevice(string $id, string $hostname): array
+ {
+ return [
+ 'id' => $id,
+ 'hostname' => $hostname,
+ 'serial_number' => 'SN-'.$id,
+ 'manufacturer' => 'Apple Inc.',
+ 'model' => 'MacBook Pro',
+ 'platform' => 'Mac',
+ ];
+ }
+}