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/CloudProtocolTest.php

181 lines
10 KiB
PHTML

<?php
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudMoney;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudOperationErrorCatalog;
use App\Services\Cloud\CloudAgentError;
use App\Services\Cloud\CloudAgentOperationReconciler;
use App\Services\Cloud\CloudWorkerService;
$assert = function ($condition, $message) { if (!$condition) { throw new RuntimeException($message); } };
$assert(CloudMoney::cents('9.99') + CloudMoney::cents('0.01') === 1000, 'Money arithmetic must be exact.');
$assert(CloudMoney::decimal(999999999999) === '9999999999.99', 'Maximum decimal value changed.');
foreach ([1.1, '-1', '1e3', '1.001', '01.00', '10000000000.00'] as $bad) {
try { CloudMoney::cents($bad); throw new RuntimeException('Invalid amount accepted.'); } catch (CloudError $expected) {}
}
$assert(CloudWorkerService::disposition(['status' => 'failed'], true) === 'uncertain', 'Unknown creation failure must not refund.');
$assert(CloudWorkerService::disposition(['status' => 'failed', 'safe_to_refund' => false], true) === 'uncertain', 'Explicitly unsafe creation failure must not refund.');
$assert(CloudWorkerService::disposition(['status' => 'failed', 'safe_to_refund' => true], true) === 'uncertain', 'A legacy refund hint bypassed managed-artifact absence evidence.');
$assert(CloudWorkerService::disposition([
'status' => 'failed',
'result' => ['creation_absent' => true],
], true) === 'uncertain',
'Create failure without managed-artifact evidence was refundable.');
$assert(CloudWorkerService::disposition([
'status' => 'failed',
'result' => [
'creation_absent' => true,
'managed_artifacts_absent' => true,
],
], true) === 'failed',
'Confirmed create absence did not become a terminal failure.');
$assert(CloudWorkerService::disposition([
'status' => 'succeeded', 'error_code' => 'reinstall_cleanup_pending',
'result' => ['reinstall_committed' => true, 'cleanup_pending' => true],
], false, 'reinstall') === 'uncertain',
'A committed reinstall with pending cleanup was reported as success.');
$assert(CloudWorkerService::disposition([
'status' => 'succeeded', 'result' => ['vm' => ['state' => 'running']],
], false, 'reinstall') === 'succeeded',
'A normal reinstall was changed to uncertain.');
$assert(CloudWorkerService::disposition([
'status' => 'succeeded',
'result' => [
'reinstall_committed' => true,
'cleanup_pending' => false,
],
], false, 'reinstall') === 'succeeded',
'A clean Agent reinstall result was changed to uncertain.');
$assert(CloudWorkerService::disposition([
'status' => 'failed',
'error_code' => 'reinstall_cleanup_pending',
'result' => ['reinstall_committed' => true, 'cleanup_pending' => true],
], false, 'reinstall') === 'uncertain',
'A failed envelope with a committed reinstall marker was replayable.');
$uncertainOperation = [
'operation_id' => 'operation-reconcile-failure',
'status' => 'uncertain',
];
$failingReconcilerClient = new class {
public function request(): array
{
throw new CloudAgentError(
'reconcile unavailable', 503, 'agent_disconnected', true, 503
);
}
};
$assert(CloudAgentOperationReconciler::ifUncertain(
$failingReconcilerClient,
'operation-reconcile-failure',
['user_id' => 1],
$uncertainOperation
) === $uncertainOperation,
'A failed reconciliation request downgraded an uncertain operation.');
foreach (['delete', 'reinstall', 'instance_settings',
'network_change', 'firewall_apply'] as $uncertainKind) {
$assert(CloudWorkerService::disposition([
'status' => 'uncertain', 'safe_to_refund' => true,
], false, $uncertainKind) === 'uncertain',
'An ambiguous ' . $uncertainKind
. ' operation was converted to a terminal failure.');
}
$normalizer = new ReflectionMethod(CloudWorkerService::class,
'normalizeAgentOperation');
$normalized = $normalizer->invoke(null, [
'status' => 'failed',
'cause_code' => 'storage_clone_failed',
'error' => ['code' => 'creation_absent', 'message' => '/srv/private'],
]);
$assert(($normalized['cause_code'] ?? null) === 'storage_clone_failed'
&& ($normalized['error_code'] ?? null) === 'creation_absent'
&& !isset($normalized['error']),
'Stable Agent cause code was lost while the free-form error was removed.');
foreach (['StorageCloneFailed', 'storage/clone', 'storage_clone_failed_'] as $badCause) {
$normalized = $normalizer->invoke(null, [
'status' => 'failed', 'cause_code' => $badCause,
]);
$assert(!isset($normalized['cause_code']),
'Malformed Agent cause code survived operation normalization.');
}
foreach (['shortA1!', 'longwithoutupper1!', 'ALLUPPERCASE!123', 'LongWithoutSymbol123',
'NoDigitsLong!Aa', "StrongPassword!1\n", 'Strong Password!123',
'StrongPassword!123含中文', str_repeat('a', 126) . 'A1!'] as $bad) {
try { CloudInput::password($bad); throw new RuntimeException('Weak guest password accepted.'); } catch (CloudError $expected) {}
}
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%*-_=+?';
$assert(CloudInput::ROOT_PASSWORD_ALPHABET === $alphabet
&& CloudInput::ROOT_PASSWORD_LENGTH === 32
&& CloudInput::ROOT_PASSWORD_MIN_LENGTH === 12
&& CloudInput::ROOT_PASSWORD_MAX_LENGTH === 128,
'PHP/Agent guest password contract drifted.');
$generated = [];
for ($index = 0; $index < 50; $index++) {
$password = CloudInput::password(null);
$generated[] = $password;
$assert(strlen($password) === 32
&& strspn($password, $alphabet) === 32
&& preg_match('/[A-Z]/', $password) === 1
&& preg_match('/[a-z]/', $password) === 1
&& preg_match('/[0-9]/', $password) === 1
&& preg_match('/[^A-Za-z0-9]/', $password) === 1,
'Generated guest password violates the uniform 32-character policy.');
}
$assert(count(array_unique($generated)) === 50
&& count(array_unique(array_map(static fn ($value) => substr($value, 0, 4), $generated))) > 1,
'Generated guest passwords repeat or retain a fixed prefix.');
$assert(strlen(CloudInput::password('Aa1!' . str_repeat('x', 124))) === 128,
'Guest manual password bounds wrong.');
$assert(CloudInput::publicIpCidr('203.0.113.10/24') === '203.0.113.10/24'
&& CloudInput::publicIpCidr('198.51.100.2/32') === '198.51.100.2/32',
'Network-change IPv4 CIDR validation rejected a valid public address.');
foreach (['203.0.113.10', '203.0.113.10/0', '203.0.113.10/33',
'2001:db8::10/64', '203.0.113.999/24', '203.0.113.10/24/1'] as $badCidr) {
try {
CloudInput::publicIpCidr($badCidr);
throw new RuntimeException('Invalid network-change CIDR accepted: ' . $badCidr);
} catch (CloudError $expected) {
$assert($expected->httpStatus === 422, 'Invalid network-change CIDR returned an unexpected status.');
}
}
$controllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/CloudAdminInstanceController.php');
$routesSource = file_get_contents(dirname(__DIR__) . '/config/routes_cloud.php');
$workerSource = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudWorkerService.php');
$adminInstanceTemplate = file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/cloud/instances.tpl');
$adminInstanceScript = file_get_contents(dirname(__DIR__) . '/public/cloud/admin-instances.js');
$assert(is_string($controllerSource) && str_contains($controllerSource, "CloudAccess::manage(\$actor)")
&& str_contains($controllerSource, "'network_change'")
&& str_contains($controllerSource, "'/network'")
&& is_string($routesSource)
&& str_contains($routesSource, "/admin/instances/{id:[0-9]+}/network-options")
&& is_string($workerSource) && str_contains($workerSource, "\$job->kind === 'network_change'")
&& str_contains($workerSource, "Agent 成功结果与预留公网 IP 不一致,必须人工核查"),
'Administrator network-change route lost its super-admin queue or post-Agent confirmation contract.');
$assert(is_string($adminInstanceTemplate)
&& str_contains($adminInstanceTemplate, '{if $admin_can_manage|default:false}')
&& str_contains($adminInstanceTemplate, 'admin-instance-network-controls')
&& str_contains($adminInstanceTemplate, 'name="public_ip_cidr"')
&& str_contains($adminInstanceTemplate, '<select')
&& str_contains($adminInstanceTemplate, 'data-network-options-empty')
&& !str_contains($adminInstanceTemplate, 'type="text" maxlength="64" autocomplete="off" spellcheck="false" placeholder="例如 216.236.1.20/24"')
&& is_string($adminInstanceScript)
&& !str_contains($adminInstanceScript, 'ADMIN_CAN_MANAGE')
&& !str_contains($adminInstanceScript, 'vm.can_manage')
&& str_contains($adminInstanceScript, '/network-options')
&& str_contains($adminInstanceScript, 'available_ips')
&& str_contains($adminInstanceScript, 'data-network-confirm-check')
&& str_contains($adminInstanceScript, 'data-network-refresh')
&& str_contains($adminInstanceScript, 'pollNetworkJob'),
'Administrator network controls must use a server-rendered permission boundary, an available-IP selector, explicit confirmation and durable job polling.');
$automaticName = CloudInput::generateInstanceName();
$assert(preg_match('/^vm-[abcdefghjkmnpqrstuvwxyz23456789]{6}$/D',
$automaticName) === 1
&& CloudInput::optionalName(null) === null
&& CloudInput::optionalName('') === null
&& CloudInput::optionalName('customer-vm') === 'customer-vm',
'Optional or generated instance-name policy drifted.');
$safe = CloudInput::safeResult(['uuid' => 'test', 'generated_password' => 'never-save', 'nested' => ['private_key' => 'secret', 'name' => 'safe']]);
$assert($safe === ['uuid' => 'test', 'nested' => ['name' => 'safe']], 'Secret entered durable job output.');
echo "Cloud money, password and Agent ambiguity checks passed.\n";
}