A free open source IT asset/license management system
Fixed #19694 - add more built-in fields to AxM adapter
snipea702e695bd13
diff --git a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.phpindex 67867ad118..436ebe77ce 100644--- a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php+++ b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerAdapter.php@@ -242,6 +242,17 @@ class AppleBusinessManagerAdapter extends SyncAdapter'abm_applecare_description' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_description'],'abm_applecare_is_canceled' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_is_canceled', 'type' => 'boolean'],'abm_applecare_is_renewable' => ['label_key' => 'admin/settings/sync_adapters.extra_applecare_is_renewable', 'type' => 'boolean'],+ 'abm_device_capacity' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_device_capacity'],+ 'abm_wifi_mac' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_wifi_mac'],+ 'abm_bluetooth_mac' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_bluetooth_mac'],+ 'abm_ethernet_mac' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_ethernet_mac'],+ 'abm_imei' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_imei'],+ 'abm_meid' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_meid'],+ 'abm_eid' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_eid'],+ 'abm_added_to_org' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_added_to_org'],+ 'abm_released_from_org' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_released_from_org'],+ 'abm_org_status' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_org_status'],+ 'abm_activation_lock_enabled' => ['label_key' => 'admin/settings/sync_adapters.abm_extra_activation_lock_enabled', 'type' => 'boolean'],];}@@ -347,6 +358,11 @@ class AppleBusinessManagerAdapter extends SyncAdapter// warranty tracking skip the cost entirely.$enrichWithAppleCare = $this->hasMappedAppleCareFields();+ // Same opt-in gate for Activation Lock. Same N+1 shape as+ // AppleCare (one extra API call per device), so we skip it+ // unless the admin has mapped the extra.+ $enrichWithActivationLock = $this->hasMappedActivationLockField();+// Allowed product families (lower-cased for comparison).// Empty means "all families".$allowedFamilies = $this->allowedProductFamilies();@@ -367,6 +383,9 @@ class AppleBusinessManagerAdapter extends SyncAdapterif ($enrichWithAppleCare) {$record = $this->enrichRecordWithAppleCare($record, $client);}+ if ($enrichWithActivationLock) {+ $record = $this->enrichRecordWithActivationLock($record, $client);+ }if ($pullImages) {$imagesHandled = $this->ensureModelImage($record, $imagesHandled);}@@ -556,6 +575,19 @@ class AppleBusinessManagerAdapter extends SyncAdapterreturn false;}+ /**+ * Gate for the Activation Lock enrichment. True when the admin has+ * routed the single abm_activation_lock_enabled extra to a real+ * target. Same shape as hasMappedAppleCareFields but scoped to one+ * key.+ */+ private function hasMappedActivationLockField(): bool+ {+ $target = $this->mappingFor('abm_activation_lock_enabled');++ return $target !== '' && $target !== 'skip';+ }+/*** Fetch AppleCare coverage for one asset, pick the most relevant* plan, and merge its fields into the record's extras. On empty@@ -612,6 +644,56 @@ class AppleBusinessManagerAdapter extends SyncAdapter);}+ /**+ * Fetch Activation Lock status for one asset and merge into the+ * record's extras. Handy for asset checkin flows because AL has+ * to be cleared before a device can be redeployed to a new user.+ * On empty or failed responses just return the un-enriched record+ * so the sync doesn't stall on a transient AL endpoint issue.+ */+ private function enrichRecordWithActivationLock(HostInventoryRecord $record, AppleBusinessManagerClient $client): HostInventoryRecord+ {+ try {+ $status = $client->deviceActivationLockStatus($record->sourceId);+ } catch (\Throwable $e) {+ \Log::channel('sync-adapters')->warning(sprintf(+ '%s activation lock fetch failed for device %s: %s',+ $this->name(),+ $record->sourceId,+ $e->getMessage(),+ ));++ return $record;+ }++ $enabled = Arr::get($status, 'attributes.activationLockEnabled');+ if (! is_bool($enabled)) {+ return $record;+ }++ $extra = $record->extra;+ $extra['abm_activation_lock_enabled'] = $enabled;++ 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,+ );+ }+/*** Pick the most relevant AppleCare coverage plan for a device.* A device can carry multiple overlapping plans (renewals,@@ -718,7 +800,12 @@ class AppleBusinessManagerAdapter extends SyncAdapter// Fleet-compatible shape instead.hardwareModel: Arr::get($attrs, 'partNumber'),manufacturer: 'Apple',- primaryMac: null,+ // ABM returns three MAC-shaped strings per device. Wi-Fi+ // is the one every enrolled device has, so it fills the+ // normalized primaryMac field. Ethernet and Bluetooth+ // stay in extras for admins who want to route them to+ // custom fields.+ primaryMac: Arr::get($attrs, 'wifiMacAddress'),primaryIp: null,os: null,osVersion: null,@@ -737,6 +824,23 @@ class AppleBusinessManagerAdapter extends SyncAdapter'abm_purchase_source_type' => Arr::get($attrs, 'purchaseSourceType'),'abm_purchase_source_id' => Arr::get($attrs, 'purchaseSourceId'),'abm_mdm_server' => $deviceToServer[$id] ?? null,+ 'abm_device_capacity' => Arr::get($attrs, 'deviceCapacity'),+ 'abm_wifi_mac' => Arr::get($attrs, 'wifiMacAddress'),+ 'abm_bluetooth_mac' => Arr::get($attrs, 'bluetoothMacAddress'),+ 'abm_ethernet_mac' => Arr::get($attrs, 'ethernetMacAddress'),+ // Cellular-only identifiers. Populated for iPhones and+ // cellular iPads, null on Macs / non-cellular devices.+ 'abm_imei' => Arr::get($attrs, 'imei'),+ 'abm_meid' => Arr::get($attrs, 'meid'),+ 'abm_eid' => Arr::get($attrs, 'eid'),+ 'abm_added_to_org' => self::parseOrderDate(Arr::get($attrs, 'addedToOrgDateTime')),+ 'abm_released_from_org' => self::parseOrderDate(Arr::get($attrs, 'releasedFromOrgDateTime')),+ 'abm_org_status' => Arr::get($attrs, 'status'),+ // Populated by enrichRecordWithActivationLock() when+ // the admin has mapped the extra. Kept as a nullable+ // slot so the mapping-target list surfaces the key+ // even before the first sync run fills it in.+ 'abm_activation_lock_enabled' => null,],);}diff --git a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerClient.php b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerClient.phpindex bea5f2de45..7134f4aadb 100644--- a/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerClient.php+++ b/app/SyncAdapters/AppleBusinessManager/AppleBusinessManagerClient.php@@ -96,6 +96,24 @@ class AppleBusinessManagerClientreturn $response['data'] ?? [];}+ /**+ * Fetch Activation Lock status for one device. Apple returns a+ * single Device-shaped object with an attributes.activationLockEnabled+ * boolean. Handy at asset-checkin time since Activation Lock has+ * to be cleared before a device can be redeployed to a new user.+ *+ * @return array<string, mixed>+ */+ public function deviceActivationLockStatus(string $deviceId): array+ {+ $response = $this->request()+ ->get('/v1/orgDevices/'.$deviceId.'/activationLockStatus')+ ->throw()+ ->json();++ return $response['data'] ?? [];+ }+/*** Build a device-id -> MDM server name map by walking every MDM* server's device linkages. Devices unassigned to any MDM serverdiff --git a/database/factories/CustomFieldFactory.php b/database/factories/CustomFieldFactory.phpindex 921404cbfc..f24f964ce4 100644--- a/database/factories/CustomFieldFactory.php+++ b/database/factories/CustomFieldFactory.php@@ -126,6 +126,69 @@ class CustomFieldFactory extends Factory});}+ public function storageCapacity()+ {+ return $this->state(function () {+ return [+ 'name' => 'Storage Capacity',+ 'help_text' => 'On-device storage capacity for this device (e.g. 256GB, 1TB).',+ ];+ });+ }++ public function bluetoothMac()+ {+ return $this->state(function () {+ return [+ 'name' => 'Bluetooth MAC',+ 'format' => 'regex:/^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}$/',+ ];+ });+ }++ public function ethernetMac()+ {+ return $this->state(function () {+ return [+ 'name' => 'Ethernet MAC',+ 'format' => 'regex:/^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}$/',+ ];+ });+ }++ public function meid()+ {+ return $this->state(function () {+ return [+ 'name' => 'MEID',+ 'help_text' => 'Mobile Equipment Identifier for CDMA cellular devices.',+ 'format' => 'regex:/^[0-9A-Fa-f]{14}$/',+ ];+ });+ }++ public function eid()+ {+ return $this->state(function () {+ return [+ 'name' => 'EID',+ 'help_text' => 'Embedded SIM Identifier (eSIM) for cellular devices.',+ 'format' => 'regex:/^[0-9]{32}$/',+ ];+ });+ }++ public function activationLock()+ {+ return $this->state(function () {+ return [+ 'name' => 'Activation Lock Enabled',+ 'help_text' => 'Whether Apple Activation Lock is enabled on this device. Must be cleared before the device can be redeployed to a new user.',+ 'element' => 'checkbox',+ ];+ });+ }+public function testEncrypted(){return $this->state(function () {diff --git a/database/seeders/CustomFieldSeeder.php b/database/seeders/CustomFieldSeeder.phpindex 9e4b14223f..6adf8e2fbf 100644--- a/database/seeders/CustomFieldSeeder.php+++ b/database/seeders/CustomFieldSeeder.php@@ -48,6 +48,18 @@ class CustomFieldSeeder extends SeederCustomField::factory()->count(1)->operatingSystem()->create();CustomField::factory()->count(1)->osVersion()->create();CustomField::factory()->count(1)->lastCheckIn()->create();+ // Extra fields the ABM adapter's device-level extras map to.+ // Same rationale as ipAddress / lastCheckIn above: pre-created+ // so a demo tenant can wire the mapping table for the ABM+ // Wi-Fi/Bluetooth/Ethernet MACs, storage capacity, cellular+ // identifiers, and Activation Lock status without hand-+ // rolling the target fields first.+ CustomField::factory()->count(1)->storageCapacity()->create();+ CustomField::factory()->count(1)->bluetoothMac()->create();+ CustomField::factory()->count(1)->ethernetMac()->create();+ CustomField::factory()->count(1)->meid()->create();+ CustomField::factory()->count(1)->eid()->create();+ CustomField::factory()->count(1)->activationLock()->create();DB::table('custom_field_custom_fieldset')->insert([[@@ -217,6 +229,65 @@ class CustomFieldSeeder extends Seeder'required' => 0,],+ // ABM device-level extras. Storage capacity, Bluetooth MAC,+ // and Activation Lock get attached to both fieldsets since+ // every device (phone or laptop) reports them. Ethernet MAC+ // is computer-only. MEID and EID are cellular-only+ [+ 'custom_field_id' => '17',+ 'custom_fieldset_id' => '1',+ 'order' => 0,+ 'required' => 0,+ ],+ [+ 'custom_field_id' => '17',+ 'custom_fieldset_id' => '2',+ 'order' => 0,+ 'required' => 0,+ ],+ [+ 'custom_field_id' => '18',+ 'custom_fieldset_id' => '1',+ 'order' => 0,+ 'required' => 0,+ ],+ [+ 'custom_field_id' => '18',+ 'custom_fieldset_id' => '2',+ 'order' => 0,+ 'required' => 0,+ ],+ [+ 'custom_field_id' => '19',+ 'custom_fieldset_id' => '2',+ 'order' => 0,+ 'required' => 0,+ ],+ [+ 'custom_field_id' => '20',+ 'custom_fieldset_id' => '1',+ 'order' => 0,+ 'required' => 0,+ ],+ [+ 'custom_field_id' => '21',+ 'custom_fieldset_id' => '1',+ 'order' => 0,+ 'required' => 0,+ ],+ [+ 'custom_field_id' => '22',+ 'custom_fieldset_id' => '1',+ 'order' => 0,+ 'required' => 0,+ ],+ [+ 'custom_field_id' => '22',+ 'custom_fieldset_id' => '2',+ 'order' => 0,+ 'required' => 0,+ ],+]);}}diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.phpindex 135f08ab7a..2ac473489a 100644--- a/resources/lang/en-US/admin/settings/sync_adapters.php+++ b/resources/lang/en-US/admin/settings/sync_adapters.php@@ -387,4 +387,15 @@ return ['abm_extra_purchase_source_type' => 'AxM Purchase Source Type','abm_extra_purchase_source_id' => 'AxM Purchase Source ID','abm_extra_mdm_server' => 'AxM MDM Server',+ 'abm_extra_device_capacity' => 'AxM Storage Capacity',+ 'abm_extra_wifi_mac' => 'AxM Wi-Fi MAC',+ 'abm_extra_bluetooth_mac' => 'AxM Bluetooth MAC',+ 'abm_extra_ethernet_mac' => 'AxM Ethernet MAC',+ 'abm_extra_imei' => 'AxM IMEI',+ 'abm_extra_meid' => 'AxM MEID',+ 'abm_extra_eid' => 'AxM EID',+ 'abm_extra_added_to_org' => 'AxM Added to Org',+ 'abm_extra_released_from_org' => 'AxM Released from Org',+ 'abm_extra_org_status' => 'AxM Org Status',+ 'abm_extra_activation_lock_enabled' => 'AxM Activation Lock Enabled',];diff --git a/tests/Feature/SyncAdapters/AppleBusinessManager/ActivationLockEnrichmentTest.php b/tests/Feature/SyncAdapters/AppleBusinessManager/ActivationLockEnrichmentTest.phpnew file mode 100644index 0000000000..b30573ac15--- /dev/null+++ b/tests/Feature/SyncAdapters/AppleBusinessManager/ActivationLockEnrichmentTest.php@@ -0,0 +1,178 @@+<?php++namespace Tests\Feature\SyncAdapters\AppleBusinessManager;++use App\Models\CustomField;+use App\Models\Statuslabel;+use App\Models\SyncAdapterConfig;+use App\Models\SyncAdapterInstance;+use App\SyncAdapters\AppleBusinessManager\AppleBusinessManagerAdapter;+use Illuminate\Support\Facades\Crypt;+use Illuminate\Support\Facades\Http;+use Tests\TestCase;+++class ActivationLockEnrichmentTest extends TestCase+{+ private string $privateKeyPem;++ protected function setUp(): void+ {+ parent::setUp();+ Statuslabel::factory()->rtd()->create();++ $key = openssl_pkey_new([+ 'private_key_type' => OPENSSL_KEYTYPE_EC,+ 'curve_name' => 'prime256v1',+ ]);+ $pem = '';+ openssl_pkey_export($key, $pem);+ $this->privateKeyPem = $pem;+ }++ public function test_pull_enriches_with_activation_lock_when_field_is_mapped()+ {+ $customField = CustomField::factory()->create(['element' => 'checkbox', 'name' => 'Activation Lock']);+ $adapter = $this->configuredAdapter();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'mapping.abm_activation_lock_enabled', 'custom:'.$customField->id);++ Http::fake([+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),+ 'api-business.apple.com/v1/orgDevices/abm-guid-a/activationLockStatus' => Http::response([+ 'data' => [+ 'id' => 'abm-guid-a',+ 'type' => 'orgDevice',+ 'attributes' => ['activationLockEnabled' => true],+ ],+ ]),+ 'api-business.apple.com/v1/orgDevices*' => Http::response([+ 'data' => [$this->minimalAbmDevice('abm-guid-a')],+ ]),+ ]);++ $record = iterator_to_array($adapter->pull())[0];+ $this->assertTrue($record->extra['abm_activation_lock_enabled']);+ }++ public function test_pull_does_not_fetch_activation_lock_when_field_is_unmapped()+ {+ // Sync should skip the per-device activationLockStatus fetch+ // when nothing is mapped, so admins that don't care about AL+ // don't pay the N+1 cost.+ $adapter = $this->configuredAdapter();++ Http::fake([+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),+ 'api-business.apple.com/v1/orgDevices*' => Http::response([+ 'data' => [$this->minimalAbmDevice('abm-guid-a')],+ ]),+ ]);++ $record = iterator_to_array($adapter->pull())[0];+ $this->assertNull($record->extra['abm_activation_lock_enabled']);++ Http::assertNotSent(function ($request) {+ return str_contains($request->url(), '/activationLockStatus');+ });+ }++ public function test_pull_survives_activation_lock_endpoint_failure()+ {+ // Transient AL endpoint issues should not stall the sync run.+ // Record still comes through with a null AL extra.+ $customField = CustomField::factory()->create(['element' => 'checkbox', 'name' => 'AL']);+ $adapter = $this->configuredAdapter();+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'mapping.abm_activation_lock_enabled', 'custom:'.$customField->id);++ Http::fake([+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),+ 'api-business.apple.com/v1/orgDevices/abm-guid-a/activationLockStatus' => Http::response(['error' => 'boom'], 500),+ 'api-business.apple.com/v1/orgDevices*' => Http::response([+ 'data' => [$this->minimalAbmDevice('abm-guid-a')],+ ]),+ ]);++ $record = iterator_to_array($adapter->pull())[0];+ $this->assertNull($record->extra['abm_activation_lock_enabled']);+ }++ public function test_normalize_populates_device_capacity_wifi_mac_and_cellular_identifiers()+ {+ // Tier 1 coverage: fields that already come back on+ // /v1/orgDevices land in the record's extras without any+ // additional API call. Wi-Fi MAC also fills the normalized+ // primaryMac slot since it's the one every enrolled device+ // reports.+ $adapter = $this->configuredAdapter();++ Http::fake([+ 'account.apple.com/*' => Http::response(['access_token' => 'stub-bearer']),+ 'api-business.apple.com/v1/mdmServers' => Http::response(['data' => []]),+ 'api-business.apple.com/v1/orgDevices*' => Http::response([+ 'data' => [[+ 'id' => 'iphone-1',+ 'attributes' => [+ 'serialNumber' => 'SN-iphone-1',+ 'partNumber' => 'MHDX3LL/A',+ 'productFamily' => 'iPhone',+ 'deviceCapacity' => '256GB',+ 'wifiMacAddress' => 'AA:BB:CC:00:11:22',+ 'bluetoothMacAddress' => 'AA:BB:CC:00:11:23',+ 'ethernetMacAddress' => null,+ 'imei' => '351234567890123',+ 'meid' => '35123456789012',+ 'eid' => '89012345678901234567890123456789',+ 'addedToOrgDateTime' => '2024-11-01T14:22:00Z',+ 'releasedFromOrgDateTime' => null,+ 'status' => 'ACTIVATED',+ ],+ ]],+ ]),+ ]);++ $record = iterator_to_array($adapter->pull())[0];++ $this->assertSame('AA:BB:CC:00:11:22', $record->primaryMac);+ $this->assertSame('256GB', $record->extra['abm_device_capacity']);+ $this->assertSame('AA:BB:CC:00:11:22', $record->extra['abm_wifi_mac']);+ $this->assertSame('AA:BB:CC:00:11:23', $record->extra['abm_bluetooth_mac']);+ $this->assertNull($record->extra['abm_ethernet_mac']);+ $this->assertSame('351234567890123', $record->extra['abm_imei']);+ $this->assertSame('35123456789012', $record->extra['abm_meid']);+ $this->assertSame('89012345678901234567890123456789', $record->extra['abm_eid']);+ $this->assertSame('2024-11-01', $record->extra['abm_added_to_org']);+ $this->assertNull($record->extra['abm_released_from_org']);+ $this->assertSame('ACTIVATED', $record->extra['abm_org_status']);+ }++ private function configuredAdapter(): AppleBusinessManagerAdapter+ {+ $instance = SyncAdapterInstance::where('slug', 'abm')->firstOrFail();+ SyncAdapterConfig::put($instance->id, 'mode', 'business');+ SyncAdapterConfig::put($instance->id, 'client_id', 'stub-client-id');+ SyncAdapterConfig::put($instance->id, 'key_id', 'stub-key-id');+ SyncAdapterConfig::put($instance->id, 'private_key', Crypt::encrypt($this->privateKeyPem));++ return new AppleBusinessManagerAdapter($instance->fresh());+ }++ /**+ * @return array<string, mixed>+ */+ private function minimalAbmDevice(string $id): array+ {+ return [+ 'id' => $id,+ 'attributes' => [+ 'serialNumber' => 'SN-'.$id,+ 'partNumber' => 'MK1E3LL/A',+ 'productFamily' => 'Mac',+ ],+ ];+ }+}