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/CloudEngineClient.php

351 lines
19 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services\Cloud;
use App\Services\Config;
use GuzzleHttp\Client;
final class CloudEngineClient
{
private float $timeoutSeconds;
public function __construct(private ?Client $client = null, float $timeoutSeconds = 20.0)
{
if ($timeoutSeconds < 1 || $timeoutSeconds > 900) {
throw new \InvalidArgumentException('Engine timeout is outside the supported range');
}
$this->timeoutSeconds = $timeoutSeconds;
$this->client ??= new Client(['connect_timeout' => 3, 'timeout' => $timeoutSeconds, 'http_errors' => false,
'allow_redirects' => false]);
}
public static function canonical(string $method, string $path, string $body, string $timestamp, string $nonce, string $actor): string
{
return self::canonicalDigest($method, $path, hash('sha256', $body), $timestamp, $nonce, $actor);
}
public static function canonicalDigest(string $method, string $path, string $digest, string $timestamp, string $nonce, string $actor): string
{
return strtoupper($method) . "\n" . $path . "\n" . $digest . "\n"
. $timestamp . "\n" . $nonce . "\n" . $actor;
}
public static function headers(string $method, string $path, string $body, array $actor, ?int $now = null, ?string $nonce = null): array
{
$encoded = rtrim(strtr(base64_encode(json_encode($actor, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)), '+/', '-_'), '=');
$timestamp = (string) ($now ?? time());
$nonce ??= bin2hex(random_bytes(16));
return ['X-Cloud-Timestamp' => $timestamp, 'X-Cloud-Nonce' => $nonce, 'X-Cloud-Actor' => $encoded,
'X-Cloud-Signature' => hash_hmac('sha256', self::canonical($method, $path, $body, $timestamp, $nonce, $encoded),
CloudSecrets::key('engine_hmac_key')), 'Content-Type' => 'application/json'];
}
public function request(string $method, string $path, array $actor, ?array $payload = null,
?string $expectedOperationId = null): array
{
$base = $this->base($path);
$body = $payload === null ? '' : json_encode($payload === [] ? (object) [] : $payload,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
return $this->send($method, $base . $path, [
'headers' => self::headers($method, $path, $body, $actor), 'body' => $body,
], $expectedOperationId, $path);
}
private function base(string $path): string
{
$base = rtrim((string) Config::get('cloud_engine_url', 'http://127.0.0.1:8000'), '/');
$url = parse_url($base);
if (!is_array($url) || ($url['scheme'] ?? '') !== 'http'
|| !in_array($url['host'] ?? '', ['127.0.0.1', '[::1]', '::1'], true)
|| isset($url['user']) || isset($url['pass']) || isset($url['query']) || isset($url['fragment'])
|| (($url['path'] ?? '') !== '' && ($url['path'] ?? '') !== '/')
|| !str_starts_with($path, '/internal/v1/') || preg_match('/[\r\n\\\\]/', $path)) {
throw new CloudError('引擎地址必须为固定本机回环地址', 503);
}
return $base;
}
private function send(string $method, string $url, array $options,
?string $expectedOperationId = null, ?string $signedPath = null): array
{
try {
$response = $this->client->request($method, $url, $options + [
'allow_redirects' => false, 'http_errors' => false, 'proxy' => '',
]);
} catch (\GuzzleHttp\Exception\ConnectException $exception) {
throw new CloudError('虚拟化引擎连接失败或请求超时,正在核对结果', 502);
} catch (\Throwable $exception) {
throw new CloudError('虚拟化引擎响应不确定,请等待任务核对', 502);
}
$result = json_decode((string) $response->getBody(), true);
if (!is_array($result)) {
throw new CloudError('虚拟化引擎响应不确定,请等待任务核对', 502);
}
if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {
// A VM mutation can return a non-2xx HTTP status together with a
// durable, signed operation outcome. Only the worker that knows
// the exact operation ID may consume it; all ordinary API callers
// still receive an exception for every non-2xx response.
if ($expectedOperationId !== null
&& preg_match('/^[A-Za-z0-9_-]{8,80}$/D', $expectedOperationId) === 1
&& ($result['operation_id'] ?? null) === $expectedOperationId
&& in_array($result['status'] ?? null, ['failed', 'uncertain'], true)
&& is_bool($result['safe_to_refund'] ?? null)) {
$result['_engine_http_status'] = $response->getStatusCode();
return $result;
}
// Only explicitly reviewed endpoint-specific policies return
// short, credential-free guidance useful to the caller. Do not
// turn this into a general engine-error passthrough: arbitrary
// errors may contain host paths, credentials or private data.
$safeError = self::safeAllowlistedError(
$signedPath, $result, $response->getStatusCode()
);
if ($safeError !== null) {
throw new CloudError($safeError, $response->getStatusCode());
}
// Never expose engine tracebacks, host credentials or arbitrary upstream strings.
throw new CloudError('虚拟化操作未成功(引擎状态 ' . $response->getStatusCode() . ')',
$response->getStatusCode() === 404 ? 404 : 502);
}
return $result;
}
private static function safeAllowlistedError(?string $path, array $result, ?int $status = null): ?string
{
if ($path === null) {
return null;
}
$parts = explode('?', $path, 2);
$route = $parts[0];
if (count($parts) === 2
&& $route !== '/internal/v1/vm-templates/upload') {
return null;
}
$update = preg_match(
'#^/internal/v1/update/(?:settings|check|apply|jobs/[A-Za-z0-9_-]{16,64})$#D', $route
) === 1;
$userIso = preg_match(
'#^/internal/v1/user-isos(?:/import|/[0-9a-f]{32}|/import-jobs/[A-Za-z0-9_-]{8,80})?$#D',
$route
) === 1;
$vmTemplate = preg_match(
'#^/internal/v1/vm-templates(?:/(?:import|upload)|/[A-Za-z0-9_-]{8,80}|/import-jobs/[A-Za-z0-9_-]{8,80})?$#D',
$route
) === 1;
$host = preg_match(
'#^/internal/v1/hosts/[1-9][0-9]*/host(?:/test)?$#D', $route
) === 1;
$hostNetworkPool = preg_match(
'#^/internal/v1/hosts/[1-9][0-9]*/host/network-pools/[0-9a-f]{32}$#D',
$route
) === 1;
if (!$update && !$userIso && !$vmTemplate && !$host
&& !$hostNetworkPool) {
return null;
}
if ($hostNetworkPool) {
// Preserve only reviewed validation/conflict statuses so the
// desired-state service can distinguish a definitive rejection
// from an ambiguous transport failure. Never expose free-form
// engine detail, which can contain host-specific diagnostics.
return in_array($status, [400, 409, 422], true)
? '公网地址池配置未通过引擎校验'
: null;
}
if ($host) {
// Host errors may describe validation failures, SSH transport
// failures or damaged engine state with the same fallback code.
// Only reviewed client-error statuses may cross this boundary;
// 5xx responses keep the generic 502 message below.
if (!in_array($status, [400, 409, 422], true)) {
return null;
}
return self::safeHostErrorMessage($result['error_code'] ?? null);
}
$detail = $result['error'] ?? ($result['detail'] ?? null);
if (!is_string($detail)) {
return null;
}
$detail = trim($detail);
if ($detail === '' || strlen($detail) > 500 || preg_match('//u', $detail) !== 1
|| preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', $detail) === 1) {
return null;
}
if ($userIso) {
return self::safeUserIsoMessage($detail)
?? '用户 ISO 操作未成功,请稍后重试或联系管理员';
}
if ($vmTemplate) {
return self::safeVmTemplateMessage($detail);
}
// Update responses are administrator-only, but the upstream message
// can still contain a checkout path, remote URL, token or command.
// Keep the useful bounded summary while applying the same unconditional
// redaction boundary used by the operation DTOs.
return CloudOperationErrorCatalog::adminSummary(null, null, $detail)
?? '在线更新请求未成功,请查看更新任务日志';
}
private static function safeHostErrorMessage($value): ?string
{
if (!is_string($value)) {
return null;
}
return [
'host_configuration_invalid' => '宿主机配置无效,请检查地址、端口、存储目录和默认网络',
'host_private_key_required' => '首次添加宿主机必须提供现有 SSH 私钥',
'host_private_key_format_invalid' => 'SSH 私钥格式无效,请提供 PEM 或 OpenSSH 格式私钥',
'host_private_key_passphrase_required' => 'SSH 私钥已加密,请填写私钥解锁口令',
'host_private_key_invalid' => 'SSH 私钥或解锁口令无效,请检查后重试',
'host_public_pool_invalid' => '公网地址池配置无效,请完整填写可路由的 IPv4 网段、网关和 DNS(网段前缀 /24 至 /30)',
'host_public_gateway_invalid' => '公网网关无效,必须位于所配置的公网地址池内',
'host_public_dns_invalid' => '公网 DNS 无效,请填写最多 4 个可路由的 IPv4 地址',
'host_public_reserved_ip_invalid' => '保留 IP 配置无效,请填写地址池内的 IPv4 地址,最多 254 个',
'host_vm_prefix_invalid' => '客户机网络前缀无效,必须介于 /24 和地址池前缀之间',
][$value] ?? null;
}
public static function safeVmTemplateMessage($value): ?string
{
if (!is_string($value)) {
return null;
}
$value = trim($value);
$allowed = [
'云镜像导入参数无效', '云镜像名称无效', '云镜像地址无效',
'仅支持 AlmaLinux 官方仓库的 9/10 x86_64 GenericCloud qcow2 镜像',
'仅支持 AlmaLinux、Debian、Ubuntu 和 CentOS Stream 官方 x86_64 云镜像直链',
'官方镜像地址发生重定向,请使用最终的官方 HTTPS 直链',
'官方云镜像地址无法解析', '官方云镜像地址解析结果无效',
'官方云镜像地址解析到非公网地址',
'无法连接官方云镜像下载地址', '官方云镜像重定向目标不安全',
'官方云镜像重定向次数过多', '官方云镜像下载服务器返回异常状态',
'官方云镜像下载响应格式无效',
'模板名称应为 1 至 64 个字符', '模板名称不能包含控制字符',
'云镜像系统版本无效', '模板标识无效', '云镜像模板范围无效',
'云镜像上传参数无效', '云镜像系统或版本不受支持',
'云镜像上传请求头重复',
'云镜像上传必须使用 application/octet-stream',
'云镜像上传内容不能压缩', '云镜像上传长度无效',
'云镜像上传内容超过声明长度', '云镜像上传内容不完整',
'云镜像上传已中断',
'云镜像上传请求无效', '云镜像上传超时',
'云镜像文件不能小于 1 MiB',
'云镜像摘要与签名不匹配',
'上传文件不是有效的 qcow2 镜像',
'面板未安装 qemu-img,无法验证云镜像',
'云镜像完整性检查失败',
'云镜像 SHA-256 格式无效',
'SHA-256 可留空;填写时必须为 64 位十六进制校验值',
'云镜像导入任务不存在', '云镜像模板不存在',
'云镜像正在导入,请稍后修改模板名称',
'云镜像正在导入,请稍后删除模板',
'云镜像正在同步到宿主机,请稍后删除',
'云镜像删除参数无效',
'云镜像版本已变化,请刷新后重试',
'云镜像目录记录损坏,无法安全删除',
'云镜像源文件无法安全删除',
'云镜像源文件删除失败,请联系管理员',
'云镜像缓存清理记录损坏,请联系管理员',
'云镜像版本记录损坏,请联系管理员',
'旧云镜像缓存仍在清理,请稍后重新导入',
'此云镜像已经导入', '已有同名云镜像模板', '该云镜像正在导入',
'已有云镜像正在导入,请等待完成后再提交',
'引擎正在停止,无法开始云镜像导入',
'面板在云镜像导入期间重启;请重新提交导入',
'下载官方云镜像失败,请检查面板服务器网络',
'云镜像下载超过 60 分钟,请检查面板服务器网络',
'云镜像下载内容不完整', '云镜像超过 4 GiB 限制',
'云镜像 SHA-256 不匹配,已丢弃下载内容',
'下载文件不是有效的 qcow2 镜像', '云镜像 qcow2 版本或簇大小不受支持',
'云镜像 qcow2 头部不完整', '云镜像包含不受支持或外部依赖的 qcow2 特性',
'云镜像含外部依赖、加密或容量超出支持范围',
'云镜像无法保存到持久目录', '面板云镜像持久目录空间不足',
'云镜像导入失败,请查看引擎日志',
'云镜像下载或保存失败,请联系管理员查看日志',
];
return in_array($value, $allowed, true) ? $value : null;
}
public static function safeUserIsoMessage($value): ?string
{
if (!is_string($value)) {
return null;
}
$value = trim($value);
$allowed = [
'ISO 标识无效', 'ISO 名称应为 1 至 64 个字符', 'ISO 名称不能包含控制字符',
'ISO 下载地址无效', 'ISO 仅支持无账号、无跳转的 HTTPS 443 直链',
'ISO 下载地址的文件名必须以 .iso 结尾',
'ISO 下载地址必须使用 ASCII/百分号编码', 'ISO 下载地址包含无效字符',
'ISO 下载地址无法解析', 'ISO 下载地址解析结果无效',
'ISO 下载地址不能指向内网、回环或保留地址', '无法连接 ISO 下载地址',
'ISO 下载响应长度无效', 'ISO 大小必须在 1 MiB 至可用配额之间',
'下载文件不是有效的 ISO 9660 镜像', 'ISO 未包含可识别的 El Torito 启动记录',
'SHA-256 可留空;填写时必须为 64 位十六进制校验值', '用户 ISO 可用配额不足',
'ISO 下载地址发生重定向,请使用最终 HTTPS 直链', 'ISO 下载响应不能使用内容压缩',
'ISO 超过用户目录的 10 GiB 总配额或剩余容量',
'ISO 超过用户全局目录的 10 GiB 配额或剩余容量',
'ISO 下载超时', 'ISO 下载内容不完整',
'ISO 的 SHA-256 校验值不匹配', 'ISO 不存在或不属于当前用户',
'ISO 导入任务不存在', '每个宿主机最多保存 5 个用户 ISO',
'每个用户最多保存 5 个 ISO',
'用户 ISO 目录的 10 GiB 存储配额已用完', '用户 ISO 目录总容量不能超过 10 GiB',
'用户 ISO 全局目录的 10 GiB 存储配额已用完', '用户 ISO 全局目录总容量不能超过 10 GiB',
'面板用户 ISO 持久目录空间不足', 'ISO 无法保存到面板持久目录',
'当前宿主机已有同名用户 ISO', '当前用户已有同名 ISO',
'已有用户 ISO 正在导入,请等待完成', '用户 ISO 正在导入,请稍后删除',
'ISO 正在同步到宿主机,请稍后删除', '宿主机用户 ISO 存储空间不足',
'用户 ISO 存储目录不可用,请联系管理员', '用户 ISO 仍被虚拟机安装过程引用,不能删除',
'引擎正在停止,无法开始 ISO 导入', 'ISO 下载或导入失败,请联系管理员查看日志',
'ISO 下载或保存失败,请联系管理员查看日志',
'面板在 ISO 下载期间重启;请重新提交导入',
'面板在任务执行期间重启;请检查宿主机实际状态,勿直接重复提交',
];
if (in_array($value, $allowed, true)
|| preg_match('/^ISO 下载服务器返回 HTTP [1-5][0-9]{2}$/D', $value) === 1) {
return $value;
}
return null;
}
public function upload(string $path, array $actor, string $filename): array
{
$base = $this->base($path);
$digest = hash_file('sha256', $filename);
if ($digest === false) {
throw new CloudError('上传文件无法读取', 503);
}
$headers = self::headers('POST', $path, '', $actor);
$headers['X-Cloud-Signature'] = hash_hmac('sha256', self::canonicalDigest('POST', $path, $digest,
$headers['X-Cloud-Timestamp'], $headers['X-Cloud-Nonce'], $headers['X-Cloud-Actor']), CloudSecrets::key('engine_hmac_key'));
$headers['X-Cloud-Content-SHA256'] = $digest;
$headers['Content-Type'] = 'application/octet-stream';
$stream = fopen($filename, 'rb');
if ($stream === false) {
throw new CloudError('上传文件无法读取', 503);
}
try {
return $this->send('POST', $base . $path, ['headers' => $headers, 'body' => $stream, 'timeout' => 900], null, $path);
} finally {
// Guzzle's PSR-7 stream owns and may close the supplied resource
// before request() returns. Avoid replacing the real engine
// response with a PHP 8 TypeError from closing it a second time.
if (is_resource($stream)) {
fclose($stream);
}
}
}
public function host(int $hostId, string $method, string $resource, array $actor,
?array $payload = null, ?string $expectedOperationId = null): array
{
if ($hostId < 1) {
throw new CloudError('宿主机不存在', 404);
}
return $this->request($method, '/internal/v1/hosts/' . $hostId . '/' . $resource,
$actor, $payload, $expectedOperationId);
}
}