From 057f2cbeb63a604b5a33e737a3e14c7b8357cc90 Mon Sep 17 00:00:00 2001 From: ahmido Date: Sun, 4 Jan 2026 02:28:29 +0000 Subject: [PATCH] feat/026-custom-compliance-scripts (#29) tenantpilot.php/graph_contracts.php include the new policy type, Graph contract, and /assign assignment flow (deviceHealthScriptAssignments payload key). ScriptsPolicyNormalizer now supports deviceComplianceScript (more metadata + script display), and InteractsWithODataTypes knows the new type. UI diff view highlights detection-script changes (same logic as other script policies) once tenantpilot.display.show_script_content is enabled. Added regression coverage in tests/Feature/Filament/ScriptPoliciesNormalizedDisplayTest plus new feature test DeviceComplianceScriptPolicyTypeTest. Runs: ScriptPoliciesNormalizedDisplayTest.php, ./vendor/bin/pint --dirty. Co-authored-by: Ahmed Darrazi Reviewed-on: https://git.cloudarix.de/ahmido/TenantAtlas/pulls/29 --- .../Intune/ScriptsPolicyNormalizer.php | 26 +++ .../Concerns/InteractsWithODataTypes.php | 4 + config/graph_contracts.php | 20 ++ config/tenantpilot.php | 10 + .../entries/normalized-diff.blade.php | 2 +- .../DeviceComplianceScriptPolicyTypeTest.php | 186 ++++++++++++++++++ .../ScriptPoliciesNormalizedDisplayTest.php | 72 ++++++- 7 files changed, 318 insertions(+), 2 deletions(-) create mode 100644 tests/Feature/DeviceComplianceScriptPolicyTypeTest.php diff --git a/app/Services/Intune/ScriptsPolicyNormalizer.php b/app/Services/Intune/ScriptsPolicyNormalizer.php index 68bf7e5..172bd8e 100644 --- a/app/Services/Intune/ScriptsPolicyNormalizer.php +++ b/app/Services/Intune/ScriptsPolicyNormalizer.php @@ -11,6 +11,7 @@ public function __construct(private readonly DefaultPolicyNormalizer $defaultNor public function supports(string $policyType): bool { return in_array($policyType, [ + 'deviceComplianceScript', 'deviceManagementScript', 'deviceShellScript', 'deviceHealthScript', @@ -39,6 +40,31 @@ public function normalize(?array $snapshot, string $policyType, ?string $platfor $entries[] = ['key' => 'Description', 'value' => $description]; } + $fileName = Arr::get($snapshot, 'fileName'); + if (is_string($fileName) && $fileName !== '') { + $entries[] = ['key' => 'File name', 'value' => $fileName]; + } + + $publisher = Arr::get($snapshot, 'publisher'); + if (is_string($publisher) && $publisher !== '') { + $entries[] = ['key' => 'Publisher', 'value' => $publisher]; + } + + $runAsAccount = Arr::get($snapshot, 'runAsAccount'); + if (is_string($runAsAccount) && $runAsAccount !== '') { + $entries[] = ['key' => 'Run as account', 'value' => $runAsAccount]; + } + + $runAs32Bit = Arr::get($snapshot, 'runAs32Bit'); + if (is_bool($runAs32Bit)) { + $entries[] = ['key' => 'Run as 32-bit', 'value' => $runAs32Bit ? 'Enabled' : 'Disabled']; + } + + $enforceSignatureCheck = Arr::get($snapshot, 'enforceSignatureCheck'); + if (is_bool($enforceSignatureCheck)) { + $entries[] = ['key' => 'Enforce signature check', 'value' => $enforceSignatureCheck ? 'Enabled' : 'Disabled']; + } + $entries = array_merge($entries, $this->contentEntries($snapshot)); $schedule = Arr::get($snapshot, 'runSchedule'); diff --git a/app/Support/Concerns/InteractsWithODataTypes.php b/app/Support/Concerns/InteractsWithODataTypes.php index 37ba8dc..3a2d09b 100644 --- a/app/Support/Concerns/InteractsWithODataTypes.php +++ b/app/Support/Concerns/InteractsWithODataTypes.php @@ -62,6 +62,10 @@ protected static function odataTypeMap(): array 'windows' => '#microsoft.graph.deviceHealthScript', 'all' => '#microsoft.graph.deviceHealthScript', ], + 'deviceComplianceScript' => [ + 'windows' => '#microsoft.graph.deviceComplianceScript', + 'all' => '#microsoft.graph.deviceComplianceScript', + ], 'enrollmentRestriction' => [ 'all' => '#microsoft.graph.deviceEnrollmentConfiguration', ], diff --git a/config/graph_contracts.php b/config/graph_contracts.php index 674e824..c2b9c5c 100644 --- a/config/graph_contracts.php +++ b/config/graph_contracts.php @@ -438,6 +438,26 @@ 'id_field' => 'id', 'hydration' => 'properties', ], + 'deviceComplianceScript' => [ + 'resource' => 'deviceManagement/deviceComplianceScripts', + 'allowed_select' => ['id', 'displayName', 'description', '@odata.type', 'lastModifiedDateTime'], + 'allowed_expand' => [], + 'type_family' => [ + '#microsoft.graph.deviceComplianceScript', + ], + 'create_method' => 'POST', + 'update_method' => 'PATCH', + 'id_field' => 'id', + 'hydration' => 'properties', + 'assignments_list_path' => '/deviceManagement/deviceComplianceScripts/{id}/assignments', + 'assignments_create_path' => '/deviceManagement/deviceComplianceScripts/{id}/assign', + 'assignments_create_method' => 'POST', + 'assignments_payload_key' => 'deviceHealthScriptAssignments', + 'assignments_update_path' => '/deviceManagement/deviceComplianceScripts/{id}/assignments/{assignmentId}', + 'assignments_update_method' => 'PATCH', + 'assignments_delete_path' => '/deviceManagement/deviceComplianceScripts/{id}/assignments/{assignmentId}', + 'assignments_delete_method' => 'DELETE', + ], 'deviceManagementScript' => [ 'resource' => 'deviceManagement/deviceManagementScripts', 'allowed_select' => ['id', 'displayName', 'description', '@odata.type', 'lastModifiedDateTime'], diff --git a/config/tenantpilot.php b/config/tenantpilot.php index d222293..f0f8062 100644 --- a/config/tenantpilot.php +++ b/config/tenantpilot.php @@ -155,6 +155,16 @@ 'restore' => 'enabled', 'risk' => 'medium', ], + [ + 'type' => 'deviceComplianceScript', + 'label' => 'Custom Compliance Scripts', + 'category' => 'Compliance', + 'platform' => 'windows', + 'endpoint' => 'deviceManagement/deviceComplianceScripts', + 'backup' => 'full', + 'restore' => 'enabled', + 'risk' => 'medium-high', + ], [ 'type' => 'windowsAutopilotDeploymentProfile', 'label' => 'Windows Autopilot Profiles', diff --git a/resources/views/filament/infolists/entries/normalized-diff.blade.php b/resources/views/filament/infolists/entries/normalized-diff.blade.php index a7623b8..0390c23 100644 --- a/resources/views/filament/infolists/entries/normalized-diff.blade.php +++ b/resources/views/filament/infolists/entries/normalized-diff.blade.php @@ -58,7 +58,7 @@ $canHighlightScripts = static function (?string $policyType): bool { return (bool) config('tenantpilot.display.show_script_content', false) - && in_array($policyType, ['deviceManagementScript', 'deviceShellScript', 'deviceHealthScript'], true); + && in_array($policyType, ['deviceManagementScript', 'deviceShellScript', 'deviceHealthScript', 'deviceComplianceScript'], true); }; $selectGrammar = static function (?string $policyType, string $code): string { diff --git a/tests/Feature/DeviceComplianceScriptPolicyTypeTest.php b/tests/Feature/DeviceComplianceScriptPolicyTypeTest.php new file mode 100644 index 0000000..c24b180 --- /dev/null +++ b/tests/Feature/DeviceComplianceScriptPolicyTypeTest.php @@ -0,0 +1,186 @@ + + */ + public array $requestCalls = []; + + /** + * @param array $requestResponses + */ + public function __construct( + private readonly GraphResponse $applyPolicyResponse, + private array $requestResponses = [], + ) {} + + public function listPolicies(string $policyType, array $options = []): GraphResponse + { + return new GraphResponse(true, []); + } + + public function getPolicy(string $policyType, string $policyId, array $options = []): GraphResponse + { + return new GraphResponse(true, ['payload' => []]); + } + + public function getOrganization(array $options = []): GraphResponse + { + return new GraphResponse(true, []); + } + + public function applyPolicy(string $policyType, string $policyId, array $payload, array $options = []): GraphResponse + { + return $this->applyPolicyResponse; + } + + public function getServicePrincipalPermissions(array $options = []): GraphResponse + { + return new GraphResponse(true, []); + } + + public function request(string $method, string $path, array $options = []): GraphResponse + { + $this->requestCalls[] = [ + 'method' => strtoupper($method), + 'path' => $path, + 'payload' => $options['json'] ?? null, + ]; + + return array_shift($this->requestResponses) ?? new GraphResponse(true, []); + } +} + +it('includes device compliance scripts in supported policy types', function () { + $supported = collect(config('tenantpilot.supported_policy_types', [])) + ->keyBy('type') + ->all(); + + expect($supported)->toHaveKey('deviceComplianceScript'); + expect($supported['deviceComplianceScript']['endpoint'] ?? null)->toBe('deviceManagement/deviceComplianceScripts'); + expect($supported['deviceComplianceScript']['restore'] ?? null)->toBe('enabled'); +}); + +it('defines device compliance script graph contract with correct assignment payload key', function () { + $contract = config('graph_contracts.types.deviceComplianceScript'); + + expect($contract)->toBeArray(); + expect($contract['resource'] ?? null)->toBe('deviceManagement/deviceComplianceScripts'); + expect($contract['assignments_create_path'] ?? null)->toBe('/deviceManagement/deviceComplianceScripts/{id}/assign'); + expect($contract['assignments_payload_key'] ?? null)->toBe('deviceHealthScriptAssignments'); +}); + +it('restores device compliance script assignments via assign action', function () { + $client = new DeviceComplianceScriptRestoreGraphClient( + applyPolicyResponse: new GraphResponse(true, []), + requestResponses: [ + new GraphResponse(true, []), // assign action + ], + ); + app()->instance(GraphClientInterface::class, $client); + + $tenant = Tenant::factory()->create([ + 'tenant_id' => 'tenant-1', + ]); + + $policy = Policy::factory()->create([ + 'tenant_id' => $tenant->id, + 'external_id' => 'dcs-1', + 'policy_type' => 'deviceComplianceScript', + 'platform' => 'windows', + ]); + + $backupSet = BackupSet::factory()->create([ + 'tenant_id' => $tenant->id, + 'status' => 'completed', + 'item_count' => 1, + ]); + + $backupItem = BackupItem::factory()->create([ + 'tenant_id' => $tenant->id, + 'backup_set_id' => $backupSet->id, + 'policy_id' => $policy->id, + 'policy_identifier' => $policy->external_id, + 'policy_type' => $policy->policy_type, + 'platform' => $policy->platform, + 'payload' => [ + 'id' => $policy->external_id, + '@odata.type' => '#microsoft.graph.deviceComplianceScript', + ], + 'assignments' => [ + [ + 'id' => 'assignment-1', + 'intent' => 'apply', + 'target' => [ + '@odata.type' => '#microsoft.graph.groupAssignmentTarget', + 'groupId' => 'source-group-1', + ], + ], + ], + ]); + + $user = User::factory()->create(['email' => 'tester@example.com']); + $this->actingAs($user); + + $service = app(RestoreService::class); + $service->execute( + tenant: $tenant, + backupSet: $backupSet, + selectedItemIds: [$backupItem->id], + dryRun: false, + actorEmail: $user->email, + actorName: $user->name, + groupMapping: [ + 'source-group-1' => 'target-group-1', + ], + ); + + $postCalls = collect($client->requestCalls) + ->filter(fn (array $call) => $call['method'] === 'POST') + ->values(); + + expect($postCalls)->toHaveCount(1); + expect($postCalls[0]['path'])->toBe('/deviceManagement/deviceComplianceScripts/dcs-1/assign'); + + $payloadAssignments = $postCalls[0]['payload']['deviceHealthScriptAssignments'] ?? []; + $groupIds = collect($payloadAssignments)->pluck('target.groupId')->all(); + + expect($groupIds)->toBe(['target-group-1']); + expect($payloadAssignments[0])->not->toHaveKey('id'); +}); + +it('normalizes device compliance script key fields', function () { + config([ + 'tenantpilot.display.show_script_content' => false, + ]); + + $normalized = app(PolicyNormalizer::class)->normalize([ + '@odata.type' => '#microsoft.graph.deviceComplianceScript', + 'displayName' => 'My script', + 'runAsAccount' => 'system', + 'runAs32Bit' => true, + 'enforceSignatureCheck' => false, + 'detectionScriptContent' => base64_encode("Write-Host 'hello'\n"), + ], 'deviceComplianceScript', 'windows'); + + $settings = $normalized['settings'][0]['entries'] ?? []; + $byKey = collect($settings)->keyBy('key'); + + expect($byKey['Run as account']['value'] ?? null)->toBe('system'); + expect($byKey['Run as 32-bit']['value'] ?? null)->toBe('Enabled'); + expect($byKey['Enforce signature check']['value'] ?? null)->toBe('Disabled'); +}); diff --git a/tests/Feature/Filament/ScriptPoliciesNormalizedDisplayTest.php b/tests/Feature/Filament/ScriptPoliciesNormalizedDisplayTest.php index 9db3154..7673fe7 100644 --- a/tests/Feature/Filament/ScriptPoliciesNormalizedDisplayTest.php +++ b/tests/Feature/Filament/ScriptPoliciesNormalizedDisplayTest.php @@ -35,6 +35,10 @@ $scriptContent = "#!/bin/zsh\n".str_repeat('X', 20); } + $contentKey = in_array($policyType, ['deviceHealthScript', 'deviceComplianceScript'], true) + ? 'detectionScriptContent' + : 'scriptContent'; + $version = PolicyVersion::factory()->create([ 'policy_id' => $policy->id, 'tenant_id' => $tenant->id, @@ -43,7 +47,7 @@ '@odata.type' => $odataType, 'displayName' => 'Script policy', 'description' => 'desc', - 'scriptContent' => $scriptContent, + $contentKey => $contentKey === 'scriptContent' ? $scriptContent : base64_encode($scriptContent), ], ]); @@ -60,6 +64,7 @@ ['deviceManagementScript', '#microsoft.graph.deviceManagementScript'], ['deviceShellScript', '#microsoft.graph.deviceShellScript'], ['deviceHealthScript', '#microsoft.graph.deviceHealthScript'], + ['deviceComplianceScript', '#microsoft.graph.deviceComplianceScript'], ]); it('renders diff tab with highlighted script content for script policies', function () { @@ -126,3 +131,68 @@ ? putenv("INTUNE_TENANT_ID={$originalEnv}") : putenv('INTUNE_TENANT_ID'); }); + +it('renders diff tab with highlighted script content for device compliance scripts', function () { + $originalEnv = getenv('INTUNE_TENANT_ID'); + putenv('INTUNE_TENANT_ID='); + + $this->actingAs(User::factory()->create()); + + config([ + 'tenantpilot.display.show_script_content' => true, + 'tenantpilot.display.max_script_content_chars' => 5000, + ]); + + $tenant = Tenant::factory()->create(); + putenv('INTUNE_TENANT_ID='.$tenant->tenant_id); + $tenant->makeCurrent(); + + $policy = Policy::factory()->create([ + 'tenant_id' => $tenant->getKey(), + 'policy_type' => 'deviceComplianceScript', + 'platform' => 'windows', + ]); + + $scriptOne = "# test\n".str_repeat("Write-Host 'one'\n", 40); + $scriptTwo = "# test\n".str_repeat("Write-Host 'two'\n", 40); + + $v1 = PolicyVersion::factory()->create([ + 'policy_id' => $policy->getKey(), + 'tenant_id' => $tenant->getKey(), + 'version_number' => 1, + 'policy_type' => 'deviceComplianceScript', + 'platform' => 'windows', + 'snapshot' => [ + '@odata.type' => '#microsoft.graph.deviceComplianceScript', + 'displayName' => 'My compliance script', + 'detectionScriptContent' => base64_encode($scriptOne), + ], + ]); + + $v2 = PolicyVersion::factory()->create([ + 'policy_id' => $policy->getKey(), + 'tenant_id' => $tenant->getKey(), + 'version_number' => 2, + 'policy_type' => 'deviceComplianceScript', + 'platform' => 'windows', + 'snapshot' => [ + '@odata.type' => '#microsoft.graph.deviceComplianceScript', + 'displayName' => 'My compliance script', + 'detectionScriptContent' => base64_encode($scriptTwo), + ], + ]); + + $url = \App\Filament\Resources\PolicyVersionResource::getUrl('view', ['record' => $v2]); + + $this->get($url.'?tab=diff') + ->assertSuccessful() + ->assertSeeText('Fullscreen') + ->assertSeeText("- Write-Host 'one'") + ->assertSeeText("+ Write-Host 'two'") + ->assertSee('bg-danger-50', false) + ->assertSee('bg-success-50', false); + + $originalEnv !== false + ? putenv("INTUNE_TENANT_ID={$originalEnv}") + : putenv('INTUNE_TENANT_ID'); +});