Skip to content

A free open source IT asset/license management system

Fixed #19745 - added additional known fields from Intune API

snipe92fb8b773cf9
diff --git a/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php b/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php
index 2659bacb4d..f95f2460f7 100644
--- a/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php
+++ b/app/SyncAdapters/CustomHttp/CustomHttpAdapter.php
@@ -1017,42 +1017,6 @@ class CustomHttpAdapter extends SyncAdapter implements PushableAdapter
);
}
- /**
- * Walk a dot-separated path into a nested array structure. Empty
- * path returns the input unchanged, so an admin using the whole
- * response body as the records array can leave records_path
- * blank. Numeric segments (like "data.0.serial") index into
- * sequential arrays too, so an API that returns a list at the
- * root plus a wrapper object further down is representable.
- */
- private static function dotPathGet(mixed $data, string $path): mixed
- {
- if ($path === '') {
- return $data;
- }
-
- $current = $data;
- foreach (explode('.', $path) as $segment) {
- if (! is_array($current)) {
- return null;
- }
- if (array_key_exists($segment, $current)) {
- $current = $current[$segment];
-
- continue;
- }
- if (ctype_digit($segment) && array_key_exists((int) $segment, $current)) {
- $current = $current[(int) $segment];
-
- continue;
- }
-
- return null;
- }
-
- return $current;
- }
-
private static function stringOrNull(mixed $value): ?string
{
if ($value === null) {
diff --git a/app/SyncAdapters/Intune/IntuneAdapter.php b/app/SyncAdapters/Intune/IntuneAdapter.php
index 9e2410b956..cbc0fd152c 100644
--- a/app/SyncAdapters/Intune/IntuneAdapter.php
+++ b/app/SyncAdapters/Intune/IntuneAdapter.php
@@ -72,6 +72,73 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
];
}
+ /**
+ * Preset extras this adapter extracts from well-known Graph
+ * managedDevice fields. Each key maps to an entry built in
+ * normalize() from the corresponding Graph attribute. Admin-
+ * defined extras (via the Custom Extras widget) merge on top via
+ * the base class.
+ *
+ * Only fields that Graph's v1.0 LIST endpoint actually populates
+ * are included here. Properties like `ethernetMacAddress`,
+ * `physicalMemoryInBytes`, and the `hardwareInformation` TPM
+ * fields return null on LIST (Microsoft requires per-device
+ * $select to get real values) - the opt-in per-device
+ * enrichment setting below fetches those separately.
+ */
+ public function presetExtraFields(): array
+ {
+ return [
+ 'intune_compliance_state' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_compliance_state'],
+ 'intune_enrolled_at' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_enrolled_at'],
+ 'intune_management_agent' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_management_agent'],
+ 'intune_ownership' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_ownership'],
+ 'intune_wifi_mac' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_wifi_mac'],
+ 'intune_total_storage_bytes' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_total_storage_bytes'],
+ 'intune_free_storage_bytes' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_free_storage_bytes'],
+ 'intune_is_encrypted' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_is_encrypted', 'type' => 'boolean'],
+ 'intune_jail_broken' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_jail_broken'],
+ 'intune_is_supervised' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_is_supervised', 'type' => 'boolean'],
+ 'intune_azure_ad_device_id' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_azure_ad_device_id'],
+ 'intune_azure_ad_registered' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_azure_ad_registered', 'type' => 'boolean'],
+ 'intune_imei' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_imei'],
+ 'intune_meid' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_meid'],
+ 'intune_exchange_access_state' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_exchange_access_state'],
+ // Additional v1.0 LIST-populated fields.
+ 'intune_user_display_name' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_user_display_name'],
+ 'intune_managed_device_name' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_managed_device_name'],
+ 'intune_partner_reported_threat_state' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_partner_reported_threat_state'],
+ 'intune_exchange_access_state_reason' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_exchange_access_state_reason'],
+ 'intune_device_category' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_device_category'],
+ 'intune_phone_number' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_phone_number'],
+ 'intune_subscriber_carrier' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_subscriber_carrier'],
+ 'intune_android_security_patch_level' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_android_security_patch_level'],
+ 'intune_enrollment_profile_name' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_enrollment_profile_name'],
+ 'intune_device_enrollment_type' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_device_enrollment_type'],
+ 'intune_management_certificate_expiration' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_management_certificate_expiration'],
+ 'intune_compliance_grace_period_expiration' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_compliance_grace_period_expiration'],
+ 'intune_device_registration_state' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_device_registration_state'],
+ // Per-device enrichment fields. Populated only when the
+ // "Fetch per-device details" opt-in is on - Graph's LIST
+ // endpoint returns null for these regardless of $select.
+ 'intune_ethernet_mac' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_ethernet_mac'],
+ 'intune_physical_memory_bytes' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_physical_memory_bytes'],
+ ];
+ }
+
+ public function supportsAdminDefinedExtras(): bool
+ {
+ return true;
+ }
+
+ public function perDeviceDetailsToggle(): ?array
+ {
+ return [
+ 'label' => trans('admin/settings/sync_adapters.intune_fetch_per_device_details_label'),
+ 'help' => trans('admin/settings/sync_adapters.intune_fetch_per_device_details_help'),
+ ];
+ }
+
public function pull(): iterable
{
$graphBaseUrl = $this->url();
@@ -84,11 +151,54 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
clientSecret: $this->credential('client_secret'),
);
+ $fetchPerDeviceDetails = $this->fetchesPerDeviceDetails();
+
foreach ($client->managedDevices() as $device) {
+ if ($fetchPerDeviceDetails) {
+ $this->fillPerDeviceEnrichment($client, $device);
+ }
yield $this->normalize($device);
}
}
+ /**
+ * Per-device enrichment pass for fields Graph's LIST endpoint
+ * returns null for. Mutates $device in-place with the fetched
+ * ethernetMacAddress + physicalMemoryInBytes so normalize()
+ * picks them up through the usual Arr::get path. One extra
+ * Graph call per device - costly on large fleets, which is why
+ * it's opt-in.
+ *
+ * @param array<string, mixed> &$device
+ */
+ private function fillPerDeviceEnrichment(IntuneClient $client, array &$device): void
+ {
+ $id = Arr::get($device, 'id');
+ if (! is_string($id) || $id === '') {
+ return;
+ }
+
+ $detail = $client->managedDeviceDetail($id, ['ethernetMacAddress', 'physicalMemoryInBytes']);
+ if ($detail === null) {
+ return;
+ }
+
+ $device['ethernetMacAddress'] = Arr::get($detail, 'ethernetMacAddress');
+ $device['physicalMemoryInBytes'] = Arr::get($detail, 'physicalMemoryInBytes');
+ }
+
+ /**
+ * Opt-in: fire a per-device Graph GET for each pulled device to
+ * backfill ethernet MAC + physical memory. Microsoft's LIST
+ * endpoint returns null for these, so admins who need them
+ * accept the per-device cost. Default off - cheap pull wins
+ * for large fleets by default.
+ */
+ public function fetchesPerDeviceDetails(): bool
+ {
+ return \App\Models\SyncAdapterConfig::get($this->instance->id, 'fetch_per_device_details') === '1';
+ }
+
/**
* Derive the OAuth login host from the Graph host so sovereign
* clouds (US Gov, China) work off a single URL config. Falls
@@ -116,12 +226,63 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
* shape. Graph's stable id is `id` (a GUID), and we key
* asset_external_sources on it. Ethernet MAC is preferred over
* WiFi because it's more likely to be a hardware-inventory MAC
- * that survives OS reinstall.
+ * that survives OS reinstall. Empty-string MAC fields fall through
+ * - Graph often returns "" rather than omitting the key for
+ * devices without that interface (e.g. laptops without built-in
+ * Ethernet), so a plain `??` would mistake empty for present.
*
* @param array<string, mixed> $device
*/
private function normalize(array $device): HostInventoryRecord
{
+ $extra = [
+ 'intune_compliance_state' => Arr::get($device, 'complianceState'),
+ 'intune_enrolled_at' => Arr::get($device, 'enrolledDateTime'),
+ 'intune_management_agent' => Arr::get($device, 'managementAgent'),
+ 'intune_ownership' => Arr::get($device, 'managedDeviceOwnerType'),
+ // Wi-Fi MAC lands here. Ethernet MAC + physical memory
+ // return null on LIST per Microsoft's docs - populated
+ // by the per-device enrichment pass instead if the admin
+ // opted in. See fillPerDeviceEnrichment().
+ 'intune_wifi_mac' => self::blankToNull(Arr::get($device, 'wiFiMacAddress')),
+ // Backfilled by fillPerDeviceEnrichment() when the opt-in
+ // setting is on. Null otherwise - Graph's LIST never
+ // populates these fields.
+ 'intune_ethernet_mac' => self::blankToNull(Arr::get($device, 'ethernetMacAddress')),
+ 'intune_physical_memory_bytes' => Arr::get($device, 'physicalMemoryInBytes'),
+ // Hardware inventory. Graph reports storage in bytes -
+ // admins who want GB can run a custom-field formula.
+ 'intune_total_storage_bytes' => Arr::get($device, 'totalStorageSpaceInBytes'),
+ 'intune_free_storage_bytes' => Arr::get($device, 'freeStorageSpaceInBytes'),
+ 'intune_is_encrypted' => Arr::get($device, 'isEncrypted'),
+ 'intune_jail_broken' => Arr::get($device, 'jailBroken'),
+ 'intune_is_supervised' => Arr::get($device, 'isSupervised'),
+ // Azure AD identity. Useful for admins who cross-reference
+ // Snipe-IT assets with Entra ID devices or conditional
+ // access policies.
+ 'intune_azure_ad_device_id' => Arr::get($device, 'azureADDeviceId'),
+ 'intune_azure_ad_registered' => Arr::get($device, 'azureADRegistered'),
+ // Cellular identifiers for iOS / Android devices.
+ 'intune_imei' => Arr::get($device, 'imei'),
+ 'intune_meid' => Arr::get($device, 'meid'),
+ 'intune_exchange_access_state' => Arr::get($device, 'exchangeAccessState'),
+ // Additional v1.0 LIST-populated fields.
+ 'intune_user_display_name' => Arr::get($device, 'userDisplayName'),
+ 'intune_managed_device_name' => Arr::get($device, 'managedDeviceName'),
+ 'intune_partner_reported_threat_state' => Arr::get($device, 'partnerReportedThreatState'),
+ 'intune_exchange_access_state_reason' => Arr::get($device, 'exchangeAccessStateReason'),
+ 'intune_device_category' => Arr::get($device, 'deviceCategoryDisplayName'),
+ 'intune_phone_number' => Arr::get($device, 'phoneNumber'),
+ 'intune_subscriber_carrier' => Arr::get($device, 'subscriberCarrier'),
+ 'intune_android_security_patch_level' => Arr::get($device, 'androidSecurityPatchLevel'),
+ 'intune_enrollment_profile_name' => Arr::get($device, 'enrollmentProfileName'),
+ 'intune_device_enrollment_type' => Arr::get($device, 'deviceEnrollmentType'),
+ 'intune_management_certificate_expiration' => Arr::get($device, 'managementCertificateExpirationDate'),
+ 'intune_compliance_grace_period_expiration' => Arr::get($device, 'complianceGracePeriodExpirationDateTime'),
+ 'intune_device_registration_state' => Arr::get($device, 'deviceRegistrationState'),
+ ];
+ $extra = $this->applyAdminExtras($extra, $device);
+
return new HostInventoryRecord(
sourceKey: $this->name(),
sourceId: (string) Arr::get($device, 'id'),
@@ -129,23 +290,33 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
hardwareSerial: Arr::get($device, 'serialNumber'),
hardwareModel: Arr::get($device, 'model'),
manufacturer: Arr::get($device, 'manufacturer'),
- primaryMac: Arr::get($device, 'ethernetMacAddress')
- ?? Arr::get($device, 'wiFiMacAddress'),
+ primaryMac: self::blankToNull(Arr::get($device, 'ethernetMacAddress'))
+ ?? self::blankToNull(Arr::get($device, 'wiFiMacAddress')),
primaryIp: null,
os: Arr::get($device, 'operatingSystem'),
osVersion: Arr::get($device, 'osVersion'),
lastSeen: $this->parseTimestamp(Arr::get($device, 'lastSyncDateTime')),
assignedUserEmail: Arr::get($device, 'userPrincipalName')
?? Arr::get($device, 'emailAddress'),
- extra: [
- 'intune_compliance_state' => Arr::get($device, 'complianceState'),
- 'intune_enrolled_at' => Arr::get($device, 'enrolledDateTime'),
- 'intune_management_agent' => Arr::get($device, 'managementAgent'),
- 'intune_ownership' => Arr::get($device, 'managedDeviceOwnerType'),
- ],
+ extra: $extra,
);
}
+ /**
+ * Graph often returns "" rather than null for interface MACs when
+ * the device doesn't have that interface. Fold both shapes to
+ * null so downstream null-guards (and the primaryMac Ethernet-
+ * then-WiFi fallback) work uniformly.
+ */
+ private static function blankToNull(mixed $value): ?string
+ {
+ if (! is_string($value) || $value === '') {
+ return null;
+ }
+
+ return $value;
+ }
+
private function parseTimestamp(mixed $value): ?Carbon
{
if ($value === null || $value === '') {
diff --git a/app/SyncAdapters/Intune/IntuneClient.php b/app/SyncAdapters/Intune/IntuneClient.php
index bddde11ac5..57e9669448 100644
--- a/app/SyncAdapters/Intune/IntuneClient.php
+++ b/app/SyncAdapters/Intune/IntuneClient.php
@@ -91,6 +91,32 @@ class IntuneClient
return $parts['scheme'].'://'.$parts['host'].(isset($parts['port']) ? ':'.$parts['port'] : '');
}
+ /**
+ * Per-device GET against Graph's managedDevice endpoint with a
+ * caller-chosen $select set. Used for properties the LIST
+ * endpoint always returns null for (ethernetMacAddress,
+ * physicalMemoryInBytes, etc. - Microsoft docs explicitly flag
+ * these as "requires per-device GET"). Returns the attributes
+ * array on success. Fails soft to null on 4xx/5xx so one bad
+ * device doesn't abort the enclosing enrichment pass.
+ *
+ * @param array<int, string> $select
+ * @return array<string, mixed>|null
+ */
+ public function managedDeviceDetail(string $deviceId, array $select): ?array
+ {
+ $url = rtrim($this->graphBaseUrl, '/').'/v1.0/deviceManagement/managedDevices/'.rawurlencode($deviceId);
+
+ try {
+ return $this->request()
+ ->get($url, ['$select' => implode(',', $select)])
+ ->throw()
+ ->json();
+ } catch (\Throwable) {
+ return null;
+ }
+ }
+
/**
* Fetch (or reuse) a bearer token via OAuth 2.0 client-credentials
* against the tenant-scoped token endpoint. Token is cached on
diff --git a/app/SyncAdapters/SyncAdapter.php b/app/SyncAdapters/SyncAdapter.php
index ccbafe91d5..53958ccd21 100644
--- a/app/SyncAdapters/SyncAdapter.php
+++ b/app/SyncAdapters/SyncAdapter.php
@@ -247,10 +247,205 @@ abstract class SyncAdapter
* @return array<string, string|array{label?: string, label_key?: string, type?: string, admin_defined?: bool}>
*/
public function extraFields(): array
+ {
+ return $this->presetExtraFields() + $this->adminDefinedExtraFields();
+ }
+
+ /**
+ * Vendor-specific extras the adapter extracts in its own normalize()
+ * from well-known API fields. Default empty - adapters that emit
+ * extras override this with their preset keys (e.g. Intune's
+ * compliance_state, Jamf's building, Kandji's blueprint).
+ *
+ * This replaced the old extraFields() hook when admin-defined extras
+ * were added. extraFields() now composes presets with admin extras
+ * so Blade / mapping-targets consumers see the union.
+ *
+ * @return array<string, string|array{label?: string, label_key?: string, type?: string, admin_defined?: bool}>
+ */
+ public function presetExtraFields(): array
{
return [];
}
+ /**
+ * Admin-defined extras surfaced as mapping targets. Every adapter
+ * gets a Custom Extras widget below its mapping table where admins
+ * can pair a Snipe-IT destination (custom:X or native:X) with a
+ * vendor-record dot-path. extraFields() includes these alongside
+ * the adapter's own presetExtraFields() so the mapping picker
+ * shows both groups.
+ *
+ * @return array<string, array{label: string, admin_defined: true}>
+ */
+ public function adminDefinedExtraFields(): array
+ {
+ $out = [];
+ foreach (array_keys($this->adminDefinedExtras()) as $key) {
+ $out[$key] = ['label' => $key, 'admin_defined' => true];
+ }
+
+ return $out;
+ }
+
+ /**
+ * Admin-configured extras rows for this instance: destination key
+ * (`custom:X` / `native:X`) mapped to a dot-path into the vendor
+ * record. Shared with CustomHttpAdapter's existing Vendor Response
+ * Paths widget via the same `field_paths` config key. Entries whose
+ * destination is a HostInventoryRecord slot (hostname / serial /
+ * etc.) are filtered out here - those are CustomHttp-specific and
+ * driven by its own normalize path, not the admin-extras overlay.
+ *
+ * @return array<string, string>
+ */
+ public function adminDefinedExtras(): array
+ {
+ $raw = SyncAdapterConfig::get($this->instance->id, 'field_paths');
+ if (! is_string($raw) || trim($raw) === '') {
+ return [];
+ }
+
+ $decoded = json_decode($raw, true);
+ if (! is_array($decoded)) {
+ return [];
+ }
+
+ $out = [];
+ foreach ($decoded as $key => $path) {
+ if (! is_string($key) || ! is_string($path) || $path === '') {
+ continue;
+ }
+ if (! str_starts_with($key, 'custom:') && ! str_starts_with($key, 'native:')) {
+ continue;
+ }
+ $out[$key] = $path;
+ }
+
+ return $out;
+ }
+
+ /**
+ * Overlay admin-defined extras onto an adapter's preset extras.
+ * Called from each adapter's normalize() after assembling the
+ * preset extras, right before yielding the HostInventoryRecord.
+ * Walks every configured dot-path against the raw vendor record
+ * and populates the corresponding extras key.
+ *
+ * @param array<string, mixed> $extra
+ * @param array<string, mixed> $vendorRecord
+ * @return array<string, mixed>
+ */
+ protected function applyAdminExtras(array $extra, array $vendorRecord): array
+ {
+ foreach ($this->adminDefinedExtras() as $key => $path) {
+ $extra[$key] = self::dotPathGet($vendorRecord, $path);
+ }
+
+ return $extra;
+ }
+
+ /**
+ * Which destination options to expose in this adapter's Custom
+ * Extras widget. Named adapters only let admins add new custom:X
+ * / native:X mappings so they can't accidentally remap an identity
+ * field (serial, hostname, etc.) that the adapter's normalize()
+ * owns. CustomHttp overrides this to include HostInventoryRecord
+ * slots because for that adapter, admins ARE the ones defining
+ * where every field comes from.
+ *
+ * @return array<string, string>
+ */
+ public function customExtrasDestinationOptions(): array
+ {
+ $options = [
+ 'native:notes' => trans('admin/settings/sync_adapters.target_native_notes'),
+ 'native:purchase_date' => MappingTargets::labelFor('native:purchase_date'),
+ 'native:order_number' => MappingTargets::labelFor('native:order_number'),
+ ];
+
+ foreach (\App\Models\CustomField::whereIn('element', ['text', 'textarea', 'markdown-textarea', 'checkbox'])->orderBy('name')->get() as $cf) {
+ $options['custom:'.$cf->id] = trans('admin/settings/sync_adapters.target_custom_prefix').': '.$cf->name;
+ }
+
+ return $options;
+ }
+
+ /**
+ * CustomHttp drives its field_paths widget via its own schema
+ * entry (type: field_map) because that widget predates admin-
+ * extras and also exposes HostInventoryRecord slots. Named
+ * adapters opt into the shared Custom Extras widget by leaving
+ * this at its default of false.
+ */
+ public function rendersFieldPathsInSchema(): bool
+ {
+ return false;
+ }
+
+ /**
+ * Whether the shared "Custom Extras" fieldset renders on this
+ * adapter's settings page. Default off so adapters that haven't
+ * been wired up (no applyAdminExtras() call in their normalize())
+ * don't advertise a widget that then does nothing at sync time.
+ * Adapters opt in once their normalize() is calling
+ * applyAdminExtras() by overriding this to true.
+ */
+ public function supportsAdminDefinedExtras(): bool
+ {
+ return false;
+ }
+
+ /**
+ * Hook for an adapter-specific "fetch extra details per device"
+ * toggle in the shared settings UI. When this returns a label +
+ * help string, the base saveConfig persists the posted
+ * `{slug}_fetch_per_device_details` boolean and the shared Blade
+ * renders a checkbox row. Adapters that don't need the toggle
+ * (every adapter whose LIST endpoint already returns everything)
+ * leave this at the default null.
+ *
+ * @return array{label: string, help: string}|null
+ */
+ public function perDeviceDetailsToggle(): ?array
+ {
+ return null;
+ }
+
+ /**
+ * Walk a dot-separated path into a nested array structure. Empty
+ * path returns the input unchanged. Numeric segments (like
+ * "data.0.serial") index into sequential arrays. Returns null for
+ * any miss so downstream null-guards do the right thing.
+ */
+ public static function dotPathGet(mixed $data, string $path): mixed
+ {
+ if ($path === '') {
+ return $data;
+ }
+
+ $current = $data;
+ foreach (explode('.', $path) as $segment) {
+ if (! is_array($current)) {
+ return null;
+ }
+ if (array_key_exists($segment, $current)) {
+ $current = $current[$segment];
+
+ continue;
+ }
+ if (ctype_digit($segment) && array_key_exists((int) $segment, $current)) {
+ $current = $current[(int) $segment];
+
+ continue;
+ }
+
+ return null;
+ }
+
+ return $current;
+ }
+
/**
* Section titles + help copy for the settings schema. Adapters
* that group their credential fields via a `section` key on
@@ -373,6 +568,19 @@ abstract class SyncAdapter
$slug.'_create_snipeit_assets_on_pull' => ['nullable', 'boolean'],
];
+ // Admin-defined extras widget. Posts as an associative array
+ // of {destination: vendor_path}. Only rendered for adapters
+ // that opt in via supportsAdminDefinedExtras(), but the rule
+ // itself is cheap and harmless when absent.
+ if ($this->supportsAdminDefinedExtras()) {
+ $rules[$slug.'_field_paths'] = ['nullable', 'array'];
+ $rules[$slug.'_field_paths.*'] = ['nullable', 'string', 'max:191'];
+ }
+
+ if ($this->perDeviceDetailsToggle() !== null) {
+ $rules[$slug.'_fetch_per_device_details'] = ['nullable', 'boolean'];
+ }
+
if ($this->usesConfigurableUrl()) {
$rules[$slug.'_url'] = ['required', new ExternalUrl];
}
@@ -442,6 +650,10 @@ abstract class SyncAdapter
$this->persistGroupMappings($request, $slug);
}
+ if ($this->supportsAdminDefinedExtras()) {
+ $this->persistAdminDefinedExtras($request, $slug);
+ }
+
$validFields = $this->validMappingFields();
$this->persistFieldMappings($request, $slug, $validFields);
$this->persistFieldDirections($request, $slug, $validFields);
@@ -449,6 +661,40 @@ abstract class SyncAdapter
$this->afterSaveConfig();
}
+ /**
+ * Persist the Custom Extras widget's rows. Posted shape is an
+ * associative array mapping destination (`custom:X` or `native:X`)
+ * to a vendor-record dot-path. Stored as a JSON blob in
+ * `field_paths` and also written as self-routing mapping entries
+ * (mapping.<key> = <key>) so the framework's extras loop writes
+ * each extracted value to its target at sync time.
+ */
+ private function persistAdminDefinedExtras(Request $request, string $slug): void
+ {
+ $posted = (array) $request->input($slug.'_field_paths', []);
+ $cleaned = [];
+ foreach ($posted as $key => $path) {
+ if (! is_string($key) || ! is_string($path)) {
+ continue;
+ }
+ $path = trim($path);
+ if ($path === '') {
+ continue;
+ }
+ if (! str_starts_with($key, 'custom:') && ! str_starts_with($key, 'native:')) {
+ continue;
+ }
+ $cleaned[$key] = $path;
+ SyncAdapterConfig::put($this->instance->id, 'mapping.'.$key, $key);
+ }
+
+ SyncAdapterConfig::put(
+ $this->instance->id,
+ 'field_paths',
+ $cleaned === [] ? '' : json_encode($cleaned, JSON_UNESCAPED_SLASHES),
+ );
+ }
+
/**
* URL is always overwritten from the form. Blank means "no URL
* configured yet" which the isEnabled() gate then treats as
@@ -644,6 +890,18 @@ abstract class SyncAdapter
$request->boolean($slug.'_create_snipeit_assets_on_pull', true) ? '1' : '0',
);
+ // Per-device enrichment opt-in. Only persisted for adapters
+ // that declare a perDeviceDetailsToggle(). Default off so
+ // large-fleet installs don't eat an extra Graph call per
+ // device unless the admin explicitly opts in.
+ if ($this->perDeviceDetailsToggle() !== null) {
+ SyncAdapterConfig::put(
+ $this->instance->id,
+ 'fetch_per_device_details',
+ $request->boolean($slug.'_fetch_per_device_details') ? '1' : '0',
+ );
+ }
+
// Push dry-run flag. When on, adapters log the push payload
// instead of sending it, so admins can verify mapping +
// direction config against real assets without any vendor
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index 4f9865c7f3..5b1efb8e20 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -167,6 +167,38 @@ return [
'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).',
+ 'intune_extra_compliance_state' => 'Intune Compliance State',
+ 'intune_extra_enrolled_at' => 'Intune Enrolled At',
+ 'intune_extra_management_agent' => 'Intune Management Agent',
+ 'intune_extra_ownership' => 'Intune Ownership',
+ 'intune_extra_wifi_mac' => 'Intune Wi-Fi MAC',
+ 'intune_extra_ethernet_mac' => 'Intune Ethernet MAC',
+ 'intune_extra_total_storage_bytes' => 'Intune Total Storage (bytes)',
+ 'intune_extra_free_storage_bytes' => 'Intune Free Storage (bytes)',
+ 'intune_extra_physical_memory_bytes' => 'Intune Physical Memory (bytes)',
+ 'intune_extra_is_encrypted' => 'Intune Encrypted',
+ 'intune_extra_jail_broken' => 'Intune Jailbroken',
+ 'intune_extra_is_supervised' => 'Intune Supervised',
+ 'intune_extra_azure_ad_device_id' => 'Intune Azure AD Device ID',
+ 'intune_extra_azure_ad_registered' => 'Intune Azure AD Registered',
+ 'intune_extra_imei' => 'Intune IMEI',
+ 'intune_extra_meid' => 'Intune MEID',
+ 'intune_extra_exchange_access_state' => 'Intune Exchange Access State',
+ 'intune_extra_user_display_name' => 'Intune User Display Name',
+ 'intune_extra_managed_device_name' => 'Intune Managed Device Name',
+ 'intune_extra_partner_reported_threat_state' => 'Intune Partner Reported Threat State',
+ 'intune_extra_exchange_access_state_reason' => 'Intune Exchange Access State Reason',
+ 'intune_extra_device_category' => 'Intune Device Category',
+ 'intune_extra_phone_number' => 'Intune Phone Number',
+ 'intune_extra_subscriber_carrier' => 'Intune Subscriber Carrier',
+ 'intune_extra_android_security_patch_level' => 'Intune Android Security Patch Level',
+ 'intune_extra_enrollment_profile_name' => 'Intune Enrollment Profile Name',
+ 'intune_extra_device_enrollment_type' => 'Intune Device Enrollment Type',
+ 'intune_extra_management_certificate_expiration' => 'Intune Management Certificate Expiration',
+ 'intune_extra_compliance_grace_period_expiration' => 'Intune Compliance Grace Period Expiration',
+ 'intune_extra_device_registration_state' => 'Intune Device Registration State',
+ 'intune_fetch_per_device_details_label' => 'Fetch per-device details on every sync (Ethernet MAC + Physical Memory)',
+ 'intune_fetch_per_device_details_help' => 'Microsoft Graph does not return Ethernet MAC Address or Physical Memory on the list endpoint we paginate through. Turning this on fires one extra Graph call per managed device at pull time to backfill those two fields. Default off because the extra call per device adds up on large fleets - leave off unless you need those fields populated.',
'meraki_sm_api_key_help' => 'Generate under your Meraki Dashboard profile -> My Profile -> API access. Needs read access to the target organization (and Systems Manager network access for the devices endpoint).',
'meraki_sm_organization_id_help' => 'Copy from Organization -> Settings -> Dashboard API access in the Meraki Dashboard, or from any org URL segment after /o/.',
'workspace_one_tenant_code_help' => 'Find under Groups & Settings -> All Settings -> System -> Advanced -> API -> REST API in your Workspace ONE console.',
@@ -257,6 +289,8 @@ return [
// Extras / mapping section wrappers
'extra_fields_section_title' => ':type-specific fields',
'extra_fields_section_intro' => 'Additional vendor fields that don\'t have a corresponding Snipe-IT field. Add a row per vendor field you want to sync and pick wheich field it maps to. Boolean values can be mapped to checkbox-type custom fields, text fields can be mapped to text-type custom fields.',
+ 'custom_extras_section_title' => 'Custom Extras',
+ 'custom_extras_section_intro' => 'Pick any custom field or native column, and point it at a dot-path into the vendor record. Useful for vendor fields the adapter doesn\'t preset. Each row you add here shows up as a mapping target in the table above once saved.',
// Mapping-picker widget (extras section repeater)
'mapping_picker_col_field' => 'Vendor Field',
diff --git a/resources/views/blade/sync-adapter/form.blade.php b/resources/views/blade/sync-adapter/form.blade.php
index f89aaeafb9..cd34543192 100644
--- a/resources/views/blade/sync-adapter/form.blade.php
+++ b/resources/views/blade/sync-adapter/form.blade.php
@@ -292,6 +292,21 @@
:help_text="trans('admin/settings/sync_adapters.create_snipeit_assets_on_pull_help')"
:disabled="$locked"
/>
+
+ {{-- Adapter-specific "fetch per-device details" opt-in. Lets
+ admins pay the extra per-device cost for fields the
+ vendor's LIST endpoint doesn't populate (Intune's
+ ethernet MAC + physical memory). --}}
+ @php $perDeviceDetailsToggle = $adapter->perDeviceDetailsToggle(); @endphp
+ @if ($perDeviceDetailsToggle !== null)
+ <x-form.checkbox-row
+ :name="$slug . '_fetch_per_device_details'"
+ :checked="method_exists($adapter, 'fetchesPerDeviceDetails') && $adapter->fetchesPerDeviceDetails()"
+ :label="$perDeviceDetailsToggle['label']"
+ :help_text="$perDeviceDetailsToggle['help']"
+ :disabled="$locked"
+ />
+ @endif
</fieldset>
{{-- Push dry-run only shows for adapters that actually support
@@ -491,6 +506,30 @@
</fieldset>
@endif
+ {{-- Admin-defined custom extras. Each row pairs a Snipe-IT
+ destination (custom:X / native:X) with a vendor-record
+ dot-path the adapter extracts at pull time. Opt-in per
+ adapter via supportsAdminDefinedExtras(). Rows show up as
+ targets in the mapping picker above once saved. --}}
+ @if ($adapter->supportsAdminDefinedExtras())
+ @php
+ $cxName = $slug.'_field_paths';
+ $cxStored = $adapter->adminDefinedExtras();
+ $cxStored = old($cxName, is_array($cxStored) ? $cxStored : []);
+ $cxStored = is_array($cxStored) ? $cxStored : [];
+ @endphp
+ <fieldset>
+ <x-form.legend icon="tip" help_text="{{ trans('admin/settings/sync_adapters.custom_extras_section_intro') }}">
+ {{ trans('admin/settings/sync_adapters.custom_extras_section_title') }}
+ </x-form.legend>
+ <x-input.field-map
+ :name="$cxName"
+ :options="$adapter->customExtrasDestinationOptions()"
+ :stored="$cxStored"
+ />
+ </fieldset>
+ @endif
+
{{-- Composed notes fieldset. Renders a multi-field notes blob
from Snipe-IT (asset_tag + status + assigned user + custom
fields, etc.) into a single vendor field. Blank template
diff --git a/tests/Feature/SyncAdapters/Intune/IntuneAdminExtrasTest.php b/tests/Feature/SyncAdapters/Intune/IntuneAdminExtrasTest.php
new file mode 100644
index 0000000000..94f814ad23
--- /dev/null
+++ b/tests/Feature/SyncAdapters/Intune/IntuneAdminExtrasTest.php
@@ -0,0 +1,261 @@
+<?php
+
+namespace Tests\Feature\SyncAdapters\Intune;
+
+use App\Models\CustomField;
+use App\Models\Statuslabel;
+use App\Models\SyncAdapterConfig;
+use App\Models\SyncAdapterInstance;
+use App\SyncAdapters\Intune\IntuneAdapter;
+use App\SyncAdapters\SyncAdapter;
+use Illuminate\Support\Facades\Crypt;
+use Illuminate\Support\Facades\Http;
+use Tests\TestCase;
+
+/**
+ * Issue #19745: Intune admins want to map arbitrary Graph fields
+ * (both MACs, storage, TPM, encryption, etc.) to Snipe-IT custom
+ * fields. Coverage splits into three parts:
+ *
+ * 1. Preset extras: fields the adapter extracts by default from
+ * the Graph managedDevice payload.
+ * 2. Admin-defined extras: the Custom Extras widget lets admins
+ * point at any dot-path in the vendor record.
+ * 3. Mapping-targets surface: both preset and admin keys appear
+ * in the mapping picker.
+ */
+class IntuneAdminExtrasTest extends TestCase
+{
+ protected function setUp(): void
+ {
+ parent::setUp();
+ Statuslabel::factory()->rtd()->create();
+ }
+
+ public function test_preset_extras_populate_from_list_only_graph_fields()
+ {
+ // These fields are documented LIST-populated on v1.0.
+ // Ethernet MAC and physical memory are LIST-null per Microsoft
+ // docs - covered separately by the per-device enrichment test.
+ $adapter = $this->configuredAdapter();
+
+ Http::fake([
+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([
+ 'value' => [[
+ 'id' => 'guid-1',
+ 'deviceName' => 'host-one',
+ 'serialNumber' => 'SN-ONE',
+ 'wiFiMacAddress' => '01:23:45:67:89:AB',
+ 'totalStorageSpaceInBytes' => 494000000000,
+ 'freeStorageSpaceInBytes' => 353000000000,
+ 'isEncrypted' => true,
+ 'jailBroken' => 'Unknown',
+ 'isSupervised' => false,
+ 'azureADDeviceId' => 'azure-guid-1',
+ 'azureADRegistered' => true,
+ 'imei' => '353912345678901',
+ 'meid' => '35123456789012',
+ 'exchangeAccessState' => 'Allowed',
+ 'userDisplayName' => 'Alice Example',
+ 'managedDeviceName' => 'alice_windows_a1b2',
+ 'partnerReportedThreatState' => 'secured',
+ 'exchangeAccessStateReason' => 'none',
+ 'deviceCategoryDisplayName' => 'Engineering',
+ 'phoneNumber' => '+15551234567',
+ 'subscriberCarrier' => 'Verizon',
+ 'androidSecurityPatchLevel' => '2024-11-01',
+ 'enrollmentProfileName' => 'Autopilot - Engineering',
+ 'deviceEnrollmentType' => 'windowsAutoEnrollment',
+ 'managementCertificateExpirationDate' => '2026-12-31T23:59:59Z',
+ 'complianceGracePeriodExpirationDateTime' => '2026-10-15T00:00:00Z',
+ 'deviceRegistrationState' => 'registered',
+ ]],
+ ]),
+ ]);
+
+ $record = iterator_to_array($adapter->pull())[0];
+
+ $this->assertSame('01:23:45:67:89:AB', $record->extra['intune_wifi_mac']);
+ $this->assertSame(494000000000, $record->extra['intune_total_storage_bytes']);
+ $this->assertSame(353000000000, $record->extra['intune_free_storage_bytes']);
+ $this->assertTrue($record->extra['intune_is_encrypted']);
+ $this->assertSame('Unknown', $record->extra['intune_jail_broken']);
+ $this->assertFalse($record->extra['intune_is_supervised']);
+ $this->assertSame('azure-guid-1', $record->extra['intune_azure_ad_device_id']);
+ $this->assertTrue($record->extra['intune_azure_ad_registered']);
+ $this->assertSame('353912345678901', $record->extra['intune_imei']);
+ $this->assertSame('35123456789012', $record->extra['intune_meid']);
+ $this->assertSame('Allowed', $record->extra['intune_exchange_access_state']);
+ $this->assertSame('Alice Example', $record->extra['intune_user_display_name']);
+ $this->assertSame('alice_windows_a1b2', $record->extra['intune_managed_device_name']);
+ $this->assertSame('secured', $record->extra['intune_partner_reported_threat_state']);
+ $this->assertSame('Engineering', $record->extra['intune_device_category']);
+ $this->assertSame('Verizon', $record->extra['intune_subscriber_carrier']);
+ $this->assertSame('windowsAutoEnrollment', $record->extra['intune_device_enrollment_type']);
+ $this->assertSame('registered', $record->extra['intune_device_registration_state']);
+ }
+
+ public function test_ethernet_mac_and_physical_memory_null_when_enrichment_opt_in_is_off()
+ {
+ // Default state. Microsoft's LIST endpoint returns null for
+ // these fields even if they're present on the device.
+ $adapter = $this->configuredAdapter();
+
+ Http::fake([
+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([
+ 'value' => [[
+ 'id' => 'guid-no-enrich',
+ 'deviceName' => 'host-no-enrich',
+ 'serialNumber' => 'SN-NO-ENRICH',
+ 'wiFiMacAddress' => '11:22:33:44:55:66',
+ ]],
+ ]),
+ ]);
+
+ $record = iterator_to_array($adapter->pull())[0];
+
+ $this->assertNull($record->extra['intune_ethernet_mac']);
+ $this->assertNull($record->extra['intune_physical_memory_bytes']);
+ }
+
+ public function test_per_device_enrichment_backfills_ethernet_mac_and_physical_memory()
+ {
+ // When the opt-in is on, the adapter fires one GET per device
+ // against /managedDevices/{id}?$select=ethernetMacAddress,physicalMemoryInBytes
+ // and merges the response into the extras.
+ $adapter = $this->configuredAdapter();
+ $instance = SyncAdapterInstance::where('slug', 'intune')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'fetch_per_device_details', '1');
+
+ // Specific URL fakes must come before broader ones - Http::fake
+ // first-match semantics would otherwise catch the per-device
+ // GET with the LIST response.
+ Http::fake([
+ '*/v1.0/deviceManagement/managedDevices/guid-enrich*' => Http::response([
+ 'ethernetMacAddress' => 'DE:AD:BE:EF:00:01',
+ 'physicalMemoryInBytes' => 17179869184,
+ ]),
+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([
+ 'value' => [[
+ 'id' => 'guid-enrich',
+ 'deviceName' => 'host-enrich',
+ 'serialNumber' => 'SN-ENRICH',
+ ]],
+ ]),
+ ]);
+
+ $record = iterator_to_array($adapter->pull())[0];
+
+ $this->assertSame('DE:AD:BE:EF:00:01', $record->extra['intune_ethernet_mac']);
+ $this->assertSame(17179869184, $record->extra['intune_physical_memory_bytes']);
+ }
+
+ public function test_admin_defined_extras_overlay_on_vendor_record()
+ {
+ // Admin configures a Custom Extras row pointing at a Graph
+ // field the adapter doesn't preset (processorArchitecture),
+ // mapped to a Snipe-IT custom field.
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'CPU arch']);
+ $adapter = $this->configuredAdapter();
+ $instance = SyncAdapterInstance::where('slug', 'intune')->firstOrFail();
+
+ SyncAdapterConfig::put($instance->id, 'field_paths', json_encode([
+ 'custom:'.$customField->id => 'processorArchitecture',
+ ]));
+ SyncAdapterConfig::put($instance->id, 'mapping.custom:'.$customField->id, 'custom:'.$customField->id);
+
+ Http::fake([
+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([
+ 'value' => [[
+ 'id' => 'guid-cpu',
+ 'deviceName' => 'host-cpu',
+ 'serialNumber' => 'SN-CPU',
+ 'processorArchitecture' => 'arm64',
+ ]],
+ ]),
+ ]);
+
+ $record = iterator_to_array($adapter->pull())[0];
+
+ $this->assertSame('arm64', $record->extra['custom:'.$customField->id]);
+ }
+
+ public function test_admin_defined_extras_support_dot_path_into_nested_vendor_fields()
+ {
+ // Deeper Graph fields (e.g. hardwareInformation.deviceGuardLocalSystemAuthorityCredentialGuardState)
+ // are reachable via dot-path. Verify the walker handles nesting.
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'Device Guard State']);
+ $adapter = $this->configuredAdapter();
+ $instance = SyncAdapterInstance::where('slug', 'intune')->firstOrFail();
+
+ SyncAdapterConfig::put($instance->id, 'field_paths', json_encode([
+ 'custom:'.$customField->id => 'hardwareInformation.deviceGuardState',
+ ]));
+ SyncAdapterConfig::put($instance->id, 'mapping.custom:'.$customField->id, 'custom:'.$customField->id);
+
+ Http::fake([
+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([
+ 'value' => [[
+ 'id' => 'guid-dg',
+ 'deviceName' => 'host-dg',
+ 'serialNumber' => 'SN-DG',
+ 'hardwareInformation' => ['deviceGuardState' => 'Running'],
+ ]],
+ ]),
+ ]);
+
+ $record = iterator_to_array($adapter->pull())[0];
+
+ $this->assertSame('Running', $record->extra['custom:'.$customField->id]);
+ }
+
+ public function test_admin_defined_extras_surface_in_mapping_targets_picker()
+ {
+ $customField = CustomField::factory()->create(['element' => 'text', 'name' => 'CPU arch']);
+ $adapter = $this->configuredAdapter();
+ $instance = SyncAdapterInstance::where('slug', 'intune')->firstOrFail();
+
+ SyncAdapterConfig::put($instance->id, 'field_paths', json_encode([
+ 'custom:'.$customField->id => 'processorArchitecture',
+ ]));
+
+ $extraFields = $adapter->extraFields();
+
+ $this->assertArrayHasKey('custom:'.$customField->id, $extraFields);
+ $this->assertTrue($extraFields['custom:'.$customField->id]['admin_defined']);
+ $this->assertArrayHasKey('intune_wifi_mac', $extraFields);
+ $this->assertArrayHasKey('intune_imei', $extraFields);
+ }
+
+ public function test_adapter_opts_into_custom_extras_widget()
+ {
+ $adapter = $this->configuredAdapter();
+
+ $this->assertTrue($adapter->supportsAdminDefinedExtras());
+ }
+
+ public function test_dot_path_get_walks_arrays_strings_and_numeric_indices()
+ {
+ $this->assertSame('top', SyncAdapter::dotPathGet(['a' => 'top'], 'a'));
+ $this->assertSame('nested', SyncAdapter::dotPathGet(['a' => ['b' => 'nested']], 'a.b'));
+ $this->assertSame('item', SyncAdapter::dotPathGet(['a' => [['b' => 'item']]], 'a.0.b'));
+ $this->assertNull(SyncAdapter::dotPathGet(['a' => 'top'], 'a.b'));
+ $this->assertNull(SyncAdapter::dotPathGet(['a' => 'top'], 'missing'));
+ }
+
+ private function configuredAdapter(): IntuneAdapter
+ {
+ $instance = SyncAdapterInstance::where('slug', 'intune')->firstOrFail();
+ SyncAdapterConfig::put($instance->id, 'url', 'https://graph.microsoft.com');
+ SyncAdapterConfig::put($instance->id, 'tenant_id', 'stub-tenant');
+ SyncAdapterConfig::put($instance->id, 'client_id', 'stub-client');
+ SyncAdapterConfig::put($instance->id, 'client_secret', Crypt::encrypt('fake-secret'));
+
+ return new IntuneAdapter($instance->fresh());
+ }
+}