TenantAtlas/app/Jobs/ProviderComplianceSnapshotJob.php
ahmido 5bcb4f6ab8 feat: harden queued execution legitimacy (#179)
## Summary
- add a canonical queued execution legitimacy contract for actor-bound and system-authority operation runs
- enforce legitimacy before queued jobs transition runs to running across provider, inventory, restore, bulk, sync, and scheduled backup flows
- surface blocked execution outcomes consistently in Monitoring, notifications, audit data, and the tenantless operation viewer
- add Spec 149 artifacts and focused Pest coverage for legitimacy decisions, middleware ordering, blocked presentation, retry behavior, and cross-family adoption

## Testing
- vendor/bin/sail artisan test --compact tests/Unit/Operations/QueuedExecutionLegitimacyGateTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Operations/QueuedExecutionMiddlewareOrderingTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Verification/ProviderExecutionReauthorizationTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Operations/RunInventorySyncExecutionReauthorizationTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Operations/ExecuteRestoreRunExecutionReauthorizationTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Operations/SystemRunBlockedExecutionNotificationTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Operations/BulkOperationExecutionReauthorizationTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Operations/QueuedExecutionRetryReauthorizationTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Operations/QueuedExecutionContractMatrixTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Operations/OperationRunBlockedExecutionPresentationTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Operations/QueuedExecutionAuditTrailTest.php
- vendor/bin/sail artisan test --compact tests/Feature/Operations/TenantlessOperationRunViewerTest.php
- vendor/bin/sail bin pint --dirty --format agent

## Manual validation
- validated queued provider execution blocking for tenant operability drift in the integrated browser on /admin/operations and /admin/operations/{run}
- validated 404 vs 403 route behavior for non-membership vs in-scope capability denial
- validated initiator-null blocked system-run behavior without creating a user terminal notification

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #179
2026-03-17 21:52:40 +00:00

153 lines
5.1 KiB
PHP

<?php
namespace App\Jobs;
use App\Jobs\Middleware\EnsureQueuedExecutionLegitimate;
use App\Jobs\Middleware\TrackOperationRun;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\Tenant;
use App\Models\User;
use App\Services\OperationRunService;
use App\Services\Providers\MicrosoftComplianceSnapshotService;
use App\Services\Providers\ProviderGateway;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OpsUx\RunFailureSanitizer;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use RuntimeException;
use Throwable;
class ProviderComplianceSnapshotJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public ?OperationRun $operationRun = null;
public function __construct(
public int $tenantId,
public int $userId,
public int $providerConnectionId,
?OperationRun $operationRun = null,
) {
$this->operationRun = $operationRun;
}
/**
* @return array<int, object>
*/
public function middleware(): array
{
return [new EnsureQueuedExecutionLegitimate, new TrackOperationRun];
}
public function handle(
MicrosoftComplianceSnapshotService $collector,
ProviderGateway $gateway,
OperationRunService $runs,
): void {
$tenant = Tenant::query()->find($this->tenantId);
if (! $tenant instanceof Tenant) {
throw new RuntimeException('Tenant not found.');
}
$user = User::query()->find($this->userId);
if (! $user instanceof User) {
throw new RuntimeException('User not found.');
}
$connection = ProviderConnection::query()
->where('tenant_id', $tenant->getKey())
->find($this->providerConnectionId);
if (! $connection instanceof ProviderConnection) {
throw new RuntimeException('ProviderConnection not found.');
}
try {
$counts = $collector->snapshot($connection);
$entraTenantName = $this->resolveEntraTenantName($connection, $gateway);
if ($entraTenantName !== null) {
$metadata = is_array($connection->metadata) ? $connection->metadata : [];
$metadata['entra_tenant_name'] = $entraTenantName;
$connection->update(['metadata' => $metadata]);
}
if ($this->operationRun instanceof OperationRun) {
$this->updateRunTargetScope($this->operationRun, $connection, $entraTenantName);
$runs->updateRun(
$this->operationRun,
status: OperationRunStatus::Completed->value,
outcome: OperationRunOutcome::Succeeded->value,
summaryCounts: $counts,
);
}
} catch (Throwable $throwable) {
if (! $this->operationRun instanceof OperationRun) {
throw $throwable;
}
$message = RunFailureSanitizer::sanitizeMessage($throwable->getMessage());
$reasonCode = RunFailureSanitizer::normalizeReasonCode($throwable->getMessage());
$runs->updateRun(
$this->operationRun,
status: OperationRunStatus::Completed->value,
outcome: OperationRunOutcome::Failed->value,
failures: [[
'code' => 'compliance.snapshot.failed',
'reason_code' => $reasonCode,
'message' => $message !== '' ? $message : 'Compliance snapshot failed.',
]],
);
}
}
private function resolveEntraTenantName(ProviderConnection $connection, ProviderGateway $gateway): ?string
{
$metadata = is_array($connection->metadata) ? $connection->metadata : [];
$existing = $metadata['entra_tenant_name'] ?? null;
if (is_string($existing) && trim($existing) !== '') {
return trim($existing);
}
try {
$response = $gateway->getOrganization($connection);
} catch (Throwable) {
return null;
}
if (! $response->successful()) {
return null;
}
$displayName = $response->data['displayName'] ?? null;
return is_string($displayName) && trim($displayName) !== '' ? trim($displayName) : null;
}
private function updateRunTargetScope(OperationRun $run, ProviderConnection $connection, ?string $entraTenantName): void
{
$context = is_array($run->context) ? $run->context : [];
$targetScope = $context['target_scope'] ?? [];
$targetScope = is_array($targetScope) ? $targetScope : [];
$targetScope['entra_tenant_id'] = $connection->entra_tenant_id;
if (is_string($entraTenantName) && $entraTenantName !== '') {
$targetScope['entra_tenant_name'] = $entraTenantName;
}
$context['target_scope'] = $targetScope;
$run->update(['context' => $context]);
}
}