diff --git a/web/app/Services/Cloud/CloudAgentHostClientResolverFactory.php b/web/app/Services/Cloud/CloudAgentHostClientResolverFactory.php new file mode 100644 index 00000000..a2376696 --- /dev/null +++ b/web/app/Services/Cloud/CloudAgentHostClientResolverFactory.php @@ -0,0 +1,102 @@ +|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 $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, + ); + } +} diff --git a/web/app/Services/Cloud/CloudAgentStaticHostResolver.php b/web/app/Services/Cloud/CloudAgentStaticHostResolver.php new file mode 100644 index 00000000..73e24b34 --- /dev/null +++ b/web/app/Services/Cloud/CloudAgentStaticHostResolver.php @@ -0,0 +1,108 @@ +> */ + private array $addressesByHost; + + /** + * @param array|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 + */ + 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; + } +} diff --git a/web/config/.config.php.example b/web/config/.config.php.example index 30eb7c40..ac23352f 100644 --- a/web/config/.config.php.example +++ b/web/config/.config.php.example @@ -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 (.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,不要指向宿主机。 diff --git a/web/tests/CloudAgentStaticHostResolverContractTest.php b/web/tests/CloudAgentStaticHostResolverContractTest.php new file mode 100644 index 00000000..822bd4b7 --- /dev/null +++ b/web/tests/CloudAgentStaticHostResolverContractTest.php @@ -0,0 +1,119 @@ + ['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");