diff --git a/README.md b/README.md index d09f4c2..d77f3a4 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ yetano.dev/yetano/core/configcmd yetano.dev/yetano/core/configfamily yetano.dev/yetano/core/version yetano.dev/yetano/core/secretref +yetano.dev/yetano/core/backup yetano.dev/yetano/core/cobracmd (separate module) yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z) @@ -486,6 +487,33 @@ plain values it accepted before checks `IsReference` and treats anything else as a literal. Used by yavebu, yacry and yadenes. +## core/backup: " backup" + +The archive behind ` backup create|list|verify|restore` (see +docs/program-conventions.md in the meta-repository). The program +chooses the content; `core/backup` writes, lists, rotates, verifies and +unpacks: + +```go +w, err := backup.Create(dir, "yanks-registry", version.Version) +w.AddFile("registry.db", snapshot) // a consistent copy, not the live file +w.AddDir("state", dataDir, skipBlobs) // regular files below a directory +w.AddFile("config/yanks-registry.yaml", cfgPath) +a, err := w.Close() // atomic: complete or nothing +removed, err := backup.Prune(dir, "yanks-registry", backup.DefaultKeep, nil) + +m, err := backup.Verify(path) // every file against MANIFEST.json +m, err := backup.Extract(path, newDir) // verified first; only below newDir +``` + +`-.tar.gz`, a gzip tar with `MANIFEST.json` last +(schema, program, version, time, each file's name, size, mode and +SHA-256). Archives and their directory are owner-only (0600/0700). +`Extract` never writes over anything and never outside its destination +(`..`, absolute names and links are rejected before a byte is written). +`Prune` keeps `Keep{Last, Daily, Weekly, Monthly}` (default 3/7/4/6); an +empty `Keep` removes nothing. + ## core/gui (separate module) `yetano.dev/yetano/core/gui` is the native WebView host for desktop diff --git a/TODO.md b/TODO.md index 6b166ee..aeddf92 100644 --- a/TODO.md +++ b/TODO.md @@ -36,6 +36,8 @@ speculatively. whose fields are alternatives (SecretRef `env`/`file`/`value`); `completion.Files` completes paths for programs without subcommands (yamc) -- 2026-10-31. +- [x] `backup` (v0.11.0): archive format, rotation, verify, safe + extract for the optional ` backup` command -- 2026-11-05. - [x] `doctor.Check` with optional `area` and `hint` (JSON and table, omitted when empty), `Report.Add` -- 2026-11-01, for v0.10.0. - [x] macOS CLI/Service system-scope `RuntimeDir` is `/var/run/` diff --git a/backup/backup.go b/backup/backup.go new file mode 100644 index 0000000..6e9e407 --- /dev/null +++ b/backup/backup.go @@ -0,0 +1,525 @@ +// Package backup is the archive format and handling behind the optional +// " backup create|list|verify|restore" commands of the Yetano +// program standard (docs/program-conventions.md in the yetano +// meta-repository). The program decides what goes in (a consistent +// database copy, its config, state files -- never what can be fetched +// again); this package writes, lists, rotates, checks and unpacks. +// +// w, err := backup.Create(dir, "yanks-registry", version.Version) +// w.AddFile("registry.db", snapshotPath) +// w.AddFile("config/yanks-registry.yaml", cfgPath) +// a, err := w.Close() // atomic: complete or nothing +// removed, err := backup.Prune(dir, "yanks-registry", backup.DefaultKeep, time.Now()) +// +// An archive is a gzip-compressed tar named +// "-.tar.gz": the files, then MANIFEST.json (program, +// version, time, and every file's name, size, mode and SHA-256). +// Archives and their directory are only readable by the owner -- they +// hold password hashes and keys as often as not. Extract verifies an +// archive completely before it writes anything, and only ever writes +// below its destination. +package backup + +import ( + "archive/tar" + "compress/gzip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "regexp" + "sort" + "strings" + "time" +) + +// Schema is the manifest version this package writes and reads. +const Schema = 1 + +// ManifestName is the archive's last entry. +const ManifestName = "MANIFEST.json" + +// timeLayout is the UTC time in archive names; it sorts as text. +const timeLayout = "20060102T150405Z" + +// Manifest describes an archive. +type Manifest struct { + Schema int `json:"schema"` + Program string `json:"program"` + Version string `json:"version,omitempty"` + CreatedAt time.Time `json:"created_at"` + Files []File `json:"files"` +} + +// File is one archived file. Name is slash-separated and relative. +type File struct { + Name string `json:"name"` + Size int64 `json:"size"` + Mode uint32 `json:"mode"` + SHA256 string `json:"sha256"` +} + +// Archive is a backup file in a directory. +type Archive struct { + Path string `json:"path"` + Program string `json:"program"` + CreatedAt time.Time `json:"created_at"` + Size int64 `json:"size"` +} + +// ErrInvalid: the archive is damaged, incomplete or not a backup. +var ErrInvalid = errors.New("backup: invalid archive") + +func invalid(format string, args ...any) error { + return fmt.Errorf("%w: %s", ErrInvalid, fmt.Sprintf(format, args...)) +} + +var ( + programRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`) + suffixRE = regexp.MustCompile(`^-[0-9]+$`) +) + +// Writer builds an archive in a temporary file next to its final name. +type Writer struct { + dir, program string + m Manifest + f *os.File + gz *gzip.Writer + tw *tar.Writer + names map[string]bool + err error +} + +// Create starts an archive of program in dir (created owner-only when +// missing). +func Create(dir, program, version string) (*Writer, error) { + if !programRE.MatchString(program) { + return nil, fmt.Errorf("backup: invalid program name %q", program) + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, fmt.Errorf("backup: %w", err) + } + f, err := os.CreateTemp(dir, "."+program+"-*.partial") + if err != nil { + return nil, fmt.Errorf("backup: %w", err) + } + if err := f.Chmod(0o600); err != nil { + f.Close() + os.Remove(f.Name()) + return nil, fmt.Errorf("backup: %w", err) + } + gz := gzip.NewWriter(f) + return &Writer{dir: dir, program: program, f: f, gz: gz, tw: tar.NewWriter(gz), names: map[string]bool{}, + m: Manifest{Schema: Schema, Program: program, Version: version, CreatedAt: time.Now().UTC().Truncate(time.Second), Files: []File{}}}, nil +} + +// validName: relative, slash-separated, clean, inside the archive. +func validName(name string) bool { + return name != "" && name != "." && name != ManifestName && !strings.HasPrefix(name, "/") && + !strings.Contains(name, `\`) && path.Clean(name) == name && name != ".." && !strings.HasPrefix(name, "../") +} + +func (w *Writer) add(name string, mode fs.FileMode, size int64, mtime time.Time, r io.Reader) error { + if w.err != nil { + return w.err + } + if !validName(name) { + return fmt.Errorf("backup: invalid name %q", name) + } + if w.names[name] { + return fmt.Errorf("backup: %s added twice", name) + } + w.names[name] = true + perm := uint32(mode.Perm()) + h := &tar.Header{Name: name, Mode: int64(perm), Size: size, ModTime: mtime, Typeflag: tar.TypeReg, Format: tar.FormatPAX} + if err := w.tw.WriteHeader(h); err != nil { + w.err = fmt.Errorf("backup: %s: %w", name, err) + return w.err + } + sum := sha256.New() + n, err := io.Copy(w.tw, io.TeeReader(r, sum)) + if err == nil && n != size { + err = fmt.Errorf("changed while it was read (%d of %d bytes)", n, size) + } + if err != nil { + w.err = fmt.Errorf("backup: %s: %w", name, err) + return w.err + } + w.m.Files = append(w.m.Files, File{Name: name, Size: size, Mode: perm, SHA256: hex.EncodeToString(sum.Sum(nil))}) + return nil +} + +// AddFile archives the regular file src as name. +func (w *Writer) AddFile(name, src string) error { + f, err := os.Open(src) + if err != nil { + return fmt.Errorf("backup: %w", err) + } + defer f.Close() + fi, err := f.Stat() + if err != nil { + return fmt.Errorf("backup: %w", err) + } + if !fi.Mode().IsRegular() { + return fmt.Errorf("backup: %s is not a regular file", src) + } + return w.add(name, fi.Mode(), fi.Size(), fi.ModTime(), f) +} + +// AddBytes archives data as name. +func (w *Writer) AddBytes(name string, data []byte, mode fs.FileMode) error { + return w.add(name, mode, int64(len(data)), w.m.CreatedAt, strings.NewReader(string(data))) +} + +// AddDir archives the regular files below src as prefix/, in a stable order. skip (may be nil) leaves out a file or, for +// a directory, everything below it; rel is slash-separated. Symbolic +// links and other special files are left out. +func (w *Writer) AddDir(prefix, src string, skip func(rel string, d fs.DirEntry) bool) error { + return filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return fmt.Errorf("backup: %w", err) + } + rel, err := filepath.Rel(src, p) + if err != nil { + return err + } + if rel == "." { + return nil + } + rel = filepath.ToSlash(rel) + if skip != nil && skip(rel, d) { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + if !d.Type().IsRegular() { + return nil + } + return w.AddFile(path.Join(prefix, rel), p) + }) +} + +// Close finishes the archive: the manifest, then an atomic rename to +// "-