test(template): harden import recovery contracts

go
codex 3 weeks ago
parent b16a1c84b4
commit 9fa30d659e

@ -184,12 +184,12 @@ Go context 无法可靠中止已进入 CGo/libvirt 的调用。父 Agent 到达
| GET/POST | `/v1/user-isos?owner_id=...` | 列出 / 导入用户 ISO |
| DELETE | `/v1/user-isos/{id}?owner_id=...` | 删除用户 ISO |
面板暂存的云镜像和救援 ISO 导入请求会在签名正文中携带
`source_size_bytes`。若反向代理把下载响应改为 chunked、使 Agent 无法读取
`Content-Length`,Agent 使用该不可变预期大小创建有界 stream;若响应仍包含
云镜像和救援 ISO 的 Agent 导入请求只携带对象存储中不可变主副本的短期
只读地址、`source_size_bytes` 与 SHA-256;管理员填写的原始官方地址和浏览器
本地文件不会下发到 Agent。若对象存储响应使用 chunked、使 Agent 无法读取
`Content-Length`,Agent 使用不可变预期大小创建有界 stream;若响应仍包含
长度则必须与预期完全一致,最终正文也必须恰好为该字节数并通过 SHA-256
校验。远程 URL 导入不携带该字段,仍必须返回有效的 `Content-Length`。
任何导入源都不得使用压缩 `Content-Encoding`。
校验。任何导入源都不得使用压缩 `Content-Encoding`。
不存在通用 mutation `reconcile`、`confirm-inspection`、`abort-job` 或任意资源 `cleanup` endpoint。`inspect` 不取得 mutation admission,不写 Journal,不继续原目标,也不能调用任何 libvirt 变更。唯一的备份工作区清理接口在下节说明:它只能消费原成功备份返回的最新 evidence-bound plan,不能接受路径、卷名或任意清理步骤。不可变 Journal 成功或明确无副作用失败可以为策略表中的任何类型提供精确结论;其他已失败且影响未知的类型只有在该 action 的专用投影证据完整匹配时才能输出 `applied/not_applied`,否则保持 `partial/inconclusive`。例如实例设置只有在 Domain metadata 与 NoCloud seed 都匹配同一 transition ID 时才是 `applied`,两者都确认未提交时才是 `not_applied`。电源、网络链路或服务的“当前状态刚好符合目标”不是原 operation 的强证据,必须保持 `inconclusive`。

@ -97,7 +97,7 @@ php xcat cloudRepairInstanceMetadata --apply
Access Key ID 与 Secret Access Key 只在超级管理员提交时进入 PHP,使用 `cloud_data_key` 的独立用途密钥密封后保存,读取页面不会回显。修改任一配置或停用应用都会清除原就绪标记;必须重新执行“验证连接并启用”。连接验证只发送签名的 `HeadBucket` 请求,需要目标 Bucket 的 `s3:ListBucket` 权限,不上传、覆盖或删除对象。管理员虚拟机管理已接入完整系统盘备份和新实例恢复,目标可以是原宿主机或其他合格宿主机;用户自动备份使用同一对象存储,在实例设置中按每天或每周于 UTC 00:00 调度并保留最多两份。云镜像导入还会先把经过校验的内容发布到 `cloud-templates/` 不可变主副本,再向宿主机签发该精确版本的只读地址;没有旧本地模板路径或直接暂存分发回退。运行账户需要在配置前缀下同时授予 `vm-backups/` 与 `cloud-templates/` 的上传、`GetObject`、`HeadObject` 和 `DeleteObject` 权限;开启 Bucket 版本控制时还必须授予 `s3:GetObjectVersion` 与 `s3:DeleteObjectVersion`,让 HEAD 与删除准确绑定 `versionId`。维护迁移使用宿主机间 PeerMigration V3 直传,不创建 S3 迁移对象,也不需要 `vm-migrations/` 权限。当前不包含增量链和管理员手工备份的自动保留策略,具体安全边界见 `docs/PORTABLE_VM_BACKUPS.md`。
生产 Bucket 必须把生命周期规则作为控制面之外的最后兜底:建议在 1 天后终止未完成 multipart upload;开启版本控制时,按业务保留要求清理 `vm-backups/` 的非当前版本和过期删除标记。生命周期不得提前删除仍由面板备份或云镜像目录引用的当前版本。管理员本地上传云镜像时,浏览器直接向对象存储执行分片 `PUT`,Bucket CORS 必须只允许面板 HTTPS origin,允许 `PUT`,并在 `ExposeHeaders` 中公开 `ETag`;不要使用 `*` origin 搭配管理站点。面板保存每个已确认分片,刷新后重新选择同一文件会跳过这些分片;取消或 24 小时过期后,普通 worker 会中止仍可确认的 multipart。若创建 multipart 的响应在 upload ID 返回前丢失,面板只能放弃该上传记录,因此上述生命周期规则是清除提供商残留分片的必需兜底。
生产 Bucket 必须把生命周期规则作为控制面之外的最后兜底:建议在 1 天后终止未完成 multipart upload;开启版本控制时,按业务保留要求清理 `vm-backups/` 与 `cloud-templates/` 的非当前版本和过期删除标记。生命周期不得提前删除仍由面板备份、云镜像目录或未完成导入意图引用的当前版本。管理员本地上传云镜像时,浏览器直接向对象存储执行分片 `PUT`,Bucket CORS 必须只允许面板 HTTPS origin,允许 `PUT`,并在 `ExposeHeaders` 中公开 `ETag`;不要使用 `*` origin 搭配管理站点。面板保存每个已确认分片,刷新后重新选择同一文件会跳过这些分片;取消或 24 小时过期后,普通 worker 会中止仍可确认的 multipart。若创建 multipart 的响应在 upload ID 返回前丢失,面板只能放弃该上传记录,因此上述生命周期规则是清除提供商残留分片的必需兜底。官方地址导入先持久化同一导入意图和唯一对象键,再由 PHP 有界下载、校验并发布;正常结束立即删除本地临时文件,进程硬中止遗留的同前缀普通文件由 worker 在 24 小时后逐个回收。PUT 结果不明时只允许用同一对象键执行 HEAD 核对,不能新建导入或盲目重写。
面板会保存 HEAD 返回的 ETag 与 `version_id`,删除时精确定位该版本;删除结果不明时先进行间隔稳定 HEAD,只有对象身份完全一致才创建新的删除代次,每个自动周期最多三次。达到上限的对象进入后台人工核对,不再自动删除;对象存储页面的“重新核对”只恢复稳定 HEAD 证据流程,不会重放原 DELETE。云镜像的人工重试同样只恢复对象存储核对,不会再次删除宿主机副本。
@ -354,7 +354,7 @@ location = /agent/console {
1. 在 `/admin/agents` 为每台宿主机保存独立密钥,在 Agent 配置中写入面板 HTTPS 地址、对应数字 ID 和同一密钥;出站连接测试通过但先保持调度 disabled。
2. 创建宿主机业务记录、地区、资源池成员关系、容量和安全余量。面板策略、reservation 与具体 IP 账本是调度事实源。
3. 配置预先存在的 bridge 和一个或多个公网 IPv4 CIDR;显式保留宿主机管理 IP。Agent 不通过扫描推测可售地址。
4. 导入云镜像和救援 ISO。远程下载只接受可公开解析的 HTTPS 直链,Agent 会校验初始地址与全部跳转;来源的发行方可信度由管理员确认。本地云镜像必须是独立、未加密、无 backing/data file 的 QCOW2,本地救援镜像必须是可启动 ISO。面板会把本地暂存文件的精确大小和摘要写入签名任务,代理可使用 chunked 传输,但不得压缩响应或改变正文;Agent 会拒绝短读、多余字节、长度或摘要不一致。
4. 导入云镜像和救援 ISO。官方地址只接受可公开解析的 HTTPS 直链,PHP 会校验初始地址及全部跳转;来源的发行方可信度由管理员确认。浏览器本地云镜像必须是独立、未加密、无 backing/data file 的 QCOW2,并通过受控 multipart 直接写入对象存储,不经过 PHP 请求正文;救援镜像只支持官方 HTTPS 地址。两类内容形成不可变主副本后,Agent 只接收该精确对象版本的短期只读地址、大小和摘要,并拒绝短读、多余字节、长度、摘要或格式不一致。
5. 为每个云镜像按需设置首次安装启动脚本。脚本最大 32 KiB UTF-8、拒绝 NUL;保存后修订递增,新创建任务快照当前版本。不要在脚本中写长期密钥。
6. 在 `/admin/config` 的“云实例计费”中用“数值+分钟/小时/天”设置新建实例账单支付期限;面板保存时统一换算为整数分钟。该值只作用于保存后新生成的开通账单,既有账单保持原截止时间。
7. 如需使用可移植备份,在 `/admin/object-storage` 保存 S3 兼容配置并执行连接验证;验证本身只检查 Bucket 可达性和 `s3:ListBucket` 权限,实际备份账户还必须具备备份前缀的 multipart 上传、读取、HEAD 和删除权限。

@ -92,7 +92,8 @@ jq empty deploy/*.json.example
- 模板/ISO 导入与删除 A 宿主已应用、B 明确未应用:保留失败审计,显示部分结果,清除父任务占用;新的显式删除仅派发至仍有副本的宿主。未知叶子、错绑副本和伪造投影仍拒绝解锁。
- 云镜像全部宿主机副本已删除但主副本仍存在:父任务不得提前发布成功,副本账本不得提前删除。对象 DELETE 明确成功或精确版本 HEAD 返回不存在后才原子退休目录;DELETE 结果不明确时原 operation 不重放,需两次间隔 HEAD 证明相同大小、ETag 和 version ID 后才生成新代次。连续三代仍不明确、对象身份变化或明确拒绝必须进入管理员核对;管理员重试只处理对象存储,不得再次调用 Agent。晚到宿主机成功回执也必须进入同一两阶段边界。
- 全新 schema 的 `cloud_templates` 不得包含 `source_type`、`sealed_source_url` 或其他旧来源路径;不得存在 `cloud_rescue_template_imports`、`cloud_rescue_template_deletions`、`cloud_upload_staging`、浏览器救援 ISO 上传路由或宿主机级目录接口。本地 QCOW2 仅允许进入私有临时捕获后发布对象存储主副本;救援 ISO 仅允许 HTTPS 远程源进入隔离区,校验通过后发布不可变对象。后续所有宿主机补齐和修复只能使用主副本生成的精确版本只读地址。
- 全新 schema 的 `cloud_templates` 不得包含 `source_type`、`sealed_source_url` 或其他旧来源路径;不得存在 `cloud_rescue_template_imports`、`cloud_rescue_template_deletions`、`cloud_upload_staging`、旧云镜像上传/导入路由、浏览器救援 ISO 上传路由或宿主机级目录接口。本地 QCOW2 只允许由浏览器对同一持久导入意图执行受控 multipart 直传,不能进入 PHP 请求正文;救援 ISO 仅允许 HTTPS 远程源进入隔离区,校验通过后发布不可变对象。后续所有宿主机补齐和修复只能使用主副本生成的精确版本只读地址。
- 云镜像导入必须覆盖同一幂等键重放、不同指纹冲突、刷新后跳过服务端已确认分片、完成/Abort 响应丢失核对、24 小时过期清理及 Bucket lifecycle 兜底。官方地址下载失败必须保留同一可恢复意图;不可变 PUT 结果不明且 HEAD 暂不可用时保持 `source_unknown`,后续 HEAD 证明对象存在只能接纳原对象,证明不存在才允许在原对象键上重新下载和发布,任何路径都不得分配第二个模板或任务代次。PHP 硬中止遗留的 `virt-cloud-template-*` 普通临时文件只能在超过 24 小时后由普通 worker 逐个删除。
- 持续填充回执、叶子与聚合队列:三个通道均在有界 tick 内获得处理机会,空通道不能浪费整轮。
- Gateway 未监听及连接阶段超时且零字节发送:明确未执行并原子收尾;已发送后超时、连接复用、缺统计、多个传输中任一可能发送均不能当作未派发。开通任务只退款一次,不重复派发。
- 快照占用及各变更入口写入前校验失败:Journal 记录无副作用失败,同资源新 operation 可以进入;写调用之后及显式 uncertain 错误继续保留保护。

@ -7,6 +7,9 @@ use GuzzleHttp\ClientInterface;
/** Cloud-template policy adapter for secure remote artifact acquisition. */
final class CloudTemplateRemoteFetcher
{
private const TEMPORARY_PREFIX = 'virt-cloud-template-';
private const STALE_FILE_SECONDS = 86400;
private CloudRemoteArtifactFetcher $fetcher;
/** @param null|callable(string):list<string> $resolver */
@ -18,7 +21,7 @@ final class CloudTemplateRemoteFetcher
'云镜像',
1048576,
4294967296,
'virt-cloud-template-',
self::TEMPORARY_PREFIX,
$http,
$resolver
);
@ -29,4 +32,45 @@ final class CloudTemplateRemoteFetcher
{
return $this->fetcher->fetch($url, $expectedSha256);
}
/**
* Reap one crash-orphaned download without touching a live request.
* A fetch has a 15-minute absolute HTTP deadline, so the 24-hour age
* fence is deliberately much larger than every legitimate acquisition.
*/
public static function cleanupOneStaleFile(?int $now = null): bool
{
$now ??= time();
if ($now < self::STALE_FILE_SECONDS) {
throw new \InvalidArgumentException(
'Template temporary-file cleanup clock is invalid'
);
}
$directory = realpath(sys_get_temp_dir());
if (!is_string($directory) || !is_dir($directory)) {
return false;
}
$paths = glob(
$directory . DIRECTORY_SEPARATOR . self::TEMPORARY_PREFIX . '*',
GLOB_NOSORT
);
if (!is_array($paths) || $paths === []) {
return false;
}
sort($paths, SORT_STRING);
foreach ($paths as $path) {
if (!is_string($path) || is_link($path) || !is_file($path)) {
continue;
}
$modified = @filemtime($path);
if (!is_int($modified)
|| $modified > $now - self::STALE_FILE_SECONDS) {
continue;
}
if (@unlink($path)) {
return true;
}
}
return false;
}
}

@ -141,6 +141,7 @@ final class CloudWorkerService
// an offline recovery target before dispatching ordinary work.
$jobWorked = !$quarantined && $this->tickJob();
$templateCleanup = false;
$templateTemporaryCleanup = false;
if (!$this->policyOnly && !$this->vpcBatchOnly) {
try {
$templateCleanup = (new CloudTemplateImportWorkflow())
@ -152,8 +153,16 @@ final class CloudWorkerService
$this->observedErrors[] =
'template_import_cleanup_unresolved';
}
try {
$templateTemporaryCleanup =
CloudTemplateRemoteFetcher::cleanupOneStaleFile();
} catch (\Throwable $error) {
$this->observedErrors[] =
'template_import_temporary_cleanup_failed';
}
}
return $quarantined || $jobWorked || $templateCleanup || $expired > 0;
return $quarantined || $jobWorked || $templateCleanup
|| $templateTemporaryCleanup || $expired > 0;
}
/**

@ -13,12 +13,16 @@ $browser = file_get_contents(
$worker = file_get_contents(
$root . '/public/cloud/template-upload-hash-worker.js'
);
$workerService = file_get_contents(
$root . '/app/Services/Cloud/CloudWorkerService.php'
);
$template = file_get_contents(
$root . '/resources/views/venix/admin/cloud/templates.tpl'
);
if (!is_string($schema) || !is_string($setup) || !is_string($routes)
|| !is_string($controller) || !is_string($browser)
|| !is_string($worker) || !is_string($template)) {
|| !is_string($worker) || !is_string($workerService)
|| !is_string($template)) {
throw new RuntimeException('Template-import contract sources are unreadable.');
}
$assert = static function (bool $condition, string $message): void {
@ -80,6 +84,8 @@ $assert(str_contains($browser,
&& str_contains($browser, 'multipartPartSchedule(')
&& str_contains($browser, 'template-upload-active-list')
&& str_contains($worker, 'hashBlob(file')
&& str_contains($workerService,
'CloudTemplateRemoteFetcher::cleanupOneStaleFile()')
&& str_contains($template, 'id="template-upload-progress"')
&& str_contains($template, '文件内容不经过面板服务器'),
'Browser template upload lost direct multipart, hashing, or progress wiring.');

@ -745,5 +745,159 @@ namespace {
)->state === 'cancelled',
'Expired official download was not reaped without provider mutation.');
// A lost immutable PUT response plus an unavailable HEAD is effect
// unknown. The same intent must stay fenced until a later HEAD proves the
// exact object; recovery must not download or PUT the image again.
$actor['request_idempotency_key'] = 'multipart-template-intent-0011';
$unknownFetchHistory = [];
$unknownFetchStack = HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'Content-Encoding' => 'identity',
], $remoteBody),
]));
$unknownFetchStack->push(Middleware::history($unknownFetchHistory));
$unknownStorageHistory = [];
$unknownStorageStack = HandlerStack::create(new MockHandler([
new ConnectException('put response lost',
new Request('PUT', 'https://objects.example.test')),
new ConnectException('head unavailable',
new Request('HEAD', 'https://objects.example.test')),
]));
$unknownStorageStack->push(Middleware::history($unknownStorageHistory));
try {
$workflow->importRemote(
array_replace($remoteInput, ['name' => 'Debian 13 unknown put']),
$actor,
new CloudTemplateRemoteFetcher(
new Client(['handler' => $unknownFetchStack]),
static fn (string $host): array => ['93.184.216.34']
),
new CloudObjectStorageS3Client(new Client([
'handler' => $unknownStorageStack,
]))
);
throw new \RuntimeException('An unknown immutable PUT was accepted.');
} catch (CloudError $error) {
$assert($error->httpStatus === 502,
'Unknown immutable PUT returned the wrong status.');
}
$unknownRemote = CloudTemplateImportIntent::query()
->where('request_idempotency_key',
'multipart-template-intent-0011')->firstOrFail();
$unknownDto = CloudTemplateImportWorkflow::dto($unknownRemote);
$assert((string) $unknownRemote->state === 'source_unknown'
&& $unknownDto['can_resume'] === true
&& $unknownDto['can_cancel'] === false
&& count($unknownFetchHistory) === 1
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $unknownStorageHistory) === [
'PUT', 'HEAD',
],
'Unknown immutable PUT was not fenced on its original object key.');
$reconcileHistory = [];
$reconcileStack = HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'ETag' => '"remote-unknown-etag"',
'x-amz-version-id' => 'remote-unknown-version',
]),
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'ETag' => '"remote-unknown-etag"',
'x-amz-version-id' => 'remote-unknown-version',
]),
]));
$reconcileStack->push(Middleware::history($reconcileHistory));
$unknownAck = $workflow->resumeRemote(
(string) $unknownRemote->id,
$actor,
$emptyFetcher,
new CloudObjectStorageS3Client(new Client([
'handler' => $reconcileStack,
]))
);
$assert((int) ($unknownAck['task_id'] ?? 0) > 0
&& count($unknownFetchHistory) === 1
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $reconcileHistory) === [
'HEAD', 'HEAD',
],
'Unknown immutable PUT recovery replayed a download or write.');
// If the reconciliation HEAD proves the PUT did not apply, retrying the
// same intent is safe and may fetch and publish that frozen key again.
$actor['request_idempotency_key'] = 'multipart-template-intent-0012';
$absentFetchStack = HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'Content-Encoding' => 'identity',
], $remoteBody),
]));
$absentStorageHistory = [];
$absentStorageStack = HandlerStack::create(new MockHandler([
new ConnectException('put response lost',
new Request('PUT', 'https://objects.example.test')),
new Response(404),
]));
$absentStorageStack->push(Middleware::history($absentStorageHistory));
try {
$workflow->importRemote(
array_replace($remoteInput, ['name' => 'Debian 13 absent put']),
$actor,
new CloudTemplateRemoteFetcher(
new Client(['handler' => $absentFetchStack]),
static fn (string $host): array => ['93.184.216.34']
),
new CloudObjectStorageS3Client(new Client([
'handler' => $absentStorageStack,
]))
);
throw new \RuntimeException('A proven absent PUT was accepted.');
} catch (CloudError $error) {
$assert($error->httpStatus === 502,
'Proven absent immutable PUT returned the wrong status.');
}
$absentRemote = CloudTemplateImportIntent::query()
->where('request_idempotency_key',
'multipart-template-intent-0012')->firstOrFail();
$assert((string) $absentRemote->state === 'source_failed'
&& array_map(static fn (array $item): string =>
$item['request']->getMethod(), $absentStorageHistory) === [
'PUT', 'HEAD',
],
'Proven absent immutable PUT was not made safely retryable.');
$absentRetryStorage = new CloudObjectStorageS3Client(new Client([
'handler' => HandlerStack::create(new MockHandler([
new Response(200, [
'ETag' => '"remote-absent-retry-etag"',
'x-amz-version-id' => 'remote-absent-retry-version',
]),
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'ETag' => '"remote-absent-retry-etag"',
'x-amz-version-id' => 'remote-absent-retry-version',
]),
])),
]));
$absentRetryAck = $workflow->resumeRemote(
(string) $absentRemote->id,
$actor,
new CloudTemplateRemoteFetcher(
new Client(['handler' => HandlerStack::create(new MockHandler([
new Response(200, [
'Content-Length' => (string) strlen($remoteBody),
'Content-Encoding' => 'identity',
], $remoteBody),
]))]),
static fn (string $host): array => ['93.184.216.34']
),
$absentRetryStorage
);
$assert((int) ($absentRetryAck['task_id'] ?? 0) > 0,
'A proven absent immutable PUT could not resume on the same intent.');
echo "Cloud-template resumable multipart import behavior passed.\n";
}

@ -62,4 +62,26 @@ try {
}
$assert($blocked, 'Remote template acquisition accepted a private target.');
// A hard process stop can bypass the workflow finally block. The ordinary
// worker must remove only old, regular template-download files and leave a
// recent in-flight file untouched.
$stale = tempnam(sys_get_temp_dir(), 'virt-cloud-template-');
$recent = tempnam(sys_get_temp_dir(), 'virt-cloud-template-');
if (!is_string($stale) || !is_string($recent)) {
throw new RuntimeException('Could not create template cleanup fixtures.');
}
$cleanupNow = time();
touch($stale, $cleanupNow - 90000);
touch($recent, $cleanupNow - 60);
try {
for ($attempt = 0; $attempt < 128 && is_file($stale); $attempt++) {
CloudTemplateRemoteFetcher::cleanupOneStaleFile($cleanupNow);
}
$assert(!is_file($stale) && is_file($recent),
'Template cleanup removed a live file or retained a crash orphan.');
} finally {
@unlink($stale);
@unlink($recent);
}
echo "Remote cloud-template acquisition contract passed.\n";

Loading…
Cancel
Save