package backup import ( "archive/tar" "compress/gzip" "errors" "io/fs" "os" "path/filepath" "runtime" "strings" "testing" "time" ) func write(t *testing.T, p, content string, mode fs.FileMode) { t.Helper() if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(p, []byte(content), mode); err != nil { t.Fatal(err) } } func makeArchive(t *testing.T, dir string) Archive { t.Helper() src := t.TempDir() write(t, filepath.Join(src, "db"), "database", 0o600) write(t, filepath.Join(src, "state", "users.json"), `{"u":1}`, 0o600) write(t, filepath.Join(src, "state", "repos", "a", "tags", "latest"), "sha256:x", 0o644) write(t, filepath.Join(src, "state", "blobs", "big"), "blob", 0o644) w, err := Create(dir, "prog", "1.2.3") if err != nil { t.Fatal(err) } if err := w.AddFile("db/registry.db", filepath.Join(src, "db")); err != nil { t.Fatal(err) } if err := w.AddDir("state", filepath.Join(src, "state"), func(rel string, d fs.DirEntry) bool { return rel == "blobs" }); err != nil { t.Fatal(err) } if err := w.AddBytes("config/prog.yaml", []byte("listen: x\n"), 0o640); err != nil { t.Fatal(err) } if err := w.AddFile("db/registry.db", filepath.Join(src, "db")); err == nil { t.Error("the same name added twice") } w.err = nil // the duplicate is the test's own doing a, err := w.Close() if err != nil { t.Fatal(err) } return a } func TestRoundTrip(t *testing.T) { dir := filepath.Join(t.TempDir(), "backups") a := makeArchive(t, dir) if !strings.HasPrefix(filepath.Base(a.Path), "prog-") || !strings.HasSuffix(a.Path, ".tar.gz") { t.Errorf("archive name %s", a.Path) } if runtime.GOOS != "windows" { for p, want := range map[string]fs.FileMode{dir: 0o700, a.Path: 0o600} { if fi, _ := os.Stat(p); fi.Mode().Perm() != want { t.Errorf("%s mode %v, want %v", p, fi.Mode().Perm(), want) } } } if left, _ := filepath.Glob(filepath.Join(dir, ".*partial")); len(left) != 0 { t.Errorf("temporary files left: %v", left) } m, err := Verify(a.Path) if err != nil { t.Fatal(err) } var names []string for _, f := range m.Files { names = append(names, f.Name) } if m.Program != "prog" || m.Version != "1.2.3" || strings.Join(names, ",") != "db/registry.db,state/repos/a/tags/latest,state/users.json,config/prog.yaml" { t.Errorf("manifest = %+v", m) } dest := filepath.Join(t.TempDir(), "restore") if _, err := Extract(a.Path, dest); err != nil { t.Fatal(err) } b, _ := os.ReadFile(filepath.Join(dest, "state", "users.json")) if string(b) != `{"u":1}` { t.Errorf("users.json = %q", b) } if _, err := os.Stat(filepath.Join(dest, "state", "blobs")); !errors.Is(err, os.ErrNotExist) { t.Error("a skipped directory was archived") } if runtime.GOOS != "windows" { if fi, _ := os.Stat(filepath.Join(dest, "config", "prog.yaml")); fi.Mode().Perm() != 0o640 { t.Errorf("restored mode %v", fi.Mode().Perm()) } } if _, err := Extract(a.Path, dest); err == nil { t.Error("extracted over an existing directory") } } func TestDamagedArchives(t *testing.T) { dir := t.TempDir() a := makeArchive(t, dir) raw, _ := os.ReadFile(a.Path) // Cut off: no manifest, or not even a complete gzip stream. cut := filepath.Join(dir, "cut.tar.gz") write(t, cut, string(raw[:len(raw)/2]), 0o600) if _, err := Verify(cut); !errors.Is(err, ErrInvalid) { t.Errorf("truncated archive: %v", err) } // A file whose content does not match the manifest. tampered := filepath.Join(dir, "tampered.tar.gz") writeTar(t, tampered, []entry{{"db/registry.db", "other!!!"}, {ManifestName, manifestFor(t, a.Path)}}) if _, err := Verify(tampered); !errors.Is(err, ErrInvalid) { t.Errorf("tampered archive: %v", err) } // Names that leave the destination are refused before anything is // written. for _, name := range []string{"../evil", "/etc/evil", "a/../../evil", `a\..\evil`} { evil := filepath.Join(dir, "evil.tar.gz") writeTar(t, evil, []entry{{name, "x"}, {ManifestName, `{"schema":1,"program":"prog","files":[]}`}}) dest := filepath.Join(t.TempDir(), "d") if _, err := Extract(evil, dest); !errors.Is(err, ErrInvalid) { t.Errorf("%q: %v", name, err) } if _, err := os.Stat(dest); !errors.Is(err, os.ErrNotExist) { t.Errorf("%q: destination created", name) } } } type entry struct{ name, content string } func writeTar(t *testing.T, p string, entries []entry) { t.Helper() f, err := os.Create(p) if err != nil { t.Fatal(err) } gz := gzip.NewWriter(f) tw := tar.NewWriter(gz) for _, e := range entries { tw.WriteHeader(&tar.Header{Name: e.name, Mode: 0o600, Size: int64(len(e.content)), Typeflag: tar.TypeReg}) tw.Write([]byte(e.content)) } tw.Close() gz.Close() f.Close() } // manifestFor is a manifest that lists only db/registry.db as in a. func manifestFor(t *testing.T, archive string) string { m, err := Verify(archive) if err != nil { t.Fatal(err) } return `{"schema":1,"program":"prog","files":[{"name":"db/registry.db","size":8,"mode":384,"sha256":"` + m.Files[0].SHA256 + `"}]}` } func TestListAndPrune(t *testing.T) { dir := t.TempDir() loc := time.UTC start := time.Date(2026, 1, 1, 3, 0, 0, 0, loc) // One archive a day for 200 days, two on the last day. for d := 0; d < 200; d++ { ts := start.AddDate(0, 0, d) write(t, filepath.Join(dir, "prog-"+ts.Format(timeLayout)+".tar.gz"), "x", 0o600) } last := start.AddDate(0, 0, 199) write(t, filepath.Join(dir, "prog-"+last.Format(timeLayout)+"-2.tar.gz"), "x", 0o600) write(t, filepath.Join(dir, "other-"+last.Format(timeLayout)+".tar.gz"), "x", 0o600) write(t, filepath.Join(dir, "prog-notatime.tar.gz"), "x", 0o600) all, err := List(dir, "prog") if err != nil { t.Fatal(err) } if len(all) != 201 || !strings.HasSuffix(all[0].Path, "-2.tar.gz") { t.Fatalf("list = %d, first %s", len(all), all[0].Path) } if none, _ := List(filepath.Join(dir, "missing"), "prog"); len(none) != 0 { t.Error("a missing directory lists archives") } if removed, _ := Prune(dir, "prog", Keep{}, loc); len(removed) != 0 { t.Error("an empty Keep removed archives") } removed, err := Prune(dir, "prog", Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}, loc) if err != nil { t.Fatal(err) } kept, _ := List(dir, "prog") if len(kept)+len(removed) != 201 { t.Fatalf("kept %d + removed %d", len(kept), len(removed)) } // 3 newest (2 of them on the last day) + 6 more days; weekly and // monthly add the older ones: at most 3+7+4+6, at least 7+6. if len(kept) < 13 || len(kept) > 20 { t.Errorf("kept %d archives", len(kept)) } months := map[string]bool{} for _, a := range kept { months[a.CreatedAt.Format("2006-01")] = true } if len(months) != 6 { t.Errorf("months kept: %v", months) } if _, err := os.Stat(filepath.Join(dir, "other-"+last.Format(timeLayout)+".tar.gz")); err != nil { t.Error("another program's archive was removed") } // Pruning again changes nothing. if again, _ := Prune(dir, "prog", Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}, loc); len(again) != 0 { t.Errorf("second prune removed %d", len(again)) } } func TestCreateRejectsBadInput(t *testing.T) { if _, err := Create(t.TempDir(), "../x", ""); err == nil { t.Error("program name with a path") } w, err := Create(t.TempDir(), "prog", "") if err != nil { t.Fatal(err) } defer w.Abort() for _, n := range []string{"", "/abs", "../up", "a/./b", ManifestName} { if err := w.AddBytes(n, nil, 0o600); err == nil { t.Errorf("name %q accepted", n) } } }