A free open source IT asset/license management system
Added mobile device option to Jamf Pro
snipe770dd5a01f0a
diff --git a/app/SyncAdapters/Jamf/JamfAdapter.php b/app/SyncAdapters/Jamf/JamfAdapter.phpindex bc8ecdf7b0..3f016361f5 100644--- a/app/SyncAdapters/Jamf/JamfAdapter.php+++ b/app/SyncAdapters/Jamf/JamfAdapter.php@@ -55,6 +55,13 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter'secret' => true,'help' => trans('admin/settings/sync_adapters.jamf_client_secret_help'),],+ [+ 'key' => 'include_mobile_devices',+ 'label' => trans('admin/settings/sync_adapters.jamf_label_include_mobile_devices'),+ 'type' => 'checkbox',+ 'required' => false,+ 'help' => trans('admin/settings/sync_adapters.jamf_include_mobile_devices_help'),+ ],];}@@ -64,6 +71,12 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter'jamf_udid' => ['label_key' => 'admin/settings/sync_adapters.extra_udid'],'jamf_last_enrolled' => ['label_key' => 'admin/settings/sync_adapters.extra_last_enrolled'],'jamf_model_identifier' => ['label_key' => 'admin/settings/sync_adapters.extra_model_identifier'],+ // Mobile-only fields. Blank on computer records so admins+ // can still map them without worrying about overwriting a+ // computer's custom field with an empty string.+ 'jamf_mobile_device_type' => ['label_key' => 'admin/settings/sync_adapters.jamf_extra_mobile_device_type'],+ 'jamf_mobile_managed' => ['label_key' => 'admin/settings/sync_adapters.jamf_extra_mobile_managed', 'type' => 'boolean'],+ 'jamf_mobile_supervised' => ['label_key' => 'admin/settings/sync_adapters.jamf_extra_mobile_supervised', 'type' => 'boolean'],];}@@ -103,7 +116,30 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter);foreach ($client->computers() as $computer) {- yield $this->normalize($computer);+ yield $this->normalizeComputer($computer);+ }++ if ($this->shouldPullMobileDevices()) {+ foreach ($client->mobileDevices() as $device) {+ yield $this->normalizeMobileDevice($device);+ }+ }+ }++ /**+ * Opt-in toggle for syncing iOS / iPadOS / tvOS devices alongside+ * computers. Off by default so adding the mobile pull doesn't+ * surprise existing installs on their next scheduled run. Reads via+ * credential() because the base class's config storage treats+ * every schema entry (secret or not) through the same get/set+ * path.+ */+ private function shouldPullMobileDevices(): bool+ {+ try {+ return $this->credential('include_mobile_devices') === '1';+ } catch (\Throwable) {+ return false;}}@@ -113,9 +149,15 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter* asset_external_sources on. Fields come from the GENERAL, HARDWARE, and* OPERATING_SYSTEM sections (the client only requests those).*+ * Computer sourceIds stay bare numeric to preserve back-compat with+ * every existing asset_external_sources.external_id row written by+ * this adapter before mobile support landed. The mobile path uses a+ * `mobile:` prefix instead to keep the two Jamf namespaces from+ * colliding (Jamf's computer id 42 and mobile id 42 are unrelated).+ ** @param array<string, mixed> $computer*/- private function normalize(array $computer): HostInventoryRecord+ private function normalizeComputer(array $computer): HostInventoryRecord{return new HostInventoryRecord(sourceKey: $this->name(),@@ -141,6 +183,47 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter);}+ /**+ * Convert a /api/v2/mobile-devices list entry into the normalized+ * record shape. Mobile Jamf payloads are flatter than computer+ * ones: everything except assigned-user info lives at the top+ * level, so no section dot-paths. Manufacturer isn't carried+ * either (Jamf Pro's mobile fleet is Apple-only in practice), so+ * we hard-code 'Apple' to match what the computer path emits for+ * macs and let model-dedup land both on the same manufacturer.+ *+ * @param array<string, mixed> $device+ */+ private function normalizeMobileDevice(array $device): HostInventoryRecord+ {+ $sourceId = 'mobile:'.(string) Arr::get($device, 'id');++ return new HostInventoryRecord(+ sourceKey: $this->name(),+ sourceId: $sourceId,+ hostname: Arr::get($device, 'name'),+ hardwareSerial: Arr::get($device, 'serialNumber'),+ hardwareModel: Arr::get($device, 'model'),+ manufacturer: 'Apple',+ primaryMac: Arr::get($device, 'wifiMacAddress'),+ primaryIp: Arr::get($device, 'ipAddress'),+ os: Arr::get($device, 'osType'),+ osVersion: Arr::get($device, 'osVersion'),+ lastSeen: $this->parseTimestamp(Arr::get($device, 'lastInventoryUpdateTimestamp')),+ assetTag: Arr::get($device, 'assetTag'),+ assignedUserEmail: Arr::get($device, 'location.emailAddress'),+ assignedUserName: Arr::get($device, 'location.username'),+ vendorGroupId: Arr::has($device, 'site.id') ? (string) Arr::get($device, 'site.id') : null,+ extra: [+ 'jamf_udid' => Arr::get($device, 'udid'),+ 'jamf_model_identifier' => Arr::get($device, 'modelIdentifier'),+ 'jamf_mobile_device_type' => Arr::get($device, 'deviceType'),+ 'jamf_mobile_managed' => Arr::get($device, 'managed'),+ 'jamf_mobile_supervised' => Arr::get($device, 'supervised'),+ ],+ );+ }+private function parseTimestamp(mixed $value): ?Carbon{if ($value === null || $value === '') {@@ -216,6 +299,15 @@ class JamfAdapter extends SyncAdapter implements PushableAdapter*/protected function dispatchPush(\App\Models\AssetExternalSource $externalSource, array $payload): void{+ // Mobile Jamf devices are pull-only in this adapter. The push+ // path only runs against /api/v1/computers-inventory-detail, so+ // short-circuit on the `mobile:` prefix the mobile normalizer+ // writes. Snipe-IT-authoritative fields on a mobile asset stay+ // local to Snipe-IT.+ if (str_starts_with($externalSource->external_id, 'mobile:')) {+ return;+ }+$client = new JamfClient(baseUrl: $this->url(),clientId: $this->credential('client_id'),diff --git a/app/SyncAdapters/Jamf/JamfClient.php b/app/SyncAdapters/Jamf/JamfClient.phpindex 90e6b0486d..4a88be6423 100644--- a/app/SyncAdapters/Jamf/JamfClient.php+++ b/app/SyncAdapters/Jamf/JamfClient.php@@ -58,11 +58,11 @@ class JamfClient'page-size' => $pageSize,]);foreach ($sections as $section) {- $query .= '§ion=' . urlencode($section);+ $query .= '§ion='.urlencode($section);}$response = $this->request()- ->get('/api/v1/computers-inventory?' . $query)+ ->get('/api/v1/computers-inventory?'.$query)->throw()->json();@@ -81,6 +81,45 @@ class JamfClient} while (! $done);}+ /**+ * Iterate every mobile device (iOS, iPadOS, tvOS) in the Jamf+ * tenant, one page at a time. Hits /api/v2/mobile-devices which,+ * unlike /api/v1/computers-inventory, already returns most of the+ * fields we need at the top level without a per-device detail+ * fetch. Separate pager from computers() because the pagination+ * terminator shape matches but the URL + fields differ enough that+ * sharing the loop would obscure both.+ *+ * @return iterable<array<string, mixed>>+ */+ public function mobileDevices(int $pageSize = 100): iterable+ {+ $page = 0;++ do {+ $query = http_build_query([+ 'page' => $page,+ 'page-size' => $pageSize,+ ]);++ $response = $this->request()+ ->get('/api/v2/mobile-devices?'.$query)+ ->throw()+ ->json();++ $results = $response['results'] ?? [];+ foreach ($results as $device) {+ yield $device;+ }++ $total = $response['totalCount'] ?? null;+ $seenSoFar = ($page + 1) * $pageSize;+ $done = count($results) < $pageSize+ || ($total !== null && $seenSoFar >= $total);+ $page++;+ } while (! $done);+ }+/*** List every Site in the Jamf Pro tenant. Used by the adapter's* fetchGroups() so admins can map Sites to Snipe-IT companies.@@ -141,7 +180,7 @@ class JamfClient$response = Http::asForm()->withOptions(['allow_redirects' => false])->timeout(30)- ->post(rtrim($this->baseUrl, '/') . '/api/oauth/token', [+ ->post(rtrim($this->baseUrl, '/').'/api/oauth/token', ['grant_type' => 'client_credentials','client_id' => $this->clientId,'client_secret' => $this->clientSecret,diff --git a/app/SyncAdapters/JamfSchool/JamfSchoolAdapter.php b/app/SyncAdapters/JamfSchool/JamfSchoolAdapter.phpindex e0cbafd692..47ae569604 100644--- a/app/SyncAdapters/JamfSchool/JamfSchoolAdapter.php+++ b/app/SyncAdapters/JamfSchool/JamfSchoolAdapter.php@@ -59,6 +59,7 @@ class JamfSchoolAdapter extends SyncAdapter'jamf_school_model_identifier' => ['label_key' => 'admin/settings/sync_adapters.extra_model_identifier'],'jamf_school_supervised' => ['label_key' => 'admin/settings/sync_adapters.extra_supervised', 'type' => 'boolean'],'jamf_school_location_id' => ['label_key' => 'admin/settings/sync_adapters.extra_location_id'],+ 'jamf_school_device_type' => ['label_key' => 'admin/settings/sync_adapters.extra_device_type'],];}@@ -129,6 +130,7 @@ class JamfSchoolAdapter extends SyncAdapter'jamf_school_model_identifier' => Arr::get($device, 'model.identifier'),'jamf_school_supervised' => Arr::get($device, 'isSupervised'),'jamf_school_location_id' => Arr::get($device, 'locationId'),+ 'jamf_school_device_type' => Arr::get($device, 'deviceType'),],);}diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex 5b1efb8e20..883b325710 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -152,8 +152,13 @@ return ['fleet_token_help' => 'Generate under My Account -> Get API token in your Fleet instance. Needs an admin or observer role with read access to hosts (and to teams if you use group-to-company mapping).','kandji_token_help' => 'Generate under Settings -> Access -> API Token in your Iru (Kandji) tenant. Needs the Device list read permission (and Blueprint list if you use group-to-company mapping).','kandji_base_url_help' => 'Your Iru (Kandji) API URL is listed on the Access page of your Iru (Kandji) admin console under the API Token section. It is not the same as the URL you use to sign into the admin console. Save the URL that ends with <code>.api.kandji.io</code>, not the dashboard URL.',- 'jamf_client_id_help' => 'Create an API Role granting Read on Computers (and Read on Sites if you use group-to-company mapping), then an API Client that uses that role, under Settings -> System -> API Roles and Clients in Jamf Pro. Copy the Client ID from the API Client detail page. The token lifetime is configurable per API Client in Jamf. Snipe-IT caches the token for the full sync run and re-exchanges automatically before it expires, so any reasonable lifetime works.',+ 'jamf_client_id_help' => 'Create an API Role granting Read on Computers (and Read on Sites if you use group-to-company mapping, Read on Mobile Devices if you enable the mobile toggle below), then an API Client that uses that role, under Settings -> System -> API Roles and Clients in Jamf Pro. Copy the Client ID from the API Client detail page. The token lifetime is configurable per API Client in Jamf. Snipe-IT caches the token for the full sync run and re-exchanges automatically before it expires, so any reasonable lifetime works.','jamf_client_secret_help' => 'Paired with the Client ID above. Jamf Pro shows the secret once at API Client creation time.',+ 'jamf_label_include_mobile_devices' => 'Include mobile devices',+ 'jamf_include_mobile_devices_help' => 'When enabled, Snipe-IT also pulls iOS / iPadOS / tvOS devices from Jamf Pro alongside computers. The API Role you created above must additionally grant Read on Mobile Devices for this to work.',+ 'jamf_extra_mobile_device_type' => 'Jamf mobile device type',+ 'jamf_extra_mobile_managed' => 'Jamf mobile managed',+ 'jamf_extra_mobile_supervised' => 'Jamf mobile supervised','jamf_school_network_id_help' => 'Find your Network ID under Organization -> Settings -> API in the Jamf School admin console.','jamf_school_api_key_help' => 'Generate under Organization -> Settings -> API in Jamf School. Needs read access to Devices (and Locations if you use group-to-company mapping).','jumpcloud_token_help' => 'Copy from your JumpCloud admin user\'s profile page (top-right menu -> My API Key). API keys inherit the admin user\'s permissions, so use an account with read access to Systems.',diff --git a/tests/Feature/SyncAdapters/Jamf/JamfAdapterTest.php b/tests/Feature/SyncAdapters/Jamf/JamfAdapterTest.phpindex 5643339de9..d3f2db13a6 100644--- a/tests/Feature/SyncAdapters/Jamf/JamfAdapterTest.php+++ b/tests/Feature/SyncAdapters/Jamf/JamfAdapterTest.php@@ -55,7 +55,7 @@ class JamfAdapterTest extends TestCase// no hardware section (and no model id). The client hand-builds// the query string to force the API shape Jamf actually reads.Http::assertSent(function ($request) {- if (!str_contains($request->url(), '/api/v1/computers-inventory')) {+ if (! str_contains($request->url(), '/api/v1/computers-inventory')) {return false;}$url = $request->url();@@ -64,8 +64,8 @@ class JamfAdapterTest extends TestCase&& str_contains($url, 'section=HARDWARE')&& str_contains($url, 'section=OPERATING_SYSTEM')&& str_contains($url, 'section=USER_AND_LOCATION')- && !str_contains($url, 'section%5B')- && !str_contains($url, 'section[');+ && ! str_contains($url, 'section%5B')+ && ! str_contains($url, 'section[');});}@@ -108,12 +108,132 @@ class JamfAdapterTest extends TestCase$this->assertNotNull($record->lastSeen);}- private function configuredJamfAdapter(): JamfAdapter+ public function test_mobile_devices_pulled_when_toggle_is_on()+ {+ $adapter = $this->configuredJamfAdapter(includeMobile: true);++ Http::fake([+ '*/api/oauth/token' => $this->jamfTokenResponse(),+ '*/api/v1/computers-inventory*' => Http::response([+ 'totalCount' => 1,+ 'results' => [$this->jamfComputer(id: 42, name: 'lab-mac-01', model: 'iMac')],+ ]),+ '*/api/v2/mobile-devices*' => Http::response([+ 'totalCount' => 2,+ 'results' => [+ $this->jamfMobileDevice(id: 10, name: 'kiosk-ipad-01', model: 'iPad Pro', serialNumber: 'DMPXYZ', osType: 'iOS', osVersion: '17.4'),+ $this->jamfMobileDevice(id: 11, name: 'conf-apple-tv', model: 'Apple TV 4K', serialNumber: 'C07ABC', osType: 'tvOS', osVersion: '17.1', deviceType: 'tvos'),+ ],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ // Three distinct external_sources rows: one bare-numeric for the+ // computer, two `mobile:`-prefixed for the devices. Prefix on+ // mobile keeps the two Jamf id namespaces from colliding on+ // the (source, external_id) uniqueness constraint.+ $this->assertDatabaseCount('asset_external_sources', 3);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'jamf', 'external_id' => '42']);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'jamf', 'external_id' => 'mobile:10']);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'jamf', 'external_id' => 'mobile:11']);++ $this->assertDatabaseHas('assets', ['name' => 'kiosk-ipad-01']);+ $this->assertDatabaseHas('assets', ['name' => 'conf-apple-tv']);+ }++ public function test_mobile_devices_skipped_when_toggle_is_off()+ {+ $adapter = $this->configuredJamfAdapter();++ Http::fake([+ '*/api/oauth/token' => $this->jamfTokenResponse(),+ '*/api/v1/computers-inventory*' => Http::response([+ 'totalCount' => 1,+ 'results' => [$this->jamfComputer(id: 42, name: 'lab-mac-01', model: 'iMac')],+ ]),+ '*/api/v2/mobile-devices*' => Http::response([+ 'totalCount' => 1,+ 'results' => [$this->jamfMobileDevice(id: 10, name: 'should-not-sync')],+ ]),+ ]);++ foreach ($adapter->pull() as $record) {+ SyncAdapter::syncFromRecord($record);+ }++ $this->assertDatabaseCount('asset_external_sources', 1);+ $this->assertDatabaseHas('asset_external_sources', ['source' => 'jamf', 'external_id' => '42']);+ $this->assertDatabaseMissing('assets', ['name' => 'should-not-sync']);++ // Toggle off means we don't bill Jamf for a mobile pull at all.+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/api/v2/mobile-devices'));+ }++ public function test_mobile_record_carries_expected_fields()+ {+ $adapter = $this->configuredJamfAdapter(includeMobile: true);++ Http::fake([+ '*/api/oauth/token' => $this->jamfTokenResponse(),+ '*/api/v1/computers-inventory*' => Http::response([+ 'totalCount' => 0,+ 'results' => [],+ ]),+ '*/api/v2/mobile-devices*' => Http::response([+ 'totalCount' => 1,+ 'results' => [+ $this->jamfMobileDevice(+ id: 55,+ name: 'ipad-55',+ model: 'iPad Air',+ serialNumber: 'C02ABC',+ osType: 'iOS',+ osVersion: '17.5',+ wifiMacAddress: 'aa:bb:cc:dd:ee:ff',+ ipAddress: '10.0.0.55',+ lastInventoryUpdateTimestamp: '2026-02-15T10:00:00.000Z',+ locationUsername: 'jdoe',+ locationEmail: '[email protected]',+ deviceType: 'ios',+ managed: true,+ supervised: true,+ ),+ ],+ ]),+ ]);++ $records = iterator_to_array($adapter->pull());+ $this->assertCount(1, $records);++ $record = $records[0];+ $this->assertSame('jamf', $record->sourceKey);+ $this->assertSame('mobile:55', $record->sourceId);+ $this->assertSame('ipad-55', $record->hostname);+ $this->assertSame('iPad Air', $record->hardwareModel);+ $this->assertSame('C02ABC', $record->hardwareSerial);+ $this->assertSame('Apple', $record->manufacturer);+ $this->assertSame('aa:bb:cc:dd:ee:ff', $record->primaryMac);+ $this->assertSame('10.0.0.55', $record->primaryIp);+ $this->assertSame('iOS', $record->os);+ $this->assertSame('17.5', $record->osVersion);+ $this->assertSame('jdoe', $record->assignedUserName);+ $this->assertSame('[email protected]', $record->assignedUserEmail);+ $this->assertNotNull($record->lastSeen);+ $this->assertSame('ios', $record->extra['jamf_mobile_device_type']);+ $this->assertTrue($record->extra['jamf_mobile_managed']);+ $this->assertTrue($record->extra['jamf_mobile_supervised']);+ }++ private function configuredJamfAdapter(bool $includeMobile = false): JamfAdapter{$instance = SyncAdapterInstance::where('slug', 'jamf')->firstOrFail();SyncAdapterConfig::put($instance->id, 'url', 'https://example.jamfcloud.com');SyncAdapterConfig::put($instance->id, 'client_id', Crypt::encrypt('fake-jamf-client-id'));SyncAdapterConfig::put($instance->id, 'client_secret', Crypt::encrypt('fake-jamf-client-secret'));+ SyncAdapterConfig::put($instance->id, 'include_mobile_devices', $includeMobile ? '1' : '0');return new JamfAdapter($instance->fresh());}@@ -134,6 +254,52 @@ class JamfAdapterTest extends TestCase]);}+ /**+ * Shape of a /api/v2/mobile-devices list entry Jamf Pro returns.+ * Mobile responses are flatter than computer ones: no section+ * nesting, just a top-level field set per device.+ *+ * @return array<string, mixed>+ */+ private function jamfMobileDevice(+ int $id,+ string $name = 'ipad',+ string $model = 'iPad',+ ?string $serialNumber = null,+ ?string $osType = 'iOS',+ ?string $osVersion = null,+ ?string $wifiMacAddress = null,+ ?string $ipAddress = null,+ ?string $lastInventoryUpdateTimestamp = null,+ ?string $locationUsername = null,+ ?string $locationEmail = null,+ string $deviceType = 'ios',+ bool $managed = true,+ bool $supervised = false,+ ): array {+ return [+ 'id' => (string) $id,+ 'name' => $name,+ 'udid' => 'jamf-mobile-udid-'.$id,+ 'serialNumber' => $serialNumber,+ 'assetTag' => null,+ 'model' => $model,+ 'modelIdentifier' => 'iPad'.$id,+ 'deviceType' => $deviceType,+ 'osType' => $osType,+ 'osVersion' => $osVersion,+ 'wifiMacAddress' => $wifiMacAddress,+ 'ipAddress' => $ipAddress,+ 'lastInventoryUpdateTimestamp' => $lastInventoryUpdateTimestamp,+ 'managed' => $managed,+ 'supervised' => $supervised,+ 'location' => [+ 'username' => $locationUsername,+ 'emailAddress' => $locationEmail,+ ],+ ];+ }+/*** @return array<string, mixed>*/