Skip to content

A free open source IT asset/license management system

By device call for scope tags for InTune

snipe74394de3e4b2
diff --git a/app/SyncAdapters/Intune/IntuneAdapter.php b/app/SyncAdapters/Intune/IntuneAdapter.php
index 999aa38cc8..0aa66d2e1f 100644
--- a/app/SyncAdapters/Intune/IntuneAdapter.php
+++ b/app/SyncAdapters/Intune/IntuneAdapter.php
@@ -164,8 +164,19 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
$fetchPerDeviceDetails = $this->fetchesPerDeviceDetails();
$scopeTagIds = $this->resolveScopeTagFilter($client);
+ $scopeTagSet = is_array($scopeTagIds) ? array_flip($scopeTagIds) : null;
+
+ foreach ($client->managedDevices() as $device) {
+ // Scope-tag filtering is client-side (see #19849). Graph
+ // does not expose a working server-side $filter on
+ // roleScopeTagIds, and the field comes back empty on the
+ // list surface even with $select, so each device needs a
+ // per-device beta GET to resolve its tag membership.
+ // Skipped entirely when no filter is configured.
+ if ($scopeTagSet !== null && ! $this->deviceMatchesScopeTags($client, $device, $scopeTagSet)) {
+ continue;
+ }
- foreach ($client->managedDevices($scopeTagIds) as $device) {
if ($fetchPerDeviceDetails) {
$this->fillPerDeviceEnrichment($client, $device);
}
@@ -173,6 +184,43 @@ class IntuneAdapter extends SyncAdapter implements PushableAdapter
}
}
+ /**
+ * Resolve the device's scope-tag membership via a beta per-device
+ * detail fetch and test it against the admin's filter set. Returns
+ * true when at least one of the device's tags is in the admin's
+ * list. On a failed detail call (4xx/5xx, timeout) we return false
+ * so the device is excluded rather than silently sneaking through
+ * the filter.
+ *
+ * @param array<string, mixed> $device
+ * @param array<string, int> $scopeTagSet Flipped id => arbitrary (for O(1) lookup)
+ */
+ private function deviceMatchesScopeTags(IntuneClient $client, array $device, array $scopeTagSet): bool
+ {
+ $deviceId = $device['id'] ?? null;
+ if (! is_string($deviceId) || $deviceId === '') {
+ return false;
+ }
+
+ $detail = $client->managedDeviceDetail($deviceId, ['id', 'roleScopeTagIds'], 'beta');
+ if ($detail === null) {
+ return false;
+ }
+
+ $deviceTagIds = $detail['roleScopeTagIds'] ?? [];
+ if (! is_array($deviceTagIds)) {
+ return false;
+ }
+
+ foreach ($deviceTagIds as $tagId) {
+ if (is_string($tagId) && isset($scopeTagSet[$tagId])) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
/**
* Resolve the admin-entered scope_tag_filter into the Graph tag ID
* list the managedDevices filter wants. Entries can be either tag
diff --git a/app/SyncAdapters/Intune/IntuneClient.php b/app/SyncAdapters/Intune/IntuneClient.php
index d398f5ff17..dde8ce45e6 100644
--- a/app/SyncAdapters/Intune/IntuneClient.php
+++ b/app/SyncAdapters/Intune/IntuneClient.php
@@ -49,35 +49,20 @@ 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.
+ * Server-side scope-tag filtering (via `$filter=roleScopeTagIds/any(...)`)
+ * was tried first but Microsoft rejects the clause on both v1.0
+ * and beta managedDevices endpoints (BadRequest, see #19849).
+ * Scope-tag filtering is now applied client-side by the adapter
+ * via per-device beta detail fetches, so this method stays on the
+ * stable list surface and returns every device.
*
- * @param array<int, string>|null $scopeTagIds Null = no filter. Empty array = no filter.
* @return iterable<int, array<string, mixed>>
*/
- public function managedDevices(?array $scopeTagIds = null): iterable
+ public function managedDevices(): iterable
{
$graphOrigin = $this->origin($this->graphBaseUrl);
-
- // roleScopeTagIds filtering lives on the beta surface. On
- // /v1.0/ the field isn't exposed, so a $filter against it
- // 400s. Fall over to /beta/ only when a filter is in use so
- // tenants that don't touch scope tags stay on the stable
- // surface.
- $apiVersion = (is_array($scopeTagIds) && $scopeTagIds !== []) ? 'beta' : 'v1.0';
- $url = rtrim($this->graphBaseUrl, '/').'/'.$apiVersion.'/deviceManagement/managedDevices';
-
+ $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, $query)->throw()->json();
@@ -86,8 +71,6 @@ class IntuneClient
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);
@@ -183,16 +166,22 @@ class IntuneClient
* 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.
+ * these as "requires per-device GET"), and for roleScopeTagIds,
+ * which the list surface also returns empty regardless of $select
+ * (see #19849). Returns the attributes array on success. Fails
+ * soft to null on 4xx/5xx so one bad device doesn't abort the
+ * enclosing enrichment pass.
+ *
+ * $apiVersion is passed through so callers can hit `beta` for
+ * fields that only populate there (roleScopeTagIds). Default
+ * stays on v1.0 for the existing enrichment call sites.
*
* @param array<int, string> $select
* @return array<string, mixed>|null
*/
- public function managedDeviceDetail(string $deviceId, array $select): ?array
+ public function managedDeviceDetail(string $deviceId, array $select, string $apiVersion = 'v1.0'): ?array
{
- $url = rtrim($this->graphBaseUrl, '/').'/v1.0/deviceManagement/managedDevices/'.rawurlencode($deviceId);
+ $url = rtrim($this->graphBaseUrl, '/').'/'.$apiVersion.'/deviceManagement/managedDevices/'.rawurlencode($deviceId);
try {
return $this->request()
diff --git a/resources/lang/en-US/admin/settings/sync_adapters.php b/resources/lang/en-US/admin/settings/sync_adapters.php
index 5a4a1b6f86..35c3d229ee 100644
--- a/resources/lang/en-US/admin/settings/sync_adapters.php
+++ b/resources/lang/en-US/admin/settings/sync_adapters.php
@@ -267,7 +267,7 @@ return [
'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". Note: scope tag filtering goes through the Microsoft Graph beta API, which Microsoft does not guarantee stable.',
+ '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. 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". Microsoft Graph does not support server-side filtering on scope tags, so Snipe-IT has to fetch each device individually from the Graph beta API to read its tags. On large tenants this adds one Graph call per device per sync, which may noticeably slow syncs down.',
'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 cbcd53b513..3c8f3b510e 100644
--- a/tests/Feature/SyncAdapters/Intune/IntuneAdapterTest.php
+++ b/tests/Feature/SyncAdapters/Intune/IntuneAdapterTest.php
@@ -150,11 +150,12 @@ class IntuneAdapterTest extends TestCase
|| str_contains($request->url(), 'graph.microsoft.com/page2'));
}
- public function test_scope_tag_filter_resolves_names_to_ids_and_sends_odata_filter()
+ public function test_scope_tag_filter_narrows_devices_via_client_side_check()
{
- // Scope tag flow runs on /beta/. The roleScopeTags resource
- // only lives there (v1.0 400s), and roleScopeTagIds is only
- // filterable on the beta managedDevices surface.
+ // Server-side scope-tag filtering is not supported by Microsoft
+ // Graph on either v1.0 or beta (see #19849). The adapter now
+ // iterates the full /v1.0/ device list and does a per-device
+ // beta GET to resolve roleScopeTagIds, then filters client-side.
$adapter = $this->configuredAdapter(scopeTagFilter: 'Marketing, 7');
Http::fake([
@@ -166,51 +167,58 @@ class IntuneAdapterTest extends TestCase
['id' => '11', 'displayName' => 'Finance'],
],
]),
- '*/beta/deviceManagement/managedDevices*' => Http::response([
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([
'value' => [
$this->intuneDevice(id: 'guid-marketing', name: 'host-marketing'),
+ $this->intuneDevice(id: 'guid-finance', name: 'host-finance'),
+ $this->intuneDevice(id: 'guid-notag', name: 'host-notag'),
],
]),
+ '*/beta/deviceManagement/managedDevices/guid-marketing*' => Http::response([
+ 'id' => 'guid-marketing',
+ 'roleScopeTagIds' => ['3'],
+ ]),
+ '*/beta/deviceManagement/managedDevices/guid-finance*' => Http::response([
+ 'id' => 'guid-finance',
+ 'roleScopeTagIds' => ['11'],
+ ]),
+ '*/beta/deviceManagement/managedDevices/guid-notag*' => Http::response([
+ 'id' => 'guid-notag',
+ 'roleScopeTagIds' => [],
+ ]),
]);
- iterator_to_array($adapter->pull());
-
- Http::assertSent(function ($request) {
- if (! str_contains($request->url(), '/beta/deviceManagement/managedDevices')) {
- return false;
- }
- $url = urldecode($request->url());
+ $records = iterator_to_array($adapter->pull());
- return str_contains($url, 'roleScopeTagIds/any(x:')
- && str_contains($url, "x eq '3'")
- && str_contains($url, "x eq '7'");
- });
+ $this->assertCount(1, $records);
+ $this->assertSame('guid-marketing', $records[0]->sourceId);
}
- public function test_blank_scope_tag_filter_sends_no_odata_filter()
+ public function test_blank_scope_tag_filter_skips_per_device_checks()
{
- // No filter means the unfiltered pull stays on /v1.0/. The
- // beta fall-over only kicks in for the scope-tag flow.
+ // No filter means we stay on /v1.0/ for the list AND we don't
+ // make any per-device beta calls.
$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' => []]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([
+ 'value' => [$this->intuneDevice(id: 'guid-whatever', name: 'host-whatever')],
+ ]),
]);
iterator_to_array($adapter->pull());
- // No roleScopeTags call fired, no $filter param on the devices call.
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'deviceManagement/roleScopeTags'));
+ Http::assertNotSent(fn ($request) => str_contains($request->url(), '/beta/deviceManagement/managedDevices'));
Http::assertSent(fn ($request) => str_contains($request->url(), '/v1.0/deviceManagement/managedDevices')
&& ! str_contains(urldecode($request->url()), '$filter'));
- Http::assertNotSent(fn ($request) => str_contains($request->url(), '/beta/deviceManagement/managedDevices'));
}
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.
+ // "Ghost" matches no tag. "Marketing" resolves to 3. Device
+ // tagged '3' should pass, device tagged '11' should not.
$adapter = $this->configuredAdapter(scopeTagFilter: 'Marketing, Ghost');
Http::fake([
@@ -218,19 +226,57 @@ class IntuneAdapterTest extends TestCase
'*/beta/deviceManagement/roleScopeTags*' => Http::response([
'value' => [['id' => '3', 'displayName' => 'Marketing']],
]),
- '*/beta/deviceManagement/managedDevices*' => Http::response(['value' => []]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([
+ 'value' => [
+ $this->intuneDevice(id: 'guid-marketing', name: 'host-marketing'),
+ $this->intuneDevice(id: 'guid-finance', name: 'host-finance'),
+ ],
+ ]),
+ '*/beta/deviceManagement/managedDevices/guid-marketing*' => Http::response([
+ 'id' => 'guid-marketing',
+ 'roleScopeTagIds' => ['3'],
+ ]),
+ '*/beta/deviceManagement/managedDevices/guid-finance*' => Http::response([
+ 'id' => 'guid-finance',
+ 'roleScopeTagIds' => ['11'],
+ ]),
]);
- iterator_to_array($adapter->pull());
+ $records = iterator_to_array($adapter->pull());
+
+ $this->assertCount(1, $records);
+ $this->assertSame('guid-marketing', $records[0]->sourceId);
+ }
+
+ public function test_scope_tag_detail_fetch_failure_excludes_the_device()
+ {
+ // If the per-device beta GET fails for one device (4xx/5xx,
+ // timeout), that device is excluded from the sync rather than
+ // silently falling through the filter.
+ $adapter = $this->configuredAdapter(scopeTagFilter: 'Marketing');
+
+ Http::fake([
+ '*/oauth2/v2.0/token' => Http::response(['access_token' => 'stub-bearer', 'expires_in' => 3600]),
+ '*/beta/deviceManagement/roleScopeTags*' => Http::response([
+ 'value' => [['id' => '3', 'displayName' => 'Marketing']],
+ ]),
+ '*/v1.0/deviceManagement/managedDevices*' => Http::response([
+ 'value' => [
+ $this->intuneDevice(id: 'guid-good', name: 'host-good'),
+ $this->intuneDevice(id: 'guid-broken', name: 'host-broken'),
+ ],
+ ]),
+ '*/beta/deviceManagement/managedDevices/guid-good*' => Http::response([
+ 'id' => 'guid-good',
+ 'roleScopeTagIds' => ['3'],
+ ]),
+ '*/beta/deviceManagement/managedDevices/guid-broken*' => Http::response([], 500),
+ ]);
- Http::assertSent(function ($request) {
- if (! str_contains($request->url(), '/beta/deviceManagement/managedDevices')) {
- return false;
- }
- $url = urldecode($request->url());
+ $records = iterator_to_array($adapter->pull());
- return str_contains($url, "x eq '3'") && ! str_contains($url, 'Ghost');
- });
+ $this->assertCount(1, $records);
+ $this->assertSame('guid-good', $records[0]->sourceId);
}
public function test_scope_tag_ids_surface_on_normalized_record_as_comma_joined_string()