feat: assemble explicit Go Agent host resolver

go-agent
admin 1 month ago
parent 7721e8dd38
commit f01dfbcbe4

@ -0,0 +1,102 @@
<?php
namespace App\Services\Cloud;
use App\Services\Config;
/**
* Production assembly boundary for the panel's Go Agent resolver.
*
* The factory deliberately has only two host-side inputs: an explicit public
* address allowlist and a root-only secret directory. It never reads the
* legacy Engine settings, SSH credentials, or key material from a database.
* `fromConfig()` is the application entry point; `create()` keeps the same
* boundary deterministic for contract tests and deployment tooling.
*/
final class CloudAgentHostClientResolverFactory
{
private const DEFAULT_SECRET_DIRECTORY = '/run/virt-cloud/agents';
private const DEFAULT_TIMEOUT_SECONDS = 15.0;
/**
* Build a resolver from the panel configuration.
*
* The optional settings array is intentionally explicit and is useful for
* a fresh deployment/bootstrap test. When omitted, values are read via
* App\\Services\\Config only; no model or environment fallback is used.
*
* @param array<string,mixed>|null $settings
*/
public static function fromConfig(
?array $settings = null,
?callable $registry = null,
?callable $clientFactory = null,
?callable $certificateFingerprint = null,
?callable $credentialPathValidator = null,
): CloudAgentHostClientResolver {
if ($settings === null) {
$settings = [
'cloud_agent_secret_dir' => Config::get(
'cloud_agent_secret_dir', self::DEFAULT_SECRET_DIRECTORY,
),
'cloud_agent_address_allowlist' => Config::get(
'cloud_agent_address_allowlist', [],
),
'cloud_agent_timeout' => Config::get(
'cloud_agent_timeout', self::DEFAULT_TIMEOUT_SECONDS,
),
];
}
return self::create(
$settings,
$registry,
$clientFactory,
$certificateFingerprint,
$credentialPathValidator,
);
}
/**
* Create the resolver from already-decoded, non-secret deployment values.
*
* @param array<string,mixed> $settings
*/
public static function create(
array $settings,
?callable $registry = null,
?callable $clientFactory = null,
?callable $certificateFingerprint = null,
?callable $credentialPathValidator = null,
): CloudAgentHostClientResolver {
$directory = $settings['cloud_agent_secret_dir'] ?? self::DEFAULT_SECRET_DIRECTORY;
if (!is_string($directory)) {
throw new \InvalidArgumentException('Agent secret directory must be a string');
}
$allowlist = $settings['cloud_agent_address_allowlist'] ?? [];
if (!is_array($allowlist)) {
throw new \InvalidArgumentException('Agent address allowlist must be an array');
}
$timeout = $settings['cloud_agent_timeout'] ?? self::DEFAULT_TIMEOUT_SECONDS;
if (is_string($timeout) && is_numeric($timeout)) {
$timeout = (float) $timeout;
}
if ((!is_int($timeout) && !is_float($timeout)) || !is_finite((float) $timeout)) {
throw new \InvalidArgumentException('Agent timeout must be a finite number');
}
$secrets = new CloudAgentFileSecretResolver($directory);
$hostResolver = new CloudAgentStaticHostResolver($allowlist);
return new CloudAgentHostClientResolver(
$registry,
$secrets,
$hostResolver,
$clientFactory,
(float) $timeout,
$certificateFingerprint,
$credentialPathValidator,
);
}
}

@ -0,0 +1,108 @@
<?php
namespace App\Services\Cloud;
/**
* Resolve Agent endpoint hosts from an explicit, deployment-owned allowlist.
*
* This resolver intentionally has no DNS fallback. A missing or malformed
* entry returns an empty result (or rejects configuration at construction),
* allowing CloudAgentEndpointPolicy to fail closed before a socket is opened.
* Each hostname maps to one or more public IP literals; the transport will
* pin the request to a deterministic address while retaining the registered
* hostname for TLS SNI and HTTP Host validation.
*/
final class CloudAgentStaticHostResolver implements CloudAgentHostResolver
{
/** @var array<string,list<string>> */
private array $addressesByHost;
/**
* @param array<string,list<string>|string> $allowlist
*/
public function __construct(array $allowlist)
{
$normalized = [];
foreach ($allowlist as $hostname => $addresses) {
if (!is_string($hostname)) {
throw new \InvalidArgumentException('Agent address allowlist host must be a string');
}
$host = self::normalizeHost($hostname);
if ($host === '') {
throw new \InvalidArgumentException('Agent address allowlist host is invalid');
}
if (array_key_exists($host, $normalized)) {
throw new \InvalidArgumentException('Agent address allowlist contains duplicate hosts');
}
if (is_string($addresses)) {
$addresses = [$addresses];
}
if (!is_array($addresses) || $addresses === []) {
throw new \InvalidArgumentException('Agent address allowlist entry is empty');
}
$normalizedAddresses = [];
foreach ($addresses as $address) {
if (!is_string($address) || trim($address) !== $address
|| filter_var($address, FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
throw new \InvalidArgumentException('Agent address allowlist contains an unsafe IP');
}
$normalizedAddresses[] = $address;
}
$normalizedAddresses = array_values(array_unique($normalizedAddresses));
sort($normalizedAddresses, SORT_STRING);
$normalized[$host] = $normalizedAddresses;
}
$this->addressesByHost = $normalized;
}
/**
* @return list<string>
*/
public function resolve(string $hostname): array
{
$host = self::normalizeHost($hostname);
return $host === '' ? [] : ($this->addressesByHost[$host] ?? []);
}
/**
* Normalize a DNS name or IP literal without consulting the resolver
* stack. A trailing DNS root dot and IPv6 brackets are presentation
* details; all other whitespace, separators and wildcard forms are
* rejected.
*/
private static function normalizeHost(string $hostname): string
{
if ($hostname === '' || $hostname !== trim($hostname)
|| preg_match('/[\x00-\x20\x7F\/?#@\\]/', $hostname) === 1) {
return '';
}
$hostname = strtolower(trim($hostname));
if (str_ends_with($hostname, '.')) {
$hostname = substr($hostname, 0, -1);
if ($hostname === '' || str_ends_with($hostname, '.')) {
return '';
}
}
if (str_starts_with($hostname, '[') || str_ends_with($hostname, ']')) {
if (!str_starts_with($hostname, '[') || !str_ends_with($hostname, ']')) {
return '';
}
$hostname = substr($hostname, 1, -1);
}
if ($hostname === '' || strlen($hostname) > 253) {
return '';
}
if (filter_var($hostname, FILTER_VALIDATE_IP) !== false) {
return $hostname;
}
if (preg_match(
'/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/D',
$hostname,
) !== 1) {
return '';
}
return $hostname;
}
}

@ -45,6 +45,19 @@ $System_Config['cloud_engine_hmac_key'] = '';
$System_Config['cloud_payload_key'] = '';
$System_Config['cloud_engine_config_file'] = dirname(__DIR__, 2) . '/runtime/engine.json';
$System_Config['cloud_engine_data_dir'] = dirname(__DIR__, 2) . '/runtime/engine';
# Go Agent control-plane transport. The registry stores only endpoint,
# identity and certificate fingerprint; the following directory contains
# root-owned per-Agent files (<agent-id>.hmac/.ca.pem/.crt/.key). The HMAC
# file is canonical standard base64 for exactly 32 raw bytes. Do not put any
# of these values in the database or in a web-accessible directory.
$System_Config['cloud_agent_secret_dir'] = '/run/virt-cloud/agents';
$System_Config['cloud_agent_timeout'] = 15.0;
# Explicit public destination pinning for enrolled Agents. Every registry
# endpoint hostname must have an exact entry; the panel never performs ambient
# DNS resolution. Keep this list in deployment configuration, not in the DB.
$System_Config['cloud_agent_address_allowlist'] = [
// 'agent.example.com' => ['203.0.113.10'],
];
# 在线更新重启的 PHP-FPM unit;使用系统默认名称时无需修改。
$System_Config['cloud_update_php_fpm_unit'] = 'php-fpm.service';
# VNC 持续检查 PHP 会话。设为面板服务器本机可访问的网站 URL,不要指向宿主机。

@ -0,0 +1,119 @@
<?php
// Dependency-free contract for the explicit Agent destination and assembly
// boundary. It intentionally does not require PHP/Composer or a database.
require dirname(__DIR__) . '/app/Services/Cloud/CloudAgentHostResolver.php';
require dirname(__DIR__) . '/app/Services/Cloud/CloudAgentSecretResolver.php';
require dirname(__DIR__) . '/app/Services/Cloud/CloudAgentFileSecretResolver.php';
require dirname(__DIR__) . '/app/Services/Cloud/CloudAgentStaticHostResolver.php';
require dirname(__DIR__) . '/app/Services/Cloud/CloudAgentEndpointPolicy.php';
require dirname(__DIR__) . '/app/Services/Cloud/CloudAgentHostClientResolver.php';
require dirname(__DIR__) . '/app/Services/Cloud/CloudAgentHostClientResolverFactory.php';
require dirname(__DIR__) . '/app/Services/Config.php';
use App\Services\Cloud\CloudAgentFileSecretResolver;
use App\Services\Cloud\CloudAgentHostClientResolver;
use App\Services\Cloud\CloudAgentHostClientResolverFactory;
use App\Services\Cloud\CloudAgentStaticHostResolver;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$resolver = new CloudAgentStaticHostResolver([
'Agent.Example.Test.' => ['8.8.8.103', '2001:4860:4860::8888', '8.8.8.103'],
]);
$assert($resolver->resolve('agent.example.test') === ['2001:4860:4860::8888', '8.8.8.103'],
'The static resolver did not normalize, de-duplicate and sort explicit addresses.');
$assert($resolver->resolve('AGENT.EXAMPLE.TEST.') === $resolver->resolve('agent.example.test'),
'DNS-name case or the root dot changed the allowlist lookup.');
$assert($resolver->resolve('missing.example.test') === []
&& $resolver->resolve('agent/example.test') === [],
'Unknown or malformed hosts were not failed closed.');
foreach ([
['agent.example.test' => []],
['agent.example.test' => ['127.0.0.1']],
['agent.example.test' => ['192.0.2.10']],
['bad host' => ['8.8.8.8']],
['agent.example.test' => ['8.8.8.8'], 'AGENT.EXAMPLE.TEST.' => ['8.8.4.4']],
] as $invalidAllowlist) {
try {
new CloudAgentStaticHostResolver($invalidAllowlist);
throw new RuntimeException('Unsafe Agent address allowlist was accepted.');
} catch (InvalidArgumentException $expected) {
$assert($expected->getMessage() !== '', 'Allowlist rejection did not include a reason.');
}
}
$settings = [
'cloud_agent_secret_dir' => '/run/virt-cloud/agents',
'cloud_agent_address_allowlist' => ['agent.example.test' => ['8.8.8.103']],
'cloud_agent_timeout' => '12.5',
];
$testClientFactory = static function (...$arguments): mixed {
// The factory contract is tested before Composer/Guzzle is installed;
// actual transport construction is covered by CloudAgentClient tests.
return null;
};
$testFingerprint = static fn (string $path): string => str_repeat('a', 64);
$testPathValidator = static fn (string $path, bool $privateKey = false): bool => true;
$assembled = CloudAgentHostClientResolverFactory::create(
$settings,
null,
$testClientFactory,
$testFingerprint,
$testPathValidator,
);
$assert($assembled instanceof CloudAgentHostClientResolver,
'The Agent resolver factory did not return the typed resolver.');
$reflection = new ReflectionClass($assembled);
$hostProperty = $reflection->getProperty('hostResolver');
$hostProperty->setAccessible(true);
$secretProperty = $reflection->getProperty('secrets');
$secretProperty->setAccessible(true);
$configuredHostResolver = $hostProperty->getValue($assembled);
$configuredSecrets = $secretProperty->getValue($assembled);
$assert($configuredHostResolver instanceof CloudAgentStaticHostResolver
&& $configuredHostResolver->resolve('agent.example.test') === ['8.8.8.103'],
'Factory configuration did not install the explicit host resolver.');
$assert($configuredSecrets instanceof CloudAgentFileSecretResolver,
'Factory configuration did not install the file-backed secret resolver.');
$GLOBALS['System_Config'] = [
'cloud_agent_secret_dir' => '/run/virt-cloud/agents',
'cloud_agent_address_allowlist' => ['agent.example.test' => ['8.8.8.103']],
'cloud_agent_timeout' => 11,
];
$fromConfig = CloudAgentHostClientResolverFactory::fromConfig(
null,
null,
$testClientFactory,
$testFingerprint,
$testPathValidator,
);
$configReflection = new ReflectionClass($fromConfig);
$configHostProperty = $configReflection->getProperty('hostResolver');
$configHostProperty->setAccessible(true);
$configHost = $configHostProperty->getValue($fromConfig);
$assert($configHost instanceof CloudAgentStaticHostResolver
&& $configHost->resolve('agent.example.test') === ['8.8.8.103'],
'fromConfig() did not read the explicit address allowlist.');
$source = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudAgentStaticHostResolver.php');
$factorySource = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudAgentHostClientResolverFactory.php');
$assert(is_string($source) && is_string($factorySource)
&& !str_contains($source, 'gethostbyname')
&& !str_contains($source, 'dns_get_record')
&& !str_contains($source, 'getaddrinfo')
&& !str_contains($source, 'ssh')
&& !str_contains($source, 'Python')
&& str_contains($factorySource, 'CloudAgentFileSecretResolver')
&& str_contains($factorySource, 'CloudAgentStaticHostResolver')
&& !str_contains($factorySource, 'CloudEngineClient')
&& !str_contains($factorySource, 'ssh'),
'The Agent assembly boundary introduced ambient DNS or a legacy transport fallback.');
fwrite(STDOUT, "Cloud Agent static resolver contract passed.\n");
Loading…
Cancel
Save