|
|
<?php
|
|
|
namespace App\Services\Cloud;
|
|
|
|
|
|
use App\Services\Config;
|
|
|
use GuzzleHttp\Client;
|
|
|
|
|
|
final class CloudEngineClient
|
|
|
{
|
|
|
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->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() >= 400) {
|
|
|
// 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);
|
|
|
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): ?string
|
|
|
{
|
|
|
if ($path === null) {
|
|
|
return null;
|
|
|
}
|
|
|
$update = preg_match(
|
|
|
'#^/internal/v1/update/(?:settings|check|apply|jobs/[A-Za-z0-9_-]{16,64})$#D', $path
|
|
|
) === 1;
|
|
|
$userIso = preg_match(
|
|
|
'#^/internal/v1/user-isos(?:/import|/[0-9a-f]{32}|/import-jobs/[A-Za-z0-9_-]{8,80})?$#D',
|
|
|
$path
|
|
|
) === 1;
|
|
|
$vmTemplate = preg_match(
|
|
|
'#^/internal/v1/vm-templates(?:/import|/[A-Za-z0-9_-]{8,80}|/import-jobs/[A-Za-z0-9_-]{8,80})?$#D',
|
|
|
$path
|
|
|
) === 1;
|
|
|
if (!$update && !$userIso && !$vmTemplate) {
|
|
|
return 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);
|
|
|
}
|
|
|
return $detail;
|
|
|
}
|
|
|
|
|
|
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 个字符', '模板名称不能包含控制字符',
|
|
|
'云镜像系统版本无效', '模板标识无效', '云镜像模板范围无效',
|
|
|
'云镜像 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 {
|
|
|
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);
|
|
|
}
|
|
|
}
|