Skip to content

A free open source IT asset/license management system

Added Unifi Access Adapter

snipea9f5137b3974
diff --git a/app/SyncAdapters/UnifiAccess/UnifiAccessAdapter.php b/app/SyncAdapters/UnifiAccess/UnifiAccessAdapter.php
new file mode 100644
index 0000000000..9577a01dc9
--- /dev/null
+++ b/app/SyncAdapters/UnifiAccess/UnifiAccessAdapter.php
@@ -0,0 +1,155 @@
+<?php
+
+namespace App\SyncAdapters\UnifiAccess;
+
+use App\SyncAdapters\HostInventoryRecord;
+use App\SyncAdapters\SyncAdapter;
+use Carbon\Carbon;
+use Illuminate\Support\Arr;
+
+/**
+ * UniFi Access adapter. Pulls access-hardware inventory (door hubs,
+ * readers, elevator hubs, Access-managed cameras) from a UniFi
+ * console's Access app and normalizes it into HostInventoryRecord
+ * objects.
+ *
+ * This is a sibling to UnifiAdapter, not a replacement. Network and
+ * Access are separate UniFi apps with separate APIs, separate API
+ * tokens, and no shared site model. Admins running both configure one
+ * instance of each (the clone pattern on the Add Adapter modal makes
+ * that cheap).
+ */
+class UnifiAccessAdapter extends SyncAdapter
+{
+ public static function typeLabel(): string
+ {
+ return 'UniFi Access';
+ }
+
+ public static function typeSlug(): string
+ {
+ return 'unifi-access';
+ }
+
+ public static function docsUrl(): ?string
+ {
+ return 'https://assets.identity.ui.com/unifi-access/api_reference.pdf';
+ }
+
+ public function baseUrlPlaceholder(): ?string
+ {
+ // UniFi Access runs its API on port 12445, independent of
+ // Network (443/8443). Server cert is self-signed per the docs.
+ return 'https://your-console:12445';
+ }
+
+ public function settingsSchema(): array
+ {
+ return [
+ [
+ 'key' => 'api_token',
+ 'label' => trans('admin/settings/sync_adapters.label_api_token'),
+ 'secret' => true,
+ 'help' => trans('admin/settings/sync_adapters.unifi_access_api_token_help'),
+ ],
+ ];
+ }
+
+ public function presetExtraFields(): array
+ {
+ return [
+ 'unifi_access_device_type' => ['label_key' => 'admin/settings/sync_adapters.extra_model_code'],
+ 'unifi_access_status' => ['label_key' => 'admin/settings/sync_adapters.extra_device_state'],
+ 'unifi_access_adopted' => ['label_key' => 'admin/settings/sync_adapters.extra_adopted', 'type' => 'boolean'],
+ ];
+ }
+
+ public function pull(): iterable
+ {
+ $client = new UnifiAccessClient(
+ baseUrl: $this->url(),
+ apiToken: $this->credential('api_token'),
+ );
+
+ foreach ($client->devices() as $device) {
+ yield $this->normalize($device);
+ }
+ }
+
+ /**
+ * Convert a UniFi Access device payload into the normalized record
+ * shape. Access's `id` is stable per adopted device and is what we
+ * key asset_external_sources on. The documented /devices response
+ * is minimal (id, name, type, alias). The mac, ip, firmware,
+ * serial, and last_seen fallbacks are opportunistic. They may be
+ * present on some firmware revisions, absent on others, and
+ * resolve to null when absent. Field-name variants (snake_case vs
+ * camelCase) also fall through so API revisions don't silently
+ * blank the record.
+ *
+ * @param array<string, mixed> $device
+ */
+ private function normalize(array $device): HostInventoryRecord
+ {
+ $id = (string) (Arr::get($device, 'id') ?? Arr::get($device, 'unique_id') ?? '');
+ $hostname = Arr::get($device, 'name') ?? Arr::get($device, 'alias');
+ $serial = Arr::get($device, 'serial_number') ?? Arr::get($device, 'serialNumber');
+ $model = Arr::get($device, 'model_name')
+ ?? Arr::get($device, 'model')
+ ?? Arr::get($device, 'type')
+ ?? Arr::get($device, 'device_type');
+ $mac = Arr::get($device, 'mac') ?? Arr::get($device, 'mac_address') ?? Arr::get($device, 'macAddress');
+ $ip = Arr::get($device, 'ip') ?? Arr::get($device, 'ip_address') ?? Arr::get($device, 'lan_ip');
+ $firmware = Arr::get($device, 'firmware_version')
+ ?? Arr::get($device, 'firmwareVersion')
+ ?? Arr::get($device, 'firmware');
+ $lastSeen = Arr::get($device, 'last_seen')
+ ?? Arr::get($device, 'lastSeen')
+ ?? Arr::get($device, 'last_activity_at');
+
+ // Status comes through as either a boolean `online` or a string
+ // `status` depending on firmware. Normalize to a short string
+ // so the extra field renders consistently.
+ $status = Arr::get($device, 'status');
+ if ($status === null) {
+ $online = Arr::get($device, 'online');
+ if ($online !== null) {
+ $status = $online ? 'online' : 'offline';
+ }
+ }
+
+ return new HostInventoryRecord(
+ sourceKey: $this->name(),
+ sourceId: $id,
+ hostname: $hostname,
+ hardwareSerial: $serial,
+ hardwareModel: $model,
+ manufacturer: 'Ubiquiti',
+ primaryMac: $mac,
+ primaryIp: $ip,
+ os: 'UniFi Access',
+ osVersion: $firmware,
+ lastSeen: $this->parseTimestamp($lastSeen),
+ extra: [
+ 'unifi_access_device_type' => Arr::get($device, 'type') ?? Arr::get($device, 'device_type'),
+ 'unifi_access_status' => $status,
+ 'unifi_access_adopted' => Arr::get($device, 'adopted'),
+ ],
+ );
+ }
+
+ private function parseTimestamp(mixed $value): ?Carbon
+ {
+ if ($value === null || $value === '') {
+ return null;
+ }
+
+ // Access reports last_seen as either a unix epoch (int or
+ // numeric string) or an ISO 8601 string, depending on firmware.
+ if (is_numeric($value)) {
+ return Carbon::createFromTimestamp((int) $value);
+ }
+
+ return Carbon::parse($value);
+ }
+}
diff --git a/app/SyncAdapters/UnifiAccess/UnifiAccessClient.php b/app/SyncAdapters/UnifiAccess/UnifiAccessClient.php
new file mode 100644
index 0000000000..82e92ef219
--- /dev/null
+++ b/app/SyncAdapters/UnifiAccess/UnifiAccessClient.php
@@ -0,0 +1,75 @@
+<?php
+
+namespace App\SyncAdapters\UnifiAccess;
+
+use Illuminate\Http\Client\PendingRequest;
+use Illuminate\Support\Facades\Http;
+
+/**
+ * Thin wrapper around the UniFi Access developer API. Owns auth for
+ * the endpoints the sync adapter uses. Yields raw decoded JSON, no
+ * normalization (that's the adapter's job).
+ *
+ * Auth model: an API token generated in UniFi Portal under
+ * Access -> Settings -> General -> Advanced -> API Token. Sent as a
+ * Bearer token. UniFi Access 1.9.1 or later is required, and the API
+ * is unavailable on consoles that upgraded to Identity Enterprise.
+ *
+ * This is a different credential from the Network API key: the two
+ * apps provision tokens independently, so admins running both
+ * configure one UniFi (Network) instance and one UniFi Access instance,
+ * each with its own token.
+ *
+ * The Access API runs on port 12445 with a self-signed cert and does
+ * not share Network's site model, so there is no site segment in the
+ * path. One console serves one Access deployment.
+ *
+ * UniFi Access developer API reference (PDF):
+ * https://assets.identity.ui.com/unifi-access/api_reference.pdf
+ */
+class UnifiAccessClient
+{
+ public function __construct(
+ private readonly string $baseUrl,
+ private readonly string $apiToken,
+ ) {}
+
+ /**
+ * List every Access device the console knows about (door hubs,
+ * readers, elevator hubs, Access-managed cameras). Yields raw
+ * decoded entries so callers stream through large deployments
+ * without buffering the whole list.
+ *
+ * @return iterable<array<string, mixed>>
+ */
+ public function devices(): iterable
+ {
+ $response = $this->request()
+ ->get('/api/v1/developer/devices')
+ ->throw()
+ ->json();
+
+ // The Access API wraps its payload in {code, msg, data}. Fall
+ // back to the top-level array shape so a future API revision
+ // that drops the envelope still works.
+ $devices = $response['data'] ?? $response;
+ if (! is_array($devices)) {
+ return;
+ }
+
+ foreach ($devices as $device) {
+ if (is_array($device)) {
+ yield $device;
+ }
+ }
+ }
+
+ private function request(): PendingRequest
+ {
+ return Http::baseUrl(rtrim($this->baseUrl, '/'))
+ ->withOptions(['allow_redirects' => false])
+ ->withToken($this->apiToken)
+ ->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 62b1f95a3f..2e3d9734b1 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -212,6 +212,7 @@ return [
'addigy_key_secret_help' => 'Paired with Client ID above. Displayed once in the Addigy admin console at creation time. Needs read access to Devices.',
'unifi_api_key_help' => 'Generate under Settings -> Admins & Users -> API Keys in your UniFi Network application (UniFi OS 4.0.6+ / Network 9.0.108+ required). Older controllers use session cookies and are not supported.',
'unifi_site_id_help' => 'The UniFi site to sync from. Click Refresh Sites above after saving the API key to populate this list from your controller.',
+ 'unifi_access_api_token_help' => 'Sign in to the UniFi Portal, open the console where Access is installed, and go to Access -> Settings -> General -> Advanced -> API Token to generate one. UniFi Access 1.9.1 or later is required, and the API is not available on consoles that have upgraded to Identity Enterprise. This is a different credential from the UniFi Network API key, so running both requires one adapter instance of each.',
'intune_tenant_id_help' => 'Copy your Azure AD tenant\'s Directory (tenant) ID from Microsoft Entra admin center -> Overview.',
'intune_client_id_help' => 'Register an application in Microsoft Entra ID -> App registrations, then copy the Application (client) ID. Grant it the DeviceManagementManagedDevices.Read.All Microsoft Graph application permission (admin consent required).',
'intune_client_secret_help' => 'Generate under your app registration -> Certificates & secrets -> New client secret. Copy the value immediately (Azure only shows it once).',
diff --git a/tests/Feature/SyncAdapters/UnifiAccess/UnifiAccessAdapterTest.php b/tests/Feature/SyncAdapters/UnifiAccess/UnifiAccessAdapterTest.php
new file mode 100644
index 0000000000..d6889c55ca
--- /dev/null
+++ b/tests/Feature/SyncAdapters/UnifiAccess/UnifiAccessAdapterTest.php
@@ -0,0 +1,194 @@
+<?php
+
+namespace Tests\Feature\SyncAdapters\UnifiAccess;
+
+use App\Models\Statuslabel;
+use App\Models\SyncAdapterConfig;
+use App\Models\SyncAdapterInstance;
+use App\SyncAdapters\SyncAdapter;
+use App\SyncAdapters\UnifiAccess\UnifiAccessAdapter;
+use Illuminate\Support\Facades\Crypt;
+use Illuminate\Support\Facades\Http;
+use Tests\TestCase;
+
+/**
+ * End-to-end coverage for the UniFi Access adapter through
+ * SyncAdapter. Mocks the Access developer API, asserts assets +
+ * asset_external_sources land correctly, and that the Bearer token
+ * (not X-API-KEY) goes out on the request.
+ */
+class UnifiAccessAdapterTest extends TestCase
+{
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ Statuslabel::factory()->rtd()->create();
+ }
+
+ public function test_pulls_devices_from_unifi_access_and_creates_assets()
+ {
+ $adapter = $this->configuredUnifiAccessAdapter();
+
+ Http::fake([
+ '*/api/v1/developer/devices' => Http::response([
+ 'code' => 'SUCCESS',
+ 'msg' => '',
+ 'data' => [
+ $this->accessDevice(id: 'door-1', name: 'Front Door Hub', type: 'UA-HUB-DOOR'),
+ $this->accessDevice(id: 'reader-1', name: 'Lobby Reader', type: 'UA-G2-PRO'),
+ ],
+ ]),
+ ]);
+
+ foreach ($adapter->pull() as $record) {
+ SyncAdapter::syncFromRecord($record);
+ }
+
+ $this->assertDatabaseCount('asset_external_sources', 2);
+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'unifi-access', 'external_id' => 'door-1']);
+ $this->assertDatabaseHas('assets', ['name' => 'Front Door Hub']);
+ }
+
+ public function test_bearer_token_is_sent_not_x_api_key_or_cookie()
+ {
+ $adapter = $this->configuredUnifiAccessAdapter();
+
+ Http::fake([
+ '*/api/v1/developer/devices' => Http::response(['code' => 'SUCCESS', 'data' => []]),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ // UniFi Access uses a Bearer token, provisioned separately
+ // from the Network X-API-KEY. A copy-paste regression that
+ // sent the token via the Network header would fail auth
+ // against a real Access console.
+ Http::assertSent(function ($request) {
+ return $request->hasHeader('Authorization', 'Bearer fake-unifi-access-token')
+ && ! $request->hasHeader('X-API-KEY')
+ && ! $request->hasHeader('Cookie');
+ });
+ }
+
+ public function test_envelope_free_payload_is_also_accepted()
+ {
+ $adapter = $this->configuredUnifiAccessAdapter();
+
+ // Some firmware revisions drop the {code, msg, data} envelope
+ // and return a bare array of devices. The client falls back to
+ // the top-level shape so an API revision doesn't break the pull.
+ Http::fake([
+ '*/api/v1/developer/devices' => Http::response([
+ $this->accessDevice(id: 'bare-1', name: 'Service Entrance Hub', type: 'UAH-DOOR'),
+ ]),
+ ]);
+
+ foreach ($adapter->pull() as $record) {
+ SyncAdapter::syncFromRecord($record);
+ }
+
+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'unifi-access', 'external_id' => 'bare-1']);
+ }
+
+ public function test_normalized_record_carries_expected_fields()
+ {
+ $adapter = $this->configuredUnifiAccessAdapter();
+
+ Http::fake([
+ '*/api/v1/developer/devices' => Http::response([
+ 'data' => [
+ $this->accessDevice(
+ id: 'hub-7',
+ name: 'West Wing Hub',
+ type: 'UAH-DOOR',
+ serial: 'UAH-7XY',
+ mac: 'aa:bb:cc:11:22:33',
+ ip: '10.0.0.42',
+ firmware: '2.14.6',
+ lastSeen: '2026-01-15T10:00:00.000Z',
+ status: 'online',
+ ),
+ ],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $this->assertCount(1, $records);
+
+ $record = $records[0];
+ $this->assertSame('unifi-access', $record->sourceKey);
+ $this->assertSame('hub-7', $record->sourceId);
+ $this->assertSame('West Wing Hub', $record->hostname);
+ $this->assertSame('UAH-7XY', $record->hardwareSerial);
+ $this->assertSame('UAH-DOOR', $record->hardwareModel);
+ $this->assertSame('Ubiquiti', $record->manufacturer);
+ $this->assertSame('aa:bb:cc:11:22:33', $record->primaryMac);
+ $this->assertSame('10.0.0.42', $record->primaryIp);
+ $this->assertSame('UniFi Access', $record->os);
+ $this->assertSame('2.14.6', $record->osVersion);
+ $this->assertNotNull($record->lastSeen);
+ $this->assertSame('online', $record->extra['unifi_access_status']);
+ }
+
+ public function test_unix_epoch_last_seen_parses_through()
+ {
+ $adapter = $this->configuredUnifiAccessAdapter();
+
+ // Older Access firmware reports last_seen as a unix epoch
+ // integer. The adapter's parseTimestamp accepts either shape.
+ Http::fake([
+ '*/api/v1/developer/devices' => Http::response([
+ 'data' => [
+ $this->accessDevice(
+ id: 'epoch-1',
+ name: 'Loading Dock Reader',
+ lastSeen: 1_736_000_000,
+ ),
+ ],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $this->assertCount(1, $records);
+ $this->assertNotNull($records[0]->lastSeen);
+ }
+
+ private function configuredUnifiAccessAdapter(): UnifiAccessAdapter
+ {
+ $instance = SyncAdapterInstance::where('slug', 'unifi-access')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'url', 'https://access.example.test');
+ SyncAdapterConfig::put($instance->id, 'api_token', Crypt::encrypt('fake-unifi-access-token'));
+
+ return new UnifiAccessAdapter($instance->fresh());
+ }
+
+ /**
+ * @return array<string, mixed>
+ */
+ private function accessDevice(
+ string $id,
+ string $name = 'Device',
+ string $type = 'UA-HUB-DOOR',
+ ?string $serial = null,
+ ?string $mac = null,
+ ?string $ip = null,
+ ?string $firmware = null,
+ string|int|null $lastSeen = null,
+ string $status = 'online',
+ ): array {
+ return [
+ 'id' => $id,
+ 'name' => $name,
+ 'type' => $type,
+ 'model_name' => $type,
+ 'serial_number' => $serial,
+ 'mac' => $mac,
+ 'ip' => $ip,
+ 'firmware_version' => $firmware,
+ 'last_seen' => $lastSeen,
+ 'status' => $status,
+ 'adopted' => true,
+ ];
+ }
+}