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

319 lines
12 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
namespace App\Services {
final class Config
{
public static function get($name, $default = null)
{
return $name === 'cloud_engine_url' ? 'http://127.0.0.1:8000' : $default;
}
}
final class AdminCsrf
{
public const HEADER_NAME = 'X-Admin-Csrf-Token';
public static function requiresProtection(string $method): bool
{
return !in_array(strtoupper($method), ['GET', 'HEAD', 'OPTIONS'], true);
}
public static function verify($request): bool
{
return true;
}
}
final class Auth
{
public static function getUser()
{
return null;
}
}
}
namespace App\Services\Cloud {
final class CloudSecrets
{
public static function key(string $purpose): string
{
return str_repeat('k', 32);
}
}
final class CloudAccess
{
public static function actor(bool $ensureSession = true): array
{
return ['user_id' => 1, 'is_admin' => true, 'can_manage' => true];
}
}
}
namespace GuzzleHttp\Exception {
class ConnectException extends \RuntimeException
{
}
}
namespace GuzzleHttp {
final class FabricAdmissionTestResponse
{
public function __construct(private int $status, private string $body)
{
}
public function getStatusCode(): int
{
return $this->status;
}
public function getBody(): string
{
return $this->body;
}
}
class Client
{
public function __construct(private array $responses = [])
{
}
public function request(string $method, string $url, array $options): FabricAdmissionTestResponse
{
$response = array_shift($this->responses);
if ($response instanceof \Throwable) {
throw $response;
}
if (!$response instanceof FabricAdmissionTestResponse) {
throw new \RuntimeException('No fake Fabric engine response was queued.');
}
return $response;
}
}
}
namespace {
use App\Middleware\CloudApi;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\FabricAdmissionTestResponse;
require dirname(__DIR__) . '/app/Services/Cloud/CloudError.php';
require dirname(__DIR__) . '/app/Services/Cloud/CloudEngineClient.php';
require dirname(__DIR__) . '/app/Middleware/CloudApi.php';
$assertions = 0;
$failures = [];
$assert = static function ($condition, string $message) use (&$assertions, &$failures): void {
$assertions++;
if (!$condition) {
$failures[] = $message;
}
};
$messages = [
'coordination_busy' => '协调资源正由原任务占用,本次请求未接纳;请先核对原操作。',
'coordination_uncertain' => '原任务结果尚未确认,本次请求未接纳;请先恢复原操作。',
];
$actor = ['user_id' => 1, 'is_admin' => true, 'can_manage' => true];
$body = static fn ($code): array => [
'error' => 'Traceback: host=/root/private key=secret', 'error_code' => $code,
];
$request = static function (string $method, string $path, int $status,
array $payload) use ($actor): CloudError {
$client = new CloudEngineClient(new Client([
new FabricAdmissionTestResponse($status, json_encode($payload, JSON_THROW_ON_ERROR)),
]));
try {
// Fabric admission has no caller-generated operation ID or receipt.
$client->request($method, $path, $actor, []);
} catch (CloudError $error) {
return $error;
}
throw new RuntimeException('The fake Fabric failure did not raise CloudError.');
};
// Only the exact mutation endpoints and bare 409 rejection cross this boundary.
foreach (['/internal/v1/fabric/apply', '/internal/v1/fabric/hk-1_2.3/reconcile',
'/internal/v1/fabric/1/reconcile', '/internal/v1/fabric/' . str_repeat('a', 64) . '/reconcile'] as $path) {
foreach ($messages as $code => $message) {
$error = $request('POST', $path, 409, $body($code));
$assert($error->httpStatus === 409 && $error->errorCode === $code
&& $error->getMessage() === $message
&& !str_contains($error->getMessage(), '/root')
&& !str_contains($error->getMessage(), 'secret'),
'A bare Fabric admission rejection lost its fixed status, code or message: ' . $code . ' ' . $path);
}
}
$invalidRoutes = [
['GET', '/internal/v1/fabric/apply'],
['PUT', '/internal/v1/fabric/apply'],
['DELETE', '/internal/v1/fabric/hk/reconcile'],
['POST', '/internal/v1/fabric'],
['POST', '/internal/v1/fabric/probe'],
['POST', '/internal/v1/fabric/hk'],
['POST', '/internal/v1/fabric/hk/reconcile/extra'],
['POST', '/internal/v1/fabric/hk/reconcile?unexpected=true'],
['POST', '/internal/v1/fabric/apply?unexpected=true'],
['POST', '/internal/v1/fabric//reconcile'],
['POST', '/internal/v1/fabric/-hk/reconcile'],
['POST', '/internal/v1/fabric/' . str_repeat('a', 65) . '/reconcile'],
['POST', '/internal/v1/vpcs/apply'],
];
foreach ($invalidRoutes as [$method, $path]) {
foreach (array_keys($messages) as $code) {
$error = $request($method, $path, 409, $body($code));
$assert($error->httpStatus === 502 && $error->errorCode === null
&& $error->getMessage() === '虚拟化操作未成功(引擎状态 409)',
'A method or path outside Fabric admission received a definitive rejection: ' . $method . ' ' . $path);
}
}
foreach ([400, 403, 404, 422, 500, 502, 503, 504] as $status) {
foreach (array_keys($messages) as $code) {
foreach (['/internal/v1/fabric/apply', '/internal/v1/fabric/hk/reconcile'] as $path) {
$error = $request('POST', $path, $status, $body($code));
$assert($error->httpStatus === ($status === 404 ? 404 : 502)
&& $error->errorCode === null
&& $error->getMessage() === '虚拟化操作未成功(引擎状态 ' . $status . ')',
'An unreviewed HTTP status became a Fabric admission rejection: ' . $status . ' ' . $code);
}
}
}
foreach (['coordination_unavailable', 'fabric_unknown_failure', '', null, ['coordination_busy']] as $code) {
$error = $request('POST', '/internal/v1/fabric/apply', 409, $body($code));
$assert($error->httpStatus === 502 && $error->errorCode === null,
'An unknown or malformed code crossed the Fabric admission allowlist.');
}
foreach ([
['operation_id' => str_repeat('b', 32)],
['operation' => ['id' => str_repeat('b', 32), 'status' => 'uncertain']],
['status' => 'uncertain'],
['safe_to_refund' => false],
['result' => ['command_accepted' => true]],
['mutation_started' => true],
['mutation_started' => false],
['execution_outcome' => 'unknown'],
['execution_outcome' => 'not_dispatched'],
['failure_phase' => 'apply'],
['extra' => null],
] as $extra) {
foreach (array_keys($messages) as $code) {
foreach (['/internal/v1/fabric/apply', '/internal/v1/fabric/hk/reconcile'] as $path) {
$error = $request('POST', $path, 409, array_replace($body($code), $extra));
$assert($error->httpStatus === 502 && $error->errorCode === null,
'An outcome or extra field was mistaken for a bare Fabric admission rejection: ' . array_key_first($extra));
}
}
}
foreach ([
new Client([new ConnectException('connection lost /root/private secret')]),
new Client([new RuntimeException('transport failed /root/private secret')]),
new Client([new FabricAdmissionTestResponse(502, '<html>bad gateway</html>')]),
new Client([new FabricAdmissionTestResponse(503, 'null')]),
] as $transportClient) {
try {
(new CloudEngineClient($transportClient))->request(
'POST', '/internal/v1/fabric/hk/reconcile', $actor, []
);
throw new RuntimeException('The fake Fabric transport failure did not raise CloudError.');
} catch (CloudError $error) {
$assert($error->httpStatus === 502 && $error->errorCode === 'engine_transport_uncertain'
&& !str_contains($error->getMessage(), '/root')
&& !str_contains($error->getMessage(), 'secret'),
'A real Fabric transport failure lost its unknown-outcome boundary.');
}
}
final class FabricAdmissionApiRequest
{
public function __construct(private string $method, private string $path)
{
}
public function getMethod(): string { return $this->method; }
public function getUri() { return new class($this->path) {
public function __construct(private string $path) {}
public function getPath(): string { return $this->path; }
}; }
public function getHeaderLine(string $name): string { return ''; }
public function getQueryParams(): array { return []; }
public function withHeader(string $name, string $value): self { return clone $this; }
public function withAttribute(string $name, $value): self { return clone $this; }
}
final class FabricAdmissionApiResponse
{
public array $payload = [];
public int $status = 200;
public array $headers = [];
public function withJson(array $payload, int $status): self
{
$response = clone $this;
$response->payload = $payload;
$response->status = $status;
return $response;
}
public function withHeader(string $name, string $value): self
{
$response = clone $this;
$response->headers[$name] = $value;
return $response;
}
}
$middleware = static function (string $method, string $path, int $status,
?string $code) use ($messages): FabricAdmissionApiResponse {
$error = new CloudError($messages[$code ?? ''] ?? '固定安全错误信息', $status, $code);
return (new CloudApi())(
new FabricAdmissionApiRequest($method, $path), new FabricAdmissionApiResponse(),
static function ($request, $response) use ($error) { throw $error; }
);
};
foreach (['/api/v1/admin/fabric/regions/1/apply', '/api/v1/admin/fabric/regions/42/reconcile'] as $path) {
foreach ($messages as $code => $message) {
$response = $middleware('POST', $path, 409, $code);
$assert($response->status === 409 && $response->payload === [
'error' => $message, 'detail' => $message, 'error_code' => $code,
] && ($response->headers['Cache-Control'] ?? null) === 'no-store',
'The exact Fabric route lost its safe admission-code projection: ' . $code . ' ' . $path);
}
}
foreach ([
['GET', '/api/v1/admin/fabric/regions/1/apply', 409, 'coordination_busy'],
['PUT', '/api/v1/admin/fabric/regions/1/reconcile', 409, 'coordination_uncertain'],
['POST', '/api/v1/admin/fabric/regions/0/reconcile', 409, 'coordination_busy'],
['POST', '/api/v1/admin/fabric/regions/01/reconcile', 409, 'coordination_busy'],
['POST', '/api/v1/admin/fabric/regions/1/probe', 409, 'coordination_busy'],
['POST', '/api/v1/admin/fabric/regions/1/reconcile/extra', 409, 'coordination_busy'],
['POST', '/api/v1/admin/fabric/regions/hk/reconcile', 409, 'coordination_busy'],
['POST', '/api/v1/admin/fabric', 409, 'coordination_busy'],
['POST', '/api/v1/vpcs/' . str_repeat('a', 32) . '/reconcile', 409, 'coordination_busy'],
['POST', '/api/v1/admin/fabric/regions/1/apply', 503, 'coordination_uncertain'],
['POST', '/api/v1/admin/fabric/regions/1/apply', 502, 'engine_transport_uncertain'],
['POST', '/api/v1/admin/fabric/regions/1/apply', 409, 'coordination_unavailable'],
['POST', '/api/v1/admin/fabric/regions/1/apply', 409, 'fabric_operation_busy'],
['POST', '/api/v1/admin/fabric/regions/1/apply', 409, null],
] as [$method, $path, $status, $code]) {
$response = $middleware($method, $path, $status, $code);
$message = $messages[$code ?? ''] ?? '固定安全错误信息';
$assert($response->status === $status
&& $response->payload === ['error' => $message, 'detail' => $message]
&& ($response->headers['Cache-Control'] ?? null) === 'no-store',
'An unrelated CloudApi error leaked a Fabric admission machine code: ' . $method . ' ' . $path);
}
if ($failures !== []) {
throw new RuntimeException(implode("\n", $failures));
}
echo 'Cloud Fabric admission error contracts passed (' . $assertions . " assertions).\n";
}