Skip to content

A free open source IT asset/license management system

Added experimental support for Unifi Site Maanager Cloud

snipea0883546e169
diff --git a/app/SyncAdapters/Unifi/UnifiAdapter.php b/app/SyncAdapters/Unifi/UnifiAdapter.php
index 3718f2489d..113d66b0db 100644
--- a/app/SyncAdapters/Unifi/UnifiAdapter.php
+++ b/app/SyncAdapters/Unifi/UnifiAdapter.php
@@ -42,7 +42,11 @@ class UnifiAdapter extends SyncAdapter
public function baseUrlPlaceholder(): ?string
{
- return 'https://your-controller:8443';
+ // A local UniFi console / Network Application
+ // reachable from this Snipe-IT install, or `https://api.ui.com`
+ // for the Site Manager cloud API (the latter is what hosted
+ // Snipe-IT installs want when the UniFi consoles are behind NAT).
+ return 'https://your-controller:8443 or https://api.ui.com';
}
public function settingsSchema(): array
diff --git a/app/SyncAdapters/Unifi/UnifiClient.php b/app/SyncAdapters/Unifi/UnifiClient.php
index af27911297..5de1c02317 100644
--- a/app/SyncAdapters/Unifi/UnifiClient.php
+++ b/app/SyncAdapters/Unifi/UnifiClient.php
@@ -7,44 +7,98 @@ use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
/**
- * Thin wrapper around the UniFi Network Integration API. Owns auth +
- * pagination for the endpoints the sync adapter uses. Yields raw
- * decoded JSON, no normalization (that's the adapter's job).
+ * Thin wrapper around the two UniFi APIs the sync adapter can target:
*
- * Auth model: API key generated in the UniFi admin console under
- * Settings -> Admins & Users -> API Keys, passed via `X-API-KEY`
- * header. Available on UniFi OS 4.0.6+, UniFi Network Application
- * 9.0.108+, and Site Manager cloud. Older controllers only support
- * session-cookie auth which this client does not implement.
+ * - Local Network Integration API, served off a UniFi console or
+ * Network Application at `/proxy/network/integration/v1/`. Admin
+ * points the base URL at the controller (LAN or exposed WAN).
+ * Pagination is offset/limit, device data is site-scoped and
+ * includes serial numbers, MACs, and last-seen timestamps.
*
- * Endpoint path is under /proxy/network/integration/v1/ on local
- * controllers, or at api.ui.com/v1/ on Site Manager cloud. The
- * adapter's Base URL setting controls which. the paths this client
- * hits are relative and identical on both.
+ * - Site Manager cloud API at `https://api.ui.com/v1/`. Admin points
+ * the base URL at `api.ui.com`. Pagination is cursor-based via
+ * `nextToken`, device data is host-scoped (not site-scoped), the
+ * envelope wraps devices under a per-host `data[].devices[]` nest,
+ * and the field names are shorter (mac/ip/version) with no serial
+ * number or lastSeen exposed. Site Manager works through consoles
+ * with Remote Access enabled, so it is the supported path for hosted
+ * Snipe-IT installs talking to consoles behind NAT.
+ *
+ * Both backends authenticate with an `X-API-KEY` header. The key
+ * types are different in UniFi's UI (Settings -> Admins & Users ->
+ * API Keys on a console vs. Site Manager -> Developer Portal) but the
+ * client handles them uniformly.
+ *
+ * This client yields a canonical device shape with the local-API
+ * field names (`serialNumber`, `macAddress`, `ipAddress`,
+ * `firmwareVersion`, `lastSeen`, `modelKey`, `state`, `uplink`,
+ * `adopted`). Cloud-mode responses are translated into that shape
+ * before yielding, with fields the cloud API does not expose set to
+ * null. `UnifiAdapter::normalize` therefore does not need to know
+ * which backend produced a record.
*
* UniFi Network Integration API reference:
* https://developer.ui.com/unifi-api/
+ *
+ * UniFi Site Manager API reference:
+ * https://developer.ui.com/site-manager-api/
*/
class UnifiClient
{
use RetriesTransientHttpErrors;
+ /**
+ * Site Manager cloud host. Hard-coded rather than configurable
+ * because the public API is only served at this one domain today
+ * (unifi.ui.com is the web-console SPA, not an API).
+ */
+ private const SITE_MANAGER_HOST = 'api.ui.com';
+
+ private readonly bool $isCloud;
+
public function __construct(
private readonly string $baseUrl,
private readonly string $apiKey,
private readonly ?string $siteId = null,
- ) {}
+ ) {
+ $this->isCloud = $this->baseUrlLooksLikeSiteManager($baseUrl);
+ }
/**
- * List every site visible to the API key. Used to populate the
- * Site ID picker on the adapter settings page so admins don't have
- * to copy the UUID out of UniFi's admin console by hand. One shot,
- * site lists for a single controller never run long enough to
- * justify pagination.
+ * List every site the API key can see. On the local backend this
+ * returns the sites configured on the one UniFi console the base
+ * URL points at. On Site Manager cloud this returns sites across
+ * every console the key has access to. The stored identifier is
+ * the host ID (which is what the device-list endpoint accepts as
+ * its filter), so two sites on the same console collapse to one
+ * dropdown row.
*
* @return array<int, array<string, mixed>>
*/
public function sites(): array
+ {
+ return $this->isCloud ? $this->sitesFromCloud() : $this->sitesFromLocal();
+ }
+
+ /**
+ * List every managed device at the configured scope. Local mode
+ * is site-scoped (siteId maps to a controller site), cloud mode
+ * is host-scoped (siteId is treated as the Site Manager hostId
+ * and all devices on that console are returned regardless of
+ * which internal site they belong to, because the public cloud
+ * device endpoint does not expose a site filter today).
+ *
+ * @return iterable<array<string, mixed>>
+ */
+ public function devices(int $limit = 100): iterable
+ {
+ return $this->isCloud ? $this->devicesFromCloud() : $this->devicesFromLocal($limit);
+ }
+
+ /**
+ * @return array<int, array<string, mixed>>
+ */
+ private function sitesFromLocal(): array
{
$response = $this->request()
->get('/proxy/network/integration/v1/sites')
@@ -55,14 +109,9 @@ class UnifiClient
}
/**
- * List every managed device in the configured UniFi site (APs,
- * switches, gateways, cameras, etc). Returns a generator so
- * callers stream through large deployments without buffering the
- * whole list in memory.
- *
* @return iterable<array<string, mixed>>
*/
- public function devices(int $limit = 100): iterable
+ private function devicesFromLocal(int $limit): iterable
{
$offset = 0;
@@ -80,9 +129,6 @@ class UnifiClient
yield $device;
}
- // Stop when seen-so-far reaches totalCount or a short
- // page comes back. Belt-and-suspenders: either signal
- // alone would work.
$total = $response['totalCount'] ?? null;
$seenSoFar = $offset + count($devices);
$done = count($devices) < $limit
@@ -91,6 +137,123 @@ class UnifiClient
} while (! $done);
}
+ /**
+ * Walk /v1/sites via nextToken cursor, flattening each row into
+ * the {id, name} shape the adapter already expects. Uses the
+ * hostId as the stored config value. Host-scoped filtering
+ * aggregates sibling sites on the same console. Adding a per-site
+ * filter would require the console to expose siteIds[] on
+ * /v1/devices, which it does not today.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ private function sitesFromCloud(): array
+ {
+ $sites = [];
+ $nextToken = null;
+
+ do {
+ $query = ['pageSize' => '100'];
+ if ($nextToken !== null) {
+ $query['nextToken'] = $nextToken;
+ }
+
+ $response = $this->request()
+ ->get('/v1/sites', $query)
+ ->throw()
+ ->json();
+
+ foreach ($response['data'] ?? [] as $row) {
+ $hostId = $row['hostId'] ?? null;
+ if ($hostId === null || $hostId === '') {
+ continue;
+ }
+
+ $sites[] = [
+ 'id' => (string) $hostId,
+ 'name' => $row['meta']['name'] ?? (string) $hostId,
+ 'displayName' => $row['meta']['name'] ?? null,
+ ];
+ }
+
+ $nextToken = $response['nextToken'] ?? null;
+ } while (! empty($nextToken));
+
+ return $sites;
+ }
+
+ /**
+ * Walk /v1/devices?hostIds[]={hostId} via nextToken cursor,
+ * flatten each host's nested devices[], and translate cloud field
+ * names to the canonical local-API shape so UnifiAdapter::normalize
+ * does not need two code paths.
+ *
+ * @return iterable<array<string, mixed>>
+ */
+ private function devicesFromCloud(): iterable
+ {
+ $nextToken = null;
+
+ do {
+ $query = [
+ 'hostIds[]' => $this->siteId,
+ 'pageSize' => '100',
+ ];
+ if ($nextToken !== null) {
+ $query['nextToken'] = $nextToken;
+ }
+
+ $response = $this->request()
+ ->get('/v1/devices', $query)
+ ->throw()
+ ->json();
+
+ foreach ($response['data'] ?? [] as $hostRow) {
+ foreach ($hostRow['devices'] ?? [] as $cloudDevice) {
+ yield $this->translateCloudDevice($cloudDevice);
+ }
+ }
+
+ $nextToken = $response['nextToken'] ?? null;
+ } while (! empty($nextToken));
+ }
+
+ /**
+ * Map Site Manager's device shape to the canonical local-API shape
+ * the adapter normalizes against. Fields Site Manager does not
+ * expose (serial number, last-seen, uplink MAC) stay null.
+ *
+ * @param array<string, mixed> $cloudDevice
+ * @return array<string, mixed>
+ */
+ private function translateCloudDevice(array $cloudDevice): array
+ {
+ return [
+ 'id' => $cloudDevice['id'] ?? null,
+ 'name' => $cloudDevice['name'] ?? null,
+ 'model' => $cloudDevice['model'] ?? null,
+ 'modelKey' => $cloudDevice['shortname'] ?? null,
+ 'serialNumber' => null,
+ 'macAddress' => $cloudDevice['mac'] ?? null,
+ 'ipAddress' => $cloudDevice['ip'] ?? null,
+ 'firmwareVersion' => $cloudDevice['version'] ?? null,
+ 'lastSeen' => null,
+ 'state' => $cloudDevice['status'] ?? null,
+ 'uplink' => ['mac' => null],
+ 'adopted' => $cloudDevice['isManaged'] ?? null,
+ ];
+ }
+
+ private function baseUrlLooksLikeSiteManager(string $url): bool
+ {
+ $host = parse_url($url, PHP_URL_HOST);
+ if (! is_string($host)) {
+ return false;
+ }
+
+ return strtolower($host) === self::SITE_MANAGER_HOST;
+ }
+
private function request(): PendingRequest
{
return $this->withTransientRetry(
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index 35c3d229ee..74470700e2 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -227,8 +227,8 @@ return [
'osctrl_environment_help' => 'The osctrl environment name to sync from (e.g. prod, dev).',
'addigy_key_id_help' => 'Generate under Integrations -> Addigy API in your Addigy admin console. Both Client ID and Client Secret come from the same "Create API Integration" flow. Client ID is a public identifier and not encrypted at rest.',
'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_api_key_help' => 'Two paths depending on the Base URL above. If pointing at a local UniFi console or Network Application (UniFi OS 4.0.6+ / Network 9.0.108+), generate the key under Settings -> Admins & Users -> API Keys. If pointing at https://api.ui.com (Site Manager cloud, used by hosted Snipe-IT installs when the UniFi consoles are behind NAT and cannot be reached directly), generate the key in the UniFi Site Manager developer portal with Site Manager + Network scopes. Older controllers using session cookies 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 or from Site Manager. On Site Manager cloud each row maps to a console (two sites on the same console share one row because the public cloud API does not expose a per-site device filter today).',
'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 the DeviceManagementManagedDevices.Read.All Microsoft Graph application permission for pull. Add DeviceManagementManagedDevices.ReadWrite.All to push composed notes back to Intune, and DeviceManagementConfiguration.Read.All to filter devices by scope tag name rather than ID. Admin consent is required.',
diff --git a/tests/Feature/SyncAdapters/Unifi/UnifiAdapterTest.php b/tests/Feature/SyncAdapters/Unifi/UnifiAdapterTest.php
index e67c4a2c10..f8d5f6927b 100644
--- a/tests/Feature/SyncAdapters/Unifi/UnifiAdapterTest.php
+++ b/tests/Feature/SyncAdapters/Unifi/UnifiAdapterTest.php
@@ -134,16 +134,169 @@ class UnifiAdapterTest extends TestCase
$this->assertNotNull($record->lastSeen);
}
- private function configuredUnifiAdapter(string $siteId = 'default'): UnifiAdapter
+ public function test_cloud_mode_pulls_devices_via_site_manager_endpoint()
{
+ // Base URL set to Site Manager (api.ui.com) flips the client to
+ // cloud mode: devices come from /v1/devices?hostIds[]=... rather
+ // than /proxy/network/integration/v1/sites/{id}/devices.
+ // Regression test for the hosted-NAT gap called out by the
+ // pennywise install (consoles behind NAT with Remote Access,
+ // adapter had no cloud path).
+ $adapter = $this->configuredUnifiAdapter(
+ url: 'https://api.ui.com',
+ siteId: 'host-abc-123',
+ );
+
+ Http::fake([
+ 'api.ui.com/v1/devices*' => Http::response([
+ 'httpStatusCode' => 200,
+ 'data' => [
+ [
+ 'hostId' => 'host-abc-123',
+ 'hostName' => 'UDM Pro Max',
+ 'devices' => [
+ $this->siteManagerDevice(id: 'dev-cloud-1', name: 'ap-cloud-1', model: 'U6-Pro'),
+ $this->siteManagerDevice(id: 'dev-cloud-2', name: 'sw-cloud-1', model: 'USW-Lite-8-PoE'),
+ ],
+ ],
+ ],
+ 'nextToken' => '',
+ ]),
+ ]);
+
+ foreach ($adapter->pull() as $record) {
+ SyncAdapter::syncFromRecord($record);
+ }
+
+ $this->assertDatabaseCount('asset_external_sources', 2);
+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'unifi', 'external_id' => 'dev-cloud-1']);
+ $this->assertDatabaseHas('assets', ['name' => 'ap-cloud-1']);
+
+ Http::assertSent(function ($request) {
+ return str_contains($request->url(), 'api.ui.com/v1/devices')
+ && str_contains(urldecode($request->url()), 'hostIds[]=host-abc-123')
+ && $request->hasHeader('X-API-KEY', 'fake-unifi-api-key');
+ });
+ }
+
+ public function test_cloud_mode_translates_short_field_names_and_fills_missing_fields_null()
+ {
+ // Site Manager uses mac/ip/version short names and does not
+ // expose serialNumber or lastSeen. Those gaps must map cleanly
+ // onto the canonical HostInventoryRecord fields rather than
+ // leaking the raw cloud payload shape through.
+ $adapter = $this->configuredUnifiAdapter(
+ url: 'https://api.ui.com',
+ siteId: 'host-xyz',
+ );
+
+ Http::fake([
+ 'api.ui.com/v1/devices*' => Http::response([
+ 'httpStatusCode' => 200,
+ 'data' => [
+ [
+ 'hostId' => 'host-xyz',
+ 'devices' => [
+ [
+ 'id' => 'dev-cloud-7',
+ 'name' => 'gw-cloud',
+ 'model' => 'UDM-SE',
+ 'shortname' => 'UDMSE',
+ 'mac' => 'aa:bb:cc:dd:ee:ff',
+ 'ip' => '192.0.2.5',
+ 'version' => '4.1.13',
+ 'status' => 'online',
+ 'isManaged' => true,
+ ],
+ ],
+ ],
+ ],
+ 'nextToken' => '',
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+ $this->assertCount(1, $records);
+
+ $record = $records[0];
+ $this->assertSame('dev-cloud-7', $record->sourceId);
+ $this->assertSame('gw-cloud', $record->hostname);
+ $this->assertSame('UDM-SE', $record->hardwareModel);
+ // Site Manager does not expose serial, so the adapter accepts
+ // null rather than inventing a value.
+ $this->assertNull($record->hardwareSerial);
+ $this->assertSame('aa:bb:cc:dd:ee:ff', $record->primaryMac);
+ $this->assertSame('192.0.2.5', $record->primaryIp);
+ $this->assertSame('4.1.13', $record->osVersion);
+ $this->assertNull($record->lastSeen);
+ }
+
+ public function test_cloud_mode_fetch_sites_hits_v1_sites_and_uses_host_id_as_identifier()
+ {
+ // Refresh Sites in cloud mode walks /v1/sites and stores the
+ // hostId as the dropdown identifier (device-list filter is
+ // host-scoped on Site Manager, not site-scoped). The local
+ // /proxy/network/integration/v1/sites path must not be hit.
+ $instance = SyncAdapterInstance::where('slug', 'unifi')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'url', 'https://api.ui.com');
+ SyncAdapterConfig::put($instance->id, 'api_key', Crypt::encrypt('fake-unifi-api-key'));
+ $adapter = new UnifiAdapter($instance->fresh());
+
+ Http::fake([
+ 'api.ui.com/v1/sites*' => Http::response([
+ 'httpStatusCode' => 200,
+ 'data' => [
+ ['siteId' => 'site-1', 'hostId' => 'host-1', 'meta' => ['name' => 'Default']],
+ ['siteId' => 'site-2', 'hostId' => 'host-2', 'meta' => ['name' => 'Guest']],
+ ],
+ 'nextToken' => '',
+ ]),
+ ]);
+
+ $sites = $adapter->fetchSites();
+
+ $this->assertCount(2, $sites);
+ $this->assertSame(['id' => 'host-1', 'label' => 'Default'], $sites[0]);
+ $this->assertSame(['id' => 'host-2', 'label' => 'Guest'], $sites[1]);
+
+ Http::assertNotSent(function ($request) {
+ return str_contains($request->url(), '/proxy/network/integration/v1/sites');
+ });
+ }
+
+ private function configuredUnifiAdapter(
+ string $siteId = 'default',
+ string $url = 'https://unifi.example.test:8443',
+ ): UnifiAdapter {
$instance = SyncAdapterInstance::where('slug', 'unifi')->firstOrFail();
- SyncAdapterConfig::put($instance->id, 'url', 'https://unifi.example.test:8443');
+ SyncAdapterConfig::put($instance->id, 'url', $url);
SyncAdapterConfig::put($instance->id, 'api_key', Crypt::encrypt('fake-unifi-api-key'));
SyncAdapterConfig::put($instance->id, 'site_id', $siteId);
return new UnifiAdapter($instance->fresh());
}
+ /**
+ * @return array<string, mixed>
+ */
+ private function siteManagerDevice(
+ string $id,
+ string $name = 'device',
+ string $model = 'U6-Pro',
+ ): array {
+ return [
+ 'id' => $id,
+ 'name' => $name,
+ 'model' => $model,
+ 'shortname' => strtoupper(str_replace('-', '', $model)),
+ 'mac' => 'aa:bb:cc:dd:ee:ff',
+ 'ip' => '192.0.2.10',
+ 'version' => '4.1.13',
+ 'status' => 'online',
+ 'isManaged' => true,
+ ];
+ }
+
/**
* @return array<string, mixed>
*/