feat(web): add S3 object storage configuration

go
codex 4 weeks ago
parent 1a5362511d
commit d7d3c621c9

@ -91,6 +91,14 @@ php xcat cloudRepairInstanceMetadata --apply
配置、密钥和数据库备份不得提交 Git。备份数据库时必须同步备份 `runtime/php/data.key`;仅有 SQL 无法解密 Agent 密钥。丢失该密钥不能通过导入旧引擎密钥或降级格式恢复。
### 对象存储应用
后台 `/admin/object-storage` 可配置一个全局 S3 兼容对象存储应用,适用于 AWS S3、MinIO 及实现 AWS Signature Version 4 的兼容服务。该功能复用业务库已有的 `configurations` 表,不需要导入新表。Endpoint 必须是带有效证书的 HTTPS origin;MinIO 通常选择路径寻址,AWS S3 通常选择虚拟主机寻址。
Access Key ID 与 Secret Access Key 只在超级管理员提交时进入 PHP,使用 `cloud_data_key` 的独立用途密钥密封后保存,读取页面不会回显。修改任一配置或停用应用都会清除原就绪标记;必须重新执行“验证连接并启用”。连接验证只发送签名的 `HeadBucket` 请求,需要目标 Bucket 的 `s3:ListBucket` 权限,不上传、覆盖或删除对象。当前阶段尚未接入云备份上传、增量备份、保留策略和异地恢复,连接验证成功不能视为备份功能已经上线。
生产环境应为面板创建独立服务账户,把权限限制到配置的 Bucket;后续启用备份写入前还需按实际前缀补充最小对象读写/列举/删除权限。数据库备份必须与原始 `cloud_data_key` 一起保管,重新生成主密钥无法恢复已保存的对象存储凭据。
## 4. 构建并安装宿主机 Agent
在与目标宿主机 ABI 相同的 Linux 环境构建,不要把 macOS CGo 产物复制到 Linux:
@ -330,7 +338,8 @@ location = /agent/console {
4. 导入云镜像和救援 ISO。远程下载只接受可公开解析的 HTTPS 直链,Agent 会校验初始地址与全部跳转;来源的发行方可信度由管理员确认。本地云镜像必须是独立、未加密、无 backing/data file 的 QCOW2,本地救援镜像必须是可启动 ISO。面板会把本地暂存文件的精确大小和摘要写入签名任务,代理可使用 chunked 传输,但不得压缩响应或改变正文;Agent 会拒绝短读、多余字节、长度或摘要不一致。
5. 为每个云镜像按需设置首次安装启动脚本。脚本最大 32 KiB UTF-8、拒绝 NUL;保存后修订递增,新创建任务快照当前版本。不要在脚本中写长期密钥。
6. 在 `/admin/config` 的“云实例计费”中用“数值+分钟/小时/天”设置新建实例账单支付期限;面板保存时统一换算为整数分钟。该值只作用于保存后新生成的开通账单,既有账单保持原截止时间。
7. 创建销售套餐和库存,再启用宿主机/Agent 调度。用户支付成功后只应创建一个 VM。
7. 如计划启用后续云备份,在 `/admin/object-storage` 保存 S3 兼容配置并执行连接验证;验证仅检查 Bucket 可达性和 `s3:ListBucket` 权限,不会写入测试对象。
8. 创建销售套餐和库存,再启用宿主机/Agent 调度。用户支付成功后只应创建一个 VM。
部署人员根据宿主机 domain capabilities 选择 Q35 UEFI loader/NVRAM 并写入该机 Agent 配置,Agent 用这组本地固定值生成明确关闭 Secure Boot 的 XML。首次启动脚本由 cloud-init 一次性 runner 执行;VM 创建成功不等待脚本完成,脚本失败或中断不自动重放。

@ -10,6 +10,7 @@
- 多宿主机、资源池、容量策略、reservation、具体公网 IP 账本、多 CIDR、云镜像、救援 ISO、快照、防火墙、指标与控制台入口。
- 管理员工单 Telegram 通知;普通用户仍只在网页处理工单。
- 公开产品落地页,以及后台统一维护、带草稿和发布历史的全局服务条款与隐私政策页面;法律内容不按域名拆分。
- 后台全局 S3 兼容对象存储应用配置、密钥密封和只读连接验证;云备份上传、增量链、保留策略与异地恢复暂未接入。
## 删除

@ -126,6 +126,9 @@ jq empty deploy/*.json.example
- 两个管理员同时编辑同一法律页面时,旧 `draft_version` 的保存或发布必须返回冲突,不能覆盖新草稿;发布成功必须新增不可变历史版本。
- 法律内容在保存、预览和公开读取时都必须经过服务端清洗;脚本、事件属性、表单、外链资源和未知标签不能进入预览或公开页面。
- 落地页、服务条款、隐私政策和后台法律编辑页必须分别在桌面与窄屏视口验收,导航、目录、编辑控件和正文不得横向溢出。
- 对象存储配置页面不得回显 Access Key ID、Secret Access Key 或数据库密文;普通管理员只能查看,保存、连接验证和停用必须同时经过超级管理员与 CSRF 校验。
- 对象存储保存后必须处于未启用状态;只有当前配置版本的签名 `HeadBucket` 成功后才能就绪。修改或停用时旧验证立即失效;失败响应只显示稳定的本地错误,不泄露 Endpoint 响应正文、凭据或服务器路径。
- 使用受控的 S3/MinIO 测试 Bucket 分别验收路径寻址和虚拟主机寻址、错误 Region、错误凭据、缺少 `s3:ListBucket`、无效证书和连接超时;验证过程中 Bucket 对象数与内容不得变化。
## 7. 非生产宿主机验收

@ -0,0 +1,94 @@
<?php
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudObjectStorageConfig;
final class ObjectStorageController extends AdminController
{
public function index($request, $response, $args)
{
$state = null;
$error = '';
$status = 200;
try {
$state = CloudObjectStorageConfig::view();
} catch (CloudError $exception) {
$error = $exception->getMessage();
$status = $exception->httpStatus;
} catch (\Throwable $exception) {
error_log('Object storage settings read failed: ' . get_class($exception));
$error = '对象存储配置暂时无法读取,请检查数据库状态。';
$status = 503;
}
$smarty = $this->view()->assign([
'object_storage' => $state,
'object_storage_error' => $error,
]);
$response->getBody()->write($smarty->fetch('admin/object_storage.tpl'));
return $response->withStatus($status)
->withHeader('Cache-Control', 'private, no-store');
}
public function save($request, $response, $args)
{
try {
$state = CloudObjectStorageConfig::save(CloudInput::object($request));
return $this->json($response, 1, '对象存储配置已保存,请执行连接验证。', 200, $state);
} catch (CloudError $exception) {
return $this->json($response, 0, $exception->getMessage(), $exception->httpStatus);
} catch (\Throwable $exception) {
error_log('Object storage settings save failed: ' . get_class($exception));
return $this->json($response, 0, '对象存储配置保存失败,请稍后重试。', 500);
}
}
public function test($request, $response, $args)
{
try {
$input = CloudInput::object($request);
CloudInput::only($input, ['expected_revision']);
$state = CloudObjectStorageConfig::testAndEnable(
$input['expected_revision'] ?? null
);
return $this->json($response, 1, '连接验证成功,对象存储已启用。', 200, $state);
} catch (CloudError $exception) {
return $this->json($response, 0, $exception->getMessage(), $exception->httpStatus);
} catch (\Throwable $exception) {
error_log('Object storage connection test failed: ' . get_class($exception));
return $this->json($response, 0, '连接验证失败,请稍后重试。', 500);
}
}
public function disable($request, $response, $args)
{
try {
$input = CloudInput::object($request);
CloudInput::only($input, ['expected_revision']);
$state = CloudObjectStorageConfig::disable(
$input['expected_revision'] ?? null
);
return $this->json($response, 1, '对象存储已停用,已保存的凭据仍保持加密。', 200, $state);
} catch (CloudError $exception) {
return $this->json($response, 0, $exception->getMessage(), $exception->httpStatus);
} catch (\Throwable $exception) {
error_log('Object storage disable failed: ' . get_class($exception));
return $this->json($response, 0, '对象存储停用失败,请稍后重试。', 500);
}
}
/** @param array<string, mixed>|null $state */
private function json($response, int $ret, string $message, int $status, ?array $state = null)
{
$payload = ['ret' => $ret, 'msg' => $message];
if ($state !== null) {
$payload['object_storage'] = $state;
}
return $response->withJson($payload, $status)
->withHeader('Cache-Control', 'private, no-store');
}
}

@ -0,0 +1,537 @@
<?php
namespace App\Services\Cloud;
use App\Models\Configurations;
/** PHP-owned global S3-compatible object-storage application settings. */
final class CloudObjectStorageConfig
{
private const PREFIX = 'cloud_object_storage_';
private const CREDENTIAL_PURPOSE = 'object-storage-credentials';
private const DEFAULTS = [
'name' => '默认对象存储',
'driver' => 's3',
'endpoint' => '',
'region' => 'us-east-1',
'bucket' => '',
'prefix' => 'virt-cloud',
'path_style' => 'true',
'enabled' => 'false',
'revision' => '0',
'tested_revision' => '0',
'last_test_status' => 'never',
'last_error_code' => '',
'last_tested_at' => '0',
'sealed_credentials' => '',
];
/** @return array<string, mixed> */
public static function view(): array
{
return self::publicState(self::readRaw());
}
/** @return array<string, mixed> */
public static function save(array $input): array
{
CloudInput::only($input, [
'name', 'endpoint', 'region', 'bucket', 'prefix', 'path_style',
'access_key_id', 'secret_access_key', 'expected_revision',
]);
$expected = self::revision($input['expected_revision'] ?? null, true);
$name = self::name($input['name'] ?? '');
$endpoint = self::endpoint($input['endpoint'] ?? '');
$region = self::region($input['region'] ?? '');
$bucket = self::bucket($input['bucket'] ?? '');
$prefix = self::objectPrefix($input['prefix'] ?? '');
$pathStyle = self::boolean($input['path_style'] ?? null, '请选择 S3 寻址方式');
if (!$pathStyle && self::endpointHostIsIp($endpoint)) {
throw new CloudError('IP 地址 Endpoint 只能使用路径寻址');
}
$accessKeyId = is_string($input['access_key_id'] ?? null)
? trim($input['access_key_id']) : '';
$secretAccessKey = is_string($input['secret_access_key'] ?? null)
? $input['secret_access_key'] : '';
if (($accessKeyId === '') !== ($secretAccessKey === '')) {
throw new CloudError('Access Key ID 和 Secret Access Key 必须同时填写');
}
$newCipher = null;
if ($accessKeyId !== '') {
self::assertCredentials($accessKeyId, $secretAccessKey);
$newCipher = CloudSecrets::encrypt([
'access_key_id' => $accessKeyId,
'secret_access_key' => $secretAccessKey,
], self::CREDENTIAL_PURPOSE);
}
self::ensureRow('revision', '0');
$connection = (new Configurations())->getConnection();
$connection->transaction(static function () use (
$expected,
$name,
$endpoint,
$region,
$bucket,
$prefix,
$pathStyle,
$newCipher
): void {
$revisionRow = Configurations::where('name', self::key('revision'))
->lockForUpdate()->firstOrFail();
$actual = (int) $revisionRow->value;
if ($actual !== $expected) {
throw new CloudError('对象存储配置已被修改,请刷新页面后重试', 409);
}
$rows = self::readRaw();
$cipher = trim((string) $rows['sealed_credentials']);
if ($newCipher !== null) {
$cipher = $newCipher;
} elseif ($cipher !== '') {
self::credentials($cipher);
}
if ($cipher === '') {
throw new CloudError('首次保存对象存储必须填写 Access Key 和 Secret Key');
}
self::set('name', $name);
self::set('driver', 's3');
self::set('endpoint', $endpoint);
self::set('region', $region);
self::set('bucket', $bucket);
self::set('prefix', $prefix);
self::set('path_style', $pathStyle ? 'true' : 'false');
self::set('sealed_credentials', $cipher);
self::set('revision', (string) ($actual + 1));
self::invalidateReadiness();
});
return self::view();
}
/** @return array<string, mixed> */
public static function testAndEnable(
$expectedRevision,
?CloudObjectStorageS3Client $client = null
): array {
$expected = self::revision($expectedRevision, false);
$raw = self::readRaw();
if ((int) $raw['revision'] !== $expected) {
throw new CloudError('对象存储配置已被修改,请刷新页面后重试', 409);
}
$runtime = self::runtimeFromRaw($raw);
try {
($client ?? new CloudObjectStorageS3Client())->headBucket(
$runtime['config'],
$runtime['credentials']
);
} catch (CloudObjectStorageTestError $exception) {
self::recordTestFailure($expected, $exception->publicCode);
throw new CloudError($exception->getMessage(), 502);
}
$connection = (new Configurations())->getConnection();
$connection->transaction(static function () use ($expected): void {
$revisionRow = Configurations::where('name', self::key('revision'))
->lockForUpdate()->firstOrFail();
if ((int) $revisionRow->value !== $expected) {
throw new CloudError('连接测试期间配置已改变,请重新测试', 409);
}
self::set('enabled', 'true');
self::set('tested_revision', (string) $expected);
self::set('last_test_status', 'healthy');
self::set('last_error_code', '');
self::set('last_tested_at', (string) time());
});
return self::view();
}
/** @return array<string, mixed> */
public static function disable($expectedRevision): array
{
$expected = self::revision($expectedRevision, false);
self::ensureRow('revision', '0');
$connection = (new Configurations())->getConnection();
$connection->transaction(static function () use ($expected): void {
$revisionRow = Configurations::where('name', self::key('revision'))
->lockForUpdate()->firstOrFail();
if ((int) $revisionRow->value !== $expected) {
throw new CloudError('对象存储配置已被修改,请刷新页面后重试', 409);
}
self::set('revision', (string) ($expected + 1));
self::set('enabled', 'false');
self::set('tested_revision', '0');
self::set('last_test_status', 'disabled');
self::set('last_error_code', '');
self::set('last_tested_at', '0');
});
return self::view();
}
/**
* Future backup services consume this server-side method. It is deliberately
* absent from controller responses so credentials cannot reach a browser.
*
* @return array{config:array<string,mixed>,credentials:array{access_key_id:string,secret_access_key:string}}
*/
public static function runtime(bool $requireReady = true): array
{
$raw = self::readRaw();
if ($requireReady && !self::isReady($raw)) {
throw new CloudError('对象存储尚未通过当前配置的连接验证', 503);
}
return self::runtimeFromRaw($raw);
}
/** @return array<string, mixed> */
private static function readRaw(): array
{
$raw = self::DEFAULTS;
$names = array_map(self::key(...), array_keys(self::DEFAULTS));
$rows = Configurations::whereIn('name', $names)->get();
foreach ($rows as $row) {
$name = (string) $row->name;
if (!str_starts_with($name, self::PREFIX)) {
continue;
}
$short = substr($name, strlen(self::PREFIX));
if (array_key_exists($short, $raw)) {
$raw[$short] = (string) $row->value;
}
}
return $raw;
}
/** @param array<string, mixed> $raw */
private static function publicState(array $raw): array
{
$status = in_array($raw['last_test_status'], ['never', 'healthy', 'failed', 'disabled'], true)
? $raw['last_test_status'] : 'never';
$credentialsConfigured = trim((string) $raw['sealed_credentials']) !== '';
$ready = self::isReady($raw);
$labels = [
'never' => $credentialsConfigured ? '等待验证' : '未配置',
'healthy' => $ready ? '已启用' : '已停用',
'failed' => '验证失败',
'disabled' => '已停用',
];
$errors = [
'endpoint_unreachable' => '无法连接 Endpoint,请检查证书、DNS 和防火墙。',
'region_mismatch' => 'Bucket 区域不匹配。',
'auth_or_permission_denied' => '凭据或 s3:ListBucket 权限验证失败。',
'bucket_not_found' => 'Bucket 不存在或不可访问。',
'rate_limited' => '对象存储暂时限制请求。',
'service_unavailable' => '对象存储服务暂时不可用。',
'request_rejected' => '对象存储拒绝兼容性检查。',
];
$errorCode = (string) $raw['last_error_code'];
$lastTestedAt = max(0, (int) $raw['last_tested_at']);
return [
'name' => (string) $raw['name'],
'driver' => 's3',
'endpoint' => (string) $raw['endpoint'],
'region' => (string) $raw['region'],
'bucket' => (string) $raw['bucket'],
'prefix' => (string) $raw['prefix'],
'path_style' => self::truthy($raw['path_style']),
'enabled' => self::truthy($raw['enabled']),
'ready' => $ready,
'configured' => (string) $raw['endpoint'] !== ''
&& (string) $raw['bucket'] !== '' && $credentialsConfigured,
'credentials_configured' => $credentialsConfigured,
'revision' => max(0, (int) $raw['revision']),
'tested_revision' => max(0, (int) $raw['tested_revision']),
'last_test_status' => $status,
'last_error_code' => $errorCode,
'last_error' => $errors[$errorCode] ?? '',
'last_tested_at' => $lastTestedAt,
'last_tested_at_text' => $lastTestedAt > 0
? date('Y-m-d H:i:s', $lastTestedAt) : '',
'status_label' => $labels[$status],
'status_class' => $ready ? 'success'
: ($status === 'failed' ? 'danger' : 'secondary'),
];
}
/**
* @param array<string, mixed> $raw
* @return array{config:array<string,mixed>,credentials:array{access_key_id:string,secret_access_key:string}}
*/
private static function runtimeFromRaw(array $raw): array
{
$config = [
'endpoint' => self::endpoint($raw['endpoint']),
'region' => self::region($raw['region']),
'bucket' => self::bucket($raw['bucket']),
'prefix' => self::objectPrefix($raw['prefix']),
'path_style' => self::truthy($raw['path_style']),
];
if (!$config['path_style'] && self::endpointHostIsIp($config['endpoint'])) {
throw new CloudError('IP 地址 Endpoint 只能使用路径寻址');
}
$cipher = trim((string) $raw['sealed_credentials']);
if ($cipher === '') {
throw new CloudError('对象存储访问凭据尚未配置', 503);
}
return ['config' => $config, 'credentials' => self::credentials($cipher)];
}
/** @return array{access_key_id:string,secret_access_key:string} */
private static function credentials(string $cipher): array
{
$credentials = CloudSecrets::decrypt($cipher, self::CREDENTIAL_PURPOSE);
$access = $credentials['access_key_id'] ?? null;
$secret = $credentials['secret_access_key'] ?? null;
if (!is_string($access) || !is_string($secret)) {
throw new CloudError('对象存储访问凭据内容无效', 503);
}
self::assertCredentials($access, $secret);
return ['access_key_id' => $access, 'secret_access_key' => $secret];
}
private static function recordTestFailure(int $expected, string $code): void
{
$connection = (new Configurations())->getConnection();
$connection->transaction(static function () use ($expected, $code): void {
$revisionRow = Configurations::where('name', self::key('revision'))
->lockForUpdate()->firstOrFail();
if ((int) $revisionRow->value !== $expected) {
throw new CloudError('连接测试期间配置已改变,请重新测试', 409);
}
self::set('enabled', 'false');
self::set('tested_revision', '0');
self::set('last_test_status', 'failed');
self::set('last_error_code', $code);
self::set('last_tested_at', (string) time());
});
}
private static function invalidateReadiness(): void
{
self::set('enabled', 'false');
self::set('tested_revision', '0');
self::set('last_test_status', 'never');
self::set('last_error_code', '');
self::set('last_tested_at', '0');
}
/** @param array<string, mixed> $raw */
private static function isReady(array $raw): bool
{
$revision = (int) $raw['revision'];
return $revision > 0
&& self::truthy($raw['enabled'])
&& (string) $raw['last_test_status'] === 'healthy'
&& (int) $raw['tested_revision'] === $revision
&& trim((string) $raw['sealed_credentials']) !== '';
}
private static function name($value): string
{
if (!is_string($value)) {
throw new CloudError('对象存储名称格式无效');
}
$value = trim($value);
if ($value === '' || mb_strlen($value, 'UTF-8') > 80
|| preg_match('//u', $value) !== 1
|| preg_match('/[\x00-\x1F\x7F]/u', $value) === 1) {
throw new CloudError('对象存储名称需为 1 至 80 个字符且不能包含控制字符');
}
return $value;
}
private static function endpoint($value): string
{
if (!is_string($value)) {
throw new CloudError('Endpoint 格式无效');
}
$value = trim($value);
$parts = parse_url($value);
if (!is_array($parts) || strtolower((string) ($parts['scheme'] ?? '')) !== 'https'
|| !isset($parts['host']) || isset($parts['user']) || isset($parts['pass'])
|| isset($parts['query']) || isset($parts['fragment'])
|| !in_array((string) ($parts['path'] ?? ''), ['', '/'], true)) {
throw new CloudError('Endpoint 必须是仅包含主机和可选端口的 HTTPS 地址');
}
$host = strtolower(trim((string) $parts['host'], '[]'));
if ($host === '' || $host === 'localhost' || str_ends_with($host, '.localhost')) {
throw new CloudError('Endpoint 主机无效');
}
if (filter_var($host, FILTER_VALIDATE_IP)) {
if (self::blockedEndpointIp($host)) {
throw new CloudError('Endpoint 不能使用回环、链路本地、未指定或组播地址');
}
} else {
if (preg_match('/^[0-9.]+$/D', $host) === 1) {
throw new CloudError('Endpoint IP 地址格式无效');
}
if (strlen($host) > 253 || str_ends_with($host, '.')) {
throw new CloudError('Endpoint 主机名无效');
}
foreach (explode('.', $host) as $label) {
if (preg_match('/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/D', $label) !== 1) {
throw new CloudError('Endpoint 主机名无效');
}
}
}
$port = isset($parts['port']) ? (int) $parts['port'] : 443;
if ($port < 1 || $port > 65535) {
throw new CloudError('Endpoint 端口必须为 1 至 65535');
}
$authority = str_contains($host, ':') ? '[' . $host . ']' : $host;
if ($port !== 443) {
$authority .= ':' . $port;
}
return 'https://' . $authority;
}
private static function endpointHostIsIp(string $endpoint): bool
{
$host = parse_url($endpoint, PHP_URL_HOST);
return is_string($host)
&& filter_var(trim($host, '[]'), FILTER_VALIDATE_IP) !== false;
}
private static function blockedEndpointIp(string $host): bool
{
$packed = inet_pton($host);
if ($packed === false) {
return true;
}
if (strlen($packed) === 4) {
$octets = array_values(unpack('C4', $packed));
return $octets[0] === 0 || $octets[0] === 127
|| ($octets[0] === 169 && $octets[1] === 254)
|| $octets[0] >= 224;
}
$bytes = array_values(unpack('C16', $packed));
return $host === '::' || $host === '::1' || $bytes[0] === 0xff
|| ($bytes[0] === 0xfe && ($bytes[1] & 0xc0) === 0x80);
}
private static function region($value): string
{
if (!is_string($value)) {
throw new CloudError('Region 格式无效');
}
$value = strtolower(trim($value));
if (preg_match('/^[a-z0-9][a-z0-9-]{0,62}$/D', $value) !== 1) {
throw new CloudError('Region 只能包含小写字母、数字和连字符,最多 63 位');
}
return $value;
}
private static function bucket($value): string
{
if (!is_string($value)) {
throw new CloudError('Bucket 名称格式无效');
}
$value = strtolower(trim($value));
if (strlen($value) < 3 || strlen($value) > 63
|| preg_match('/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/D', $value) !== 1
|| str_contains($value, '..') || str_contains($value, '.-')
|| str_contains($value, '-.') || filter_var($value, FILTER_VALIDATE_IP)) {
throw new CloudError('Bucket 名称需符合 S3 DNS 命名规则(3 至 63 位)');
}
return $value;
}
private static function objectPrefix($value): string
{
if (!is_string($value)) {
throw new CloudError('对象前缀格式无效');
}
$value = trim($value, " \t\n\r\0\x0B/");
if ($value === '') {
return '';
}
if (strlen($value) > 255
|| preg_match('/^[A-Za-z0-9][A-Za-z0-9._\/-]*$/D', $value) !== 1
|| str_contains($value, '//')) {
throw new CloudError('对象前缀只能包含英文、数字、点、下划线、连字符和斜线,最多 255 位');
}
foreach (explode('/', $value) as $segment) {
if ($segment === '.' || $segment === '..') {
throw new CloudError('对象前缀不能包含点路径段');
}
}
return $value;
}
private static function assertCredentials(string $access, string $secret): void
{
if (preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]{2,127}$/D', $access) !== 1) {
throw new CloudError('Access Key ID 需为 3 至 128 位英文、数字、点、下划线或连字符');
}
if (strlen($secret) < 8 || strlen($secret) > 256
|| trim($secret) !== $secret
|| preg_match('/[\x00-\x1F\x7F]/', $secret) === 1) {
throw new CloudError('Secret Access Key 需为 8 至 256 位且不能包含首尾空格或控制字符');
}
}
private static function revision($value, bool $allowZero): int
{
if (is_int($value)) {
$revision = $value;
} elseif (is_string($value) && preg_match('/^(?:0|[1-9][0-9]{0,9})$/D', $value) === 1) {
$revision = (int) $value;
} else {
throw new CloudError('对象存储配置版本无效,请刷新页面后重试', 409);
}
if ($revision < ($allowZero ? 0 : 1)) {
throw new CloudError('对象存储配置版本无效,请刷新页面后重试', 409);
}
return $revision;
}
private static function boolean($value, string $message): bool
{
$parsed = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($parsed === null) {
throw new CloudError($message);
}
return $parsed;
}
private static function truthy($value): bool
{
return in_array(strtolower(trim((string) $value)), ['1', 'true', 'yes', 'on'], true);
}
private static function key(string $name): string
{
return self::PREFIX . $name;
}
private static function set(string $name, string $value): void
{
$row = Configurations::where('name', self::key($name))->first();
if ($row === null) {
$row = new Configurations();
$row->name = self::key($name);
}
$row->value = $value;
$row->save();
}
private static function ensureRow(string $name, string $value): void
{
if (Configurations::where('name', self::key($name))->first() !== null) {
return;
}
$row = new Configurations();
$row->name = self::key($name);
$row->value = $value;
try {
$row->save();
} catch (\Throwable $exception) {
if (Configurations::where('name', self::key($name))->first() === null) {
throw $exception;
}
}
}
}

@ -0,0 +1,118 @@
<?php
namespace App\Services\Cloud;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
/** Signed, read-only S3 compatibility check. */
final class CloudObjectStorageS3Client
{
public function __construct(private readonly ?ClientInterface $http = null)
{
}
/**
* @param array<string, mixed> $config
* @param array{access_key_id:string,secret_access_key:string} $credentials
* @return array{status:string,http_status:int,region:string}
*/
public function headBucket(array $config, array $credentials): array
{
$url = self::bucketUrl(
(string) $config['endpoint'],
(string) $config['bucket'],
(bool) $config['path_style']
);
$headers = CloudS3Signer::sign(
'HEAD',
$url,
(string) $config['region'],
$credentials['access_key_id'],
$credentials['secret_access_key'],
time()
);
try {
$response = ($this->http ?? new Client())->request('HEAD', $url, [
'headers' => $headers,
'http_errors' => false,
'allow_redirects' => false,
'connect_timeout' => 5.0,
'timeout' => 15.0,
'verify' => true,
'proxy' => '',
]);
} catch (GuzzleException $exception) {
throw new CloudObjectStorageTestError(
'无法连接对象存储,请检查地址、证书、DNS 和防火墙。',
'endpoint_unreachable'
);
}
$status = $response->getStatusCode();
$responseRegion = trim($response->getHeaderLine('x-amz-bucket-region'));
if ($status >= 200 && $status < 300) {
return [
'status' => 'healthy',
'http_status' => $status,
'region' => $responseRegion,
];
}
if (in_array($status, [301, 307], true)
|| ($status === 400 && $responseRegion !== '')) {
throw new CloudObjectStorageTestError(
'Bucket 区域不匹配,请按对象存储返回的区域修改配置。',
'region_mismatch'
);
}
if (in_array($status, [401, 403], true)) {
throw new CloudObjectStorageTestError(
'凭据或 s3:ListBucket 权限不正确,请同时检查面板服务器时间。',
'auth_or_permission_denied'
);
}
if ($status === 404) {
throw new CloudObjectStorageTestError(
'指定的 Bucket 不存在,或当前地址无法访问该 Bucket。',
'bucket_not_found'
);
}
if ($status === 429) {
throw new CloudObjectStorageTestError(
'对象存储暂时限制请求,请稍后重试。',
'rate_limited'
);
}
if ($status >= 500) {
throw new CloudObjectStorageTestError(
'对象存储服务暂时不可用,请稍后重试。',
'service_unavailable'
);
}
throw new CloudObjectStorageTestError(
'对象存储拒绝了兼容性检查,请核对 Endpoint、Region 和寻址方式。',
'request_rejected'
);
}
private static function bucketUrl(
string $endpoint,
string $bucket,
bool $pathStyle
): string {
if ($pathStyle) {
return rtrim($endpoint, '/') . '/' . rawurlencode($bucket) . '/';
}
$parts = parse_url($endpoint);
if (!is_array($parts) || !isset($parts['scheme'], $parts['host'])) {
throw new \InvalidArgumentException('Invalid S3 endpoint');
}
$authority = $bucket . '.' . strtolower((string) $parts['host']);
if (isset($parts['port'])) {
$authority .= ':' . (int) $parts['port'];
}
return strtolower((string) $parts['scheme']) . '://' . $authority . '/';
}
}

@ -0,0 +1,14 @@
<?php
namespace App\Services\Cloud;
/** Stable, non-secret error returned by an S3 connectivity check. */
final class CloudObjectStorageTestError extends \RuntimeException
{
public function __construct(
string $message,
public readonly string $publicCode
) {
parent::__construct($message);
}
}

@ -0,0 +1,112 @@
<?php
namespace App\Services\Cloud;
/** Minimal AWS Signature Version 4 signer for S3 control requests. */
final class CloudS3Signer
{
private const EMPTY_PAYLOAD_HASH =
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
/**
* Return the request headers required for an AWS Signature Version 4 call.
*
* @return array<string, string>
*/
public static function sign(
string $method,
string $url,
string $region,
string $accessKeyId,
string $secretAccessKey,
int $timestamp,
?string $payloadHash = null
): array {
$parts = parse_url($url);
if (!is_array($parts) || !isset($parts['scheme'], $parts['host'])) {
throw new \InvalidArgumentException('Invalid S3 request URL');
}
$method = strtoupper($method);
$payloadHash = $payloadHash ?? self::EMPTY_PAYLOAD_HASH;
if (preg_match('/^[a-f0-9]{64}$/D', $payloadHash) !== 1) {
throw new \InvalidArgumentException('Invalid S3 payload hash');
}
$amzDate = gmdate('Ymd\THis\Z', $timestamp);
$date = gmdate('Ymd', $timestamp);
$host = self::hostHeader($parts);
$canonicalHeaders = 'host:' . $host . "\n"
. 'x-amz-content-sha256:' . $payloadHash . "\n"
. 'x-amz-date:' . $amzDate . "\n";
$signedHeaders = 'host;x-amz-content-sha256;x-amz-date';
$canonicalRequest = $method . "\n"
. self::canonicalUri((string) ($parts['path'] ?? '/')) . "\n"
. self::canonicalQuery((string) ($parts['query'] ?? '')) . "\n"
. $canonicalHeaders . "\n"
. $signedHeaders . "\n"
. $payloadHash;
$scope = $date . '/' . $region . '/s3/aws4_request';
$stringToSign = "AWS4-HMAC-SHA256\n" . $amzDate . "\n"
. $scope . "\n" . hash('sha256', $canonicalRequest);
$dateKey = hash_hmac('sha256', $date, 'AWS4' . $secretAccessKey, true);
$regionKey = hash_hmac('sha256', $region, $dateKey, true);
$serviceKey = hash_hmac('sha256', 's3', $regionKey, true);
$signingKey = hash_hmac('sha256', 'aws4_request', $serviceKey, true);
$signature = hash_hmac('sha256', $stringToSign, $signingKey);
return [
'Host' => $host,
'X-Amz-Content-Sha256' => $payloadHash,
'X-Amz-Date' => $amzDate,
'Authorization' => 'AWS4-HMAC-SHA256 Credential=' . $accessKeyId
. '/' . $scope . ',SignedHeaders=' . $signedHeaders
. ',Signature=' . $signature,
];
}
/** @param array<string, mixed> $parts */
private static function hostHeader(array $parts): string
{
$host = strtolower(trim((string) $parts['host'], '[]'));
if (str_contains($host, ':')) {
$host = '[' . $host . ']';
}
$port = isset($parts['port']) ? (int) $parts['port'] : null;
$scheme = strtolower((string) $parts['scheme']);
if ($port !== null && !(($scheme === 'https' && $port === 443)
|| ($scheme === 'http' && $port === 80))) {
$host .= ':' . $port;
}
return $host;
}
private static function canonicalUri(string $path): string
{
if ($path === '') {
return '/';
}
return implode('/', array_map(
static fn (string $segment): string => rawurlencode(rawurldecode($segment)),
explode('/', str_starts_with($path, '/') ? $path : '/' . $path)
));
}
private static function canonicalQuery(string $query): string
{
if ($query === '') {
return '';
}
$pairs = [];
foreach (explode('&', $query) as $part) {
[$name, $value] = array_pad(explode('=', $part, 2), 2, '');
$pairs[] = [rawurlencode(rawurldecode($name)), rawurlencode(rawurldecode($value))];
}
usort($pairs, static fn (array $left, array $right): int =>
$left[0] <=> $right[0] ?: $left[1] <=> $right[1]);
return implode('&', array_map(
static fn (array $pair): string => $pair[0] . '=' . $pair[1],
$pairs
));
}
}

@ -172,6 +172,10 @@ $app->group('/admin', function () {
// Host network preparation (administrator only).
$this->get('/hosts', 'App\Controllers\Admin\CloudPageController:hosts');
$this->get('/agents', 'App\Controllers\Admin\CloudPageController:agents');
$this->get('/object-storage', 'App\Controllers\Admin\ObjectStorageController:index');
$this->post('/object-storage/config', 'App\Controllers\Admin\ObjectStorageController:save')->add(new SuperAdmin());
$this->post('/object-storage/test', 'App\Controllers\Admin\ObjectStorageController:test')->add(new SuperAdmin());
$this->post('/object-storage/disable', 'App\Controllers\Admin\ObjectStorageController:disable')->add(new SuperAdmin());
$this->get('/cloud/templates', 'App\Controllers\Admin\CloudPageController:templates');
$this->get('/cloud/rescue', 'App\Controllers\Admin\CloudPageController:rescue');
$this->get('/cloud/instances', 'App\Controllers\Admin\CloudPageController:instances');

@ -0,0 +1,224 @@
{assign var=admin_active value='object-storage'}
{include file='admin/static_header.tpl'}
{literal}<style>
.os-page{display:grid;gap:20px;min-width:0;max-width:1080px;padding-bottom:30px}.os-head{display:flex;align-items:flex-start;justify-content:space-between;gap:18px}.os-head h1{margin:0 0 7px;font-size:28px;color:#0f172a}.os-head p{margin:0;color:#64748b;line-height:1.7}.os-card{min-width:0;border:1px solid #e2e8f0;border-radius:10px;background:#fff;box-shadow:0 10px 28px rgba(15,23,42,.05);padding:22px}.os-card-head{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;margin-bottom:20px}.os-card-head h2{margin:0 0 5px;font-size:20px;color:#172033}.os-card-head p{margin:0;color:#64748b;line-height:1.65}.os-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.os-field{display:grid;gap:7px;min-width:0}.os-field.is-wide{grid-column:1/-1}.os-field label{font-weight:700;color:#334155}.os-help{font-size:12px;line-height:1.55;color:#64748b}.os-mono{font-family:SFMono-Regular,Consolas,Liberation Mono,monospace}.os-secret-state{display:inline-flex;align-items:center;gap:6px;color:#047857;font-weight:700}.os-actions{display:flex;flex-wrap:wrap;align-items:center;gap:10px;margin-top:22px}.os-notice{display:none;flex:1 1 300px;padding:11px 13px;border-radius:7px;font-size:13px;line-height:1.55}.os-notice.is-show{display:block}.os-notice.is-ok{background:#ecfdf5;color:#047857}.os-notice.is-error{background:#fef2f2;color:#b91c1c}.os-alert{padding:13px 15px;border-radius:8px;line-height:1.65}.os-alert.is-error{background:#fef2f2;color:#b91c1c}.os-alert.is-info{background:#eff6ff;color:#1d4ed8}.os-status{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:18px}.os-status-item{padding:14px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc}.os-status-item span{display:block;margin-bottom:5px;color:#64748b;font-size:12px}.os-status-item strong{display:block;color:#1e293b;overflow-wrap:anywhere}.os-readonly{margin-bottom:16px;padding:11px 13px;border-radius:7px;background:#fff7ed;color:#9a3412}.os-scope{display:grid;gap:11px;margin:0;padding:0;list-style:none}.os-scope li{display:flex;align-items:flex-start;gap:10px;color:#475569;line-height:1.6}.os-scope i{margin-top:2px;color:#0ea5a4;font-size:18px}.os-scope li.is-muted i{color:#94a3b8}@media(max-width:760px){.os-page{gap:16px}.os-head{display:grid}.os-head h1{font-size:24px}.os-card{padding:17px}.os-grid,.os-status{grid-template-columns:1fr}.os-field.is-wide{grid-column:auto}.os-actions .btn{width:100%}.os-notice{flex-basis:100%}}
</style>{/literal}
<div class="os-page">
<header class="os-head">
<div>
<h1>对象存储</h1>
<p>配置一个由面板统一管理的 S3 兼容对象存储应用,支持 AWS S3、MinIO 及兼容服务。</p>
</div>
{if $object_storage}
<span class="badge bg-{$object_storage.status_class|escape}">{$object_storage.status_label|escape}</span>
{/if}
</header>
{if $object_storage_error != ''}
<div class="os-alert is-error">{$object_storage_error|escape}</div>
{/if}
<section class="os-card">
<div class="os-card-head">
<div>
<h2>连接配置</h2>
<p>保存后必须重新验证连接;验证成功前不会被后续云备份功能使用。</p>
</div>
<i class="mdi mdi-database-lock-outline fs-3 text-primary"></i>
</div>
{if $object_storage}
{if !$admin_can_manage|default:false}
<div class="os-readonly">当前账户只有查看权限,只有超级管理员可以保存、验证或停用对象存储。</div>
{/if}
<form id="objectStorageForm" action="/admin/object-storage/config" method="post" data-can-manage="{if $admin_can_manage|default:false}1{else}0{/if}">
<fieldset {if !$admin_can_manage|default:false}disabled{/if}>
<input type="hidden" name="expected_revision" value="{$object_storage.revision}">
<div class="os-grid">
<div class="os-field">
<label for="osName">应用名称</label>
<input class="form-control" id="osName" name="name" type="text" maxlength="80" value="{$object_storage.name|escape}" required>
</div>
<div class="os-field">
<label for="osDriver">驱动</label>
<input class="form-control" id="osDriver" type="text" value="S3 兼容(AWS S3 / MinIO)" readonly>
</div>
<div class="os-field is-wide">
<label for="osEndpoint">Endpoint</label>
<input class="form-control os-mono" id="osEndpoint" name="endpoint" type="url" inputmode="url" value="{$object_storage.endpoint|escape}" placeholder="https://s3.example.com" required>
<span class="os-help">必须使用有效 HTTPS 证书,只填写主机和可选端口,不包含 Bucket、路径或查询参数。</span>
</div>
<div class="os-field">
<label for="osRegion">Region</label>
<input class="form-control os-mono" id="osRegion" name="region" type="text" maxlength="63" value="{$object_storage.region|escape}" placeholder="us-east-1" required>
</div>
<div class="os-field">
<label for="osBucket">Bucket</label>
<input class="form-control os-mono" id="osBucket" name="bucket" type="text" minlength="3" maxlength="63" value="{$object_storage.bucket|escape}" placeholder="virt-cloud-backups" required>
</div>
<div class="os-field">
<label for="osPrefix">对象前缀</label>
<input class="form-control os-mono" id="osPrefix" name="prefix" type="text" maxlength="255" value="{$object_storage.prefix|escape}" placeholder="virt-cloud">
<span class="os-help">后续对象默认写入该逻辑目录;可留空使用 Bucket 根目录。</span>
</div>
<div class="os-field">
<label for="osPathStyle">寻址方式</label>
<select class="form-select" id="osPathStyle" name="path_style">
<option value="true" {if $object_storage.path_style}selected{/if}>路径寻址(MinIO / 兼容服务推荐)</option>
<option value="false" {if !$object_storage.path_style}selected{/if}>虚拟主机寻址(AWS S3 推荐)</option>
</select>
</div>
<div class="os-field">
<label for="osAccessKey">Access Key ID</label>
<input class="form-control os-mono" id="osAccessKey" name="access_key_id" type="password" value="" autocomplete="new-password" placeholder="{if $object_storage.credentials_configured}已加密保存,留空不修改{else}请输入 Access Key ID{/if}">
</div>
<div class="os-field">
<label for="osSecretKey">Secret Access Key</label>
<input class="form-control os-mono" id="osSecretKey" name="secret_access_key" type="password" value="" autocomplete="new-password" placeholder="{if $object_storage.credentials_configured}已加密保存,留空不修改{else}请输入 Secret Access Key{/if}">
</div>
<div class="os-field is-wide">
{if $object_storage.credentials_configured}
<span class="os-secret-state"><i class="mdi mdi-shield-check-outline"></i>访问凭据已使用面板 cloud_data_key 加密保存,页面不会回显。</span>
{else}
<span class="os-help">首次保存必须同时填写两项访问凭据。建议使用仅限目标 Bucket 的独立服务账户。</span>
{/if}
</div>
</div>
</fieldset>
<div class="os-status">
<div class="os-status-item"><span>配置版本</span><strong>#{$object_storage.revision}</strong></div>
<div class="os-status-item"><span>连接状态</span><strong>{$object_storage.status_label|escape}</strong></div>
<div class="os-status-item"><span>上次验证</span><strong>{if $object_storage.last_tested_at > 0}{$object_storage.last_tested_at_text|escape}{else}尚未验证{/if}</strong></div>
</div>
{if $object_storage.last_error != ''}
<div class="os-alert is-error" style="margin-top:14px">{$object_storage.last_error|escape}</div>
{/if}
<div class="os-actions">
<button class="btn btn-primary" id="osSave" type="submit" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-content-save-outline me-1"></i>保存配置</button>
<button class="btn btn-success" id="osTest" type="button" {if !$admin_can_manage|default:false || $object_storage.revision < 1}disabled{/if}><i class="mdi mdi-lan-connect me-1"></i>验证连接并启用</button>
<button class="btn btn-outline-danger" id="osDisable" type="button" {if !$admin_can_manage|default:false || !$object_storage.enabled}disabled{/if}><i class="mdi mdi-power me-1"></i>停用</button>
<div class="os-notice" id="osNotice" role="status" aria-live="polite"></div>
</div>
</form>
{/if}
</section>
<section class="os-card">
<div class="os-card-head"><div><h2>当前功能边界</h2><p>本阶段只建立安全、可验证的对象存储配置基础。</p></div></div>
<ul class="os-scope">
<li><i class="mdi mdi-check-circle-outline"></i><span>保存 S3 Endpoint、Region、Bucket、前缀和寻址方式,并加密保存访问凭据。</span></li>
<li><i class="mdi mdi-check-circle-outline"></i><span>使用签名的 HeadBucket 请求验证 Bucket 可达性和 <span class="os-mono">s3:ListBucket</span> 权限;测试不会写入对象。</span></li>
<li class="is-muted"><i class="mdi mdi-clock-outline"></i><span>云备份上传、增量链、保留策略、加密备份和异地恢复尚未接入,等待对象存储配置稳定后单独开发。</span></li>
</ul>
</section>
</div>
{literal}<script>
(function () {
'use strict';
var form = document.getElementById('objectStorageForm');
if (!form) return;
var notice = document.getElementById('osNotice');
var saveButton = document.getElementById('osSave');
var testButton = document.getElementById('osTest');
var disableButton = document.getElementById('osDisable');
var canManage = form.dataset.canManage === '1';
var dirty = false;
function show(message, ok) {
notice.textContent = message;
notice.className = 'os-notice is-show ' + (ok ? 'is-ok' : 'is-error');
}
function request(url, payload) {
return fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
body: JSON.stringify(payload)
}).then(function (response) {
return response.text().then(function (text) {
var result;
try { result = JSON.parse(text); }
catch (error) { throw new Error('服务器未返回有效结果(HTTP ' + response.status + ')'); }
if (!response.ok || Number(result.ret) !== 1) {
throw new Error(result.msg || '请求失败');
}
return result;
});
});
}
function revision() {
return Number(form.elements.expected_revision.value || 0);
}
function setBusy(busy) {
saveButton.disabled = busy || !canManage;
testButton.disabled = busy || !canManage || revision() < 1 || dirty;
disableButton.disabled = busy || !canManage || disableButton.dataset.disabled === '1';
}
disableButton.dataset.disabled = disableButton.disabled ? '1' : '0';
form.addEventListener('input', function () {
if (!canManage || dirty) return;
dirty = true;
setBusy(false);
show('配置已修改,请先保存,再验证当前版本。', true);
});
form.addEventListener('submit', function (event) {
event.preventDefault();
if (!canManage || saveButton.disabled) return;
var payload = {};
new FormData(form).forEach(function (value, key) { payload[key] = String(value); });
setBusy(true);
show('正在加密并保存配置...', true);
request('/admin/object-storage/config', payload).then(function (result) {
form.elements.access_key_id.value = '';
form.elements.secret_access_key.value = '';
show(result.msg, true);
window.setTimeout(function () { window.location.reload(); }, 650);
}).catch(function (error) {
show(error.message, false);
setBusy(false);
});
});
testButton.addEventListener('click', function () {
if (!canManage || testButton.disabled) return;
setBusy(true);
show('正在执行签名的 Bucket 连接验证...', true);
request('/admin/object-storage/test', { expected_revision: revision() }).then(function (result) {
show(result.msg, true);
window.setTimeout(function () { window.location.reload(); }, 650);
}).catch(function (error) {
show(error.message, false);
window.setTimeout(function () { window.location.reload(); }, 1200);
});
});
disableButton.addEventListener('click', function () {
if (!canManage || disableButton.disabled) return;
if (!window.confirm('确认停用对象存储?已保存的加密凭据不会被删除。')) return;
setBusy(true);
show('正在停用对象存储...', true);
request('/admin/object-storage/disable', { expected_revision: revision() }).then(function (result) {
show(result.msg, true);
window.setTimeout(function () { window.location.reload(); }, 650);
}).catch(function (error) {
show(error.message, false);
setBusy(false);
});
});
})();
</script>{/literal}
{include file='admin/static_footer.tpl'}

@ -162,6 +162,7 @@
<li><a class="{if $admin_active|default:'' == 'resources'}active{/if}" href="/admin/resources"><i class="mdi mdi-server-network-outline"></i><span>资源调度</span></a></li>
<li><a class="{if $admin_active|default:'' == 'hosts'}active{/if}" href="/admin/hosts"><i class="mdi mdi-router-network"></i><span>计算节点</span></a></li>
<li><a class="{if $admin_active|default:'' == 'agents'}active{/if}" href="/admin/agents"><i class="mdi mdi-api"></i><span>Agent API</span></a></li>
<li><a class="{if $admin_active|default:'' == 'object-storage'}active{/if}" href="/admin/object-storage"><i class="mdi mdi-cloud-lock-outline"></i><span>对象存储</span></a></li>
<li><a class="{if $admin_active|default:'' == 'cloud-templates'}active{/if}" href="/admin/cloud/templates"><i class="mdi mdi-disc"></i><span>云镜像模版</span></a></li>
<li><a class="{if $admin_active|default:'' == 'cloud-rescue'}active{/if}" href="/admin/cloud/rescue"><i class="mdi mdi-lifebuoy"></i><span>救援模版</span></a></li>
<li><a class="{if $admin_active|default:'' == 'cloud-instances'}active{/if}" href="/admin/cloud/instances"><i class="mdi mdi-server"></i><span>虚拟机管理</span></a></li>

@ -0,0 +1,65 @@
<?php
$root = dirname(__DIR__);
$read = static function (string $path) use ($root): string {
$contents = file_get_contents($root . '/' . $path);
if ($contents === false) {
throw new RuntimeException('Unable to read ' . $path);
}
return $contents;
};
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$routes = $read('config/routes.php');
$controller = $read('app/Controllers/Admin/ObjectStorageController.php');
$service = $read('app/Services/Cloud/CloudObjectStorageConfig.php');
$client = $read('app/Services/Cloud/CloudObjectStorageS3Client.php');
$template = $read('resources/views/venix/admin/object_storage.tpl');
$sidebar = $read('resources/views/venix/admin/static_header.tpl');
$deployment = file_get_contents(dirname($root) . '/docs/DEPLOYMENT.md');
$validation = file_get_contents(dirname($root) . '/docs/VALIDATION.md');
$assert(str_contains($routes,
"get('/object-storage', 'App\\Controllers\\Admin\\ObjectStorageController:index')"),
'Object-storage admin page route is missing.');
foreach (['config' => 'save', 'test' => 'test', 'disable' => 'disable'] as $path => $action) {
$needle = "post('/object-storage/{$path}', 'App\\Controllers\\Admin\\ObjectStorageController:{$action}')->add(new SuperAdmin())";
$assert(str_contains($routes, $needle),
'Object-storage mutation lost SuperAdmin/CSRF middleware: ' . $action);
}
$assert(str_contains($sidebar, 'href="/admin/object-storage"')
&& str_contains($sidebar, '<span>对象存储</span>'),
'Object-storage navigation entry is missing.');
$assert(str_contains($service, "CloudSecrets::encrypt([")
&& str_contains($service, "'object-storage-credentials'")
&& str_contains($service, "lockForUpdate()")
&& str_contains($service, "tested_revision")
&& str_contains($service, "expected_revision"),
'Object-storage encryption, revision, or readiness gate is missing.');
$assert(str_contains($client, "request('HEAD'")
&& str_contains($client, "'allow_redirects' => false")
&& str_contains($client, "'verify' => true")
&& str_contains($client, "'proxy' => ''")
&& !str_contains($client, "request('PUT'")
&& !str_contains($client, "request('DELETE'"),
'Connectivity test is no longer a bounded, read-only, TLS-strict HeadBucket call.');
$assert(substr_count($template, 'name="access_key_id" type="password" value=""') === 1
&& substr_count($template, 'name="secret_access_key" type="password" value=""') === 1
&& !str_contains($template, '$object_storage.access_key_id')
&& !str_contains($template, '$object_storage.secret_access_key')
&& str_contains($template, 'data-can-manage=')
&& str_contains($template, 's3:ListBucket'),
'Admin UI can expose credentials or lost its permission/test boundary.');
$assert(str_contains($controller, "'Cache-Control', 'private, no-store'")
&& preg_match('/error_log\\([^\\n]*getMessage/', $controller) !== 1,
'Object-storage responses lost no-store or may log raw exception messages.');
$assert(is_string($deployment) && str_contains($deployment, '### 对象存储应用')
&& str_contains($deployment, '尚未接入云备份上传')
&& is_string($validation) && str_contains($validation, '对象存储配置页面不得回显'),
'Deployment or validation boundaries are not documented.');
echo "Object-storage admin routes, UI, security, and documentation contract passed.\n";

@ -0,0 +1,153 @@
<?php
namespace App\Services {
final class Config
{
public static string $dataKey = '';
public static function get($name, $default = null)
{
return $name === 'cloud_data_key' ? self::$dataKey : $default;
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\Configurations;
use App\Services\Config;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudObjectStorageConfig;
use App\Services\Cloud\CloudObjectStorageS3Client;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
if (!function_exists('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt')) {
echo "SKIPPED CloudObjectStorageConfigTest: runtime lacks sodium.\n";
exit(0);
}
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expectCloudError = static function (callable $callback, int $status) use ($assert): CloudError {
try {
$callback();
} catch (CloudError $error) {
$assert($error->httpStatus === $status,
'Unexpected object-storage error status: ' . $error->httpStatus);
return $error;
}
throw new RuntimeException('Expected object-storage error was not raised.');
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema()->create('configurations', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name')->unique();
$table->text('value')->nullable();
});
Config::$dataKey = base64_encode(str_repeat('o', 32));
$payload = [
'name' => '测试对象存储',
'endpoint' => 'https://minio.internal:9000',
'region' => 'us-east-1',
'bucket' => 'test-bucket',
'prefix' => 'virt-cloud/backups',
'path_style' => 'true',
'access_key_id' => 'TESTACCESSKEY',
'secret_access_key' => 'test-secret-key-value',
'expected_revision' => 0,
];
$saved = CloudObjectStorageConfig::save($payload);
$databaseValues = Configurations::pluck('value')->map(
static fn ($value): string => (string) $value
)->implode("\n");
$publicJson = json_encode($saved, JSON_THROW_ON_ERROR);
$assert($saved['revision'] === 1 && !$saved['enabled'] && !$saved['ready']
&& $saved['credentials_configured']
&& !str_contains($databaseValues, 'TESTACCESSKEY')
&& !str_contains($databaseValues, 'test-secret-key-value')
&& !str_contains($publicJson, 'TESTACCESSKEY')
&& !str_contains($publicJson, 'test-secret-key-value')
&& !array_key_exists('sealed_credentials', $saved)
&& !array_key_exists('access_key_id', $saved)
&& !array_key_exists('secret_access_key', $saved),
'Object-storage save did not seal credentials or leaked them in its DTO.');
$healthyClient = new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create(new MockHandler([new Response(200)])),
]));
$ready = CloudObjectStorageConfig::testAndEnable(1, $healthyClient);
$assert($ready['enabled'] && $ready['ready']
&& $ready['tested_revision'] === 1
&& $ready['last_test_status'] === 'healthy',
'Successful current-revision connectivity test did not enable storage.');
$changed = $payload;
$changed['bucket'] = 'second-bucket';
$changed['access_key_id'] = '';
$changed['secret_access_key'] = '';
$changed['expected_revision'] = '1';
$changedState = CloudObjectStorageConfig::save($changed);
$assert($changedState['revision'] === 2 && !$changedState['enabled']
&& !$changedState['ready'] && $changedState['last_test_status'] === 'never'
&& $changedState['credentials_configured'],
'Configuration change did not preserve sealed credentials and invalidate readiness.');
$expectCloudError(static function () use ($changed): void {
$changed['expected_revision'] = '1';
CloudObjectStorageConfig::save($changed);
}, 409);
$expectCloudError(static function () use ($changed): void {
$changed['endpoint'] = 'http://127.0.0.1:9000';
$changed['expected_revision'] = '2';
CloudObjectStorageConfig::save($changed);
}, 422);
$deniedClient = new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create(new MockHandler([new Response(403)])),
]));
$denied = $expectCloudError(static function () use ($deniedClient): void {
CloudObjectStorageConfig::testAndEnable(2, $deniedClient);
}, 502);
$failed = CloudObjectStorageConfig::view();
$assert($failed['last_test_status'] === 'failed'
&& $failed['last_error_code'] === 'auth_or_permission_denied'
&& !$failed['enabled'] && !$failed['ready']
&& !str_contains($denied->getMessage(), 'test-secret'),
'Failed test was not persisted safely or exposed credential material.');
$recovered = CloudObjectStorageConfig::testAndEnable(2,
new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create(new MockHandler([new Response(200)])),
])));
$assert($recovered['ready'], 'A later successful test did not recover readiness.');
$disabled = CloudObjectStorageConfig::disable('2');
$assert($disabled['revision'] === 3 && !$disabled['enabled']
&& !$disabled['ready'] && $disabled['credentials_configured']
&& $disabled['last_test_status'] === 'disabled'
&& $disabled['status_label'] === '已停用',
'Disable did not invalidate an in-flight test generation or preserve credentials.');
$ipv6Virtual = $changed;
$ipv6Virtual['endpoint'] = 'https://[2001:db8::2]:9000';
$ipv6Virtual['path_style'] = 'false';
$ipv6Virtual['expected_revision'] = '3';
$expectCloudError(static function () use ($ipv6Virtual): void {
CloudObjectStorageConfig::save($ipv6Virtual);
}, 422);
echo "Object-storage encrypted configuration and revision gate passed.\n";
}

@ -0,0 +1,101 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
if ((error_reporting() & $severity) && ($severity & (E_WARNING | E_USER_WARNING | E_DEPRECATED))) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
return false;
});
$smarty = new Smarty();
$compileDir = sys_get_temp_dir() . '/object-storage-view-' . bin2hex(random_bytes(6));
mkdir($compileDir);
$smarty->setCompileDir($compileDir);
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
$smarty->assign('config', ['appName' => 'Virt Test']);
$smarty->assign('cdn', '');
$smarty->assign('user', (object) ['isLogin' => false]);
$smarty->assign('admin_csrf_token', str_repeat('c', 64));
$smarty->assign('admin_display_user_name', 'admin');
$state = [
'name' => '"><script>window.__objectStorageXss=1</script>测试存储',
'driver' => 's3',
'endpoint' => 'https://minio.example.com:9000',
'region' => 'us-east-1',
'bucket' => 'test-bucket',
'prefix' => 'virt-cloud/backups',
'path_style' => true,
'enabled' => true,
'ready' => true,
'configured' => true,
'credentials_configured' => true,
'revision' => 7,
'tested_revision' => 7,
'last_test_status' => 'healthy',
'last_error_code' => '',
'last_error' => '',
'last_tested_at' => 1792876800,
'last_tested_at_text' => '2026-10-25 00:00:00',
'status_label' => '已启用',
'status_class' => 'success',
];
$render = static function (bool $canManage) use ($smarty, $state): string {
$smarty->assign('admin_can_manage', $canManage);
$smarty->assign('object_storage', $state);
$smarty->assign('object_storage_error', '');
return $smarty->fetch('admin/object_storage.tpl');
};
$html = $render(true);
$readonlyHtml = $render(false);
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$parse = static function (string $document): DOMXPath {
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8">' . $document);
return new DOMXPath($dom);
};
$one = static function (DOMXPath $xpath, string $query) use ($assert): DOMElement {
$nodes = $xpath->query($query);
$assert($nodes->length === 1 && $nodes->item(0) instanceof DOMElement,
'Expected one element matching ' . $query);
return $nodes->item(0);
};
$xpath = $parse($html);
$form = $one($xpath, '//form[@id="objectStorageForm"]');
$assert($form->getAttribute('action') === '/admin/object-storage/config'
&& $form->getAttribute('method') === 'post'
&& $form->getAttribute('data-can-manage') === '1',
'Object-storage form method, endpoint, or permission marker changed.');
$assert($one($xpath, '//input[@id="osName"]')->getAttribute('value') === $state['name']
&& $xpath->query('//script[contains(.,"__objectStorageXss")]')->length === 0,
'Object-storage application name escaped its value attribute.');
foreach (['osAccessKey', 'osSecretKey'] as $id) {
$secret = $one($xpath, '//input[@id="' . $id . '"]');
$assert($secret->getAttribute('type') === 'password'
&& $secret->getAttribute('value') === '',
'A stored object-storage credential can be rendered into the browser.');
}
$assert($one($xpath, '//input[@name="expected_revision"]')->getAttribute('value') === '7'
&& !$one($xpath, '//button[@id="osSave"]')->hasAttribute('disabled')
&& !$one($xpath, '//button[@id="osTest"]')->hasAttribute('disabled')
&& !$one($xpath, '//button[@id="osDisable"]')->hasAttribute('disabled'),
'Writable object-storage state did not render its current revision and actions.');
$readonly = $parse($readonlyHtml);
$assert($one($readonly, '//fieldset')->hasAttribute('disabled')
&& $one($readonly, '//button[@id="osSave"]')->hasAttribute('disabled')
&& $one($readonly, '//button[@id="osTest"]')->hasAttribute('disabled')
&& $one($readonly, '//button[@id="osDisable"]')->hasAttribute('disabled'),
'Ordinary administrator object-storage controls are not read-only.');
$assert(str_contains($html, 'window.ADMIN_CSRF_TOKEN ='),
'Shared administrator CSRF bootstrap is missing from object-storage page.');
echo "Object-storage administrator template rendering passed.\n";

@ -0,0 +1,95 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudObjectStorageS3Client;
use App\Services\Cloud\CloudObjectStorageTestError;
use App\Services\Cloud\CloudS3Signer;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Response;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$timestamp = strtotime('2013-05-24T00:00:00Z');
$secret = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';
$expected = 'AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/'
. '20130524/us-east-1/s3/aws4_request,'
. 'SignedHeaders=host;x-amz-content-sha256;x-amz-date,'
. 'Signature=34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7';
$headers = CloudS3Signer::sign(
'GET',
'https://examplebucket.s3.amazonaws.com/?max-keys=2&prefix=J',
'us-east-1',
'AKIAIOSFODNN7EXAMPLE',
$secret,
$timestamp
);
$assert($headers['Authorization'] === $expected,
'AWS published Signature Version 4 example no longer matches.');
$reordered = CloudS3Signer::sign(
'GET',
'https://examplebucket.s3.amazonaws.com/?prefix=J&max-keys=2',
'us-east-1',
'AKIAIOSFODNN7EXAMPLE',
$secret,
$timestamp
);
$assert($reordered['Authorization'] === $expected,
'S3 query parameters were not canonicalized before signing.');
$history = [];
$stack = HandlerStack::create(new MockHandler([
new Response(200, ['x-amz-bucket-region' => 'us-east-1']),
]));
$stack->push(Middleware::history($history));
$client = new CloudObjectStorageS3Client(new Client(['handler' => $stack]));
$result = $client->headBucket([
'endpoint' => 'https://minio.example.com:9000',
'region' => 'us-east-1',
'bucket' => 'test-bucket',
'path_style' => true,
], [
'access_key_id' => 'TESTACCESSKEY',
'secret_access_key' => 'test-secret-key-value',
]);
$assert($result['status'] === 'healthy' && count($history) === 1,
'Successful HeadBucket response was not accepted.');
$transaction = $history[0];
$assert($transaction['request']->getMethod() === 'HEAD'
&& (string) $transaction['request']->getUri()
=== 'https://minio.example.com:9000/test-bucket/'
&& str_starts_with($transaction['request']->getHeaderLine('Authorization'),
'AWS4-HMAC-SHA256 ')
&& $transaction['options']['allow_redirects'] === false
&& $transaction['options']['verify'] === true
&& $transaction['options']['proxy'] === '',
'Object-storage check lost its signed, read-only, TLS-strict request contract.');
$denied = new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create(new MockHandler([new Response(403)])),
]));
try {
$denied->headBucket([
'endpoint' => 'https://s3.example.com',
'region' => 'us-east-1',
'bucket' => 'test-bucket',
'path_style' => true,
], [
'access_key_id' => 'TESTACCESSKEY',
'secret_access_key' => 'never-leak-this-secret',
]);
throw new RuntimeException('Denied HeadBucket response was accepted.');
} catch (CloudObjectStorageTestError $error) {
$assert($error->publicCode === 'auth_or_permission_denied'
&& !str_contains($error->getMessage(), 'never-leak'),
'HeadBucket error mapping leaked credentials or changed its stable code.');
}
echo "S3 Signature Version 4 and read-only HeadBucket contract passed.\n";
Loading…
Cancel
Save