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

205 lines
8.1 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudAgentClient;
use App\Services\Cloud\CloudAgentHostClientResolver;
use App\Services\Cloud\CloudAgentHostResolver;
use App\Services\Cloud\CloudAgentSecretResolver;
use App\Services\Cloud\CloudError;
use GuzzleHttp\Client;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$row = static fn (array $overrides = []): array => array_replace([
'host_id' => 103,
'agent_id' => 'agent-103',
'endpoint' => 'https://agent.example.test:9443',
'protocol_version' => 'v1',
'client_certificate_fingerprint' => str_repeat('a', 64),
'status' => 'active',
], $overrides);
$secret = new class implements CloudAgentSecretResolver {
public array $requested = [];
public function resolve(string $agentId): ?array
{
$this->requested[] = $agentId;
return [
'hmac_key' => str_repeat('k', 32),
'ca_file' => '/run/virt-cloud/agent-ca.pem',
'cert_file' => '/run/virt-cloud/panel-agent.pem',
'key_file' => '/run/virt-cloud/panel-agent.key',
];
}
};
$hostResolver = new class implements CloudAgentHostResolver {
public array $requested = [];
public function resolve(string $hostname): array
{
$this->requested[] = $hostname;
return ['8.8.8.103'];
}
};
$factoryCalls = [];
$factory = static function (
string $endpoint,
string $hmacKey,
string $agentId,
array $tls,
float $timeout,
array $addresses,
string $expectedFingerprint,
) use (&$factoryCalls): CloudAgentClient {
$factoryCalls[] = compact('endpoint', 'hmacKey', 'agentId', 'tls', 'timeout', 'addresses', 'expectedFingerprint');
return new CloudAgentClient(
$endpoint,
$hmacKey,
new Client(),
$tls,
$timeout,
$agentId,
$addresses,
$expectedFingerprint,
);
};
$pathValidator = static fn (string $path, bool $privateKey = false): bool => true;
$resolver = new CloudAgentHostClientResolver(
fn (int $hostId): array => [$row()],
$secret,
$hostResolver,
$factory,
12.0,
static fn (string $path): string => str_repeat('a', 64),
$pathValidator,
);
$handle = $resolver->resolve(103);
$assert($handle->hostId === 103 && $handle->agentId === 'agent-103'
&& $handle->protocolVersion === 'v1'
&& $handle->certificateFingerprint === str_repeat('a', 64),
'A valid Agent registry row did not produce the expected identity handle.');
$assert($secret->requested === ['agent-103']
&& $hostResolver->requested === ['agent.example.test'],
'Resolver did not use the registered Agent identity and explicit host resolver.');
$assert(count($factoryCalls) === 1
&& $factoryCalls[0]['hmacKey'] === str_repeat('k', 32)
&& $factoryCalls[0]['addresses'] === ['8.8.8.103']
&& $factoryCalls[0]['tls']['key_file'] === '/run/virt-cloud/panel-agent.key',
'Resolved mTLS/HMAC material or pinned address did not reach the client factory.');
$cases = [
'missing' => [[], '宿主机尚未注册 Go Agent'],
'duplicate' => [[$row(), $row(['agent_id' => 'agent-103-b'])], '宿主机 Go Agent 注册身份不唯一'],
'host_type' => [[$row(['host_id' => 'not-an-id'])], '宿主机 Go Agent 注册身份与宿主机不匹配'],
'agent_whitespace' => [[$row(['agent_id' => ' agent-103'])], '宿主机 Go Agent 身份格式无效'],
'disabled' => [[$row(['status' => 'disabled'])], '宿主机 Go Agent 当前不可用'],
'protocol' => [[$row(['protocol_version' => 'v2'])], '宿主机 Go Agent 协议版本不受支持'],
'fingerprint' => [[$row(['client_certificate_fingerprint' => strtoupper(str_repeat('a', 64))])], '宿主机 Go Agent 客户端证书指纹无效'],
'endpoint_type' => [[$row(['endpoint' => 123])], '宿主机 Go Agent 地址无效', 422],
];
foreach ($cases as $name => $case) {
[$rows, $message] = $case;
$expectedStatus = $case[2] ?? 503;
try {
(new CloudAgentHostClientResolver(static fn (int $hostId): array => $rows, $secret, $hostResolver, $factory, 15.0,
static fn (string $path): string => str_repeat('a', 64), $pathValidator))
->resolve(103);
throw new RuntimeException('Resolver accepted invalid case: ' . $name);
} catch (CloudError $error) {
$assert($error->getMessage() === $message && $error->httpStatus === ($expectedStatus ?? 503),
'Resolver returned an unexpected error for case: ' . $name);
}
}
$degraded = new CloudAgentHostClientResolver(
static fn (int $hostId): array => [$row(['status' => 'degraded'])],
$secret,
$hostResolver,
$factory,
15.0,
static fn (string $path): string => str_repeat('a', 64),
$pathValidator,
);
try {
$degraded->resolve(103);
throw new RuntimeException('Mutating resolver accepted a degraded Agent.');
} catch (CloudError $error) {
$assert($error->httpStatus === 503, 'Degraded Agent returned an unexpected mutating status.');
}
$readOnlyHandle = $degraded->resolveReadOnly(103);
$assert($readOnlyHandle->agentId === 'agent-103' && $readOnlyHandle->readOnly,
'Read-only resolver did not allow a degraded Agent observation.');
try {
$readOnlyHandle->operation(
'11111111-1111-4111-8111-111111111111',
'degraded-read-only',
'capability_probe',
'host-103',
[],
[],
);
throw new RuntimeException('A degraded read-only handle accepted an operation.');
} catch (CloudError $error) {
$assert($error->httpStatus === 503, 'Degraded read-only handle returned an unexpected write status.');
}
$rejectingPathValidator = static fn (string $path, bool $privateKey = false): bool => false;
try {
(new CloudAgentHostClientResolver(static fn (int $hostId): array => [$row()], $secret, $hostResolver, $factory, 15.0,
static fn (string $path): string => str_repeat('a', 64), $rejectingPathValidator))
->resolve(103);
throw new RuntimeException('Resolver accepted credentials rejected by its path policy.');
} catch (CloudError $error) {
$assert($error->getMessage() === '宿主机 Go Agent mTLS 未配置' && $error->httpStatus === 503,
'Credential path policy did not fail closed.');
}
$missingSecret = new class implements CloudAgentSecretResolver {
public function resolve(string $agentId): ?array { return null; }
};
try {
(new CloudAgentHostClientResolver(static fn (int $hostId): array => [$row()], $missingSecret, $hostResolver, $factory, 15.0,
static fn (string $path): string => str_repeat('a', 64), $pathValidator))
->resolve(103);
throw new RuntimeException('Resolver accepted missing secret material.');
} catch (CloudError $error) {
$assert($error->getMessage() === '宿主机 Go Agent 请求签名密钥未配置',
'Missing Agent secret did not fail closed.');
}
$badEndpointResolver = new CloudAgentHostClientResolver(
static fn (int $hostId): array => [$row(['endpoint' => 'https://127.0.0.1'])],
$secret,
$hostResolver,
$factory,
15.0,
static fn (string $path): string => str_repeat('a', 64),
$pathValidator,
);
try {
$badEndpointResolver->resolve(103);
throw new RuntimeException('Resolver accepted a private Agent endpoint.');
} catch (CloudError $error) {
$assert($error->httpStatus === 422, 'Private Agent endpoint returned an unexpected status.');
}
$source = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudAgentHostClientResolver.php');
$handleSource = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudAgentHandle.php');
$assert($source !== false && $handleSource !== false
&& str_contains($source, 'CloudAgentEndpointPolicy::validate')
&& str_contains($source, 'resolveReadOnly')
&& !str_contains($source, 'CloudEngineClient')
&& !str_contains($source, 'private_key')
&& !str_contains($source, 'ssh')
&& !str_contains($handleSource, 'hmac_key')
&& !str_contains($handleSource, 'cert_file'),
'Agent resolver crossed the legacy SSH boundary or exposed secret material.');
echo "Cloud Agent host resolver contract checks passed.\n";