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

133 lines
6.9 KiB
PHP

<?php
namespace App\Services {
final class Config
{
public static function get($key, $default = null) { return $default; }
}
}
namespace App\Services\Cloud {
final class CloudSecrets
{
public static function key(string $purpose): string { return str_repeat('k', 32); }
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInventoryRequestError;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
$assert = static function ($ok, string $message): void {
if (!$ok) { throw new \RuntimeException($message); }
};
$client = static function (array $replies, array &$history): CloudEngineClient {
$history = [];
$handler = HandlerStack::create(new MockHandler($replies));
$handler->push(Middleware::history($history));
return new CloudEngineClient(new Client(['handler' => $handler]), 8.0);
};
$actor = ['user_id' => 1, 'is_admin' => true, 'is_super_admin' => true];
$id = str_repeat('a', 32);
$history = [];
$engine = $client([new Response(200, [], '{"health":"healthy"}')], $history);
$assert($engine->hostInventory(1, 'host/capacity', $actor, $id)['health'] === 'healthy',
'Inventory response changed');
$request = $history[0]['request'];
$target = '/internal/v1/hosts/1/host/capacity?inventory_attempt_id=' . $id;
$expected = hash_hmac('sha256', CloudEngineClient::canonical('GET', $target, '',
$request->getHeaderLine('X-Cloud-Timestamp'), $request->getHeaderLine('X-Cloud-Nonce'),
$request->getHeaderLine('X-Cloud-Actor')), str_repeat('k', 32));
$assert($request->getRequestTarget() === $target
&& hash_equals($expected, $request->getHeaderLine('X-Cloud-Signature')),
'Correlation ID must be authenticated with the complete query');
$assert($history[0]['options']['timeout'] === 8.0
&& $history[0]['options']['connect_timeout'] === 3.0
&& $history[0]['options']['allow_redirects'] === false,
'Effective bounded inventory request options missing');
$cases = [
[new ConnectException('SECRET', new Request('GET', 'http://localhost'), null,
['errno' => 28]), 'engine_http_timeout', null, 502],
[new ConnectException('SECRET', new Request('GET', 'http://localhost'), null,
['errno' => 7]), 'engine_connect_failed', null, 502],
[new ConnectException('SECRET timed out', new Request('GET', 'http://localhost')),
'engine_connection_or_timeout', null, 502],
[new Response(302, [], '{"redirect":"SECRET"}'), 'engine_request_rejected', 302, 502],
[new Response(401, [], 'SECRET'), 'engine_auth_rejected', 401, 502],
[new Response(403, [], 'SECRET'), 'engine_auth_rejected', 403, 502],
[new Response(404, [], 'SECRET'), 'engine_resource_missing', 404, 502],
[new Response(404, [], '{"error":"SECRET"}'), 'engine_resource_missing', 404, 404],
[new Response(409, [], 'SECRET'), 'engine_request_conflict', 409, 502],
[new Response(423, [], 'SECRET'), 'engine_configuration_locked', 423, 502],
[new Response(429, [], 'SECRET'), 'engine_rate_limited', 429, 502],
[new Response(500, [], 'SECRET'), 'engine_service_error', 500, 502],
[new Response(504, [], 'SECRET'), 'engine_http_timeout', 504, 502],
[new Response(200, [], 'SECRET'), 'engine_response_invalid', 200, 502],
];
foreach ($cases as [$reply, $code, $upstream, $legacy]) {
$engine = $client([$reply], $history);
try {
$engine->hostInventory(1, 'host/network-options', $actor, $id);
throw new \RuntimeException('Expected inventory failure');
} catch (CloudInventoryRequestError $error) {
$assert($error->diagnosticCode === $code && $error->upstreamHttpStatus === $upstream
&& $error->httpStatus === $legacy && !str_contains($error->getMessage(), 'SECRET'),
'Incorrect safe inventory error classification: ' . $code);
$assert(count($history) === 1, 'Errors must not trigger fallback scans');
}
}
$trace = ['resource' => 'capacity', 'state' => 'running', 'stage' => 'update_lock_wait',
'error_code' => '', 'http_status' => null, 'started_at' => time(), 'finished_at' => null,
'duration_ms' => 8001, 'engine_version' => 'SECRET', 'raw_error' => 'SECRET',
'stages' => [['stage' => 'update_lock_wait', 'state' => 'running', 'duration_ms' => 8000]]];
$engine = $client([new Response(200, [], json_encode(['attempt_id' => $id,
'traces' => [$trace], 'password' => 'SECRET']))], $history);
$evidence = $engine->inventoryDiagnostics(1, $actor, $id);
$assert($evidence['traces'][0]['stage'] === 'update_lock_wait'
&& !str_contains(json_encode($evidence), 'SECRET')
&& $history[0]['options']['timeout'] === 1.0
&& $history[0]['options']['connect_timeout'] === 1.0
&& $history[0]['request']->getUri()->getPath()
=== '/internal/v1/hosts/1/host/inventory-diagnostics/' . $id,
'Evidence reads must be bounded, sanitized and separate from inventory');
foreach ([['attempt_id' => str_repeat('b', 32), 'traces' => [$trace]],
['attempt_id' => $id, 'traces' => [array_replace($trace, ['stage' => 'SECRET'])]]] as $invalid) {
$engine = $client([new Response(200, [], json_encode($invalid))], $history);
try {
$engine->inventoryDiagnostics(1, $actor, $id);
throw new \RuntimeException('Invalid evidence accepted');
} catch (CloudInventoryRequestError $error) {
$assert($error->diagnosticCode === 'engine_response_invalid', 'Evidence contract failed');
}
}
// General VM mutation handling must retain its original error boundary.
$engine = $client([new Response(423, [], '{"error":"SECRET"}')], $history);
try {
$engine->host(1, 'POST', 'vms/example/start', $actor, []);
throw new \RuntimeException('Expected mutation error');
} catch (CloudError $error) {
$assert($error->httpStatus === 502 && !str_contains($error->getMessage(), 'SECRET'),
'Inventory diagnostics changed mutation error semantics');
}
$engine = $client([new Response(302, [], '{"status":"ok","accepting_mutations":true}')],
$history);
try {
$engine->request('GET', '/internal/v1/health', $actor);
throw new \RuntimeException('Redirect-like engine response was accepted');
} catch (CloudError $error) {
$assert($error->httpStatus === 502 && count($history) === 1,
'A non-2xx engine response crossed the private client boundary.');
}
echo "Inventory engine diagnostics client checks passed.\n";
}