TenantAtlas/apps/platform/app/Services/Providers/ProviderOperationStartGate.php
ahmido bd26e209de
Some checks failed
Main Confidence / confidence (push) Failing after 57s
feat: harden provider boundaries (#273)
## Summary
- add the provider boundary catalog, boundary support types, and guardrails for platform-core versus provider-owned seams
- harden provider gateway, identity resolution, operation registry, and start-gate behavior to require explicit provider bindings
- add unit and feature coverage for boundary classification, runtime preservation, unsupported paths, and platform-core leakage guards
- add the full Spec Kit artifact set for spec 237 and update roadmap/spec-candidate tracking

## Validation
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Unit/Providers/ProviderBoundaryClassificationTest.php tests/Unit/Providers/ProviderBoundaryGuardrailTest.php tests/Feature/Providers/ProviderBoundaryHardeningTest.php tests/Feature/Providers/UnsupportedProviderBoundaryPathTest.php tests/Feature/Guards/ProviderBoundaryPlatformCoreGuardTest.php`
- `cd apps/platform && ./vendor/bin/sail artisan test --compact tests/Unit/Providers/ProviderGatewayTest.php tests/Unit/Providers/ProviderIdentityResolverTest.php tests/Unit/Providers/ProviderOperationStartGateTest.php`
- `cd apps/platform && ./vendor/bin/sail bin pint --dirty --format agent`
- browser smoke: `http://localhost/admin/provider-connections?tenant_id=18000000-0000-4000-8000-000000000180` loaded with the local smoke user, the empty-state CTA reached the canonical create route, and cancel returned to the scoped list

Co-authored-by: Ahmed Darrazi <ahmed.darrazi@live.de>
Reviewed-on: #273
2026-04-24 21:05:37 +00:00

315 lines
12 KiB
PHP

<?php
namespace App\Services\Providers;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\Tenant;
use App\Models\User;
use App\Services\OperationRunService;
use App\Support\Auth\Capabilities;
use App\Support\Operations\ExecutionAuthorityMode;
use App\Support\Operations\OperationRunCapabilityResolver;
use App\Support\Providers\ProviderNextStepsRegistry;
use App\Support\Providers\ProviderReasonCodes;
use App\Support\Verification\BlockedVerificationReportFactory;
use App\Support\Verification\StaleQueuedVerificationReportFactory;
use App\Support\Verification\VerificationReportWriter;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use ReflectionFunction;
use ReflectionMethod;
final class ProviderOperationStartGate
{
public function __construct(
private readonly OperationRunService $runs,
private readonly ProviderOperationRegistry $registry,
private readonly ProviderConnectionResolver $resolver,
private readonly ProviderNextStepsRegistry $nextStepsRegistry,
private readonly OperationRunCapabilityResolver $capabilityResolver,
) {}
/**
* @param array<string, mixed> $extraContext
*/
public function start(
Tenant $tenant,
?ProviderConnection $connection,
string $operationType,
callable $dispatcher,
?User $initiator = null,
array $extraContext = [],
): ProviderOperationStartResult {
$definition = $this->registry->get($operationType);
$binding = $this->resolveProviderBinding($operationType, $connection);
if (($binding['binding_status'] ?? null) !== ProviderOperationRegistry::BINDING_ACTIVE) {
return $this->startBlocked(
tenant: $tenant,
operationType: $operationType,
provider: (string) ($binding['provider'] ?? 'unknown'),
module: (string) $definition['module'],
reasonCode: ProviderReasonCodes::ProviderBindingUnsupported,
extensionReasonCode: 'ext.provider_binding_missing',
reasonMessage: 'No explicit provider binding supports this operation/provider combination.',
connection: $connection,
initiator: $initiator,
extraContext: array_merge($extraContext, [
'provider_binding' => $this->bindingContext($binding),
]),
);
}
$resolution = $connection instanceof ProviderConnection
? $this->resolver->validateConnection($tenant, (string) $binding['provider'], $connection)
: $this->resolver->resolveDefault($tenant, (string) $binding['provider']);
if (! $resolution->resolved || ! $resolution->connection instanceof ProviderConnection) {
return $this->startBlocked(
tenant: $tenant,
operationType: $operationType,
provider: (string) $binding['provider'],
module: (string) $definition['module'],
reasonCode: $resolution->effectiveReasonCode(),
extensionReasonCode: $resolution->extensionReasonCode,
reasonMessage: $resolution->message,
connection: $resolution->connection ?? $connection,
initiator: $initiator,
extraContext: array_merge($extraContext, [
'provider_binding' => $this->bindingContext($binding),
]),
);
}
return DB::transaction(function () use ($tenant, $operationType, $dispatcher, $initiator, $extraContext, $definition, $binding, $resolution): ProviderOperationStartResult {
$connection = $resolution->connection;
if (! $connection instanceof ProviderConnection) {
throw new InvalidArgumentException('Resolved provider connection is missing.');
}
$lockedConnection = ProviderConnection::query()
->whereKey($connection->getKey())
->lockForUpdate()
->firstOrFail();
$activeRun = OperationRun::query()
->where('tenant_id', $tenant->getKey())
->active()
->where('context->provider_connection_id', (int) $lockedConnection->getKey())
->orderByDesc('id')
->lockForUpdate()
->first();
if ($activeRun instanceof OperationRun) {
if ($this->runs->isStaleQueuedRun($activeRun)) {
$this->runs->failStaleQueuedRun($activeRun);
if ($activeRun->type === 'provider.connection.check') {
VerificationReportWriter::write(
run: $activeRun,
checks: StaleQueuedVerificationReportFactory::checks($activeRun),
identity: StaleQueuedVerificationReportFactory::identity($activeRun),
);
$activeRun->refresh();
}
$activeRun = null;
}
}
if ($activeRun instanceof OperationRun) {
if ($activeRun->type === $operationType) {
return ProviderOperationStartResult::deduped($activeRun);
}
return ProviderOperationStartResult::scopeBusy($activeRun);
}
$context = array_merge($extraContext, [
'execution_authority_mode' => is_string($extraContext['execution_authority_mode'] ?? null)
? $extraContext['execution_authority_mode']
: ($initiator instanceof User ? ExecutionAuthorityMode::ActorBound->value : ExecutionAuthorityMode::SystemAuthority->value),
'required_capability' => $this->resolveRequiredCapability($operationType, $extraContext),
'provider' => $lockedConnection->provider,
'module' => $definition['module'],
'provider_binding' => $this->bindingContext($binding),
'provider_connection_id' => (int) $lockedConnection->getKey(),
'target_scope' => [
'entra_tenant_id' => $lockedConnection->entra_tenant_id,
],
]);
$run = $this->runs->ensureRunWithIdentity(
tenant: $tenant,
type: $operationType,
identityInputs: [
'provider_connection_id' => (int) $lockedConnection->getKey(),
],
context: $context,
initiator: $initiator,
);
$dispatched = false;
if ($run->wasRecentlyCreated) {
$this->invokeDispatcher($dispatcher, $run);
$dispatched = true;
}
return ProviderOperationStartResult::started($run, $dispatched);
});
}
/**
* @param array<string, mixed> $extraContext
*/
private function startBlocked(
Tenant $tenant,
string $operationType,
string $provider,
string $module,
string $reasonCode,
?string $extensionReasonCode = null,
?string $reasonMessage = null,
?ProviderConnection $connection = null,
?User $initiator = null,
array $extraContext = [],
): ProviderOperationStartResult {
$context = array_merge($extraContext, [
'execution_authority_mode' => is_string($extraContext['execution_authority_mode'] ?? null)
? $extraContext['execution_authority_mode']
: ($initiator instanceof User ? ExecutionAuthorityMode::ActorBound->value : ExecutionAuthorityMode::SystemAuthority->value),
'required_capability' => $this->resolveRequiredCapability($operationType, $extraContext),
'provider' => $provider,
'module' => $module,
'target_scope' => [
'entra_tenant_id' => $tenant->graphTenantId(),
],
]);
$identityInputs = [
'provider' => $provider,
'reason_code' => $reasonCode,
];
if (is_string($extensionReasonCode) && $extensionReasonCode !== '') {
$context['reason_code_extension'] = $extensionReasonCode;
$identityInputs['reason_code_extension'] = $extensionReasonCode;
}
if ($connection instanceof ProviderConnection) {
$context['provider_connection_id'] = (int) $connection->getKey();
$identityInputs['provider_connection_id'] = (int) $connection->getKey();
}
$run = $this->runs->ensureRunWithIdentity(
tenant: $tenant,
type: $operationType,
identityInputs: $identityInputs,
context: $context,
initiator: $initiator,
);
$run = $this->runs->finalizeBlockedRun(
$run,
reasonCode: ProviderReasonCodes::isKnown($reasonCode) ? $reasonCode : ProviderReasonCodes::UnknownError,
nextSteps: $this->nextStepsRegistry->forReason($tenant, $reasonCode, $connection),
message: $reasonMessage,
);
if ($operationType === 'provider.connection.check') {
VerificationReportWriter::write(
run: $run,
checks: BlockedVerificationReportFactory::checks($run),
identity: BlockedVerificationReportFactory::identity($run),
);
$run->refresh();
}
return ProviderOperationStartResult::blocked($run);
}
private function invokeDispatcher(callable $dispatcher, OperationRun $run): void
{
$ref = null;
if (is_array($dispatcher) && count($dispatcher) === 2) {
$ref = new ReflectionMethod($dispatcher[0], (string) $dispatcher[1]);
} elseif (is_string($dispatcher) && str_contains($dispatcher, '::')) {
[$class, $method] = explode('::', $dispatcher, 2);
$ref = new ReflectionMethod($class, $method);
} elseif ($dispatcher instanceof \Closure) {
$ref = new ReflectionFunction($dispatcher);
} elseif (is_object($dispatcher) && method_exists($dispatcher, '__invoke')) {
$ref = new ReflectionMethod($dispatcher, '__invoke');
}
if ($ref && $ref->getNumberOfParameters() >= 1) {
$dispatcher($run);
return;
}
$dispatcher();
}
/**
* @return array{operation_type: string, provider: string, binding_status: string, handler_notes: string, exception_notes: string}
*/
private function resolveProviderBinding(string $operationType, ?ProviderConnection $connection): array
{
if ($connection instanceof ProviderConnection) {
$provider = trim((string) $connection->provider);
return $this->registry->bindingFor($operationType, $provider)
?? $this->registry->unsupportedBinding($operationType, $provider);
}
return $this->registry->activeBindingFor($operationType)
?? $this->registry->unsupportedBinding($operationType, 'unknown');
}
/**
* @param array{operation_type: string, provider: string, binding_status: string, handler_notes: string, exception_notes: string} $binding
* @return array{provider: string, binding_status: string, handler_notes: string, exception_notes: string}
*/
private function bindingContext(array $binding): array
{
return [
'provider' => (string) $binding['provider'],
'binding_status' => (string) $binding['binding_status'],
'handler_notes' => (string) $binding['handler_notes'],
'exception_notes' => (string) $binding['exception_notes'],
];
}
/**
* @param array<string, mixed> $extraContext
*/
private function resolveRequiredCapability(string $operationType, array $extraContext): ?string
{
if (is_string($extraContext['required_capability'] ?? null) && trim((string) $extraContext['required_capability']) !== '') {
return trim((string) $extraContext['required_capability']);
}
if ($this->registry->isAllowed($operationType)) {
$definition = $this->registry->get($operationType);
$requiredCapability = $definition['required_capability'] ?? null;
if (is_string($requiredCapability) && trim($requiredCapability) !== '') {
return trim($requiredCapability);
}
}
if ($this->registry->isAllowed($operationType)) {
return Capabilities::PROVIDER_RUN;
}
return $this->capabilityResolver->requiredExecutionCapabilityForType($operationType);
}
}