harden agent transport and degraded handle boundary

go-agent
admin 1 month ago
parent 42f6d6cf89
commit 44a227fa69

@ -22,7 +22,15 @@ shadow `CloudAgentRegistryHealthService`,以及按 host 解析 mTLS/HMAC clien
明确的 `resolveReadOnly()` 调用,避免把只读降级状态误用于电源/生命周期写操作。
它还核对请求的 `host_id`、`protocol_version=v1`、小写 SHA-256 客户端证书指纹,
并把本地 cert 文件的实际指纹与 registry 比对;HMAC/TLS 路径只存在于 resolver
的瞬时调用中,不进入 `CloudAgentHandle`。
的瞬时调用中,不进入 `CloudAgentHandle`。只读 handle 在类型上拒绝
`operation()`/`reconcile()`,不会因为调用方误用而向 degraded Agent 发写请求。
- `key_file` 必须是 regular、非 symlink、非 group/other writable 且没有任何
group/other 权限(通常为 `0600`/`0400`);CA/cert 至少拒绝 group/other 写和
超大/空文件。最终文件的祖先目录也必须是不可被 group/other 写入的真实目录;
解析后的路径不接受首尾空白、控制字符或相对路径。
- PHP transport 的 operation kind 先经过当前 v1 白名单;原始 `domain_define` 和
其他未实现 kind 在面板侧即被拒绝,不会穿透到 Agent。底层 raw `request()`
也不是公开扩展点,避免绕过该白名单直接 POST 任意 operation payload。
## Endpoint/SSRF 边界

@ -21,6 +21,17 @@ final class CloudAgentClient
private const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
/** @var list<string> */
private const SUPPORTED_OPERATION_KINDS = [
'capability_probe',
'domain_read',
'domain_power',
'seed_prepare',
'domain_preflight',
'domain_create_plan',
'domain_create_validate',
];
private ClientInterface $client;
private string $endpoint;
@ -37,6 +48,11 @@ final class CloudAgentClient
/** @var array{ca_file:string,cert_file:string,key_file:string} */
private array $tls;
private string $expectedCertificateFingerprint;
/** @var \Closure(string):string|null */
private \Closure $certificateFingerprintReader;
/**
* @param array{ca_file?:string,cert_file?:string,key_file?:string} $tls
* @param string $hmacKey decoded raw 32-byte key from a host-local secret resolver
@ -52,6 +68,8 @@ final class CloudAgentClient
float $timeoutSeconds = 15.0,
string $agentId = '',
array $resolvedAddresses = [],
string $expectedCertificateFingerprint = '',
?callable $certificateFingerprintReader = null,
) {
if ($timeoutSeconds < 1 || $timeoutSeconds > 900) {
throw new \InvalidArgumentException('Agent timeout is outside the supported range');
@ -59,7 +77,10 @@ final class CloudAgentClient
$this->endpoint = self::validateEndpoint($endpoint);
$this->hmacKey = $hmacKey;
$this->agentId = trim($agentId);
if ($agentId !== trim($agentId)) {
throw new CloudError('宿主机 Agent 身份无效', 422);
}
$this->agentId = $agentId;
if ($this->agentId !== '' && preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $this->agentId) !== 1) {
throw new CloudError('宿主机 Agent 身份无效', 422);
}
@ -72,6 +93,15 @@ final class CloudAgentClient
$this->timeoutSeconds = $timeoutSeconds;
$this->tls = self::validateTls($tls);
$this->resolvedAddresses = self::validateResolvedAddresses($resolvedAddresses);
if ($expectedCertificateFingerprint !== trim($expectedCertificateFingerprint)
|| ($expectedCertificateFingerprint !== ''
&& preg_match('/^[0-9a-f]{64}$/D', $expectedCertificateFingerprint) !== 1)) {
throw new CloudError('宿主机 Agent 客户端证书指纹无效', 503);
}
$this->expectedCertificateFingerprint = $expectedCertificateFingerprint;
$this->certificateFingerprintReader = \Closure::fromCallable(
$certificateFingerprintReader ?? [self::class, 'certificateFingerprint'],
);
$clientOptions = [
'connect_timeout' => 3,
@ -249,10 +279,11 @@ final class CloudAgentClient
): array {
self::assertOperationID($operationId);
self::assertIdempotencyKey($idempotencyKey);
if (preg_match('/^[a-z][A-Za-z0-9_.-]{0,47}$/D', $kind) !== 1) {
if (!in_array($kind, self::SUPPORTED_OPERATION_KINDS, true)) {
throw new CloudError('宿主机 Agent 操作类型无效', 422);
}
if ($target !== '' && (strlen($target) > 128 || preg_match('/[\x00-\x1F\x7F]/', $target) === 1)) {
if ($target !== '' && ($target !== trim($target) || strlen($target) > 128
|| preg_match('/[\x00-\x1F\x7F]/', $target) === 1)) {
throw new CloudError('宿主机 Agent 操作目标无效', 422);
}
return $this->request(
@ -299,7 +330,7 @@ final class CloudAgentClient
* @param array<string,mixed> $actor
* @param array<string,mixed>|null $payload
*/
public function request(
private function request(
string $method,
string $path,
array $actor = [],
@ -351,9 +382,12 @@ final class CloudAgentClient
unset($headers['Content-Type']);
}
$this->assertCertificateFingerprint();
$requestOptions = [
'headers' => $headers,
'body' => $body,
'connect_timeout' => 3,
'timeout' => $this->timeoutSeconds,
'http_errors' => false,
'allow_redirects' => false,
@ -425,6 +459,9 @@ final class CloudAgentClient
private static function validateEndpoint(string $endpoint): string
{
if ($endpoint !== trim($endpoint)) {
throw new CloudError('宿主机 Agent 地址无效', 422);
}
$endpoint = rtrim(trim($endpoint), '/');
if ($endpoint === '' || preg_match('/[\x00-\x20\x7F\\]/', $endpoint) === 1) {
throw new CloudError('宿主机 Agent 地址无效', 422);
@ -484,14 +521,59 @@ final class CloudAgentClient
$result = [];
foreach (['ca_file', 'cert_file', 'key_file'] as $key) {
$value = $tls[$key] ?? '';
if (!is_string($value) || preg_match('/[\x00-\x1F\x7F]/', $value) === 1) {
if (!is_string($value) || preg_match('/[\x00-\x1F\x7F]/', $value) === 1
|| ($value !== '' && ($value[0] !== '/' || $value !== trim($value)))) {
throw new CloudError('宿主机 Agent TLS 配置无效', 503);
}
$result[$key] = trim($value);
$result[$key] = $value;
}
return $result;
}
private function assertCertificateFingerprint(): void
{
if ($this->expectedCertificateFingerprint === '') {
return;
}
try {
$observed = ($this->certificateFingerprintReader)($this->tls['cert_file']);
} catch (\Throwable) {
$observed = null;
}
if (!is_string($observed)
|| preg_match('/^[0-9a-f]{64}$/D', $observed) !== 1
|| !hash_equals($this->expectedCertificateFingerprint, $observed)) {
throw new CloudError('宿主机 Agent 客户端证书指纹已变化', 503);
}
}
public static function certificateFingerprint(string $path): ?string
{
if ($path === '' || $path[0] !== '/' || trim($path) !== $path
|| preg_match('/[\x00-\x1F\x7F]/', $path) === 1
|| !function_exists('openssl_x509_read')
|| !function_exists('openssl_x509_fingerprint')) {
return null;
}
$stat = @lstat($path);
if (!is_array($stat)
|| (($stat['mode'] ?? 0) & 0170000) !== 0100000
|| (($stat['mode'] ?? 0) & 0022) !== 0
|| !isset($stat['size']) || (int) $stat['size'] < 1 || (int) $stat['size'] > 1024 * 1024) {
return null;
}
$contents = @file_get_contents($path);
if (!is_string($contents) || $contents === '' || strlen($contents) > 1024 * 1024) {
return null;
}
$certificate = @openssl_x509_read($contents);
if ($certificate === false) {
return null;
}
$fingerprint = @openssl_x509_fingerprint($certificate, 'sha256');
return is_string($fingerprint) ? strtolower($fingerprint) : null;
}
/** @param list<string> $addresses */
private static function validateResolvedAddresses(array $addresses): array
{

@ -7,6 +7,9 @@ final class CloudAgentEndpointPolicy
{
public static function validate(string $endpoint, ?callable $resolveHost = null): string
{
if ($endpoint !== trim($endpoint)) {
throw new CloudError('宿主机 Agent 地址必须为安全的 HTTPS 地址', 422);
}
$endpoint = rtrim(trim($endpoint), '/');
$parts = parse_url($endpoint);
if (!is_array($parts) || ($parts['scheme'] ?? '') !== 'https'

@ -5,18 +5,85 @@ namespace App\Services\Cloud;
/**
* A fully resolved, authenticated connection to one registered Go Agent.
*
* The handle deliberately exposes no endpoint secret or TLS material. A
* caller may use the client for an operation, while registry identity remains
* available for audit and operation routing.
* The handle deliberately exposes no endpoint secret or TLS material. An
* active handle may submit a whitelisted operation; a degraded handle is a
* read-only observation handle and rejects operation/reconcile calls. Registry
* identity remains available for audit and operation routing.
*/
final class CloudAgentHandle
{
public function __construct(
private CloudAgentClient $client;
public readonly bool $readOnly;
private function __construct(
public readonly int $hostId,
public readonly string $agentId,
public readonly string $protocolVersion,
public readonly string $certificateFingerprint,
public readonly CloudAgentClient $client,
CloudAgentClient $client,
bool $readOnly,
) {
if ($hostId < 1
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $agentId) !== 1
|| $protocolVersion !== 'v1'
|| preg_match('/^[0-9a-f]{64}$/D', $certificateFingerprint) !== 1) {
throw new \InvalidArgumentException('Invalid resolved Agent identity');
}
$this->client = $client;
$this->readOnly = $readOnly;
}
public static function fromResolved(
int $hostId,
string $agentId,
string $protocolVersion,
string $certificateFingerprint,
CloudAgentClient $client,
bool $readOnly = false,
): self {
return new self($hostId, $agentId, $protocolVersion, $certificateFingerprint, $client, $readOnly);
}
public function health(): array
{
return $this->client->health();
}
public function capabilities(array $actor): array
{
return $this->client->capabilities($actor);
}
public function agentTest(array $actor): array
{
return $this->client->agentTest($actor);
}
public function operation(
string $operationId,
string $idempotencyKey,
string $kind,
string $target,
array $payload,
array $actor,
): array {
if ($this->readOnly) {
throw new CloudError('降级宿主机 Agent 仅允许只读观察', 503);
}
return $this->client->operation($operationId, $idempotencyKey, $kind, $target, $payload, $actor);
}
public function getOperation(string $operationId, array $actor): array
{
return $this->client->getOperation($operationId, $actor);
}
public function reconcile(string $operationId, array $actor): array
{
if ($this->readOnly) {
throw new CloudError('降级宿主机 Agent 仅允许只读观察', 503);
}
return $this->client->reconcile($operationId, $actor);
}
}

@ -24,13 +24,16 @@ final class CloudAgentHostClientResolver
private \Closure $registry;
/**
* @var \Closure(string,string,string,array,float,string,list<string>):CloudAgentClient
* @var \Closure(string,string,string,array,float,array,string):CloudAgentClient
*/
private \Closure $clientFactory;
/** @var \Closure(string):string|null */
private \Closure $certificateFingerprint;
/** @var \Closure(string,bool):bool */
private \Closure $credentialPathValidator;
public function __construct(
?callable $registry = null,
private readonly ?CloudAgentSecretResolver $secrets = null,
@ -38,6 +41,7 @@ final class CloudAgentHostClientResolver
?callable $clientFactory = null,
private readonly float $timeoutSeconds = 15.0,
?callable $certificateFingerprint = null,
?callable $credentialPathValidator = null,
) {
if ($timeoutSeconds < 1.0 || $timeoutSeconds > 900.0) {
throw new \InvalidArgumentException('Agent timeout is outside the supported range');
@ -57,6 +61,7 @@ final class CloudAgentHostClientResolver
array $tls,
float $timeoutSeconds,
array $resolvedAddresses,
string $expectedCertificateFingerprint,
): CloudAgentClient {
return new CloudAgentClient(
$endpoint,
@ -66,10 +71,14 @@ final class CloudAgentHostClientResolver
$timeoutSeconds,
$agentId,
$resolvedAddresses,
$expectedCertificateFingerprint,
);
});
$this->certificateFingerprint = \Closure::fromCallable(
$certificateFingerprint ?? [self::class, 'readCertificateFingerprint'],
$certificateFingerprint ?? [CloudAgentClient::class, 'certificateFingerprint'],
);
$this->credentialPathValidator = \Closure::fromCallable(
$credentialPathValidator ?? [self::class, 'validateCredentialPath'],
);
}
@ -80,17 +89,17 @@ final class CloudAgentHostClientResolver
*/
public function resolve(int $hostId): CloudAgentHandle
{
return $this->resolveWithStatuses($hostId, ['active']);
return $this->resolveWithStatuses($hostId, ['active'], false);
}
/** Resolve an Agent for a read-only observation while it is degraded. */
public function resolveReadOnly(int $hostId): CloudAgentHandle
{
return $this->resolveWithStatuses($hostId, self::ACTIVE_STATUSES);
return $this->resolveWithStatuses($hostId, self::ACTIVE_STATUSES, true);
}
/** @param list<string> $allowedStatuses */
private function resolveWithStatuses(int $hostId, array $allowedStatuses): CloudAgentHandle
private function resolveWithStatuses(int $hostId, array $allowedStatuses, bool $readOnly): CloudAgentHandle
{
if ($hostId < 1) {
throw new CloudError('宿主机编号无效', 422);
@ -115,28 +124,43 @@ final class CloudAgentHostClientResolver
}
$row = $rows[0];
if ((int) ($row['host_id'] ?? 0) !== $hostId) {
$rawHostId = $row['host_id'] ?? null;
if ((is_int($rawHostId) && $rawHostId !== $hostId)
|| (is_string($rawHostId) && (!preg_match('/^[1-9][0-9]*$/D', $rawHostId)
|| (int) $rawHostId !== $hostId))
|| (!is_int($rawHostId) && !is_string($rawHostId))) {
throw new CloudError('宿主机 Go Agent 注册身份与宿主机不匹配', 503);
}
$agentId = trim((string) ($row['agent_id'] ?? ''));
if (!in_array((string) ($row['status'] ?? ''), $allowedStatuses, true)) {
$rawAgentId = $row['agent_id'] ?? null;
if (!is_string($rawAgentId) || $rawAgentId === trim($rawAgentId)) {
$agentId = is_string($rawAgentId) ? $rawAgentId : '';
} else {
throw new CloudError('宿主机 Go Agent 身份格式无效', 503);
}
$status = $row['status'] ?? null;
if (!is_string($status) || !in_array($status, $allowedStatuses, true)) {
throw new CloudError('宿主机 Go Agent 当前不可用', 503);
}
if ((string) ($row['protocol_version'] ?? '') !== 'v1') {
$protocolVersion = $row['protocol_version'] ?? null;
if (!is_string($protocolVersion) || $protocolVersion !== 'v1') {
throw new CloudError('宿主机 Go Agent 协议版本不受支持', 503);
}
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D', $agentId) !== 1) {
throw new CloudError('宿主机 Go Agent 身份无效', 503);
}
$fingerprint = (string) ($row['client_certificate_fingerprint'] ?? '');
if (preg_match('/^[0-9a-f]{64}$/D', $fingerprint) !== 1) {
$fingerprint = $row['client_certificate_fingerprint'] ?? null;
if (!is_string($fingerprint) || preg_match('/^[0-9a-f]{64}$/D', $fingerprint) !== 1) {
throw new CloudError('宿主机 Go Agent 客户端证书指纹无效', 503);
}
$resolvedAddresses = [];
try {
$rawEndpoint = $row['endpoint'] ?? null;
if (!is_string($rawEndpoint) || $rawEndpoint !== trim($rawEndpoint)) {
throw new CloudError('宿主机 Go Agent 地址无效', 422);
}
$endpoint = CloudAgentEndpointPolicy::validate(
(string) ($row['endpoint'] ?? ''),
$rawEndpoint,
function (string $host) use (&$resolvedAddresses): array {
$resolvedAddresses = $this->hostResolver->resolve($host);
return $resolvedAddresses;
@ -161,10 +185,12 @@ final class CloudAgentHostClientResolver
$tls = [];
foreach (['ca_file', 'cert_file', 'key_file'] as $key) {
$value = $material[$key] ?? null;
if (!is_string($value) || trim($value) === '' || preg_match('/[\x00-\x1F\x7F]/', $value) === 1) {
if (!is_string($value) || $value === '' || $value !== trim($value)
|| preg_match('/[\x00-\x1F\x7F]/', $value) === 1
|| !$this->isCredentialPathValid($value, $key === 'key_file')) {
throw new CloudError('宿主机 Go Agent mTLS 未配置', 503);
}
$tls[$key] = trim($value);
$tls[$key] = $value;
}
try {
$observedFingerprint = ($this->certificateFingerprint)($tls['cert_file']);
@ -185,6 +211,7 @@ final class CloudAgentHostClientResolver
$tls,
$this->timeoutSeconds,
array_values($resolvedAddresses),
$fingerprint,
);
} catch (CloudError $error) {
throw $error;
@ -195,12 +222,13 @@ final class CloudAgentHostClientResolver
throw new CloudError('宿主机 Go Agent client 类型无效', 503);
}
return new CloudAgentHandle(
return CloudAgentHandle::fromResolved(
$hostId,
$agentId,
'v1',
$fingerprint,
$client,
$readOnly,
);
}
@ -213,20 +241,59 @@ final class CloudAgentHostClientResolver
return is_array($row) ? $row : [];
}
private static function readCertificateFingerprint(string $path): ?string
private static function validateCredentialPath(string $path, bool $privateKey = false): bool
{
if (!function_exists('openssl_x509_read') || !function_exists('openssl_x509_fingerprint')) {
return null;
if ($path === '' || $path[0] !== '/' || trim($path) !== $path
|| preg_match('/[\x00-\x1F\x7F]/', $path) === 1) {
return false;
}
$contents = @file_get_contents($path);
if (!is_string($contents) || $contents === '') {
return null;
$stat = @lstat($path);
$mode = is_array($stat) ? (int) ($stat['mode'] ?? 0) : 0;
if (!is_array($stat)
|| ($mode & 0170000) !== 0100000
|| ($mode & 006000) !== 0
|| ($mode & 0022) !== 0
|| !isset($stat['size']) || (int) $stat['size'] < 1
|| (int) $stat['size'] > 1024 * 1024) {
return false;
}
$certificate = @openssl_x509_read($contents);
if ($certificate === false) {
return null;
if ($privateKey && ($mode & 0077) !== 0) {
return false;
}
if ($privateKey && function_exists('posix_geteuid')
&& isset($stat['uid']) && (int) $stat['uid'] !== 0
&& (int) $stat['uid'] !== (int) posix_geteuid()) {
return false;
}
// Do not trust a safe-looking leaf below a group/world-writable or
// symlinked directory. This keeps a later Guzzle open from being
// redirected by a replaceable parent during certificate rotation.
$directory = dirname($path);
while ($directory !== '/' && $directory !== '.') {
$directoryStat = @lstat($directory);
$directoryMode = is_array($directoryStat) ? (int) ($directoryStat['mode'] ?? 0) : 0;
if (!is_array($directoryStat)
|| ($directoryMode & 0170000) !== 0040000
|| ($directoryMode & 006000) !== 0
|| ($directoryMode & 0022) !== 0) {
return false;
}
$parent = dirname($directory);
if ($parent === $directory) {
break;
}
$directory = $parent;
}
return true;
}
private function isCredentialPathValid(string $path, bool $privateKey): bool
{
try {
return ($this->credentialPathValidator)($path, $privateKey);
} catch (\Throwable) {
return false;
}
$fingerprint = @openssl_x509_fingerprint($certificate, 'sha256');
return is_string($fingerprint) ? strtolower($fingerprint) : null;
}
}

@ -122,6 +122,12 @@ $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',
@ -156,4 +162,38 @@ try {
'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.');
}
}
echo "Cloud Agent transport contract checks passed.\n";

@ -55,8 +55,9 @@ $factory = static function (
array $tls,
float $timeout,
array $addresses,
string $expectedFingerprint,
) use (&$factoryCalls): CloudAgentClient {
$factoryCalls[] = compact('endpoint', 'hmacKey', 'agentId', 'tls', 'timeout', 'addresses');
$factoryCalls[] = compact('endpoint', 'hmacKey', 'agentId', 'tls', 'timeout', 'addresses', 'expectedFingerprint');
return new CloudAgentClient(
$endpoint,
$hmacKey,
@ -65,8 +66,10 @@ $factory = static function (
$timeout,
$agentId,
$addresses,
$expectedFingerprint,
);
};
$pathValidator = static fn (string $path, bool $privateKey = false): bool => true;
$resolver = new CloudAgentHostClientResolver(
fn (int $hostId): array => [$row()],
$secret,
@ -74,6 +77,7 @@ $resolver = new CloudAgentHostClientResolver(
$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'
@ -92,18 +96,23 @@ $assert(count($factoryCalls) === 1
$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 => [$rows, $message]) {
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)))
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 === 503,
$assert($error->getMessage() === $message && $error->httpStatus === ($expectedStatus ?? 503),
'Resolver returned an unexpected error for case: ' . $name);
}
}
@ -115,6 +124,7 @@ $degraded = new CloudAgentHostClientResolver(
$factory,
15.0,
static fn (string $path): string => str_repeat('a', 64),
$pathValidator,
);
try {
$degraded->resolve(103);
@ -122,15 +132,40 @@ try {
} catch (CloudError $error) {
$assert($error->httpStatus === 503, 'Degraded Agent returned an unexpected mutating status.');
}
$assert($degraded->resolveReadOnly(103)->agentId === 'agent-103',
$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)))
static fn (string $path): string => str_repeat('a', 64), $pathValidator))
->resolve(103);
throw new RuntimeException('Resolver accepted missing secret material.');
} catch (CloudError $error) {
@ -145,6 +180,7 @@ $badEndpointResolver = new CloudAgentHostClientResolver(
$factory,
15.0,
static fn (string $path): string => str_repeat('a', 64),
$pathValidator,
);
try {
$badEndpointResolver->resolve(103);

Loading…
Cancel
Save