From d7d3c621c9e90d5973cd8f44fba0c9dddb8a5356 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 25 Oct 2026 05:14:26 +0800 Subject: [PATCH] feat(web): add S3 object storage configuration --- docs/DEPLOYMENT.md | 11 +- docs/PRUNING_REPORT.md | 1 + docs/VALIDATION.md | 3 + .../Admin/ObjectStorageController.php | 94 +++ .../Cloud/CloudObjectStorageConfig.php | 537 ++++++++++++++++++ .../Cloud/CloudObjectStorageS3Client.php | 118 ++++ .../Cloud/CloudObjectStorageTestError.php | 14 + web/app/Services/Cloud/CloudS3Signer.php | 112 ++++ web/config/routes.php | 4 + .../views/venix/admin/object_storage.tpl | 224 ++++++++ .../views/venix/admin/static_header.tpl | 1 + .../CloudObjectStorageAdminContractTest.php | 65 +++ web/tests/CloudObjectStorageConfigTest.php | 153 +++++ web/tests/CloudObjectStorageViewTest.php | 101 ++++ web/tests/CloudS3SignerTest.php | 95 ++++ 15 files changed, 1532 insertions(+), 1 deletion(-) create mode 100644 web/app/Controllers/Admin/ObjectStorageController.php create mode 100644 web/app/Services/Cloud/CloudObjectStorageConfig.php create mode 100644 web/app/Services/Cloud/CloudObjectStorageS3Client.php create mode 100644 web/app/Services/Cloud/CloudObjectStorageTestError.php create mode 100644 web/app/Services/Cloud/CloudS3Signer.php create mode 100644 web/resources/views/venix/admin/object_storage.tpl create mode 100644 web/tests/CloudObjectStorageAdminContractTest.php create mode 100644 web/tests/CloudObjectStorageConfigTest.php create mode 100644 web/tests/CloudObjectStorageViewTest.php create mode 100644 web/tests/CloudS3SignerTest.php diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 59329b17..bb309746 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -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 创建成功不等待脚本完成,脚本失败或中断不自动重放。 diff --git a/docs/PRUNING_REPORT.md b/docs/PRUNING_REPORT.md index 31626cc3..6e702e0c 100644 --- a/docs/PRUNING_REPORT.md +++ b/docs/PRUNING_REPORT.md @@ -10,6 +10,7 @@ - 多宿主机、资源池、容量策略、reservation、具体公网 IP 账本、多 CIDR、云镜像、救援 ISO、快照、防火墙、指标与控制台入口。 - 管理员工单 Telegram 通知;普通用户仍只在网页处理工单。 - 公开产品落地页,以及后台统一维护、带草稿和发布历史的全局服务条款与隐私政策页面;法律内容不按域名拆分。 +- 后台全局 S3 兼容对象存储应用配置、密钥密封和只读连接验证;云备份上传、增量链、保留策略与异地恢复暂未接入。 ## 删除 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 41fe3c6e..90adf5f1 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -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. 非生产宿主机验收 diff --git a/web/app/Controllers/Admin/ObjectStorageController.php b/web/app/Controllers/Admin/ObjectStorageController.php new file mode 100644 index 00000000..31d536c2 --- /dev/null +++ b/web/app/Controllers/Admin/ObjectStorageController.php @@ -0,0 +1,94 @@ +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|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'); + } +} diff --git a/web/app/Services/Cloud/CloudObjectStorageConfig.php b/web/app/Services/Cloud/CloudObjectStorageConfig.php new file mode 100644 index 00000000..1e98c976 --- /dev/null +++ b/web/app/Services/Cloud/CloudObjectStorageConfig.php @@ -0,0 +1,537 @@ + '默认对象存储', + '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 */ + public static function view(): array + { + return self::publicState(self::readRaw()); + } + + /** @return array */ + 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 */ + 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 */ + 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,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 */ + 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 $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 $raw + * @return array{config:array,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 $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; + } + } + } +} diff --git a/web/app/Services/Cloud/CloudObjectStorageS3Client.php b/web/app/Services/Cloud/CloudObjectStorageS3Client.php new file mode 100644 index 00000000..a9bd4ead --- /dev/null +++ b/web/app/Services/Cloud/CloudObjectStorageS3Client.php @@ -0,0 +1,118 @@ + $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 . '/'; + } +} diff --git a/web/app/Services/Cloud/CloudObjectStorageTestError.php b/web/app/Services/Cloud/CloudObjectStorageTestError.php new file mode 100644 index 00000000..12834c8a --- /dev/null +++ b/web/app/Services/Cloud/CloudObjectStorageTestError.php @@ -0,0 +1,14 @@ + + */ + 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 $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 + )); + } +} diff --git a/web/config/routes.php b/web/config/routes.php index f6db1981..6bf9d64e 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -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'); diff --git a/web/resources/views/venix/admin/object_storage.tpl b/web/resources/views/venix/admin/object_storage.tpl new file mode 100644 index 00000000..1c408d5e --- /dev/null +++ b/web/resources/views/venix/admin/object_storage.tpl @@ -0,0 +1,224 @@ +{assign var=admin_active value='object-storage'} +{include file='admin/static_header.tpl'} + +{literal}{/literal} + +
+
+
+

对象存储

+

配置一个由面板统一管理的 S3 兼容对象存储应用,支持 AWS S3、MinIO 及兼容服务。

+
+ {if $object_storage} + {$object_storage.status_label|escape} + {/if} +
+ + {if $object_storage_error != ''} +
{$object_storage_error|escape}
+ {/if} + +
+
+
+

连接配置

+

保存后必须重新验证连接;验证成功前不会被后续云备份功能使用。

+
+ +
+ + {if $object_storage} + {if !$admin_can_manage|default:false} +
当前账户只有查看权限,只有超级管理员可以保存、验证或停用对象存储。
+ {/if} +
+
+ +
+
+ + +
+
+ + +
+
+ + + 必须使用有效 HTTPS 证书,只填写主机和可选端口,不包含 Bucket、路径或查询参数。 +
+
+ + +
+
+ + +
+
+ + + 后续对象默认写入该逻辑目录;可留空使用 Bucket 根目录。 +
+
+ + +
+
+ + +
+
+ + +
+
+ {if $object_storage.credentials_configured} + 访问凭据已使用面板 cloud_data_key 加密保存,页面不会回显。 + {else} + 首次保存必须同时填写两项访问凭据。建议使用仅限目标 Bucket 的独立服务账户。 + {/if} +
+
+
+ +
+
配置版本#{$object_storage.revision}
+
连接状态{$object_storage.status_label|escape}
+
上次验证{if $object_storage.last_tested_at > 0}{$object_storage.last_tested_at_text|escape}{else}尚未验证{/if}
+
+ {if $object_storage.last_error != ''} +
{$object_storage.last_error|escape}
+ {/if} + +
+ + + +
+
+
+ {/if} +
+ +
+

当前功能边界

本阶段只建立安全、可验证的对象存储配置基础。

+
    +
  • 保存 S3 Endpoint、Region、Bucket、前缀和寻址方式,并加密保存访问凭据。
  • +
  • 使用签名的 HeadBucket 请求验证 Bucket 可达性和 s3:ListBucket 权限;测试不会写入对象。
  • +
  • 云备份上传、增量链、保留策略、加密备份和异地恢复尚未接入,等待对象存储配置稳定后单独开发。
  • +
+
+
+ +{literal}{/literal} + +{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/static_header.tpl b/web/resources/views/venix/admin/static_header.tpl index b9fbaca0..d12ef338 100644 --- a/web/resources/views/venix/admin/static_header.tpl +++ b/web/resources/views/venix/admin/static_header.tpl @@ -162,6 +162,7 @@
  • 资源调度
  • 计算节点
  • Agent API
  • +
  • 对象存储
  • 云镜像模版
  • 救援模版
  • 虚拟机管理
  • diff --git a/web/tests/CloudObjectStorageAdminContractTest.php b/web/tests/CloudObjectStorageAdminContractTest.php new file mode 100644 index 00000000..965e6981 --- /dev/null +++ b/web/tests/CloudObjectStorageAdminContractTest.php @@ -0,0 +1,65 @@ + '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, '对象存储'), + '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"; diff --git a/web/tests/CloudObjectStorageConfigTest.php b/web/tests/CloudObjectStorageConfigTest.php new file mode 100644 index 00000000..60b910f0 --- /dev/null +++ b/web/tests/CloudObjectStorageConfigTest.php @@ -0,0 +1,153 @@ +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"; +} diff --git a/web/tests/CloudObjectStorageViewTest.php b/web/tests/CloudObjectStorageViewTest.php new file mode 100644 index 00000000..9821626c --- /dev/null +++ b/web/tests/CloudObjectStorageViewTest.php @@ -0,0 +1,101 @@ +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' => '">测试存储', + '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('' . $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"; diff --git a/web/tests/CloudS3SignerTest.php b/web/tests/CloudS3SignerTest.php new file mode 100644 index 00000000..cac4e65a --- /dev/null +++ b/web/tests/CloudS3SignerTest.php @@ -0,0 +1,95 @@ + '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";