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/CloudPlatformTestNetworkPol...

212 lines
7.8 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudPlatformTestPolicyRule;
use App\Models\CloudPlatformTestPolicyState;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudPlatformTestNetworkPolicy as Policy;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expect = static function (callable $callable, int $status,
string $message) use ($assert): void {
try {
$callable();
} catch (CloudError $error) {
$assert($error->httpStatus === $status,
$message . ' Unexpected status: ' . $error->httpStatus);
return;
}
throw new RuntimeException($message);
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_platform_test_policy_state', static function (
Blueprint $table): void {
$table->integer('id')->primary();
$table->integer('revision')->default(0);
$table->integer('updated_by')->nullable();
$table->integer('updated_at')->default(0);
});
$schema->create('cloud_platform_test_policy_rules', static function (
Blueprint $table): void {
$table->increments('id');
$table->string('rule_key', 32)->unique();
$table->string('service', 120);
$table->string('protocol', 8);
$table->integer('port_from');
$table->integer('port_to');
$table->string('direction', 8);
$table->string('reason', 500);
$table->integer('created_by');
$table->integer('updated_by');
$table->integer('deleted_by')->nullable();
$table->integer('deleted_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$state = new CloudPlatformTestPolicyState();
$state->id = 1;
$state->revision = 0;
$state->updated_by = null;
$state->updated_at = 0;
$state->save();
$manager = [
'user_id' => 1, 'is_admin' => true,
'is_super_admin' => true, 'can_manage' => true,
];
$regularAdmin = [
'user_id' => 2, 'is_admin' => true,
'is_super_admin' => false, 'can_manage' => false,
];
$input = [
'expected_revision' => 0,
'service' => 'Temporary web test',
'protocol' => 'tcp',
'port' => '8080',
'direction' => 'ingress',
'reason' => 'Verify one future-instance snapshot.',
];
$empty = Policy::page();
$defaultSnapshot = Policy::snapshotForProvisioning();
$assert($empty['revision'] === 0 && $empty['rules'] === []
&& $empty['base_expanded_rules'] === 26
&& $empty['available_expanded_rules'] === 44
&& $defaultSnapshot['catalog_revision'] === 0
&& count($defaultSnapshot['rules']) === 9
&& $defaultSnapshot['digest']
=== 'df7199f5f6ab5419403347be0c6fa7aee0009716d8b2111a36f8644ed59dc5bf',
'The empty catalog does not match the cross-language baseline snapshot.');
$lineTerminatorRules = $defaultSnapshot['rules'];
$lineTerminatorRules[] = [
'id' => 'test-' . str_repeat('1', 32),
'label' => "Line\u{2028}separator",
'category' => 'test',
'protocols' => ['tcp'],
'port_from' => 8080,
'port_to' => 8080,
'directions' => ['ingress'],
'reason' => "Paragraph\u{2029}separator",
];
$lineTerminatorSnapshot = [
'schema_version' => 1,
'base_policy_version' => 1,
'catalog_revision' => 7,
'rules' => $lineTerminatorRules,
'digest' => 'ffb4b8b3e09189d55180b280cde172e1dbbd83ef0965d27e2f8210cc6b20bb2f',
];
$assert(Policy::assertSnapshot($lineTerminatorSnapshot)
=== $lineTerminatorSnapshot,
'PHP snapshot encoding drifted from Python for U+2028/U+2029 text.');
$expect(static fn () => Policy::create($input, $regularAdmin), 403,
'A regular administrator changed the global test catalog.');
$created = Policy::create($input, $manager);
$ruleKey = (string) ($created['rules'][0]['id'] ?? '');
$assert($created['revision'] === 1
&& preg_match('/^[a-f0-9]{32}$/D', $ruleKey) === 1
&& $created['rules'][0]['port'] === '8080'
&& $created['available_expanded_rules'] === 43,
'Creating a test rule lost its revision, identity or expanded budget.');
$sealed = Policy::snapshotForProvisioning();
$assert($sealed['catalog_revision'] === 1
&& count($sealed['rules']) === 10
&& $sealed['rules'][9]['id'] === 'test-' . $ruleKey
&& Policy::assertSnapshot($sealed) === $sealed,
'The provisioning snapshot did not seal the active test rule.');
$expect(static fn () => Policy::update($ruleKey, array_replace($input, [
'expected_revision' => 0,
]), $manager), 409, 'A stale administrator revision overwrote the catalog.');
$expect(static fn () => Policy::create(array_replace($input, [
'expected_revision' => 1,
'service' => 'SMTP submission must remain open',
'port' => '587',
]), $manager), 422, 'TCP 587 was accepted into the restricted test catalog.');
$expect(static fn () => Policy::create(array_replace($input, [
'expected_revision' => 1,
'service' => 'Overlaps the static SMTP rule',
'port' => '25',
'direction' => 'egress',
]), $manager), 422, 'A test rule overlapped the immutable platform baseline.');
$updated = Policy::update($ruleKey, [
'expected_revision' => 1,
'service' => 'Temporary dual-stack protocol test',
'protocol' => 'tcp_udp',
'port' => '8080-8081',
'direction' => 'both',
'reason' => 'Exercise all protocol and direction combinations.',
], $manager);
$assert($updated['revision'] === 2
&& $updated['rules'][0]['protocol'] === 'tcp_udp'
&& $updated['rules'][0]['direction'] === 'both'
&& $updated['rules'][0]['port'] === '8080–8081'
&& $updated['available_expanded_rules'] === 40,
'Editing a rule did not replace its complete typed definition.');
$deleted = Policy::delete($ruleKey, ['expected_revision' => 2], $manager);
$afterDelete = Policy::snapshotForProvisioning();
$assert($deleted['revision'] === 3 && $deleted['rules'] === []
&& $afterDelete['catalog_revision'] === 3
&& count($afterDelete['rules']) === 9
&& $afterDelete['digest'] !== $sealed['digest']
&& Policy::assertSnapshot($sealed) === $sealed
&& CloudPlatformTestPolicyRule::count() === 1
&& CloudPlatformTestPolicyRule::first()->deleted_at !== null,
'Deleting a catalog rule altered a sealed historical snapshot or erased audit data.');
$sizeRevision = (int) $deleted['revision'];
$sizeAccepted = 0;
$sizeRejected = false;
for ($index = 0; $index < 44; $index++) {
try {
$catalog = Policy::create([
'expected_revision' => $sizeRevision,
'service' => str_repeat('S', 116) . sprintf('%04d', $index),
'protocol' => 'tcp',
'port' => (string) (30000 + $index),
'direction' => 'ingress',
'reason' => str_repeat('R', 500),
], $manager);
$sizeRevision = (int) $catalog['revision'];
$sizeAccepted++;
} catch (CloudError $error) {
$assert($error->httpStatus === 422
&& str_contains($error->getMessage(), '32 KiB'),
'An unrelated validation error masked the snapshot byte limit.');
$sizeRejected = true;
break;
}
}
$afterSizeRejection = Policy::page();
$boundedSnapshot = Policy::snapshotForProvisioning();
$assert($sizeRejected
&& $afterSizeRejection['revision'] === $sizeRevision
&& count($afterSizeRejection['rules']) === $sizeAccepted
&& Policy::assertSnapshot($boundedSnapshot) === $boundedSnapshot,
'An oversized catalog was committed or corrupted the last valid snapshot.');
$tampered = $sealed;
$tampered['digest'] = str_repeat('0', 64);
$expect(static fn () => Policy::assertSnapshot($tampered), 409,
'A tampered historical snapshot passed strict validation.');
echo "Platform test policy CRUD, validation and immutable snapshot contracts passed.\n";