package main // Direct daemon-side coverage for the adpanel:backup-cap-fallback count gate // in handleBackupsCreate. Until now the gate had no Go test of its own — its // behavior was pinned only indirectly, through the panel-side header pins (JS // suite) and tests/backup-cap-daemon-wiring.test.js. // // The gate resolves the count ceiling in exactly this order (pinned here // against the code, not the description): // // 1. meta resources.backupsMax — wins UNCHANGED when present and > 0 // (present-but-nonpositive meta — a hand-edited 0/negative — is not a // ceiling and falls through to the next source); // 2. the X-ADPanel-Backups-Max request header — the fallback, applied only // when step 1 left the ceiling at 0; strconv.Atoi must parse it AND the // parsed value must be > 0, so absent/empty/garbage/negative/zero all // resolve to no fallback; // 3. 0 = gate off: a direct daemon caller that sends neither source keeps // the pre-feature unlimited behavior. // // When the ceiling is positive the gate counts ONLY top-level directories of // the server's backups dir (os.ReadDir + IsDir — a stray file never counts) // and refuses with 403 backup_limit_reached once currentCount >= ceiling, // writing the exact four-key error/message/current/max body the panel relays // verbatim. import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" ) // headerVal takes the address of its argument so a table row can distinguish // an ABSENT X-ADPanel-Backups-Max header (nil) from one explicitly sent with // an empty value (non-nil, "") — Header.Get renders both as "", but they are // distinct wire states and both must resolve to no fallback. func headerVal(s string) *string { return &s } // countGateDrive runs handleBackupsCreate with a minimal JSON body and an // optional X-ADPanel-Backups-Max request header. func countGateDrive(t *testing.T, a *Agent, serverName string, header *string) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(http.MethodPost, "/v1/servers/"+serverName+"/backups", strings.NewReader(`{"name":"count-gate-probe"}`)) if header != nil { req.Header.Set("X-ADPanel-Backups-Max", *header) } rec := httptest.NewRecorder() a.handleBackupsCreate(rec, req, serverName) return rec } // seedCountGateBackups pre-seeds the server's backups dir the way the gate // measures it: top-level subdirectories count, files do not. Dirs are laid // out in the production shape (_/data) so the seed matches what real // backups leave behind. func seedCountGateBackups(t *testing.T, a *Agent, serverName string, dirs, files int) string { t.Helper() backupsDir := a.serverBackupsDir(serverName) for i := 0; i < dirs; i++ { backupDir := filepath.Join(backupsDir, fmt.Sprintf("1700000000_gate%03d", i)) if err := os.MkdirAll(filepath.Join(backupDir, "data"), 0o750); err != nil { t.Fatalf("seed backup dir: %v", err) } } for i := 0; i < files; i++ { stray := filepath.Join(backupsDir, fmt.Sprintf("stray%03d.txt", i)) if err := os.WriteFile(stray, []byte("not-a-backup"), 0o644); err != nil { t.Fatalf("seed stray file: %v", err) } } return backupsDir } // assertBackupLimitReached pins the gate's EXACT 403 body: the four keys // error/message/current/max (the panel relays this body verbatim, so it must // not gain or lose fields), the settled error code, the counts, and the wire // message format. func assertBackupLimitReached(t *testing.T, rec *httptest.ResponseRecorder, wantCurrent, wantMax int) { t.Helper() if rec.Code != 403 { t.Fatalf("create status %d body %s, want 403 backup_limit_reached", rec.Code, rec.Body.String()) } var body map[string]any if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatalf("decode 403 body: %v", err) } if body["error"] != "backup_limit_reached" { t.Fatalf("error = %v, want backup_limit_reached", body["error"]) } if len(body) != 4 { t.Fatalf("403 body must keep the exact gate shape (error/message/current/max), got %d keys: %v", len(body), body) } if got, _ := body["current"].(float64); int(got) != wantCurrent { t.Fatalf("current = %v, want %d (directories only)", body["current"], wantCurrent) } if got, _ := body["max"].(float64); int(got) != wantMax { t.Fatalf("max = %v, want %d", body["max"], wantMax) } wantMessage := fmt.Sprintf("Maximum backup limit reached (%d/%d). Delete old backups to create new ones.", wantCurrent, wantMax) if msg, _ := body["message"].(string); msg != wantMessage { t.Fatalf("message = %q, want %q", msg, wantMessage) } } // Every row reaches the gate with currentCount >= the resolved ceiling and // must be refused 403 with the pinned body — and the gate must fire BEFORE // any backup dir is created (the backups dir still holds exactly the seed). func TestBackupsCreateCountGateBlocksAtLimit(t *testing.T) { // Inert on the 403 paths (the gate fires before any docker call) and // hermetic if a regression routes a row into the full create. stubDockerInspectState(t, false) cases := []struct { name string meta map[string]any // nil = no meta file at all (loadMeta -> empty map) header *string // nil = request header absent dirs int wantCurrent int wantMax int }{ { // meta wins: resources.backupsMax = 2 with 2 seeded dirs. name: "meta_backupsMax_wins", meta: map[string]any{"resources": map[string]any{"backupsMax": float64(2)}}, dirs: 2, wantCurrent: 2, wantMax: 2, }, { // Header fallback: no meta file at all. name: "header_fallback_when_meta_file_absent", meta: nil, header: headerVal("2"), dirs: 2, wantCurrent: 2, wantMax: 2, }, { // Header fallback: meta present but carries no backupsMax key. name: "header_fallback_when_meta_lacks_backupsMax", meta: map[string]any{"resources": map[string]any{"storageMb": float64(200)}}, header: headerVal("2"), dirs: 2, wantCurrent: 2, wantMax: 2, }, { // The "garbage degrades" parity semantics: a hand-edited // present-but-zero backupsMax is NOT a ceiling, so the resolution // falls through to the header instead of leaving the gate off // with a seeded 2/2 tree. name: "meta_backupsMax_zero_falls_through_to_header", meta: map[string]any{"resources": map[string]any{"backupsMax": float64(0)}}, header: headerVal("2"), dirs: 2, wantCurrent: 2, wantMax: 2, }, { name: "meta_backupsMax_negative_falls_through_to_header", meta: map[string]any{"resources": map[string]any{"backupsMax": float64(-1)}}, header: headerVal("2"), dirs: 2, wantCurrent: 2, wantMax: 2, }, { // Boundary upper edge: count == max blocks. name: "boundary_count_equals_max_blocks", meta: nil, header: headerVal("2"), dirs: 2, wantCurrent: 2, wantMax: 2, }, { // current != max: the symmetric 2/2 rows above cannot detect a // swapped current/max (or a count read from the wrong side of the // comparison) — 3 seeded dirs under cap 2 must refuse with // current=3, max=2 and the "(3/2)" message. name: "over_cap_current_differs_from_max_blocks", meta: nil, header: headerVal("2"), dirs: 3, wantCurrent: 3, wantMax: 2, }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { a, _ := newTestAgent(t) // fresh agent per row: meta lives per server name const name = "alpha" serverDir := a.serverDir(name) writeSeedFile(t, filepath.Join(serverDir, "world.txt"), "seed", 0o644) if tc.meta != nil { if err := a.saveMeta(serverDir, tc.meta); err != nil { t.Fatalf("saveMeta: %v", err) } } backupsDir := seedCountGateBackups(t, a, name, tc.dirs, 0) rec := countGateDrive(t, a, name, tc.header) assertBackupLimitReached(t, rec, tc.wantCurrent, tc.wantMax) entries, err := os.ReadDir(backupsDir) if err != nil { t.Fatalf("read backups dir: %v", err) } if len(entries) != tc.dirs { t.Fatalf("refused create must not add backup entries, got %d: %v", len(entries), entries) } }) } } // Every row resolves either to a lower ceiling than the seeded count or to // gate-off, and must PASS the gate: the create runs to completion (200, cold // copy via the docker stub) and lands exactly one more backups-dir entry than // were seeded. A row that 403s here means the resolution order drifted. func TestBackupsCreateCountGatePassesThrough(t *testing.T) { // Cold-copy stub: once the gate passes, every row terminates // deterministically in a full, successful create. stubDockerInspectState(t, false) cases := []struct { name string meta map[string]any header *string dirs int files int }{ { // The ceiling is meta's 3, NOT the header's 1: 2 seeded dirs are // under 3, so the create must proceed (a header-first resolution // would 403 here). name: "meta_backupsMax_wins_over_lower_header", meta: map[string]any{"resources": map[string]any{"backupsMax": float64(3)}}, header: headerVal("1"), dirs: 2, }, { // Garbage headers parse to no fallback: gate off (1 seeded dir). name: "garbage_header_abc_leaves_gate_off", header: headerVal("abc"), dirs: 1, }, { name: "garbage_header_negative_leaves_gate_off", header: headerVal("-1"), dirs: 1, }, { name: "garbage_header_zero_leaves_gate_off", header: headerVal("0"), dirs: 1, }, { // Explicitly sent empty value: Atoi("") errors, gate off. name: "garbage_header_empty_value_leaves_gate_off", header: headerVal(""), dirs: 1, }, { // Neither source: the pre-feature unlimited behavior. name: "no_meta_no_header_gate_off", dirs: 1, }, { // Boundary lower edge: count < max passes. name: "boundary_count_below_max_passes", header: headerVal("2"), dirs: 1, }, { // The gate counts only directories: a stray file in the backups // dir must not push the count to the cap (with files counted, // 2 >= 2 would 403). name: "stray_file_not_counted_toward_cap", header: headerVal("2"), dirs: 1, files: 1, }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { a, _ := newTestAgent(t) const name = "alpha" serverDir := a.serverDir(name) writeSeedFile(t, filepath.Join(serverDir, "world.txt"), "seed", 0o644) if tc.meta != nil { if err := a.saveMeta(serverDir, tc.meta); err != nil { t.Fatalf("saveMeta: %v", err) } } backupsDir := seedCountGateBackups(t, a, name, tc.dirs, tc.files) rec := countGateDrive(t, a, name, tc.header) if rec.Code == http.StatusForbidden { t.Fatalf("count gate must NOT block this create: status %d body %s", rec.Code, rec.Body.String()) } if rec.Code != 200 { t.Fatalf("create status %d body %s, want 200 (gate passes, create completes)", rec.Code, rec.Body.String()) } var resp struct { Ok bool `json:"ok"` Backup BackupMeta `json:"backup"` } if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decode create response: %v body=%s", err, rec.Body.String()) } if !resp.Ok || resp.Backup.ID == "" { t.Fatalf("create envelope must confirm the backup: %s", rec.Body.String()) } entries, err := os.ReadDir(backupsDir) if err != nil { t.Fatalf("read backups dir: %v", err) } if len(entries) != tc.dirs+tc.files+1 { t.Fatalf("backups dir must hold the %d seeded entries + the new backup, got %d", tc.dirs+tc.files+1, len(entries)) } }) } }