feat: add deviceComplianceScript policy type
This commit is contained in:
parent
69d98e925c
commit
0c8106277c
@ -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');
|
||||
|
||||
@ -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',
|
||||
],
|
||||
|
||||
@ -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'],
|
||||
|
||||
@ -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',
|
||||
|
||||
@ -0,0 +1,14 @@
|
||||
# Requirements Checklist (026)
|
||||
|
||||
**Created**: 2026-01-04
|
||||
**Feature**: [spec.md](../spec.md)
|
||||
|
||||
- [ ] `deviceComplianceScript` exists in `config/tenantpilot.php` (category, endpoint, restore mode, risk).
|
||||
- [ ] Graph contract exists in `config/graph_contracts.php` (resource, type family, assignments paths).
|
||||
- [ ] Sync lists and stores compliance scripts in inventory.
|
||||
- [ ] Snapshot capture stores full payload + assignments.
|
||||
- [ ] Restore preview is available and respects restore mode.
|
||||
- [ ] Restore execution applies only patchable fields and re-encodes script content correctly.
|
||||
- [ ] Normalized settings view is readable and safe.
|
||||
- [ ] Pest tests cover sync + snapshot + preview + execution.
|
||||
|
||||
25
specs/026-custom-compliance-scripts/plan.md
Normal file
25
specs/026-custom-compliance-scripts/plan.md
Normal file
@ -0,0 +1,25 @@
|
||||
# Plan: Custom Compliance Scripts (Windows) (026)
|
||||
|
||||
**Branch**: `feat/026-custom-compliance-scripts`
|
||||
**Date**: 2026-01-04
|
||||
**Input**: [spec.md](./spec.md)
|
||||
|
||||
## Approach
|
||||
1. Confirm Graph contract details:
|
||||
- resource: `deviceManagement/deviceComplianceScripts` (beta)
|
||||
- patchable fields vs read-only fields
|
||||
- assignment pattern: `/deviceComplianceScripts/{id}/assign` and `/assignments`
|
||||
2. Add `deviceComplianceScript` to `config/tenantpilot.php` (category “Compliance”, risk, restore mode).
|
||||
3. Add contract entry to `config/graph_contracts.php` (resource + assignment endpoints + scope tags support).
|
||||
4. Implement snapshot capture:
|
||||
- ensure `detectionScriptContent` is preserved and treated like other scripts (safe display, encode/decode where needed)
|
||||
5. Implement restore:
|
||||
- sanitize payload via contract
|
||||
- ensure `detectionScriptContent` is encoded as expected by Graph
|
||||
- apply assignments via assign action
|
||||
6. Add normalizer and targeted tests.
|
||||
|
||||
## Decisions / Notes
|
||||
- **Restore mode**: default `enabled` (risk: medium-high) because tenant recovery often depends on these scripts.
|
||||
- Use the existing script content display rules (`TENANTPILOT_SHOW_SCRIPT_CONTENT`, max chars).
|
||||
|
||||
52
specs/026-custom-compliance-scripts/spec.md
Normal file
52
specs/026-custom-compliance-scripts/spec.md
Normal file
@ -0,0 +1,52 @@
|
||||
# Feature Specification: Custom Compliance Scripts (Windows) (026)
|
||||
|
||||
**Feature Branch**: `feat/026-custom-compliance-scripts`
|
||||
**Created**: 2026-01-04
|
||||
**Status**: Draft
|
||||
**Priority**: P1
|
||||
|
||||
## Context
|
||||
Windows Custom Compliance is widely used. Without `deviceComplianceScripts`, backup/restore for compliance posture is incomplete. Restore must include assignments.
|
||||
|
||||
## User Scenarios & Testing
|
||||
|
||||
### User Story 1 — Inventory + view compliance scripts (Priority: P1)
|
||||
As an admin, I can see Custom Compliance Scripts in inventory and view their script/config in a readable way.
|
||||
|
||||
**Acceptance Scenarios**
|
||||
1. Given device compliance scripts exist, sync shows them as type `deviceComplianceScript`.
|
||||
2. Detail view shows key settings (runAsAccount, enforceSignatureCheck, runAs32Bit) and script content (safe display rules).
|
||||
|
||||
### User Story 2 — Backup + versioning (Priority: P1)
|
||||
As an admin, I can capture versions/backups of compliance scripts so I can diff changes.
|
||||
|
||||
**Acceptance Scenarios**
|
||||
1. Snapshot capture stores the full payload including `detectionScriptContent`.
|
||||
2. Diff highlights script changes and operational flags.
|
||||
|
||||
### User Story 3 — Restore preview + execution (Priority: P1)
|
||||
As an admin, I can restore a compliance script and its assignments defensively.
|
||||
|
||||
**Acceptance Scenarios**
|
||||
1. Preview shows create/update + restore mode and warnings.
|
||||
2. Execution strips read-only fields and re-encodes script content correctly.
|
||||
3. Assignments are applied via Graph assign action.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Functional Requirements
|
||||
- **FR-001**: Add policy type `deviceComplianceScript` backed by Graph `deviceManagement/deviceComplianceScripts` (beta).
|
||||
- **FR-002**: Snapshot stores full payload (including `detectionScriptContent`) and assignments.
|
||||
- **FR-003**: Restore supports create/update with contract-driven sanitization.
|
||||
- **FR-004**: Restore applies assignments (`/assign`) and records audit logs.
|
||||
- **FR-005**: Add normalized display support for key fields and script content (with safety limits).
|
||||
- **FR-006**: Add Pest tests for sync + snapshot + preview + execution.
|
||||
|
||||
### Non-Functional Requirements
|
||||
- **NFR-001**: Script content must never be logged; UI display must be bounded (config-driven).
|
||||
- **NFR-002**: Preview-only fallback when Graph returns unexpected shapes or missing contracts.
|
||||
|
||||
## Success Criteria
|
||||
- **SC-001**: Custom compliance scripts appear in inventory and backups.
|
||||
- **SC-002**: Restore execution works and assignments are applied.
|
||||
|
||||
33
specs/026-custom-compliance-scripts/tasks.md
Normal file
33
specs/026-custom-compliance-scripts/tasks.md
Normal file
@ -0,0 +1,33 @@
|
||||
# Tasks: Custom Compliance Scripts (Windows) (026)
|
||||
|
||||
**Branch**: `feat/026-custom-compliance-scripts`
|
||||
**Date**: 2026-01-04
|
||||
**Input**: [spec.md](./spec.md), [plan.md](./plan.md)
|
||||
|
||||
## Phase 1: Setup
|
||||
- [x] T001 Create spec/plan/tasks and checklist.
|
||||
|
||||
## Phase 2: Research & Design
|
||||
- [ ] T002 Confirm Graph resource + `@odata.type` and required permissions.
|
||||
- [ ] T003 Confirm patchable fields and define `update_strip_keys` / `update_whitelist`.
|
||||
- [ ] T004 Confirm assignments endpoints (`/assignments`, `/assign`) and body shape.
|
||||
- [ ] T005 Decide restore mode + risk classification.
|
||||
|
||||
## Phase 3: Tests (TDD)
|
||||
- [ ] T006 Add sync test for `deviceComplianceScript`.
|
||||
- [ ] T007 Add snapshot/version capture test (incl. `detectionScriptContent`).
|
||||
- [ ] T008 Add restore preview test (restore_mode + action).
|
||||
- [ ] T009 Add restore execution test (sanitization + assignment apply).
|
||||
- [ ] T010 Add normalized display test for key fields.
|
||||
|
||||
## Phase 4: Implementation
|
||||
- [ ] T011 Add `deviceComplianceScript` to `config/tenantpilot.php`.
|
||||
- [ ] T012 Add Graph contract entry in `config/graph_contracts.php`.
|
||||
- [ ] T013 Implement snapshot capture handling (script content preservation rules).
|
||||
- [ ] T014 Implement restore apply support (contract-driven sanitization + assignments).
|
||||
- [ ] T015 Add `DeviceComplianceScriptNormalizer` and register it.
|
||||
|
||||
## Phase 5: Verification
|
||||
- [ ] T016 Run targeted tests.
|
||||
- [ ] T017 Run Pint (`./vendor/bin/pint --dirty`).
|
||||
|
||||
186
tests/Feature/DeviceComplianceScriptPolicyTypeTest.php
Normal file
186
tests/Feature/DeviceComplianceScriptPolicyTypeTest.php
Normal file
@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
use App\Models\BackupItem;
|
||||
use App\Models\BackupSet;
|
||||
use App\Models\Policy;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\Graph\GraphClientInterface;
|
||||
use App\Services\Graph\GraphResponse;
|
||||
use App\Services\Intune\PolicyNormalizer;
|
||||
use App\Services\Intune\RestoreService;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
class DeviceComplianceScriptRestoreGraphClient implements GraphClientInterface
|
||||
{
|
||||
/**
|
||||
* @var array<int, array{method:string,path:string,payload:array|null}>
|
||||
*/
|
||||
public array $requestCalls = [];
|
||||
|
||||
/**
|
||||
* @param array<int, GraphResponse> $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');
|
||||
});
|
||||
@ -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 () {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user