Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,991 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func makeBudgetTestZip(t *testing.T, dir string, size int) string {
|
||||
t.Helper()
|
||||
src := filepath.Join(dir, "in.zip")
|
||||
out, err := os.Create(src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer out.Close()
|
||||
w := zip.NewWriter(out)
|
||||
f, err := w.Create("payload.bin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.Write(make([]byte, size)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return src
|
||||
}
|
||||
|
||||
func TestExtractZipSafeBudgetExceeded(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
src := makeBudgetTestZip(t, dir, 64*1024)
|
||||
|
||||
dest := filepath.Join(dir, "out")
|
||||
if err := os.MkdirAll(dest, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err := extractZipSafe(src, dest, 1024)
|
||||
if err == nil || !strings.Contains(err.Error(), "extraction size limit exceeded") {
|
||||
t.Fatalf("expected budget error, got: %v", err)
|
||||
}
|
||||
entries, _ := os.ReadDir(dest)
|
||||
for _, e := range entries {
|
||||
info, _ := e.Info()
|
||||
if info != nil && !info.IsDir() && info.Size() > 1024+4096 {
|
||||
t.Fatalf("file written beyond budget: %s (%d bytes)", e.Name(), info.Size())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractZipSafeWithinBudget(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
src := makeBudgetTestZip(t, dir, 32*1024)
|
||||
|
||||
dest := filepath.Join(dir, "out")
|
||||
if err := extractZipSafe(src, dest, int64(maxExtractSize)); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dest, "payload.bin"))
|
||||
if err != nil || len(data) != 32*1024 {
|
||||
t.Fatalf("payload missing or wrong size: %v (%d)", err, len(data))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTarSafeBudgetExceeded(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pr, pw, _ := os.Pipe()
|
||||
go func() {
|
||||
tw := tar.NewWriter(pw)
|
||||
hdr := &tar.Header{Name: "big.bin", Mode: 0o644, Size: int64(128 * 1024)}
|
||||
_ = tw.WriteHeader(hdr)
|
||||
_, _ = tw.Write(make([]byte, 128*1024))
|
||||
_ = tw.Close()
|
||||
_ = pw.Close()
|
||||
}()
|
||||
defer pr.Close()
|
||||
|
||||
dest := filepath.Join(dir, "out")
|
||||
if _, err := extractTarSafe(tar.NewReader(pr), dest, 1024, true); err == nil ||
|
||||
!strings.Contains(err.Error(), "extraction size limit exceeded") {
|
||||
t.Fatalf("expected budget error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractTarSafeRejectsTraversal(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pr, pw, _ := os.Pipe()
|
||||
go func() {
|
||||
tw := tar.NewWriter(pw)
|
||||
hdr := &tar.Header{Name: "../../escape.txt", Mode: 0o644, Size: 4}
|
||||
_ = tw.WriteHeader(hdr)
|
||||
_, _ = tw.Write([]byte("pwn\n"))
|
||||
_ = tw.Close()
|
||||
_ = pw.Close()
|
||||
}()
|
||||
defer pr.Close()
|
||||
|
||||
if _, err := extractTarSafe(tar.NewReader(pr), dir, int64(maxExtractSize), true); err == nil ||
|
||||
!strings.Contains(err.Error(), "tar-slip blocked") {
|
||||
t.Fatalf("expected tar-slip block, got: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "..", "escape.txt")); !os.IsNotExist(err) {
|
||||
t.Fatal("file escaped destination")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAndMoveExtractedBudgetAndSymlinks(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
buildTree := func(root string, big bool) {
|
||||
inner := filepath.Join(root, "pkg")
|
||||
_ = os.MkdirAll(inner, 0o755)
|
||||
content := []byte("hello")
|
||||
if big {
|
||||
content = make([]byte, 64*1024)
|
||||
}
|
||||
_ = os.WriteFile(filepath.Join(inner, "a.txt"), content, 0o644)
|
||||
_ = os.Symlink("/etc/passwd", filepath.Join(inner, "evil-link"))
|
||||
}
|
||||
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
// Oversized payload: must be rejected wholesale, nothing moved.
|
||||
tmpBig := filepath.Join(dir, "tmp-big")
|
||||
destA := filepath.Join(dir, "dest-a")
|
||||
_ = os.MkdirAll(destA, 0o755)
|
||||
buildTree(tmpBig, true)
|
||||
if _, err := validateAndMoveExtracted(scope, tmpBig, destA, 1024, true); err == nil ||
|
||||
!strings.Contains(err.Error(), "extraction size limit exceeded") {
|
||||
t.Fatalf("expected oversize rejection, got: %v", err)
|
||||
}
|
||||
if entries, _ := os.ReadDir(destA); len(entries) != 0 {
|
||||
t.Fatalf("destination polluted despite rejection: %d entries", len(entries))
|
||||
}
|
||||
|
||||
// Small payload: regular files move, symlinks do not.
|
||||
tmpOk := filepath.Join(dir, "tmp-ok")
|
||||
destB := filepath.Join(dir, "dest-b")
|
||||
_ = os.MkdirAll(destB, 0o755)
|
||||
buildTree(tmpOk, false)
|
||||
if _, err := validateAndMoveExtracted(scope, tmpOk, destB, int64(maxExtractSize), true); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if data, err := os.ReadFile(filepath.Join(destB, "pkg", "a.txt")); err != nil || string(data) != "hello" {
|
||||
t.Fatalf("regular file not moved: %v", err)
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(destB, "pkg", "evil-link")); !os.IsNotExist(err) {
|
||||
t.Fatal("symlink escaped into destination")
|
||||
}
|
||||
}
|
||||
|
||||
// --- adpanel:extract-hardlinks - hardlinks must not survive the scratch-dir pre-scan ---
|
||||
|
||||
// A hardlinked regular file planted in the scratch dir (what a crafted
|
||||
// RAR/7z can make an external extractor materialize) must be rejected by the
|
||||
// pre-scan with the same message the tar extractors use, and nothing may be
|
||||
// moved into the destination: relocating a shared inode would otherwise give
|
||||
// the server a live handle that potentially points outside its scope.
|
||||
func TestValidateAndMoveExtractedRejectsHardlinks(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
tmp := filepath.Join(dir, "scratch")
|
||||
if err := os.MkdirAll(tmp, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(tmp, "payload.txt"), []byte("shared"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Link(filepath.Join(tmp, "payload.txt"), filepath.Join(tmp, "linked.txt")); err != nil {
|
||||
t.Skipf("hardlinks unsupported: %v", err)
|
||||
}
|
||||
dest := filepath.Join(dir, "dest")
|
||||
if err := os.MkdirAll(dest, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
if _, err := validateAndMoveExtracted(scope, tmp, dest, int64(maxExtractSize), true); err == nil ||
|
||||
!strings.Contains(err.Error(), "hardlinks not allowed for security") {
|
||||
t.Fatalf("expected hardlink refusal, got: %v", err)
|
||||
}
|
||||
if entries, _ := os.ReadDir(dest); len(entries) != 0 {
|
||||
t.Fatalf("destination polluted despite hardlink rejection: %d entries", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractBudget7zSltParserSumsSizes(t *testing.T) {
|
||||
const listing = `Listing archive: bomb.7z
|
||||
|
||||
--
|
||||
Path = bomb.7z
|
||||
Type = 7z
|
||||
Physical Size = 10485760
|
||||
Headers Size = 512
|
||||
Method = LZMA2:24
|
||||
Solid = +
|
||||
Blocks = 1
|
||||
|
||||
----------
|
||||
Path = zeros.bin
|
||||
Size = 1073741824
|
||||
Packed Size = 4096
|
||||
Method = LZMA2:24
|
||||
Block = 0
|
||||
|
||||
Path = docs
|
||||
Folder = +
|
||||
Size = 0
|
||||
Packed Size = 0
|
||||
|
||||
Path = docs/readme.txt
|
||||
Size = 2048
|
||||
Packed Size = 256
|
||||
Block = 0
|
||||
`
|
||||
stats, err := parse7zSltSizes(listing)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if stats.totalSize != 1073741824+2048 {
|
||||
t.Fatalf("wrong summed size: %d", stats.totalSize)
|
||||
}
|
||||
if stats.fileCount != 3 { // header block's own Path has no Size line, so only 3 entries count
|
||||
t.Fatalf("wrong entry count: %d", stats.fileCount)
|
||||
}
|
||||
if stats.maxFileSize != 1073741824 || stats.maxFileName != "zeros.bin" {
|
||||
t.Fatalf("wrong largest entry: %d (%s)", stats.maxFileSize, stats.maxFileName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractBudgetUnrarVtParserSumsSizes(t *testing.T) {
|
||||
const listing = `UNRAR 6.24 by Alexander Roshal
|
||||
|
||||
Archive: payload.rar
|
||||
Details: RAR 5
|
||||
|
||||
Name: payload.bin
|
||||
Type: File
|
||||
Size: 3221225472
|
||||
Packed size: 10485760
|
||||
Ratio: 0%
|
||||
mtime: 2024-01-01 00:00:00,000
|
||||
Attributes: -rw-r--r--
|
||||
CRC32: 00000000
|
||||
Host OS: Unix
|
||||
|
||||
Name: docs
|
||||
Type: Directory
|
||||
Size: 0
|
||||
Packed size: 0
|
||||
Host OS: Unix
|
||||
`
|
||||
stats, err := parseUnrarVtSizes(listing)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if stats.totalSize != 3221225472 {
|
||||
t.Fatalf("wrong summed size: %d", stats.totalSize)
|
||||
}
|
||||
if stats.fileCount != 2 {
|
||||
t.Fatalf("wrong entry count: %d", stats.fileCount)
|
||||
}
|
||||
if stats.maxFileSize != 3221225472 || stats.maxFileName != "payload.bin" {
|
||||
t.Fatalf("wrong largest entry: %d (%s)", stats.maxFileSize, stats.maxFileName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractBudgetParserRejectsBadSizes(t *testing.T) {
|
||||
if _, err := parse7zSltSizes("Path = a.bin\nSize = twelve\n"); err == nil {
|
||||
t.Fatal("expected 7z parse error for non-numeric size")
|
||||
}
|
||||
if _, err := parseUnrarVtSizes("Name: a.bin\nSize: 1 2 3\n"); err == nil {
|
||||
t.Fatal("expected unrar parse error for non-numeric size")
|
||||
}
|
||||
// Empty sizes (directory entries) are legal and count as zero.
|
||||
stats, err := parse7zSltSizes("Path = dir\nSize =\n")
|
||||
if err != nil || stats.totalSize != 0 {
|
||||
t.Fatalf("empty size must parse as zero: %v %d", err, stats.totalSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractBudgetExternalListingChecks(t *testing.T) {
|
||||
if err := checkExternalListingBudget(externalListingStats{fileCount: maxExtractFiles + 1}, int64(maxExtractSize)); err == nil ||
|
||||
!strings.Contains(err.Error(), "too many files in archive") {
|
||||
t.Fatalf("expected file-count rejection, got: %v", err)
|
||||
}
|
||||
if err := checkExternalListingBudget(externalListingStats{maxFileSize: maxSingleFile + 1, maxFileName: "big.bin"}, int64(maxExtractSize)); err == nil ||
|
||||
!strings.Contains(err.Error(), "file too large") {
|
||||
t.Fatalf("expected single-file rejection, got: %v", err)
|
||||
}
|
||||
if err := checkExternalListingBudget(externalListingStats{totalSize: 1025}, 1024); err == nil ||
|
||||
!strings.Contains(err.Error(), "extraction size limit exceeded") {
|
||||
t.Fatalf("expected total-size rejection, got: %v", err)
|
||||
}
|
||||
if err := checkExternalListingBudget(externalListingStats{totalSize: 1024, fileCount: 1}, 1024); err != nil {
|
||||
t.Fatalf("within-budget listing must pass, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// installFakeExtractor drops a shell-script stand-in for bin (7z/unrar) into a
|
||||
// directory prepended to PATH so the pre-flight and watchdog layers can be
|
||||
// exercised without the real binaries. listOutput is printed when the tool is
|
||||
// asked to list (7z l -slt / unrar vt); extractSnippet runs on extraction with
|
||||
// the destination directory in $d.
|
||||
func installFakeExtractor(t *testing.T, bin, listOutput, extractSnippet string) {
|
||||
t.Helper()
|
||||
if _, err := os.Stat("/bin/sh"); err != nil {
|
||||
t.Skip("/bin/sh unavailable for fake extractor")
|
||||
}
|
||||
binDir := t.TempDir()
|
||||
dLine := "d=\"$4\"\n" // unrar x gets the destination as its 4th argument
|
||||
if bin == "7z" {
|
||||
dLine = "d=\"${3#-o}\"\n" // 7z x passes it as -o<dir>
|
||||
}
|
||||
script := "#!/bin/sh\n" +
|
||||
"if [ \"$1\" = \"l\" ] || [ \"$1\" = \"vt\" ]; then\n" +
|
||||
"cat <<'ADPANEL_LIST_EOF'\n" + listOutput + "\nADPANEL_LIST_EOF\n" +
|
||||
"exit 0\nfi\n" +
|
||||
dLine + extractSnippet + "\n"
|
||||
if err := os.WriteFile(filepath.Join(binDir, bin), []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
}
|
||||
|
||||
func fakeBudgetArchive(t *testing.T, dir string) string {
|
||||
t.Helper()
|
||||
archive := filepath.Join(dir, "fake-archive.bin")
|
||||
if err := os.WriteFile(archive, []byte("not a real archive"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return archive
|
||||
}
|
||||
|
||||
func TestExtractWithExternalToolPreflightRejectsOversizeListing(t *testing.T) {
|
||||
installFakeExtractor(t, "7z", "Path = big.bin\nSize = 1073741824\n", "exit 0\n")
|
||||
a := &Agent{}
|
||||
dir := t.TempDir()
|
||||
archive := fakeBudgetArchive(t, dir)
|
||||
dest := filepath.Join(dir, "dest")
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
_, err := a.extractWithExternalTool("7z", archive, dest, 1024, true, scope)
|
||||
if err == nil || !strings.Contains(err.Error(), "extraction size limit exceeded") {
|
||||
t.Fatalf("expected pre-flight budget rejection, got: %v", err)
|
||||
}
|
||||
if entries, _ := os.ReadDir(dest); len(entries) != 0 {
|
||||
t.Fatalf("destination touched despite pre-flight rejection: %d entries", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractWithExternalToolWatchdogKillsOverBudget(t *testing.T) {
|
||||
// The listing claims a tiny payload; the fake extractor then writes far
|
||||
// beyond the budget and hangs, so only the runtime watchdog can stop it.
|
||||
installFakeExtractor(t, "7z", "Path = payload.bin\nSize = 16\n",
|
||||
"head -c 4194304 /dev/zero > \"$d/payload.bin\"\nsleep 30\n")
|
||||
a := &Agent{}
|
||||
dir := t.TempDir()
|
||||
archive := fakeBudgetArchive(t, dir)
|
||||
dest := filepath.Join(dir, "dest")
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
start := time.Now()
|
||||
_, err := a.extractWithExternalTool("7z", archive, dest, 1024*1024, true, scope)
|
||||
if err == nil || !strings.Contains(err.Error(), "extraction size limit exceeded") {
|
||||
t.Fatalf("expected watchdog budget error, got: %v", err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 15*time.Second {
|
||||
t.Fatalf("watchdog did not kill the tool in time (took %v)", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractWithExternalToolUnrarWatchdog(t *testing.T) {
|
||||
// rar pre-flight may be skipped on unrar listing trouble, so the watchdog
|
||||
// must cap it regardless: the listing claims a tiny payload while the
|
||||
// extraction blows past the budget and hangs.
|
||||
installFakeExtractor(t, "unrar", " Name: payload.bin\n Size: 16\n",
|
||||
"head -c 4194304 /dev/zero > \"$d/payload.bin\"\nsleep 30\n")
|
||||
a := &Agent{}
|
||||
dir := t.TempDir()
|
||||
archive := fakeBudgetArchive(t, dir)
|
||||
dest := filepath.Join(dir, "dest")
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
start := time.Now()
|
||||
_, err := a.extractWithExternalTool("unrar", archive, dest, 1024*1024, true, scope)
|
||||
if err == nil || !strings.Contains(err.Error(), "extraction size limit exceeded") {
|
||||
t.Fatalf("expected watchdog budget error, got: %v", err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 15*time.Second {
|
||||
t.Fatalf("watchdog did not kill the tool in time (took %v)", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractWithExternalToolHappyPathFake(t *testing.T) {
|
||||
installFakeExtractor(t, "7z", "Path = payload.bin\nSize = 13\n",
|
||||
"printf 'hello payload' > \"$d/payload.bin\"\n")
|
||||
a := &Agent{}
|
||||
dir := t.TempDir()
|
||||
archive := fakeBudgetArchive(t, dir)
|
||||
dest := filepath.Join(dir, "dest")
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
if _, err := a.extractWithExternalTool("7z", archive, dest, int64(maxExtractSize), true, scope); err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dest, "payload.bin"))
|
||||
if err != nil || string(data) != "hello payload" {
|
||||
t.Fatalf("payload not moved: %v (%q)", err, string(data))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractWithExternalToolFailureShapePreserved(t *testing.T) {
|
||||
installFakeExtractor(t, "7z", "Path = payload.bin\nSize = 16\n", "echo boom >&2\nexit 3\n")
|
||||
a := &Agent{}
|
||||
dir := t.TempDir()
|
||||
archive := fakeBudgetArchive(t, dir)
|
||||
dest := filepath.Join(dir, "dest")
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
_, err := a.extractWithExternalTool("7z", archive, dest, int64(maxExtractSize), true, scope)
|
||||
if err == nil || !strings.Contains(err.Error(), "7z extraction failed: exit status 3 - boom") {
|
||||
t.Fatalf("expected legacy failure shape, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// --- adpanel:fs-toctou - the pinned-root move phase ---
|
||||
|
||||
// A planted intermediate symlink on the DESTINATION side of the move (where
|
||||
// the scratch entries land) must be refused by the move phase and the outside
|
||||
// directory must never materialize (the old EvalSymlinks-then-MkdirAll +
|
||||
// os.Rename-by-name flow created it there before failing, or lost the swap
|
||||
// race entirely).
|
||||
func TestValidateAndMoveExtracted_PlantedIntermediateDirEscapeBlocked(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
tmp := filepath.Join(dir, "scratch")
|
||||
if err := os.MkdirAll(filepath.Join(tmp, "evil", "newdir"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(tmp, "evil", "newdir", "payload.txt"), []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dest := filepath.Join(dir, "dest")
|
||||
if err := os.MkdirAll(dest, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(dest, "evil")); err != nil {
|
||||
t.Skipf("symlinks unsupported: %v", err)
|
||||
}
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
_, err := validateAndMoveExtracted(scope, tmp, dest, 1<<20, true)
|
||||
if err == nil || !strings.Contains(err.Error(), "symlink escape blocked during extract") {
|
||||
t.Fatalf("expected escape refusal, got: %v", err)
|
||||
}
|
||||
if _, statErr := os.Lstat(filepath.Join(outside, "newdir")); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("outside target must not gain newdir, err=%v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
// End-to-end: a fake extractor planting entries under an escaping symlink
|
||||
// inside its scratch dir must fail the move phase without materializing
|
||||
// anything outside the scope.
|
||||
func TestExtractWithExternalTool_MovePhaseEscapeBlocked(t *testing.T) {
|
||||
installFakeExtractor(t, "7z", "Path = payload.bin\nSize = 5\n",
|
||||
"mkdir -p \"$d/evil/newdir\"\nprintf evil > \"$d/evil/newdir/payload.txt\"\n")
|
||||
a := &Agent{}
|
||||
dir := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
archive := fakeBudgetArchive(t, dir)
|
||||
dest := filepath.Join(dir, "dest")
|
||||
if err := os.MkdirAll(dest, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(dest, "evil")); err != nil {
|
||||
t.Skipf("symlinks unsupported: %v", err)
|
||||
}
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
_, err := a.extractWithExternalTool("7z", archive, dest, int64(maxExtractSize), true, scope)
|
||||
if err == nil || !strings.Contains(err.Error(), "symlink escape blocked during extract") {
|
||||
t.Fatalf("expected escape refusal, got: %v", err)
|
||||
}
|
||||
if _, statErr := os.Lstat(filepath.Join(outside, "newdir")); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("outside target must not gain newdir, err=%v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
// --- pre-flight bounding: timeout + output cap ---
|
||||
|
||||
// installSleepingListFakeExtractor installs a fake extractor whose listing
|
||||
// (7z l / unrar vt) emits a tiny listing and then sleeps past the pre-flight
|
||||
// timeout, so only the timeout can bound the pre-flight.
|
||||
func installSleepingListFakeExtractor(t *testing.T, bin, seconds string) {
|
||||
t.Helper()
|
||||
if _, err := os.Stat("/bin/sh"); err != nil {
|
||||
t.Skip("/bin/sh unavailable for fake extractor")
|
||||
}
|
||||
binDir := t.TempDir()
|
||||
script := "#!/bin/sh\n" +
|
||||
"if [ \"$1\" = \"l\" ] || [ \"$1\" = \"vt\" ]; then\n" +
|
||||
"printf 'Path = payload.bin\\nSize = 5\\n'\n" +
|
||||
"sleep " + seconds + "\n" +
|
||||
"exit 0\nfi\n" +
|
||||
"exit 0\n"
|
||||
if err := os.WriteFile(filepath.Join(binDir, bin), []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
}
|
||||
|
||||
// A 7z listing emitting more than the output cap must fail closed, promptly,
|
||||
// with the existing listing-failure shape.
|
||||
func TestExtractWithExternalToolPreflightListingOverCapFailsClosed(t *testing.T) {
|
||||
installFakeExtractor(t, "7z", strings.Repeat("Path = entry.bin\nSize = 1\n", 200), "exit 0\n")
|
||||
oldCap := preflightMaxListingBytes
|
||||
preflightMaxListingBytes = 1024
|
||||
defer func() { preflightMaxListingBytes = oldCap }()
|
||||
a := &Agent{}
|
||||
dir := t.TempDir()
|
||||
archive := fakeBudgetArchive(t, dir)
|
||||
dest := filepath.Join(dir, "dest")
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
start := time.Now()
|
||||
_, err := a.extractWithExternalTool("7z", archive, dest, int64(maxExtractSize), true, scope)
|
||||
if err == nil || !strings.Contains(err.Error(), "7z pre-flight listing failed") {
|
||||
t.Fatalf("expected over-cap listing failure, got: %v", err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 15*time.Second {
|
||||
t.Fatalf("over-cap listing did not fail promptly (took %v)", elapsed)
|
||||
}
|
||||
if entries, _ := os.ReadDir(dest); len(entries) != 0 {
|
||||
t.Fatalf("destination touched despite listing failure: %d entries", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
// A 7z listing stalling past the pre-flight timeout must fail closed with the
|
||||
// listing-failure shape instead of hanging the request.
|
||||
func TestExtractWithExternalToolPreflightListingTimeoutFailsClosed(t *testing.T) {
|
||||
installSleepingListFakeExtractor(t, "7z", "30")
|
||||
oldTO := preflightListingTimeout
|
||||
preflightListingTimeout = 1 * time.Second
|
||||
defer func() { preflightListingTimeout = oldTO }()
|
||||
a := &Agent{}
|
||||
dir := t.TempDir()
|
||||
archive := fakeBudgetArchive(t, dir)
|
||||
dest := filepath.Join(dir, "dest")
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
start := time.Now()
|
||||
_, err := a.extractWithExternalTool("7z", archive, dest, int64(maxExtractSize), true, scope)
|
||||
if err == nil || !strings.Contains(err.Error(), "7z pre-flight listing failed") {
|
||||
t.Fatalf("expected listing-timeout failure, got: %v", err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 15*time.Second {
|
||||
t.Fatalf("stalled listing did not fail promptly (took %v)", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// unrar pre-flight is fail-open: a listing that cannot complete in time only
|
||||
// skips the pre-flight (the runtime watchdog plus the post-extraction scan
|
||||
// remain the cap), and the extraction still completes.
|
||||
func TestExtractWithExternalToolPreflightListingTimeoutUnrarSkips(t *testing.T) {
|
||||
installSleepingListFakeExtractor(t, "unrar", "30")
|
||||
oldTO := preflightListingTimeout
|
||||
preflightListingTimeout = 1 * time.Second
|
||||
defer func() { preflightListingTimeout = oldTO }()
|
||||
a := &Agent{}
|
||||
dir := t.TempDir()
|
||||
archive := fakeBudgetArchive(t, dir)
|
||||
dest := filepath.Join(dir, "dest")
|
||||
scope, serr := safeOpenRoot(dir)
|
||||
if serr != nil {
|
||||
t.Fatalf("safeOpenRoot: %v", serr)
|
||||
}
|
||||
defer scope.Close()
|
||||
|
||||
start := time.Now()
|
||||
if _, err := a.extractWithExternalTool("unrar", archive, dest, int64(maxExtractSize), true, scope); err != nil {
|
||||
t.Fatalf("unrar pre-flight timeout must skip the pre-flight, got: %v", err)
|
||||
}
|
||||
if elapsed := time.Since(start); elapsed > 15*time.Second {
|
||||
t.Fatalf("stalled unrar listing did not skip promptly (took %v)", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
// --- pre-flight file-count alignment ---
|
||||
|
||||
// An archive with exactly maxExtractFiles entries must pass the pre-flight
|
||||
// exactly like the in-process zip path (len(r.File) == maxExtractFiles is
|
||||
// accepted); the 7z header block's own "Path = <archive>" line (no Size line)
|
||||
// must not inflate the count, and maxExtractFiles+1 entries must still be
|
||||
// rejected.
|
||||
func TestExtractBudgetPreflightFileCountAlignedWithInProcessZip(t *testing.T) {
|
||||
var b strings.Builder
|
||||
b.WriteString("Listing archive: bomb.7z\n\n--\nPath = bomb.7z\nType = 7z\n\n----------\n\n")
|
||||
for i := 0; i < maxExtractFiles; i++ {
|
||||
fmt.Fprintf(&b, "Path = f%06d.bin\nSize = 1\n\n", i)
|
||||
}
|
||||
stats, err := parse7zSltSizes(b.String())
|
||||
if err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
if stats.fileCount != maxExtractFiles {
|
||||
t.Fatalf("entry count mismatch: %d want %d", stats.fileCount, maxExtractFiles)
|
||||
}
|
||||
if err := checkExternalListingBudget(stats, int64(maxExtractSize)); err != nil {
|
||||
t.Fatalf("exactly maxExtractFiles entries must pass, got: %v", err)
|
||||
}
|
||||
|
||||
b.WriteString("Path = extra.bin\nSize = 1\n\n")
|
||||
stats, err = parse7zSltSizes(b.String())
|
||||
if err != nil {
|
||||
t.Fatalf("parse: %v", err)
|
||||
}
|
||||
if err := checkExternalListingBudget(stats, int64(maxExtractSize)); err == nil ||
|
||||
!strings.Contains(err.Error(), "too many files in archive") {
|
||||
t.Fatalf("maxExtractFiles+1 entries must be rejected, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// --- adpanel:import-extract-budget — the routed import extract's per-entry quota bound ---
|
||||
//
|
||||
// The import-tar handler runs quota PRE-checks only (checkDiskLimit /
|
||||
// checkDiskCapacity with extra=0) and then streams an undeclared tar into the
|
||||
// wiped server scope — the last long quota-accounted write without a
|
||||
// mid-write bound before this fix. extractTarSafeRouted now takes the same
|
||||
// optional transfer-budget callback copyDir standardized
|
||||
// (adpanel:backup-copy-budget): nil = unlimited (old call shape for unbudgeted
|
||||
// callers), armed = consulted per extracted file, breach = the
|
||||
// errImportExtractBudgetExceeded sentinel.
|
||||
|
||||
// A budget that trips aborts the walk with the sentinel: files extracted
|
||||
// before the breach stay (documented partial extract, cleaned by the
|
||||
// handler), files after it never land — the same walk-order contract as
|
||||
// copyDir's budget test.
|
||||
func TestExtractTarSafeRoutedBudgetTripAbortsExtract(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
serverDir := filepath.Join(dir, "alpha")
|
||||
backupsDir := filepath.Join(dir, "backups")
|
||||
for _, d := range []string{serverDir, backupsDir} {
|
||||
if err := os.MkdirAll(d, 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
pr, pw, _ := os.Pipe()
|
||||
go func() {
|
||||
tw := tar.NewWriter(pw)
|
||||
for _, n := range []string{"a.txt", "b.txt"} {
|
||||
hdr := &tar.Header{Name: n, Mode: 0o644, Size: 4}
|
||||
_ = tw.WriteHeader(hdr)
|
||||
_, _ = tw.Write([]byte("pwn\n"))
|
||||
}
|
||||
_ = tw.Close()
|
||||
_ = pw.Close()
|
||||
}()
|
||||
defer pr.Close()
|
||||
|
||||
budget := func(extractedSoFar int64) error {
|
||||
if extractedSoFar > 0 {
|
||||
return errImportExtractBudgetExceeded
|
||||
}
|
||||
return nil
|
||||
}
|
||||
err := extractTarSafeRouted(tar.NewReader(pr), serverDir, backupsDir, budget)
|
||||
if !errors.Is(err, errImportExtractBudgetExceeded) {
|
||||
t.Fatalf("expected errImportExtractBudgetExceeded, got: %v", err)
|
||||
}
|
||||
// Entry order is the tar's write order: a.txt was extracted before the
|
||||
// sentinel, b.txt was aborted.
|
||||
if data, rerr := os.ReadFile(filepath.Join(serverDir, "a.txt")); rerr != nil || string(data) != "pwn\n" {
|
||||
t.Fatalf("a.txt must be present from before the breach: %v (%q)", rerr, string(data))
|
||||
}
|
||||
if _, serr := os.Lstat(filepath.Join(serverDir, "b.txt")); !os.IsNotExist(serr) {
|
||||
t.Fatalf("b.txt must not be extracted past the breach, err=%v", serr)
|
||||
}
|
||||
}
|
||||
|
||||
// A nil budget is unlimited and keeps the pre-budget semantics exactly: the
|
||||
// global archive-bomb cap (limitedWriter, maxExtractSize) remains the only
|
||||
// in-walk bound, as documented.
|
||||
func TestExtractTarSafeRoutedNilBudgetUnlimited(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
serverDir := filepath.Join(dir, "alpha")
|
||||
backupsDir := filepath.Join(dir, "backups")
|
||||
pr, pw, _ := os.Pipe()
|
||||
go func() {
|
||||
tw := tar.NewWriter(pw)
|
||||
hdr := &tar.Header{Name: "payload.txt", Mode: 0o644, Size: 6}
|
||||
_ = tw.WriteHeader(hdr)
|
||||
_, _ = tw.Write([]byte("hello\n"))
|
||||
_ = tw.Close()
|
||||
_ = pw.Close()
|
||||
}()
|
||||
defer pr.Close()
|
||||
|
||||
if err := extractTarSafeRouted(tar.NewReader(pr), serverDir, backupsDir, nil); err != nil {
|
||||
t.Fatalf("unbudgeted extract (nil budget) failed: %v", err)
|
||||
}
|
||||
if data, err := os.ReadFile(filepath.Join(serverDir, "payload.txt")); err != nil || string(data) != "hello\n" {
|
||||
t.Fatalf("unbudgeted extract wrong: %v (%q)", err, string(data))
|
||||
}
|
||||
}
|
||||
|
||||
// buildSizedImportTar produces the transfer-tar shape handleExportServer
|
||||
// emits (server files at the root, a .adpanel_backups/ artifact, the meta
|
||||
// under .adpanel_meta/) with the server payload sized to payloadBytes, so a
|
||||
// test can make the tar's own content the deterministic "growth" between the
|
||||
// handler's validated pre-checks and the extract walk — no timing dependence
|
||||
// (the growth-injection style of stubDockerInspectGrowingTree, realized
|
||||
// through the request body itself).
|
||||
func buildSizedImportTar(t *testing.T, name string, payloadBytes int64) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
tw := tar.NewWriter(&buf)
|
||||
writeEntry := func(tarName string, data []byte) {
|
||||
hdr := &tar.Header{Name: tarName, Mode: 0o644, Size: int64(len(data)), Typeflag: tar.TypeReg}
|
||||
if err := tw.WriteHeader(hdr); err != nil {
|
||||
t.Fatalf("write header %s: %v", tarName, err)
|
||||
}
|
||||
if _, err := tw.Write(data); err != nil {
|
||||
t.Fatalf("write body %s: %v", tarName, err)
|
||||
}
|
||||
}
|
||||
writeEntry("server.properties", []byte("level-name=world\n"))
|
||||
writeEntry("world.dat", make([]byte, payloadBytes))
|
||||
writeEntry(".adpanel_backups/backup-1.tar.gz", []byte("fake-backup-bytes"))
|
||||
metaBytes, err := json.Marshal(map[string]any{"type": "custom"})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal meta: %v", err)
|
||||
}
|
||||
writeEntry(".adpanel_meta/"+sanitizeName(name)+".json", metaBytes)
|
||||
if err := tw.Close(); err != nil {
|
||||
t.Fatalf("close tar: %v", err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// createSparseFile creates a file whose APPARENT size is n bytes without
|
||||
// writing them (truncate): du -sb and the Go-walk fallback both report
|
||||
// apparent size, so the quota walks see n bytes deterministically without a
|
||||
// gigabyte of real writes.
|
||||
func createSparseFile(t *testing.T, path string, n int64) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
|
||||
t.Fatalf("mkdir for %s: %v", path, err)
|
||||
}
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
if err := f.Truncate(n); err != nil {
|
||||
t.Fatalf("truncate %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The mid-extract budget aborts an import whose archive outgrows the
|
||||
// validated allowance: 507 with the EXACT disk_limit_exceeded body shape
|
||||
// (shared diskLimitExceededBody) naming the cause, and the partial extract
|
||||
// (server dir + backups dir — both partial after the breach) is cleaned.
|
||||
//
|
||||
// Deterministic growth injection: the handler's pre-checks validate with
|
||||
// extra=0 (15 MiB used <= 20 MB limit), the purge then frees the 15 MiB, so
|
||||
// the armed allowance is the full 20 MB + 16 MiB slack = 36 MiB — and the
|
||||
// tar's own 40 MiB payload IS the growth, landing strictly after the
|
||||
// validated projection (the request body is the mid-write writer).
|
||||
func TestImportTarExtractBudgetBreach507CleansPartialExtract(t *testing.T) {
|
||||
a, _ := newTestAgent(t)
|
||||
const name = "alpha"
|
||||
serverDir := a.serverDir(name)
|
||||
const limitBytes = int64(20 << 20)
|
||||
writeBigFile(t, filepath.Join(serverDir, "old-world.dat"), 15<<20)
|
||||
if err := a.saveMeta(serverDir, map[string]any{"resources": map[string]any{"storageMb": float64(20)}}); err != nil {
|
||||
t.Fatalf("saveMeta: %v", err)
|
||||
}
|
||||
// Test premise: the handler's own pre-check must PASS, so the 507 below
|
||||
// can only come from the mid-extract budget.
|
||||
if diskErr := a.checkDiskLimit(serverDir, 0); diskErr != nil {
|
||||
t.Fatalf("test premise: pre-check must pass, got %v", diskErr)
|
||||
}
|
||||
|
||||
tarBytes := buildSizedImportTar(t, name, 40<<20)
|
||||
rec, _ := doImportTar(t, a, name, "", tarBytes)
|
||||
if rec.Code != 507 {
|
||||
t.Fatalf("import status %d body %s, want 507 from the extract budget", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode 507 body: %v", err)
|
||||
}
|
||||
if body["error"] != "disk_limit_exceeded" {
|
||||
t.Fatalf("error = %v, want disk_limit_exceeded (settled panel pass-through)", body["error"])
|
||||
}
|
||||
if len(body) != len(diskLimitBodyKeys) {
|
||||
t.Fatalf("507 body must keep the exact checkDiskLimit shape (%v), got %d keys: %v", diskLimitBodyKeys, len(body), body)
|
||||
}
|
||||
for _, k := range diskLimitBodyKeys {
|
||||
if _, ok := body[k]; !ok {
|
||||
t.Fatalf("507 body missing key %q: %v", k, body)
|
||||
}
|
||||
}
|
||||
if msg, _ := body["message"].(string); !strings.Contains(msg, "Import extract aborted") {
|
||||
t.Fatalf("message %q must name the growth cause (the server may be UNDER its limit; the settled whitelist keys on the error code only)", msg)
|
||||
}
|
||||
if limit, _ := body["limitBytes"].(float64); int64(limit) != limitBytes {
|
||||
t.Fatalf("limitBytes = %v, want the configured 20MB", body["limitBytes"])
|
||||
}
|
||||
|
||||
// The partial extract must be cleaned from BOTH quota-accounted trees.
|
||||
if _, err := os.Lstat(serverDir); !os.IsNotExist(err) {
|
||||
t.Fatalf("budget-aborted import must remove the partial server dir, err=%v", err)
|
||||
}
|
||||
if _, err := os.Lstat(a.serverBackupsDir(name)); !os.IsNotExist(err) {
|
||||
t.Fatalf("budget-aborted import must remove the partial backups dir, err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// adpanel:import-extract-budget + adpanel:multidisk — the budget must arm
|
||||
// whenever the projection was validated against ANY cap, not only the
|
||||
// per-server limit: a server with NO resources storageMb/storageGb that lands
|
||||
// on a secondary disk with a LimitGb ceiling has its projection validated by
|
||||
// checkDiskCapacity alone, so the mid-extract budget must still be armed —
|
||||
// nothing else re-checks the per-disk axis mid-extract, so the shared
|
||||
// physical disk could fill. A sparse 1000 MiB file in a sibling server's dir
|
||||
// consumes the 1 GiB disk's allowance deterministically (apparent size),
|
||||
// leaving ~24 MiB; the 48 MiB payload breaches the folded allowance
|
||||
// (~24 MiB) + slack mid-walk and aborts 507 with the SAME
|
||||
// disk_limit_exceeded body shape, and the partial extract is cleaned.
|
||||
// (The body's limitBytes stays keyed to the per-server axis and reads 0
|
||||
// here — the settled panel whitelist keys on the error code only.)
|
||||
func TestImportTarExtractBudgetArmedByDiskCeiling507CleansPartialExtract(t *testing.T) {
|
||||
a, _ := newTestAgent(t)
|
||||
mount := t.TempDir()
|
||||
d := registerTestDisk(t, a, mount, 1) // 1 GiB per-disk ceiling: the ONLY bound
|
||||
const name = "alpha"
|
||||
a.setServerDiskMapping(name, d.ID)
|
||||
serverDir := a.serverDir(name)
|
||||
// Test premise: no per-server storage limit — the disk ceiling is the
|
||||
// only cap the pre-checks validated against.
|
||||
if limit := a.getServerDiskLimitBytes(serverDir); limit != 0 {
|
||||
t.Fatalf("test premise: per-server storage limit must be absent, got %d", limit)
|
||||
}
|
||||
if disk := a.diskForServer(name); diskCapacityCeilingBytes(disk) != 1<<30 {
|
||||
t.Fatalf("test premise: server must resolve onto the limited secondary disk, got %+v", disk)
|
||||
}
|
||||
createSparseFile(t, filepath.Join(a.diskLayoutVolumes(mount), "beta", "fat.dat"), 1000<<20)
|
||||
|
||||
// The pre-check must PASS (~1000 MiB <= 1 GiB), so the 507 below can only
|
||||
// come from the mid-extract budget.
|
||||
if capErr := a.checkDiskCapacity(a.diskForServer(name), 0); capErr != nil {
|
||||
t.Fatalf("test premise: pre-check must pass, got %v", capErr)
|
||||
}
|
||||
|
||||
tarBytes := buildSizedImportTar(t, name, 48<<20)
|
||||
rec, _ := doImportTar(t, a, name, d.ID, tarBytes)
|
||||
if rec.Code != 507 {
|
||||
t.Fatalf("import status %d body %s, want 507 from the extract budget armed by the disk ceiling", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode 507 body: %v", err)
|
||||
}
|
||||
if body["error"] != "disk_limit_exceeded" {
|
||||
t.Fatalf("error = %v, want disk_limit_exceeded (settled panel pass-through)", body["error"])
|
||||
}
|
||||
if len(body) != len(diskLimitBodyKeys) {
|
||||
t.Fatalf("507 body must keep the exact checkDiskLimit shape (%v), got %d keys: %v", diskLimitBodyKeys, len(body), body)
|
||||
}
|
||||
if msg, _ := body["message"].(string); !strings.Contains(msg, "Import extract aborted") {
|
||||
t.Fatalf("message %q must name the growth cause (the settled whitelist keys on the error code only)", msg)
|
||||
}
|
||||
if limit, _ := body["limitBytes"].(float64); limit != 0 {
|
||||
t.Fatalf("limitBytes = %v, want 0 (armed by the disk ceiling; keyed to the per-server axis as documented)", body["limitBytes"])
|
||||
}
|
||||
|
||||
// The partial extract must be cleaned from BOTH quota-accounted trees.
|
||||
if _, err := os.Lstat(serverDir); !os.IsNotExist(err) {
|
||||
t.Fatalf("budget-aborted import must remove the partial server dir, err=%v", err)
|
||||
}
|
||||
if _, err := os.Lstat(a.serverBackupsDir(name)); !os.IsNotExist(err) {
|
||||
t.Fatalf("budget-aborted import must remove the partial backups dir, err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// The allowance is sampled AFTER the purge, honestly: the wipe frees the
|
||||
// server's old usage on both axes, so the extract may repurpose it. With a
|
||||
// 20 MB limit and 15 MiB of pre-import files, a 25 MiB payload — larger than
|
||||
// the limit itself — must land (post-wipe allowance 20 MB + slack = 36 MiB);
|
||||
// a pre-wipe snapshot would have derived 20-15+16=21 MiB and false-aborted a
|
||||
// legitimate transfer. This is the import's documented replace-state
|
||||
// semantics made quota-honest, not a relaxation: the pre-checks still gate
|
||||
// the pre-import state byte-identically.
|
||||
func TestImportTarExtractBudgetWipeFreesAllowance(t *testing.T) {
|
||||
a, _ := newTestAgent(t)
|
||||
const name = "alpha"
|
||||
serverDir := a.serverDir(name)
|
||||
writeBigFile(t, filepath.Join(serverDir, "old-world.dat"), 15<<20)
|
||||
if err := a.saveMeta(serverDir, map[string]any{"resources": map[string]any{"storageMb": float64(20)}}); err != nil {
|
||||
t.Fatalf("saveMeta: %v", err)
|
||||
}
|
||||
if diskErr := a.checkDiskLimit(serverDir, 0); diskErr != nil {
|
||||
t.Fatalf("test premise: pre-check must pass, got %v", diskErr)
|
||||
}
|
||||
|
||||
tarBytes := buildSizedImportTar(t, name, 25<<20)
|
||||
rec, resp := doImportTar(t, a, name, "", tarBytes)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("import status %d body %s, want 200 (the wipe freed the old usage, so the extract's allowance is the full limit + slack)", rec.Code, rec.Body.String())
|
||||
}
|
||||
if ok, _ := resp["ok"].(bool); !ok {
|
||||
t.Fatalf("import not ok: %v", resp)
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(serverDir, "world.dat")); err != nil {
|
||||
t.Fatalf("imported payload must land: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A server with NEITHER bound (no resources storage limit, primary disk) keeps
|
||||
// its unlimited extract: no budget is armed and behavior is unchanged — the
|
||||
// pre-existing global archive-bomb cap remains the only in-walk bound.
|
||||
func TestImportTarExtractBudgetUnlimitedPostureUnchanged(t *testing.T) {
|
||||
a, _ := newTestAgent(t)
|
||||
const name = "alpha"
|
||||
tarBytes := buildSizedImportTar(t, name, 25<<20)
|
||||
rec, resp := doImportTar(t, a, name, "", tarBytes)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("import status %d body %s, want 200 (no bound exists, no budget armed)", rec.Code, rec.Body.String())
|
||||
}
|
||||
if ok, _ := resp["ok"].(bool); !ok {
|
||||
t.Fatalf("import not ok: %v", resp)
|
||||
}
|
||||
if _, err := os.Lstat(filepath.Join(a.serverDir(name), "world.dat")); err != nil {
|
||||
t.Fatalf("imported payload must land: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user