Skip to content

A free open source IT asset/license management system

Aync Adapters: Added scope tag filters for InTune

snipe88ded67f8da5
diff --git a/app/SyncAdapters/Intune/IntuneAdapter.php b/app/SyncAdapters/Intune/IntuneAdapter.php
index cbc0fd152c..999aa38cc8 100644
--- a/app/SyncAdapters/Intune/IntuneAdapter.php
+++ b/app/SyncAdapters/Intune/IntuneAdapter.php
@@ -69,6 +69,12 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
'secret' => true,
'help' => trans('admin/settings/sync_adapters.intune_client_secret_help'),
],
+ [
+ 'key' => 'scope_tag_filter',
+ 'label' => trans('admin/settings/sync_adapters.intune_scope_tag_filter_label'),
+ 'required' => false,
+ 'help' => trans('admin/settings/sync_adapters.intune_scope_tag_filter_help'),
+ ],
];
}
@@ -118,6 +124,11 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
'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'],
+ // Comma-joined roleScopeTagIds the device belongs to in
+ // Intune. Admins who use scope tags for RBAC separation
+ // can route this to a custom field to see which slice of
+ // IT owns each asset.
+ 'intune_role_scope_tag_ids' => ['label_key' => 'admin/settings/sync_adapters.intune_extra_role_scope_tag_ids'],
// 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.
@@ -152,8 +163,9 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
);
$fetchPerDeviceDetails = $this->fetchesPerDeviceDetails();
+ $scopeTagIds = $this->resolveScopeTagFilter($client);
- foreach ($client->managedDevices() as $device) {
+ foreach ($client->managedDevices($scopeTagIds) as $device) {
if ($fetchPerDeviceDetails) {
$this->fillPerDeviceEnrichment($client, $device);
}
@@ -161,6 +173,65 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
}
}
+ /**
+ * Resolve the admin-entered scope_tag_filter into the Graph tag ID
+ * list the managedDevices filter wants. Entries can be either tag
+ * displayNames (friendly) or raw IDs (short-circuit). We hit
+ * roleScopeTags() once per sync, build a name -> id map, resolve
+ * names, and pass through anything that looks like an id already.
+ * Unresolvable names are logged and skipped so one bad entry does
+ * not kill the whole pull.
+ *
+ * Returns null when no filter is configured so the client can skip
+ * the $filter query param entirely.
+ *
+ * @return array<int, string>|null
+ */
+ private function resolveScopeTagFilter(IntuneClient $client): ?array
+ {
+ $raw = '';
+ try {
+ $raw = (string) $this->credential('scope_tag_filter');
+ } catch (\Throwable) {
+ // Credential not set yet. Treat as unconfigured.
+ }
+
+ $entries = array_values(array_filter(array_map('trim', explode(',', $raw))));
+ if ($entries === []) {
+ return null;
+ }
+
+ $tags = $client->roleScopeTags();
+ $nameToId = [];
+ $idSet = [];
+ foreach ($tags as $tag) {
+ $nameToId[strtolower($tag['displayName'])] = $tag['id'];
+ $idSet[$tag['id']] = true;
+ }
+
+ $resolved = [];
+ foreach ($entries as $entry) {
+ $lower = strtolower($entry);
+ if (isset($nameToId[$lower])) {
+ $resolved[] = $nameToId[$lower];
+
+ continue;
+ }
+ if (isset($idSet[$entry])) {
+ $resolved[] = $entry;
+
+ continue;
+ }
+ Log::channel('sync-adapters')->warning(sprintf(
+ '%s: scope_tag_filter entry "%s" did not match any Intune role scope tag name or id. Skipping.',
+ $this->name(),
+ $entry,
+ ));
+ }
+
+ return $resolved === [] ? null : array_values(array_unique($resolved));
+ }
+
/**
* Per-device enrichment pass for fields Graph's LIST endpoint
* returns null for. Mutates $device in-place with the fetched
@@ -280,6 +351,10 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
'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'),
+ // Scope tags live on the device as an array of ID strings.
+ // Comma-join for custom-field display convenience. See
+ // scope_tag_filter in settingsSchema() for the usage hook.
+ 'intune_role_scope_tag_ids' => self::joinScopeTagIds(Arr::get($device, 'roleScopeTagIds')),
];
$extra = $this->applyAdminExtras($extra, $device);
@@ -317,6 +392,26 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
return $value;
}
+ /**
+ * Flatten Graph's roleScopeTagIds array into a comma-joined string
+ * for the extras bag so admins can route it to a text custom field
+ * without juggling array types. Returns null when the device has
+ * no scope tags.
+ */
+ private static function joinScopeTagIds(mixed $value): ?string
+ {
+ if (! is_array($value) || $value === []) {
+ return null;
+ }
+
+ $parts = array_values(array_filter(array_map(
+ fn ($v) => is_scalar($v) ? (string) $v : null,
+ $value,
+ )));
+
+ return $parts === [] ? null : implode(',', $parts);
+ }
+
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 57e9669448..141233a6f0 100644
--- a/app/SyncAdapters/Intune/IntuneClient.php
+++ b/app/SyncAdapters/Intune/IntuneClient.php
@@ -37,22 +37,73 @@ class IntuneClient
* Iterate every managed device visible to the app registration.
* Uses Graph's `@odata.nextLink` for cursor pagination.
*
+ * When $scopeTagIds is non-empty, appends an OData `$filter` that
+ * only returns devices whose `roleScopeTagIds` array intersects the
+ * caller's list. Pushes the filter server-side so large tenants
+ * with distributed-IT separation don't pay the pagination cost for
+ * devices they don't even care about.
+ * See https://learn.microsoft.com/en-us/intune/fundamentals/role-based-access-control/scope-tags.
+ *
+ * @param array<int, string>|null $scopeTagIds Null = no filter. Empty array = no filter.
* @return iterable<int, array<string, mixed>>
*/
- public function managedDevices(): iterable
+ public function managedDevices(?array $scopeTagIds = null): iterable
{
$graphOrigin = $this->origin($this->graphBaseUrl);
$url = rtrim($this->graphBaseUrl, '/').'/v1.0/deviceManagement/managedDevices';
+ $query = [];
+ if (is_array($scopeTagIds) && $scopeTagIds !== []) {
+ // Graph expects: $filter=roleScopeTagIds/any(x: x eq 'id1' or x eq 'id2')
+ // Quote each id and OR them inside a single any() clause.
+ $clauses = array_map(fn(string $id) => "x eq '" . addslashes($id) . "'", $scopeTagIds);
+ $query['$filter'] = 'roleScopeTagIds/any(x: ' . implode(' or ', $clauses) . ')';
+ }
+
do {
- $response = $this->request()->get($url)->throw()->json();
+ $response = $this->request()->get($url, $query)->throw()->json();
foreach (($response['value'] ?? []) as $device) {
yield $device;
}
+ // Query only on the first page. Graph's nextLink carries
+ // the filter forward in its own cursor opaquely.
+ $query = [];
+
+ $url = $this->rebasedCursor($response['@odata.nextLink'] ?? null, $graphOrigin);
+ } while ($url !== null);
+ }
+
+ /**
+ * Fetch every role scope tag defined in the tenant. Used by the
+ * adapter to resolve admin-entered scope tag names into the IDs
+ * the managedDevices filter needs, and (eventually) to populate
+ * a settings-page multiselect of available tags.
+ *
+ * Returns an array of ['id' => '...', 'displayName' => '...'].
+ *
+ * @return array<int, array{id: string, displayName: string}>
+ */
+ public function roleScopeTags(): array
+ {
+ $graphOrigin = $this->origin($this->graphBaseUrl);
+ $url = rtrim($this->graphBaseUrl, '/') . '/v1.0/deviceManagement/roleScopeTags';
+
+ $out = [];
+ do {
+ $response = $this->request()->get($url)->throw()->json();
+ foreach (($response['value'] ?? []) as $tag) {
+ $id = $tag['id'] ?? null;
+ $name = $tag['displayName'] ?? null;
+ if (is_scalar($id) && is_string($name)) {
+ $out[] = ['id' => (string) $id, 'displayName' => $name];
+ }
+ }
$url = $this->rebasedCursor($response['@odata.nextLink'] ?? null, $graphOrigin);
} while ($url !== null);
+
+ return $out;
}
/**
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index 883b325710..18888e0da6 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -202,8 +202,11 @@ return [
'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_extra_role_scope_tag_ids' => 'Intune Scope Tag IDs',
'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.',
+ 'intune_scope_tag_filter_label' => 'Scope tag filter',
+ 'intune_scope_tag_filter_help' => 'Comma-separated Intune Scope Tag names (or IDs) to limit the sync to. Devices with any of these tags are synced, everything else is skipped at the Graph API layer so unrelated devices never leave Microsoft. Leave blank to sync every device the app registration can see. Scope tags are managed under Tenant admin -> Roles -> Scope (Tags) in Intune. Example: "Marketing, Engineering".',
'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.',
diff --git a/tests/Feature/SyncAdapters/Intune/IntuneAdapterTest.php b/tests/Feature/SyncAdapters/Intune/IntuneAdapterTest.php
index 798d2b530e..080edf03b3 100644
--- a/tests/Feature/SyncAdapters/Intune/IntuneAdapterTest.php
+++ b/tests/Feature/SyncAdapters/Intune/IntuneAdapterTest.php
@@ -120,13 +120,115 @@ class IntuneAdapterTest extends TestCase
&& $request->hasHeader('Authorization', 'Bearer leak-canary'));
}
- private function configuredAdapter(): IntuneAdapter
+ public function test_scope_tag_filter_resolves_names_to_ids_and_sends_odata_filter()
+ {
+ $adapter = $this->configuredAdapter(scopeTagFilter: 'Marketing, 7');
+
+ Http::fake([
+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ '*/v1.0/deviceManagement/roleScopeTags*' => Http::response([
+ 'value' => [
+ ['id' => '3', 'displayName' => 'Marketing'],
+ ['id' => '7', 'displayName' => 'Engineering'],
+ ['id' => '11', 'displayName' => 'Finance'],
+ ],
+ ]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([
+ 'value' => [
+ $this->intuneDevice(id: 'guid-marketing', name: 'host-marketing'),
+ ],
+ ]),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ Http::assertSent(function ($request) {
+ if (! str_contains($request->url(), '/v1.0/deviceManagement/managedDevices')) {
+ return false;
+ }
+ $url = urldecode($request->url());
+
+ return str_contains($url, 'roleScopeTagIds/any(x:')
+ && str_contains($url, "x eq '3'")
+ && str_contains($url, "x eq '7'");
+ });
+ }
+
+ public function test_blank_scope_tag_filter_sends_no_odata_filter()
+ {
+ $adapter = $this->configuredAdapter(scopeTagFilter: '');
+
+ Http::fake([
+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response(['value' => []]),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ // No roleScopeTags call fired, no $filter param on the devices call.
+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v1.0/deviceManagement/roleScopeTags'));
+ Http::assertSent(fn ($request) => str_contains($request->url(), '/v1.0/deviceManagement/managedDevices')
+ && ! str_contains(urldecode($request->url()), '$filter'));
+ }
+
+ public function test_unresolved_scope_tag_entry_is_dropped()
+ {
+ // "Ghost" matches no tag. "Marketing" resolves to 3. Expect the
+ // outgoing filter to carry 3 only.
+ $adapter = $this->configuredAdapter(scopeTagFilter: 'Marketing, Ghost');
+
+ Http::fake([
+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ '*/v1.0/deviceManagement/roleScopeTags*' => Http::response([
+ 'value' => [['id' => '3', 'displayName' => 'Marketing']],
+ ]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response(['value' => []]),
+ ]);
+
+ iterator_to_array($adapter->pull());
+
+ Http::assertSent(function ($request) {
+ if (! str_contains($request->url(), '/v1.0/deviceManagement/managedDevices')) {
+ return false;
+ }
+ $url = urldecode($request->url());
+
+ return str_contains($url, "x eq '3'") && ! str_contains($url, 'Ghost');
+ });
+ }
+
+ public function test_scope_tag_ids_surface_on_normalized_record_as_comma_joined_string()
+ {
+ $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-tagged',
+ 'deviceName' => 'tagged-host',
+ 'serialNumber' => 'SN-TAGGED',
+ 'model' => 'Surface Pro 9',
+ 'roleScopeTagIds' => ['3', '7'],
+ ]],
+ ]),
+ ]);
+
+ $records = iterator_to_array($adapter->pull());
+
+ $this->assertSame('3,7', $records[0]->extra['intune_role_scope_tag_ids']);
+ }
+
+ private function configuredAdapter(?string $scopeTagFilter = null): 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'));
+ if ($scopeTagFilter !== null) {
+ SyncAdapterConfig::put($instance->id, 'scope_tag_filter', $scopeTagFilter);
+ }
return new IntuneAdapter($instance->fresh());
}