346 lines
13 KiB
Go
346 lines
13 KiB
Go
package main
|
|
|
|
// adpanel:archive-no-clobber - the files/archive endpoint used to finalize its
|
|
// archive with a plain overwrite rename, so two archives made in the same
|
|
// directory within one second (two sub-users, two admins acting concurrently)
|
|
// silently destroyed the first, and a user file that happened to carry the
|
|
// exact timestamped name was replaced without warning - both answering 200 as
|
|
// if nothing happened. Every other destination-creating path in the files API
|
|
// is create-only; these tests pin the archive to the same discipline: the
|
|
// commit is RENAME_NOREPLACE, collisions resolve to deterministic -N fallback
|
|
// names, and an existing file is never replaced.
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// archiveSentinelContent makes every pre-existing file's content verifiable:
|
|
// a preserved file must keep its exact bytes, not just its name.
|
|
func archiveSentinelContent(name string) []byte {
|
|
return []byte("DO-NOT-DELETE sentinel for " + name)
|
|
}
|
|
|
|
func precreateArchiveNames(t *testing.T, dir string, names []string) {
|
|
t.Helper()
|
|
for _, name := range names {
|
|
if err := os.WriteFile(filepath.Join(dir, name), archiveSentinelContent(name), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func assertArchiveNamesIntact(t *testing.T, dir string, names []string) {
|
|
t.Helper()
|
|
for _, name := range names {
|
|
data, err := os.ReadFile(filepath.Join(dir, name))
|
|
if err != nil {
|
|
t.Fatalf("pre-existing file %s was destroyed: %v", name, err)
|
|
}
|
|
if string(data) != string(archiveSentinelContent(name)) {
|
|
t.Fatalf("pre-existing file %s was overwritten (content %q)", name, data)
|
|
}
|
|
}
|
|
}
|
|
|
|
func decodeArchiveResponse(t *testing.T, rec *httptest.ResponseRecorder) (string, string) {
|
|
t.Helper()
|
|
var resp map[string]any
|
|
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
|
t.Fatalf("bad response json: %v", err)
|
|
}
|
|
name, _ := resp["name"].(string)
|
|
path, _ := resp["path"].(string)
|
|
return name, path
|
|
}
|
|
|
|
// The core finding: a user file that happens to carry the exact timestamped
|
|
// destination name must survive the archive run, and the produced archive must
|
|
// land under a fresh -N fallback name. The first few candidates for the
|
|
// current AND the next second are pre-created, so the run has to walk past
|
|
// them no matter where the second boundary falls during the request.
|
|
func TestHandleFilesArchiveNeverOverwritesExistingName(t *testing.T) {
|
|
a, vol := newArchiveTestAgent(t)
|
|
serverDir := filepath.Join(vol, "srv1")
|
|
writeArchiveFixture(t, serverDir)
|
|
outDir := filepath.Join(serverDir, "out")
|
|
if err := os.MkdirAll(outDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
now := time.Now()
|
|
var taken []string
|
|
for _, second := range []time.Time{now, now.Add(time.Second)} {
|
|
candidates := archiveDestinationNames(second)
|
|
taken = append(taken, candidates[:5]...)
|
|
}
|
|
precreateArchiveNames(t, outDir, taken)
|
|
|
|
rec := callFilesArchive(t, a, "srv1", []string{"a.txt"}, "out")
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
name, path := decodeArchiveResponse(t, rec)
|
|
if !strings.HasPrefix(name, "archive-") || !strings.HasSuffix(name, ".tar.gz") {
|
|
t.Fatalf("unexpected archive name %q", name)
|
|
}
|
|
for _, takenName := range taken {
|
|
if name == takenName {
|
|
t.Fatalf("archive reused an existing name %q instead of a fallback", name)
|
|
}
|
|
}
|
|
if want := filepath.Join("out", name); path != want {
|
|
t.Fatalf("response path = %q, want %q", path, want)
|
|
}
|
|
|
|
// The whole point: every pre-existing file is still there, byte-identical.
|
|
assertArchiveNamesIntact(t, outDir, taken)
|
|
|
|
// The produced archive exists under the fresh name and is a valid stream.
|
|
if _, err := os.Stat(filepath.Join(outDir, name)); err != nil {
|
|
t.Fatalf("final archive missing: %v", err)
|
|
}
|
|
readTarMembers(t, filepath.Join(outDir, name))
|
|
|
|
// No in-flight temp file may survive.
|
|
entries, _ := os.ReadDir(outDir)
|
|
for _, e := range entries {
|
|
if isArchiveTempName(e.Name()) {
|
|
t.Fatalf("temp archive left behind: %s", e.Name())
|
|
}
|
|
}
|
|
}
|
|
|
|
// When every candidate of the running second is already taken (101 pre-existing
|
|
// files - the only way to exhaust the list), the endpoint must REFUSE with the
|
|
// 409 "archive name already exists" shape instead of falling back to an
|
|
// overwrite. Normally the handler's second equals the setup second and the 409
|
|
// is deterministic; should the second boundary fall between setup and request
|
|
// anyway, the next second's primary is free and a 200 with a fresh name is
|
|
// equally correct - either way nothing pre-existing may be touched.
|
|
func TestHandleFilesArchiveAllCandidatesTakenRefuses(t *testing.T) {
|
|
a, vol := newArchiveTestAgent(t)
|
|
serverDir := filepath.Join(vol, "srv1")
|
|
writeArchiveFixture(t, serverDir)
|
|
outDir := filepath.Join(serverDir, "out")
|
|
if err := os.MkdirAll(outDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
now := time.Now()
|
|
taken := append(archiveDestinationNames(now), archiveDestinationNames(now.Add(time.Second))...)
|
|
precreateArchiveNames(t, outDir, taken)
|
|
|
|
rec := callFilesArchive(t, a, "srv1", []string{"a.txt"}, "out")
|
|
switch rec.Code {
|
|
case http.StatusConflict:
|
|
if !strings.Contains(rec.Body.String(), "archive name already exists") {
|
|
t.Fatalf("409 body = %s, want the archive name conflict shape", rec.Body.String())
|
|
}
|
|
case http.StatusOK:
|
|
name, _ := decodeArchiveResponse(t, rec)
|
|
for _, takenName := range taken {
|
|
if name == takenName {
|
|
t.Fatalf("archive reused an existing name %q instead of refusing", name)
|
|
}
|
|
}
|
|
default:
|
|
t.Fatalf("expected 409 or 200, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
assertArchiveNamesIntact(t, outDir, taken)
|
|
entries, _ := os.ReadDir(outDir)
|
|
for _, e := range entries {
|
|
if isArchiveTempName(e.Name()) {
|
|
t.Fatalf("temp archive left behind: %s", e.Name())
|
|
}
|
|
}
|
|
}
|
|
|
|
// The walk-time self-exclusion must track the name that will actually be
|
|
// written: a pre-existing file at the primary timestamped name keeps getting
|
|
// archived like any other file (it is not the output - the output lands at the
|
|
// fallback name), and it stays on disk afterwards.
|
|
func TestHandleFilesArchiveArchivesPreExistingCollidingFile(t *testing.T) {
|
|
a, vol := newArchiveTestAgent(t)
|
|
serverDir := filepath.Join(vol, "srv1")
|
|
writeArchiveFixture(t, serverDir)
|
|
outDir := filepath.Join(serverDir, "out")
|
|
if err := os.MkdirAll(outDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
collidingName := archiveDestinationNames(time.Now())[0]
|
|
precreateArchiveNames(t, outDir, []string{collidingName})
|
|
|
|
rec := callFilesArchive(t, a, "srv1", []string{"."}, "out")
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
|
|
}
|
|
name, _ := decodeArchiveResponse(t, rec)
|
|
|
|
// The colliding file survived...
|
|
assertArchiveNamesIntact(t, outDir, []string{collidingName})
|
|
|
|
// ...and was archived as an ordinary member, with its exact content.
|
|
names, contents := readTarMembers(t, filepath.Join(outDir, name))
|
|
found := false
|
|
for _, member := range names {
|
|
if filepath.Base(strings.TrimSuffix(member, "/")) == collidingName {
|
|
found = true
|
|
if got := contents[member]; got != string(archiveSentinelContent(collidingName)) {
|
|
t.Fatalf("archived colliding file content = %q, want sentinel", got)
|
|
}
|
|
}
|
|
if filepath.Base(strings.TrimSuffix(member, "/")) == name {
|
|
t.Fatalf("the archive contains its own output as member %q", member)
|
|
}
|
|
}
|
|
if !found {
|
|
t.Fatalf("pre-existing file %s missing from archive members [%s]", collidingName, strings.Join(names, ","))
|
|
}
|
|
}
|
|
|
|
// Two archive runs into the same directory must both succeed and both survive
|
|
// - even when they share the same second-resolution timestamp.
|
|
func TestHandleFilesArchiveConsecutiveRunsBothSurvive(t *testing.T) {
|
|
a, vol := newArchiveTestAgent(t)
|
|
serverDir := filepath.Join(vol, "srv1")
|
|
writeArchiveFixture(t, serverDir)
|
|
outDir := filepath.Join(serverDir, "out")
|
|
if err := os.MkdirAll(outDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
committed := map[string]bool{}
|
|
for run := 0; run < 2; run++ {
|
|
rec := callFilesArchive(t, a, "srv1", []string{"a.txt"}, "out")
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("run %d: expected 200, got %d: %s", run, rec.Code, rec.Body.String())
|
|
}
|
|
name, _ := decodeArchiveResponse(t, rec)
|
|
if committed[name] {
|
|
t.Fatalf("run %d reused already-committed name %q", run, name)
|
|
}
|
|
committed[name] = true
|
|
names, _ := readTarMembers(t, filepath.Join(outDir, name))
|
|
if len(names) == 0 || names[0] != "a.txt" {
|
|
t.Fatalf("run %d produced unexpected members %v", run, names)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestArchiveDestinationNamesShape(t *testing.T) {
|
|
names := archiveDestinationNames(time.Date(2026, 10, 12, 15, 30, 45, 0, time.UTC))
|
|
if len(names) != 101 {
|
|
t.Fatalf("candidate count = %d, want 101 (primary + 100 fallbacks)", len(names))
|
|
}
|
|
if names[0] != "archive-20261012-153045.tar.gz" {
|
|
t.Fatalf("primary candidate = %q", names[0])
|
|
}
|
|
seen := map[string]bool{}
|
|
for i, name := range names {
|
|
if seen[name] {
|
|
t.Fatalf("duplicate candidate %q", name)
|
|
}
|
|
seen[name] = true
|
|
if !strings.HasPrefix(name, "archive-20261012-153045") || !strings.HasSuffix(name, ".tar.gz") {
|
|
t.Fatalf("candidate %d %q breaks the archive-<ts>[-N].tar.gz shape", i, name)
|
|
}
|
|
}
|
|
if names[1] != "archive-20261012-153045-1.tar.gz" || names[100] != "archive-20261012-153045-100.tar.gz" {
|
|
t.Fatalf("fallback names malformed: %q / %q", names[1], names[100])
|
|
}
|
|
}
|
|
|
|
// Direct unit coverage of the two new pathsafe helpers: the advisory pick
|
|
// walks the candidate list and reports exhaustion as errSafeDestExists, and
|
|
// the commit refuses to replace an existing destination, falling through to
|
|
// the next candidate while every earlier file stays byte-identical.
|
|
func TestPickAndCommitArchiveNameNoReplace(t *testing.T) {
|
|
rootDir := t.TempDir()
|
|
root, err := safeOpenRoot(rootDir)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer root.Close()
|
|
|
|
candidates := archiveDestinationNames(time.Now())
|
|
|
|
// Empty directory: the primary candidate is picked.
|
|
name, err := pickArchiveDestinationName(root, ".", candidates)
|
|
if err != nil || name != candidates[0] {
|
|
t.Fatalf("pick on empty dir = (%q, %v), want (%q, nil)", name, err, candidates[0])
|
|
}
|
|
|
|
// Primary taken: the first fallback is picked.
|
|
if err := os.WriteFile(filepath.Join(rootDir, candidates[0]), []byte("taken"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
name, err = pickArchiveDestinationName(root, ".", candidates)
|
|
if err != nil || name != candidates[1] {
|
|
t.Fatalf("pick with primary taken = (%q, %v), want (%q, nil)", name, err, candidates[1])
|
|
}
|
|
|
|
// Everything taken: exhaustion surfaces as errSafeDestExists (the handler
|
|
// maps it onto the 409 "archive name already exists" response).
|
|
precreateArchiveNames(t, rootDir, candidates)
|
|
if _, err := pickArchiveDestinationName(root, ".", candidates); !errors.Is(err, errSafeDestExists) {
|
|
t.Fatalf("pick with all candidates taken: err = %v, want errSafeDestExists", err)
|
|
}
|
|
|
|
// Commit: create-only. The temp file renames onto the picked name; a
|
|
// second commit whose picked name is now taken falls through to the next
|
|
// candidate and never touches the file already at the picked name.
|
|
rootDir2 := t.TempDir()
|
|
root2, err := safeOpenRoot(rootDir2)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer root2.Close()
|
|
|
|
tempRel := ".archive-test.tmp"
|
|
if err := os.WriteFile(filepath.Join(rootDir2, tempRel), []byte("archive-bytes"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(rootDir2, candidates[0]), []byte("pre-existing"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
committed, err := commitArchiveNoReplace(root2, tempRel, candidates, candidates[0])
|
|
if err != nil {
|
|
t.Fatalf("commit with primary taken: %v", err)
|
|
}
|
|
if committed != candidates[1] {
|
|
t.Fatalf("commit = %q, want first fallback %q", committed, candidates[1])
|
|
}
|
|
if data, err := os.ReadFile(filepath.Join(rootDir2, candidates[0])); err != nil || string(data) != "pre-existing" {
|
|
t.Fatalf("pre-existing file at primary name damaged: %q, %v", data, err)
|
|
}
|
|
if data, err := os.ReadFile(filepath.Join(rootDir2, candidates[1])); err != nil || string(data) != "archive-bytes" {
|
|
t.Fatalf("committed archive content wrong: %q, %v", data, err)
|
|
}
|
|
if _, err := os.Lstat(filepath.Join(rootDir2, tempRel)); !os.IsNotExist(err) {
|
|
t.Fatalf("temp file survived the commit: %v", err)
|
|
}
|
|
|
|
// Exhaustion: every candidate taken, the temp file must remain untouched
|
|
// (the handler's deferred cleanup removes it) and the error must be
|
|
// errSafeDestExists. The previous commit consumed the temp file, so a
|
|
// fresh one is written first.
|
|
if err := os.WriteFile(filepath.Join(rootDir2, tempRel), []byte("archive-bytes-2"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := commitArchiveNoReplace(root2, tempRel, candidates[:2], candidates[1]); !errors.Is(err, errSafeDestExists) {
|
|
t.Fatalf("commit with every candidate taken: err = %v, want errSafeDestExists", err)
|
|
}
|
|
if data, err := os.ReadFile(filepath.Join(rootDir2, tempRel)); err != nil || string(data) != "archive-bytes-2" {
|
|
t.Fatalf("temp file damaged by refused commit: %q, %v", data, err)
|
|
}
|
|
}
|