Fix staged imports without Content-Length

go
codex 1 month ago
parent f3f655ba2d
commit efd766afe9

@ -567,6 +567,38 @@ func validSourceToken(token string) bool {
return token == "" || sourceTokenPattern.MatchString(token)
}
func validateExpectedImportSourceSize(expected, maximum int64) error {
if expected == 0 {
return nil
}
if expected < minImportBytes || expected > maximum {
return NewError(ErrInvalid, "invalid_source_size", "source image size is invalid or exceeds its limit", nil)
}
return nil
}
// resolveImportSourceSize keeps remote imports strict while allowing a
// panel-staged upload to survive an intermediary that converts the response
// to chunked transfer encoding. The expected size is part of the signed,
// immutable operation request and the streaming path still enforces it byte
// for byte.
func resolveImportSourceSize(contentLength, expected, maximum int64) (int64, error) {
if err := validateExpectedImportSourceSize(expected, maximum); err != nil {
return 0, err
}
if contentLength >= 0 {
if contentLength < minImportBytes || contentLength > maximum ||
(expected > 0 && contentLength != expected) {
return 0, NewError(ErrInvalid, "invalid_source_size", "source image size is invalid or does not match the expected size", nil)
}
return contentLength, nil
}
if expected > 0 {
return expected, nil
}
return 0, NewError(ErrInvalid, "invalid_source_size", "source image size is missing or exceeds its limit", nil)
}
func remoteHTTPClient(allowRedirects bool) *http.Client {
dialer := &net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}
transport := &http.Transport{

@ -0,0 +1,44 @@
package hypervisor
import (
"errors"
"testing"
)
func TestResolveImportSourceSize(t *testing.T) {
const (
maximum = int64(8 << 30)
expected = int64(2 << 20)
)
tests := []struct {
name string
contentLength int64
expected int64
want int64
wantError bool
}{
{name: "staged chunked response", contentLength: -1, expected: expected, want: expected},
{name: "staged matching content length", contentLength: expected, expected: expected, want: expected},
{name: "remote content length", contentLength: expected, want: expected},
{name: "staged mismatch", contentLength: expected + 1, expected: expected, wantError: true},
{name: "remote missing content length", contentLength: -1, wantError: true},
{name: "expected below minimum", contentLength: -1, expected: minImportBytes - 1, wantError: true},
{name: "expected above maximum", contentLength: -1, expected: maximum + 1, wantError: true},
{name: "header above maximum", contentLength: maximum + 1, wantError: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got, err := resolveImportSourceSize(test.contentLength, test.expected, maximum)
if !test.wantError {
if err != nil || got != test.want {
t.Fatalf("resolve size = %d, %v; want %d, nil", got, err, test.want)
}
return
}
var typed *Error
if !errors.As(err, &typed) || typed.Code != "invalid_source_size" || got != 0 {
t.Fatalf("resolve size = %d, %#v; want invalid_source_size", got, err)
}
})
}
}

@ -115,6 +115,9 @@ func (l *Libvirt) ImportTemplate(ctx context.Context, request ImportTemplateRequ
if !displayNamePattern.MatchString(request.Name) || !displayNamePattern.MatchString(request.OSFamily) || !displayNamePattern.MatchString(request.Version) || !namePattern.MatchString(request.Architecture) || (request.SHA256 != "" && !sha256Pattern.MatchString(request.SHA256)) || !validSourceToken(request.SourceToken) {
return ImageTemplate{}, NewError(ErrInvalid, "invalid_template", "template metadata is invalid", nil)
}
if err := validateExpectedImportSourceSize(request.SourceSizeBytes, maxTemplateBytes); err != nil {
return ImageTemplate{}, err
}
if _, err := validateRemoteSource(request.SourceURL); err != nil {
return ImageTemplate{}, err
}
@ -141,7 +144,7 @@ func (l *Libvirt) ImportTemplate(ctx context.Context, request ImportTemplateRequ
}
defer pool.Free()
mutationStarted = true
volume, size, digest, err := l.downloadVolume(ctx, pool, templateVolumeName(request.ID), "qcow2", request.SourceURL, request.SourceToken, maxTemplateBytes, request.SHA256)
volume, size, digest, err := l.downloadVolume(ctx, pool, templateVolumeName(request.ID), "qcow2", request.SourceURL, request.SourceToken, request.SourceSizeBytes, maxTemplateBytes, request.SHA256)
if err != nil {
return ImageTemplate{}, err
}
@ -317,6 +320,9 @@ func (l *Libvirt) ImportRescueTemplate(ctx context.Context, request ImportRescue
if request.SHA256 != "" && !sha256Pattern.MatchString(request.SHA256) {
return RescueTemplate{}, NewError(ErrInvalid, "invalid_sha256", "sha256 must contain 64 lowercase hexadecimal characters", nil)
}
if err := validateExpectedImportSourceSize(request.SourceSizeBytes, maxRescueISOBytes); err != nil {
return RescueTemplate{}, err
}
if _, err := validateRemoteSource(request.SourceURL); err != nil {
return RescueTemplate{}, err
}
@ -354,7 +360,7 @@ func (l *Libvirt) ImportRescueTemplate(ctx context.Context, request ImportRescue
}
defer pool.Free()
mutationStarted = true
volume, size, digest, err := l.downloadVolume(ctx, pool, rescueImageVolumeName(id), "raw", request.SourceURL, request.SourceToken, maxRescueISOBytes, request.SHA256)
volume, size, digest, err := l.downloadVolume(ctx, pool, rescueImageVolumeName(id), "raw", request.SourceURL, request.SourceToken, request.SourceSizeBytes, maxRescueISOBytes, request.SHA256)
if err != nil {
return RescueTemplate{}, err
}
@ -532,7 +538,7 @@ func (l *Libvirt) ImportUserISO(ctx context.Context, request ImportUserISOReques
}
defer pool.Free()
mutationStarted = true
volume, size, digest, err := l.downloadVolume(ctx, pool, userISOImageVolumeName(request.OwnerID, id), "raw", request.SourceURL, request.SourceToken, maxUserISOBytes, request.SHA256)
volume, size, digest, err := l.downloadVolume(ctx, pool, userISOImageVolumeName(request.OwnerID, id), "raw", request.SourceURL, request.SourceToken, 0, maxUserISOBytes, request.SHA256)
if err != nil {
return UserISO{}, err
}
@ -784,7 +790,7 @@ func (l *Libvirt) templateVolume(id string) (*libvirt.StoragePool, *libvirt.Stor
return pool, volume, nil
}
func (l *Libvirt) downloadVolume(ctx context.Context, pool *libvirt.StoragePool, name, format, sourceURL, sourceToken string, maximum int64, expectedSHA string) (_ *libvirt.StorageVol, _ int64, _ string, resultErr error) {
func (l *Libvirt) downloadVolume(ctx context.Context, pool *libvirt.StoragePool, name, format, sourceURL, sourceToken string, expectedSize, maximum int64, expectedSHA string) (_ *libvirt.StorageVol, _ int64, _ string, resultErr error) {
// Download/format checks precede the first host mutation. Callers may already
// have entered this mutating helper, so preserve this narrower no-effect proof.
mutationStarted := false
@ -820,11 +826,12 @@ func (l *Libvirt) downloadVolume(ctx context.Context, pool *libvirt.StoragePool,
if encoding := strings.TrimSpace(strings.ToLower(response.Header.Get("Content-Encoding"))); encoding != "" && encoding != "identity" {
return nil, 0, "", NewError(ErrInvalid, "invalid_source_encoding", "source image must use identity content encoding", nil)
}
if response.ContentLength < minImportBytes || response.ContentLength > maximum {
return nil, 0, "", NewError(ErrInvalid, "invalid_source_size", "source image size is missing or exceeds its limit", nil)
sourceSize, err := resolveImportSourceSize(response.ContentLength, expectedSize, maximum)
if err != nil {
return nil, 0, "", err
}
source := io.Reader(response.Body)
capacity := uint64(response.ContentLength)
capacity := uint64(sourceSize)
if format == "qcow2" {
header := make([]byte, qcow2HeaderBytes)
if _, err := io.ReadFull(response.Body, header); err != nil {
@ -853,7 +860,7 @@ func (l *Libvirt) downloadVolume(ctx context.Context, pool *libvirt.StoragePool,
return nil, 0, "", failure
}
transfer := &storageStreamTransfer{stream: stream}
if err := volume.Upload(stream, 0, uint64(response.ContentLength), 0); err != nil {
if err := volume.Upload(stream, 0, uint64(sourceSize), 0); err != nil {
failure := mutationLibvirtError("open imported image upload", transfer.abort(err))
failure = l.rollbackImportedVolume(volume, failure, "imported image")
volume.Free()
@ -861,7 +868,7 @@ func (l *Libvirt) downloadVolume(ctx context.Context, pool *libvirt.StoragePool,
}
hash := sha256.New()
hashedSource := io.TeeReader(source, hash)
written, copyErr := io.CopyN(&storageStreamWriter{ctx: ctx, transfer: transfer}, hashedSource, response.ContentLength)
written, copyErr := io.CopyN(&storageStreamWriter{ctx: ctx, transfer: transfer}, hashedSource, sourceSize)
if errors.Is(copyErr, io.EOF) {
copyErr = io.ErrUnexpectedEOF
}

@ -47,7 +47,7 @@ func TestMutationPreconditionFailuresDoNotFenceResource(t *testing.T) {
{"import-iso", func() error { _, err := backend.ImportUserISO(ctx, ImportUserISORequest{}); return err }},
{"delete-iso", func() error { return backend.DeleteUserISO(ctx, "invalid", 17) }},
{"download-source", func() error {
_, _, _, err := backend.downloadVolume(ctx, nil, "volume", "raw", "invalid", "", 100, "")
_, _, _, err := backend.downloadVolume(ctx, nil, "volume", "raw", "invalid", "", 0, 100, "")
return err
}},
}

@ -469,6 +469,7 @@ type ImportTemplateRequest struct {
Name string `json:"name"`
SourceURL string `json:"source_url"`
SourceToken string `json:"source_token,omitempty"`
SourceSizeBytes int64 `json:"source_size_bytes,omitempty"`
OSFamily string `json:"os_family"`
Version string `json:"version"`
Architecture string `json:"architecture"`
@ -512,12 +513,13 @@ type RescueTemplate struct {
}
type ImportRescueTemplateRequest struct {
OperationID string `json:"operation_id,omitempty"`
ID string `json:"id,omitempty"`
Name string `json:"name"`
SourceURL string `json:"source_url"`
SourceToken string `json:"source_token,omitempty"`
SHA256 string `json:"sha256,omitempty"`
OperationID string `json:"operation_id,omitempty"`
ID string `json:"id,omitempty"`
Name string `json:"name"`
SourceURL string `json:"source_url"`
SourceToken string `json:"source_token,omitempty"`
SourceSizeBytes int64 `json:"source_size_bytes,omitempty"`
SHA256 string `json:"sha256,omitempty"`
}
type StorageConfigurationRequest struct {

@ -177,6 +177,13 @@ 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;若响应仍包含
长度则必须与预期完全一致,最终正文也必须恰好为该字节数并通过 SHA-256
校验。远程 URL 导入不携带该字段,仍必须返回有效的 `Content-Length`。
任何导入源都不得使用压缩 `Content-Encoding`。
不存在 mutation `reconcile`、`confirm-inspection`、`abort-job` 或 `cleanup` endpoint。`inspect` 不取得 mutation admission,不写 Journal,不继续原目标,也不能调用任何 libvirt 变更。不可变 Journal 成功或明确无副作用失败可以为策略表中的任何类型提供精确结论;其他已失败且影响未知的类型只有在该 action 的专用投影证据完整匹配时才能输出 `applied/not_applied`,否则保持 `partial/inconclusive`。例如实例设置只有在 Domain metadata 与 NoCloud seed 都匹配同一 transition ID 时才是 `applied`,两者都确认未提交时才是 `not_applied`。电源、网络链路或服务的“当前状态刚好符合目标”不是原 operation 的强证据,必须保持 `inconclusive`。
## 关键资源语义

@ -311,7 +311,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。
4. 导入云镜像和救援 ISO。远程下载只接受可公开解析的 HTTPS 直链,Agent 会校验初始地址与全部跳转;来源的发行方可信度由管理员确认。本地云镜像必须是独立、未加密、无 backing/data file 的 QCOW2,本地救援镜像必须是可启动 ISO。面板会把本地暂存文件的精确大小和摘要写入签名任务,代理可使用 chunked 传输,但不得压缩响应或改变正文;Agent 会拒绝短读、多余字节、长度或摘要不一致。
5. 为每个云镜像按需设置首次安装启动脚本。脚本最大 32 KiB UTF-8、拒绝 NUL;保存后修订递增,新创建任务快照当前版本。不要在脚本中写长期密钥。
6. 在 `/admin/config` 的“云实例计费”中设置新建实例账单支付期限,单位为分钟;`60` 表示 1 小时,`1440` 表示 1 天。该值只作用于保存后新生成的开通账单,既有账单保持原截止时间。
7. 创建销售套餐和库存,再启用宿主机/Agent 调度。用户支付成功后只应创建一个 VM。

@ -87,7 +87,7 @@ Agent 在连接前注册并持续运行 libvirt event loop;每个连接 genera
- 云镜像由 PHP 保存目录元数据和启动脚本。创建任务快照镜像 generation、revision 和脚本正文后签名发送给目标 Agent;删除后重新导入的同名镜像不能继承旧脚本。
- 启动脚本仅用于新云镜像实例的首次安装,不用于普通重启、网络设置、重装、救援或用户 ISO。脚本限制 32 KiB UTF-8,拒绝 NUL,CRLF 规范化为 LF,空值表示禁用。
- Agent 将脚本以 root 私有文件写入 cloud-init seed,由一次性 runner 原子记录 started 状态。成功、失败和中断都不自动重放;VM 创建成功不等待脚本结束。
- 镜像下载始终使用独立 HTTPS 请求,WSS 只传递一次性下载 URL/token/摘要等任务元数据,不传镜像字节。Agent 限制来源、解析后的公网地址、全部跳转、大小、超时和摘要;校验 QCOW2 格式,拒绝 backing file、外部 data file、加密或 raw 内容。
- 镜像下载始终使用独立 HTTPS 请求,WSS 只传递一次性下载 URL/token/摘要等任务元数据,不传镜像字节。面板暂存上传还会把已捕获文件的精确大小写入签名任务;即使代理改用 chunked 响应,Agent 也按该大小有界读取,并拒绝长度不符、多余字节、短读或摘要不符。远程 URL 没有面板大小快照,仍要求来源返回有效 `Content-Length`。Agent 限制来源、解析后的公网地址、全部跳转、大小、超时和摘要;校验 QCOW2 格式,拒绝 backing file、外部 data file、加密或 raw 内容。
## 网络与账期

@ -289,6 +289,7 @@ final class CloudAdminController
$url,
'',
$digest,
0,
$actor
),
202
@ -318,7 +319,7 @@ final class CloudAdminController
$this->host((int) $hostId);
$name = self::catalogName($query['name'] ?? null);
$file = CloudUploadStagingService::capture(
$request, 'iso', 32768, 8 * 1024 * 1024 * 1024
$request, 'iso', 1024 * 1024, 8 * 1024 * 1024 * 1024
);
try {
$staging = CloudUploadStagingService::issue(
@ -332,6 +333,7 @@ final class CloudAdminController
(string) $staging['url'],
(string) $staging['token'],
(string) $staging['sha256'],
(int) $staging['size_bytes'],
$actor
),
202

@ -908,8 +908,8 @@ final class CloudOperationRecoveryIdentity
self::expectRequest($method, $target, 'POST', '/v1/templates');
self::assertAllowedBody($body, [
'operation_id', 'id', 'name', 'source_url', 'source_token',
'os_family', 'version', 'architecture', 'sha256', 'revision',
'generation_token',
'source_size_bytes', 'os_family', 'version', 'architecture',
'sha256', 'revision', 'generation_token',
]);
if (($body['id'] ?? null) !== $id
|| (int) ($body['revision'] ?? 0) !== (int) $replica->revision
@ -958,7 +958,7 @@ final class CloudOperationRecoveryIdentity
'/v1/rescue-templates');
self::assertAllowedBody($body, [
'operation_id', 'id', 'name', 'source_url', 'source_token',
'sha256',
'source_size_bytes', 'sha256',
]);
if ($row === null || (int) $row->job_id !== (int) $job->id
|| ($body['id'] ?? null) !== $id

@ -15,17 +15,18 @@ final class CloudRescueTemplateImportService
string $sourceUrl,
string $sourceToken,
string $sha256,
int $sourceSizeBytes,
array $actor
): array {
CloudAccess::manage($actor);
self::validateInput($hostId, $importType, $name, $sourceUrl,
$sourceToken, $sha256);
$sourceToken, $sha256, $sourceSizeBytes);
$operationId = bin2hex(random_bytes(16));
$templateId = bin2hex(random_bytes(16));
$connection = (new CloudRescueTemplateImport())->getConnection();
$job = $connection->transaction(static function () use (
$hostId, $importType, $name, $sourceUrl, $sourceToken, $sha256,
$actor, $operationId, $templateId
$sourceSizeBytes, $actor, $operationId, $templateId
): CloudJob {
$body = [
'id' => $templateId,
@ -36,6 +37,9 @@ final class CloudRescueTemplateImportService
if ($sourceToken !== '') {
$body['source_token'] = $sourceToken;
}
if ($sourceSizeBytes > 0) {
$body['source_size_bytes'] = $sourceSizeBytes;
}
[$job, $created] = CloudJobService::reserveStandaloneAgentMutation(
$actor, $hostId, 'rescue_template_import', 'POST',
'/v1/rescue-templates', $body,
@ -47,6 +51,7 @@ final class CloudRescueTemplateImportService
'source' => $importType === 'remote'
? $sourceUrl : $sha256,
'sha256' => $sha256,
'source_size_bytes' => $sourceSizeBytes,
],
$operationId
);
@ -235,11 +240,16 @@ final class CloudRescueTemplateImportService
private static function validateInput(int $hostId, string $importType,
string $name, string $sourceUrl, string $sourceToken,
string $sha256): void
string $sha256, int $sourceSizeBytes): void
{
$validSize = $importType === 'upload'
? $sourceSizeBytes >= 1024 * 1024
&& $sourceSizeBytes <= 8 * 1024 * 1024 * 1024
: $sourceSizeBytes === 0;
if ($hostId < 1 || !in_array($importType, ['remote', 'upload'], true)
|| $name === '' || mb_strlen($name, 'UTF-8') > 64
|| $sourceUrl === '' || strlen($sourceUrl) > 4096
|| !$validSize
|| ($sourceToken !== ''
&& preg_match('/^[A-Za-z0-9_-]{32,512}$/D', $sourceToken)
!== 1)

@ -134,7 +134,9 @@ final class CloudTemplateCatalogService
$source = $sourceForHost($hostId);
if (!is_array($source)
|| !is_string($source['source_url'] ?? null)
|| !is_string($source['sha256'] ?? null)) {
|| !is_string($source['sha256'] ?? null)
|| ($sourceType === 'upload'
&& ($source['size_bytes'] ?? null) !== $bytes)) {
throw new CloudError('云镜像导入源快照无效', 503);
}
$body = [
@ -155,6 +157,9 @@ final class CloudTemplateCatalogService
&& $source['source_token'] !== '') {
$body['source_token'] = $source['source_token'];
}
if ($sourceType === 'upload') {
$body['source_size_bytes'] = $bytes;
}
$operationId = bin2hex(random_bytes(16));
$child = CloudJobService::reserveAgentMutation(
$actor, $hostId, 'template_import_replica', 'POST',

@ -834,6 +834,7 @@ namespace {
'name' => 'Matrix Template',
'source_url' => 'https://example.invalid/template.qcow2',
'source_token' => 'matrix-token',
'source_size_bytes' => 2097152,
'os_family' => 'linux',
'version' => '13',
'architecture' => 'x86_64',
@ -946,6 +947,7 @@ namespace {
'name' => 'Matrix Rescue',
'source_url' => 'https://example.invalid/rescue.iso',
'source_token' => 'matrix-token',
'source_size_bytes' => 2097152,
'sha256' => str_repeat('2', 64),
],
'owner_id' => $ownerId,

@ -367,6 +367,7 @@ namespace {
'https://example.invalid/new-rescue.qcow2',
'',
'',
0,
$actor
);
$retryImportJob = CloudJob::findOrFail((int) $retryImport['task_id']);
@ -378,6 +379,29 @@ namespace {
->count() === 2,
'A proven not-applied rescue import did not admit a new operation.');
$uploadBytes = 2 * 1024 * 1024;
$uploadDigest = str_repeat('a', 64);
$uploadImport = CloudRescueTemplateImportService::start(
1,
'upload',
'chunked-upload-rescue',
'https://panel.example.test/api/internal/cloud/upload-staging/'
. str_repeat('a', 32),
str_repeat('t', 32),
$uploadDigest,
$uploadBytes,
$actor
);
$uploadJob = CloudJob::findOrFail((int) $uploadImport['task_id']);
$uploadPayload = CloudSecrets::decrypt(
(string) $uploadJob->sealed_payload,
'job-payload'
);
$assert(($uploadPayload['body']['source_size_bytes'] ?? null)
=== $uploadBytes
&& ($uploadPayload['body']['sha256'] ?? null) === $uploadDigest,
'A rescue upload did not preserve its exact size in the immutable Agent request.');
foreach ([
['applied-rescue', str_repeat('c', 32), 'applied', false],
['incident-rescue', str_repeat('d', 32), 'not_applied', true],
@ -392,6 +416,7 @@ namespace {
'https://example.invalid/blocked-rescue.qcow2',
'',
'',
0,
$actor
);
throw new RuntimeException(
@ -425,6 +450,7 @@ namespace {
'https://example.invalid/tuple-rescue.qcow2',
'',
'',
0,
$actor
);
throw new RuntimeException(
@ -536,6 +562,7 @@ namespace {
'https://example.invalid/identity-rescue.qcow2',
'',
'',
0,
$actor
);
throw new RuntimeException(

@ -32,6 +32,7 @@ $assert(is_string($catalog)
&& str_contains($catalog, 'CloudJobService::reserveAggregate(')
&& str_contains($catalog, 'CloudJobService::reserveAgentMutation(')
&& str_contains($catalog, "'template_import_replica', 'POST'")
&& str_contains($catalog, "\$body['source_size_bytes'] = \$bytes")
&& str_contains($catalog, "'template_delete_replica', 'DELETE'")
&& str_contains($catalog, 'CloudJobService::acknowledgement($parent)')
&& str_contains($catalog, 'public static function finishJobLocked(')

@ -142,6 +142,7 @@ namespace {
'cloud-template');
$assert($first['id'] !== $second['id']
&& $first['token'] !== $second['token']
&& (int) $first['size_bytes'] === strlen($payload)
&& str_starts_with($first['url'],
'https://panel.example.test/base/api/internal/cloud/upload-staging/')
&& !str_contains($first['url'], $first['token']),

Loading…
Cancel
Save