You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/CloudVpcCreatePolicyTest.php

682 lines
33 KiB
PHTML

<?php
use App\Models\CloudPrivateNetwork;
use App\Models\CloudVpc;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudPrivateCidrAllocator;
use App\Services\Cloud\CloudVpcService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$root = dirname(__DIR__);
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
if (!is_file($root . '/vendor/autoload.php')) {
echo "VPC create policy runtime skipped (vendor missing).\n";
return;
}
require $root . '/vendor/autoload.php';
// Keep the test independent from a developer's local configuration while
// exercising the same bounded deployment setting used in production.
$System_Config = ['cloud_max_vpcs_per_account' => 5];
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id');
});
$schema->create('cloud_regions', static function (Blueprint $table): void {
$table->increments('id');
$table->string('code', 32)->unique();
$table->string('name', 80);
$table->string('country_code', 2)->nullable();
$table->string('status', 16);
$table->integer('sort')->default(0);
$table->unsignedBigInteger('created_at')->default(0);
$table->unsignedBigInteger('updated_at')->default(0);
});
$schema->create('cloud_region_fabrics', static function (Blueprint $table): void {
$table->increments('id');
$table->unsignedInteger('region_id')->unique();
$table->string('fabric_id', 64);
$table->string('fabric_region', 64);
$table->unsignedBigInteger('fabric_revision');
$table->string('state', 16);
$table->unsignedBigInteger('created_at')->default(0);
$table->unsignedBigInteger('updated_at')->default(0);
});
$schema->create('cloud_private_cidr_allocator_configs', static function (Blueprint $table): void {
$table->unsignedTinyInteger('id')->primary();
$table->string('pool_cidr', 18);
$table->unsignedTinyInteger('quantum_prefix_length');
$table->unsignedTinyInteger('min_prefix_length');
$table->unsignedTinyInteger('max_prefix_length');
$table->unsignedBigInteger('revision');
$table->unsignedBigInteger('updated_at');
});
$schema->create('cloud_private_cidr_claims', static function (Blueprint $table): void {
$table->increments('id');
$table->string('block_cidr', 18)->unique();
$table->string('allocation_key', 32);
$table->unsignedBigInteger('created_at');
$table->index(['allocation_key', 'block_cidr']);
});
$schema->create('cloud_private_networks', static function (Blueprint $table): void {
$table->increments('id');
$table->string('vpc_key', 32)->unique();
$table->string('allocation_key', 32)->unique();
$table->unsignedInteger('user_id');
$table->unsignedInteger('region_id');
$table->string('cidr', 18);
$table->string('requested_cidr', 18)->nullable();
$table->string('active_cidr', 18)->nullable()->unique();
$table->unsignedBigInteger('network_address');
$table->unsignedBigInteger('broadcast_address');
$table->unsignedTinyInteger('prefix_length');
$table->string('state', 16);
$table->unsignedBigInteger('revision');
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
$table->unsignedBigInteger('released_at')->nullable();
});
$schema->create('cloud_vpcs', static function (Blueprint $table): void {
$table->increments('id');
$table->string('vpc_key', 32)->unique();
$table->unsignedInteger('user_id');
$table->unsignedInteger('region_id');
$table->unsignedInteger('private_network_id')->unique();
$table->string('name', 63);
$table->string('cidr', 18);
$table->string('fabric_id', 64);
$table->string('fabric_region', 64);
$table->unsignedBigInteger('fabric_revision');
$table->unsignedInteger('max_members');
$table->string('state', 16);
$table->unsignedBigInteger('desired_revision');
$table->unsignedBigInteger('observed_revision');
$table->string('desired_digest', 64);
$table->string('observed_digest', 64)->nullable();
$table->string('sync_state', 16);
$table->string('last_operation_id', 32)->nullable();
$table->string('last_error_code', 64)->nullable();
$table->unsignedBigInteger('last_success_at')->default(0);
$table->unsignedBigInteger('last_failure_at')->default(0);
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
$table->index(['user_id', 'state', 'id']);
});
$schema->create('cloud_vpc_subnets', static function (Blueprint $table): void {
$table->increments('id');
$table->string('subnet_key', 32);
$table->unsignedInteger('vpc_id');
$table->string('cidr', 18);
$table->unsignedBigInteger('network_address');
$table->unsignedBigInteger('broadcast_address');
$table->unsignedTinyInteger('prefix_length');
$table->string('gateway_ip', 15)->nullable();
$table->string('state', 16);
$table->unsignedBigInteger('desired_revision');
$table->unsignedBigInteger('observed_revision');
$table->string('desired_digest', 64)->nullable();
$table->string('observed_digest', 64)->nullable();
$table->string('last_error_code', 64)->nullable();
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
$table->unique(['vpc_id', 'subnet_key']);
$table->unique(['vpc_id', 'cidr']);
});
$schema->create('cloud_vpc_private_ips', static function (Blueprint $table): void {
$table->increments('id');
$table->string('ip_key', 32);
$table->unsignedInteger('vpc_id');
$table->unsignedInteger('subnet_id');
$table->unsignedInteger('member_id')->nullable();
$table->unsignedInteger('instance_id')->nullable();
$table->string('private_ip', 15);
$table->unsignedBigInteger('private_ip_int');
$table->string('state', 16);
$table->unsignedBigInteger('desired_revision');
$table->unsignedBigInteger('observed_revision');
$table->string('desired_digest', 64)->nullable();
$table->string('observed_digest', 64)->nullable();
$table->string('last_error_code', 64)->nullable();
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
$schema->create('cloud_vpc_members', static function (Blueprint $table): void {
$table->increments('id');
$table->string('member_key', 32);
$table->unsignedInteger('vpc_id');
$table->unsignedInteger('subnet_id');
$table->unsignedInteger('private_ip_id')->nullable();
$table->unsignedInteger('instance_id');
$table->unsignedInteger('host_id');
$table->string('private_ip', 15);
$table->unsignedBigInteger('private_ip_int');
$table->string('state', 16);
$table->unsignedBigInteger('desired_revision');
$table->unsignedBigInteger('observed_revision');
$table->string('desired_digest', 64)->nullable();
$table->string('observed_digest', 64)->nullable();
$table->string('last_operation_id', 32)->nullable();
$table->string('last_error_code', 64)->nullable();
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
$schema->create('cloud_vpc_routes', static function (Blueprint $table): void {
$table->increments('id');
$table->string('route_key', 32);
$table->unsignedInteger('vpc_id');
$table->unsignedInteger('member_id');
$table->string('destination_cidr', 18);
$table->unsignedBigInteger('destination_int');
$table->unsignedBigInteger('broadcast_int');
$table->unsignedTinyInteger('prefix_length');
$table->string('next_hop_ip', 15);
$table->unsignedSmallInteger('metric');
$table->string('state', 16);
$table->unsignedBigInteger('desired_revision');
$table->unsignedBigInteger('observed_revision');
$table->string('desired_digest', 64)->nullable();
$table->string('observed_digest', 64)->nullable();
$table->string('last_error_code', 64)->nullable();
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
$schema->create('cloud_vpc_acl_rules', static function (Blueprint $table): void {
$table->increments('id');
$table->string('rule_key', 32);
$table->unsignedInteger('vpc_id');
$table->unsignedInteger('priority');
$table->string('direction', 8);
$table->string('action', 8);
$table->string('protocol', 8);
$table->string('source_cidr', 18);
$table->unsignedBigInteger('source_int');
$table->unsignedBigInteger('source_broadcast_int');
$table->unsignedTinyInteger('source_prefix_length');
$table->string('destination_cidr', 18);
$table->unsignedBigInteger('destination_int');
$table->unsignedBigInteger('destination_broadcast_int');
$table->unsignedTinyInteger('destination_prefix_length');
$table->unsignedSmallInteger('port_from')->nullable();
$table->unsignedSmallInteger('port_to')->nullable();
$table->string('state', 16);
$table->unsignedBigInteger('desired_revision')->default(1);
$table->unsignedBigInteger('observed_revision')->default(0);
$table->string('desired_digest', 64)->nullable();
$table->string('observed_digest', 64)->nullable();
$table->string('last_error_code', 64)->nullable();
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
});
$schema->create('cloud_vpc_host_deployments', static function (Blueprint $table): void {
$table->increments('id');
$table->unsignedInteger('vpc_id');
$table->unsignedInteger('host_id');
$table->unsignedBigInteger('fabric_revision')->default(0);
$table->string('state', 16);
$table->unsignedBigInteger('desired_revision');
$table->unsignedBigInteger('observed_revision');
$table->string('desired_digest', 64)->nullable();
$table->string('observed_digest', 64)->nullable();
$table->string('last_operation_id', 32)->nullable();
$table->string('last_error_code', 64)->nullable();
$table->unsignedBigInteger('last_success_at')->default(0);
$table->unsignedBigInteger('last_failure_at')->default(0);
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
$table->unique(['vpc_id', 'host_id']);
});
$schema->create('cloud_vpc_operations', static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id', 32)->unique();
$table->unsignedInteger('vpc_id');
$table->unsignedInteger('user_id');
$table->string('kind', 24);
$table->unsignedBigInteger('desired_revision');
$table->string('idempotency_key', 128);
$table->string('request_hash', 64);
$table->string('status', 24);
$table->text('payload_json');
$table->text('observed_json')->nullable();
$table->unsignedSmallInteger('evidence_version')->default(0);
$table->string('error_code', 64)->nullable();
$table->unsignedBigInteger('created_at');
$table->unsignedBigInteger('updated_at');
$table->unsignedBigInteger('finished_at')->nullable();
$table->string('lease_token', 32)->nullable();
$table->unsignedBigInteger('lease_until')->default(0);
$table->unsignedInteger('attempts')->default(0);
$table->unique(['vpc_id', 'idempotency_key']);
$table->unique(['vpc_id', 'desired_revision']);
});
$now = time();
Capsule::table('user')->insert(['id' => 7]);
Capsule::table('cloud_regions')->insert([
['id' => 1, 'code' => 'region-one', 'name' => 'Region One',
'status' => 'active', 'sort' => 1, 'created_at' => $now, 'updated_at' => $now],
]);
Capsule::table('cloud_region_fabrics')->insert([
'id' => 1, 'region_id' => 1, 'fabric_id' => 'fabric-one',
'fabric_region' => 'region-one', 'fabric_revision' => 7,
'state' => 'active', 'created_at' => $now, 'updated_at' => $now,
]);
Capsule::table('cloud_private_cidr_allocator_configs')->insert([
'id' => 1, 'pool_cidr' => '10.0.0.0/8', 'quantum_prefix_length' => 24,
'min_prefix_length' => 16, 'max_prefix_length' => 24,
'revision' => 1, 'updated_at' => $now,
]);
$actor = [
'user_id' => 7,
'is_admin' => false,
'is_super_admin' => false,
'can_manage' => false,
];
$create = static fn (string $name, int $regionId, string $requestKey): array =>
CloudVpcService::create($actor, [
'name' => $name,
'region_id' => $regionId,
'request_key' => $requestKey,
]);
$expectError = static function (
int $status,
callable $operation,
string $message
) use ($assert): CloudError {
try {
$operation();
} catch (CloudError $error) {
$assert($error->httpStatus === $status,
$message . ' returned HTTP ' . $error->httpStatus . ' instead of ' . $status . '.');
return $error;
}
throw new RuntimeException($message . ' did not fail.');
};
// The public create contract contains only stable tenant intent. Supplying a
// value equal to platform policy is still forbidden so callers cannot depend
// on or later widen an implementation detail.
$forbidden = [
'cidr' => '10.20.0.0/24',
'prefix_length' => 24,
'max_members' => 200,
'fabric_id' => 'fabric-one',
'fabric_revision' => 7,
'subnet_cidr' => '10.20.0.0/24',
'subnet_gateway' => null,
];
foreach ($forbidden as $field => $value) {
$input = [
'name' => 'strict-' . str_replace('_', '-', $field),
'region_id' => 1,
'request_key' => 'strict-' . str_replace('_', '-', $field),
$field => $value,
];
$expectError(422, static fn () => CloudVpcService::create($actor, $input),
'Tenant create accepted platform-owned field ' . $field);
}
$assert(Capsule::table('cloud_vpcs')->count() === 0
&& Capsule::table('cloud_private_networks')->count() === 0
&& Capsule::table('cloud_private_cidr_claims')->count() === 0,
'Rejected platform-owned fields changed durable VPC or CIDR state.');
$System_Config['cloud_max_vpcs_per_account'] = 0;
$expectError(503, static fn () => $create(
'invalid-quota', 1, 'invalid-quota-0001'
), 'An invalid account quota configuration was accepted');
$assert(Capsule::table('cloud_vpcs')->count() === 0
&& Capsule::table('cloud_private_networks')->count() === 0
&& Capsule::table('cloud_private_cidr_claims')->count() === 0,
'Invalid account quota configuration changed durable VPC or CIDR state.');
$System_Config['cloud_max_vpcs_per_account'] = 5;
$alphaInput = ['name' => 'alpha', 'region_id' => 1, 'request_key' => 'create-alpha-0001'];
Capsule::statement(
"CREATE TRIGGER cloud_vpc_create_failure_probe "
. "BEFORE INSERT ON cloud_vpc_subnets BEGIN "
. "SELECT RAISE(ABORT, 'forced subnet failure'); END"
);
$expectError(503, static fn () => CloudVpcService::create($actor, $alphaInput),
'A forced post-allocation create failure escaped as success');
$assert(Capsule::table('cloud_vpcs')->count() === 0
&& Capsule::table('cloud_private_networks')->count() === 0
&& Capsule::table('cloud_private_cidr_claims')->count() === 0
&& Capsule::table('cloud_vpc_operations')->count() === 0,
'A failed root transaction leaked its allocation, claim or operation.');
Capsule::statement('DROP TRIGGER cloud_vpc_create_failure_probe');
// A failure after the first default rule must roll the entire create back,
// including the allocator reservation and the already inserted rule.
Capsule::statement(
"CREATE TRIGGER cloud_vpc_default_acl_failure_probe "
. "BEFORE INSERT ON cloud_vpc_acl_rules WHEN NEW.direction = 'egress' BEGIN "
. "SELECT RAISE(ABORT, 'forced second default ACL failure'); END"
);
$expectError(503, static fn () => CloudVpcService::create($actor, $alphaInput),
'A failed default ACL insertion escaped as success');
$assert(Capsule::table('cloud_vpcs')->count() === 0
&& Capsule::table('cloud_private_networks')->count() === 0
&& Capsule::table('cloud_private_cidr_claims')->count() === 0
&& Capsule::table('cloud_vpc_subnets')->count() === 0
&& Capsule::table('cloud_vpc_acl_rules')->count() === 0
&& Capsule::table('cloud_vpc_operations')->count() === 0,
'A failed default ACL transaction leaked a root, allocation or partial ACL.');
Capsule::statement('DROP TRIGGER cloud_vpc_default_acl_failure_probe');
$alpha = CloudVpcService::create($actor, $alphaInput);
$alphaRoot = Capsule::table('cloud_vpcs')->where('vpc_key', $alpha['vpc']['vpc_key'])->first();
$alphaNetwork = $alphaRoot === null ? null : Capsule::table('cloud_private_networks')
->where('id', (int) $alphaRoot->private_network_id)->first();
$alphaSubnet = $alphaRoot === null ? null : Capsule::table('cloud_vpc_subnets')
->where('vpc_id', (int) $alphaRoot->id)->first();
$alphaSubnetCount = $alphaRoot === null ? 0 : Capsule::table('cloud_vpc_subnets')
->where('vpc_id', (int) $alphaRoot->id)->count();
$assert($alphaRoot !== null && $alphaNetwork !== null && $alphaSubnet !== null
&& $alphaSubnetCount === 1
&& (string) $alphaRoot->cidr === '10.0.0.0/24'
&& (int) $alphaRoot->max_members === CloudVpcService::DEFAULT_MAX_MEMBERS
&& (int) $alphaRoot->max_members === 200
&& (string) $alphaNetwork->cidr === (string) $alphaRoot->cidr
&& $alphaNetwork->requested_cidr === null
&& (int) $alphaNetwork->prefix_length === 24
&& (string) $alphaSubnet->cidr === (string) $alphaRoot->cidr
&& (int) $alphaSubnet->prefix_length === 24
&& $alphaSubnet->gateway_ip === null
&& Capsule::table('cloud_private_cidr_claims')
->where('allocation_key', (string) $alphaNetwork->allocation_key)->count() === 1,
'Automatic create did not persist one /24, the 200-member policy and a whole-CIDR subnet.');
$assertDefaults = static function (array $document) use ($assert): void {
$rules = $document['acl_rules'];
$assert(count($rules) === 2, 'A new VPC must have exactly two default ACL rules.');
$assert(array_column($rules, 'direction') === ['ingress', 'egress'],
'New VPC defaults did not cover both directions.');
$assert(count(array_unique(array_column($rules, 'priority'))) === 2,
'Default priorities conflict with the engine globally unique priority contract.');
foreach ($rules as $rule) {
$assert($rule['action'] === 'allow' && $rule['protocol'] === 'all'
&& $rule['source_cidr'] === $document['vpc']['cidr']
&& $rule['destination_cidr'] === $document['vpc']['cidr']
&& str_ends_with($rule['source_cidr'], '/24')
&& $rule['port_from'] === null && $rule['port_to'] === null
&& $rule['state'] === 'applying',
'A default ACL widened beyond its own /24, restricted traffic or claimed host success.');
}
$operation = Capsule::table('cloud_vpc_operations')
->where('operation_id', $document['vpc']['last_operation_id'])->first();
$payload = json_decode($operation->payload_json, true, 512, JSON_THROW_ON_ERROR);
$assert(count($payload['acls']) === 2, 'The initial desired revision omitted its default ACLs.');
foreach ($payload['acls'] as $rule) {
$assert($rule['protocol'] === 'any'
&& $rule['source_cidr'] === $document['vpc']['cidr']
&& $rule['destination_cidr'] === $document['vpc']['cidr']
&& !isset($rule['port_from']) && !isset($rule['port_to']),
'Default ACLs failed translation to the engine contract.');
}
};
$assertDefaults($alpha);
CloudVpcService::recordObserved(
$alpha['vpc']['vpc_key'], $alpha['vpc']['desired_revision'],
(string) $alphaRoot->desired_digest, [
'evidence_version' => CloudVpcService::OBSERVATION_EVIDENCE_VERSION,
'revision' => 0, 'digest' => null, 'state' => 'degraded',
'next_stage_allowed' => false, 'private_dataplane_verified' => false,
'fabric_gate' => ['active' => false, 'error_code' => 'vpc_no_members'],
'hosts' => [],
], $alpha['vpc']['last_operation_id']
);
$reserved = CloudVpcService::show($alpha['vpc']['vpc_key'], $actor);
$assert($reserved['vpc']['setup_state'] === 'awaiting_members'
&& $reserved['vpc']['usable'] === false
&& $reserved['vpc']['sync_state'] === 'applied'
&& Capsule::table('cloud_vpc_operations')
->where('operation_id', $alpha['vpc']['last_operation_id'])->value('status') === 'succeeded'
&& Capsule::table('cloud_vpc_acl_rules')->where('vpc_id', $alphaRoot->id)
->where('state', 'applying')->where('observed_revision', 0)->count() === 2,
'Initial default ACLs prevented empty-VPC reservation or were falsely marked installed.');
// Reserving the default policy does not excuse a changed or corrupt policy
// ledger when projecting a successful empty revision.
Capsule::table('cloud_vpc_acl_rules')->where('vpc_id', $alphaRoot->id)
->where('direction', 'ingress')->update(['destination_cidr' => '10.1.0.0/24']);
$assert(CloudVpcService::show($alpha['vpc']['vpc_key'], $actor)['vpc']['setup_state'] === null,
'A default ACL for another VPC bypassed the empty-reservation policy gate.');
Capsule::table('cloud_vpc_acl_rules')->where('vpc_id', $alphaRoot->id)
->where('direction', 'ingress')->update(['destination_cidr' => $alpha['vpc']['cidr']]);
$countsAfterAlpha = [
'vpcs' => Capsule::table('cloud_vpcs')->count(),
'networks' => Capsule::table('cloud_private_networks')->count(),
'claims' => Capsule::table('cloud_private_cidr_claims')->count(),
'operations' => Capsule::table('cloud_vpc_operations')->count(),
];
$alphaReplay = CloudVpcService::create($actor, $alphaInput);
$assert($alphaReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key']
&& $alphaReplay['acl_rules'] === $alpha['acl_rules']
&& Capsule::table('cloud_vpcs')->count() === $countsAfterAlpha['vpcs']
&& Capsule::table('cloud_private_networks')->count() === $countsAfterAlpha['networks']
&& Capsule::table('cloud_private_cidr_claims')->count() === $countsAfterAlpha['claims']
&& Capsule::table('cloud_vpc_operations')->count() === $countsAfterAlpha['operations'],
'An identical create replay duplicated its root, allocation, claim or operation.');
// Defaults are ordinary editable ACLs: a custom higher-priority deny may be
// retained alongside them, and later removal is never undone by create replay.
$customRules = array_map(static fn (array $rule): array => array_intersect_key(
$rule, array_flip(['rule_key', 'priority', 'direction', 'action', 'protocol',
'source_cidr', 'destination_cidr', 'port_from', 'port_to'])
), $alpha['acl_rules']);
$deny = $customRules[0];
$deny['rule_key'] = str_repeat('d', 32);
$deny['priority'] = 10;
$deny['action'] = 'deny';
$deny['protocol'] = 'tcp';
$deny['port_from'] = $deny['port_to'] = 22;
$customRules[] = $deny;
$custom = CloudVpcService::replaceAcl($alpha['vpc']['vpc_key'], $actor, [
'rules' => $customRules, 'request_key' => 'alpha-custom-acl-0001',
]);
$assert(count($custom['acl_rules']) === 3
&& $custom['acl_rules'][0]['rule_key'] === $deny['rule_key']
&& $custom['acl_rules'][0]['action'] === 'deny',
'A higher-priority custom deny could not be saved alongside the defaults.');
$customReplay = CloudVpcService::create($actor, $alphaInput);
$assert($customReplay['acl_rules'] === $custom['acl_rules'],
'A create replay overwrote edited ACLs.');
CloudVpcService::replaceAcl($alpha['vpc']['vpc_key'], $actor, [
'rules' => [], 'request_key' => 'alpha-remove-acl-0001',
]);
// Model the existing confirmed cleanup path; no default is special-cased.
Capsule::table('cloud_vpc_acl_rules')->where('vpc_id', $alphaRoot->id)
->where('state', 'deleting')->update(['state' => 'deleted']);
$removedReplay = CloudVpcService::create($actor, $alphaInput);
$assert(Capsule::table('cloud_vpc_acl_rules')->where('vpc_id', $alphaRoot->id)
->whereNotIn('state', ['deleted', 'deleting'])->count() === 0
&& count($removedReplay['acl_rules']) === 3,
'A create replay resurrected defaults after the owner deleted them.');
// Historical create hashes contained mutable platform policy. The committed
// root tuple and operation identity remain the compatibility proof.
$historicalHash = hash('sha256', 'historical-create-policy');
Capsule::table('cloud_vpc_operations')->where('vpc_id', (int) $alphaRoot->id)
->where('kind', 'vpc_create')->update(['request_hash' => $historicalHash]);
$historicalReplay = CloudVpcService::create($actor, $alphaInput);
$assert($historicalReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key'],
'A historical create-operation hash stopped an otherwise exact replay.');
// Early replay must retain the allocator's exact claim-ledger proof even
// though it intentionally does not consult mutable allocator policy.
$alphaClaim = Capsule::table('cloud_private_cidr_claims')
->where('allocation_key', (string) $alphaNetwork->allocation_key)->first();
$assert($alphaClaim !== null, 'The initial /24 claim fixture is missing.');
Capsule::table('cloud_private_cidr_claims')->where('id', (int) $alphaClaim->id)->delete();
$expectError(503, static fn () => CloudVpcService::create($actor, $alphaInput),
'A create replay accepted a missing live CIDR claim');
Capsule::table('cloud_private_cidr_claims')->insert([
'block_cidr' => (string) $alphaClaim->block_cidr,
'allocation_key' => (string) $alphaNetwork->allocation_key,
'created_at' => (int) $alphaClaim->created_at,
]);
// Replay must resolve from durable tenant intent before mutable platform
// readiness. A lost successful response stays recoverable during maintenance.
Capsule::table('cloud_region_fabrics')->where('region_id', 1)->update([
'fabric_revision' => 8, 'updated_at' => $now + 1,
]);
$revisionReplay = CloudVpcService::create($actor, $alphaInput);
Capsule::table('cloud_region_fabrics')->where('region_id', 1)->update([
'state' => 'inactive', 'updated_at' => $now + 2,
]);
$inactiveFabricReplay = CloudVpcService::create($actor, $alphaInput);
Capsule::table('cloud_regions')->where('id', 1)->update([
'status' => 'inactive', 'updated_at' => $now + 3,
]);
$inactiveRegionReplay = CloudVpcService::create($actor, $alphaInput);
$assert($revisionReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key']
&& $inactiveFabricReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key']
&& $inactiveRegionReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key']
&& (int) Capsule::table('cloud_vpcs')->where('id', $alphaRoot->id)
->value('fabric_revision') === 7,
'A mutable Fabric/region change broke replay or rewrote the committed root.');
$expectError(409, static fn () => CloudVpcService::create($actor, [
'name' => 'alpha-renamed', 'region_id' => 1,
'request_key' => $alphaInput['request_key'],
]), 'A create replay accepted name drift');
$expectError(409, static fn () => CloudVpcService::create($actor, [
'name' => 'alpha', 'region_id' => 2,
'request_key' => $alphaInput['request_key'],
]), 'A create replay accepted region drift');
Capsule::table('cloud_regions')->where('id', 1)->update([
'status' => 'active', 'updated_at' => $now + 4,
]);
Capsule::table('cloud_region_fabrics')->where('region_id', 1)->update([
'fabric_revision' => 8, 'state' => 'active', 'updated_at' => $now + 4,
]);
$quotaRoots = [];
foreach ([
['beta', 'create-beta-0001'],
['gamma', 'create-gamma-0001'],
['delta', 'create-delta-0001'],
['epsilon', 'create-epsilon-0001'],
] as [$name, $requestKey]) {
$quotaRoots[$name] = $create($name, 1, $requestKey);
$assertDefaults($quotaRoots[$name]);
$assert($quotaRoots[$name]['vpc']['cidr'] !== $alpha['vpc']['cidr'],
'A second VPC default accidentally shares the first VPC address range.');
}
Capsule::table('cloud_vpcs')
->where('vpc_key', $quotaRoots['epsilon']['vpc']['vpc_key'])
->update(['state' => 'deleting', 'updated_at' => $now + 5]);
$assert(Capsule::table('cloud_vpcs')->where('user_id', 7)
->where('state', '<>', 'deleted')->count() === 5,
'Quota fixture did not retain five non-deleted roots including deleting.');
$fullQuotaCounts = [
'vpcs' => Capsule::table('cloud_vpcs')->count(),
'networks' => Capsule::table('cloud_private_networks')->count(),
'claims' => Capsule::table('cloud_private_cidr_claims')->count(),
'operations' => Capsule::table('cloud_vpc_operations')->count(),
];
$fullQuotaReplay = CloudVpcService::create($actor, $alphaInput);
$assert($fullQuotaReplay['vpc']['vpc_key'] === $alpha['vpc']['vpc_key']
&& Capsule::table('cloud_vpcs')->count() === $fullQuotaCounts['vpcs']
&& Capsule::table('cloud_private_networks')->count() === $fullQuotaCounts['networks']
&& Capsule::table('cloud_private_cidr_claims')->count() === $fullQuotaCounts['claims']
&& Capsule::table('cloud_vpc_operations')->count() === $fullQuotaCounts['operations'],
'A committed create stopped being replayable after the account became full.');
$beforeQuotaFailure = [
'vpcs' => Capsule::table('cloud_vpcs')->count(),
'networks' => Capsule::table('cloud_private_networks')->count(),
'claims' => Capsule::table('cloud_private_cidr_claims')->count(),
'operations' => Capsule::table('cloud_vpc_operations')->count(),
];
$quotaError = $expectError(409, static fn () => $create(
'zeta', 1, 'create-zeta-0001'
), 'A sixth non-deleted VPC bypassed the account quota');
$assert(str_contains($quotaError->getMessage(), '5')
&& Capsule::table('cloud_vpcs')->count() === $beforeQuotaFailure['vpcs']
&& Capsule::table('cloud_private_networks')->count() === $beforeQuotaFailure['networks']
&& Capsule::table('cloud_private_cidr_claims')->count() === $beforeQuotaFailure['claims']
&& Capsule::table('cloud_vpc_operations')->count() === $beforeQuotaFailure['operations'],
'Quota rejection leaked a VPC, allocation, CIDR claim or operation.');
// Model a fully converged delete: the root tombstone remains for audit, while
// the allocator row and exact /24 claim have been safely released.
$betaRoot = CloudVpc::where('vpc_key', $quotaRoots['beta']['vpc']['vpc_key'])->firstOrFail();
$betaNetwork = CloudPrivateNetwork::where('id', (int) $betaRoot->private_network_id)->firstOrFail();
CloudPrivateCidrAllocator::release(
(string) $betaNetwork->allocation_key,
(int) $betaNetwork->revision
);
Capsule::table('cloud_vpc_subnets')->where('vpc_id', (int) $betaRoot->id)->delete();
$betaRoot->state = 'deleted';
$betaRoot->updated_at = $now + 6;
$betaRoot->save();
Capsule::table('cloud_private_cidr_claims')->insert([
'block_cidr' => (string) $betaNetwork->cidr,
'allocation_key' => (string) $betaNetwork->allocation_key,
'created_at' => $now + 6,
]);
$expectError(503, static fn () => $create(
'beta', 1, 'create-beta-0001'
), 'A deleted create replay accepted a residual released CIDR claim');
Capsule::table('cloud_private_cidr_claims')
->where('allocation_key', (string) $betaNetwork->allocation_key)->delete();
$beforeDeletedReplay = [
'vpcs' => Capsule::table('cloud_vpcs')->count(),
'networks' => Capsule::table('cloud_private_networks')->count(),
'claims' => Capsule::table('cloud_private_cidr_claims')->count(),
'operations' => Capsule::table('cloud_vpc_operations')->count(),
];
$betaReplay = $create('beta', 1, 'create-beta-0001');
$assert(($betaReplay['vpc']['state'] ?? null) === 'deleted'
&& $betaReplay['vpc']['vpc_key'] === $quotaRoots['beta']['vpc']['vpc_key']
&& Capsule::table('cloud_vpcs')->count() === $beforeDeletedReplay['vpcs']
&& Capsule::table('cloud_private_networks')->count() === $beforeDeletedReplay['networks']
&& Capsule::table('cloud_private_cidr_claims')->count() === $beforeDeletedReplay['claims']
&& Capsule::table('cloud_vpc_operations')->count() === $beforeDeletedReplay['operations'],
'A deleted create replay resurrected the root, allocation, claim or operation.');
$zeta = $create('zeta', 1, 'create-zeta-0001');
$assert($zeta['vpc']['vpc_key'] !== ''
&& Capsule::table('cloud_vpcs')->where('user_id', 7)
->where('state', '<>', 'deleted')->count() === 5
&& Capsule::table('cloud_private_networks')->where('state', 'released')->count() === 1
&& Capsule::table('cloud_private_cidr_claims')->count() === 5,
'A deleted root did not release one account slot and its exact CIDR claim.');
// A deterministic root without its create operation is not safe to replay:
// returning it would hide a partial commit or damaged audit trail.
$zetaRoot = Capsule::table('cloud_vpcs')->where('vpc_key', $zeta['vpc']['vpc_key'])->first();
$assert($zetaRoot !== null, 'The post-release quota create did not persist its root.');
Capsule::table('cloud_vpc_operations')->where('vpc_id', (int) $zetaRoot->id)
->where('kind', 'vpc_create')->delete();
$beforeBrokenReplay = [
'vpcs' => Capsule::table('cloud_vpcs')->count(),
'networks' => Capsule::table('cloud_private_networks')->count(),
'claims' => Capsule::table('cloud_private_cidr_claims')->count(),
];
$expectError(503, static fn () => $create(
'zeta', 1, 'create-zeta-0001'
), 'A create replay returned a root with a missing create-operation ledger');
$assert(Capsule::table('cloud_vpcs')->count() === $beforeBrokenReplay['vpcs']
&& Capsule::table('cloud_private_networks')->count() === $beforeBrokenReplay['networks']
&& Capsule::table('cloud_private_cidr_claims')->count() === $beforeBrokenReplay['claims'],
'A failed damaged-ledger replay changed VPC or CIDR state.');
echo "VPC create policy, quota and idempotency tests passed.\n";