Files
Kelx/download_quota_test.go
2026-11-30 16:32:37 +00:00

215 lines
8.3 KiB
Go

package main
// Tests for the apply-version quota guard (Downloader.quotaCheck + Agent.
// quotaGuardedDownloader).
//
// handleApplyVersion (REMOTE_APPLY_PROXY_DOWNLOAD=0 forward mode) checked the
// server's disk quota exactly once, with extraBytes=0, before the download —
// so a download could write up to the downloader's full maxBytes ceiling
// (10 GiB by default) past the server's quota before anything stopped it. The
// guard aborts the commit copy the moment usedBefore+written crosses the
// limit, mapping the abort to the same 507 disk_limit_exceeded body the
// pre-check emits.
//
// Like download_test.go, the commit half is driven directly: downloadToFile's
// SSRF gate refuses the loopback a test HTTP server binds to, by design.
import (
"bytes"
"errors"
"os"
"path/filepath"
"strings"
"testing"
)
func TestWriteDownloadToFileQuotaCheckAbortsMidCopy(t *testing.T) {
dir := t.TempDir()
dest := filepath.Join(dir, "server.jar")
payload := blockPattern(1<<20, 0x41) // 1 MiB body
const budget = 256 * 1024
// Record every consultation: the hook must be consulted DURING the copy
// with the running total (io.Copy writes in <=32 KiB chunks), not batched
// to a single end-of-copy evaluation — a batched hook would let a fast
// upstream commit the whole body before the quota ever saw a byte.
var seen []int64
dl := Downloader{quotaCheck: func(written int64) error {
seen = append(seen, written)
if written > budget {
return errDownloadQuotaExceeded
}
return nil
}}
err := dl.writeDownloadToFile(bytes.NewReader(payload), dest)
if !errors.Is(err, errDownloadQuotaExceeded) {
t.Fatalf("quota-exceeded copy must abort with errDownloadQuotaExceeded, got %v", err)
}
if _, statErr := os.Stat(dest); !os.IsNotExist(statErr) {
t.Fatalf("aborted download must not have committed the destination (stat err: %v)", statErr)
}
if strays := strayTempFiles(t, dir, "server.jar"); len(strays) != 0 {
t.Fatalf("temp files survived an aborted commit: %v", strays)
}
if len(seen) < 2 {
t.Fatalf("the quota hook must be consulted repeatedly during the copy, saw %d consultation(s): %v", len(seen), seen)
}
for i := 1; i < len(seen); i++ {
if seen[i] <= seen[i-1] {
t.Fatalf("hook observations must be strictly increasing running totals: %v", seen)
}
}
// The abort must have happened near the budget: one write chunk of slack,
// NOT after the full 1 MiB body had been committed.
if maxSeen := seen[len(seen)-1]; maxSeen > budget+32*1024 {
t.Fatalf("the copy ran %d bytes past the budget before aborting — the hook is not consulted mid-copy", maxSeen-budget)
}
}
func TestWriteDownloadToFileQuotaCheckAcceptsUnderBudget(t *testing.T) {
dir := t.TempDir()
dest := filepath.Join(dir, "server.jar")
payload := blockPattern(128*1024, 0x41)
// A hook that never rejects must be byte-for-byte transparent.
seen := make([]int64, 0, 8)
dl := Downloader{quotaCheck: func(written int64) error {
seen = append(seen, written)
return nil
}}
if err := dl.writeDownloadToFile(bytes.NewReader(payload), dest); err != nil {
t.Fatalf("under-budget download: %v", err)
}
got, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("read dest: %v", err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("dest content mismatch under quota hook: got %d bytes, want %d", len(got), len(payload))
}
if len(seen) == 0 || seen[len(seen)-1] != int64(len(payload)) {
t.Fatalf("quota hook must observe the running total, final=%v want %d", seen, len(payload))
}
if strays := strayTempFiles(t, dir, "server.jar"); len(strays) != 0 {
t.Fatalf("temp files survived: %v", strays)
}
}
func TestQuotaGuardedDownloaderAbortsAtQuotaBoundary(t *testing.T) {
root := t.TempDir()
a := &Agent{volumesDir: root}
const server = "srv-quota"
serverDir := a.serverDir(server)
if err := os.MkdirAll(serverDir, 0o755); err != nil {
t.Fatalf("mkdir server dir: %v", err)
}
const seedBytes = 600 * 1024
if err := os.WriteFile(filepath.Join(serverDir, "world.dat"), make([]byte, seedBytes), 0o644); err != nil {
t.Fatalf("seed usage: %v", err)
}
// 1 MiB storage quota, set the way the panel sets it (meta resources).
if err := a.saveMeta(serverDir, map[string]any{
"resources": map[string]any{"storageMb": 1},
}); err != nil {
t.Fatalf("save meta: %v", err)
}
dl := a.quotaGuardedDownloader(serverDir)
if dl.quotaCheck == nil {
t.Fatal("a server with a storage limit must get a quota guard")
}
// The guard compares sampled usage + committed bytes against the limit.
// Sample usage through the same walker the guard samples with (du -sb
// counts directory inodes too, so hardcoding the seeded byte count here
// would be wrong): filling exactly up to the limit is allowed, one byte
// more aborts. (Before the fix, no hook existed at all and the download
// ran to the downloader's full 10 GiB maxBytes ceiling.)
usedBefore := a.getServerTotalUsage(serverDir)
if usedBefore <= 0 {
t.Fatalf("seeded usage must be visible to the guard, got %d", usedBefore)
}
const limitBytes = 1 << 20
remaining := limitBytes - usedBefore
if remaining <= 0 {
t.Fatalf("seed must leave room under the 1 MiB limit, used=%d", usedBefore)
}
if err := dl.quotaCheck(remaining); err != nil {
t.Fatalf("writing up to exactly the quota must be allowed (used=%d), got %v", usedBefore, err)
}
if err := dl.quotaCheck(remaining + 1); !errors.Is(err, errDownloadQuotaExceeded) {
t.Fatalf("one byte past the quota must abort, got %v", err)
}
}
func TestQuotaGuardedDownloaderNoLimitKeepsPlainDownloader(t *testing.T) {
root := t.TempDir()
a := &Agent{volumesDir: root}
const server = "srv-unlimited"
serverDir := a.serverDir(server)
if err := os.MkdirAll(serverDir, 0o755); err != nil {
t.Fatalf("mkdir server dir: %v", err)
}
dl := a.quotaGuardedDownloader(serverDir)
if dl.quotaCheck != nil {
t.Fatal("a server without a storage limit must keep the plain downloader (no hook)")
}
if dl.maxBytes != a.dl.maxBytes || dl.headerTimeout != a.dl.headerTimeout {
t.Fatal("the guarded copy must preserve the agent downloader's other settings")
}
}
func TestErrDownloadQuotaExceededMessageIsOperatorReadable(t *testing.T) {
// The message surfaces inside daemon logs when the 507 body cannot be
// built (checkDiskLimit returning nil is the fallback path); it must name
// the cause, not carry an empty/implementation error string.
if !strings.Contains(errDownloadQuotaExceeded.Error(), "disk limit") {
t.Fatalf("sentinel message must mention the disk limit, got %q", errDownloadQuotaExceeded.Error())
}
}
// TestHandleApplyVersionKeepsQuotaGuardedDownloader pins the wiring itself:
// the mechanism tests above would still pass if the handler's two download
// call sites were reverted to the unquotaed a.dl. Like the panel's structural
// tests read index.js, this reads the source window and fails on the revert.
func TestHandleApplyVersionKeepsQuotaGuardedDownloader(t *testing.T) {
src, err := os.ReadFile("main.go")
if err != nil {
t.Fatalf("read main.go: %v", err)
}
const anchor = "func (a *Agent) handleApplyVersion("
start := strings.Index(string(src), anchor)
if start < 0 {
t.Fatalf("anchor not found: %s", anchor)
}
s := string(src)
end := strings.Index(s[start:], "\nfunc ")
if end < 0 {
t.Fatal("could not bound the handleApplyVersion source window")
}
window := s[start : start+end]
if got := strings.Count(window, "a.quotaGuardedDownloader(baseDir).downloadToFile"); got != 2 {
t.Fatalf("handleApplyVersion must download through the quota-guarded downloader at BOTH sites (server.jar and plugins/mods), found %d", got)
}
if strings.Contains(window, "a.dl.downloadToFile") {
t.Fatal("handleApplyVersion must not download through the unquotaed a.dl — a revert re-opens the 10 GiB quota overshoot")
}
// The quota pre-check must stay BEHIND the signature gate: it walks the
// whole server tree (spawning du), and this endpoint is routed before
// bearer-token auth — an unauthenticated prober must not buy a walk per
// request. Ordered pin: verifyPanelSignature above checkDiskLimit.
sigAt := strings.Index(window, "a.verifyPanelSignature(")
quotaAt := strings.Index(window, "a.checkDiskLimit(serverDir, 0)")
if sigAt < 0 || quotaAt < 0 {
t.Fatal("handleApplyVersion must keep both the signature gate and the quota pre-check")
}
if sigAt > quotaAt {
t.Fatal("the quota pre-check must run only AFTER verifyPanelSignature — moving it ahead re-opens a pre-auth directory-walk DoS")
}
}