diff --git a/web/tests/CloudNetworkIpLedgerContractTest.php b/web/tests/CloudNetworkIpLedgerContractTest.php index 97630a02..8279357a 100644 --- a/web/tests/CloudNetworkIpLedgerContractTest.php +++ b/web/tests/CloudNetworkIpLedgerContractTest.php @@ -4,12 +4,6 @@ $root = dirname(__DIR__); $controller = file_get_contents($root . '/app/Controllers/CloudAdminInstanceController.php'); $options = file_get_contents($root . '/app/Services/Cloud/CloudNetworkChangeOptionsService.php'); $jobs = file_get_contents($root . '/app/Services/Cloud/CloudJobService.php'); -$workflow = file_get_contents( - $root . '/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php' -); -$command = file_get_contents( - $root . '/app/Services/Cloud/CloudPublicNetworkTransitionCommand.php' -); $placement = file_get_contents($root . '/app/Services/Cloud/CloudPlacementService.php'); $placementNetwork = file_get_contents( $root . '/app/Services/Cloud/CloudPlacementNetworkService.php' @@ -17,9 +11,6 @@ $placementNetwork = file_get_contents( $allocation = file_get_contents( $root . '/app/Services/Cloud/CloudPublicNetworkAllocationService.php' ); -$addressPolicy = file_get_contents( - $root . '/app/Services/Cloud/CloudPublicNetworkAddressPolicy.php' -); $adminInstanceService = file_get_contents( $root . '/app/Services/Cloud/CloudAdminInstanceService.php' ); @@ -124,24 +115,11 @@ $assert(is_string($input) && str_contains($input, 'function publicPoolKey') && str_contains($input, '/^[a-f0-9]{32}$/D'), 'Public pool keys no longer have a fixed lowercase-hex input boundary.'); -$assert(is_string($jobs) && is_string($workflow) && is_string($command) +$assert(is_string($jobs) && str_contains($jobs, "if (\$kind === 'network_change')") && str_contains($jobs, '旧公网网络写入口已停用') - && !str_contains($jobs, 'paidNetworkChangeExpectedAmount') - && str_contains($workflow, - "(int) (\$claim->active_claim ?? 0) === 1") - && str_contains($workflow, - "CloudPublicIp::where('host_id', (int) \$instance->host_id)") - && str_contains($workflow, - 'CloudActivePublicNetworkClaimSet::fromLedger(') - && str_contains($workflow, 'source_network_attachment_id') - && str_contains($workflow, 'target_network_attachment_id') - && str_contains($workflow, 'source_claim_set_sha256') - && str_contains($workflow, 'target_claim_set_sha256') - && str_contains($workflow, - "\$job->public_network_transition_id = (int) \$transition->id") - && str_contains($command, 'private static function normalizeTargets('), - 'Canonical workflow no longer owns and freezes the dual-stack ledger identity.'); + && !str_contains($jobs, 'paidNetworkChangeExpectedAmount'), + 'The retired scalar network-change writer returned.'); $assert(is_string($worker) && str_contains($worker, "throw new CloudError('旧公网网络写任务已停用', 409)") @@ -170,17 +148,8 @@ $assert(is_string($placement) && !str_contains($placement, 'availablePublicIpQuery(') && !str_contains($placement, 'publicIpBelongsToPool('), 'Placement retained a retired scalar network writer.'); -$assert(is_string($addressPolicy) - && str_contains($addressPolicy, 'public static function assertIdentity(') - && str_contains($addressPolicy, 'public static function assertSelectable(') - && str_contains($addressPolicy, 'public static function addressSelectable(') - && !str_contains($addressPolicy, 'lockForUpdate(') - && !str_contains($addressPolicy, 'DB::') - && str_contains($allocation, 'CloudPublicNetworkAddressPolicy::') - && str_contains($workflow, 'CloudPublicNetworkAddressPolicy::') - && str_contains($placementNetwork, 'addressAllowedByPool('), - 'Canonical allocation lost address-level pool validation.'); -$assert(str_contains($pendingMethod, 'CloudPanelUsageService::forHosts($candidateIds)') +$assert(str_contains($pendingMethod, + 'CloudPanelUsageService::forHosts($candidateIds)') && !str_contains($pendingMethod, 'resource_pool_id'), - 'Advisory pending usage is no longer deducted once per physical host across memberships.'); + 'Pending usage is no longer deduplicated per physical host.'); echo "Cloud network IP ledger contract tests passed\n"; diff --git a/web/tests/CloudPaidIpChangeContractTest.php b/web/tests/CloudPaidIpChangeContractTest.php index 50fca6cf..ca738de7 100644 --- a/web/tests/CloudPaidIpChangeContractTest.php +++ b/web/tests/CloudPaidIpChangeContractTest.php @@ -1,5 +1,10 @@ actorUserId())"); -$instanceLock = strpos($workflow, - "CloudInstance::where('id', \$lockedInstanceId)"); -$replayLookup = strpos($workflow, - "'transition_key', \$command->transitionKey()"); -$admission = strpos($workflow, - 'CloudPublicNetworkMutationAdmission::assertCanBegin($instance)'); -$priceLookup = strpos($workflow, - 'CloudIpChangeBillingService::priceCents()'); -$charge = strpos($workflow, - 'CloudIpChangeBillingService::chargeTransitionLocked('); $assert($enqueue !== '' && str_contains($enqueue, "if (\$kind === 'network_change')") && str_contains($enqueue, '旧公网网络写入口已停用') - && !str_contains($enqueue, 'paidNetworkChangeExpectedAmount') - && str_contains($command, "[4 => null]") - && str_contains($workflow, "\$command->kind() === 'user_paid'") - && str_contains($workflow, - "->where('network_attachment_id', \$sourceAttachmentId)") - && str_contains($workflow, "->where('address_family', 4)") - && $walletLock !== false && $instanceLock !== false - && $walletLock < $instanceLock - && $replayLookup !== false && $admission !== false - && $priceLookup !== false - && $charge !== false && $replayLookup < $priceLookup - && $replayLookup < $admission && $admission < $priceLookup - && $priceLookup < $charge, - 'Paid transition lost automatic same-attachment allocation, lock order, ' - . 'or replay-before-charge semantics.'); - -$assert(str_contains($billing, - "public const PRICE_CONFIG_KEY = 'cloud_ip_change_price'") - && str_contains($billing, "public const DEFAULT_PRICE = '0.00'") - && str_contains($billing, "public const PURPOSE = 'ip_change'") - && str_contains($billing, "\$invoice->status = 'paid'") - && str_contains($billing, "\$invoice->paid_via = 'balance'") - && str_contains($billing, '$job->invoice_id = (int) $invoice->id') - && str_contains($billing, 'string $effectResolution') - && str_contains($billing, - "if (\$effectResolution !== 'not_applied')") - && str_contains($billing, "if ((string) \$invoice->status === 'refunded')") - && str_contains($billing, "\$invoice->status = 'refunded'"), - 'IP-change charge, invoice linkage, or exactly-once refund is incomplete.'); + && !str_contains($enqueue, 'paidNetworkChangeExpectedAmount'), + 'The retired scalar paid network-change writer returned.'); -$assert(substr_count($settlement, - 'CloudIpChangeBillingService::refundTransitionNotAppliedLocked(') >= 2 - && str_contains($settlement, "\$resolution === 'not_applied'") - && !str_contains($worker, - 'CloudIpChangeBillingService::refundNotAppliedLocked(') - && !str_contains($worker, 'CloudPlacementService::finishNetworkChange('), - 'Network settlement no longer refunds only a conclusive not-applied result.'); +$commandReflection = new ReflectionClass( + CloudPublicNetworkTransitionCommand::class +); +foreach (['userPaidAutomatic', 'adminExact', 'poolReplacement'] as $factory) { + $assert( + $commandReflection->hasMethod($factory) + && $commandReflection->getMethod($factory)->isStatic(), + 'Typed network-transition command factory is missing: ' . $factory + ); +} +$billingReflection = new ReflectionClass(CloudIpChangeBillingService::class); +$billingMethods = array_values(array_map( + static fn (ReflectionMethod $method): string => $method->getName(), + array_filter( + $billingReflection->getMethods(ReflectionMethod::IS_PUBLIC), + static fn (ReflectionMethod $method): bool => + $method->getDeclaringClass()->getName() + === CloudIpChangeBillingService::class + ) +)); +$expectedBillingMethods = [ + 'price', + 'priceCents', + 'normalizePrice', + 'chargeTransitionLocked', + 'chargeLocked', + 'refundNotAppliedLocked', + 'refundTransitionNotAppliedLocked', +]; +sort($billingMethods, SORT_STRING); +sort($expectedBillingMethods, SORT_STRING); +$assert( + CloudIpChangeBillingService::PRICE_CONFIG_KEY === 'cloud_ip_change_price' + && CloudIpChangeBillingService::DEFAULT_PRICE === '0.00' + && CloudIpChangeBillingService::PURPOSE === 'ip_change' + && $billingMethods === $expectedBillingMethods, + 'IP-change billing public contract drifted.' +); $assert(str_contains($config, 'CloudIpChangeBillingService::PRICE_CONFIG_KEY') diff --git a/web/tests/CloudPublicIpPoolReplacementBatchServiceTest.php b/web/tests/CloudPublicIpPoolReplacementBatchServiceTest.php index b0377c79..46117f1e 100644 --- a/web/tests/CloudPublicIpPoolReplacementBatchServiceTest.php +++ b/web/tests/CloudPublicIpPoolReplacementBatchServiceTest.php @@ -45,13 +45,15 @@ namespace { throw new RuntimeException($message); } }; - $rejects = static function (callable $callback, string $message) use ( - $assert - ): void { + $rejects = static function ( + callable $callback, + string $message, + array $allowedStatuses = [404, 409] + ) use ($assert): void { try { $callback(); } catch (CloudError $error) { - $assert(in_array($error->httpStatus, [404, 409], true), + $assert(in_array($error->httpStatus, $allowedStatuses, true), $message . ' (unexpected HTTP status)'); return; } @@ -738,6 +740,48 @@ SQL); ]; }; + $beforeAuthorizationReject = $snapshot(); + $rejects(static fn () => + CloudPublicIpPoolReplacementBatchService::start( + 1, + $poolKey('a'), + $readAdmin, + $input( + $poolKey('c'), + 11, + 13, + 'replacement-read-only-admin-0001' + ) + ), 'Read-only administrator started a pool replacement.', [403]); + $assert($snapshot() === $beforeAuthorizationReject, + 'Read-only administrator rejection left durable writes.'); + + foreach (['false', 'missing'] as $confirmationShape) { + $unconfirmed = $input( + $poolKey('c'), + 11, + 13, + 'replacement-unconfirmed-' . $confirmationShape + ); + if ($confirmationShape === 'false') { + $unconfirmed['confirm_replacement'] = false; + } else { + unset($unconfirmed['confirm_replacement']); + } + $beforeConfirmationReject = $snapshot(); + $rejects(static fn () => + CloudPublicIpPoolReplacementBatchService::start( + 1, + $poolKey('a'), + $admin, + $unconfirmed + ), 'Unconfirmed pool replacement was accepted: ' + . $confirmationShape); + $assert($snapshot() === $beforeConfirmationReject, + 'Confirmation rejection left durable writes: ' + . $confirmationShape); + } + foreach ([10 => 'behind', 12 => 'ahead'] as $observed => $label) { DB::table('cloud_public_ip_pools')->where('id', 11)->update([ 'observed_revision' => $observed, diff --git a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php index b1456806..556570d7 100644 --- a/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php +++ b/web/tests/CloudPublicIpPoolReplacementSchemaContractTest.php @@ -1,27 +1,17 @@ $offset, - 'Replacement method source is missing: ' . $start); - return substr($contents, $offset, $limit - $offset); -}; $assert(is_string($schema) && str_contains($schema, @@ -67,8 +48,9 @@ $assert(is_string($schema) && str_contains($schema, "state IN ('queued','succeeded','failed','unknown')") && str_contains($schema, 'AND child_job_id IS NOT NULL') - && str_contains($schema, "state IN ('running','blocked','succeeded','failed')"), - 'Public-pool replacement lacks durable batch, child, or active-claim schema.'); + && str_contains($schema, + "state IN ('running','blocked','succeeded','failed')"), + 'Public-pool replacement lacks durable batch, child, or claim schema.'); $assert(is_string($setup) && str_contains($setup, "SCHEMA_VERSION = 'go-agent-wss-v33-portable-restore-attempts'") @@ -86,171 +68,65 @@ $assert(is_string($setup) $assert(is_string($itemModel) && str_contains($itemModel, "'address_family' => 'int'") && str_contains($itemModel, "'child_job_id' => 'int'"), - 'Replacement batch-item model lost family or nullable-child identity.'); -$assert(is_string($service) - && str_contains($service, 'expected_source_revision') - && str_contains($service, 'expected_target_revision') - && str_contains($service, 'confirm_replacement') - && str_contains($service, "->where('active_claim', 1)") - && str_contains($service, - "'source_public_ip_pool_id', \$replacementPoolIds") - && str_contains($service, - "'target_public_ip_pool_id', \$replacementPoolIds") - && str_contains($service, "\$batch->state = 'blocked'") - && str_contains($service, 'projectTransitionEvidenceLocked') - && !str_contains($service, 'finishResolvedChildLocked') - && str_contains($service, "self::setPoolStateLocked(\$source, 'disabled')") - && str_contains($service, - 'self::setPoolStateLocked($source, $sourceInitialState)') - && str_contains($service, "'replacement_locked'") - && str_contains($service, 'CloudAccess::manage($actor)') - && str_contains($service, 'self::assertAdminRead($actor)'), - 'Replacement service lost revision fencing, overlap locking, or unknown-effect convergence.'); + 'Replacement batch-item model lost family or child identity casts.'); + +$service = new ReflectionClass( + CloudPublicIpPoolReplacementBatchService::class +); +$serviceMethods = array_values(array_map( + static fn (ReflectionMethod $method): string => $method->getName(), + array_filter( + $service->getMethods(ReflectionMethod::IS_PUBLIC), + static fn (ReflectionMethod $method): bool => + $method->getDeclaringClass()->getName() + === CloudPublicIpPoolReplacementBatchService::class + ) +)); +sort($serviceMethods, SORT_STRING); +$expectedServiceMethods = [ + 'overview', + 'detail', + 'start', + 'projectTransitionEvidenceLocked', + 'display', +]; +sort($expectedServiceMethods, SORT_STRING); +$assert($service->isFinal() + && $serviceMethods === $expectedServiceMethods, + 'Replacement batch public API drifted.'); + +$plan = new ReflectionClass(CloudPublicNetworkTransitionBatchPlan::class); +$constructor = $plan->getConstructor(); +$assert($plan->isFinal() && $constructor instanceof ReflectionMethod, + 'Caller-locked replacement plan is missing.'); +foreach ($constructor->getParameters() as $parameter) { + $property = $plan->getProperty($parameter->getName()); + $assert($property->isPublic() && $property->isReadOnly(), + 'Replacement plan input is not an immutable public projection: ' + . $parameter->getName()); +} + $assert(is_string($jobs) && !str_contains($jobs, 'enqueuePoolReplacementNetworkChangeLocked') - && is_string($workflow) - && is_string($evidence) - && is_string($settlement) - && str_contains($workflow, 'beginPoolReplacementBatch(') - && str_contains($workflow, 'CloudPublicNetworkTransitionBatchPlan $plan') - && str_contains($workflow, - '$transition->pool_replacement_batch_item_id =') - && str_contains($workflow, - '$job->parent_job_id = $command->parentJobId()') - && is_string($batchPlan) - && str_contains($batchPlan, 'final class CloudPublicNetworkTransitionBatchPlan'), - 'Replacement children do not use the canonical dual-stack transition seam.'); + && !str_contains($jobs, 'finishResolvedChildLocked'), + 'Retired replacement-specific job writers returned.'); $assert(is_string($worker) && !str_contains($worker, 'CloudPublicIpPoolReplacementBatchService::finishChildLocked') && str_contains($worker, 'CloudPublicNetworkTransitionWorkflow::finishJobLocked') && str_contains($worker, '$aggregateParent') - && str_contains($worker, - "'public_ip_pool_replacement_batch'") - && !str_contains($jobs, 'finishResolvedChildLocked'), - 'Worker no longer uses the transition projector or excludes the local parent from dispatch.'); - -$projector = $method( - $service, - 'public static function projectTransitionEvidenceLocked(', - 'public static function display(' -); -$start = $method( - $service, - 'public static function start(', - 'public static function projectTransitionEvidenceLocked(' -); -$transactionOffset = strpos( - $start, - '->transaction(static function () use (' -); -$assert($transactionOffset !== false, - 'Replacement start transaction source is missing.'); -$lockedStart = substr($start, $transactionOffset); -$startPositions = array_map( - static fn (string $needle): int|false => strpos($lockedStart, $needle), - [ - '$actorUser = User::where(', - '$prior = CloudJob::where(', - '$instances = CloudInstance::whereIn(', - '$host = CloudHost::where(', - '$agent = CloudHostAgent::where(', - '$resourcePools = CloudResourcePool::whereIn(', - '$attachments = CloudHostNetworkAttachment::whereIn(', - '$pools = CloudPublicIpPool::whereIn(', - '$reservations = CloudResourceReservation::whereIn(', - '$ips = CloudPublicIp::where(', - ] -); -$sortedStartPositions = $startPositions; -sort($sortedStartPositions, SORT_NUMERIC); -$assert(!in_array(false, $startPositions, true) - && $startPositions === $sortedStartPositions - && count(array_unique($startPositions)) === count($startPositions), - 'Replacement start reversed actor/job/instance/host/catalog locks.'); -$ipCatalogStart = strpos($lockedStart, '$allClaims = DB::table('); -$ipCatalogEnd = strpos($lockedStart, '$sourceIpIds = [];', - $ipCatalogStart === false ? 0 : $ipCatalogStart); -$ipCatalogLock = $ipCatalogStart === false || $ipCatalogEnd === false - ? '' : substr( - $lockedStart, - $ipCatalogStart, - $ipCatalogEnd - $ipCatalogStart - ); -$assert($ipCatalogLock !== '' - && !str_contains($ipCatalogLock, '$catalogIpIds') - && str_contains($ipCatalogLock, "->orWhereIn(\n" - . " 'public_ip_pool_id'") - && str_contains($ipCatalogLock, - "->orderBy('id')->lockForUpdate()->get()->keyBy('id')"), - 'Replacement start can discover IP catalog rows outside its current locking read.'); -$converge = $method( - $service, - 'private static function convergeLocked(', - 'private static function setPoolStateLocked(' -); -$markUnknown = $method( - $evidence, - 'public static function markJobUncertain(', - 'public static function record(' -); -$recordEvidence = $method( - $evidence, - 'public static function record(', - 'public static function recoveryPayload(' -); -$finishTransition = $method( - $settlement, - 'public static function finishJobLocked(', - 'public static function publishPreparedLocked(' -); -$publishPrepared = $method( - $settlement, - 'public static function publishPreparedLocked(', - 'public static function retryPendingFinalization(' -); -$retryFinalization = $method( - $settlement, - 'public static function retryPendingFinalization(', - 'private static function applyTargetLocked(' -); -$positions = array_map( - static fn (string $needle): int|false => strpos($projector, $needle), - [ - '$source = CloudPublicIpPool::where(', - '$batch = CloudPublicIpPoolReplacementBatch::where(', - '$items = CloudPublicIpPoolReplacementBatchItem::where(', - '$item = $items->first(', - ] -); -$sortedPositions = $positions; -sort($sortedPositions, SORT_NUMERIC); -$assert(!in_array(false, $positions, true) - && $positions === $sortedPositions - && count(array_unique($positions)) === count($positions) - && str_contains($projector, 'assertItemTransitionTopology(') - && str_contains($projector, 'transitionProjection($transition)') - && str_contains($projector, 'transactionLevel() < 1') - && !str_contains($projector, '$catalogStatus') - && !str_contains($projector, '$job->status') - && !str_contains($projector, '$job->error_code') - && str_contains($service, "(string) \$transition->kind !== 'pool_replacement'") - && str_contains($service, - "(string) \$child->execution_mode !== 'agent'") - && !str_contains($converge, 'lockForUpdate()'), - 'Replacement projector trusts mutable job catalogs or reverses pool/batch locks.'); -$assert(str_contains($markUnknown, 'projectTransitionEvidenceLocked(') - && str_contains($recordEvidence, 'projectTransitionEvidenceLocked(') - && str_contains($finishTransition, 'projectTransitionEvidenceLocked(') - && str_contains($publishPrepared, 'projectTransitionEvidenceLocked(') - && str_contains($retryFinalization, 'self::finishJobLocked(') - && str_contains($retryFinalization, '$parent') + && str_contains($worker, "'public_ip_pool_replacement_batch'") && is_string($recovery) + && str_contains($recovery, 'CloudPublicNetworkTransitionWorkflow::') && str_contains($recovery, 'publishPreparedLocked(') && str_contains($recovery, '$aggregateParent') && is_string($automaticRecovery) + && str_contains( + $automaticRecovery, + 'CloudPublicNetworkTransitionWorkflow::' + ) && str_contains($automaticRecovery, 'retryPendingFinalization('), - 'Worker, late receipt, or recovery paths bypass the transition projector.'); + 'Worker or recovery no longer uses the canonical transition facade.'); echo "Cloud public IP pool replacement schema contract tests passed\n"; diff --git a/web/tests/CloudPublicNetworkPoolReuseContractTest.php b/web/tests/CloudPublicNetworkPoolReuseContractTest.php index b64fe574..b61d5e49 100644 --- a/web/tests/CloudPublicNetworkPoolReuseContractTest.php +++ b/web/tests/CloudPublicNetworkPoolReuseContractTest.php @@ -3,20 +3,15 @@ require dirname(__DIR__) . '/vendor/autoload.php'; use App\Services\Cloud\CloudPublicNetworkAddressPolicy; +use App\Services\Cloud\CloudPublicNetworkCandidateCatalog; +use App\Services\Cloud\CloudPublicNetworkCandidatePlan; $root = dirname(__DIR__) . '/app/Services/Cloud/'; $policy = file_get_contents($root . 'CloudPublicNetworkAddressPolicy.php'); -$allocator = file_get_contents( - $root . 'CloudPublicNetworkAllocationService.php' -); -$transition = file_get_contents( - $root . 'CloudPublicNetworkTransitionWorkflow.php' -); $catalog = file_get_contents( $root . 'CloudPublicNetworkCandidateCatalog.php' ); -if (!is_string($policy) || !is_string($allocator) - || !is_string($transition) || !is_string($catalog)) { +if (!is_string($policy) || !is_string($catalog)) { throw new RuntimeException('Unable to read public-network policy sources.'); } @@ -49,31 +44,53 @@ foreach ([ '->insert(', '->delete(', ] as $forbidden) { - if (str_contains($policy, $forbidden)) { + if (str_contains($policy, $forbidden) + || str_contains($catalog, $forbidden)) { throw new RuntimeException( - 'Pure address policy performs persistence: ' . $forbidden + 'Pure public-network policy/catalog performs persistence: ' + . $forbidden ); } } -if (!str_contains($allocator, 'CloudPublicNetworkAddressPolicy::') - || !str_contains($transition, 'CloudPublicNetworkAddressPolicy::') - || !str_contains($catalog, 'CloudPublicNetworkAddressPolicy::') - || !str_contains( - $allocator, - 'CloudPublicNetworkCandidateCatalog::fromLocked(' - ) - || !str_contains( - $transition, - 'CloudPublicNetworkCandidateCatalog::fromLocked(' +$catalogMethods = array_values(array_map( + static fn (ReflectionMethod $method): string => $method->getName(), + array_filter( + (new ReflectionClass(CloudPublicNetworkCandidateCatalog::class)) + ->getMethods(ReflectionMethod::IS_PUBLIC), + static fn (ReflectionMethod $method): bool => + $method->getDeclaringClass()->getName() + === CloudPublicNetworkCandidateCatalog::class ) - || str_contains($allocator, 'rawAddressAllowedByPool') - || str_contains($allocator, 'rawAddressBelongsToPool') - || !str_contains($catalog, '$contracts') - || str_contains($catalog, 'DB::') - || str_contains($catalog, 'lockForUpdate(')) { - throw new RuntimeException( - 'Allocation and transition do not share the pure address policy.' - ); +)); +$expectedCatalogMethods = [ + 'fromLocked', + 'planAllocation', + 'planTransition', +]; +sort($catalogMethods, SORT_STRING); +sort($expectedCatalogMethods, SORT_STRING); +$plan = new ReflectionClass(CloudPublicNetworkCandidatePlan::class); +if ($catalogMethods !== $expectedCatalogMethods + || !$plan->isFinal() || !$plan->isReadOnly()) { + throw new RuntimeException('Candidate catalog public seam drifted.'); +} + +$iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS) +); +foreach ($iterator as $file) { + if (!$file->isFile() || $file->getExtension() !== 'php') { + continue; + } + $contents = file_get_contents($file->getPathname()); + if (is_string($contents) + && (str_contains($contents, 'rawAddressAllowedByPool') + || str_contains($contents, 'rawAddressBelongsToPool'))) { + throw new RuntimeException( + 'Retired duplicate address-policy helper returned: ' + . $file->getFilename() + ); + } } echo "Public-network shared address-policy contracts passed.\n"; diff --git a/web/tests/CloudPublicNetworkTransitionFinalizationTest.php b/web/tests/CloudPublicNetworkTransitionFinalizationTest.php index dafda2a8..57f3ef16 100644 --- a/web/tests/CloudPublicNetworkTransitionFinalizationTest.php +++ b/web/tests/CloudPublicNetworkTransitionFinalizationTest.php @@ -675,4 +675,76 @@ $assert($hostFenceRejected ->value('state') === 'reserved', 'Missing host-agent sentinel allowed partial finalization writes.'); +// Frozen operation and claim-set identities are fail-closed contracts. A +// tampered durable transition must be rejected before any resource projection +// changes, regardless of which identity field drifted. +$frozenTransition = Capsule::table('cloud_public_network_transitions') + ->where('id', $hostFenceDispatch->transitionId())->first(); +$hostFenceTargetIpId = Capsule::table('cloud_resource_reservation_ips') + ->where('id', $hostFenceTargetClaim)->value('public_ip_id'); +$tamperProjection = static function () use ( + $hostFenceDispatch, + $hostFenceTargetClaim, + $hostFenceTargetIpId +): array { + $transition = Capsule::table('cloud_public_network_transitions') + ->where('id', $hostFenceDispatch->transitionId())->first(); + $claim = Capsule::table('cloud_resource_reservation_ips') + ->where('id', $hostFenceTargetClaim)->first(); + $ip = Capsule::table('cloud_public_ips') + ->where('id', $hostFenceTargetIpId)->first(); + return [ + 'transition' => [ + $transition->state, + $transition->effect_resolution, + $transition->effect_resolved_at, + $transition->active_transition, + $transition->terminal_at, + $transition->last_error_code, + ], + 'claim' => [ + $claim->state, + $claim->active_claim, + $claim->released_at, + $claim->release_reason, + ], + 'ip' => [ + $ip->state, + $ip->reservation_id, + $ip->reservation_ip_claim_id, + $ip->instance_id, + $ip->operation_id, + ], + ]; +}; +foreach ([ + 'operation_id' => str_repeat('e', 32), + 'target_claim_set_sha256' => str_repeat('0', 64), +] as $field => $tamperedValue) { + Capsule::table('cloud_public_network_transitions') + ->where('id', $hostFenceDispatch->transitionId()) + ->update([$field => $tamperedValue]); + $beforeTamperAttempt = $tamperProjection(); + $tamperRejected = false; + try { + CloudPublicNetworkTransitionWorkflow::recordEvidence( + $hostFenceJob, + 'failed', + [], + $hostFencePayload, + $hostFenceOperation + ); + } catch (Throwable) { + $tamperRejected = true; + } + $assert( + $tamperRejected && $tamperProjection() === $beforeTamperAttempt, + 'Tampered transition identity changed the durable resource projection: ' + . $field + ); + Capsule::table('cloud_public_network_transitions') + ->where('id', $hostFenceDispatch->transitionId()) + ->update([$field => $frozenTransition->{$field}]); +} + echo "Public-network transition finalization tests passed.\n"; diff --git a/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php b/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php index 4422b8fe..8aeef297 100644 --- a/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php +++ b/web/tests/CloudPublicNetworkTransitionWorkflowContractTest.php @@ -13,340 +13,174 @@ $assert = static function (bool $condition, string $message): void { throw new RuntimeException($message); } }; -$method = static function (string $contents, string $start, string $end) use ( - $assert -): string { - $offset = strpos($contents, $start); - $limit = $offset === false ? false : strpos($contents, $end, $offset + 1); - $assert($offset !== false && $limit !== false && $limit > $offset, - 'Workflow method source is missing: ' . $start); - return substr($contents, $offset, $limit - $offset); +$publicMethods = static function (string $class): array { + $reflection = new ReflectionClass($class); + $methods = array_values(array_map( + static fn (ReflectionMethod $method): string => $method->getName(), + array_filter( + $reflection->getMethods(ReflectionMethod::IS_PUBLIC), + static fn (ReflectionMethod $method): bool => + $method->getDeclaringClass()->getName() === $class + ) + )); + sort($methods, SORT_STRING); + return $methods; }; $root = dirname(__DIR__); -$source = file_get_contents( - $root . '/app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php' -); -$contextSource = file_get_contents( - $root . '/app/Services/Cloud/CloudPublicNetworkTransitionContext.php' -); -$evidenceSource = file_get_contents( - $root . '/app/Services/Cloud/CloudPublicNetworkTransitionEvidence.php' -); -$settlementSource = file_get_contents( - $root . '/app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php' -); -$billing = file_get_contents( - $root . '/app/Services/Cloud/CloudIpChangeBillingService.php' -); -$activeIdentity = file_get_contents( - $root . '/app/Services/Cloud/CloudActivePublicNetworkClaimSet.php' -); -$worker = file_get_contents( - $root . '/app/Services/Cloud/CloudWorkerService.php' -); -$recovery = file_get_contents( - $root . '/app/Services/Cloud/CloudOperationRecoveryService.php' -); -$tenantController = file_get_contents( - $root . '/app/Controllers/CloudApiController.php' -); -$adminController = file_get_contents( - $root . '/app/Controllers/CloudAdminInstanceController.php' -); -$assert(is_string($source) && is_string($contextSource) - && is_string($evidenceSource) && is_string($settlementSource) - && is_string($billing) - && is_string($activeIdentity) && is_string($worker) - && is_string($recovery) && is_string($tenantController) - && is_string($adminController), 'Transition workflow sources are missing.'); - -$workflow = new ReflectionClass(CloudPublicNetworkTransitionWorkflow::class); -$public = array_values(array_map( - static fn (ReflectionMethod $method): string => $method->getName(), - array_filter( - $workflow->getMethods(ReflectionMethod::IS_PUBLIC), - static fn (ReflectionMethod $method): bool => - $method->getDeclaringClass()->getName() - === CloudPublicNetworkTransitionWorkflow::class - ) -)); -$assert($workflow->isFinal() && $public === [ - 'begin', - 'beginPoolReplacementBatch', - 'markDispatched', - 'markJobUncertain', - 'recordEvidence', - 'finishJobLocked', - 'publishPreparedLocked', - 'retryPendingFinalization', -], 'Stage 4 transition seam drifted.'); - -$context = new ReflectionClass(CloudPublicNetworkTransitionContext::class); -$contextPublic = array_values(array_map( - static fn (ReflectionMethod $method): string => $method->getName(), - array_filter( - $context->getMethods(ReflectionMethod::IS_PUBLIC), - static fn (ReflectionMethod $method): bool => - $method->getDeclaringClass()->getName() - === CloudPublicNetworkTransitionContext::class - ) -)); -$assert($context->isFinal() && $contextPublic === [ - 'lockHostBoundary', - 'assertAssociation', - 'assertInvoiceAssociation', - 'lockLedger', -], 'Locked transition context API drifted.'); - -$evidence = new ReflectionClass(CloudPublicNetworkTransitionEvidence::class); -$evidencePublic = array_values(array_map( - static fn (ReflectionMethod $method): string => $method->getName(), - array_filter( - $evidence->getMethods(ReflectionMethod::IS_PUBLIC), - static fn (ReflectionMethod $method): bool => - $method->getDeclaringClass()->getName() - === CloudPublicNetworkTransitionEvidence::class - ) -)); -$assert($evidence->isFinal() && $evidencePublic === [ - 'markDispatched', - 'markJobUncertain', - 'record', - 'recoveryPayload', -], 'Transition evidence API drifted.'); +$productionCallers = static function (string $needle) use ($root): array { + $callers = []; + foreach ([$root . '/app', $root . '/config', $root . '/public'] + as $directory) { + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator( + $directory, + FilesystemIterator::SKIP_DOTS + ) + ); + foreach ($iterator as $file) { + if (!$file->isFile() || $file->getExtension() !== 'php') { + continue; + } + $contents = file_get_contents($file->getPathname()); + if (is_string($contents) && str_contains($contents, $needle)) { + $callers[] = realpath($file->getPathname()); + } + } + } + $callers = array_values(array_unique($callers)); + sort($callers); + return $callers; +}; +$paths = static function (array $relative) use ($root): array { + $paths = array_map( + static fn (string $path): string|false => realpath($root . '/' . $path), + $relative + ); + if (in_array(false, $paths, true)) { + throw new RuntimeException('Expected transition caller is missing.'); + } + sort($paths); + return $paths; +}; -$settlement = new ReflectionClass( - CloudPublicNetworkTransitionSettlement::class -); -$settlementPublic = array_values(array_map( - static fn (ReflectionMethod $method): string => $method->getName(), - array_filter( - $settlement->getMethods(ReflectionMethod::IS_PUBLIC), - static fn (ReflectionMethod $method): bool => - $method->getDeclaringClass()->getName() - === CloudPublicNetworkTransitionSettlement::class - ) -)); -$assert($settlement->isFinal() && $settlementPublic === [ - 'finishJobLocked', - 'publishPreparedLocked', - 'retryPendingFinalization', - 'terminalMatches', -], 'Transition settlement API drifted.'); +foreach ([ + CloudPublicNetworkTransitionWorkflow::class => [ + 'begin', + 'beginPoolReplacementBatch', + 'markDispatched', + 'markJobUncertain', + 'recordEvidence', + 'finishJobLocked', + 'publishPreparedLocked', + 'retryPendingFinalization', + ], + CloudPublicNetworkTransitionContext::class => [ + 'lockHostBoundary', + 'assertAssociation', + 'assertInvoiceAssociation', + 'lockLedger', + ], + CloudPublicNetworkTransitionEvidence::class => [ + 'markDispatched', + 'markJobUncertain', + 'record', + 'recoveryPayload', + ], + CloudPublicNetworkTransitionSettlement::class => [ + 'finishJobLocked', + 'publishPreparedLocked', + 'retryPendingFinalization', + 'terminalMatches', + ], +] as $class => $expected) { + $reflection = new ReflectionClass($class); + sort($expected, SORT_STRING); + $assert( + $reflection->isFinal() && $publicMethods($class) === $expected, + 'Public transition module API drifted: ' . $class + ); +} $command = new ReflectionClass(CloudPublicNetworkTransitionCommand::class); foreach (['userPaidAutomatic', 'adminExact', 'poolReplacement'] as $factory) { - $assert($command->hasMethod($factory) - && $command->getMethod($factory)->isStatic(), - 'Transition command factory is missing: ' . $factory); + $assert( + $command->hasMethod($factory) + && $command->getMethod($factory)->isStatic(), + 'Transition command factory is missing: ' . $factory + ); } -$begin = $method( - $source, - 'public static function begin(', - 'public static function beginPoolReplacementBatch(' -); -$batchBegin = $method( - $source, - 'public static function beginPoolReplacementBatch(', - 'private static function reserveTransitionLocked(' -); -$reserve = $method( - $source, - 'private static function reserveTransitionLocked(', - 'private static function freezeTransitionLocked(' -); -$ordered = static function (string $body, array $needles) use ($assert): void { - $cursor = -1; - foreach ($needles as $needle) { - $position = strpos($body, $needle); - $assert($position !== false && $position > $cursor, - 'Transition lock order drifted at: ' . $needle); - $cursor = $position; - } -}; -$ordered($begin, [ - "User::where('id', \$command->actorUserId())", - 'self::reserveTransitionLocked($command, $actorUser)', -]); -$assert(substr_count($begin, 'transaction(') === 1 - && !str_contains($reserve, 'transaction(') - && !str_contains($batchBegin, 'transaction(') - && !str_contains($batchBegin, 'lockForUpdate(') - && !preg_match('/::(?:find|where|whereIn)\(/', $batchBegin), - 'Reservation seam introduced a nested transaction.'); -$assert(str_contains($batchBegin, - 'CloudPublicNetworkTransitionBatchPlan $plan') - && str_contains($batchBegin, '$item->state = \'queued\'') - && str_contains($batchBegin, '$item->child_job_id = $dispatch->jobId()'), - 'Batch transition seam no longer consumes only a caller-locked plan.'); -$ordered($reserve, [ - '$jobHint = CloudJob::where(', - '$existingParent = CloudJob::where(', - '$existingJob = CloudJob::where(', - '$instance = CloudInstance::where(', - '[$replayHost] = CloudPublicNetworkTransitionContext::lockHostBoundary(', - '$existing = CloudPublicNetworkTransition::where(', -]); -$assert(str_contains($source, - '(int) $parent->id !== (int) $command->parentJobId()') - && str_contains($source, - '(int) ($job->parent_job_id ?? 0)') - && str_contains($source, - '!== (int) $command->parentJobId()'), - 'Batch replay no longer binds the locked parent identity.'); -$ordered($reserve, [ - '$priorJob = CloudJob::where(', - '$instance = CloudInstance::where(', - '[$host, $agent] = CloudPublicNetworkTransitionContext::lockHostBoundary(', - '$active = CloudPublicNetworkTransition::where(', - '$resourcePool = CloudResourcePool::where(', - '$attachments = CloudHostNetworkAttachment::whereIn(', - '$pools = CloudPublicIpPool::whereIn(\'id\', $poolIds)', - '$reservation = CloudResourceReservation::where(', - '$allClaims = DB::table(\'cloud_resource_reservation_ips\')', - '$ips = CloudPublicIp::where(\'host_id\', (int) $instance->host_id)', -]); -foreach ([ - ['public static function markJobUncertain(', - 'public static function record('], - ['public static function record(', - 'public static function recoveryPayload('], -] as [$start, $end]) { - $ordered($method($evidenceSource, $start, $end), [ - '$instance = CloudInstance::where(', - 'CloudPublicNetworkTransitionContext::lockHostBoundary(', - '$transition = CloudPublicNetworkTransition::where(', - ]); -} -foreach ([ - ['public static function finishJobLocked(', - 'public static function publishPreparedLocked('], - ['public static function publishPreparedLocked(', - 'public static function retryPendingFinalization('], -] as [$start, $end]) { - $ordered($method($settlementSource, $start, $end), [ - '$instance = CloudInstance::where(', - 'CloudPublicNetworkTransitionContext::lockHostBoundary(', - '$transition = CloudPublicNetworkTransition::where(', - ]); -} -$retry = $method( - $settlementSource, - 'public static function retryPendingFinalization(', - 'private static function applyTargetLocked(' -); -$ordered($retry, [ - '$actor = User::where(\'id\', $userId)', - '$parent = $parentId > 0', - '$job = CloudJob::where(\'id\', $jobId)', - 'self::finishJobLocked(', -]); -$topology = $method( - $contextSource, - 'private static function lockFrozenTopologyLocked(', - 'private static function assertFrozenRowIdentity(' +$assert( + $productionCallers('CloudPublicNetworkTransitionSettlement') === $paths([ + 'app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php', + 'app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php', + ]), + 'Production code bypasses the transition workflow settlement facade.' +); +$assert( + $productionCallers('CloudPublicNetworkTransitionEvidence') === $paths([ + 'app/Services/Cloud/CloudPublicNetworkTransitionEvidence.php', + 'app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php', + 'app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php', + ]), + 'Production code bypasses the transition workflow evidence facade.' +); +$assert( + $productionCallers('CloudPublicNetworkTransitionContext') === $paths([ + 'app/Services/Cloud/CloudPublicNetworkTransitionContext.php', + 'app/Services/Cloud/CloudPublicNetworkTransitionEvidence.php', + 'app/Services/Cloud/CloudPublicNetworkTransitionSettlement.php', + 'app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php', + ]), + 'Production code bypasses the transition context boundary.' +); +$assert( + $productionCallers('CloudPublicNetworkTransitionWorkflow') === $paths([ + 'app/Controllers/CloudAdminInstanceController.php', + 'app/Controllers/CloudApiController.php', + 'app/Services/Cloud/CloudAutomaticOperationRecoveryService.php', + 'app/Services/Cloud/CloudOperationRecoveryService.php', + 'app/Services/Cloud/CloudPublicIpPoolReplacementBatchService.php', + 'app/Services/Cloud/CloudPublicNetworkTransitionWorkflow.php', + 'app/Services/Cloud/CloudWorkerService.php', + ]), + 'Production transition workflow callers escaped the approved facades.' +); +$assert( + $productionCallers('CloudPublicNetworkTransitionWorkflow::begin(') + === $paths([ + 'app/Controllers/CloudAdminInstanceController.php', + 'app/Controllers/CloudApiController.php', + ]), + 'Transition begin callers escaped the tenant and administrator seams.' ); -$ordered($topology, [ - '$attachments = CloudHostNetworkAttachment::whereIn(', - "->orderBy('id')->lockForUpdate()->get()", - '$pools = CloudPublicIpPool::where(', - "->whereIn('pool_key', \$poolKeys)->orderBy('id')", -]); -$assert(str_contains($source, "\$transition->state = 'reserved';") - && str_contains($source, "'active_claim' => null") - && str_contains($source, "'state' => 'reserved'") - && str_contains($source, "\$transition->state = 'queued';") - && strpos($source, "\$transition->state = 'reserved';") - < strpos($source, "\$transition->state = 'queued';"), - 'Transition must fence targets before atomically becoming queued.'); -$replayPosition = strpos($reserve, 'return self::replayLocked('); -$admissionPosition = strpos( - $reserve, - 'CloudPublicNetworkMutationAdmission::assertCanBegin($instance)' +$tenantController = file_get_contents( + $root . '/app/Controllers/CloudApiController.php' ); -$activeTransitionPosition = strpos( - $reserve, - "->where('active_transition', 1)->lockForUpdate()->first()" +$adminController = file_get_contents( + $root . '/app/Controllers/CloudAdminInstanceController.php' ); -$assert($replayPosition !== false && $admissionPosition !== false - && $activeTransitionPosition !== false - && $replayPosition < $admissionPosition - && $admissionPosition < $activeTransitionPosition, - 'Exact replay, shared admission, or locked transition recheck drifted.'); -$assert(str_contains($source, "(\$spec['managed'] ?? false) !== true") - && str_contains($source, - "(\$spec['os_source'] ?? null) !== 'cloud_template'"), - 'The deep workflow seam does not enforce managed cloud-template admission.'); -$assert(str_contains($source, "\$job->kind = 'network_change';") - && str_contains($source, - "\$job->public_network_transition_id = (int) \$transition->id;") - && str_contains($source, - "'public_network' => \$targetSnapshot->toArray()") - && str_contains($source, "'price_cents' => \$command->priceCents()") - && str_contains($source, "'charged_amount' => \$invoice === null") - && !str_contains($source, "'source_public_ip_id' =>") - && !str_contains($source, "'target_public_ip_id' =>"), - 'Queued job does not freeze the complete transition contract.'); -$assert(str_contains($billing, - 'CloudPublicNetworkTransitionCommand $command') - && str_contains($billing, "\$command->kind() !== 'user_paid'") - && str_contains($activeIdentity, - 'CloudPublicNetworkClaimSetIdentity::fromLedger('), - 'Billing or claim-set identity is not delegated through the deep seam.'); -$assert(str_contains($worker, 'markDispatched($job)') - && str_contains($worker, 'recordEvidence(') - && str_contains($worker, 'finishJobLocked(') - && str_contains($worker, 'markJobUncertain(') - && str_contains($recovery, 'publishPreparedLocked('), - 'Worker or recovery coordinator bypasses the Stage 4 transition seam.'); - -$allowedBeginCallers = [ - realpath($root . '/app/Controllers/CloudApiController.php'), - realpath($root . '/app/Controllers/CloudAdminInstanceController.php'), -]; -$actualBeginCallers = []; -foreach ([$root . '/app', $root . '/config'] as $directory) { - $iterator = new RecursiveIteratorIterator( - new RecursiveDirectoryIterator( - $directory, - FilesystemIterator::SKIP_DOTS +$assert( + is_string($tenantController) && is_string($adminController) + && str_contains( + $tenantController, + 'CloudPublicNetworkTransitionCommand::' ) - ); - foreach ($iterator as $file) { - if (!$file->isFile() || $file->getExtension() !== 'php' - || $file->getPathname() - === $root - . '/app/Services/Cloud/' - . 'CloudPublicNetworkTransitionWorkflow.php') { - continue; - } - $contents = file_get_contents($file->getPathname()); - if (is_string($contents) && str_contains( - $contents, - 'CloudPublicNetworkTransitionWorkflow::begin(' - )) { - $actualBeginCallers[] = realpath($file->getPathname()); - } - } -} -$actualBeginCallers = array_values(array_unique($actualBeginCallers)); -sort($actualBeginCallers); -sort($allowedBeginCallers); -$assert($actualBeginCallers === $allowedBeginCallers, - 'Production workflow callers escaped the two Stage 5 controller seams.'); -$assert(str_contains($tenantController, - 'CloudPublicNetworkTransitionCommand::') - && str_contains($tenantController, 'userPaidAutomatic(') - && str_contains($tenantController, - 'CloudPublicNetworkTransitionWorkflow::begin($command)') - && !str_contains($tenantController, - "CloudJobService::enqueue(\n \$instance,\n \$actor,\n 'network_change'") - && str_contains($adminController, - 'CloudPublicNetworkTransitionCommand::adminExact(') - && str_contains($adminController, - 'CloudPublicNetworkTransitionWorkflow::begin($command)'), - 'A Stage 5 controller bypasses the command plus transition seam.'); + && str_contains($tenantController, 'userPaidAutomatic(') + && str_contains( + $tenantController, + 'CloudPublicNetworkTransitionWorkflow::begin($command)' + ) + && str_contains( + $adminController, + 'CloudPublicNetworkTransitionCommand::adminExact(' + ) + && str_contains( + $adminController, + 'CloudPublicNetworkTransitionWorkflow::begin($command)' + ), + 'A controller bypasses the typed command plus transition facade.' +); echo "Public-network transition workflow contract tests passed.\n";