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

225 lines
9.5 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudAgentClient;
use App\Services\Cloud\CloudAgentHandle;
use App\Services\Cloud\CloudError;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$key = str_repeat('k', 32);
$tls = [
'ca_file' => '/tmp/agent-ca.pem',
'cert_file' => '/tmp/panel-agent.pem',
'key_file' => '/tmp/panel-agent.key',
];
$protocolEncodedKey = 'MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=';
$protocolKey = base64_decode($protocolEncodedKey, true);
$assert($protocolKey !== false && strlen($protocolKey) === 32
&& base64_encode($protocolKey) === $protocolEncodedKey,
'Agent HMAC fixture must be canonical base64 for exactly 32 raw bytes.');
$protocolBody = '{"ok":true}';
$protocolSignature = hash_hmac('sha256', CloudAgentClient::canonical(
'POST', '/v1/operations', $protocolBody, '1700000000', '0123456789abcdef', 'panel-agent',
), $protocolKey);
$assert($protocolSignature === 'cdaa0263ea55989caf519362660358ea67d78002ff428490d39734f0c7a1cb37',
'PHP HMAC fixture no longer matches the Go Agent protocol vector.');
$agentBoundSignature = hash_hmac('sha256', CloudAgentClient::canonicalForAgent(
'POST', '/v1/operations', hash('sha256', $protocolBody), '1700000000',
'0123456789abcdef', 'host-103', 'panel-agent',
), $protocolKey);
$assert($agentBoundSignature === '727720b3ed11cc15b2664cdb8c4bc1c2f7befa9742666815137cb281d873b41c',
'PHP agent-bound HMAC fixture no longer matches the Go Agent protocol.');
try {
new CloudAgentClient('https://agent.example.test', $protocolEncodedKey, new Client(), $tls);
throw new RuntimeException('Base64 HMAC file text was accepted as raw key material.');
} catch (CloudError $expected) {
$assert($expected->httpStatus === 503, 'Encoded HMAC key returned an unexpected status.');
}
$actor = [
'user_id' => 1,
'is_admin' => true,
'is_super_admin' => true,
'can_manage' => true,
'session_id' => 'agent-contract-test',
];
$operationId = '11111111-1111-4111-8111-111111111111';
$idempotencyKey = 'idem-contract-001';
$mock = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'], json_encode([
'status' => 'ok', 'readiness' => 'ready', 'protocol_version' => 'v1',
], JSON_THROW_ON_ERROR)),
new Response(200, ['Content-Type' => 'application/json'], '{"uefi_q35":true}'),
new Response(200, ['Content-Type' => 'application/json'], '{"uefi_q35":true}'),
new Response(200, ['Content-Type' => 'application/json'], json_encode([
'operation_id' => $operationId, 'status' => 'succeeded', 'version' => 2,
], JSON_THROW_ON_ERROR)),
new Response(200, ['Content-Type' => 'application/json'], json_encode([
'operation_id' => $operationId, 'status' => 'succeeded', 'version' => 2,
], JSON_THROW_ON_ERROR)),
new Response(409, ['Content-Type' => 'application/json'], json_encode([
'operation_id' => $operationId, 'status' => 'uncertain', 'version' => 3,
'error_message' => 'do not expose this text',
], JSON_THROW_ON_ERROR)),
]);
$history = [];
$stack = HandlerStack::create($mock);
$stack->push(Middleware::history($history));
$client = new CloudAgentClient(
'https://agent.example.test:9443',
$key,
new Client(['handler' => $stack, 'http_errors' => false]),
$tls,
15.0,
'host-1',
);
$assert(($client->health()['status'] ?? null) === 'ok', 'Agent health response was not decoded.');
$assert(($client->capabilities($actor)['uefi_q35'] ?? null) === true, 'Agent capabilities were not decoded.');
$client->agentTest($actor);
$client->operation($operationId, $idempotencyKey, 'capability_probe', 'host-1', ['read_only' => true], $actor);
$client->getOperation($operationId, $actor);
$reconciled = $client->reconcile($operationId, $actor);
$assert(($reconciled['status'] ?? null) === 'uncertain'
&& ($reconciled['_agent_http_status'] ?? null) === 409
&& !array_key_exists('error_message', $reconciled),
'Only the safe operation envelope crossed the Agent error boundary.');
$assert(count($history) === 6, 'Unexpected number of Agent requests.');
$healthRequest = $history[0]['request'];
$assert($healthRequest->getRequestTarget() === '/v1/health'
&& $healthRequest->getHeaderLine('X-Cloud-Signature') === '',
'Health must remain callable without a signing header.');
$operationRequest = $history[3]['request'];
$operationBody = (string) $operationRequest->getBody();
$actorHeader = $operationRequest->getHeaderLine('X-Cloud-Actor');
$agentIdHeader = $operationRequest->getHeaderLine('X-Cloud-Agent-ID');
$timestamp = $operationRequest->getHeaderLine('X-Cloud-Timestamp');
$nonce = $operationRequest->getHeaderLine('X-Cloud-Nonce');
$signature = $operationRequest->getHeaderLine('X-Cloud-Signature');
$assert($operationRequest->getRequestTarget() === '/v1/operations'
&& $operationRequest->getHeaderLine('X-Cloud-Request-ID') === $operationId
&& $operationRequest->getHeaderLine('X-Cloud-Idempotency-Key') === $idempotencyKey
&& $agentIdHeader === 'host-1'
&& hash('sha256', $operationBody) === $operationRequest->getHeaderLine('X-Cloud-Request-Hash')
&& hash_hmac('sha256', CloudAgentClient::canonicalForAgent(
'POST', '/v1/operations', hash('sha256', $operationBody), $timestamp, $nonce,
$agentIdHeader, $actorHeader,
), $key) === $signature,
'PHP Agent headers no longer match Go auth.Verifier canonical signing.');
$operation = json_decode($operationBody, true, 16, JSON_THROW_ON_ERROR);
$assert(($operation['operation_id'] ?? null) === $operationId
&& ($operation['idempotency_key'] ?? null) === $idempotencyKey,
'Operation identity was not sent in the v1 request body.');
try {
$client->operation($operationId, $idempotencyKey, 'domain_define', 'host-1', [], $actor);
throw new RuntimeException('The retired raw domain_define operation was accepted by PHP.');
} catch (CloudError $error) {
$assert($error->httpStatus === 422, 'Retired operation kind returned an unexpected status.');
}
foreach ([
'http://agent.example.test',
'ssh://agent.example.test',
'https://user:password@agent.example.test',
'https://agent.example.test/path',
'https://agent.example.test/?query=1',
] as $invalidEndpoint) {
try {
new CloudAgentClient($invalidEndpoint, $key, new Client(), $tls);
throw new RuntimeException('Unsafe Agent endpoint accepted: ' . $invalidEndpoint);
} catch (CloudError $expected) {
$assert($expected->httpStatus === 422, 'Unsafe endpoint returned an unexpected status.');
}
}
$errorClient = new CloudAgentClient(
'https://agent.example.test',
$key,
new Client(['handler' => HandlerStack::create(new MockHandler([
new Response(500, ['Content-Type' => 'application/json'], '{"error":"/etc/private-key leaked"}'),
])), 'http_errors' => false]),
$tls,
15.0,
'host-1',
);
try {
$errorClient->capabilities($actor);
throw new RuntimeException('Agent upstream failure was accepted.');
} catch (CloudError $error) {
$assert($error->httpStatus === 502 && !str_contains($error->getMessage(), '/etc/private-key'),
'Agent upstream details crossed the PHP error boundary.');
}
$mismatchClient = new CloudAgentClient(
'https://agent.example.test',
$key,
new Client(['handler' => HandlerStack::create(new MockHandler([new Response(200, [], '{}')]))]),
$tls,
15.0,
'host-1',
[],
str_repeat('a', 64),
static fn (string $path): string => str_repeat('b', 64),
);
try {
$mismatchClient->health();
throw new RuntimeException('A rotated client certificate fingerprint was accepted.');
} catch (CloudError $error) {
$assert($error->httpStatus === 503 && $error->getMessage() === '宿主机 Agent 客户端证书指纹已变化',
'Client certificate fingerprint drift did not fail closed.');
}
foreach ([
static fn (): CloudAgentClient => new CloudAgentClient('https://agent.example.test', $key, new Client(), $tls, 15.0, ' host-1'),
static fn (): CloudAgentClient => new CloudAgentClient('https://agent.example.test', $key, new Client(), [
'ca_file' => 'relative-ca.pem', 'cert_file' => '/tmp/panel-agent.pem', 'key_file' => '/tmp/panel-agent.key',
]),
] as $invalidFactory) {
try {
$invalidFactory();
throw new RuntimeException('CloudAgentClient accepted a non-canonical identity or TLS path.');
} catch (CloudError $error) {
$assert(in_array($error->httpStatus, [422, 503], true),
'Invalid direct Agent client configuration returned an unexpected status.');
}
}
$handle = CloudAgentHandle::fromResolved(
1,
'host-1',
'v1',
str_repeat('a', 64),
$client,
);
foreach (['client' => $client, 'handle' => $handle] as $label => $value) {
try {
serialize($value);
throw new RuntimeException('Cloud Agent ' . $label . ' unexpectedly became serializable.');
} catch (LogicException $error) {
$assert($error->getMessage() !== '',
'Cloud Agent ' . $label . ' serialization rejection was empty.');
}
try {
$value->__unserialize([]);
throw new RuntimeException('Cloud Agent ' . $label . ' unexpectedly accepted unserialization.');
} catch (LogicException $error) {
$assert($error->getMessage() !== '',
'Cloud Agent ' . $label . ' unserialization rejection was empty.');
}
}
echo "Cloud Agent transport contract checks passed.\n";