Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
764b6f36ea | ||
|
|
71b4dda990 | ||
|
|
3d286da90d |
No files matched your search
@@ -1,9 +1,15 @@
|
||||
Copyright (c) 2026 yetano. All rights reserved.
|
||||
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
|
||||
|
||||
core is proprietary software. No license is granted to use, copy,
|
||||
modify, merge, publish, distribute, sublicense or sell copies of it, in
|
||||
whole or in part, except with the prior written permission of the
|
||||
This software and its documentation are proprietary
|
||||
(SPDX: LicenseRef-Proprietary). No license to use, copy, modify, merge,
|
||||
publish, distribute, sublicense or sell copies of this software, in whole
|
||||
or in part, is granted without the prior written permission of the
|
||||
copyright holder.
|
||||
|
||||
The Yetano projects are closed source for now; until their license is
|
||||
decided, this notice applies.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
@@ -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)
|
||||
@@ -328,7 +329,11 @@ docs/program-conventions.md in the meta-repository):
|
||||
- `doctor.Report` collects the locations the program resolves
|
||||
(`AddPaths(app)` adds the standard `core/paths` ones) and named checks;
|
||||
`Run(args, stdout, stderr)` prints a table or `--json` and returns the
|
||||
exit code (0 all good, 1 a check failed, 2 usage).
|
||||
exit code (0 all good, 1 a check failed, 2 usage). A check may carry
|
||||
an `area` (a group such as "config" or "services") and a `hint` (what
|
||||
to do about it), recorded with `Add(doctor.Check{...})`; both are
|
||||
omitted from the JSON when empty, and the table only gets an AREA or
|
||||
HINT column when some check uses it (since v0.10.0).
|
||||
|
||||
## core/configcmd: "<program> config"
|
||||
|
||||
@@ -482,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: "<program> backup"
|
||||
|
||||
The archive behind `<program> 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
|
||||
```
|
||||
|
||||
`<program>-<UTC time>.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
|
||||
@@ -500,3 +532,7 @@ pitfalls and the yet-gui migration: [gui/README.md](gui/README.md).
|
||||
`slate`/`dialog`/`midnight` and their lipgloss styles, `Paint`/`Outer`,
|
||||
`ListState` and text helpers. No app shell or screens yet -- see
|
||||
[tui/README.md](tui/README.md), which also has the migration steps.
|
||||
|
||||
## License
|
||||
|
||||
Proprietary (`LicenseRef-Proprietary`), see [LICENSE](LICENSE).
|
||||
@@ -36,6 +36,10 @@ 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 `<program> 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/<app>`
|
||||
(was `/run/<app>`, which macOS does not have) -- v0.5.0.
|
||||
- [x] `core/gui`: the native WebView host from
|
||||
|
||||
@@ -0,0 +1,525 @@
|
||||
// Package backup is the archive format and handling behind the optional
|
||||
// "<program> 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
|
||||
// "<program>-<UTC time>.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/<relative
|
||||
// path>, 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
|
||||
// "<program>-<time>.tar.gz". After an error the archive is removed.
|
||||
func (w *Writer) Close() (Archive, error) {
|
||||
if w.err != nil {
|
||||
w.Abort()
|
||||
return Archive{}, w.err
|
||||
}
|
||||
b, err := json.MarshalIndent(w.m, "", " ")
|
||||
if err == nil {
|
||||
err = w.tw.WriteHeader(&tar.Header{Name: ManifestName, Mode: 0o600, Size: int64(len(b)), ModTime: w.m.CreatedAt,
|
||||
Typeflag: tar.TypeReg, Format: tar.FormatPAX})
|
||||
}
|
||||
if err == nil {
|
||||
_, err = w.tw.Write(b)
|
||||
}
|
||||
if err == nil {
|
||||
err = w.tw.Close()
|
||||
}
|
||||
if err == nil {
|
||||
err = w.gz.Close()
|
||||
}
|
||||
if err == nil {
|
||||
err = w.f.Sync()
|
||||
}
|
||||
if cerr := w.f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(w.f.Name())
|
||||
return Archive{}, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
final, err := freeName(w.dir, w.program, w.m.CreatedAt)
|
||||
if err == nil {
|
||||
err = os.Rename(w.f.Name(), final)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(w.f.Name())
|
||||
return Archive{}, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
fi, err := os.Stat(final)
|
||||
if err != nil {
|
||||
return Archive{}, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
return Archive{Path: final, Program: w.program, CreatedAt: w.m.CreatedAt, Size: fi.Size()}, nil
|
||||
}
|
||||
|
||||
// Abort drops an unfinished archive.
|
||||
func (w *Writer) Abort() {
|
||||
w.f.Close()
|
||||
os.Remove(w.f.Name())
|
||||
}
|
||||
|
||||
func freeName(dir, program string, t time.Time) (string, error) {
|
||||
base := program + "-" + t.UTC().Format(timeLayout)
|
||||
for i := 1; i < 100; i++ {
|
||||
name := base + ".tar.gz"
|
||||
if i > 1 {
|
||||
name = fmt.Sprintf("%s-%d.tar.gz", base, i)
|
||||
}
|
||||
p := filepath.Join(dir, name)
|
||||
if _, err := os.Lstat(p); errors.Is(err, os.ErrNotExist) {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no free archive name for %s", base)
|
||||
}
|
||||
|
||||
// parseName reads the time and the sequence number (1, or n of "-n")
|
||||
// from an archive's file name.
|
||||
func parseName(name, program string) (time.Time, int, bool) {
|
||||
rest, ok := strings.CutPrefix(name, program+"-")
|
||||
if !ok {
|
||||
return time.Time{}, 0, false
|
||||
}
|
||||
rest, ok = strings.CutSuffix(rest, ".tar.gz")
|
||||
if !ok || len(rest) < len(timeLayout) {
|
||||
return time.Time{}, 0, false
|
||||
}
|
||||
stamp, suffix := rest[:len(timeLayout)], rest[len(timeLayout):]
|
||||
seq := 1
|
||||
if suffix != "" {
|
||||
if !suffixRE.MatchString(suffix) {
|
||||
return time.Time{}, 0, false
|
||||
}
|
||||
fmt.Sscanf(suffix[1:], "%d", &seq)
|
||||
}
|
||||
t, err := time.Parse(timeLayout, stamp)
|
||||
return t, seq, err == nil
|
||||
}
|
||||
|
||||
// List returns program's archives in dir, newest first. A missing dir
|
||||
// is no archive.
|
||||
func List(dir, program string) ([]Archive, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return []Archive{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
out := []Archive{}
|
||||
seq := map[string]int{}
|
||||
for _, e := range entries {
|
||||
t, n, ok := parseName(e.Name(), program)
|
||||
if !ok || !e.Type().IsRegular() {
|
||||
continue
|
||||
}
|
||||
fi, err := e.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
p := filepath.Join(dir, e.Name())
|
||||
seq[p] = n
|
||||
out = append(out, Archive{Path: p, Program: program, CreatedAt: t, Size: fi.Size()})
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool {
|
||||
if !out[i].CreatedAt.Equal(out[j].CreatedAt) {
|
||||
return out[i].CreatedAt.After(out[j].CreatedAt)
|
||||
}
|
||||
return seq[out[i].Path] > seq[out[j].Path]
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Keep says which archives Prune keeps: the Last newest, and the newest
|
||||
// of each of the last Daily days, Weekly ISO weeks and Monthly months
|
||||
// that have one (local time).
|
||||
type Keep struct {
|
||||
Last int `json:"last" yaml:"last"`
|
||||
Daily int `json:"daily" yaml:"daily"`
|
||||
Weekly int `json:"weekly" yaml:"weekly"`
|
||||
Monthly int `json:"monthly" yaml:"monthly"`
|
||||
}
|
||||
|
||||
// DefaultKeep: the 3 newest, a week of days, a month of weeks, half a
|
||||
// year of months.
|
||||
var DefaultKeep = Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}
|
||||
|
||||
// Prune removes program's archives in dir that keep does not hold and
|
||||
// returns them. A Keep of all zeros removes nothing (a misconfiguration
|
||||
// must not delete every backup).
|
||||
func Prune(dir, program string, keep Keep, loc *time.Location) ([]Archive, error) {
|
||||
if keep == (Keep{}) {
|
||||
return []Archive{}, nil
|
||||
}
|
||||
if loc == nil {
|
||||
loc = time.Local
|
||||
}
|
||||
all, err := List(dir, program)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kept := map[string]bool{}
|
||||
for i := 0; i < keep.Last && i < len(all); i++ {
|
||||
kept[all[i].Path] = true
|
||||
}
|
||||
bucket := func(n int, key func(time.Time) string) {
|
||||
seen := map[string]bool{}
|
||||
for _, a := range all { // newest first: the first of a bucket is its newest
|
||||
k := key(a.CreatedAt.In(loc))
|
||||
if seen[k] {
|
||||
continue
|
||||
}
|
||||
if len(seen) == n {
|
||||
return
|
||||
}
|
||||
seen[k] = true
|
||||
kept[a.Path] = true
|
||||
}
|
||||
}
|
||||
bucket(keep.Daily, func(t time.Time) string { return t.Format("2006-01-02") })
|
||||
bucket(keep.Weekly, func(t time.Time) string { y, w := t.ISOWeek(); return fmt.Sprintf("%d-%02d", y, w) })
|
||||
bucket(keep.Monthly, func(t time.Time) string { return t.Format("2006-01") })
|
||||
removed := []Archive{}
|
||||
for _, a := range all {
|
||||
if kept[a.Path] {
|
||||
continue
|
||||
}
|
||||
if err := os.Remove(a.Path); err != nil {
|
||||
return removed, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
removed = append(removed, a)
|
||||
}
|
||||
return removed, nil
|
||||
}
|
||||
|
||||
// walk reads an archive, calling fn for every file entry with its
|
||||
// content; it returns the manifest after checking that it lists exactly
|
||||
// the files read, with their sizes and checksums.
|
||||
func walk(archive string, fn func(h *tar.Header, r io.Reader) error) (Manifest, error) {
|
||||
var m Manifest
|
||||
f, err := os.Open(archive)
|
||||
if err != nil {
|
||||
return m, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
gz, err := gzip.NewReader(f)
|
||||
if err != nil {
|
||||
return m, invalid("%s: %v", filepath.Base(archive), err)
|
||||
}
|
||||
tr := tar.NewReader(gz)
|
||||
got := map[string]File{}
|
||||
haveManifest := false
|
||||
for {
|
||||
h, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return m, invalid("%s: %v", filepath.Base(archive), err)
|
||||
}
|
||||
if haveManifest {
|
||||
return m, invalid("an entry after the manifest: %q", h.Name)
|
||||
}
|
||||
if h.Name == ManifestName {
|
||||
b, err := io.ReadAll(io.LimitReader(tr, 64<<20))
|
||||
if err != nil {
|
||||
return m, invalid("manifest: %v", err)
|
||||
}
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
return m, invalid("manifest: %v", err)
|
||||
}
|
||||
haveManifest = true
|
||||
continue
|
||||
}
|
||||
if h.Typeflag != tar.TypeReg || !validName(h.Name) {
|
||||
return m, invalid("unexpected entry %q", h.Name)
|
||||
}
|
||||
if _, dup := got[h.Name]; dup {
|
||||
return m, invalid("%q twice", h.Name)
|
||||
}
|
||||
sum := sha256.New()
|
||||
r := io.TeeReader(tr, sum)
|
||||
if fn != nil {
|
||||
if err := fn(h, r); err != nil {
|
||||
return m, err
|
||||
}
|
||||
}
|
||||
if _, err := io.Copy(io.Discard, r); err != nil { // what fn did not read
|
||||
return m, invalid("%s: %v", h.Name, err)
|
||||
}
|
||||
got[h.Name] = File{Name: h.Name, Size: h.Size, SHA256: hex.EncodeToString(sum.Sum(nil))}
|
||||
}
|
||||
if !haveManifest {
|
||||
return m, invalid("no manifest: the archive is incomplete")
|
||||
}
|
||||
if m.Schema != Schema {
|
||||
return m, invalid("manifest schema %d, this program reads %d", m.Schema, Schema)
|
||||
}
|
||||
if len(m.Files) != len(got) {
|
||||
return m, invalid("the manifest lists %d files, the archive holds %d", len(m.Files), len(got))
|
||||
}
|
||||
for _, mf := range m.Files {
|
||||
g, ok := got[mf.Name]
|
||||
if !ok {
|
||||
return m, invalid("%s is missing", mf.Name)
|
||||
}
|
||||
if g.Size != mf.Size || g.SHA256 != mf.SHA256 {
|
||||
return m, invalid("%s does not match its checksum", mf.Name)
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Verify reads an archive completely and checks every file against the
|
||||
// manifest.
|
||||
func Verify(archive string) (Manifest, error) {
|
||||
return walk(archive, nil)
|
||||
}
|
||||
|
||||
// Extract verifies the archive, then unpacks it into dest, which must
|
||||
// not exist yet (its parent must): nothing is ever written over, and
|
||||
// nothing outside dest. On an error dest is removed again.
|
||||
func Extract(archive, dest string) (Manifest, error) {
|
||||
if _, err := Verify(archive); err != nil {
|
||||
return Manifest{}, err
|
||||
}
|
||||
if _, err := os.Lstat(dest); err == nil {
|
||||
return Manifest{}, fmt.Errorf("backup: %s exists; extract into a new directory", dest)
|
||||
}
|
||||
if err := os.Mkdir(dest, 0o700); err != nil {
|
||||
return Manifest{}, fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
m, err := walk(archive, func(h *tar.Header, r io.Reader) error {
|
||||
target := filepath.Join(dest, filepath.FromSlash(h.Name))
|
||||
if rel, err := filepath.Rel(dest, target); err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
||||
return invalid("%q leaves the destination", h.Name)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
|
||||
return fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
f, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, fs.FileMode(h.Mode).Perm()|0o200)
|
||||
if err != nil {
|
||||
return fmt.Errorf("backup: %w", err)
|
||||
}
|
||||
_, err = io.Copy(f, r)
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Chmod(target, fs.FileMode(h.Mode).Perm())
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Chtimes(target, h.ModTime, h.ModTime)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("backup: %s: %w", h.Name, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
os.RemoveAll(dest)
|
||||
return Manifest{}, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+31
-3
@@ -36,11 +36,16 @@ type Path struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Check is one named check.
|
||||
// Check is one named check. Area (a group such as "config" or
|
||||
// "services") and Hint (what to do about a failed check) are optional
|
||||
// and omitted from the JSON form when empty, so a report without them
|
||||
// looks exactly as before they existed.
|
||||
type Check struct {
|
||||
Area string `json:"area,omitempty"`
|
||||
Name string `json:"name"`
|
||||
OK bool `json:"ok"`
|
||||
Note string `json:"note,omitempty"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
}
|
||||
|
||||
// Report is "<program> doctor --json"'s output.
|
||||
@@ -110,6 +115,12 @@ func (r *Report) Check(name string, ok bool, note string) {
|
||||
r.Checks = append(r.Checks, Check{Name: name, OK: ok, Note: note})
|
||||
}
|
||||
|
||||
// Add records a check with all its fields, for a program that groups its
|
||||
// checks into areas or gives hints.
|
||||
func (r *Report) Add(c Check) {
|
||||
r.Checks = append(r.Checks, c)
|
||||
}
|
||||
|
||||
// Problems counts failed checks.
|
||||
func (r Report) Problems() int {
|
||||
n := 0
|
||||
@@ -148,9 +159,26 @@ func (r Report) Write(w io.Writer, asJSON bool) error {
|
||||
}
|
||||
fmt.Fprintln(tw)
|
||||
}
|
||||
fmt.Fprintf(tw, "CHECK\tOK\tNOTE\n")
|
||||
// The AREA and HINT columns only appear when some check uses them,
|
||||
// so the table of a program without them is unchanged.
|
||||
withArea, withHint := false, false
|
||||
for _, c := range r.Checks {
|
||||
fmt.Fprintf(tw, "%s\t%s\t%s\n", c.Name, yesNo(c.OK), c.Note)
|
||||
withArea = withArea || c.Area != ""
|
||||
withHint = withHint || c.Hint != ""
|
||||
}
|
||||
row := func(area, name, ok, note, hint string) {
|
||||
cols := []string{name, ok, note}
|
||||
if withArea {
|
||||
cols = append([]string{area}, cols...)
|
||||
}
|
||||
if withHint {
|
||||
cols = append(cols, hint)
|
||||
}
|
||||
fmt.Fprintln(tw, strings.Join(cols, "\t"))
|
||||
}
|
||||
row("AREA", "CHECK", "OK", "NOTE", "HINT")
|
||||
for _, c := range r.Checks {
|
||||
row(c.Area, c.Name, yesNo(c.OK), c.Note, c.Hint)
|
||||
}
|
||||
return tw.Flush()
|
||||
}
|
||||
|
||||
@@ -49,3 +49,37 @@ func TestAddPaths(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAreaAndHint(t *testing.T) {
|
||||
// Without area/hint neither the JSON nor the table mentions them.
|
||||
plain := Report{Program: "tool"}
|
||||
plain.Check("config valid", true, "")
|
||||
var out strings.Builder
|
||||
if err := plain.Write(&out, true); err != nil || strings.Contains(out.String(), "area") || strings.Contains(out.String(), "hint") {
|
||||
t.Fatalf("plain json: %v %s", err, out.String())
|
||||
}
|
||||
out.Reset()
|
||||
if err := plain.Write(&out, false); err != nil || strings.Contains(out.String(), "AREA") || strings.Contains(out.String(), "HINT") {
|
||||
t.Fatalf("plain table: %v %s", err, out.String())
|
||||
}
|
||||
|
||||
r := Report{Program: "tool"}
|
||||
r.Add(Check{Area: "config", Name: "config loads", OK: false, Note: "line 3", Hint: "run tool config validate"})
|
||||
r.Check("other", true, "")
|
||||
out.Reset()
|
||||
if err := r.Write(&out, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got Report
|
||||
if err := json.Unmarshal([]byte(out.String()), &got); err != nil || got.Checks[0].Area != "config" || got.Checks[0].Hint != "run tool config validate" || got.Checks[1].Area != "" {
|
||||
t.Fatalf("json: %v %+v", err, got)
|
||||
}
|
||||
out.Reset()
|
||||
if err := r.Write(&out, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lines := strings.Split(out.String(), "\n")
|
||||
if !strings.HasPrefix(lines[0], "AREA") || !strings.Contains(lines[0], "HINT") || !strings.HasPrefix(lines[1], "config") || !strings.Contains(lines[1], "run tool config validate") {
|
||||
t.Fatalf("table:\n%s", out.String())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user