TenantAtlas/tests/Feature/Baselines/BaselineCompareProtectedChangeTest.php
ahmido cd811cff4f Spec 120: harden secret redaction integrity (#146)
## Summary
- replace broad substring-based masking with a shared exact/path-based secret classifier and workspace-scoped fingerprint hashing
- persist protected snapshot metadata on `policy_versions` and keep secret-only changes visible in compare, drift, restore, review, verification, and ops surfaces
- add Spec 120 artifacts, audit documentation, and focused Pest regression coverage for snapshot, audit, verification, review-pack, and notification behavior

## Validation
- `vendor/bin/sail artisan test --compact tests/Feature/Intune/PolicySnapshotRedactionTest.php tests/Feature/Intune/PolicySnapshotFingerprintIsolationTest.php tests/Feature/ReviewPack/ReviewPackRedactionIntegrityTest.php tests/Feature/OpsUx/OperationRunNotificationRedactionTest.php tests/Feature/Verification/VerificationReportViewerDbOnlyTest.php`
- `vendor/bin/sail bin pint --dirty --format agent`

## Spec / checklist status
| Checklist | Total | Completed | Incomplete | Status |
|-----------|-------|-----------|------------|--------|
| requirements.md | 16 | 16 | 0 | ✓ PASS |

- `tasks.md`: T001-T032 complete
- `tasks.md`: T033 manual quickstart validation is still open and noted for follow-up

## Filament / platform notes
- Livewire v4 compliance is unchanged
- no panel provider changes; `bootstrap/providers.php` remains the registration location
- no new globally searchable resources were introduced, so global search requirements are unchanged
- no new destructive Filament actions were added
- no new Filament assets were added; no `filament:assets` deployment change is required

## Testing coverage touched
- snapshot persistence and fingerprint isolation
- compare/drift protected-change evidence
- audit, verification, review-pack, ops-failure, and notification sanitization
- viewer/read-only Filament presentation updates

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #146
2026-03-07 16:43:01 +00:00

194 lines
7.4 KiB
PHP

<?php
declare(strict_types=1);
use App\Jobs\CompareBaselineToTenantJob;
use App\Models\BaselineProfile;
use App\Models\BaselineSnapshot;
use App\Models\BaselineSnapshotItem;
use App\Models\Finding;
use App\Models\InventoryItem;
use App\Models\Policy;
use App\Models\PolicyVersion;
use App\Services\Baselines\BaselineSnapshotIdentity;
use App\Services\Drift\DriftFindingDiffBuilder;
use App\Services\Drift\DriftHasher;
use App\Services\Drift\Normalizers\AssignmentsNormalizer;
use App\Services\Drift\Normalizers\ScopeTagsNormalizer;
use App\Services\Drift\Normalizers\SettingsNormalizer;
use App\Services\Intune\AuditLogger;
use App\Services\Intune\PolicySnapshotRedactor;
use App\Services\OperationRunService;
use App\Support\Baselines\BaselineSubjectKey;
use App\Support\OperationRunType;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('creates a drift finding for secret-only snapshot changes and surfaces protected-change evidence', function (): void {
[$user, $tenant] = createUserWithTenant(role: 'owner');
$profile = BaselineProfile::factory()->active()->create([
'workspace_id' => (int) $tenant->workspace_id,
'scope_jsonb' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
]);
$baselineCapturedAt = CarbonImmutable::parse('2026-03-01 00:00:00');
$snapshot = BaselineSnapshot::factory()->create([
'workspace_id' => (int) $tenant->workspace_id,
'baseline_profile_id' => (int) $profile->getKey(),
'captured_at' => $baselineCapturedAt,
]);
$profile->update(['active_snapshot_id' => $snapshot->getKey()]);
$inventorySyncRun = createInventorySyncOperationRunWithCoverage(
tenant: $tenant,
statusByType: ['deviceConfiguration' => 'succeeded'],
);
$policy = Policy::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'policy_type' => 'deviceConfiguration',
'external_id' => 'policy-secret',
'platform' => 'windows',
'display_name' => 'Protected Policy',
]);
/** @var PolicySnapshotRedactor $redactor */
$redactor = app(PolicySnapshotRedactor::class);
/** @var DriftHasher $hasher */
$hasher = app(DriftHasher::class);
/** @var SettingsNormalizer $settingsNormalizer */
$settingsNormalizer = app(SettingsNormalizer::class);
/** @var AssignmentsNormalizer $assignmentsNormalizer */
$assignmentsNormalizer = app(AssignmentsNormalizer::class);
/** @var ScopeTagsNormalizer $scopeTagsNormalizer */
$scopeTagsNormalizer = app(ScopeTagsNormalizer::class);
$baselineProtected = $redactor->protect(
workspaceId: (int) $tenant->workspace_id,
payload: [
'wifi' => [
'ssid' => 'Corp',
'password' => 'baseline-secret',
],
],
);
$baselineHash = $hasher->hashNormalized([
'settings' => $settingsNormalizer->normalizeForDiff($baselineProtected->snapshot, 'deviceConfiguration', 'windows'),
'assignments' => $assignmentsNormalizer->normalizeForDiff([]),
'scope_tag_ids' => $scopeTagsNormalizer->normalizeIds([]),
'secret_fingerprints' => $baselineProtected->secretFingerprints,
'redaction_version' => $baselineProtected->redactionVersion,
]);
$subjectKey = BaselineSubjectKey::fromDisplayName((string) $policy->display_name);
expect($subjectKey)->not->toBeNull();
BaselineSnapshotItem::factory()->create([
'baseline_snapshot_id' => (int) $snapshot->getKey(),
'subject_type' => 'policy',
'subject_external_id' => BaselineSubjectKey::workspaceSafeSubjectExternalId(
policyType: (string) $policy->policy_type,
subjectKey: (string) $subjectKey,
),
'subject_key' => (string) $subjectKey,
'policy_type' => (string) $policy->policy_type,
'baseline_hash' => $baselineHash,
'meta_jsonb' => [
'display_name' => (string) $policy->display_name,
'evidence' => [
'fidelity' => 'content',
'source' => 'policy_version',
'observed_at' => $baselineCapturedAt->toIso8601String(),
'observed_operation_run_id' => null,
],
],
]);
InventoryItem::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'external_id' => (string) $policy->external_id,
'policy_type' => (string) $policy->policy_type,
'display_name' => (string) $policy->display_name,
'meta_jsonb' => [
'odata_type' => '#microsoft.graph.deviceConfiguration',
'etag' => 'W/"same-etag"',
'scope_tag_ids' => [],
'assignment_target_count' => 1,
],
'last_seen_operation_run_id' => (int) $inventorySyncRun->getKey(),
'last_seen_at' => now(),
]);
$baselineVersion = PolicyVersion::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(),
'version_number' => 1,
'policy_type' => (string) $policy->policy_type,
'platform' => (string) $policy->platform,
'captured_at' => $baselineCapturedAt,
'snapshot' => $baselineProtected->snapshot,
'secret_fingerprints' => $baselineProtected->secretFingerprints,
'redaction_version' => $baselineProtected->redactionVersion,
]);
$currentProtected = $redactor->protect(
workspaceId: (int) $tenant->workspace_id,
payload: [
'wifi' => [
'ssid' => 'Corp',
'password' => 'rotated-secret',
],
],
);
$currentVersion = PolicyVersion::factory()->create([
'tenant_id' => (int) $tenant->getKey(),
'policy_id' => (int) $policy->getKey(),
'version_number' => 2,
'policy_type' => (string) $policy->policy_type,
'platform' => (string) $policy->platform,
'captured_at' => $baselineCapturedAt->addHour(),
'snapshot' => $currentProtected->snapshot,
'secret_fingerprints' => $currentProtected->secretFingerprints,
'redaction_version' => $currentProtected->redactionVersion,
]);
$opService = app(OperationRunService::class);
$run = $opService->ensureRunWithIdentity(
tenant: $tenant,
type: OperationRunType::BaselineCompare->value,
identityInputs: ['baseline_profile_id' => (int) $profile->getKey()],
context: [
'baseline_profile_id' => (int) $profile->getKey(),
'baseline_snapshot_id' => (int) $snapshot->getKey(),
'effective_scope' => ['policy_types' => ['deviceConfiguration'], 'foundation_types' => []],
],
initiator: $user,
);
(new CompareBaselineToTenantJob($run))->handle(
app(BaselineSnapshotIdentity::class),
app(AuditLogger::class),
$opService,
);
$finding = Finding::query()
->where('tenant_id', (int) $tenant->getKey())
->where('subject_external_id', (string) $policy->external_id)
->first();
expect($finding)->toBeInstanceOf(Finding::class);
expect($finding?->evidence_jsonb['summary']['kind'] ?? null)->toBe('policy_snapshot');
$diff = app(DriftFindingDiffBuilder::class)->buildSettingsDiff($baselineVersion, $currentVersion);
expect($diff['summary']['message'] ?? null)->toContain('protected value change');
expect($diff['changed'])->toHaveKey('Protected > /wifi/password (value changed)');
});