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

463 lines
20 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudAgentClient;
use App\Services\Cloud\CloudAgentError;
use App\Services\Cloud\CloudAgentGatewayEndpoint;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$gateway = CloudAgentGatewayEndpoint::normalize(
'http://127.0.0.1:8001/internal/agent/request'
);
$assert($gateway === 'http://127.0.0.1:8001/internal/agent/request',
'Loopback Agent gateway normalization changed.');
foreach ([
'http://203.0.113.10:8001/internal/agent/request',
'http://10.20.30.40:8001/internal/agent/request',
'http://localhost:8001/internal/agent/request',
'https://[::1]:8443/internal/agent/request',
'http://127.0.0.1:/internal/agent/request',
'http://127.0.0.1:8002/internal/agent/request',
'http://127.0.0.1:8001/other',
'http://user:pass@127.0.0.1:8001/internal/agent/request',
'http://127.0.0.1:8001/internal/agent/request?target=other',
] as $unsafe) {
try {
CloudAgentGatewayEndpoint::normalize($unsafe);
throw new RuntimeException('Unsafe Agent gateway accepted: ' . $unsafe);
} catch (InvalidArgumentException $error) {
// Expected.
}
}
$actor = [
'user_id' => 17,
'is_admin' => true,
'is_super_admin' => true,
'can_manage' => true,
'operation_id' => 'operation_12345678',
'session_id' => 'must-not-cross-host-boundary',
];
$body = '{"name":"测试"}';
$secret = 'test-secret-which-is-at-least-32-bytes';
$gatewaySecret = 'test-gateway-secret-at-least-32-bytes';
$nonce = '00112233445566778899aabbccddeeff';
foreach (["/v1/vms\\escape", '/v1/vms#fragment'] as $invalidTarget) {
try {
CloudAgentClient::headers('GET', $invalidTarget, '', $actor, $secret,
1800000000, $nonce);
throw new RuntimeException('Unsafe Agent request target was accepted.');
} catch (InvalidArgumentException $error) {
// Expected.
}
}
$headers = CloudAgentClient::headers('post', '/v1/vms?wait=1', $body,
$actor, $secret, 1800000000, $nonce);
$actorBase64 = strtr($headers['X-Virt-Actor'], '-_', '+/');
$actorBase64 .= str_repeat('=', (4 - strlen($actorBase64) % 4) % 4);
$decodedActor = json_decode(base64_decode($actorBase64, true), true, 32,
JSON_THROW_ON_ERROR);
$assert($decodedActor === [
'user_id' => 17,
'is_admin' => true,
'is_super_admin' => true,
'can_manage' => true,
'operation_id' => 'operation_12345678',
], 'Agent actor leaked panel session state or changed its typed contract.');
try {
CloudAgentClient::headers('GET', '/v1/operations/operation_12345678/inspect',
'', array_replace($actor, ['system_recovery' => true]), $secret,
1800000000, $nonce);
throw new RuntimeException(
'A normal caller forged the system recovery capability.'
);
} catch (InvalidArgumentException $error) {
// Expected: this capability is only constructed by the dedicated client
// path and can never be copied from a panel actor array.
}
$digest = hash('sha256', $body);
$canonical = "POST\n/v1/vms?wait=1\n{$digest}\n1800000000\n{$nonce}\n"
. $headers['X-Virt-Actor'];
$assert($headers['X-Virt-Content-SHA256'] === $digest
&& $headers['X-Virt-Signature'] === hash_hmac('sha256', $canonical, $secret)
&& $headers['X-Virt-Content-SHA256']
=== '827361636cbd9dfdb06cb0fc540ee89605f405bfd3e5dd36e2eec7d10908c600'
&& $headers['X-Virt-Actor']
=== 'eyJ1c2VyX2lkIjoxNywiaXNfYWRtaW4iOnRydWUsImlzX3N1cGVyX2FkbWluIjp0cnVlLCJjYW5fbWFuYWdlIjp0cnVlLCJvcGVyYXRpb25faWQiOiJvcGVyYXRpb25fMTIzNDU2NzgifQ'
&& $headers['X-Virt-Signature']
=== '9a3fd49fcedbe4d79f6bf8efc5c0867efb5b6d0bffdc9bca602d24507205dcd7',
'Agent inner HMAC contract changed.');
$history = [];
$handler = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'],
json_encode(['status' => 'ok', 'service' => 'virt-host-agent',
'version' => 'test'], JSON_THROW_ON_ERROR)),
new Response(401, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'unauthorized',
'message' => 'secret details',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(401, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'replayed_request',
'message' => 'request nonce has already been used',
'retryable' => false,
]], JSON_THROW_ON_ERROR)),
new Response(400, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'gateway_request_invalid',
'message' => 'Agent gateway request is invalid',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(503, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'agent_busy',
'message' => 'Agent control request was not dispatched',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(403, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'gateway_forbidden',
'message' => 'Agent gateway request is forbidden',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(403, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'forbidden',
'message' => 'administrator privileges are required',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(404, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'not_found',
'message' => 'endpoint not found',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(405, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'method_not_allowed',
'message' => 'method is not allowed',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(503, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'nonce_store_unavailable',
'message' => 'authentication state is unavailable',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
]], JSON_THROW_ON_ERROR)),
new Response(422, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'invalid_request',
'message' => 'request is invalid',
'retryable' => false,
]], JSON_THROW_ON_ERROR)),
new Response(422, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'invalid_request',
'message' => 'request is invalid',
'retryable' => false,
'dispatch_state' => 'not_dispatched',
'unexpected' => true,
]], JSON_THROW_ON_ERROR)),
new Response(503, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'operation_starting',
'message' => 'operation dispatch is already starting',
'retryable' => false,
'operation' => [
'operation_id' => 'operation_12345678',
'action' => 'create-vm',
'resource_id' => 'operation-resource-12345678',
'fingerprint' => str_repeat('a', 64),
'status' => 'reserved',
],
]], JSON_THROW_ON_ERROR)),
new Response(409, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'operation_failed',
'message' => 'private upstream detail',
'retryable' => false,
'operation' => [
'operation_id' => 'operation_12345678',
'action' => 'create-vm',
'resource_id' => 'operation-resource-12345678',
'fingerprint' => str_repeat('a', 64),
'status' => 'failed',
'cause_code' => 'storage_clone_failed',
'error' => ['code' => 'creation_absent'],
],
]], JSON_THROW_ON_ERROR)),
new Response(409, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'operation_failed',
'message' => 'private upstream detail',
'retryable' => false,
'operation' => [
'operation_id' => 'operation_12345678',
'action' => 'create-vm',
'resource_id' => 'operation-resource-12345678',
'fingerprint' => str_repeat('a', 64),
'status' => 'failed',
'cause_code' => 'StorageCloneFailed',
'error' => ['code' => 'creation_absent'],
],
]], JSON_THROW_ON_ERROR)),
new Response(409, ['Content-Type' => 'application/json'],
json_encode(['error' => [
'code' => 'resource_operation_blocked',
'message' => 'private blocker detail',
'retryable' => false,
'operation' => [
'operation_id' => 'operation_12345678',
'action' => 'create-vm',
'resource_id' => 'operation-resource-12345678',
'fingerprint' => str_repeat('a', 64),
'status' => 'failed',
'error' => ['code' => 'operation_not_dispatched'],
],
]], JSON_THROW_ON_ERROR)),
]);
$stack = HandlerStack::create($handler);
$stack->push(Middleware::history($history));
$client = new CloudAgentClient('42', $secret,
new Client(['handler' => $stack]), 20.0, $gateway, $gatewaySecret);
$health = $client->request('GET', '/v1/health', $actor);
$assert($health['service'] === 'virt-host-agent',
'Gateway-transported Agent health response did not round-trip.');
$wireRequest = $history[0]['request'];
$wireBody = (string) $wireRequest->getBody();
$envelope = json_decode($wireBody, true, 16, JSON_THROW_ON_ERROR);
$gatewayActor = $wireRequest->getHeaderLine('X-Virt-Actor');
$gatewayCanonical = "POST\n/internal/agent/request\n"
. hash('sha256', $wireBody) . "\n"
. $wireRequest->getHeaderLine('X-Virt-Timestamp') . "\n"
. $wireRequest->getHeaderLine('X-Virt-Nonce') . "\n" . $gatewayActor;
$assert($wireRequest->getMethod() === 'POST'
&& $wireRequest->getUri()->getPath() === '/internal/agent/request'
&& ($envelope['agent_id'] ?? null) === '42'
&& ($envelope['type'] ?? null) === 'request'
&& preg_match('/^[a-f0-9]{32}$/D', $envelope['id'] ?? '') === 1
&& ($envelope['method'] ?? null) === 'GET'
&& ($envelope['request_target'] ?? null) === '/v1/health'
&& ($envelope['body'] ?? null) === ''
&& isset($envelope['headers']['X-Virt-Signature'])
&& hash_equals(hash_hmac('sha256', $gatewayCanonical, $gatewaySecret),
$wireRequest->getHeaderLine('X-Virt-Signature')),
'PHP did not preserve the signed request inside an authenticated local gateway envelope.');
try {
$client->request('GET', '/v1/capabilities', $actor);
throw new RuntimeException('Agent authentication failure was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'unauthorized'
&& $error->httpStatus === 502 && !$error->retryable
&& $error->safeValidationFailure
&& !$error->safePreDispatchFailure
&& !str_contains($error->getMessage(), 'secret details'),
'Agent errors lost typed handling or exposed upstream detail.');
}
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException('Agent replay rejection was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'replayed_request'
&& !$error->safeValidationFailure
&& !$error->safePreDispatchFailure,
'Agent replay rejection incorrectly claimed the original request was not dispatched.');
}
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException('Gateway validation failure was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'gateway_request_invalid'
&& !$error->retryable && $error->safeValidationFailure
&& $error->agentHttpStatus === 400,
'Typed local gateway rejection was treated as an ambiguous dispatch.');
}
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException('Definitive pre-dispatch busy response was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'agent_busy'
&& $error->retryable && !$error->safeValidationFailure
&& $error->safePreDispatchFailure
&& $error->agentHttpStatus === 503,
'Strict non-retryable not-dispatched proof was not preserved as a zero-call result.');
}
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException('Gateway authentication failure was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'gateway_forbidden'
&& !$error->retryable && $error->safeValidationFailure
&& !$error->safePreDispatchFailure
&& $error->agentHttpStatus === 403,
'Gateway authentication rejection was not terminal pre-dispatch.');
}
foreach ([
['forbidden', 403],
['not_found', 404],
['method_not_allowed', 405],
] as [$code, $status]) {
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException("Terminal {$code} response was accepted.");
} catch (CloudAgentError $error) {
$assert($error->agentCode === $code
&& $error->agentHttpStatus === $status
&& $error->safeValidationFailure
&& !$error->safePreDispatchFailure,
"Terminal {$code} response lost its strict no-journal proof.");
}
}
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException('Nonce-store outage was accepted.');
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'nonce_store_unavailable'
&& $error->retryable && !$error->safeValidationFailure
&& $error->safePreDispatchFailure,
'Non-retryable Agent authentication-state failure lost its zero-call proof.');
}
foreach (['missing marker', 'unexpected field'] as $case) {
try {
$client->request('POST', '/v1/vms', $actor, ['operation_id' =>
'operation_12345678']);
throw new RuntimeException("Loose {$case} response was accepted.");
} catch (CloudAgentError $error) {
$assert($error->agentCode === 'invalid_request'
&& !$error->safeValidationFailure
&& !$error->safePreDispatchFailure,
"A {$case} envelope was accepted as definitive no-journal proof.");
}
}
$starting = $client->request('POST', '/v1/vms', $actor,
['operation_id' => 'operation_12345678']);
$assert(($starting['status'] ?? null) === 'reserved'
&& ($starting['retryable'] ?? null) === false
&& ($starting['error']['code'] ?? null) === 'operation_starting',
'An admission claimant loser was treated as definitively not dispatched.');
$journalFailure = $client->request('POST', '/v1/vms', $actor,
['operation_id' => 'operation_12345678']);
$assert(($journalFailure['status'] ?? null) === 'failed'
&& ($journalFailure['action'] ?? null) === 'create-vm'
&& ($journalFailure['resource_id'] ?? null)
=== 'operation-resource-12345678'
&& ($journalFailure['request_fingerprint'] ?? null)
=== str_repeat('a', 64)
&& ($journalFailure['cause_code'] ?? null) === 'storage_clone_failed'
&& ($journalFailure['error']['code'] ?? null) === 'creation_absent'
&& !isset($journalFailure['message']),
'A valid durable Agent cause code was lost or free-form detail escaped its envelope.');
$malformedCause = $client->request('POST', '/v1/vms', $actor,
['operation_id' => 'operation_12345678']);
$assert(($malformedCause['status'] ?? null) === 'failed'
&& !isset($malformedCause['cause_code']),
'A malformed durable Agent cause code crossed the PHP trust boundary.');
$outerCause = $client->request('POST', '/v1/vms', $actor,
['operation_id' => 'operation_12345678']);
$assert(($outerCause['status'] ?? null) === 'failed'
&& ($outerCause['cause_code'] ?? null) === 'resource_operation_blocked'
&& ($outerCause['error']['code'] ?? null) === 'operation_not_dispatched'
&& !isset($outerCause['message']),
'A stable outer Agent cause was lost or replaced the embedded terminal error.');
$recoveryHistory = [];
$recoveryHandler = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'], json_encode([
'operation_id' => 'operation_recovery_1234',
'operation_status' => 'failed',
'checked_at' => 1800000000,
'outcome' => 'uncertain',
'summary_code' => 'evidence_incomplete',
'effect_resolution' => 'inconclusive',
'abort_job' => ['available' => false],
'cleanup' => ['available' => false],
], JSON_THROW_ON_ERROR)),
]);
$recoveryStack = HandlerStack::create($recoveryHandler);
$recoveryStack->push(Middleware::history($recoveryHistory));
$recoveryClient = new CloudAgentClient('42', $secret,
new Client(['handler' => $recoveryStack]), 20.0, $gateway, $gatewaySecret);
$recovery = $recoveryClient->systemRecoveryRequest(
'GET', '/v1/operations/operation_recovery_1234/inspect',
'operation_recovery_1234'
);
$assert(($recovery['effect_resolution'] ?? null) === 'inconclusive'
&& count($recoveryHistory) === 1,
'The operation-bound system recovery request did not round-trip.');
$recoveryEnvelope = json_decode(
(string) $recoveryHistory[0]['request']->getBody(),
true,
16,
JSON_THROW_ON_ERROR
);
$innerActor = (string) ($recoveryEnvelope['headers']['X-Virt-Actor'] ?? '');
$innerActorBase64 = strtr($innerActor, '-_', '+/');
$innerActorBase64 .= str_repeat('=',
(4 - strlen($innerActorBase64) % 4) % 4);
$systemActor = json_decode(
base64_decode($innerActorBase64, true),
true,
16,
JSON_THROW_ON_ERROR
);
$assert($systemActor === [
'user_id' => 0,
'is_admin' => false,
'is_super_admin' => false,
'can_manage' => false,
'system_recovery' => true,
'operation_id' => 'operation_recovery_1234',
], 'System recovery did not use the exact least-privilege actor contract.');
foreach ([
['GET', '/v1/operations/another_operation_1234/inspect',
'operation_recovery_1234', null],
['POST', '/v1/vms', 'operation_recovery_1234',
['operation_id' => 'operation_recovery_1234']],
] as [$method, $target, $operationId, $payload]) {
try {
$recoveryClient->systemRecoveryRequest(
$method,
$target,
$operationId,
$payload
);
throw new RuntimeException(
'System recovery escaped its exact operation route.'
);
} catch (InvalidArgumentException $error) {
// Expected before any network request.
}
}
$assert(count($recoveryHistory) === 1,
'A mismatched system recovery route reached the gateway.');
echo "Agent outbound gateway and nested HMAC protocol contract passed.\n";