A free open source IT asset/license management system
Adddd KaseyVSA10 adapter
snipe0cd7d6a4194d
diff --git a/app/SyncAdapters/KaseyaVsa10/KaseyaVsa10Adapter.php b/app/SyncAdapters/KaseyaVsa10/KaseyaVsa10Adapter.phpnew file mode 100644index 0000000000..0946ba4a98--- /dev/null+++ b/app/SyncAdapters/KaseyaVsa10/KaseyaVsa10Adapter.php@@ -0,0 +1,367 @@+<?php++namespace App\SyncAdapters\KaseyaVsa10;++use App\SyncAdapters\HostInventoryRecord;+use App\SyncAdapters\Support\ConfigurableAdapter;+use Carbon\Carbon;+use Illuminate\Support\Arr;++/**+ * Kaseya VSA 10 (formerly Kaseya X, product code "vsax") adapter.+ * Pulls managed endpoints from the /api/v3/assets endpoint using HTTP+ * Basic auth with a token-id / token-secret pair issued from the VSA+ * admin console. Keyed on VSA's stable `Identifier` GUID.+ *+ * Hardware inventory in VSA 10 lives in a nested AssetInfo array of+ * category blocks (System, BIOS, Operating System, ...). Each block+ * has a CategoryName plus a CategoryData map whose keys are+ * human-readable strings ("Serial Number" with a space, "Number of+ * Cores", etc). normalize() walks the array by category and extracts+ * the fields Snipe-IT cares about.+ *+ * Base URL is customer-specific: each VSA tenant has its own server+ * hostname (no shared regional endpoints like Workspace ONE or+ * NinjaOne). Admins paste the full https URL on the settings page.+ *+ * Group scoping uses VSA's Organization as the natural tenant+ * boundary. Sites and Groups are internal RMM groupings that can be+ * mapped to custom fields via extraFields() if admins want them.+ *+ * Push: not implemented in the initial pass. VSA exposes a writable+ * Description field on /devices and a /customfields/assign endpoint;+ * both are candidates for a later push implementation once we have+ * a real tenant to validate the update-endpoint shape.+ */+class KaseyaVsa10Adapter extends ConfigurableAdapter+{+ public static function typeLabel(): string+ {+ return 'Kaseya VSA 10';+ }++ public function baseUrlPlaceholder(): ?string+ {+ return 'https://your-tenant.vsax.net';+ }++ public function credentialSchema(): array+ {+ return [+ [+ 'key' => 'token_id',+ 'label' => 'Token ID',+ 'secret' => true,+ 'help' => trans('admin/settings/sync_adapters.kaseya_vsa10_token_id_help'),+ ],+ [+ 'key' => 'token_secret',+ 'label' => 'Token Secret',+ 'secret' => true,+ 'help' => trans('admin/settings/sync_adapters.kaseya_vsa10_token_secret_help'),+ ],+ ];+ }++ public function extraFields(): array+ {+ $extras = [+ 'kaseya_vsa10_group' => ['label_key' => 'admin/settings/sync_adapters.extra_group'],+ 'kaseya_vsa10_computer_type' => ['label_key' => 'admin/settings/sync_adapters.extra_computer_type'],+ 'kaseya_vsa10_client_version' => ['label_key' => 'admin/settings/sync_adapters.extra_agent_version'],+ 'kaseya_vsa10_domain' => ['label_key' => 'admin/settings/sync_adapters.extra_domain'],+ 'kaseya_vsa10_cpu' => ['label_key' => 'admin/settings/sync_adapters.extra_cpu'],+ 'kaseya_vsa10_tags' => ['label_key' => 'admin/settings/sync_adapters.extra_tags'],+ ];++ // Merge in any tenant-defined VSA custom fields the admin+ // captured via the "Refresh custom fields" button. Type is+ // translated to Snipe-IT's extras type vocabulary so booleans+ // land on checkbox custom fields and everything else stays+ // free-text. admin_defined restricts the target pool to+ // custom-only in the mapping UI (native:asset_tag / notes+ // don't make sense for admin-labeled tenant data).+ foreach ($this->cachedVendorCustomFields() as $field) {+ $key = self::vendorCustomFieldKey($field['name']);+ if ($key === '') {+ continue;+ }+ $extras[$key] = [+ 'label' => 'Kaseya: '.$field['name'],+ 'type' => self::translateVendorType($field['type']),+ 'admin_defined' => true,+ ];+ }++ return $extras;+ }++ /**+ * Convert a VSA custom field Name to the extra-key we store in+ * the mapping table. Prefix + slug of the vendor name keeps the+ * key namespaced away from built-in extras and stable across+ * refreshes (renaming a field in VSA breaks the mapping but that+ * is expected).+ */+ private static function vendorCustomFieldKey(string $name): string+ {+ $slug = strtolower(preg_replace('/[^A-Za-z0-9]+/', '_', trim($name)));+ $slug = trim($slug, '_');++ return $slug === '' ? '' : 'kaseya_vsa10_cf_'.$slug;+ }++ /**+ * Translate a VSA field Type ("Text", "Number", "Date",+ * "Boolean", "Dropdown") to the Snipe-IT extras type vocabulary+ * ('text', 'boolean'). Unknown types fall through to 'text' so+ * the value still lands in a free-text custom field.+ */+ private static function translateVendorType(string $vendorType): string+ {+ return match ($vendorType) {+ 'Boolean', 'Checkbox' => 'boolean',+ default => 'text',+ };+ }++ public function supportsVendorCustomFields(): bool+ {+ return true;+ }++ /**+ * Refresh the cached list of device-applicable custom fields.+ * Returns definitions as normalized {id, name, type} entries so+ * the controller can persist them without leaking VSA's+ * PascalCase key names into cache storage.+ *+ * @return array<int, array{id: string, name: string, type: string}>+ */+ public function fetchVendorCustomFields(): array+ {+ $client = new KaseyaVsa10Client(+ baseUrl: $this->url(),+ tokenId: $this->credential('token_id'),+ tokenSecret: $this->credential('token_secret'),+ );++ $out = [];+ foreach ($client->deviceCustomFieldDefinitions() as $field) {+ $name = (string) ($field['Name'] ?? '');+ if ($name === '') {+ continue;+ }+ $out[] = [+ 'id' => (string) ($field['Id'] ?? ''),+ 'name' => $name,+ 'type' => (string) ($field['Type'] ?? 'Text'),+ ];+ }++ return $out;+ }++ public function supportsGroupScoping(): bool+ {+ return true;+ }++ public function vendorGroupLabel(): string+ {+ return 'Kaseya Organization';+ }++ public function fetchGroups(): array+ {+ // Organizations live at /api/v3/organizations. Not fetched+ // here yet. The settings UI degrades to a free-text field so+ // admins can still type OrganizationId manually.+ //+ // TODO(vsa10-organizations): add fetchOrganizations() on the+ // client and wire it here once we have a tenant to test+ // against.+ return [];+ }++ public function pull(): iterable+ {+ $client = new KaseyaVsa10Client(+ baseUrl: $this->url(),+ tokenId: $this->credential('token_id'),+ tokenSecret: $this->credential('token_secret'),+ );++ // Only enrich records with per-device custom-field values+ // when the admin has both refreshed the custom-field list AND+ // mapped at least one to a Snipe-IT target. Skipping the+ // /devices/{id}/customfields call when nothing is mapped+ // saves ~one API call per asset (VSA rate limit is+ // 3600/hour) and matches admin intent (no mapping = no+ // reason to fetch).+ $enrichWithCustomFields = $this->hasMappedVendorCustomFields();++ foreach ($client->assets() as $row) {+ $record = $this->normalize($row);+ if ($enrichWithCustomFields) {+ $record = $this->enrichRecordWithCustomFields($record, $client);+ }+ yield $record;+ }+ }++ /**+ * Whether at least one cached VSA custom field has a non-skip+ * mapping stored. Determines whether pull() spends an extra API+ * call per asset fetching /devices/{id}/customfields.+ */+ private function hasMappedVendorCustomFields(): bool+ {+ foreach ($this->cachedVendorCustomFields() as $field) {+ $key = self::vendorCustomFieldKey($field['name']);+ if ($key === '') {+ continue;+ }+ $target = $this->mappingFor($key);+ if ($target !== '' && $target !== 'skip') {+ return true;+ }+ }++ return false;+ }++ /**+ * Fetch the per-device custom-field values for one asset and+ * merge them into a fresh HostInventoryRecord. Values come back+ * from VSA as {Id, Name, Value, Type}. We key the merged extras+ * by the same vendorCustomFieldKey we advertise in extraFields()+ * so the mapping table lines up. Network failures on the+ * customfields call are non-fatal: we log and return the+ * un-enriched record so a transient customfields outage doesn't+ * poison the whole sync.+ */+ private function enrichRecordWithCustomFields(HostInventoryRecord $record, KaseyaVsa10Client $client): HostInventoryRecord+ {+ try {+ $values = $client->deviceCustomFieldValues($record->sourceId);+ } catch (\Throwable $e) {+ \Log::channel('sync-adapters')->warning(sprintf(+ '%s customfields fetch failed for device %s: %s',+ $this->name(),+ $record->sourceId,+ $e->getMessage(),+ ));++ return $record;+ }++ $extra = $record->extra;+ foreach ($values as $entry) {+ $key = self::vendorCustomFieldKey($entry['Name'] ?? '');+ if ($key === '') {+ continue;+ }+ $extra[$key] = $entry['Value'] ?? null;+ }++ return new HostInventoryRecord(+ sourceKey: $record->sourceKey,+ sourceId: $record->sourceId,+ hostname: $record->hostname,+ hardwareSerial: $record->hardwareSerial,+ hardwareModel: $record->hardwareModel,+ manufacturer: $record->manufacturer,+ primaryMac: $record->primaryMac,+ primaryIp: $record->primaryIp,+ os: $record->os,+ osVersion: $record->osVersion,+ lastSeen: $record->lastSeen,+ assetTag: $record->assetTag,+ assignedUserEmail: $record->assignedUserEmail,+ assignedUserName: $record->assignedUserName,+ vendorGroupId: $record->vendorGroupId,+ extra: $extra,+ );+ }++ /**+ * Convert a VSA 10 asset row into the normalized record shape.+ * `Identifier` is a stable GUID per registered endpoint and is+ * what we key asset_external_sources on.+ *+ * Hardware inventory is nested under AssetInfo[] with per-category+ * blocks. Keys inside CategoryData contain spaces ("Serial Number",+ * "Number of Cores"), so we go through Arr::get with the exact+ * verbatim key string.+ *+ * @param array<string, mixed> $row+ */+ private function normalize(array $row): HostInventoryRecord+ {+ $system = $this->assetCategory($row, 'System');+ $bios = $this->assetCategory($row, 'BIOS');+ $os = $this->assetCategory($row, 'Operating System');++ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: (string) Arr::get($row, 'Identifier'),+ hostname: Arr::get($row, 'Name'),+ hardwareSerial: Arr::get($bios, 'Serial Number'),+ hardwareModel: Arr::get($system, 'Model'),+ manufacturer: Arr::get($system, 'Manufacturer'),+ primaryMac: Arr::get($row, 'LocalIpAddresses.0.PhysicalAddress'),+ primaryIp: Arr::get($row, 'PublicIpAddress')+ ?? Arr::get($row, 'LocalIpAddresses.0.IpV4'),+ os: Arr::get($os, 'Name') ?? Arr::get($row, 'Type'),+ osVersion: Arr::get($os, 'Version'),+ lastSeen: $this->parseTimestamp(Arr::get($row, 'LastSeenOnline')),+ assignedUserEmail: null,+ assignedUserName: null,+ vendorGroupId: Arr::has($row, 'OrganizationId')+ ? (string) Arr::get($row, 'OrganizationId')+ : null,+ extra: [+ 'kaseya_vsa10_group' => Arr::get($row, 'GroupName'),+ 'kaseya_vsa10_computer_type' => Arr::get($row, 'Type'),+ 'kaseya_vsa10_client_version' => Arr::get($row, 'ClientVersion'),+ 'kaseya_vsa10_domain' => Arr::get($system, 'Domain'),+ 'kaseya_vsa10_cpu' => Arr::get($system, 'CPU'),+ 'kaseya_vsa10_tags' => Arr::get($row, 'Tags'),+ ],+ );+ }++ /**+ * Locate the CategoryData for a named AssetInfo category on an+ * asset row. Returns an empty array when the category isn't+ * present, so downstream Arr::get calls just resolve to null.+ *+ * @param array<string, mixed> $row+ * @return array<string, mixed>+ */+ private function assetCategory(array $row, string $categoryName): array+ {+ foreach ($row['AssetInfo'] ?? [] as $block) {+ if (($block['CategoryName'] ?? null) === $categoryName) {+ return $block['CategoryData'] ?? [];+ }+ }++ return [];+ }++ /**+ * Parse a VSA 10 timestamp. LastSeenOnline is ISO 8601 with a+ * trailing Z. Bail on null / empty so we don't record 1970 for+ * assets that haven't checked in.+ */+ private function parseTimestamp(mixed $value): ?Carbon+ {+ if ($value === null || $value === '') {+ return null;+ }++ return Carbon::parse($value);+ }+}diff --git a/app/SyncAdapters/KaseyaVsa10/KaseyaVsa10Client.php b/app/SyncAdapters/KaseyaVsa10/KaseyaVsa10Client.phpnew file mode 100644index 0000000000..4caa20e4b3--- /dev/null+++ b/app/SyncAdapters/KaseyaVsa10/KaseyaVsa10Client.php@@ -0,0 +1,164 @@+<?php++namespace App\SyncAdapters\KaseyaVsa10;++use Illuminate\Http\Client\PendingRequest;+use Illuminate\Support\Facades\Http;++/**+ * Thin wrapper around the Kaseya VSA 10 (formerly Kaseya X, product code+ * "vsax") REST API v3. Auth is HTTP Basic with a paired token id and+ * token secret issued from the VSA 10 admin console. Both halves are+ * treated as secret because the token id is opaque and offers no+ * value to expose. Base URL is customer-specific (each tenant has its+ * own VSA server hostname), so admins paste theirs on the settings+ * page.+ *+ * Pull uses the /api/v3/assets endpoint (not /devices). VSA models+ * managed endpoints as "assets" in the API sense, with hardware+ * inventory nested under an AssetInfo array of category blocks+ * (System, BIOS, Operating System, etc.). /devices returns a coarser+ * summary without hardware info, so /assets is the right choice for a+ * Snipe-IT inventory adapter.+ *+ * Pagination follows OData conventions: $top and $skip. VSA emits a+ * NextQueryLink cursor when a result set exceeds 5,000 items. This+ * client uses $skip pagination for simplicity. If a tenant regularly+ * runs past 5k assets, we can add NextQueryLink following later.+ */+class KaseyaVsa10Client+{+ private ?string $basicAuth = null;++ public function __construct(+ private readonly string $baseUrl,+ private readonly string $tokenId,+ private readonly string $tokenSecret,+ ) {}++ /**+ * Iterate every asset visible to the API token. Requests /assets in+ * $top-sized pages and follows $skip forward until a short page+ * comes back. Yields the raw asset rows so the adapter's+ * normalize() can pull fields by their VSA-specific names.+ *+ * @return iterable<int, array<string, mixed>>+ */+ public function assets(int $pageSize = 500): iterable+ {+ $skip = 0;++ do {+ $response = $this->request()+ ->get('/assets', [+ '$top' => $pageSize,+ '$skip' => $skip,+ ])+ ->throw()+ ->json();++ // VSA wraps in {Data: [...], Meta: {TotalCount, ResponseCode}}.+ // Some smaller endpoints return a bare array, so handle both.+ $rows = $response['Data'] ?? (is_array($response) ? $response : []);+ $count = count($rows);++ foreach ($rows as $row) {+ yield $row;+ }++ $skip += $count;+ } while ($count === $pageSize);+ }++ /**+ * Fetch the full inventory record for a single asset. Not used by+ * the primary pull path (the list endpoint already returns the+ * full inventory shape) but handy for on-demand refresh.+ *+ * @return array<string, mixed>+ */+ public function asset(string $identifier): array+ {+ return $this->request()+ ->get('/assets/'.$identifier)+ ->throw()+ ->json();+ }++ /**+ * Fetch every custom-field definition applicable to devices. VSA+ * scopes custom fields to entity types via a Contexts array, so+ * we OData-filter to only those whose Contexts include "Device"+ * to keep the mapping UI free of org-only / site-only fields+ * admins can't map to a per-device Snipe-IT column anyway. The+ * ExpirationDate filter drops archived fields.+ *+ * @return iterable<int, array<string, mixed>>+ */+ public function deviceCustomFieldDefinitions(int $pageSize = 100): iterable+ {+ $skip = 0;++ do {+ $response = $this->request()+ ->get('/customfields', [+ '$top' => $pageSize,+ '$skip' => $skip,+ '$filter' => "Contexts/any(p: p eq 'Device') and ExpirationDate eq null",+ ])+ ->throw()+ ->json();++ $rows = $response['Data'] ?? (is_array($response) ? $response : []);+ $count = count($rows);++ foreach ($rows as $row) {+ yield $row;+ }++ $skip += $count;+ } while ($count === $pageSize);+ }++ /**+ * Fetch the custom-field values for a single device. Response+ * shape is {Data: [{Id, Name, Value, Type}, ...]}. The Identifier+ * GUID is shared between the /assets and /devices endpoints, so+ * callers pass the same GUID they already have from the pull.+ *+ * @return array<int, array<string, mixed>>+ */+ public function deviceCustomFieldValues(string $identifier): array+ {+ $response = $this->request()+ ->get('/devices/'.$identifier.'/customfields')+ ->throw()+ ->json();++ return $response['Data'] ?? (is_array($response) ? $response : []);+ }++ private function request(): PendingRequest+ {+ return Http::baseUrl(rtrim($this->baseUrl, '/').'/api/v3')+ ->withHeaders(['Authorization' => 'Basic '.$this->basicAuth()])+ ->acceptJson()+ ->timeout(30);+ }++ /**+ * Encode the paired token as a Basic auth header value. Cached on+ * this instance so we don't recompute per request. Empty either+ * half produces the empty string. The API will reject it with 401+ * on the first call, which surfaces the misconfiguration to the+ * admin via the sync log.+ */+ private function basicAuth(): string+ {+ if ($this->basicAuth !== null) {+ return $this->basicAuth;+ }++ return $this->basicAuth = base64_encode($this->tokenId.':'.$this->tokenSecret);+ }+}diff --git a/database/migrations/2026_09_09_120000_seed_kaseya_vsa10_adapter_instance.php b/database/migrations/2026_09_09_120000_seed_kaseya_vsa10_adapter_instance.phpnew file mode 100644index 0000000000..2c8ab2849d--- /dev/null+++ b/database/migrations/2026_09_09_120000_seed_kaseya_vsa10_adapter_instance.php@@ -0,0 +1,33 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Support\Facades\DB;++return new class extends Migration+{+ public function up(): void+ {+ if (DB::table('sync_adapter_instances')->where('slug', 'kaseya_vsa10')->exists()) {+ return;+ }++ $now = now();+ DB::table('sync_adapter_instances')->insert([+ 'slug' => 'kaseya_vsa10',+ 'adapter_type' => 'kaseya_vsa10',+ 'label' => 'Kaseya VSA 10',+ 'active' => false,+ 'built_in' => true,+ 'created_at' => $now,+ 'updated_at' => $now,+ ]);+ }++ public function down(): void+ {+ DB::table('sync_adapter_instances')+ ->where('slug', 'kaseya_vsa10')+ ->where('built_in', true)+ ->delete();+ }+};diff --git a/tests/Feature/SyncAdapters/KaseyaVsa10/KaseyaVsa10AdapterTest.php b/tests/Feature/SyncAdapters/KaseyaVsa10/KaseyaVsa10AdapterTest.phpnew file mode 100644index 0000000000..1772093356--- /dev/null+++ b/tests/Feature/SyncAdapters/KaseyaVsa10/KaseyaVsa10AdapterTest.php@@ -0,0 +1,265 @@+<?php++namespace Tests\Feature\SyncAdapters\KaseyaVsa10;++use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\SyncAdapters\KaseyaVsa10\KaseyaVsa10Adapter;+use App\SyncAdapters\SyncHostFromAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;++/**+ * End-to-end coverage for the Kaseya VSA 10 adapter through+ * SyncHostFromAdapter. Fakes the Basic-auth /api/v3/assets endpoint+ * and asserts extraction from the nested AssetInfo[] category shape.+ */+class KaseyaVsa10AdapterTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ }++ public function test_pulls_assets_from_vsa10_and_creates_snipe_it_assets()+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/api/v3/assets*' => Http::response([+ 'Data' => [+ $this->vsaAsset(identifier: 'guid-1', name: 'vsa-host-1', model: 'OptiPlex 7080'),+ $this->vsaAsset(identifier: 'guid-2', name: 'vsa-host-2', model: 'Latitude 5420'),+ ],+ 'Meta' => ['TotalCount' => 2, 'ResponseCode' => 200],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncHostFromAdapter::run($record);+ }++ $this->assertDatabaseCount('asset_external_sources', 2);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'kaseya_vsa10', 'external_id' => 'guid-1']);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'kaseya_vsa10', 'external_id' => 'guid-2']);+ }++ public function test_normalized_record_extracts_hardware_and_os_from_asset_info_categories()+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/api/v3/assets*' => Http::response([+ 'Data' => [+ [+ 'Identifier' => 'guid-abc',+ 'Name' => 'vsa-desktop',+ 'GroupName' => 'Windows Workstations',+ 'Type' => 'windows',+ 'ClientVersion' => '5.1.2',+ 'LastSeenOnline' => '2026-08-11T15:10:06Z',+ 'PublicIpAddress' => '203.0.113.7',+ 'OrganizationId' => 42,+ 'Tags' => ['production'],+ 'LocalIpAddresses' => [+ [+ 'Name' => 'Ethernet0',+ 'PhysicalAddress' => 'AA:BB:CC:DD:EE:FF',+ 'IpV4' => '10.0.0.5',+ 'IpV6' => null,+ ],+ ],+ 'AssetInfo' => [+ [+ 'CategoryName' => 'System',+ 'CategoryData' => [+ 'Manufacturer' => 'Dell Inc.',+ 'Model' => 'OptiPlex 7080',+ 'CPU' => 'Intel Core i7-10700',+ 'Domain' => 'CORP',+ ],+ ],+ [+ 'CategoryName' => 'BIOS',+ 'CategoryData' => [+ 'Serial Number' => 'ABC123XYZ',+ 'Manufacturer' => 'Dell Inc.',+ 'Version' => '2.15.0',+ ],+ ],+ [+ 'CategoryName' => 'Operating System',+ 'CategoryData' => [+ 'Name' => 'Windows 11 Enterprise',+ 'Version' => '10.0.22631.0',+ ],+ ],+ ],+ ],+ ],+ 'Meta' => ['TotalCount' => 1, 'ResponseCode' => 200],+ ]),+ ]);++ $records = iterator_to_array($adapter->pull());+ $this->assertCount(1, $records);++ $record = $records[0];+ $this->assertSame('kaseya_vsa10', $record->sourceKey);+ $this->assertSame('guid-abc', $record->sourceId);+ $this->assertSame('vsa-desktop', $record->hostname);+ $this->assertSame('ABC123XYZ', $record->hardwareSerial);+ $this->assertSame('OptiPlex 7080', $record->hardwareModel);+ $this->assertSame('Dell Inc.', $record->manufacturer);+ $this->assertSame('AA:BB:CC:DD:EE:FF', $record->primaryMac);+ $this->assertSame('203.0.113.7', $record->primaryIp);+ $this->assertSame('Windows 11 Enterprise', $record->os);+ $this->assertSame('10.0.22631.0', $record->osVersion);+ $this->assertNotNull($record->lastSeen);+ $this->assertSame('42', $record->vendorGroupId);+ $this->assertSame('Intel Core i7-10700', $record->extra['kaseya_vsa10_cpu']);+ $this->assertSame('CORP', $record->extra['kaseya_vsa10_domain']);+ $this->assertSame('Windows Workstations', $record->extra['kaseya_vsa10_group']);+ }++ public function test_missing_asset_info_categories_yield_null_hardware_fields()+ {+ // An asset that hasn't reported a BIOS or Operating System+ // category yet (fresh agent install still auditing) should+ // still normalize cleanly. Fields that depend on missing+ // categories come back null and downstream saveOrFail paths+ // decide whether the record has enough to create a shell+ // asset.+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/api/v3/assets*' => Http::response([+ 'Data' => [+ [+ 'Identifier' => 'guid-fresh',+ 'Name' => 'freshly-enrolled',+ 'Type' => 'mac',+ 'AssetInfo' => [+ [+ 'CategoryName' => 'System',+ 'CategoryData' => [+ 'Manufacturer' => 'Apple Inc.',+ 'Model' => 'MacBookPro18,3',+ ],+ ],+ ],+ ],+ ],+ ]),+ ]);++ $record = iterator_to_array($adapter->pull())[0];+ $this->assertSame('MacBookPro18,3', $record->hardwareModel);+ $this->assertSame('Apple Inc.', $record->manufacturer);+ $this->assertNull($record->hardwareSerial);+ $this->assertNull($record->osVersion);+ // OS falls back to the coarse Type when the OS category is absent.+ $this->assertSame('mac', $record->os);+ }++ public function test_falls_back_to_local_ip_when_public_missing()+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/api/v3/assets*' => Http::response([+ 'Data' => [+ [+ 'Identifier' => 'guid-lan-only',+ 'Name' => 'vsa-lan',+ 'LocalIpAddresses' => [+ ['PhysicalAddress' => '11:22:33:44:55:66', 'IpV4' => '10.0.0.99', 'IpV6' => null],+ ],+ 'AssetInfo' => [+ [+ 'CategoryName' => 'System',+ 'CategoryData' => ['Manufacturer' => 'Foo', 'Model' => 'Bar'],+ ],+ ],+ ],+ ],+ ]),+ ]);++ $record = iterator_to_array($adapter->pull())[0];+ $this->assertSame('10.0.0.99', $record->primaryIp);+ }++ public function test_sends_basic_auth_header_from_token_pair()+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/api/v3/assets*' => Http::response(['Data' => []]),+ ]);++ iterator_to_array($adapter->pull());++ $expected = 'Basic '.base64_encode('stub-token-id:fake-token-secret');+ Http::assertSent(fn ($request) => $request->hasHeader('Authorization', $expected));+ }++ public function test_handles_bare_array_response_shape()+ {+ // Belt-and-suspenders: if VSA ever returns a flat array+ // instead of {Data: [...]}, iterate it directly rather than+ // silently yielding zero records.+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/api/v3/assets*' => Http::response([+ $this->vsaAsset(identifier: 'guid-flat', name: 'flat-host', model: 'Generic'),+ ]),+ ]);++ $records = iterator_to_array($adapter->pull());+ $this->assertCount(1, $records);+ $this->assertSame('guid-flat', $records[0]->sourceId);+ }++ private function configuredAdapter(): KaseyaVsa10Adapter+ {+ $instance = SyncAdapterInstance::where('slug', 'kaseya_vsa10')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://acme.vsax.net');+ SyncAdapterConfig::put($instance->id, 'token_id', Crypt::encrypt('stub-token-id'));+ SyncAdapterConfig::put($instance->id, 'token_secret', Crypt::encrypt('fake-token-secret'));++ return new KaseyaVsa10Adapter($instance->fresh());+ }++ /**+ * Minimal asset row with just enough fields for a shell Snipe-IT+ * asset save (Manufacturer + Model in the System category, and a+ * BIOS serial). Full field coverage is exercised in+ * test_normalized_record_extracts_hardware_and_os_from_asset_info_categories.+ *+ * @return array<string, mixed>+ */+ private function vsaAsset(string $identifier, string $name, string $model): array+ {+ return [+ 'Identifier' => $identifier,+ 'Name' => $name,+ 'OrganizationId' => 1,+ 'Type' => 'windows',+ 'AssetInfo' => [+ [+ 'CategoryName' => 'System',+ 'CategoryData' => ['Manufacturer' => 'Test Corp', 'Model' => $model],+ ],+ [+ 'CategoryName' => 'BIOS',+ 'CategoryData' => ['Serial Number' => 'SN-'.$identifier],+ ],+ ],+ ];+ }+}diff --git a/tests/Feature/SyncAdapters/KaseyaVsa10/KaseyaVsa10CustomFieldsTest.php b/tests/Feature/SyncAdapters/KaseyaVsa10/KaseyaVsa10CustomFieldsTest.phpnew file mode 100644index 0000000000..9488be3cac--- /dev/null+++ b/tests/Feature/SyncAdapters/KaseyaVsa10/KaseyaVsa10CustomFieldsTest.php@@ -0,0 +1,282 @@+<?php++namespace Tests\Feature\SyncAdapters\KaseyaVsa10;++use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\Models\User;+use App\SyncAdapters\KaseyaVsa10\KaseyaVsa10Adapter;+use App\SyncAdapters\Support\MappingTargets;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;++/**+ * Coverage for the VSA 10 vendor-custom-field flow:+ * - fetching the definitions from /customfields+ * - caching them under vendor_custom_fields+ * - surfacing them in extraFields() with admin_defined = true+ * - narrowing the mapping-target pool to skip + custom-only+ * - enriching pulled records with per-device values only when at+ * least one field has been mapped+ * - refresh route flow via the settings controller+ */+class KaseyaVsa10CustomFieldsTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();+ }++ public function test_fetch_vendor_custom_fields_filters_to_device_context()+ {+ $adapter = $this->configuredAdapter();++ Http::fake([+ '*/api/v3/customfields*' => Http::response([+ 'Data' => [+ ['Id' => 850, 'Name' => 'Purchase Cost', 'Type' => 'Number', 'Contexts' => ['Device']],+ ['Id' => 851, 'Name' => 'Compliance', 'Type' => 'Boolean', 'Contexts' => ['Device']],+ ],+ 'Meta' => ['TotalCount' => 2, 'ResponseCode' => 200],+ ]),+ ]);++ $fields = $adapter->fetchVendorCustomFields();++ $this->assertCount(2, $fields);+ $this->assertSame(['id' => '850', 'name' => 'Purchase Cost', 'type' => 'Number'], $fields[0]);+ $this->assertSame(['id' => '851', 'name' => 'Compliance', 'type' => 'Boolean'], $fields[1]);++ Http::assertSent(fn ($request) => str_contains(urldecode($request->url()), "Contexts/any(p: p eq 'Device')"));+ }++ public function test_cached_custom_fields_show_up_in_extra_fields_with_admin_defined_flag()+ {+ $adapter = $this->configuredAdapter();++ SyncAdapterConfig::put(+ $this->instanceId(),+ 'vendor_custom_fields',+ json_encode([+ ['id' => '850', 'name' => 'Purchase Cost', 'type' => 'Number'],+ ['id' => '851', 'name' => 'Compliance', 'type' => 'Boolean'],+ ]),+ );++ $extras = $adapter->extraFields();++ $this->assertArrayHasKey('kaseya_vsa10_cf_purchase_cost', $extras);+ $this->assertArrayHasKey('kaseya_vsa10_cf_compliance', $extras);++ $cost = $extras['kaseya_vsa10_cf_purchase_cost'];+ $this->assertSame('Kaseya: Purchase Cost', $cost['label']);+ $this->assertSame('text', $cost['type']);+ $this->assertTrue($cost['admin_defined']);++ $compliance = $extras['kaseya_vsa10_cf_compliance'];+ $this->assertSame('boolean', $compliance['type']);+ $this->assertTrue($compliance['admin_defined']);+ }++ public function test_options_for_admin_defined_extra_omits_native_targets()+ {+ \App\Models\CustomField::factory()->create(['element' => 'text', 'name' => 'Purchase Info']);++ $adapterExtras = MappingTargets::optionsForExtra('text', adminDefined: false);+ $adminExtras = MappingTargets::optionsForExtra('text', adminDefined: true);++ // Adapter-declared text extras keep the native branch+ // (asset_tag, model, notes).+ $this->assertArrayHasKey('native:asset_tag', $adapterExtras);+ $this->assertArrayHasKey('native:model', $adapterExtras);+ $this->assertArrayHasKey('native:notes', $adapterExtras);++ // Admin-defined extras drop them. Skip + custom fields only.+ $this->assertArrayNotHasKey('native:asset_tag', $adminExtras);+ $this->assertArrayNotHasKey('native:model', $adminExtras);+ $this->assertArrayNotHasKey('native:notes', $adminExtras);+ $this->assertArrayHasKey('skip', $adminExtras);+ foreach (array_keys($adminExtras) as $target) {+ if ($target === 'skip') {+ continue;+ }+ $this->assertStringStartsWith('custom:', $target);+ }+ }++ public function test_pull_enriches_records_when_a_vendor_custom_field_is_mapped()+ {+ $customField = \App\Models\CustomField::factory()->create(['element' => 'text', 'name' => 'Purchase Cost']);+ $adapter = $this->configuredAdapter();++ SyncAdapterConfig::put(+ $this->instanceId(),+ 'vendor_custom_fields',+ json_encode([['id' => '850', 'name' => 'Purchase Cost', 'type' => 'Text']]),+ );+ SyncAdapterConfig::put(+ $this->instanceId(),+ 'mapping.kaseya_vsa10_cf_purchase_cost',+ 'custom:'.$customField->id,+ );++ Http::fake([+ '*/api/v3/assets*' => Http::response([+ 'Data' => [$this->minimalAsset('guid-1')],+ ]),+ '*/api/v3/devices/guid-1/customfields' => Http::response([+ 'Data' => [+ ['Id' => 850, 'Name' => 'Purchase Cost', 'Value' => '1299.00', 'Type' => 'Text'],+ ['Id' => 851, 'Name' => 'Unmapped Field', 'Value' => 'ignored', 'Type' => 'Text'],+ ],+ 'Meta' => ['TotalCount' => 2, 'ResponseCode' => 200],+ ]),+ ]);++ $record = iterator_to_array($adapter->pull())[0];++ $this->assertSame('1299.00', $record->extra['kaseya_vsa10_cf_purchase_cost']);+ // Unmapped field still gets stashed under its slug key, so a+ // follow-up mapping picks up the value from the same pull if+ // the admin adds it. Extras that aren't mapped simply never+ // get written (the mapping-loop's target check handles it).+ $this->assertSame('ignored', $record->extra['kaseya_vsa10_cf_unmapped_field']);+ }++ public function test_pull_skips_customfields_call_when_nothing_is_mapped()+ {+ $adapter = $this->configuredAdapter();++ SyncAdapterConfig::put(+ $this->instanceId(),+ 'vendor_custom_fields',+ json_encode([['id' => '850', 'name' => 'Purchase Cost', 'type' => 'Text']]),+ );+ // No mapping.kaseya_vsa10_cf_purchase_cost row.++ Http::fake([+ '*/api/v3/assets*' => Http::response([+ 'Data' => [$this->minimalAsset('guid-x')],+ ]),+ '*/api/v3/devices/*/customfields' => Http::response(+ ['Data' => []],+ 500, // deliberately unreachable so any accidental call would fail loudly+ ),+ ]);++ iterator_to_array($adapter->pull());++ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/customfields'));+ }++ public function test_pull_survives_customfields_endpoint_failure()+ {+ $customField = \App\Models\CustomField::factory()->create(['element' => 'text', 'name' => 'Anything']);+ $adapter = $this->configuredAdapter();++ SyncAdapterConfig::put(+ $this->instanceId(),+ 'vendor_custom_fields',+ json_encode([['id' => '850', 'name' => 'Anything', 'type' => 'Text']]),+ );+ SyncAdapterConfig::put(+ $this->instanceId(),+ 'mapping.kaseya_vsa10_cf_anything',+ 'custom:'.$customField->id,+ );++ Http::fake([+ '*/api/v3/assets*' => Http::response(['Data' => [$this->minimalAsset('guid-transient')]]),+ '*/api/v3/devices/*/customfields' => Http::response(['error' => 'boom'], 503),+ ]);++ $records = iterator_to_array($adapter->pull());++ // Record still comes through; the un-enriched fields just stay+ // absent from extra. Sync doesn't abort on a partial customfields+ // outage.+ $this->assertCount(1, $records);+ $this->assertArrayNotHasKey('kaseya_vsa10_cf_anything', $records[0]->extra);+ }++ public function test_refresh_route_populates_the_cache_and_flashes_a_success()+ {+ $this->configuredAdapter();++ Http::fake([+ '*/api/v3/customfields*' => Http::response([+ 'Data' => [+ ['Id' => 850, 'Name' => 'Purchase Cost', 'Type' => 'Number', 'Contexts' => ['Device']],+ ],+ ]),+ ]);++ $instance = SyncAdapterInstance::where('slug', 'kaseya_vsa10')->firstOrFail();+ $instance->active = true;+ $instance->save();++ $response = $this+ ->actingAs(User::factory()->superuser()->create())+ ->post(route('settings.adapters.refresh_custom_fields', $instance->slug));++ $response->assertRedirect(route('settings.adapters.index', ['adapter' => $instance->slug]));+ $response->assertSessionHas('success');++ $stored = SyncAdapterConfig::get($instance->id, 'vendor_custom_fields');+ $decoded = json_decode($stored, true);+ $this->assertSame('Purchase Cost', $decoded[0]['name']);+ }++ public function test_refresh_route_404s_for_adapters_that_do_not_support_vendor_custom_fields()+ {+ $fleet = SyncAdapterInstance::where('slug', 'fleet')->firstOrFail();+ $fleet->active = true;+ $fleet->save();++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('settings.adapters.refresh_custom_fields', $fleet->slug))+ ->assertNotFound();+ }++ private function configuredAdapter(): KaseyaVsa10Adapter+ {+ $instance = SyncAdapterInstance::where('slug', 'kaseya_vsa10')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'url', 'https://acme.vsax.net');+ SyncAdapterConfig::put($instance->id, 'token_id', Crypt::encrypt('stub-token-id'));+ SyncAdapterConfig::put($instance->id, 'token_secret', Crypt::encrypt('fake-token-secret'));++ return new KaseyaVsa10Adapter($instance->fresh());+ }++ private function instanceId(): int+ {+ return SyncAdapterInstance::where('slug', 'kaseya_vsa10')->firstOrFail()->id;+ }++ /**+ * Minimum asset row with enough hardware fields for a shell save.+ *+ * @return array<string, mixed>+ */+ private function minimalAsset(string $identifier): array+ {+ return [+ 'Identifier' => $identifier,+ 'Name' => 'vsa-'.$identifier,+ 'OrganizationId' => 1,+ 'AssetInfo' => [+ [+ 'CategoryName' => 'System',+ 'CategoryData' => ['Manufacturer' => 'Test Corp', 'Model' => 'Model X'],+ ],+ [+ 'CategoryName' => 'BIOS',+ 'CategoryData' => ['Serial Number' => 'SN-'.$identifier],+ ],+ ],+ ];+ }+}