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/app/Services/Cloud/CloudAgentHostClientResolve...

308 lines
12 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudAgent;
/**
* Resolve a panel host to exactly one enrolled Go Agent.
*
* This is the only non-shadow panel-side construction boundary for an Agent
* client. It never consults CloudHost, old engine settings, encrypted
* database values or SSH credentials. Registry rows are identity metadata;
* HMAC/TLS material is supplied by a separate root-only secret provider.
* CloudAgentRegistryHealthService uses the same resolver policies for health
* probes, but keeps its bounded liveness response separate from operation
* dispatch.
*/
final class CloudAgentHostClientResolver
{
private const ACTIVE_STATUSES = ['active', 'degraded'];
/**
* @var \Closure(int):iterable<array|object>
*/
private \Closure $registry;
/**
* @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,
private readonly ?CloudAgentHostResolver $hostResolver = null,
?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');
}
$this->registry = \Closure::fromCallable($registry ?? static function (int $hostId): iterable {
try {
return CloudAgent::query()->where('host_id', $hostId)->get()->all();
} catch (\Throwable) {
return [];
}
});
$this->clientFactory = \Closure::fromCallable($clientFactory ?? static function (
string $endpoint,
string $hmacKey,
string $agentId,
array $tls,
float $timeoutSeconds,
array $resolvedAddresses,
string $expectedCertificateFingerprint,
): CloudAgentClient {
return new CloudAgentClient(
$endpoint,
$hmacKey,
null,
$tls,
$timeoutSeconds,
$agentId,
$resolvedAddresses,
$expectedCertificateFingerprint,
);
});
$this->certificateFingerprint = \Closure::fromCallable(
$certificateFingerprint ?? [CloudAgentClient::class, 'certificateFingerprint'],
);
$this->credentialPathValidator = \Closure::fromCallable(
$credentialPathValidator ?? [self::class, 'validateCredentialPath'],
);
}
/**
* Resolve an Agent for a mutating control-plane operation. A degraded
* registration is intentionally rejected here; callers that only need a
* liveness/read-only observation must opt into resolveReadOnly().
*/
public function resolve(int $hostId): CloudAgentHandle
{
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, true);
}
/** @param list<string> $allowedStatuses */
private function resolveWithStatuses(int $hostId, array $allowedStatuses, bool $readOnly): CloudAgentHandle
{
if ($hostId < 1) {
throw new CloudError('宿主机编号无效', 422);
}
if ($this->secrets === null || $this->hostResolver === null) {
throw new CloudError('宿主机 Agent resolver 尚未配置', 503);
}
try {
$rows = [];
foreach (($this->registry)($hostId) as $row) {
$rows[] = self::row($row);
}
} catch (\Throwable) {
throw new CloudError('宿主机 Agent 注册表不可用', 503);
}
if (count($rows) !== 1) {
throw new CloudError(
count($rows) === 0 ? '宿主机尚未注册 Go Agent' : '宿主机 Go Agent 注册身份不唯一',
503,
);
}
$row = $rows[0];
$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);
}
$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);
}
$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 = $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(
$rawEndpoint,
function (string $host) use (&$resolvedAddresses): array {
$resolvedAddresses = $this->hostResolver->resolve($host);
return $resolvedAddresses;
},
);
} catch (CloudError $error) {
throw $error;
} catch (\Throwable) {
throw new CloudError('宿主机 Go Agent 地址解析失败', 503);
}
try {
$material = $this->secrets->resolve($agentId);
} catch (\Throwable) {
throw new CloudError('宿主机 Go Agent secret resolver 不可用', 503);
}
if (!is_array($material)
|| !is_string($material['hmac_key'] ?? null)
|| strlen($material['hmac_key']) !== 32) {
throw new CloudError('宿主机 Go Agent 请求签名密钥未配置', 503);
}
$tls = [];
foreach (['ca_file', 'cert_file', 'key_file'] as $key) {
$value = $material[$key] ?? null;
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] = $value;
}
try {
$observedFingerprint = ($this->certificateFingerprint)($tls['cert_file']);
} catch (\Throwable) {
$observedFingerprint = null;
}
if (!is_string($observedFingerprint)
|| preg_match('/^[0-9a-f]{64}$/Di', trim($observedFingerprint)) !== 1
|| !hash_equals($fingerprint, strtolower(trim($observedFingerprint)))) {
throw new CloudError('宿主机 Go Agent 客户端证书指纹不匹配', 503);
}
try {
$client = ($this->clientFactory)(
$endpoint,
$material['hmac_key'],
$agentId,
$tls,
$this->timeoutSeconds,
array_values($resolvedAddresses),
$fingerprint,
);
} catch (CloudError $error) {
throw $error;
} catch (\Throwable) {
throw new CloudError('宿主机 Go Agent client 初始化失败', 503);
}
if (!$client instanceof CloudAgentClient) {
throw new CloudError('宿主机 Go Agent client 类型无效', 503);
}
return CloudAgentHandle::fromResolved(
$hostId,
$agentId,
'v1',
$fingerprint,
$client,
$readOnly,
);
}
/** @return array<string,mixed> */
private static function row(mixed $row): array
{
if (is_object($row)) {
$row = method_exists($row, 'toArray') ? $row->toArray() : get_object_vars($row);
}
return is_array($row) ? $row : [];
}
/**
* Validate a credential path before any TLS library opens it. This is
* public so health probes and other request-local assembly paths cannot
* accidentally bypass the same ownership/symlink boundary.
*/
public static function validateCredentialPath(string $path, bool $privateKey = false): bool
{
if ($path === '' || $path[0] !== '/' || trim($path) !== $path
|| preg_match('/[\x00-\x1F\x7F]/', $path) === 1) {
return false;
}
$stat = @lstat($path);
$mode = is_array($stat) ? (int) ($stat['mode'] ?? 0) : 0;
$effectiveUid = function_exists('posix_geteuid') ? (int) posix_geteuid() : null;
$ownerUid = is_array($stat) && isset($stat['uid']) ? (int) $stat['uid'] : null;
$ownerAllowed = $ownerUid !== null
&& ($ownerUid === 0 || ($effectiveUid !== null && $ownerUid === $effectiveUid));
if (!is_array($stat)
|| ($mode & 0170000) !== 0100000
|| ($mode & 006000) !== 0
|| ($mode & 0022) !== 0
|| !$ownerAllowed
|| !isset($stat['size']) || (int) $stat['size'] < 1
|| (int) $stat['size'] > 1024 * 1024) {
return false;
}
if ($privateKey && ($mode & 0077) !== 0) {
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
|| !isset($directoryStat['uid'])
|| !((int) $directoryStat['uid'] === 0
|| ($effectiveUid !== null && (int) $directoryStat['uid'] === $effectiveUid))) {
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;
}
}
}