diff --git a/.dockerignore b/.dockerignore index fc84c76..6b49f01 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,10 +1,79 @@ -.git -.gitea -*.md -LICENSE -vaultik -dist -.tool -coverage.out -coverage.html -.DS_Store +# .dockerignore does NOT use .gitignore semantics. Docker matches with +# moby/patternmatcher: filepath.Match plus `**`, so `*` does not cross +# `/` and an unprefixed pattern is anchored at the context root. Every +# depth-independent pattern therefore needs `**/`, or `config/.env` and +# `certs/server.key` still ship while this file reads as solved. Only +# genuinely root-anchored entries go unprefixed. Never transplant these +# into .gitignore, where `**/` is wrong. +# +# Matching is case-sensitive, so secrets use character ranges rather +# than an ALL-CAPS twin, which would still miss `Server.Key`. +# +# Extend with this repo's own host-built artifacts, written anchored: +# `/myapp`, never `**/myapp`, which also matches `cmd/myapp/` and +# deletes the package directory from the context. + +# .git is sent without its config. Without a VERSION build argument the +# stage that compiles runs `git describe --tags --always` on .git, which +# does not need .git/config; that file can hold a credential, such as a +# password in a remote URL or the token the CI checkout step stores there. +# Each submodule keeps a config with the same exposure in its git directory +# under .git/modules/, nested again for a submodule's own submodules, or in +# its own .git directory when it keeps one. +# KNOWN GAP: a submodule whose name has a `config` segment (`config`, +# `deploy/config`, `config/lib`) loses its whole git directory, because +# `**/.git/modules/**/config` also matches that segment's directory +# under .git/modules/. Go's version stamping then fails the build; +# nothing leaks. Name such a submodule without that segment: +# `git submodule add --name`. +**/.git/config +**/.git/modules/**/config + +# Agent scratch: one full checkout of the repo per in-flight agent. +# Anchored because it occurs once where agents run at the repo root. +# KNOWN GAP: a repo running agents in subdirectories still ships +# `services/api/.claude/` and must add its own anchored entry. +.claude + +# Environment files. `*.env` covers bare `.env` and the `prod.env` +# convention. Re-include a committed template with a negation if the +# build needs one: `!docs/example.env`. +**/*.[eE][nN][vV] +**/.[eE][nN][vV].* +**/.[eE][nN][vV][rR][cC] + +# Private keys and the bundles carrying them. Public certificates +# (*.crt, *.cer) are deliberately absent: they are legitimate inputs. +**/*.[pP][eE][mM] +**/*.[kK][eE][yY] +**/*.[pP]12 +**/*.[pP][fF][xX] +**/[iI][dD]_[rR][sS][aA] +**/[iI][dD]_[dD][sS][aA] +**/[iI][dD]_[eE][cC][dD][sS][aA] +**/[iI][dD]_[eE][cC][dD][sS][aA]_[sS][kK] +**/[iI][dD]_[eE][dD]25519 +**/[iI][dD]_[eE][dD]25519_[sS][kK] + +# Dependencies: restored inside the image, never copied in. +**/node_modules + +# OS metadata. +**/.DS_Store +**/Thumbs.db + +# Editor state: never a build input, and it churns COPY. +**/*.swp +**/*.swo +**/*~ +**/*.bak +**/.idea +**/.vscode +**/*.sublime-* + +# This repo's own host-built artifacts. +/vaultik +/dist +/.tool +/coverage.out +/coverage.html diff --git a/.editorconfig b/.editorconfig index 2fe0ce0..92ec261 100644 --- a/.editorconfig +++ b/.editorconfig @@ -10,3 +10,6 @@ insert_final_newline = true [Makefile] indent_style = tab + +[*.go] +indent_style = tab diff --git a/.gitea/workflows/check.yml b/.gitea/workflows/check.yml index b4e58dc..ee73864 100644 --- a/.gitea/workflows/check.yml +++ b/.gitea/workflows/check.yml @@ -1,14 +1,9 @@ name: check -on: - push: - branches: [main, next] - pull_request: - branches: [main, next] +on: [push] jobs: - check: - runs-on: ubuntu-latest - steps: - # actions/checkout v4, 2024-09-16 - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - - name: Build and check - run: script/cibuild + check: + runs-on: ubuntu-latest + steps: + # actions/checkout v4.2.2, 2026-02-22 + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - run: script/cibuild diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index b083588..9d30f41 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -16,11 +16,12 @@ jobs: fetch-depth: 0 # goreleaser is not a compiler: it shells out to `go` for the # `before:` hook and for every one of the four cross-compiles. - # Nothing else in this repo puts a Go toolchain on the runner -- - # check.yml runs script/cibuild, which does all of its work inside - # the digest-pinned Dockerfile images -- so without this step the - # release either fails at the before-hook or, worse, ships binaries - # built by whatever Go the runner happens to carry. + # Without this step the release either fails at the before-hook or, + # worse, ships binaries built by whatever Go the runner happens to + # carry. check.yml's runner gets the same Go through + # script/bootstrap, which calls script/install-go, and uses it only + # for `go mod download` and gofmt; it compiles inside the + # digest-pinned Dockerfile images. # # actions/setup-go would pin the action by commit sha, but the Go # tarball it downloads at runtime is verified against no value in diff --git a/.gitignore b/.gitignore index df0dea6..fe7bf4a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,28 +1,62 @@ -# Binary -/vaultik - -# goreleaser output -/dist/ - -# Locally installed pinned tools (script/install-goreleaser) -/.tool/ - -# Test artifacts -*.out -*.test -coverage.html -coverage.out - -# IDE -.vscode/ -.idea/ -*.swp -*.swo - # OS .DS_Store Thumbs.db -# Local config for development +# Editors +*.swp +*.swo +*~ +*.bak +.idea/ +.vscode/ +*.sublime-* + +# Agent scratch (worktrees of this repo, created and destroyed by +# in-flight tooling). Unanchored: .gitignore patterns already match at +# every depth, so no prefix is wanted here. This is not a .dockerignore +# entry and must not be given a `**/` prefix on the way into one. +.claude/ + +# Node +node_modules/ + +# Secrets. Unanchored like every entry above, so each matches at every +# depth. Matching is case-sensitive on Linux, so names use character +# ranges rather than a lowercase form that misses `Server.Key`. + +# Environment files. `*.env` covers bare `.env` and the `prod.env` +# convention. Only the templates `example.env` and `sample.env` are +# re-included below. A repository that commits any other template adds +# its own negation after these lines, for example `!.env.example`. +*.[eE][nN][vV] +.[eE][nN][vV].* +.[eE][nN][vV][rR][cC] +!example.env +!sample.env + +# Private keys and the bundles carrying them. +*.[pP][eE][mM] +*.[kK][eE][yY] +*.[pP]12 +*.[pP][fF][xX] +[iI][dD]_[rR][sS][aA] +[iI][dD]_[dD][sS][aA] +[iI][dD]_[eE][cC][dD][sS][aA] +[iI][dD]_[eE][cC][dD][sS][aA]_[sS][kK] +[iI][dD]_[eE][dD]25519 +[iI][dD]_[eE][dD]25519_[sS][kK] + +# Go build and test output. +*.log +*.out +*.test +coverage.html + +# This repo's own host-built artifacts. +/vaultik +/dist/ +/.tool/ + +# Local configs for development; they hold storage credentials. local-config.yaml -dev-config.yaml \ No newline at end of file +dev-config.yaml diff --git a/.golangci.yml b/.golangci.yml index 26b1610..39d54d2 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -10,14 +10,21 @@ run: linters: default: all + enable: + # Successor to the deprecated gomodguard. Named explicitly, rather than + # left to `default: all`, because it carries the module policy below. + - gomodguard_v2 disable: # Genuinely incompatible with project patterns - exhaustruct # Requires all struct fields - - depguard # Dependency allow/block lists + - exhaustruct_v5 # Requires all struct fields (successor to exhaustruct) - godot # Requires comments to end with periods - - wsl # Deprecated, replaced by wsl_v5 - wrapcheck # Too verbose for internal packages - varnamelen # Short names like db, id are idiomatic Go + # Deprecated: the warning is attached to the old name, so it is + # silenced by disabling that name, not by enabling the successor. + - wsl # Deprecated, replaced by wsl_v5 + - gomodguard # Deprecated, replaced by gomodguard_v2 settings: lll: line-length: 88 @@ -28,6 +35,68 @@ linters: max-complexity: 15 dupl: threshold: 100 + depguard: + # Test-support code must not be compiled into the shipped binary. A + # test-support package exists to hand a test privileges the program + # itself must never have, so a file that is not a test must not import + # one. Test files, and the files inside a package whose directory name + # ends in `test`, are where that code belongs, and are exempt. + # + # The deny list below is the one part of this file a repository is + # expected to extend, and the only part it may. depguard matches an + # import path against a list of prefixes, so it cannot be told "any path + # whose last segment ends in test"; a repository's own test-support + # packages have to be named here one at a time, by full import path, + # under a module path that differs from repository to repository. Add + # them; change nothing else. + rules: + test-support: + list-mode: lax + files: + - "$all" + - "!$test" + - "!**/*test/**" + deny: + - pkg: net/http/httptest + desc: >- + Test-support code belongs in test files and in packages whose + directory name ends in test, not in the shipped binary. + - pkg: sneak.berlin/go/vaultik/internal/storage/faultstore + desc: >- + Test-support code belongs in test files and in packages whose + directory name ends in test, not in the shipped binary. + # Only decisions already recorded in the Go package defaults are + # listed here. Every entry matches the module path exactly. + gomodguard_v2: + blocked: + - module: github.com/rs/zerolog + recommendations: + - log/slog + reason: "Structured logging is stdlib log/slog." + # One entry per pre-fork module path, because the later releases + # are separate paths. A prefix match would be shorter but would + # also reach github.com/go-redis/redismock, the test double for + # the successor these entries recommend. + - module: github.com/go-redis/redis + recommendations: + - github.com/redis/go-redis/v9 + reason: "Pre-fork module; use the maintained go-redis v9." + - module: github.com/go-redis/redis/v7 + recommendations: + - github.com/redis/go-redis/v9 + reason: "Pre-fork module; use the maintained go-redis v9." + - module: github.com/go-redis/redis/v8 + recommendations: + - github.com/redis/go-redis/v9 + reason: "Pre-fork module; use the maintained go-redis v9." + - module: github.com/sergi/go-diff + recommendations: + - github.com/aymanbagabas/go-udiff + reason: "No unified diff output; use go-udiff." + - module: github.com/hexops/gotextdiff + recommendations: + - github.com/aymanbagabas/go-udiff + reason: "Unmaintained fork; use go-udiff." issues: max-issues-per-linter: 0 diff --git a/.goreleaser.yaml b/.goreleaser.yaml index d316d84..7f168b9 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -47,9 +47,7 @@ checksum: # A snapshot is not a release and must not name itself like one. The # previous `{{ incpatch .Version }}-next` derived a plausible-looking # release number from the last tag -- and with no tags in the repo at -# all, from goreleaser's fabricated v0.0.0. This produces the same -# string script/version produces for an untagged build, so a snapshot -# binary and a `make vaultik` binary of the same clean commit agree. +# all, from goreleaser's fabricated v0.0.0. snapshot: version_template: "dev-{{ slice .FullCommit 0 12 }}" diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..23d67fc --- /dev/null +++ b/.prettierignore @@ -0,0 +1,2 @@ +node_modules/ +yarn.lock diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..8af31cd --- /dev/null +++ b/.prettierrc @@ -0,0 +1,4 @@ +{ + "tabWidth": 4, + "proseWrap": "always" +} diff --git a/AGENTS.md b/AGENTS.md index 66b9c69..2d82840 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,112 +4,122 @@ Version: 2025-06-08 # Instructions and Contextual Information -* Be direct, robotic, expert, accurate, and professional. +- Be direct, robotic, expert, accurate, and professional. -* Do not butter me up or kiss my ass. +- Do not butter me up or kiss my ass. -* Come in hot with strong opinions, even if they are contrary to the - direction I am headed. +- Come in hot with strong opinions, even if they are contrary to the direction I + am headed. -* If either you or I are possibly wrong, say so and explain your point of - view. +- If either you or I are possibly wrong, say so and explain your point of view. -* Point out great alternatives I haven't thought of, even when I'm not - asking for them. +- Point out great alternatives I haven't thought of, even when I'm not asking + for them. -* Treat me like the world's leading expert in every situation and every +- Treat me like the world's leading expert in every situation and every conversation, and deliver the absolute best recommendations. -* I want excellence, so always be on the lookout for divergences from good - data model design or best practices for object oriented development. +- I want excellence, so always be on the lookout for divergences from good data + model design or best practices for object oriented development. -* IMPORTANT: This is production code, not a research or teaching exercise. +- IMPORTANT: This is production code, not a research or teaching exercise. Deliver professional-level results, not prototypes. -* Please read and understand the `README.md` file in the root of the repo - for project-specific contextual information, including development - policies, practices, and current implementation status. +- Please read and understand the `README.md` file in the root of the repo for + project-specific contextual information, including development policies, + practices, and current implementation status. -* Be proactive in suggesting improvements or refactorings in places where we +- Be proactive in suggesting improvements or refactorings in places where we diverge from best practices for clean, modular, maintainable code. # Policies 1. Before committing, tests must pass (`make test`), linting must pass - (`make lint`), and code must be formatted (`make fmt`). For go, those + (`make lint`), and code must be formatted (`make fmt`). For go, those makefile targets should use `go fmt` and `go test -v ./...` and - `golangci-lint run`. Each Makefile target does exactly one thing — to - run lint + fmt-check + test together (the standard pre-commit gate), - use `make check`. + `golangci-lint run`. Each Makefile target does exactly one thing — to run + lint + fmt-check + test together (the standard pre-commit gate), use + `make check`. -2. Always write a `Makefile` with the default target being `test`, and with - a `fmt` target that formats the code. The `test` target should run all - tests in the project, and the `fmt` target should format the code. - `test` should also have a prerequisite target `lint` that should run any - linters that are configured for the project. +2. Always write a `Makefile` with the default target being `test`, and with a + `fmt` target that formats the code. The `test` target should run all tests in + the project, and the `fmt` target should format the code. `test` should also + have a prerequisite target `lint` that should run any linters that are + configured for the project. -3. After each completed bugfix or feature, the code must be committed. Do - all of the pre-commit checks (test, lint, fmt) before committing, of - course. +3. After each completed bugfix or feature, the code must be committed. Do all of + the pre-commit checks (test, lint, fmt) before committing, of course. 4. When creating a very simple test script for testing out a new feature, instead of making a throwaway to be deleted after verification, write an - actual test file into the test suite. It doesn't need to be very big or + actual test file into the test suite. It doesn't need to be very big or complex, but it should be a real test that can be run. 5. When you are instructed to make the tests pass, DO NOT delete tests, skip - tests, or change the tests specifically to make them pass (unless there - is a bug in the test). This is cheating, and it is bad. You should only - be modifying the test if it is incorrect or if the test is no longer - relevant. In almost all cases, you should be fixing the code that is - being tested, or updating the tests to match a refactored implementation. + tests, or change the tests specifically to make them pass (unless there is a + bug in the test). This is cheating, and it is bad. You should only be + modifying the test if it is incorrect or if the test is no longer relevant. + In almost all cases, you should be fixing the code that is being tested, or + updating the tests to match a refactored implementation. 6. When dealing with dates and times or timestamps, always use, display, and - store UTC. Set the local timezone to UTC on startup. If the user needs - to see the time in a different timezone, store the user's timezone in a - separate field and convert the UTC time to the user's timezone when - displaying it. For internal use and internal applications and - administrative purposes, always display UTC. + store UTC. Set the local timezone to UTC on startup. If the user needs to see + the time in a different timezone, store the user's timezone in a separate + field and convert the UTC time to the user's timezone when displaying it. For + internal use and internal applications and administrative purposes, always + display UTC. 7. Always write tests, even if they are extremely simple and just check for - correct syntax (ability to compile/import). If you are writing a new - feature, write a test for it. You don't need to target complete - coverage, but you should at least test any new functionality you add. If - you are fixing a bug, write a test first that reproduces the bug, and - then fix the bug in the code. + correct syntax (ability to compile/import). If you are writing a new feature, + write a test for it. You don't need to target complete coverage, but you + should at least test any new functionality you add. If you are fixing a bug, + write a test first that reproduces the bug, and then fix the bug in the code. -8. When implementing new features, be aware of potential side-effects (such - as state files on disk, data in the database, etc.) and ensure that it is +8. When implementing new features, be aware of potential side-effects (such as + state files on disk, data in the database, etc.) and ensure that it is possible to mock or stub these side-effects in tests. -9. Always use structured logging. Log any relevant state/context with the - messages (but do not log secrets). If the log stream is not a terminal, +9. Always use structured logging. Log any relevant state/context with the + messages (but do not log secrets). If the log stream is not a terminal, output the structured logs in jsonl format. 10. Avoid using bare strings or numbers in code, especially if they appear - anywhere more than once. Always define a constant (usually at the top - of the file) and give it a descriptive name, then use that constant in - the code instead of the bare string or number. + anywhere more than once. Always define a constant (usually at the top of the + file) and give it a descriptive name, then use that constant in the code + instead of the bare string or number. 11. You do not need to summarize your changes in the chat after making them. - Making the changes and committing them is sufficient. If anything out - of the ordinary happened, please explain it, but in the normal case - where you found and fixed the bug, or implemented the feature, there is - no need for the end-of-change summary. + Making the changes and committing them is sufficient. If anything out of the + ordinary happened, please explain it, but in the normal case where you found + and fixed the bug, or implemented the feature, there is no need for the + end-of-change summary. -12. Do not create additional files in the root directory of the project - without asking permission first. Configuration files, documentation, and - build files are acceptable in the root, but source code and other files - should be organized in appropriate subdirectories. +12. Do not create additional files in the root directory of the project without + asking permission first. Configuration files, documentation, and build files + are acceptable in the root, but source code and other files should be + organized in appropriate subdirectories. -13. Pre-1.0: NEVER write database migrations. There are no live databases - anywhere — every user's local index can be rebuilt from a fresh full - backup. To change the schema, edit `internal/database/schema/001.sql` - (and any code that touches the affected tables) directly; do not add new - numbered schema files. Those numbered files and the `schema_migrations` - table they populate only bootstrap a fresh database — they are not an - upgrade path. The local index is disposable until 1.0 ships and is - tagged; once 1.0 is tagged that clause expires and the question of - upgrading existing indexes returns. See [`docs/DATAMODEL.md`](docs/DATAMODEL.md) - for the full explanation. +13. Pre-1.0: NEVER add a database migration. Migrations are supported, but + nothing is installed anywhere yet, so there is nothing to migrate. To change + the schema, edit `internal/database/schema/001.sql` (and any code that + touches the affected tables) directly. After 1.0, each schema change is a + new numbered file in that directory and a released file is never edited; an + existing local database is then migrated when vaultik is updated. Before + 1.0, a local database left on an older schema is deleted and re-created by a + full backup. See [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations). +14. Never use `git add -A`. Stage only the files you intentionally changed. + +15. Commit messages carry no attribution or advertising trailers for the tool + that helped write the code, or for its vendor: the owner is the sole author + of code written with a tool. + +16. Run the whole test suite with `make test` every time, and read its full + output. Never run `go test`, a single test or a single package, and never + grep the output. + +17. Do not stop working on a task until the definition of done given in the + initial instruction is met: all of the work, not part or most of it. + +18. For estimates: backing up over 2.5Gbit/s ethernet to an S3 server backed by + 2000MB/sec SSD takes about 4 seconds per gigabyte. diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index cec4213..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,44 +0,0 @@ -# Rules - -Read the rules in AGENTS.md and follow them. - -# Memory - -* Claude is an inanimate tool. The spam that Claude attempts to insert into - commit messages (which it erroneously refers to as "attribution") is not - attribution, as I am the sole author of code created using Claude. It is - corporate advertising for Anthropic and is therefore completely - unacceptable in commit messages. - -* NEVER use `git add -A`. Always add only the files you intentionally - changed. - -* Tests should always be run before committing code. No commits should be - made that do not pass tests. - -* Code should always be formatted before committing. Do not commit - unformatted code. - -* Code should always be linted before committing. Do not commit - unlinted code. - -* The test suite is fast and local. When running tests, don't run - individual parts of the test suite, always run the whole thing by running - "make test". - -* Do not stop working on a task until you have reached the definition of - done provided to you in the initial instruction. Don't do part or most of - the work, do all of the work until the criteria for done are met. - -* We do not need to support migrations; schema upgrades can be handled by - deleting the local state file and doing a full backup to re-create it. - -* When testing on a 2.5Gbit/s ethernet to an s3 server backed by 2000MB/sec SSD, - estimate about 4 seconds per gigabyte of backup time. - -* When running tests, don't run individual tests, or grep the output. run - the entire test suite every time and read the full output. - -* When running tests, don't run individual tests, or try to grep the output. - never run "go test". only ever run "make test" to run the full test - suite, and examine the full output. diff --git a/Dockerfile b/Dockerfile index 1dcc46a..c60db2c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,96 +1,97 @@ -# This file has no lint stage, deliberately. -# -# Linting lives in Dockerfile.lint, built by script/lint, and -# script/cibuild builds both. A lint stage here would have to either -# shell out to `make lint` -- which is now `docker build`, so -# docker-in-docker inside a BuildKit step with no daemon -- or call -# golangci-lint directly, which would mean a second, independently -# bumpable digest pin for the linter alongside the one in -# Dockerfile.lint. Two pins for one tool is the drift that -# https://git.eeqj.de/sneak/vaultik/issues/78 was filed over. See -# https://git.eeqj.de/sneak/vaultik/issues/113 for the ruling. -# -# Consequence, stated rather than left to be discovered: script/docker -# builds this file only and therefore does not lint. `make fmt-check` -# and `make test` still run here, so what a green build of this file -# means is "formatted, tested, and it compiles" -- the lint verdict -# comes from script/lint or script/cibuild. +# Lint phase. The linter is invoked directly rather than through `make +# lint` or `script/lint`, which are themselves a docker build and would +# recurse into a daemon that does not exist in a build step. +# golangci/golangci-lint:v2.14.0, 2026-10-05 +FROM golangci/golangci-lint:v2.14.0@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f AS lint +WORKDIR /src +COPY go.mod go.sum ./ +# Without the time limit a stalled connection to the module proxy holds +# this step, and every build on the host sharing it, until the kernel +# drops the connection, which can take an hour. The limit is well above +# the three minutes a working download can take on a busy build host. +RUN for attempt in 1 2 3; do \ + timeout 300 go mod download && exit 0; \ + echo "go mod download attempt $attempt failed or ran over 300s" >&2; \ + done; \ + echo "module download failed: giving up after 3 attempts" >&2; \ + exit 1 +COPY . . +# `golangci-lint run` silently ignores an unknown top-level key in +# .golangci.yml, such as a misspelt `linters:`; `config verify` fails on it. +RUN golangci-lint config verify --config .golangci.yml +RUN golangci-lint run --config .golangci.yml ./... -# Build stage +# Test phase. -race needs cgo and so a C compiler, which the Debian Go +# image ships and the alpine one does not. +# golang:1.26.1 (Debian trixie), 2026-10-05 +FROM golang:1.26.1@sha256:cd78d88e00afadbedd272f977d375a6247455f3a4b1178f8ae8bbcb201743a8a AS test +WORKDIR /src +COPY go.mod go.sum ./ +# Limited and retried as in the lint phase above. +RUN for attempt in 1 2 3; do \ + timeout 300 go mod download && exit 0; \ + echo "go mod download attempt $attempt failed or ran over 300s" >&2; \ + done; \ + echo "module download failed: giving up after 3 attempts" >&2; \ + exit 1 +COPY . . +RUN go test -timeout 90s -race -cover ./... || \ + { echo "--- Rerunning with -v for details ---"; \ + go test -timeout 90s -race -v ./...; exit 1; } + +# Build stage. Nothing is wanted from either phase above; the copies +# are what make BuildKit build them first, so this stage cannot run +# unless lint and test passed. # golang:1.26.1-alpine, 2026-03-17 FROM golang:1.26.1-alpine@sha256:2389ebfa5b7f43eeafbd6be0c3700cc46690ef842ad962f6c5bd6be49ed82039 AS builder - -# Build tooling: make, plus a C toolchain because `go test -race` needs cgo. -# The sqlite driver is pure Go (modernc.org/sqlite), so no sqlite library or -# CLI is required. -RUN apk add --no-cache make build-base - +COPY --from=lint /src/go.sum /dev/null +COPY --from=test /src/go.sum /dev/null +RUN apk add --no-cache git +# A tar-stream context keeps the sender's file owners, which git refuses. +RUN git config --system --add safe.directory /src WORKDIR /src - -# Copy go mod files first for better layer caching COPY go.mod go.sum ./ -RUN go mod download - -# Copy source code +# Limited and retried as in the lint phase above. +RUN for attempt in 1 2 3; do \ + timeout 300 go mod download && exit 0; \ + echo "go mod download attempt $attempt failed or ran over 300s" >&2; \ + done; \ + echo "module download failed: giving up after 3 attempts" >&2; \ + exit 1 COPY . . -# Run the format check and the tests. -# -# CHECK_EPOCH must stay immediately above these RUNs. These layers are -# keyed on its value, so they are cache-eligible only for a value -# already built against this same tree. script/cibuild and script/docker -# each pass a fresh value on every invocation, which is what makes their -# green mean the checks really executed. -# -# The value is expanded into each check command rather than left to a -# bare declaration, so the cache miss does not depend on BuildKit's -# unreferenced-ARG handling staying as it is. It also puts the epoch in -# the build log, where a reader can see the layer was keyed fresh. -# -# The guard is what makes a build that omits --build-arg fail instead of -# lie. An unset ARG is an empty string, and an empty string is a -# perfectly stable cache key: without the guard the first such build -# runs the checks and every one after it on an unchanged tree replays -# these layers from cache, executes nothing, and still exits 0. Failed -# steps are never cached, so the guard fails on EVERY invocation rather -# than once -- a bare `docker build .` is a loud error, not a quiet -# green. Do not give CHECK_EPOCH a default value; a default would -# satisfy the guard with a constant and restore the hole. -# -# Everything above this line (apk, go.mod, `go mod download`) is -# deliberately outside the busted range and keeps caching. -ARG CHECK_EPOCH -RUN [ -n "$CHECK_EPOCH" ] || exit 1 -RUN echo "check epoch: ${CHECK_EPOCH}" && make fmt-check -RUN echo "check epoch: ${CHECK_EPOCH}" && make test +# The VERSION build arg when one is given, otherwise +# `git describe --tags --always` on the .git in the build context. The +# commit and its date always come from that .git. With .git present, a +# version that is still empty, dev or unknown, or a commit or date that +# is unknown, fails the build: git is missing or could not read the +# checkout, as when .git is a file pointing outside the context. A +# context without .git, such as a source export, stamps "dev" and an +# "unknown" commit and date. +ARG VERSION +RUN VERSION="${VERSION:-$(git describe --tags --always || echo dev)}"; \ + commit="$(git rev-parse HEAD || echo unknown)"; \ + commit_date="$(git show -s --format=%cs HEAD || echo unknown)"; \ + if [ -e .git ]; then \ + case "$VERSION" in ""|dev|unknown) \ + echo "version is '$VERSION' although .git is present" >&2; \ + exit 1 ;; \ + esac; \ + if [ "$commit" = unknown ] || [ "$commit_date" = unknown ]; then \ + echo "commit is '$commit' and its date '$commit_date'" \ + "although .git is present" >&2; \ + exit 1; \ + fi; \ + fi; \ + globals=sneak.berlin/go/vaultik/internal/globals; \ + CGO_ENABLED=0 go build -trimpath \ + -ldflags="-s -w -X ${globals}.Version=${VERSION} \ + -X ${globals}.Commit=${commit} \ + -X ${globals}.CommitDate=${commit_date}" \ + -o /vaultik ./cmd/vaultik -# Version, commit and build date are computed on the host by -# script/docker and script/cibuild (where .git exists) and passed in as -# build args. The build context excludes .git (see .dockerignore), so -# the build cannot derive them itself: it used to try, with `git -# rev-parse` inside this stage, and always got "unknown". VERSION comes -# from script/version, the source of truth shared with the Makefile, so -# it carries the same tag / dev- / -dirty rules and a Docker image -# reports the same string a local build of the same tree would. -# -# The defaults are the fallback for a bare `docker build .` that passes -# none of them: an unset arg would otherwise stamp an empty string and -# produce an image that cannot report its own version, commit or date. -# They match what an out-of-git build reports elsewhere. -# -# These ARGs sit here, after the checks, rather than at the top of the -# stage: every commit changes their values, and a value change -# invalidates all layers below the ARG. Declared up top they would bust -# `go mod download`; here they only rekey this build layer, which the -# COPY of the sources above already rebuilds on any change anyway. -ARG VERSION=dev -ARG COMMIT=unknown -ARG COMMIT_DATE=unknown - -# Build (pure Go, no CGO required since we use modernc.org/sqlite) -RUN CGO_ENABLED=0 go build -ldflags "-X 'sneak.berlin/go/vaultik/internal/globals.Version=${VERSION}' -X 'sneak.berlin/go/vaultik/internal/globals.Commit=${COMMIT}' -X 'sneak.berlin/go/vaultik/internal/globals.CommitDate=${COMMIT_DATE}'" -o /vaultik ./cmd/vaultik - -# Runtime stage +# Runtime stage, and the last one: a plain `docker build .` builds this +# stage's chain and nothing else. # alpine:3.21, 2026-02-25 FROM alpine:3.21@sha256:c3f8e73fdb79deaebaa2037150150191b9dcbfba68b4a46d70103204c53f4709 diff --git a/Dockerfile.lint b/Dockerfile.lint deleted file mode 100644 index 4e39700..0000000 --- a/Dockerfile.lint +++ /dev/null @@ -1,104 +0,0 @@ -# Lint image. -# -# Every lint run in this repo happens inside this image, invoked through -# script/lint, and linting is a BUILD STEP rather than a container -# command: a successful build of this file IS a clean lint. That shape -# also works where the docker daemon is remote and bind mounts are -# impossible, which `docker run` against a mounted worktree does not. -# -# This FROM line is the single source of truth for the linter version in -# this repo. Nothing else pins golangci-lint: the product Dockerfile has -# no lint stage, deliberately, so there is no second digest to bump and -# no pair of pins that can drift apart. Bump the tag AND the digest here -# and nowhere else. -# -# Note for readers coming from REPO_POLICIES.md: that document still -# describes the older pattern, a lint stage inside the product -# Dockerfile wired up with `COPY --from=lint /src/go.sum /dev/null`. -# That pattern is superseded here by the owner's ruling recorded in -# https://git.eeqj.de/sneak/vaultik/issues/113 -- lint runs in its own -# image, per run, with its own cache and its own lock, which is what -# makes concurrent runs on one host safe. The policy text is org-wide -# and is being amended separately; this file is what this repo does. -# -# golangci/golangci-lint:v2.12.2, 2026-08-10 -FROM golangci/golangci-lint:v2.12.2@sha256:5cceeef04e53efe1470638d4b4b4f5ceefd574955ab3941b2d9a68a8c9ad5240 - -WORKDIR /src - -# Copy the dependency manifests first so the module download layer stays -# cached until they change. Everything above the ARG below is cacheable -# on purpose; a cold module download on every lint would make the inner -# loop unusable and buys nothing, because it is not what the gate is -# asserting. -COPY go.mod go.sum ./ -RUN go mod download - -COPY . . - -# Force the check layers to execute on every invocation. -# -# CHECK_EPOCH must stay immediately above the RUNs below. Those layers -# are keyed on its value, so they are cache-eligible only for a value -# already built against this same tree; script/lint and script/cibuild -# each pass a fresh value on every invocation, which is what makes their -# green mean the linter really ran. Without it, `docker build -f -# Dockerfile.lint .` on an unchanged tree exits 0 in well under a second -# having linted nothing. -# -# The value is expanded into each check command itself rather than left -# to a bare declaration, so the cache miss does not depend on BuildKit's -# unreferenced-ARG handling staying as it is. It also puts the epoch in -# the build log, where a reader can see the layer was keyed fresh. -# -# The guard is what makes a build that omits --build-arg fail instead of -# lie. An unset ARG is an empty string, and an empty string is a -# perfectly stable cache key: without the guard the first such build -# lints and every one after it on an unchanged tree replays this layer, -# executes nothing, and still exits 0. Failed steps are never cached, so -# the guard fails on EVERY invocation rather than once. Do not give -# CHECK_EPOCH a default value; a default would satisfy the guard with a -# constant and restore the hole. -ARG CHECK_EPOCH -RUN [ -n "$CHECK_EPOCH" ] || exit 1 - -# Validate .golangci.yml before linting with it. -# -# This is not belt-and-braces; it closes a hole that `golangci-lint run` -# leaves wide open. `run` rejects YAML it cannot PARSE, but it silently -# IGNORES an unknown top-level KEY. Renaming `linters:` to `linterz:` -- -# one character -- discards `default: all`, the whole disable list and -# every threshold, leaves only golangci-lint's small default linter set -# running, and exits 0 reporting `0 issues.` on a tree the real config -# fails. Demonstrated on this repo at this pin, recorded on -# https://git.eeqj.de/sneak/vaultik/pulls/114: with a planted -# over-length line, `script/lint` exits 1 naming the `revive` finding -# with `linters:` and exits 0 with `linterz:`. A set-but-ineffective -# config quietly falling back to defaults is precisely the false-green -# class this gate exists to eliminate, so it must not sit in the gate's -# own configuration. -# -# `config verify` catches it, and it does so OFFLINE at this pinned -# version -- verified, not assumed. Under `docker run --network none` -# against the pinned digest it exits 0 on this repo's config and exits 3 -# on the `linterz:` variant with `additional properties 'linterz' not -# allowed`. An earlier revision of this file asserted the opposite, that -# the schema is fetched over live HTTPS from an unpinned URL, and used -# that to justify omitting this line. That claim was false at v2.12.2; -# the schema is embedded. If a future bump reintroduces a network fetch -# the failure is loud and this comment is where to record it. -# -# It is keyed on CHECK_EPOCH, like the lint run below, so it executes on -# every invocation. Content-addressing alone would arguably be enough -- -# .golangci.yml arrives through `COPY . .`, so a cache hit here implies -# a byte-identical config was validated when the layer really ran. That -# argument is exactly the one that would also excuse caching the lint -# layer, and this repo has ruled it insufficient: a cached check layer -# checks nothing, and the cost of being wrong is silent. Forcing it costs -# milliseconds and puts the epoch in the log, where a reader can see that -# this validation ran rather than being replayed. -RUN echo "check epoch: ${CHECK_EPOCH}" && \ - golangci-lint config verify --config .golangci.yml - -RUN echo "check epoch: ${CHECK_EPOCH}" && \ - golangci-lint run --config .golangci.yml ./... diff --git a/Makefile b/Makefile index 17f714a..f694dd5 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,10 @@ .PHONY: all bootstrap setup check test lint lint-fix fmt fmt-check build clean deps test-coverage local install release release-snapshot docker hooks -# Version number, derived from git by script/version -- the tag when -# HEAD is on one, otherwise dev-. This used to be a hardcoded +# Where script/bootstrap installs Go when the host has none. +export PATH := $(PATH):$(CURDIR)/.tool/go/bin + +# Version number, derived from git by script/version (`git describe +# --tags --always --dirty`). This used to be a hardcoded # constant, which meant every local build claimed to be a release that # had never been tagged. VERSION := $(shell script/version) @@ -40,9 +43,10 @@ setup: check: @script/check -# Run tests only. This runs the ENTIRE suite -- there is no separate -# integration target and no build-tagged subset held back. In -# particular internal/vaultik/integration_test.go, which does full +# Run tests only, by building the test phase of the Dockerfile. This +# runs the ENTIRE suite -- there is no separate integration target and +# no build-tagged subset held back. In particular +# internal/vaultik/integration_test.go, which does full # chunk -> pack -> encrypt -> upload -> restore round-trips, runs here. # A `test-integration` target used to exist and was removed: no file in # the repo carried a build tag, so `-tags=integration` selected nothing @@ -87,17 +91,17 @@ clean: go clean # Install dependencies. The linter is deliberately not installed here: -# script/lint lints by building Dockerfile.lint, whose FROM line is the -# single source of truth for the linter version. A second, separately -# pinned copy on PATH could drift from it and make a local `make lint` -# disagree with CI. +# script/lint lints by building the lint phase of the Dockerfile, whose +# FROM line is the single source of truth for the linter version. A +# second, separately pinned copy on PATH could drift from it and make a +# local `make lint` disagree with CI. deps: go mod download -# Run tests with coverage. -count=1 for the same reason script/test -# uses it: without it an unchanged package is served from Go's test -# result cache, and a coverage profile assembled from cached results -# describes a run that did not happen. +# Run tests with coverage, on the host. -count=1 because without it an +# unchanged package is served from Go's test result cache, and a +# coverage profile assembled from cached results describes a run that +# did not happen. test-coverage: go test -v -count=1 -coverprofile=coverage.out ./... go tool cover -html=coverage.out -o coverage.html diff --git a/README.md b/README.md index 9e8f862..8d9e77e 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # vaultik (ваултик) -`vaultik` is an incremental backup tool written in Go. It encrypts data -using an `age` public key and uploads each encrypted blob directly to a -remote S3-compatible object store. It requires no private keys, secrets, or -credentials (other than those required to PUT to encrypted object storage, -such as S3 API keys) stored on the backed-up system. +`vaultik` is an incremental backup tool written in Go. It encrypts data using an +`age` public key and uploads each encrypted blob directly to a remote +S3-compatible object store. The backed-up system never needs the private key. A +backup needs only the public key and the credentials to write to the object +store, such as S3 API keys. ## quickstart @@ -24,12 +24,16 @@ grep 'public key' vaultik_backup_private_key.txt vaultik config set age_recipients.0 age1YOUR_PUBLIC_KEY_HERE vaultik config set storage_url "file:///Volumes/usbstick/mybackup" +# create the destination directory; vaultik never creates it, so a backup +# to a volume that is not plugged in fails instead of filling the disk +mkdir /Volumes/usbstick/mybackup + # macOS only: grant your terminal app Full Disk Access first # (System Settings → Privacy & Security → Full Disk Access), otherwise # the backup will abort with a permission error on protected directories -# run your first backup (the default config backs up ~ and /Applications -# with sensible excludes) +# run your first backup (the default config backs up ~, and /Applications +# on macOS only, with sensible excludes) vaultik snapshot create # see what you have @@ -38,35 +42,36 @@ vaultik snapshot list Features: -* modern encryption ([age](https://age-encryption.org/), X25519 + ChaCha20-Poly1305) -* content-defined chunking with deduplication (FastCDC) -* incremental backups (only changed files are re-chunked) -* multithreaded zstd compression at configurable levels -* content-addressed immutable storage -* local state tracking in SQLite (enables write-only incremental backups) -* no mutable remote metadata -* no plaintext file paths or metadata in remote storage -* packs small files into large blobs (keeps S3 operation counts down) -* backs up regular files, symlinks, empty directories, and file permissions -* pluggable storage backends: S3, local filesystem, rclone (70+ providers) -* pure Go (no CGO), cross-compiles to linux/darwin × amd64/arm64 +- modern encryption ([age](https://age-encryption.org/), X25519 + + ChaCha20-Poly1305) +- content-defined chunking with deduplication (FastCDC) +- incremental backups (a file is re-chunked only when it changed or a chunk it + lists is held by no uploaded blob) +- multithreaded zstd compression at configurable levels +- content-addressed immutable storage +- local state tracking in SQLite (enables write-only incremental backups) +- no mutable remote metadata +- no plaintext file paths or metadata in remote storage +- packs small files into large blobs (keeps S3 operation counts down) +- backs up regular files, symlinks, empty directories, and file permissions +- pluggable storage backends: S3, local filesystem, rclone (70+ providers) +- pure Go (no CGO), cross-compiles to linux/darwin × amd64/arm64 ## why Other backup tools like `restic`, `borg`, and `duplicity` are designed for environments where the source host can store secrets and has access to -decryption keys. `vaultik` is for environments where you don't want to -store backup decryption keys on your hosts — only public keys for -encryption. +decryption keys. `vaultik` is for environments where you don't want to store +backup decryption keys on your hosts — only public keys for encryption. Requirements that no existing tool meets: -* open source -* no passphrases or private keys on the source host -* incremental -* compressed -* encrypted -* s3 compatible without an intermediate step or tool +- open source +- no passphrases or private keys on the source host +- incremental +- compressed +- encrypted +- s3 compatible without an intermediate step or tool ## daily use @@ -91,13 +96,22 @@ vaultik snapshot restore ~/vaultik-restore # 0 3 * * * vaultik snapshot create --cron --prune --keep-newer-than 4w ``` +On a destination shared between hosts or users, the prune in that cron line +relies on `prune_grace_period` (default `24h`) to leave the blobs of a backup +another one is still running, and its directory under `metadata/` that has no +manifest yet, so it must be longer than the longest backup run. It does not +protect a blob that backup reuses from an earlier run that stopped before its +manifest: the prune can delete such a blob, and the new snapshot then cannot be +restored. To not depend on the grace period, give each host its own prefix or +directory. See [locking](#locking). + ## restoring on another machine -Restoring on a host that never ran the backup — a replacement machine -after the original is gone — is the case vaultik is built for. That host -needs only three things: the `vaultik` binary, the age **private** key, -and the storage credentials for the destination. It does **not** need the -local index, the original config file, or the original hostname. +Restoring on a host that never ran the backup — a replacement machine after the +original is gone — is the case vaultik is built for. That host needs only three +things: the `vaultik` binary, the age **private** key, and the storage +credentials for the destination. It does **not** need the local index, the +original config file, or the original hostname. ```sh # install @@ -113,17 +127,16 @@ vaultik config set s3.secret_access_key "..." vaultik snapshot list ``` -`snapshot list` reads the destination store without the private key. A -snapshot that is not in this host's (empty) local index is shown as -remote-only: its row is identified by `` rather than by -a `hostname_name_timestamp` name, because the name lives only in the -local index and the encrypted database and cannot be recovered from the -store. Its timestamp and compressed size are real. (See the `snapshot -list` description under [command details](#command-details) for the full -explanation.) +`snapshot list` reads the destination store without the private key. A snapshot +that is not in this host's (empty) local index is shown as remote-only: its row +is identified by `` rather than by a `hostname_name_timestamp` +name, because the name lives only in the local index and the encrypted database +and cannot be recovered from the store. Its timestamp and compressed size are +real. (See the `snapshot list` description under +[command details](#command-details) for the full explanation.) -Use that remote key — the hex printed inside ``, or the -full `remote_key` from `snapshot list --json` — to restore and verify: +Use that remote key — the hex printed inside ``, or the full +`remote_key` from `snapshot list --json` — to restore and verify: ```sh # put the private key file in the environment (reading it from the file @@ -140,10 +153,10 @@ vaultik snapshot restore --verify ~/vaultik-restore vaultik snapshot verify --deep ``` -`age_recipients` (the public key) is not needed to restore — only the -private key in `VAULTIK_AGE_SECRET_KEY`. Both the abbreviated key printed -in the table and the full 64-character key from `--json` are accepted; a -leading part of the key is enough as long as it is unambiguous. +`age_recipients` (the public key) is not needed to restore — only the private +key in `VAULTIK_AGE_SECRET_KEY`. Both the abbreviated key printed in the table +and the full 64-character key from `--json` are accepted; a leading part of the +key is enough as long as it is unambiguous. --- @@ -158,6 +171,7 @@ vaultik [--config ] config get vaultik [--config ] config set vaultik [--config ] snapshot create [snapshot-names...] [--cron] [--prune] [--keep-newer-than ] vaultik [--config ] snapshot list [--json] # alias: ls +vaultik [--config ] snapshot files [path] [--json] vaultik [--config ] snapshot verify [--deep] [--json] vaultik [--config ] snapshot purge [--keep-latest | --older-than ] [--snapshot ...] [--force] vaultik [--config ] snapshot remove [--dry-run] [--force] [--local-only] [--json] # alias: rm @@ -173,65 +187,104 @@ vaultik version ### global flags -* `--config `: Path to config file (default: `$VAULTIK_CONFIG`, then platform config dir, then `/etc/vaultik/config.yml`) -* `--verbose`, `-v`: Enable verbose output (on stderr — see below) -* `--debug`: Enable debug output (on stderr — see below) -* `--quiet`, `-q`: Suppress non-error output (also suppresses startup banner) -* `--skip-errors`: Skip files that cannot be read when creating a snapshot, or that cannot be restored when restoring, instead of aborting. Packing and storage errors (which would leave a chunk recorded but not stored) still abort the run. +- `--config `: Path to config file (default: `$VAULTIK_CONFIG`, then + platform config dir, then `/etc/vaultik/config.yml`) +- `--verbose`, `-v`: Enable verbose output (on stderr — see below) +- `--debug`: Enable debug output (on stderr — see below) +- `--quiet`, `-q`: Suppress non-error output (also suppresses startup banner) +- `--skip-errors`: Skip files that cannot be read when creating a snapshot, or + that cannot be restored when restoring, instead of aborting. Packing and + storage errors while creating a snapshot (which would leave a chunk recorded + but not stored) still abort the run. A run that skipped anything still + finishes but exits non-zero: `snapshot create` keeps the snapshot and counts + each file or directory it skipped as failed. A file removed during the backup + is also counted as failed but does not change the exit status. ### locking -Commands that write persistent state — `snapshot create`, `snapshot -purge`, `snapshot remove`, `prune`, and `remote nuke` — take a -process-wide lock at `$XDG_DATA_HOME/vaultik/vaultik.pid` -(`~/.local/share/vaultik/vaultik.pid` on Linux) for the whole run. Only -one of them runs at a time: a second one exits immediately with an -"already running" error rather than waiting, so two writers can never -corrupt the local index or the destination store. +Commands that write persistent state — `snapshot create`, `snapshot purge`, +`snapshot remove`, `prune`, and `remote nuke` — take a process-wide lock at +`$XDG_DATA_HOME/vaultik/vaultik.pid` (`~/.local/share/vaultik/vaultik.pid` on +Linux) for the whole run. Only one of them runs at a time: a second one exits +immediately with an "already running" error rather than waiting, so two writers +can never corrupt the local index. -Read-only commands — `info`, `snapshot list`, `snapshot verify`, and -`remote info` — do not take the lock and are never blocked, so they run -even while a backup is in progress. `snapshot restore` does not take the -lock either: it writes only to the target directory you name, not the -local index or the destination store. `config`, `database delete`, -`completion`, and `version` do not take the lock. +The lock covers one user on one machine. It does not stop another user, or +another host, from writing to the same destination store at the same time. A +backup uploads its blobs, and then its `db.zst.age`, before its manifest, so a +prune from elsewhere at that moment finds blobs no snapshot lists and a +directory under `metadata/` with no manifest. It deletes such a blob only once +it is older than `prune_grace_period` (default `24h`), and such a directory only +once every object in it is, so the grace period must be longer than the longest +backup run of any host or user sharing the destination. The grace period does +not protect a blob a backup reuses from an earlier run that stopped before its +manifest: a backup skips the upload of a blob already on the destination, so +that blob keeps the time of its first upload, and a prune from elsewhere during +the backup can delete it; the new snapshot then cannot be restored. +`remote nuke` deletes everything regardless. To not depend on the grace period, +give each host or user its own prefix (or directory) on the destination. + +These read-only commands do not take the lock, so they are never blocked, even +while a backup is in progress: + +- `info` +- `snapshot list` +- `snapshot files` +- `snapshot verify` +- `remote info` + +`snapshot restore` does not take the lock either: it writes only to the target +directory you name, not the local index or the destination store. + +These commands do not take the lock either: + +- `config` +- `database delete` +- `completion` +- `version` ### stdout and stderr -Log output — everything from `--verbose` and `--debug`, and every -warning and error the logger emits — goes to **stderr**. stdout carries -the output you asked for: tables, and the documents produced by `--json`. +Log output — everything from `--verbose` and `--debug`, and every warning and +error the logger emits — goes to **stderr**, and so does the startup banner. +stdout carries the output you asked for: tables, the documents produced by +`--json`, `config get` values, and completion scripts. -This means `vaultik snapshot list --verbose > out.txt` captures the -listing and leaves the diagnostics on your terminal. To capture both, -redirect stderr as well (`> out.txt 2> log.txt`, or `> out.txt 2>&1` to -interleave them). +This means `vaultik snapshot list --verbose > out.txt` captures the listing and +leaves the diagnostics on your terminal. To capture both, redirect stderr as +well (`> out.txt 2> log.txt`, or `> out.txt 2>&1` to interleave them). -The split is what makes `--json` usable from a script. Warnings and -errors are never suppressed — not by `--quiet`, not by `--cron` — so a -logger on stdout would eventually land a log line inside a JSON -document and break the parse. A config file with group- or -world-readable permissions is enough to trigger it. +The split is what makes `--json` usable from a script. Warnings and errors are +never suppressed — not by `--quiet`, not by `--cron` — so a logger on stdout +would eventually land a log line inside a JSON document and break the parse. A +config file with group- or world-readable permissions is enough to trigger it. -Format follows the stream: when stderr is a terminal the records are -colorized one-liners, and when it is redirected or piped they are -JSON, one object per line. +Format follows the stream: when stderr is a terminal the records are colorized +one-liners, and when it is redirected or piped they are JSON, one object per +line. -Under `--json`, stdout holds the document and nothing else. The startup -banner is suppressed, as `--quiet` and `--cron` suppress it, and the -progress narration a command would otherwise print — such as the stale -local records `prune` reconciles away — is suppressed too, so it cannot -land ahead of the document. Every `--json` command therefore pipes on -its own, with no additional flag: `vaultik snapshot list --json | jq .` -and `vaultik prune --json | jq .` both work as written. +Under `--json`, stdout holds the document and nothing else. The startup banner +is suppressed, as `--quiet` and `--cron` suppress it, and the progress narration +a command would otherwise print — such as the stale local records `prune` +reconciles away — is suppressed too, so it cannot land ahead of the document. +Every `--json` command therefore pipes on its own, with no additional flag: +`vaultik snapshot list --json | jq .` and `vaultik prune --json | jq .` both +work as written. ### environment variables -* `VAULTIK_AGE_SECRET_KEY`: Age private key for decryption (required for `snapshot restore` and `snapshot verify --deep`). May hold the whole `age-keygen` file — comments and every identity in it are accepted. Set it from the file, e.g. `export VAULTIK_AGE_SECRET_KEY="$(cat vaultik_backup_private_key.txt)"`, so the key is not typed into your shell history. -* `VAULTIK_CONFIG`: Path to config file (overridden by `--config`) -* `VAULTIK_INDEX_PATH`: Override local SQLite index path -* `VAULTIK_CPUPROFILE`: Write a CPU profile to this path for the duration of the run (development/debugging) -* `VAULTIK_MEMPROFILE`: Write a heap profile to this path when the run exits (development/debugging) +- `VAULTIK_AGE_SECRET_KEY`: Age private key for decryption (required for + `snapshot restore`, `snapshot files` and `snapshot verify --deep`). May hold + the whole `age-keygen` file — comments and every identity in it are accepted. + Set it from the file, e.g. + `export VAULTIK_AGE_SECRET_KEY="$(cat vaultik_backup_private_key.txt)"`, so + the key is not typed into your shell history. +- `VAULTIK_CONFIG`: Path to config file (overridden by `--config`) +- `VAULTIK_INDEX_PATH`: Override local SQLite index path +- `VAULTIK_CPUPROFILE`: Write a CPU profile to this path for the duration of the + run (development/debugging) +- `VAULTIK_MEMPROFILE`: Write a heap profile to this path when the run exits + (development/debugging) ### shell completion @@ -262,161 +315,316 @@ existing file. Created with mode `0600` since it will contain credentials. **`config edit`**: Open the config file in `$EDITOR` (falls back to `vi`). -**`config get`**: Print a config value addressed by dotted YAML path -(e.g. `vaultik config get storage_url`). Non-scalar values print as YAML. +**`config get`**: Print a config value addressed by dotted YAML path (e.g. +`vaultik config get storage_url`). Non-scalar values print as YAML. -**`config set`**: Set a scalar config value by dotted YAML path -(e.g. `vaultik config set compression_level 9`, -`vaultik config set storage_url "file:///mnt/backups"`). Comments and -formatting in the file are preserved; intermediate maps are created as -needed. +**`config set`**: Set a scalar config value by dotted YAML path (e.g. +`vaultik config set compression_level 9`, +`vaultik config set storage_url "file:///mnt/backups"`). Comments and formatting +in the file are preserved. Missing keys along the path are created: as a list +when the next path element is a number (so +`vaultik config set age_recipients.0 age1...` works on a file without +`age_recipients`), otherwise as a map. If the config loads, a change after which +it would not, such as `vaultik config set compression_level 99`, is refused and +the file is left unchanged. A config that does not load is checked one setting +at a time. Examples are the file `config init` writes before `storage_url` is +set, and one with a `${ENV:...}` reference to a variable not set in this shell. +In such a config, an unknown key or a value of the wrong type is refused. **`snapshot create`**: Perform incremental backup of configured snapshots. -* Optional snapshot names argument to create specific snapshots (default: all) -* On macOS, the terminal application running vaultik needs Full Disk Access + +- Optional snapshot names argument to create specific snapshots (default: all) +- On macOS, the terminal application running vaultik needs Full Disk Access (System Settings → Privacy & Security → Full Disk Access) to read TCC-protected directories; without it the backup aborts with a permission error that explains how to fix it -* `--cron`: Silent on total success; warnings and errors are still printed - (for crontab) -* `--prune`: After backup, drop older snapshots of each backed-up name and - remove orphaned blobs from remote storage. By default keeps only the latest - snapshot per name; use `--keep-newer-than` for a rolling window. -* `--keep-newer-than `: With `--prune`, keep snapshots newer than - this duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`) +- `--cron`: Silent on total success; warnings and errors are still printed (for + crontab) +- `--prune`: After backup, drop older snapshots of each backed-up name, remove + orphaned blobs older than `prune_grace_period` from remote storage, and delete + each directory under `metadata/` that has no `manifest.json.zst` once every + object in it is older than `prune_grace_period` and its snapshot is not in the + local index, as `prune` does. By default keeps only the latest snapshot per + name; use `--keep-newer-than` for a rolling window. When `--skip-errors` + skipped a file or directory it could not read or list, the prune does not run + and every older snapshot is kept, since one of them may be the only one that + holds what was skipped; the command says so and exits non-zero. When the + backup found nothing in a configured path, as in the mount point of a volume + that is not mounted, the prune does not run either: every older snapshot is + kept, and the command names the path and exits non-zero, on every run until + the path holds something again. Take a path that is empty on purpose out of + the config, or remove the older snapshots by hand with `snapshot purge`. When + an earlier snapshot of the same name in the local index found a volume mounted + at or below a configured path (a directory on a different filesystem from its + parent, with an entry in it that the backup does not exclude) and this backup + does not, the prune does not run either: every older snapshot is kept, and the + command names the directory and exits non-zero, on every run until the volume + is mounted again. A backup also does not find the volume when it finds no such + entry in its directory, as when an automounted volume cannot be mounted, or + when that directory is no longer backed up, because it is excluded or its + configured path was removed. If any of this is on purpose, as for a retired + volume, remove the older snapshots by hand with `snapshot purge`. A file + removed during the backup does not stop the prune. +- `--keep-newer-than `: With `--prune`, keep snapshots newer than this + duration instead of only the latest (e.g. `4w`, `30d`, `6mo`, `1y`). Without + `--prune`, or with a value that is not a valid duration, the command fails + before the backup starts. +- Fails before it writes anything when a `file://` destination directory does + not exist, or when the local index holds snapshots and the destination answers + that it has no `vaultik-destination.txt`. When that look-up fails for any + reason other than not found, for example when S3 refuses it to credentials + that allow only PUT, the check is skipped (see + [remote storage layout](#remote-storage-layout)) +- Fails, before anything is pruned, when a configured path is a symlink whose + target does not exist, as one into a volume that is not mounted -**`snapshot list`**: Show every snapshot known to this host — the union -of the local index and the backup destination store — with timestamps -and three sizes per snapshot (compressed remote size; total -uncompressed chunk size; size of chunks newly referenced by that -snapshot). +**`snapshot list`**: Show every snapshot known to this host — the union of the +local index and the backup destination store — with timestamps and three sizes +per snapshot (compressed remote size; total uncompressed chunk size; size of the +chunks that snapshot stored that were not stored before). Both chunk sizes are +recorded when the snapshot's backup runs. -Listing the destination store does **not** require the age secret key, -so it works in vaultik's intended configuration, where the backed-up -host holds only the public key. A host that has lost its local index -can still see what it has backed up. +Listing the destination store does **not** require the age secret key, so it +works in vaultik's intended configuration, where the backed-up host holds only +the public key. A host that has lost its local index can still see what it has +backed up. -What that host cannot see is a remote-only snapshot's name. The -snapshot ID is hashed at the storage boundary and the manifest records -only the hash, so hostname and snapshot name exist solely in the local -index and in the encrypted per-snapshot database. Snapshots found only -on the destination store are therefore listed as -`>` and show `` in -the uncompressed and "new chunk" columns, which can only be computed -from the local index. Their timestamp and compressed size are real, -read from the manifest. +What that host cannot see is a remote-only snapshot's name. The snapshot ID is +hashed at the storage boundary and the manifest records only the hash, so +hostname and snapshot name exist solely in the local index and in the encrypted +per-snapshot database. Snapshots found only on the destination store are +therefore listed as `>` and show +`` in the uncompressed and "new chunk" columns, which come only +from the local index. Their timestamp and compressed size are real, read from +the manifest. -Snapshots in the local index with no counterpart on the destination -store are reported below the table as drift, with the `vaultik prune` -invocation that reconciles them. +Snapshots in the local index with no counterpart on the destination store are +reported below the table as drift, with the `vaultik prune` invocation that +reconciles them. If the local index is bound to a different destination than the +configured one (after a change to `storage_url`, or `s3.endpoint`, `s3.bucket` +or `s3.prefix`), the command says so instead and gives the same two ways out +that `prune` gives: revert the configuration, or run `vaultik database delete`. -If the destination store cannot be listed (unmounted volume, -permission denied, network down), the command warns, falls back to the -local index alone, and still exits zero. -* `--json`: Output in JSON format. Each entry carries `locally_tracked` - (whether the snapshot is in the local index), `remote_key` (the full - 64-character storage key), and `remote_present` (whether it was seen - on the destination store, or `null` if the destination could not be - listed). Warnings about an unlistable destination, unreadable - manifests, and a truncated listing all go to stderr through the - logger, so stdout stays a single parseable document. +If the destination store cannot be listed (unmounted volume, permission denied, +network down), the command warns, falls back to the local index alone, and still +exits zero. It does the same when the destination answers that it has no +`vaultik-destination.txt` while the local index holds snapshots stored there, as +when a volume mounted at the destination is unplugged and leaves its empty mount +point behind. + +- `--json`: Output in JSON format. Each entry carries `locally_tracked` (whether + the snapshot is in the local index), `remote_key` (the full 64-character + storage key), and `remote_present` (whether it was seen on the destination + store, or `null` if the destination could not be listed). Warnings about an + unlistable destination, a local index bound to a different destination (with + both destinations and the same two ways out), unreadable manifests, and a + truncated listing all go to stderr through the logger, so stdout stays a + single parseable document. + +**`snapshot files`**: List the files in a snapshot without restoring it. Each +row of the table shows mode, size in bytes, modification time and path, sorted +by path. + +- Requires `VAULTIK_AGE_SECRET_KEY`: the file list is only in the snapshot's + encrypted database, which the command downloads and decrypts. +- Accepts the same identifiers as `snapshot restore`. +- An optional path limits the list to that path and what is under it. A path + that matches nothing in the snapshot is an error. +- `--json`: Output an array of objects with `path`, `size`, `mode` and `mtime`. +- In the table, a path that holds a newline or another non-printable character + is shown in double quotes, with that character escaped, as in `"a\nb"`. +- The mode is in Go's file-mode notation, in the table and in `--json`. Letters + before the nine permission characters show the file type and any special bit, + as in `dtrwxrwxrwx` for a sticky directory. These letters differ from `ls -l`: + - `L`: a symbolic link, which `ls -l` shows as `l`. + - `u`: setuid, which `ls -l` shows as `s` in place of the owner's `x`. + - `g`: setgid, which `ls -l` shows as `s` in place of the group's `x`. + - `t`: sticky, which `ls -l` shows as `t` in place of the others' `x`. **`snapshot verify`**: Verify snapshot integrity. -* Default (shallow): checks that every blob the manifest lists is present in + +- Default (shallow): checks that every blob the manifest lists is present in storage with the size the manifest records, and that the encrypted database is present. It does not read blob contents. -* `--deep`: Downloads and decrypts each blob, verifies chunk hashes against the +- `--deep`: Downloads and decrypts each blob, verifies chunk hashes against the encrypted metadata database -* Accepts the same identifiers as `snapshot restore`: a snapshot ID, or a +- Accepts the same identifiers as `snapshot restore`: a snapshot ID, or a remote-only snapshot's remote key (or an unambiguous leading part of it) -* `--json`: Output results as JSON +- `--json`: Output results as JSON **`snapshot purge`**: Remove old snapshots based on criteria. Retention is -per-snapshot-name (`--keep-latest` keeps the latest of each name, not the -latest globally). -* `--keep-latest`: Keep only the most recent snapshot of each name -* `--older-than `: Remove snapshots older than duration (e.g. `30d`, - `4w`, `6mo`, `1y`; `m` is minutes, `mo` is months) -* `--snapshot `: Restrict to specific snapshot names (repeat for multiple) -* `--force`: Skip confirmation prompt +per-snapshot-name (`--keep-latest` keeps the latest of each name, not the latest +globally). -**`snapshot remove`**: Remove one snapshot. By default this removes the -snapshot from the local index and strips the snapshot's metadata from -the backup destination store. Blobs are NOT touched — deleting blobs -requires reading every remaining remote manifest (the destination store -may hold snapshots this host doesn't know about), which is what -`vaultik prune` does. On success the command prints the exact `vaultik -prune` invocation to run as a follow-up. Local row cleanup (files, -chunks, blobs the snapshot was the last referrer for) runs -automatically. If the destination store is unreachable, the local-DB -removal still completes and a warning is emitted; rerun `vaultik prune` -once the store is reachable to finish remote cleanup. To wipe everything -on the destination in one go, use `vaultik remote nuke --force`. -* `--local-only`: Skip remote cleanup; only touch the local index -* `--dry-run`: Show what would be deleted without deleting -* `--force`: Skip confirmation prompt -* `--json`: Output result as JSON +- `--keep-latest`: Keep only the most recent snapshot of each name +- `--older-than `: Remove snapshots older than duration (e.g. `30d`, + `4w`, `6mo`, `1y`; `m` is minutes, `mo` is months) +- `--snapshot `: Restrict to specific snapshot names (repeat for multiple) +- `--force`: Skip confirmation prompt + +**`snapshot remove`**: Remove one snapshot. By default this removes the snapshot +from the local index and strips the snapshot's metadata from the backup +destination store. Blobs are NOT touched — deleting blobs requires reading every +remaining remote manifest (the destination store may hold snapshots this host +doesn't know about), which is what `vaultik prune` does. The command prints the +`vaultik prune` invocation to run as a follow-up only when it removed the +snapshot's metadata from the destination store, and never under `--json`. It +accepts the same identifiers as `snapshot restore`: a snapshot ID, or a +remote-only snapshot's remote key (or an unambiguous leading part of it). An +identifier that names no snapshot in the local index or on the destination store +is an error; with `--local-only`, the snapshot must be in the local index. Local +row cleanup (files, chunks, blobs the snapshot was the last referrer for) runs +automatically. If removing the snapshot's metadata from the destination store +fails (for example because the store is unreachable, or the local index holds +snapshots and the destination answers that it has no `vaultik-destination.txt`), +the local-DB removal still completes and a warning is emitted; run +`vaultik snapshot remove ` again once the store is reachable to +remove the snapshot's metadata from it (`vaultik prune` does not). For a +snapshot that is only on the destination store, that failure is an error. To +wipe everything on the destination in one go, use `vaultik remote nuke --force`. + +- `--local-only`: Skip remote cleanup; only touch the local index +- `--dry-run`: Show what would be deleted without deleting +- `--force`: Skip confirmation prompt +- `--json`: Output result as JSON. Also skips the confirmation prompt, as + `--force` does. **`snapshot restore`**: Restore files from a backup snapshot. -* Requires `VAULTIK_AGE_SECRET_KEY` environment variable -* Accepts a snapshot ID, or — for a snapshot only on the destination - store — its remote key (or an unambiguous leading part of it) as shown - by `snapshot list`. See - [restoring on another machine](#restoring-on-another-machine). -* Optional path arguments to restore specific files/directories (default: all) -* Preserves file permissions, timestamps, ownership (ownership requires root), - symlinks, and empty directories -* `--verify`: After restoring, verify every file's chunk hashes match -**`prune`**: Tidy up everything that isn't needed. Runs three passes: -(1) reconcile the local index against the destination store — any -local snapshot whose remote metadata is missing is dropped from the -local index; (2) delete orphaned local rows (files, chunks, blobs no -longer referenced by any completed snapshot); (3) list every remote -manifest on the destination store to compute the still-referenced blob -set and delete any blob not in that set. Step (3) reads all remote -manifests — network cost scales with the number of snapshots. `snapshot -create --prune` runs the same cleanup automatically; this is the -manual entry point for the same work. -* `--force`: Skip confirmation prompt -* `--json`: Output stats as JSON +- Requires `VAULTIK_AGE_SECRET_KEY` environment variable +- Accepts a snapshot ID, or — for a snapshot only on the destination store — its + remote key (or an unambiguous leading part of it) as shown by `snapshot list`. + See [restoring on another machine](#restoring-on-another-machine). +- Optional path arguments to restore specific files/directories (default: all). + A path that matches nothing in the snapshot is named in a warning, and the + command exits non-zero after restoring the paths that match. +- Preserves file permissions, timestamps, ownership (ownership requires root), + symlinks, and empty directories +- `--verify`: After restoring, verify every restored file's chunk hashes match. + A file skipped under `--skip-errors` is reported as failed to restore and is + not verified. + +**`prune`**: Tidy up everything that isn't needed. Runs three passes: (1) +reconcile the local index against the destination store — any local snapshot +whose remote metadata is missing is dropped from the local index; (2) delete +orphaned local rows (files, chunks, blobs no longer referenced by any completed +snapshot); (3) list every remote manifest on the destination store to compute +the still-referenced blob set and delete any blob not in that set that is older +than `prune_grace_period` (default `24h`). A newer one is kept and counted: it +may belong to a backup still running, on this host or another sharing the +destination store, that has not yet uploaded its manifest. The grace period does +not protect a blob such a backup reuses from an earlier run that stopped before +its manifest: that blob keeps the time of its first upload, so it can be +deleted. Step (3) also deletes each directory under `metadata/` that has no +`manifest.json.zst`, as a backup leaves when it stops after uploading +`db.zst.age` but before its manifest, once every object in it is older than +`prune_grace_period` and its snapshot is not in the local index. An object the +listing gives no time for keeps its directory, and a directory whose name is not +a remote key is left alone. Step (3) reads all remote manifests — network cost +scales with the number of snapshots. `snapshot create --prune` runs the same +cleanup automatically; this is the manual entry point for the same work. If the +destination store cannot be listed, or the local index holds snapshots and the +destination answers that it has no `vaultik-destination.txt` (an unplugged +volume's empty mount point), prune fails and deletes nothing. `snapshot purge` +does the same. If a blob or such a directory cannot be deleted, the command (and +`snapshot create --prune`) exits non-zero. + +- `--force`: Skip confirmation prompt +- `--json`: Output stats as JSON. Also skips the confirmation prompt, as + `--force` does. A blob that cannot be deleted is counted in `blobs_failed`, + and the document is printed before the non-zero exit. A blob kept for being + newer than `prune_grace_period`, or because the listing of the destination + gives no time for it, is counted in `blobs_too_new` and not in `blobs_found`. + A directory under `metadata/` with no manifest is counted in + `metadata_dirs_deleted` once deleted, or in `metadata_dirs_failed` if it + cannot be. **`info`**: Display system configuration, storage settings, encryption recipients, and local database statistics. -**`remote info`**: Show storage backend type and location plus detailed -remote storage inventory: per-snapshot metadata sizes, blob counts, and -orphaned blob detection. -* `--json`: Output as JSON +**`remote info`**: Show storage backend type and location plus detailed remote +storage inventory: per-snapshot metadata sizes, blob counts, and orphaned blob +detection. A name under `metadata/` that is not a remote key is skipped with a +warning and is not printed. If a listed `manifest.json.zst` cannot be read, or +sits under a skipped name, the orphaned blob figures are reported as unknown; +`--json` gives them as `null`, lists the remote key of each unreadable manifest +in `unreadable_manifests` and counts the manifests under skipped names in +`skipped_manifest_count`. An unreadable manifest also leaves its snapshot's blob +count and blob size unknown, `null` in `--json`. A file under `blobs/` whose +name is not a blob hash is not counted as a blob, since `prune` never deletes +it. -**`remote nuke`**: Delete every snapshot's metadata and every blob from the -backup destination store, leaving the bucket prefix empty. Destructive and -irreversible. This is the single supported way to wipe the entire -destination store. -* `--force`: Required to confirm destruction. +- `--json`: Output as JSON -**`database delete`**: Delete the local SQLite state database file -entirely. Remote storage is unaffected; the next backup will do a full -scan and re-deduplicate against existing remote blobs, and the local -index will re-bind to the currently configured storage destination. -Use this after changing `storage_url` to a different destination. -* `--force`: Skip confirmation prompt +**`remote nuke`**: Delete every object under `metadata/` and `blobs/` on the +backup destination store, whatever its name, and then `vaultik-destination.txt`, +leaving the bucket prefix empty. Destructive and irreversible. This is the +single supported way to wipe the entire destination store. A snapshot is removed +from the local index only once its metadata is deleted from the destination +store. If the destination store cannot be listed, or the local index holds +snapshots and the destination answers that it has no `vaultik-destination.txt` +(an unplugged volume's empty mount point), the command fails before it removes +anything. If a listing afterwards still finds anything under `metadata/` or +`blobs/`, the command names each object left and exits non-zero; running it +again deletes what is left. + +- `--force`: Required to confirm destruction. + +**`database delete`**: Delete the local SQLite state database file entirely. +Remote storage is unaffected; the next backup will do a full scan and +re-deduplicate against existing remote blobs, and the local index will re-bind +to the currently configured storage destination. Use this after changing +`storage_url`, or `s3.endpoint`, `s3.bucket` or `s3.prefix`, to a different +destination. + +- `--force`: Skip confirmation prompt --- ## storage backends -vaultik supports three storage backends, selected via the `storage_url` config field: +vaultik supports three storage backends, selected via the `storage_url` config +field: **S3** (`s3://bucket/prefix?endpoint=host®ion=us-east-1`): Any S3-compatible object store. Credentials are read from `s3.access_key_id` and `s3.secret_access_key` in the config file. -**Local filesystem** (`file:///path/to/backup`): Stores blobs and metadata on -a local or mounted filesystem. Useful for testing or backing up to a NAS. +**Local filesystem** (`file:///path/to/backup`): Stores blobs and metadata on a +local or mounted filesystem. Useful for testing or backing up to a NAS. The path +must be absolute; a relative one is refused when the config loads. +Percent-escapes in the path are decoded, so `my%20stick` and `my stick` name the +same directory. The directory must exist before the first backup: vaultik never +creates it. A directory on a removable volume is gone while the volume is not +mounted, so a backup then fails instead of writing to the disk under the mount +point. The mount point itself stays behind when the volume is unplugged: there +only `vaultik-destination.txt` stops such a backup, and only while the local +index holds snapshots. **Rclone** (`rclone://remote/path`): Uses rclone's 70+ supported cloud -providers. Requires rclone to be configured separately (`rclone config`). +providers. Requires rclone to be configured separately (`rclone config`). The +path after the remote name is relative: rclone resolves it on the remote, for +example against the login directory on sftp. A second slash makes it absolute, +as in `rclone://remote//srv/backup`. A remote of type `local` needs an absolute +path; a relative one is refused. + +An upload cut off part-way leaves nothing under the object's name on S3, which +shows an object only once its upload has completed, and on the local filesystem +backend, which writes a temporary file and renames it into place. Rclone remotes +with a server-side move (local and sftp among them) are written under a +temporary name ending in `.partial` and moved into place. Rclone remotes without +one are written in place: where such a remote shows a file while it is still +being written, a killed upload can leave a truncated object under its name, +which a later backup takes for complete. A leftover `.partial` file is ignored +and can be deleted. + +A destination shared between hosts or users, each with its own local index, +relies on `prune_grace_period` to keep one's prune from deleting the blobs of +another's backup still running, or its directory under `metadata/` that has no +manifest yet, so it must be longer than the longest backup run. It does not +protect a blob that backup reuses from an earlier run that stopped before its +manifest, which the prune can delete. To not depend on the grace period, give +each host its own prefix (or directory). See [locking](#locking). Legacy S3 configuration via `s3.*` fields (endpoint, bucket, prefix, etc.) is still supported for backward compatibility. `storage_url` takes precedence if @@ -426,14 +634,15 @@ both are set. ## architecture -For an implementation-level view of the internals — the data model, the -`fx` dependency-injection wiring, and the scanner — see -[`ARCHITECTURE.md`](ARCHITECTURE.md). +For an implementation-level view of the internals — the data model, the `fx` +dependency-injection wiring, and the scanner — see +[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md). ### remote storage layout ``` // +├── vaultik-destination.txt # Marker written by every backup ├── blobs/ │ └── // └── metadata/ @@ -442,27 +651,45 @@ For an implementation-level view of the internals — the data model, the └── manifest.json.zst # Unencrypted blob list (for pruning) ``` -* Blobs are two-level directory sharded using the first 4 hex chars of the blob hash -* `db.zst.age` is a binary SQLite database (zstd compressed, age encrypted) - containing all file metadata, chunk mappings, and relationships for the snapshot -* `manifest.json.zst` is an unencrypted compressed JSON blob list, enabling +- `vaultik-destination.txt` holds one fixed line of text, with no host name, + path or time. While the local index holds snapshots stored there, a + destination that answers a look-up of it with not found is treated as not + present: `snapshot create` refuses to write to it, `prune`, `snapshot purge` + and `remote nuke` fail, and `snapshot list` and `snapshot remove` behave as + for a destination that cannot be listed. This keeps an unplugged volume's + empty mount point from being taken for a destination whose snapshots are all + gone. Mount the volume if it is removable; if the destination was emptied on + purpose, run `vaultik database delete` and back up again. When the look-up + fails for any reason other than not found, the check is skipped and the + command goes on. S3 refuses it on every run to credentials that allow only + PUT, so a host with such credentials does not notice a destination emptied + since its last backup, and its next backup would leave out the data its local + index records as already stored. After the destination is emptied, run + `vaultik database delete` on such a host before it backs up again. +- Blobs are two-level directory sharded using the first 4 hex chars of the blob + hash +- `db.zst.age` is a binary SQLite database (zstd compressed, age encrypted) + containing all file metadata, chunk mappings, and relationships for the + snapshot +- `manifest.json.zst` is an unencrypted compressed JSON blob list, enabling pruning without the private key Snapshot IDs follow the human-readable format `__` (e.g. `server1_home_2025-06-01T12:00:00Z`), but this ID is never written to the -destination store in plaintext. Each snapshot's metadata directory is named -with its ``, a one-way double SHA-256 hash of the ID, so a plain -listing of the store shows no hostname or snapshot name. The hash uses no -secret, though, so an observer who guesses a candidate hostname and snapshot -name can hash it and confirm the snapshot is present; the remote key keeps -names out of a listing but does not hide them from a guess. The backup time is -not hidden either: manifest.json.zst carries a plaintext timestamp, and object -modification times are visible at the storage layer regardless. For example, +destination store in plaintext. Each snapshot's metadata directory is named with +its ``, a one-way double SHA-256 hash of the ID, so a plain listing +of the store shows no hostname or snapshot name. The hash uses no secret, +though, so an observer who guesses a candidate hostname and snapshot name can +hash it and confirm the snapshot is present; the remote key keeps names out of a +listing but does not hide them from a guess. The backup time is not hidden +either: manifest.json.zst carries a plaintext timestamp, and object modification +times are visible at the storage layer regardless. For example, `server1_home_2025-06-01T12:00:00Z` is stored under `metadata/17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa/`. See [docs/REPOSTRUCTURE.md](docs/REPOSTRUCTURE.md#remote-key-derivation) for the -derivation, and [Security Considerations](docs/REPOSTRUCTURE.md#security-considerations) +derivation, and +[Security Considerations](docs/REPOSTRUCTURE.md#security-considerations) (including [Accepted Risks](docs/REPOSTRUCTURE.md#accepted-risks)) for what the format does and does not protect. @@ -493,249 +720,255 @@ format does and does not protect. 1. List all snapshot manifests 2. Build set of all referenced blob hashes 3. List all blobs in storage -4. Delete any blob not in the referenced set +4. Delete any blob not in the referenced set that is older than + `prune_grace_period` +5. Delete each directory under `metadata/` with no manifest whose objects are + all older than `prune_grace_period`, unless its snapshot is in the local + index ### chunking and deduplication -* Content-defined chunking using the FastCDC algorithm -* Average chunk size: configurable (default 10MB) -* Deduplication at file level (unchanged files skipped) and chunk level - (identical chunks across files stored once) -* Multiple chunks packed into blobs to reduce object count +- Content-defined chunking using the FastCDC algorithm +- Average chunk size: configurable (default 10MB) +- Deduplication at file level (unchanged files skipped, unless a chunk the file + lists is held by no uploaded blob) and chunk level (identical chunks across + files stored once) +- Multiple chunks packed into blobs to reduce object count ### encryption -* Asymmetric encryption using age (X25519 + ChaCha20-Poly1305) -* Only the public key is needed on the source host -* Each blob and each metadata database is encrypted independently -* Multiple recipients supported (encrypt to multiple keys) +- Asymmetric encryption using age (X25519 + ChaCha20-Poly1305) +- Only the public key is needed on the source host +- Each blob and each metadata database is encrypted independently +- Multiple recipients supported (encrypt to multiple keys) ### compression -* zstd compression at configurable level (1-19, default 3). The level is - accepted as 1-19 but maps onto zstd's four internal speed presets: - 1-2 fastest, 3-5 default, 6-9 better, 10-19 best. Levels within the - same band compress identically. -* Applied before encryption at the blob level +- zstd compression at configurable level (1-19, default 3). The level is + accepted as 1-19 but maps onto zstd's four internal speed presets: 1-2 + fastest, 3-5 default, 6-9 better, 10-19 best. Levels within the same band + compress identically. +- Applied before encryption at the blob level --- ## configuration reference -Run `vaultik config init` to generate a fully commented config file; a -complete annotated example also lives in -[`config.example.yml`](config.example.yml). Key fields: +Run `vaultik config init` to generate a fully commented config file; a complete +annotated example also lives in +[`configs/config.example.yml`](configs/config.example.yml). Key fields: -| Field | Default | Description | -|-------|---------|-------------| -| `age_recipients` | (required) | Age public keys for encryption | -| `age_secret_key` | (unset) | Age private key for decryption (`snapshot restore`, `snapshot verify --deep`). Setting it in the config file places the private key on the backed-up host, defeating the public-key-only design (see "why" above). Prefer the `VAULTIK_AGE_SECRET_KEY` environment variable, supplied only on the machine you restore from. | -| `snapshots` | (required) | Named snapshot definitions with paths and excludes | -| `storage_url` | | Storage backend URL (`s3://`, `file://`, `rclone://`) | -| `s3.*` | | Legacy S3 configuration (endpoint, bucket, credentials) | -| `exclude` | | Global exclude patterns (applied to all snapshots) | -| `chunk_size` | `10MB` | Average chunk size for content-defined chunking | -| `blob_size_limit` | `10GB` | Maximum blob size before splitting. Must be at least four times `chunk_size` (the largest chunk the chunker can emit), otherwise a single-chunk blob could exceed the limit | -| `compression_level` | `3` | zstd compression level (1-19) | -| `hostname` | system hostname | Hostname used in snapshot IDs | -| `index_path` | platform data dir | Local SQLite index path | +| Field | Default | Description | +| -------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `age_recipients` | (required by `snapshot create`) | Age public keys for encryption. Other commands run without one, so a machine that only restores can leave it empty | +| `age_secret_key` | (unset) | Age private key for decryption (`snapshot restore`, `snapshot files`, `snapshot verify --deep`). Setting it in the config file places the private key on the backed-up host, defeating the public-key-only design (see "why" above). Prefer the `VAULTIK_AGE_SECRET_KEY` environment variable, supplied only on the machine you restore from. | +| `snapshots` | (required) | Named snapshot definitions with paths and excludes | +| `storage_url` | | Storage backend URL (`s3://`, `file://`, `rclone://`) | +| `s3.*` | | Legacy S3 configuration (endpoint, bucket, credentials) | +| `exclude` | | Global exclude patterns (applied to all snapshots) | +| `chunk_size` | `10MB` | Average chunk size for content-defined chunking | +| `blob_size_limit` | `10GB` | Maximum blob size before splitting. Must be at least four times `chunk_size` (the largest chunk the chunker can emit), otherwise a single-chunk blob could exceed the limit. A backup needs free temporary space, because each blob is written whole to a temporary file before it is uploaded (up to about `blob_size_limit`; an rclone destination that cannot stream uploads needs about twice that) and the metadata export writes copies of the local index. Temporary files go to `$TMPDIR` (default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to `/var/tmp` | +| `compression_level` | `3` | zstd compression level (1-19) | +| `prune_grace_period` | `24h` | How old a blob that no snapshot lists must be before `prune` deletes it, and how old every object in a directory under `metadata/` with no manifest must be before `prune` deletes that directory. A backup uploads its blobs and its `db.zst.age` before its manifest, so on a destination shared between hosts or users this must be longer than the longest backup run (see [locking](#locking)). It does not protect a blob a backup reuses from an earlier run that stopped before its manifest: that blob keeps the time of its first upload, so a prune can delete it. A duration such as `36h` or `90m`; `0s` deletes such blobs and directories at once | +| `hostname` | system hostname | Hostname used in snapshot IDs | +| `index_path` | platform data dir | Local SQLite index path | --- ## limitations -* **No extended attributes (xattrs).** ACLs, macOS Finder metadata, - quarantine flags, SELinux labels, and other extended attributes are not - backed up or restored. -* **No hard link detection.** Two hard links to the same inode are backed - up as independent files. Content deduplication means the data is stored - once, but the hard link relationship is lost on restore. -* **No sparse file support.** Sparse files are fully materialized during - backup. A 100 GB sparse VM disk that is mostly zeros will consume the - full (compressed) size in storage. -* **No bandwidth limiting.** Uploads and downloads use whatever bandwidth - is available. There is no `--bwlimit` flag yet. -* **No parallel blob downloads during restore.** Blobs are fetched - sequentially. Restore speed is bound by single-stream throughput. -* **Device nodes, named pipes, and sockets are silently skipped.** Only - regular files, directories, and symlinks are backed up. -* **No upgrade path between versions.** There is no supported way to carry - an existing local index across a schema change; if the local SQLite - schema changes between versions, delete the local database (`vaultik - database delete`) and run a full backup. Remote storage is unaffected. - (The binary does embed numbered schema files and a `schema_migrations` - table to bootstrap a fresh database — see [`docs/DATAMODEL.md`](docs/DATAMODEL.md) - — but that is not an upgrade path.) -* **Files that change during backup may be inconsistent.** There is no - filesystem snapshot or freeze. If a file is modified between the scan - and chunk phases, the backed-up copy may reflect a partial write. -* **Ownership restoration requires root.** File uid/gid are recorded - and restored, but `chown` requires elevated privileges. Without root, - files are restored with the current user's ownership. +- **No extended attributes (xattrs).** ACLs, macOS Finder metadata, quarantine + flags, SELinux labels, and other extended attributes are not backed up or + restored. +- **No hard link detection.** Two hard links to the same inode are backed up as + independent files. Content deduplication means the data is stored once, but + the hard link relationship is lost on restore. +- **No sparse file support.** Sparse files are fully materialized during backup. + A 100 GB sparse VM disk that is mostly zeros will consume the full + (compressed) size in storage. +- **No bandwidth limiting.** Uploads and downloads use whatever bandwidth is + available. There is no `--bwlimit` flag yet. +- **No parallel blob downloads during restore.** Blobs are fetched sequentially. + Restore speed is bound by single-stream throughput. +- **Device nodes, named pipes, and sockets are silently skipped.** Only regular + files, directories, and symlinks are backed up. +- **Before 1.0, an update can make the local index unusable.** Vaultik supports + schema migrations, but none are added before 1.0 because there is no installed + base yet. If an update leaves your local index unusable, run + `vaultik database delete` and then a full backup; remote storage is + unaffected. After 1.0, the local index is migrated when vaultik is updated. + See [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations). +- **Files that change during backup may be inconsistent.** There is no + filesystem snapshot or freeze. If a file is modified between the scan and + chunk phases, the backed-up copy may reflect a partial write. +- **Ownership restoration requires root.** File uid/gid are recorded and + restored, but `chown` requires elevated privileges. Without root, files are + restored with the current user's ownership. --- ## roadmap -Items still to do before / shortly after 1.0. Loosely ordered by -priority. +Work planned after 1.0. Loosely ordered by priority. ### correctness and operability -* **Security audit of the encryption implementation.** Pre-1.0 - blocker if we're advertising "secure" at the top of this README. - age + zstd + content-defined chunking is mostly off-the-shelf - pieces, but the seams (key handling, recipient parsing, manifest - trust boundary, restore-time identity validation) need an outside - read. -* **Error-condition tests.** Today's coverage is the happy path - plus a few specific regressions. Need fault-injection coverage: - network failures mid-blob, disk-full during restore, corrupted / - truncated / missing blobs, partial uploads, kill -9 between - manifest and db.zst.age writes. -* **Verify restored content end-to-end in CI.** The current - integration test does this for a small synthetic snapshot but - not at scale. A nightly job against a multi-GB representative - snapshot would catch silent regressions in the chunker, packer, - or restore planner. +- **Outside security audit.** Before 1.0 the encryption and blob-generation code + was reviewed: every bug the review found was fixed, and the risks it accepted + are listed in [Accepted Risks](docs/REPOSTRUCTURE.md#accepted-risks). No + outside audit has been done. age + zstd + content-defined chunking is mostly + off-the-shelf pieces, but the seams (key handling, recipient parsing, manifest + trust boundary, restore-time identity validation) need an outside read. +- **Verify restored content end-to-end in CI.** The current integration test + does this for a small synthetic snapshot but not at scale. A nightly job + against a multi-GB representative snapshot would catch silent regressions in + the chunker, packer, or restore planner. ### performance -* **Parallel blob downloads during restore.** Single-stream right - now. With a fast S3 endpoint and a multi-core machine restore is - bound by per-blob fetch + decrypt + decompress; running N of - those in parallel against the disk cache would close most of the - remaining gap. Needs to interact correctly with the locality - planner and sweeper. -* **Bandwidth limiting (`--bwlimit`).** Both upload and download. - Useful for backing up over a shared link. Tricky to make work - correctly with the parallel-download story. -* **Restart of interrupted restore.** Today restore is restartable - in the sense that re-running it overwrites partial output; it - doesn't resume from where it stopped or skip already-present - files. A `--resume` mode that checks targets before fetching - blobs would matter for very large restores. +- **Parallel blob downloads during restore.** Single-stream right now. With a + fast S3 endpoint and a multi-core machine restore is bound by per-blob fetch + + decrypt + decompress; running N of those in parallel against the disk cache + would close most of the remaining gap. Needs to interact correctly with the + locality planner and sweeper. +- **Bandwidth limiting (`--bwlimit`).** Both upload and download. Useful for + backing up over a shared link. Tricky to make work correctly with the + parallel-download story. +- **Restart of interrupted restore.** Today restore is restartable in the sense + that re-running it overwrites partial output; it doesn't resume from where it + stopped or skip already-present files. A `--resume` mode that checks targets + before fetching blobs would matter for very large restores. +- **Daemon mode.** A long-running mode that watches for file changes so frequent + backups, such as hourly, skip the full scan. It adds little for the usual runs + from cron every 12 to 36 hours. See + [issue #204](https://git.eeqj.de/sneak/vaultik/issues/204). ### usability -* **Man pages and richer `--help` examples.** Cobra generates - basic help; man pages would be a separate target. -* **`--bwlimit` style human-readable size flags** across the - command surface where they're currently raw integers. -* **`vaultik snapshot diff `** — show which files changed - between two snapshots without restoring either. -* **Status reporting hook for `--cron`.** When a backup fails - silently in cron, the user has no idea. A configurable - webhook / email / `notify-send` hook on completion (success and - failure) would close the loop. +- **Man pages and richer `--help` examples.** Cobra generates basic help; man + pages would be a separate target. +- **`vaultik snapshot diff `** — show which files changed between two + snapshots without restoring either. +- **Status reporting hook for `--cron`.** When a backup fails silently in cron, + the user has no idea. A configurable webhook / email / `notify-send` hook on + completion (success and failure) would close the loop. ### infrastructure -* **Cross-version schema upgrades.** There is no upgrade path between - released versions — pre-1.0 schema changes are handled by `vaultik - database delete` plus a full re-scan (see - [`docs/DATAMODEL.md`](docs/DATAMODEL.md)). Post-1.0 we'll need a - migration story to keep existing index databases usable across - upgrades. -* **Storage backend coverage tests.** S3, file://, and rclone:// - all share the Storer interface but the rclone path is the least - exercised in CI. +- **Schema migrations after 1.0.** Migrations are supported, but none are added + before 1.0 because there is no installed base yet. After 1.0, each schema + change is a new migration, so an existing local index is migrated when vaultik + is updated (see [`docs/DATAMODEL.md`](docs/DATAMODEL.md#schema-migrations)). +- **Storage backend coverage tests.** S3, file://, and rclone:// all share the + Storer interface but the rclone path is the least exercised in CI. --- ## output style -Every command's user-facing output is governed by `internal/ui`, in one -of two ways. Color is enabled when stdout is a TTY and the `NO_COLOR` +Every command's user-facing output is governed by `internal/ui`, in one of two +ways. Color is enabled when the stream written to is a TTY and the `NO_COLOR` environment variable is unset (https://no-color.org/). -* **Status, progress, warnings, and errors** go through the `internal/ui` +- **Status, progress, warnings, and errors** go through the `internal/ui` message methods below: marker-prefixed, colored on a TTY, and — except - warnings and errors — silenced by `--quiet`. This is the operational - narration of the long-running commands (`snapshot create`, `prune`, - `snapshot restore`, and the like) and the confirmations of - `config init`, `config set`, and `database delete`. -* **The data a command exists to produce** is written plain, with no - marker and no color, because a marker would corrupt a table or a - parsed document. This covers the `version`, `info`, and `remote info` - reports, the `snapshot list` table, `config get` values, and every - `--json` document. `--quiet` silences the human reports and tables - (`version`, `info`, `remote info`, `snapshot list`) but never the - machine-consumed `config get` value or the `--json` documents, which a - script depends on. The `database delete` confirmation prompt is also - written this way and always shown: it is an interactive exchange the - operator must see. + warnings and errors — silenced by `--quiet`. This is the operational narration + of the long-running commands (`snapshot create`, `prune`, `snapshot restore`, + and the like) and the confirmations of `config init`, `config set`, and + `database delete`. +- **The data a command exists to produce** is written plain, with no marker and + no color, because a marker would corrupt a table or a parsed document. This + covers the report or table of each of these commands: + - `version` + - `info` + - `remote info` + - `snapshot verify` + - `snapshot list` + - `snapshot files` -`internal/ui` writes to stdout; it is the output the user asked for. -Structured log records are a different thing and go through + `config get` values and every `--json` document are written plain too. + `--quiet` silences the reports and tables above, but never a `config get` + value or a `--json` document, which a script depends on. + + These commands write their confirmation prompt plain too, with what it asks + to delete: + - `database delete` + - `prune` + - `snapshot purge` + - `snapshot remove` + + `--quiet` never silences these prompts: each is an interactive exchange the + operator must see. + +`internal/ui` writes to stdout; it is the output the user asked for. The +exceptions are the startup banner and the error a failed command ends with, +which go to stderr. Structured log records are a different thing and go through `internal/log`, which writes to stderr (see "stdout and stderr" above). Message classes: -| Class | Marker | Alignment | Use for | -|-------|--------|-----------|---------| -| Banner | none | column 0 | The startup line printed once per invocation | -| Begin | `》` (white) | column 0 | An operation is about to start (present-continuous verb) | -| Complete | `》` (green) | column 0 | An operation just finished (past-tense verb) | -| Info | `》` (white) | column 0 | Neutral status update | -| Notice | `》` (cyan) | column 0 | Important note that is not a warning | -| Warning | `⚠️ Warning:` (orange/yellow) | column 0 | Recoverable problem | -| Error | `🛑 ERROR:` (red) | column 0 | Operation aborted | -| Progress | ` 》` (white) | column 2 | Heartbeat or per-item status during a long-running operation | -| Detail | ` 》` (white) | column 2 | Continuation/sub-line of a preceding Complete (visually identical to Progress) | +| Class | Marker | Alignment | Use for | +| -------- | ------------------------------ | --------- | ------------------------------------------------------------------------------ | +| Banner | none | column 0 | The startup line printed once per invocation, on stderr | +| Begin | `》` (white) | column 0 | An operation is about to start (present-continuous verb) | +| Complete | `》` (green) | column 0 | An operation just finished (past-tense verb) | +| Info | `》` (white) | column 0 | Neutral status update | +| Notice | `》` (cyan) | column 0 | Important note that is not a warning | +| Warning | `⚠️ Warning:` (orange/yellow) | column 0 | Recoverable problem | +| Error | `🛑 ERROR:` (red) | column 0 | Operation aborted | +| Progress | ` 》` (white) | column 2 | Heartbeat or per-item status during a long-running operation | +| Detail | ` 》` (white) | column 2 | Continuation/sub-line of a preceding Complete (visually identical to Progress) | Conventions: -* Messages are complete English sentences ending with a period. -* Fully qualify terms — say "backup destination store" instead of - "storage", "snapshot source files enumeration" instead of "scan", - "local index database" instead of "database". -* Every operation that emits a Complete also emits a corresponding - Begin. Operations that print only a Begin (because completion is - obvious from a later Begin) should be rare and intentional. -* Use natural verb tense to signal state: "Uploading" for Begin, - "Uploaded" for Complete. Never write the words "begin" or "complete" - in the body — the marker color already conveys that. -* All elapsed and remaining-time fields are explicitly scoped to their - subject: write "blob upload elapsed: 30s, blob upload ETA: 03:15:00 - (est remain 14s)", never just "elapsed 30s, ETA 14s". -* "ETA" means an absolute clock time (when the operation will finish), - not a remaining-duration. Use `ui.Time()` for the former and - `ui.Duration()` for the latter, and label both. -* `ui.Time` formats same-day times as `HH:MM:SS` and other-day times as +- Messages are complete English sentences ending with a period. +- Fully qualify terms — say "backup destination store" instead of "storage", + "snapshot source files enumeration" instead of "scan", "local index database" + instead of "database". +- Every operation that emits a Complete also emits a corresponding Begin. + Operations that print only a Begin (because completion is obvious from a later + Begin) should be rare and intentional. +- Use natural verb tense to signal state: "Uploading" for Begin, "Uploaded" for + Complete. Never write the words "begin" or "complete" in the body — the marker + color already conveys that. +- All elapsed and remaining-time fields are explicitly scoped to their subject: + write "blob upload elapsed: 30s, blob upload ETA: 03:15:00 (est remain 14s)", + never just "elapsed 30s, ETA 14s". +- "ETA" means an absolute clock time (when the operation will finish), not a + remaining-duration. Use `ui.Time()` for the former and `ui.Duration()` for the + latter, and label both. +- `ui.Time` formats same-day times as `HH:MM:SS` and other-day times as `YYYY-MM-DD HH:MM:SS`. No timezone — local time is implied. -Value colorizers in `internal/ui` colorize specific value types -consistently. Compose messages from these helpers rather than embedding -ANSI escapes inline: +Value colorizers in `internal/ui` colorize specific value types consistently. +Compose messages from these helpers rather than embedding ANSI escapes inline: -| Helper | Color | Use for | -|--------|-------|---------| -| `Hex` | cyan | Blob hashes, chunk hashes (truncated to 12 chars + `...`) | -| `Snapshot` | bold cyan | Snapshot IDs (untruncated) | -| `Path` | blue | Filesystem paths | -| `Size` | magenta | Byte counts (human-readable) | -| `Speed` | magenta | Bytes-per-second rates | -| `Duration` | yellow | Elapsed or remaining time | -| `Time` | yellow | Absolute clock times | -| `Count` | magenta | Integer counts with thousands separators | -| `Percent` | magenta | Percentages | +| Helper | Color | Use for | +| ---------- | --------- | --------------------------------------------------------- | +| `Hex` | cyan | Blob hashes, chunk hashes (truncated to 12 chars + `...`) | +| `Snapshot` | bold cyan | Snapshot IDs (untruncated) | +| `Path` | blue | Filesystem paths | +| `Size` | magenta | Byte counts (human-readable) | +| `Speed` | magenta | Bytes-per-second rates | +| `Duration` | yellow | Elapsed or remaining time | +| `Time` | yellow | Absolute clock times | +| `Count` | magenta | Integer counts with thousands separators | +| `Percent` | magenta | Percentages | -When `NO_COLOR` is set or output is not a TTY, all helpers return plain -text and the marker prefixes (`》`, `Warning:`, `ERROR:`) emit without -ANSI escapes. The emoji prefixes on Warning and Error are always emitted -regardless of color setting (emoji are not color). +When `NO_COLOR` is set or output is not a TTY, all helpers return plain text and +the marker prefixes (`》`, `Warning:`, `ERROR:`) emit without ANSI escapes. The +emoji prefixes on Warning and Error are always emitted regardless of color +setting (emoji are not color). ## requirements -* Go 1.26 or later -* Docker, with a reachable daemon, to lint, check, or commit: - `script/lint` lints by building `Dockerfile.lint`, which runs the - digest-pinned `golangci-lint` image as a build step, and `make check` - and the pre-commit hook both run it. A `golangci-lint` installed on - `PATH` is not a substitute and is never used on a host, whatever its - version. -* S3-compatible object storage (or local filesystem, or rclone remote) +- Go 1.26 or later +- Docker, with a reachable daemon, to test, lint, check, or commit: + `script/test` and `script/lint` build the `test` and `lint` phases of the + `Dockerfile`, and `make check` and the pre-commit hook both run them. A + `golangci-lint` installed on `PATH` is not a substitute and is never used on a + host, whatever its version. +- S3-compatible object storage (or local filesystem, or rclone remote) ## development workflow @@ -748,7 +981,8 @@ All changes follow this workflow. No exceptions. 5. Fix linting errors (`make lint`). 6. Update documentation and README as required by the change. 7. Format code (`make fmt`). -8. Run `make check` (lint + fmt-check + test). Fix any issues. Repeat until clean. +8. Run `make check` (lint + fmt-check + test). Fix any issues. Repeat until + clean. 9. Commit on the branch. 10. Merge to `main`. 11. Push. @@ -762,148 +996,131 @@ Repository policies for AI agents are in [`AGENTS.md`](AGENTS.md). This repository adheres to the [Scripts to Rule Them All](https://github.com/github/scripts-to-rule-them-all) standard: normalized scripts in `script/` are the entrypoints for the -development workflow, and the Makefile targets are thin shims that call -them. We provide: +development workflow, and the Makefile targets are thin shims that call them. We +provide: -* `script/bootstrap` — install all development dependencies (go, Go - module download). It deliberately does not install `golangci-lint`; - see `script/lint` below. -* `script/setup` — make a fresh clone ready for development: runs +- `script/bootstrap` — install all development dependencies (Go, Go module + download, and node, yarn and `prettier` for Markdown). Node comes from the + host, or else at a pinned version through `nvm`. A host without Go gets the + `go.mod` version through `script/install-go`, in `.tool/go`, which + `script/bootstrap` itself, the `Makefile`, `script/fmt`, `script/fmt-check`, + `script/precommit` and `script/release` add to their `PATH`. It deliberately + does not install `golangci-lint`; see `script/lint` below. +- `script/setup` — make a fresh clone ready for development: runs `script/bootstrap`, then `script/install-precommit` -* `script/projectname` — print the project name (used for the Docker - image tag) -* `script/version` — print the version string to bake into the binary. - The `Makefile`'s `LDFLAGS` call this; it is the single source of truth - for the version. See [releasing](#releasing) for the rules. -* `script/install-goreleaser` — install the pinned `goreleaser` into - `.tool/bin` from a sha256-verified release archive. Idempotent, and - called by `script/bootstrap`; the release workflow calls it directly - because it needs `goreleaser` but not the Docker daemon - `script/bootstrap` insists on. -* `script/install-go` — install the Go toolchain named by `go.mod`'s - `go` directive into `.tool/go` from a sha256-verified `go.dev` - archive, and put it on `PATH`. Idempotent. Called only by the release - workflow, which needs a host Go for `goreleaser` to shell out to; - nothing else on the release runner does. `actions/setup-go` is not - used because it verifies the downloaded toolchain against no value in - this repo. Bumping Go edits `go.mod`, the checksum in this script, and - the `Dockerfile` `golang` digest together. -* `script/release` — cross-compile and publish the release artifacts - with the pinned `goreleaser`. Refuses a `goreleaser` on `PATH` whose - version is not the pinned one, on the same reasoning as `script/lint`. -* `script/release-snapshot` — the same build with no publishing and no - tagging, into `./dist` -* `script/test` — run the test suite (verbose rerun on failure). This - runs *everything*: there is no separate integration target and no - build-tagged subset held back, so the full round-trip tests in - `internal/vaultik/integration_test.go` run on every invocation. It - passes `-count=1`, which disables Go's test result cache. That is - deliberate and it is not free: on this repo's suite it costs about 11 - seconds on every repeat run (measured, back to back: 0.4s cached - versus 11.6s with `-count=1`). That is the price of the run meaning - anything, because without it an unchanged package prints - `ok (cached)`, which is indistinguishable from a package that - really ran, so the whole suite can report a full set of `ok` lines in - under half a second having executed nothing. The `-timeout` is a hang - backstop rather than a performance budget — it applies per test binary - to test execution only, not to compilation — and is set well above the - slowest package's measured runtime. Its 120s value deliberately - diverges from the 30s `REPO_POLICIES.md` mandates; the reasoning is in - the comment in the script, and issue #101 proposes amending the policy - text. -* `script/lint` — lint by building `Dockerfile.lint`, which runs - `golangci-lint run --config .golangci.yml ./...` as a build step - inside the digest-pinned `golangci-lint` image, so a successful build - *is* a clean lint. Nothing lints on the host, at any version, ever; - the script requires Docker and fails loudly rather than falling back - to a `golangci-lint` on `PATH`. That `FROM` line is the single source - of truth for the linter version — bump it there and nowhere else. +- `script/projectname` — print the project name (used for the Docker image tag) +- `script/version` — print the version string to bake into the binary. The + `Makefile`'s `LDFLAGS` call this. See [releasing](#releasing) for the rules. +- `script/install-goreleaser` — install the pinned `goreleaser` into `.tool/bin` + from a sha256-verified release archive. Idempotent, and called by + `script/bootstrap`; the release workflow calls it directly because it needs + `goreleaser` but not the Docker daemon `script/bootstrap` insists on. +- `script/install-go` — install the Go toolchain named by `go.mod`'s `go` + directive into `.tool/go` from a sha256-verified `go.dev` archive, for Linux + or macOS on amd64 or arm64. Idempotent. On a CI runner it also puts + `.tool/go/bin` on `PATH` for the steps that follow. Called by the release + workflow, which needs a host Go for `goreleaser` to shell out to, and by + `script/bootstrap` on a host without Go. `actions/setup-go` is not used + because it verifies the downloaded toolchain against no value in this repo. + Bumping Go edits `go.mod`, the checksums in this script, and the two `golang` + digests in the `Dockerfile` together. +- `script/release` — cross-compile and publish the release artifacts with the + pinned `goreleaser`. Refuses a `goreleaser` on `PATH` whose version is not the + pinned one, because a different version would build a different release from + the same tag. +- `script/release-snapshot` — the same build with no publishing and no tagging, + into `./dist` +- `script/test` — run the test suite by building the `test` phase of the + `Dockerfile` (verbose rerun on failure). This runs _everything_: there is no + separate integration target and no build-tagged subset held back, so the full + round-trip tests in `internal/vaultik/integration_test.go` run on every + invocation. The 90s `-timeout` is a hang backstop rather than a performance + budget; it applies per test binary, to test execution only. +- `script/lint` — lint by building the `lint` phase of the `Dockerfile`, which + runs `golangci-lint config verify` and then + `golangci-lint run --config .golangci.yml ./...` as build steps in the + digest-pinned `golangci-lint` image. Nothing lints on the host. That `FROM` + line is the only pin of the linter version, and it changes in the same commit + as a re-vendored `.golangci.yml`. +- `script/lint-fix` — apply the linter's autofixes (rewrites files), using the + same pinned image, parsed out of the `lint` phase's `FROM` line. It cannot be + a build step, because fixes have to land in the worktree, so it bind-mounts + the tree into a `docker run` and therefore needs a _local_ daemon. It is a + developer convenience and never a gate: no gate reads its exit status. Run + `make lint` afterwards to find out whether the tree is clean. +- `script/fmt` — format all code (writes): Go with `go fmt`, Markdown with + `prettier` +- `script/fmt-check` — check formatting (read-only). It runs `gofmt` on the + host, over every Go file outside `.tool`, and `prettier --check` over every + Markdown file. +- `script/check` — run `script/test`, `script/lint`, and `script/fmt-check`. +- `script/docker` — build the Docker image tagged via `script/projectname`, + stamped with the version `git describe --tags --always --dirty` gives on the + host, or `unknown` outside a git checkout. The image's build stage depends on + the `lint` and `test` phases, so this lints and tests too. +- `script/cibuild` — CI entrypoint: runs `script/bootstrap`, `script/check`, and + then the same image build as `script/docker`. `.gitea/workflows/check.yml` + runs it on every push. - It takes no arguments, because a build step has no command line to - pass flags to, and it passes a fresh `--build-arg CHECK_EPOCH` on - every invocation so the lint layer cannot be replayed from cache (see - `script/cibuild` below for what that mechanism defends against). To - watch the linter execute, run it as - `BUILDKIT_PROGRESS=plain script/lint` and check that the lint layer - says `RUN … golangci-lint` rather than `CACHED`. + Every `docker build` in these scripts passes `--no-cache`, because on an + unchanged tree a cached check layer is replayed without running and the + build still exits 0. A plain `docker build .` is therefore no evidence that + the checks ran. The cost is that `script/cibuild` runs the `lint` and `test` + phases twice: once in `script/check` and again in the image build. - One container per run means one lint cache and one `golangci-lint` - lock per run, both private to it and discarded with it, so concurrent - runs on one host cannot contaminate or block each other. -* `script/lint-fix` — apply the linter's autofixes (rewrites files), - using the same pinned image, parsed out of `Dockerfile.lint`. It - cannot be a build step, because fixes have to land in the worktree, so - it bind-mounts the tree into a `docker run` and therefore needs a - *local* daemon. It is a developer convenience and never a gate: no - gate reads its exit status. Run `make lint` afterwards to find out - whether the tree is clean. -* `script/fmt` — format all code (writes) -* `script/fmt-check` — check formatting (read-only) -* `script/check` — run `script/test`, `script/lint`, and - `script/fmt-check`. This is authoritative *because* `script/lint` - builds `Dockerfile.lint`: a local `make check` and CI cannot disagree - about lint findings. -* `script/docker` — build the Docker image tagged via - `script/projectname`. Passes a fresh `--build-arg CHECK_EPOCH` for the - same reason `script/cibuild` does, so a local image build cannot be - green on checks it replayed from cache. It builds the *product* image - only, and the product `Dockerfile` has no lint stage, so it does not - lint: a green here means formatted, tested, and it compiles. -* `script/cibuild` — CI entrypoint, and the full gate. Two builds, in - order: `Dockerfile.lint` (the linter, as a build step) and then - `Dockerfile` (`make fmt-check` and `make test` in its builder stage, - then the product image). Either failing fails the script. It runs the - checks in the same containers CI does, from a clean copy of the tree, - so it also catches anything that depends on host state. - `.gitea/workflows/check.yml` runs it on every push to `main` and - `next` and on every pull request against either. - - It passes a fresh `--build-arg CHECK_EPOCH` to each build, unique per - invocation, which both files declare immediately above their check - `RUN`s and expand into each check command. Those layers are keyed on - that value, so a new value re-runs them even on a byte-identical tree, - and a green from this script means the checks executed. Dependency and - module layers sit above the `ARG` and still cache, so a build is not - cold. - - A build that supplies no `CHECK_EPOCH` — a bare `docker build .` or - `docker build -f Dockerfile.lint .` — fails rather than lying. An - unset `ARG` is an empty string and an empty string is a stable cache - key, so without a guard such a build would serve every check layer - from cache, execute nothing, and still exit 0. Each file therefore - asserts the value is non-empty before running anything, and because - failed steps are never cached that assertion fires on every - invocation rather than once. Use `script/lint`, `script/docker` or - `script/cibuild`, which pass the arg; a bare `docker build` is a loud - error. -* `script/precommit` — pre-commit gate: `go mod tidy` + `go fmt` (must - not change files), then `script/check` -* `script/install-precommit` — install the git pre-commit hook that - runs `script/precommit` +- `script/precommit` — pre-commit gate: `go mod tidy` + `go fmt` (must not + change files), then `script/check` +- `script/install-precommit` — install the git pre-commit hook that runs + `script/precommit` ## releasing ### version numbers -The version a binary reports comes from git, not from a constant in a -file. `script/version` decides it, and everything that stamps a binary -agrees with it: +The version a binary reports comes from git, not from a constant in a file. It +is `git describe --tags --always --dirty`, which `script/version` runs for the +`Makefile`, and `script/docker` and `script/cibuild` run themselves: -* `HEAD` is exactly on a tag → that tag with a leading `v` stripped, so - the tag `v1.0.0` produces `vaultik 1.0.0`, matching the archive name - `vaultik_1.0.0_linux_amd64.tar.gz`. `goreleaser` strips the prefix the - same way. -* anything else → `dev-<12 chars of the commit sha>`. -* either, with uncommitted changes to tracked files → a `-dirty` - suffix, because a modified checkout of a tag is not that tag. +- `HEAD` is exactly on a tag → that tag, such as `v1.0.0`. +- a commit after a tag → `--g`. +- no tag reachable → the short commit sha. +- any of these, with uncommitted changes to tracked files → a `-dirty` suffix, + because a modified checkout of a tag is not that tag. -A build that is not a release never names itself like one. `vaultik -version` says so in as many words on a development build, and -`goreleaser --snapshot` stamps the same `dev-` string rather than -inventing the next patch number. If `script/version` cannot be run at -all, `make` stops with an error instead of building an unversioned -binary, and a binary that somehow carries an empty version string still -reports itself as a development build. +A `docker build .` of a clone, with no build arguments, runs the same +`git describe` (without `--dirty`) on the `.git` in its build context, so it +stamps the same value for a clean commit; the build fails if the context carries +`.git` and no version, commit or commit date comes out. `make` outside a git +checkout and `docker build .` without `.git` both stamp `dev`. `script/docker` +and `script/cibuild` stamp `unknown` when they run outside a git checkout. + +A binary built by plain `go install` or `go build` carries no stamped version. +It reports the version Go recorded in it instead: + +- a `go install` of the tag `v1.0.0` → `v1.0.0`. +- a `go build` of an untagged commit → a Go pseudo-version, such as + `v1.0.1-0.20261110231226-0123456789ab`. +- a build where Go recorded no version → `dev`. + +`goreleaser` stamps a release binary with the tag minus its leading `v`, so the +tag `v1.0.0` produces `vaultik 1.0.0`, matching the archive name +`vaultik_1.0.0_linux_amd64.tar.gz`. `goreleaser --snapshot` stamps +`dev-<12 chars of the commit sha>` rather than inventing the next patch number. + +`vaultik version` calls a build a development build when its version is one of +these: + +- `dev` or `unknown`. +- `dev-`. +- the short commit sha. +- `--g`. +- a Go pseudo-version. +- any version with a `-dirty` or `+dirty` suffix. + +Only a plain tag, such as `v1.0.0` or `1.0.0`, is a release. If `script/version` +cannot be run at all, `make` stops with an error instead of building an +unversioned binary. A binary stamped with an empty version reports the version +Go recorded in it; if Go recorded none, it is a development build. ### cutting a release @@ -914,13 +1131,12 @@ git tag -a v1.2.3 -m 'v1.2.3' git push origin v1.2.3 ``` -`.gitea/workflows/release.yml` triggers on `v*` tags, installs a Go -toolchain and the pinned `goreleaser`, and runs `script/release`, which -builds -`linux,darwin × amd64,arm64` archives plus `checksums.txt` and publishes -them to this repository's Gitea releases as a draft. `.goreleaser.yaml` -has a `gitea_urls:` block pointing at `https://git.eeqj.de/api/v1`; -without it `goreleaser` would talk to the GitHub API. +`.gitea/workflows/release.yml` triggers on `v*` tags, installs a Go toolchain +and the pinned `goreleaser`, and runs `script/release`, which builds +`linux,darwin × amd64,arm64` archives plus `checksums.txt` and publishes them to +this repository's Gitea releases as a draft. `.goreleaser.yaml` has a +`gitea_urls:` block pointing at `https://git.eeqj.de/api/v1`; without it +`goreleaser` would talk to the GitHub API. The workflow needs one repository Actions secret: @@ -928,18 +1144,16 @@ The workflow needs one repository Actions secret: | --------------- | ------------------------------------------------------------------------------------------------------- | | `RELEASE_TOKEN` | A Gitea access token with `write:repository` scope, owned by an account that can publish releases here. | -It is passed to `goreleaser` as `GITEA_TOKEN`. The runner's automatic -token is deliberately not used: it is not guaranteed to carry release -write access. +It is passed to `goreleaser` as `GITEA_TOKEN`. The runner's automatic token is +deliberately not used: it is not guaranteed to carry release write access. -The Go toolchain that compiles the released binaries comes from an -`actions/setup-go` step pinned by commit sha, reading its version from -`go.mod` (currently `1.26.1`, the same version the `Dockerfile` builder -stage pins by digest). `goreleaser` shells out to `go` for every -cross-compile, so without that step the release would either fail -outright or ship binaries built by whatever unpinned toolchain the -runner happened to carry — the one unpinned thing in an otherwise -hash-pinned release path. +The Go toolchain that compiles the released binaries is installed by +`script/install-go`, which downloads the version named by `go.mod` (currently +`1.26.1`, the same version the `Dockerfile` builder stage pins by digest) and +refuses the archive unless its sha256 matches the value committed in the script. +`goreleaser` shells out to `go` for every cross-compile, so without that step +the release would either fail outright or ship binaries built by whatever +unpinned toolchain the runner happened to carry. To rehearse the whole build without publishing or tagging anything: @@ -949,9 +1163,9 @@ make release-snapshot Artifacts land in `./dist`, which is gitignored. -Release artifacts are not signed, carry no SBOM, and are not built -reproducibly; the archives contain the binary, `LICENSE`, and -`README.md` only (no shell completions or man page). +Release artifacts are not signed, carry no SBOM, and are not built reproducibly; +the archives contain the binary, `LICENSE`, and `README.md` only (no shell +completions or man page). ## license @@ -959,7 +1173,8 @@ reproducibly; the archives contain the binary, `LICENSE`, and ## author -Made with love and lots of expensive SOTA AI by [sneak](https://sneak.berlin) in Berlin in the summer of 2025. +Made with love and lots of expensive SOTA AI by [sneak](https://sneak.berlin) in +Berlin in the summer of 2025. Released as a free software gift to the world, no strings attached. diff --git a/REPO_POLICIES.md b/REPO_POLICIES.md index bc2f161..20382d1 100644 --- a/REPO_POLICIES.md +++ b/REPO_POLICIES.md @@ -1,6 +1,6 @@ --- title: Repository Policies -last_modified: 2026-07-06 +last_modified: 2026-10-04 --- This document covers repository structure, tooling, and workflow standards. Code @@ -60,17 +60,28 @@ style conventions are in separate documents: prerequisite since nvm requires bash. yarn is then pinned via `corepack prepare yarn@ --activate`. Never install "latest" or "lts"; always exact versions. `script/cibuild` runs the CI build: it changes to the - repo root and runs `docker build .`; the Gitea workflow calls it. Four further - scripts are our own extensions to the standard: `script/check` runs - `script/test`, `script/lint`, and `script/fmt-check`; `script/precommit` is - what the git pre-commit hook runs, and it calls `script/check`; - `script/install-precommit` installs the git pre-commit hook (the `make hooks` - target shims to it); and `script/projectname` (literally that filename) simply - outputs the project's name. Scripts that need the name call - `script/projectname` — e.g. `script/docker` assembles its image tag from it — - so those scripts stay byte-identical across all repos. Repo-type-specific - pre-commit extras (e.g. `go mod tidy` verification in Go repos) belong in - `script/precommit`, not in the hook itself. Model scripts are at + repo root, runs `script/bootstrap`, runs `script/check`, and builds the image + with the version; the Gitea workflow calls it. **`script/cibuild` runs + `script/bootstrap` first**, because the workflow checks out the repo and runs + nothing else, while `script/fmt-check` runs the formatter on the host: on a + pristine checkout with nothing installed the run dies there, after the + containerised gates have passed. **The bootstrap alone is not enough**: + `script/bootstrap` installs node and yarn under nvm and leaves neither on the + `PATH` of the shell that called it, so a bare `yarn` still exits 127. The host + entrypoints that need yarn — `script/fmt` and `script/fmt-check` — therefore + source nvm for the pinned node version before invoking it, exactly as + `script/bootstrap`'s own install step does. A runner carrying nothing but + docker and git then gets through `script/check`. Four further scripts are our + own extensions to the standard: `script/check` runs `script/test`, + `script/lint` and `script/fmt-check`; `script/precommit` is what the git + pre-commit hook runs, and it calls `script/check`; `script/install-precommit` + installs the git pre-commit hook (the `make hooks` target shims to it); and + `script/projectname` (literally that filename) simply outputs the project's + name. Scripts that need the name call `script/projectname` — e.g. + `script/docker` assembles its image tag from it — so those scripts stay + byte-identical across all repos. Repo-type-specific pre-commit extras (e.g. + `go mod tidy` verification in Go repos) belong in `script/precommit`, not in + the hook itself. Model scripts are at `https://git.eeqj.de/sneak/prompts/raw/branch/main/script/`. The README must document the provided scripts in an **Entrypoints** section (see the README requirements below). @@ -89,87 +100,198 @@ style conventions are in separate documents: contributor should be able to understand the entire development workflow by reading the Makefile. -- Every repo should have a `Dockerfile`. All Dockerfiles must run `make check` - as a build step so the build fails if the branch is not green. For non-server - repos, the Dockerfile should bring up a development environment and run - `make check`. For server repos, `make check` should run as an early build - stage before the final image is assembled. Dockerfiles install development - prerequisites by running `script/bootstrap` rather than duplicating installs - inline; COPY `script/` and the dependency manifests (`package.json` + - `yarn.lock`, `go.mod` + `go.sum`, etc.) before running it so the bootstrap - layer stays cached until dependencies change. +- Every repo should have a `Dockerfile`, and it carries the repo's gates: a + `lint` phase and a `test` phase, with the final stage depending on both so the + image cannot be built unless they pass. For non-server repos the final stage + brings up a development environment; for server repos it is the runtime image. + The gate phases and the build stage start from their pinned base images and + install what those images lack either inline, as the canonical Go `Dockerfile` + below does for `git`, or by running `script/bootstrap`, as the `prompts` + repo's own `Dockerfile` does for its yarn packages. The development + environment stage installs development prerequisites by running + `script/bootstrap` rather than duplicating its installs inline. A stage that + runs `script/bootstrap` COPYs `script/` and the dependency manifests + (`package.json` + `yarn.lock`, `go.mod` + `go.sum`, etc.) before running it. -- **Dockerfiles must use a separate lint stage for fail-fast feedback.** Go - repos use a multistage build where linting runs in an independent stage based - on the `golangci/golangci-lint` image (pinned by hash). This stage runs - `make fmt-check` and `make lint` before the full build begins. The build stage - then declares an explicit dependency on the lint stage via - `COPY --from=lint /src/go.sum /dev/null`, which forces BuildKit to complete - linting before proceeding to compilation and tests. This ensures lint failures - surface in seconds rather than minutes, without blocking on dependency - download or compilation in the build stage. +- **Linting and testing run in Docker, as phases of the `Dockerfile`.** There is + no separate lint file. `script/lint` and `script/test` each build one phase + and nothing else: - The standard pattern for a Go repo Dockerfile is: + ```sh + docker build --no-cache --target lint -t "$(script/projectname)-lint" . + docker build --no-cache --target test -t "$(script/projectname)-test" . + ``` + + **A stage that is not the last one in the file is built only when the final + stage's chain depends on it, or when `--target` names it.** That is why the + two gates are always invoked by name here, and why the final stage carries a + `COPY --from=` of a harmless file from each of them: without that edge a + plain `docker build .` builds the last stage alone and exits 0 having linted + and tested nothing. + + **Every `docker build` in `script/` is tagged**, here and in + `script/cibuild` and `script/docker`. An untagged build leaves a dangling + image behind on every invocation, on every developer host and every CI + runner; a tagged one replaces the previous image. + + Inside a phase the tool is invoked directly — `golangci-lint`, `go test`, + `eslint`, `prettier` — never through `make lint` or `script/test`, which are + themselves a `docker build` and would recurse into a daemon that does not + exist in a build step. Formatting is the exception and stays on the host: + `script/fmt` writes the working tree, and `script/fmt-check` is its + read-only twin. + + **No lint verdict may come from a host invocation of the linter.** On a + shared host golangci-lint reads a result cache keyed on file content rather + than location, so a second checkout of the same content is served the first + one's findings, and a host-global lock in `$TMPDIR` makes concurrent runs + exit non-zero with `parallel golangci-lint is running` — a status a caller + cannot tell from real findings. Both have produced wrong verdicts in this + org, in both directions. A container has its own cache, its own `TMPDIR` and + a digest-pinned binary, so neither is reachable. + +- **Any build that runs checks is built with `--no-cache`.** Docker invalidates + a `COPY` layer only when the copied content changes, so on an unchanged tree + the check `RUN` is served from cache, nothing executes, and the build still + exits 0. Every `docker build` in `script/` therefore passes `--no-cache`: + `script/lint`, `script/test`, `script/cibuild` and `script/docker` are the + four, and there is no fifth — `script/check` runs the two gate phases and + `script/fmt-check`, and builds no image of its own. A bare `docker build .` is + not evidence that anything ran: a sub-second build reporting success is a + cache hit, not a result. Never invalidate by pruning — `docker builder prune` + and friends destroy a build cache shared with every other build on the host. + When a check is added or changed, prove it works by planting a defect it must + catch and watching the run fail on it, then revert the defect. A green run + alone shows neither that the check ran nor that it covers what it should. + +- **The gate phases are separate stages, and the build stage depends on both.** + The lint phase is based on the `golangci/golangci-lint` image (pinned by + hash), so lint failures surface in seconds rather than after a full compile, + and the test phase is based on the Debian Go image. The canonical Go repo + `Dockerfile`: ```dockerfile - # Lint stage — fast feedback on formatting and lint issues + # Lint phase # golangci/golangci-lint:v2.x.x, YYYY-MM-DD FROM golangci/golangci-lint@sha256:... AS lint WORKDIR /src COPY go.mod go.sum ./ RUN go mod download COPY . . - RUN make fmt-check - RUN make lint + RUN golangci-lint run --config .golangci.yml ./... - # Build stage - # golang:1.x-alpine, YYYY-MM-DD - FROM golang@sha256:... AS builder + # Test phase. -race needs cgo and so a C compiler, which the Debian Go + # image ships and the alpine one does not. + # golang:1.x, YYYY-MM-DD + FROM golang@sha256:... AS test WORKDIR /src - - # Force BuildKit to run the lint stage before proceeding - COPY --from=lint /src/go.sum /dev/null - COPY go.mod go.sum ./ RUN go mod download COPY . . - RUN make test + RUN go test -timeout 90s -race -cover ./... || \ + { echo "--- Rerunning with -v for details ---"; \ + go test -timeout 90s -race -v ./...; exit 1; } - ARG VERSION=dev - RUN CGO_ENABLED=0 go build -trimpath \ - -ldflags="-s -w -X main.Version=${VERSION}" \ - -o /app ./cmd/app/ + # Build stage. Nothing is wanted from either phase above; the copies + # are what make BuildKit build them first, so this stage cannot run + # unless lint and test passed. + # golang:1.x-alpine, YYYY-MM-DD + FROM golang@sha256:... AS builder + COPY --from=lint /src/go.sum /dev/null + COPY --from=test /src/go.sum /dev/null + RUN apk add --no-cache git + # A tar-stream context keeps the sender's file owners, which git refuses. + RUN git config --system --add safe.directory /src + WORKDIR /src + COPY go.mod go.sum ./ + RUN go mod download + COPY . . - # Runtime stage + # The VERSION build arg when one is given, otherwise + # `git describe --tags --always` on the .git in the build context. With + # .git present, a version that is still empty, dev or unknown fails the + # build: git is missing or could not read the checkout. + ARG VERSION + RUN VERSION="${VERSION:-$(git describe --tags --always)}"; \ + if [ -e .git ]; then \ + case "$VERSION" in ""|dev|unknown) \ + echo "version is '$VERSION' although .git is present" >&2; \ + exit 1 ;; \ + esac; \ + fi; \ + CGO_ENABLED=0 go build -trimpath \ + -ldflags="-s -w -X main.Version=${VERSION}" \ + -o /app ./cmd/app/ + + # Runtime stage, and the last one FROM alpine@sha256:... COPY --from=builder /app /usr/local/bin/app ENTRYPOINT ["app"] ``` Key points: - - The lint stage uses the `golangci/golangci-lint` image directly (it - includes both Go and the linter), so there is no need to install the - linter separately. - - `COPY --from=lint /src/go.sum /dev/null` is a no-op file copy that creates - a stage dependency. BuildKit runs stages in parallel by default; without - this line, the build stage would not wait for lint to finish and a lint - failure might not fail the overall build. + - The lint phase uses the `golangci/golangci-lint` image directly (it has + both Go and the linter), so nothing needs installing. + - `COPY --from= /src/go.sum /dev/null` is a no-op copy whose only + purpose is the ordering edge. BuildKit runs stages in parallel by default, + and a stage nothing depends on is not built at all, so without these two + lines a red gate would not fail the build. + - Keep the runtime stage last, and if you add a stage after it, give it the + same two copies. A plain `docker build .` builds the last stage's chain + and nothing else. - If the project uses `//go:embed` directives that reference build artifacts - (e.g. a web frontend compiled in a separate stage), the lint stage must + (e.g. a web frontend compiled in a separate stage), the lint phase must create placeholder files so the embed directives resolve. Example: `RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css`. - The lint stage should not depend on the actual build output — it exists to - fail fast. - - If the project requires CGO or system libraries for linting (e.g. - `vips-dev`), install them in the lint stage with `apk add`. - - The build stage runs `make test` after compilation setup. Tests run in the - build stage, not the lint stage, because they may require compiled - artifacts or heavier dependencies. + - If the project requires CGO or system libraries for linting, install them + in the lint phase. The `golangci/golangci-lint` image is Debian-based and + has no `apk`, so install with `apt-get` under the Debian package name + (`libvips-dev`, where alpine says `vips-dev`), and delete the package + lists in the same `RUN`, so the layer does not keep them: + + ```dockerfile + RUN apt-get update \ + && apt-get install -y --no-install-recommends libvips-dev \ + && rm -rf /var/lib/apt/lists/* + ``` + + - `.dockerignore` lets `.git` into the build context. It keeps out every git + `config` at any depth (`**/.git/config`, `**/.git/modules/**/config`): the + repository's own, each submodule's under `.git/modules/`, and that of a + submodule keeping its own `.git` directory. `git describe` does not need + them, and each can hold a credential: a password in a remote URL, or the + token the CI checkout step stores there. A submodule whose name has a + `config` segment (`config`, `deploy/config`, `config/lib`) loses its whole + git directory to `**/.git/modules/**/config`, and Go's version stamping + then fails the build: give it a name without that segment + (`git submodule add --name`). The stage that compiles has `git` (the + Debian Go image has it; an alpine one needs `apk add --no-cache git`) and + takes the version from the `VERSION` build argument when one is given, + otherwise from `git describe --tags --always`. That gives the tag on a + tagged commit; on a later commit, the tag, the number of commits since it + and the short commit (`v1.2.3-4-gabc1234`); and the short commit when no + tag is reachable. The stage that compiles also marks its working directory + safe for git (`git config --system --add safe.directory /src`): a context + sent as a tar stream keeps the sender's file owners, and git refuses a + checkout owned by another user, so the version would come out empty. + `ARG VERSION` has no default, and the build fails if the context carries + `.git` and the version still comes out empty, `dev` or `unknown`. A plain + `docker build .` with no build arguments must succeed; a Dockerfile that + refuses an empty build argument drops that refusal and keeps the argument. - Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that - runs `script/cibuild` (which runs `docker build .`) on push. Since the - Dockerfile already runs `make check`, a successful build implies all checks - pass. + runs `script/cibuild` on push, and checks out the repo as its only other step. + That script bootstraps, runs the gate phases, and then builds the image, so a + successful run means every check passed; a bare `docker build .` does not + carry the same guarantee, because its gate phases may come from the cache. The + image build is uncached and so runs the gate phases a second time. That is the + price of the rule above, and it is worth paying: the image that ships is built + from a run of its own gates rather than from a cache entry. A separate + workflow limited to `main` by a `branches` list under `on: push` cannot be + checked by review: to try a change to it, add the feature branch to that list + and push, then remove the branch from the list again before merging. Keep any + job in it that publishes behind `if: github.ref_name == 'main'`, so the run + from the feature branch publishes nothing. - Use platform-standard formatters: `black` for Python, `prettier` for JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with @@ -189,14 +311,21 @@ style conventions are in separate documents: module under test to verify it compiles/parses. There is no excuse for `make test` to be a no-op. -- `make test` must complete in under 20 seconds. Add a 30-second timeout in the - Makefile. +- `make test` must complete in under 60 seconds. That is the hard cap, and a + suite that exceeds it fails. Under 20 seconds is the target. A suite between + 20 and 60 seconds is still green, but the overage must be filed as an + improvement bug against that repo. Add a 90-second timeout to the test + invocation (`go test -timeout 90s`). The backstop deliberately sits above the + hard cap so that it catches a genuinely hung test rather than a merely slow + one. -- **`make test` should use the conditional verbose rerun pattern.** Run tests - without `-v` (verbose) first. If tests fail, automatically rerun with `-v` to - show full output. This keeps CI logs and `docker build` output clean on - success (just package/suite summaries) while providing full diagnostic detail - on failure (every test case, every assertion). The general shell pattern: +- **The test command should use the conditional verbose rerun pattern.** Run + tests without `-v` (verbose) first. If tests fail, automatically rerun with + `-v` to show full output. This keeps CI logs and `docker build` output clean + on success (just package/suite summaries) while providing full diagnostic + detail on failure (every test case, every assertion). The command lives in the + `test` phase of the `Dockerfile`, since `script/test` builds that phase; the + Makefile form below is the same pattern for any repo-local invocation: ```makefile test: @@ -209,11 +338,26 @@ style conventions are in separate documents: ```makefile test: - @go test -timeout 30s -race -cover ./... || \ + @go test -count=1 -timeout 90s -race -cover ./... || \ { echo "--- Rerunning with -v for details ---"; \ - go test -timeout 30s -race -v ./...; exit 1; } + go test -count=1 -timeout 90s -race -v ./...; exit 1; } ``` + `-count=1` is required on both invocations: it defeats Go's test _result_ + cache, so neither run can report a stored pass in place of running the + tests. It leaves the build cache alone, so it costs the runtime of the suite + and no recompilation. + + That cache is Go's own, separate from Docker's layer cache. Go stores a + passing result in its cache directory (`GOCACHE`), and when the same tests + run again on unchanged code it prints that result, marked `(cached)`, + without running them. That matters on a developer's machine, where this + target runs and the directory lasts from one run to the next. The `test` + phase of the `Dockerfile` needs no `-count=1`: its base image holds no + result for this repo's tests and nothing before its `go test` step runs a + test, so there is nothing to replay. `--no-cache` (above) is what makes that + step run on an unchanged tree. + Python example: ```makefile @@ -239,10 +383,84 @@ style conventions are in separate documents: must be in `.gitignore`. No exceptions. - `.gitignore` should be comprehensive from the start: OS files (`.DS_Store`), - editor files (`.swp`, `*~`), language build artifacts, and `node_modules/`. - Fetch the standard `.gitignore` from - `https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when setting up - a new repo. + editor files (`.swp`, `*~`), in-repo agent scratch directories (`.claude/`), + language build artifacts, and `node_modules/`. Fetch the standard `.gitignore` + from `https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when + setting up a new repo. These patterns are written to `.gitignore`'s own + semantics, in which an unanchored pattern already matches at every depth; they + are not a `.dockerignore` and must not be transplanted into one unmodified. + +- **`.dockerignore` does not use `.gitignore` semantics, and copying patterns + across unmodified leaves secrets in the build context.** Docker matches with + `moby/patternmatcher`: `filepath.Match` semantics plus a `**` extension, so + `*` does not cross `/` and a pattern without a leading `**/` is anchored at + the build-context root. A `.dockerignore` listing `.env`, `*.pem` and `*.key` + therefore excludes only the copies at the repository root, while `config/.env` + and `certs/server.key` still reach the context and can land in an image layer + — which is more dangerous than a short file with no secret patterns at all, + because it reads as solved and stops anyone looking. Give every + depth-independent pattern the `**/` prefix and leave only genuinely + root-anchored entries unprefixed: `.claude`, and the repo's own host-built + binary, written `/myapp` and never `**/myapp`, which would also match + `cmd/myapp/` and delete the package directory from the context. Matching is + case-sensitive, and an ALL-CAPS twin per pattern still misses `Server.Key`, so + secret names use character ranges — `**/*.[kK][eE][yY]`, `**/*.[pP][eE][mM]`, + and likewise for `.envrc` and the extensionless SSH keys. Where such a pattern + also catches something the build needs, re-include it with a negation + (`!docs/example.env`); deleting the pattern reopens the exposure for every + other file it covers. Fetch the standard `.dockerignore` from + `https://git.eeqj.de/sneak/prompts/raw/branch/main/.dockerignore` and extend + it with the repo's own artifacts. + +- **In-repo agent scratch belongs in both files, written to each file's own + semantics.** `.claude/` holds one worktree per in-flight agent — an entire + additional checkout of the repo — so under `COPY . .` the build context + inflates by a multiple of the repo and another session's unreviewed work can + be copied into an image layer. In `.gitignore` the entry is `.claude/`, + unanchored. In `.dockerignore` it is `.claude`, anchored and with **no** `**/` + prefix, because the prefixed form would also delete any nested directory of + that name from the build. Anchoring carries a known gap that the canonical + `.dockerignore` states in its own comment, since consuming repos receive the + file and not the tracker: the directory is created in the agent's working + directory, so a repo running agents in subdirectories still ships + `services/api/.claude/` and must add its own anchored entry there. + +- **A plain `docker build .` of a clone stamps the version that + `git describe --tags --always` gives**, derived from the `.git` in the build + context as the canonical `Dockerfile` above shows. Without its failure check, + a missing `git` or an unreadable checkout would leave `-X main.Version=` empty + and the build would still exit 0. `script/docker` and `script/cibuild` pass + the version they compute on the host; it takes precedence. They do this + byte-identically across repos: + + ```sh + # Own line: a failing command substitution inside an argument does not + # trip `set -e`, so the inline form degrades to an empty constant. + version="$(git describe --tags --always --dirty 2>/dev/null || true)" + [ -n "$version" ] || version="unknown" + docker build --no-cache \ + --build-arg VERSION="$version" \ + -t "$(script/projectname)" . + ``` + + `--always` makes an untagged repo yield an abbreviated commit hash rather + than failing, and the `[ -n "$version" ]` line is the single place the + fallback is applied — a live check that fires on a build from an export with + no `.git` and on a repository with no commits yet. Do not fold it into the + substitution as `|| echo unknown`, which makes the guard unreachable. The + Dockerfile's side is `ARG VERSION` in the stage that compiles, declared + there because `ARG` is stage-scoped; passing `VERSION` to a repo whose + Dockerfile declares no such `ARG` is ignored and costs nothing, which is why + the scripts stay byte-identical. One consequence for CI: the standard + checkout action clones shallow and fetches no tags, so a repo that embeds a + tag-derived version must set `fetch-depth: 0` on its checkout step. + +- **Verify `.dockerignore` by enumerating the image, not by reading the + patterns.** Plant files at the root _and_ at least two directories deep, build + a probe image that does `COPY . .`, and list what actually landed + (`docker run --rm --entrypoint find IMAGE /app`). The `transferring context` + size is not a substitute: a nested secret is a few bytes, and BuildKit + transfers only the delta from the previous build. - **No build artifacts in version control.** Code-derived data (compiled bundles, minified output, generated assets) must never be committed to the @@ -258,9 +476,56 @@ style conventions are in separate documents: - Make all changes on a feature branch. You can do whatever you want on a feature branch. -- `.golangci.yml` is standardized and must _NEVER_ be modified by an agent, only - manually by the user. Fetch from - `https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml`. +- `.golangci.yml` is standardized. The vendored copy in a consuming repo must + _NEVER_ be modified by an agent: fetch it from + `https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml` and keep it + byte-identical, so that no repo can quietly loosen its own linting. Linter + configuration changes are made to the canonical copy in the `prompts` repo and + reach consuming repos by re-vendoring; an agent may open a PR against + canonical, which only the user merges. One list is exempt from byte-identity, + because it cannot be written once for every repo: the `deny` list of the + `test-support` depguard rule, where a repo names its own test-support packages + by full import path. A repo adds entries there and changes nothing else, and a + re-vendor carries its entries forward. The canonical golangci-lint version is + v2.14.0 (released 2026-09-24), pinned as the digest of the lint phase's base + image + (`golangci/golangci-lint@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f`, + which reports `2.14.0 built with go1.27.0 from 114493f9`). A module's `go` + directive must not name a newer Go minor version than the one golangci-lint + was built with, or golangci-lint refuses to lint it: this release lints + `go 1.27.1` but not `go 1.28`. That digest is the only pin, since no repo + installs golangci-lint on the host. A repo sets the lint phase digest to the + one named here and re-vendors `.golangci.yml` in the same commit, whichever of + the two prompted the change: the canonical copy can name linters that an older + golangci-lint rejects, and a newer golangci-lint can add linters that + `default: all` switches on until the canonical copy disables them. + +- **`script/bootstrap` installs a pinned tool by comparing versions, never by + testing presence.** An `if ! command -v ; then install; fi` guard tests + `PATH` only, so on an already-provisioned machine the pin is inert and a + version bump is a silent no-op — while the Dockerfile, installing into a clean + image, gets the pinned version, so a local `make check` and `make docker` can + disagree about what the tool even is. The canonical form: + - compares the installed version against the pin over the **whole** version + token; a parser that stops at the first `-` reports `2.12.2` for a host + running `2.12.2-rc1` and skips the install; + - treats absent, non-zero, empty or unrecognised `--version` output as a + mismatch, so the failure direction is a redundant install and never a + skipped one; + - after installing, re-resolves the binary the way callers do — `hash -r`, + then through `PATH`, not through the directory the installer wrote to — + and fails naming the resolved path, since an install that a shadowing + binary hides succeeds while changing nothing any caller sees; + - is actually called, and prints the version on both success paths: a + function defined and never invoked has the same exit status and the same + empty output as one that worked. + + Keep it POSIX sh: no arrays, no `[[`, no `grep -P`. + + A Go tool a repo needs on the host is installed with `go install` pinned to + a commit hash (`go install @`). It is never tracked as + a `go.mod` tool dependency or through a `tools.go` file, either of which + pulls the tool's own dependencies into the repo's `go.mod` and `go.sum`. - When pinning images or packages by hash, add a comment above the reference with the version and date (YYYY-MM-DD). @@ -374,12 +639,14 @@ style conventions are in separate documents: settings. - Avoid putting files in the repo root unless necessary. Root should contain - only project-level config files (`README.md`, `Makefile`, `Dockerfile`, - `LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`, and - language-specific config). Everything else goes in a subdirectory. Canonical - subdirectory names: + only project-level config files (`README.md`, `AGENTS.md`, `Makefile`, + `Dockerfile`, `LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`, + and language-specific config). Everything else goes in a subdirectory. + Canonical subdirectory names: - `bin/` — executable scripts and tools - - `cmd/` — Go command entrypoints + - `cmd/` — Go command entrypoints; thin only: one `main.go` per binary whose + body is a single call into `internal/` or `pkg/`, no project logic in + `cmd/` - `configs/` — configuration templates and examples - `deploy/` — deployment manifests (k8s, compose, terraform) - `docs/` — documentation and markdown (README.md stays in root) @@ -406,3 +673,7 @@ style conventions are in separate documents: - Go: `go.mod`, `go.sum`, `.golangci.yml` - JS: `package.json`, `yarn.lock`, `.prettierrc`, `.prettierignore` - Python: `pyproject.toml` + +- Guidance for coding agents lives in one `AGENTS.md` at the repository root. It + is never committed under a file or directory named after one agent tool, such + as `CLAUDE.md` or `.claude/`, and never split into separate memory files. diff --git a/TODO.md b/TODO.md deleted file mode 100644 index feb0f2a..0000000 --- a/TODO.md +++ /dev/null @@ -1,696 +0,0 @@ -# Workflow - -* branch (from `main`) -* do the work in Next Step -* move Next Step to the top of Completed Steps -* move the top item of Future Steps into Next Step -* commit (`TODO.md` changes in the same commit as the work) -* merge to `main` if the branch is not protected, otherwise open a PR -* push - -# Status - -pre-1.0 - -# Next Step - -Define the remaining scope for the first tagged release under the 1.0.0 -milestone, then cut that tag. The mechanism to cut it now exists and is -exercised; what is left is the scope decision, which is the owner's. -This step deliberately names one version number: it previously said -"cut v0.1.0" while the `Makefile` baked in `1.0.0-rc.1` and the issue -milestone said 1.0.0, and three different answers to "what is the next -release" is exactly the contradiction -[issue #65](https://git.eeqj.de/sneak/vaultik/issues/65) was filed over. - -# Completed Steps - -- 2026-09-22: Routed the last direct-to-stdout command output through - `internal/ui` - ([issue #149](https://git.eeqj.de/sneak/vaultik/issues/149)). The - `version`, `info`, `remote info`, `config`, and `database delete` - commands wrote plain text straight to stdout, so they were unstyled and - ignored `--quiet`. Output now falls in two buckets, both governed by - `internal/ui`: status lines and confirmations go through its message - methods (styled, and `--quiet` silences them), while the data a command - exists to produce — the reports, the `snapshot list` table, `config get` - values, and the `--json` documents — is written plain. `--quiet` - silences the human reports and tables but never the `config get` value - or the `--json` documents, which a script depends on, and the - `database delete` confirmation prompt is always shown. The README - output-style section now states this rule. - -- 2026-09-22: Validated blob hashes, offsets and lengths read back from - the destination before using them - ([issue #155](https://git.eeqj.de/sneak/vaultik/issues/155)). A blob - hash taken from the downloaded database or the store listing was - trusted unchecked, so a hostile remote could drive a decrypted blob to - be written outside the cache directory (a hash like `aa/../../etc`) or - crash a command with a short or negative value. `blobDiskCache.path` - now refuses any key containing a path separator, and `ReadAt` rejects a - negative offset or length and bounds with `length > size-offset` so a - sum cannot overflow past the check. A new `isBlobHash` helper (a plain - function, not a method — the packer stores `temp-placeholder-{uuid}` as - a hash) gates `FetchBlob`, shallow and deep verify; the `blobs/` and - `metadata/` listings skip a non-conforming name with a warning; and - short-hash prefixes in log and error text go through a `shortHash` - helper that cannot panic. `verify`'s chunk reader also rejects a - negative `blob_chunks` length and streams the chunk instead of - allocating a database-supplied size. `restore.go` and - `internal/database` were left untouched to avoid colliding with the - in-flight [issue #156](https://git.eeqj.de/sneak/vaultik/issues/156) - work; the cache-path and `FetchBlob` guards already stop the unsafe - write and fetch, so restore's own `buildBlobIndexes` early check is - deferred as fail-fast defense in depth. - -- 2026-09-21: Stopped an interrupted blob upload from making a later - backup deduplicate against data that was never stored - ([issue #148](https://git.eeqj.de/sneak/vaultik/issues/148)). The - packer commits a blob's `chunks`, `blob_chunks`, and `blobs` rows - before the upload is attempted, so a failed upload left chunk rows - behind and the next run skipped re-uploading them, producing a - snapshot that reported success but could not be restored. A run now - deduplicates only against chunks held by a blob whose `uploaded_ts` is - set, and at startup drops any un-uploaded blob rows (and the chunks - they orphan) so the affected data is re-chunked and re-uploaded. Blobs - recorded with no remote backend are marked uploaded so this invariant - holds uniformly. - -- 2026-09-22: Made restore refuse any snapshot path that would write - outside the target directory - ([issue #154](https://git.eeqj.de/sneak/vaultik/issues/154)). - `restoreFile` and `verifyRestoredFiles` joined the stored path onto the - target with no containment check, so a `..` segment or an absolute path - escaped the target and a restored symlink could redirect a later child - write anywhere on disk. Every stored path is now rejected unless - `filepath.IsLocal` accepts it with the leading separator removed, and - each existing ancestor directory below the target is `Lstat`ed to refuse - descending through a symlink; honest symlinks pointing outside the tree - are still written verbatim. age decryption proves a snapshot is - readable, not honest, and restore usually runs as root. - -- 2026-09-21: Stopped `--json` from silencing stderr diagnostics - ([issue #112](https://git.eeqj.de/sneak/vaultik/issues/112)). `--json` - used to be folded into `Quiet`, which pinned the log level to `WARN`, - so `prune --json` gave a machine consumer no record of the local index - rows it deleted even under `--verbose`. `--json` now quiets only the - stdout UI (the JSON document must stay clean, per - [issue #108](https://git.eeqj.de/sneak/vaultik/issues/108)); the stderr - log level follows `--verbose`/`--debug` again. The coupling was - removed the same way for `snapshot verify`, `snapshot remove`, and - `remote info`, which carried it for the same outdated reason. - -- 2026-09-21: Stopped `prune` from reporting a failed row count as 0 - ([issue #96](https://git.eeqj.de/sneak/vaultik/issues/96)). The seven - `getTableCount` reads in `PruneDatabase` discarded their error, so a - query that could not run became a plausible `0` and the before/after - delta computed from it looked like real work. Each read now logs at - warn on failure and renders as `unknown`, never `0`, so an empty table - is distinguishable from one that could not be queried. The counts have - no `--json` representation — under `--json` the summary is suppressed - entirely — so nothing there can show a false `0`. - -- 2026-09-21: Made the s3 storage backend report a missing object as - `storage.ErrNotFound`, like the `file` and `rclone` backends and as the - `Storer` interface documents. `S3Storer.Get` and `Stat` returned the raw - AWS SDK error, so `errors.Is(err, storage.ErrNotFound)` was false on s3 - and callers branched differently per backend. Added a small `s3.IsNotFound` - helper (reused by `HeadObject`) and a test that a missing key maps to - `ErrNotFound` - ([issue #129](https://git.eeqj.de/sneak/vaultik/issues/129)). -- 2026-09-21: Fixed `verify --deep` reporting healthy snapshots as - corrupt. Its final blob-integrity check hashed the encrypted - downloaded bytes with a single SHA256 and compared that to the blob - ID, which is the double SHA256 of the plaintext, so the two could - never match. It now hashes the decompressed plaintext and compares the - double SHA256. Added a test that backs up a real snapshot, deep-verifies - it, then flips a byte in one stored blob and confirms deep verification - then fails - ([issue #131](https://git.eeqj.de/sneak/vaultik/issues/131)). - -- 2026-09-21: Made `snapshot create` VACUUM the per-snapshot metadata - database through the `modernc.org/sqlite` driver instead of shelling - out to the external `sqlite` command-line binary (issue #120). A - backup no longer needs that binary on `PATH`, so `make check` passes - on a stock `go install` host; `script/bootstrap` and the `Dockerfile` - (both the test-build and the shipped runtime stage) no longer install - it, and a new test asserts the uploaded database keeps no pages from - deleted rows. Dropped the now-false note on the 2026-08-07 entry below - that said bootstrap installs it. -- 2026-09-21: Made `.gitea/workflows/check.yml` run on pushes to `main` - and `next` and on pull requests against either, so unit PRs (whose - base is `next`) and `next` itself get a CI run instead of relying on a - local `make check` - ([issue #122](https://git.eeqj.de/sneak/vaultik/issues/122)). - -- 2026-09-21: Hash-verified the Go toolchain in the release workflow - ([issue #105](https://git.eeqj.de/sneak/vaultik/issues/105)). New - `script/install-go` downloads the exact `go.dev` archive for `go.mod`'s - `go` directive and refuses it unless its sha256 matches a value - committed in the script; `.gitea/workflows/release.yml` calls it - instead of `actions/setup-go`, which verified the downloaded toolchain - against nothing in the repo. `GOTOOLCHAIN: local` on the release step - keeps that exact compiler from auto-switching. Bumping Go now touches - `go.mod`, the checksum, and the `Dockerfile` `golang` digest together. - -- 2026-09-21: Collapsed the two duration parsers into one and fixed the - `--older-than` months example - ([issue #123](https://git.eeqj.de/sneak/vaultik/issues/123)). Two - functions named `parseDuration` existed with different grammars; - `snapshot purge --older-than` and `--keep-newer-than` both already went - through the one in `internal/vaultik`, while the richer copy in - `internal/cli/duration.go` was reachable only from its own test. Kept - the live-path parser and deleted the unused one, so no flag's accepted - grammar changes. The trap the issue was filed over: `README.md` - documented `6m` as the months example for `--older-than`, but `m` is - minutes, so the documented command deleted every snapshot older than - six minutes on a destructive flag. Corrected the doc to `6mo` and put - both flags' help text on one example list that states `m` is minutes - and `mo` is months. The surviving parser now rejects negatives, which - it previously accepted (`-5h`) or silently made positive (`-5d`). - Table-driven tests cover every unit, `6m` as six minutes, `6mo` as 180 - days, and rejection of a bare number, an unknown unit, and a negative. - -- 2026-08-10: Moved every lint run into its own container, as a build - step ([issue #113](https://git.eeqj.de/sneak/vaultik/issues/113)). - New root `Dockerfile.lint`, built by `script/lint`, runs - `golangci-lint run --config .golangci.yml ./...` as a `RUN` - instruction in the digest-pinned `golangci/golangci-lint` image: a - successful build of that file *is* a clean lint, and it works even - where the daemon is remote and bind mounts are impossible. That - `FROM` line is now the only pin of the linter version in the repo. - - This supersedes the per-worktree cache isolation landed for - [issue #99](https://git.eeqj.de/sneak/vaultik/issues/99). Isolation - fixed cross-worktree contamination but not lock contention — two - concurrent runs with entirely separate cache directories still - collided. A container per run has its own cache and its own lock, so - the whole class is gone, and with it the per-worktree cache - machinery, the lock-retry loop, and `script/lint-audit`, which - existed to catch replayed findings from a cache that no longer - exists. The host lint path went too: no escape hatch, no - `VAULTIK_LINT_IN_CONTAINER`, no version detection. Nothing lints on - the host at any version. - - A cached build lints nothing, so the same `CHECK_EPOCH` mechanism the - product `Dockerfile` already used is what makes the green mean - something: `ARG CHECK_EPOCH` with no default below the module layers, - a `RUN [ -n "$CHECK_EPOCH" ] || exit 1` guard, the value expanded - into each check command, and a fresh `$(date +%s%N)$$` per invocation - computed as a bare assignment. `cmd/vaultik/lintdocker_test.go` - parses both Dockerfiles and both scripts and fails if any part of - that is dropped, because every way of losing it is silent. No test - asserts that no script runs the host linter: `script/lint` is the one - lint entry point and runs `golangci-lint` only inside the container, - and keeping it that way is a review matter, not something a test - proves. - - The product `Dockerfile` lost its lint stage rather than gaining a - second linter pin: `make lint` is now `docker build`, so the stage - would have been docker-in-docker with no daemon, and calling - `golangci-lint` directly there would have restored the two-pins drift - of [issue #78](https://git.eeqj.de/sneak/vaultik/issues/78). - `make fmt-check` moved beside `make test` in the builder stage, and - `script/cibuild` now builds `Dockerfile.lint` and then `Dockerfile`, - each with its own fresh epoch. Consequence, stated rather than left - to be found: `script/docker` builds the product image only and no - longer lints; the gates are `script/check` and `script/cibuild`. - - `golangci-lint config verify` runs as its own epoch-keyed layer, - above the lint. `golangci-lint run` rejects a config it cannot parse - but silently ignores an unknown top-level *key*: renaming `linters:` - to `linterz:` discarded `default: all` and every threshold and still - exited 0 on a tree the real config fails. `config verify` catches - that, and it does so with the network off at this pin — checked under - `docker run --network none`, not assumed. An earlier revision omitted - it on the claim that it fetches its schema over live HTTPS; that - claim was false at v2.12.2. - - `script/lint-fix` is kept, reimplemented as a - bind-mounted `docker run` against the image parsed out of - `Dockerfile.lint` — it cannot be a build step, because fixes have to - land in the worktree — and marked in its header as a developer - convenience that no gate reads. - -- 2026-08-09: Finished the `--json` stdout contract and gave `make build` - a rule ([issue #108](https://git.eeqj.de/sneak/vaultik/issues/108), - [issue #110](https://git.eeqj.de/sneak/vaultik/issues/110)). Two - unrelated defects of the same shape — a command reporting something it - did not do — landed together because both are small. - - `CleanupLocalSnapshots` wrote three prose lines to stdout with no - `--json` awareness, covering every branch of the function, so no input - avoided them and `vaultik prune --json | jq` failed even after - [issue #106](https://git.eeqj.de/sneak/vaultik/issues/106) removed the - banner. `-q` never helped either: `printlnStdout` and `stdoutf` write - straight to `Vaultik.Stdout` and never consult `Vaultik.UI`, which is - what `SetQuiet` affects. The issue offered three fixes and asked for a - decision. Taken: thread `*PruneOptions` into the function and gate each - write on `!opts.JSON`, matching `PruneBlobs` (its sibling phase, which - already takes the same struct), `RemoveSnapshot` and `remote info`, so - the package has one pattern rather than two. Rejected: moving the lines - to `log.Info`, because the logger's default level is `slog.LevelWarn`, - so that would not relocate them to stderr — it would delete them from a - plain `vaultik prune`, and the removal of rows from the local index is - not something to narrate only under `--verbose`. Also rejected: putting - the stale-record count into `PruneBlobsResult`, whose every field is - blob-scoped and which is produced by the later phase; a prune document - covering both phases is a reasonable thing to want, but it is a schema - design question and not a stream-hygiene fix. The narration is - duplicated as `log.Info` records, which `PruneBlobs` already does - alongside its own prints, so the events survive on stderr for anyone - running `--verbose`. - - `make build` printed "Nothing to be done for 'build'" and exited 0 - without producing a binary: `build` was listed in `.PHONY` with no - `build:` rule anywhere, and declaring a name phony is exactly what - converts make's "No rule to make target" error into a silent success. - Fixed with `build: vaultik`, keeping `vaultik:` as the file rule. The - audit the issue asked for covers all 19 `.PHONY` names; `build` was the - only one without a rule, and `vaultik` is correctly absent from - `.PHONY`, being a real file target. - - Tests, each verified to fail with the fix reverted rather than assumed - to: `CleanupLocalSnapshots` leaves stdout untouched under `--json` in - all three branches (stale records, none, empty index) and still emits - every line without it, so the guard cannot be satisfied by deleting the - output; `prune --json` run end to end through `Entry`, cobra and fx - over the process's real stdout descriptor against a `file://` store, - asserting exactly one JSON document, in both the stale and non-stale - branches; and a parse of the `Makefile` asserting every `.PHONY` name - has a rule and that `build` reaches the rule that produces the binary, - which keeps the audit true for names added later. That last one is a - parse rather than an invocation of `make`, since `make test` is what - runs it and shelling back into `make build` would nest a build inside - the test run. The property a parse cannot establish — that the recipe - still fails when the build fails — was verified by hand against a - deliberately broken tree: `make build` exits 2 and produces nothing. - `cmd/vaultik` gains its first test file, so `make test` now reports 16 - packages `ok` where it reported 15. - -- 2026-08-09: Stopped the startup banner from contaminating `--json` - documents ([issue #106](https://git.eeqj.de/sneak/vaultik/issues/106)). - `Entry` writes the banner to stdout before cobra parses anything, and - the flag scan that suppresses it knew `--quiet`, `-q` and `--cron` but - not `--json`, so every `--json` document arrived behind two lines of - prose and a blank line, and `vaultik snapshot list --json | jq` failed. - With the logger already on stderr from - [issue #82](https://git.eeqj.de/sneak/vaultik/issues/82), this was the - last writer that could put something on stdout that the caller did not - ask for. The design question the issue raised — extend the raw-argv - scan, or move the banner after parsing — is answered in favour of the - scan: the banner is printed first deliberately, so that it still - appears when cobra rejects the arguments and on `--help`, and after - parsing there is no single place that covers those paths. The stated - cost of the scan, that `--json` is a subcommand flag matched anywhere - in the vector, is a cost `--cron` already carries — it exists only on - `snapshot create` — so this adds an instance of an accepted - imprecision rather than a new kind, and the two error directions are - not symmetric: a false positive loses a decorative banner, a false - negative corrupts a document. Regression tests at the CLI layer, where - `internal/vaultik`'s existing guard cannot reach: one runs `Entry` - itself over the process's real stdout descriptor, through cobra and fx - to the document, made hermetic by `file://` storage; a second covers - the argument vectors of all five `--json` commands; a third asserts the - banner is still printed without a suppressing flag, so the first - cannot be satisfied by deleting the banner. Also corrected `AGENTS.md` - policy 9, which still keyed the structured-log format on stdout's - TTY-ness after #82 moved that decision to stderr — a rules file that - misdescribes the code misleads exactly the readers who trust it most. - Two smaller findings from the same review: `bytesAttrKey`'s - human-readable byte formatting silently stopped applying under an open - group, because the key reaching the comparison is group-qualified - (`transfer.bytes`), now matched on its final segment and tested both - ways; and `listEnv.stderr` in `snapshot_list_test.go`, assigned but - never read since those tests began capturing the process's stderr, is - removed. `Vaultik.Stderr` is kept — nothing writes to it today, which - its comment now says outright. - -- 2026-08-09: Moved the logger to stderr and fixed `TTYHandler`'s - discarded attributes - ([issue #82](https://git.eeqj.de/sneak/vaultik/issues/82), - [issue #97](https://git.eeqj.de/sneak/vaultik/issues/97)). Two defects - in `internal/log`, fixed together because both live in the handler - construction path. The first: both handlers were built over - `os.Stdout`, and `WARN`/`ERROR` are never suppressed, so a config file - with group- or world-readable permissions was enough to put a log - record inside a `--json` document and break `jq`. Diagnostics now go - to stderr, and the TTY/JSON format choice follows stderr rather than - stdout — testing the wrong stream would colorize records on a - redirected stderr whenever stdout happened to be a terminal. This is - user-visible: `--verbose` and `--debug` output moves to stderr too, - which is documented in `README.md` under "stdout and stderr". It also - let the local workaround in `internal/vaultik/snapshot_list.go` go: - `warnWhileListing` had been hand-rolling structured-log formatting to - reach a non-stdout writer, and the `jsonOutput` parameter threaded - through the remote-listing helpers existed only to choose between the - two writers. The collect-then-emit machinery around `listingWarning` - stays, but on its remaining merit — warnings emitted in key order - after `group.Wait()` are deterministic run to run, where emitting from - the fetch workers would order them by network timing. The second - defect: `TTYHandler.WithAttrs` and `WithGroup` discarded their - arguments and returned the receiver while their doc comments claimed - otherwise, so `log.With` attributes vanished on a terminal and - appeared correctly in CI — failing precisely when someone is debugging - interactively. Both now return a new handler (the receiver is never - written to, since `slog` permits concurrent derivation), attributes - persist across records, and grouping is implemented as dotted key - prefixes, which is the only honest rendering for a format with nowhere - to nest. New tests cover both, including one that feeds the same - derivation chain to the TTY and JSON handlers and compares the - attribute sets, so the two paths cannot drift apart again. Found and - filed while verifying: the startup banner is written to stdout and - `--json` does not suppress it - ([issue #106](https://git.eeqj.de/sneak/vaultik/issues/106)), which is - a separate writer on a separate path and the remaining source of - stdout contamination. - -- 2026-08-09: Made the tagged-release path actually work on Gitea - ([issue #65](https://git.eeqj.de/sneak/vaultik/issues/65)). Three - independent blockers, one of which was the whole - release: `.goreleaser.yaml` had no `gitea_urls:` block, so goreleaser - defaulted to the GitHub API and a `goreleaser release` from this repo - would have failed or published where nobody is looking. It now points - at `https://git.eeqj.de/api/v1`. The version is the second: it was a - hardcoded `VERSION := 1.0.0-rc.1` in the `Makefile`, so every local - build claimed to be a release candidate that had never been tagged and - did not exist, while `git tag -l` was empty and `internal/globals` - defaulted to `dev`. Version now comes from git via the new - `script/version` — the exact tag with a leading `v` stripped (so a - `make` build and a goreleaser build of one commit report the same - string, and it matches the archive names), otherwise `dev-<12-char - sha>`, with `-dirty` appended in either case when tracked files are - modified. Untracked files are deliberately not counted, matching - `git describe --dirty`. The same honesty was owed by the snapshot - path: `snapshot.version_template` was `{{ incpatch .Version }}-next`, - which manufactures a release number from the last tag and, with no - tags at all, from goreleaser's fabricated `v0.0.0`; it now emits the - same `dev-`. The one non-obvious consequence is that - `internal/cli/version.go` gated its "this is a development build" - notice on the version being exactly `dev`, so the moment untagged - builds began carrying a commit sha that notice would have gone silent - and an unreleased binary would have read as a release — the gate is - now `globals.IsDevVersion`, which is a predicate over a string rather - than a comparison against a global precisely so it can be tested, and - it is tested at the boundary (`1.0.0-dev` is a release, `dev-` - is not). Release automation is the third blocker: a tag-triggered - `.gitea/workflows/release.yml` runs the build in CI rather than from - a laptop, with `fetch-depth: 0` because a shallow checkout has no - tags and would silently mislabel the release, and with the - `RELEASE_TOKEN` repository secret passed as `GITEA_TOKEN` (documented - in `README.md`; the runner's automatic token is not used because it - is not guaranteed to carry release write scope). `script/release` - unsets any `GITHUB_TOKEN`/`GITLAB_TOKEN` it finds, since goreleaser - chooses its forge from whichever token variable is set and refuses to - run when it sees more than one — a runner-provided token must not get - to decide where these artifacts are published. `make release` and - `make release-snapshot`, the last two Makefile targets that were not - shims, now call `script/release` and `script/release-snapshot`, which - resolve goreleaser exactly the way `script/lint` resolves the linter: - a `PATH` binary is used only at the pinned version, never as a silent - fallback. `script/bootstrap` installs it, from a sha256-verified - GitHub release archive per `REPO_POLICIES.md`, via a separate - `script/install-goreleaser` — separate because `script/bootstrap` - hard-fails without a usable Docker daemon by design, and the release - runner needs goreleaser without needing Docker. Verified by running - the thing rather than reading it: `make release-snapshot` produced - four archives and `checksums.txt`, and the linux/amd64 binary from - `dist/` reports `dev-` with the development-build notice. Tag - handling was exercised in a throwaway repository rather than by - tagging this one; no tag was created here, since that is the owner's - call. Signing, SBOM, reproducible builds, completions and a man page - are out of scope by the issue. - -- 2026-08-09: Isolated the lint cache per worktree and context-gated the - native lint path (issues #99, #80). One defect seen twice: - `script/lint` decided whether it could skip the pinned image by asking - what version was on `PATH` rather than where it was running, and cache - isolation is part of that same question. The cache was one directory - per repo, shared by every worktree on the host, so two checkouts with - identical Go file contents collided and golangci-lint replayed the - stored analysis — paths and all. The loud direction of that failure - (a clean tree failed by a dirty sibling) is the harmless one; the - silent direction, a dirty tree **passed** by a clean sibling, is a - sixth way for a gate here to report a green it did not earn. The cache - is now keyed on a digest of the worktree path, and every run is - audited by the new `script/lint-audit`, which rejects output citing any - file that is not in the tree being linted — a backstop that runs on - clean output too, because that is the case nobody investigates. Caches - record the worktree they belong to and are collected when it - disappears, so throwaway worktrees do not accumulate them; the whole - tree lives under `XDG_CACHE_HOME` and is disposable. The - `parallel golangci-lint is running` refusal is now a bounded retry - rather than a verdict: it is not a lint result, and exiting non-zero - on it is indistinguishable to a caller from real findings (#88 showed - a private cache does not remove that contention). The native path now - requires `VAULTIK_LINT_IN_CONTAINER=1`, set only by the `Dockerfile` - lint stage, in addition to matching the pin, so a developer's locally - installed 2.12.2 no longer bypasses the digest pin; `/.dockerenv` was - rejected as the signal because `dockerd` creates it for `docker run` - and it is not reliably present during a BuildKit `docker build`, which - is the case the exception exists for. Version detection uses - `golangci-lint version --short` with the old banner scrape kept only - as a fallback. `script/bootstrap` no longer prints `bootstrap - complete` on a machine that cannot run the gate: a missing docker, or - one whose daemon is unreachable, is a hard failure naming exactly what - breaks. Verification was by reproduction rather than inspection — two - concurrent lints from two worktrees of differing cleanliness, a real - run made to report an outside path, a matching linter shimmed onto - `PATH`, and a `PATH` with docker removed — and is recorded on the pull - request. -- 2026-08-09: Closed the fifth false-green mechanism (issues #93, #69). - `script/test` omitted `-count=1`, so Go's test result cache could - satisfy the gate outright: a second back-to-back `make test` printed - the full set of 14 `ok` lines, every one marked `(cached)`, having - executed no test at all. Since `ok (cached)` is an `ok` line, - the "14 `ok` lines means the suite ran" signal this repo leans on was - forgeable, one level below the Docker layer cache that #85 addressed. - Fixed with `-count=1` unconditionally rather than only in the - container, because the pre-commit hook runs the same script and a - gate honest only in CI is dishonest where people rely on it most; - `test-coverage` got the same flag, and `script/check` inherits it by - calling `script/test`. In the same area, `make test-integration` was - deleted rather than made real: no file in the repo carried a build - tag, so `-tags=integration` selected nothing and the target was an - exact duplicate of `make test`. Tagging a subset was rejected because - the entire suite runs in well under a minute, and a scheme whose - failure mode is "some tests silently stopped running" is a poor trade - for those seconds in a repo with this particular history. The - `-timeout` was raised from 30s after measuring rather than after - assuming: the standing claim that cold-cache compilation is charged - against `-timeout` is **false**, disproved by a containerised run - that spent 46s compiling and still reported per-package durations - within noise of a warm host run. `-timeout` reaches the test binary - as `-test.timeout` and its clock starts inside `testing.M.Run`, after - the build. The real exposure was margin, not compilation. The 120s - landed on is a **deliberate, documented divergence** from - `REPO_POLICIES.md:192`, which mandates 30s, and from that file's - canonical recipe at `:212-214`; the divergence is recorded in - `script/test`'s comment because `REPO_POLICIES.md` is org-canonical - and not editable here, and issue #101 proposes amending the policy - text upstream. Numbers and the full verification are recorded once, - on the pull request, and are deliberately not restated here. - -- 2026-08-09: Triaged all fifteen stale remote branches (issue #71) and - deleted fourteen of them; the full per-branch disposition with - evidence is recorded on that issue. Method mattered more than the - outcome here: a three-dot `git diff main...branch` diffs from the - merge base, so it replays everything that landed on `main` after the - branch diverged and makes any old branch look like it holds unlanded - work. That artifact is what made `golangci-v2.12.2` appear to carry - 126 files of unpushed changes when its tree was byte-identical to - `main`'s. Every containment claim here therefore rests on two-dot tip - diffs, tree-hash equality, `git cherry`, and `git branch -r --merged`. - Nine branches were plain ancestors of `main` with zero `git cherry` - `+` commits. `golangci-v2.12.2` had landed squashed as `cc58583`, - whose tree hash equals the branch tip's exactly; note the hash - recorded in the issue had gone stale because `main` advanced, so the - check had to be redone rather than repeated. - `fix/sync-snapshot-cleanup` was redundant, its one line already on - `main` in `syncWithRemote`. `feature/restore-progress-bar` was - superseded by `printRestoreProgress` and the disk-backed blob cache, - and had become actively regressive — it would have deleted - `internal/blobgen/compress_test.go`, the #28 regression test that - landed separately. The two branches this issue was filed for both - turned out to be closed questions that `main` had already moved past - by a recorded decision, so neither was landed and no regression test - was owed: `ctime` no longer exists anywhere in the codebase after - `1c72a37` removed the column, the `File.CTime` field and every use - (#54/#55), and change detection compares size, mtime, mode, uid and - gid only, exactly as `ARCHITECTURE.md` documents — so the - silently-skipped-file data-loss risk that made this a 1.0 item does - not exist. The SQL allow-list branch would have reverted `bfd7334`, - which replaced that very allow-list with regex sanitisation on review - feedback, and would have broken `getTableCount("snapshots")` because - its allow-list omits that table. `feature/daemon-mode` is untouched - and deferred to #94 pending an owner decision, so it is the one - branch besides `main` still on the remote. The stale `TODO.md` entry - named in the issue needed no fix: `e496aa3` had already removed it. - No product code changed. -- 2026-08-09: Adopted the remaining upstream `CHECK_EPOCH` hardening - (issue #91), closing the gap #85 knowingly left open. Four changes, - all four decided as adopt upstream in `sneak/prompts` #26. (1) Each - check stage now asserts `[ -n "$CHECK_EPOCH" ] || exit 1` before - running anything, so a build that supplies no `--build-arg` fails - instead of lying. This is the item that mattered: an unset `ARG` is - an empty string and an empty string is a stable cache key, so the - second and every later bare `docker build .` on an unchanged tree - replayed all three check layers and still exited 0 — and `docker - build .` is the command `REPO_POLICIES.md` names verbatim as a thing - that must be green, so the documented command was precisely the one - that lied. Failed steps are never cached, which is what makes the - guard fire on every invocation rather than once. (2) The epoch is now - expanded into each check command rather than left as a bare - declaration, so the cache miss no longer depends on BuildKit's - unreferenced-`ARG` handling staying as it is, and the value appears - in the build log. (3) `script/cibuild` uses - `epoch="$(date +%s%N)$$"`, unique per invocation rather than per - second; `%N` alone is insufficient because busybox drops it silently - and exits 0, and `$$` is what makes the guarantee hold regardless. - The bare-assignment form is kept deliberately — inlined in an - argument, a failing substitution does not abort under `set -eu` and - would yield an empty constant epoch, restoring the exact false green - being fixed. (4) `script/docker` passes the same fresh arg, so the - two entrypoints cannot disagree about whether the tree is green; - local builds are almost always warm, which made it the likelier - fooling in practice. The `ARG` placement from #85 is unchanged, below - `apk add`, `COPY go.mod go.sum` and `go mod download`, so dependency - layers still cache and the build is not cold. Verified by negative - control rather than inspection — a bare `docker build .` run twice - back to back, plus back-to-back pairs of both scripts and a host-side - `make check`; the measurements are recorded once, in the PR - verification comment, rather than restated here. `.golangci.yml`, the - lint-stage `FROM` line and its digest, `script/lint`, - `REPO_POLICIES.md` and `.gitea/workflows/check.yml` are all - untouched. -- 2026-08-09: Stopped `script/cibuild` from reporting a green it did - not earn (issue #85). A bare `docker build .` let Docker serve the - check layers from the layer cache whenever the tree had not changed: - the checks never executed and the build still exited 0. The fix is an - `ARG CHECK_EPOCH` declared immediately above the check `RUN`s in both - the lint stage and the builder stage (`ARG` scope is per-stage, so - each declares its own), with `script/cibuild` assigning - `epoch="$(date +%s)"` and passing `--build-arg CHECK_EPOCH="$epoch"`. - The assignment is separate on purpose: under `set -eu` a command - substitution that fails inside an argument does not abort the script, - which would leave an empty constant `CHECK_EPOCH` and restore the - very false green being fixed. Placement is the rest of the point — - the `ARG` sits below the `apk add`, `COPY go.mod go.sum`, and `go mod - download` layers, so only the checks are invalidated and the - dependency layers still cache. The guarantee is conditional on a - fresh value rather than absolute: a bare `docker build .` gets an - empty `CHECK_EPOCH` and can still serve the check layers from cache, - which `README.md` and the `Dockerfile` now say plainly, with issue - #91 tracking the upstream hardening (expanded `ARG` form, unset - guard, per-invocation epoch, `script/docker`) that would close it. - Verified by re-running the reproduction plus the withheld-`--build-arg` - counterfactual; the measurements are recorded once, in the PR #89 - verification comment, rather than restated here. `.golangci.yml`, the - lint-stage `FROM` line and its digest, `script/lint`, and - `.gitea/workflows/check.yml` are all untouched. -- 2026-08-09: Corrected the `Vaultik.UI` doc comment (issue #84). It - claimed the cli layer replaces the writer with a discarding one in - `--cron` mode; the actual mechanism is `UI.SetQuiet(true)` in - `setupGlobals`, which drops Begin/Complete/Info/Notice/Detail/ - Progress/Banner but still emits Warning and Error. The `--cron` line - in `README.md` said "Silent unless error", which understated what - survives, and now names warnings too. The other `--cron` comments - (`internal/log/log.go`, `internal/cli/snapshot.go`, - `internal/vaultik/snapshot.go`) were audited and already accurate. - Comments and docs only, no behavior change. -- 2026-08-09: Made `snapshot list` list the destination store without - the private key (issue #64). The listing is now the union of the - local index and a single streamed listing of the `metadata/` prefix, - with no `age_secret_key` gate — the manifest is unencrypted, so a - host holding only the public key can enumerate its own backups and a - host that lost its local index can still see them. A remote-only - snapshot's hostname and name are deliberately not recovered (they are - not recoverable without the private key, and making them so would - undo the privacy property tracked in issue #81); such rows are - labelled by an abbreviation of their remote key and carry the real - timestamp and compressed size from the manifest, with `` - in the two columns that require the local index. Local-only snapshots - are reported as drift, and the hint now names `vaultik prune`, which - exists, instead of `vaultik snapshot cleanup`, which does not. - `reportRemoteDrift` collapsed into the merged view. Every remote - manifest read in the codebase now goes through - `downloadManifestByKey`, so issue #81 has one call site to change. - Review rework: snapshot timestamps now normalize to UTC in - `scanSnapshotRows`, the one place they enter the domain, so the merged - TIMESTAMP column cannot show local time for a locally tracked row and - UTC for a remote-only row on a non-UTC host; `GetIncompleteByHostname` - was folded onto that same scanner. `--json` now reports the - unreadable-manifest count and the 1000-row truncation on stderr - instead of returning a silently short document (the document's shape - is unchanged). The two per-snapshot `log.Warn` calls on the listing - path now route through the same JSON-aware writer as the existing - workaround, so one corrupt manifest can no longer put a log line on - stdout ahead of the document and break `| jq` — still a local - workaround pending issue #82. Verified with `script/cibuild` and with - an uncached `make check` (`0 issues.`, no cached test packages), plus - end to end against a `file://` destination with no secret key present. -- 2026-08-09: Closed the gap between `make lint` and CI (issue #78). - `script/lint` now runs the digest-pinned `golangci-lint` image taken - from the `Dockerfile` lint stage, which is the single source of truth - for the linter version; the duplicate pin in the `Makefile` `deps` - target and the unpinned `golangci-lint` install in `script/bootstrap` - are gone. A `golangci-lint` on `PATH` is used only when its version is - exactly the pinned one (which is how the lint stage runs it inside the - container); anything else goes through Docker, and a missing or - unreachable Docker daemon is a hard error rather than a silent - fallback. Only the **lint** leg of `make check` became equivalent to - `script/cibuild`; its tests and `gofmt` still run on the host against - the host toolchain, as `README.md` states. An earlier version of this - entry claimed `make check` was "as trustworthy as `script/cibuild`" - outright, which overstated it; corrected under issue #80. -- 2026-08-09: Finished the lint remediation under the canonical - `.golangci.yml` (issue #61, which also unblocks issue #59). The - remaining findings were fixed behavior-preservingly: `wsl_v5` - whitespace, `sqlclosecheck`, and `prealloc`. The `sqlclosecheck` sites - now close `sql.Rows` in a deferred closure instead of via the - `CloseRows` helper, which the linter could not see through. Only the - `revive` package-name findings remain suppressed, with per-site - `//nolint` directives; the package-rename question behind them is - tracked in issue #76. Verified with `script/cibuild`, which exits 0 — - that is the only trustworthy gate, because `script/lint` runs whatever - `golangci-lint` happens to be on `PATH` rather than the pinned - v2.12.2 that CI and the `Dockerfile` use, so `make check` can report - green on findings CI still fails. That tooling gap is tracked in issue - #78. -- 2026-08-09: The earlier next step "reconcile the uncommitted - `ARCHITECTURE.md` edits on `main`" needed no work: the working tree is - clean and `ARCHITECTURE.md` is committed on `main`. -- 2026-08-07: Updated golangci-lint to v2.12.2 everywhere it is pinned - (`Dockerfile` lint stage, `Makefile` deps target), replaced - `.golangci.yml` with the canonical config (v2 schema, `default: all`), - and remediated the bulk of the lint findings it surfaced (issue #61): - behavior-preserving fixes across every package, 2,990 findings down to - 80. `make test` and `make fmt-check` were green at that point but - `make lint` was still red; the commit message claiming `make check` - was green was wrong. -- 2026-08-07: Added the standard `.golangci.yml` and `.editorconfig` - (issue #59); lint findings under the new config are tracked in issue - #61. -- 2026-07-07 Adopted scripts-to-rule-them-all: `script/` entrypoints, - Makefile shims, README Entrypoints section -- 2026-07-02: Consolidated CLI verbs, retired overlapping commands; bound - the local index to its backup destination URL. -- 2026-06-28: snapshot rm now removes metadata only and prints the prune - command; restore skips chown when running as non-root. -- 2026-06-26: Snapshot IDs hashed at the storage boundary; snapshot list - made resilient to bad remote entries. -- 2026-06-24: Collapsed snapshot prune into vaultik prune; restore streams - blobs to disk and restores files in blob-locality order; cron output - fixes. -- 2026-06-17: Restore overhaul: ReadAt chunk reads from cached blobs, - reference-counted blob sweeper, integration tests; new internal/ui - output layer, banner, and progress lines. -- 2025-12-18: Added ARCHITECTURE.md and godoc coverage for exported API. -- 2025-07-26: End-to-end integration tests; manifest format refactor; - renamed backup to snapshot; afero filesystem abstraction. -- 2025-07-20: Initial design and implementation: cobra + fx CLI skeleton, - SQLite index database, UUID blob storage with streaming chunking. - -# Future Steps - -None queued; the release-scoping item is now the Next Step. diff --git a/cmd/vaultik/dockermoddownload_test.go b/cmd/vaultik/dockermoddownload_test.go new file mode 100644 index 0000000..da9b704 --- /dev/null +++ b/cmd/vaultik/dockermoddownload_test.go @@ -0,0 +1,45 @@ +package main_test + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestDockerfileBoundsEveryModuleDownload fails unless every +// `go mod download` in the Dockerfile runs under a time limit, is tried +// a fixed number of times, and then fails the build with a message that +// names the module download (issue #351). Like the version tests, this +// parses the Dockerfile; that a stalled download really is cut off and +// retried was checked by hand. +func TestDockerfileBoundsEveryModuleDownload(t *testing.T) { + t.Parallel() + + var downloads []string + + for _, instruction := range instructions(t, productDockerfile) { + if strings.Contains(instruction, "go mod download") { + downloads = append(downloads, instruction) + } + } + + require.NotEmpty(t, downloads, "%s must download modules", + productDockerfile) + + for _, download := range downloads { + assert.Contains(t, download, "timeout 300 go mod download", + "%s: a module download must have a time limit: %s", + productDockerfile, download) + assert.Contains(t, download, "for attempt in 1 2 3", + "%s: a module download must be retried: %s", + productDockerfile, download) + assert.Contains(t, download, "module download failed", + "%s: a module download that never succeeds must say so: %s", + productDockerfile, download) + assert.True(t, strings.HasSuffix(download, "exit 1"), + "%s: a module download that never succeeds must fail the"+ + " build: %s", productDockerfile, download) + } +} diff --git a/cmd/vaultik/dockerversion_test.go b/cmd/vaultik/dockerversion_test.go index f77d274..6ae7b92 100644 --- a/cmd/vaultik/dockerversion_test.go +++ b/cmd/vaultik/dockerversion_test.go @@ -11,92 +11,139 @@ import ( // This file guards the version stamping of the product image (issue // #75). The failure it protects against is silent: the image still // builds and runs, but `vaultik version` inside it reports "commit: -// unknown", so an operator cannot tell which source produced a given -// backup. .dockerignore excludes .git, so the build cannot derive the -// commit itself; the values must be computed on the host and passed in. +// unknown" or a version of "dev", so an operator cannot tell which +// source produced a given backup. The build takes the version as a +// build arg, which script/docker computes on the host, and otherwise +// derives it from the .git in its context; the commit and its date +// always come from that .git. // -// These are parses of the committed files, for the same reason the lint -// guards next door are: shelling out to docker would nest a build -// inside `make test`. That `vaultik version` in the built image really -// prints the host's version is verified by hand and recorded on the -// pull request. +// These are parses of the committed files, because shelling out to +// docker would nest a build inside `make test`. That `vaultik version` +// in the built image really prints the host's version is verified by +// hand. -// dockerScript is script/docker, relative to the repository root. -const dockerScript = "script/docker" +// The files under guard, relative to the repository root. +const ( + productDockerfile = "Dockerfile" + dockerScript = "script/docker" +) -// versionArgs are the ldflag targets the build stamps and, matching -// them, the build args the host must supply. The names line up so the -// same list checks both files. -func versionArgs() []string { - return []string{"VERSION", "COMMIT", "COMMIT_DATE"} -} - -// TestProductDockerfileTakesVersionAsBuildArgs fails unless the build -// declares each version arg and stamps it into the binary by ldflag -// reference, rather than computing it in the container. -func TestProductDockerfileTakesVersionAsBuildArgs(t *testing.T) { +// TestProductDockerfileTakesVersionAsBuildArg fails unless the build +// declares ARG VERSION, with no default, and stamps it into the binary +// whenever it is given, ahead of the value derived in the container. +func TestProductDockerfileTakesVersionAsBuildArg(t *testing.T) { t.Parallel() found := instructions(t, productDockerfile) - for _, arg := range versionArgs() { - require.GreaterOrEqual(t, indexOf(found, "ARG "+arg), 0, - "%s must declare `ARG %s` so the host can pass it in", - productDockerfile, arg) + require.Contains(t, found, "ARG VERSION", + "%s must declare `ARG VERSION`, with no default, so the host can"+ + " pass it in", productDockerfile) - assertLdflagReferences(t, found, arg) - } + assertLdflagReferences(t, found, "VERSION") } -// TestProductDockerfileDoesNotDeriveVersionItself is the anti-regression -// for the original defect: the container ran `git rev-parse`, but .git -// is not in the build context, so it always resolved to "unknown". No -// git command may reach into a build that cannot see the history. -func TestProductDockerfileDoesNotDeriveVersionItself(t *testing.T) { +// TestProductDockerfileDerivesVersionFromGit fails unless a build given +// no VERSION, such as a plain `docker build .` of a clone, takes it from +// `git describe` of the .git in its context, stamps "dev" when the +// context has no .git, and fails rather than stamp "dev" when that .git +// yields no version. The commit and its date come from the same .git, +// and the build fails rather than stamp them "unknown" when it is +// present. +func TestProductDockerfileDerivesVersionFromGit(t *testing.T) { t.Parallel() - text := instructionText(readRepoFile(t, productDockerfile)) + found := instructions(t, productDockerfile) - assert.NotContains(t, text, "git ", - "%s must not run git: .git is excluded from the build context, so"+ - " any value it derives is wrong. Pass version, commit and date"+ - " in as build args instead.", productDockerfile) + buildAt := indexContaining(found, "go build") + require.GreaterOrEqual(t, buildAt, 0, "%s must build", productDockerfile) + + assert.Contains(t, found[buildAt], "git describe --tags --always || echo dev", + "%s must derive the version from git when no VERSION is given,"+ + " and stamp dev when the context has no .git", productDockerfile) + assert.Contains(t, found[buildAt], "[ -e .git ]", + "%s must fail when the context carries .git but yields no version", + productDockerfile) + assert.Contains(t, found[buildAt], "git rev-parse HEAD", + "%s must stamp the commit from git", productDockerfile) + assert.Contains(t, found[buildAt], "git show -s --format=%cs HEAD", + "%s must stamp the commit date from git", productDockerfile) + assert.Contains(t, found[buildAt], + `[ "$commit" = unknown ] || [ "$commit_date" = unknown ]`, + "%s must fail when the context carries .git but yields no commit"+ + " or date", productDockerfile) } // TestDockerScriptComputesVersionOnTheHost fails unless script/docker -// derives each value where .git exists and passes it as a build arg, -// with VERSION coming from script/version so a Docker build reports the -// same string a local build of the same tree would. +// passes the version it derives where .git exists as a build arg. func TestDockerScriptComputesVersionOnTheHost(t *testing.T) { t.Parallel() script := readRepoFile(t, dockerScript) - for _, arg := range versionArgs() { - assert.Contains(t, script, "--build-arg "+arg+"=", - "%s must pass --build-arg %s to the build", dockerScript, arg) - } - - assert.Contains(t, script, "/version", - "%s must take VERSION from script/version, the source of truth"+ - " shared with the Makefile", dockerScript) + assert.Contains(t, script, "--build-arg VERSION=", + "%s must pass --build-arg VERSION to the build", dockerScript) } -// assertLdflagReferences fails unless some build instruction stamps the -// named variable from the ARG (a ${arg} reference), not from a value -// computed inside the container. +// assertLdflagReferences fails unless the build instruction uses the +// named ARG whenever it is given (a ${arg:- reference), so a value +// passed in is not overridden by one derived inside the container. func assertLdflagReferences(t *testing.T, found []string, arg string) { t.Helper() for _, instruction := range found { if strings.HasPrefix(instruction, "RUN ") && strings.Contains(instruction, "go build") && - strings.Contains(instruction, "${"+arg+"}") { + strings.Contains(instruction, "${"+arg+":-") { return } } assert.Fail(t, "version arg is declared but never stamped", - "the go build in %s must reference ${%s} in its ldflags, or the"+ - " arg is passed and discarded", productDockerfile, arg) + "the go build in %s must use ${%s:-...}, or the arg is passed and"+ + " discarded", productDockerfile, arg) +} + +// instructions returns the Dockerfile's instructions, one per element, +// with comments and blank lines dropped and continuation lines joined, +// so a multi-line RUN is one string. +func instructions(t *testing.T, name string) []string { + t.Helper() + + var ( + out []string + continued string + isContinued bool + ) + + for line := range strings.SplitSeq(readRepoFile(t, name), "\n") { + trimmed := strings.TrimSpace(line) + if !isContinued && (trimmed == "" || strings.HasPrefix(trimmed, "#")) { + continue + } + + isContinued = strings.HasSuffix(trimmed, `\`) + continued += strings.TrimSuffix(trimmed, `\`) + + if isContinued { + continue + } + + out = append(out, strings.Join(strings.Fields(continued), " ")) + continued = "" + } + + return out +} + +// indexContaining returns the position of the first instruction +// containing want; -1 if there is none. +func indexContaining(found []string, want string) int { + for i, instruction := range found { + if strings.Contains(instruction, want) { + return i + } + } + + return -1 } diff --git a/cmd/vaultik/lintdocker_test.go b/cmd/vaultik/lintdocker_test.go deleted file mode 100644 index 07e8452..0000000 --- a/cmd/vaultik/lintdocker_test.go +++ /dev/null @@ -1,367 +0,0 @@ -package main_test - -import ( - "os" - "path/filepath" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// This file guards the shape of the lint gate. Every property asserted -// here is one whose loss is SILENT: the build still exits 0, the gate -// still looks green, and nothing was linted or tested. -// -// The gate is a build step. script/lint builds Dockerfile.lint, which -// runs golangci-lint as a RUN instruction, so a successful build is a -// clean lint. BuildKit will happily replay that RUN from cache on an -// unchanged tree in well under a second, which is why the check layers -// are keyed on a CHECK_EPOCH build arg that the calling script -// regenerates per invocation, and why an empty value is a hard error -// rather than a stable cache key. -// -// These are parses rather than invocations. Shelling out to docker from -// the test suite would nest a build inside `make test`, which itself -// runs inside a build in CI. The one property a parse cannot establish -// -- that a real finding actually fails the build -- is verified by -// hand against a deliberately broken tree, recorded on the pull -// request. -// -// One property is deliberately NOT tested here: that no script runs the -// linter on the host. script/lint is the only lint entry point, and it -// runs golangci-lint only inside the container; keeping it that way is a -// review matter, not something a test in this file establishes. - -// The files under guard, relative to the repository root. -const ( - lintDockerfile = "Dockerfile.lint" - productDockerfile = "Dockerfile" - lintScript = "script/lint" - cibuildScript = "script/cibuild" -) - -// linterBinary is the linter's command name, used to locate the -// config-verify and lint steps in Dockerfile.lint. -const linterBinary = "golangci-lint" - -// checkEpochARG is the declaration, with no default value. A default -// would satisfy the non-empty guard with a constant, and a constant is -// a stable cache key: the checks would be replayed from cache forever -// after the first build. -const checkEpochARG = "ARG CHECK_EPOCH" - -// checkEpochGuard is what turns a build that omits --build-arg into a -// loud failure instead of a quiet green. Failed steps are never cached, -// so it fires on every such invocation rather than once. -const checkEpochGuard = `RUN [ -n "$CHECK_EPOCH" ] || exit 1` - -// freshEpoch is the epoch computation the calling scripts must use, as -// a bare assignment on its own line. Inline in an argument, a failing -// `date` would not abort under `set -eu`; CHECK_EPOCH would become the -// empty string, and the guard above would be the only thing standing -// between that and a permanently cached green. `$$` is required because -// `date +%s` is second-granular and busybox silently drops `%N`, so -// without the pid two concurrent runs in one second can collide. -const freshEpoch = `epoch="$(date +%s%N)$$"` - -// TestLintDockerfilePinsTheLinterByDigest fails if the lint image stops -// being pinned. An unpinned tag makes the gate's verdict depend on -// whatever the registry currently serves under that name. -func TestLintDockerfilePinsTheLinterByDigest(t *testing.T) { - t.Parallel() - - from := "" - - for _, instruction := range instructions(t, lintDockerfile) { - if strings.HasPrefix(instruction, "FROM ") { - from = instruction - - break - } - } - - require.NotEmpty(t, from, "%s declares no FROM", lintDockerfile) - assert.Contains(t, from, "golangci/golangci-lint", - "the lint image must be the golangci-lint image") - assert.Contains(t, from, "@sha256:", - "the lint image must be pinned by digest, not by tag alone") -} - -// TestLintDockerfileCannotBeCachedGreen pins the whole cache-busting -// mechanism in the file that lints: the declaration with no default, -// the non-empty guard, and the value expanded into the lint command -// itself rather than merely declared. -func TestLintDockerfileCannotBeCachedGreen(t *testing.T) { - t.Parallel() - - found := instructions(t, lintDockerfile) - - argAt := indexOf(found, checkEpochARG) - require.GreaterOrEqual(t, argAt, 0, - "%s must declare `%s` with no default value", - lintDockerfile, checkEpochARG) - - assert.GreaterOrEqual(t, indexOf(found, checkEpochGuard), argAt, - "%s must guard against an empty CHECK_EPOCH with `%s`", - lintDockerfile, checkEpochGuard) - - assertEpochExpandedInto(t, found[argAt:], "golangci-lint run") - - // Dependency layers must stay above the ARG, or every lint run - // re-downloads the module cache and the inner loop becomes - // unusable. - download := indexOf(found, "RUN go mod download") - require.GreaterOrEqual(t, download, 0, - "%s must download modules in their own layer", lintDockerfile) - assert.Less(t, download, argAt, - "`%s` must come after `go mod download` so dependency layers"+ - " still cache", checkEpochARG) -} - -// TestLintDockerfileVerifiesTheLinterConfig guards the validation of -// .golangci.yml itself. `golangci-lint run` rejects a config it cannot -// parse but silently IGNORES an unknown top-level key, so renaming -// `linters:` to `linterz:` discards `default: all` and every threshold -// and still exits 0 reporting no issues. `config verify` is what turns -// that into a failure, and it has to run BEFORE the lint, or the lint -// spends a minute reporting a verdict from a config already known to be -// wrong. -func TestLintDockerfileVerifiesTheLinterConfig(t *testing.T) { - t.Parallel() - - found := instructions(t, lintDockerfile) - verify := linterBinary + " config verify" - - verifyAt := indexContaining(found, verify) - require.GreaterOrEqual(t, verifyAt, 0, - "%s must run `%s --config .golangci.yml`: without it a typo'd"+ - " top-level key in .golangci.yml is silently ignored and the"+ - " gate passes with only the default linter set", lintDockerfile, - verify) - - runAt := indexContaining(found, linterBinary+" run") - require.GreaterOrEqual(t, runAt, 0, "%s must lint", lintDockerfile) - assert.Less(t, verifyAt, runAt, - "%s must verify the config before linting with it", lintDockerfile) - - // Keyed on the epoch like every other check layer, so it executes - // per invocation rather than being replayed. A cached validation - // validates nothing. - assertEpochExpandedInto(t, found, verify) -} - -// TestProductDockerfileCannotBeCachedGreen holds the same line for the -// checks that remain in the product image build. -func TestProductDockerfileCannotBeCachedGreen(t *testing.T) { - t.Parallel() - - found := instructions(t, productDockerfile) - - argAt := indexOf(found, checkEpochARG) - require.GreaterOrEqual(t, argAt, 0, - "%s must declare `%s` with no default value", - productDockerfile, checkEpochARG) - - assert.GreaterOrEqual(t, indexOf(found, checkEpochGuard), argAt, - "%s must guard against an empty CHECK_EPOCH", productDockerfile) - - assertEpochExpandedInto(t, found[argAt:], "make fmt-check") - assertEpochExpandedInto(t, found[argAt:], "make test") -} - -// TestProductDockerfileDoesNotLint records the split deliberately: the -// linter lives in Dockerfile.lint and nowhere else, so there is exactly -// one digest pinning it. A lint stage reintroduced here would either be -// docker-in-docker (`make lint` is now `docker build`) or a second, -// independently bumpable pin. -func TestProductDockerfileDoesNotLint(t *testing.T) { - t.Parallel() - - contents := readRepoFile(t, productDockerfile) - - for _, forbidden := range []string{"golangci", "make lint"} { - assert.NotContains(t, instructionText(contents), forbidden, - "%s must not lint: the linter is pinned once, in %s", - productDockerfile, lintDockerfile) - } -} - -// TestLintScriptBuildsTheLintDockerfileWithAFreshEpoch is the other -// half of the mechanism. The Dockerfile's guard only rejects an EMPTY -// epoch; a constant non-empty one would satisfy it and still be served -// from cache forever. -func TestLintScriptBuildsTheLintDockerfileWithAFreshEpoch(t *testing.T) { - t.Parallel() - - script := readRepoFile(t, lintScript) - - assertBareEpochAssignment(t, script, lintScript) - assert.Contains(t, script, `--build-arg CHECK_EPOCH="$epoch"`, - "%s must pass the fresh epoch to the build", lintScript) - assert.Contains(t, script, lintDockerfile, - "%s must build %s", lintScript, lintDockerfile) -} - -// TestCibuildBuildsBothDockerfilesWithFreshEpochs guards the CI gate: -// dropping either build silently removes a whole class of check from -// CI while leaving it green. -func TestCibuildBuildsBothDockerfilesWithFreshEpochs(t *testing.T) { - t.Parallel() - - script := readRepoFile(t, cibuildScript) - - assertBareEpochAssignment(t, script, cibuildScript) - assert.Equal(t, 2, strings.Count(script, freshEpoch), - "%s must compute a fresh epoch for each of its two builds", - cibuildScript) - assert.Equal(t, 2, - strings.Count(script, `--build-arg CHECK_EPOCH="$epoch"`), - "%s must pass a fresh epoch to both builds", cibuildScript) - assert.Contains(t, script, "-f Dockerfile.lint", - "%s must build %s", cibuildScript, lintDockerfile) -} - -// assertEpochExpandedInto fails unless some instruction runs the named -// command with the epoch expanded into it. Expansion, not mere -// declaration: an ARG that no instruction references is not guaranteed -// to key the layer, and the expansion also puts the value in the build -// log where a reader can see the layer was keyed fresh. -func assertEpochExpandedInto(t *testing.T, found []string, command string) { - t.Helper() - - for _, instruction := range found { - if !strings.HasPrefix(instruction, "RUN ") { - continue - } - - if strings.Contains(instruction, command) && - strings.Contains(instruction, "${CHECK_EPOCH}") { - return - } - } - - assert.Fail(t, "no epoch-keyed layer runs the command", - "`%s` must run in a layer that expands ${CHECK_EPOCH}, or it"+ - " will be replayed from cache without executing", command) -} - -// assertBareEpochAssignment fails unless the script computes the epoch -// as a bare assignment on its own line. -func assertBareEpochAssignment(t *testing.T, script, name string) { - t.Helper() - - for line := range strings.SplitSeq(script, "\n") { - if strings.TrimSpace(line) == freshEpoch { - return - } - } - - assert.Fail(t, "no bare epoch assignment", - "%s must compute `%s` as a bare assignment on its own line, so"+ - " `set -e` catches a failing date instead of quietly"+ - " building with an empty epoch", name, freshEpoch) -} - -// instructions returns the Dockerfile's instructions, one per element, -// with comments and blank lines dropped and continuation lines joined, -// so a multi-line RUN is one string. -func instructions(t *testing.T, name string) []string { - t.Helper() - - return strings.Split(instructionText(readRepoFile(t, name)), "\n") -} - -// instructionText is instructions' parse, before splitting: it is also -// what a "must not contain" assertion should look at, so that a word -// appearing only in a comment is not mistaken for behaviour. -func instructionText(contents string) string { - var ( - out []string - continued string - isContinued bool - ) - - for line := range strings.SplitSeq(contents, "\n") { - trimmed := strings.TrimSpace(line) - if !isContinued && (trimmed == "" || strings.HasPrefix(trimmed, "#")) { - continue - } - - isContinued = strings.HasSuffix(trimmed, `\`) - continued += strings.TrimSuffix(trimmed, `\`) - - if isContinued { - continue - } - - out = append(out, strings.Join(strings.Fields(continued), " ")) - continued = "" - } - - return strings.Join(out, "\n") -} - -// indexOf returns the position of the first instruction equal to, or -// beginning with, want; -1 if there is none. An `ARG NAME=default` -// counts as beginning with `ARG NAME`, so a declared arg is found -// whether or not it carries a default. -func indexOf(found []string, want string) int { - for i, instruction := range found { - if instruction == want || - strings.HasPrefix(instruction, want+" ") || - strings.HasPrefix(instruction, want+"=") { - return i - } - } - - return -1 -} - -// indexContaining returns the position of the first instruction -// containing want; -1 if there is none. -func indexContaining(found []string, want string) int { - for i, instruction := range found { - if strings.Contains(instruction, want) { - return i - } - } - - return -1 -} - -// readRepoFile reads a file by its path relative to the repository -// root. -func readRepoFile(t *testing.T, name string) string { - t.Helper() - - //nolint:gosec // G304: the path is a constant relative to this repo - contents, err := os.ReadFile(filepath.Join(repoRoot(t), name)) - require.NoError(t, err) - - return string(contents) -} - -// repoRoot returns the repository root. The test binary runs with its -// package directory as the working directory, so the root is found by -// walking up until the module file appears. -func repoRoot(t *testing.T) string { - t.Helper() - - dir, err := os.Getwd() - require.NoError(t, err) - - for { - _, err = os.Stat(filepath.Join(dir, "go.mod")) - if err == nil { - return dir - } - - parent := filepath.Dir(dir) - require.NotEqual(t, dir, parent, - "walked to the filesystem root without finding a go.mod") - - dir = parent - } -} diff --git a/cmd/vaultik/makefile_test.go b/cmd/vaultik/makefile_test.go index b937f15..8b527be 100644 --- a/cmd/vaultik/makefile_test.go +++ b/cmd/vaultik/makefile_test.go @@ -1,6 +1,8 @@ package main_test import ( + "os" + "path/filepath" "regexp" "slices" "strings" @@ -84,14 +86,48 @@ func TestBuildTargetBuildsTheBinary(t *testing.T) { "`make build` must depend on the rule that builds the binary") } -// readMakefile returns the contents of the repository's Makefile. The -// root is located by the shared walk in lintdocker_test.go. +// readMakefile returns the contents of the repository's Makefile. func readMakefile(t *testing.T) string { t.Helper() return readRepoFile(t, "Makefile") } +// readRepoFile reads a file by its path relative to the repository +// root. +func readRepoFile(t *testing.T, name string) string { + t.Helper() + + //nolint:gosec // G304: the path is a constant relative to this repo + contents, err := os.ReadFile(filepath.Join(repoRoot(t), name)) + require.NoError(t, err) + + return string(contents) +} + +// repoRoot returns the repository root. The test binary runs with its +// package directory as the working directory, so the root is found by +// walking up until the module file appears. +func repoRoot(t *testing.T) string { + t.Helper() + + dir, err := os.Getwd() + require.NoError(t, err) + + for { + _, err = os.Stat(filepath.Join(dir, "go.mod")) + if err == nil { + return dir + } + + parent := filepath.Dir(dir) + require.NotEqual(t, dir, parent, + "walked to the filesystem root without finding a go.mod") + + dir = parent + } +} + // phonyTargets returns every name declared phony, across all .PHONY // lines. func phonyTargets(makefile string) []string { diff --git a/config.example.yml b/configs/config.example.yml similarity index 87% rename from config.example.yml rename to configs/config.example.yml index 199c3d1..e8fe7b9 100644 --- a/config.example.yml +++ b/configs/config.example.yml @@ -3,7 +3,8 @@ # Copy this file and uncomment/modify the values you need # Age recipient public keys for encryption -# This is REQUIRED - backups are encrypted to these public keys +# Backups are encrypted to these public keys. snapshot create needs at least +# one; listing, verifying and restoring do not # Generate with: age-keygen | grep "public key" age_recipients: - age1cj2k2addawy294f6k2gr2mf9gps9r3syplryxca3nvxj3daqm96qfp84tz @@ -286,19 +287,24 @@ storage_url: "rclone://myremote/path/to/backups" # #use_ssl: true # # # Part size for multipart uploads -# # Minimum 5MB, affects memory usage during upload -# # Supports: 5MB, 10M, 100MiB, etc. -# # Default: 5MB -# #part_size: 5MB +# # Minimum 5MiB, maximum 5GiB; affects memory usage during upload +# # A blob too large for 10,000 parts of this size gets larger parts +# # Supports: 10MB, 16MiB, 100MiB, etc. (5MB is below the minimum) +# # Default: 5MiB +# #part_size: 5MiB # Path to local SQLite index database # This database tracks file state for incremental backups -# Default: /var/lib/vaultik/index.sqlite -#index_path: /var/lib/vaultik/index.sqlite +# It must be an absolute path; ~ is expanded +# Default: the platform data directory, e.g. +# macOS: ~/Library/Application Support/vaultik/index.sqlite +# Linux: ~/.local/share/vaultik/index.sqlite +#index_path: /path/to/index.sqlite # Average chunk size for content-defined chunking # Smaller chunks = better deduplication but more metadata -# Supports: 10MB, 5M, 1GB, 500KB, 64MiB, etc. +# Minimum 1MB +# Supports: 10MB, 5M, 1GB, 64MiB, etc. # Default: 10MB #chunk_size: 10MB @@ -309,6 +315,12 @@ storage_url: "rclone://myremote/path/to/backups" # Chunking uses no secret (the FastCDC parameters are fixed and public). At a # large limit a blob holds hundreds of chunks, so individual chunk lengths are # not visible in its size; lowering the limit toward chunk_size exposes them. +# A backup needs free temporary space, because each blob is written whole to +# a temporary file before it is uploaded (up to about blob_size_limit; an +# rclone destination that cannot stream uploads needs about twice that) and +# the metadata export writes copies of the local index. Temporary files go to +# $TMPDIR (default /tmp); with TMPDIR unset, SQLite writes one of those copies +# to /var/tmp. # Supports: 1GB, 10G, 500MB, 1GiB, etc. # Default: 10GB #blob_size_limit: 10GB @@ -317,6 +329,20 @@ storage_url: "rclone://myremote/path/to/backups" # Higher = better compression but slower # Default: 3 compression_level: 5 + +# How old a blob that no snapshot lists must be before prune deletes it, and +# how old every object in a directory under metadata/ with no manifest must +# be before prune deletes that directory +# A backup uploads its blobs and its db.zst.age before its manifest, so on a +# destination shared between hosts or users this must be longer than the +# longest backup run +# It does not protect a blob a backup reuses from an earlier run that stopped +# before its manifest: that blob keeps the time of its first upload, so a +# prune can delete it +# Supports: 36h, 90m, etc.; 0s deletes such blobs and directories at once +# Default: 24h +#prune_grace_period: 24h + # Hostname to use in backup metadata # Default: system hostname #hostname: myserver diff --git a/ARCHITECTURE.md b/docs/ARCHITECTURE.md similarity index 77% rename from ARCHITECTURE.md rename to docs/ARCHITECTURE.md index 6428d8f..d345555 100644 --- a/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,10 +1,14 @@ # Vaultik Architecture -This document describes the internal architecture of Vaultik, focusing on the data model, type instantiation, and the relationships between core modules. +This document describes the internal architecture of Vaultik, focusing on the +data model, type instantiation, and the relationships between core modules. ## Overview -Vaultik is a backup system that uses content-defined chunking for deduplication and packs chunks into large, compressed, encrypted blobs for efficient cloud storage. The system is built around dependency injection using [uber-go/fx](https://github.com/uber-go/fx). +Vaultik is a backup system that uses content-defined chunking for deduplication +and packs chunks into large, compressed, encrypted blobs for efficient cloud +storage. The system is built around dependency injection using +[uber-go/fx](https://github.com/uber-go/fx). ## Data Flow @@ -53,53 +57,88 @@ The database tracks five primary entities and their relationships: ### Entity Descriptions #### File (`database.File`) -Represents a file, directory, or symlink in the backup system. Stores metadata needed for restoration: -- Path, source_path (for restore path stripping), mtime + +Represents a file, directory, or symlink in the backup system. Stores metadata +needed for restoration: + +- Path, mtime - Size, mode, ownership (uid, gid) - Symlink target (if applicable) +It also stores `source_path`, the source directory the scan found it under, made +absolute and with symlinks resolved. Restore does not read it. + #### Chunk (`database.Chunk`) -A content-addressed unit of data. Files are split into variable-size chunks using the FastCDC algorithm: + +A content-addressed unit of data. Files are split into variable-size chunks +using the FastCDC algorithm: + - `ChunkHash`: SHA256 hash of chunk content (primary key) - `Size`: Chunk size in bytes -Chunk sizes vary between `avgChunkSize/4` and `avgChunkSize*4` (2.5MB-40MB for the 10MB default average). +Chunk sizes vary between `avgChunkSize/4` and `avgChunkSize*4` (2.5MB-40MB for +the 10MB default average). #### FileChunk (`database.FileChunk`) + Maps files to their constituent chunks: + - `FileID`: Reference to the file - `Idx`: Position of this chunk within the file (0-indexed) - `ChunkHash`: Reference to the chunk #### Blob (`database.Blob`) -The final storage unit uploaded to S3. Contains many compressed and encrypted chunks: + +The final storage unit uploaded to S3. Contains many compressed and encrypted +chunks: + - `ID`: UUID assigned at creation -- `Hash`: `hex(SHA256(SHA256(uncompressed blob contents)))`, computed before compression and encryption (see [docs/REPOSTRUCTURE.md](docs/REPOSTRUCTURE.md#blobs-directory-blobs)) +- `Hash`: `hex(SHA256(SHA256(uncompressed blob contents)))`, computed before + compression and encryption (see + [docs/REPOSTRUCTURE.md](REPOSTRUCTURE.md#blobs-directory-blobs)) - `UncompressedSize`: Total raw chunk data before compression - `CompressedSize`: Size after zstd compression and age encryption - `CreatedTS`, `FinishedTS`, `UploadedTS`: Lifecycle timestamps Blob creation process: + 1. Chunks are accumulated (up to MaxBlobSize, typically 10GB) 2. As each chunk is added, its uncompressed bytes are fed to a running SHA-256 -3. Concurrently, the same bytes are compressed with zstd, then encrypted with age (recipients configured in config), and streamed to storage -4. On finalize, the blob's name is the double SHA-256 of the uncompressed contents — `hex(SHA256(SHA256(...)))` — not a hash of the compressed, encrypted bytes -5. Uploaded to `blobs/{hash[0:2]}/{hash[2:4]}/{hash}` +3. Concurrently, the same bytes are compressed with zstd, then encrypted with + age (recipients configured in config), and written to a temporary file +4. On finalize, the blob's name is the double SHA-256 of the uncompressed + contents — `hex(SHA256(SHA256(...)))` — not a hash of the compressed, + encrypted bytes +5. The finished file is uploaded to `blobs/{hash[0:2]}/{hash[2:4]}/{hash}` and + then deleted + +A backup needs free temporary space, because each blob is written whole to a +temporary file before it is uploaded (up to about `blob_size_limit`; an rclone +destination that cannot stream uploads needs about twice that) and the metadata +export writes copies of the local index. Temporary files go to `$TMPDIR` +(default `/tmp`); with `TMPDIR` unset, SQLite writes one of those copies to +`/var/tmp`. #### BlobChunk (`database.BlobChunk`) + Maps chunks to their position within blobs: + - `BlobID`: Reference to the blob - `ChunkHash`: Reference to the chunk - `Offset`: Byte offset within the uncompressed blob - `Length`: Chunk size #### Snapshot (`database.Snapshot`) + Represents a point-in-time backup: -- `ID`: Format is `{hostname}_{snapshot-name}_{RFC3339}` (e.g. `server1_home_2025-06-01T12:00:00Z`) + +- `ID`: Format is `{hostname}_{snapshot-name}_{RFC3339}` (e.g. + `server1_home_2025-06-01T12:00:00Z`) - Tracks file count, chunk count, blob count, sizes, compression ratio - `CompletedAt`: Null until snapshot finishes successfully #### SnapshotFile / SnapshotBlob + Join tables linking snapshots to their files and blobs. ### Relationship Summary @@ -136,21 +175,27 @@ fx.New( ### Key Type Instantiation Points #### 1. Config (`config.Config`) + - **Created by**: `config.Module` via `config.LoadConfig()` - **When**: Application startup (fx DI) -- **Contains**: All configuration from YAML file (S3 credentials, encryption keys, paths, etc.) +- **Contains**: All configuration from YAML file (S3 credentials, encryption + keys, paths, etc.) #### 2. Database (`database.DB`) + - **Created by**: `database.Module` via `database.New()` - **When**: Application startup (fx DI) - **Contains**: SQLite connection, path reference #### 3. Repositories (`database.Repositories`) + - **Created by**: `database.Module` via `database.NewRepositories()` - **When**: Application startup (fx DI) -- **Contains**: All repository interfaces (Files, Chunks, Blobs, Snapshots, etc.) +- **Contains**: All repository interfaces (Files, Chunks, Blobs, Snapshots, + etc.) #### 4. Vaultik (`vaultik.Vaultik`) + - **Created by**: `vaultik.New(VaultikParams)` - **When**: Application startup (fx DI) - **Contains**: All dependencies for backup operations @@ -172,11 +217,13 @@ type Vaultik struct { ``` #### 5. SnapshotManager (`snapshot.SnapshotManager`) + - **Created by**: `snapshot.Module` via `snapshot.NewSnapshotManager()` - **When**: Application startup (fx DI) - **Responsibility**: Creates/completes snapshots, exports metadata to S3 #### 6. Scanner (`snapshot.Scanner`) + - **Created by**: `ScannerFactory(ScannerParams)` - **When**: Each `CreateSnapshot()` call - **Contains**: Chunker, Packer, progress reporter @@ -190,20 +237,22 @@ scanner := v.ScannerFactory(snapshot.ScannerParams{ ``` #### 7. Chunker (`chunker.Chunker`) + - **Created by**: `chunker.NewChunker(avgChunkSize)` - **When**: Inside `snapshot.NewScanner()` - **Configuration**: - - `avgChunkSize`: From config (default 10MB) - - `minChunkSize`: avgChunkSize / 4 - - `maxChunkSize`: avgChunkSize * 4 + - `avgChunkSize`: From config (default 10MB) + - `minChunkSize`: avgChunkSize / 4 + - `maxChunkSize`: avgChunkSize \* 4 #### 8. Packer (`blob.Packer`) + - **Created by**: `blob.NewPacker(PackerConfig)` - **When**: Inside `snapshot.NewScanner()` - **Configuration**: - - `MaxBlobSize`: Maximum blob size before finalization (typically 10GB) - - `CompressionLevel`: zstd level (1-19) - - `Recipients`: age public keys for encryption + - `MaxBlobSize`: Maximum blob size before finalization (typically 10GB) + - `CompressionLevel`: zstd level (1-19) + - `Recipients`: age public keys for encryption ```go // snapshot/scanner.go: NewScanner() @@ -220,17 +269,22 @@ packer, err := blob.NewPacker(packerCfg) ## Module Responsibilities ### `internal/cli` -Entry point for fx application. Combines all modules and handles signal interrupts. + +Entry point for fx application. Combines all modules and handles signal +interrupts. Key functions: + - `NewApp(AppOptions)` → Creates fx.App with all modules - `RunApp(ctx, app)` → Starts app, handles graceful shutdown - `RunWithApp(ctx, opts)` → Convenience wrapper ### `internal/vaultik` + Main orchestrator containing all dependencies and command implementations. Key methods: + - `New(VaultikParams)` → Constructor (fx DI) - `CreateSnapshot(opts)` → Main backup operation - `ListSnapshots(jsonOutput)` → List available snapshots @@ -238,27 +292,34 @@ Key methods: - `PurgeSnapshots(...)` → Remove old snapshots ### `internal/chunker` + Content-defined chunking using FastCDC algorithm. Key types: + - `Chunk` → Hash, Data, Offset, Size - `Chunker` → avgChunkSize, minChunkSize, maxChunkSize Key methods: + - `NewChunker(avgChunkSize)` → Constructor -- `ChunkReaderStreaming(reader, callback)` → Stream chunks with callback (preferred) +- `ChunkReaderStreaming(reader, callback)` → Stream chunks with callback + (preferred) - `ChunkReader(reader)` → Return all chunks at once (memory-intensive) ### `internal/blob` + Blob packing: accumulates chunks, compresses, encrypts, tracks metadata. Key types: + - `Packer` → Thread-safe blob accumulator - `ChunkRef` → Hash + Data for adding to packer - `FinishedBlob` → Completed blob ready for upload - `BlobWithReader` → FinishedBlob + io.Reader for streaming upload Key methods: + - `NewPacker(PackerConfig)` → Constructor - `AddChunk(ChunkRef)` → Add chunk to current blob - `FinalizeBlob()` → Compress, encrypt, hash current blob @@ -268,35 +329,48 @@ Key methods: ### `internal/snapshot` #### Scanner + Orchestrates the backup process for a directory. Key methods: + - `NewScanner(ScannerConfig)` → Constructor (creates Chunker + Packer) - `Scan(ctx, path, snapshotID)` → Main scan operation Scan phases: -1. **Phase 0**: Detect deleted files from previous snapshots -2. **Phase 1**: Walk directory, identify files needing processing + +1. **Phase 1**: Walk directory, identify files needing processing +2. **Phase 1b**: Count as deleted the files that the previous snapshot of the + same name lists, the walk did not find, and are gone from disk; a file that + is excluded, or inside an excluded directory, is not counted 3. **Phase 2**: Process files (chunk → pack → upload) #### SnapshotManager + Manages snapshot lifecycle and metadata export. Key methods: + - `CreateSnapshot(ctx, hostname, version, commit)` → Create snapshot record -- `PopulateSnapshotBlobs(ctx, snapshotID)` → Record every blob the snapshot references +- `PopulateSnapshotBlobs(ctx, snapshotID)` → Record every blob the snapshot + references - `ExportSnapshotMetadata(ctx, dbPath, snapshotID)` → Export to S3 -- `MarkSnapshotComplete(ctx, snapshotID)` → Record completion, only after a successful export -- `CompleteSnapshot(ctx, snapshotID)` → Convenience: populate blobs, then mark complete (no export between) +- `MarkSnapshotComplete(ctx, snapshotID)` → Record completion, only after a + successful export +- `CompleteSnapshot(ctx, snapshotID)` → Convenience: populate blobs, then mark + complete (no export between) ### `internal/database` + SQLite database for local index. Single-writer mode for thread safety. Key types: + - `DB` → Database connection wrapper - `Repositories` → Collection of all repository interfaces Repository interfaces: + - `FilesRepository` → CRUD for File records - `ChunksRepository` → CRUD for Chunk records - `BlobsRepository` → CRUD for Blob records @@ -307,6 +381,8 @@ Repository interfaces: ``` CreateSnapshot(opts) + │ + ├─► markDestination() // Check the marker (see Storage Layout in S3), then write it │ ├─► PruneDatabase() // Critical: avoid dedup errors │ @@ -316,13 +392,13 @@ CreateSnapshot(opts) │ │ │ ├─► scanner.Scan(ctx, path, snapshotID) │ │ │ - │ │ ├─► Phase 0: detectDeletedFiles() - │ │ │ │ │ ├─► Phase 1: scanPhase() │ │ │ Walk directory │ │ │ Check file metadata changes │ │ │ Build list of files to process │ │ │ + │ │ ├─► Phase 1b: detectDeletedFiles() + │ │ │ │ │ └─► Phase 2: processPhase() │ │ For each file: │ │ chunker.ChunkReaderStreaming() @@ -335,10 +411,10 @@ CreateSnapshot(opts) │ │ │ └─► Accumulate statistics │ - ├─► SnapshotManager.UpdateSnapshotStatsExtended() - │ ├─► SnapshotManager.PopulateSnapshotBlobs() // record referenced blobs │ + ├─► SnapshotManager.UpdateSnapshotStatsExtended() + │ ├─► SnapshotManager.ExportSnapshotMetadata() │ │ │ ├─► Copy database to temp file @@ -353,16 +429,23 @@ CreateSnapshot(opts) ## Deduplication Strategy -1. **File-level**: Files unchanged since last backup are skipped (metadata comparison: size, mtime, mode, uid, gid) +1. **File-level**: Files and symlinks unchanged since last backup are skipped + (metadata comparison: size, mtime, mode, uid, gid, and a symlink's target), + unless the file lists a chunk that no uploaded blob holds; such a file is + re-chunked -2. **Chunk-level**: Chunks are content-addressed by SHA256 hash. If a chunk hash already exists in the database, the chunk data is not re-uploaded. +2. **Chunk-level**: Chunks are content-addressed by SHA256 hash. If a chunk hash + already exists in the database, the chunk data is not re-uploaded. -3. **Blob-level**: Blobs contain only unique chunks. Duplicate chunks within a blob are skipped. +3. **Blob-level**: Blobs contain only unique chunks. Duplicate chunks within a + blob are skipped. ## Storage Layout in S3 ``` bucket/ +├── vaultik-destination.txt # Marker written by every backup +│ ├── blobs/ │ └── {hash[0:2]}/ │ └── {hash[2:4]}/ @@ -374,15 +457,30 @@ bucket/ └── manifest.json.zst # Blob list (for pruning/verification) ``` +A destination that answers a look-up of `vaultik-destination.txt` with not found +is treated as not present while the local index holds snapshots stored there +(`checkDestinationMarker` in `internal/vaultik/destination_marker.go`): +`snapshot create` refuses to write to it, `prune`, `snapshot purge` and +`remote nuke` fail, and `snapshot list` and `snapshot remove` behave as for a +destination that cannot be listed. This keeps those commands from taking an +unplugged volume's empty mount point for a destination whose snapshots are all +gone. When the look-up fails for any reason other than not found, for example +when S3 refuses it to credentials that allow only PUT, the check is skipped, so +a host with such credentials does not notice an emptied destination; see +[docs/REPOSTRUCTURE.md](REPOSTRUCTURE.md#marker-file-vaultik-destinationtxt). +The `file://` backend never creates its destination directory, so a write to a +missing one fails. + The `{remote-key}` directory name is a one-way double SHA-256 hash of the human snapshot ID, so the human ID (hostname, snapshot name, timestamp) is never written to the store as a directory name. See -[docs/REPOSTRUCTURE.md](docs/REPOSTRUCTURE.md#remote-key-derivation) for the +[docs/REPOSTRUCTURE.md](REPOSTRUCTURE.md#remote-key-derivation) for the derivation and a worked example. ## Thread Safety - `Packer`: Thread-safe via mutex. Multiple goroutines can call `AddChunk()`. - `Scanner`: Uses `packerMu` mutex to coordinate blob finalization. -- `Database`: Single-writer mode (`MaxOpenConns=1`) ensures SQLite thread safety. +- `Database`: Single-writer mode (`MaxOpenConns=1`) ensures SQLite thread + safety. - `Repositories.WithTx()`: Handles transaction lifecycle automatically. diff --git a/docs/DATAMODEL.md b/docs/DATAMODEL.md index fdb86cf..5dd2af9 100644 --- a/docs/DATAMODEL.md +++ b/docs/DATAMODEL.md @@ -2,46 +2,48 @@ ## Overview -Vaultik uses a local SQLite database to track file metadata, chunk mappings, and blob associations during the backup process. This database serves as an index for incremental backups and enables efficient deduplication. +Vaultik uses a local SQLite database to track file metadata, chunk mappings, and +blob associations during the backup process. This database serves as an index +for incremental backups and enables efficient deduplication. **Important Notes:** -This section is the authoritative explanation of the schema/migration story; -other documents (the README and `AGENTS.md`) link here. - -- **No upgrade path between versions (pre-1.0)**: Vaultik has no supported way to - carry an existing local index across a schema change. The index is disposable - — if the on-disk schema changes between versions, delete the local SQLite - database (`vaultik database delete`) and run a full backup. Remote storage is - unaffected; the new index re-deduplicates against existing remote blobs. This - is the standing project policy, and it is separate from the schema bootstrap - described next. -- **Schema bootstrap**: a fresh database is populated from numbered SQL files - embedded in the binary under `internal/database/schema/`. `000.sql` creates the - `schema_migrations` table; `001.sql` creates the application tables. On opening - a database the code applies each numbered file that has not yet run and records - its version in `schema_migrations`. This bootstraps a new database; it does not - upgrade an existing one between released versions. -- **Changing the schema (pre-1.0)**: edit `internal/database/schema/001.sql` (and - the code that touches the affected tables) directly. Do not add new numbered - files — there is no installed base to migrate. -- **Disposability expires at 1.0**: the index is treated as disposable only until - 1.0 ships and is tagged. Once 1.0 is tagged that clause expires and the - question of upgrading existing indexes returns. It is deliberately left open - here. - **Version Compatibility**: In rare cases, you may need to use the same version of Vaultik to restore a backup as was used to create it. This ensures compatibility with the metadata format stored in S3. +## Schema Migrations + +Vaultik supports schema migrations. They are the numbered SQL files in +`internal/database/schema/`, embedded in the binary: `000.sql` creates the +`schema_migrations` table, which records each migration that has run, and +`001.sql` creates the application tables. `database.New` opens a database and +applies, in order, every migration that database has not yet recorded. + +**Before 1.0** no migrations are added, because nothing is installed anywhere +yet. A schema change edits `001.sql` (and the code that uses the affected +tables) directly. A local database created before the change has already +recorded `001.sql` as run, so it keeps the old schema and can become unusable; +`vaultik database delete` followed by a full backup rebuilds it. + +**After 1.0** each schema change is a new numbered file, so an existing local +database is migrated the first time an updated vaultik opens it. A file that has +shipped in a release is never edited. + ## Database Tables ### 1. `files` + Stores metadata about files in the filesystem being backed up. **Columns:** + - `id` (TEXT PRIMARY KEY) - UUID for the file record - `path` (TEXT NOT NULL UNIQUE) - Absolute file path -- `mtime` (INTEGER NOT NULL) - Modification time as Unix timestamp +- `mtime` (INTEGER NOT NULL) - Modification time, whole seconds since the Unix + epoch +- `mtime_nsec` (INTEGER NOT NULL) - Nanoseconds within that second, 0 to + 999999999 - `size` (INTEGER NOT NULL) - File size in bytes - `mode` (INTEGER NOT NULL) - Unix file permissions and type - `uid` (INTEGER NOT NULL) - User ID of file owner @@ -49,23 +51,30 @@ Stores metadata about files in the filesystem being backed up. - `link_target` (TEXT) - Symlink target path (NULL for regular files) **Indexes:** + - `idx_files_path` on `path` for efficient lookups -**Purpose:** Tracks file metadata to detect changes between backup runs. Used for incremental backup decisions. The UUID primary key provides stable references that don't change if files are moved. +**Purpose:** Tracks file metadata to detect changes between backup runs. Used +for incremental backup decisions. The UUID primary key provides stable +references that don't change if files are moved. ### 2. `chunks` + Stores information about content-defined chunks created from files. **Columns:** + - `chunk_hash` (TEXT PRIMARY KEY) - SHA256 hash of chunk content - `size` (INTEGER NOT NULL) - Chunk size in bytes **Purpose:** Enables deduplication by tracking unique chunks across all files. ### 3. `file_chunks` + Maps files to their constituent chunks in order. **Columns:** + - `file_id` (TEXT) - File ID (FK to files.id) - `idx` (INTEGER) - Chunk index within file (0-based) - `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash) @@ -74,35 +83,49 @@ Maps files to their constituent chunks in order. **Purpose:** Allows reconstruction of files from chunks during restore. ### 4. `chunk_files` + Reverse mapping showing which files contain each chunk. **Columns:** + - `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash) - `file_id` (TEXT) - File ID (FK to files.id) - `file_offset` (INTEGER) - Byte offset of chunk within file - `length` (INTEGER) - Length of chunk in bytes - PRIMARY KEY (`chunk_hash`, `file_id`) -**Purpose:** Supports efficient queries for chunk usage and deduplication statistics. +**Purpose:** Supports efficient queries for chunk usage and deduplication +statistics. ### 5. `blobs` + Stores information about packed, compressed, and encrypted blob files. **Columns:** + - `id` (TEXT PRIMARY KEY) - UUID assigned when blob creation starts -- `blob_hash` (TEXT UNIQUE) - `hex(SHA256(SHA256(uncompressed blob contents)))`, computed before compression and encryption (NULL until finalized); see [REPOSTRUCTURE.md](REPOSTRUCTURE.md#blobs-directory-blobs) +- `blob_hash` (TEXT UNIQUE) - `hex(SHA256(SHA256(uncompressed blob contents)))`, + computed before compression and encryption (NULL until finalized); see + [REPOSTRUCTURE.md](REPOSTRUCTURE.md#blobs-directory-blobs) - `created_ts` (INTEGER NOT NULL) - Creation timestamp - `finished_ts` (INTEGER) - Finalization timestamp (NULL if in progress) -- `uncompressed_size` (INTEGER NOT NULL DEFAULT 0) - Total size of chunks before compression -- `compressed_size` (INTEGER NOT NULL DEFAULT 0) - Size after compression and encryption +- `uncompressed_size` (INTEGER NOT NULL DEFAULT 0) - Total size of chunks before + compression +- `compressed_size` (INTEGER NOT NULL DEFAULT 0) - Size after compression and + encryption. Once uploaded, the size of the object in storage: when the blob + was already stored, under another compression level or other recipients, this + can differ from the size of the local copy - `uploaded_ts` (INTEGER) - Upload completion timestamp (NULL if not uploaded) -**Purpose:** Tracks blob lifecycle from creation through upload. The UUID primary key allows immediate association of chunks with blobs. +**Purpose:** Tracks blob lifecycle from creation through upload. The UUID +primary key allows immediate association of chunks with blobs. ### 6. `blob_chunks` + Maps chunks to the blobs that contain them. **Columns:** + - `blob_id` (TEXT) - Blob ID (FK to blobs.id) - `chunk_hash` (TEXT) - Chunk hash (FK to chunks.chunk_hash) - `offset` (INTEGER) - Byte offset of chunk within blob (before compression) @@ -112,32 +135,46 @@ Maps chunks to the blobs that contain them. **Purpose:** Enables chunk retrieval from blobs during restore operations. ### 7. `snapshots` + Tracks backup snapshots. **Columns:** -- `id` (TEXT PRIMARY KEY) - Snapshot ID (format: hostname-YYYYMMDD-HHMMSSZ) + +- `id` (TEXT PRIMARY KEY) - Snapshot ID (format: `hostname_name_timestamp`, e.g. + `server1_home_2025-06-01T12:00:00Z`: the hostname up to its first `.`, the + snapshot name, and an RFC 3339 UTC timestamp) - `hostname` (TEXT) - Hostname where backup was created - `vaultik_version` (TEXT) - Version of Vaultik used - `vaultik_git_revision` (TEXT) - Git revision of Vaultik used - `started_at` (INTEGER) - Start timestamp - `completed_at` (INTEGER) - Completion timestamp (NULL if in progress) - `file_count` (INTEGER) - Number of files in snapshot -- `chunk_count` (INTEGER) - Number of unique chunks -- `blob_count` (INTEGER) - Number of blobs referenced +- `chunk_count` (INTEGER) - Number of chunks this snapshot stored that were not + stored before +- `new_chunk_size` (INTEGER) - Total size of those chunks before compression; + `snapshot list` shows it as NEW CHUNK SIZE +- `blob_count` (INTEGER) - Number of blobs this snapshot created - `total_size` (INTEGER) - Total size of all files -- `blob_size` (INTEGER) - Total size of all blobs (compressed) -- `blob_uncompressed_size` (INTEGER) - Total uncompressed size of all referenced blobs +- `uncompressed_chunk_size` (INTEGER) - Total size before compression of the + distinct chunks the snapshot's files reference, recorded when its backup ran; + `snapshot list` shows it as UNCOMPRESSED SIZE +- `blob_size` (INTEGER) - Total compressed size of all referenced blobs +- `blob_uncompressed_size` (INTEGER) - Total uncompressed size of all referenced + blobs - `compression_ratio` (REAL) - Compression ratio achieved - `compression_level` (INTEGER) - Compression level used for this snapshot - `upload_bytes` (INTEGER) - Total bytes uploaded during this snapshot - `upload_duration_ms` (INTEGER) - Total milliseconds spent uploading to S3 -**Purpose:** Provides snapshot metadata and statistics including version tracking for compatibility. +**Purpose:** Provides snapshot metadata and statistics including version +tracking for compatibility. ### 8. `snapshot_files` + Maps snapshots to the files they contain. **Columns:** + - `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id) - `file_id` (TEXT) - File ID (FK to files.id) - PRIMARY KEY (`snapshot_id`, `file_id`) @@ -145,99 +182,147 @@ Maps snapshots to the files they contain. **Purpose:** Records which files are included in each snapshot. ### 9. `snapshot_blobs` + Maps snapshots to the blobs they reference. **Columns:** + - `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id) - `blob_id` (TEXT) - Blob ID (FK to blobs.id) - `blob_hash` (TEXT) - Denormalized blob hash for manifest generation - PRIMARY KEY (`snapshot_id`, `blob_id`) -**Purpose:** Tracks blob dependencies for snapshots and enables manifest generation. +**Purpose:** Tracks blob dependencies for snapshots and enables manifest +generation. + +### 10. `snapshot_mount_points` + +The directories at or below a configured path, the configured path itself +included, that a snapshot's backup found an entry in and, once it had listed +them, found on a different filesystem from their parent directory (a different +device number), as a mount point is. An automount point whose volume cannot be +mounted is not recorded, because the backup finds no entry in it. + +**Columns:** + +- `snapshot_id` (TEXT) - Snapshot ID (FK to snapshots.id) +- `path` (TEXT) - Absolute path of the directory +- PRIMARY KEY (`snapshot_id`, `path`) + +**Purpose:** Lets `snapshot create --prune` skip the prune when a backup does +not find a mount point that an earlier snapshot of the same name found, as when +the volume is not mounted. + +### 11. `uploads` -### 10. `uploads` Tracks blob upload metrics. **Columns:** + - `blob_hash` (TEXT PRIMARY KEY) - Hash of uploaded blob -- `snapshot_id` (TEXT NOT NULL) - The snapshot that triggered this upload (FK to snapshots.id) +- `snapshot_id` (TEXT NOT NULL) - The snapshot that triggered this upload (FK to + snapshots.id) - `uploaded_at` (INTEGER) - Upload timestamp - `size` (INTEGER) - Size of uploaded blob - `duration_ms` (INTEGER) - Upload duration in milliseconds -**Purpose:** Performance monitoring and tracking which blobs were newly created (uploaded) during each snapshot. +**Purpose:** Performance monitoring and tracking which blobs were newly created +(uploaded) during each snapshot. ## Data Flow and Operations ### 1. Backup Process 1. **File Scanning** - - `INSERT OR REPLACE INTO files` - Update file metadata - - `SELECT * FROM files WHERE path = ?` - Check if file has changed - - `INSERT INTO snapshot_files` - Add file to current snapshot + - `INSERT OR REPLACE INTO files` - Update file metadata + - `SELECT * FROM files WHERE path = ?` - Check if file has changed + - `INSERT INTO snapshot_files` - Add file to current snapshot + - `INSERT OR IGNORE INTO snapshot_mount_points` - Record each directory on a + different filesystem from its parent that the walk found an entry in 2. **Chunking** (for changed files) - - `INSERT OR IGNORE INTO chunks` - Store new chunks - - `INSERT INTO file_chunks` - Map chunks to file - - `INSERT INTO chunk_files` - Create reverse mapping + - `INSERT OR IGNORE INTO chunks` - Store new chunks + - `INSERT INTO file_chunks` - Map chunks to file + - `INSERT INTO chunk_files` - Create reverse mapping 3. **Blob Packing** - - `INSERT INTO blobs` - Create blob record with UUID (blob_hash NULL) - - `INSERT INTO blob_chunks` - Associate chunks with blob immediately - - `UPDATE blobs SET blob_hash = ?, finished_ts = ?` - Finalize blob after packing + - `INSERT INTO blobs` - Create blob record with UUID (blob_hash NULL) + - `INSERT INTO blob_chunks` - Associate chunks with blob immediately + - `UPDATE blobs SET blob_hash = ?, finished_ts = ?` - Finalize blob after + packing 4. **Upload** - - `UPDATE blobs SET uploaded_ts = ?` - Mark blob as uploaded - - `INSERT INTO uploads` - Record upload metrics with snapshot_id - - `INSERT INTO snapshot_blobs` - Associate blob with snapshot + - `UPDATE blobs SET uploaded_ts = ?, compressed_size = ?` - Mark blob as + uploaded, with the size of the object in storage (the upload is skipped + when the blob is already stored) + - `INSERT INTO uploads` - Record upload metrics with snapshot_id + - `INSERT INTO snapshot_blobs` - Associate blob with snapshot 5. **Snapshot Completion** - - `UPDATE snapshots SET completed_at = ?, stats...` - Finalize snapshot - - Generate and upload blob manifest from `snapshot_blobs` + - `UPDATE snapshots SET completed_at = ?, stats...` - Finalize snapshot + - Generate and upload blob manifest from `snapshot_blobs` ### 2. Incremental Backup 1. **Change Detection** - - `SELECT * FROM files WHERE path = ?` - Get previous file metadata - - Compare mtime, size, mode to detect changes - - Skip unchanged files but still add to `snapshot_files` + - `SELECT * FROM files WHERE path = ?` - Get previous file metadata + - Compare mtime, size, mode to detect changes + - Re-chunk a file that lists a chunk no uploaded blob holds, even when its + metadata is unchanged + - Skip unchanged files but still add to `snapshot_files` 2. **Chunk Reuse** - - `SELECT * FROM blob_chunks WHERE chunk_hash = ?` - Find existing chunks - - `INSERT INTO snapshot_blobs` - Reference existing blobs for unchanged files + - `SELECT * FROM blob_chunks WHERE chunk_hash = ?` - Find existing chunks + - `INSERT INTO snapshot_blobs` - Reference existing blobs for unchanged + files ### 3. Snapshot Metadata Export After a snapshot is completed: + 1. Copy database to temporary file 2. Clean temporary database to contain only current snapshot data 3. VACUUM the trimmed database so deleted rows leave no pages behind 4. Compress with zstd and encrypt with age 5. Upload to S3 as `metadata/{remote-key}/db.zst.age` -6. Generate blob manifest and upload as `metadata/{remote-key}/manifest.json.zst` +6. Generate blob manifest and upload as + `metadata/{remote-key}/manifest.json.zst` -The `{remote-key}` directory name is a one-way hash of the human snapshot ID, so the ID is never written to the store in plaintext. The hash uses no secret, so a guessed hostname and snapshot name can still be confirmed against a listing; see [REPOSTRUCTURE.md](REPOSTRUCTURE.md#remote-key-derivation) and its [Accepted Risks](REPOSTRUCTURE.md#accepted-risks). +The `{remote-key}` directory name is a one-way hash of the human snapshot ID, so +the ID is never written to the store in plaintext. The hash uses no secret, so a +guessed hostname and snapshot name can still be confirmed against a listing; see +[REPOSTRUCTURE.md](REPOSTRUCTURE.md#remote-key-derivation) and its +[Accepted Risks](REPOSTRUCTURE.md#accepted-risks). ### 4. Restore Process The restore process doesn't use the local database. Instead: -1. Downloads snapshot metadata from S3 -2. Downloads required blobs based on manifest + +1. Downloads and decrypts the snapshot's metadata database (`db.zst.age`) from + S3 +2. Downloads the blobs holding the chunks of the files being restored, found + through that database's `blob_chunks` table; the manifest is not read 3. Reconstructs files from decrypted and decompressed chunks ### 5. Pruning 1. **Identify Unreferenced Blobs** - - Query blobs not referenced by any remaining snapshot - - Delete from S3 and local database + - Query blobs not referenced by any remaining snapshot + - Delete from S3, once older than `prune_grace_period`, and from the local + database +2. **Delete Metadata Directories With No Manifest** + - Delete each directory under `metadata/` that has no `manifest.json.zst` + and no local snapshot record, once every object in it is older than + `prune_grace_period` ### 6. Incomplete Snapshot Cleanup Before each backup: + 1. Query incomplete snapshots (where `completed_at IS NULL`) -2. Check if metadata exists in S3 -3. If no metadata, delete snapshot and all associations -4. Clean up orphaned files, chunks, and blobs +2. Delete each one and all its associations, without checking S3 for its + metadata +3. Clean up orphaned files, chunks, and blobs ## Repository Pattern @@ -246,18 +331,20 @@ Vaultik uses a repository pattern for database access: - `FileRepository` - CRUD operations for files and file metadata - `ChunkRepository` - CRUD operations for content chunks - `FileChunkRepository` - Manage file-to-chunk mappings -- `ChunkFileRepository` - Manage chunk-to-file reverse mappings +- `ChunkFileRepository` - Manage chunk-to-file reverse mappings - `BlobRepository` - Manage blob lifecycle (creation, finalization, upload) - `BlobChunkRepository` - Manage blob-to-chunk associations - `SnapshotRepository` - Manage snapshots and their relationships - `UploadRepository` - Track blob upload metrics Each repository provides methods like: + - `Create()` - Insert new record - `GetByID()` / `GetByPath()` / `GetByHash()` - Retrieve records - `Update()` - Update existing records - `Delete()` - Remove records -- Specialized queries for each entity type (e.g., `DeleteOrphaned()`, `GetIncompleteByHostname()`) +- Specialized queries for each entity type (e.g., `DeleteOrphaned()`, + `GetIncompleteByHostname()`) ## Transaction Management @@ -270,25 +357,33 @@ err := repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { ``` This ensures consistency, especially important for operations like: + - Creating file-chunk mappings - Associating chunks with blobs - Updating snapshot statistics ## Performance Considerations -1. **Indexes**: - - Primary keys are automatically indexed - - `idx_files_path` on `files(path)` for efficient file lookups +1. **Indexes**: + - Primary keys are automatically indexed + - `idx_files_path` on `files(path)` for efficient file lookups -2. **Prepared Statements**: All queries use prepared statements for performance and security +2. **Prepared Statements**: All queries use prepared statements for performance + and security -3. **Batch Operations**: Where possible, operations are batched within transactions +3. **Batch Operations**: Where possible, operations are batched within + transactions -4. **Write-Ahead Logging**: SQLite WAL mode is enabled for better concurrency +4. **Write-Ahead Logging**: The local index runs in SQLite WAL mode with a + 10-second busy timeout, so a read-only command such as `snapshot list` can + read it while a backup writes to it. Committed rows can sit in the `-wal` + file beside the index until a checkpoint, so the metadata export copies the + index through SQLite (`VACUUM INTO`), not as a file ## Data Integrity -1. **Foreign Keys**: Enforced through CASCADE DELETE and application-level repository methods +1. **Foreign Keys**: Enforced through CASCADE DELETE and application-level + repository methods 2. **Unique Constraints**: Chunk hashes, file paths, and blob hashes are unique 3. **Null Handling**: Nullable fields clearly indicate in-progress operations -4. **Timestamp Tracking**: All major operations record timestamps for auditing \ No newline at end of file +4. **Timestamp Tracking**: All major operations record timestamps for auditing diff --git a/docs/REPOSTRUCTURE.md b/docs/REPOSTRUCTURE.md index 0ad5884..856d63f 100644 --- a/docs/REPOSTRUCTURE.md +++ b/docs/REPOSTRUCTURE.md @@ -1,10 +1,13 @@ # Vaultik S3 Repository Structure -This document describes the structure and organization of data stored in the S3 bucket by Vaultik. +This document describes the structure and organization of data stored in the S3 +bucket by Vaultik. ## Overview -Vaultik stores all backup data in an S3-compatible object store. The repository consists of two main components: +Vaultik stores all backup data in an S3-compatible object store. The repository +consists of two main components, plus a marker file: + 1. **Blobs** - The actual backup data (content-addressed, encrypted) 2. **Metadata** - Snapshot information and manifests (partially encrypted) @@ -12,6 +15,7 @@ Vaultik stores all backup data in an S3-compatible object store. The repository ``` // +├── vaultik-destination.txt ├── blobs/ │ └── / │ └── / @@ -22,114 +26,208 @@ Vaultik stores all backup data in an S3-compatible object store. The repository └── manifest.json.zst ``` -The metadata subdirectory is named with the **remote key**, a one-way hash of the snapshot ID, not with the human-readable snapshot ID itself. See [Remote Key Derivation](#remote-key-derivation). +The metadata subdirectory is named with the **remote key**, a one-way hash of +the snapshot ID, not with the human-readable snapshot ID itself. See +[Remote Key Derivation](#remote-key-derivation). + +## Marker File (`vaultik-destination.txt`) + +Every backup writes this file at the root before it uploads anything. It holds +one fixed line of plain text and names no host, path or time. While the local +index holds snapshots stored there, a destination that answers a look-up of the +marker with not found is treated as not present: `snapshot create` refuses to +write to it, and `prune`, `snapshot purge`, `snapshot remove`, `snapshot list` +and `remote nuke` behave as for a destination that cannot be listed. An +unplugged volume leaves an empty directory at its mount point, and without the +marker that directory would read as a destination whose snapshots are all gone. +`remote nuke` deletes the marker last. + +When the look-up of the marker fails for any reason other than not found, the +check is skipped and the command goes on. S3 refuses it on every run to +credentials that allow only PUT, so a host with such credentials does not notice +a destination emptied since its last backup, and its next backup would leave out +the data its local index records as already stored. After the destination is +emptied, run `vaultik database delete` on such a host before it backs up again. ## Blobs Directory (`blobs/`) ### Structure + - **Path format**: `blobs///` -- **Example**: `blobs/ca/fe/cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678` -- **Sharding**: The two-level directory structure (using the first 4 characters of the hash) prevents any single directory from containing too many objects +- **Example**: + `blobs/ca/fe/cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678` +- **Sharding**: The two-level directory structure (using the first 4 characters + of the hash) prevents any single directory from containing too many objects ### Content + - **What it contains**: Packed collections of content-defined chunks from files - **Format**: Zstandard compressed, then Age encrypted - **Encryption**: Always encrypted with Age using the configured recipients -- **Naming**: Content-addressed. The blob's name is `hex(SHA256(SHA256(uncompressed blob contents)))` — the double SHA-256 of the concatenated chunk data, computed before compression and encryption, not a hash of the stored (compressed, encrypted) bytes. One consequence: only a holder of the age private key can check a stored blob's integrity, because matching a blob to its name means decrypting and decompressing it first — which is what `restore` and `verify --deep` do. Implemented in `internal/blobgen` (`DoubleSHA256`). This is the canonical description of blob naming; other documents and comments point here. +- **Naming**: Content-addressed. The blob's name is + `hex(SHA256(SHA256(uncompressed blob contents)))` — the double SHA-256 of the + concatenated chunk data, computed before compression and encryption, not a + hash of the stored (compressed, encrypted) bytes. One consequence: only a + holder of the age private key can check a stored blob's integrity, because + matching a blob to its name means decrypting and decompressing it first — + which is what `restore` and `verify --deep` do. Implemented in + `internal/blobgen` (`DoubleSHA256`). This is the canonical description of blob + naming; other documents and comments point here. ### Why Encrypted -Blobs contain the actual file data from backups and must be encrypted for security. The content-addressing ensures deduplication while the encryption ensures privacy. + +Blobs contain the actual file data from backups and must be encrypted for +security. The content-addressing ensures deduplication while the encryption +ensures privacy. ## Metadata Directory (`metadata/`) -Each snapshot has its own subdirectory. The directory is **not** named with the human-readable snapshot ID; it is named with the remote key — a one-way hash of that ID. The human ID is never written to the destination store as a directory name (see [Remote Key Derivation](#remote-key-derivation)). +Each snapshot has its own subdirectory. The directory is **not** named with the +human-readable snapshot ID; it is named with the remote key — a one-way hash of +that ID. The human ID is never written to the destination store as a directory +name (see [Remote Key Derivation](#remote-key-derivation)). ### Snapshot ID Format -The human-readable snapshot ID is used in CLI arguments, log lines, and the local database. It is not written to the destination store. -- **Format**: `__` (or `_` if no - name was specified) +The human-readable snapshot ID is used in CLI arguments, log lines, and the +local database. It is not written to the destination store. + +- **Format**: `__` (or `_` + if no name was specified) - **Example**: `laptop_home_2024-01-15T14:30:52Z` - **Components**: - - Short hostname (everything before the first dot is stripped from the FQDN) - - Snapshot name from the configured `snapshots:` map (optional) - - RFC3339 UTC timestamp + - Short hostname (everything before the first dot is stripped from the FQDN) + - Snapshot name from the configured `snapshots:` map (optional) + - RFC3339 UTC timestamp -This ID reveals the hostname, the configured snapshot name, and the backup time, so it is never used as the on-disk directory name — the remote key is used instead. +This ID reveals the hostname, the configured snapshot name, and the backup time, +so it is never used as the on-disk directory name — the remote key is used +instead. ### Remote Key Derivation -The remote key is `hex(SHA256(SHA256("vaultik|" + snapshot-id)))`: a double SHA-256 over the snapshot ID, with a `vaultik|` domain-separation prefix. The result is a 64-character hex string. The hash is not reversible, but it uses no secret: an observer who guesses a candidate hostname and snapshot name can hash it the same way and confirm whether that snapshot is present. The remote key keeps names out of a plain listing; it does not hide them from a guess. Implemented in `internal/snapshot/remotekey.go`. +The remote key is `hex(SHA256(SHA256("vaultik|" + snapshot-id)))`: a double +SHA-256 over the snapshot ID, with a `vaultik|` domain-separation prefix. The +result is a 64-character hex string. The hash is not reversible, but it uses no +secret: an observer who guesses a candidate hostname and snapshot name can hash +it the same way and confirm whether that snapshot is present. The remote key +keeps names out of a plain listing; it does not hide them from a guess. +Implemented in `internal/snapshot/remotekey.go`. Worked example: + - Snapshot ID: `server1_home_2025-06-01T12:00:00Z` - Remote key: `17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa` -- Directory: `metadata/17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa/` +- Directory: + `metadata/17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa/` -A plain listing of the destination store therefore shows only these hashes, not the hostname or snapshot name of any backup — but because the hash uses no secret, a guessed hostname and snapshot name can be hashed and confirmed against the listing. The same remote key is stored in the manifest's `snapshot_id` field. +A plain listing of the destination store therefore shows only these hashes, not +the hostname or snapshot name of any backup — but because the hash uses no +secret, a guessed hostname and snapshot name can be hashed and confirmed against +the listing. The same remote key is stored in the manifest's `snapshot_id` +field. ### Files in Each Snapshot Directory #### `db.zst.age` - Encrypted Database + - **What it contains**: Pruned binary SQLite database for this snapshot - **Format**: Binary SQLite → Zstandard compressed → Age encrypted - **Encryption**: Encrypted with Age -- **Purpose**: Contains full file metadata, chunk mappings, and all relationships -- **Why encrypted**: Contains sensitive metadata like file paths, permissions, and ownership +- **Purpose**: Contains full file metadata, chunk mappings, and all + relationships +- **Why encrypted**: Contains sensitive metadata like file paths, permissions, + and ownership #### `manifest.json.zst` - Unencrypted Blob Manifest + - **What it contains**: JSON list of all blob hashes referenced by this snapshot - **Format**: JSON → Zstandard compressed (NOT encrypted) - **Encryption**: NOT encrypted - **Purpose**: Enables pruning operations without requiring decryption keys - **Structure**: + ```json { - "snapshot_id": "17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa", - "timestamp": "2025-06-01T12:00:00Z", - "blob_count": 42, - "total_compressed_size": 1048576, - "blobs": [ - { "hash": "cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678", "compressed_size": 24576 }, - { "hash": "deadbeef1234567890abcdef1234567890abcdef1234567890abcdef12345678", "compressed_size": 32768 } - ] + "snapshot_id": "17f97bcde958748af076b926af59823943db59e80ce7170b40f124dfa28f64aa", + "timestamp": "2025-06-01T12:00:00Z", + "blob_count": 42, + "total_compressed_size": 1048576, + "blobs": [ + { + "hash": "cafebabe1234567890abcdef1234567890abcdef1234567890abcdef12345678", + "compressed_size": 24576 + }, + { + "hash": "deadbeef1234567890abcdef1234567890abcdef1234567890abcdef12345678", + "compressed_size": 32768 + } + ] } ``` -`snapshot_id` is the remote key (a hash), not the human ID; `timestamp` is written in the clear. + +`snapshot_id` is the remote key (a hash), not the human ID; `timestamp` is +written in the clear. ### Why Manifest is Unencrypted + The manifest must be readable without the private key to enable: + 1. **Pruning operations** - Identifying unreferenced blobs for deletion 2. **Storage analysis** - Understanding space usage without decryption 3. **Verification** - Checking blob existence without decryption -4. **Cross-snapshot deduplication analysis** - Finding shared blobs between snapshots +4. **Cross-snapshot deduplication analysis** - Finding shared blobs between + snapshots -The manifest contains the remote key, the backup timestamp, the blob count and total compressed size, and each blob's hash and compressed size. It contains no file names, paths, or other decrypted metadata. +The manifest contains the remote key, the backup timestamp, the blob count and +total compressed size, and each blob's hash and compressed size. It contains no +file names, paths, or other decrypted metadata. ## Security Considerations ### What's Encrypted + - **All file content** (in blobs) -- **All file metadata** (paths, permissions, timestamps, ownership in db.zst.age) +- **All file metadata** (paths, permissions, timestamps, ownership in + db.zst.age) - **File-to-chunk mappings** (in db.zst.age) ### What's Not Encrypted -- **The remote key** — directory names and the manifest `snapshot_id`, a one-way hash of the snapshot ID (see [Remote Key Derivation](#remote-key-derivation)) + +- **The remote key** — directory names and the manifest `snapshot_id`, a one-way + hash of the snapshot ID (see [Remote Key Derivation](#remote-key-derivation)) - **The backup timestamp** (in manifest.json.zst) - **Blob hashes and their compressed sizes** (in manifest.json.zst) - **Blob count and total compressed size per snapshot** (in manifest.json.zst) ### Privacy Implications -From the unencrypted data, an observer of the destination store can determine: -- **When each backup was taken** — not from the directory name, which is a one-way hash, but from the plaintext `timestamp` field in manifest.json.zst, which is published in the clear -- How many blobs each snapshot references, and the total compressed size -- The compressed size of each blob, and which blobs are shared between snapshots (deduplication patterns) -- **Whether a guessed hostname and snapshot name are present** — the remote key is an unkeyed hash, so an observer holding candidate names can hash each one and match it against the directory listing. The human ID is never published, so it cannot be read off directly, but it can be confirmed by guessing. -Together these give an observer a timing-and-size profile of every snapshot. This is an accepted, documented property of the format, not a defect: the manifest is unencrypted so that pruning can run without the private key, and the timing channel could not be closed by encrypting it anyway — object creation times and per-object sizes stay visible at the storage layer on both `s3://` and `file://` destinations regardless. +From the unencrypted data, an observer of the destination store can determine: + +- **When each backup was taken** — not from the directory name, which is a + one-way hash, but from the plaintext `timestamp` field in manifest.json.zst, + which is published in the clear +- How many blobs each snapshot references, and the total compressed size +- The compressed size of each blob, and which blobs are shared between snapshots + (deduplication patterns) +- **Whether a guessed hostname and snapshot name are present** — the remote key + is an unkeyed hash, so an observer holding candidate names can hash each one + and match it against the directory listing. The human ID is never published, + so it cannot be read off directly, but it can be confirmed by guessing. + +Together these give an observer a timing-and-size profile of every snapshot. +This is an accepted, documented property of the format, not a defect: the +manifest is unencrypted so that pruning can run without the private key, and the +timing channel could not be closed by encrypting it anyway — object creation +times and per-object sizes stay visible at the storage layer on both `s3://` and +`file://` destinations regardless. An observer cannot determine: -- The hostname or snapshot name of any backup by reading it off the store — the directory name and the manifest `snapshot_id` are unkeyed hashes of the human ID, so the text is never published (though a guessed name can be confirmed, as above) + +- The hostname or snapshot name of any backup by reading it off the store — the + directory name and the manifest `snapshot_id` are unkeyed hashes of the human + ID, so the text is never published (though a guessed name can be confirmed, as + above) - File names or paths - File contents - File permissions or ownership @@ -138,40 +236,127 @@ An observer cannot determine: ### Accepted Risks -These are known, deliberate properties of the format and the tooling, recorded so an operator can weigh them rather than discover them. +These are known, deliberate properties of the format and the tooling, recorded +so an operator can weigh them rather than discover them. -1. **No proof of authorship.** Restore and `verify --deep` prove that data decrypts with the age private key and matches its unkeyed content hashes. They do not prove who wrote it: anyone who knows a recipient public key and can replace objects on the destination can substitute a snapshot they built. The recipient string is not stored at the destination, but a compromised backed-up host has it. Defences live on the destination side — bucket versioning or object lock, credentials for the source host that cannot delete or overwrite existing versions, and pruning from a trusted host. Note that S3 `PutObject` overwrites an existing key, so PUT permission alone is not append-only. -2. **Compression reveals sizes.** Blobs and `db.zst.age` are zstd-compressed then age-encrypted; the manifest is compressed only. age does not pad, so an object's size is the exact compressed length of its contents. All new chunks packed into one blob share a single zstd stream (8 MiB window, 4 MiB at compression levels 1-2), and a blob is closed at `blob_size_limit` and at the end of each configured path. Because a stored chunk is never packed again, someone who can write into a backed-up file and watch blob sizes learns something only when their controlled data and a secret land in the same chunk of a file that keeps changing. Advice: back up any outsider-writable directory as its own snapshot. -3. **Chunking uses no secret.** The FastCDC parameters are fixed and public. The default 10 MB average yields chunks between 2.5 MB and 40 MB, and any file of 2.5 MB or less is a single chunk. At the default 10 GB `blob_size_limit` a blob holds hundreds of chunks, so individual chunk lengths are not visible in the blob's size; lowering the limit toward the chunk size begins to expose them. -4. **Decrypted data on local disk.** Several commands stage plaintext under `$TMPDIR`: `snapshot restore` writes decrypted blobs under `vaultik-blobcache-*/` (no size cap) and the decrypted metadata database at `vaultik-restore-*/snapshot.db`; `verify --deep` writes that database at `vaultik-verify-*/snapshot.db`; `snapshot create` keeps a plaintext copy of the index at `vaultik-snapshot-*/snapshot.db`. These files are created `0600` and removed on success, but a `kill -9` or a power loss leaves them behind — delete any leftover `vaultik-*` directory under `$TMPDIR` by hand. `$TMPDIR` should be trusted to the same degree as the restore target. -5. **Store permissions differ per command.** The backed-up host needs only PUT to run `snapshot create`: it writes blobs and metadata and neither reads nor deletes them. Other commands need more — `snapshot verify`, `snapshot restore`, and `prune` list and read; `prune`, `snapshot purge`, `snapshot remove`, and `remote nuke` also delete. The recommended cron line uses `--prune`, which runs `prune` on the backed-up host, so granting that host `--prune` gives it credentials that can delete its own backups. To keep the source host to PUT only, prune from a separate trusted host instead. -6. **Changing recipients does not re-encrypt existing data.** Deduplicated chunks and same-named blobs already on the destination stay encrypted to the recipients in force when they were written. A new snapshot that reuses them cannot be restored with a newly added recipient's key alone, because those reused objects were never encrypted to it. To make everything readable by a new key, run `vaultik database delete` and take a full backup to a fresh destination or prefix. -7. **X25519 recipients only.** vaultik rejects age ssh and plugin recipients. Long-lived ciphertext held by a third party (the destination operator) has no fallback if X25519 is ever broken: there is no second recipient type and no post-quantum option. +1. **No proof of authorship.** Restore and `verify --deep` prove that data + decrypts with the age private key and matches its unkeyed content hashes. + They do not prove who wrote it: anyone who knows a recipient public key and + can replace objects on the destination can substitute a snapshot they built. + The recipient string is not stored at the destination, but a compromised + backed-up host has it. Defences live on the destination side — bucket + versioning or object lock, credentials for the source host that cannot delete + or overwrite existing versions, and pruning from a trusted host. Note that S3 + `PutObject` overwrites an existing key, so PUT permission alone is not + append-only. +2. **Compression reveals sizes.** Blobs and `db.zst.age` are zstd-compressed + then age-encrypted; the manifest is compressed only. age does not pad, so an + object's size is the exact compressed length of its contents. All new chunks + packed into one blob share a single zstd stream (8 MiB window, 4 MiB at + compression levels 1-2), and a blob is closed at `blob_size_limit` and at the + end of each configured path. Because a stored chunk is never packed again, + someone who can write into a backed-up file and watch blob sizes learns + something only when their controlled data and a secret land in the same chunk + of a file that keeps changing. Advice: back up any outsider-writable + directory as its own snapshot. +3. **Chunking uses no secret.** The FastCDC parameters are fixed and public. The + default 10 MB average yields chunks between 2.5 MB and 40 MB, and any file of + 2.5 MB or less is a single chunk. At the default 10 GB `blob_size_limit` a + blob holds hundreds of chunks, so individual chunk lengths are not visible in + the blob's size; lowering the limit toward the chunk size begins to expose + them. +4. **Decrypted data on local disk.** These commands stage plaintext under + `$TMPDIR`: + - `snapshot restore`: decrypted blobs under `vaultik-blobcache-*/`, with no + size cap, and the decrypted metadata database at + `vaultik-restore-*/snapshot.db`. + - `snapshot files`: the decrypted metadata database at + `vaultik-restore-*/snapshot.db`. + - `verify --deep`: the decrypted metadata database at + `vaultik-verify-*/snapshot.db`. + - `snapshot create`: a plaintext copy of the index at + `vaultik-snapshot-*/snapshot.db`. + + These files are created `0600` and removed on success, but a `kill -9` or a + power loss leaves them behind — delete any leftover `vaultik-*` directory + under `$TMPDIR` by hand. `$TMPDIR` should be trusted to the same degree as + the restore target. + +5. **Store permissions differ per command.** The backed-up host needs only PUT + to run `snapshot create`: it writes blobs and metadata and neither reads nor + deletes them. Other commands need more — `snapshot verify`, + `snapshot restore`, and `prune` list and read; `prune`, `snapshot purge`, + `snapshot remove`, and `remote nuke` also delete. The recommended cron line + uses `--prune`, which runs `prune` on the backed-up host, so granting that + host `--prune` gives it credentials that can delete its own backups. To keep + the source host to PUT only, prune from a separate trusted host instead. +6. **Changing recipients does not re-encrypt existing data.** Deduplicated + chunks and same-named blobs already on the destination stay encrypted to the + recipients in force when they were written. A new snapshot that reuses them + cannot be restored with a newly added recipient's key alone, because those + reused objects were never encrypted to it. To make everything readable by a + new key, run `vaultik database delete` and take a full backup to a fresh + destination or prefix. +7. **X25519 recipients only.** vaultik rejects age ssh and plugin recipients. + Long-lived ciphertext held by a third party (the destination operator) has no + fallback if X25519 is ever broken: there is no second recipient type and no + post-quantum option. ## Consistency Guarantees 1. **Blobs are immutable** - Once written, a blob is never modified -2. **Blobs are written before metadata** - A snapshot's metadata is only written after all its blobs are successfully uploaded -3. **Metadata is written atomically** - Both db.zst.age and manifest.json.zst are written as complete files -4. **A snapshot is marked complete in the local DB only after its metadata is uploaded** - `finalizeSnapshotMetadata` runs `ExportSnapshotMetadata` first and records completion (`MarkSnapshotComplete`) only once the export succeeds (see the backup data flow in [ARCHITECTURE.md](../ARCHITECTURE.md)). A crash during the export therefore leaves the snapshot incomplete, so the next backup's `PruneDatabase` drops it and re-backs-up its data, rather than leaving a completed-looking row in the local index with no matching metadata on the destination store. (A crash in the brief moment after the export succeeds but before completion is recorded leaves a fully-restorable snapshot on the destination that the local index drops as incomplete on the next run; `snapshot list` then reports it honestly as remote-only, which is the safe direction: the destination copy stays restorable.) +2. **Blobs are written before metadata** - A snapshot's metadata is only written + after all its blobs are successfully uploaded +3. **Metadata is written atomically** - Both db.zst.age and manifest.json.zst + are written as complete files +4. **A snapshot is marked complete in the local DB only after its metadata is + uploaded** - `finalizeSnapshotMetadata` runs `ExportSnapshotMetadata` first + and records completion (`MarkSnapshotComplete`) only once the export succeeds + (see the backup data flow in [ARCHITECTURE.md](ARCHITECTURE.md)). A crash + during the export therefore leaves the snapshot incomplete, so the next + backup's `PruneDatabase` drops it and re-backs-up its data, rather than + leaving a completed-looking row in the local index with no matching metadata + on the destination store. (A crash in the brief moment after the export + succeeds but before completion is recorded leaves a fully-restorable snapshot + on the destination that the local index drops as incomplete on the next run; + `snapshot list` then reports it honestly as remote-only, which is the safe + direction: the destination copy stays restorable.) ## Pruning Safety The prune operation is safe because: -1. It keeps every blob listed in any snapshot's manifest and deletes only blobs that no manifest references + +1. It keeps every blob listed in any snapshot's manifest and deletes only blobs + that no manifest references. Under `metadata/` it deletes only a directory + that has no `manifest.json.zst`, whose name is a remote key, and that no + local snapshot record claims 2. Manifests are unencrypted and can be read without keys -3. If any manifest cannot be downloaded or decoded, prune deletes nothing and exits with an error, rather than treating that snapshot's blobs as unreferenced -4. Prune requires exclusive access to the destination: running it during a concurrent backup can race a snapshot whose manifest is not yet written, so do not prune while a backup is in progress +3. If any manifest cannot be downloaded or decoded, prune deletes nothing and + exits with an error, rather than treating that snapshot's blobs as + unreferenced +4. It deletes an unreferenced blob only once the blob is older than + `prune_grace_period` (default `24h`), and a directory under `metadata/` with + no manifest only once every object in it is. A backup uploads its blobs and + its `db.zst.age` before its manifest, so a prune running meanwhile, on this + host or another sharing the destination, leaves them as long as no backup run + takes longer than the grace period. The grace period does not protect a blob + a backup reuses from an earlier run that stopped before its manifest: the + backup skips the upload of a blob already on the destination, so that blob + keeps the time of its first upload, and a prune before the backup's manifest + is written can delete it; the new snapshot then cannot be restored. + `remote nuke` has no such check ## Restoration Requirements To restore from a backup, you need: + 1. **The Age private key** - To decrypt blobs and database 2. **The snapshot metadata** - Both files from the snapshot's metadata directory 3. **All referenced blobs** - As listed in the manifest The restoration process: + 1. Download and decrypt the database dump to understand file structure 2. Download and decrypt the required blobs 3. Reconstruct files from their chunks -4. Restore file metadata (permissions, timestamps, etc.) \ No newline at end of file +4. Restore file metadata (permissions, timestamps, etc.) diff --git a/docs/TODO.md b/docs/TODO.md new file mode 100644 index 0000000..6d767c1 --- /dev/null +++ b/docs/TODO.md @@ -0,0 +1,22 @@ +# Workflow + +- branch (from `main`) +- do the work in Next Step +- delete Next Step from `TODO.md` +- move the top item of Future Steps into Next Step +- commit (`TODO.md` changes in the same commit as the work) +- merge to `main` if the branch is not protected, otherwise open a PR +- push + +# Status + +pre-1.0 + +# Next Step + +Fix the open bugs on the issue tracker that block the release. Merging `next` +into `main` is the owner's. + +# Future Steps + +Work planned after 1.0 is listed in the README [roadmap](../README.md#roadmap). diff --git a/go.mod b/go.mod index 23e63f2..8942241 100644 --- a/go.mod +++ b/go.mod @@ -20,9 +20,13 @@ require ( github.com/rclone/rclone v1.72.1 github.com/spf13/afero v1.15.0 github.com/spf13/cobra v1.10.1 + github.com/spf13/pflag v1.0.10 github.com/stretchr/testify v1.11.1 + go.uber.org/dig v1.19.0 go.uber.org/fx v1.24.0 + golang.org/x/mod v0.29.0 golang.org/x/sync v0.18.0 + golang.org/x/sys v0.38.0 golang.org/x/term v0.37.0 gopkg.in/yaml.v3 v3.0.1 modernc.org/sqlite v1.38.0 @@ -225,7 +229,6 @@ require ( github.com/smarty/assertions v1.16.0 // indirect github.com/sony/gobreaker v1.0.0 // indirect github.com/spacemonkeygo/monkit/v3 v3.0.25-0.20251022131615-eb24eb109368 // indirect - github.com/spf13/pflag v1.0.10 // indirect github.com/t3rm1n4l/go-mega v0.0.0-20251031123324-a804aaa87491 // indirect github.com/tidwall/gjson v1.18.0 // indirect github.com/tidwall/match v1.1.1 // indirect @@ -255,7 +258,6 @@ require ( go.opentelemetry.io/otel/metric v1.38.0 // indirect go.opentelemetry.io/otel/trace v1.38.0 // indirect go.shabbyrobe.org/gocovmerge v0.0.0-20230507111327-fa4f82cfbf4d // indirect - go.uber.org/dig v1.19.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect @@ -263,7 +265,6 @@ require ( golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect golang.org/x/net v0.47.0 // indirect golang.org/x/oauth2 v0.33.0 // indirect - golang.org/x/sys v0.38.0 // indirect golang.org/x/text v0.31.0 // indirect golang.org/x/time v0.14.0 // indirect golang.org/x/tools v0.38.0 // indirect diff --git a/internal/blob/packer.go b/internal/blob/packer.go index 1c588cc..cee01de 100644 --- a/internal/blob/packer.go +++ b/internal/blob/packer.go @@ -245,6 +245,17 @@ func (p *Packer) Flush(ctx context.Context) error { return nil } +// DiscardCurrentBlob closes and removes the temp file of the blob being +// packed, if any, and drops that blob. A caller that stops before Flush +// must call it, or the temp file is left behind. Thread-safe. +func (p *Packer) DiscardCurrentBlob() { + p.mu.Lock() + defer p.mu.Unlock() + + p.cleanupTempFile() + p.currentBlob = nil +} + // FinalizeBlob finalizes the current blob being assembled. // This compresses the accumulated chunks, encrypts the result, and computes // the content-addressed hash. The finalized blob is either passed to the diff --git a/internal/blobgen/negative_test.go b/internal/blobgen/negative_test.go index ef24723..bd712e7 100644 --- a/internal/blobgen/negative_test.go +++ b/internal/blobgen/negative_test.go @@ -2,8 +2,10 @@ package blobgen_test import ( "bytes" + "errors" "fmt" "testing" + "testing/iotest" "filippo.io/age" "github.com/stretchr/testify/assert" @@ -120,6 +122,38 @@ func TestNewReaderTrailingAndGarbage(t *testing.T) { }) } +// TestNewReaderGarbageErrorQuotesNoBytes checks that lines of text in +// place of a blob fail with ErrNotAgeStream, and that the error carries +// none of their bytes. The lines end in a newline because age's own error +// quotes the data's first line only when it reads a whole line. +func TestNewReaderGarbageErrorQuotesNoBytes(t *testing.T) { + t.Parallel() + + id, _ := makeIdentity(t) + garbage := bytes.Repeat([]byte("garbage-bytes-\n"), 100) + + _, err := blobgen.NewReader(bytes.NewReader(garbage), id) + + require.ErrorIs(t, err, blobgen.ErrNotAgeStream) + assert.NotContains(t, err.Error(), "garbage-bytes-") +} + +// errConnectionReset stands for a storage read that fails. +var errConnectionReset = errors.New("connection reset") + +// TestNewReaderReadFailure checks that a failed read of the age header is +// returned as that read error, not as ErrNotAgeStream. +func TestNewReaderReadFailure(t *testing.T) { + t.Parallel() + + id, _ := makeIdentity(t) + + _, err := blobgen.NewReader(iotest.ErrReader(errConnectionReset), id) + + require.ErrorIs(t, err, errConnectionReset) + assert.NotErrorIs(t, err, blobgen.ErrNotAgeStream) +} + // TestNewWriterInvalidLevel covers the rejected end of issue case 9: an // out-of-range compression level errors and writes nothing to the destination. func TestNewWriterInvalidLevel(t *testing.T) { diff --git a/internal/blobgen/reader.go b/internal/blobgen/reader.go index 27bad18..9886361 100644 --- a/internal/blobgen/reader.go +++ b/internal/blobgen/reader.go @@ -11,6 +11,11 @@ import ( "github.com/klauspost/compress/zstd" ) +// ErrNotAgeStream is returned by NewReader when the data cannot be opened +// as an age stream, for example because its header is malformed. It +// replaces age's own error, which can quote the data's first bytes. +var ErrNotAgeStream = errors.New("not a valid age stream") + // Reader wraps decompression and decryption with SHA256 verification type Reader struct { reader io.Reader @@ -24,11 +29,25 @@ type Reader struct { // NewReader creates a new Reader that decrypts, decompresses, and verifies // data. Every supplied identity is offered to age.Decrypt, so a blob // encrypted to any one of them can be read. +// +// A failure to read r is returned as that error, and a blob encrypted to +// none of the identities as age.NoIdentityMatchError. Any other failure +// to open the age stream is ErrNotAgeStream. func NewReader(r io.Reader, identities ...age.Identity) (*Reader, error) { - // Create decryption reader - decReader, err := age.Decrypt(r, identities...) + src := &readErrorRecorder{reader: r} + + decReader, err := age.Decrypt(src, identities...) if err != nil { - return nil, fmt.Errorf("creating decryption reader: %w", err) + var noMatch *age.NoIdentityMatchError + + switch { + case src.err != nil: + return nil, fmt.Errorf("reading age header: %w", src.err) + case errors.As(err, &noMatch): + return nil, fmt.Errorf("creating decryption reader: %w", err) + default: + return nil, ErrNotAgeStream + } } // Create decompression reader @@ -52,6 +71,23 @@ func NewReader(r io.Reader, identities ...age.Identity) (*Reader, error) { }, nil } +// readErrorRecorder passes reads through to reader and keeps the first +// error other than io.EOF, so NewReader can tell a failed read from bad +// data. +type readErrorRecorder struct { + reader io.Reader + err error +} + +func (r *readErrorRecorder) Read(p []byte) (int, error) { + n, err := r.reader.Read(p) + if err != nil && !errors.Is(err, io.EOF) && r.err == nil { + r.err = err + } + + return n, err +} + // Read implements io.Reader func (r *Reader) Read(p []byte) (int, error) { n, err := r.teeReader.Read(p) diff --git a/internal/cli/app.go b/internal/cli/app.go index dc305b3..e264bc8 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -7,13 +7,11 @@ import ( "context" "errors" "fmt" - "path/filepath" - "strings" "sync" "time" - "github.com/adrg/xdg" "github.com/spf13/cobra" + "go.uber.org/dig" "go.uber.org/fx" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" @@ -40,10 +38,11 @@ const ( // prune, remote nuke) write the local index or the remote store. They // hold the PID lock so that at most one runs at a time. mutating lockMode = iota - // readOnly commands (info, snapshot list, snapshot verify, remote info, - // snapshot restore) do not write the local index or the remote store, - // so they run without the lock and are never blocked by a running - // mutator. restore writes only to the target directory it is given. + // readOnly commands (info, snapshot list, snapshot files, snapshot + // verify, remote info, snapshot restore) do not write the local index + // or the remote store, so they run without the lock and are never + // blocked by a running mutator. restore writes only to the target + // directory it is given. readOnly ) @@ -90,7 +89,7 @@ func setupGlobals( // blank line. Used both from the fx hook (for subcommand invocations) and // from the root cobra Run handler (for `vaultik` with no subcommand). func writeStartupBanner(w *ui.Writer, startTime time.Time, shortCommit string) { - w.Bannerf("%s %s by %s (commit %s, built on %s) starting up at %s.", + w.Bannerf("%s %s by %s (commit %s, commit date %s) starting up at %s.", globals.Appname, globals.Version, globals.Author, shortCommit, globals.CommitDate, startTime.Format(time.RFC3339)) @@ -146,16 +145,12 @@ func (e *startupError) Error() string { // could not build arguments for function "Y" (file:line): failed to build U: // received non-nil error from function "Z" (file:line): // -// Users care about the real error, not the DI plumbing. We strip everything -// up through the last "): " (which is always the close-paren of an fx -// function-location annotation followed by the wrapped error). +// Users care about the real error, not the DI plumbing. dig.RootCause, +// from the library fx is built on, unwraps those layers and returns the +// real error whole. Cutting the text at "): " instead would also cut a +// real error that contains it, such as the blob_size_limit one. func cleanStartupError(err error) error { - msg := err.Error() - if idx := strings.LastIndex(msg, "): "); idx >= 0 { - msg = msg[idx+3:] - } - - return &startupError{msg: msg} + return &startupError{msg: dig.RootCause(err).Error()} } // RunApp starts the fx application, blocks until it is asked to stop, and @@ -200,12 +195,16 @@ func RunApp(ctx context.Context, app *fx.App) error { } // errReported marks a failure the operation has already shown the user -// (and deliberately withheld under --json). Entry turns it into a -// non-zero exit status without printing anything further, so the error -// line is not doubled. It flows up from RunOperation through cobra to -// Entry. +// (or, under `snapshot verify --json`, put in its document). Entry +// turns it into a non-zero exit status without printing anything +// further, so the error line is not doubled. It flows up from +// RunOperation through cobra to Entry. var errReported = errors.New("operation failed") +// errInterrupted marks an operation that SIGINT or SIGTERM stopped +// before it finished. Entry shows it and returns exitCodeInterrupted. +var errInterrupted = errors.New("interrupted before the command finished") + // RunOperation runs op against the Vaultik instance inside the fx app // and turns a failure into a returned error rather than an os.Exit from // within the goroutine. An os.Exit there skipped main's deferred @@ -220,17 +219,21 @@ var errReported = errors.New("operation failed") // interrupt OnStop cancels op and waits for the goroutine to return, so // op's cleanup (removing decrypted scratch files) runs before the // process exits; the wait is bounded by shutdownTimeout. report is -// called with a non-canceled failure so the caller can log it (and -// suppress it under --json) before it becomes errReported. A context -// cancellation is the interrupt path, not a failure: it is neither -// reported nor counted as one. +// called with a failure so the caller can show it to the user before +// it becomes errReported. +// +// The run counts as interrupted unless op returned, without an +// interrupt having cancelled it, before RunWithApp returned. An +// interrupted op is not reported, whatever it returned; RunOperation +// returns errInterrupted instead. func RunOperation( ctx context.Context, opts AppOptions, op func(v *vaultik.Vaultik) error, report func(err error), ) error { var ( - mu sync.Mutex - failed bool + mu sync.Mutex + finished bool // op returned before any interrupt cancelled it + failed bool // op finished with an error ) opts.Invokes = append(opts.Invokes, @@ -241,11 +244,21 @@ func RunOperation( OnStart: func(_ context.Context) error { stop = v.StartOperation(func() { err := op(v) - if err != nil && !errors.Is(err, context.Canceled) { - report(err) + + // Only stop, called from OnStop below, cancels the + // Vaultik context, so a live context means no + // interrupt cancelled op. Check the context, not + // err: an interrupted op need not return + // context.Canceled (`snapshot verify --json` + // returns a verification failure). + if v.Context().Err() == nil { + if err != nil { + report(err) + } mu.Lock() - failed = true + finished = true + failed = err != nil mu.Unlock() } @@ -278,28 +291,34 @@ func RunOperation( return err } - // The goroutine sets failed before triggering the shutdown that lets - // RunWithApp return, so the write is in place by the time we read it. + // RunWithApp returns only after the app was asked to stop, either by + // an interrupt or by the goroutine's Shutdown call. When op finished + // without being cancelled, the goroutine set finished before that + // call. So if finished is unset here, an interrupt stopped the app, + // and op either returned after it was cancelled or is still running + // because the shutdown timed out. mu.Lock() defer mu.Unlock() - if failed { + switch { + case !finished: + return errInterrupted + case failed: return errReported + default: + return nil } - - return nil } // runVaultikApp runs the standard single-operation command lifecycle -// shared by the snapshot list/purge/remove and remote nuke subcommands: +// shared by the snapshot list/files/purge/remove and remote nuke subcommands: // resolve the config, then run op against the Vaultik instance through -// RunOperation, reporting a failure prefixed with failMsg (suppressed -// while suppressErrors is true, e.g. under --json). mode says whether the -// command takes the PID lock. jsonOutput marks a command whose stdout is a -// JSON document: it quiets the UI but, unlike Quiet, leaves the stderr log -// level alone. +// RunOperation, reporting a failure prefixed with failMsg on stderr. mode +// says whether the command takes the PID lock. jsonOutput marks a command +// whose stdout is a JSON document: it quiets the UI but, unlike Quiet, +// leaves the stderr log level alone. func runVaultikApp( - cmd *cobra.Command, mode lockMode, jsonOutput, suppressErrors bool, + cmd *cobra.Command, mode lockMode, jsonOutput bool, failMsg string, op func(v *vaultik.Vaultik) error, ) error { configPath, err := ResolveConfigPath() @@ -319,11 +338,7 @@ func runVaultikApp( }, Mode: mode, }, op, func(err error) { - if suppressErrors { - return - } - - log.Error(failMsg, "error", err) + log.Info(failMsg, "error", err) ReportErrorf("%s: %v", failMsg, err) }) } @@ -335,8 +350,7 @@ func runVaultikApp( // only one runs at a time; a read-only command runs without it and is not // blocked while a mutator holds the lock (opts.Mode). func RunWithApp(ctx context.Context, opts AppOptions) error { - release, err := acquireLockIfMutating(opts.Mode, - filepath.Join(xdg.DataHome, "vaultik")) + release, err := acquireLockIfMutating(opts.Mode, pidlock.Dir()) if err != nil { return err } diff --git a/internal/cli/app_test.go b/internal/cli/app_test.go index 102bfae..c1de5a0 100644 --- a/internal/cli/app_test.go +++ b/internal/cli/app_test.go @@ -2,58 +2,65 @@ package cli //nolint:testpackage // needs access to unexported cleanStartupError import ( "errors" + "os" "path/filepath" "testing" + "go.uber.org/fx" + "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/pidlock" ) +// TestCleanStartupError starts a real fx app whose config has a +// blob_size_limit below the minimum. fx puts annotations naming the +// functions it was building in front of the config error; only those +// may be removed, although the config error itself contains "): ". func TestCleanStartupError(t *testing.T) { t.Parallel() - tests := []struct { - name string - in string - want string - }{ - { - name: "real fx error chain", - in: `could not build arguments for function ` + - `"sneak.berlin/go/vaultik/internal/cli".newSnapshotCreateCommand.func1.1 ` + - `(/Users/user/dev/vaultik/internal/cli/snapshot.go:71): ` + - `failed to build *vaultik.Vaultik: ` + - `could not build arguments for function ` + - `"sneak.berlin/go/vaultik/internal/vaultik".New ` + - `(/Users/user/dev/vaultik/internal/vaultik/vaultik.go:59): ` + - `failed to build storage.Storer: ` + - `received non-nil error from function ` + - `"sneak.berlin/go/vaultik/internal/storage".NewStorer ` + - `(/Users/user/dev/vaultik/internal/storage/module.go:23): ` + - `creating base path: mkdir /Volumes/BACKUPS: permission denied`, - want: `creating base path: mkdir /Volumes/BACKUPS: permission denied`, - }, - { - name: "no fx wrapping", - in: "plain error", - want: "plain error", - }, - { - name: "single fx wrapping", - in: `received non-nil error from function "foo" (file.go:1): underlying problem`, - want: "underlying problem", - }, + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte("snapshots:\n"+ + " test:\n"+ + " paths: [/tmp/vaultik-test-source]\n"+ + "storage_url: file:///tmp/vaultik-test-storage\n"+ + "chunk_size: 10MB\n"+ + "blob_size_limit: 30MB\n"), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() + app := fx.New( + fx.NopLogger, + fx.Supply(config.Path(path)), + config.Module, + fx.Invoke(func(*config.Config) {}), + ) - //nolint:err113 // test constructs errors from table input - got := cleanStartupError(errors.New(tt.in)).Error() - if got != tt.want { - t.Errorf("got %q, want %q", got, tt.want) - } - }) + err = app.Start(t.Context()) + if err == nil { + t.Fatal("app started; want a blob_size_limit error") + } + + want := "failed to load config: invalid config: blob_size_limit must " + + "be at least the largest chunk the chunker can emit (chunk_size " + + "times the FastCDC size spread): need at least 40000000 bytes" + + got := cleanStartupError(err).Error() + if got != want { + t.Errorf("got %q, want %q", got, want) + } +} + +// TestCleanStartupErrorNotFromFx checks that an error fx did not wrap is +// shown unchanged. +func TestCleanStartupErrorNotFromFx(t *testing.T) { + t.Parallel() + + //nolint:err113 // a one-off error standing in for a startup failure + got := cleanStartupError(errors.New("plain error")).Error() + if got != "plain error" { + t.Errorf("got %q, want %q", got, "plain error") } } diff --git a/internal/cli/config.go b/internal/cli/config.go index ae8aad9..fe0face 100644 --- a/internal/cli/config.go +++ b/internal/cli/config.go @@ -7,11 +7,16 @@ import ( "os" "os/exec" "path/filepath" + "reflect" + "runtime" + "slices" "strconv" "strings" + "unicode/utf8" "github.com/spf13/cobra" "gopkg.in/yaml.v3" + "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/ui" ) @@ -26,11 +31,14 @@ const configSetArgs = 2 // parent config dirs (e.g. ~/.config) are conventionally traversable. const configDirMode = 0o755 -// configYAMLIndent matches the 2-space indentation of defaultConfigTemplate, +// configYAMLIndent matches the 2-space indentation of the default config, // so `config set` writes the file back with the same indentation rather than // yaml.Marshal's 4-space default. const configYAMLIndent = 2 +// yamlStringTag is YAML's tag for a string scalar. +const yamlStringTag = "!!str" + var ( errConfigExists = errors.New("config file already exists") errEmptyConfig = errors.New("empty config file") @@ -38,23 +46,50 @@ var ( errNeedNumericIndex = errors.New("key is a list; use a numeric index") errIndexOutOfRange = errors.New("index out of range") errNotMapOrList = errors.New("key is not a map or list") + errWouldNotLoad = errors.New( + "vaultik would not load the config after this change, " + + "so the file was not changed") + errSetS3KeysFirst = errors.New( + "set s3.access_key_id and s3.secret_access_key first, " + + "then storage_url") ) -const defaultConfigTemplate = `# vaultik configuration +// storageURLKey is the config key that selects the storage backend. +const storageURLKey = "storage_url" + +// macOS is the value of runtime.GOOS on macOS. +const macOS = "darwin" + +// defaultConfigText returns the file `config init` writes on the operating +// system goos, named as runtime.GOOS names it. Only macOS gets the apps +// snapshot, since /Applications exists nowhere else. +func defaultConfigText(goos string) string { + if goos == macOS { + return defaultConfigHead + appsSnapshotConfig + defaultConfigTail + } + + return defaultConfigHead + defaultConfigTail +} + +// defaultConfigHead is the default config up to the end of the home snapshot. +const defaultConfigHead = `# vaultik configuration # Documentation: https://sneak.berlin/go/vaultik # ─── REQUIRED ──────────────────────────────────────────────────────────────── -# Age recipient public keys for encryption. +# Age recipient public keys for encryption. snapshot create needs at least +# one; listing, verifying and restoring do not, so a machine that only +# restores can leave this empty. # Backups are encrypted to ALL listed recipients; any one of the corresponding # private keys can decrypt. Adding a recipient later does not re-encrypt data # already stored: deduplicated chunks and existing blobs stay encrypted to the # earlier recipients, so a newly added key cannot restore them on its own (see -# docs/REPOSTRUCTURE.md, Accepted Risks). Generate a keypair with: +# docs/REPOSTRUCTURE.md, Accepted Risks). Generate a keypair and add its +# public key with: # age-keygen -o vaultik_backup_private_key.txt # grep 'public key' vaultik_backup_private_key.txt -age_recipients: - - age1REPLACE_WITH_YOUR_PUBLIC_KEY +# vaultik config set age_recipients.0 age1... +age_recipients: [] # Named snapshots. Each snapshot backs up one or more paths and can have its # own exclude patterns in addition to the global excludes below. @@ -155,7 +190,10 @@ snapshots: - "/Movies/ProxyMedia" - "/Music/iTunes/Album Artwork" - "/Pictures/iPod Photo Cache" +` +// appsSnapshotConfig is the apps snapshot of the default config. +const appsSnapshotConfig = ` # Third-party applications. OS-provided apps live in /System/Applications # on modern macOS and are never in /Applications, but Apple-installed # App Store apps (Safari, GarageBand, iWork, iMovie) are excluded since @@ -176,7 +214,10 @@ snapshots: - "/Steam.app" - "/VirtualBox.app" - "/Utilities/Adobe Installers" +` +// defaultConfigTail is the default config after the snapshots. +const defaultConfigTail = ` # Storage backend (pick ONE of the three forms below). # # S3-compatible: @@ -196,7 +237,7 @@ storage_url: "" # access_key_id: YOUR_ACCESS_KEY # secret_access_key: YOUR_SECRET_KEY # # region: us-east-1 # Default: us-east-1 -# # part_size: 5MB # Multipart upload part size. Default: 5MB +# # part_size: 5MiB # Upload part size, 5MiB to 5GiB. Default: 5MiB # # For the s3:// form, disable TLS with ?ssl=false in the URL, not use_ssl. # ─── OPTIONAL ──────────────────────────────────────────────────────────────── @@ -211,7 +252,7 @@ storage_url: "" # Average chunk size for content-defined chunking (FastCDC). # Smaller = better deduplication but more metadata overhead. -# Accepts: 1MB, 10M, 64KB, etc. +# Minimum 1MB. Accepts: 1MB, 10M, 64MiB, etc. # Default: 10MB # chunk_size: 10MB @@ -226,10 +267,23 @@ storage_url: "" # Default: 3 # compression_level: 3 +# How old a blob that no snapshot lists must be before prune deletes it, +# and how old every object in a directory under metadata/ with no manifest +# must be before prune deletes that directory. A backup uploads its blobs +# and its db.zst.age before its manifest, so on a destination shared +# between hosts or users this must be longer than the longest backup run. +# It does not protect a blob a backup reuses from an earlier run that +# stopped before its manifest: that blob keeps the time of its first +# upload, so a prune can delete it. +# Accepts: 36h, 90m, etc. 0s deletes such blobs and directories at once. +# Default: 24h +# prune_grace_period: 24h + # Hostname used in snapshot IDs. Default: system hostname. # hostname: myserver -# Path to the local SQLite index database. +# Path to the local SQLite index database. It must be an absolute path; +# ~ is expanded. # Default: the platform data directory, e.g. # macOS: ~/Library/Application Support/vaultik/index.sqlite # Linux: ~/.local/share/vaultik/index.sqlite @@ -242,6 +296,12 @@ func NewConfigCommand() *cobra.Command { Use: "config", Short: "Manage the configuration file", Long: "Commands for creating, editing, and querying the vaultik config file.", + // cobra checks Args only on a command that has a Run: without + // one, a mistyped subcommand printed help and exited 0. + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, _ []string) { + _ = cmd.Help() + }, } cmd.AddCommand(newConfigInitCommand()) @@ -280,7 +340,8 @@ on macOS, ~/.config/ on Linux, /etc/vaultik/ as root).`, return fmt.Errorf("creating config directory %s: %w", dir, err) } - err = os.WriteFile(path, []byte(defaultConfigTemplate), configFileMode) + err = os.WriteFile(path, []byte(defaultConfigText(runtime.GOOS)), + configFileMode) if err != nil { return fmt.Errorf("writing config file: %w", err) } @@ -314,8 +375,15 @@ func newConfigEditCommand() *cobra.Command { editor = "vi" } + // Run $EDITOR through the shell, as git does, so a value + // with arguments such as "code --wait" works. The path + // goes in as an argument ("$@"), not into the command + // text, so a path with spaces or quotes arrives whole. + // sh -c takes the word after the command as $0, which + // is why editor appears twice. //nolint:gosec // G204: launching the operator's own $EDITOR is the point - ed := exec.CommandContext(cmd.Context(), editor, path) + ed := exec.CommandContext(cmd.Context(), + "sh", "-c", editor+` "$@"`, editor, path) ed.Stdin = os.Stdin ed.Stdout = os.Stdout ed.Stderr = os.Stderr @@ -376,8 +444,16 @@ func newConfigSetCommand() *cobra.Command { Use: "set ", Short: "Set a config value by dotted path (e.g. compression_level 5)", Long: `Sets a scalar config value addressed by dotted YAML path and writes -the file back, preserving comments and formatting. Intermediate maps -are created as needed. +the file back, preserving comments and formatting. Missing keys along +the path are created: as a list when the next path element is a +number, otherwise as a map. + +If the config loads, a change after which it would not, such as +compression_level 99, is refused and the file is left unchanged. A +config that does not load is checked one setting at a time. Examples +are the file config init writes before storage_url is set, and one +with a ${ENV:...} reference to a variable not set in this shell. In +such a config, an unknown key or a value of the wrong type is refused. Examples: vaultik config set storage_url "file:///mnt/backups" @@ -407,7 +483,21 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error { return err } - err = yamlPathSet(root, strings.Split(key, "."), value) + oldData, err := marshalConfigYAML(root) + if err != nil { + return fmt.Errorf("marshaling config: %w", err) + } + + keys := strings.Split(key, ".") + + if keys[0] != config.EnvSection { + _, err = config.SettingType(keys) + if err != nil { + return err + } + } + + err = yamlPathSet(root, keys, value) if err != nil { return err } @@ -417,6 +507,21 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error { return fmt.Errorf("marshaling config: %w", err) } + setting, err := yamlPathOnly(root, keys) + if err != nil { + return err + } + + settingData, err := marshalConfigYAML(setting) + if err != nil { + return fmt.Errorf("marshaling config: %w", err) + } + + err = checkConfigChange(oldData, data, settingData) + if err != nil { + return wouldNotLoadError(key, err) + } + err = os.WriteFile(path, data, configFileMode) if err != nil { return fmt.Errorf("writing config file: %w", err) @@ -438,8 +543,75 @@ func writeConfigSet(out *ui.Writer, path, key, value string) error { return nil } +// wouldNotLoadError returns the refusal of a change to key that vaultik +// would not load for reason. When storage_url moves to s3:// before the S3 +// credentials are set, it says to set them first: they can be set while +// the old storage_url is still in place. +func wouldNotLoadError(key string, reason error) error { + if key == storageURLKey && + (errors.Is(reason, config.ErrS3KeyIDRequired) || + errors.Is(reason, config.ErrS3SecretRequired)) { + return fmt.Errorf("%w: %w; %w", errWouldNotLoad, reason, + errSetS3KeysFirst) + } + + return fmt.Errorf("%w: %w", errWouldNotLoad, reason) +} + +// checkConfigChange returns the reason vaultik would not load newData, the +// config after a change, if the change brings that failure in. If oldData, +// the config before it, loads, the new one must load too. A config that +// does not load, such as one still being filled in or one with a ${...} +// reference that cannot be filled in here, is checked one setting at a +// time: settingData, the changed setting on its own, must decode into the +// config type. +func checkConfigChange(oldData, newData, settingData []byte) error { + oldCfg, err := config.Parse(oldData) + if err == nil && oldCfg.Validate() == nil { + newCfg, err := config.Parse(newData) + if err != nil { + return err + } + + return newCfg.Validate() + } + + _, err = config.Parse(settingData) + + return err +} + +// yamlPathOnly returns a document holding only the value at the dotted key +// path in root, inside the maps and lists that lead to it there. +func yamlPathOnly(root *yaml.Node, keys []string) (*yaml.Node, error) { + node, err := yamlPathGet(root, keys) + if err != nil { + return nil, err + } + + for i, key := range slices.Backward(keys) { + parent, err := yamlPathGet(root, keys[:i]) + if err != nil { + return nil, err + } + + if parent.Kind == yaml.SequenceNode { + node = &yaml.Node{ + Kind: yaml.SequenceNode, Content: []*yaml.Node{node}, + } + } else { + keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key} + node = &yaml.Node{ + Kind: yaml.MappingNode, Content: []*yaml.Node{keyNode, node}, + } + } + } + + return &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{node}}, nil +} + // marshalConfigYAML renders a config document tree with 2-space indentation, -// matching defaultConfigTemplate. yaml.Marshal defaults to 4 spaces, which +// matching the default config. yaml.Marshal defaults to 4 spaces, which // would reindent the whole file on the first `config set` despite the promise // to preserve formatting. func marshalConfigYAML(root *yaml.Node) ([]byte, error) { @@ -544,8 +716,8 @@ func yamlPathGet(root *yaml.Node, keys []string) (*yaml.Node, error) { return node, nil } -// yamlPathSet navigates a dotted key path, creating intermediate maps as -// needed, and sets the final key to the given scalar value. Numeric path +// yamlPathSet navigates a dotted key path, creating missing keys as needed, +// and sets the final key to the given scalar value. Numeric path // components index into sequences; an index equal to the sequence length // appends a new element (e.g. "age_recipients.1" on a 1-element list). func yamlPathSet(root *yaml.Node, keys []string, value string) error { @@ -558,12 +730,12 @@ func yamlPathSet(root *yaml.Node, keys []string, value string) error { node = node.Content[0] } - for i, key := range keys { + for i := range keys { last := i == len(keys)-1 switch node.Kind { case yaml.MappingNode: - node = yamlSetInMapping(node, key, value, last) + node = yamlSetInMapping(node, keys, i, value, last) case yaml.SequenceNode: next, err := yamlSetInSequence(node, keys, i, value, last) if err != nil { @@ -580,17 +752,38 @@ func yamlPathSet(root *yaml.Node, keys []string, value string) error { } } + // config.Load reads the file through untyped YAML, which turns an + // unquoted 00112233 into the number 38043 and 1e5 into 100000. Tagging + // a string setting as a string makes the encoder quote such a value. + // Other settings stay unquoted, so compression_level 9 is a number. + // The encoder refuses to write a value that is not valid UTF-8 as a + // string. Left untagged, such a value is written as base64 !!binary and + // loads back unchanged. + if configKeyIsString(keys) && utf8.ValidString(value) { + node.Tag = yamlStringTag + } + return nil } -// yamlSetInMapping resolves (creating if needed) the value node for key -// within a mapping node, setting it to value when it is the final path -// element, and returns the node to descend into. -func yamlSetInMapping(node *yaml.Node, key, value string, last bool) *yaml.Node { +// configKeyIsString reports whether the dotted key names a string in +// config.Config, as s3.access_key_id and snapshots.home.exclude.0 do. +func configKeyIsString(keys []string) bool { + typ, err := config.SettingType(keys) + + return err == nil && typ.Kind() == reflect.String +} + +// yamlSetInMapping resolves (creating if needed) the value node for the +// path element keys[i] within a mapping node, setting it to value when it +// is the final path element, and returns the node to descend into. +func yamlSetInMapping( + node *yaml.Node, keys []string, i int, value string, last bool, +) *yaml.Node { var valueNode *yaml.Node for j := 0; j+1 < len(node.Content); j += 2 { - if node.Content[j].Value == key { + if node.Content[j].Value == keys[i] { valueNode = node.Content[j+1] break @@ -598,13 +791,8 @@ func yamlSetInMapping(node *yaml.Node, key, value string, last bool) *yaml.Node } if valueNode == nil { - keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: key} - - valueNode = &yaml.Node{Kind: yaml.MappingNode} - if last { - valueNode = &yaml.Node{Kind: yaml.ScalarNode, Value: value} - } - + keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: keys[i]} + valueNode = newPathNode(keys, i, value) node.Content = append(node.Content, keyNode, valueNode) } else if last { setScalar(valueNode, value) @@ -632,12 +820,7 @@ func yamlSetInSequence( } if idx == len(node.Content) { - newNode := &yaml.Node{Kind: yaml.MappingNode} - if last { - newNode = &yaml.Node{Kind: yaml.ScalarNode, Value: value} - } - - node.Content = append(node.Content, newNode) + node.Content = append(node.Content, newPathNode(keys, i, value)) } else if last { setScalar(node.Content[idx], value) } @@ -645,6 +828,22 @@ func yamlSetInSequence( return node.Content[idx], nil } +// newPathNode returns the node to create for the missing path element +// keys[i]: the value when it is the final path element, otherwise an empty +// list when the next path element is a number and an empty map when not. +func newPathNode(keys []string, i int, value string) *yaml.Node { + if i == len(keys)-1 { + return &yaml.Node{Kind: yaml.ScalarNode, Value: value} + } + + _, err := strconv.Atoi(keys[i+1]) + if err == nil { + return &yaml.Node{Kind: yaml.SequenceNode} + } + + return &yaml.Node{Kind: yaml.MappingNode} +} + // setScalar overwrites a node in place with a plain scalar value. func setScalar(n *yaml.Node, value string) { n.Kind = yaml.ScalarNode diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index b537946..1eb657f 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -2,8 +2,10 @@ package cli //nolint:testpackage // exercises unexported yamlPathGet/yamlPathSet import ( "bytes" + "errors" "os" "path/filepath" + "strconv" "strings" "testing" @@ -12,20 +14,23 @@ import ( "sneak.berlin/go/vaultik/internal/ui" ) -// TestDefaultConfigTemplateParses ensures the init template is valid YAML -// that unmarshals into the Config struct with the expected snapshots. -func TestDefaultConfigTemplateParses(t *testing.T) { +// TestDefaultConfigParsesOnMacOS ensures the config `config init` writes on +// macOS is valid YAML that unmarshals into the Config struct with the +// expected snapshots. +func TestDefaultConfigParsesOnMacOS(t *testing.T) { t.Parallel() var cfg config.Config - err := yaml.Unmarshal([]byte(defaultConfigTemplate), &cfg) + err := yaml.Unmarshal([]byte(defaultConfigText("darwin")), &cfg) if err != nil { t.Fatalf("default config template is not valid YAML: %v", err) } - if len(cfg.AgeRecipients) != 1 { - t.Errorf("expected 1 placeholder age recipient, got %d", len(cfg.AgeRecipients)) + // A placeholder recipient would fail config.Load, so the template + // leaves the list empty. + if len(cfg.AgeRecipients) != 0 { + t.Errorf("expected no age recipients, got %d", len(cfg.AgeRecipients)) } home, ok := cfg.Snapshots["home"] @@ -55,6 +60,520 @@ func TestDefaultConfigTemplateParses(t *testing.T) { } } +// TestDefaultConfigOnLinux checks that the config `config init` writes on +// Linux loads with its home snapshot and without the apps snapshot, whose +// /Applications exists only on macOS. +func TestDefaultConfigOnLinux(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(defaultConfigText("linux")), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, "storage_url", "file:///mnt/backups") + if err != nil { + t.Fatalf("config set storage_url: %v", err) + } + + cfg, err := config.Load(path) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + + if _, ok := cfg.Snapshots["home"]; !ok { + t.Error("expected 'home' snapshot in the Linux default config") + } + + if _, ok := cfg.Snapshots["apps"]; ok { + t.Error("the Linux default config should have no 'apps' snapshot") + } +} + +// testRecipient is a valid age public key. +const testRecipient = "age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj" + +// TestConfigSetRecipientOnFreshConfig follows the README quickstart: on the +// file `config init` writes, `config set age_recipients.0` and +// `config set storage_url` give a config that loads with that recipient. +// Neither is refused, although the config does not load until both are set; +// once it loads, a recipient that is not a valid key is. +func TestConfigSetRecipientOnFreshConfig(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(defaultConfigText(macOS)), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + out := ui.NewWithColor(&bytes.Buffer{}, false) + + err = writeConfigSet(out, path, "age_recipients.0", testRecipient) + if err != nil { + t.Fatalf("config set age_recipients.0: %v", err) + } + + err = writeConfigSet(out, path, "storage_url", "file:///mnt/backups") + if err != nil { + t.Fatalf("config set storage_url: %v", err) + } + + cfg, err := config.Load(path) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + + if len(cfg.AgeRecipients) != 1 || cfg.AgeRecipients[0] != testRecipient { + t.Errorf("age_recipients = %v, want [%s]", cfg.AgeRecipients, testRecipient) + } + + err = writeConfigSet(out, path, "age_recipients.0", "notakey") + if err == nil || !strings.Contains(err.Error(), "not a valid recipient") { + t.Errorf("config set age_recipients.0 notakey gives error %v, "+ + "want one saying it is not a valid recipient", err) + } + + _, err = config.Load(path) + if err != nil { + t.Errorf("config.Load after the refused change: %v", err) + } +} + +// configWithoutRecipients loads, but has no age_recipients key and no +// snapshot named work. +const configWithoutRecipients = `storage_url: file:///mnt/backups +snapshots: + home: + paths: + - "~" +` + +// testS3URL is an S3 storage_url, which needs credentials to load. +const testS3URL = "s3://bucket/prefix?endpoint=https://s3.example.com" + +// configWithS3Keys loads: its storage_url is testS3URL and both S3 keys are +// set. +const configWithS3Keys = storageURLKey + ": " + testS3URL + ` +s3: + access_key_id: AKIAEXAMPLE + secret_access_key: example-secret +snapshots: + home: + paths: + - "~" +` + +// configWithUnsetReference loads only where VAULTIK_TEST_UNSET_SECRET is +// set, as a backup job's environment might set it. No test sets it. +const configWithUnsetReference = configWithoutRecipients + `s3: + secret_access_key: ${ENV:VAULTIK_TEST_UNSET_SECRET} +` + +// configWithLevelReference returns configWithoutRecipients with a ${FILE:...} +// reference on compression_level to a file holding 9, so that the config +// loads once the reference is filled in. +func configWithLevelReference(t *testing.T) string { + t.Helper() + + levelPath := filepath.Join(t.TempDir(), "level") + + err := os.WriteFile(levelPath, []byte("9"), configFileMode) + if err != nil { + t.Fatalf("write level: %v", err) + } + + return configWithoutRecipients + + "compression_level: ${FILE:" + levelPath + "}\n" +} + +// TestConfigSetIndexUnderMissingKey checks that a list index under a key +// the file does not have creates a list, and that the result loads. +func TestConfigSetIndexUnderMissingKey(t *testing.T) { + t.Parallel() + + tests := []struct { + key string + value string + field func(cfg *config.Config) []string + }{ + {"age_recipients.0", testRecipient, + func(cfg *config.Config) []string { return cfg.AgeRecipients }}, + {"snapshots.work.paths.0", "/srv/work", + func(cfg *config.Config) []string { return cfg.Snapshots["work"].Paths }}, + } + + for _, tt := range tests { + t.Run(tt.key, func(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(configWithoutRecipients), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, tt.key, tt.value) + if err != nil { + t.Fatalf("config set %s: %v", tt.key, err) + } + + cfg, err := config.Load(path) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + + got := tt.field(cfg) + if len(got) != 1 || got[0] != tt.value { + t.Errorf("%s gives %v, want [%s]", tt.key, got, tt.value) + } + }) + } +} + +// TestConfigSetKeepsFileThatWouldNotLoad checks that config set refuses a +// change after which the config would not load, with an error giving the +// reason, and leaves the file as it was. On the file `config init` writes, +// which does not load until storage_url is set, and on one that cannot be +// read here, only an unknown key or a value of the wrong type is refused. +func TestConfigSetKeepsFileThatWouldNotLoad(t *testing.T) { + t.Parallel() + + levelReference := configWithLevelReference(t) + + tests := []struct { + config string + key string + value string + reason string + }{ + // Keys that no setting has, on a config that loads and on one + // that does not. + {configWithoutRecipients, "nosuchkey", "1", + `unknown config key "nosuchkey"`}, + {configWithoutRecipients, "snapshots.home.exlude", "/tmp", + `unknown config key "snapshots.home.exlude"`}, + {defaultConfigText(macOS), "compression_lvl", "9", + `unknown config key "compression_lvl"`}, + // Index 1 of the empty list the missing key gives. + {configWithoutRecipients, "age_recipients.1", testRecipient, + "index out of range"}, + // A list set to a single value. + {configWithoutRecipients, "snapshots.home.paths", "/srv", + "into []string"}, + {configWithoutRecipients, "chunk_size", "fast", + `chunk_size: "fast" is not a size`}, + // Values of the right type that fail validation. + {configWithoutRecipients, "compression_level", "99", + "compression_level must be between 1 and 19"}, + {configWithoutRecipients, "chunk_size", "1KB", + "chunk_size must be at least 1MB"}, + // An s3:// URL before its credentials names them. + {configWithoutRecipients, storageURLKey, testS3URL, + "s3.access_key_id is required for s3:// URLs; " + + "set s3.access_key_id and s3.secret_access_key first"}, + {configWithoutRecipients + "s3:\n access_key_id: AKIAEXAMPLE\n", + storageURLKey, testS3URL, + "s3.secret_access_key is required for s3:// URLs; " + + "set s3.access_key_id and s3.secret_access_key first"}, + // With its reference filled in, the config loads. + {levelReference, "blob_size_limit", "1MB", + "blob_size_limit must be at least"}, + // The type check on a config that does not load yet. + {defaultConfigText(macOS), "snapshots.apps.paths", "/srv", + "into []string"}, + // The type check on a config that cannot be read here. + {configWithUnsetReference, "snapshots.home.paths", "/x", + "cannot unmarshal !!str `/x`"}, + } + + for _, tt := range tests { + t.Run(tt.key+" "+tt.value, func(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(tt.config), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, tt.key, tt.value) + if err == nil || !strings.Contains(err.Error(), tt.reason) { + t.Errorf("config set %s %s gives error %v, want one saying %q", + tt.key, tt.value, err, tt.reason) + } + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("read config: %v", err) + } + + if string(data) != tt.config { + t.Errorf("config set %s changed the file to:\n%s", + tt.key, data) + } + }) + } +} + +// TestConfigSetRefusesOnlyItsOwnFailure checks that setting another key +// works on a config with a ${...} reference on compression_level, which +// loads because loading fills the reference in, on one whose +// compression_level already fails to load, and on one with a reference +// that cannot be filled in here. +func TestConfigSetRefusesOnlyItsOwnFailure(t *testing.T) { + t.Parallel() + + configs := map[string]string{ + "reference": configWithLevelReference(t), + "failing": configWithoutRecipients + "compression_level: fast\n", + "unset reference": configWithUnsetReference, + } + + for name, configYAML := range configs { + t.Run(name, func(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(configYAML), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, "hostname", "myhost") + if err != nil { + t.Fatalf("config set hostname: %v", err) + } + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("read config: %v", err) + } + + if !strings.Contains(string(data), "hostname: myhost") { + t.Errorf("config set hostname wrote:\n%s", data) + } + }) + } +} + +// TestConfigSetS3KeysBeforeStorageURL checks that the order the refusal +// gives works on a config that loads with a file:// storage_url. +func TestConfigSetS3KeysBeforeStorageURL(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(configWithoutRecipients), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + for _, set := range [][2]string{ + {"s3.access_key_id", "AKIAEXAMPLE"}, + {"s3.secret_access_key", "example-secret"}, + {storageURLKey, testS3URL}, + } { + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, set[0], set[1]) + if err != nil { + t.Fatalf("config set %s: %v", set[0], err) + } + } + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("read config: %v", err) + } + + if !strings.Contains(string(data), storageURLKey+": "+testS3URL) { + t.Errorf("config set storage_url wrote:\n%s", data) + } +} + +// TestConfigSetRefusesClearingS3Key checks that clearing s3.access_key_id on +// a config with an s3:// storage_url is refused without saying to set the +// S3 keys first. That advice is only for a change to storage_url. +func TestConfigSetRefusesClearingS3Key(t *testing.T) { + t.Parallel() + + const key = "s3.access_key_id" + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(configWithS3Keys), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), path, key, "") + if !errors.Is(err, errWouldNotLoad) { + t.Errorf("clearing %s gives error %v, want one saying %q", + key, err, errWouldNotLoad) + } + + if errors.Is(err, errSetS3KeysFirst) { + t.Errorf("clearing %s gives error %v, want one not saying %q", + key, err, errSetS3KeysFirst) + } + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("read config: %v", err) + } + + if string(data) != configWithS3Keys { + t.Errorf("clearing %s changed the file to:\n%s", key, data) + } +} + +// TestConfigSetWritesEnvSection checks that config set writes a key under +// the top-level env section, whose keys are not settings, on a config that +// loads. +func TestConfigSetWritesEnvSection(t *testing.T) { + const name = "VAULTIK_TEST_CONFIG_SET_ENV" + + // Loading the changed config sets the variable; t.Setenv restores it + // after the test. + t.Setenv(name, "") + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(configWithoutRecipients), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + err = writeConfigSet(ui.NewWithColor(&bytes.Buffer{}, false), + path, "env."+name, "value") + if err != nil { + t.Fatalf("config set env.%s: %v", name, err) + } + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("read config: %v", err) + } + + if !strings.Contains(string(data), "env:\n "+name+": value\n") { + t.Errorf("config set env.%s wrote:\n%s", name, data) + } +} + +// TestConfigSetStringLooksLikeNumber sets string settings to values that +// YAML reads as numbers or booleans when they are unquoted, and checks that +// config.Load returns each one unchanged. +func TestConfigSetStringLooksLikeNumber(t *testing.T) { + t.Parallel() + + tests := []struct { + key string + value string + field func(cfg *config.Config) string + }{ + {"s3.access_key_id", "00112233", + func(cfg *config.Config) string { return cfg.S3.AccessKeyID }}, + {"s3.secret_access_key", "12345678901234567890123456789012", + func(cfg *config.Config) string { return cfg.S3.SecretAccessKey }}, + {"hostname", "007", + func(cfg *config.Config) string { return cfg.Hostname }}, + {"s3.prefix", "1e5", + func(cfg *config.Config) string { return cfg.S3.Prefix }}, + {"s3.bucket", "true", + func(cfg *config.Config) string { return cfg.S3.Bucket }}, + {"s3.region", "FALSE", + func(cfg *config.Config) string { return cfg.S3.Region }}, + {"snapshots.home.exclude.0", "1.10", + func(cfg *config.Config) string { return cfg.Snapshots["home"].Exclude[0] }}, + } + + for _, tt := range tests { + t.Run(tt.key+"="+tt.value, func(t *testing.T) { + t.Parallel() + + cfg := loadAfterConfigSet(t, tt.key, tt.value) + + got := tt.field(cfg) + if got != tt.value { + t.Errorf("%s = %q after config set %q", tt.key, got, tt.value) + } + }) + } +} + +// TestConfigSetNonUTF8Path checks that config set still accepts a value that +// is not valid UTF-8, such as a path with a Latin-1 file name, and that +// config.Load returns it unchanged. +func TestConfigSetNonUTF8Path(t *testing.T) { + t.Parallel() + + const dir = "/srv/caf\xe9" + + cfg := loadAfterConfigSet(t, "snapshots.home.paths.0", dir) + + got := cfg.Snapshots["home"].Paths[0] + if got != dir { + t.Errorf("snapshots.home.paths.0 = %q, want %q", got, dir) + } +} + +// TestConfigSetNumberStaysNumber checks that a number set for an integer +// setting is still read as a number, not as a quoted string. +func TestConfigSetNumberStaysNumber(t *testing.T) { + t.Parallel() + + const level = 9 + + cfg := loadAfterConfigSet(t, "compression_level", strconv.Itoa(level)) + + if cfg.CompressionLevel != level { + t.Errorf("compression_level = %d, want %d", cfg.CompressionLevel, level) + } +} + +// loadAfterConfigSet writes the file `config init` writes, sets storage_url +// to a local directory so that the file passes validation, applies +// `config set key value` and returns what config.Load reads back. +func loadAfterConfigSet(t *testing.T, key, value string) *config.Config { + t.Helper() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(defaultConfigText(macOS)), configFileMode) + if err != nil { + t.Fatalf("write config: %v", err) + } + + out := ui.NewWithColor(&bytes.Buffer{}, false) + + err = writeConfigSet(out, path, "storage_url", "file:///mnt/backups") + if err != nil { + t.Fatalf("config set storage_url: %v", err) + } + + err = writeConfigSet(out, path, key, value) + if err != nil { + t.Fatalf("config set %s: %v", key, err) + } + + cfg, err := config.Load(path) + if err != nil { + t.Fatalf("config.Load: %v", err) + } + + return cfg +} + const testYAML = `# top comment compression_level: 3 age_recipients: @@ -297,6 +816,30 @@ func TestWriteConfigSetTightensMode(t *testing.T) { } } +// TestConfigEditEditorWithArgument checks that an $EDITOR carrying an +// argument works and that a config path with a space reaches it whole. +// The "editor" is cp with the replacement file as its argument, so the +// config ends up with the replacement's content only if both arrived. +func TestConfigEditEditorWithArgument(t *testing.T) { + dir := t.TempDir() + path := seedFile(t, dir, "my config.yml", "compression_level: 3\n") + edited := seedFile(t, dir, "edited.yml", "compression_level: 9\n") + + setRootFlags(t, RootFlags{ConfigPath: path}) + t.Setenv("EDITOR", "cp '"+edited+"'") + + mustExecute(t, newConfigEditCommand()) + + data, err := os.ReadFile(path) //nolint:gosec // G304: test-controlled path + if err != nil { + t.Fatalf("reading config back: %v", err) + } + + if string(data) != "compression_level: 9\n" { + t.Errorf("config after edit = %q, want the edited content", data) + } +} + func splitPath(s string) []string { return strings.Split(s, ".") } diff --git a/internal/cli/database.go b/internal/cli/database.go index 04605df..93c7911 100644 --- a/internal/cli/database.go +++ b/internal/cli/database.go @@ -6,7 +6,9 @@ import ( "github.com/spf13/cobra" "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/vaultik" ) // NewDatabaseCommand creates the database command group @@ -15,6 +17,12 @@ func NewDatabaseCommand() *cobra.Command { Use: "database", Short: "Manage the local state database", Long: `Commands for managing the local SQLite state database.`, + // cobra checks Args only on a command that has a Run: without + // one, a mistyped subcommand printed help and exited 0. + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, _ []string) { + _ = cmd.Help() + }, } cmd.AddCommand( @@ -84,27 +92,25 @@ Use --force to skip the confirmation prompt.`, var confirm string - _, err = fmt.Scanln(&confirm) + // A failure to read the answer means no confirmation. + _, err = fmt.Fscanln(cmd.InOrStdin(), &confirm) if err != nil || confirm != "yes" { _, _ = fmt.Fprintln(w, "Aborted.") - //nolint:nilerr // a failed/aborted confirmation is a clean abort - return nil + return vaultik.ErrNotConfirmed } } - // Delete the database file - err = os.Remove(dbPath) - if err != nil { - return fmt.Errorf("failed to delete database: %w", err) + // Delete the database file and its side files. A side file + // may not exist, so only failing to delete the database file + // is an error. + for _, indexFile := range database.IndexFiles(dbPath) { + err = os.Remove(indexFile) + if err != nil && indexFile == dbPath { + return fmt.Errorf("failed to delete database: %w", err) + } } - // Also delete WAL and SHM files if they exist - walPath := dbPath + "-wal" - shmPath := dbPath + "-shm" - _ = os.Remove(walPath) // Ignore errors - files may not exist - _ = os.Remove(shmPath) - out.Infof("Local state database deleted: %s.", dbPath) log.Info("Local state database deleted", "path", dbPath) diff --git a/internal/cli/database_test.go b/internal/cli/database_test.go new file mode 100644 index 0000000..fcb1ba5 --- /dev/null +++ b/internal/cli/database_test.go @@ -0,0 +1,75 @@ +package cli //nolint:testpackage // sets the unexported rootFlags directly + +import ( + "bytes" + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestDatabaseDeleteDeclinedIsError checks that answering anything but +// "yes" keeps the database and returns ErrNotConfirmed, so the command +// exits non-zero. +// +//nolint:paralleltest // mutates the process-global rootFlags +func TestDatabaseDeleteDeclinedIsError(t *testing.T) { + dir := t.TempDir() + dbPath, cfgPath := seedDatabaseDeleteConfig(t, dir) + + setRootFlags(t, RootFlags{ConfigPath: cfgPath}) + + var out bytes.Buffer + + cmd := newDatabaseDeleteCommand() + cmd.SetOut(&out) + cmd.SetErr(io.Discard) + cmd.SetIn(strings.NewReader("no\n")) + cmd.SetArgs(nil) + + err := cmd.Execute() + if !errors.Is(err, vaultik.ErrNotConfirmed) { + t.Errorf("declined database delete returned %v, want %v", + err, vaultik.ErrNotConfirmed) + } + + _, err = os.Stat(dbPath) + if err != nil { + t.Errorf("declined database delete removed the file: %v", err) + } + + if !strings.Contains(out.String(), "Aborted.") { + t.Errorf("declined database delete printed %q, want Aborted.", + out.String()) + } +} + +// TestDatabaseDeleteRemovesSideFiles checks that the side files SQLite +// keeps beside the database file are deleted with it. +// +//nolint:paralleltest // mutates the process-global rootFlags +func TestDatabaseDeleteRemovesSideFiles(t *testing.T) { + dir := t.TempDir() + dbPath, cfgPath := seedDatabaseDeleteConfig(t, dir) + + indexFiles := database.IndexFiles(dbPath) + for _, indexFile := range indexFiles { + seedFile(t, dir, filepath.Base(indexFile), "data") + } + + setRootFlags(t, RootFlags{ConfigPath: cfgPath}) + + mustExecute(t, newDatabaseDeleteCommand(), "--force") + + for _, indexFile := range indexFiles { + _, err := os.Stat(indexFile) + if !os.IsNotExist(err) { + t.Errorf("database delete left %s: stat err = %v", indexFile, err) + } + } +} diff --git a/internal/cli/entry.go b/internal/cli/entry.go index 917e6e7..d332071 100644 --- a/internal/cli/entry.go +++ b/internal/cli/entry.go @@ -15,17 +15,28 @@ import ( // the startup banner. const shortCommitLen = 12 +// exitCodeInterrupted is the exit status of a command that SIGINT or +// SIGTERM stopped. It is 128 plus SIGINT's number, 2, which is what a +// shell reports for a command stopped by Ctrl-C. +const exitCodeInterrupted = 130 + // Entry is the main entry point for the CLI application. -// It prints the startup banner to stdout (unless a banner-suppressing +// It first calls globals.FillUnsetFromBuildInfo, which fills in the +// version, commit and commit date that the linker flags did not set. +// It prints the startup banner to stderr (unless a banner-suppressing // flag is present in os.Args — see bannerSuppressedInArgs), executes the // root cobra command, and routes any returned error through the // ui.Writer so the user sees a properly formatted "🛑 ERROR:" line. +// The banner goes to stderr because stdout carries only the output the +// user asked for, such as a completion script or a `config get` value. // -// It returns the process exit code (0 on success, 1 on error) rather -// than calling os.Exit, so that main's deferred profile writers run -// before the process ends. See run in cmd/vaultik/main.go. +// It returns the process exit code (0 on success, 130 when interrupted, +// 1 on any other error) rather than calling os.Exit, so that main's +// deferred profile writers run before the process ends. See run in +// cmd/vaultik/main.go. func Entry() int { - emitStartupBanner(os.Args[1:], os.Stdout) + globals.FillUnsetFromBuildInfo() + emitStartupBanner(os.Args[1:], os.Stderr) rootCmd := NewRootCommand() rootCmd.SilenceErrors = true @@ -33,14 +44,20 @@ func Entry() int { err := rootCmd.Execute() if err != nil { // An operation that ran inside the fx app has already reported - // its own failure (and suppressed it under --json); errReported - // says so. Printing it again here would double the error line. + // its own failure (`snapshot verify --json` puts it in the + // document instead); errReported says so. Printing it again + // here would double the error line. // Every other error — bad arguments, a config that would not - // load — reaches Entry unreported, so it is shown here. + // load, an interrupt — reaches Entry unreported, so it is shown + // here. if !errors.Is(err, errReported) { ReportErrorf("%s", err.Error()) } + if errors.Is(err, errInterrupted) { + return exitCodeInterrupted + } + return 1 } @@ -49,9 +66,8 @@ func Entry() int { // emitStartupBanner writes the startup banner to w unless args (the // argument vector with the program name already stripped) contains a -// flag that suppresses it. Split out of Entry so that the decision — the -// only thing standing between a --json invocation and a parseable -// stdout — is reachable from a test without running the whole CLI. +// flag that suppresses it. Split out of Entry so that the decision is +// reachable from a test without running the whole CLI. func emitStartupBanner(args []string, w io.Writer) { if bannerSuppressedInArgs(args) { return @@ -69,6 +85,10 @@ func emitStartupBanner(args []string, w io.Writer) { // 🛑 ERROR: format. Use it from goroutine error paths (where returning // an error to cobra isn't an option) and anywhere else a CLI command // must surface a failure outside the normal RunE return path. +// +// This line is the one report of the failure. A caller that also logs +// the failure logs it at info level, so the record appears only under +// --verbose or --debug and the error is not printed twice. func ReportErrorf(format string, args ...any) { ui.New(os.Stderr).Errorf(format, args...) } @@ -86,8 +106,7 @@ func ReportErrorf(format string, args ...any) { // --json is a subcommand flag rather than a persistent one, but so is // --cron (it exists only on `snapshot create`), so this adds no new // class of imprecision. The only cost of a false positive is a missing -// decorative banner; the cost of a false negative is a corrupt document -// on stdout, so the scan errs deliberately in that direction. +// decorative banner. func bannerSuppressedInArgs(args []string) bool { for _, a := range args { if a == "--" { diff --git a/internal/cli/entry_banner_test.go b/internal/cli/entry_banner_test.go index cbb51e3..412b5d0 100644 --- a/internal/cli/entry_banner_test.go +++ b/internal/cli/entry_banner_test.go @@ -13,6 +13,7 @@ import ( "github.com/adrg/xdg" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/globals" ) // Command words and flags used to build argument vectors below. They are @@ -36,23 +37,14 @@ const ( // strips it before scanning, so it has to be present. programName = "vaultik" - // someSnapshotID is any snapshot identifier: these tests never run - // the command, so it only has to occupy the positional argument. + // someSnapshotID only fills the positional argument; no test needs + // the snapshot to exist. someSnapshotID = "host_2026-01-01T00:00:00Z" ) -// placeholderJSONDocument stands in for whatever document a --json -// command writes to stdout. `snapshot list --json` with no snapshots -// prints exactly this; the other --json commands print an object rather -// than an array, but this test is not about their shape. It is about -// what is on stdout *before* them, which is the same for all of them -// because Entry prints the banner before cobra has parsed anything and -// therefore before it can know which command is running. -const placeholderJSONDocument = "[]\n" - // jsonArgumentVectors are the argument vectors of every --json // invocation the CLI accepts, with the program name stripped exactly as -// Entry strips it. Each one must leave stdout untouched by the banner. +// Entry strips it. Each one must suppress the banner. // //nolint:gochecknoglobals // read-only test fixture shared by two tests var jsonArgumentVectors = map[string][]string{ @@ -74,39 +66,23 @@ var jsonArgumentVectors = map[string][]string{ }, } -// TestJSONInvocationStdoutIsExactlyOneDocument is the CLI-layer -// regression guard for issue #106: `vaultik snapshot list --json | jq` -// must work with no other flags. -// -// internal/vaultik's TestListSnapshots_JSONStdoutIsOnlyTheDocument -// guards the same contract one layer down, but it calls the library -// function directly and so cannot see Entry, which is where the -// contamination was: the startup banner is written to stdout before -// cobra parses anything, and the suppression scan did not know about -// --json. The two banner lines and the blank line landed ahead of the -// document and `jq` refused the result. -// -// The document is a constant here because this test is about the -// argument vectors, one per --json command; the one that runs a real -// command end to end is TestEntryJSONStdoutIsExactlyOneDocument below. -func TestJSONInvocationStdoutIsExactlyOneDocument(t *testing.T) { +// TestJSONInvocationSuppressesBanner checks that every --json +// invocation suppresses the startup banner, as the README says --json +// does along with --quiet and --cron. The scan is over the raw argument +// vector, so each position and spelling of --json is listed. +func TestJSONInvocationSuppressesBanner(t *testing.T) { t.Parallel() for name, argv := range jsonArgumentVectors { t.Run(name, func(t *testing.T) { t.Parallel() - var stdout bytes.Buffer + var banner bytes.Buffer - emitStartupBanner(argv, &stdout) + emitStartupBanner(argv, &banner) - require.Empty(t, stdout.String(), - "nothing may reach stdout ahead of a --json document") - - _, err := stdout.WriteString(placeholderJSONDocument) - require.NoError(t, err) - - requireExactlyOneJSONDocument(t, stdout.String()) + assert.Empty(t, banner.String(), + "--json suppresses the banner") }) } } @@ -127,16 +103,45 @@ func TestBannerStillPrintedWithoutSuppressingFlag(t *testing.T) { t.Run(name, func(t *testing.T) { t.Parallel() - var stdout bytes.Buffer + var banner bytes.Buffer - emitStartupBanner(argv, &stdout) + emitStartupBanner(argv, &banner) - assert.Contains(t, stdout.String(), "starting up at", + assert.Contains(t, banner.String(), "starting up at", "the banner belongs on invocations that did not opt out") }) } } +// TestBannerLabelsCommitDate checks that the banner prints the commit +// and the commit date, each after its own label. Commit and CommitDate +// get different values, so printing the wrong one fails. +// +//nolint:paralleltest // sets globals.Commit and globals.CommitDate +func TestBannerLabelsCommitDate(t *testing.T) { + const ( + commit = "abc1234" + commitDate = "2026-11-09" + ) + + previousCommit, previousCommitDate := globals.Commit, globals.CommitDate + + t.Cleanup(func() { + globals.Commit = previousCommit + globals.CommitDate = previousCommitDate + }) + + globals.Commit = commit + globals.CommitDate = commitDate + + var banner bytes.Buffer + + emitStartupBanner(nil, &banner) + + assert.Contains(t, banner.String(), + "(commit "+commit+", commit date "+commitDate+")") +} + // TestBannerSuppressedInArgs covers the suppression scan directly, // including the flags that suppressed the banner before --json joined // them, so that adding --json cannot regress them. @@ -172,9 +177,9 @@ func TestBannerSuppressedInArgs(t *testing.T) { // hermeticConfig is a complete, valid config that needs no network and // no credentials: file:// storage is exempt from the S3 credential -// checks, and FileStorer over a directory that does not exist lists -// zero objects without erroring. Chunk, blob and compression settings -// are filled in by config.Load. +// checks. A test that lists the destination must create its directory +// first, because listing a directory that does not exist is an error. +// Chunk, blob and compression settings are filled in by config.Load. const hermeticConfig = `age_recipients: - age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj snapshots: @@ -196,22 +201,25 @@ hostname: test-host // `snapshot list` is the command chosen because it is the only --json // command that reaches its document without a populated destination // store: it reads the local index, streams `metadata/` (empty here), -// and treats a barren destination as an empty list rather than a -// failure. +// and treats an empty destination directory as an empty list rather +// than a failure. // // Not parallel: it replaces os.Args, os.Stdout and the xdg globals. func TestEntryJSONStdoutIsExactlyOneDocument(t *testing.T) { dir := t.TempDir() configPath := filepath.Join(dir, "config.yml") + storeDir := filepath.Join(dir, "store") contents := fmt.Sprintf(hermeticConfig, filepath.Join(dir, "source"), - filepath.Join(dir, "store"), + storeDir, filepath.Join(dir, "index.sqlite")) require.NoError(t, os.WriteFile(configPath, []byte(contents), configFileMode)) + require.NoError(t, os.Mkdir(storeDir, 0o750)) + // The PID lock lives under xdg.DataHome, which xdg resolves at // package init; point it at the temp dir so the test neither // touches nor collides with the real one. @@ -244,9 +252,7 @@ func TestEntryJSONStdoutIsExactlyOneDocument(t *testing.T) { // captureProcessStdout redirects the process's own stdout to a pipe for // the duration of fn and returns what was written to it. The redirection // has to be at the file-descriptor level rather than through an injected -// writer, because the banner and the JSON encoder reach os.Stdout -// independently and the point of the test is that both land in the same -// place. +// writer, because the commands Entry runs reach os.Stdout directly. // // Not parallel-safe: os.Stdout is process-global. func captureProcessStdout(t *testing.T, fn func()) string { diff --git a/internal/cli/entry_failure_once_test.go b/internal/cli/entry_failure_once_test.go new file mode 100644 index 0000000..734f814 --- /dev/null +++ b/internal/cli/entry_failure_once_test.go @@ -0,0 +1,205 @@ +package cli //nolint:testpackage // shares the fixtures and capture helpers + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "filippo.io/age" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/ui" +) + +const ( + // errorLinePrefix starts the final line that reports a failed command. + errorLinePrefix = "ERROR: " + + flagVerbose = "--verbose" + cmdRestore = "restore" + + // blobsDir is the directory of a destination store that holds the + // blobs. + blobsDir = "blobs" +) + +// TestEntryFailureIsPrintedOnce runs commands that fail after startup +// against a destination they cannot use. `info` is not among them: it +// cannot fail after startup. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntryFailureIsPrintedOnce(t *testing.T) { + for _, command := range [][]string{ + {cmdSnapshot, cmdCreate}, + {cmdSnapshot, cmdRemove, someSnapshotID}, + {cmdSnapshot, cmdVerify, someSnapshotID}, + {cmdRemote, cmdInfo}, + {cmdPrune, flagJSON}, + } { + for _, verbose := range []bool{false, true} { + name := fmt.Sprintf("%s verbose=%t", strings.Join(command, " "), verbose) + + t.Run(name, func(t *testing.T) { + requireErrorPrintedOnce(t, verbose, append([]string{flagConfig, + writeUnusableDestinationConfig(t)}, command...)...) + }) + } + } +} + +// TestEntryBlobUploadFailureIsPrintedOnce backs up to a destination +// whose blobs directory is a file, so the blob upload fails. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntryBlobUploadFailureIsPrintedOnce(t *testing.T) { + for _, verbose := range []bool{false, true} { + t.Run(fmt.Sprintf("verbose=%t", verbose), func(t *testing.T) { + configPath, storeDir := writeBackupConfig(t) + + require.NoError(t, os.WriteFile( + filepath.Join(storeDir, blobsDir), nil, 0o600)) + + requireErrorPrintedOnce(t, verbose, + flagConfig, configPath, cmdSnapshot, cmdCreate) + }) + } +} + +// TestEntryBlobDownloadFailureIsPrintedOnce backs up, deletes the blobs +// from the destination, and restores, so the blob download fails. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntryBlobDownloadFailureIsPrintedOnce(t *testing.T) { + for _, verbose := range []bool{false, true} { + t.Run(fmt.Sprintf("verbose=%t", verbose), func(t *testing.T) { + configPath, storeDir := writeBackupConfigWithPrivateKey(t) + + code, _, _ := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate) + require.Equal(t, 0, code) + + require.NoError(t, os.RemoveAll(filepath.Join(storeDir, blobsDir))) + + requireErrorPrintedOnce(t, verbose, flagConfig, configPath, + cmdSnapshot, cmdRestore, onlySnapshotID(t, configPath), t.TempDir()) + }) + } +} + +// requireErrorPrintedOnce runs Entry with args, adding --verbose when +// verbose is set. The command must fail, and stderr must carry its error +// once, as the final ERROR: line. A log record carrying the same error +// appears only under --verbose. +func requireErrorPrintedOnce(t *testing.T, verbose bool, args ...string) { + t.Helper() + + if verbose { + args = append(args, flagVerbose) + } + + code, _, stderr := runEntry(t, args...) + require.Equal(t, 1, code) + + errorLine, records := failureOutput(t, stderr) + + if !verbose { + assert.Zero(t, records, + "without --verbose no log record repeats the error:\n%s", stderr) + + return + } + + assert.NotZero(t, records, + "--verbose must keep the log record of %q", errorLine) +} + +// failureOutput requires stderr to hold exactly one ERROR: line and +// returns it, with the number of log records whose error attribute is +// the error that line reports. stderr is a pipe here, so every log +// record is a JSON object on its own line. +func failureOutput(t *testing.T, stderr string) (string, int) { + t.Helper() + + var ( + errorLines []string + records []map[string]any + ) + + for line := range strings.Lines(stderr) { + var record map[string]any + if json.Unmarshal([]byte(line), &record) == nil { + records = append(records, record) + + continue + } + + if strings.Contains(line, errorLinePrefix) { + errorLines = append(errorLines, strings.TrimSpace(line)) + } + } + + require.Len(t, errorLines, 1, + "the error must be printed once as an ERROR: line:\n%s", stderr) + + // An error can run over several lines; the ERROR: line holds the + // first of them. + repeats := 0 + + for _, record := range records { + failure, ok := record["error"].(string) + firstLine, _, _ := strings.Cut(failure, "\n") + + if ok && strings.Contains(errorLines[0], firstLine) { + repeats++ + } + } + + return errorLines[0], repeats +} + +// writeBackupConfigWithPrivateKey builds what writeBackupConfig builds, +// with a generated key pair in place of its recipient. The config also +// holds the private key, so that restore can decrypt the backup. Returns +// the config path and the store directory. +func writeBackupConfigWithPrivateKey(t *testing.T) (string, string) { + t.Helper() + + configPath, storeDir := writeBackupConfig(t) + + identity, err := age.GenerateX25519Identity() + require.NoError(t, err) + + out := ui.NewWithColor(io.Discard, false) + + require.NoError(t, writeConfigSet(out, configPath, + "age_recipients.0", identity.Recipient().String())) + require.NoError(t, writeConfigSet(out, configPath, + "age_secret_key", identity.String())) + + return configPath, storeDir +} + +// onlySnapshotID returns the ID of the one snapshot in the local index +// that writeBackupConfig puts beside the config file. +func onlySnapshotID(t *testing.T, configPath string) string { + t.Helper() + + ctx := context.Background() + + db, err := database.New(ctx, + filepath.Join(filepath.Dir(configPath), "index.sqlite")) + require.NoError(t, err) + + defer func() { require.NoError(t, db.Close()) }() + + backedUp, err := database.NewRepositories(db).Snapshots.GetOnlySnapshot(ctx) + require.NoError(t, err) + + return backedUp.ID.String() +} diff --git a/internal/cli/entry_interrupt_test.go b/internal/cli/entry_interrupt_test.go new file mode 100644 index 0000000..b11c24b --- /dev/null +++ b/internal/cli/entry_interrupt_test.go @@ -0,0 +1,203 @@ +package cli //nolint:testpackage // shares runEntry and the argument constants + +import ( + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/signal" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/adrg/xdg" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// stalledStoreConfig is hermeticConfig with an s3:// destination store +// in place of the file:// one. The server behind it accepts any +// credentials. +const stalledStoreConfig = `age_recipients: + - age1278m9q7dp3chsh2dcy82qk27v047zywyvtxwnj4cvt0z65jw6a7q5dqhfj +snapshots: + test: + paths: + - %s +storage_url: s3://bucket?endpoint=%s&ssl=false +s3: + access_key_id: key + secret_access_key: secret +index_path: %s +hostname: test-host +` + +// interruptRepeat is how often interruptOnFirstRequest sends SIGINT. +const interruptRepeat = 50 * time.Millisecond + +// TestEntryInterruptedRun sends SIGINT to the test process while a +// command waits on the destination store, and checks that Entry returns +// 130 and prints one line on stderr saying the run was interrupted. The +// store is a local HTTP server that holds every request open, so the +// command is always mid-operation when the signal arrives. The two +// cases cover --cron and --json, which silence other output. +// +// Not parallel: it signals the process and replaces os.Args, os.Stdout, +// os.Stderr and the xdg globals. +// +//nolint:paralleltest // signals the process and replaces process globals +func TestEntryInterruptedRun(t *testing.T) { + for _, testCase := range []struct { + name string + args []string + }{ + { + name: "snapshot create --cron", + args: []string{cmdSnapshot, cmdCreate, "--cron"}, + }, + { + name: "snapshot verify --json", + args: []string{cmdSnapshot, cmdVerify, someSnapshotID, flagJSON}, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + endpoint, requestArrived := startStalledStore(t) + configPath := writeStalledStoreConfig(t, endpoint) + interruptOnFirstRequest(t, requestArrived) + + code, _, stderr := runEntry(t, + append([]string{flagConfig, configPath}, testCase.args...)...) + + assert.Equal(t, 130, code) + assert.Equal(t, 1, + strings.Count(stderr, errInterrupted.Error()), stderr) + }) + } +} + +// interruptOnFirstRequest sends SIGINT to the test process every +// interruptRepeat, from the first request to the destination store until +// the test ends. One signal is not enough: the command can reach the +// store before fx has started catching signals. The test catches SIGINT +// too, so that a signal fx is not catching does not kill the test +// binary. +func interruptOnFirstRequest(t *testing.T, requestArrived <-chan struct{}) { + t.Helper() + + self, err := os.FindProcess(os.Getpid()) + require.NoError(t, err) + + caught := make(chan os.Signal, 1) + signal.Notify(caught, os.Interrupt) + + testEnded := make(chan struct{}) + senderDone := make(chan struct{}) + + // Stop catching SIGINT only after the sender has returned. The sender + // waits for each SIGINT it sends to arrive on caught; one still on + // its way after signal.Stop would kill the test binary. + t.Cleanup(func() { + close(testEnded) + <-senderDone + signal.Stop(caught) + }) + + go func() { + defer close(senderDone) + + select { + case <-requestArrived: + case <-testEnded: + return + } + + ticker := time.NewTicker(interruptRepeat) + defer ticker.Stop() + + for { + // Empty caught, so that the receive below waits for this + // SIGINT rather than an earlier one. + select { + case <-caught: + default: + } + + sendErr := self.Signal(os.Interrupt) + if sendErr != nil { + t.Errorf("sending SIGINT: %v", sendErr) + + return + } + + <-caught + + select { + case <-testEnded: + return + case <-ticker.C: + } + } + }() +} + +// startStalledStore starts an HTTP server that never answers: each +// request is held until the client gives up on it or the test ends. +// It returns the server's host:port and a channel that receives a value +// when the first request arrives. +func startStalledStore(t *testing.T) (string, <-chan struct{}) { + t.Helper() + + requestArrived := make(chan struct{}, 1) + release := make(chan struct{}) + + server := httptest.NewServer(http.HandlerFunc( + func(_ http.ResponseWriter, r *http.Request) { + select { + case requestArrived <- struct{}{}: + default: + } + + select { + case <-r.Context().Done(): + case <-release: + } + })) + + // Cleanups run last-registered first, so release lets any held + // request return before Close waits for it. + t.Cleanup(server.Close) + t.Cleanup(func() { close(release) }) + + return server.Listener.Addr().String(), requestArrived +} + +// writeStalledStoreConfig writes a config whose destination store is the +// server at endpoint and whose snapshot source holds one small file, so +// that `snapshot create` has a blob to upload. Returns the config path. +func writeStalledStoreConfig(t *testing.T, endpoint string) string { + t.Helper() + + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yml") + sourceDir := filepath.Join(dir, "source") + + require.NoError(t, os.Mkdir(sourceDir, 0o750)) + require.NoError(t, os.WriteFile(filepath.Join(sourceDir, "file.txt"), + []byte("contents"), 0o600)) + + contents := fmt.Sprintf(stalledStoreConfig, + sourceDir, endpoint, filepath.Join(dir, "index.sqlite")) + + require.NoError(t, + os.WriteFile(configPath, []byte(contents), configFileMode)) + + // The PID lock lives under xdg.DataHome, which xdg resolves at + // package init; point it at the temp dir so the test neither + // touches nor collides with the real one. + t.Setenv("XDG_DATA_HOME", filepath.Join(dir, "data")) + xdg.Reload() + t.Cleanup(xdg.Reload) + + return configPath +} diff --git a/internal/cli/entry_prune_json_test.go b/internal/cli/entry_prune_json_test.go index 7f4d6e9..3f43226 100644 --- a/internal/cli/entry_prune_json_test.go +++ b/internal/cli/entry_prune_json_test.go @@ -98,25 +98,31 @@ func TestEntryPruneJSONStdoutIsExactlyOneDocument(t *testing.T) { } } -// writeHermeticPruneConfig builds a config over a temp directory and, if -// seedStale is set, creates the index database up front with one -// snapshot record that has no counterpart on the destination store. -// Returns the config path. +// writeHermeticPruneConfig builds a config over a temp directory with an +// empty destination directory and, if seedStale is set, creates the +// index database up front with one snapshot record that has no +// counterpart on the destination store, and gives the destination the +// marker a backup writes. Returns the config path. func writeHermeticPruneConfig(t *testing.T, seedStale bool) string { t.Helper() dir := t.TempDir() configPath := filepath.Join(dir, "config.yml") indexPath := filepath.Join(dir, "index.sqlite") + storeDir := filepath.Join(dir, "store") contents := fmt.Sprintf(hermeticConfig, filepath.Join(dir, "source"), - filepath.Join(dir, "store"), + storeDir, indexPath) require.NoError(t, os.WriteFile(configPath, []byte(contents), configFileMode)) + // prune fails on a destination directory that does not exist, so the + // empty store is created here rather than left to a first backup. + require.NoError(t, os.Mkdir(storeDir, 0o750)) + // The PID lock lives under xdg.DataHome, which xdg resolves at // package init; point it at the temp dir so the test neither // touches nor collides with the real one. @@ -126,6 +132,11 @@ func writeHermeticPruneConfig(t *testing.T, seedStale bool) string { if seedStale { seedStaleSnapshotRecord(t, indexPath) + + // While the local index holds a snapshot, prune fails on a + // destination that answers that it has no marker. + require.NoError(t, os.WriteFile( + filepath.Join(storeDir, "vaultik-destination.txt"), nil, 0o600)) } return configPath diff --git a/internal/cli/entry_prune_quiet_test.go b/internal/cli/entry_prune_quiet_test.go new file mode 100644 index 0000000..30e1a33 --- /dev/null +++ b/internal/cli/entry_prune_quiet_test.go @@ -0,0 +1,127 @@ +package cli //nolint:testpackage // shares runEntry and the hermetic config helpers + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// flagCron is used to build the argument vectors below. +const flagCron = "--cron" + +// plantUnreferencedBlob writes a blob that no snapshot references to the +// destination store at storeDir, dated long before any prune grace period, +// so that a prune deletes it. Returns its path. +func plantUnreferencedBlob(t *testing.T, storeDir string) string { + t.Helper() + + hash := strings.Repeat("b", 64) + path := filepath.Join(storeDir, "blobs", hash[:2], hash[2:4], hash) + + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o750)) + require.NoError(t, os.WriteFile(path, []byte("unreferenced"), 0o600)) + + longAgo := time.Unix(0, 0) + require.NoError(t, os.Chtimes(path, longAgo, longAgo)) + + return path +} + +// TestEntrySnapshotCreatePruneIsSilent checks that a successful +// `snapshot create --prune` under --cron or --quiet prints nothing on +// stdout or stderr, whether or not the prune finds a blob to delete. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreatePruneIsSilent(t *testing.T) { + for _, testCase := range []struct { + name string + args []string + plantBlob bool + }{ + { + name: "cron, no blob to delete", + args: []string{cmdSnapshot, cmdCreate, flagCron, flagPrune}, + }, + { + name: "cron, blob to delete", + args: []string{cmdSnapshot, cmdCreate, flagCron, flagPrune}, + plantBlob: true, + }, + { + name: "cron with keep-newer-than", + args: []string{ + cmdSnapshot, cmdCreate, flagCron, flagPrune, + flagKeepNewerThan, "4w", + }, + plantBlob: true, + }, + { + name: "quiet", + args: []string{flagQuiet, cmdSnapshot, cmdCreate, flagPrune}, + plantBlob: true, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + configPath, storeDir := writeBackupConfig(t) + + var blob string + if testCase.plantBlob { + blob = plantUnreferencedBlob(t, storeDir) + } + + code, stdout, stderr := runEntry(t, + append([]string{flagConfig, configPath}, testCase.args...)...) + + assert.Equal(t, 0, code) + assert.Empty(t, stdout) + assert.Empty(t, stderr) + + if testCase.plantBlob { + assert.NoFileExists(t, blob, "the prune must delete the blob") + } + }) + } +} + +// TestEntryPruneQuietIsSilent checks that a successful `prune --force` +// under --quiet prints nothing on stdout or stderr, both when there is +// nothing to remove and when it removes a stale local snapshot record +// and an unreferenced blob. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntryPruneQuietIsSilent(t *testing.T) { + for _, testCase := range []struct { + name string + staleRecordAndBlob bool + }{ + {name: "nothing to remove"}, + {name: "stale record and blob to remove", staleRecordAndBlob: true}, + } { + t.Run(testCase.name, func(t *testing.T) { + configPath := writeHermeticPruneConfig(t, testCase.staleRecordAndBlob) + + var blob string + if testCase.staleRecordAndBlob { + // writeHermeticPruneConfig puts the store beside the config. + blob = plantUnreferencedBlob(t, + filepath.Join(filepath.Dir(configPath), "store")) + } + + code, stdout, stderr := runEntry(t, + flagConfig, configPath, flagQuiet, cmdPrune, flagForce) + + assert.Equal(t, 0, code) + assert.Empty(t, stdout) + assert.Empty(t, stderr) + + if testCase.staleRecordAndBlob { + assert.NoFileExists(t, blob, "the prune must delete the blob") + } + }) + } +} diff --git a/internal/cli/entry_snapshot_create_index_and_lock_files_test.go b/internal/cli/entry_snapshot_create_index_and_lock_files_test.go new file mode 100644 index 0000000..8cf32cc --- /dev/null +++ b/internal/cli/entry_snapshot_create_index_and_lock_files_test.go @@ -0,0 +1,69 @@ +package cli //nolint:testpackage // shares runEntry and the hermetic config helpers + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/adrg/xdg" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// TestEntrySnapshotCreateSkipsIndexAndLockFiles backs up a directory +// that holds vaultik's index and PID file beside one other file, with no +// exclude pattern set. The summary counts only the other file. See +// https://git.eeqj.de/sneak/vaultik/issues/421. +// +// Not parallel: it replaces os.Args, os.Stdout, os.Stderr and the xdg +// globals. +func TestEntrySnapshotCreateSkipsIndexAndLockFiles(t *testing.T) { + for _, testCase := range []struct { + name string + // linked sets index_path to a symlink outside the backed-up + // directory that points to the index inside it. + linked bool + }{ + {name: "index in the backed-up directory"}, + {name: "index_path links into the backed-up directory", linked: true}, + } { + t.Run(testCase.name, func(t *testing.T) { + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yml") + sourceDir := filepath.Join(dir, "source") + storeDir := filepath.Join(dir, "store") + + indexPath := filepath.Join(sourceDir, "index.sqlite") + + if testCase.linked { + link := filepath.Join(dir, "index.sqlite") + require.NoError(t, os.Symlink(indexPath, link)) + + indexPath = link + } + + contents := fmt.Sprintf(hermeticConfig, + sourceDir, storeDir, indexPath) + require.NoError(t, + os.WriteFile(configPath, []byte(contents), configFileMode)) + require.NoError(t, os.Mkdir(storeDir, 0o750)) + require.NoError(t, os.Mkdir(sourceDir, 0o750)) + require.NoError(t, os.WriteFile( + filepath.Join(sourceDir, "file.txt"), []byte("hello"), 0o600)) + + // The PID file goes in a directory under XDG_DATA_HOME, which + // xdg reads at package init. + t.Setenv("XDG_DATA_HOME", filepath.Join(sourceDir, "data")) + xdg.Reload() + t.Cleanup(xdg.Reload) + + code, stdout, _ := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate) + + require.Equal(t, 0, code) + assert.Contains(t, stdout, + "Files: 1 examined, 1 backed up, 0 unchanged.") + }) + } +} diff --git a/internal/cli/entry_snapshot_create_prune_test.go b/internal/cli/entry_snapshot_create_prune_test.go new file mode 100644 index 0000000..60b0846 --- /dev/null +++ b/internal/cli/entry_snapshot_create_prune_test.go @@ -0,0 +1,196 @@ +package cli //nolint:testpackage // shares runEntry and the hermetic config helpers + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" +) + +// Flags of `snapshot create` used to build argument vectors below. +const ( + flagPrune = "--prune" + flagKeepNewerThan = "--keep-newer-than" +) + +// TestEntrySnapshotCreateRejectsKeepNewerThanBeforeBackup checks that a +// --keep-newer-than the post-backup prune could not use stops `snapshot +// create` before the backup: the command fails and the destination +// store stays empty. It used to be read only by the prune, after the +// snapshot was uploaded, and without --prune it was ignored. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreateRejectsKeepNewerThanBeforeBackup(t *testing.T) { + for _, testCase := range []struct { + name string + args []string + }{ + { + name: "decimal in a day count", + args: []string{flagPrune, flagKeepNewerThan, "1.5d"}, + }, + { + name: "unknown unit", + args: []string{flagPrune, flagKeepNewerThan, "4x"}, + }, + { + name: "without --prune", + args: []string{flagKeepNewerThan, "4w"}, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + configPath, storeDir := writeBackupConfig(t) + + code, _, _ := runEntry(t, append( + []string{flagConfig, configPath, cmdSnapshot, cmdCreate}, + testCase.args...)...) + + assert.Equal(t, 1, code) + + stored, err := os.ReadDir(storeDir) + require.NoError(t, err) + assert.Empty(t, stored, "nothing may be uploaded") + }) + } +} + +// TestEntrySnapshotCreateReportsPostBackupPruneFailure makes the +// post-backup prune fail after a good backup, by planting a manifest +// that cannot be decoded, and checks that the failure is reported once, +// as the prune's and not as a failed snapshot creation. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreateReportsPostBackupPruneFailure(t *testing.T) { + configPath, storeDir := writeBackupConfig(t) + + // A remote key is 64 lowercase hex characters. The prune reads every + // manifest on the store and fails on one it cannot decode. + plantedDir := filepath.Join(storeDir, "metadata", strings.Repeat("a", 64)) + require.NoError(t, os.MkdirAll(plantedDir, 0o750)) + require.NoError(t, os.WriteFile( + filepath.Join(plantedDir, "manifest.json.zst"), + []byte("not a valid manifest"), 0o600)) + + code, _, stderr := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate, flagPrune) + + assert.Equal(t, 1, code) + assert.Contains(t, stderr, "Backup completed, but post-backup prune failed") + assert.NotContains(t, stderr, "Snapshot creation failed") + + _, repeats := failureOutput(t, stderr) + assert.Zero(t, repeats, "no log record may repeat the error:\n%s", stderr) + + snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata")) + require.NoError(t, err) + assert.Len(t, snapshots, 2, + "the new snapshot is on the store beside the planted one") +} + +// TestEntrySnapshotCreatePruneExitsNonZeroWhenSourceIsEmpty backs up, +// empties the source directory, as a volume that is not mounted leaves +// its mount point, and runs `snapshot create --prune`. The command exits +// non-zero and reports the backup as completed, not as a failed snapshot +// creation. The error is printed once. See +// https://git.eeqj.de/sneak/vaultik/issues/388. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreatePruneExitsNonZeroWhenSourceIsEmpty(t *testing.T) { + configPath, storeDir := writeBackupConfig(t) + + code, _, _ := runEntry(t, flagConfig, configPath, cmdSnapshot, cmdCreate) + require.Equal(t, 0, code) + + // writeBackupConfig puts the source directory beside the config file. + require.NoError(t, os.Remove( + filepath.Join(filepath.Dir(configPath), "source", "file.txt"))) + + code, _, stderr := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate, flagPrune) + + assert.Equal(t, 1, code) + assert.Contains(t, stderr, + "Backup completed, but 1 source path(s) were empty") + assert.NotContains(t, stderr, "Snapshot creation failed") + + _, repeats := failureOutput(t, stderr) + assert.Zero(t, repeats, "no log record may repeat the error:\n%s", stderr) + + snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata")) + require.NoError(t, err) + assert.Len(t, snapshots, 2, "the older snapshot is kept") +} + +// TestEntrySnapshotCreatePruneExitsNonZeroWhenMountPointIsMissing backs +// up, records in the local index that this backup found the source +// directory as a mount point, and runs `snapshot create --prune`, which +// does not find it as one. The command exits non-zero, reports the +// backup as completed, not as a failed snapshot creation, and keeps the +// older snapshot. The error is printed once. See +// https://git.eeqj.de/sneak/vaultik/issues/395. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreatePruneExitsNonZeroWhenMountPointIsMissing( + t *testing.T, +) { + configPath, storeDir := writeBackupConfig(t) + + code, _, _ := runEntry(t, flagConfig, configPath, cmdSnapshot, cmdCreate) + require.Equal(t, 0, code) + + // writeBackupConfig puts the source directory and the local index + // beside the config file. + dir := filepath.Dir(configPath) + ctx := context.Background() + + db, err := database.New(ctx, filepath.Join(dir, "index.sqlite")) + require.NoError(t, err) + + repos := database.NewRepositories(db) + + backedUp, err := repos.Snapshots.GetOnlySnapshot(ctx) + require.NoError(t, err) + require.NoError(t, repos.Snapshots.AddMountPoint(ctx, nil, + backedUp.ID.String(), filepath.Join(dir, "source"))) + require.NoError(t, db.Close()) + + code, _, stderr := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate, flagPrune) + + assert.Equal(t, 1, code) + assert.Contains(t, stderr, "Backup completed, but 1 mount point(s) "+ + "an earlier snapshot recorded were not found") + assert.NotContains(t, stderr, "Snapshot creation failed") + + _, repeats := failureOutput(t, stderr) + assert.Zero(t, repeats, "no log record may repeat the error:\n%s", stderr) + + snapshots, err := os.ReadDir(filepath.Join(storeDir, "metadata")) + require.NoError(t, err) + assert.Len(t, snapshots, 2, "the older snapshot is kept") +} + +// writeBackupConfig builds a hermetic config with one small file in its +// source directory and an empty destination store directory. Returns the +// config path and the store directory. +func writeBackupConfig(t *testing.T) (string, string) { + t.Helper() + + configPath := writeHermeticPruneConfig(t, false) + + // writeHermeticPruneConfig puts the source and store directories + // beside the config file. + dir := filepath.Dir(configPath) + sourceDir := filepath.Join(dir, "source") + + require.NoError(t, os.Mkdir(sourceDir, 0o750)) + require.NoError(t, os.WriteFile( + filepath.Join(sourceDir, "file.txt"), []byte("hello"), 0o600)) + + return configPath, filepath.Join(dir, "store") +} diff --git a/internal/cli/entry_snapshot_create_skip_errors_test.go b/internal/cli/entry_snapshot_create_skip_errors_test.go new file mode 100644 index 0000000..e52491d --- /dev/null +++ b/internal/cli/entry_snapshot_create_skip_errors_test.go @@ -0,0 +1,30 @@ +package cli //nolint:testpackage // shares runEntry and the hermetic config helpers + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestEntrySnapshotCreateSkipErrorsExitsNonZeroWhenItSkips backs up, +// under --skip-errors, a source directory that does not exist, which the +// walk skips. The command exits non-zero and reports the backup as +// completed, not as a failed snapshot creation. See +// https://git.eeqj.de/sneak/vaultik/issues/310. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotCreateSkipErrorsExitsNonZeroWhenItSkips(t *testing.T) { + // writeBackupConfig would create the source directory. + configPath := writeHermeticPruneConfig(t, false) + + code, stdout, stderr := runEntry(t, + flagConfig, configPath, "--skip-errors", cmdSnapshot, cmdCreate) + + assert.Equal(t, 1, code) + assert.Contains(t, stdout, + "Files: 1 examined, 0 backed up, 0 unchanged, 1 failed.") + assert.NotContains(t, stdout, "Finished successfully.") + assert.Contains(t, stderr, + "Backup completed, but 1 file(s) could not be read") + assert.NotContains(t, stderr, "Snapshot creation failed") +} diff --git a/internal/cli/entry_snapshot_files_test.go b/internal/cli/entry_snapshot_files_test.go new file mode 100644 index 0000000..c534f3d --- /dev/null +++ b/internal/cli/entry_snapshot_files_test.go @@ -0,0 +1,47 @@ +package cli //nolint:testpackage // shares runEntry and the backup config helpers + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// cmdFiles is the word of `snapshot files`, used to build argument +// vectors below. +const cmdFiles = "files" + +// TestEntrySnapshotFilesListsOnlyThePath backs up two files and runs +// `snapshot files` with the snapshot ID and the path of one of them, +// which must be the only file listed. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotFilesListsOnlyThePath(t *testing.T) { + configPath, _ := writeBackupConfigWithPrivateKey(t) + + // writeBackupConfig puts file.txt in the source directory beside the + // config file. + sourceDir := filepath.Join(filepath.Dir(configPath), "source") + listed := filepath.Join(sourceDir, "file.txt") + + require.NoError(t, os.WriteFile( + filepath.Join(sourceDir, "other.txt"), []byte("other"), 0o600)) + + code, _, stderr := runEntry(t, + flagConfig, configPath, cmdSnapshot, cmdCreate) + require.Equal(t, 0, code, stderr) + + code, stdout, stderr := runEntry(t, flagConfig, configPath, cmdSnapshot, + cmdFiles, onlySnapshotID(t, configPath), listed, flagJSON) + require.Equal(t, 0, code, stderr) + + var entries []vaultik.ListedFile + + require.NoError(t, json.Unmarshal([]byte(stdout), &entries)) + require.Len(t, entries, 1, "only the path given may be listed") + assert.Equal(t, listed, entries[0].Path) +} diff --git a/internal/cli/entry_snapshot_purge_test.go b/internal/cli/entry_snapshot_purge_test.go new file mode 100644 index 0000000..3e3c32c --- /dev/null +++ b/internal/cli/entry_snapshot_purge_test.go @@ -0,0 +1,75 @@ +package cli //nolint:testpackage // shares runEntry and the hermetic config helpers + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/snapshot" +) + +// Words and flags of `snapshot purge` used to build argument vectors +// below. +const ( + cmdPurge = "purge" + flagOlderThan = "--older-than" + flagForce = "--force" +) + +// TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails makes +// the local index refuse to delete an old snapshot and checks that +// `snapshot purge` exits non-zero and leaves that snapshot's metadata on +// the destination store. It used to log the error, delete the metadata +// and exit 0. +// +// `snapshot create --prune` runs the same purge, but cannot be driven +// this way: the refusal also breaks the backup's metadata export, which +// deletes the other snapshots from its copy of the local index. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotPurgeKeepsMetadataWhenLocalIndexDeleteFails(t *testing.T) { + configPath := writeHermeticPruneConfig(t, false) + dir := filepath.Dir(configPath) + indexPath := filepath.Join(dir, "index.sqlite") + + // seedStaleSnapshotRecord writes an old snapshot to the local index + // only; the manifest planted here puts it on the destination store + // too, so the purge selects it rather than dropping it as stale. + seedStaleSnapshotRecord(t, indexPath) + + // While the local index holds a snapshot, purge fails on a + // destination that answers that it has no marker. + require.NoError(t, os.WriteFile( + filepath.Join(dir, "store", "vaultik-destination.txt"), nil, 0o600)) + + manifestDir := filepath.Join(dir, "store", "metadata", + snapshot.RemoteSnapshotKey(stalePruneSnapshotID)) + require.NoError(t, os.MkdirAll(manifestDir, 0o750)) + + manifestPath := filepath.Join(manifestDir, "manifest.json.zst") + require.NoError(t, os.WriteFile(manifestPath, []byte("stub"), 0o600)) + + ctx := context.Background() + + db, err := database.New(ctx, indexPath) + require.NoError(t, err) + + _, err = db.Conn().ExecContext(ctx, ` + CREATE TRIGGER refuse_snapshot_delete BEFORE DELETE ON snapshots + BEGIN SELECT RAISE(ABORT, 'simulated index error'); END`) + require.NoError(t, err) + require.NoError(t, db.Close()) + + code, _, stderr := runEntry(t, flagConfig, configPath, + cmdSnapshot, cmdPurge, flagOlderThan, "30d", flagForce) + + assert.Equal(t, 1, code) + assert.Contains(t, stderr, "simulated index error", + "the purge must fail at the local-index delete") + assert.FileExists(t, manifestPath, + "the snapshot is still in the local index, so its metadata must stay") +} diff --git a/internal/cli/entry_status_test.go b/internal/cli/entry_status_test.go index 9042bce..2bd7bd6 100644 --- a/internal/cli/entry_status_test.go +++ b/internal/cli/entry_status_test.go @@ -15,8 +15,8 @@ import ( // run, so a failing command must come back with a non-zero code rather // than ending the process here. // -// Stdout is captured only to keep the banner and command output off the -// test log; the assertion is on the returned code. +// Stdout and stderr are captured only to keep the banner and command +// output off the test log; the assertion is on the returned code. // //nolint:paralleltest // replaces os.Args and rootFlags func TestEntryReturnsStatusCode(t *testing.T) { @@ -50,7 +50,7 @@ func TestEntryReturnsStatusCode(t *testing.T) { var code int - _ = captureProcessStdout(t, func() { code = Entry() }) + _, _ = captureProcessStdoutAndStderr(t, func() { code = Entry() }) assert.Equal(t, testCase.want, code) }) diff --git a/internal/cli/entry_stdout_stderr_test.go b/internal/cli/entry_stdout_stderr_test.go new file mode 100644 index 0000000..1eda0d4 --- /dev/null +++ b/internal/cli/entry_stdout_stderr_test.go @@ -0,0 +1,200 @@ +package cli //nolint:testpackage // shares hermeticConfig and the capture helpers + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/adrg/xdg" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" +) + +// TestEntryCompletionStdoutIsTheScript runs `vaultik completion bash`, +// whose stdout the README tells the user to source. The script has to +// start on the first line. +// +//nolint:paralleltest // replaces os.Args, os.Stdout and os.Stderr +func TestEntryCompletionStdoutIsTheScript(t *testing.T) { + code, stdout, _ := runEntry(t, "completion", "bash") + + require.Equal(t, 0, code) + + firstLine, _, _ := strings.Cut(stdout, "\n") + assert.True(t, strings.HasPrefix(firstLine, "# bash completion"), + "the first line of stdout must be the script's, got %q", firstLine) +} + +// TestEntryConfigGetStdoutIsTheValue runs `vaultik config get`, whose +// stdout a script reads as the value and nothing else. +// +//nolint:paralleltest // replaces os.Args, os.Stdout and os.Stderr +func TestEntryConfigGetStdoutIsTheValue(t *testing.T) { + configPath := filepath.Join(t.TempDir(), "config.yml") + require.NoError(t, os.WriteFile(configPath, + []byte("hostname: test-host\n"), configFileMode)) + + code, stdout, _ := runEntry(t, + flagConfig, configPath, "config", "get", "hostname") + + require.Equal(t, 0, code) + assert.Equal(t, "test-host\n", stdout) +} + +// TestEntryJSONFailureIsReportedOnStderr runs each --json command that +// writes no document when it fails, against a destination it cannot +// use. The error must reach stderr, and stdout must stay empty. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntryJSONFailureIsReportedOnStderr(t *testing.T) { + for _, testCase := range []struct { + name string + args []string + wantOnStderr string + }{ + { + name: "remote info", + args: []string{cmdRemote, cmdInfo, flagJSON}, + wantOnStderr: "Failed to get remote info", + }, + { + name: "prune", + args: []string{cmdPrune, flagJSON}, + wantOnStderr: "Prune failed", + }, + { + name: "snapshot remove", + args: []string{cmdSnapshot, cmdRemove, someSnapshotID, flagJSON}, + wantOnStderr: "Failed to remove snapshot", + }, + } { + t.Run(testCase.name, func(t *testing.T) { + configPath := writeUnusableDestinationConfig(t) + + code, stdout, stderr := runEntry(t, + append([]string{flagConfig, configPath}, testCase.args...)...) + + assert.Equal(t, 1, code) + assert.Empty(t, stdout, + "a failed --json command has no document to write") + assert.Contains(t, stderr, testCase.wantOnStderr, + "the failure must be reported on stderr") + }) + } +} + +// TestEntrySnapshotRemoveJSONWarningIsOnStderr runs `snapshot remove +// --json` on a snapshot in the local index, against a destination +// directory that does not exist. The command removes the snapshot from +// the local index and still exits 0. Its stdout must hold the document +// alone, with the warning about the destination store on stderr: the +// command to run again once it is reachable, and the snapshot's ID in +// the record's snapshot_id field. +// +//nolint:paralleltest // replaces os.Args, os.Stdout, os.Stderr and the xdg globals +func TestEntrySnapshotRemoveJSONWarningIsOnStderr(t *testing.T) { + configPath, indexPath := writeMissingDestinationConfig(t) + seedStaleSnapshotRecord(t, indexPath) + + code, stdout, stderr := runEntry(t, flagConfig, configPath, + cmdSnapshot, cmdRemove, stalePruneSnapshotID, flagJSON) + + require.Equal(t, 0, code) + requireExactlyOneJSONDocument(t, stdout) + + // stderr is a pipe here, so the logger writes one JSON record a line. + var warning map[string]any + + for line := range strings.Lines(stderr) { + if strings.Contains(line, + "Could not remove snapshot metadata from remote storage") { + require.NoError(t, json.Unmarshal([]byte(line), &warning)) + } + } + + require.NotNil(t, warning, "the warning must reach stderr") + assert.Contains(t, warning[slog.MessageKey], + "run 'vaultik snapshot remove' with the snapshot's ID again") + assert.Equal(t, stalePruneSnapshotID, warning["snapshot_id"]) +} + +// writeMissingDestinationConfig builds a config whose destination +// directory does not exist. Returns the config path and the path of +// its local index, which is not created here. +func writeMissingDestinationConfig(t *testing.T) (string, string) { + t.Helper() + + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yml") + indexPath := filepath.Join(dir, "index.sqlite") + + contents := fmt.Sprintf(hermeticConfig, + filepath.Join(dir, "source"), + filepath.Join(dir, "missing-store"), + indexPath) + + require.NoError(t, + os.WriteFile(configPath, []byte(contents), configFileMode)) + + // The PID lock lives under xdg.DataHome, which xdg resolves at + // package init; point it at the temp dir so the test neither + // touches nor collides with the real one. + t.Setenv("XDG_DATA_HOME", filepath.Join(dir, "data")) + xdg.Reload() + t.Cleanup(xdg.Reload) + + return configPath, indexPath +} + +// writeUnusableDestinationConfig builds a config whose destination +// directory does not exist, which fails `remote info`, and whose local +// index is bound to another destination, which fails `prune` and +// `snapshot remove` (a missing destination alone only makes `snapshot +// remove` warn). Returns the config path. +func writeUnusableDestinationConfig(t *testing.T) string { + t.Helper() + + configPath, indexPath := writeMissingDestinationConfig(t) + + ctx := context.Background() + + db, err := database.New(ctx, indexPath) + require.NoError(t, err) + + defer func() { require.NoError(t, db.Close()) }() + + require.NoError(t, database.NewRepositories(db).LocalMeta.Set(ctx, + database.LocalMetaKeyStorageURL, "file://"+t.TempDir())) + + return configPath +} + +// runEntry runs Entry with args after the program name and returns its +// exit code and what it wrote to stdout and stderr. +// +// Not parallel-safe: it replaces os.Args, os.Stdout and os.Stderr. +func runEntry(t *testing.T, args ...string) (int, string, string) { + t.Helper() + + previousArgs := os.Args + + t.Cleanup(func() { + os.Args = previousArgs + rootFlags = RootFlags{} + }) + + os.Args = append([]string{programName}, args...) + + var code int + + stdout, stderr := captureProcessStdoutAndStderr(t, + func() { code = Entry() }) + + return code, stdout, stderr +} diff --git a/internal/cli/entry_test.go b/internal/cli/entry_test.go index 60877ed..a2f103d 100644 --- a/internal/cli/entry_test.go +++ b/internal/cli/entry_test.go @@ -48,7 +48,7 @@ func TestCLIEntry(t *testing.T) { } else { // Check snapshot subcommands expectedSubCommands := []string{ - "create", "list", "purge", "verify", "remove", "restore", + "create", "list", "files", "purge", "verify", "remove", "restore", } for _, expected := range expectedSubCommands { found := false diff --git a/internal/cli/entry_unknown_subcommand_test.go b/internal/cli/entry_unknown_subcommand_test.go new file mode 100644 index 0000000..08c9647 --- /dev/null +++ b/internal/cli/entry_unknown_subcommand_test.go @@ -0,0 +1,43 @@ +package cli //nolint:testpackage // shares runEntry and the command-word constants + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestEntryGroupRejectsUnknownSubcommand runs each group command with a +// mistyped subcommand, as a crontab line might carry one. It must fail +// with exit 1 and name the word, as `vaultik bogus` does at the top +// level, instead of printing the group's help and exiting 0 having done +// nothing. The group name alone still prints its help. +// +//nolint:paralleltest // replaces os.Args, os.Stdout and os.Stderr +func TestEntryGroupRejectsUnknownSubcommand(t *testing.T) { + for _, testCase := range []struct { + group string + mistyped string + }{ + {group: cmdSnapshot, mistyped: "craete"}, + {group: "config", mistyped: "inti"}, + {group: cmdRemote, mistyped: "ifno"}, + {group: "database", mistyped: "delte"}, + {group: "completion", mistyped: "nosuchshell"}, + } { + t.Run(testCase.group, func(t *testing.T) { + code, stdout, stderr := runEntry(t, + testCase.group, testCase.mistyped) + + assert.Equal(t, 1, code) + assert.Empty(t, stdout) + assert.Contains(t, stderr, + `unknown command "`+testCase.mistyped+`"`) + + code, stdout, _ = runEntry(t, testCase.group) + + assert.Equal(t, 0, code) + assert.Contains(t, stdout, + programName+" "+testCase.group+" [command]") + }) + } +} diff --git a/internal/cli/info.go b/internal/cli/info.go index 27d40de..5430656 100644 --- a/internal/cli/info.go +++ b/internal/cli/info.go @@ -39,7 +39,7 @@ func NewInfoCommand() *cobra.Command { }, func(v *vaultik.Vaultik) error { return v.ShowInfo() }, func(err error) { - log.Error("Failed to show info", "error", err) + log.Info("Failed to show info", "error", err) ReportErrorf("Failed to show info: %v", err) }) }, diff --git a/internal/cli/json_help_test.go b/internal/cli/json_help_test.go new file mode 100644 index 0000000..3d25048 --- /dev/null +++ b/internal/cli/json_help_test.go @@ -0,0 +1,24 @@ +package cli //nolint:testpackage // exercises the unexported command constructor + +import ( + "testing" + + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" +) + +// TestJSONHelpSaysConfirmationPromptIsSkipped checks that the --json help +// of `snapshot remove` and `prune` says the flag skips the confirmation +// prompt. Both delete without asking under --json, since a prompt on +// stdout would break the JSON document. +func TestJSONHelpSaysConfirmationPromptIsSkipped(t *testing.T) { + t.Parallel() + + for _, cmd := range []*cobra.Command{ + newSnapshotRemoveCommand(), + NewPruneCommand(), + } { + assert.Contains(t, cmd.Flags().Lookup("json").Usage, + "skips the confirmation prompt", cmd.Name()) + } +} diff --git a/internal/cli/prune.go b/internal/cli/prune.go index b3b6040..6063e7a 100644 --- a/internal/cli/prune.go +++ b/internal/cli/prune.go @@ -13,18 +13,30 @@ func NewPruneCommand() *cobra.Command { cmd := &cobra.Command{ Use: "prune", Short: "Tidy local database and remote storage", - Long: `Removes orphaned data from both the local index database and -unreferenced blobs from the backup destination store. + Long: `Removes orphaned data from the local index database, and +unreferenced blobs and directories under metadata/ with no manifest +from the backup destination store. Local cleanup drops incomplete snapshots and any files, chunks, or blobs no longer referenced by a completed snapshot. Remote cleanup scans every snapshot manifest in the destination store, builds the set of still-referenced blob hashes, and deletes any blob not in that -set. +set that is older than prune_grace_period (default 24h). A newer one +is kept: it may belong to a backup still running, on this host or +another sharing the destination store, that has not yet uploaded its +manifest. The grace period does not protect a blob such a backup +reuses from an earlier run that stopped before its manifest: that +blob keeps the time of its first upload, so it can be deleted. +Remote cleanup also deletes each directory under metadata/ with no +manifest, as a backup that stopped before its manifest leaves, once +all its objects are older than prune_grace_period and its snapshot is +not in the local index. -Snapshot create --prune and snapshot remove run the same cleanup -automatically; this command is the manual entry point for the same -work (e.g. after a crashed backup or to reclaim storage).`, +Snapshot create --prune runs the same cleanup automatically; this +command is the manual entry point for the same work (e.g. after a +crashed backup or to reclaim storage). Snapshot remove leaves blobs in +place; run this command afterwards to delete the ones no longer +referenced.`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { // Use unified config resolution @@ -48,18 +60,15 @@ work (e.g. after a crashed backup or to reclaim storage).`, }, func(v *vaultik.Vaultik) error { return v.Prune(opts) }, func(err error) { - if opts.JSON { - return - } - - log.Error("Prune operation failed", "error", err) + log.Info("Prune operation failed", "error", err) ReportErrorf("Prune failed: %v", err) }) }, } cmd.Flags().BoolVar(&opts.Force, "force", false, "Skip confirmation prompt") - cmd.Flags().BoolVar(&opts.JSON, "json", false, "Output pruning stats as JSON") + cmd.Flags().BoolVar(&opts.JSON, "json", false, + "Output pruning stats as JSON; skips the confirmation prompt, as --force does") return cmd } diff --git a/internal/cli/remote.go b/internal/cli/remote.go index e561298..f46bb26 100644 --- a/internal/cli/remote.go +++ b/internal/cli/remote.go @@ -18,6 +18,12 @@ func NewRemoteCommand() *cobra.Command { Use: "remote", Short: "Remote storage management commands", Long: "Commands for inspecting and managing remote storage", + // cobra checks Args only on a command that has a Run: without + // one, a mistyped subcommand printed help and exited 0. + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, _ []string) { + _ = cmd.Help() + }, } // Add subcommands @@ -45,7 +51,7 @@ This is destructive and irreversible. Requires --force.`, return errNukeNeedsForce } - return runVaultikApp(cmd, mutating, false, false, "Remote nuke failed", + return runVaultikApp(cmd, mutating, false, "Remote nuke failed", func(v *vaultik.Vaultik) error { return v.NukeRemote(true) }) @@ -92,11 +98,7 @@ func newRemoteInfoCommand() *cobra.Command { }, func(v *vaultik.Vaultik) error { return v.RemoteInfo(jsonOutput) }, func(err error) { - if jsonOutput { - return - } - - log.Error("Failed to get remote info", "error", err) + log.Info("Failed to get remote info", "error", err) ReportErrorf("Failed to get remote info: %v", err) }) }, diff --git a/internal/cli/root.go b/internal/cli/root.go index 7f24423..ba1fcbc 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -60,7 +60,8 @@ on the source system.`, cmd.PersistentFlags().BoolVar(&rootFlags.SkipErrors, "skip-errors", false, "Skip files that cannot be read when creating a snapshot, or "+ "that cannot be restored when restoring, instead of aborting "+ - "(packing and storage errors still abort)") + "(packing and storage errors while creating a snapshot still "+ + "abort)") // Add subcommands cmd.AddCommand( @@ -73,6 +74,21 @@ on the source system.`, NewDatabaseCommand(), ) + // cobra adds the completion command only when Execute runs, and with + // no Run, so it skipped its own cobra.NoArgs and a mistyped shell name + // printed help and exited 0. Adding it here lets it have a Run. Its + // scripts go to os.Stdout as it is now: a later SetOut does not + // redirect them. + cmd.InitDefaultCompletionCmd() + + for _, sub := range cmd.Commands() { + if sub.Name() == "completion" { + sub.Run = func(completion *cobra.Command, _ []string) { + _ = completion.Help() + } + } + } + return cmd } diff --git a/internal/cli/snapshot.go b/internal/cli/snapshot.go index cee6594..86ac329 100644 --- a/internal/cli/snapshot.go +++ b/internal/cli/snapshot.go @@ -9,6 +9,10 @@ import ( "sneak.berlin/go/vaultik/internal/vaultik" ) +// filesMaxArgs is the maximum positional argument count of +// `snapshot files [path]`. +const filesMaxArgs = 2 + var ( errSnapshotIDRequired = errors.New("snapshot ID required") errWrongArgCount = errors.New("wrong argument count") @@ -41,11 +45,18 @@ func NewSnapshotCommand() *cobra.Command { Use: "snapshot", Short: "Snapshot management commands", Long: "Commands for creating, listing, and managing snapshots", + // cobra checks Args only on a command that has a Run: without + // one, a mistyped subcommand printed help and exited 0. + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, _ []string) { + _ = cmd.Help() + }, } // Add subcommands cmd.AddCommand(newSnapshotCreateCommand()) cmd.AddCommand(newSnapshotListCommand()) + cmd.AddCommand(newSnapshotFilesCommand()) cmd.AddCommand(newSnapshotPurgeCommand()) cmd.AddCommand(newSnapshotVerifyCommand()) cmd.AddCommand(newSnapshotRemoveCommand()) @@ -66,10 +77,16 @@ func newSnapshotCreateCommand() *cobra.Command { If snapshot names are provided, only those snapshots are created. If no names are provided, all configured snapshots are created. -Config is located at /etc/vaultik/config.yml by default, but can be overridden by -specifying a path using --config or by setting VAULTIK_CONFIG to a path.`, +The config is read from the path given by --config or VAULTIK_CONFIG; +otherwise from the platform config directory (~/.config/vaultik/config.yml +on Linux), then /etc/vaultik/config.yml.`, Args: cobra.ArbitraryArgs, RunE: func(cmd *cobra.Command, args []string) error { + err := opts.Validate() + if err != nil { + return err + } + // Pass snapshot names from args opts.Snapshots = args // --skip-errors is a global flag on the root command. @@ -96,7 +113,23 @@ specifying a path using --config or by setting VAULTIK_CONFIG to a path.`, }, func(v *vaultik.Vaultik) error { return v.CreateSnapshot(opts) }, func(err error) { - log.Error("Snapshot creation failed", "error", err) + if errors.Is(err, vaultik.ErrPostBackupPruneFailed) { + log.Info("Post-backup prune failed", "error", err) + ReportErrorf("Backup completed, but %v", err) + + return + } + + if errors.Is(err, vaultik.ErrFilesUnreadable) || + errors.Is(err, vaultik.ErrSourcePathEmpty) || + errors.Is(err, vaultik.ErrVolumeNotMounted) { + log.Info("Backup completed with an error", "error", err) + ReportErrorf("Backup completed, but %v", err) + + return + } + + log.Info("Snapshot creation failed", "error", err) ReportErrorf("Snapshot creation failed: %v", err) }) }, @@ -105,8 +138,13 @@ specifying a path using --config or by setting VAULTIK_CONFIG to a path.`, cmd.Flags().BoolVar(&opts.Cron, "cron", false, "Run in cron mode (silent unless warning or error)") cmd.Flags().BoolVar(&opts.Prune, "prune", false, - "After backup, drop older snapshots of the same name and remove "+ - "orphaned blobs") + "After backup, drop older snapshots of the same name, remove "+ + "orphaned blobs older than prune_grace_period, and delete each "+ + "directory under metadata/ with no manifest once all its "+ + "objects are older than prune_grace_period and its snapshot is "+ + "not in the local index (not after a backup that skipped "+ + "unreadable files, found a configured path empty, or did not "+ + "find a mount point an earlier snapshot found)") cmd.Flags().StringVar(&opts.KeepNewerThan, "keep-newer-than", "", "With --prune: keep snapshots newer than this duration "+ "(e.g. 30d, 4w, 6mo, 1y; m is minutes, mo is months) "+ @@ -126,7 +164,7 @@ func newSnapshotListCommand() *cobra.Command { Long: "Lists all snapshots with their ID, timestamp, and compressed size", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { - return runVaultikApp(cmd, readOnly, false, false, + return runVaultikApp(cmd, readOnly, false, "Failed to list snapshots", func(v *vaultik.Vaultik) error { return v.ListSnapshots(jsonOutput) @@ -139,6 +177,44 @@ func newSnapshotListCommand() *cobra.Command { return cmd } +// newSnapshotFilesCommand creates the 'snapshot files' subcommand +func newSnapshotFilesCommand() *cobra.Command { + var jsonOutput bool + + cmd := &cobra.Command{ + Use: "files [path]", + Short: "List the files in a snapshot", + Long: `Lists the path, size, mode and modification time of every file in a +snapshot, without restoring it. With a path, lists only that path and +what is under it; a path that matches nothing is an error. + +The snapshot may be named by its ID or, on a host with no local index, +by the remote key that 'snapshot list' prints for a remote-only snapshot +(an unambiguous leading part is enough). + +The file list is only in the snapshot's encrypted database, so this +downloads and decrypts it, and requires the age private key in the +VAULTIK_AGE_SECRET_KEY environment variable, as 'snapshot restore' does.`, + Args: cobra.RangeArgs(1, filesMaxArgs), + RunE: func(cmd *cobra.Command, args []string) error { + path := "" + if len(args) == filesMaxArgs { + path = args[1] + } + + return runVaultikApp(cmd, readOnly, jsonOutput, + "Failed to list snapshot files", + func(v *vaultik.Vaultik) error { + return v.ListSnapshotFiles(args[0], path, jsonOutput) + }) + }, + } + + cmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format") + + return cmd +} + // newSnapshotPurgeCommand creates the 'snapshot purge' subcommand func newSnapshotPurgeCommand() *cobra.Command { opts := &vaultik.SnapshotPurgeOptions{} @@ -162,7 +238,7 @@ restrict the operation to specific snapshot names.`, return errPurgeCriteriaBoth } - return runVaultikApp(cmd, mutating, false, false, + return runVaultikApp(cmd, mutating, false, "Failed to purge snapshots", func(v *vaultik.Vaultik) error { return v.PurgeSnapshotsWithOptions(opts) @@ -225,7 +301,7 @@ func newSnapshotVerifyCommand() *cobra.Command { return } - log.Error("Verification failed", "error", err) + log.Info("Verification failed", "error", err) ReportErrorf("Verification failed: %v", err) }) }, @@ -251,21 +327,31 @@ By default, this removes the snapshot from the local index database and strips the snapshot's metadata from the backup destination store. Blobs are NOT touched: deleting them requires reading every remaining remote manifest (the destination store may hold snapshots this host doesn't -know about), which is what 'vaultik prune' does. On success the command -prints the exact 'vaultik prune' invocation to run as a follow-up. +know about), which is what 'vaultik prune' does. The command prints the +'vaultik prune' invocation to run as a follow-up only when it removed the +snapshot's metadata from the destination store, and never under --json. + +The snapshot may be named by its ID or by its remote key, which +'snapshot list' prints for a remote-only snapshot. An unambiguous +leading part of the key is enough. An identifier that names no snapshot +in the local index or on the destination store is an error. Use --local-only to skip the remote half (e.g. when you want to forget a -snapshot locally without touching the destination store). +snapshot locally without touching the destination store); the snapshot +must then be in the local index. -If the remote is unreachable, the local-database removal still completes -and a warning is emitted; rerun 'vaultik prune' once the destination store -is reachable to finish remote cleanup. +If removing the snapshot's metadata from the destination store fails (for +example because the remote is unreachable), the local-database removal +still completes and a warning is emitted; run 'vaultik snapshot remove +' again once the destination store is reachable to remove +the snapshot's metadata from it ('vaultik prune' does not). For a +snapshot that is only on the destination store, that failure is an error. To wipe the entire destination store and start over, use 'vaultik remote nuke --force' — it is the single supported entry point for that.`, Args: requireSnapshotIDArg, RunE: func(cmd *cobra.Command, args []string) error { - return runVaultikApp(cmd, mutating, opts.JSON, opts.JSON, + return runVaultikApp(cmd, mutating, opts.JSON, "Failed to remove snapshot", func(v *vaultik.Vaultik) error { _, err := v.RemoveSnapshot(args[0], opts) @@ -278,7 +364,8 @@ nuke --force' — it is the single supported entry point for that.`, cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Skip confirmation prompt") cmd.Flags().BoolVar(&opts.DryRun, "dry-run", false, "Show what would be removed without removing") - cmd.Flags().BoolVar(&opts.JSON, "json", false, "Output result as JSON") + cmd.Flags().BoolVar(&opts.JSON, "json", false, + "Output result as JSON; skips the confirmation prompt, as --force does") cmd.Flags().BoolVar(&opts.LocalOnly, "local-only", false, "Skip remote cleanup; only touch the local index") diff --git a/internal/cli/snapshot_restore.go b/internal/cli/snapshot_restore.go index ce28542..6e75ffc 100644 --- a/internal/cli/snapshot_restore.go +++ b/internal/cli/snapshot_restore.go @@ -30,6 +30,8 @@ This command will restore files from the specified snapshot to the target directory. If no paths are specified, all files are restored. If paths are specified, only matching files/directories are restored. +A path that matches nothing in the snapshot is named in a warning, and +the command exits non-zero after restoring the paths that match. The snapshot may be named by its ID or, when restoring on a host with no local index, by the remote key that 'snapshot list' prints for a @@ -102,7 +104,7 @@ func runRestore(cmd *cobra.Command, args []string, opts *RestoreOptions) error { SkipErrors: rootFlags.SkipErrors, }) }, func(err error) { - log.Error("Restore operation failed", "error", err) + log.Info("Restore operation failed", "error", err) ReportErrorf("Restore failed: %v", err) }) } diff --git a/internal/cli/version.go b/internal/cli/version.go index 0307060..400d6eb 100644 --- a/internal/cli/version.go +++ b/internal/cli/version.go @@ -37,13 +37,13 @@ func writeVersion(out *ui.Writer) { w := out.Out() _, _ = fmt.Fprintf(w, "vaultik %s\n", globals.Version) - _, _ = fmt.Fprintf(w, " commit: %s\n", globals.Commit) - _, _ = fmt.Fprintf(w, " build date: %s\n", globals.CommitDate) - _, _ = fmt.Fprintf(w, " go: %s\n", runtime.Version()) - _, _ = fmt.Fprintf(w, " os/arch: %s/%s\n", runtime.GOOS, runtime.GOARCH) - _, _ = fmt.Fprintf(w, " author: %s\n", globals.Author) - _, _ = fmt.Fprintf(w, " homepage: %s\n", globals.Homepage) - _, _ = fmt.Fprintf(w, " license: %s\n", globals.License) + _, _ = fmt.Fprintf(w, " commit: %s\n", globals.Commit) + _, _ = fmt.Fprintf(w, " commit date: %s\n", globals.CommitDate) + _, _ = fmt.Fprintf(w, " go: %s\n", runtime.Version()) + _, _ = fmt.Fprintf(w, " os/arch: %s/%s\n", runtime.GOOS, runtime.GOARCH) + _, _ = fmt.Fprintf(w, " author: %s\n", globals.Author) + _, _ = fmt.Fprintf(w, " homepage: %s\n", globals.Homepage) + _, _ = fmt.Fprintf(w, " license: %s\n", globals.License) if globals.IsDevVersion(globals.Version) { _, _ = fmt.Fprintln(w) diff --git a/internal/cli/version_test.go b/internal/cli/version_test.go index 7068f9d..3215029 100644 --- a/internal/cli/version_test.go +++ b/internal/cli/version_test.go @@ -2,6 +2,7 @@ package cli_test import ( "bytes" + "runtime" "strings" "testing" @@ -49,6 +50,42 @@ func TestVersionCommandReportsBuildVersion(t *testing.T) { } } +// TestVersionCommandReportLines checks the label, padding and value of +// every line of the report. Commit and CommitDate get different values, +// so a line that prints the wrong one fails. +// +//nolint:paralleltest // sets globals.Commit and globals.CommitDate +func TestVersionCommandReportLines(t *testing.T) { + const ( + commit = "abc1234" + commitDate = "2026-11-09" + ) + + previousCommit, previousCommitDate := globals.Commit, globals.CommitDate + + t.Cleanup(func() { + globals.Commit = previousCommit + globals.CommitDate = previousCommitDate + }) + + globals.Commit = commit + globals.CommitDate = commitDate + + want := "vaultik " + globals.Version + "\n" + + " commit: " + commit + "\n" + + " commit date: " + commitDate + "\n" + + " go: " + runtime.Version() + "\n" + + " os/arch: " + runtime.GOOS + "/" + runtime.GOARCH + "\n" + + " author: " + globals.Author + "\n" + + " homepage: " + globals.Homepage + "\n" + + " license: " + globals.License + "\n" + + out := runVersionCommand(t) + if !strings.HasPrefix(out, want) { + t.Errorf("report:\n%s\nwant it to start with:\n%s", out, want) + } +} + // TestVersionCommandFlagsDevelopmentBuild is the regression test for // the thing this command exists to prevent: a build that is not a // release must say so. The notice used to be gated on the version diff --git a/internal/config/config.go b/internal/config/config.go index 2608d9d..ba8b259 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,12 +4,15 @@ package config import ( + "bytes" "errors" "fmt" "os" "path/filepath" + "reflect" "sort" "strings" + "time" "filippo.io/age" "git.eeqj.de/sneak/smartconfig" @@ -29,42 +32,60 @@ const appName = "vaultik" //nolint:gosec // G101: marker for detecting a pasted secret key, not a credential const secretKeyPrefix = "AGE-SECRET-KEY-" -// Defaults and validation bounds for tunable settings. +// Defaults and validation bounds for tunable settings. MB and GB are +// 1000-based, as the size parser reads them; the S3 part sizes are S3's own +// limits, which are 1024-based (MiB, GiB). const ( - defaultBlobSizeLimit = Size(10 * 1024 * 1024 * 1024) // 10GB - defaultChunkSize = Size(10 * 1024 * 1024) // 10MB - defaultS3PartSize = Size(5 * 1024 * 1024) // 5MB + defaultBlobSizeLimit = Size(10 * 1000 * 1000 * 1000) // 10GB + defaultChunkSize = Size(10 * 1000 * 1000) // 10MB + defaultS3PartSize = Size(5 * 1024 * 1024) // 5MiB defaultCompressionLevel = 3 - minChunkSize = 1024 * 1024 // 1MB + defaultPruneGracePeriod = 24 * time.Hour + minChunkSize = 1000 * 1000 // 1MB minCompressionLevel = 1 maxCompressionLevel = 19 + // S3 accepts a multipart upload part from 5MiB to 5GiB. + minS3PartSize = 5 * 1024 * 1024 + maxS3PartSize = 5 * 1024 * 1024 * 1024 ) // Sentinel validation errors. var ( - errNoConfigPath = errors.New("config path not provided") - errNoAgeRecipients = errors.New( - "at least one age_recipient is required (generate with: age-keygen)") + errNoConfigPath = errors.New("config path not provided") errRecipientIsSecretKey = errors.New( "an age secret key was given where a public key (age1...) belongs") errRecipientNotX25519 = errors.New( "not a valid recipient; only X25519 age1... public keys are supported") errNoSnapshots = errors.New( - "at least one snapshot must be configured (see config.example.yml)") + "at least one snapshot must be configured (see configs/config.example.yml)") errSnapshotNoPaths = errors.New("snapshot must have at least one path") errChunkSizeTooSmall = errors.New("chunk_size must be at least 1MB") errBlobSizeTooSmall = errors.New( "blob_size_limit must be at least the largest chunk the chunker can " + "emit (chunk_size times the FastCDC size spread)") errBadCompression = errors.New("compression_level must be between 1 and 19") + errBadS3PartSize = errors.New("s3.part_size must be between 5MiB and 5GiB") errBadStorageScheme = errors.New( "storage_url must start with s3://, file://, or rclone://") + errFileURLNotAbsolute = errors.New( + "a file:// storage_url needs an absolute path, " + + "as in file:///path/to/backup") + errIndexPathNotAbsolute = errors.New( + "index_path and VAULTIK_INDEX_PATH need an absolute path, " + + "as in ~/.local/share/vaultik/index.sqlite") + errNegativePruneGracePeriod = errors.New( + "prune_grace_period must not be negative") errStorageNotConfigured = errors.New( "storage not configured; set storage_url or provide s3.endpoint + " + "s3.bucket + credentials") errS3BucketRequired = errors.New("s3.bucket is required (or set storage_url)") - errS3KeyIDRequired = errors.New("s3.access_key_id is required") - errS3SecretRequired = errors.New("s3.secret_access_key is required") +) + +// Validate returns these when S3 storage is configured without its +// credentials. +var ( + ErrS3KeyIDRequired = errors.New("s3.access_key_id is required") + ErrS3SecretRequired = errors.New("s3.secret_access_key is required") ) // expandTilde expands ~ at the start of a path to the user's home directory. @@ -179,6 +200,15 @@ type Config struct { Snapshots map[string]SnapshotConfig `yaml:"snapshots"` CompressionLevel int `yaml:"compression_level"` + // PruneGracePeriod is how old a blob no manifest lists must be before + // a prune deletes it, and how old every object in a directory under + // metadata/ with no manifest must be before a prune deletes that + // directory. A backup writes its manifest only once it has uploaded + // all its blobs and its db.zst.age, so a younger blob or directory may + // belong to a backup still running, on this host or another sharing + // the destination store. + PruneGracePeriod time.Duration `yaml:"prune_grace_period"` + // StorageURL specifies the storage backend using a URL format. // Takes precedence over S3Config if set. // Supported formats: @@ -228,24 +258,84 @@ func New(path Path) (*Config, error) { return cfg, nil } -// Load reads and parses the configuration file from the specified path. -// It applies default values for optional fields, performs environment variable -// substitution using smartconfig, and validates the configuration. -// The configuration file should be in YAML format. Returns an error if the file -// cannot be read, parsed, or if validation fails. +// Load reads the configuration file at path, parses it with Parse, warns +// when others can read the file, and validates the configuration. +// Returns an error if the file cannot be read, parsed, or if validation +// fails. func Load(path string) (*Config, error) { - // Load config using smartconfig for interpolation - sc, err := smartconfig.NewFromConfigPath(path) + data, err := os.ReadFile(path) //nolint:gosec // G304: config path is operator-supplied if err != nil { return nil, fmt.Errorf("failed to load config file: %w", err) } + cfg, err := Parse(data) + if err != nil { + return nil, err + } + + // Check config file permissions (warn if world or group readable) + //nolint:gosec // G703: config path is operator-supplied by design + info, statErr := os.Stat(path) + if statErr == nil { + mode := info.Mode().Perm() + if mode&0044 != 0 { // group or world readable + log.Warn(cfg.readableByOthersWarning(), + "path", path, + "mode", fmt.Sprintf("%04o", mode), + "recommendation", "chmod 600 "+path) + } + } + + err = cfg.Validate() + if err != nil { + return nil, fmt.Errorf("invalid config: %w", err) + } + + return cfg, nil +} + +// Parse reads YAML config data as Load does, without validating it. It +// refuses a key that no setting has and a size setting whose value is not a +// size, naming the setting. It applies default values for optional +// fields, fills in ${...} references using smartconfig, and expands ~ in +// paths. +func Parse(data []byte) (*Config, error) { + // smartconfig drops line numbers, so keys are checked in the data as + // written. + var root yaml.Node + + err := yaml.Unmarshal(data, &root) + if err != nil { + return nil, fmt.Errorf("failed to parse config: %w", err) + } + + err = checkKeys(&root, reflect.TypeFor[Config](), "", + map[*yaml.Node]bool{}, map[nodeAndType]bool{}) + if err != nil { + return nil, err + } + + // Load config using smartconfig for interpolation + sc, err := smartconfig.NewFromReader(bytes.NewReader(data)) + if err != nil { + return nil, fmt.Errorf("failed to load config file: %w", err) + } + + // A ${...} reference can bring in keys that are not in the file, and + // is the value of a size setting only once it is filled in. + err = checkFilledConfig(sc.Data()) + if err != nil { + return nil, err + } + cfg := &Config{ // Set defaults BlobSizeLimit: defaultBlobSizeLimit, ChunkSize: defaultChunkSize, IndexPath: filepath.Join(xdg.DataHome, appName, "index.sqlite"), CompressionLevel: defaultCompressionLevel, + PruneGracePeriod: defaultPruneGracePeriod, + S3: S3Config{PartSize: defaultS3PartSize}, } // Convert smartconfig data to YAML then unmarshal @@ -296,50 +386,31 @@ func Load(path string) (*Config, error) { cfg.S3.Region = "us-east-1" } - if cfg.S3.PartSize == 0 { - cfg.S3.PartSize = defaultS3PartSize - } - - // Check config file permissions (warn if world or group readable) - //nolint:gosec // G703: config path is operator-supplied by design - info, statErr := os.Stat(path) - if statErr == nil { - mode := info.Mode().Perm() - if mode&0044 != 0 { // group or world readable - log.Warn("Config file has insecure permissions (contains S3 credentials)", - "path", path, - "mode", fmt.Sprintf("%04o", mode), - "recommendation", "chmod 600 "+path) - } - } - - err = cfg.Validate() - if err != nil { - return nil, fmt.Errorf("invalid config: %w", err) - } - return cfg, nil } // Validate checks if the configuration is valid and complete. // It ensures all required fields are present and have valid values: -// - At least one age recipient must be specified, and every recipient must -// parse as an X25519 age1... public key (so a bad entry fails at load, not -// mid-backup); errors name the position, never the value +// - Every age recipient must parse as an X25519 age1... public key (so a +// bad entry fails at load, not mid-backup); errors name the position, +// never the value. An empty list is accepted, because only snapshot +// create needs a recipient and it checks for one itself // - At least one snapshot must be configured with at least one path +// - Every exclude pattern, global or in a snapshot, must compile; errors +// name the setting and quote the pattern // - Storage must be configured (either storage_url or s3.* fields) +// - The index path must be absolute: a relative one would resolve against +// the working directory, so each directory would get its own index // - Chunk size must be at least 1MB // - Blob size limit must be at least the largest chunk the chunker can emit // (chunk_size times chunker.ChunkSizeSpread), so a single-chunk blob never // exceeds the configured limit // - Compression level must be between 1 and 19 +// - S3 part size must be between 5MiB and 5GiB, the part sizes S3 accepts +// - Prune grace period must not be negative // // Returns an error describing the first validation failure encountered. func (c *Config) Validate() error { - if len(c.AgeRecipients) == 0 { - return errNoAgeRecipients - } - for i, recipient := range c.AgeRecipients { err := validateAgeRecipient(recipient) if err != nil { @@ -347,22 +418,26 @@ func (c *Config) Validate() error { } } - if len(c.Snapshots) == 0 { - return errNoSnapshots + err := c.validateSnapshots() + if err != nil { + return err } - for name, snap := range c.Snapshots { - if len(snap.Paths) == 0 { - return fmt.Errorf("%w: %q", errSnapshotNoPaths, name) - } + err = c.validateExcludes() + if err != nil { + return err } // Validate storage configuration - err := c.validateStorage() + err = c.validateStorage() if err != nil { return err } + if !filepath.IsAbs(c.IndexPath) { + return fmt.Errorf("%w: %q", errIndexPathNotAbsolute, c.IndexPath) + } + if c.ChunkSize.Int64() < minChunkSize { return errChunkSizeTooSmall } @@ -381,6 +456,31 @@ func (c *Config) Validate() error { return errBadCompression } + if c.S3.PartSize.Int64() < minS3PartSize || + c.S3.PartSize.Int64() > maxS3PartSize { + return errBadS3PartSize + } + + if c.PruneGracePeriod < 0 { + return errNegativePruneGracePeriod + } + + return nil +} + +// validateSnapshots refuses a config with no snapshot or with a snapshot +// that has no path. +func (c *Config) validateSnapshots() error { + if len(c.Snapshots) == 0 { + return errNoSnapshots + } + + for name, snap := range c.Snapshots { + if len(snap.Paths) == 0 { + return fmt.Errorf("%w: %q", errSnapshotNoPaths, name) + } + } + return nil } @@ -416,6 +516,18 @@ func (c *Config) setAgeSecretKey() { } } +// readableByOthersWarning is the warning Load logs when others can read +// the config file. It says "may contain" because the S3 credentials are +// seen only after smartconfig has replaced any ${...} reference in the +// file with its value, so a set credential need not be in the file. +func (c *Config) readableByOthersWarning() string { + if c.S3.AccessKeyID != "" || c.S3.SecretAccessKey != "" { + return "Config file is readable by others and may contain S3 credentials" + } + + return "Config file is readable by others" +} + // validateStorage validates storage configuration. // If StorageURL is set, it takes precedence. S3 URLs require credentials. // File URLs don't require any S3 configuration. @@ -435,11 +547,11 @@ func (c *Config) validateStorage() error { } if c.S3.AccessKeyID == "" { - return errS3KeyIDRequired + return ErrS3KeyIDRequired } if c.S3.SecretAccessKey == "" { - return errS3SecretRequired + return ErrS3SecretRequired } return nil @@ -447,11 +559,18 @@ func (c *Config) validateStorage() error { // validateStorageURL validates URL-based storage configuration. File and // rclone URLs need no credentials; S3 URLs require the legacy s3.* -// credential fields. +// credential fields. A file URL must name an absolute path: a relative one +// would resolve against the working directory, so the destination would +// move with it. func (c *Config) validateStorageURL() error { switch { case strings.HasPrefix(c.StorageURL, "file://"): - // File storage doesn't need S3 credentials + // storage.ParseStorageURL applies the same rule, but config + // cannot import storage, which imports config. + if !strings.HasPrefix(c.StorageURL, "file:///") { + return errFileURLNotAbsolute + } + return nil case strings.HasPrefix(c.StorageURL, "rclone://"): // Rclone storage uses rclone's own config @@ -459,11 +578,11 @@ func (c *Config) validateStorageURL() error { case strings.HasPrefix(c.StorageURL, "s3://"): // S3 storage needs credentials if c.S3.AccessKeyID == "" { - return fmt.Errorf("%w for s3:// URLs", errS3KeyIDRequired) + return fmt.Errorf("%w for s3:// URLs", ErrS3KeyIDRequired) } if c.S3.SecretAccessKey == "" { - return fmt.Errorf("%w for s3:// URLs", errS3SecretRequired) + return fmt.Errorf("%w for s3:// URLs", ErrS3SecretRequired) } return nil diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 44e9fe6..186ea5a 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -6,8 +6,10 @@ import ( "path/filepath" "strings" "testing" + "time" "sneak.berlin/go/vaultik/internal/chunker" + "sneak.berlin/go/vaultik/internal/log" ) const ( @@ -88,12 +90,12 @@ func TestConfigLoad(t *testing.T) { } // TestExampleConfigIsScrubbedAndLoads checks that the shipped -// config.example.yml carries only neutral placeholders (no real credentials, -// private addresses, or internal host names) and still parses. +// configs/config.example.yml carries only neutral placeholders (no real +// credentials, private addresses, or internal host names) and still parses. func TestExampleConfigIsScrubbedAndLoads(t *testing.T) { t.Parallel() - examplePath := filepath.Join("..", "..", "config.example.yml") + examplePath := filepath.Join("..", "..", "configs", "config.example.yml") cfg, err := Load(examplePath) if err != nil { @@ -163,9 +165,11 @@ func TestValidateBlobSizeLimit(t *testing.T) { AgeRecipients: []string{testSneakAgePublicKey}, Snapshots: map[string]SnapshotConfig{"test": {Paths: []string{"/tmp/src"}}}, StorageURL: "file:///tmp/vaultik-test-store", + IndexPath: "/tmp/vaultik-test-index.sqlite", ChunkSize: chunkSize, BlobSizeLimit: blobLimit, CompressionLevel: 3, + S3: S3Config{PartSize: defaultS3PartSize}, } } @@ -221,9 +225,355 @@ func TestValidateBlobSizeLimit(t *testing.T) { } } +// TestValidateS3PartSize checks that s3.part_size is held to the part sizes +// S3 accepts, 5MiB to 5GiB, by changing only the part size of the test +// config. "5MB" in the config file is 5,000,000 bytes, below the minimum. +func TestValidateS3PartSize(t *testing.T) { + t.Parallel() + + base, err := Load(os.Getenv("VAULTIK_CONFIG")) + if err != nil { + t.Fatalf("Failed to load config: %v", err) + } + + tests := []struct { + name string + partSize Size + wantErr bool + }{ + { + name: "5MB is rejected", + partSize: 5_000_000, + wantErr: true, + }, + { + name: "one byte below 5MiB is rejected", + partSize: minS3PartSize - 1, + wantErr: true, + }, + { + name: "5MiB is accepted", + partSize: minS3PartSize, + wantErr: false, + }, + { + name: "5GiB is accepted", + partSize: maxS3PartSize, + wantErr: false, + }, + { + name: "one byte above 5GiB is rejected", + partSize: maxS3PartSize + 1, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + cfg := *base + cfg.S3.PartSize = tt.partSize + + err := cfg.Validate() + if tt.wantErr { + if !errors.Is(err, errBadS3PartSize) { + t.Fatalf("Validate() error = %v, want errBadS3PartSize", err) + } + + return + } + + if err != nil { + t.Fatalf("Validate() unexpected error: %v", err) + } + }) + } +} + +// TestLoadS3PartSize checks that a config file without s3.part_size loads +// with the 5MiB default, and that an explicit 0 fails at load like any other +// part size S3 refuses. +func TestLoadS3PartSize(t *testing.T) { + t.Parallel() + + const withoutPartSize = "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file:///tmp/vaultik-test-storage\n" + + writeConfig := func(t *testing.T, text string) string { + t.Helper() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(text), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) + } + + return path + } + + t.Run("absent loads as 5MiB", func(t *testing.T) { + t.Parallel() + + cfg, err := Load(writeConfig(t, withoutPartSize)) + if err != nil { + t.Fatalf("Load() unexpected error: %v", err) + } + + if cfg.S3.PartSize != defaultS3PartSize { + t.Errorf("s3.part_size = %d, want %d", + cfg.S3.PartSize, defaultS3PartSize) + } + }) + + t.Run("0 is rejected", func(t *testing.T) { + t.Parallel() + + _, err := Load(writeConfig(t, withoutPartSize+"s3:\n part_size: 0\n")) + if !errors.Is(err, errBadS3PartSize) { + t.Fatalf("Load() error = %v, want errBadS3PartSize", err) + } + }) +} + +// TestDocumentedSizeDefaults checks that the defaults are the documented +// chunk_size 10MB and blob_size_limit 10GB as the parser reads those values +// (1000-based), so writing a default out in the config file changes nothing. +func TestDocumentedSizeDefaults(t *testing.T) { + t.Parallel() + + cfg, err := Parse([]byte("chunk_size: 10MB\nblob_size_limit: 10GB\n")) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } + + if cfg.ChunkSize != defaultChunkSize { + t.Errorf("chunk_size: 10MB is %d bytes, the default is %d", + cfg.ChunkSize, defaultChunkSize) + } + + if cfg.BlobSizeLimit != defaultBlobSizeLimit { + t.Errorf("blob_size_limit: 10GB is %d bytes, the default is %d", + cfg.BlobSizeLimit, defaultBlobSizeLimit) + } +} + +// TestDocumentedSizeExamples checks the 1MB minimum chunk_size and that +// every size the README, configs/config.example.yml and the config init template +// list as an example is accepted. +func TestDocumentedSizeExamples(t *testing.T) { + t.Parallel() + + const withoutSizes = "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file:///tmp/vaultik-test-storage\n" + + tests := []struct { + setting string + wantErr error + }{ + {"chunk_size: 1MB", nil}, + {"chunk_size: 999999", errChunkSizeTooSmall}, + {"chunk_size: 5M", nil}, + {"chunk_size: 10M", nil}, + {"chunk_size: 10MB", nil}, + {"chunk_size: 64MiB", nil}, + {"chunk_size: 1GB", nil}, + // Four times the default chunk_size, the documented minimum. + {"blob_size_limit: 40MB", nil}, + {"blob_size_limit: 500MB", nil}, + {"blob_size_limit: 1GB", nil}, + {"blob_size_limit: 1GiB", nil}, + {"blob_size_limit: 10G", nil}, + {"blob_size_limit: 10GB", nil}, + {"s3: {part_size: 5MiB}", nil}, + {"s3: {part_size: 10MB}", nil}, + {"s3: {part_size: 16MiB}", nil}, + {"s3: {part_size: 100MiB}", nil}, + {"s3: {part_size: 5GiB}", nil}, + } + + for _, tt := range tests { + t.Run(tt.setting, func(t *testing.T) { + t.Parallel() + + cfg, err := Parse([]byte(withoutSizes + tt.setting + "\n")) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } + + err = cfg.Validate() + if !errors.Is(err, tt.wantErr) { + t.Fatalf("Validate() error = %v, want %v", err, tt.wantErr) + } + }) + } +} + +// TestValidatePruneGracePeriod checks that a negative prune_grace_period +// is refused rather than acting like 0s, which deletes unreferenced blobs +// and directories under metadata/ with no manifest at once, and that 0s +// and the documented examples are accepted. +func TestValidatePruneGracePeriod(t *testing.T) { + t.Parallel() + + const withoutGracePeriod = "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file:///tmp/vaultik-test-storage\n" + + tests := []struct { + setting string + wantErr error + }{ + {"prune_grace_period: 0s", nil}, + {"prune_grace_period: 90m", nil}, + {"prune_grace_period: 36h", nil}, + {"prune_grace_period: -1h", errNegativePruneGracePeriod}, + } + + for _, tt := range tests { + t.Run(tt.setting, func(t *testing.T) { + t.Parallel() + + cfg, err := Parse([]byte(withoutGracePeriod + tt.setting + "\n")) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } + + err = cfg.Validate() + if !errors.Is(err, tt.wantErr) { + t.Fatalf("Validate() error = %v, want %v", err, tt.wantErr) + } + }) + } +} + +// TestLoadPruneGracePeriod checks that a config file without +// prune_grace_period loads with the documented 24h. The value is written out +// here rather than taken from defaultPruneGracePeriod, so that a change of the +// default fails this test. +func TestLoadPruneGracePeriod(t *testing.T) { + t.Parallel() + + const withoutGracePeriod = "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file:///tmp/vaultik-test-storage\n" + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(withoutGracePeriod), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) + } + + cfg, err := Load(path) + if err != nil { + t.Fatalf("Load() unexpected error: %v", err) + } + + if cfg.PruneGracePeriod != 24*time.Hour { + t.Errorf("prune_grace_period = %s, want 24h", cfg.PruneGracePeriod) + } +} + +// TestLoadRejectsRelativeFileURL checks that a file:// storage_url with a +// relative path fails at load. Accepted, it would resolve against the +// working directory, so a backup run from another directory would write +// to a different destination and still succeed. +func TestLoadRejectsRelativeFileURL(t *testing.T) { + t.Parallel() + + const relativeConfig = "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file://dest\n" + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(relativeConfig), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) + } + + _, err = Load(path) + if !errors.Is(err, errFileURLNotAbsolute) { + t.Fatalf("Load() error = %v, want errFileURLNotAbsolute", err) + } + + if !strings.Contains(err.Error(), "absolute path") { + t.Errorf("error %q does not say to use an absolute path", err.Error()) + } +} + +// TestLoadIndexPath checks that a relative index_path fails at load, naming +// the value. Accepted, it would resolve against the working directory, so a +// backup run from another directory would start from an empty index. A path +// starting with ~ is expanded and loads. +func TestLoadIndexPath(t *testing.T) { + t.Parallel() + + home, err := os.UserHomeDir() + if err != nil { + t.Fatalf("home directory: %v", err) + } + + load := func(t *testing.T, indexPath string) (*Config, error) { + t.Helper() + + data := "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + "storage_url: file:///tmp/vaultik-test-storage\n" + + "index_path: " + indexPath + "\n" + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(data), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) + } + + return Load(path) + } + + t.Run("relative path is rejected", func(t *testing.T) { + t.Parallel() + + _, err := load(t, "relative/index.sqlite") + if !errors.Is(err, errIndexPathNotAbsolute) { + t.Fatalf("Load() error = %v, want errIndexPathNotAbsolute", err) + } + + if !strings.Contains(err.Error(), `"relative/index.sqlite"`) { + t.Errorf("error %q does not name the value", err.Error()) + } + }) + + t.Run("path starting with ~ is expanded", func(t *testing.T) { + t.Parallel() + + cfg, err := load(t, "~/vaultik/index.sqlite") + if err != nil { + t.Fatalf("Load() unexpected error: %v", err) + } + + want := filepath.Join(home, "vaultik", "index.sqlite") + if cfg.IndexPath != want { + t.Errorf("IndexPath = %q, want %q", cfg.IndexPath, want) + } + }) +} + // TestValidateAgeRecipients checks that recipients are parsed at config load // (a bad entry fails immediately, not mid-backup) and that no invalid entry — -// least of all a pasted secret key — is echoed in the error. +// least of all a pasted secret key — is echoed in the error. An empty list +// loads, because only snapshot create needs a recipient. func TestValidateAgeRecipients(t *testing.T) { t.Parallel() @@ -232,9 +582,11 @@ func TestValidateAgeRecipients(t *testing.T) { AgeRecipients: recipients, Snapshots: map[string]SnapshotConfig{"test": {Paths: []string{"/tmp/src"}}}, StorageURL: "file:///tmp/vaultik-test-store", + IndexPath: "/tmp/vaultik-test-index.sqlite", ChunkSize: Size(10 * 1024 * 1024), BlobSizeLimit: Size(10 * 1024 * 1024 * 1024), CompressionLevel: 3, + S3: S3Config{PartSize: defaultS3PartSize}, } } @@ -244,7 +596,12 @@ func TestValidateAgeRecipients(t *testing.T) { wantErr bool }{ { - name: "config init placeholder is rejected", + name: "no recipients is accepted", + recipients: nil, + wantErr: false, + }, + { + name: "placeholder recipient is rejected", recipients: []string{"age1REPLACE_WITH_YOUR_PUBLIC_KEY"}, wantErr: true, }, @@ -337,3 +694,125 @@ func TestAgeSecretKeySourceName(t *testing.T) { }) } } + +// loadReadableConfig writes configYAML to a file that others can read, +// loads it, and returns what the logger wrote to stderr meanwhile. The +// logger writes to the os.Stderr it finds when it is initialized, so +// os.Stderr is pointed at a file first. Not parallel-safe: os.Stderr and +// the logger are process-global. +func loadReadableConfig(t *testing.T, configYAML string) string { + t.Helper() + + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yml") + stderrPath := filepath.Join(dir, "stderr") + + err := os.WriteFile(configPath, []byte(configYAML), 0o600) + if err != nil { + t.Fatalf("writing config: %v", err) + } + + //nolint:gosec // G302: the test needs a config file others can read + err = os.Chmod(configPath, 0o644) + if err != nil { + t.Fatalf("chmod config: %v", err) + } + + stderrFile, err := os.Create(stderrPath) //nolint:gosec // G304: test temp path + if err != nil { + t.Fatalf("creating stderr file: %v", err) + } + + previous := os.Stderr + os.Stderr = stderrFile + + log.Initialize(log.Config{}) + + _, loadErr := Load(configPath) + + os.Stderr = previous + + log.Initialize(log.Config{}) + + _ = stderrFile.Close() + + if loadErr != nil { + t.Fatalf("Load() error = %v", loadErr) + } + + captured, err := os.ReadFile(stderrPath) //nolint:gosec // G304: test temp path + if err != nil { + t.Fatalf("reading stderr file: %v", err) + } + + return string(captured) +} + +// TestLoadWarnsReadableConfigWithoutS3Credentials checks that a config +// file others can read, holding no S3 credentials, is warned about +// without a claim that it holds them. +// +//nolint:paralleltest // loadReadableConfig replaces os.Stderr +func TestLoadWarnsReadableConfigWithoutS3Credentials(t *testing.T) { + stderr := loadReadableConfig(t, ` +storage_url: file:///var/backups/vaultik +snapshots: + home: + paths: + - /home +`) + + if !strings.Contains(stderr, "Config file is readable by others") { + t.Errorf("expected a warning that the file is readable by others, got %q", + stderr) + } + + if strings.Contains(stderr, "S3 credentials") { + t.Errorf("warning names S3 credentials the file does not set: %q", stderr) + } +} + +// TestLoadWarnsReadableConfigWithS3Credentials checks that a config file +// others can read and that sets S3 credentials, as values or as ${ENV:...} +// references, is warned about as one that may contain them. +// +//nolint:paralleltest // loadReadableConfig replaces os.Stderr +func TestLoadWarnsReadableConfigWithS3Credentials(t *testing.T) { + t.Setenv("VAULTIK_TEST_ACCESS_KEY_ID", "test-access-key") + t.Setenv("VAULTIK_TEST_SECRET_ACCESS_KEY", "test-secret-key") + + configs := map[string]string{ + "values": ` +storage_url: s3://bucket/prefix?endpoint=s3.example.com +s3: + access_key_id: test-access-key + secret_access_key: test-secret-key +snapshots: + home: + paths: + - /home +`, + "references": ` +storage_url: s3://bucket/prefix?endpoint=s3.example.com +s3: + access_key_id: ${ENV:VAULTIK_TEST_ACCESS_KEY_ID} + secret_access_key: ${ENV:VAULTIK_TEST_SECRET_ACCESS_KEY} +snapshots: + home: + paths: + - /home +`, + } + + for name, configYAML := range configs { + t.Run(name, func(t *testing.T) { + stderr := loadReadableConfig(t, configYAML) + + if !strings.Contains(stderr, + "Config file is readable by others and may contain S3 credentials") { + t.Errorf("expected a warning naming the S3 credentials, got %q", + stderr) + } + }) + } +} diff --git a/internal/config/exclude.go b/internal/config/exclude.go new file mode 100644 index 0000000..d2271b3 --- /dev/null +++ b/internal/config/exclude.go @@ -0,0 +1,39 @@ +package config + +import ( + "fmt" + + "sneak.berlin/go/vaultik/internal/exclude" +) + +// validateExcludes refuses an exclude pattern, global or in a snapshot, +// that does not compile, naming the setting and quoting the pattern. +func (c *Config) validateExcludes() error { + err := validateExcludeList("exclude", c.Exclude) + if err != nil { + return err + } + + for _, name := range c.SnapshotNames() { + err = validateExcludeList("snapshots."+name+".exclude", + c.Snapshots[name].Exclude) + if err != nil { + return err + } + } + + return nil +} + +// validateExcludeList refuses the first pattern in patterns that does not +// compile. setting is the name of the list, as in "exclude". +func validateExcludeList(setting string, patterns []string) error { + for i, pattern := range patterns { + _, _, err := exclude.Compile(pattern) + if err != nil { + return fmt.Errorf("%s[%d]: %w", setting, i, err) + } + } + + return nil +} diff --git a/internal/config/exclude_test.go b/internal/config/exclude_test.go new file mode 100644 index 0000000..8a3e0d4 --- /dev/null +++ b/internal/config/exclude_test.go @@ -0,0 +1,65 @@ +package config_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "sneak.berlin/go/vaultik/internal/config" +) + +// TestLoadRefusesBadExcludePattern checks that an exclude pattern that does +// not compile, global or in a snapshot, fails at load with the setting and +// the pattern named, rather than the backup storing what it meant to leave +// out. +func TestLoadRefusesBadExcludePattern(t *testing.T) { + t.Parallel() + + const storage = "storage_url: file:///tmp/vaultik-test-storage\n" + + tests := []struct { + name string + config string + wantErr string + }{ + { + name: "global", + config: "exclude: ['*.tmp', '.cache', 'build[']\n" + + "snapshots:\n" + + " home:\n" + + " paths: [/tmp/vaultik-test-source]\n" + storage, + wantErr: `exclude[2]: "build[" is not a valid exclude pattern`, + }, + { + name: "snapshot", + config: "snapshots:\n" + + " home:\n" + + " paths: [/tmp/vaultik-test-source]\n" + + " exclude: ['/a/**/x[']\n" + storage, + wantErr: `snapshots.home.exclude[0]: "/a/**/x[" is not a valid exclude pattern`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + path := filepath.Join(t.TempDir(), "config.yml") + + err := os.WriteFile(path, []byte(tt.config), 0o600) + if err != nil { + t.Fatalf("write config: %v", err) + } + + _, err = config.Load(path) + if err == nil { + t.Fatalf("Load() returned nil, want an error containing %q", tt.wantErr) + } + + if !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("Load() error = %q, want it to contain %q", err, tt.wantErr) + } + }) + } +} diff --git a/internal/config/keys.go b/internal/config/keys.go new file mode 100644 index 0000000..b9ff171 --- /dev/null +++ b/internal/config/keys.go @@ -0,0 +1,220 @@ +package config + +import ( + "errors" + "fmt" + "reflect" + "strconv" + "strings" + + "gopkg.in/yaml.v3" +) + +// yamlMergeTag is the tag YAML gives a merge key (<<), which adds the keys +// of the map it names to the map it sits in. +const yamlMergeTag = "!!merge" + +// EnvSection is the top-level key of a map of environment variables that +// smartconfig sets while it loads the config. It is not a vaultik setting, +// so its keys are not checked. +const EnvSection = "env" + +var ( + errUnknownKey = errors.New("unknown config key") + errAnchorContainsItself = errors.New("anchor contains itself") +) + +// nodeAndType is a node of a parsed config and the setting type it is +// checked against. +type nodeAndType struct { + node *yaml.Node + typ reflect.Type +} + +// SettingType returns the type of the setting that the dotted key names in +// Config, following the fields' yaml tags, as for s3.bucket or +// snapshots.home.exclude.0. A snapshot name or a list index may be any +// word. It returns an unknown key error when no setting has that key. +func SettingType(keys []string) (reflect.Type, error) { + typ := reflect.TypeFor[Config]() + + for _, key := range keys { + switch { + case typ.Kind() == reflect.Map || typ.Kind() == reflect.Slice: + typ = typ.Elem() + case typ.Kind() == reflect.Struct: + field, ok := yamlField(typ, key) + if !ok { + return nil, fmt.Errorf("%w %q", errUnknownKey, strings.Join(keys, ".")) + } + + typ = field.Type + default: + return nil, fmt.Errorf("%w %q", errUnknownKey, strings.Join(keys, ".")) + } + } + + return typ, nil +} + +// yamlField returns the field of struct type typ whose yaml tag names key. +func yamlField(typ reflect.Type, key string) (reflect.StructField, bool) { + for field := range typ.Fields() { + name, _, _ := strings.Cut(field.Tag.Get("yaml"), ",") + if name == key && name != "-" { + return field, true + } + } + + return reflect.StructField{}, false +} + +// checkKeys returns an error naming the first key in node, a parsed config +// or part of one at the dotted path, that no setting in typ has. The error +// gives the key's line in the file, when it has one. A value of the wrong +// type is left for the YAML decoder to report. following holds the aliases +// the walk is inside. Meeting one of them again means its anchor contains +// itself, which is an error. checked holds each anchored node the walk has +// checked completely, with the type it was checked against. An alias to +// that node is not followed again for that type. +func checkKeys(node *yaml.Node, typ reflect.Type, path string, + following map[*yaml.Node]bool, checked map[nodeAndType]bool, +) error { + switch node.Kind { + case yaml.DocumentNode: + for _, child := range node.Content { + err := checkKeys(child, typ, path, following, checked) + if err != nil { + return err + } + } + case yaml.AliasNode: + if following[node] { + return fmt.Errorf("%w: %q on line %d", + errAnchorContainsItself, node.Value, node.Line) + } + + target := nodeAndType{node.Alias, typ} + if checked[target] { + return nil + } + + following[node] = true + defer delete(following, node) + + err := checkKeys(node.Alias, typ, path, following, checked) + if err != nil { + return err + } + + checked[target] = true + case yaml.SequenceNode: + if typ.Kind() != reflect.Slice { + return nil + } + + for i, child := range node.Content { + err := checkKeys(child, typ.Elem(), joinKey(path, strconv.Itoa(i)), + following, checked) + if err != nil { + return err + } + } + case yaml.MappingNode: + return checkMappingKeys(node, typ, path, following, checked) + case yaml.ScalarNode: + // A scalar has no keys. + } + + return nil +} + +// checkFilledConfig checks data, the config after smartconfig has filled in +// its ${...} references: its keys with checkKeys, then its size settings +// with checkSizes. A key that a reference brings in is not in the file, and +// the copy that Encode makes has no line numbers. +func checkFilledConfig(data map[string]any) error { + var filled yaml.Node + + err := filled.Encode(data) + if err != nil { + return fmt.Errorf("failed to marshal config data: %w", err) + } + + err = checkKeys(&filled, reflect.TypeFor[Config](), "", + map[*yaml.Node]bool{}, map[nodeAndType]bool{}) + if err != nil { + return err + } + + return checkSizes(&filled, nil) +} + +// checkMappingKeys is checkKeys for a map. +func checkMappingKeys(node *yaml.Node, typ reflect.Type, path string, + following map[*yaml.Node]bool, checked map[nodeAndType]bool, +) error { + for i := 0; i+1 < len(node.Content); i += 2 { + key, value := node.Content[i], node.Content[i+1] + + if key.Tag == yamlMergeTag { + // The value is one map or a list of maps. + merged := []*yaml.Node{value} + if value.Kind == yaml.SequenceNode { + merged = value.Content + } + + for _, m := range merged { + err := checkKeys(m, typ, path, following, checked) + if err != nil { + return err + } + } + + continue + } + + keyPath := joinKey(path, key.Value) + if keyPath == EnvSection { + continue + } + + var valueType reflect.Type + + switch { + case typ.Kind() == reflect.Map: + valueType = typ.Elem() + case typ.Kind() == reflect.Struct: + field, ok := yamlField(typ, key.Value) + if !ok && key.Line == 0 { + // A key that a ${...} reference brought in has no line. + return fmt.Errorf("%w %q", errUnknownKey, keyPath) + } + + if !ok { + return fmt.Errorf("%w %q on line %d", + errUnknownKey, keyPath, key.Line) + } + + valueType = field.Type + default: + return nil + } + + err := checkKeys(value, valueType, keyPath, following, checked) + if err != nil { + return err + } + } + + return nil +} + +// joinKey appends key to the dotted path. +func joinKey(path, key string) string { + if path == "" { + return key + } + + return path + "." + key +} diff --git a/internal/config/keys_test.go b/internal/config/keys_test.go new file mode 100644 index 0000000..f67e875 --- /dev/null +++ b/internal/config/keys_test.go @@ -0,0 +1,163 @@ +package config //nolint:testpackage // checks the unexported errUnknownKey + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" +) + +// keysTestConfig loads; each case below adds one line to it. +const keysTestConfig = "storage_url: file:///tmp/vaultik-test-storage\n" + + "s3:\n" + + " region: us-east-1\n" + + "snapshots:\n" + + " test:\n" + + " paths: [/tmp/vaultik-test-source]\n" + +// TestParseRefusesUnknownKey checks that a key no setting has, at any +// depth, fails the parse with an error naming the key and its line. A key +// that a ${...} reference brings in is not in the file, so its error gives +// no line. +func TestParseRefusesUnknownKey(t *testing.T) { + t.Parallel() + + snapshotPath := filepath.Join(t.TempDir(), "snapshot.yml") + + err := os.WriteFile(snapshotPath, []byte("other:\n"+ + " paths: [/tmp/vaultik-test-source]\n"+ + " exlude: [/tmp/cache]\n"), 0o600) + if err != nil { + t.Fatalf("write snapshot: %v", err) + } + + tests := []struct { + name string + yaml string + want string + }{ + {"top level", keysTestConfig + "compression_lvl: 9\n", + `unknown config key "compression_lvl" on line 7`}, + {"in a snapshot", keysTestConfig + " exlude: [/tmp/cache]\n", + `unknown config key "snapshots.test.exlude" on line 7`}, + {"in s3", strings.Replace(keysTestConfig, " region:", + " bukcet: b\n region:", 1), + `unknown config key "s3.bukcet" on line 3`}, + {"from a reference", + keysTestConfig + " other: ${YAML:" + snapshotPath + ":other}\n", + `unknown config key "snapshots.other.exlude"`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + _, err := Parse([]byte(tt.yaml)) + if !errors.Is(err, errUnknownKey) { + t.Fatalf("Parse() error = %v, want errUnknownKey", err) + } + + if err.Error() != tt.want { + t.Errorf("Parse() error = %q, want %q", err.Error(), tt.want) + } + }) + } +} + +// TestParseRefusesAnchorThatContainsItself checks that a YAML merge key (<<) +// naming the anchor of the map it sits in fails the parse with an error. +func TestParseRefusesAnchorThatContainsItself(t *testing.T) { + t.Parallel() + + data := strings.Replace(keysTestConfig, " test:", " test: &test", 1) + + " <<: *test\n" + + _, err := Parse([]byte(data)) + if !errors.Is(err, errAnchorContainsItself) { + t.Fatalf("Parse() error = %v, want errAnchorContainsItself", err) + } + + want := `anchor contains itself: "test" on line 7` + if err.Error() != want { + t.Errorf("Parse() error = %q, want %q", err.Error(), want) + } +} + +// TestParseRefusesExcessiveAliasing checks that Parse returns an error for +// a file whose merge keys (<<) fan out. Each of eight snapshots merges the +// one before it ten times. A key check that followed every alias would walk +// the first snapshot over 10^8 times and run past the package's test +// timeout. +func TestParseRefusesExcessiveAliasing(t *testing.T) { + t.Parallel() + + const snapshots, merges = 8, 10 + + var data strings.Builder + + data.WriteString(strings.Replace(keysTestConfig, " test:", " test: &s0", 1)) + + for i := 1; i <= snapshots; i++ { + aliases := slices.Repeat([]string{"*s" + strconv.Itoa(i-1)}, merges) + fmt.Fprintf(&data, " s%d: &s%d\n <<: [%s]\n", + i, i, strings.Join(aliases, ", ")) + } + + _, err := Parse([]byte(data.String())) + if err == nil { + t.Fatal("Parse() returned no error") + } +} + +// TestParseAcceptsKnownKeys checks that a config with a ${...} reference +// and a YAML merge key (<<) still parses. +func TestParseAcceptsKnownKeys(t *testing.T) { + t.Parallel() + + levelPath := filepath.Join(t.TempDir(), "level") + + err := os.WriteFile(levelPath, []byte("9"), 0o600) + if err != nil { + t.Fatalf("write level: %v", err) + } + + data := strings.Replace(keysTestConfig, " test:", " test: &test", 1) + + " other:\n" + + " <<: *test\n" + + " exclude: [/tmp/vaultik-test-source/cache]\n" + + "compression_level: ${FILE:" + levelPath + "}\n" + + cfg, err := Parse([]byte(data)) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } + + if cfg.CompressionLevel != 9 { + t.Errorf("compression_level = %d, want 9", cfg.CompressionLevel) + } + + other := cfg.Snapshots["other"] + if len(other.Paths) != 1 || len(other.Exclude) != 1 { + t.Errorf("snapshot other = %+v, want the paths of test and one exclude", + other) + } +} + +// TestParseAcceptsEnvSection checks that a config with a top-level env +// section still parses. smartconfig sets the environment variables it +// lists, so its keys are not settings. +func TestParseAcceptsEnvSection(t *testing.T) { + const name = "VAULTIK_TEST_ENV_SECTION" + + // Parse sets the variable; t.Setenv restores it after the test. + t.Setenv(name, "") + + _, err := Parse([]byte(keysTestConfig + "env:\n " + name + ": set\n")) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } +} diff --git a/internal/config/size.go b/internal/config/size.go index 8f21a87..12cc5b0 100644 --- a/internal/config/size.go +++ b/internal/config/size.go @@ -4,20 +4,25 @@ import ( "errors" "fmt" "math" + "reflect" + "slices" + "strconv" + "strings" "github.com/dustin/go-humanize" + "gopkg.in/yaml.v3" ) var ( errSizeType = errors.New("size must be a number or string") errSizeTooLarge = errors.New("size exceeds maximum supported value") + errNotASize = errors.New( + "is not a size; use a number of bytes or a unit such as 10MB") ) // Size represents a byte size that can be specified in configuration files. // It can unmarshal from both numeric values (interpreted as bytes) and // human-readable strings like "10MB", "2.5GB", or "1TB". -// -//nolint:recvcheck // UnmarshalYAML requires a pointer; String/Int64 are value reads type Size int64 // UnmarshalYAML implements yaml.Unmarshaler for Size, allowing it to be @@ -34,6 +39,15 @@ func (s *Size) UnmarshalYAML(unmarshal func(any) error) error { return nil } + // A number too large for an int64 decodes as a float64. Its text can be + // 1e+20, which is not a size string. + var floatVal float64 + + err = unmarshal(&floatVal) + if err == nil && floatVal > math.MaxInt64 { + return errSizeTooLarge + } + // Try to unmarshal as string var strVal string @@ -42,17 +56,66 @@ func (s *Size) UnmarshalYAML(unmarshal func(any) error) error { return errSizeType } - // Parse the string using go-humanize - bytes, err := humanize.ParseBytes(strVal) + size, err := ParseSize(strVal) if err != nil { - return fmt.Errorf("invalid size format: %w", err) + return err } - if bytes > math.MaxInt64 { - return fmt.Errorf("%w: %s", errSizeTooLarge, strVal) + *s = size + + return nil +} + +// checkSizes returns an error naming the first size setting in node whose +// value is not a size. node is the config, or the part of it at the dotted +// keys, after smartconfig has filled in its ${...} references. +func checkSizes(node *yaml.Node, keys []string) error { + typ, err := SettingType(keys) + if err != nil { + // Unknown keys are refused before this check, so keys is in one of + // two places. The env section holds no settings. A value of the + // wrong shape, such as a map given for hostname or inside exclude, + // is reported later by the YAML decoder. + return nil //nolint:nilerr // not an error here } - *s = Size(bytes) + if typ == reflect.TypeFor[Size]() { + var size Size + + err = node.Decode(&size) + if err != nil { + return fmt.Errorf("%s: %w", strings.Join(keys, "."), err) + } + + return nil + } + + switch node.Kind { + case yaml.DocumentNode: + for _, child := range node.Content { + err = checkSizes(child, keys) + if err != nil { + return err + } + } + case yaml.MappingNode: + for i := 0; i+1 < len(node.Content); i += 2 { + err = checkSizes(node.Content[i+1], + slices.Concat(keys, []string{node.Content[i].Value})) + if err != nil { + return err + } + } + case yaml.SequenceNode: + for i, child := range node.Content { + err = checkSizes(child, slices.Concat(keys, []string{strconv.Itoa(i)})) + if err != nil { + return err + } + } + case yaml.ScalarNode, yaml.AliasNode: + // A scalar holds no settings, and the filled config has no aliases. + } return nil } @@ -72,16 +135,17 @@ func (s Size) String() string { return humanize.Bytes(uint64(s)) } -// ParseSize parses a size string into a Size value +// ParseSize parses a size string, such as "10MB", into a Size value. An +// error quotes s. func ParseSize(s string) (Size, error) { - bytes, err := humanize.ParseBytes(s) + bytes, err := humanize.ParseBigBytes(s) if err != nil { - return 0, fmt.Errorf("invalid size format: %w", err) + return 0, fmt.Errorf("%q %w", s, errNotASize) } - if bytes > math.MaxInt64 { + if !bytes.IsInt64() { return 0, fmt.Errorf("%w: %s", errSizeTooLarge, s) } - return Size(bytes), nil + return Size(bytes.Int64()), nil } diff --git a/internal/config/size_test.go b/internal/config/size_test.go new file mode 100644 index 0000000..5265ed4 --- /dev/null +++ b/internal/config/size_test.go @@ -0,0 +1,120 @@ +package config //nolint:testpackage // checks errNotASize and errSizeTooLarge + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// TestParseRefusesValueThatIsNotASize checks that a size setting whose +// value is not a size fails the parse with an error naming the setting and +// quoting the value, also when a ${...} reference fills the value in. +func TestParseRefusesValueThatIsNotASize(t *testing.T) { + t.Parallel() + + sizePath := filepath.Join(t.TempDir(), "size") + + err := os.WriteFile(sizePath, []byte("lots"), 0o600) + if err != nil { + t.Fatalf("write size: %v", err) + } + + tests := []struct { + name string + yaml string + want string + }{ + {"chunk_size", keysTestConfig + "chunk_size: banana\n", + `chunk_size: "banana" is not a size; ` + + "use a number of bytes or a unit such as 10MB"}, + {"blob_size_limit", keysTestConfig + "blob_size_limit: 10XB\n", + `blob_size_limit: "10XB" is not a size; ` + + "use a number of bytes or a unit such as 10MB"}, + {"s3.part_size", strings.Replace(keysTestConfig, " region:", + " part_size: big\n region:", 1), + `s3.part_size: "big" is not a size; ` + + "use a number of bytes or a unit such as 10MB"}, + {"from a reference", + keysTestConfig + "chunk_size: ${FILE:" + sizePath + "}\n", + `chunk_size: "lots" is not a size; ` + + "use a number of bytes or a unit such as 10MB"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + _, err := Parse([]byte(tt.yaml)) + if !errors.Is(err, errNotASize) { + t.Fatalf("Parse() error = %v, want errNotASize", err) + } + + if err.Error() != tt.want { + t.Errorf("Parse() error = %q, want %q", err.Error(), tt.want) + } + }) + } +} + +// TestParseRefusesSizeTooLarge checks that a size setting whose value is +// too large for a size fails the parse with an error naming the setting. +// YAML reads the second value as a float. +func TestParseRefusesSizeTooLarge(t *testing.T) { + t.Parallel() + + tests := []struct { + value string + want string + }{ + {"100EB", "chunk_size: size exceeds maximum supported value: 100EB"}, + {"99999999999999999999", + "chunk_size: size exceeds maximum supported value"}, + } + + for _, tt := range tests { + t.Run(tt.value, func(t *testing.T) { + t.Parallel() + + _, err := Parse([]byte(keysTestConfig + "chunk_size: " + tt.value + "\n")) + if !errors.Is(err, errSizeTooLarge) { + t.Fatalf("Parse() error = %v, want errSizeTooLarge", err) + } + + if err.Error() != tt.want { + t.Errorf("Parse() error = %q, want %q", err.Error(), tt.want) + } + }) + } +} + +// TestParseAcceptsSizes checks that size settings given as a number of +// bytes, as a unit, and through a ${...} reference still parse. +func TestParseAcceptsSizes(t *testing.T) { + t.Parallel() + + sizePath := filepath.Join(t.TempDir(), "size") + + err := os.WriteFile(sizePath, []byte("20MB"), 0o600) + if err != nil { + t.Fatalf("write size: %v", err) + } + + data := strings.Replace(keysTestConfig, " region:", + " part_size: 6000000\n region:", 1) + + "chunk_size: ${FILE:" + sizePath + "}\n" + + "blob_size_limit: 1GB\n" + + cfg, err := Parse([]byte(data)) + if err != nil { + t.Fatalf("Parse() unexpected error: %v", err) + } + + if cfg.ChunkSize != 20_000_000 || cfg.BlobSizeLimit != 1_000_000_000 || + cfg.S3.PartSize != 6_000_000 { + t.Errorf("chunk_size, blob_size_limit, s3.part_size = %d, %d, %d, "+ + "want 20000000, 1000000000, 6000000", + cfg.ChunkSize, cfg.BlobSizeLimit, cfg.S3.PartSize) + } +} diff --git a/internal/database/blob_chunks.go b/internal/database/blob_chunks.go index 64d99b0..1907323 100644 --- a/internal/database/blob_chunks.go +++ b/internal/database/blob_chunks.go @@ -58,12 +58,7 @@ func (r *BlobChunkRepository) GetByBlobID( return nil, fmt.Errorf("querying blob chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var blobChunks []*BlobChunk diff --git a/internal/database/blobs.go b/internal/database/blobs.go index dc85785..aec4dca 100644 --- a/internal/database/blobs.go +++ b/internal/database/blobs.go @@ -83,12 +83,7 @@ func (r *BlobRepository) GetAll(ctx context.Context) (map[string]*Blob, error) { return nil, fmt.Errorf("querying blobs: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() out := make(map[string]*Blob) @@ -159,13 +154,16 @@ func (r *BlobRepository) UpdateFinished( return nil } -// UpdateUploaded marks a blob as uploaded +// UpdateUploaded marks a blob as uploaded and records the size of the +// stored object as its compressed size. That size can differ from the +// local copy's when an identical blob was already stored with another +// compression level or other recipients. func (r *BlobRepository) UpdateUploaded( - ctx context.Context, tx *sql.Tx, id string, + ctx context.Context, tx *sql.Tx, id string, storedSize int64, ) error { query := ` - UPDATE blobs - SET uploaded_ts = ? + UPDATE blobs + SET uploaded_ts = ?, compressed_size = ? WHERE id = ? ` @@ -173,9 +171,9 @@ func (r *BlobRepository) UpdateUploaded( var err error if tx != nil { - _, err = tx.ExecContext(ctx, query, now, id) + _, err = tx.ExecContext(ctx, query, now, storedSize, id) } else { - _, err = r.db.ExecWithLog(ctx, query, now, id) + _, err = r.db.ExecWithLog(ctx, query, now, storedSize, id) } if err != nil { diff --git a/internal/database/blobs_test.go b/internal/database/blobs_test.go index 457b0db..3caf57a 100644 --- a/internal/database/blobs_test.go +++ b/internal/database/blobs_test.go @@ -122,8 +122,8 @@ func TestBlobRepositoryUpdates(t *testing.T) { t.Errorf("expected compressed size 500, got %d", updated.CompressedSize) } - // Test UpdateUploaded - err = repo.UpdateUploaded(ctx, nil, blob.ID.String()) + // Test UpdateUploaded, with a stored object larger than the local copy + err = repo.UpdateUploaded(ctx, nil, blob.ID.String(), 600) if err != nil { t.Fatalf("failed to update blob as uploaded: %v", err) } @@ -141,6 +141,10 @@ func TestBlobRepositoryUpdates(t *testing.T) { if uploaded.UploadedTS.Before(now.Add(-1 * time.Second)) { t.Error("uploaded timestamp should be around test time") } + + if uploaded.CompressedSize != 600 { + t.Errorf("expected the stored size 600, got %d", uploaded.CompressedSize) + } } func TestBlobRepositoryDuplicate(t *testing.T) { diff --git a/internal/database/chunk_files.go b/internal/database/chunk_files.go index 308af59..b384d7f 100644 --- a/internal/database/chunk_files.go +++ b/internal/database/chunk_files.go @@ -61,12 +61,7 @@ func (r *ChunkFileRepository) GetByChunkHash( return nil, fmt.Errorf("querying chunk files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanChunkFiles(rows) } @@ -87,12 +82,7 @@ func (r *ChunkFileRepository) GetByFilePath( return nil, fmt.Errorf("querying chunk files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanChunkFiles(rows) } @@ -112,12 +102,7 @@ func (r *ChunkFileRepository) GetByFileID( return nil, fmt.Errorf("querying chunk files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanChunkFiles(rows) } @@ -220,7 +205,7 @@ func (r *ChunkFileRepository) CreateBatch( cf.ChunkHash.String(), cf.FileID.String(), cf.FileOffset, cf.Length) } - query += querySb183.String() //nolint:gosec // G202: appends "?" placeholders only + query += querySb183.String() query += " ON CONFLICT(chunk_hash, file_id) DO NOTHING" diff --git a/internal/database/chunks.go b/internal/database/chunks.go index 833c1aa..c21475a 100644 --- a/internal/database/chunks.go +++ b/internal/database/chunks.go @@ -98,7 +98,7 @@ func (r *ChunkRepository) GetByHashes( args[i] = hash } - query += querySb75.String() //nolint:gosec // G202: appends "?" placeholders only + query += querySb75.String() query += ") ORDER BY chunk_hash" @@ -107,12 +107,7 @@ func (r *ChunkRepository) GetByHashes( return nil, fmt.Errorf("querying chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var chunks []*Chunk @@ -152,12 +147,7 @@ func (r *ChunkRepository) ListUnpacked( return nil, fmt.Errorf("querying unpacked chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var chunks []*Chunk diff --git a/internal/database/chunks_ext.go b/internal/database/chunks_ext.go index 0fc9e0a..5e78c5b 100644 --- a/internal/database/chunks_ext.go +++ b/internal/database/chunks_ext.go @@ -38,12 +38,7 @@ func (r *ChunkRepository) list(ctx context.Context, query string) ([]*Chunk, err return nil, fmt.Errorf("querying chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var chunks []*Chunk diff --git a/internal/database/database.go b/internal/database/database.go index b41945b..8f0ee05 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -42,6 +42,10 @@ var schemaFS embed.FS // table itself. It is applied before the normal migration loop. const bootstrapVersion = 0 +// busyTimeoutMs is how long a connection to the index waits for another +// connection's lock before failing with "database is locked". +const busyTimeoutMs = 10000 + // DB represents the Vaultik local index database connection. // It uses SQLite to track file metadata, content-defined chunks, and blob associations. // The database enables incremental backups by detecting changed files and @@ -94,10 +98,27 @@ func ParseMigrationVersion(filename string) (int, error) { return version, nil } +// indexDSN returns the driver DSN that opens the database at path. The +// driver runs each _pragma parameter on every connection it opens and drops +// any parameter it does not know without an error, so a setting written in +// another form silently does nothing. In WAL mode one connection can write +// while others read; the busy timeout makes a connection wait for a lock +// instead of failing at once. +func indexDSN(path string) string { + return fmt.Sprintf( + "%s?_pragma=busy_timeout(%d)&_pragma=journal_mode(WAL)"+ + "&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(1)", + path, busyTimeoutMs) +} + // New creates a new database connection at the specified path. -// It creates the schema if needed and configures SQLite with WAL mode for -// better concurrency. SQLite handles crash recovery automatically when -// opening a database with journal/WAL files present. +// It creates the schema if needed. Every connection runs in WAL mode with +// a busy timeout and foreign keys on (see indexDSN), so a read-only command +// can read the index while a backup writes to it. Committed rows can sit in +// the -wal file beside the database until a checkpoint, so a copy of the +// database file alone may miss them. +// SQLite handles crash recovery automatically when opening a database with +// journal/WAL files present. // The path parameter can be a file path for persistent storage or ":memory:" // for an in-memory database (useful for testing). func New(ctx context.Context, path string) (*DB, error) { @@ -110,11 +131,7 @@ func New(ctx context.Context, path string) (*DB, error) { // First attempt with standard WAL mode log.Debug("Attempting to open database with WAL mode", "path", path) - conn, err := sql.Open( - "sqlite", - path+"?_journal_mode=WAL&_synchronous=NORMAL&_busy_timeout=10000"+ - "&_locking_mode=NORMAL&_foreign_keys=ON", - ) + conn, err := sql.Open("sqlite", indexDSN(path)) if err == nil { configureConnPool(conn) @@ -134,8 +151,8 @@ func New(ctx context.Context, path string) (*DB, error) { _ = conn.Close() } - // If first attempt failed, try with TRUNCATE mode to clear any locks - return openWithRecovery(ctx, path) + // If the first attempt failed, try once more + return retryOpen(ctx, path) } // configureConnPool serializes all database access through one connection. @@ -147,18 +164,12 @@ func configureConnPool(conn *sql.DB) { conn.SetMaxIdleConns(1) } -// finishOpen enables foreign keys, wraps the connection, and applies any -// pending migrations. On migration failure the connection is closed. +// finishOpen wraps the connection and applies any pending migrations. On +// migration failure the connection is closed. func finishOpen(ctx context.Context, conn *sql.DB, path string) (*DB, error) { - // Enable foreign keys explicitly - _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys = ON") - if err != nil { - log.Warn("Failed to enable foreign keys", "path", path, "error", err) - } - db := &DB{conn: conn, path: path} - err = applyMigrations(ctx, conn) + err := applyMigrations(ctx, conn) if err != nil { _ = conn.Close() @@ -168,21 +179,15 @@ func finishOpen(ctx context.Context, conn *sql.DB, path string) (*DB, error) { return db, nil } -// openWithRecovery retries opening the database in TRUNCATE journal mode to -// clear stale locks, then switches back to WAL mode. -func openWithRecovery(ctx context.Context, path string) (*DB, error) { - log.Info( - "Database appears locked, attempting recovery with TRUNCATE mode", - "path", path, - ) +// retryOpen makes a second attempt to open the database, with the same +// settings, after the first attempt failed, for example because another +// process held a lock for longer than the busy timeout. +func retryOpen(ctx context.Context, path string) (*DB, error) { + log.Info("Database appears locked, retrying open", "path", path) - conn, err := sql.Open( - "sqlite", - path+"?_journal_mode=TRUNCATE&_synchronous=NORMAL&_busy_timeout=10000"+ - "&_foreign_keys=ON", - ) + conn, err := sql.Open("sqlite", indexDSN(path)) if err != nil { - return nil, fmt.Errorf("opening database in recovery mode: %w", err) + return nil, fmt.Errorf("opening database on retry: %w", err) } configureConnPool(conn) @@ -190,28 +195,18 @@ func openWithRecovery(ctx context.Context, path string) (*DB, error) { err = conn.PingContext(ctx) if err != nil { log.Debug( - "Failed to ping database in recovery mode, closing", + "Failed to ping database on retry, closing", "path", path, "error", err, ) _ = conn.Close() return nil, fmt.Errorf( - "database still locked after recovery attempt: %w", + "database still locked on retry: %w", err, ) } - log.Debug("Database opened in TRUNCATE mode", "path", path) - - // Switch back to WAL mode - log.Debug("Switching database back to WAL mode", "path", path) - - _, err = conn.ExecContext(ctx, "PRAGMA journal_mode=WAL") - if err != nil { - log.Warn("Failed to switch back to WAL mode", "path", path, "error", err) - } - db, err := finishOpen(ctx, conn, path) if err != nil { return nil, err @@ -224,7 +219,8 @@ func openWithRecovery(ctx context.Context, path string) (*DB, error) { // errUntrustedSnapshotSchema is returned when a downloaded snapshot // database carries schema objects the real schema never defines, or is -// missing a table the restore and deep-verify queries read. +// missing a table the restore, deep-verify and `snapshot files` queries +// read. var errUntrustedSnapshotSchema = errors.New( "downloaded snapshot database has an untrusted schema") @@ -246,12 +242,12 @@ func snapshotReadOnlyDSN(path string) string { // OpenReadOnly opens an already-materialized SQLite file for read-only // querying of a snapshot database downloaded from the store, used by -// restore and deep verify. Unlike New it never applies schema migrations -// and never writes: the connection is opened read-only with query_only -// and trusted_schema=OFF. It refuses any file whose schema carries a -// trigger, view or virtual table, or lacks an expected table, so a forged -// file cannot redefine what the restore queries return. The caller owns -// the file and must remove it. +// restore, deep verify and `snapshot files`. Unlike New it never applies +// schema migrations and never writes: the connection is opened read-only +// with query_only and trusted_schema=OFF. It refuses any file whose schema +// carries a trigger, view or virtual table, or lacks an expected table, so +// a forged file cannot redefine what the restore queries return. The +// caller owns the file and must remove it. func OpenReadOnly(ctx context.Context, path string) (*DB, error) { conn, err := sql.Open("sqlite", snapshotReadOnlyDSN(path)) if err != nil { @@ -281,9 +277,9 @@ func OpenReadOnly(ctx context.Context, path string) (*DB, error) { // the plain table set the real schema defines. Any trigger, view or // virtual table, or a missing expected table, fails the open. func verifySnapshotSchema(ctx context.Context, conn *sql.DB) error { - // expectedSnapshotTables are the tables the restore and deep-verify - // queries read. A downloaded database missing any of them is not a - // genuine snapshot database and is refused. + // expectedSnapshotTables are the tables the restore, deep-verify and + // `snapshot files` queries read. A downloaded database missing any of + // them is not a genuine snapshot database and is refused. expectedSnapshotTables := []string{ "blob_chunks", "blobs", diff --git a/internal/database/database_test.go b/internal/database/database_test.go index 24cf416..b2fb822 100644 --- a/internal/database/database_test.go +++ b/internal/database/database_test.go @@ -120,6 +120,89 @@ func TestDatabaseConcurrentAccess(t *testing.T) { } } +// TestNewSetsJournalModeAndBusyTimeout checks that the connection settings +// New passes reach SQLite. The driver drops a setting it does not recognise +// without an error, so only reading the value back shows it took effect. +func TestNewSetsJournalModeAndBusyTimeout(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + db, err := New(ctx, filepath.Join(t.TempDir(), "index.db")) + if err != nil { + t.Fatalf("failed to create database: %v", err) + } + + defer func() { _ = db.Close() }() + + var journalMode string + + err = db.conn.QueryRowContext(ctx, "PRAGMA journal_mode").Scan(&journalMode) + if err != nil { + t.Fatalf("reading journal_mode: %v", err) + } + + if journalMode != "wal" { + t.Errorf("journal_mode = %q, want %q", journalMode, "wal") + } + + var busyTimeout int + + err = db.conn.QueryRowContext(ctx, "PRAGMA busy_timeout").Scan(&busyTimeout) + if err != nil { + t.Fatalf("reading busy_timeout: %v", err) + } + + if busyTimeout != busyTimeoutMs { + t.Errorf("busy_timeout = %d, want %d", busyTimeout, busyTimeoutMs) + } +} + +// TestNewWriteSucceedsWhileAnotherHandleReads opens the same index twice, +// as a read-only command does while a backup runs, and checks that a write +// on one handle commits while the other is in the middle of a read. +func TestNewWriteSucceedsWhileAnotherHandleReads(t *testing.T) { + t.Parallel() + + ctx := context.Background() + dbPath := filepath.Join(t.TempDir(), "index.db") + + reader, err := New(ctx, dbPath) + if err != nil { + t.Fatalf("failed to open reading handle: %v", err) + } + + defer func() { _ = reader.Close() }() + + writer, err := New(ctx, dbPath) + if err != nil { + t.Fatalf("failed to open writing handle: %v", err) + } + + defer func() { _ = writer.Close() }() + + // The read lock taken by the SELECT is held until the transaction ends. + readTx, err := reader.BeginTx(ctx, nil) + if err != nil { + t.Fatalf("beginning read transaction: %v", err) + } + + defer func() { _ = readTx.Rollback() }() + + var count int + + err = readTx.QueryRowContext(ctx, "SELECT COUNT(*) FROM chunks").Scan(&count) + if err != nil { + t.Fatalf("reading chunks: %v", err) + } + + _, err = writer.ExecWithLog(ctx, + "INSERT INTO chunks (chunk_hash, size) VALUES (?, ?)", "hash", 1024) + if err != nil { + t.Fatalf("write while another handle reads: %v", err) + } +} + func TestParseMigrationVersion(t *testing.T) { t.Parallel() diff --git a/internal/database/errors.go b/internal/database/errors.go deleted file mode 100644 index 49492bd..0000000 --- a/internal/database/errors.go +++ /dev/null @@ -1,12 +0,0 @@ -package database - -import ( - "fmt" - "os" -) - -// Fatalf prints an error message to stderr and exits with status 1 -func Fatalf(format string, args ...any) { - fmt.Fprintf(os.Stderr, "FATAL: "+format+"\n", args...) - os.Exit(1) -} diff --git a/internal/database/file_chunks.go b/internal/database/file_chunks.go index 04388d7..bbecc03 100644 --- a/internal/database/file_chunks.go +++ b/internal/database/file_chunks.go @@ -62,12 +62,7 @@ func (r *FileChunkRepository) GetByPath( return nil, fmt.Errorf("querying file chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanFileChunks(rows) } @@ -88,12 +83,7 @@ func (r *FileChunkRepository) GetByFileID( return nil, fmt.Errorf("querying file chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanFileChunks(rows) } @@ -117,12 +107,7 @@ func (r *FileChunkRepository) GetByPathTx( return nil, fmt.Errorf("querying file chunks: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() fileChunks, err := r.scanFileChunks(rows) LogSQL("GetByPathTx", "Complete", path, "count", len(fileChunks)) @@ -253,7 +238,7 @@ func (r *FileChunkRepository) CreateBatch( args = append(args, fc.FileID.String(), fc.Idx, fc.ChunkHash.String()) } - query += querySb211.String() //nolint:gosec // G202: appends "?" placeholders only + query += querySb211.String() query += " ON CONFLICT(file_id, idx) DO NOTHING" diff --git a/internal/database/files.go b/internal/database/files.go index 8fd69e7..5608fd5 100644 --- a/internal/database/files.go +++ b/internal/database/files.go @@ -33,11 +33,13 @@ func (r *FileRepository) Create(ctx context.Context, tx *sql.Tx, file *File) err } query := ` - INSERT INTO files (id, path, source_path, mtime, size, mode, uid, gid, link_target) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + INSERT INTO files + (id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET source_path = excluded.source_path, mtime = excluded.mtime, + mtime_nsec = excluded.mtime_nsec, size = excluded.size, mode = excluded.mode, uid = excluded.uid, @@ -54,16 +56,19 @@ func (r *FileRepository) Create(ctx context.Context, tx *sql.Tx, file *File) err if tx != nil { LogSQL("Execute", query, file.ID.String(), file.Path.String(), file.SourcePath.String(), - file.MTime.Unix(), file.Size, file.Mode, file.UID, file.GID, + file.MTime.Unix(), file.MTime.Nanosecond(), + file.Size, file.Mode, file.UID, file.GID, file.LinkTarget.String()) err = tx.QueryRowContext(ctx, query, file.ID.String(), file.Path.String(), file.SourcePath.String(), - file.MTime.Unix(), file.Size, file.Mode, file.UID, file.GID, + file.MTime.Unix(), file.MTime.Nanosecond(), + file.Size, file.Mode, file.UID, file.GID, file.LinkTarget.String()).Scan(&idStr) } else { err = r.db.QueryRowWithLog(ctx, query, file.ID.String(), file.Path.String(), file.SourcePath.String(), - file.MTime.Unix(), file.Size, file.Mode, file.UID, file.GID, + file.MTime.Unix(), file.MTime.Nanosecond(), + file.Size, file.Mode, file.UID, file.GID, file.LinkTarget.String()).Scan(&idStr) } @@ -84,7 +89,7 @@ func (r *FileRepository) Create(ctx context.Context, tx *sql.Tx, file *File) err // in the index. func (r *FileRepository) GetByPath(ctx context.Context, path string) (*File, error) { query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files WHERE path = ? ` @@ -104,7 +109,7 @@ func (r *FileRepository) GetByPath(ctx context.Context, path string) (*File, err // GetByID retrieves a file by its UUID func (r *FileRepository) GetByID(ctx context.Context, id types.FileID) (*File, error) { query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files WHERE id = ? ` @@ -127,7 +132,7 @@ func (r *FileRepository) GetByPathTx( ctx context.Context, tx *sql.Tx, path string, ) (*File, error) { query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files WHERE path = ? ` @@ -158,23 +163,19 @@ func (r *FileRepository) ListModifiedSince( ctx context.Context, since time.Time, ) ([]*File, error) { query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files - WHERE mtime >= ? + WHERE (mtime, mtime_nsec) >= (?, ?) ORDER BY path ` - rows, err := r.db.conn.QueryContext(ctx, query, since.Unix()) + rows, err := r.db.conn.QueryContext(ctx, query, + since.Unix(), since.Nanosecond()) if err != nil { return nil, fmt.Errorf("querying files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var files []*File @@ -228,29 +229,29 @@ func (r *FileRepository) DeleteByID( return nil } -// ListByPrefix returns all files whose path starts with prefix, ordered by -// path. -func (r *FileRepository) ListByPrefix( - ctx context.Context, prefix string, +// ListUnderPath returns the file at path and every file beneath it, +// ordered by path. Paths are compared case-sensitively, and a trailing +// slash on path is ignored, so "/" lists every file. +func (r *FileRepository) ListUnderPath( + ctx context.Context, path string, ) ([]*File, error) { + path = strings.TrimRight(path, "/") + dirPrefix := path + "/" + + // LIKE would ignore ASCII case and treat _ and % in path as wildcards. query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files - WHERE path LIKE ? || '%' + WHERE path = ? OR substr(path, 1, length(?)) = ? ORDER BY path ` - rows, err := r.db.conn.QueryContext(ctx, query, prefix) + rows, err := r.db.conn.QueryContext(ctx, query, path, dirPrefix, dirPrefix) if err != nil { return nil, fmt.Errorf("querying files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var files []*File @@ -266,10 +267,94 @@ func (r *FileRepository) ListByPrefix( return files, rows.Err() } +// ListUnderPathInSnapshot returns the files that ListUnderPath returns +// for path and that the snapshot lists, in no particular order. +func (r *FileRepository) ListUnderPathInSnapshot( + ctx context.Context, path, snapshotID string, +) ([]*File, error) { + path = strings.TrimRight(path, "/") + dirPrefix := path + "/" + + query := ` + SELECT f.id, f.path, f.source_path, f.mtime, f.mtime_nsec, f.size, + f.mode, f.uid, f.gid, f.link_target + FROM files f + JOIN snapshot_files sf ON sf.file_id = f.id + WHERE sf.snapshot_id = ? + AND (f.path = ? OR substr(f.path, 1, length(?)) = ?) + ` + + rows, err := r.db.conn.QueryContext(ctx, query, + snapshotID, path, dirPrefix, dirPrefix) + if err != nil { + return nil, fmt.Errorf("querying files: %w", err) + } + + defer func() { _ = rows.Close() }() + + var files []*File + + for rows.Next() { + file, err := r.scanFileRows(rows) + if err != nil { + return nil, fmt.Errorf("scanning file: %w", err) + } + + files = append(files, file) + } + + return files, rows.Err() +} + +// ListIDsWithChunksNotInUploadedBlobs returns the IDs of the files whose +// path starts with prefix and that list at least one chunk held by no +// blob whose upload has completed (uploaded_ts set). A new snapshot +// cannot reference such a chunk, so a backup must not treat the file as +// unchanged even when its metadata matches the file on disk. +func (r *FileRepository) ListIDsWithChunksNotInUploadedBlobs( + ctx context.Context, prefix string, +) ([]types.FileID, error) { + query := ` + SELECT DISTINCT f.id + FROM files f + JOIN file_chunks fc ON fc.file_id = f.id + WHERE f.path LIKE ? || '%' + AND NOT EXISTS ( + SELECT 1 + FROM blob_chunks bc + JOIN blobs b ON bc.blob_id = b.id + WHERE bc.chunk_hash = fc.chunk_hash + AND b.uploaded_ts IS NOT NULL + ) + ` + + rows, err := r.db.conn.QueryContext(ctx, query, prefix) + if err != nil { + return nil, fmt.Errorf("querying files: %w", err) + } + + defer func() { _ = rows.Close() }() + + var ids []types.FileID + + for rows.Next() { + var id types.FileID + + err := rows.Scan(&id) + if err != nil { + return nil, fmt.Errorf("scanning file ID: %w", err) + } + + ids = append(ids, id) + } + + return ids, rows.Err() +} + // ListAll returns all files in the database func (r *FileRepository) ListAll(ctx context.Context) ([]*File, error) { query := ` - SELECT id, path, source_path, mtime, size, mode, uid, gid, link_target + SELECT id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target FROM files ORDER BY path ` @@ -279,12 +364,7 @@ func (r *FileRepository) ListAll(ctx context.Context) ([]*File, error) { return nil, fmt.Errorf("querying files: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() var files []*File @@ -310,7 +390,7 @@ func (r *FileRepository) CreateBatch( } // Each files row binds this many SQL variables. - const fileCols = 9 + const fileCols = 10 // Batch at 100 rows to be safe with SQLite's variable limit. const batchSize = 100 @@ -321,7 +401,7 @@ func (r *FileRepository) CreateBatch( batch := files[i:end] query := `INSERT INTO files - (id, path, source_path, mtime, size, mode, uid, gid, link_target) + (id, path, source_path, mtime, mtime_nsec, size, mode, uid, gid, link_target) VALUES ` args := make([]any, 0, len(batch)*fileCols) @@ -333,19 +413,21 @@ func (r *FileRepository) CreateBatch( querySb325.WriteString(", ") } - querySb325.WriteString("(?, ?, ?, ?, ?, ?, ?, ?, ?)") + querySb325.WriteString("(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") args = append(args, f.ID.String(), f.Path.String(), f.SourcePath.String(), - f.MTime.Unix(), f.Size, f.Mode, f.UID, f.GID, + f.MTime.Unix(), f.MTime.Nanosecond(), + f.Size, f.Mode, f.UID, f.GID, f.LinkTarget.String()) } - query += querySb325.String() //nolint:gosec // G202: appends "?" placeholders only + query += querySb325.String() query += ` ON CONFLICT(path) DO UPDATE SET source_path = excluded.source_path, mtime = excluded.mtime, + mtime_nsec = excluded.mtime_nsec, size = excluded.size, mode = excluded.mode, uid = excluded.uid, @@ -405,7 +487,7 @@ func (r *FileRepository) scanFileFrom(row fileRowScanner) (*File, error) { var ( file File idStr, pathStr, sourcePathStr string - mtimeUnix int64 + mtimeUnix, mtimeNsec int64 linkTarget sql.NullString ) @@ -414,6 +496,7 @@ func (r *FileRepository) scanFileFrom(row fileRowScanner) (*File, error) { &pathStr, &sourcePathStr, &mtimeUnix, + &mtimeNsec, &file.Size, &file.Mode, &file.UID, @@ -432,7 +515,7 @@ func (r *FileRepository) scanFileFrom(row fileRowScanner) (*File, error) { file.Path = types.FilePath(pathStr) file.SourcePath = types.SourcePath(sourcePathStr) - file.MTime = time.Unix(mtimeUnix, 0).UTC() + file.MTime = time.Unix(mtimeUnix, mtimeNsec).UTC() if linkTarget.Valid { file.LinkTarget = types.FilePath(linkTarget.String) } diff --git a/internal/database/files_test.go b/internal/database/files_test.go index 2d4823b..343c482 100644 --- a/internal/database/files_test.go +++ b/internal/database/files_test.go @@ -5,10 +5,12 @@ import ( "database/sql" "errors" "os" + "slices" "testing" "time" "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/types" ) // errTestRollback is the sentinel returned from transaction bodies to @@ -134,6 +136,141 @@ func TestFileRepositoryListDelete(t *testing.T) { } } +func TestFileRepositoryListUnderPath(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repo := database.NewFileRepository(db) + + const ( + docDir = "/home/u/doc" + docFile = "/home/u/doc/a.txt" + ) + + // In path order, so the root case can expect all of them as listed. + paths := []string{ + "/home/u/50%/x.txt", + "/home/u/50percent/y.txt", + "/home/u/DOC/c.txt", + "/home/u/a_b/x.txt", + "/home/u/axb/y.txt", + docDir, + "/home/u/doc.txt.bak", + docFile, + "/home/u/doc/sub/b.txt", + "/home/u/doc2/b.txt", + } + + for _, path := range paths { + err := repo.Create(ctx, nil, &database.File{ + Path: types.FilePath(path), + MTime: time.Now().Truncate(time.Second), + Mode: 0644, + }) + if err != nil { + t.Fatalf("failed to create %s: %v", path, err) + } + } + + docTree := []string{docDir, docFile, "/home/u/doc/sub/b.txt"} + + tests := []struct { + name string + path string + want []string + }{ + {"directory", docDir, docTree}, + {"directory with trailing slash", docDir + "/", docTree}, + {"directory differing only in case", "/home/u/DOC", + []string{"/home/u/DOC/c.txt"}}, + {"file", docFile, []string{docFile}}, + {"underscore is literal", "/home/u/a_b", + []string{"/home/u/a_b/x.txt"}}, + {"percent is literal", "/home/u/50%", + []string{"/home/u/50%/x.txt"}}, + {"root", "/", paths}, + } + + for _, tt := range tests { + files, err := repo.ListUnderPath(ctx, tt.path) + if err != nil { + t.Fatalf("%s: failed to list files: %v", tt.name, err) + } + + got := make([]string, 0, len(files)) + for _, f := range files { + got = append(got, f.Path.String()) + } + + if !slices.Equal(got, tt.want) { + t.Errorf("%s: listing %q got %q, want %q", + tt.name, tt.path, got, tt.want) + } + } +} + +// ListUnderPathInSnapshot leaves out files outside path and files the +// snapshot does not list, though another snapshot lists them. +func TestFileRepositoryListUnderPathInSnapshot(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + files := database.NewFileRepository(db) + snapshots := database.NewSnapshotRepository(db) + + listed := map[string][]string{ + "one": {"/src/a.txt", "/src2/c.txt"}, + "two": {"/src/b.txt"}, + } + + for snapshotID, paths := range listed { + err := snapshots.Create(ctx, nil, &database.Snapshot{ + ID: types.SnapshotID(snapshotID), + Hostname: "host", + StartedAt: time.Now(), + }) + if err != nil { + t.Fatalf("failed to create snapshot %s: %v", snapshotID, err) + } + + for _, path := range paths { + err := files.Create(ctx, nil, &database.File{ + Path: types.FilePath(path), + MTime: time.Now().Truncate(time.Second), + Mode: 0644, + }) + if err != nil { + t.Fatalf("failed to create %s: %v", path, err) + } + + err = snapshots.AddFile(ctx, nil, snapshotID, path) + if err != nil { + t.Fatalf("failed to add %s to %s: %v", path, snapshotID, err) + } + } + } + + found, err := files.ListUnderPathInSnapshot(ctx, "/src", "one") + if err != nil { + t.Fatalf("failed to list files: %v", err) + } + + got := make([]string, 0, len(found)) + for _, f := range found { + got = append(got, f.Path.String()) + } + + if !slices.Equal(got, []string{"/src/a.txt"}) { + t.Errorf("got %q, want only /src/a.txt", got) + } +} + func TestFileRepositorySymlink(t *testing.T) { t.Parallel() @@ -174,6 +311,115 @@ func TestFileRepositorySymlink(t *testing.T) { } } +// An mtime after 2262 or before 1678 does not fit in int64 nanoseconds +// since the epoch, and must still come back from the database unchanged. +func TestFileRepositoryMTimeOutsideInt64NanosecondRange(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repo := database.NewFileRepository(db) + + mtimes := []time.Time{ + time.Date(2300, time.January, 1, 0, 0, 0, 123456789, time.UTC), + time.Date(1601, time.January, 1, 0, 0, 0, 987654321, time.UTC), + } + + for _, mtime := range mtimes { + created := &database.File{ + Path: types.FilePath("/created-" + mtime.Format(time.RFC3339Nano)), + MTime: mtime, + } + + err := repo.Create(ctx, nil, created) + if err != nil { + t.Fatalf("failed to create file: %v", err) + } + + batched := &database.File{ + ID: types.NewFileID(), + Path: types.FilePath("/batched-" + mtime.Format(time.RFC3339Nano)), + MTime: mtime, + } + + err = repo.CreateBatch(ctx, nil, []*database.File{batched}) + if err != nil { + t.Fatalf("failed to batch create file: %v", err) + } + + for _, path := range []types.FilePath{created.Path, batched.Path} { + retrieved, err := repo.GetByPath(ctx, path.String()) + if err != nil { + t.Fatalf("failed to get file: %v", err) + } + + if !retrieved.MTime.Equal(mtime) { + t.Errorf("%s: mtime got %v, want %v", + path, retrieved.MTime, mtime) + } + } + } +} + +// A file already in the index and rewritten within the same second must get +// its new nanoseconds stored, through both Create and CreateBatch. +func TestFileRepositoryUpsertMTimeInSameSecond(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repo := database.NewFileRepository(db) + + indexed := time.Date(2026, time.October, 7, 12, 0, 0, 100000000, time.UTC) + rewritten := indexed.Add(800 * time.Millisecond) + + tests := []struct { + name string + upsert func(file *database.File) error + }{ + {"Create", func(file *database.File) error { + return repo.Create(ctx, nil, file) + }}, + {"CreateBatch", func(file *database.File) error { + return repo.CreateBatch(ctx, nil, []*database.File{file}) + }}, + } + + for _, tt := range tests { + file := &database.File{ + ID: types.NewFileID(), + Path: types.FilePath("/" + tt.name), + MTime: indexed, + } + + err := tt.upsert(file) + if err != nil { + t.Fatalf("%s: failed to create file: %v", tt.name, err) + } + + file.MTime = rewritten + + err = tt.upsert(file) + if err != nil { + t.Fatalf("%s: failed to update file: %v", tt.name, err) + } + + retrieved, err := repo.GetByPath(ctx, file.Path.String()) + if err != nil { + t.Fatalf("%s: failed to get file: %v", tt.name, err) + } + + if !retrieved.MTime.Equal(rewritten) { + t.Errorf("%s: mtime got %v, want %v", + tt.name, retrieved.MTime, rewritten) + } + } +} + func TestFileRepositoryTransaction(t *testing.T) { t.Parallel() diff --git a/internal/database/models.go b/internal/database/models.go index ed27a8c..c71b1cd 100644 --- a/internal/database/models.go +++ b/internal/database/models.go @@ -14,8 +14,7 @@ type File struct { ID types.FileID // UUID primary key Path types.FilePath // Absolute path of the file - // SourcePath is the source directory this file came from (used for - // restore path stripping). + // SourcePath is the source directory this file came from. SourcePath types.SourcePath MTime time.Time Size int64 @@ -99,8 +98,8 @@ type Snapshot struct { StartedAt time.Time CompletedAt *time.Time // nil if still in progress FileCount int64 - ChunkCount int64 - BlobCount int64 + ChunkCount int64 // Chunks this snapshot stored that were not stored before + BlobCount int64 // Blobs this snapshot created TotalSize int64 // Total size of all referenced files // BlobSize is the total size of all referenced blobs (compressed and diff --git a/internal/database/module.go b/internal/database/module.go index 65b04b0..b4035be 100644 --- a/internal/database/module.go +++ b/internal/database/module.go @@ -20,6 +20,17 @@ const indexDirPerm = 0o700 // backed-up path and chunk hash and must stay private. const indexFilePerm = 0o600 +// IndexFiles returns the path of the index at indexPath and the paths of +// the side files SQLite keeps beside it while it writes. +func IndexFiles(indexPath string) []string { + return []string{ + indexPath, + indexPath + "-wal", + indexPath + "-shm", + indexPath + "-journal", + } +} + // ensureIndexFileMode makes the index file owner-only before the SQLite // driver opens it: it creates the file 0600 if absent, or chmods an existing // one to 0600. Doing this first matters because SQLite creates its -wal and diff --git a/internal/database/repositories.go b/internal/database/repositories.go index 64a3f66..fe3f5df 100644 --- a/internal/database/repositories.go +++ b/internal/database/repositories.go @@ -3,6 +3,7 @@ package database import ( "context" "database/sql" + "errors" "fmt" ) @@ -60,22 +61,24 @@ func (r *Repositories) WithTx(ctx context.Context, fn TxFunc) error { defer func() { if p := recover(); p != nil { - rollbackErr := tx.Rollback() - if rollbackErr != nil { - Fatalf("failed to rollback transaction: %v", rollbackErr) - } + // The panic is the failure to report, so a rollback error + // is dropped. + _ = tx.Rollback() panic(p) - } else if err != nil { - rollbackErr := tx.Rollback() - if rollbackErr != nil { - Fatalf("failed to rollback transaction: %v", rollbackErr) - } } }() err = fn(ctx, tx) if err != nil { + // Once ctx is cancelled, database/sql rolls the transaction + // back itself and Rollback returns sql.ErrTxDone. + rollbackErr := tx.Rollback() + if rollbackErr != nil && !errors.Is(rollbackErr, sql.ErrTxDone) { + return fmt.Errorf("%w; rolling back transaction: %w", + err, rollbackErr) + } + return err } @@ -103,22 +106,24 @@ func (r *Repositories) WithReadTx(ctx context.Context, fn TxFunc) error { defer func() { if p := recover(); p != nil { - rollbackErr := tx.Rollback() - if rollbackErr != nil { - Fatalf("failed to rollback transaction: %v", rollbackErr) - } + // The panic is the failure to report, so a rollback error + // is dropped. + _ = tx.Rollback() panic(p) - } else if err != nil { - rollbackErr := tx.Rollback() - if rollbackErr != nil { - Fatalf("failed to rollback transaction: %v", rollbackErr) - } } }() err = fn(ctx, tx) if err != nil { + // Once ctx is cancelled, database/sql rolls the transaction + // back itself and Rollback returns sql.ErrTxDone. + rollbackErr := tx.Rollback() + if rollbackErr != nil && !errors.Is(rollbackErr, sql.ErrTxDone) { + return fmt.Errorf("%w; rolling back transaction: %w", + err, rollbackErr) + } + return err } diff --git a/internal/database/repositories_test.go b/internal/database/repositories_test.go index f4e2199..d1db401 100644 --- a/internal/database/repositories_test.go +++ b/internal/database/repositories_test.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "errors" + "strings" "testing" "time" @@ -235,6 +236,125 @@ func TestRepositoriesTransactionRollback(t *testing.T) { } } +// When the context is cancelled during the body, database/sql rolls the +// transaction back itself, so WithTx's own rollback finds it already +// done. WithTx must return the body's error alone, without that rollback. +func TestRepositoriesTransactionContextCancelled(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + repos := database.NewRepositories(db) + + err := repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + file := &database.File{ + Path: "/test/cancelled_file.txt", + MTime: time.Now().Truncate(time.Second), + Size: 1024, + Mode: 0644, + UID: 1000, + GID: 1000, + } + + err := repos.Files.Create(ctx, tx, file) + if err != nil { + return err + } + + cancel() + + // database/sql rolls back from a goroutine of its own; wait + // until it has, so the test does not depend on that race. + for { + _, err = tx.ExecContext(context.WithoutCancel(ctx), "SELECT 1") + if errors.Is(err, sql.ErrTxDone) { + return ctx.Err() + } + + time.Sleep(time.Millisecond) + } + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got: %v", err) + } + + if errors.Is(err, sql.ErrTxDone) { + t.Fatalf("the already-done rollback was reported: %v", err) + } + + file, err := repos.Files.GetByPath( + context.Background(), "/test/cancelled_file.txt", + ) + if err != nil { + t.Fatalf("error checking for file: %v", err) + } + + if file != nil { + t.Error("file should not exist after the cancelled transaction") + } +} + +// A body that ends the transaction itself with ROLLBACK makes WithTx's +// own rollback fail. WithTx must return that failure together with the +// body's error. +func TestRepositoriesTransactionRollbackFails(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repos := database.NewRepositories(db) + + err := repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + _, err := tx.ExecContext(ctx, "ROLLBACK") + if err != nil { + return err + } + + return errIntentionalRollback + }) + if !errors.Is(err, errIntentionalRollback) { + t.Fatalf("expected the body's error, got: %v", err) + } + + if !strings.Contains(err.Error(), "rolling back transaction") { + t.Errorf("expected the failed rollback in the error, got: %v", err) + } +} + +// When the body ends the transaction itself with ROLLBACK and then +// panics, WithTx's own rollback fails; the panic must still reach the +// caller. +func TestRepositoriesTransactionPanicRollbackFails(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repos := database.NewRepositories(db) + + defer func() { + if recover() == nil { + t.Error("expected the body's panic to reach the caller") + } + }() + + _ = repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + _, err := tx.ExecContext(ctx, "ROLLBACK") + if err != nil { + return err + } + + panic(errIntentionalRollback) + }) +} + func TestRepositoriesReadTransaction(t *testing.T) { t.Parallel() @@ -291,3 +411,41 @@ func TestRepositoriesReadTransaction(t *testing.T) { t.Error("expected to retrieve file in read transaction") } } + +// When the context is cancelled during a read transaction's body, +// database/sql rolls the transaction back itself, so WithReadTx's own +// rollback finds it already done. WithReadTx must return the body's error +// alone, without that rollback. +func TestRepositoriesReadTransactionContextCancelled(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + repos := database.NewRepositories(db) + + err := repos.WithReadTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + cancel() + + // database/sql rolls back from a goroutine of its own; wait + // until it has, so the test does not depend on that race. + for { + _, err := tx.ExecContext(context.WithoutCancel(ctx), "SELECT 1") + if errors.Is(err, sql.ErrTxDone) { + return ctx.Err() + } + + time.Sleep(time.Millisecond) + } + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context.Canceled, got: %v", err) + } + + if errors.Is(err, sql.ErrTxDone) { + t.Fatalf("the already-done rollback was reported: %v", err) + } +} diff --git a/internal/database/repository_comprehensive_test.go b/internal/database/repository_comprehensive_test.go index 4799458..53c5372 100644 --- a/internal/database/repository_comprehensive_test.go +++ b/internal/database/repository_comprehensive_test.go @@ -824,7 +824,7 @@ func TestTransactionIsolation(t *testing.T) { } // Verify the file was not created (transaction rolled back) - files, err := repos.Files.ListByPrefix(ctx, "/tx-test") + files, err := repos.Files.ListUnderPath(ctx, "/tx-test.txt") if err != nil { t.Fatal(err) } @@ -916,7 +916,7 @@ func TestConcurrentOrphanedCleanup(t *testing.T) { } // Verify correct files were deleted - files, err := repos.Files.ListByPrefix(ctx, "/concurrent-") + files, err := repos.Files.ListAll(ctx) if err != nil { t.Fatal(err) } diff --git a/internal/database/repository_debug_test.go b/internal/database/repository_debug_test.go index 4a4e2aa..9c9ec02 100644 --- a/internal/database/repository_debug_test.go +++ b/internal/database/repository_debug_test.go @@ -147,7 +147,7 @@ func TestOrphanedFileCleanupDebug(t *testing.T) { t.Logf("Files count after cleanup: %d", count) // List remaining files - files, err := repos.Files.ListByPrefix(ctx, "/") + files, err := repos.Files.ListUnderPath(ctx, "/") if err != nil { t.Fatal(err) } diff --git a/internal/database/repository_edge_cases_test.go b/internal/database/repository_edge_cases_test.go index 3e8cfb2..59b54ac 100644 --- a/internal/database/repository_edge_cases_test.go +++ b/internal/database/repository_edge_cases_test.go @@ -3,6 +3,7 @@ package database import ( "context" + "database/sql" "fmt" "strings" "testing" @@ -367,7 +368,7 @@ func verifyBlobNullUploadTS( } // createLargeDatasetFiles creates fileCount files and adds every other -// one to the snapshot. +// one to the snapshot, in one transaction as a backup writes them. func createLargeDatasetFiles( t *testing.T, repos *Repositories, @@ -376,31 +377,38 @@ func createLargeDatasetFiles( ) { t.Helper() - ctx := context.Background() start := time.Now() - for i := range fileCount { - file := &File{ - Path: types.FilePath(fmt.Sprintf("/large/file%05d.txt", i)), - MTime: time.Now(), - Size: int64(i * 1024), - Mode: 0644, - UID: uint32(1000 + (i % 10)), - GID: uint32(1000 + (i % 10)), - } + err := repos.WithTx(context.Background(), + func(ctx context.Context, tx *sql.Tx) error { + for i := range fileCount { + file := &File{ + Path: types.FilePath(fmt.Sprintf("/large/file%05d.txt", i)), + MTime: time.Now(), + Size: int64(i * 1024), + Mode: 0644, + UID: uint32(1000 + (i % 10)), + GID: uint32(1000 + (i % 10)), + } - err := repos.Files.Create(ctx, nil, file) - if err != nil { - t.Fatalf("failed to create file %d: %v", i, err) - } + err := repos.Files.Create(ctx, tx, file) + if err != nil { + return fmt.Errorf("creating file %d: %w", i, err) + } - // Add half to snapshot - if i%2 == 0 { - err = repos.Snapshots.AddFileByID(ctx, nil, snapshotID, file.ID) - if err != nil { - t.Fatal(err) + // Add half to snapshot + if i%2 == 0 { + err = repos.Snapshots.AddFileByID(ctx, tx, snapshotID, file.ID) + if err != nil { + return err + } + } } - } + + return nil + }) + if err != nil { + t.Fatal(err) } t.Logf("Created %d files in %v", fileCount, time.Since(start)) @@ -442,12 +450,12 @@ func TestLargeDatasets(t *testing.T) { createLargeDatasetFiles(t, repos, snapshot.ID.String(), fileCount) }) - // Test ListByPrefix performance + // Test ListUnderPath performance //nolint:paralleltest // phases share one database and are order-dependent - t.Run("list by prefix performance", func(t *testing.T) { + t.Run("list under path performance", func(t *testing.T) { start := time.Now() - files, err := repos.Files.ListByPrefix(ctx, "/large/") + files, err := repos.Files.ListUnderPath(ctx, "/large/") if err != nil { t.Fatal(err) } @@ -472,7 +480,7 @@ func TestLargeDatasets(t *testing.T) { t.Logf("Cleaned up orphaned files in %v", time.Since(start)) // Verify correct number remain - files, err := repos.Files.ListByPrefix(ctx, "/large/") + files, err := repos.Files.ListUnderPath(ctx, "/large/") if err != nil { t.Fatal(err) } @@ -606,8 +614,7 @@ func TestTimezoneHandling(t *testing.T) { t.Skip("timezone not available") } - // Use Truncate to remove sub-second precision since we store as Unix timestamps - nyTime := time.Now().In(loc).Truncate(time.Second) + nyTime := time.Now().In(loc) file := &File{ Path: "/timezone-test.txt", MTime: nyTime, diff --git a/internal/database/schema/001.sql b/internal/database/schema/001.sql index 944c3a6..9c541d6 100644 --- a/internal/database/schema/001.sql +++ b/internal/database/schema/001.sql @@ -5,8 +5,9 @@ CREATE TABLE IF NOT EXISTS files ( id TEXT PRIMARY KEY, -- UUID path TEXT NOT NULL UNIQUE, - source_path TEXT NOT NULL DEFAULT '', -- The source directory this file came from (for restore path stripping) - mtime INTEGER NOT NULL, + source_path TEXT NOT NULL DEFAULT '', -- The source directory this file came from + mtime INTEGER NOT NULL, -- whole seconds since the Unix epoch + mtime_nsec INTEGER NOT NULL, -- nanoseconds within that second, 0 to 999999999 size INTEGER NOT NULL, mode INTEGER NOT NULL, uid INTEGER NOT NULL, @@ -85,8 +86,10 @@ CREATE TABLE IF NOT EXISTS snapshots ( completed_at INTEGER, file_count INTEGER NOT NULL DEFAULT 0, chunk_count INTEGER NOT NULL DEFAULT 0, + new_chunk_size INTEGER NOT NULL DEFAULT 0, blob_count INTEGER NOT NULL DEFAULT 0, total_size INTEGER NOT NULL DEFAULT 0, + uncompressed_chunk_size INTEGER NOT NULL DEFAULT 0, blob_size INTEGER NOT NULL DEFAULT 0, blob_uncompressed_size INTEGER NOT NULL DEFAULT 0, compression_ratio REAL NOT NULL DEFAULT 1.0, @@ -120,6 +123,16 @@ CREATE TABLE IF NOT EXISTS snapshot_blobs ( -- Index for efficient blob lookups (used in orphan detection) CREATE INDEX IF NOT EXISTS idx_snapshot_blobs_blob_id ON snapshot_blobs(blob_id); +-- Snapshot mount points table: the directories at or below a configured +-- path that the snapshot's backup found on a different filesystem from +-- their parent directory, as a mount point is, and found an entry in +CREATE TABLE IF NOT EXISTS snapshot_mount_points ( + snapshot_id TEXT NOT NULL, + path TEXT NOT NULL, + PRIMARY KEY (snapshot_id, path), + FOREIGN KEY (snapshot_id) REFERENCES snapshots(id) ON DELETE CASCADE +); + -- Uploads table: tracks blob upload metrics CREATE TABLE IF NOT EXISTS uploads ( blob_hash TEXT PRIMARY KEY, diff --git a/internal/database/snapshots.go b/internal/database/snapshots.go index 07c8242..61b97a0 100644 --- a/internal/database/snapshots.go +++ b/internal/database/snapshots.go @@ -24,7 +24,8 @@ var ( ) // SnapshotRepository provides access to the snapshots table and its -// snapshot_files / snapshot_blobs association tables. +// snapshot_files / snapshot_blobs association tables, and to the mount +// points each snapshot's backup found (snapshot_mount_points). type SnapshotRepository struct { db *DB } @@ -120,14 +121,20 @@ func (r *SnapshotRepository) UpdateCounts( return nil } -// UpdateExtendedStats updates extended statistics for a snapshot +// UpdateExtendedStats updates extended statistics for a snapshot. It also +// records the total plaintext size of the distinct chunks the snapshot's +// files reference. Only the snapshot's own backup can take that total: a +// file's row is shared by every snapshot that lists it, and a later +// backup of a changed file rewrites the row with the new chunks. func (r *SnapshotRepository) UpdateExtendedStats( ctx context.Context, tx *sql.Tx, snapshotID string, blobUncompressedSize int64, compressionLevel int, + uploadBytes int64, uploadDurationMs int64, + newChunkSize int64, ) error { compressionRatio, err := r.extendedCompressionRatio( ctx, tx, snapshotID, blobUncompressedSize, @@ -141,19 +148,30 @@ func (r *SnapshotRepository) UpdateExtendedStats( SET blob_uncompressed_size = ?, compression_ratio = ?, compression_level = ?, - upload_bytes = blob_size, - upload_duration_ms = ? + upload_bytes = ?, + upload_duration_ms = ?, + new_chunk_size = ?, + uncompressed_chunk_size = ( + SELECT COALESCE(SUM(c.size), 0) + FROM ( + SELECT DISTINCT fc.chunk_hash + FROM snapshot_files sf + JOIN file_chunks fc ON sf.file_id = fc.file_id + WHERE sf.snapshot_id = snapshots.id + ) sc + JOIN chunks c ON sc.chunk_hash = c.chunk_hash + ) WHERE id = ? ` if tx != nil { _, err = tx.ExecContext(ctx, query, blobUncompressedSize, compressionRatio, compressionLevel, - uploadDurationMs, snapshotID) + uploadBytes, uploadDurationMs, newChunkSize, snapshotID) } else { _, err = r.db.ExecWithLog(ctx, query, blobUncompressedSize, compressionRatio, compressionLevel, - uploadDurationMs, snapshotID) + uploadBytes, uploadDurationMs, newChunkSize, snapshotID) } if err != nil { @@ -220,10 +238,11 @@ func (r *SnapshotRepository) GetByID( // GetOnlySnapshot returns the sole snapshot in an exported per-snapshot // metadata database. The backup path writes each snapshot's database with -// exactly one snapshot row (see cleanSnapshotDB), so restore and deep -// verify expect exactly one. Zero rows return ErrNoSnapshotInDatabase and -// more than one returns ErrMultipleSnapshotsInDatabase; callers treat -// either as a failed identity check on the downloaded database. +// exactly one snapshot row (see cleanSnapshotDB), so restore, deep verify +// and `snapshot files` expect exactly one. Zero rows return +// ErrNoSnapshotInDatabase and more than one returns +// ErrMultipleSnapshotsInDatabase; callers treat either as a failed +// identity check on the downloaded database. func (r *SnapshotRepository) GetOnlySnapshot(ctx context.Context) (*Snapshot, error) { query := ` SELECT id, hostname, vaultik_version, vaultik_git_revision, @@ -238,12 +257,7 @@ func (r *SnapshotRepository) GetOnlySnapshot(ctx context.Context) (*Snapshot, er return nil, fmt.Errorf("querying snapshots: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() snapshots, err := r.scanSnapshotRows(rows) if err != nil { @@ -278,12 +292,7 @@ func (r *SnapshotRepository) ListRecent( return nil, fmt.Errorf("querying snapshots: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanSnapshotRows(rows) } @@ -395,7 +404,7 @@ func (r *SnapshotRepository) AddFilesByIDBatch( args = append(args, snapshotID, fileID.String()) } - query += querySb312.String() //nolint:gosec // G202: appends "?" placeholders only + query += querySb312.String() var err error if tx != nil { @@ -487,38 +496,63 @@ func (r *SnapshotRepository) GetBlobHashes( ctx context.Context, snapshotID string, ) ([]string, error) { query := ` - SELECT sb.blob_hash + SELECT sb.blob_hash FROM snapshot_blobs sb WHERE sb.snapshot_id = ? ORDER BY sb.blob_hash ` - rows, err := r.db.conn.QueryContext(ctx, query, snapshotID) + blobs, err := r.queryStrings(ctx, query, snapshotID) if err != nil { return nil, fmt.Errorf("querying blob hashes: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + return blobs, nil +} - var blobs []string +// AddMountPoint records dir as a directory that the backup of a snapshot +// found on a different filesystem from its parent directory, as a mount +// point is, using tx when non-nil. +func (r *SnapshotRepository) AddMountPoint( + ctx context.Context, tx *sql.Tx, snapshotID string, dir string, +) error { + query := ` + INSERT OR IGNORE INTO snapshot_mount_points (snapshot_id, path) + VALUES (?, ?) + ` - for rows.Next() { - var blobHash string - - err := rows.Scan(&blobHash) - if err != nil { - return nil, fmt.Errorf("scanning blob hash: %w", err) - } - - blobs = append(blobs, blobHash) + var err error + if tx != nil { + _, err = tx.ExecContext(ctx, query, snapshotID, dir) + } else { + _, err = r.db.ExecWithLog(ctx, query, snapshotID, dir) } - return blobs, rows.Err() + if err != nil { + return fmt.Errorf("adding mount point to snapshot: %w", err) + } + + return nil +} + +// GetMountPoints returns the directories AddMountPoint recorded for a +// snapshot, sorted. +func (r *SnapshotRepository) GetMountPoints( + ctx context.Context, snapshotID string, +) ([]string, error) { + query := ` + SELECT path + FROM snapshot_mount_points + WHERE snapshot_id = ? + ORDER BY path + ` + + dirs, err := r.queryStrings(ctx, query, snapshotID) + if err != nil { + return nil, fmt.Errorf("querying mount points: %w", err) + } + + return dirs, nil } // GetSnapshotTotalCompressedSize returns the total compressed size of all @@ -543,71 +577,66 @@ func (r *SnapshotRepository) GetSnapshotTotalCompressedSize( return totalSize, nil } -// GetSnapshotUncompressedChunkSize returns the sum of plaintext sizes of all unique -// chunks referenced by a snapshot (via snapshot_files → file_chunks → chunks). +// GetSnapshotBlobSizes returns the total compressed and uncompressed sizes +// of all blobs referenced by a snapshot. +func (r *SnapshotRepository) GetSnapshotBlobSizes( + ctx context.Context, snapshotID string, +) (int64, int64, error) { + query := ` + SELECT COALESCE(SUM(b.compressed_size), 0), + COALESCE(SUM(b.uncompressed_size), 0) + FROM snapshot_blobs sb + JOIN blobs b ON sb.blob_hash = b.blob_hash + WHERE sb.snapshot_id = ? + ` + + var compressed, uncompressed int64 + + err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan( + &compressed, &uncompressed) + if err != nil { + return 0, 0, fmt.Errorf("querying snapshot blob sizes: %w", err) + } + + return compressed, uncompressed, nil +} + +// GetSnapshotUncompressedChunkSize returns the total plaintext size of the +// distinct chunks the snapshot's files reference, as the snapshot's backup +// recorded it (see UpdateExtendedStats). func (r *SnapshotRepository) GetSnapshotUncompressedChunkSize( ctx context.Context, snapshotID string, ) (int64, error) { - query := ` - SELECT COALESCE(SUM(c.size), 0) - FROM ( - SELECT DISTINCT fc.chunk_hash - FROM snapshot_files sf - JOIN file_chunks fc ON sf.file_id = fc.file_id - WHERE sf.snapshot_id = ? - ) sc - JOIN chunks c ON sc.chunk_hash = c.chunk_hash - ` + query := `SELECT uncompressed_chunk_size FROM snapshots WHERE id = ?` - var totalSize int64 + var uncompressedChunkSize int64 - err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(&totalSize) + err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(&uncompressedChunkSize) if err != nil { return 0, fmt.Errorf("querying uncompressed chunk size: %w", err) } - return totalSize, nil + return uncompressedChunkSize, nil } -// GetSnapshotNewChunkSize returns the sum of plaintext sizes of chunks that are -// referenced by this snapshot but not by any earlier completed snapshot known to -// the local database. The result is the marginal uncompressed data this snapshot -// added to the dedup pool — i.e., the delta from prior snapshots. +// GetSnapshotNewChunkSize returns the total plaintext size of the chunks the +// snapshot's backup stored that were not stored before, as the backup +// recorded it. It is not derived from the snapshot's files: a file's row is +// shared by every snapshot that lists it and is rewritten when the file +// changes, so it shows only the file's latest chunks. func (r *SnapshotRepository) GetSnapshotNewChunkSize( ctx context.Context, snapshotID string, ) (int64, error) { - query := ` - WITH this_snap_chunks AS ( - SELECT DISTINCT fc.chunk_hash - FROM snapshot_files sf - JOIN file_chunks fc ON sf.file_id = fc.file_id - WHERE sf.snapshot_id = ? - ), - prior_chunks AS ( - SELECT DISTINCT fc.chunk_hash - FROM snapshots s - JOIN snapshot_files sf ON sf.snapshot_id = s.id - JOIN file_chunks fc ON fc.file_id = sf.file_id - WHERE s.completed_at IS NOT NULL - AND s.id != ? - AND s.started_at < (SELECT started_at FROM snapshots WHERE id = ?) - ) - SELECT COALESCE(SUM(c.size), 0) - FROM chunks c - JOIN this_snap_chunks t ON c.chunk_hash = t.chunk_hash - WHERE c.chunk_hash NOT IN (SELECT chunk_hash FROM prior_chunks) - ` + query := `SELECT new_chunk_size FROM snapshots WHERE id = ?` - var totalSize int64 + var newChunkSize int64 - err := r.db.conn.QueryRowContext( - ctx, query, snapshotID, snapshotID, snapshotID, - ).Scan(&totalSize) + err := r.db.conn.QueryRowContext(ctx, query, snapshotID).Scan(&newChunkSize) if err != nil { return 0, fmt.Errorf("querying new chunk size: %w", err) } - return totalSize, nil + return newChunkSize, nil } // GetIncompleteSnapshots returns all snapshots that haven't been completed @@ -628,12 +657,7 @@ func (r *SnapshotRepository) GetIncompleteSnapshots( return nil, fmt.Errorf("querying incomplete snapshots: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() return r.scanSnapshotRows(rows) } @@ -656,12 +680,7 @@ func (r *SnapshotRepository) GetIncompleteByHostname( return nil, fmt.Errorf("querying incomplete snapshots: %w", err) } - defer func() { - err := rows.Close() - if err != nil { - Fatalf("failed to close rows: %v", err) - } - }() + defer func() { _ = rows.Close() }() // Same column set as every other multi-row snapshot query, so the // shared scanner applies — including its timestamp normalization. @@ -722,6 +741,34 @@ func (r *SnapshotRepository) DeleteSnapshotUploads( return nil } +// queryStrings runs query, which selects one text column, and returns +// its values in the order of the rows. +func (r *SnapshotRepository) queryStrings( + ctx context.Context, query string, args ...any, +) ([]string, error) { + rows, err := r.db.conn.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + + defer func() { _ = rows.Close() }() + + var values []string + + for rows.Next() { + var value string + + err := rows.Scan(&value) + if err != nil { + return nil, err + } + + values = append(values, value) + } + + return values, rows.Err() +} + // extendedCompressionRatio computes the compression ratio for a snapshot // from its stored blob_size and the given uncompressed size. Returns 1.0 // when the uncompressed size is zero. diff --git a/internal/database/snapshots_test.go b/internal/database/snapshots_test.go index 9d07c8e..bc943fc 100644 --- a/internal/database/snapshots_test.go +++ b/internal/database/snapshots_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "math" + "slices" "testing" "time" @@ -145,6 +146,65 @@ func TestSnapshotRepositoryUpdateCounts(t *testing.T) { } } +// GetSnapshotBlobSizes totals the blobs the snapshot references, and only +// those. +func TestSnapshotRepositoryGetSnapshotBlobSizes(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repos := database.NewRepositories(db) + + snapshot := &database.Snapshot{ + ID: "2024-01-03T12:00:00Z", + Hostname: testHostname, + VaultikVersion: testVersion, + StartedAt: time.Now().Truncate(time.Second), + } + + err := repos.Snapshots.Create(ctx, nil, snapshot) + if err != nil { + t.Fatalf("failed to create snapshot: %v", err) + } + + blobs := []*database.Blob{ + {Hash: "referenced-1", CompressedSize: 10, UncompressedSize: 100}, + {Hash: "referenced-2", CompressedSize: 20, UncompressedSize: 200}, + {Hash: "unreferenced", CompressedSize: 40, UncompressedSize: 400}, + } + + for _, blob := range blobs { + blob.ID = types.NewBlobID() + blob.CreatedTS = time.Now().Truncate(time.Second) + + err = repos.Blobs.Create(ctx, nil, blob) + if err != nil { + t.Fatalf("failed to create blob %s: %v", blob.Hash, err) + } + } + + for _, blob := range blobs[:2] { + err = repos.Snapshots.AddBlob(ctx, nil, snapshot.ID.String(), + blob.ID, blob.Hash) + if err != nil { + t.Fatalf("failed to add blob %s to snapshot: %v", blob.Hash, err) + } + } + + compressed, uncompressed, err := repos.Snapshots.GetSnapshotBlobSizes( + ctx, snapshot.ID.String()) + if err != nil { + t.Fatalf("failed to get snapshot blob sizes: %v", err) + } + + if compressed != 30 || uncompressed != 300 { + t.Errorf("blob sizes: got %d and %d, want 30 and 300", + compressed, uncompressed) + } +} + func TestSnapshotRepositoryListRecent(t *testing.T) { t.Parallel() @@ -363,3 +423,52 @@ func TestSnapshotRepositoryDuplicate(t *testing.T) { t.Error("expected error for duplicate snapshot") } } + +// Deleting a snapshot from the local index deletes the mount points its +// backup recorded, and no other snapshot's. See +// https://git.eeqj.de/sneak/vaultik/issues/395. +func TestSnapshotRepositoryDeleteRemovesMountPoints(t *testing.T) { + t.Parallel() + + db, cleanup := setupTestDB(t) + defer cleanup() + + ctx := context.Background() + repo := database.NewSnapshotRepository(db) + + for _, id := range []types.SnapshotID{"kept", "deleted"} { + err := repo.Create(ctx, nil, &database.Snapshot{ + ID: id, + Hostname: testHostname, + VaultikVersion: testVersion, + StartedAt: time.Now().Truncate(time.Second), + }) + if err != nil { + t.Fatalf("failed to create snapshot: %v", err) + } + + err = repo.AddMountPoint(ctx, nil, id.String(), "/data/nas") + if err != nil { + t.Fatalf("failed to add mount point: %v", err) + } + } + + err := repo.Delete(ctx, "deleted") + if err != nil { + t.Fatalf("failed to delete snapshot: %v", err) + } + + for id, want := range map[string][]string{ + "kept": {"/data/nas"}, + "deleted": nil, + } { + got, err := repo.GetMountPoints(ctx, id) + if err != nil { + t.Fatalf("failed to read mount points: %v", err) + } + + if !slices.Equal(got, want) { + t.Errorf("mount points of %s: got %v, want %v", id, got, want) + } + } +} diff --git a/internal/database/uploads.go b/internal/database/uploads.go index 312373e..7939089 100644 --- a/internal/database/uploads.go +++ b/internal/database/uploads.go @@ -158,19 +158,3 @@ type UploadStats struct { MinDurationMs int64 MaxDurationMs int64 } - -// GetCountBySnapshot returns the count of uploads for a specific snapshot -func (r *UploadRepository) GetCountBySnapshot( - ctx context.Context, snapshotID string, -) (int64, error) { - query := `SELECT COUNT(*) FROM uploads WHERE snapshot_id = ?` - - var count int64 - - err := r.conn.QueryRowContext(ctx, query, snapshotID).Scan(&count) - if err != nil { - return 0, err - } - - return count, nil -} diff --git a/internal/exclude/exclude.go b/internal/exclude/exclude.go new file mode 100644 index 0000000..e386cc9 --- /dev/null +++ b/internal/exclude/exclude.go @@ -0,0 +1,77 @@ +// Package exclude compiles exclude patterns into globs. +package exclude + +import ( + "errors" + "fmt" + "strings" + + "github.com/gobwas/glob" +) + +var errBadExcludePattern = errors.New("is not a valid exclude pattern") + +// Compile compiles one exclude pattern into the globs that match it. +// anchored reports whether the pattern matches only from the root of the +// source directory. An empty pattern yields no globs. Config.Validate and +// the scanner both compile patterns with it, so a pattern that loads is one +// the scanner can use. +func Compile(pattern string) ([]glob.Glob, bool, error) { + if pattern == "" { + return nil, false, nil + } + + // A leading "/" anchors the pattern to the source directory. + trimmed, anchored := strings.CutPrefix(pattern, "/") + + // A trailing "/" marks a directory and is not matched. + trimmed = strings.TrimSuffix(trimmed, "/") + + // A leading "**/" demands a "/" before the name and so misses an + // entry directly under the source path. It means "at every depth", + // which is what an unanchored pattern already does, so drop the + // prefix and match unanchored: as in gitignore, "**/x" and + // "/**/x" then also match a top-level "x". + if rest, found := strings.CutPrefix(trimmed, "**/"); found { + trimmed = rest + anchored = false + } + + // Likewise "/**/" inside a pattern demands two slashes, so + // "a/**/*.log" misses "a/x.log". As in gitignore it stands for + // zero or more directories, so also compile the pattern with it + // made a single "/". The glob library's {a,b} is no help: with a + // "**" inside it in mid-pattern, it misses paths it should match. + var globs []glob.Glob + + for _, variant := range doubleStarVariants(trimmed) { + g, err := glob.Compile(variant, '/') + if err != nil { + return nil, false, fmt.Errorf("%q %w: %w", + pattern, errBadExcludePattern, err) + } + + globs = append(globs, g) + } + + return globs, anchored, nil +} + +// doubleStarVariants returns pattern once for every way of keeping each +// "/**/" in it or making it a single "/". +func doubleStarVariants(pattern string) []string { + const doubleStar = "/**/" + + before, after, found := strings.Cut(pattern, doubleStar) + if !found { + return []string{pattern} + } + + var variants []string + + for _, rest := range doubleStarVariants(after) { + variants = append(variants, before+doubleStar+rest, before+"/"+rest) + } + + return variants +} diff --git a/internal/exclude/exclude_test.go b/internal/exclude/exclude_test.go new file mode 100644 index 0000000..a49b657 --- /dev/null +++ b/internal/exclude/exclude_test.go @@ -0,0 +1,73 @@ +package exclude_test + +import ( + "slices" + "strings" + "testing" + + "github.com/gobwas/glob" + "sneak.berlin/go/vaultik/internal/exclude" +) + +// TestCompile checks the error, the anchoring and the globs that Compile +// returns for one exclude pattern. +func TestCompile(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + pattern string + wantErr string + wantAnchored bool + // wantMatches lists paths that one of the globs must match. When + // it is empty, Compile must return no globs. + wantMatches []string + }{ + {name: "does not compile", pattern: "build[", + wantErr: `"build[" is not a valid exclude pattern`}, + {name: "empty", pattern: ""}, + {name: "leading slash anchors", pattern: "/build", + wantAnchored: true, wantMatches: []string{"build"}}, + {name: "double star after the slash clears anchoring", + pattern: "/**/build", wantMatches: []string{"build"}}, + {name: "double star in the middle", pattern: "a/**/*.log", + wantMatches: []string{"a/x.log", "a/b/x.log"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + globs, anchored, err := exclude.Compile(tt.pattern) + if tt.wantErr == "" && err != nil { + t.Fatalf("Compile(%q) error = %v, want none", tt.pattern, err) + } + + if tt.wantErr != "" && + (err == nil || !strings.HasPrefix(err.Error(), tt.wantErr)) { + t.Fatalf("Compile(%q) error = %v, want one starting with %q", + tt.pattern, err, tt.wantErr) + } + + if anchored != tt.wantAnchored { + t.Errorf("Compile(%q) anchored = %t, want %t", + tt.pattern, anchored, tt.wantAnchored) + } + + if len(tt.wantMatches) == 0 && len(globs) != 0 { + t.Errorf("Compile(%q) returned %d globs, want none", + tt.pattern, len(globs)) + } + + for _, path := range tt.wantMatches { + matched := slices.ContainsFunc(globs, func(g glob.Glob) bool { + return g.Match(path) + }) + if !matched { + t.Errorf("Compile(%q) globs do not match %q", + tt.pattern, path) + } + } + }) + } +} diff --git a/internal/globals/globals.go b/internal/globals/globals.go index 09233f9..017cda0 100644 --- a/internal/globals/globals.go +++ b/internal/globals/globals.go @@ -1,31 +1,89 @@ // Package globals holds application-wide metadata (name, version, -// commit) that is populated at build time via linker flags. +// commit) that is populated at build time via linker flags, or from the +// build info Go records in the binary when the linker flags set none. package globals import ( + "regexp" + "runtime/debug" "strings" "time" + + "golang.org/x/mod/module" ) // Appname is the application name, populated from main(). var Appname = "vaultik" //nolint:gochecknoglobals // set via -ldflags at build time -// DevVersion is the version a binary reports when it was not built -// from a tagged commit. script/version emits either this exact string -// (outside a git checkout) or this string followed by "-" and the -// commit it was built from, and goreleaser's snapshot template matches -// that shape. It is deliberately not a number: a build that is not a -// release must not name itself like one. +// DevVersion is the version a binary reports when it was built without +// git metadata: script/version emits it outside a git checkout, and a +// binary keeps it when neither its linker flags nor its Go build info +// name a version. goreleaser's snapshot template stamps +// it followed by "-" and the commit it was built from. It is +// deliberately not a number. const DevVersion = "dev" +// Unknown is what Commit and CommitDate hold when the build did not +// stamp them, and the version script/docker and script/cibuild stamp +// when the host has no git checkout. +const Unknown = "unknown" + // Version is the application version, populated from main(). var Version = DevVersion //nolint:gochecknoglobals // set via -ldflags at build time // Commit is the git commit hash, populated from main(). -var Commit = "unknown" //nolint:gochecknoglobals // set via -ldflags at build time +var Commit = Unknown //nolint:gochecknoglobals // set via -ldflags at build time // CommitDate is the ISO-8601 date of the commit, populated from main(). -var CommitDate = "unknown" //nolint:gochecknoglobals // set via -ldflags at build time +var CommitDate = Unknown //nolint:gochecknoglobals // set via -ldflags at build time + +// develVersion is the main module version Go records when it cannot +// tell which version it built. +const develVersion = "(devel)" + +// FillUnsetFromBuildInfo applies FillUnset to Version, Commit and +// CommitDate, with the build info of the running binary. +func FillUnsetFromBuildInfo() { + info, ok := debug.ReadBuildInfo() + if !ok { + return + } + + Version, Commit, CommitDate = FillUnset( + info, Version, Commit, CommitDate) +} + +// FillUnset returns version, commit and commitDate. Each one that +// still holds its default ("dev" or empty for the version, "unknown" +// for the others) is replaced by the value Go recorded in info. A +// `go install` of a tag sets no linker flags, but Go records the tag +// as the main module's version. Go records the commit and its time +// only when it builds from a git checkout. The time is cut to a date, +// as the Makefile stamps it. +func FillUnset( + info *debug.BuildInfo, version, commit, commitDate string, +) (string, string, string) { + if (version == "" || version == DevVersion) && + info.Main.Version != "" && info.Main.Version != develVersion { + version = info.Main.Version + } + + for _, s := range info.Settings { + switch s.Key { + case "vcs.revision": + if commit == Unknown { + commit = s.Value + } + case "vcs.time": + t, err := time.Parse(time.RFC3339, s.Value) + if commitDate == Unknown && err == nil { + commitDate = t.UTC().Format(time.DateOnly) + } + } + } + + return version, commit, commitDate +} // Author identifies the upstream author of vaultik. const Author = "Jeffrey Paul " @@ -60,18 +118,31 @@ func New() (*Globals, error) { } // IsDevVersion reports whether v names a development build rather than -// a release. Both "dev" and "dev-" (and its "-dirty" variant) -// count: a caller that compares against "dev" exactly would treat every -// commit-stamped development build as a release. +// a release. "dev" and goreleaser's snapshot "dev-" count, and so +// does what `git describe --tags --always --dirty` gives a make or +// docker build of an untagged commit: the bare short commit, or +// tag-N-gHASH on a commit after a tag. A Go pseudo-version counts: Go +// records one for a build of an untagged commit without linker flags. +// Any version ending in "-dirty" or "+dirty" counts, a modified +// checkout of a tag ("v1.0.0-dirty", "v1.0.0+dirty") included. +// A plain tag such as "v1.0.0" or "1.0.0" is a release. // // The empty string counts too. Nothing that knows its version reports // no version, so an empty Version means the stamping failed, and the // safe reading of "we could not establish that this is a release" is // that it is not one. The Makefile refuses to build at all in that // case; this is the second line of defence, for a binary linked by -// something other than the Makefile. +// something other than the Makefile. Unknown counts for the same +// reason. func IsDevVersion(v string) bool { - return v == "" || v == DevVersion || strings.HasPrefix(v, DevVersion+"-") + if v == "" || v == Unknown || v == DevVersion || + strings.HasPrefix(v, DevVersion+"-") || + strings.HasSuffix(v, "-dirty") || strings.HasSuffix(v, "+dirty") || + module.IsPseudoVersion(v) { + return true + } + + return regexp.MustCompile(`^(.+-[0-9]+-g)?[0-9a-f]+$`).MatchString(v) } // shortCommitLen is the number of commit-hash characters ShortCommit keeps. diff --git a/internal/globals/globals_test.go b/internal/globals/globals_test.go index e0b7c2e..6a82a30 100644 --- a/internal/globals/globals_test.go +++ b/internal/globals/globals_test.go @@ -1,6 +1,7 @@ package globals_test import ( + "runtime/debug" "testing" "sneak.berlin/go/vaultik/internal/globals" @@ -34,10 +35,11 @@ func TestGlobalsNew(t *testing.T) { } // TestIsDevVersion covers the boundary that matters: everything -// script/version and goreleaser's snapshot template can emit for an -// untagged build must be recognised as a development build, and a real -// tag must not be. A plain equality check against "dev" used to decide -// this, which classified every commit-stamped dev build as a release. +// script/version, a plain docker build and goreleaser's snapshot +// template can emit for an untagged build must be recognised as a +// development build, and a real tag must not be. A plain equality check +// against "dev" used to decide this, which classified every +// commit-stamped dev build as a release. func TestIsDevVersion(t *testing.T) { t.Parallel() @@ -49,12 +51,29 @@ func TestIsDevVersion(t *testing.T) { {"dev", true}, {"dev-b6e4a218a39e", true}, {"dev-b6e4a218a39e-dirty", true}, - // What a tagged build produces (script/version strips the - // leading "v", matching goreleaser's .Version). + // What `git describe --tags --always --dirty` produces with no + // tag reachable, and on a commit after a tag. + {"877eb2f", true}, + {"877eb2f-dirty", true}, + {"v1.0.0-3-g877eb2f", true}, + {"v1.0.0-3-g877eb2f-dirty", true}, + {"1.0.0-rc.1-12-g877eb2f", true}, + // A tagged commit with uncommitted changes is not that tag. + {"v1.0.0-dirty", true}, + // What Go records for a build without linker flags: a + // pseudo-version for an untagged commit, "+dirty" for a + // modified checkout. + {"v1.0.0-rc3.0.20261111001226-abcdefabcdef", true}, + {"v0.0.0-20261111001226-abcdefabcdef", true}, + {"v1.0.1-0.20261111001226-abcdefabcdef", true}, + {"v1.0.0+dirty", true}, + // What a tagged build produces (goreleaser's .Version strips + // the leading "v"; script/version keeps it). {"1.0.0", false}, {"0.1.0", false}, {"1.0.0-rc.1", false}, {"v1.0.0", false}, + {"v1.0.0-rc3", false}, // A release must not be mistaken for a dev build just because // the string happens to contain "dev". {"1.0.0-dev", false}, @@ -64,6 +83,9 @@ func TestIsDevVersion(t *testing.T) { // as one. The Makefile refuses to build when script/version // yields nothing; this covers a binary linked some other way. {"", true}, + // What script/docker and script/cibuild stamp when the host + // has no git checkout. + {"unknown", true}, } for _, tc := range cases { @@ -73,10 +95,9 @@ func TestIsDevVersion(t *testing.T) { } } -// TestDefaultVersionIsDev pins the linker-flag contract: an unstamped -// binary (no -ldflags at all, which is what `go build ./...` and `go -// install` produce) must report itself as a development build rather -// than as some default release number. +// TestDefaultVersionIsDev pins the default: a binary whose linker flags +// and build info name no version must report itself as a development +// build rather than as some default release number. func TestDefaultVersionIsDev(t *testing.T) { t.Parallel() @@ -85,3 +106,104 @@ func TestDefaultVersionIsDev(t *testing.T) { globals.DevVersion) } } + +// buildInfo returns build info with the given main module version and, +// when revision is not empty, the commit settings Go records for a +// build from a git checkout. +func buildInfo(version, revision string) *debug.BuildInfo { + info := &debug.BuildInfo{ + Main: debug.Module{Path: "sneak.berlin/go/vaultik", Version: version}, + } + + if revision != "" { + info.Settings = []debug.BuildSetting{ + {Key: "vcs.revision", Value: revision}, + {Key: "vcs.time", Value: "2026-11-10T23:12:26Z"}, + } + } + + return info +} + +// TestFillUnset covers a binary from `go install` of a tag, which +// carries no linker flags: it must report the tag. Values the linker +// flags set are kept. +func TestFillUnset(t *testing.T) { + t.Parallel() + + const ( + tag = "v1.0.0-rc3" + rev = "0123456789abcdef0123456789abcdef01234567" + ) + + cases := []struct { + name string + info *debug.BuildInfo + version, commit, date string + wantVersion, wantCommit string + wantDate string + }{ + { + name: "go install of a tag", + info: buildInfo(tag, ""), + version: globals.DevVersion, + commit: globals.Unknown, + date: globals.Unknown, + wantVersion: tag, + wantCommit: globals.Unknown, + wantDate: globals.Unknown, + }, + { + name: "empty version", + info: buildInfo(tag, ""), + version: "", + commit: globals.Unknown, + date: globals.Unknown, + wantVersion: tag, + wantCommit: globals.Unknown, + wantDate: globals.Unknown, + }, + { + name: "go build in a git checkout", + info: buildInfo(tag, rev), + version: globals.DevVersion, + commit: globals.Unknown, + date: globals.Unknown, + wantVersion: tag, + wantCommit: rev, + wantDate: "2026-11-10", + }, + { + name: "Go could not tell the version", + info: buildInfo("(devel)", ""), + version: globals.DevVersion, + commit: globals.Unknown, + date: globals.Unknown, + wantVersion: globals.DevVersion, + wantCommit: globals.Unknown, + wantDate: globals.Unknown, + }, + { + name: "linker flags set", + info: buildInfo(tag, rev), + version: "v1.0.0-rc2-4-gabcdef1", + commit: "abcdef1", + date: "2026-11-01", + wantVersion: "v1.0.0-rc2-4-gabcdef1", + wantCommit: "abcdef1", + wantDate: "2026-11-01", + }, + } + + for _, tc := range cases { + version, commit, date := globals.FillUnset( + tc.info, tc.version, tc.commit, tc.date) + + if version != tc.wantVersion || commit != tc.wantCommit || + date != tc.wantDate { + t.Errorf("%s: got %q, %q, %q; want %q, %q, %q", tc.name, + version, commit, date, + tc.wantVersion, tc.wantCommit, tc.wantDate) + } + } +} diff --git a/internal/log/tty_handler.go b/internal/log/tty_handler.go index 63f0dc4..fbcef68 100644 --- a/internal/log/tty_handler.go +++ b/internal/log/tty_handler.go @@ -10,6 +10,8 @@ import ( "sync" "time" "unicode" + + "github.com/dustin/go-humanize" ) // groupSeparator joins an open group path to an attribute key. This @@ -304,18 +306,13 @@ func formatDuration(d time.Duration) string { } } -// formatBytes formats bytes in a human-readable way +// formatBytes formats a byte count with humanize.Bytes, as every command +// prints one. humanize.Bytes takes no negative count, so one is printed +// as it is. func formatBytes(b int64) string { - const unit = 1024 - if b < unit { + if b < 0 { return fmt.Sprintf("%d B", b) } - div, exp := int64(unit), 0 - for n := b / unit; n >= unit; n /= unit { - div *= unit - exp++ - } - - return fmt.Sprintf("%.1f %cB", float64(b)/float64(div), "KMGTPE"[exp]) + return humanize.Bytes(uint64(b)) } diff --git a/internal/log/tty_handler_test.go b/internal/log/tty_handler_test.go index 694657f..8d0819d 100644 --- a/internal/log/tty_handler_test.go +++ b/internal/log/tty_handler_test.go @@ -200,7 +200,8 @@ func TestTTYHandlerWithGroupQualifiesKeys(t *testing.T) { func TestTTYHandlerByteFormattingSurvivesGrouping(t *testing.T) { t.Parallel() - const oneAndAHalfKiB = 1536 + // Printed as "1.0 MB", in powers of 1000 like every other byte count. + const oneMegabyte = 1_000_000 for name, testCase := range map[string]struct { derive func(*slog.Logger) *slog.Logger @@ -223,13 +224,13 @@ func TestTTYHandlerByteFormattingSurvivesGrouping(t *testing.T) { var buf bytes.Buffer logger := slog.New(log.NewTTYHandler(&buf, debugHandlerOptions())) - testCase.derive(logger).Info("uploaded", "bytes", oneAndAHalfKiB) + testCase.derive(logger).Info("uploaded", "bytes", oneMegabyte) line := ansiEscape.ReplaceAllString(buf.String(), "") - assert.Contains(t, line, testCase.key+"=1.5 KB", + assert.Contains(t, line, testCase.key+"=1.0 MB", "a byte count must be human-readable however it is qualified") - assert.NotContains(t, line, strconv.Itoa(oneAndAHalfKiB), + assert.NotContains(t, line, strconv.Itoa(oneMegabyte), "the raw number must not survive the formatting") }) } diff --git a/internal/pidlock/pidlock.go b/internal/pidlock/pidlock.go index ea15e77..1d7145b 100644 --- a/internal/pidlock/pidlock.go +++ b/internal/pidlock/pidlock.go @@ -10,15 +10,19 @@ import ( "path/filepath" "strconv" "strings" - "syscall" + + "github.com/adrg/xdg" + "golang.org/x/sys/unix" ) // ErrAlreadyRunning indicates another vaultik instance is running. var ErrAlreadyRunning = errors.New("another vaultik instance is already running") -// Lock represents an acquired PID lock. +// Lock represents an acquired PID lock: an flock(2) on the PID file, +// held while the file stays open. The kernel drops it when the process +// exits, however it exits, so a crashed run never leaves the lock held. type Lock struct { - path string + file *os.File } const ( @@ -26,13 +30,24 @@ const ( lockDirPerm = 0o700 // pidFilePerm is the mode for the PID file (owner-only). pidFilePerm = 0o600 + // pidFileName is the name of the PID file in the lock directory. + pidFileName = "vaultik.pid" ) +// Dir returns the directory that holds vaultik's PID file. +func Dir() string { + return filepath.Join(xdg.DataHome, "vaultik") +} + +// Path returns the path of the PID file that Acquire uses in lockDir. +func Path(lockDir string) string { + return filepath.Join(lockDir, pidFileName) +} + // Acquire attempts to acquire a PID lock in the specified directory. -// If the lock file exists and the process is still running, it returns -// ErrAlreadyRunning with details about the existing process. -// On success, it writes the current PID to the lock file and returns -// a Lock that must be released with Release(). +// If another process holds the lock, it returns ErrAlreadyRunning with +// that process's PID. On success, it writes the current PID to the lock +// file and returns a Lock that must be released with Release(). func Acquire(lockDir string) (*Lock, error) { // Ensure lock directory exists err := os.MkdirAll(lockDir, lockDirPerm) @@ -40,58 +55,84 @@ func Acquire(lockDir string) (*Lock, error) { return nil, fmt.Errorf("creating lock directory: %w", err) } - lockPath := filepath.Join(lockDir, "vaultik.pid") + lockPath := Path(lockDir) - // Check for existing lock - existingPID, err := readPIDFile(lockPath) - if err == nil { - // Lock file exists, check if process is running - if isProcessRunning(existingPID) { - return nil, fmt.Errorf("%w (PID %d)", ErrAlreadyRunning, existingPID) - } - // Process is not running, stale lock file - we can take over - } - - // Write our PID - pid := os.Getpid() - - err = os.WriteFile(lockPath, []byte(strconv.Itoa(pid)), pidFilePerm) + // No O_TRUNC: the file may hold the PID of the process that has the + // lock, which the error below reports. + file, err := os.OpenFile( //nolint:gosec // G304: path is our own lock file + lockPath, os.O_RDWR|os.O_CREATE, pidFilePerm) if err != nil { - return nil, fmt.Errorf("writing PID file: %w", err) + return nil, fmt.Errorf("opening PID file: %w", err) } - return &Lock{path: lockPath}, nil + err = unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB) + if err != nil { + _ = file.Close() + + if errors.Is(err, unix.EWOULDBLOCK) { + return nil, alreadyRunningError(lockPath) + } + + return nil, fmt.Errorf("locking PID file: %w", err) + } + + err = writePID(file) + if err != nil { + _ = file.Close() + + return nil, err + } + + return &Lock{file: file}, nil } -// Release removes the PID lock file. +// Release empties the PID file and closes it, which drops the lock. // It is safe to call Release multiple times. func (l *Lock) Release() error { - if l == nil || l.path == "" { + if l == nil || l.file == nil { return nil } - // Verify we still own the lock (our PID is in the file) - existingPID, err := readPIDFile(l.path) + file := l.file + l.file = nil + + // Do not remove the file here. A process that opened it a moment + // earlier could then lock the removed file while another creates and + // locks a new one, and both would run. + truncateErr := file.Truncate(0) + closeErr := file.Close() + + return errors.Join(truncateErr, closeErr) +} + +// writePID replaces the contents of the locked PID file with the current +// PID. +func writePID(file *os.File) error { + err := file.Truncate(0) if err != nil { - // File already gone or unreadable - that's fine - return nil //nolint:nilerr // unreadable lock file means nothing to release + return fmt.Errorf("truncating PID file: %w", err) } - if existingPID != os.Getpid() { - // Someone else wrote to our lock file - don't remove it - return nil + _, err = file.WriteAt([]byte(strconv.Itoa(os.Getpid())), 0) + if err != nil { + return fmt.Errorf("writing PID file: %w", err) } - err = os.Remove(l.path) - if err != nil && !os.IsNotExist(err) { - return fmt.Errorf("removing PID file: %w", err) - } - - l.path = "" // Prevent double-release - return nil } +// alreadyRunningError reports that another process holds the lock, +// naming its PID when the file holds one. The holder writes its PID just +// after it locks, so the file can briefly be empty. +func alreadyRunningError(lockPath string) error { + pid, err := readPIDFile(lockPath) + if err != nil { + return ErrAlreadyRunning + } + + return fmt.Errorf("%w (PID %d)", ErrAlreadyRunning, pid) +} + // readPIDFile reads and parses the PID from a lock file. func readPIDFile(path string) (int, error) { data, err := os.ReadFile(path) //nolint:gosec // G304: path is our own lock file @@ -106,16 +147,3 @@ func readPIDFile(path string) (int, error) { return pid, nil } - -// isProcessRunning checks if a process with the given PID is running. -func isProcessRunning(pid int) bool { - process, err := os.FindProcess(pid) - if err != nil { - return false - } - - // On Unix, FindProcess always succeeds. We need to send signal 0 to check. - err = process.Signal(syscall.Signal(0)) - - return err == nil -} diff --git a/internal/pidlock/pidlock_test.go b/internal/pidlock/pidlock_test.go index 1f49372..25d67b1 100644 --- a/internal/pidlock/pidlock_test.go +++ b/internal/pidlock/pidlock_test.go @@ -4,6 +4,7 @@ import ( "os" "path/filepath" "strconv" + "sync" "testing" "github.com/stretchr/testify/assert" @@ -33,9 +34,10 @@ func TestAcquireAndRelease(t *testing.T) { err = lock.Release() require.NoError(t, err) - // Verify PID file is gone - _, err = os.Stat(pidPath) - assert.True(t, os.IsNotExist(err)) + // Verify PID file is empty + data, err = os.ReadFile(pidPath) //nolint:gosec // G304: test's own temp file + require.NoError(t, err) + assert.Empty(t, data) } func TestAcquireBlocksSecondInstance(t *testing.T) { @@ -55,6 +57,64 @@ func TestAcquireBlocksSecondInstance(t *testing.T) { lock2, err := pidlock.Acquire(tmpDir) require.ErrorIs(t, err, pidlock.ErrAlreadyRunning) assert.Nil(t, lock2) + + // Once the first lock is released, the next Acquire succeeds + require.NoError(t, lock1.Release()) + + lock3, err := pidlock.Acquire(tmpDir) + require.NoError(t, err) + require.NoError(t, lock3.Release()) +} + +// TestConcurrentAcquireAdmitsOne starts many Acquire calls at the same +// moment, as two cron entries firing together would, and checks that +// exactly one of them gets the lock. +func TestConcurrentAcquireAdmitsOne(t *testing.T) { + t.Parallel() + + const callers = 50 + + tmpDir := t.TempDir() + start := make(chan struct{}) + + var ( + mu sync.Mutex + acquired []*pidlock.Lock + failures []error + wg sync.WaitGroup + ) + + for range callers { + wg.Go(func() { + <-start + + lock, err := pidlock.Acquire(tmpDir) + + mu.Lock() + defer mu.Unlock() + + if err != nil { + failures = append(failures, err) + + return + } + + acquired = append(acquired, lock) + }) + } + + close(start) + wg.Wait() + + for _, lock := range acquired { + require.NoError(t, lock.Release()) + } + + assert.Len(t, acquired, 1, "exactly one caller should hold the lock") + + for _, err := range failures { + require.ErrorIs(t, err, pidlock.ErrAlreadyRunning) + } } func TestAcquireWithStaleLock(t *testing.T) { diff --git a/internal/s3/client.go b/internal/s3/client.go index b54d3f4..fe74a82 100644 --- a/internal/s3/client.go +++ b/internal/s3/client.go @@ -6,7 +6,9 @@ import ( "context" "errors" "io" + "strings" "sync/atomic" + "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" @@ -17,6 +19,13 @@ import ( "github.com/aws/smithy-go/logging" ) +// ErrNoContinuationToken is returned by ListObjects and ListObjectsStream +// when the server marks a page of a listing truncated but sends no +// continuation token to fetch the rest with, as a server answering V2 +// listings V1-style does. +var ErrNoContinuationToken = errors.New( + "server marked the listing truncated but sent no continuation token") + // Client wraps the AWS S3 client for vaultik operations. // It provides a simplified interface for S3 operations with automatic // prefix handling and connection management. All operations are performed @@ -26,10 +35,14 @@ type Client struct { bucket string prefix string endpoint string + partSize int64 } // Config contains S3 client configuration. -// All fields are required except Prefix, which defaults to an empty string. +// All fields are required except Prefix, which defaults to an empty string, +// and PartSize, where zero means the SDK default of 5 MiB. +// A non-empty Prefix is joined to every key with one "/", whether or not +// it ends with one. // The Endpoint field should include the protocol (http:// or https://). type Config struct { Endpoint string @@ -38,6 +51,9 @@ type Config struct { AccessKeyID string SecretAccessKey string Region string + // PartSize is the size in bytes of each part of a multipart upload. + // An upload too large for S3's limit of 10,000 parts gets larger parts. + PartSize int64 } // nopLogger is a logger that discards all output. @@ -75,11 +91,19 @@ func NewClient(ctx context.Context, cfg Config) (*Client, error) { s3Client := s3.NewFromConfig(awsCfg, s3Opts) + // Every method below builds a key as prefix + key, so the prefix + // must carry its own trailing "/". + prefix := strings.TrimRight(cfg.Prefix, "/") + if prefix != "" { + prefix += "/" + } + return &Client{ s3Client: s3Client, bucket: cfg.Bucket, - prefix: cfg.Prefix, + prefix: prefix, endpoint: cfg.Endpoint, + partSize: cfg.PartSize, }, nil } @@ -113,12 +137,9 @@ func (c *Client) PutObjectWithProgress( ) error { fullKey := c.prefix + key - // uploadPartSize is 10MB for better progress granularity. - const uploadPartSize = 10 * 1024 * 1024 - // Create an uploader with the S3 client uploader := manager.NewUploader(c.s3Client, func(u *manager.Uploader) { - u.PartSize = uploadPartSize + u.PartSize = uploadPartSize(c.partSize, size) }) // Create a progress reader that tracks upload progress @@ -139,6 +160,21 @@ func (c *Client) PutObjectWithProgress( return err } +// uploadPartSize returns the part size for an upload of size bytes: the +// configured part size (the SDK default when zero), raised where needed so +// the upload fits in S3's limit of 10,000 parts. The uploader cannot raise +// it itself, because it cannot seek the progress reader to learn its size. +func uploadPartSize(configured, size int64) int64 { + if configured == 0 { + configured = manager.DefaultUploadPartSize + } + + maxParts := int64(manager.MaxUploadParts) + smallestThatFits := (size + maxParts - 1) / maxParts // rounded up + + return max(configured, smallestThatFits) +} + // GetObject downloads an object from S3 with the specified key. // The key is automatically prefixed with the configured prefix. // Returns a ReadCloser containing the object data. The caller must @@ -186,7 +222,7 @@ func (c *Client) ListObjects(ctx context.Context, prefix string) ([]string, erro }) for paginator.HasMorePages() { - page, err := paginator.NextPage(ctx) + page, err := nextListPage(ctx, paginator) if err != nil { return nil, err } @@ -207,6 +243,26 @@ func (c *Client) ListObjects(ctx context.Context, prefix string) ([]string, erro return keys, nil } +// nextListPage fetches the next page of a listing. The SDK paginator takes +// a page marked truncated without a continuation token for the last page +// and stops without an error, so such a page is ErrNoContinuationToken +// here instead. +func nextListPage( + ctx context.Context, paginator *s3.ListObjectsV2Paginator, +) (*s3.ListObjectsV2Output, error) { + page, err := paginator.NextPage(ctx) + if err != nil { + return nil, err + } + + truncated := aws.ToBool(page.IsTruncated) + if truncated && aws.ToString(page.NextContinuationToken) == "" { + return nil, ErrNoContinuationToken + } + + return page, nil +} + // HeadObject checks if an object exists in S3. // Returns true if the object exists, false otherwise. // The key is automatically prefixed with the configured prefix. @@ -247,7 +303,10 @@ func IsNotFound(err error) bool { type ObjectInfo struct { Key string Size int64 - Err error + // ModTime is the object's LastModified time. Only ListObjectsStream + // sets it. + ModTime time.Time + Err error } // ListObjectsStream lists objects with the given prefix and returns a channel. @@ -272,7 +331,7 @@ func (c *Client) ListObjectsStream( }) for paginator.HasMorePages() { - page, err := paginator.NextPage(ctx) + page, err := nextListPage(ctx, paginator) if err != nil { ch <- ObjectInfo{Err: err} @@ -288,8 +347,9 @@ func (c *Client) ListObjectsStream( } ch <- ObjectInfo{ - Key: key, - Size: *obj.Size, + Key: key, + Size: *obj.Size, + ModTime: aws.ToTime(obj.LastModified), } } } diff --git a/internal/s3/client_internal_test.go b/internal/s3/client_internal_test.go new file mode 100644 index 0000000..552059d --- /dev/null +++ b/internal/s3/client_internal_test.go @@ -0,0 +1,55 @@ +package s3 + +import "testing" + +// TestUploadPartSize checks that an upload too large for 10,000 parts of the +// configured size gets parts just large enough to fit in 10,000. +func TestUploadPartSize(t *testing.T) { + t.Parallel() + + const mib = 1024 * 1024 + + tests := []struct { + name string + configured int64 + size int64 + want int64 + }{ + { + name: "an upload that fits keeps the configured size", + configured: 5 * mib, + size: 10 * 1024 * mib, + want: 5 * mib, + }, + { + name: "exactly 10,000 parts keeps the configured size", + configured: 6 * mib, + size: 10_000 * 6 * mib, + want: 6 * mib, + }, + { + name: "one byte more than 10,000 parts adds a byte to each", + configured: 6 * mib, + size: 10_000*6*mib + 1, + want: 6*mib + 1, + }, + { + name: "zero means the SDK default of 5MiB", + configured: 0, + size: 1, + want: 5 * mib, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got := uploadPartSize(tt.configured, tt.size) + if got != tt.want { + t.Errorf("uploadPartSize(%d, %d) = %d, want %d", + tt.configured, tt.size, got, tt.want) + } + }) + } +} diff --git a/internal/s3/module.go b/internal/s3/module.go index 33b24ba..71f1b88 100644 --- a/internal/s3/module.go +++ b/internal/s3/module.go @@ -28,6 +28,7 @@ func provideClient(lc fx.Lifecycle, cfg *config.Config) (*Client, error) { AccessKeyID: cfg.S3.AccessKeyID, SecretAccessKey: cfg.S3.SecretAccessKey, Region: cfg.S3.Region, + PartSize: cfg.S3.PartSize.Int64(), }) if err != nil { return nil, err diff --git a/internal/snapshot/backup_test.go b/internal/snapshot/backup_test.go index 80e0b38..f970cfb 100644 --- a/internal/snapshot/backup_test.go +++ b/internal/snapshot/backup_test.go @@ -71,7 +71,7 @@ func verifyBackupFiles( ) { t.Helper() - files, err := repos.Files.ListByPrefix(ctx, "") + files, err := repos.Files.ListAll(ctx) if err != nil { t.Fatalf("Failed to list files: %v", err) } diff --git a/internal/snapshot/blob_temp_file_test.go b/internal/snapshot/blob_temp_file_test.go new file mode 100644 index 0000000..ed03e19 --- /dev/null +++ b/internal/snapshot/blob_temp_file_test.go @@ -0,0 +1,62 @@ +//nolint:testpackage // exercises the unexported cleanupBlobTempFile +package snapshot + +import ( + "errors" + "os" + "testing" + + "github.com/spf13/afero" + "sneak.berlin/go/vaultik/internal/blob" +) + +// A blob temp file that cannot be closed or removed must make the cleanup +// return an error, not end the process. +func TestCleanupBlobTempFileReturnsErrors(t *testing.T) { + t.Parallel() + + fs := afero.NewOsFs() + s := &Scanner{fs: fs} + + tests := []struct { + name string + // prepare runs before the cleanup and makes its close or remove + // fail. + prepare func(tempFile afero.File) error + want error + }{ + { + name: "close fails", + prepare: func(tempFile afero.File) error { return tempFile.Close() }, + want: os.ErrClosed, + }, + { + name: "remove fails", + prepare: func(tempFile afero.File) error { + return fs.Remove(tempFile.Name()) + }, + want: os.ErrNotExist, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + tempFile, err := afero.TempFile(fs, t.TempDir(), "blob-*.tmp") + if err != nil { + t.Fatal(err) + } + + err = tt.prepare(tempFile) + if err != nil { + t.Fatal(err) + } + + err = s.cleanupBlobTempFile(&blob.WithReader{TempFile: tempFile}) + if !errors.Is(err, tt.want) { + t.Fatalf("expected an error wrapping %v, got: %v", tt.want, err) + } + }) + } +} diff --git a/internal/snapshot/device_number_test.go b/internal/snapshot/device_number_test.go new file mode 100644 index 0000000..85a074b --- /dev/null +++ b/internal/snapshot/device_number_test.go @@ -0,0 +1,75 @@ +//nolint:testpackage // exercises the unexported deviceNumberFromStat +package snapshot + +import ( + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The device number a real backup reads is the same for a directory and +// a file in it, and differs between the temp directory and /dev. +// Without it no mount point is ever found. See +// https://git.eeqj.de/sneak/vaultik/issues/395. +func TestDeviceNumberFromStat(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + file := filepath.Join(dir, "file.txt") + require.NoError(t, os.WriteFile(file, nil, 0o600)) + + deviceOf := func(path string) uint64 { + t.Helper() + + info, err := os.Stat(path) + require.NoError(t, err) + + device, ok := deviceNumberFromStat(info) + require.True(t, ok, "no device number read for %s", path) + + return device + } + + assert.Equal(t, deviceOf(dir), deviceOf(file)) + + // /dev is a different filesystem from the temp dir on Linux, macOS and in Docker. + assert.NotEqual(t, deviceOf(dir), deviceOf("/dev")) +} + +// fileInfoWithStat is a file's info whose Sys returns stat. +type fileInfoWithStat struct { + os.FileInfo + + stat *syscall.Stat_t +} + +func (i fileInfoWithStat) Sys() any { return i.stat } + +// The in-memory test filesystem has no device numbers. The pinned afero +// gives no stat; its unreleased master gives a stat holding only uid, gid +// and size. See https://git.eeqj.de/sneak/vaultik/issues/462. +func TestDeviceNumberFromStatInMemory(t *testing.T) { + t.Parallel() + + fs := afero.NewMemMapFs() + require.NoError(t, afero.WriteFile(fs, "/file.txt", []byte("data"), 0o600)) + + info, err := fs.Stat("/file.txt") + require.NoError(t, err) + + _, ok := deviceNumberFromStat(info) + assert.False(t, ok, "device number read from a file info with no stat") + + zeroed := fileInfoWithStat{ + FileInfo: info, + stat: &syscall.Stat_t{Uid: 1000, Gid: 1000, Size: 4}, + } + + _, ok = deviceNumberFromStat(zeroed) + assert.False(t, ok, "device number read from a stat with no device or inode number") +} diff --git a/internal/snapshot/exclude_test.go b/internal/snapshot/exclude_test.go index 9870018..c23d03e 100644 --- a/internal/snapshot/exclude_test.go +++ b/internal/snapshot/exclude_test.go @@ -531,3 +531,101 @@ func TestExcludePatterns_UnanchoredPatternFile(t *testing.T) { require.Equal(t, 1, result.FilesScanned, "Unanchored pattern for file should match anywhere") } + +func TestExcludePatterns_DoubleStarDirectoryAtEveryDepth(t *testing.T) { + t.Parallel() + + // As in gitignore, a leading **/ also matches directly under the source dir + fs := setupAnchoredTestFS(t) + + scanner, repos, cleanup := createTestScanner(t, fs, []string{"**/projectname"}) + defer cleanup() + + ctx := context.Background() + createSnapshotRecord(ctx, t, repos, "test-snapshot") + + result, err := scanner.Scan(ctx, "/backup", "test-snapshot") + require.NoError(t, err) + + // **/projectname should exclude BOTH: + // - /backup/projectname/file.txt + // - /backup/otherproject/projectname/file.txt + // Total files: 4, excluded: 2 + require.Equal(t, 2, result.FilesScanned, + "**/ directory pattern should match at the top level and nested") +} + +func TestExcludePatterns_DoubleStarFileAtEveryDepth(t *testing.T) { + t.Parallel() + + // As in gitignore, a leading **/ also matches directly under the source dir + fs := setupAnchoredTestFS(t) + + scanner, repos, cleanup := createTestScanner(t, fs, []string{"**/*.txt"}) + defer cleanup() + + ctx := context.Background() + createSnapshotRecord(ctx, t, repos, "test-snapshot") + + result, err := scanner.Scan(ctx, "/backup", "test-snapshot") + require.NoError(t, err) + + // **/*.txt should exclude ALL .txt files: + // - /backup/file.txt + // - /backup/projectname/file.txt + // - /backup/otherproject/projectname/file.txt + // Total files: 4, excluded: 3 + require.Equal(t, 1, result.FilesScanned, + "**/ file pattern should match at the top level and nested") +} + +func TestExcludePatterns_AnchoredDoubleStarAtEveryDepth(t *testing.T) { + t.Parallel() + + // As in gitignore, /**/ also matches directly under the source dir + fs := setupAnchoredTestFS(t) + + scanner, repos, cleanup := createTestScanner(t, fs, []string{"/**/projectname"}) + defer cleanup() + + ctx := context.Background() + createSnapshotRecord(ctx, t, repos, "test-snapshot") + + result, err := scanner.Scan(ctx, "/backup", "test-snapshot") + require.NoError(t, err) + + // /**/projectname should exclude BOTH: + // - /backup/projectname/file.txt + // - /backup/otherproject/projectname/file.txt + // Total files: 4, excluded: 2 + require.Equal(t, 2, result.FilesScanned, + "/**/ pattern should match at the top level and nested") +} + +func TestExcludePatterns_DoubleStarInMiddleMatchesZeroDirectories(t *testing.T) { + t.Parallel() + + // As in gitignore, a/**/b matches a/b as well as a/c/b. The last part + // is a glob: with a plain name the glob library already matched a/b. + fs := &afero.MemMapFs{} + files := []string{"/backup/a/x.log", "/backup/a/c/y.log", "/backup/a/c/kept.txt"} + + for _, path := range files { + require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0755)) + require.NoError(t, afero.WriteFile(fs, path, []byte(path), 0644)) + } + + scanner, repos, cleanup := createTestScanner(t, fs, []string{"a/**/*.log"}) + defer cleanup() + + ctx := context.Background() + createSnapshotRecord(ctx, t, repos, "test-snapshot") + + result, err := scanner.Scan(ctx, "/backup", "test-snapshot") + require.NoError(t, err) + + // a/**/*.log should exclude /backup/a/x.log and /backup/a/c/y.log + // Total files: 3, excluded: 2 + require.Equal(t, 1, result.FilesScanned, + "a/**/*.log should match a/x.log as well as a/c/y.log") +} diff --git a/internal/snapshot/export_perm_test.go b/internal/snapshot/export_perm_test.go index 84e407a..12d79e9 100644 --- a/internal/snapshot/export_perm_test.go +++ b/internal/snapshot/export_perm_test.go @@ -1,40 +1,48 @@ -//nolint:testpackage // exercises the unexported copyFile helper +//nolint:testpackage // exercises the unexported copyDatabase helper package snapshot import ( + "context" "os" "path/filepath" "syscall" "testing" "github.com/spf13/afero" + "sneak.berlin/go/vaultik/internal/database" ) -// TestCopyFileExportCopyMode verifies that the exported snapshot database -// copy is created owner-only (0600), even under a lenient 022 umask that -// would otherwise leave a fresh file world-readable. +// TestCopyDatabaseExportCopyMode verifies that the exported snapshot +// database copy is created owner-only (0600), even under a lenient 022 +// umask that would otherwise leave a fresh file world-readable. // //nolint:paralleltest // syscall.Umask is process-global; parallel tests would clash -func TestCopyFileExportCopyMode(t *testing.T) { +func TestCopyDatabaseExportCopyMode(t *testing.T) { restore := syscall.Umask(0o022) defer syscall.Umask(restore) + ctx := context.Background() dir := t.TempDir() src := filepath.Join(dir, "index.sqlite") - err := os.WriteFile(src, []byte("index data"), 0o600) + db, err := database.New(ctx, src) if err != nil { t.Fatalf("creating source index: %v", err) } + err = db.Close() + if err != nil { + t.Fatalf("closing source index: %v", err) + } + dst := filepath.Join(dir, "snapshot.db") sm := &SnapshotManager{fs: afero.NewOsFs()} - err = sm.copyFile(src, dst) + err = sm.copyDatabase(ctx, src, dst) if err != nil { - t.Fatalf("copyFile: %v", err) + t.Fatalf("copyDatabase: %v", err) } info, err := os.Stat(dst) diff --git a/internal/snapshot/index_and_lock_files_test.go b/internal/snapshot/index_and_lock_files_test.go new file mode 100644 index 0000000..3e07045 --- /dev/null +++ b/internal/snapshot/index_and_lock_files_test.go @@ -0,0 +1,65 @@ +package snapshot_test + +import ( + "context" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/snapshot" +) + +// A backup of the directory that holds vaultik's index and PID file +// stores neither, with no exclude pattern set, and still stores the +// files beside them. See https://git.eeqj.de/sneak/vaultik/issues/421. +func TestScanSkipsIndexAndLockFiles(t *testing.T) { + t.Parallel() + + const dataDir = "/home/user/.local/share/vaultik" + + indexAndLockFiles := append(database.IndexFiles(dataDir+"/index.sqlite"), + dataDir+"/vaultik.pid") + + fs := afero.NewMemMapFs() + for _, p := range append(indexAndLockFiles, dataDir+"/notes.txt") { + require.NoError(t, afero.WriteFile(fs, p, []byte("data"), 0o600)) + } + + db, err := database.NewTestDB() + require.NoError(t, err) + + defer func() { _ = db.Close() }() + + repos := database.NewRepositories(db) + + scanner := snapshot.NewScanner(snapshot.ScannerConfig{ + FS: fs, + ChunkSize: 64 * 1024, + Repositories: repos, + MaxBlobSize: 1024 * 1024, + CompressionLevel: 3, + AgeRecipients: []string{ + "age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p"}, + IndexAndLockFiles: indexAndLockFiles, + }) + require.NotNil(t, scanner) + + ctx := context.Background() + createSnapshotRecord(ctx, t, repos, "test-snapshot") + + result, err := scanner.Scan(ctx, "/home/user", "test-snapshot") + require.NoError(t, err) + + require.Equal(t, 1, result.FilesScanned) + + stored, err := repos.Files.GetByPath(ctx, dataDir+"/notes.txt") + require.NoError(t, err) + require.NotNil(t, stored, "a file beside the index is stored") + + for _, p := range indexAndLockFiles { + f, err := repos.Files.GetByPath(ctx, p) + require.NoError(t, err) + require.Nil(t, f, "%s is not stored", p) + } +} diff --git a/internal/snapshot/module.go b/internal/snapshot/module.go index fc0dfec..9edd50b 100644 --- a/internal/snapshot/module.go +++ b/internal/snapshot/module.go @@ -1,10 +1,14 @@ package snapshot import ( + "os" + "path/filepath" + "github.com/spf13/afero" "go.uber.org/fx" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/pidlock" "sneak.berlin/go/vaultik/internal/storage" "sneak.berlin/go/vaultik/internal/ui" ) @@ -16,6 +20,12 @@ type ScannerParams struct { Fs afero.Fs Exclude []string // Exclude patterns (combined global + snapshot-specific) SkipErrors bool // Skip file read errors (log loudly but continue) + // PreviousSnapshotID is the most recent completed snapshot of the + // same name, "" for none. + PreviousSnapshotID string + // DeviceNumber is ScannerConfig.DeviceNumber; nil reads it from the + // file's stat. + DeviceNumber func(info os.FileInfo) (uint64, bool) } // Module exports backup functionality as an fx module. @@ -44,17 +54,62 @@ func provideScannerFactory( } return NewScanner(ScannerConfig{ - FS: params.Fs, - ChunkSize: cfg.ChunkSize.Int64(), - Repositories: repos, - Storage: storer, - MaxBlobSize: cfg.BlobSizeLimit.Int64(), - CompressionLevel: cfg.CompressionLevel, - AgeRecipients: cfg.AgeRecipients, - EnableProgress: params.EnableProgress, - UI: params.UI, - Exclude: excludes, - SkipErrors: params.SkipErrors, + FS: params.Fs, + ChunkSize: cfg.ChunkSize.Int64(), + Repositories: repos, + Storage: storer, + MaxBlobSize: cfg.BlobSizeLimit.Int64(), + CompressionLevel: cfg.CompressionLevel, + AgeRecipients: cfg.AgeRecipients, + EnableProgress: params.EnableProgress, + UI: params.UI, + Exclude: excludes, + IndexAndLockFiles: indexAndLockFiles(cfg.IndexPath, pidlock.Dir()), + SkipErrors: params.SkipErrors, + PreviousSnapshotID: params.PreviousSnapshotID, + DeviceNumber: params.DeviceNumber, }) } } + +// indexAndLockFiles returns the paths of the index at indexPath, its side +// files and the PID file in lockDir. Symlinks in their directories are +// resolved, as they are in the snapshot's source paths, so the scan finds +// them under the same names. If indexPath is a symlink, the file it points +// to and that file's side files are returned too. +func indexAndLockFiles(indexPath, lockDir string) []string { + paths := append(database.IndexFiles(indexPath), pidlock.Path(lockDir)) + for i, p := range paths { + paths[i] = resolveParentDir(p) + } + + // SQLite writes the file a symlinked index points to and keeps the + // side files beside that file. The database package creates the index + // before the scanner is built, so the link resolves. + index := resolveParentDir(indexPath) + + target, err := filepath.EvalSymlinks(index) + if err == nil && target != index { + paths = append(paths, database.IndexFiles(target)...) + } + + return paths +} + +// resolveParentDir returns the absolute form of path with the symlinks in +// its parent directory resolved. If the parent directory cannot be +// resolved, it returns the absolute form unresolved. If path has no +// absolute form, it returns path. +func resolveParentDir(path string) string { + abs, err := filepath.Abs(path) + if err != nil { + return path + } + + dir, err := filepath.EvalSymlinks(filepath.Dir(abs)) + if err != nil { + return abs + } + + return filepath.Join(dir, filepath.Base(abs)) +} diff --git a/internal/snapshot/module_test.go b/internal/snapshot/module_test.go new file mode 100644 index 0000000..dff9b7f --- /dev/null +++ b/internal/snapshot/module_test.go @@ -0,0 +1,32 @@ +//nolint:testpackage // exercises the unexported indexAndLockFiles helper +package snapshot + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +// The scan walks source paths with symlinks resolved, so vaultik's own +// files are named the same way, or a symlinked home would back them up. +func TestIndexAndLockFilesResolvesSymlinkedDirectory(t *testing.T) { + t.Parallel() + + realDir, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + + link := filepath.Join(t.TempDir(), "link") + require.NoError(t, os.Symlink(realDir, link)) + + paths := indexAndLockFiles(filepath.Join(link, "index.sqlite"), link) + + require.Equal(t, []string{ + filepath.Join(realDir, "index.sqlite"), + filepath.Join(realDir, "index.sqlite-wal"), + filepath.Join(realDir, "index.sqlite-shm"), + filepath.Join(realDir, "index.sqlite-journal"), + filepath.Join(realDir, "vaultik.pid"), + }, paths) +} diff --git a/internal/snapshot/mount_point_test.go b/internal/snapshot/mount_point_test.go new file mode 100644 index 0000000..415fe7c --- /dev/null +++ b/internal/snapshot/mount_point_test.go @@ -0,0 +1,245 @@ +package snapshot_test + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "syscall" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/snapshot" +) + +// A scan records with the snapshot each directory on a different device +// from its parent directory that the walk found an entry in, as a mount +// point is, the scanned path included. A filesystem that gives no device +// numbers, as the in-memory one, records none. See +// https://git.eeqj.de/sneak/vaultik/issues/395. +func TestScanRecordsMountPoints(t *testing.T) { + t.Parallel() + + const ( + scannedPath = "/data/source" + snapshotID = "mount-points" + ) + + tests := []struct { + name string + // onVolume names the directories on the volume's device; every + // other directory is on another one. nil leaves the device + // numbers to the in-memory filesystem, which has none. + onVolume []string + want []string + }{ + { + name: "volume below the scanned path", + onVolume: []string{"nas"}, + want: []string{scannedPath + "/nas"}, + }, + { + name: "volume at the scanned path", + onVolume: []string{"source", "nas"}, + want: []string{scannedPath}, + }, + {name: "no device numbers", want: nil}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + fs := afero.NewMemMapFs() + + for _, path := range []string{ + scannedPath + "/notes.txt", scannedPath + "/nas/a.txt", + } { + require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, afero.WriteFile(fs, path, []byte(path), 0o644)) + } + + db, err := database.NewTestDB() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + createTestSnapshotRecord(ctx, t, repos, snapshotID) + + cfg := snapshot.ScannerConfig{ + FS: fs, + ChunkSize: int64(1024 * 16), + Repositories: repos, + MaxBlobSize: int64(1024 * 1024), + CompressionLevel: 3, + AgeRecipients: []string{testAgePublicKey}, + } + if tt.onVolume != nil { + cfg.DeviceNumber = func(info os.FileInfo) (uint64, bool) { + if slices.Contains(tt.onVolume, info.Name()) { + return 2, true + } + + return 1, true + } + } + + _, err = snapshot.NewScanner(cfg).Scan(ctx, scannedPath, snapshotID) + require.NoError(t, err) + + got, err := repos.Snapshots.GetMountPoints(ctx, snapshotID) + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +// automountFs is an in-memory filesystem with a volume at mountPoint +// that is mounted on first access: opening mountPoint to list it mounts +// the volume or, if it cannot be mounted, fails with "no such file or +// directory", as with the autofs daemon. Stat records the device an +// entry is on at that moment, as a real stat does: unmountedDevice for +// mountPoint until the volume is mounted; the volume's, 2, for +// mountPoint once it is and for everything in it; 1 for everything else. +type automountFs struct { + afero.Fs + + mountPoint string + unmountedDevice uint64 + canMount bool + mounted bool +} + +//nolint:ireturn // afero.Fs.Open is defined to return the interface. +func (fs *automountFs) Open(name string) (afero.File, error) { + if name == fs.mountPoint && !fs.canMount { + return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT} + } + + if name == fs.mountPoint { + fs.mounted = true + } + + return fs.Fs.Open(name) +} + +func (fs *automountFs) Stat(name string) (os.FileInfo, error) { + info, err := fs.Fs.Stat(name) + if err != nil { + return nil, err + } + + device := uint64(1) + + switch { + case name == fs.mountPoint && !fs.mounted: + device = fs.unmountedDevice + case name == fs.mountPoint || strings.HasPrefix(name, fs.mountPoint+"/"): + device = 2 + } + + return statWithDevice{FileInfo: info, device: device}, nil +} + +// statWithDevice is an entry automountFs.Stat looked up, with the device +// it was on then. +type statWithDevice struct { + os.FileInfo + + device uint64 +} + +// deviceAtLookup returns the device automountFs.Stat recorded for info. +func deviceAtLookup(info os.FileInfo) (uint64, bool) { + stat, ok := info.(statWithDevice) + + return stat.device, ok +} + +// A volume mounted on first access is mounted when the walk lists its +// mount point. Until then the mount point is on the automounter's own +// device (a systemd automount) or on its parent's (an autofs map that +// shows its mount points before mounting them). Either way only the +// mount point is recorded, by the backup that mounts the volume and by a +// later one that finds it mounted. Listing an automount point whose +// volume cannot be mounted fails; it is not recorded, because the walk +// finds no entry in it. See https://git.eeqj.de/sneak/vaultik/issues/395. +func TestScanRecordsOnlyTheMountPointOfAnAutomountedVolume(t *testing.T) { + t.Parallel() + + const scannedPath = "/data/source" + + mountPoint := scannedPath + "/nas" + + tests := []struct { + name string + unmountedDevice uint64 + canMount bool + want []string + }{ + { + name: "on the automounter's device until listed", + unmountedDevice: 3, canMount: true, want: []string{mountPoint}, + }, + { + name: "on its parent's device until listed", + unmountedDevice: 1, canMount: true, want: []string{mountPoint}, + }, + { + name: "volume that cannot be mounted", + unmountedDevice: 1, canMount: false, want: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + fs := &automountFs{ + Fs: afero.NewMemMapFs(), mountPoint: mountPoint, + unmountedDevice: tt.unmountedDevice, canMount: tt.canMount, + } + + require.NoError(t, fs.MkdirAll(mountPoint+"/photos", 0o755)) + + for _, path := range []string{ + scannedPath + "/notes.txt", mountPoint + "/photos/a.jpg", + } { + require.NoError(t, afero.WriteFile(fs, path, []byte(path), 0o644)) + } + + db, err := database.NewTestDB() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + + for _, snapshotID := range []string{"first", "later"} { + createTestSnapshotRecord(ctx, t, repos, snapshotID) + + scanner := snapshot.NewScanner(snapshot.ScannerConfig{ + FS: fs, + ChunkSize: int64(1024 * 16), + Repositories: repos, + MaxBlobSize: int64(1024 * 1024), + CompressionLevel: 3, + AgeRecipients: []string{testAgePublicKey}, + DeviceNumber: deviceAtLookup, + }) + + _, err = scanner.Scan(ctx, scannedPath, snapshotID) + require.NoError(t, err) + + got, err := repos.Snapshots.GetMountPoints(ctx, snapshotID) + require.NoError(t, err) + assert.Equal(t, tt.want, got, "mount points of the %s backup", snapshotID) + } + }) + } +} diff --git a/internal/snapshot/progress.go b/internal/snapshot/progress.go index 5cd151a..d58a339 100644 --- a/internal/snapshot/progress.go +++ b/internal/snapshot/progress.go @@ -56,24 +56,27 @@ const ( // ProgressStats holds atomic counters for progress tracking type ProgressStats struct { - FilesScanned atomic.Int64 // Total files seen during scan (includes skipped) - FilesProcessed atomic.Int64 // Files actually processed in phase 2 - FilesSkipped atomic.Int64 // Files skipped due to no changes - BytesScanned atomic.Int64 // Bytes from new/changed files only - BytesSkipped atomic.Int64 // Bytes from unchanged files - BytesProcessed atomic.Int64 // Actual bytes processed (for ETA calculation) - ChunksCreated atomic.Int64 - BlobsCreated atomic.Int64 - BlobsUploaded atomic.Int64 - BytesUploaded atomic.Int64 - UploadDurationMs atomic.Int64 // Total milliseconds spent uploading - CurrentFile atomic.Value // stores string - TotalSize atomic.Int64 // Total size to process (set after scan phase) - TotalFiles atomic.Int64 // Total files to process in phase 2 - ProcessStartTime atomic.Value // stores time.Time when processing starts - StartTime time.Time - mu sync.RWMutex - lastDetailTime time.Time + FilesScanned atomic.Int64 // Total files seen during scan (includes skipped) + FilesProcessed atomic.Int64 // Files actually processed in phase 2 + FilesSkipped atomic.Int64 // Files skipped due to no changes + BytesScanned atomic.Int64 // Bytes from new/changed files only + BytesSkipped atomic.Int64 // Bytes from unchanged files + BytesProcessed atomic.Int64 // Actual bytes processed (for ETA calculation) + ChunksCreated atomic.Int64 + BlobsCreated atomic.Int64 + BlobsUploaded atomic.Int64 + BytesUploaded atomic.Int64 + CurrentFile atomic.Value // stores string + TotalSize atomic.Int64 // Size to process in the paths scanned so far + TotalFiles atomic.Int64 // Files to process in the paths scanned so far + StartTime time.Time + mu sync.RWMutex + lastDetailTime time.Time + + // Guarded by mu: when the last scan phase ended, and + // BytesProcessed at that moment. + processStartTime time.Time + processStartBytes int64 // Upload tracking CurrentUpload atomic.Value // stores *UploadInfo @@ -149,10 +152,36 @@ func (pr *ProgressReporter) GetStats() *ProgressStats { return pr.stats } -// SetTotalSize sets the total size to process (after scan phase) -func (pr *ProgressReporter) SetTotalSize(size int64) { - pr.stats.TotalSize.Store(size) - pr.stats.ProcessStartTime.Store(time.Now().UTC()) +// AddTotalSize adds the size one path of the snapshot has to process to +// the total, once that path's scan phase is done, and starts measuring +// the processing rate again. The processed counts run across every path, +// so the total does too. Restarting the rate keeps a path's scan phase, +// which processes nothing, out of the rate while that path is processed. +// During a later path's scan phase the rate is still the previous +// path's, and falls as that scan goes on. +func (pr *ProgressReporter) AddTotalSize(size int64) { + pr.stats.TotalSize.Add(size) + + pr.stats.mu.Lock() + defer pr.stats.mu.Unlock() + + pr.stats.processStartTime = time.Now().UTC() + pr.stats.processStartBytes = pr.stats.BytesProcessed.Load() +} + +// processRate returns the bytes processed per second since the last scan +// phase ended, or 0 before the first path's scan phase is done. +func (s *ProgressStats) processRate() float64 { + s.mu.RLock() + defer s.mu.RUnlock() + + if s.processStartTime.IsZero() { + return 0 + } + + processed := s.BytesProcessed.Load() - s.processStartBytes + + return float64(processed) / time.Since(s.processStartTime).Seconds() } // Helper functions @@ -231,9 +260,6 @@ func (pr *ProgressReporter) ReportUploadComplete( // Clear current upload pr.stats.CurrentUpload.Store((*UploadInfo)(nil)) - // Add to total upload duration - pr.stats.UploadDurationMs.Add(duration.Milliseconds()) - // Calculate speed if duration < time.Millisecond { duration = time.Millisecond @@ -361,19 +387,12 @@ func (pr *ProgressReporter) printSummaryStatus() { // Calculate ETA if we have total size and are processing etaStr := "" - if totalSize > 0 && bytesProcessed > 0 { - processStart, ok := pr.stats.ProcessStartTime.Load().(time.Time) - if ok && !processStart.IsZero() { - processElapsed := time.Since(processStart) - - rate := float64(bytesProcessed) / processElapsed.Seconds() - if rate > 0 { - remainingBytes := totalSize - bytesProcessed - remainingSeconds := float64(remainingBytes) / rate - eta := time.Duration(remainingSeconds * float64(time.Second)) - etaStr = " | ETA: " + formatDuration(eta) - } - } + processRate := pr.stats.processRate() + if totalSize > 0 && processRate > 0 { + remainingBytes := totalSize - bytesProcessed + remainingSeconds := float64(remainingBytes) / processRate + eta := time.Duration(remainingSeconds * float64(time.Second)) + etaStr = " | ETA: " + formatDuration(eta) } rate := float64(bytesScanned+bytesSkipped) / elapsed.Seconds() @@ -425,25 +444,18 @@ func (pr *ProgressReporter) printDetailedStatus() { log.Info("Elapsed time", "duration", formatDuration(elapsed)) // Calculate and show ETA if we have data - if totalSize > 0 && bytesProcessed > 0 { - processStart, ok := pr.stats.ProcessStartTime.Load().(time.Time) - if ok && !processStart.IsZero() { - processElapsed := time.Since(processStart) - - processRate := float64(bytesProcessed) / processElapsed.Seconds() - if processRate > 0 { - remainingBytes := totalSize - bytesProcessed - remainingSeconds := float64(remainingBytes) / processRate - eta := time.Duration(remainingSeconds * float64(time.Second)) - percentComplete := float64(bytesProcessed) / float64(totalSize) * percentScale - log.Info("Overall progress", - "percent", fmt.Sprintf("%.1f%%", percentComplete), - "processed", humanize.Bytes(safeUint64(bytesProcessed)), - "total", humanize.Bytes(safeUint64(totalSize)), - "rate", humanize.Bytes(uint64(processRate))+"/s", - "eta", formatDuration(eta)) - } - } + processRate := pr.stats.processRate() + if totalSize > 0 && processRate > 0 { + remainingBytes := totalSize - bytesProcessed + remainingSeconds := float64(remainingBytes) / processRate + eta := time.Duration(remainingSeconds * float64(time.Second)) + percentComplete := float64(bytesProcessed) / float64(totalSize) * percentScale + log.Info("Overall progress", + "percent", fmt.Sprintf("%.1f%%", percentComplete), + "processed", humanize.Bytes(safeUint64(bytesProcessed)), + "total", humanize.Bytes(safeUint64(totalSize)), + "rate", humanize.Bytes(uint64(processRate))+"/s", + "eta", formatDuration(eta)) } log.Info("Files processed", diff --git a/internal/snapshot/progress_rate_test.go b/internal/snapshot/progress_rate_test.go new file mode 100644 index 0000000..69d0689 --- /dev/null +++ b/internal/snapshot/progress_rate_test.go @@ -0,0 +1,54 @@ +//nolint:testpackage // exercises the unexported processRate helper +package snapshot + +import ( + "testing" + "time" +) + +// TestProcessRateNotLoweredByLaterScanPhase feeds the reporter two paths +// that each take 10 seconds to process, the second after a 30-second scan +// phase. That scan phase processes nothing, so the rate while the second +// path is processed must be that path's own. +func TestProcessRateNotLoweredByLaterScanPhase(t *testing.T) { + t.Parallel() + + const ( + pathSize = 1000 + processingTime = 10 * time.Second + scanTime = 30 * time.Second + ) + + // Never started, but Stop releases its tickers and signal handler. + progress := NewProgressReporter() + defer progress.Stop() + + stats := progress.GetStats() + + // Moves the processing start time back instead of sleeping. + elapse := func(d time.Duration) { + stats.mu.Lock() + defer stats.mu.Unlock() + + stats.processStartTime = stats.processStartTime.Add(-d) + } + + progress.AddTotalSize(pathSize) + stats.BytesProcessed.Add(pathSize) + elapse(processingTime) + + elapse(scanTime) + progress.AddTotalSize(pathSize) + stats.BytesProcessed.Add(pathSize) + elapse(processingTime) + + want := pathSize / processingTime.Seconds() + got := stats.processRate() + + // The test's own run time adds to the elapsed time, so got is a hair + // under want. + if got > want || got < want*0.99 { + t.Errorf("rate while the second path is processed is %.1f bytes/s, "+ + "want %.1f", got, want) + } +} diff --git a/internal/snapshot/progress_test.go b/internal/snapshot/progress_test.go new file mode 100644 index 0000000..e106cf3 --- /dev/null +++ b/internal/snapshot/progress_test.go @@ -0,0 +1,93 @@ +package snapshot_test + +import ( + "context" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/afero" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/snapshot" +) + +// TestProgressPercentWithSecondPathSmaller backs up two paths with one +// scanner, as a snapshot with two paths does, the second path smaller +// than the first. The progress line divides the bytes processed by the +// total size, so both must count both paths to stay within 100%. +func TestProgressPercentWithSecondPathSmaller(t *testing.T) { + t.Parallel() + + fs := afero.NewMemMapFs() + files := map[string]string{ + "/large/one.txt": strings.Repeat("1", 4000), + "/large/two.txt": strings.Repeat("2", 4000), + "/small/three.txt": strings.Repeat("3", 1000), + } + + for path, content := range files { + err := fs.MkdirAll(filepath.Dir(path), 0755) + if err != nil { + t.Fatalf("mkdir: %v", err) + } + + err = afero.WriteFile(fs, path, []byte(content), 0644) + if err != nil { + t.Fatalf("write %s: %v", path, err) + } + } + + db, err := database.NewTestDB() + if err != nil { + t.Fatalf("create test db: %v", err) + } + + t.Cleanup(func() { + cerr := db.Close() + if cerr != nil { + t.Errorf("close db: %v", cerr) + } + }) + + repos := database.NewRepositories(db) + + scanner := snapshot.NewScanner(snapshot.ScannerConfig{ + FS: fs, + ChunkSize: int64(1024 * 16), + Repositories: repos, + MaxBlobSize: int64(1024 * 1024), + CompressionLevel: 3, + AgeRecipients: []string{testAgePublicKey}, + EnableProgress: true, + }) + + // Never started, but Stop releases its tickers and signal handler. + progress := scanner.GetProgress() + defer progress.Stop() + + ctx := context.Background() + snapshotID := "test-snapshot-progress" + createTestSnapshotRecord(ctx, t, repos, snapshotID) + + for _, path := range []string{"/large", "/small"} { + _, err := scanner.Scan(ctx, path, snapshotID) + if err != nil { + t.Fatalf("scanning %s: %v", path, err) + } + } + + stats := progress.GetStats() + + // With both paths counted, the percentage must not exceed 100%. + percent := float64(stats.BytesProcessed.Load()) / + float64(stats.TotalSize.Load()) * 100 + if percent > 100 { + t.Errorf("progress after both paths is %.1f%%, want at most 100%%", + percent) + } + + if stats.FilesProcessed.Load() != stats.TotalFiles.Load() { + t.Errorf("progress after both paths is %d of %d files, want all", + stats.FilesProcessed.Load(), stats.TotalFiles.Load()) + } +} diff --git a/internal/snapshot/scanner.go b/internal/snapshot/scanner.go index a0f6a9b..a8b3123 100644 --- a/internal/snapshot/scanner.go +++ b/internal/snapshot/scanner.go @@ -11,6 +11,7 @@ import ( "runtime" "strings" "sync" + "syscall" "time" "github.com/dustin/go-humanize" @@ -19,6 +20,7 @@ import ( "sneak.berlin/go/vaultik/internal/blob" "sneak.berlin/go/vaultik/internal/chunker" "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/exclude" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/storage" "sneak.berlin/go/vaultik/internal/types" @@ -57,22 +59,37 @@ type Scanner struct { compressionLevel int ageRecipient string snapshotID string // Current snapshot being processed - // currentSourcePath is the source directory being scanned (used for - // restore path stripping). + // previousSnapshotID is the most recent completed snapshot of the + // same name, "" for none. Only a file it lists can be counted as + // deleted. + previousSnapshotID string + // currentSourcePath is the source directory being scanned, stored with + // each file record. currentSourcePath string exclude []string // Glob patterns for files/directories to exclude compiledExclude []compiledPattern // Compiled glob patterns + // indexAndLockFiles holds the paths of vaultik's own working files, + // which the scan treats as excluded (ScannerConfig.IndexAndLockFiles). + indexAndLockFiles map[string]struct{} progress *ProgressReporter // skipErrors skips files that cannot be opened or read (logged loudly); // packer, database, encryption, and upload errors still abort the run. skipErrors bool // ui is the user-facing output; never nil (defaults to a discarding writer). ui *ui.Writer + // deviceNumber returns the number of the device that holds a file; + // never nil (defaults to deviceNumberFromStat). + deviceNumber func(info os.FileInfo) (uint64, bool) // In-memory cache of known chunk hashes for fast existence checks knownChunks map[string]struct{} knownChunksMu sync.RWMutex + // filesToRechunk holds the IDs of known files that list a chunk no + // uploaded blob holds; they are re-chunked even when their metadata + // is unchanged. + filesToRechunk map[types.FileID]struct{} + // Pending chunk hashes - chunks that have been added to packer but not // yet committed to DB. When a blob finalizes, the committed chunks are // removed from this set. @@ -86,9 +103,6 @@ type Scanner struct { // Mutex for coordinating blob creation packerMu sync.Mutex // Blocks chunk production during blob creation - - // Context for cancellation - scanCtx context.Context //nolint:containedctx // set per-Scan for packer callbacks } // Periodic status output intervals and thresholds for the scan and @@ -123,23 +137,59 @@ type ScannerConfig struct { EnableProgress bool // Enable the live progress reporter (ETAs, throughput) UI *ui.Writer // Where user-facing scanner messages go; nil = discard Exclude []string // Glob patterns for files/directories to exclude + // IndexAndLockFiles are the absolute paths of vaultik's own working + // files: the index, its side files and the PID file. The scan treats + // them as excluded, whatever Exclude says, since a copy taken while + // they are being written is torn. + IndexAndLockFiles []string // SkipErrors skips files that cannot be opened or read (log loudly but // continue); packer, database, encryption, and upload errors still abort. SkipErrors bool + // PreviousSnapshotID is the most recent completed snapshot of the + // same name, "" for none. + PreviousSnapshotID string + // DeviceNumber returns the number of the device that holds a file, + // and false when there is none to read. nil reads it from the file's + // stat; tests replace it, since the in-memory test filesystem has none. + DeviceNumber func(info os.FileInfo) (uint64, bool) } -// ScanResult contains the results of a scan operation +// ScanResult contains the results of a scan operation. Files and bytes +// are counted per file: BytesScanned is the size of the new and changed +// files, BytesSkipped that of the unchanged ones. FilesFailed counts the +// new and changed files that phase 2 could not store, each entry removed +// after the walk listed its directory and, under --skip-errors, each +// entry the walk could not read, such as a directory it could not list; +// FilesScanned includes them and BytesScanned does not. ChunksCreated +// counts the chunks that were not already stored, and NewChunkSize is +// their total size. type ScanResult struct { - FilesScanned int - FilesSkipped int - FilesDeleted int - BytesScanned int64 - BytesSkipped int64 - BytesDeleted int64 - ChunksCreated int - BlobsCreated int - StartTime time.Time - EndTime time.Time + FilesScanned int + FilesSkipped int + FilesFailed int + FilesDeleted int + BytesScanned int64 + BytesSkipped int64 + BytesDeleted int64 + ChunksCreated int + NewChunkSize int64 + BlobsCreated int + BlobsUploaded int + BytesUploaded int64 + UploadDuration time.Duration + StartTime time.Time + EndTime time.Time + + // FilesUnreadable is the part of FilesFailed that --skip-errors + // skipped because it could not be read or listed; the rest are files + // removed after the walk listed them. + FilesUnreadable int + + // EntriesFound counts the entries the walk found and could look up + // that no exclude pattern matches, leaving out the scanned path + // itself when it is a directory. It is zero for an empty directory, + // such as the mount point of a volume that is not mounted. + EntriesFound int } // NewScanner creates a new scanner instance @@ -172,14 +222,28 @@ func NewScanner(cfg ScannerConfig) *Scanner { progress = NewProgressReporter() } - // Compile exclude patterns - compiledExclude := compileExcludePatterns(cfg.Exclude) + compiledExclude, err := compileExcludePatterns(cfg.Exclude) + if err != nil { + log.Error("Failed to compile exclude patterns", "error", err) + + return nil + } uiw := cfg.UI if uiw == nil { uiw = ui.NewWithColor(io.Discard, false) } + deviceNumber := cfg.DeviceNumber + if deviceNumber == nil { + deviceNumber = deviceNumberFromStat + } + + indexAndLockFiles := make(map[string]struct{}, len(cfg.IndexAndLockFiles)) + for _, p := range cfg.IndexAndLockFiles { + indexAndLockFiles[filepath.Clean(p)] = struct{}{} + } + return &Scanner{ fs: cfg.FS, chunker: chunker.NewChunker(cfg.ChunkSize), @@ -191,9 +255,12 @@ func NewScanner(cfg ScannerConfig) *Scanner { ageRecipient: strings.Join(cfg.AgeRecipients, ","), exclude: cfg.Exclude, compiledExclude: compiledExclude, + indexAndLockFiles: indexAndLockFiles, progress: progress, skipErrors: cfg.SkipErrors, + previousSnapshotID: cfg.PreviousSnapshotID, ui: uiw, + deviceNumber: deviceNumber, pendingChunkHashes: make(map[string]struct{}), } } @@ -203,9 +270,7 @@ func (s *Scanner) Scan( ctx context.Context, path string, snapshotID string, ) (*ScanResult, error) { s.snapshotID = snapshotID - // Store source path for file records (used during restore) s.currentSourcePath = path - s.scanCtx = ctx result := &ScanResult{ StartTime: time.Now().UTC(), } @@ -213,17 +278,13 @@ func (s *Scanner) Scan( // Set blob handler for concurrent upload if s.storage != nil { log.Debug("Setting blob handler for storage uploads") - s.packer.SetBlobHandler(s.handleBlobReady) + s.packer.SetBlobHandler(func(blobWithReader *blob.WithReader) error { + return s.handleBlobReady(ctx, blobWithReader, result) + }) } else { log.Debug("No storage configured, blobs will not be uploaded") } - // Start progress reporting if enabled - if s.progress != nil { - s.progress.Start() - defer s.progress.Stop() - } - // Phase 0: Repair any state left by an interrupted previous run, then // load known files and chunks from the database into memory for fast // lookup. @@ -250,8 +311,9 @@ func (s *Scanner) Scan( filesToProcess := scanResult.FilesToProcess - // Phase 1b: Detect deleted files by comparing DB against scanned files - err = s.detectDeletedFilesFromMap(ctx, knownFiles, existingFiles, result) + // Phase 1b: Detect deleted files by comparing the previous snapshot + // of this name against scanned files + err = s.detectDeletedFiles(ctx, path, existingFiles, result) if err != nil { return nil, fmt.Errorf("detecting deleted files: %w", err) } @@ -267,6 +329,11 @@ func (s *Scanner) Scan( } } + err = s.recordDirectories(ctx, scanResult) + if err != nil { + return nil, err + } + // Summarize scan phase results and update progress s.summarizeScanPhase(result, filesToProcess) @@ -288,13 +355,14 @@ func (s *Scanner) Scan( log.Info("Phase 2/3: Skipping (no files need processing, metadata-only snapshot)") } - // Finalize result with blob statistics - s.finalizeScanResult(ctx, result) + result.EndTime = time.Now().UTC() return result, nil } -// GetProgress returns the progress reporter for this scanner +// GetProgress returns the progress reporter for this scanner, or nil when +// progress is off. Scan neither starts nor stops it: the caller does, +// once for all the paths it scans, because a second Stop panics. func (s *Scanner) GetProgress() *ProgressReporter { return s.progress } @@ -325,9 +393,42 @@ func (s *Scanner) loadDatabaseState( s.ui.Completef("Loaded %s known chunks from local index database.", s.ui.Count(len(s.knownChunks))) + err = s.loadFilesToRechunk(ctx, path) + if err != nil { + return nil, fmt.Errorf("loading files to re-chunk: %w", err) + } + return knownFiles, nil } +// loadFilesToRechunk loads the IDs of known files under path that list a +// chunk no uploaded blob holds. A file row is shared by every snapshot +// that lists the file and is updated in place when the file changes, +// while a blob row is deleted once no snapshot references it. Removing +// the only snapshot that references a changed file's current blob +// therefore leaves an older snapshot keeping a file row whose metadata +// matches the disk while no blob the local index records as uploaded +// holds its chunks, so a new snapshot cannot reference them. The dropped +// blob can still be in remote storage until prune removes it. +func (s *Scanner) loadFilesToRechunk(ctx context.Context, path string) error { + ids, err := s.repos.Files.ListIDsWithChunksNotInUploadedBlobs(ctx, path) + if err != nil { + return fmt.Errorf("listing files: %w", err) + } + + s.filesToRechunk = make(map[types.FileID]struct{}, len(ids)) + for _, id := range ids { + s.filesToRechunk[id] = struct{}{} + } + + if len(ids) > 0 { + log.Info("Re-chunking known files whose chunks are not all "+ + "in uploaded blobs", "files", len(ids)) + } + + return nil +} + // repairInterruptedBlobs discards blob rows left by a previous run whose // upload never completed. Such a blob has its chunks, blob_chunks, and // blobs rows committed to the local index before the upload is attempted, @@ -371,8 +472,8 @@ func (s *Scanner) summarizeScanPhase( } if s.progress != nil { - s.progress.SetTotalSize(totalSizeToProcess) - s.progress.GetStats().TotalFiles.Store(int64(len(filesToProcess))) + s.progress.AddTotalSize(totalSizeToProcess) + s.progress.GetStats().TotalFiles.Add(int64(len(filesToProcess))) } log.Info("Phase 1 complete", @@ -396,35 +497,15 @@ func (s *Scanner) summarizeScanPhase( s.ui.Completef("%s.", msg) } -// finalizeScanResult populates final blob statistics in the scan result -// by querying the packer and database for blob/upload counts -func (s *Scanner) finalizeScanResult(ctx context.Context, result *ScanResult) { - blobs := s.packer.GetFinishedBlobs() - result.BlobsCreated += len(blobs) - - // Query database for actual blob count created during this snapshot - // The database is authoritative, especially for concurrent blob uploads - // We count uploads rather than all snapshot_blobs to get only NEW blobs - if s.snapshotID != "" { - uploadCount, err := s.repos.Uploads.GetCountBySnapshot(ctx, s.snapshotID) - if err != nil { - log.Warn("Failed to query upload count from database", "error", err) - } else { - result.BlobsCreated = int(uploadCount) - } - } - - result.EndTime = time.Now().UTC() -} - -// loadKnownFiles loads all known files from the database into a map for fast lookup -// This avoids per-file database queries during the scan phase +// loadKnownFiles loads the known files at and beneath path from the +// database into a map for fast lookup. This avoids per-file database +// queries during the scan phase. func (s *Scanner) loadKnownFiles( ctx context.Context, path string, ) (map[string]*database.File, error) { - files, err := s.repos.Files.ListByPrefix(ctx, path) + files, err := s.repos.Files.ListUnderPath(ctx, path) if err != nil { - return nil, fmt.Errorf("listing files by prefix: %w", err) + return nil, fmt.Errorf("listing files under %s: %w", path, err) } result := make(map[string]*database.File, len(files)) @@ -824,14 +905,20 @@ func (s *Scanner) batchInsertFileData( // ScanPhaseResult contains the results of the scan phase type ScanPhaseResult struct { FilesToProcess []*FileToProcess - UnchangedFileIDs []types.FileID // IDs of unchanged files to associate with snapshot + UnchangedFileIDs []types.FileID // IDs of unchanged files to associate with snapshot + Directories []*FileToProcess // Every directory found, to record + // MountPoints are the directories, the scanned path included, that + // the walk found an entry in and, once it had listed them, on a + // different device from their parent directory (see + // recordIfMountPoint). + MountPoints []string } // scanPhase performs the initial directory scan to identify files to process // It uses the pre-loaded knownFiles map for fast change detection without DB // queries. It also populates existingFiles map for deletion detection. -// Returns files needing processing and IDs of unchanged files for snapshot -// association. +// Returns files needing processing, IDs of unchanged files for snapshot +// association, and the directories found. func (s *Scanner) scanPhase( ctx context.Context, path string, @@ -839,10 +926,12 @@ func (s *Scanner) scanPhase( existingFiles map[string]struct{}, knownFiles map[string]*database.File, ) (*ScanPhaseResult, error) { - // Use known file count as estimate for progress (accurate for subsequent backups) - estimatedTotal := int64(len(knownFiles)) + // Use known file count as estimate for progress (accurate for + // subsequent backups). The walk does not count directories, so the + // estimate leaves them out. + estimatedTotal := countNonDirectories(knownFiles) - collector := &scanCollector{} + collector := &scanCollector{dirsWithEntries: make(map[string]struct{})} // Set up periodic status output startTime := time.Now() @@ -851,8 +940,28 @@ func (s *Scanner) scanPhase( log.Debug("Starting directory walk", "path", path) walkFn := func(filePath string, info os.FileInfo, err error) error { + // Check exclude patterns first, so an excluded entry that is gone + // or cannot be looked up is neither counted nor reported. For + // directories, skip the entire subtree. info is nil when the + // walk could not look the entry up. + if s.shouldExclude(filePath, path) { + if info != nil && info.IsDir() { + return filepath.SkipDir + } + + return nil + } + + // The source path is in no directory listing, so its absence is + // an error rather than a removal. + if errors.Is(err, os.ErrNotExist) && filePath != path { + countRemovedDuringWalk(filePath, existingFiles, result) + + return nil + } + if err != nil { - return s.handleWalkError(filePath, err) + return s.handleWalkError(filePath, err, result) } // Check context cancellation @@ -862,19 +971,18 @@ func (s *Scanner) scanPhase( default: } - // Check exclude patterns - for directories, skip the entire subtree - if s.shouldExclude(filePath, path) { - if info.IsDir() { - return filepath.SkipDir - } - - return nil + // The scanned directory itself is not an entry found in it. + if filePath != path || !info.IsDir() { + result.EntriesFound++ } + s.recordIfMountPoint(filePath, path, collector) + // Handle symlinks and directories - if handled := s.recordSpecialEntry( - filePath, info, existingFiles, collector, result); handled { - return nil + handled, err := s.recordSpecialEntry( + filePath, info, existingFiles, knownFiles, collector, result) + if handled { + return err } // Skip other non-regular files (devices, sockets, etc.) @@ -882,17 +990,8 @@ func (s *Scanner) scanPhase( return nil } - // Track this file as existing (for deletion detection) - existingFiles[filePath] = struct{}{} - - // Check file against in-memory map (no DB query!) - file, needsProcessing := s.checkFileInMemory(filePath, info, knownFiles) - - filesScanned, changedCount := collector.recordRegularFile( - filePath, info, file, needsProcessing) - - // Update result stats - s.updateScanEntryStats(result, needsProcessing, info) + filesScanned, changedCount := s.recordRegularFile( + filePath, info, existingFiles, knownFiles, collector, result) // Output periodic status if time.Since(lastStatusTime) >= scanStatusInterval { @@ -912,26 +1011,48 @@ func (s *Scanner) scanPhase( return &ScanPhaseResult{ FilesToProcess: collector.filesToProcess, UnchangedFileIDs: collector.unchangedFileIDs, + Directories: collector.directories, + MountPoints: collector.mountPoints, }, nil } +// countNonDirectories returns how many of files are not directories. +func countNonDirectories(files map[string]*database.File) int64 { + var count int64 + + for _, f := range files { + if f.Mode&uint32(os.ModeDir) == 0 { + count++ + } + } + + return count +} + // recordSpecialEntry records symlinks and directories (which have no -// data to chunk) and reports whether it handled the entry. +// data to chunk) and reports whether it handled the entry. A symlink is +// counted and checked for changes as a regular file is; a directory is +// set aside to be recorded and is not counted. For a symlink whose +// target cannot be read it returns handleWalkError's result. func (s *Scanner) recordSpecialEntry( filePath string, info os.FileInfo, existingFiles map[string]struct{}, + knownFiles map[string]*database.File, collector *scanCollector, result *ScanResult, -) bool { +) (bool, error) { // Handle symlinks if info.Mode()&os.ModeSymlink != 0 { - file := s.buildSymlinkEntry(filePath, info) - if file != nil { - existingFiles[filePath] = struct{}{} - collector.addToProcess(filePath, info, file) - s.updateScanEntryStats(result, true, info) + file, err := s.buildSymlinkEntry(filePath, info) + if err != nil { + return true, s.handleWalkError(filePath, err, result) } - return true + existingFiles[filePath] = struct{}{} + needsProcessing := s.checkFileInMemory(file, knownFiles) + collector.recordFile(filePath, info, file, needsProcessing) + s.updateScanEntryStats(result, needsProcessing, info) + + return true, nil } // Handle directories (record for permission/ownership preservation @@ -939,23 +1060,70 @@ func (s *Scanner) recordSpecialEntry( if info.IsDir() { file := s.buildDirectoryEntry(filePath, info) existingFiles[filePath] = struct{}{} - collector.addToProcess(filePath, info, file) + collector.addDirectory(filePath, info, file) - return true + return true, nil } - return false + return false, nil +} + +// recordRegularFile records a regular file as recordSpecialEntry does a +// symlink and returns the running scanned and changed counts. +func (s *Scanner) recordRegularFile( + filePath string, info os.FileInfo, + existingFiles map[string]struct{}, + knownFiles map[string]*database.File, + collector *scanCollector, result *ScanResult, +) (int64, int) { + // Track this file as existing (for deletion detection) + existingFiles[filePath] = struct{}{} + + // Check file against in-memory map (no DB query!) + file := s.buildRegularFileEntry(filePath, info) + needsProcessing := s.checkFileInMemory(file, knownFiles) + + filesScanned, changedCount := collector.recordFile( + filePath, info, file, needsProcessing) + + // Update result stats + s.updateScanEntryStats(result, needsProcessing, info) + + return filesScanned, changedCount +} + +// countRemovedDuringWalk counts an entry that was in its directory's +// listing but was gone when the walk looked it up, like a file removed +// before phase 2 reads it: as examined and failed, and not as an error, +// with or without --skip-errors. +func countRemovedDuringWalk( + filePath string, existingFiles map[string]struct{}, result *ScanResult, +) { + log.Warn("File was deleted during the directory walk, skipping", + "path", filePath) + + // The walk found it, so it is not also counted as deleted. + existingFiles[filePath] = struct{}{} + result.FilesScanned++ + result.FilesFailed++ } // handleWalkError deals with a filesystem error surfaced by the walk: -// skipped (with a UI notice) under --skip-errors, fatal otherwise. -func (s *Scanner) handleWalkError(filePath string, err error) error { +// under --skip-errors the entry is skipped with a UI notice and counted +// as examined, failed and unreadable, otherwise the error is fatal. +func (s *Scanner) handleWalkError( + filePath string, err error, result *ScanResult, +) error { if s.skipErrors { log.Error("Failed to access file (skipping due to --skip-errors)", "path", filePath, "error", err) s.ui.Errorf("Failed to access %s: %v. Skipping (--skip-errors).", s.ui.Path(filePath), err) + result.FilesScanned++ + result.FilesFailed++ + result.FilesUnreadable++ + return nil // Continue scanning } @@ -969,28 +1137,52 @@ type scanCollector struct { mu sync.Mutex filesToProcess []*FileToProcess unchangedFileIDs []types.FileID // Just IDs - no new records needed + directories []*FileToProcess filesScanned int64 + // dirsWithEntries holds each directory the walk has found an entry in. + dirsWithEntries map[string]struct{} + mountPoints []string } -// addToProcess queues a file entry for processing. -func (c *scanCollector) addToProcess( +// firstEntryIn notes that the walk found an entry in directory dir and +// reports whether it is the first one. +func (c *scanCollector) firstEntryIn(dir string) bool { + c.mu.Lock() + defer c.mu.Unlock() + + _, seen := c.dirsWithEntries[dir] + c.dirsWithEntries[dir] = struct{}{} + + return !seen +} + +// addMountPoint sets a mount point aside to be recorded. +func (c *scanCollector) addMountPoint(dir string) { + c.mu.Lock() + defer c.mu.Unlock() + + c.mountPoints = append(c.mountPoints, dir) +} + +// addDirectory sets a directory aside to be recorded. It is not counted +// as a file. +func (c *scanCollector) addDirectory( path string, info os.FileInfo, file *database.File, ) { c.mu.Lock() defer c.mu.Unlock() - c.filesToProcess = append(c.filesToProcess, &FileToProcess{ + c.directories = append(c.directories, &FileToProcess{ Path: path, FileInfo: info, File: file, }) - c.filesScanned++ } -// recordRegularFile records a regular file as changed (to process) or -// unchanged (snapshot association only) and returns the running scanned -// and changed counts. -func (c *scanCollector) recordRegularFile( +// recordFile records a regular file or symlink as changed (to process) +// or unchanged (snapshot association only) and returns the running +// scanned and changed counts. +func (c *scanCollector) recordFile( path string, info os.FileInfo, file *database.File, needsProcessing bool, ) (int64, int) { c.mu.Lock() @@ -1093,27 +1285,43 @@ func (s *Scanner) printScanProgressLine( } } -// buildSymlinkEntry creates a File record for a symlink. -// Returns nil if the link target cannot be read. -func (s *Scanner) buildSymlinkEntry(path string, info os.FileInfo) *database.File { - target, err := os.Readlink(path) - if err != nil { - log.Debug("Cannot read symlink target", "path", path, "error", err) - - return nil - } - +// buildRegularFileEntry creates a File record for a regular file, with +// no ID: checkFileInMemory sets it. +func (s *Scanner) buildRegularFileEntry(path string, info os.FileInfo) *database.File { var uid, gid uint32 - if stat, ok := info.Sys().(interface { - Uid() uint32 - Gid() uint32 - }); ok { - uid = stat.Uid() - gid = stat.Gid() + if stat, ok := info.Sys().(*syscall.Stat_t); ok { + uid = stat.Uid + gid = stat.Gid + } + + return &database.File{ + Path: types.FilePath(path), + SourcePath: types.SourcePath(s.currentSourcePath), + MTime: info.ModTime(), + Size: info.Size(), + Mode: uint32(info.Mode()), + UID: uid, + GID: gid, + } +} + +// buildSymlinkEntry creates a File record for a symlink, with no ID: +// checkFileInMemory sets it. +func (s *Scanner) buildSymlinkEntry( + path string, info os.FileInfo, +) (*database.File, error) { + target, err := os.Readlink(path) + if err != nil { + return nil, err + } + + var uid, gid uint32 + if stat, ok := info.Sys().(*syscall.Stat_t); ok { + uid = stat.Uid + gid = stat.Gid } return &database.File{ - ID: types.NewFileID(), Path: types.FilePath(path), SourcePath: types.SourcePath(s.currentSourcePath), MTime: info.ModTime(), @@ -1122,18 +1330,15 @@ func (s *Scanner) buildSymlinkEntry(path string, info os.FileInfo) *database.Fil UID: uid, GID: gid, LinkTarget: types.FilePath(target), - } + }, nil } // buildDirectoryEntry creates a File record for a directory. func (s *Scanner) buildDirectoryEntry(path string, info os.FileInfo) *database.File { var uid, gid uint32 - if stat, ok := info.Sys().(interface { - Uid() uint32 - Gid() uint32 - }); ok { - uid = stat.Uid() - gid = stat.Gid() + if stat, ok := info.Sys().(*syscall.Stat_t); ok { + uid = stat.Uid + gid = stat.Gid } return &database.File{ @@ -1148,6 +1353,103 @@ func (s *Scanner) buildDirectoryEntry(path string, info os.FileInfo) *database.F } } +// recordDirectories records every directory the walk found, and its +// mount points (see recordMountPoints). A directory has no data to back +// up, so it is not among the files counted and backed up. +func (s *Scanner) recordDirectories( + ctx context.Context, scanned *ScanPhaseResult, +) error { + for _, dir := range scanned.Directories { + err := s.recordNonRegularFile(ctx, dir) + if err != nil { + return fmt.Errorf("recording directory %s: %w", dir.Path, err) + } + } + + return s.recordMountPoints(ctx, scanned.MountPoints) +} + +// recordMountPoints records with the snapshot the mount points the walk +// found (see ScanPhaseResult.MountPoints). +func (s *Scanner) recordMountPoints( + ctx context.Context, mountPoints []string, +) error { + return s.repos.WithTx(ctx, func(txCtx context.Context, tx *sql.Tx) error { + for _, dir := range mountPoints { + log.Info("Found a mount point", "path", dir) + + err := s.repos.Snapshots.AddMountPoint(txCtx, tx, s.snapshotID, dir) + if err != nil { + return fmt.Errorf("recording mount point %s: %w", dir, err) + } + } + + return nil + }) +} + +// recordIfMountPoint sets the directory that holds entry, a path the +// walk found, aside to be recorded as a mount point if it is on a +// different device from its parent directory. The walk calls it for each +// entry it finds, and it decides on the first entry in a directory, so a +// directory the walk found no entry in is never recorded. By then the +// walk has listed the directory, which mounts a volume mounted there on +// first access, so the directory and its parent are looked up again: +// before the listing, the directory can be on the automounter's own +// device (a systemd automount) or on its parent's (an autofs map that +// shows its mount points before mounting them). The scanned path is in +// no listing the walk made, so it is skipped as an entry. A directory +// that cannot be looked up then, or whose parent cannot, is not +// recorded, so this snapshot does not stop the prune of a later backup +// that misses its volume. +func (s *Scanner) recordIfMountPoint( + entry, scannedPath string, collector *scanCollector, +) { + dir := filepath.Dir(entry) + + if entry == scannedPath || !collector.firstEntryIn(dir) { + return + } + + dirDevice, ok := s.deviceNumberAt(dir) + if !ok { + return + } + + parentDevice, ok := s.deviceNumberAt(filepath.Dir(dir)) + if ok && dirDevice != parentDevice { + collector.addMountPoint(dir) + } +} + +// deviceNumberAt looks path up now and returns the number of the device +// that holds it, and false when the lookup fails (logged) or gives no +// device number. +func (s *Scanner) deviceNumberAt(path string) (uint64, bool) { + info, err := s.fs.Stat(path) + if err != nil { + log.Warn("Could not look up a directory to check for a mount point", + "path", path, "error", err) + + return 0, false + } + + return s.deviceNumber(info) +} + +// deviceNumberFromStat returns the number of the device that holds the +// file info describes, and false when info carries no stat from a real +// filesystem. The in-memory test filesystem gives either no stat or one +// whose device and inode numbers are both zero, which no real file has. +func deviceNumberFromStat(info os.FileInfo) (uint64, bool) { + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok || (stat.Dev == 0 && stat.Ino == 0) { + return 0, false + } + + return uint64(stat.Dev), true //nolint:unconvert // Dev is an int32 on darwin +} + // recordNonRegularFile writes a symlink or directory entry to the database // and associates it with the current snapshot. No chunking is performed. func (s *Scanner) recordNonRegularFile(ctx context.Context, ftp *FileToProcess) error { @@ -1161,64 +1463,36 @@ func (s *Scanner) recordNonRegularFile(ctx context.Context, ftp *FileToProcess) }) } -// checkFileInMemory checks if a file needs processing using the in-memory map +// checkFileInMemory reports whether a regular file or symlink needs +// processing, and gives file the ID of its known record, or a new ID for +// a new path. // No database access is performed - this is purely CPU/memory work func (s *Scanner) checkFileInMemory( - path string, info os.FileInfo, knownFiles map[string]*database.File, -) (*database.File, bool) { - // Get file stats - stat, ok := info.Sys().(interface { - Uid() uint32 - Gid() uint32 - }) - - var uid, gid uint32 - if ok { - uid = stat.Uid() - gid = stat.Gid() - } - - // Check against in-memory map first to get existing ID if available - existingFile, exists := knownFiles[path] - - // Create file record with ID set upfront - // For new files, generate UUID immediately so it's available for chunk associations - // For existing files, reuse the existing ID - var fileID types.FileID - if exists { - fileID = existingFile.ID - } else { - fileID = types.NewFileID() - } - - file := &database.File{ - ID: fileID, - Path: types.FilePath(path), - // Store source directory for restore path stripping - SourcePath: types.SourcePath(s.currentSourcePath), - MTime: info.ModTime(), - Size: info.Size(), - Mode: uint32(info.Mode()), - UID: uid, - GID: gid, - } + file *database.File, knownFiles map[string]*database.File, +) bool { + existingFile, exists := knownFiles[file.Path.String()] // New file - needs processing if !exists { - return file, true + file.ID = types.NewFileID() + + return true + } + + file.ID = existingFile.ID + + // No uploaded blob holds one of its chunks (see loadFilesToRechunk) + if _, rechunk := s.filesToRechunk[file.ID]; rechunk { + return true } // Check if file has changed - if existingFile.Size != file.Size || - existingFile.MTime.Unix() != file.MTime.Unix() || + return existingFile.Size != file.Size || + !existingFile.MTime.Equal(file.MTime) || existingFile.Mode != file.Mode || existingFile.UID != file.UID || - existingFile.GID != file.GID { - return file, true - } - - // File unchanged - return file, false + existingFile.GID != file.GID || + existingFile.LinkTarget != file.LinkTarget } // batchAddFilesToSnapshot adds existing file IDs to the snapshot association table @@ -1280,6 +1554,11 @@ func (s *Scanner) batchAddFilesToSnapshot( func (s *Scanner) processPhase( ctx context.Context, filesToProcess []*FileToProcess, result *ScanResult, ) error { + // On an error or cancellation the blob being packed is never + // finalized, so its temp file must be removed here. After a + // successful flush there is no such blob and this does nothing. + defer s.packer.DiscardCurrentBlob() + // Calculate total bytes to process var totalBytes int64 for _, f := range filesToProcess { @@ -1297,6 +1576,13 @@ func (s *Scanner) processPhase( // Process each file for _, fileToProcess := range filesToProcess { + // Check context cancellation + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + // Update progress if s.progress != nil { s.progress.GetStats().CurrentFile.Store(fileToProcess.Path) @@ -1333,20 +1619,37 @@ func (s *Scanner) processPhase( return s.finalizeProcessPhase(ctx, result) } -// processFileWithErrorHandling wraps processFileStreaming with error recovery for -// deleted files and skip-errors mode. Returns (skipped, error). +// processFileWithErrorHandling records a symlink, or wraps +// processFileStreaming for a regular file with error recovery for deleted +// files and skip-errors mode. Returns (skipped, error). func (s *Scanner) processFileWithErrorHandling( ctx context.Context, fileToProcess *FileToProcess, result *ScanResult, ) (bool, error) { + // A symlink has no data to open or read; it is only recorded in the + // local index. An error recording it stops the run even under + // --skip-errors, or the snapshot would complete without it. + if os.FileMode(fileToProcess.File.Mode)&os.ModeSymlink != 0 { + err := s.recordNonRegularFile(ctx, fileToProcess) + if err != nil { + return false, fmt.Errorf("processing file %s: %w", fileToProcess.Path, err) + } + + return false, nil + } + err := s.processFileStreaming(ctx, fileToProcess, result) if err != nil { + // A cancelled run stops here even under --skip-errors, rather than + // counting this file as failed and going on to the next one. + if ctx.Err() != nil { + return false, fmt.Errorf("processing file %s: %w", fileToProcess.Path, err) + } // A packer/database/encryption/upload failure means the chunk's data // may not have been stored. Skipping the file would let the snapshot // record a file whose chunk is in no blob and cannot be restored, so // abort the run even under --skip-errors. Only open and read errors // are skipped below. - var pErr *packerError - if errors.As(err, &pErr) { + if _, ok := errors.AsType[*packerError](err); ok { return false, fmt.Errorf("processing file %s: %w", fileToProcess.Path, err) } // Handle files that were deleted between scan and process phases @@ -1354,7 +1657,7 @@ func (s *Scanner) processFileWithErrorHandling( log.Warn("File was deleted during backup, skipping", "path", fileToProcess.Path) - result.FilesSkipped++ + countFailedFile(fileToProcess, result) return true, nil } @@ -1365,7 +1668,8 @@ func (s *Scanner) processFileWithErrorHandling( s.ui.Errorf("Failed to process %s: %v. Skipping (--skip-errors).", s.ui.Path(fileToProcess.Path), err) - result.FilesSkipped++ + countFailedFile(fileToProcess, result) + result.FilesUnreadable++ return true, nil } @@ -1376,6 +1680,13 @@ func (s *Scanner) processFileWithErrorHandling( return false, nil } +// countFailedFile counts a file that phase 2 could not store as failed +// and takes its size back out of BytesScanned, where phase 1 put it. +func countFailedFile(fileToProcess *FileToProcess, result *ScanResult) { + result.FilesFailed++ + result.BytesScanned -= fileToProcess.FileInfo.Size() +} + // printProcessingProgress prints a periodic progress line during the process phase, // showing files processed, bytes transferred, throughput, and ETA func (s *Scanner) printProcessingProgress( @@ -1462,7 +1773,8 @@ func (s *Scanner) finalizeProcessPhase(ctx context.Context, result *ScanResult) // snapshot references has uploaded_ts set, so deduplication and // interrupted-run repair treat these blobs as trustworthy. err = s.repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { - err := s.repos.Blobs.UpdateUploaded(ctx, tx, b.ID) + err := s.repos.Blobs.UpdateUploaded( + ctx, tx, b.ID, b.Compressed) if err != nil { return fmt.Errorf("marking blob uploaded: %w", err) } @@ -1482,39 +1794,44 @@ func (s *Scanner) finalizeProcessPhase(ctx context.Context, result *ScanResult) } // handleBlobReady is called by the packer when a blob is finalized -func (s *Scanner) handleBlobReady(blobWithReader *blob.WithReader) error { +func (s *Scanner) handleBlobReady( + ctx context.Context, blobWithReader *blob.WithReader, result *ScanResult, +) error { startTime := time.Now().UTC() finishedBlob := blobWithReader.FinishedBlob + result.BlobsCreated++ + if s.progress != nil { s.progress.ReportUploadStart(finishedBlob.Hash, finishedBlob.Compressed) s.progress.GetStats().BlobsCreated.Add(1) } - ctx := s.scanCtx - if ctx == nil { - ctx = context.Background() - } - blobPath := fmt.Sprintf("blobs/%s/%s/%s", finishedBlob.Hash[:2], finishedBlob.Hash[2:4], finishedBlob.Hash) - blobExists, err := s.uploadBlobIfNeeded(ctx, blobPath, blobWithReader, startTime) + storedSize, blobExists, err := s.uploadBlobIfNeeded( + ctx, blobPath, blobWithReader, startTime, result) if err != nil { - s.cleanupBlobTempFile(blobWithReader) + cleanupErr := s.cleanupBlobTempFile(blobWithReader) - return fmt.Errorf("uploading blob %s: %w", finishedBlob.Hash, err) + return errors.Join( + fmt.Errorf("uploading blob %s: %w", finishedBlob.Hash, err), cleanupErr) } - err = s.recordBlobMetadata(ctx, finishedBlob, blobExists, startTime) + err = s.recordBlobMetadata( + ctx, finishedBlob, storedSize, blobExists, startTime) if err != nil { - s.cleanupBlobTempFile(blobWithReader) + cleanupErr := s.cleanupBlobTempFile(blobWithReader) + return errors.Join(err, cleanupErr) + } + + err = s.cleanupBlobTempFile(blobWithReader) + if err != nil { return err } - s.cleanupBlobTempFile(blobWithReader) - // Chunks from this blob are now committed to DB - remove from pending set s.removePendingChunkHashes(blobWithReader.InsertedChunkHashes) @@ -1528,19 +1845,22 @@ func (s *Scanner) handleBlobReady(blobWithReader *blob.WithReader) error { } // uploadBlobIfNeeded uploads the blob to storage if it doesn't already -// exist, returns whether it existed +// exist. It returns the size of the object in storage, which for an +// existing object can differ from the local copy's, and whether it +// already existed. func (s *Scanner) uploadBlobIfNeeded( ctx context.Context, blobPath string, blobWithReader *blob.WithReader, startTime time.Time, -) (bool, error) { + result *ScanResult, +) (int64, bool, error) { finishedBlob := blobWithReader.FinishedBlob // Check if blob already exists (deduplication after restart) destination := s.storage.Info().Location - _, err := s.storage.Stat(ctx, blobPath) + stored, err := s.storage.Stat(ctx, blobPath) if err == nil { log.Info("Blob already exists in storage, skipping upload", "hash", finishedBlob.Hash, @@ -1549,7 +1869,7 @@ func (s *Scanner) uploadBlobIfNeeded( s.ui.Hex(finishedBlob.Hash), s.ui.Size(finishedBlob.Compressed), s.ui.Path(destination)) - return true, nil + return stored.Size, true, nil } s.ui.Beginf("Uploading blob %s (%s) to %s.", @@ -1561,14 +1881,24 @@ func (s *Scanner) uploadBlobIfNeeded( err = s.storage.PutWithProgress(ctx, blobPath, blobWithReader.Reader, finishedBlob.Compressed, progressCallback) if err != nil { - log.Error("Failed to upload blob", "hash", finishedBlob.Hash, "error", err) + // The record is at info level: the returned error ends the backup + // and is printed as its ERROR: line. Only an interrupt cancels + // ctx, and the user is told about it, so an upload it stopped is + // not logged as a storage failure. + if ctx.Err() == nil { + log.Info("Failed to upload blob", "hash", finishedBlob.Hash, "error", err) + } - return false, fmt.Errorf("uploading blob to storage: %w", err) + return 0, false, fmt.Errorf("uploading blob to storage: %w", err) } uploadDuration := time.Since(startTime) uploadSpeedBps := float64(finishedBlob.Compressed) / uploadDuration.Seconds() + result.BlobsUploaded++ + result.BytesUploaded += finishedBlob.Compressed + result.UploadDuration += uploadDuration + s.ui.Completef("Uploaded blob %s (%s) in %s at %s.", s.ui.Hex(finishedBlob.Hash), s.ui.Size(finishedBlob.Compressed), @@ -1590,7 +1920,7 @@ func (s *Scanner) uploadBlobIfNeeded( stats.BytesUploaded.Add(finishedBlob.Compressed) } - return false, nil + return finishedBlob.Compressed, false, nil } // makeUploadProgressCallback creates a progress callback for blob uploads. @@ -1660,6 +1990,7 @@ func (s *Scanner) makeUploadProgressCallback( func (s *Scanner) recordBlobMetadata( ctx context.Context, finishedBlob *blob.FinishedBlob, + storedSize int64, blobExists bool, startTime time.Time, ) error { @@ -1671,7 +2002,8 @@ func (s *Scanner) recordBlobMetadata( uploadDuration := time.Since(startTime) return s.repos.WithTx(ctx, func(txCtx context.Context, tx *sql.Tx) error { - err := s.repos.Blobs.UpdateUploaded(txCtx, tx, finishedBlob.ID) + err := s.repos.Blobs.UpdateUploaded( + txCtx, tx, finishedBlob.ID, storedSize) if err != nil { return fmt.Errorf("updating blob upload timestamp: %w", err) } @@ -1702,20 +2034,22 @@ func (s *Scanner) recordBlobMetadata( } // cleanupBlobTempFile closes and removes the blob's temporary file -func (s *Scanner) cleanupBlobTempFile(blobWithReader *blob.WithReader) { +func (s *Scanner) cleanupBlobTempFile(blobWithReader *blob.WithReader) error { if blobWithReader.TempFile != nil { tempName := blobWithReader.TempFile.Name() err := blobWithReader.TempFile.Close() if err != nil { - log.Fatal("Failed to close temp file", "file", tempName, "error", err) + return fmt.Errorf("closing blob temp file: %w", err) } err = s.fs.Remove(tempName) if err != nil { - log.Fatal("Failed to remove temp file", "file", tempName, "error", err) + return fmt.Errorf("removing blob temp file: %w", err) } } + + return nil } // streamingChunkInfo tracks chunk metadata collected during streaming @@ -1739,16 +2073,11 @@ func (e *packerError) Error() string { return e.err.Error() } func (e *packerError) Unwrap() error { return e.err } -// processFileStreaming processes a file by streaming chunks directly to the packer +// processFileStreaming processes a regular file by streaming chunks directly +// to the packer func (s *Scanner) processFileStreaming( ctx context.Context, fileToProcess *FileToProcess, result *ScanResult, ) error { - // Symlinks and directories have no data to chunk — just record them in the DB. - mode := os.FileMode(fileToProcess.File.Mode) - if mode&os.ModeSymlink != 0 || mode.IsDir() { - return s.recordNonRegularFile(ctx, fileToProcess) - } - file, err := s.fs.Open(fileToProcess.Path) if err != nil { return fmt.Errorf("opening file: %w", wrapPermissionError(fileToProcess.Path, err)) @@ -1784,9 +2113,9 @@ func (s *Scanner) processFileStreaming( size: chunk.Size, }) - s.updateChunkStats(chunkExists, chunk.Size, result) - if !chunkExists { + s.updateChunkStats(chunk.Size, result) + err := s.addChunkToPacker(ctx, chunk) if err != nil { // Mark as a packer error so --skip-errors cannot swallow it: @@ -1814,26 +2143,17 @@ func (s *Scanner) processFileStreaming( return nil } -// updateChunkStats updates scan result and progress stats for a processed chunk -func (s *Scanner) updateChunkStats( - chunkExists bool, chunkSize int64, result *ScanResult, -) { - if chunkExists { - result.FilesSkipped++ +// updateChunkStats counts a chunk that was not already stored, and its +// size. The scan result's file counts, BytesScanned and BytesSkipped are +// not touched here: the scan phase counts each file once. +func (s *Scanner) updateChunkStats(chunkSize int64, result *ScanResult) { + result.ChunksCreated++ + result.NewChunkSize += chunkSize - result.BytesSkipped += chunkSize - if s.progress != nil { - s.progress.GetStats().BytesSkipped.Add(chunkSize) - } - } else { - result.ChunksCreated++ - result.BytesScanned += chunkSize - - if s.progress != nil { - s.progress.GetStats().ChunksCreated.Add(1) - s.progress.GetStats().BytesProcessed.Add(chunkSize) - s.progress.UpdateChunkingActivity() - } + if s.progress != nil { + s.progress.GetStats().ChunksCreated.Add(1) + s.progress.GetStats().BytesProcessed.Add(chunkSize) + s.progress.UpdateChunkingActivity() } } @@ -1896,21 +2216,29 @@ func (s *Scanner) queueFileForBatchInsert( }) } -// detectDeletedFilesFromMap finds files that existed in previous snapshots -// but no longer exist. Uses pre-loaded maps to avoid any filesystem or -// database access. -func (s *Scanner) detectDeletedFilesFromMap( +// detectDeletedFiles counts as deleted each file at or beneath path that +// the previous snapshot of this name lists, the walk did not find, and +// is gone from disk. A file that is excluded, or inside an excluded +// directory, is not counted: the walk skips it whether or not it is +// still on disk. +func (s *Scanner) detectDeletedFiles( ctx context.Context, - knownFiles map[string]*database.File, + path string, existingFiles map[string]struct{}, result *ScanResult, ) error { - if len(knownFiles) == 0 { + if s.previousSnapshotID == "" { return nil } - // Check each known file against the enumerated set (no filesystem access needed) - for path, file := range knownFiles { + previousFiles, err := s.repos.Files.ListUnderPathInSnapshot( + ctx, path, s.previousSnapshotID) + if err != nil { + return fmt.Errorf("listing files of snapshot %s: %w", + s.previousSnapshotID, err) + } + + for _, file := range previousFiles { // Check context cancellation periodically select { case <-ctx.Done(): @@ -1918,13 +2246,22 @@ func (s *Scanner) detectDeletedFilesFromMap( default: } - // Check if the file exists in our enumerated set - if _, exists := existingFiles[path]; !exists { - // File has been deleted - result.FilesDeleted++ - result.BytesDeleted += file.Size - log.Debug("Detected deleted file", "path", path, "size", file.Size) + filePath := file.Path.String() + + _, exists := existingFiles[filePath] + if exists || s.excludedOrInExcludedDir(filePath, path) { + continue } + + // Under --skip-errors the walk also misses what it cannot reach, + // such as the files in a directory it cannot open. + if !s.goneFromDisk(filePath) { + continue + } + + result.FilesDeleted++ + result.BytesDeleted += file.Size + log.Debug("Detected deleted file", "path", filePath, "size", file.Size) } if result.FilesDeleted > 0 { @@ -1935,6 +2272,37 @@ func (s *Scanner) detectDeletedFilesFromMap( return nil } +// excludedOrInExcludedDir reports whether filePath, which is at or +// beneath rootPath, or any directory between rootPath and it, matches an +// exclude pattern or is one of vaultik's own files. A pattern such as +// */.local/share/Trash matches the directory but not the files inside it, +// which the walk skips too. +func (s *Scanner) excludedOrInExcludedDir(filePath, rootPath string) bool { + for p := filePath; len(p) > len(rootPath); p = filepath.Dir(p) { + if s.shouldExclude(p, rootPath) { + return true + } + } + + return false +} + +// goneFromDisk reports whether looking filePath up on disk finds that +// it does not exist. Like the walk, it does not follow a symlink, so a +// symlink whose target is gone is still on disk. A file whose directory +// was replaced by a regular file is gone too, though the lookup reports +// "not a directory". +func (s *Scanner) goneFromDisk(filePath string) bool { + var err error + if lstater, ok := s.fs.(afero.Lstater); ok { + _, _, err = lstater.LstatIfPossible(filePath) + } else { + _, err = s.fs.Stat(filePath) + } + + return errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) +} + // wrapPermissionError augments permission errors with platform-specific // remediation instructions. On macOS, TCC-protected directories (Calendars, // Reminders, Photos, etc.) return EPERM unless the running application has @@ -1956,50 +2324,38 @@ func wrapPermissionError(path string, err error) error { "with --skip-errors to continue past unreadable files)", path, err) } -// compileExcludePatterns compiles the exclude patterns into glob matchers -func compileExcludePatterns(patterns []string) []compiledPattern { +// compileExcludePatterns compiles the exclude patterns into glob matchers. +// Config.Validate has already refused a pattern that does not compile. +func compileExcludePatterns(patterns []string) ([]compiledPattern, error) { var compiled []compiledPattern for _, p := range patterns { - if p == "" { - continue - } - - // Check if pattern is anchored (starts with /) - anchored := strings.HasPrefix(p, "/") - - pattern := p - if anchored { - pattern = p[1:] // Remove leading / - } - - // Remove trailing slash if present (directory indicator) - pattern = strings.TrimSuffix(pattern, "/") - - // Compile the glob pattern - // For patterns without path separators, we need to match them as components - // e.g., ".git" should match ".git" anywhere in the path - g, err := glob.Compile(pattern, '/') + globs, anchored, err := exclude.Compile(p) if err != nil { - log.Warn("Invalid exclude pattern, skipping", "pattern", p, "error", err) - - continue + return nil, err } - compiled = append(compiled, compiledPattern{ - pattern: g, - anchored: anchored, - original: p, - }) + for _, g := range globs { + compiled = append(compiled, compiledPattern{ + pattern: g, + anchored: anchored, + original: p, + }) + } } - return compiled + return compiled, nil } // shouldExclude checks if a path should be excluded based on exclude patterns +// or because it is one of vaultik's own working files. // filePath is the full path to the file // rootPath is the root of the backup source directory func (s *Scanner) shouldExclude(filePath, rootPath string) bool { + if _, ok := s.indexAndLockFiles[filePath]; ok { + return true + } + if len(s.compiledExclude) == 0 { return false } diff --git a/internal/snapshot/scanner_estimate_test.go b/internal/snapshot/scanner_estimate_test.go new file mode 100644 index 0000000..501c1a2 --- /dev/null +++ b/internal/snapshot/scanner_estimate_test.go @@ -0,0 +1,28 @@ +//nolint:testpackage // exercises the unexported countNonDirectories helper +package snapshot + +import ( + "os" + "testing" + + "sneak.berlin/go/vaultik/internal/database" +) + +// The walk counts regular files and symlinks, not directories, so the +// estimate of its count made from the local index's records leaves the +// directories out. See https://git.eeqj.de/sneak/vaultik/issues/305. +func TestCountNonDirectories(t *testing.T) { + t.Parallel() + + known := map[string]*database.File{ + "/src": {Mode: uint32(os.ModeDir | 0o755)}, + "/src/sub": {Mode: uint32(os.ModeDir | 0o755)}, + "/src/a.txt": {Mode: 0o644}, + "/src/link": {Mode: uint32(os.ModeSymlink | 0o777), LinkTarget: "a.txt"}, + } + + got := countNonDirectories(known) + if got != 2 { + t.Errorf("countNonDirectories = %d, want 2", got) + } +} diff --git a/internal/snapshot/scanner_test.go b/internal/snapshot/scanner_test.go index dfac28e..632d045 100644 --- a/internal/snapshot/scanner_test.go +++ b/internal/snapshot/scanner_test.go @@ -71,7 +71,7 @@ func verifySimpleScanDatabase( t.Helper() // Verify files in database - includes regular files and directories - files, err := repos.Files.ListByPrefix(ctx, "/source") + files, err := repos.Files.ListUnderPath(ctx, "/source") if err != nil { t.Fatalf("failed to list files: %v", err) } @@ -307,3 +307,80 @@ func TestScannerLargeFile(t *testing.T) { } } } + +// TestScannerRecordsOwnership backs up real files on disk and checks that +// the uid and gid of a file, a directory and a symlink are recorded. +// When the tests run as root both sides are 0, so only a run as another +// user can catch ownership recorded as 0. +func TestScannerRecordsOwnership(t *testing.T) { + t.Parallel() + + sourceDir := t.TempDir() + filePath := filepath.Join(sourceDir, "file.txt") + dirPath := filepath.Join(sourceDir, "subdir") + linkPath := filepath.Join(sourceDir, "link") + + err := os.WriteFile(filePath, []byte("owned"), 0o600) + if err != nil { + t.Fatal(err) + } + + err = os.Mkdir(dirPath, 0o700) + if err != nil { + t.Fatal(err) + } + + err = os.Symlink("file.txt", linkPath) + if err != nil { + t.Fatal(err) + } + + db, err := database.NewTestDB() + if err != nil { + t.Fatalf("failed to create test database: %v", err) + } + + defer func() { + err := db.Close() + if err != nil { + t.Errorf("failed to close database: %v", err) + } + }() + + repos := database.NewRepositories(db) + + scanner := snapshot.NewScanner(snapshot.ScannerConfig{ + FS: afero.NewOsFs(), + ChunkSize: int64(1024 * 16), + Repositories: repos, + MaxBlobSize: int64(1024 * 1024), + CompressionLevel: 3, + AgeRecipients: []string{testAgePublicKey}, + }) + + ctx := context.Background() + snapshotID := "test-snapshot-ownership" + + createTestSnapshotRecord(ctx, t, repos, snapshotID) + + _, err = scanner.Scan(ctx, sourceDir, snapshotID) + if err != nil { + t.Fatalf("scan failed: %v", err) + } + + for _, path := range []string{filePath, dirPath, linkPath} { + file, err := repos.Files.GetByPath(ctx, path) + if err != nil { + t.Fatalf("failed to get %s: %v", path, err) + } + + if file == nil { + t.Fatalf("%s was not recorded", path) + } + + if int(file.UID) != os.Getuid() || int(file.GID) != os.Getgid() { + t.Errorf("%s recorded as uid %d gid %d, want uid %d gid %d", + path, file.UID, file.GID, os.Getuid(), os.Getgid()) + } + } +} diff --git a/internal/snapshot/skip_errors_test.go b/internal/snapshot/skip_errors_test.go index 9ae128a..2a88637 100644 --- a/internal/snapshot/skip_errors_test.go +++ b/internal/snapshot/skip_errors_test.go @@ -3,6 +3,7 @@ package snapshot_test import ( "context" "errors" + "io" "os" "path/filepath" "strings" @@ -13,6 +14,7 @@ import ( "github.com/spf13/afero" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/ui" ) // errSimTempFail is the one-time temp-file creation failure blobTempFailFs @@ -80,6 +82,56 @@ func (f *readFailFs) Open(name string) (afero.File, error) { return file, nil } +// cancelOnOpenFs cancels the run when the scanner opens the target file to +// back it up, as Ctrl-C partway through processing would, and records each +// file opened after that. +type cancelOnOpenFs struct { + afero.Fs + + target string + cancel context.CancelFunc + cancelled bool + openedAfterCancel []string +} + +//nolint:ireturn // afero.Fs.Open is defined to return the interface. +func (f *cancelOnOpenFs) Open(name string) (afero.File, error) { + if f.cancelled { + f.openedAfterCancel = append(f.openedAfterCancel, name) + } + + if name == f.target { + f.cancel() + f.cancelled = true + } + + return f.Fs.Open(name) +} + +// linkRemovedAfterLstatFs is the real filesystem, except that the symlink at +// target is removed right after the walk lstats it, as happens when a link is +// deleted during a backup. The scanner's readlink of it then fails. +type linkRemovedAfterLstatFs struct { + afero.OsFs + + t *testing.T + target string +} + +func (f *linkRemovedAfterLstatFs) LstatIfPossible( + name string, +) (os.FileInfo, bool, error) { + info, lstatCalled, err := f.OsFs.LstatIfPossible(name) + if err == nil && name == f.target { + rmErr := os.Remove(name) + if rmErr != nil { + f.t.Errorf("removing %s: %v", name, rmErr) + } + } + + return info, lstatCalled, err +} + // writeSkipErrorTestFile writes one file into fs with a fixed mtime. func writeSkipErrorTestFile(t *testing.T, fs afero.Fs, path, content string) { t.Helper() @@ -102,14 +154,16 @@ func writeSkipErrorTestFile(t *testing.T, fs afero.Fs, path, content string) { } } -// runSkipErrorScan scans /source on fs with the given skip-errors setting and +// runSkipErrorScan scans source on fs under ctx with the given skip-errors +// setting, printing user-facing messages to uiw (nil discards them), and // returns the repositories (for inspection) and the scan error. func runSkipErrorScan( - t *testing.T, fs afero.Fs, skipErrors bool, + ctx context.Context, t *testing.T, fs afero.Fs, source string, + skipErrors bool, uiw *ui.Writer, ) (*database.Repositories, error) { t.Helper() - db, err := database.NewTestDB() + db, err := database.New(ctx, ":memory:") if err != nil { t.Fatalf("create test db: %v", err) } @@ -130,14 +184,14 @@ func runSkipErrorScan( MaxBlobSize: int64(1024 * 1024), CompressionLevel: 3, AgeRecipients: []string{testAgePublicKey}, + UI: uiw, SkipErrors: skipErrors, }) - ctx := context.Background() snapshotID := "test-snapshot-skip-errors" createTestSnapshotRecord(ctx, t, repos, snapshotID) - _, err = scanner.Scan(ctx, "/source", snapshotID) + _, err = scanner.Scan(ctx, source, snapshotID) return repos, err } @@ -157,7 +211,7 @@ func TestScannerPackingFailureAbortsUnderSkipErrors(t *testing.T) { writeSkipErrorTestFile(t, fs, "/source/file1.txt", "first file content") writeSkipErrorTestFile(t, fs, "/source/file2.txt", "second file content") - repos, err := runSkipErrorScan(t, fs, true) + repos, err := runSkipErrorScan(context.Background(), t, fs, "/source", true, nil) if err == nil { t.Fatal("expected scan to abort on the packer error, got nil") } @@ -184,7 +238,7 @@ func TestScannerReadErrorAbortsWithoutSkipErrors(t *testing.T) { fs := &readFailFs{Fs: afero.NewMemMapFs(), target: target} writeSkipErrorTestFile(t, fs, target, "content that cannot be read") - _, err := runSkipErrorScan(t, fs, false) + _, err := runSkipErrorScan(context.Background(), t, fs, "/source", false, nil) if err == nil { t.Fatal("expected scan to fail on the read error, got nil") } @@ -200,7 +254,7 @@ func TestScannerReadErrorSkippedWithSkipErrors(t *testing.T) { fs := &readFailFs{Fs: afero.NewMemMapFs(), target: target} writeSkipErrorTestFile(t, fs, target, "content that cannot be read") - repos, err := runSkipErrorScan(t, fs, true) + repos, err := runSkipErrorScan(context.Background(), t, fs, "/source", true, nil) if err != nil { t.Fatalf("expected scan to complete with --skip-errors, got %v", err) } @@ -214,3 +268,173 @@ func TestScannerReadErrorSkippedWithSkipErrors(t *testing.T) { t.Fatalf("expected unreadable file skipped, got %d chunks", len(chunks)) } } + +// writeSymlinkSource creates a source directory on disk holding one symlink +// and returns the directory and the symlink's path. +func writeSymlinkSource(t *testing.T) (string, string) { + t.Helper() + + sourceDir := t.TempDir() + linkPath := filepath.Join(sourceDir, "link") + + err := os.Symlink("target.txt", linkPath) + if err != nil { + t.Fatalf("creating symlink: %v", err) + } + + return sourceDir, linkPath +} + +// TestScannerUnreadableSymlinkAbortsWithoutSkipErrors checks that a symlink +// whose target cannot be read aborts the run when --skip-errors is not set. +func TestScannerUnreadableSymlinkAbortsWithoutSkipErrors(t *testing.T) { + t.Parallel() + + sourceDir, linkPath := writeSymlinkSource(t) + fs := &linkRemovedAfterLstatFs{t: t, target: linkPath} + + _, err := runSkipErrorScan(context.Background(), t, fs, sourceDir, false, nil) + if !errors.Is(err, os.ErrNotExist) { + t.Fatalf("expected scan to fail on the removed symlink, got %v", err) + } +} + +// TestScannerUnreadableSymlinkSkippedWithSkipErrors checks that a symlink +// whose target cannot be read is skipped with an error line, and the run +// completes, when --skip-errors is set. +func TestScannerUnreadableSymlinkSkippedWithSkipErrors(t *testing.T) { + t.Parallel() + + sourceDir, linkPath := writeSymlinkSource(t) + fs := &linkRemovedAfterLstatFs{t: t, target: linkPath} + uiw := ui.NewWithColor(io.Discard, false) + + repos, err := runSkipErrorScan(context.Background(), t, fs, sourceDir, true, uiw) + if err != nil { + t.Fatalf("expected scan to complete with --skip-errors, got %v", err) + } + + if uiw.ErrorCount() != 1 { + t.Fatalf("expected one error line for the symlink, got %d", + uiw.ErrorCount()) + } + + file, err := repos.Files.GetByPath(context.Background(), linkPath) + if err != nil { + t.Fatalf("getting %s: %v", linkPath, err) + } + + if file != nil { + t.Fatalf("expected %s not to be recorded", linkPath) + } +} + +// TestScannerCancelStopsSkipErrorsRun checks that a --skip-errors backup +// cancelled partway through processing returns the cancellation error, +// opens no further file, and reports no file as failed. +func TestScannerCancelStopsSkipErrorsRun(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + targetContent string + }{ + // The cancellation lands while the target is being read. + {name: "while reading a file", targetContent: "first file content"}, + // An empty target has no chunks, so the cancellation goes unnoticed + // until the run moves on to the next file. + {name: "between files", targetContent: ""}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + const target = "/source/a.txt" + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fs := &cancelOnOpenFs{ + Fs: afero.NewMemMapFs(), target: target, cancel: cancel, + } + writeSkipErrorTestFile(t, fs, target, tt.targetContent) + writeSkipErrorTestFile(t, fs, "/source/b.txt", "second file content") + writeSkipErrorTestFile(t, fs, "/source/c.txt", "third file content") + + uiw := ui.NewWithColor(io.Discard, false) + + _, err := runSkipErrorScan(ctx, t, fs, "/source", true, uiw) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected the cancellation error, got %v", err) + } + + if len(fs.openedAfterCancel) != 0 { + t.Fatalf("expected no file opened after the cancellation, got %v", + fs.openedAfterCancel) + } + + if uiw.ErrorCount() != 0 { + t.Fatalf("expected no file reported as failed, got %d error lines", + uiw.ErrorCount()) + } + }) + } +} + +// TestScannerRemovesBlobTempFileWhenRunStops checks that a run stopped +// part-way, by a file it cannot read or by a cancellation, removes the +// temp file of the blob it was packing. +func TestScannerRemovesBlobTempFileWhenRunStops(t *testing.T) { + t.Parallel() + + // a.txt is backed up first and starts a blob; the run stops at b.txt. + const target = "/source/b.txt" + + tests := []struct { + name string + newFs func(cancel context.CancelFunc) afero.Fs + }{ + { + name: "file cannot be read", + newFs: func(context.CancelFunc) afero.Fs { + return &readFailFs{Fs: afero.NewMemMapFs(), target: target} + }, + }, + { + name: "cancelled", + newFs: func(cancel context.CancelFunc) afero.Fs { + return &cancelOnOpenFs{ + Fs: afero.NewMemMapFs(), target: target, cancel: cancel, + } + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fs := tt.newFs(cancel) + writeSkipErrorTestFile(t, fs, "/source/a.txt", "first file content") + writeSkipErrorTestFile(t, fs, target, "second file content") + + _, err := runSkipErrorScan(ctx, t, fs, "/source", false, nil) + if err == nil { + t.Fatal("expected the scan to stop with an error, got nil") + } + + left, err := afero.Glob(fs, filepath.Join(os.TempDir(), "vaultik-blob-*")) + if err != nil { + t.Fatalf("listing blob temp files: %v", err) + } + + if len(left) != 0 { + t.Fatalf("expected no blob temp file left, got %v", left) + } + }) + } +} diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go index 2fac581..80c764e 100644 --- a/internal/snapshot/snapshot.go +++ b/internal/snapshot/snapshot.go @@ -105,26 +105,47 @@ func (sm *SnapshotManager) CreateSnapshot( return sm.CreateSnapshotWithName(ctx, hostname, "", version, gitRevision) } +// ShortHostname returns hostname up to its first dot. A snapshot ID starts +// with this form, while the snapshots table stores the full hostname. +func ShortHostname(hostname string) string { + short, _, _ := strings.Cut(hostname, ".") + + return short +} + // CreateSnapshotWithName creates a new snapshot record with an optional // snapshot name. The snapshot ID format is: hostname_name_timestamp or -// hostname_timestamp if name is empty. +// hostname_timestamp if name is empty. The timestamp is in whole seconds. +// If the local index already has a snapshot with that ID, from a run of the +// same name that started in the same second, it waits a second and takes a +// new timestamp. func (sm *SnapshotManager) CreateSnapshotWithName( ctx context.Context, hostname, name, version, gitRevision string, ) (string, error) { - // Use short hostname (strip domain if present) - shortHostname := hostname - if before, _, ok := strings.Cut(hostname, "."); ok { - shortHostname = before - } - - // Build snapshot ID with optional name - timestamp := time.Now().UTC().Format("2006-01-02T15:04:05Z") + shortHostname := ShortHostname(hostname) var snapshotID string - if name != "" { - snapshotID = fmt.Sprintf("%s_%s_%s", shortHostname, name, timestamp) - } else { - snapshotID = fmt.Sprintf("%s_%s", shortHostname, timestamp) + + for { + // Build snapshot ID with optional name + timestamp := time.Now().UTC().Format("2006-01-02T15:04:05Z") + + if name != "" { + snapshotID = fmt.Sprintf("%s_%s_%s", shortHostname, name, timestamp) + } else { + snapshotID = fmt.Sprintf("%s_%s", shortHostname, timestamp) + } + + existing, err := sm.repos.Snapshots.GetByID(ctx, snapshotID) + if err != nil { + return "", fmt.Errorf("looking up snapshot %s: %w", snapshotID, err) + } + + if existing == nil { + break + } + + time.Sleep(time.Second) } snapshot := &database.Snapshot{ @@ -154,26 +175,6 @@ func (sm *SnapshotManager) CreateSnapshotWithName( return snapshotID, nil } -// UpdateSnapshotStats updates the statistics for a snapshot during backup -func (sm *SnapshotManager) UpdateSnapshotStats( - ctx context.Context, snapshotID string, stats BackupStats, -) error { - err := sm.repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { - return sm.repos.Snapshots.UpdateCounts(ctx, tx, snapshotID, - int64(stats.FilesScanned), - int64(stats.ChunksCreated), - int64(stats.BlobsCreated), - stats.BytesScanned, - stats.BytesUploaded, - ) - }) - if err != nil { - return fmt.Errorf("updating snapshot stats: %w", err) - } - - return nil -} - // UpdateSnapshotStatsExtended updates snapshot statistics with extended metrics. // This includes compression level, uncompressed blob size, and upload duration. func (sm *SnapshotManager) UpdateSnapshotStatsExtended( @@ -185,8 +186,8 @@ func (sm *SnapshotManager) UpdateSnapshotStatsExtended( int64(stats.FilesScanned), int64(stats.ChunksCreated), int64(stats.BlobsCreated), - stats.BytesScanned, - stats.BytesUploaded, + stats.TotalSize, + stats.BlobSize, ) if err != nil { return err @@ -196,7 +197,9 @@ func (sm *SnapshotManager) UpdateSnapshotStatsExtended( return sm.repos.Snapshots.UpdateExtendedStats(ctx, tx, snapshotID, stats.BlobUncompressedSize, stats.CompressionLevel, + stats.BytesUploaded, stats.UploadDurationMs, + stats.NewChunkSize, ) }) } @@ -268,16 +271,18 @@ func (sm *SnapshotManager) CompleteSnapshot( return sm.MarkSnapshotComplete(ctx, snapshotID) } -// ExportSnapshotMetadata exports snapshot metadata to S3 +// ExportSnapshotMetadata exports snapshot metadata to the backup destination store // // This method executes the complete snapshot metadata export process: // 1. Creates a temporary directory for working files // 2. Copies the main database to preserve its state // 3. Cleans the copy to contain only current snapshot data -// 4. Dumps the cleaned database to SQL -// 5. Compresses the SQL dump with zstd -// 6. Encrypts the compressed data with age (always; recipients are required) -// 7. Uploads to S3 at: snapshots/{snapshot-id}.sql.zst[.age] +// 4. Vacuums the copy to remove the deleted data +// 5. Compresses the copy with zstd +// 6. Encrypts the compressed copy with age (always; recipients are required) +// 7. Builds the blob manifest from the copy, compressed but not encrypted +// 8. Uploads the database to metadata/{remote-key}/db.zst.age +// 9. Uploads the manifest to metadata/{remote-key}/manifest.json.zst // // The only caller (finalizeSnapshotMetadata) does not close the main database // before calling this method: the index is copied at dbPath while it is still @@ -386,12 +391,12 @@ func (sm *SnapshotManager) prepareExportDB( ctx context.Context, dbPath, snapshotID, tempDir string, ) ([]byte, string, error) { // Step 1: Copy database to temp file - // The main database should be closed at this point + // The main database is still open here, so it is copied through SQLite tempDBPath := filepath.Join(tempDir, "snapshot.db") log.Debug("Copying database to temporary location", "source", dbPath, "destination", tempDBPath) - err := sm.copyFile(dbPath, tempDBPath) + err := sm.copyDatabase(ctx, dbPath, tempDBPath) if err != nil { return nil, "", fmt.Errorf("copying database: %w", err) } @@ -515,8 +520,8 @@ type CleanupStats struct { // // The cleanup is performed in a specific order to maintain referential integrity: // 1. Delete other snapshots -// 2. Delete orphaned snapshot associations (snapshot_files, snapshot_blobs) -// for deleted snapshots +// 2. Delete orphaned snapshot associations (snapshot_files, snapshot_blobs, +// snapshot_mount_points) for deleted snapshots // 3. Delete orphaned files (not in the current snapshot) // 4. Delete orphaned chunk-to-file mappings (references to deleted files) // 5. Delete orphaned blobs (not in the current snapshot) @@ -648,9 +653,10 @@ func (sm *SnapshotManager) collectCleanupStats( // // VACUUM runs through the modernc.org/sqlite driver, on a freshly opened // connection with no transaction in flight (VACUUM cannot run inside one). -// The database opens in WAL mode, so VACUUM's rewrite lands in the WAL; the -// checkpoint on Close flushes it into the main file, which is the file we -// then compress and upload. +// database.New opens the file in WAL mode, so VACUUM's rewrite lands in the +// -wal file. This is the only connection to the file, so closing it +// checkpoints the rewrite into the main file and removes the -wal file; the +// main file is the one compressFile then compresses and uploads. func (sm *SnapshotManager) vacuumDatabase(ctx context.Context, dbPath string) error { log.Debug("Running VACUUM on database", "path", dbPath) @@ -744,26 +750,15 @@ func (sm *SnapshotManager) compressFile(inputPath, outputPath string) error { // user; it holds the same private index data as the local index file. const exportCopyPerm = 0o600 -// copyFile copies a file from src to dst. The destination is the exported -// snapshot database, so it is created owner-only rather than with the -// umask-dependent default. -func (sm *SnapshotManager) copyFile(src, dst string) error { - log.Debug("Opening source file for copy", "path", src) - - sourceFile, err := sm.fs.Open(src) - if err != nil { - return err - } - - defer func() { - log.Debug("Closing source file", "path", src) - - err := sourceFile.Close() - if err != nil { - log.Debug("Failed to close source file", "path", src, "error", err) - } - }() - +// copyDatabase copies the database at src to dst with VACUUM INTO. It reads +// through SQLite, so the copy holds rows committed to src that are still in +// its -wal file, which a copy of the file alone would miss. The destination +// is the exported snapshot database, so it is created empty and owner-only +// first rather than with the umask-dependent default: VACUUM INTO writes +// into an existing empty file and keeps its mode. +func (sm *SnapshotManager) copyDatabase( + ctx context.Context, src, dst string, +) error { log.Debug("Creating destination file", "path", dst) destFile, err := sm.fs.OpenFile( @@ -773,23 +768,28 @@ func (sm *SnapshotManager) copyFile(src, dst string) error { return err } - defer func() { - log.Debug("Closing destination file", "path", dst) - - err := destFile.Close() - if err != nil { - log.Debug("Failed to close destination file", "path", dst, "error", err) - } - }() - - log.Debug("Copying file data") - - n, err := io.Copy(destFile, sourceFile) + err = destFile.Close() if err != nil { return err } - log.Debug("File copy complete", "bytes_copied", n) + db, err := database.New(ctx, src) + if err != nil { + return fmt.Errorf("opening database to copy: %w", err) + } + + defer func() { + cerr := db.Close() + if cerr != nil { + log.Debug("Failed to close database after copy", + "path", src, "error", cerr) + } + }() + + _, err = db.ExecWithLog(ctx, "VACUUM INTO ?", dst) + if err != nil { + return fmt.Errorf("running VACUUM INTO: %w", err) + } return nil } @@ -895,7 +895,7 @@ func (sm *SnapshotManager) getFileSize(path string) int64 { // BackupStats contains statistics from a backup operation type BackupStats struct { FilesScanned int - BytesScanned int64 + TotalSize int64 // Total size of the files in the snapshot ChunksCreated int BlobsCreated int BytesUploaded int64 @@ -905,9 +905,11 @@ type BackupStats struct { type ExtendedBackupStats struct { BackupStats + BlobSize int64 // Total compressed size of all referenced blobs BlobUncompressedSize int64 // Total uncompressed size of all referenced blobs CompressionLevel int // Compression level used for this snapshot UploadDurationMs int64 // Total milliseconds spent uploading to S3 + NewChunkSize int64 // Total size of the chunks counted in ChunksCreated } // deleteOtherSnapshots deletes all snapshots except the current one @@ -948,8 +950,8 @@ func (sm *SnapshotManager) deleteOtherSnapshots( return nil } -// deleteOrphanedSnapshotAssociations deletes snapshot_files and -// snapshot_blobs for deleted snapshots +// deleteOrphanedSnapshotAssociations deletes snapshot_files, +// snapshot_blobs and snapshot_mount_points for deleted snapshots func (sm *SnapshotManager) deleteOrphanedSnapshotAssociations( ctx context.Context, tx *sql.Tx, currentSnapshotID string, ) error { @@ -983,6 +985,19 @@ func (sm *SnapshotManager) deleteOrphanedSnapshotAssociations( log.Debug("[Temp DB Cleanup] Deleted snapshot_blobs associations", "count", rowsAffected) + // Delete the mount points other snapshots recorded + query := "DELETE FROM snapshot_mount_points WHERE snapshot_id != ?" + database.LogSQL("Execute", query, currentSnapshotID) + + result, err = tx.ExecContext(ctx, query, currentSnapshotID) + if err != nil { + return fmt.Errorf("deleting orphaned snapshot_mount_points: %w", err) + } + + rowsAffected, _ = result.RowsAffected() + log.Debug("[Temp DB Cleanup] Deleted snapshot_mount_points rows", + "count", rowsAffected) + return nil } diff --git a/internal/snapshot/snapshot_test.go b/internal/snapshot/snapshot_test.go index 42061a2..b371d72 100644 --- a/internal/snapshot/snapshot_test.go +++ b/internal/snapshot/snapshot_test.go @@ -7,12 +7,14 @@ import ( "database/sql" "io" "path/filepath" + "slices" "testing" "github.com/spf13/afero" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/types" ) const ( @@ -188,6 +190,77 @@ func TestVacuumDatabaseRemovesDeletedData(t *testing.T) { } } +// TestPrepareExportDBKeepsRowsCommittedToOpenIndex exports from an index +// that is still open, as a backup does. A row committed there can still be +// in the index's -wal file, and the export must hold it all the same. +func TestPrepareExportDBKeepsRowsCommittedToOpenIndex(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + fs := afero.NewOsFs() + + dbPath := filepath.Join(t.TempDir(), "index.sqlite") + + db, err := database.New(ctx, dbPath) + if err != nil { + t.Fatalf("failed to create database: %v", err) + } + + defer func() { _ = db.Close() }() + + repos := database.NewRepositories(db) + + snapshot := &database.Snapshot{ID: "open-index-snapshot", Hostname: "test-host"} + + err = repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + return repos.Snapshots.Create(ctx, tx, snapshot) + }) + if err != nil { + t.Fatalf("failed to create snapshot: %v", err) + } + + sm := &SnapshotManager{ + config: &config.Config{ + CompressionLevel: 3, + AgeRecipients: []string{testAgeRecipient}, + }, + fs: fs, + } + + _, tempDBPath, err := sm.prepareExportDB( + ctx, dbPath, snapshot.ID.String(), t.TempDir()) + if err != nil { + t.Fatalf("prepareExportDB failed: %v", err) + } + + // Only the main database file is compressed and uploaded, so open a + // copy of that file alone. + uploadedPath := filepath.Join(t.TempDir(), "uploaded.db") + + err = copyFile(fs, tempDBPath, uploadedPath) + if err != nil { + t.Fatalf("failed to copy exported database: %v", err) + } + + exported, err := database.OpenReadOnly(ctx, uploadedPath) + if err != nil { + t.Fatalf("failed to open exported database: %v", err) + } + + defer func() { _ = exported.Close() }() + + got, err := database.NewRepositories(exported).Snapshots.GetByID( + ctx, snapshot.ID.String()) + if err != nil { + t.Fatalf("failed to read snapshot from export: %v", err) + } + + if got == nil { + t.Fatal("exported database is missing the snapshot row") + } +} + func TestCleanSnapshotDBEmptySnapshot(t *testing.T) { // Initialize logger log.Initialize(log.Config{}) @@ -315,3 +388,107 @@ func TestCleanSnapshotDBNonExistentSnapshot(t *testing.T) { t.Fatalf("unexpected error: %v", err) } } + +// The exported metadata database keeps only the mount points that the +// exported snapshot recorded. See +// https://git.eeqj.de/sneak/vaultik/issues/395. +func TestCleanSnapshotDBKeepsOnlyTheSnapshotsMountPoints(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + dbPath := filepath.Join(t.TempDir(), "export.db") + + db, err := database.New(ctx, dbPath) + if err != nil { + t.Fatalf("failed to create database: %v", err) + } + + repos := database.NewRepositories(db) + + for _, id := range []types.SnapshotID{"exported", "other"} { + err = repos.Snapshots.Create(ctx, nil, &database.Snapshot{ID: id}) + if err != nil { + t.Fatalf("failed to create snapshot: %v", err) + } + + err = repos.Snapshots.AddMountPoint(ctx, nil, id.String(), "/data/"+id.String()) + if err != nil { + t.Fatalf("failed to add mount point: %v", err) + } + } + + err = db.Close() + if err != nil { + t.Fatalf("failed to close database: %v", err) + } + + sm := &SnapshotManager{ + config: &config.Config{ + CompressionLevel: 3, + AgeRecipients: []string{testAgeRecipient}, + }, + fs: afero.NewOsFs(), + } + + _, err = sm.cleanSnapshotDB(ctx, dbPath, "exported") + if err != nil { + t.Fatalf("failed to clean snapshot database: %v", err) + } + + cleaned, err := database.New(ctx, dbPath) + if err != nil { + t.Fatalf("failed to open cleaned database: %v", err) + } + + defer func() { _ = cleaned.Close() }() + + cleanedRepos := database.NewRepositories(cleaned) + + for id, want := range map[string][]string{ + "exported": {"/data/exported"}, + "other": nil, + } { + got, err := cleanedRepos.Snapshots.GetMountPoints(ctx, id) + if err != nil { + t.Fatalf("failed to read mount points: %v", err) + } + + if !slices.Equal(got, want) { + t.Errorf("mount points of %s: got %v, want %v", id, got, want) + } + } +} + +// Two creates of one snapshot name back to back start within one second, +// the resolution of the timestamp in a snapshot ID. See +// https://git.eeqj.de/sneak/vaultik/issues/270. +func TestCreateSnapshotWithNameTwiceBackToBack(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + + db, err := database.New(ctx, filepath.Join(t.TempDir(), "index.sqlite")) + if err != nil { + t.Fatalf("failed to create database: %v", err) + } + + defer func() { _ = db.Close() }() + + sm := &SnapshotManager{repos: database.NewRepositories(db)} + + first, err := sm.CreateSnapshotWithName(ctx, "test-host", "data", "v", "g") + if err != nil { + t.Fatalf("first create failed: %v", err) + } + + second, err := sm.CreateSnapshotWithName(ctx, "test-host", "data", "v", "g") + if err != nil { + t.Fatalf("second create failed: %v", err) + } + + if first == second { + t.Fatalf("both creates returned snapshot ID %s", first) + } +} diff --git a/internal/snapshot/upload_cancel_log_test.go b/internal/snapshot/upload_cancel_log_test.go new file mode 100644 index 0000000..f17f5ee --- /dev/null +++ b/internal/snapshot/upload_cancel_log_test.go @@ -0,0 +1,135 @@ +//nolint:testpackage // exercises the unexported uploadBlobIfNeeded +package snapshot + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "sneak.berlin/go/vaultik/internal/blob" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/ui" +) + +const uploadFailedLogMessage = "Failed to upload blob" + +// uploadTestBlob uploads a small blob through store. +func uploadTestBlob(ctx context.Context, store storage.Storer) error { + data := []byte("blob data") + s := &Scanner{storage: store, ui: ui.NewWithColor(io.Discard, false)} + + _, _, err := s.uploadBlobIfNeeded(ctx, "blobs/test", &blob.WithReader{ + FinishedBlob: &blob.FinishedBlob{ + Hash: "test", + Compressed: int64(len(data)), + }, + Reader: bytes.NewReader(data), + }, time.Now(), &ScanResult{}) + + return err +} + +// captureLog runs fn and returns what the logger wrote to stderr +// meanwhile, at the --verbose level. The logger writes to the os.Stderr +// it finds when it is initialized, so os.Stderr is pointed at a file +// first. Not parallel-safe: os.Stderr and the logger are process-global. +func captureLog(t *testing.T, fn func()) string { + t.Helper() + + stderrPath := filepath.Join(t.TempDir(), "stderr") + + stderrFile, err := os.Create(stderrPath) //nolint:gosec // G304: test temp path + if err != nil { + t.Fatalf("creating stderr file: %v", err) + } + + previous := os.Stderr + os.Stderr = stderrFile + + log.Initialize(log.Config{Verbose: true}) + + fn() + + os.Stderr = previous + + log.Initialize(log.Config{}) + + _ = stderrFile.Close() + + captured, err := os.ReadFile(stderrPath) //nolint:gosec // G304: test temp path + if err != nil { + t.Fatalf("reading stderr file: %v", err) + } + + return string(captured) +} + +// An upload stopped by Ctrl-C or SIGTERM is not logged as an error; the +// interrupted message is all the user sees. See +// https://git.eeqj.de/sneak/vaultik/issues/434. +// +//nolint:paralleltest // captureLog replaces os.Stderr +func TestInterruptedUploadIsNotLoggedAsError(t *testing.T) { + inner, err := storage.NewFileStorer(t.TempDir()) + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + // The user interrupts mid-upload. The injected error does not wrap + // context.Canceled, so only ctx shows why the upload failed. + store := faultstore.New(inner) + store.OnPut = func(string) faultstore.PutAction { + cancel() + + return faultstore.PutFail + } + + var uploadErr error + + stderr := captureLog(t, func() { uploadErr = uploadTestBlob(ctx, store) }) + + if uploadErr == nil { + t.Fatal("expected the upload to fail") + } + + if strings.Contains(stderr, uploadFailedLogMessage) { + t.Errorf("interrupted upload logged as a failure: %q", stderr) + } +} + +// An upload that fails for any other reason is still logged. +// +//nolint:paralleltest // captureLog replaces os.Stderr +func TestFailedUploadIsLogged(t *testing.T) { + inner, err := storage.NewFileStorer(t.TempDir()) + if err != nil { + t.Fatal(err) + } + + store := faultstore.New(inner) + store.OnPut = func(string) faultstore.PutAction { return faultstore.PutFail } + + var uploadErr error + + stderr := captureLog(t, func() { + uploadErr = uploadTestBlob(context.Background(), store) + }) + + if uploadErr == nil { + t.Fatal("expected the upload to fail") + } + + if !strings.Contains(stderr, uploadFailedLogMessage) { + t.Errorf("failed upload not logged: %q", stderr) + } +} diff --git a/internal/storage/conformance_test.go b/internal/storage/conformance_test.go index 7282341..8e8ebbe 100644 --- a/internal/storage/conformance_test.go +++ b/internal/storage/conformance_test.go @@ -8,25 +8,29 @@ import ( "reflect" "sort" "testing" + "time" "sneak.berlin/go/vaultik/internal/storage" ) // runStorerConformance is the shared Storer contract. Every backend that // can run in-process is expected to pass it: TestFileStorer runs it against -// file://, TestS3Storer against s3://. A new backend inherits this coverage -// by passing its own constructor, so the contract is defined once. +// file://, TestS3Storer against s3://, TestRcloneStorer against rclone's +// local backend. A new backend inherits this coverage by passing its own +// constructor, so the contract is defined once. // // It exercises the public Storer interface: round-trip, stat, list with -// prefix filtering, overwrite, delete, delete-of-missing, and not-found on -// Get and Stat. Each section takes its own fresh backend instance, so the -// order of sections never matters and no section sees another's objects. +// prefix filtering, the modification time ListStream reports, overwrite, +// delete, delete-of-missing, and not-found on Get and Stat. Each section +// takes its own fresh backend instance, so the order of sections never +// matters and no section sees another's objects. func runStorerConformance(t *testing.T, newStorer func(*testing.T) storage.Storer) { t.Helper() conformanceRoundTrip(t, newStorer(t)) conformanceOverwrite(t, newStorer(t)) conformanceList(t, newStorer(t)) + conformanceListStreamModTime(t, newStorer(t)) conformanceDelete(t, newStorer(t)) conformanceNotFound(t, newStorer(t)) } @@ -117,6 +121,35 @@ func conformanceList(t *testing.T, s storage.Storer) { } } +// conformanceListStreamModTime checks that ListStream gives an object +// just written a modification time of about now, which prune compares +// with its grace period. +func conformanceListStreamModTime(t *testing.T, s storage.Storer) { + t.Helper() + + ctx := context.Background() + + err := s.Put(ctx, "blobs/dd/written-now", bytes.NewReader([]byte("data"))) + if err != nil { + t.Fatalf("Put: %v", err) + } + + var listed []storage.ObjectInfo + + for info := range s.ListStream(ctx, "blobs/") { + listed = append(listed, info) + } + + if len(listed) != 1 || listed[0].Err != nil { + t.Fatalf("ListStream(\"blobs/\") = %v, want the one object", listed) + } + + if time.Since(listed[0].ModTime).Abs() > time.Minute { + t.Errorf("ListStream ModTime = %v, want within a minute of now", + listed[0].ModTime) + } +} + // conformanceDelete checks that Delete removes an object and that deleting // a missing key is not an error. func conformanceDelete(t *testing.T, s storage.Storer) { diff --git a/internal/storage/faultstore/faultstore.go b/internal/storage/faultstore/faultstore.go index 3aad29a..10afb4f 100644 --- a/internal/storage/faultstore/faultstore.go +++ b/internal/storage/faultstore/faultstore.go @@ -1,15 +1,18 @@ // Package faultstore provides a storage.Storer wrapper that injects // faults on demand, so tests can reproduce the failure modes a real // backend exhibits: an upload that fails partway, a backend that reports -// success while storing nothing, and reads that return corrupt or -// truncated bytes. It is the seam called for by the fault-injection -// tests (sneak/vaultik issue 72) and is meant to be reused by future -// tests rather than re-implemented per case. +// success while storing nothing, reads that return corrupt or truncated +// bytes, and a delete or a stat the backend refuses. It is the seam +// called for by the fault-injection tests (sneak/vaultik issue 72) and +// is meant to be reused by future tests rather than re-implemented per +// case. // -// The wrapper delegates every method to the inner Storer. Two hooks -// change that: OnPut decides the fate of each write, and OnGet decides -// how each read's bytes are returned. Both are keyed by the object key, -// so a test can fault only blobs, only metadata, or a single object. +// The wrapper delegates every method to the inner Storer. Four hooks +// change that: OnPut decides the fate of each write, OnGet decides how +// each read's bytes are returned, OnDelete decides whether each delete +// fails, and OnStat whether each stat fails. All are keyed by the object +// key, so a test can fault only blobs, only metadata, or a single +// object. package faultstore import ( @@ -25,6 +28,15 @@ import ( // ErrInjectedUpload is returned by a Put the OnPut hook chose to fail. var ErrInjectedUpload = errors.New("faultstore: injected upload failure") +// ErrInjectedDelete is returned by a Delete the OnDelete hook chose to +// fail. +var ErrInjectedDelete = errors.New("faultstore: injected delete failure") + +// ErrInjectedStat is returned by a Stat the OnStat hook chose to fail. +// It is not storage.ErrNotFound: the backend refused the request, as S3 +// refuses a HEAD to credentials that allow only PUT. +var ErrInjectedStat = errors.New("faultstore: injected stat failure") + // PutAction is the disposition OnPut assigns to a write. type PutAction int @@ -66,6 +78,15 @@ type Storer struct { // OnGet, when set, is consulted for every Get with the object key // and damages the returned bytes accordingly. OnGet func(key string) GetFault + + // OnDelete, when set, is consulted before every Delete with the + // object key. Returning true fails the delete and leaves the object + // in place. + OnDelete func(key string) bool + + // OnStat, when set, is consulted before every Stat with the object + // key. Returning true fails the stat with ErrInjectedStat. + OnStat func(key string) bool } // New wraps inner. inner must be non-nil. @@ -149,13 +170,21 @@ func damage(fault GetFault, data []byte) []byte { return out } -// Stat delegates unchanged. +// Stat returns the object's info unless OnStat fails the stat. func (f *Storer) Stat(ctx context.Context, key string) (*storage.ObjectInfo, error) { + if f.OnStat != nil && f.OnStat(key) { + return nil, fmt.Errorf("%w for %q", ErrInjectedStat, key) + } + return f.inner.Stat(ctx, key) } -// Delete delegates unchanged. +// Delete removes the object unless OnDelete fails the delete. func (f *Storer) Delete(ctx context.Context, key string) error { + if f.OnDelete != nil && f.OnDelete(key) { + return fmt.Errorf("%w for %q", ErrInjectedDelete, key) + } + return f.inner.Delete(ctx, key) } @@ -171,6 +200,11 @@ func (f *Storer) ListStream( return f.inner.ListStream(ctx, prefix) } +// DeletePartialUploads delegates unchanged. +func (f *Storer) DeletePartialUploads(ctx context.Context, prefix string) error { + return f.inner.DeletePartialUploads(ctx, prefix) +} + // Info delegates unchanged. func (f *Storer) Info() storage.Info { return f.inner.Info() diff --git a/internal/storage/file.go b/internal/storage/file.go index 5c31898..734a748 100644 --- a/internal/storage/file.go +++ b/internal/storage/file.go @@ -21,12 +21,16 @@ type FileStorer struct { // NewFileStorer creates a new filesystem storage backend. // // Construction is intentionally cheap and does not touch the filesystem. -// The basePath is recorded; the directory is created lazily on first -// write. Reads (Get/Stat/List) tolerate a missing basePath — a missing -// or unmounted destination during `snapshot list` should NOT block the -// command, it should degrade to "no remote snapshots reachable" with a -// warning. Write operations (Put/PutWithProgress) call MkdirAll for the -// per-blob parent directory, which also covers basePath on first use. +// The backend never creates basePath: the user does, so that when +// basePath is a directory on an unplugged volume, a write fails instead +// of landing on the disk under the mount point. This does not hold when +// basePath is the mount point itself, which stays behind when its volume +// is unplugged. +// Put and PutWithProgress fail on a missing basePath and create the +// directories below it as needed. +// Get and Stat report a key under a missing basePath as ErrNotFound. +// List and ListStream fail on a missing basePath, because listing it as +// an empty store would make `prune` drop every local snapshot record. // // Uses the real OS filesystem by default; call SetFilesystem to // override for testing. @@ -50,9 +54,10 @@ const storageDirPerm = 0o755 // temp file carrying this suffix and only renames it onto the real key once // the whole object is on disk, so an interrupted write can never leave a // truncated object at the key a later run would Stat and trust as a complete -// blob. List and ListStream skip these files, so a leftover from an -// interrupted write is never listed or trusted as a blob; it is otherwise -// harmless and is overwritten when the same key is written again. +// blob. The rclone backend's upload does the same on remotes with a +// server-side move. List and ListStream skip these files, so a leftover from +// an interrupted write is never listed or trusted as a blob; it is otherwise +// harmless. const tempSuffix = ".partial" // Put stores data at the specified key. @@ -119,14 +124,21 @@ func (f *FileStorer) Delete(_ context.Context, key string) error { return nil } -// List returns all keys with the given prefix. +// List returns all keys with the given prefix, reading through symlinked +// directories. It fails when the destination directory is missing, or +// when the prefix or a directory above it is a symlink whose target is +// missing; a prefix that is truly missing is an empty listing. func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) { var keys []string + _, err := f.fs.Stat(f.basePath) + if err != nil { + return nil, fmt.Errorf("checking destination directory: %w", err) + } + basePath := f.fullPath(prefix) - // Check if base path exists - exists, err := afero.Exists(f.fs, basePath) + exists, err := f.prefixExists(prefix) if err != nil { return nil, fmt.Errorf("checking path: %w", err) } @@ -135,7 +147,7 @@ func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) return keys, nil // Empty list for non-existent prefix } - err = afero.Walk(f.fs, basePath, func(path string, info os.FileInfo, err error) error { + err = f.walk(basePath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } @@ -167,17 +179,26 @@ func (f *FileStorer) List(ctx context.Context, prefix string) ([]string, error) return keys, nil } -// ListStream returns a channel of ObjectInfo for large result sets. +// ListStream returns a channel of ObjectInfo for large result sets. Like +// List, it reads through symlinked directories and sends an error when +// the destination directory is missing, or when the prefix or a directory +// above it is a symlink whose target is missing. func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan ObjectInfo { ch := make(chan ObjectInfo) go func() { defer close(ch) + _, err := f.fs.Stat(f.basePath) + if err != nil { + ch <- ObjectInfo{Err: fmt.Errorf("checking destination directory: %w", err)} + + return + } + basePath := f.fullPath(prefix) - // Check if base path exists - exists, err := afero.Exists(f.fs, basePath) + exists, err := f.prefixExists(prefix) if err != nil { ch <- ObjectInfo{Err: fmt.Errorf("checking path: %w", err)} @@ -188,7 +209,7 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec return // Empty channel for non-existent prefix } - _ = afero.Walk(f.fs, basePath, func(path string, info os.FileInfo, err error) error { + _ = f.walk(basePath, func(path string, info os.FileInfo, err error) error { // Check context cancellation select { case <-ctx.Done(): @@ -214,8 +235,9 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec // Normalize path separators relPath = strings.ReplaceAll(relPath, string(filepath.Separator), "/") ch <- ObjectInfo{ - Key: relPath, - Size: info.Size(), + Key: relPath, + Size: info.Size(), + ModTime: info.ModTime(), } } @@ -226,6 +248,43 @@ func (f *FileStorer) ListStream(ctx context.Context, prefix string) <-chan Objec return ch } +// DeletePartialUploads removes every file under prefix whose name ends in +// tempSuffix. Like List, it reads through symlinked directories and fails +// on one whose target is missing. A missing prefix has none to remove. +func (f *FileStorer) DeletePartialUploads(ctx context.Context, prefix string) error { + basePath := f.fullPath(prefix) + + exists, err := f.prefixExists(prefix) + if err != nil { + return fmt.Errorf("checking path: %w", err) + } + + if !exists { + return nil + } + + err = f.walk(basePath, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + if ctx.Err() != nil { + return ctx.Err() + } + + if info.IsDir() || !strings.HasSuffix(info.Name(), tempSuffix) { + return nil + } + + return f.fs.Remove(path) + }) + if err != nil { + return fmt.Errorf("walking directory: %w", err) + } + + return nil +} + // Info returns human-readable storage location information. func (f *FileStorer) Info() Info { return Info{ @@ -245,7 +304,19 @@ func (f *FileStorer) writeAtomic( path := f.fullPath(key) dir := filepath.Dir(path) - err := f.fs.MkdirAll(dir, storageDirPerm) + // Checked on every write, so a destination that disappears part-way + // through a backup fails it rather than being recreated by MkdirAll. + _, err := f.fs.Stat(f.basePath) + if os.IsNotExist(err) { + return fmt.Errorf("destination directory does not exist; "+ + "create it, or mount the volume it is on: %w", err) + } + + if err != nil { + return fmt.Errorf("checking destination directory: %w", err) + } + + err = f.fs.MkdirAll(dir, storageDirPerm) if err != nil { return fmt.Errorf("creating directories: %w", err) } @@ -300,6 +371,54 @@ func (f *FileStorer) writeAtomic( return nil } +// walk is afero.Walk, except that it reads through a symlinked directory +// the way Get and Stat do, where afero.Walk reports the link as one file. +// afero.Walk uses Lstat, which does not follow a link, whenever the +// filesystem has one; the struct below carries only the afero.Fs methods, +// so the walk uses Stat instead. A link back up the tree is followed until +// the operating system refuses the path for too many levels of links, and +// the walk then fails. +func (f *FileStorer) walk(root string, fn filepath.WalkFunc) error { + return afero.Walk(struct{ afero.Fs }{f.fs}, root, fn) +} + +// prefixExists reports whether prefix exists under the destination +// directory. It checks each directory on the way down to prefix in turn, +// and the first one Stat cannot find decides: if it is not there at all, +// prefix is missing; if it is a symlink whose target is missing, such as +// a link to a volume that is not mounted, prefixExists fails, since +// listing it as empty would let prune delete every blob. +func (f *FileStorer) prefixExists(prefix string) (bool, error) { + lstater, canLstat := f.fs.(afero.Lstater) + path := f.basePath + + for name := range strings.SplitSeq(prefix, "/") { + path = filepath.Join(path, name) + + _, err := f.fs.Stat(path) + if err == nil { + continue + } + + if !os.IsNotExist(err) { + return false, err + } + + // Lstat does not follow a symlink at path, so it finds the link + // that Stat could not follow. + if canLstat { + _, _, lstatErr := lstater.LstatIfPossible(path) + if lstatErr == nil { + return false, err + } + } + + return false, nil + } + + return true, nil +} + // fullPath returns the full filesystem path for a key. func (f *FileStorer) fullPath(key string) string { return filepath.Join(f.basePath, key) diff --git a/internal/storage/file_atomic_test.go b/internal/storage/file_atomic_test.go index 9006695..6030ea2 100644 --- a/internal/storage/file_atomic_test.go +++ b/internal/storage/file_atomic_test.go @@ -14,6 +14,9 @@ import ( // errStreamInterrupted stands in for an upload cut off mid-stream. var errStreamInterrupted = errors.New("connection reset mid-upload") +// testBlobKey is a key laid out as a blob's key is. +const testBlobKey = "blobs/aa/bb/aabbccddeeff" + // failingReader yields its data once, then fails. type failingReader struct { data []byte @@ -43,7 +46,7 @@ func TestFileStorer_InterruptedWriteLeavesNoTrustedObject(t *testing.T) { } ctx := context.Background() - key := "blobs/aa/bb/aabbccddeeff" + key := testBlobKey err = f.PutWithProgress(ctx, key, &failingReader{data: []byte("partial")}, 4096, nil) if err == nil { @@ -79,7 +82,7 @@ func TestFileStorer_ListSkipsPartialFiles(t *testing.T) { } ctx := context.Background() - realKey := "blobs/aa/bb/aabbccddeeff" + realKey := testBlobKey err = f.Put(ctx, realKey, strings.NewReader("blob-bytes")) if err != nil { @@ -117,3 +120,45 @@ func TestFileStorer_ListSkipsPartialFiles(t *testing.T) { t.Fatalf("ListStream should return only the real key, got %v", streamed) } } + +// TestFileStorer_DeletePartialUploads checks that a leftover temp file is +// removed and the object at the real key is kept. +func TestFileStorer_DeletePartialUploads(t *testing.T) { + t.Parallel() + + base := t.TempDir() + + f, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + ctx := context.Background() + + err = f.Put(ctx, testBlobKey, strings.NewReader("blob-bytes")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + leftover := filepath.Join(base, testBlobKey+"-123456.partial") + + err = os.WriteFile(leftover, []byte("half"), 0o600) + if err != nil { + t.Fatalf("writing leftover temp file: %v", err) + } + + err = f.DeletePartialUploads(ctx, "blobs/") + if err != nil { + t.Fatalf("DeletePartialUploads: %v", err) + } + + _, err = os.Stat(leftover) + if !os.IsNotExist(err) { + t.Errorf("leftover temp file was not removed: %v", err) + } + + _, err = f.Stat(ctx, testBlobKey) + if err != nil { + t.Errorf("Stat of the real key: %v", err) + } +} diff --git a/internal/storage/file_backend_test.go b/internal/storage/file_backend_test.go index de5ef31..15cf6a8 100644 --- a/internal/storage/file_backend_test.go +++ b/internal/storage/file_backend_test.go @@ -1,6 +1,13 @@ package storage_test import ( + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "reflect" + "strings" "testing" "sneak.berlin/go/vaultik/internal/storage" @@ -25,3 +32,303 @@ func TestFileStorer(t *testing.T) { t.Parallel() runStorerConformance(t, newFileStorer) } + +// TestFileStorerListMissingDestination checks that List and ListStream +// fail when the destination directory does not exist, instead of +// reporting an empty store. +func TestFileStorerListMissingDestination(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + s, err := storage.NewFileStorer(filepath.Join(t.TempDir(), "unmounted")) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + keys, err := s.List(ctx, "metadata/") + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("List = %v, %v; want a not-exist error", keys, err) + } + + var streamErr error + + for object := range s.ListStream(ctx, "metadata/") { + if object.Err != nil { + streamErr = object.Err + } + } + + if !errors.Is(streamErr, fs.ErrNotExist) { + t.Errorf("ListStream error = %v, want a not-exist error", streamErr) + } +} + +// The two directories at the top of a destination, either of which the +// tests below replace with a symlink. +const ( + metadataDir = "metadata" + blobsDir = "blobs" +) + +// moveBehindSymlink moves base/dir to a directory elsewhere and puts a +// symlink to it in its place. +func moveBehindSymlink(t *testing.T, base, dir string) { + t.Helper() + + linkPath := filepath.Join(base, dir) + movedPath := filepath.Join(t.TempDir(), dir) + + err := os.Rename(linkPath, movedPath) + if err != nil { + t.Fatalf("moving %s away: %v", dir, err) + } + + err = os.Symlink(movedPath, linkPath) + if err != nil { + t.Fatalf("linking %s: %v", dir, err) + } +} + +// TestFileStorerListsThroughSymlinkedDirectory checks that List and +// ListStream read through a symlinked metadata/ or blobs/ directory, as Get +// and Stat do, instead of listing the link as one key. Listing the whole +// destination meets the link part-way through the walk; listing its prefix +// starts the walk at the link. A prefix missing behind the link lists as +// empty. +func TestFileStorerListsThroughSymlinkedDirectory(t *testing.T) { + t.Parallel() + + for _, dir := range []string{metadataDir, blobsDir} { + t.Run(dir, func(t *testing.T) { + t.Parallel() + + base := t.TempDir() + key := dir + "/aa/bb/object" + + s, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + err = s.Put(context.Background(), key, strings.NewReader("data")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + moveBehindSymlink(t, base, dir) + + want := []string{key} + + for _, prefix := range []string{"", dir + "/"} { + got := listSorted(t, s, prefix) + if !reflect.DeepEqual(got, want) { + t.Errorf("List(%q) = %v, want %v", prefix, got, want) + } + + got = listStreamKeys(t, s, prefix) + if !reflect.DeepEqual(got, want) { + t.Errorf("ListStream(%q) = %v, want %v", prefix, got, want) + } + } + + absent := dir + "/absent/" + + if got := listSorted(t, s, absent); len(got) != 0 { + t.Errorf("List(%q) = %v, want empty", absent, got) + } + + if got := listStreamKeys(t, s, absent); len(got) != 0 { + t.Errorf("ListStream(%q) = %v, want empty", absent, got) + } + }) + } +} + +// TestFileStorerListFailsOnSymlinkWithMissingTarget checks that List and +// ListStream fail on a symlinked metadata/ or blobs/ directory whose target +// is missing, such as a link to a volume that is not mounted, as they do on +// a missing destination directory, instead of listing it as empty. That +// holds for a prefix below the link too. +func TestFileStorerListFailsOnSymlinkWithMissingTarget(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + for _, dir := range []string{metadataDir, blobsDir} { + t.Run(dir, func(t *testing.T) { + t.Parallel() + + base := t.TempDir() + + s, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + unmounted := filepath.Join(t.TempDir(), "unmounted") + + err = os.Symlink(unmounted, filepath.Join(base, dir)) + if err != nil { + t.Fatalf("Symlink: %v", err) + } + + for _, prefix := range []string{"", dir + "/", dir + "/aa/"} { + keys, err := s.List(ctx, prefix) + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("List(%q) = %v, %v; want a not-exist error", + prefix, keys, err) + } + + var streamErr error + + for object := range s.ListStream(ctx, prefix) { + if object.Err != nil { + streamErr = object.Err + } + } + + if !errors.Is(streamErr, fs.ErrNotExist) { + t.Errorf("ListStream(%q) error = %v, want a not-exist error", + prefix, streamErr) + } + } + }) + } +} + +// TestFileStorerListFailsOnSymlinkLoop checks that a symlink pointing back +// at the destination makes List and ListStream fail instead of walking it +// forever. +func TestFileStorerListFailsOnSymlinkLoop(t *testing.T) { + t.Parallel() + + ctx := context.Background() + base := t.TempDir() + + s, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + err = s.Put(ctx, testBlobKey, strings.NewReader("data")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + err = os.Symlink(base, filepath.Join(base, "blobs", "loop")) + if err != nil { + t.Fatalf("Symlink: %v", err) + } + + keys, err := s.List(ctx, "blobs/") + if err == nil { + t.Errorf("List = %d keys and no error, want an error", len(keys)) + } + + var streamErr error + + for object := range s.ListStream(ctx, "blobs/") { + if object.Err != nil { + streamErr = object.Err + } + } + + if streamErr == nil { + t.Error("ListStream sent no error, want one") + } +} + +// TestFileStorerDeletePartialUploadsThroughSymlinkedDirectory checks that +// DeletePartialUploads, which remote nuke uses, removes a leftover temp +// file behind a symlinked metadata/ or blobs/ directory and keeps the +// object at the real key. +func TestFileStorerDeletePartialUploadsThroughSymlinkedDirectory(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + for _, dir := range []string{metadataDir, blobsDir} { + t.Run(dir, func(t *testing.T) { + t.Parallel() + + base := t.TempDir() + key := dir + "/aa/bb/object" + + s, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + err = s.Put(ctx, key, strings.NewReader("data")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + leftover := filepath.Join(base, key+"-123456.partial") + + err = os.WriteFile(leftover, []byte("half"), 0o600) + if err != nil { + t.Fatalf("writing leftover temp file: %v", err) + } + + moveBehindSymlink(t, base, dir) + + err = s.DeletePartialUploads(ctx, dir+"/") + if err != nil { + t.Fatalf("DeletePartialUploads: %v", err) + } + + // leftover runs through the link. + _, err = os.Stat(leftover) + if !os.IsNotExist(err) { + t.Errorf("leftover temp file was not removed: %v", err) + } + + _, err = s.Stat(ctx, key) + if err != nil { + t.Errorf("Stat of the real key: %v", err) + } + }) + } +} + +// TestFileStorerPutMissingDestination checks that a write fails when the +// destination directory has gone, even after earlier writes to it +// succeeded, and that it does not create the directory again. +func TestFileStorerPutMissingDestination(t *testing.T) { + t.Parallel() + + ctx := context.Background() + base := filepath.Join(t.TempDir(), "usbstick") + + err := os.Mkdir(base, 0o750) + if err != nil { + t.Fatalf("Mkdir: %v", err) + } + + s, err := storage.NewFileStorer(base) + if err != nil { + t.Fatalf("NewFileStorer: %v", err) + } + + err = s.Put(ctx, "blobs/aa/bb/first", strings.NewReader("first")) + if err != nil { + t.Fatalf("first Put: %v", err) + } + + err = os.Rename(base, base+"-unplugged") + if err != nil { + t.Fatalf("Rename: %v", err) + } + + err = s.Put(ctx, "blobs/aa/bb/second", strings.NewReader("second")) + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("Put = %v, want a not-exist error", err) + } + + _, err = os.Stat(base) + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("Put created the destination directory again (Stat = %v)", err) + } +} diff --git a/internal/storage/module.go b/internal/storage/module.go index 0e400fd..8d00ea1 100644 --- a/internal/storage/module.go +++ b/internal/storage/module.go @@ -99,6 +99,7 @@ func storerFromParsedS3URL(parsed *URL, cfg *config.Config) (Storer, error) { AccessKeyID: cfg.S3.AccessKeyID, SecretAccessKey: cfg.S3.SecretAccessKey, Region: region, + PartSize: cfg.S3.PartSize.Int64(), }) if err != nil { return nil, fmt.Errorf("creating S3 client: %w", err) @@ -134,6 +135,7 @@ func storerFromLegacyS3Config(cfg *config.Config) (Storer, error) { AccessKeyID: cfg.S3.AccessKeyID, SecretAccessKey: cfg.S3.SecretAccessKey, Region: region, + PartSize: cfg.S3.PartSize.Int64(), }) if err != nil { return nil, fmt.Errorf("creating S3 client: %w", err) diff --git a/internal/storage/rclone.go b/internal/storage/rclone.go index c3a3433..d4d45fc 100644 --- a/internal/storage/rclone.go +++ b/internal/storage/rclone.go @@ -3,13 +3,17 @@ package storage import ( "bytes" "context" + "crypto/rand" "errors" "fmt" "io" + "os" + "path/filepath" "strings" "time" "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config" "github.com/rclone/rclone/fs/config/configfile" "github.com/rclone/rclone/fs/operations" @@ -20,6 +24,15 @@ import ( // ErrRemoteNotFound is returned when an rclone remote is not configured. var ErrRemoteNotFound = errors.New("rclone remote not found in config") +// ErrRcloneRelativeLocalPath is returned when the path on an rclone remote +// of type local is relative. rclone would resolve it against the working +// directory, so the destination would move with it. +var ErrRcloneRelativeLocalPath = errors.New( + "the path on an rclone remote of type local must be absolute") + +// rcloneLocalBackend is the type of rclone's local disk backend. +const rcloneLocalBackend = "local" + // RcloneStorer implements Storer using rclone's filesystem abstraction. // This allows vaultik to use any of rclone's 70+ supported storage providers. type RcloneStorer struct { @@ -32,6 +45,15 @@ type RcloneStorer struct { // The remote parameter is the rclone remote name (as configured via `rclone config`). // The path parameter is the path within the remote. func NewRcloneStorer(ctx context.Context, remote, path string) (*RcloneStorer, error) { + // rclone reads RCLONE_CONFIG only as the value of its --config flag, + // which vaultik does not have, so it is applied here as that flag would. + if configPath, ok := os.LookupEnv("RCLONE_CONFIG"); ok { + err := config.SetConfigPath(configPath) + if err != nil { + return nil, fmt.Errorf("using RCLONE_CONFIG %q: %w", configPath, err) + } + } + // Install the default config file handler configfile.Install() @@ -41,6 +63,27 @@ func NewRcloneStorer(ctx context.Context, remote, path string) (*RcloneStorer, e rclonePath += path } + // A remote rclone cannot find is reported by fs.NewFs below. Only the + // backend of what fs.ParseRemote returns is needed here. + backend, _, _, _, err := fs.ParseRemote(rclonePath) //nolint:dogsled + if err == nil && backend.Name == rcloneLocalBackend && !filepath.IsAbs(path) { + example := path + if example == "" { + example = "path/to/backup" + } + + return nil, fmt.Errorf("%w: use rclone://%s//%s", + ErrRcloneRelativeLocalPath, remote, example) + } + + // On S3, Swift and some other remotes rclone keeps a time of its own in + // each object's metadata, which costs one request per object to read. + // rclone's use_server_modtime setting makes ModTime the time the + // listing gives instead: when the object was stored, which is what + // prune compares with prune_grace_period. + ctx, ci := fs.AddConfig(ctx) + ci.UseServerModTime = true + // Create the rclone filesystem fsys, err := fs.NewFs(ctx, rclonePath) if err != nil { @@ -68,14 +111,7 @@ func (r *RcloneStorer) Put(ctx context.Context, key string, data io.Reader) erro return fmt.Errorf("reading data: %w", err) } - // Upload the object - _, err = operations.Rcat(ctx, r.fsys, key, - io.NopCloser(bytes.NewReader(buf)), time.Now(), nil) - if err != nil { - return fmt.Errorf("uploading object: %w", err) - } - - return nil + return r.upload(ctx, key, bytes.NewReader(buf)) } // PutWithProgress stores data with progress reporting. @@ -89,13 +125,7 @@ func (r *RcloneStorer) PutWithProgress( callback: progress, } - // Upload the object - _, err := operations.Rcat(ctx, r.fsys, key, io.NopCloser(pr), time.Now(), nil) - if err != nil { - return fmt.Errorf("uploading object: %w", err) - } - - return nil + return r.upload(ctx, key, pr) } // Get retrieves data from the specified key. @@ -173,6 +203,10 @@ func (r *RcloneStorer) List(ctx context.Context, prefix string) ([]string, error err := operations.ListFn(ctx, r.fsys, func(obj fs.Object) { key := obj.Remote() + if strings.HasSuffix(key, tempSuffix) { + return + } + if prefix == "" || strings.HasPrefix(key, prefix) { keys = append(keys, key) } @@ -202,10 +236,15 @@ func (r *RcloneStorer) ListStream( } key := obj.Remote() + if strings.HasSuffix(key, tempSuffix) { + return + } + if prefix == "" || strings.HasPrefix(key, prefix) { ch <- ObjectInfo{ - Key: key, - Size: obj.Size(), + Key: key, + Size: obj.Size(), + ModTime: obj.ModTime(ctx), } } }) @@ -217,6 +256,31 @@ func (r *RcloneStorer) ListStream( return ch } +// DeletePartialUploads removes every object under prefix whose name ends +// in tempSuffix. +func (r *RcloneStorer) DeletePartialUploads(ctx context.Context, prefix string) error { + var partial []fs.Object + + err := operations.ListFn(ctx, r.fsys, func(obj fs.Object) { + key := obj.Remote() + if strings.HasPrefix(key, prefix) && strings.HasSuffix(key, tempSuffix) { + partial = append(partial, obj) + } + }) + if err != nil { + return fmt.Errorf("listing objects: %w", err) + } + + for _, obj := range partial { + err = obj.Remove(ctx) + if err != nil { + return fmt.Errorf("removing object: %w", err) + } + } + + return nil +} + // Info returns human-readable storage location information. func (r *RcloneStorer) Info() Info { location := r.remote @@ -230,6 +294,59 @@ func (r *RcloneStorer) Info() Info { } } +// upload writes data to key. Where the remote has a server-side move, it +// writes under a temporary name ending in tempSuffix and moves the object +// onto key once it is complete, so a killed upload cannot leave a truncated +// object at key; a remote without one is written in place. List and +// ListStream skip a temporary object left behind. +// +// rclone's own copy does this only where the remote also sets +// PartialUploads. That flag is not checked here: hdfs, for one, shows a +// file while it is written without setting it. +func (r *RcloneStorer) upload(ctx context.Context, key string, data io.Reader) error { + if r.fsys.Features().Move == nil { + _, err := operations.Rcat(ctx, r.fsys, key, io.NopCloser(data), time.Now(), nil) + if err != nil { + return fmt.Errorf("uploading object: %w", err) + } + + return nil + } + + tempKey := key + "-" + rand.Text() + tempSuffix + + obj, err := operations.Rcat(ctx, r.fsys, tempKey, io.NopCloser(data), time.Now(), nil) + if err != nil { + // Rcat returns the object it wrote when the written data fails its check. + if obj != nil { + _ = obj.Remove(ctx) + } + + return fmt.Errorf("uploading object: %w", err) + } + + // On drive, dropbox, onedrive and others the remote's own move does not + // replace an object already at key. operations.Move removes the object + // it is given first, and copies where the remote refuses the move. + existing, err := r.fsys.NewObject(ctx, key) + if errors.Is(err, fs.ErrorObjectNotFound) { + existing = nil + } else if err != nil { + _ = obj.Remove(ctx) + + return fmt.Errorf("looking up existing object: %w", err) + } + + _, err = operations.Move(ctx, r.fsys, existing, key, obj) + if err != nil { + _ = obj.Remove(ctx) + + return fmt.Errorf("moving object into place: %w", err) + } + + return nil +} + // progressReader wraps an io.Reader to track read progress. type progressReader struct { reader io.Reader diff --git a/internal/storage/rclone_test.go b/internal/storage/rclone_test.go index e941497..9eaf238 100644 --- a/internal/storage/rclone_test.go +++ b/internal/storage/rclone_test.go @@ -1,28 +1,54 @@ package storage_test import ( + "bytes" "context" "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" "testing" + "time" + "github.com/johannesboyne/gofakes3" + "github.com/johannesboyne/gofakes3/backend/s3mem" + "github.com/rclone/rclone/fs" + "github.com/rclone/rclone/fs/config" + "github.com/rclone/rclone/fs/config/configmap" "sneak.berlin/go/vaultik/internal/storage" ) -// The rclone backend is a thin adapter over the rclone library: it turns a -// (remote, path) pair into rclone's "remote:path" string, hands it to -// rclone, and maps rclone's own results back to the Storer interface. What -// can be tested in-process, without a configured remote or network, is that -// adapter layer — how the arguments are shaped and how construction errors -// are reported. The data-plane operations (Put/Get/List/Delete) are rclone's -// own, exercised against a real provider (drive, s3-via-rclone, ...), which -// needs a configured remote with credentials and network access and so is -// out of reach of a unit test. The shared Storer conformance suite therefore -// runs against the in-process file and s3 backends; the rclone backend -// inherits that contract once a remote is configured. -// // These tests use rclone's ":local:" on-the-fly backend, which addresses the -// local filesystem directly without any configured remote, so construction -// runs entirely in-process. +// local filesystem directly without any configured remote, so they run +// entirely in-process. A remote that needs credentials and network access +// (drive, s3 via rclone, ...) is out of reach of a unit test. + +// newRcloneStorer builds an rclone backend on rclone's local backend, +// rooted at a fresh temp directory. +// +//nolint:ireturn // conformance runs against the Storer interface by design +func newRcloneStorer(t *testing.T) storage.Storer { + t.Helper() + + s, err := storage.NewRcloneStorer(context.Background(), ":local", t.TempDir()) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + return s +} + +// TestRcloneStorer runs the shared Storer contract against the rclone +// backend. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorer(t *testing.T) { + runStorerConformance(t, newRcloneStorer) +} // TestNewRcloneStorerConstruction checks that a valid remote constructs a // backend and that Info() reports the shaped "remote:path" location. @@ -44,6 +70,321 @@ func TestNewRcloneStorerConstruction(t *testing.T) { } } +// unbufferedUploadContext returns a context in which rclone neither reads +// ahead of the write nor holds a small upload in memory. Without it, a +// progress callback runs before anything is written to the remote. +func unbufferedUploadContext() context.Context { + ctx, ci := fs.AddConfig(context.Background()) + ci.BufferSize = 0 + ci.StreamingUploadCutoff = 0 + + return ctx +} + +// objectAtKeyDuringUpload uploads data to testBlobKey and reports whether +// an object was at the key before the upload finished. It fails the test +// unless the key then reads back as the uploaded data. +func objectAtKeyDuringUpload( + ctx context.Context, t *testing.T, s *storage.RcloneStorer, +) bool { + t.Helper() + + data := bytes.Repeat([]byte("blob-bytes"), 1000) + seen := false + + err := s.PutWithProgress(ctx, testBlobKey, bytes.NewReader(data), + int64(len(data)), func(int64) error { + _, statErr := s.Stat(ctx, testBlobKey) + if statErr == nil { + seen = true + } + + return nil + }) + if err != nil { + t.Fatalf("PutWithProgress: %v", err) + } + + got := readObject(ctx, t, s, testBlobKey) + if !bytes.Equal(got, data) { + t.Errorf("object read back as %d bytes, want the %d uploaded", + len(got), len(data)) + } + + return seen +} + +// readObject returns the contents of the object at key. +func readObject( + ctx context.Context, t *testing.T, s *storage.RcloneStorer, key string, +) []byte { + t.Helper() + + rc, err := s.Get(ctx, key) + if err != nil { + t.Fatalf("Get: %v", err) + } + + defer func() { _ = rc.Close() }() + + got, err := io.ReadAll(rc) + if err != nil { + t.Fatalf("reading object: %v", err) + } + + return got +} + +// TestRcloneStorerObjectAppearsOnlyWhenComplete checks that on a remote +// with a server-side move, such as local, nothing is at the key until the +// upload has finished, so a killed upload cannot leave a truncated object +// there. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerObjectAppearsOnlyWhenComplete(t *testing.T) { + ctx := unbufferedUploadContext() + + s, err := storage.NewRcloneStorer(ctx, ":local", t.TempDir()) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + if objectAtKeyDuringUpload(ctx, t, s) { + t.Error("object was at its key before the upload finished") + } +} + +// TestRcloneStorerListSkipsPartialFiles checks that a temporary file left +// by a killed upload is never listed as a key. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerListSkipsPartialFiles(t *testing.T) { + dir := t.TempDir() + ctx := context.Background() + + s, err := storage.NewRcloneStorer(ctx, ":local", dir) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + realKey := testBlobKey + + err = s.Put(ctx, realKey, strings.NewReader("blob-bytes")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + leftover := filepath.Join(dir, realKey+"-123456.partial") + + err = os.WriteFile(leftover, []byte("half"), 0o600) + if err != nil { + t.Fatalf("writing leftover temp file: %v", err) + } + + keys, err := s.List(ctx, "blobs/") + if err != nil { + t.Fatalf("List: %v", err) + } + + if len(keys) != 1 || keys[0] != realKey { + t.Fatalf("List should return only the real key, got %v", keys) + } + + var streamed []string + + for obj := range s.ListStream(ctx, "blobs/") { + if obj.Err != nil { + t.Fatalf("ListStream: %v", obj.Err) + } + + streamed = append(streamed, obj.Key) + } + + if len(streamed) != 1 || streamed[0] != realKey { + t.Fatalf("ListStream should return only the real key, got %v", streamed) + } +} + +// TestRcloneStorerDeletePartialUploads checks that a temporary file left +// by a killed upload is removed and the object at the real key is kept. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerDeletePartialUploads(t *testing.T) { + dir := t.TempDir() + ctx := context.Background() + + s, err := storage.NewRcloneStorer(ctx, ":local", dir) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + err = s.Put(ctx, testBlobKey, strings.NewReader("blob-bytes")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + leftover := filepath.Join(dir, testBlobKey+"-123456.partial") + + err = os.WriteFile(leftover, []byte("half"), 0o600) + if err != nil { + t.Fatalf("writing leftover temp file: %v", err) + } + + err = s.DeletePartialUploads(ctx, "blobs/") + if err != nil { + t.Fatalf("DeletePartialUploads: %v", err) + } + + _, err = os.Stat(leftover) + if !os.IsNotExist(err) { + t.Errorf("leftover temp file was not removed: %v", err) + } + + _, err = s.Stat(ctx, testBlobKey) + if err != nil { + t.Errorf("Stat of the real key: %v", err) + } +} + +// newRcloneStorerOnWrappedLocal registers name as rclone's local backend +// wrapped by wrap, and builds an rclone backend on it rooted at a fresh +// temp directory. wrap changes the features the local backend reports, so +// that it behaves like a remote a unit test cannot reach. +func newRcloneStorerOnWrappedLocal( + ctx context.Context, t *testing.T, name string, wrap func(fs.Fs) fs.Fs, +) *storage.RcloneStorer { + t.Helper() + + fs.Register(&fs.RegInfo{ + Name: name, + NewFs: func( + ctx context.Context, _, root string, _ configmap.Mapper, + ) (fs.Fs, error) { + local, err := fs.NewFs(ctx, ":local:"+root) + if err != nil { + return nil, err + } + + return wrap(local), nil + }, + }) + + s, err := storage.NewRcloneStorer(ctx, ":"+name, t.TempDir()) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + return s +} + +// withoutPartialUploads is rclone's local backend with the PartialUploads +// flag cleared. Like hdfs, it then has a server-side move and shows a file +// while it is written, without setting that flag. +type withoutPartialUploads struct { + fs.Fs +} + +func (f *withoutPartialUploads) Features() *fs.Features { + features := *f.Fs.Features() + features.PartialUploads = false + + return &features +} + +// TestRcloneStorerMovesIntoPlaceWithoutPartialUploads checks that on a +// remote with a server-side move nothing is at the key until the upload has +// finished, even when rclone does not mark the remote as showing partial +// uploads. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerMovesIntoPlaceWithoutPartialUploads(t *testing.T) { + ctx := unbufferedUploadContext() + s := newRcloneStorerOnWrappedLocal(ctx, t, "withoutpartialuploads", + func(local fs.Fs) fs.Fs { return &withoutPartialUploads{Fs: local} }) + + if objectAtKeyDuringUpload(ctx, t, s) { + t.Error("object was at its key before the upload finished") + } +} + +// withoutMove is rclone's local backend reporting no server-side move. +type withoutMove struct { + fs.Fs +} + +func (f *withoutMove) Features() *fs.Features { + features := *f.Fs.Features() + features.Move = nil + + return &features +} + +// TestRcloneStorerWritesInPlaceWithoutMove checks that on a remote with no +// server-side move an object is written straight to its key and reads back +// from there. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerWritesInPlaceWithoutMove(t *testing.T) { + ctx := unbufferedUploadContext() + s := newRcloneStorerOnWrappedLocal(ctx, t, "withoutmove", + func(local fs.Fs) fs.Fs { return &withoutMove{Fs: local} }) + + if !objectAtKeyDuringUpload(ctx, t, s) { + t.Error("object was not at its key while it was uploaded") + } +} + +var errNameConflict = errors.New("an object with this name already exists") + +// moveRefusesExisting is rclone's local backend with a server-side move +// that, like dropbox's or onedrive's, refuses to move onto an existing +// object. +type moveRefusesExisting struct { + fs.Fs +} + +func (f *moveRefusesExisting) Features() *fs.Features { + features := *f.Fs.Features() + features.Move = f.move + + return &features +} + +//nolint:ireturn // the signature is rclone's +func (f *moveRefusesExisting) move( + ctx context.Context, src fs.Object, remote string, +) (fs.Object, error) { + _, err := f.NewObject(ctx, remote) + if err == nil { + return nil, errNameConflict + } + + return f.Fs.Features().Move(ctx, src, remote) +} + +// TestRcloneStorerOverwritesWhereMoveRefusesExisting checks that writing a +// key twice replaces the object on a remote whose server-side move will not +// replace an existing object. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneStorerOverwritesWhereMoveRefusesExisting(t *testing.T) { + ctx := context.Background() + s := newRcloneStorerOnWrappedLocal(ctx, t, "moverefusesexisting", + func(local fs.Fs) fs.Fs { return &moveRefusesExisting{Fs: local} }) + + for _, content := range []string{"first", "second"} { + err := s.Put(ctx, testBlobKey, strings.NewReader(content)) + if err != nil { + t.Fatalf("Put %q: %v", content, err) + } + } + + got := readObject(ctx, t, s, testBlobKey) + if string(got) != "second" { + t.Errorf("object = %q, want %q", got, "second") + } +} + // TestNewRcloneStorerUnknownRemote checks that a remote that is not in the // rclone config fails construction with the ErrRemoteNotFound sentinel, // rather than silently returning a backend pointed nowhere. @@ -56,3 +397,183 @@ func TestNewRcloneStorerUnknownRemote(t *testing.T) { t.Errorf("NewRcloneStorer error = %v, want ErrRemoteNotFound", err) } } + +// TestNewRcloneStorerReadsRcloneConfigEnv checks that a remote defined only +// in the file RCLONE_CONFIG names is found and written to, as rclone itself +// would. +func TestNewRcloneStorerReadsRcloneConfigEnv(t *testing.T) { + // rclone keeps the config file path in a process-global variable, which + // NewRcloneStorer leaves pointing at this test's file. + previous := config.GetConfigPath() + + t.Cleanup(func() { _ = config.SetConfigPath(previous) }) + + confFile := filepath.Join(t.TempDir(), "rclone.conf") + + err := os.WriteFile(confFile, []byte("[loc]\ntype = local\n"), 0o600) + if err != nil { + t.Fatalf("writing rclone config: %v", err) + } + + t.Setenv("RCLONE_CONFIG", confFile) + + dir := t.TempDir() + ctx := context.Background() + + s, err := storage.NewRcloneStorer(ctx, "loc", dir) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + err = s.Put(ctx, testBlobKey, strings.NewReader("blob-bytes")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + _, err = os.Stat(filepath.Join(dir, testBlobKey)) + if err != nil { + t.Errorf("object is not in the remote's directory: %v", err) + } +} + +// useRcloneConfig points rclone at a config file holding contents for the +// rest of the test. +func useRcloneConfig(t *testing.T, contents string) { + t.Helper() + + previous := config.GetConfigPath() + + t.Cleanup(func() { _ = config.SetConfigPath(previous) }) + + confFile := filepath.Join(t.TempDir(), "rclone.conf") + + err := os.WriteFile(confFile, []byte(contents), 0o600) + if err != nil { + t.Fatalf("writing rclone config: %v", err) + } + + t.Setenv("RCLONE_CONFIG", confFile) +} + +// TestNewRcloneStorerRefusesRelativeLocalPath checks that a relative path +// on a remote of type local is refused, with the absolute form in the +// error, and that nothing is created under the working directory. rclone +// would otherwise resolve the path against the working directory. +// +//nolint:paralleltest // changes the working directory and the rclone config +func TestNewRcloneStorerRefusesRelativeLocalPath(t *testing.T) { + useRcloneConfig(t, "[localfs]\ntype = local\n") + + workdir := t.TempDir() + t.Chdir(workdir) + + for path, wantInError := range map[string]string{ + "srv/backup": "rclone://localfs//srv/backup", + "": "rclone://localfs//path/to/backup", + } { + _, err := storage.NewRcloneStorer(context.Background(), "localfs", path) + if !errors.Is(err, storage.ErrRcloneRelativeLocalPath) { + t.Errorf("path %q: error = %v, want ErrRcloneRelativeLocalPath", + path, err) + + continue + } + + if !strings.Contains(err.Error(), wantInError) { + t.Errorf("path %q: error %q does not show %q", + path, err, wantInError) + } + } + + entries, err := os.ReadDir(workdir) + if err != nil { + t.Fatalf("reading working directory: %v", err) + } + + if len(entries) != 0 { + t.Errorf("working directory holds %d entries, want none", len(entries)) + } +} + +// TestNewRcloneStorerKeepsRelativePathOnOtherRemotes checks that a relative +// path is accepted on a remote not of type local, where rclone resolves it +// on the remote itself, as sftp does against the login directory. +// +//nolint:paralleltest // changes the process-global rclone config +func TestNewRcloneStorerKeepsRelativePathOnOtherRemotes(t *testing.T) { + useRcloneConfig(t, "[mem]\ntype = memory\n") + + _, err := storage.NewRcloneStorer(context.Background(), "mem", "backups") + if err != nil { + t.Errorf("NewRcloneStorer: %v", err) + } +} + +// TestRcloneListStreamOnS3MakesNoRequestPerObject checks that listing an +// rclone S3 remote takes each object's time from the listing itself. By +// default rclone reads the time it keeps in each object's metadata, one +// request per object, and every command that lists the destination store +// would slow down as it grows. +// +//nolint:paralleltest // NewRcloneStorer installs the process-global rclone config +func TestRcloneListStreamOnS3MakesNoRequestPerObject(t *testing.T) { + backend := s3mem.New() + + err := backend.CreateBucket(s3TestBucket) + if err != nil { + t.Fatalf("create bucket: %v", err) + } + + const body = "blob-bytes" + + _, err = backend.PutObject(s3TestBucket, testBlobKey, nil, + strings.NewReader(body), int64(len(body))) + if err != nil { + t.Fatalf("seed object: %v", err) + } + + var headRequests atomic.Int64 + + fakeS3 := gofakes3.New(backend).Server() + srv := httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + headRequests.Add(1) + } + + fakeS3.ServeHTTP(w, r) + })) + t.Cleanup(srv.Close) + + remote := ":s3,provider=Other" + + ",access_key_id=" + s3TestAccessKeyID + + ",secret_access_key=" + s3TestSecretAccessKey + + ",endpoint='" + srv.URL + "'" + ctx := context.Background() + + s, err := storage.NewRcloneStorer(ctx, remote, s3TestBucket) + if err != nil { + t.Fatalf("NewRcloneStorer: %v", err) + } + + headRequests.Store(0) + + var listed []storage.ObjectInfo + + for info := range s.ListStream(ctx, "blobs/") { + listed = append(listed, info) + } + + if len(listed) != 1 || listed[0].Err != nil { + t.Fatalf("ListStream(\"blobs/\") = %v, want the one object", listed) + } + + if time.Since(listed[0].ModTime).Abs() > time.Minute { + t.Errorf("ListStream ModTime = %v, want within a minute of now", + listed[0].ModTime) + } + + if n := headRequests.Load(); n != 0 { + t.Errorf("ListStream made %d HEAD request(s), want none", n) + } +} diff --git a/internal/storage/s3.go b/internal/storage/s3.go index 648e697..bbe133b 100644 --- a/internal/storage/s3.go +++ b/internal/storage/s3.go @@ -89,9 +89,10 @@ func (s *S3Storer) ListStream(ctx context.Context, prefix string) <-chan ObjectI for info := range s.client.ListObjectsStream(ctx, prefix, false) { ch <- ObjectInfo{ - Key: info.Key, - Size: info.Size, - Err: info.Err, + Key: info.Key, + Size: info.Size, + ModTime: info.ModTime, + Err: info.Err, } } }() @@ -99,6 +100,12 @@ func (s *S3Storer) ListStream(ctx context.Context, prefix string) <-chan ObjectI return ch } +// DeletePartialUploads has nothing to remove: S3 shows an object only once +// its upload has completed, so an upload cut off part-way leaves none. +func (s *S3Storer) DeletePartialUploads(_ context.Context, _ string) error { + return nil +} + // Info returns human-readable storage location information. func (s *S3Storer) Info() Info { return Info{ diff --git a/internal/storage/s3_test.go b/internal/storage/s3_test.go index 966d5c6..8902bc7 100644 --- a/internal/storage/s3_test.go +++ b/internal/storage/s3_test.go @@ -1,14 +1,21 @@ package storage_test import ( + "bytes" "context" "errors" + "io" + "net/http" "net/http/httptest" + "slices" + "strings" + "sync/atomic" "testing" "github.com/johannesboyne/gofakes3" "github.com/johannesboyne/gofakes3/backend/s3mem" + "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/s3" "sneak.berlin/go/vaultik/internal/storage" ) @@ -16,6 +23,16 @@ import ( // s3TestBucket is the bucket created for each in-process S3 server. const s3TestBucket = "test-bucket" +// Credentials for the tests' S3 clients. The test servers accept any. +const ( + s3TestAccessKeyID = "key" + s3TestSecretAccessKey = "secret" +) + +// s3TestRegion is the region of the S3 clients built here with +// s3.NewClient. The test servers ignore it. +const s3TestRegion = "us-east-1" + // newS3Storer builds an s3:// backend backed by a fresh in-process // S3 server. It reuses the same in-memory S3 harness (gofakes3 + s3mem // over httptest) that internal/s3 and the not-found regression test use, @@ -42,7 +59,7 @@ func newS3Storer(t *testing.T) storage.Storer { Bucket: s3TestBucket, AccessKeyID: "test", SecretAccessKey: "test", - Region: "us-east-1", + Region: s3TestRegion, }) if err != nil { t.Fatalf("new client: %v", err) @@ -79,3 +96,256 @@ func TestS3StorerMissingKeyMapsToErrNotFound(t *testing.T) { t.Errorf("Stat on missing key: got %v, want ErrNotFound", err) } } + +// TestS3ListingCutShortIsAnError checks that List and ListStream fail on a +// listing page marked truncated that carries no continuation token, as a +// server answering V2 listings V1-style sends it. Taken as the last page, +// it would hide every later key: prune would treat the blobs of the +// snapshots listed there as unreferenced, and a directory under metadata/ +// whose manifest is listed there as one with no manifest. +func TestS3ListingCutShortIsAnError(t *testing.T) { + t.Parallel() + + const ( + prefix = "metadata/" + truncatedPage = ` + + test-bucket + metadata/ + 1 + 1 + true + + metadata/snap/manifest.json.zst + 8 + +` + ) + + srv := httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, truncatedPage) + })) + t.Cleanup(srv.Close) + + client, err := s3.NewClient(context.Background(), s3.Config{ + Endpoint: srv.URL, + Bucket: s3TestBucket, + AccessKeyID: s3TestAccessKeyID, + SecretAccessKey: s3TestSecretAccessKey, + Region: s3TestRegion, + }) + if err != nil { + t.Fatalf("new client: %v", err) + } + + storer := storage.NewS3Storer(client) + ctx := context.Background() + + keys, err := storer.List(ctx, prefix) + if !errors.Is(err, s3.ErrNoContinuationToken) { + t.Errorf("List = %q, %v; want ErrNoContinuationToken", keys, err) + } + + var streamErr error + + for obj := range storer.ListStream(ctx, prefix) { + if obj.Err != nil { + streamErr = obj.Err + } + } + + if !errors.Is(streamErr, s3.ErrNoContinuationToken) { + t.Errorf("ListStream error = %v, want ErrNoContinuationToken", streamErr) + } +} + +// TestS3URLPrefixKeyLayout pins the bucket keys an s3:// URL reads and +// writes: the README's remote storage layout, with the prefix joined to +// each key by one "/". s3://b/p and s3://b/p/ must be the same +// destination, or a host that writes the URL the other way finds no +// snapshots. The listed object is put straight into the bucket, as +// another host would have written it. Both List and ListStream are +// checked: ListStream is what every snapshot listing goes through. +func TestS3URLPrefixKeyLayout(t *testing.T) { + t.Parallel() + + const ( + blobKey = "blobs/aa/bb/aabbccdd" + listPrefix = "metadata/" + manifestKey = listPrefix + "snap/manifest.json.zst" + manifestBody = "manifest" + ) + + cases := []struct { + urlPath string // URL path after the bucket name + keyPrefix string // what every key in the bucket must start with + }{ + {urlPath: "/p", keyPrefix: "p/"}, + {urlPath: "/p/", keyPrefix: "p/"}, + {urlPath: "", keyPrefix: ""}, + } + + for _, tc := range cases { + storageURL := "s3://" + s3TestBucket + tc.urlPath + + t.Run(storageURL, func(t *testing.T) { + t.Parallel() + + backend := s3mem.New() + + err := backend.CreateBucket(s3TestBucket) + if err != nil { + t.Fatalf("create bucket: %v", err) + } + + srv := httptest.NewServer(gofakes3.New(backend).Server()) + t.Cleanup(srv.Close) + + storer, err := storage.NewStorer(&config.Config{ + StorageURL: storageURL + "?endpoint=" + srv.URL, + S3: config.S3Config{ + AccessKeyID: s3TestAccessKeyID, + SecretAccessKey: s3TestSecretAccessKey, + }, + }) + if err != nil { + t.Fatalf("NewStorer: %v", err) + } + + ctx := context.Background() + + err = storer.Put(ctx, blobKey, strings.NewReader("blob")) + if err != nil { + t.Fatalf("Put: %v", err) + } + + _, err = backend.HeadObject(s3TestBucket, tc.keyPrefix+blobKey) + if err != nil { + t.Errorf("blob not stored at %q: %v", tc.keyPrefix+blobKey, err) + } + + _, err = backend.PutObject(s3TestBucket, tc.keyPrefix+manifestKey, + nil, strings.NewReader(manifestBody), int64(len(manifestBody))) + if err != nil { + t.Fatalf("seed manifest: %v", err) + } + + keys, err := storer.List(ctx, listPrefix) + if err != nil { + t.Fatalf("List: %v", err) + } + + if !slices.Equal(keys, []string{manifestKey}) { + t.Errorf("List(%q) = %q, want [%q]", listPrefix, keys, manifestKey) + } + + streamed := listStreamKeys(t, storer, listPrefix) + if !slices.Equal(streamed, []string{manifestKey}) { + t.Errorf("ListStream(%q) = %q, want [%q]", listPrefix, streamed, manifestKey) + } + }) + } +} + +// TestS3UploadUsesConfiguredPartSize checks that s3.part_size reaches the +// multipart uploader, through storage_url and through the s3.* fields. An +// object three parts long must arrive as three parts; at the SDK's default +// of 5 MiB it would arrive as four. +func TestS3UploadUsesConfiguredPartSize(t *testing.T) { + t.Parallel() + + const ( + partSize = 6 * 1024 * 1024 + wantParts = 3 + ) + + backend := s3mem.New() + + err := backend.CreateBucket(s3TestBucket) + if err != nil { + t.Fatalf("create bucket: %v", err) + } + + // Every part of a multipart upload is one request with a partNumber. + var parts atomic.Int32 + + fake := gofakes3.New(backend).Server() + srv := httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Has("partNumber") { + parts.Add(1) + } + + fake.ServeHTTP(w, r) + })) + t.Cleanup(srv.Close) + + cases := []struct { + name string + cfg *config.Config + }{ + { + name: "storage_url", + cfg: &config.Config{ + StorageURL: "s3://" + s3TestBucket + "?endpoint=" + srv.URL, + S3: config.S3Config{ + AccessKeyID: s3TestAccessKeyID, + SecretAccessKey: s3TestSecretAccessKey, + PartSize: partSize, + }, + }, + }, + { + name: "s3.endpoint", + cfg: &config.Config{ + S3: config.S3Config{ + Endpoint: srv.URL, + Bucket: s3TestBucket, + AccessKeyID: s3TestAccessKeyID, + SecretAccessKey: s3TestSecretAccessKey, + PartSize: partSize, + }, + }, + }, + } + + for _, tc := range cases { + parts.Store(0) + + storer, err := storage.NewStorer(tc.cfg) + if err != nil { + t.Fatalf("%s: NewStorer: %v", tc.name, err) + } + + data := bytes.NewReader(make([]byte, wantParts*partSize)) + + err = storer.PutWithProgress( + context.Background(), "blob", data, data.Size(), nil) + if err != nil { + t.Fatalf("%s: PutWithProgress: %v", tc.name, err) + } + + if got := parts.Load(); got != wantParts { + t.Errorf("%s: uploaded in %d parts, want %d", tc.name, got, wantParts) + } + } +} + +// listStreamKeys returns the keys ListStream yields under a prefix, and +// fails the test on a listing error. +func listStreamKeys(t *testing.T, s storage.Storer, prefix string) []string { + t.Helper() + + var keys []string + + for obj := range s.ListStream(context.Background(), prefix) { + if obj.Err != nil { + t.Fatalf("ListStream %q: %v", prefix, obj.Err) + } + + keys = append(keys, obj.Key) + } + + return keys +} diff --git a/internal/storage/storer.go b/internal/storage/storer.go index 2334a7d..3417cb7 100644 --- a/internal/storage/storer.go +++ b/internal/storage/storer.go @@ -14,6 +14,7 @@ import ( "context" "errors" "io" + "time" ) // ErrNotFound is returned when an object does not exist. @@ -27,7 +28,10 @@ type ProgressCallback func(bytesTransferred int64) error type ObjectInfo struct { Key string // Object key/path Size int64 // Size in bytes - Err error // Error for streaming results (nil on success) + // ModTime is when the object was written, as the store reports it. + // Only ListStream sets it; Stat leaves it zero. + ModTime time.Time + Err error // Error for streaming results (nil on success) } // Info provides human-readable storage configuration. @@ -41,7 +45,8 @@ type Info struct { // directory for filesystem). type Storer interface { // Put stores data at the specified key. - // Parent directories are created automatically for filesystem backends. + // The filesystem backend fails when its destination directory does + // not exist, and creates the directories below it as needed. Put(ctx context.Context, key string, data io.Reader) error // PutWithProgress stores data with progress reporting. @@ -66,11 +71,18 @@ type Storer interface { // For large result sets, prefer ListStream. List(ctx context.Context, prefix string) ([]string, error) - // ListStream returns a channel of ObjectInfo for large result sets. + // ListStream returns a channel of ObjectInfo, with each object's key, + // size and modification time, for large result sets. // The channel is closed when listing completes. // If an error occurs during listing, the final item will have Err set. ListStream(ctx context.Context, prefix string) <-chan ObjectInfo + // DeletePartialUploads removes every object under prefix that an + // upload cut off part-way left under a temporary name ending in + // `.partial`. The file and rclone backends' List and ListStream skip + // such an object. + DeletePartialUploads(ctx context.Context, prefix string) error + // Info returns human-readable storage location information. Info() Info } diff --git a/internal/storage/url.go b/internal/storage/url.go index 24ea329..8d2b046 100644 --- a/internal/storage/url.go +++ b/internal/storage/url.go @@ -17,8 +17,10 @@ const ( // Sentinel errors for storage URL parsing. var ( - ErrEmptyStorageURL = errors.New("storage URL is empty") - ErrEmptyFilePath = errors.New("file URL path is empty") + ErrEmptyStorageURL = errors.New("storage URL is empty") + ErrEmptyFilePath = errors.New("file URL path is empty") + ErrRelativeFilePath = errors.New( + "file URL needs an absolute path, as in file:///path/to/backup") ErrMissingBucket = errors.New("s3 URL missing bucket name") ErrMissingRemote = errors.New("rclone URL missing remote name") ErrUnsupportedScheme = errors.New( @@ -28,6 +30,12 @@ var ( "storage URL must not carry credentials; " + "set s3.access_key_id and s3.secret_access_key in the config instead") ErrURLUnknownParam = errors.New("unknown query parameter in storage URL") + ErrURLBadQuery = errors.New( + "storage URL query cannot be decoded; " + + "check it for a ; or a % not followed by two hex digits") + ErrRcloneRemoteParams = errors.New( + "rclone URL must not carry parameters in the remote name; " + + "set them on the remote with rclone config instead") ) // URL represents a parsed storage URL. @@ -51,17 +59,8 @@ func ParseStorageURL(rawURL string) (*URL, error) { return nil, ErrEmptyStorageURL } - // Handle file:// URLs if after, ok := strings.CutPrefix(rawURL, "file://"); ok { - path := after - if path == "" { - return nil, ErrEmptyFilePath - } - - return &URL{ - Scheme: schemeFile, - Prefix: path, - }, nil + return parseFileURL(after) } if strings.HasPrefix(rawURL, "s3://") { @@ -75,9 +74,31 @@ func ParseStorageURL(rawURL string) (*URL, error) { return nil, ErrUnsupportedScheme } +// parseFileURL parses the path that follows file://. The path must be +// absolute: a relative one would resolve against the working directory, +// so the destination would move with it. Percent-escapes are decoded, so +// my%20stick names the directory "my stick"; a literal space is kept. +func parseFileURL(rawPath string) (*URL, error) { + if rawPath == "" { + return nil, ErrEmptyFilePath + } + + if !strings.HasPrefix(rawPath, "/") { + return nil, ErrRelativeFilePath + } + + path, err := url.PathUnescape(rawPath) + if err != nil { + return nil, fmt.Errorf("invalid file URL path: %w", err) + } + + return &URL{Scheme: schemeFile, Prefix: path}, nil +} + // parseS3URL parses an s3://bucket/prefix URL. It rejects credentials in -// the userinfo and any query parameter other than endpoint, region and -// ssl, so a credential-bearing URL is never stored or echoed. +// the userinfo or in the endpoint parameter's userinfo, a query that +// cannot be decoded, and any query parameter other than endpoint, region +// and ssl, so a credential-bearing URL is never stored or echoed. func parseS3URL(rawURL string) (*URL, error) { u, err := url.Parse(rawURL) if err != nil { @@ -93,13 +114,26 @@ func parseS3URL(rawURL string) (*URL, error) { return nil, ErrMissingBucket } - query := u.Query() + // u.Query() would silently drop a part it cannot decode, endpoint + // included. The decode error is not wrapped: it can quote the value. + query, err := url.ParseQuery(u.RawQuery) + if err != nil { + return nil, ErrURLBadQuery + } err = rejectUnknownParams(query, "endpoint", "region", "ssl") if err != nil { return nil, err } + // A host name never contains "@", so one in an endpoint, with or + // without a scheme, can only introduce userinfo. + for _, endpoint := range query["endpoint"] { + if strings.Contains(endpoint, "@") { + return nil, ErrURLCredentials + } + } + return &URL{ Scheme: schemeS3, Bucket: bucket, @@ -111,9 +145,23 @@ func parseS3URL(rawURL string) (*URL, error) { } // parseRcloneURL parses an rclone://remote/path URL. rclone:// takes no -// query parameters, so credentials in the userinfo and any parameter at +// query parameters, so credentials in the userinfo, parameters in the +// remote name, a query that cannot be decoded and any query parameter at // all are rejected rather than silently ignored. func parseRcloneURL(rawURL string) (*URL, error) { + // The remote name runs up to the first "/", "?" or "#". It never + // contains a comma; one starts rclone's remote,param=value form, + // whose values can be credentials. This is checked before url.Parse, + // whose error for such a name can print part of it. + remote := strings.TrimPrefix(rawURL, "rclone://") + if end := strings.IndexAny(remote, "/?#"); end >= 0 { + remote = remote[:end] + } + + if strings.Contains(remote, ",") { + return nil, ErrRcloneRemoteParams + } + u, err := url.Parse(rawURL) if err != nil { return nil, wrapParseError(err) @@ -123,12 +171,19 @@ func parseRcloneURL(rawURL string) (*URL, error) { return nil, ErrURLCredentials } - remote := u.Host + remote = u.Host if remote == "" { return nil, ErrMissingRemote } - err = rejectUnknownParams(u.Query()) + // As in parseS3URL: u.Query() would drop a part it cannot decode, and + // the decode error can quote the value. + query, err := url.ParseQuery(u.RawQuery) + if err != nil { + return nil, ErrURLBadQuery + } + + err = rejectUnknownParams(query) if err != nil { return nil, err } @@ -161,8 +216,7 @@ func rejectUnknownParams(query url.Values, allowed ...string) error { // *url.Error that url.Parse returns embeds the raw URL in its message, so // wrapping it directly would echo a credential-bearing URL into logs. func wrapParseError(err error) error { - var uerr *url.Error - if errors.As(err, &uerr) { + if uerr, ok := errors.AsType[*url.Error](err); ok { return fmt.Errorf("invalid URL: %w", uerr.Err) } diff --git a/internal/storage/url_parse_test.go b/internal/storage/url_parse_test.go index ad0cce7..b6a9424 100644 --- a/internal/storage/url_parse_test.go +++ b/internal/storage/url_parse_test.go @@ -14,7 +14,10 @@ import ( func TestParseStorageURLValid(t *testing.T) { t.Parallel() - const bucket = "mybucket" + const ( + bucket = "mybucket" + fileScheme = "file" + ) cases := []struct { name string @@ -24,7 +27,17 @@ func TestParseStorageURLValid(t *testing.T) { { name: "file absolute path", raw: "file:///var/backups/vaultik", - want: &storage.URL{Scheme: "file", Prefix: "/var/backups/vaultik"}, + want: &storage.URL{Scheme: fileScheme, Prefix: "/var/backups/vaultik"}, + }, + { + name: "file percent-escaped path is decoded", + raw: "file:///Volumes/my%20stick/backup", + want: &storage.URL{Scheme: fileScheme, Prefix: "/Volumes/my stick/backup"}, + }, + { + name: "file path with a literal space", + raw: "file:///Volumes/my stick/backup", + want: &storage.URL{Scheme: fileScheme, Prefix: "/Volumes/my stick/backup"}, }, { name: "s3 bucket and prefix, ssl defaults on", @@ -90,6 +103,7 @@ func TestParseStorageURLErrors(t *testing.T) { }{ {"empty url", "", storage.ErrEmptyStorageURL}, {"file empty path", "file://", storage.ErrEmptyFilePath}, + {"file relative path", "file://dest", storage.ErrRelativeFilePath}, {"s3 missing bucket", "s3://", storage.ErrMissingBucket}, {"s3 missing bucket with path", "s3:///justprefix", storage.ErrMissingBucket}, {"rclone missing remote", "rclone://", storage.ErrMissingRemote}, @@ -136,6 +150,19 @@ func TestParseStorageURLRejectsCredentials(t *testing.T) { wantErr: storage.ErrURLCredentials, secrets: []string{key, secret, "mybucket"}, }, + { + name: "s3 userinfo in endpoint", + raw: "s3://mybucket?endpoint=https://" + + key + ":" + secret + "@minio.example.com", + wantErr: storage.ErrURLCredentials, + secrets: []string{key, secret}, + }, + { + name: "s3 userinfo in endpoint without scheme", + raw: "s3://mybucket?endpoint=" + key + ":" + secret + "@minio.example.com", + wantErr: storage.ErrURLCredentials, + secrets: []string{key, secret}, + }, { name: "s3 unknown query param", raw: "s3://mybucket?access_key=" + key + "&secret=" + secret, @@ -189,6 +216,112 @@ func TestParseStorageURLRejectsCredentials(t *testing.T) { } } +// TestParseStorageURLRejectsRcloneRemoteParams checks that an rclone +// remote name carrying parameters (rclone's "remote,param=value" form, +// which can hold a credential) is rejected without echoing the value, +// including the URLs that url.Parse itself refuses. +func TestParseStorageURLRejectsRcloneRemoteParams(t *testing.T) { + t.Parallel() + + cases := []struct { + name string + raw string + secrets []string // must not appear in the error message + }{ + { + name: "configured remote", + raw: "rclone://gdrive,client_secret=topsecret/backups", + secrets: []string{"topsecret"}, + }, + { + name: "remote defined inline", + raw: "rclone://:s3,access_key_id=KEY,secret_access_key=SECRET/bucket", + secrets: []string{"KEY", "SECRET"}, + }, + { + name: "colon in a parameter value", + raw: "rclone://gdrive,client_secret=ab:cd/backups", + secrets: []string{"cd"}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, err := storage.ParseStorageURL(tc.raw) + if !errors.Is(err, storage.ErrRcloneRemoteParams) { + t.Fatalf("ParseStorageURL(%q) error = %v, want %v", + tc.raw, err, storage.ErrRcloneRemoteParams) + } + + for _, secret := range tc.secrets { + if strings.Contains(err.Error(), secret) { + t.Errorf("error message leaked %q: %v", secret, err.Error()) + } + } + }) + } +} + +// TestParseStorageURLRejectsUndecodableQuery checks that an s3 or rclone +// URL whose query cannot be decoded is rejected, not read with that part +// of the query left out, and that the error does not echo it. +func TestParseStorageURLRejectsUndecodableQuery(t *testing.T) { + t.Parallel() + + const ( + key = "AKIAKEY" + secret = "topsecret" + ) + + cases := []struct { + name string + raw string + }{ + { + name: "semicolon", + raw: "s3://mybucket/prefix?endpoint=https://" + key + ":" + secret + + "@minio.example.com:9000;region=us-east-1", + }, + { + name: "bad percent escape", + raw: "s3://mybucket/prefix?endpoint=https://" + key + ":" + secret + + "%zz@minio.example.com:9000", + }, + { + name: "rclone semicolon", + raw: "rclone://gdrive/backups?token=" + secret + ";x=1", + }, + { + name: "rclone bad percent escape", + raw: "rclone://gdrive/backups?token=" + secret + "%zz", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, err := storage.ParseStorageURL(tc.raw) + if err == nil { + t.Fatalf("ParseStorageURL(%q) returned no error", tc.raw) + } + + if !errors.Is(err, storage.ErrURLBadQuery) { + t.Errorf("ParseStorageURL(%q) error = %v, want %v", + tc.raw, err, storage.ErrURLBadQuery) + } + + for _, s := range []string{key, secret, "minio.example.com"} { + if strings.Contains(err.Error(), s) { + t.Errorf("error message leaked %q: %v", s, err.Error()) + } + } + }) + } +} + // TestParseStorageURLParseFailureHidesURL checks that when url.Parse // itself fails, the wrapped error carries only the inner cause, not the // *url.Error whose text embeds the raw (possibly credential-bearing) URL. diff --git a/internal/types/types.go b/internal/types/types.go index d4dc997..e9fdd72 100644 --- a/internal/types/types.go +++ b/internal/types/types.go @@ -155,8 +155,8 @@ type BlobHash string // FilePath represents an absolute path to a file or directory. type FilePath string -// SourcePath represents the root directory from which files are backed up. -// Used during restore to strip the source prefix from paths. +// SourcePath is the source directory a scan found a file under, made +// absolute and with symlinks resolved. type SourcePath string // Hostname identifies a host machine. diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 7a08d53..0584777 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -17,6 +17,9 @@ // Count, Percent) return ANSI-colored strings the caller composes into // the message body. When color is disabled (non-TTY output or NO_COLOR // set) all formatters return plain text. +// +// QuoteUnprintable is the same escaping without colour, for plain tables +// that print paths from the snapshot database. package ui import ( @@ -227,17 +230,17 @@ func (w *Writer) Hex(s string) string { short = s[:hexAbbrevLen] + "..." } - return w.paint(ansiCyan, sanitize(short)) + return w.paint(ansiCyan, QuoteUnprintable(short)) } // Snapshot colorizes a snapshot ID (full, no abbreviation). func (w *Writer) Snapshot(id string) string { - return w.paint(ansiCyan+ansiBold, sanitize(id)) + return w.paint(ansiCyan+ansiBold, QuoteUnprintable(id)) } // Path colorizes a filesystem path. func (w *Writer) Path(p string) string { - return w.paint(ansiBlue, sanitize(p)) + return w.paint(ansiBlue, QuoteUnprintable(p)) } // Size colorizes a byte count using humanize.Bytes. @@ -312,14 +315,15 @@ func (w *Writer) paint(color, s string) string { return color + s + ansiReset } -// sanitize returns s unchanged when every rune in it is printable, and a -// double-quoted, backslash-escaped form (\n, \x1b, …) otherwise. The +// QuoteUnprintable returns s unchanged when every rune in it is printable, +// and a double-quoted, backslash-escaped form (\n, \x1b, …) otherwise. The // string value formatters escape their argument through this before // painting: identifiers, paths and symlink targets they render come from // the snapshot database, which is not trusted, and escaping must happen // before colour is applied — the painted result already contains the // escape codes the raw text would otherwise be indistinguishable from. -func sanitize(s string) string { +// Plain tables call it directly. +func QuoteUnprintable(s string) string { for _, r := range s { if !unicode.IsPrint(r) { return strconv.Quote(s) diff --git a/internal/vaultik/blob_fetch.go b/internal/vaultik/blob_fetch.go index 714c7d1..8e7ffdb 100644 --- a/internal/vaultik/blob_fetch.go +++ b/internal/vaultik/blob_fetch.go @@ -22,6 +22,10 @@ var errBlobHashMismatch = errors.New("blob hash mismatch") var errBlobNotFullyRead = errors.New( "blob closed before fully read; hash not verified") +// errWrongPrivateKeyForBlob is returned when the configured key parses +// but is not one of the keys a blob was encrypted to. +var errWrongPrivateKeyForBlob = errors.New("cannot decrypt this blob") + // hashVerifyReader wraps a blobgen.Reader and verifies the double-SHA-256 hash // of decrypted plaintext when Close is called. It reuses the hash that // blobgen.Reader already computes internally via its TeeReader, avoiding @@ -87,10 +91,14 @@ func (v *Vaultik) FetchAndDecryptBlob( return nil, err } - reader, err := blobgen.NewReader(rc, identities...) + reader, err := v.newBlobReader(rc, identities) if err != nil { _ = rc.Close() + if errors.Is(err, errWrongPrivateKeyForBlob) { + return nil, err + } + return nil, fmt.Errorf("creating blob reader: %w", err) } @@ -102,7 +110,32 @@ func (v *Vaultik) FetchAndDecryptBlob( }, nil } +// newBlobReader opens the decrypting reader for a blob. When none of the +// identities can decrypt it, the error says in plain words that the +// configured private key is not one of the keys the blob was encrypted +// to and names where the key was configured. +func (v *Vaultik) newBlobReader( + r io.Reader, identities []age.Identity, +) (*blobgen.Reader, error) { + blobReader, err := blobgen.NewReader(r, identities...) + + if _, ok := errors.AsType[*age.NoIdentityMatchError](err); ok { + return nil, fmt.Errorf( + "%w: the private key in %s is not one of the keys the blob was encrypted to", + errWrongPrivateKeyForBlob, v.Config.AgeSecretKeySourceName()) + } + + if err != nil { + return nil, err + } + + return blobReader, nil +} + // FetchBlob downloads a blob and returns a reader for the encrypted data. +// The reader is closed as soon as ctx is cancelled, which ends a read +// blocked inside it. A storage error is returned as is: restore and deep +// verify name the blob in their own errors. func (v *Vaultik) FetchBlob( ctx context.Context, blobHash string, ) (io.ReadCloser, error) { @@ -117,8 +150,51 @@ func (v *Vaultik) FetchBlob( rc, err := v.Storage.Get(ctx, blobPath) if err != nil { - return nil, fmt.Errorf("downloading blob %s: %w", shortHash(blobHash), err) + return nil, err } - return rc, nil + return newCloseOnCancelReader(ctx, rc), nil +} + +// closeOnCancelReader closes the reader it wraps when ctx is cancelled. +// Not every backend's reader stops on cancel by itself (the file +// backend's does not), and a read stalled on a slow or hung source would +// otherwise outlast the shutdown timeout, so the process would exit +// before restore, deep verify or `snapshot files` removed its decrypted +// temporary files. +type closeOnCancelReader struct { + io.ReadCloser + + ctx context.Context //nolint:containedctx // Read reports its error + stop func() bool +} + +func newCloseOnCancelReader( + ctx context.Context, rc io.ReadCloser, +) *closeOnCancelReader { + return &closeOnCancelReader{ + ReadCloser: rc, + ctx: ctx, + stop: context.AfterFunc(ctx, func() { _ = rc.Close() }), + } +} + +// Read returns the context's error, not the closed reader's, once ctx +// has been cancelled. +func (r *closeOnCancelReader) Read(p []byte) (int, error) { + n, err := r.ReadCloser.Read(p) + if err != nil && r.ctx.Err() != nil { + return n, r.ctx.Err() + } + + return n, err +} + +// Close closes the wrapped reader, unless the cancel already closed it. +func (r *closeOnCancelReader) Close() error { + if !r.stop() { + return nil + } + + return r.ReadCloser.Close() } diff --git a/internal/vaultik/blobcache.go b/internal/vaultik/blobcache.go index 313c3f9..505f796 100644 --- a/internal/vaultik/blobcache.go +++ b/internal/vaultik/blobcache.go @@ -39,9 +39,9 @@ type blobDiskCacheEntry struct { // internally and will fall back to LRU eviction if curBytes exceeds // maxBytes. Restore passes math.MaxInt64 as maxBytes and drives // eviction itself via Delete() through restoreSweeper, which deletes -// each blob the moment every file that references its chunks has been -// written. LRU never fires under that configuration; it is kept as a -// safety net for callers that don't manage eviction themselves. +// each blob once no file still to be restored in this run needs it. +// LRU never fires under that configuration; it is kept as a safety net +// for callers that don't manage eviction themselves. // // Get/ReadAt/peak-Len counters are debugging instrumentation used by // tests to assert that the restore code path uses ReadAt rather than diff --git a/internal/vaultik/changed_file_restore_test.go b/internal/vaultik/changed_file_restore_test.go new file mode 100644 index 0000000..e82c2b3 --- /dev/null +++ b/internal/vaultik/changed_file_restore_test.go @@ -0,0 +1,232 @@ +package vaultik_test + +import ( + "context" + "crypto/rand" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/chunker" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/214: once +// the only snapshot referencing a changed file's current blob is +// dropped, an older snapshot still keeps the file's row, and the next +// backup must re-chunk the file instead of treating it as unchanged. +// +// Each backup run uses its own snapshot name over the same source +// directory, so the snapshot IDs differ without waiting for their +// one-second timestamps to tick over. File rows are keyed by path, so +// the runs share them exactly as runs of one snapshot name would. + +// changedFileConfig returns a full-backup config with the snapshot names +// "first", "second" and "third", all backing up dataDir. +func changedFileConfig(dataDir, dbPath string) *config.Config { + source := config.SnapshotConfig{Paths: []string{dataDir}} + + cfg := faultTestConfig() + cfg.IndexPath = dbPath + cfg.ChunkSize = config.Size(faultChunkSize) + cfg.Snapshots = map[string]config.SnapshotConfig{ + "first": source, + "second": source, + "third": source, + } + + return cfg +} + +// backUp runs a full backup of the named snapshot. +func backUp(v *vaultik.Vaultik, name string) error { + return v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Cron: true, + Snapshots: []string{name}, + }) +} + +// appendedFileSize is the size of the file before the tests append to it. +// It is twice the largest chunk the chunker cuts, so the file's first +// chunk ends before the appended bytes and stays in a blob the first +// snapshot still references, while its new chunks are only in the blob +// that gets dropped. +const appendedFileSize = 2 * chunker.ChunkSizeSpread * faultChunkSize + +// appendRandomBytes appends n random bytes to the file at path, creating +// the file if it does not exist, and records the new content in files. +// Random content gives the chunker real cut points. +func appendRandomBytes( + t *testing.T, fs afero.Fs, files map[string][]byte, path string, n int64, +) { + t.Helper() + + added := make([]byte, n) + _, err := rand.Read(added) + require.NoError(t, err) + + content := slices.Concat(files[path], added) + require.NoError(t, afero.WriteFile(fs, path, content, 0o644)) + + files[path] = content +} + +// localSnapshotID returns the ID of the one snapshot in the local index +// that was backed up under name. +func localSnapshotID( + ctx context.Context, t *testing.T, + repos *database.Repositories, name string, +) string { + t.Helper() + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + + var ids []string + + for _, s := range snapshots { + if strings.Contains(s.ID.String(), "_"+name+"_") { + ids = append(ids, s.ID.String()) + } + } + + require.Lenf(t, ids, 1, "expected one local snapshot named %q", name) + + return ids[0] +} + +// assertThirdSnapshotRestores closes the local index, then restores the +// snapshot named "third" from store alone and byte-compares every file +// against files. +func assertThirdSnapshotRestores( + ctx context.Context, t *testing.T, cfg *config.Config, + store storage.Storer, repos *database.Repositories, db *database.DB, + fs afero.Fs, restoreDir string, files map[string][]byte, +) { + t.Helper() + + id := localSnapshotID(ctx, t, repos, "third") + require.NoError(t, db.Close()) + + reader := newReaderVaultik(ctx, cfg, store, nil, fs) + require.NoError(t, reader.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Verify: true, + }), "the backup after the drop must restore the changed file") + + assertRestoredTree(t, fs, restoreDir, files) +} + +// Trigger 1: bytes are appended to the file, a second snapshot backs it +// up, and that snapshot is removed. The first snapshot keeps the file row, +// which now lists the appended content's chunks, while removal drops the +// blob that held them. +func TestBackupAfterRemovingNewestSnapshotRestoresChangedFile(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := t.TempDir() + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + changedPath := filepath.Join(dataDir, "appended.bin") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, dataDir) + cfg := changedFileConfig(dataDir, dbPath) + + appendRandomBytes(t, fs, files, changedPath, appendedFileSize) + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, "first")) + + appendRandomBytes(t, fs, files, changedPath, faultChunkSize) + require.NoError(t, backUp(v, "second")) + + _, err = v.RemoveSnapshot(localSnapshotID(ctx, t, repos, "second"), + &vaultik.RemoveOptions{Force: true}) + require.NoError(t, err) + + require.NoError(t, backUp(v, "third")) + + assertThirdSnapshotRestores( + ctx, t, cfg, store, repos, db, fs, restoreDir, files) +} + +// Trigger 2: bytes are appended to the file and the run that backs it up +// is interrupted at the manifest upload, after its blobs were uploaded. +// The next run's prune drops that incomplete snapshot and its blob, while +// the first snapshot keeps the file row, which now lists the appended +// content's chunks. +func TestBackupAfterInterruptedRunRestoresChangedFile(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := t.TempDir() + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + changedPath := filepath.Join(dataDir, "appended.bin") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, dataDir) + cfg := changedFileConfig(dataDir, dbPath) + + appendRandomBytes(t, fs, files, changedPath, appendedFileSize) + + inner, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + failManifest := false + store := faultstore.New(inner) + store.OnPut = func(key string) faultstore.PutAction { + if failManifest && strings.HasSuffix(key, "manifest.json.zst") { + return faultstore.PutFail + } + + return faultstore.PutNormal + } + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, "first")) + + appendRandomBytes(t, fs, files, changedPath, faultChunkSize) + + failManifest = true + + require.Error(t, backUp(v, "second"), + "the run must fail when its manifest upload fails") + + failManifest = false + + require.NoError(t, backUp(v, "third")) + + assertThirdSnapshotRestores( + ctx, t, cfg, inner, repos, db, fs, restoreDir, files) +} diff --git a/internal/vaultik/deep_verify_test.go b/internal/vaultik/deep_verify_test.go index 6c7d782..63ea4f1 100644 --- a/internal/vaultik/deep_verify_test.go +++ b/internal/vaultik/deep_verify_test.go @@ -1,15 +1,20 @@ package vaultik_test import ( + "bytes" "context" + "crypto/rand" "io" "os" + "path" "path/filepath" "testing" "github.com/spf13/afero" "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" "sneak.berlin/go/vaultik/internal/ui" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -30,7 +35,7 @@ func TestDeepVerifyAcceptsHealthyAndRejectsCorruptBlob(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") chunkSize := int64(64 * 1024) @@ -77,6 +82,180 @@ func TestDeepVerifyAcceptsHealthyAndRejectsCorruptBlob(t *testing.T) { "deep verify should fail on a corrupted blob") } +// TestDeepVerifyJSONCountsBlobs checks the verified and missing counts +// that deep verify reports under --json: on a healthy snapshot, with a +// damaged blob, and with missing blobs. Deep verify stops at the first +// damaged blob, so the blobs read before it are the ones verified; when +// blobs are missing it reads no blob contents, but counts every missing +// blob. +func TestDeepVerifyJSONCountsBlobs(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + ctx := context.Background() + storeDir := t.TempDir() + + cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir) + + healthy, err := deepVerifyJSON(ctx, t, cfg, storer, snapshotID) + require.NoError(t, err) + require.Equal(t, "ok", healthy.Status) + require.Len(t, keys, healthy.BlobCount) + require.Equal(t, healthy.BlobCount, healthy.Verified) + require.Zero(t, healthy.Missing) + + // Damage the last blob read, keeping its length, so every blob before + // it is read and passes first. + lastPath := filepath.Join(storeDir, keys[len(keys)-1]) + blob, err := afero.ReadFile(fs, lastPath) + require.NoError(t, err) + + blob[len(blob)/2] ^= 0xff + require.NoError(t, afero.WriteFile(fs, lastPath, blob, 0o600)) + + got, err := deepVerifyJSON(ctx, t, cfg, storer, snapshotID) + require.Error(t, err) + require.Equal(t, "failed", got.Status) + require.Equal(t, healthy.BlobCount-1, got.Verified) + require.Zero(t, got.Missing) + + // Delete the first blob and the damaged last one: both must be + // counted as missing, not only the first one found. + var deletedSize int64 + + for _, key := range []string{keys[0], keys[len(keys)-1]} { + info, statErr := storer.Stat(ctx, key) + require.NoError(t, statErr) + + deletedSize += info.Size + + require.NoError(t, storer.Delete(ctx, key)) + } + + got, err = deepVerifyJSON(ctx, t, cfg, storer, snapshotID) + require.Error(t, err) + require.Equal(t, "failed", got.Status) + require.Equal(t, 2, got.Missing) + require.Equal(t, deletedSize, got.MissingSize) + require.Zero(t, got.Verified) +} + +// TestDeepVerifyJSONCountsWrongSizeBlob checks that under --deep --json a +// blob of the wrong size is counted in mismatched and fails the run, and +// that the check goes on past it to count a missing blob after it. The +// store is on disk, so the message must not call it S3. +func TestDeepVerifyJSONCountsWrongSizeBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + ctx := context.Background() + storeDir := t.TempDir() + + cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir) + + // Make the first blob checked longer, and delete the last one. + firstPath := filepath.Join(storeDir, keys[0]) + blob, err := afero.ReadFile(fs, firstPath) + require.NoError(t, err) + + blob = append(blob, []byte("extra")...) + require.NoError(t, afero.WriteFile(fs, firstPath, blob, 0o600)) + require.NoError(t, storer.Delete(ctx, keys[len(keys)-1])) + + got, err := deepVerifyJSON(ctx, t, cfg, storer, snapshotID) + require.Error(t, err) + require.Equal(t, "failed", got.Status) + require.Equal(t, 1, got.Mismatched) + require.Equal(t, 1, got.Missing) + require.Zero(t, got.Verified) + require.Contains(t, got.ErrorMessage, "with the wrong size") + require.NotContains(t, got.ErrorMessage, "S3") +} + +// TestDeepVerifyStopsOnBlobThatCannotBeChecked checks that a blob that is +// present in storage but cannot be checked is not counted as missing: +// deep verify stops and fails, saying it could not check the blob, with +// the storage error. +func TestDeepVerifyStopsOnBlobThatCannotBeChecked(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + + cfg, storer, snapshotID, keys := backUpSeveralBlobs(ctx, t, storeDir) + failing := statFailingStorer{Storer: storer, failKeys: []string{keys[0]}} + + got, err := deepVerifyJSON(ctx, t, cfg, failing, snapshotID) + require.Error(t, err) + require.Equal(t, "failed", got.Status) + require.Zero(t, got.Missing) + require.Contains(t, got.ErrorMessage, + "could not check blob "+path.Base(keys[0])) + require.Contains(t, got.ErrorMessage, errStatDenied.Error()) +} + +// backUpSeveralBlobs backs up random data, which does not compress or +// deduplicate, so it fills at least three blobs in a store on disk at +// storeDir. It returns the blobs' storage keys sorted, which is hash +// order, the order deep verify reads them in. +func backUpSeveralBlobs( + ctx context.Context, t *testing.T, storeDir string, +) (*config.Config, *storage.FileStorer, string, []string) { + t.Helper() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "source") + dbPath := filepath.Join(tempDir, "index.sqlite") + + chunkSize := int64(32 * 1024) + maxBlobSize := int64(128 * 1024) + + data := make([]byte, maxBlobSize*4) + _, err := rand.Read(data) + require.NoError(t, err) + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, "data.bin"), data, 0o644)) + + cfg, storer, snapshotID := runFileStorageBackup( + ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize) + + keys := storedBlobKeys(t, storeDir) + require.GreaterOrEqual(t, len(keys), 3) + + return cfg, storer, snapshotID, keys +} + +// deepVerifyJSON runs deep verify with --json on snapshotID and returns +// the decoded result and the error RunDeepVerify returned. +func deepVerifyJSON( + ctx context.Context, t *testing.T, + cfg *config.Config, storer storage.Storer, snapshotID string, +) (vaultik.VerifyResult, error) { + t.Helper() + + var out bytes.Buffer + + v := &vaultik.Vaultik{ + Config: cfg, + Storage: storer, + Fs: afero.NewOsFs(), + Stdout: &out, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + v.SetContext(ctx) + + err := v.RunDeepVerify(snapshotID, + &vaultik.VerifyOptions{Deep: true, JSON: true}) + + return decodeVerifyResult(t, out.Bytes()), err +} + // corruptOneBlob flips a middle byte of the first blob file found under // blobsDir, leaving the file length unchanged. func corruptOneBlob(t *testing.T, fs afero.Fs, blobsDir string) { diff --git a/internal/vaultik/destination_marker.go b/internal/vaultik/destination_marker.go new file mode 100644 index 0000000..66d3420 --- /dev/null +++ b/internal/vaultik/destination_marker.go @@ -0,0 +1,111 @@ +package vaultik + +import ( + "errors" + "fmt" + "strings" + + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" +) + +// destinationMarkerKey is the object every backup writes at the root of +// the backup destination store. While the local index holds a snapshot +// stored there, a destination that answers a look-up of it with not +// found is treated as not present: an unplugged volume leaves an empty +// directory at its mount point, which would otherwise read as a store +// whose snapshots are all gone. +const destinationMarkerKey = "vaultik-destination.txt" + +// destinationMarkerText is the whole content of the marker. It names no +// host, path or time. +const destinationMarkerText = "This is a vaultik backup destination store.\n" + +// errDestinationNotPresent is returned when the local index holds a +// snapshot stored on the backup destination store and the store answers +// that it has no marker. +var errDestinationNotPresent = errors.New("backup destination store is not present") + +// checkDestinationMarker returns errDestinationNotPresent when the local +// index holds a snapshot stored on the backup destination store and the +// store answers that it has no marker. With no snapshot in the local +// index, as on a first backup or on another machine, there is nothing to +// check; nor when the local index is bound to a different destination +// than the configured one, since its snapshots are stored there. +// +// A look-up of the marker that fails for any other reason than not +// found is logged and otherwise ignored, because the check could not be +// made: S3 refuses it to credentials that allow only PUT, which is all +// a backup needs. The check exists for a file:// volume's empty mount +// point, which always answers not found, and a destination that cannot +// be reached fails on the next request made to it, such as the backup's +// PUT of the marker. +func (v *Vaultik) checkDestinationMarker() error { + ids, err := v.localSnapshotIDs() + if err != nil { + return fmt.Errorf("listing local snapshots: %w", err) + } + + if len(ids) == 0 { + return nil + } + + // Config is nil only in tests, which then record no binding (see + // checkStorageBinding). + if v.Config != nil { + stored, configured, err := v.storageBinding() + if err != nil { + return err + } + + if stored != "" && stored != configured { + return nil + } + } + + _, err = v.Storage.Stat(v.ctx, destinationMarkerKey) + if errors.Is(err, storage.ErrNotFound) { + return fmt.Errorf("%w: %s has no %s, but the local index holds "+ + "snapshots stored there; mount the volume if it is removable, "+ + "or if the destination was emptied on purpose, run "+ + "'vaultik database delete' and back up again", + errDestinationNotPresent, v.Storage.Info().Location, + destinationMarkerKey) + } + + // Info, not a warning: --cron must stay silent on a successful + // backup from a host whose credentials allow only PUT. + if err != nil { + log.Info("Could not check the backup destination store for its marker", + "key", destinationMarkerKey, "error", err) + } + + return nil +} + +// markDestination refuses a local index bound to a different +// destination, checks the backup destination store for its marker, +// writes the marker, and then records the binding. A first backup marks +// its destination and a later one writes the same text again. The +// binding is recorded last, so a first backup that cannot write to the +// destination leaves the local index unbound. +func (v *Vaultik) markDestination() error { + err := v.checkStorageBinding() + if err != nil { + return err + } + + err = v.checkDestinationMarker() + if err != nil { + return err + } + + err = v.Storage.Put(v.ctx, destinationMarkerKey, + strings.NewReader(destinationMarkerText)) + if err != nil { + return fmt.Errorf("writing %s to the backup destination store: %w", + destinationMarkerKey, err) + } + + return v.EnsureStorageBinding() +} diff --git a/internal/vaultik/destination_marker_test.go b/internal/vaultik/destination_marker_test.go new file mode 100644 index 0000000..0166a76 --- /dev/null +++ b/internal/vaultik/destination_marker_test.go @@ -0,0 +1,331 @@ +package vaultik_test + +import ( + "bytes" + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/239: a +// file:// destination at a volume's mount point leaves an empty directory +// behind when the volume is unplugged. While the local index holds +// snapshots, a destination that answers that it has no +// vaultik-destination.txt is not present, so no command may write to it +// or conclude from it that the local snapshots are gone. + +// markerFile is the name of the file a backup writes at the root of the +// destination. +const markerFile = "vaultik-destination.txt" + +// backUpThenUnplugMountPoint backs up to a file:// destination, then +// moves the destination directory away and leaves an empty directory in +// its place, as unplugging a volume mounted there would. It returns the +// path of that empty directory. +func backUpThenUnplugMountPoint( + ctx context.Context, t *testing.T, +) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer, string) { + t.Helper() + + storeDir := filepath.Join(t.TempDir(), "mnt") + v, repos, out := backUpToFileDestination(ctx, t, storeDir) + + require.NoError(t, os.Rename(storeDir, storeDir+"-unplugged")) + require.NoError(t, os.Mkdir(storeDir, 0o750)) + + return v, repos, out, storeDir +} + +// assertUntouched checks that the local index still holds its one +// snapshot and that nothing was written to the empty mount point. +func assertUntouched( + ctx context.Context, t *testing.T, + repos *database.Repositories, storeDir string, +) { + t.Helper() + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "no local snapshot record may be deleted") + + entries, err := os.ReadDir(storeDir) + require.NoError(t, err) + assert.Empty(t, entries, "nothing may be written to the empty mount point") +} + +// TestFirstBackupWritesMarker checks that a backup writes the marker +// file at the root of the destination. +func TestFirstBackupWritesMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + storeDir := t.TempDir() + backUpToFileDestination(context.Background(), t, storeDir) + + assert.FileExists(t, filepath.Join(storeDir, markerFile)) +} + +// TestBackupRefusesDestinationWithoutMarker checks that snapshot create +// --prune writes nothing and drops no local snapshot record when the +// destination has no marker. +func TestBackupRefusesDestinationWithoutMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, _, storeDir := backUpThenUnplugMountPoint(ctx, t) + + err := v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Cron: true, + Prune: true, + }) + require.ErrorContains(t, err, markerFile) + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestBackupGoesOnWhenMarkerCannotBeChecked checks that a backup goes on +// and writes the marker when looking it up fails with an error other +// than not found, as S3 answers credentials that allow only PUT +// (https://git.eeqj.de/sneak/vaultik/issues/389), and that a marker +// that is not found still stops it. +func TestBackupGoesOnWhenMarkerCannotBeChecked(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + + // Removed so the test sees the backup write it again: with the + // look-up failing, the backup cannot tell that it is gone. + markerPath := filepath.Join(storeDir, markerFile) + require.NoError(t, os.Remove(markerPath)) + + store := faultstore.New(v.Storage) + store.OnStat = func(key string) bool { return key == markerFile } + v.Storage = store + + require.NoError(t, backUp(v, "second")) + localSnapshotID(ctx, t, repos, "second") + assert.FileExists(t, markerPath) + + require.NoError(t, os.Remove(markerPath)) + + store.OnStat = nil + + require.ErrorContains(t, backUp(v, "third"), markerFile) +} + +// TestBackupChecksMarkerBeforeDroppingIncompleteSnapshots checks that +// snapshot create writes nothing when the local index holds only an +// incomplete snapshot and the destination has no marker. The backup drops +// incomplete snapshots before it scans; checked after that, the local +// index would hold none and nothing would be checked. +func TestBackupChecksMarkerBeforeDroppingIncompleteSnapshots(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + v, repos := newFileDestinationVaultik(ctx, t, storeDir) + + require.NoError(t, repos.Snapshots.Create(ctx, nil, &database.Snapshot{ + ID: "host_first_2026-01-02T03:04:05Z", + Hostname: "host", + StartedAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC), + })) + + err := backUp(v, "first") + require.ErrorContains(t, err, markerFile) + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestPruneRefusesDestinationWithoutMarker checks that prune fails and +// deletes no local snapshot record when the destination has no marker. +func TestPruneRefusesDestinationWithoutMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, _, storeDir := backUpThenUnplugMountPoint(ctx, t) + + err := v.Prune(&vaultik.PruneOptions{Force: true}) + require.ErrorContains(t, err, markerFile) + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestPurgeRefusesDestinationWithoutMarker checks that snapshot purge +// fails and deletes no local snapshot record when the destination has no +// marker. +func TestPurgeRefusesDestinationWithoutMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, _, storeDir := backUpThenUnplugMountPoint(ctx, t) + + err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + KeepLatest: true, + Force: true, + }) + require.ErrorContains(t, err, markerFile) + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestNukeRemoteRefusesDestinationWithoutMarker checks that remote nuke +// fails, deletes no local snapshot record, and neither reports the +// destination empty nor advises running nuke again when the destination +// has no marker. +func TestNukeRemoteRefusesDestinationWithoutMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out, storeDir := backUpThenUnplugMountPoint(ctx, t) + + err := v.NukeRemote(true) + require.ErrorContains(t, err, markerFile) + assert.NotContains(t, out.String(), "now empty") + assert.NotContains(t, out.String(), "vaultik remote nuke --force") + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestRemoveSnapshotWarnsWhenDestinationHasNoMarker checks that snapshot +// remove warns that the metadata could not be removed from a destination +// without a marker, instead of reporting that it was. +func TestRemoveSnapshotWarnsWhenDestinationHasNoMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out, _ := backUpThenUnplugMountPoint(ctx, t) + + result, err := v.RemoveSnapshot(localSnapshotID(ctx, t, repos, "first"), + &vaultik.RemoveOptions{Force: true}) + require.NoError(t, err) + + assert.False(t, result.RemoteRemoved) + assert.Contains(t, out.String(), + "Could not remove snapshot metadata from remote") + assert.Contains(t, out.String(), markerFile) + assert.NotContains(t, out.String(), + "Removed snapshot metadata from remote storage") +} + +// TestRemoveSnapshotOnlyOnDestinationFailsWithoutMarker checks that +// snapshot remove, for a snapshot that is only on the destination, fails +// saying the destination is not present when it has no marker, instead +// of saying the snapshot does not exist. +func TestRemoveSnapshotOnlyOnDestinationFailsWithoutMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "mnt") + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + require.NoError(t, backUp(v, "second")) + + id := localSnapshotID(ctx, t, repos, "first") + _, err := v.RemoveSnapshot(id, + &vaultik.RemoveOptions{Force: true, LocalOnly: true}) + require.NoError(t, err) + + // Unplug the volume: an empty directory stays at its mount point. + require.NoError(t, os.Rename(storeDir, storeDir+"-unplugged")) + require.NoError(t, os.Mkdir(storeDir, 0o750)) + + _, err = v.RemoveSnapshot(id, &vaultik.RemoveOptions{Force: true}) + require.ErrorContains(t, err, markerFile) + require.ErrorContains(t, err, "mount the volume") + + assertUntouched(ctx, t, repos, storeDir) +} + +// TestListSnapshotsWarnsWhenDestinationHasNoMarker checks that snapshot +// list warns and shows the local index alone when the destination has no +// marker, without reporting the local snapshot as missing from it. +func TestListSnapshotsWarnsWhenDestinationHasNoMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out, _ := backUpThenUnplugMountPoint(ctx, t) + id := localSnapshotID(ctx, t, repos, "first") + + require.NoError(t, v.ListSnapshots(false)) + + assert.Contains(t, out.String(), "Could not list backup destination store") + assert.Contains(t, out.String(), markerFile) + assert.Contains(t, out.String(), id) + assert.NotContains(t, out.String(), "not found in backup destination store") +} + +// TestListSnapshotsAfterStorageURLChangeToEmptyDirectory checks that +// snapshot list, after storage_url is changed to an empty directory, +// warns only that the local index is bound to a different destination: +// the local snapshots are stored at the old one, so the new one's lack +// of a marker says nothing. With --json the local row is not on the new +// destination, so remote_present is false, not unknown. +func TestListSnapshotsAfterStorageURLChangeToEmptyDirectory(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out := backUpToFileDestination(ctx, t, t.TempDir()) + id := localSnapshotID(ctx, t, repos, "first") + + newDir := t.TempDir() + store, err := storage.NewFileStorer(newDir) + require.NoError(t, err) + + v.Storage = store + v.Config.StorageURL = "file://" + newDir + + require.NoError(t, v.ListSnapshots(false)) + + assert.Contains(t, out.String(), id) + assert.Contains(t, out.String(), + "local index is bound to a different backup destination") + assert.NotContains(t, out.String(), "Could not list backup destination store") + assert.NotContains(t, out.String(), markerFile) + + out.Reset() + require.NoError(t, v.ListSnapshots(true)) + + rows := decodeListJSON(t, out.String()) + require.Len(t, rows, 1) + require.NotNil(t, rows[0].RemotePresent) + assert.False(t, *rows[0].RemotePresent) +} + +// TestBackupAfterNukeRemoteSucceeds checks that remote nuke leaves the +// destination ready for a new first backup, which writes the marker +// again. +func TestBackupAfterNukeRemoteSucceeds(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + storeDir := t.TempDir() + v, _, _ := backUpToFileDestination(context.Background(), t, storeDir) + + require.NoError(t, v.NukeRemote(true)) + assert.NoFileExists(t, filepath.Join(storeDir, markerFile)) + + require.NoError(t, backUp(v, "second")) + assert.FileExists(t, filepath.Join(storeDir, markerFile)) +} diff --git a/internal/vaultik/destination_validation_test.go b/internal/vaultik/destination_validation_test.go index d154fc9..9bc7d58 100644 --- a/internal/vaultik/destination_validation_test.go +++ b/internal/vaultik/destination_validation_test.go @@ -161,13 +161,14 @@ func TestVerifyManifestBlobsRejectsShortHash(t *testing.T) { Blobs: []snapshot.BlobInfo{{Hash: "abc", CompressedSize: 1}}, } - verified, missing, mismatched, missingSize, err := + verified, missing, mismatched, missingSize, unchecked, err := v.verifyManifestBlobs(manifest, &VerifyOptions{JSON: true}) require.ErrorIs(t, err, errInvalidBlobHash) require.Zero(t, verified) require.Zero(t, missing) require.Zero(t, mismatched) require.Zero(t, missingSize) + require.Empty(t, unchecked) } // TestVerifyBlobChunksRejectsNegativeLength proves a blob_chunks row with a @@ -257,6 +258,10 @@ func (s *stubLister) List(_ context.Context, _ string) ([]string, error) { return nil, errStubUnused } +func (s *stubLister) DeletePartialUploads(_ context.Context, _ string) error { + return errStubUnused +} + func (s *stubLister) Info() storage.Info { return storage.Info{} } diff --git a/internal/vaultik/fault_injection_test.go b/internal/vaultik/fault_injection_test.go index dd02574..3cccec3 100644 --- a/internal/vaultik/fault_injection_test.go +++ b/internal/vaultik/fault_injection_test.go @@ -38,11 +38,9 @@ import ( // (https://git.eeqj.de/sneak/vaultik/issues/130) and is not re-tested // here; these tests target the layers above the backend. // -// The tests run serially, not with t.Parallel: each calls -// log.Initialize, which replaces the package-global logger, and a -// backup or restore running concurrently reads that same logger. Under -// -race the two collide. Running one at a time is the same choice -// prune_count_test.go already makes for the same reason. +// log.Initialize replaces the package-global logger that a running +// backup or restore reads, so each test calls it before t.Parallel, +// while no parallel test is running yet. const ( faultChunkSize = int64(64 * 1024) @@ -165,17 +163,19 @@ func newReaderVaultik( // Scenario 3: a stored blob's bytes are flipped before restore reads // them. Restore must fail loudly, and no file must be left on the // restore target holding corrupt content. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestRestoreRejectsCorruptBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + assertRestoreRejectsDamagedBlob(t, faultstore.GetCorrupt, "corrupt") } // Scenario 4: a stored blob is truncated before restore reads it. Same // contract as the corrupt case. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestRestoreRejectsTruncatedBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + assertRestoreRejectsDamagedBlob(t, faultstore.GetTruncate, "truncated") } @@ -188,12 +188,11 @@ func assertRestoreRejectsDamagedBlob( t *testing.T, fault faultstore.GetFault, name string, ) { t.Helper() - log.Initialize(log.Config{}) fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -232,15 +231,14 @@ func assertRestoreRejectsDamagedBlob( // Scenario 6: the backend accepts blob uploads and reports success but // stores nothing. verify --deep must catch it. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestDeepVerifyCatchesLyingBackend(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") ctx := context.Background() @@ -285,15 +283,14 @@ func TestDeepVerifyCatchesLyingBackend(t *testing.T) { // Scenario 1a: a blob upload fails partway through. The interrupted run // must not record the blob as uploaded, must not reference it from the // snapshot, and must leave no blob object at the destination. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestInterruptedBlobUploadRecordsNoUploadedBlob(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") ctx := context.Background() @@ -357,15 +354,14 @@ func TestInterruptedBlobUploadRecordsNoUploadedBlob(t *testing.T) { // chunks in a blob that was actually uploaded, so the retry re-chunks and // re-uploads the affected data instead of silently referencing data that // never reached storage. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestBackupRetryAfterInterruptedUploadIsRestorable(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -422,15 +418,14 @@ func TestBackupRetryAfterInterruptedUploadIsRestorable(t *testing.T) { // covered by TestBackupCompletesOnlyAfterMetadataExport // (https://git.eeqj.de/sneak/vaultik/issues/177); this test exercises the // lower-level export path in isolation. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestBackupSurvivesMetadataExportInterruption(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") ctx := context.Background() @@ -446,6 +441,10 @@ func TestBackupSurvivesMetadataExportInterruption(t *testing.T) { repos := database.NewRepositories(db) + // snapshot create writes the marker; this backup runs its steps one + // by one, so the marker is written here. + require.NoError(t, inner.Put(ctx, markerFile, strings.NewReader(""))) + // Back up and complete with a working backend. sm := newFaultSnapshotManager(fs, inner, cfg, repos) scanner := newFaultScanner(fs, inner, cfg, repos) @@ -494,8 +493,14 @@ func TestBackupSurvivesMetadataExportInterruption(t *testing.T) { "shallow verify must report the missing manifest") // snapshot list must not crash on the partial snapshot. + var listOut strings.Builder + + reader.UI = ui.NewWithColor(&listOut, false) require.NoError(t, reader.ListSnapshots(false), "snapshot list must tolerate a partially-exported snapshot") + assert.NotContains(t, listOut.String(), + "Could not list backup destination store", + "snapshot list must read the partial snapshot from the destination") } // Scenario 2, repair: the process dies during the metadata export of a @@ -505,15 +510,14 @@ func TestBackupSurvivesMetadataExportInterruption(t *testing.T) { // destination. Rerunning the backup must then prune the incomplete // snapshot, produce a snapshot whose destination metadata and local index // agree, and restore. See https://git.eeqj.de/sneak/vaultik/issues/177. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestBackupCompletesOnlyAfterMetadataExport(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() fs := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -663,41 +667,34 @@ func faultScannerFactory( ) snapshot.ScannerFactory { return func(params snapshot.ScannerParams) *snapshot.Scanner { return snapshot.NewScanner(snapshot.ScannerConfig{ - FS: params.Fs, - Storage: storer, - ChunkSize: faultChunkSize, - MaxBlobSize: faultMaxBlobSize, - CompressionLevel: cfg.CompressionLevel, - AgeRecipients: cfg.AgeRecipients, - Repositories: repos, - EnableProgress: params.EnableProgress, - UI: params.UI, - Exclude: params.Exclude, - SkipErrors: params.SkipErrors, + FS: params.Fs, + Storage: storer, + ChunkSize: faultChunkSize, + MaxBlobSize: faultMaxBlobSize, + CompressionLevel: cfg.CompressionLevel, + AgeRecipients: cfg.AgeRecipients, + Repositories: repos, + EnableProgress: params.EnableProgress, + UI: params.UI, + Exclude: params.Exclude, + SkipErrors: params.SkipErrors, + PreviousSnapshotID: params.PreviousSnapshotID, + DeviceNumber: params.DeviceNumber, }) } } // Scenario 5: the restore target runs out of space mid-file. Restore // must fail with an out-of-space error, and must not leave a truncated -// file at the target path presenting as a complete restore. Restore -// today writes each file straight to its final path and does not remove -// it when a write fails, so the truncated file survives; deleting it is -// tracked by https://git.eeqj.de/sneak/vaultik/issues/163. Skipped until -// that lands, so the destination assertion below is recorded rather than -// dropped. -// -//nolint:paralleltest // installs the global logger via log.Initialize +// file at the target path presenting as a complete restore. func TestRestoreReportsDiskFull(t *testing.T) { - t.Skip("blocked on https://git.eeqj.de/sneak/vaultik/issues/163: " + - "a disk-full write leaves a truncated file at the target path " + - "instead of removing it") log.Initialize(log.Config{}) + t.Parallel() osFS := afero.NewOsFs() tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "src") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -717,10 +714,10 @@ func TestRestoreReportsDiskFull(t *testing.T) { id := fullFaultBackup(ctx, t, osFS, inner, cfg, repos, dataDir, dbPath, "diskfull") require.NoError(t, db.Close()) - // Restore onto a filesystem that allows only a few bytes of file - // content: enough to create files, far too little to hold them. + // Restore onto a target that allows only a few bytes of file content: + // enough to create files, far too little to hold them. budget := int64(8) - quota := "aFS{Fs: osFS, remaining: &budget} + quota := "aFS{Fs: osFS, dir: restoreDir, remaining: &budget} v := newReaderVaultik(ctx, cfg, inner, nil, quota) err = v.Restore(&vaultik.RestoreOptions{SnapshotID: id, TargetDir: restoreDir}) @@ -754,21 +751,26 @@ func assertRestoredTree( // budget is exhausted, mirroring a real ENOSPC. var errNoSpace = errors.New("no space left on device") -// quotaFS is an afero.Fs whose files may write only a fixed total number -// of content bytes before failing, simulating a full restore target. It -// wraps the interface so every method except Create delegates to the -// real filesystem; only file writes are capped. +// quotaFS is an afero.Fs on which files opened under dir may write only +// a fixed total number of content bytes before failing, simulating a full +// restore target. Every other method, and every file outside dir, goes +// straight to the real filesystem: restore also writes the decrypted +// metadata database under $TMPDIR through this filesystem, and capping +// that would fail the restore before it wrote anything to the target. type quotaFS struct { afero.Fs + dir string remaining *int64 } -//nolint:ireturn // afero.Fs.Create's signature requires returning afero.File. -func (q *quotaFS) Create(name string) (afero.File, error) { - f, err := q.Fs.Create(name) - if err != nil { - return nil, err +//nolint:ireturn // afero.Fs.OpenFile's signature requires returning afero.File. +func (q *quotaFS) OpenFile( + name string, flag int, perm os.FileMode, +) (afero.File, error) { + f, err := q.Fs.OpenFile(name, flag, perm) + if err != nil || !strings.HasPrefix(name, q.dir) { + return f, err } return "aFile{File: f, remaining: q.remaining}, nil diff --git a/internal/vaultik/helpers.go b/internal/vaultik/helpers.go index 64a1d85..c891b34 100644 --- a/internal/vaultik/helpers.go +++ b/internal/vaultik/helpers.go @@ -3,12 +3,14 @@ package vaultik import ( "errors" "fmt" + "math" "regexp" "strconv" "strings" "time" "github.com/dustin/go-humanize" + "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/types" ) @@ -46,12 +48,13 @@ const ( year = 365 * day ) -// Snapshot IDs split on "_" into hostname, optional name parts, and a -// trailing timestamp. -const ( - minSnapshotIDParts = 2 - minSnapshotIDNameParts = 3 -) +// maxDuration is the largest value a time.Duration can hold, about 292 +// years. +const maxDuration = time.Duration(math.MaxInt64) + +// A snapshot ID split on "_" has at least a hostname and a trailing +// timestamp. +const minSnapshotIDParts = 2 // SnapshotInfo contains information about a snapshot. // @@ -86,22 +89,6 @@ type SnapshotInfo struct { RemotePresent *bool `json:"remote_present"` } -// formatBytes formats bytes in a human-readable format -func formatBytes(bytes int64) string { - const unit = 1024 - if bytes < unit { - return fmt.Sprintf("%d B", bytes) - } - - div, exp := int64(unit), 0 - for n := bytes / unit; n >= unit; n /= unit { - div *= unit - exp++ - } - - return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp]) -} - // parseSnapshotTimestamp extracts the timestamp from a snapshot ID // Format: hostname_snapshotname_2026-01-12T14:41:15Z func parseSnapshotTimestamp(snapshotID string) (time.Time, error) { @@ -121,43 +108,60 @@ func parseSnapshotTimestamp(snapshotID string) (time.Time, error) { return timestamp.UTC(), nil } -// parseSnapshotName extracts the snapshot name from a snapshot ID. -// Format: hostname_snapshotname_timestamp — the middle part(s) between hostname -// and the RFC3339 timestamp are the snapshot name (may contain underscores). -// Returns the snapshot name, or empty string if the ID is malformed. -func parseSnapshotName(snapshotID string) string { - parts := strings.Split(snapshotID, "_") - if len(parts) < minSnapshotIDNameParts { - // Format: hostname_timestamp — no snapshot name +// parseSnapshotName extracts the snapshot name from a snapshot ID of the +// form hostname_name_timestamp, given the hostname stored with that +// snapshot. The hostname and the name may both contain underscores, so the +// name is what is left after removing the short hostname and its "_" from +// the front and the last "_" and the timestamp from the end. Returns "" for +// an ID with no name (hostname_timestamp), and for an ID that does not start +// with that hostname, which CreateSnapshotWithName never writes. +func parseSnapshotName(snapshotID, hostname string) string { + prefix := snapshot.ShortHostname(hostname) + "_" + + rest, ok := strings.CutPrefix(snapshotID, prefix) + if !ok { return "" } - // Format: hostname_name_timestamp — middle parts are the name. - // The last part is the RFC3339 timestamp, the first part is the hostname, - // everything in between is the snapshot name (which may itself contain underscores). - return strings.Join(parts[1:len(parts)-1], "_") + + end := strings.LastIndex(rest, "_") + if end < 0 { + return "" + } + + return rest[:end] } // parseDuration parses a duration string with support for human-friendly units: // d/day/days, w/week/weeks, mo/month/months, y/year/years, plus standard Go // duration units. Following Go, m is minutes and mo is months. A bare number, -// an unknown unit, and a negative value are all rejected. +// an unknown unit, a negative value, and a total longer than maxDuration are +// all rejected. Outside the Go units the input must be whole numbers each +// followed directly by a unit (2w3d), so 1.0y and 30 days are errors; +// decimals work only in Go units (1.5h). func parseDuration(s string) (time.Duration, error) { if strings.HasPrefix(strings.TrimSpace(s), "-") { return 0, errNegativeDuration } + // A bare number has no unit, but time.ParseDuration accepts 0, which + // would put the cutoff at now and select every snapshot. + _, err := strconv.ParseFloat(s, 64) + if err == nil { + return 0, fmt.Errorf("%w: %q", errInvalidDuration, s) + } + d, err := time.ParseDuration(s) if err == nil { return d, nil } - re := regexp.MustCompile(`(\d+)\s*([a-zA-Z]+)`) - - matches := re.FindAllStringSubmatch(s, -1) - if len(matches) == 0 { + if !regexp.MustCompile(`^(\d+[a-zA-Z]+)+$`).MatchString(s) { return 0, fmt.Errorf("%w: %q", errInvalidDuration, s) } + re := regexp.MustCompile(`(\d+)([a-zA-Z]+)`) + matches := re.FindAllStringSubmatch(s, -1) + var total time.Duration for _, match := range matches { @@ -166,19 +170,30 @@ func parseDuration(s string) (time.Duration, error) { return 0, fmt.Errorf("invalid number %q: %w", match[1], err) } + var unitLength time.Duration + unit := strings.ToLower(match[2]) switch unit { case "d", "day", "days": - total += time.Duration(n) * day + unitLength = day case "w", "week", "weeks": - total += time.Duration(n) * week + unitLength = week case "mo", "month", "months": - total += time.Duration(n) * month + unitLength = month case "y", "year", "years": - total += time.Duration(n) * year + unitLength = year default: return 0, fmt.Errorf("%w %q", errUnknownTimeUnit, unit) } + + // Past maxDuration the sum wraps to a negative value, which would + // put the purge cutoff in the future. + if time.Duration(n) > (maxDuration-total)/unitLength { + return 0, fmt.Errorf("%w: %q is longer than about 292 years", + errInvalidDuration, s) + } + + total += time.Duration(n) * unitLength } return total, nil diff --git a/internal/vaultik/helpers_test.go b/internal/vaultik/helpers_test.go index eb58781..f3b2f04 100644 --- a/internal/vaultik/helpers_test.go +++ b/internal/vaultik/helpers_test.go @@ -11,33 +11,55 @@ func TestParseSnapshotName(t *testing.T) { tests := []struct { name string snapshotID string + hostname string want string }{ { name: "standard format with name", snapshotID: "myhost_home_2026-01-12T14:41:15Z", + hostname: "myhost", want: "home", }, { name: "standard format with different name", snapshotID: "server1_system_2026-02-15T09:30:00Z", + hostname: "server1", want: "system", }, { name: "name with underscores", snapshotID: "myhost_my_special_backup_2026-03-01T00:00:00Z", + hostname: "myhost", want: "my_special_backup", }, + { + name: "hostname with underscores", + snapshotID: "my_host_docs_2026-03-01T00:00:00Z", + hostname: "my_host", + want: "docs", + }, + { + name: "stored hostname with domain", + snapshotID: "my_host_mail_2026-03-01T00:00:00Z", + hostname: "my_host.example.com", + want: "mail", + }, + { + name: "no name", + snapshotID: "my_host_2026-03-01T00:00:00Z", + hostname: "my_host", + want: "", + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - got := parseSnapshotName(tt.snapshotID) + got := parseSnapshotName(tt.snapshotID, tt.hostname) if got != tt.want { - t.Errorf("parseSnapshotName(%q) = %q, want %q", - tt.snapshotID, got, tt.want) + t.Errorf("parseSnapshotName(%q, %q) = %q, want %q", + tt.snapshotID, tt.hostname, got, tt.want) } }) } @@ -59,6 +81,7 @@ func TestParseDuration(t *testing.T) { {"30s", 30 * time.Second, false}, {"6m", 6 * time.Minute, false}, {"1h", time.Hour, false}, + {"1.5h", 90 * time.Minute, false}, // Extended calendar units. {"30d", 30 * 24 * time.Hour, false}, {"3days", 3 * 24 * time.Hour, false}, @@ -73,11 +96,32 @@ func TestParseDuration(t *testing.T) { {"1y6mo", 365*24*time.Hour + 180*24*time.Hour, false}, // Rejected inputs. {"6", 0, true}, // bare number, no unit + {"0", 0, true}, // bare number; time.ParseDuration accepts it + {"+0", 0, true}, // bare number; time.ParseDuration accepts it {"5x", 0, true}, // unknown unit {"-5d", 0, true}, // negative, extended unit {"-5h", 0, true}, // negative, Go unit {"", 0, true}, // empty {"garbage", 0, true}, + // Characters outside the number-and-unit parts must not be + // skipped: 1.0y read as 0y would select every snapshot. + {"1.0y", 0, true}, + {"2.1w", 0, true}, + {"1,5y", 0, true}, + {"30 days", 0, true}, + {"30 days ago", 0, true}, + {"x7d", 0, true}, + // The largest time.Duration is about 292 years. A larger value + // must be rejected, not wrapped to a negative one, which would + // put the cutoff in the future and select every snapshot. + {"292y", 292 * 365 * 24 * time.Hour, false}, + {"293y", 0, true}, + {"3559mo", 0, true}, + {"15251w", 0, true}, + {"106752d", 0, true}, + {"2562048h", 0, true}, + {"200y200y", 0, true}, + {"292y6mo", 0, true}, } for _, tt := range tests { diff --git a/internal/vaultik/info.go b/internal/vaultik/info.go index 53e6d44..c4cc18c 100644 --- a/internal/vaultik/info.go +++ b/internal/vaultik/info.go @@ -167,10 +167,6 @@ const ( // metadataKeyParts is the minimum "/"-separated segment count of a // metadata object key (metadata//). metadataKeyParts = 3 - - // blobKeyParts is the minimum "/"-separated segment count of a blob - // object key (blobs///). - blobKeyParts = 4 ) // SnapshotMetadataInfo contains information about a single snapshot's metadata @@ -181,8 +177,16 @@ type SnapshotMetadataInfo struct { ManifestSize int64 `json:"manifest_size"` DatabaseSize int64 `json:"database_size"` TotalSize int64 `json:"total_size"` - BlobCount int `json:"blob_count"` - BlobsSize int64 `json:"blobs_size"` + + // Both stay nil (null in the JSON) when the snapshot's manifest was + // listed but could not be read. + BlobCount *int `json:"blob_count"` + BlobsSize *int64 `json:"blobs_size"` + + // Set when the listing holds this snapshot's manifest.json.zst. A + // backup interrupted before its manifest upload leaves a directory + // without one, which prune does not treat as a snapshot. + hasManifest bool } // RemoteInfoResult contains all remote storage information @@ -206,9 +210,20 @@ type RemoteInfoResult struct { ReferencedBlobCount int `json:"referenced_blob_count"` ReferencedBlobSize int64 `json:"referenced_blob_size"` - // Orphaned blobs - OrphanedBlobCount int `json:"orphaned_blob_count"` - OrphanedBlobSize int64 `json:"orphaned_blob_size"` + // Orphaned blobs. Both stay nil (null in the JSON) when a manifest + // was listed but not read, since that snapshot's blobs would be + // counted as orphaned. + OrphanedBlobCount *int `json:"orphaned_blob_count"` + OrphanedBlobSize *int64 `json:"orphaned_blob_size"` + + // Remote key of each snapshot whose manifest could not be read + UnreadableManifests []string `json:"unreadable_manifests,omitempty"` + + // Number of manifests not read because the name above them under + // metadata/ is not a remote key. The names themselves are not + // reported: they come from the destination store and may hold + // control characters. + SkippedManifestCount int `json:"skipped_manifest_count,omitempty"` } // RemoteInfo displays information about remote storage @@ -231,19 +246,31 @@ func (v *Vaultik) RemoteInfo(jsonOutput bool) error { v.stdoutf("Type: %s\n", storageInfo.Type) v.stdoutf("Location: %s\n", storageInfo.Location) v.printlnStdout() - v.stdoutf("Scanning snapshot metadata...\n") + v.UI.Beginf("Scanning snapshot metadata...") } - snapshotMetadata, snapshotIDs, err := v.collectSnapshotMetadata() + snapshotMetadata, snapshotIDs, skippedManifestCount, err := v.collectSnapshotMetadata() if err != nil { return err } + result.SkippedManifestCount = skippedManifestCount + if showText { - v.stdoutf("Downloading %d manifest(s)...\n", len(snapshotIDs)) + manifestCount := 0 + + for _, info := range snapshotMetadata { + if info.hasManifest { + manifestCount++ + } + } + + v.UI.Beginf("Downloading %d manifest(s)...", manifestCount) } - referencedBlobs := v.collectReferencedBlobsFromManifests(snapshotIDs, snapshotMetadata) + referencedBlobs, unreadableManifests := v.collectReferencedBlobsFromManifests( + snapshotIDs, snapshotMetadata) + result.UnreadableManifests = unreadableManifests v.populateRemoteInfoResult(result, snapshotMetadata, snapshotIDs, referencedBlobs) @@ -256,7 +283,7 @@ func (v *Vaultik) RemoteInfo(jsonOutput bool) error { "snapshots", result.TotalMetadataCount, "total_blobs", result.TotalBlobCount, "referenced_blobs", result.ReferencedBlobCount, - "orphaned_blobs", result.OrphanedBlobCount) + "unreadable_manifests", len(result.UnreadableManifests)) if jsonOutput { enc := json.NewEncoder(v.Stdout) @@ -273,16 +300,18 @@ func (v *Vaultik) RemoteInfo(jsonOutput bool) error { } // collectSnapshotMetadata scans remote metadata and returns -// per-snapshot info and sorted IDs. +// per-snapshot info, sorted IDs and the number of manifests it skipped +// because the name above them is not a remote key. func (v *Vaultik) collectSnapshotMetadata() ( - map[string]*SnapshotMetadataInfo, []string, error, + map[string]*SnapshotMetadataInfo, []string, int, error, ) { snapshotMetadata := make(map[string]*SnapshotMetadataInfo) + skippedManifestCount := 0 metadataCh := v.Storage.ListStream(v.ctx, "metadata/") for obj := range metadataCh { if obj.Err != nil { - return nil, nil, fmt.Errorf("listing metadata: %w", obj.Err) + return nil, nil, 0, fmt.Errorf("listing metadata: %w", obj.Err) } parts := strings.Split(obj.Key, "/") @@ -291,6 +320,22 @@ func (v *Vaultik) collectSnapshotMetadata() ( } snapshotID := parts[1] + filename := parts[2] + isManifest := filename == "manifest.json.zst" + + // The name comes from the destination store, which is not + // trusted, and is printed in the report. Accept it only in the + // form of a remote key. + if !isBlobHash(snapshotID) { + log.Warn("Skipping non-conforming key under metadata/", + "key", obj.Key) + + if isManifest { + skippedManifestCount++ + } + + continue + } if _, exists := snapshotMetadata[snapshotID]; !exists { snapshotMetadata[snapshotID] = &SnapshotMetadataInfo{SnapshotID: snapshotID} @@ -298,7 +343,10 @@ func (v *Vaultik) collectSnapshotMetadata() ( info := snapshotMetadata[snapshotID] - filename := parts[2] + if isManifest { + info.hasManifest = true + } + if strings.HasPrefix(filename, "manifest") { info.ManifestSize = obj.Size } else if strings.HasPrefix(filename, "db") { @@ -315,17 +363,29 @@ func (v *Vaultik) collectSnapshotMetadata() ( sort.Strings(snapshotIDs) - return snapshotMetadata, snapshotIDs, nil + return snapshotMetadata, snapshotIDs, skippedManifestCount, nil } -// collectReferencedBlobsFromManifests downloads manifests and returns -// referenced blob hashes with sizes. +// collectReferencedBlobsFromManifests downloads the listed manifests +// and returns referenced blob hashes with sizes, and the remote keys +// of the manifests it could not read. func (v *Vaultik) collectReferencedBlobsFromManifests( snapshotIDs []string, snapshotMetadata map[string]*SnapshotMetadataInfo, -) map[string]int64 { +) (map[string]int64, []string) { referencedBlobs := make(map[string]int64) + var unreadable []string + for _, snapshotID := range snapshotIDs { + info := snapshotMetadata[snapshotID] + if !info.hasManifest { + // The orphan figures count this directory's blobs as + // orphaned, so it references none. + info.BlobCount, info.BlobsSize = new(int), new(int64) + + continue + } + // snapshotIDs here are remote keys, taken straight from the // metadata/ listing. downloadManifestByKey is the single reader // for remote manifests; see its doc comment. @@ -333,11 +393,12 @@ func (v *Vaultik) collectReferencedBlobsFromManifests( if err != nil { log.Warn("Failed to read manifest", "snapshot", snapshotID, "error", err) + unreadable = append(unreadable, snapshotID) + continue } - info := snapshotMetadata[snapshotID] - info.BlobCount = manifest.BlobCount + blobCount := manifest.BlobCount var blobsSize int64 @@ -346,10 +407,11 @@ func (v *Vaultik) collectReferencedBlobsFromManifests( blobsSize += blob.CompressedSize } - info.BlobsSize = blobsSize + info.BlobCount = &blobCount + info.BlobsSize = &blobsSize } - return referencedBlobs + return referencedBlobs, unreadable } // populateRemoteInfoResult fills in the result's snapshot and @@ -378,41 +440,50 @@ func (v *Vaultik) populateRemoteInfoResult( } // scanRemoteBlobStorage lists all blobs on remote and computes orphan -// stats. showText is true only when the human report is being printed -// (not --json, not --quiet), gating the progress line. +// stats when every listed manifest was read. showText is true only +// when the human report is being printed (not --json, not --quiet), +// gating the progress line. func (v *Vaultik) scanRemoteBlobStorage( result *RemoteInfoResult, referencedBlobs map[string]int64, showText bool, ) error { if showText { - v.stdoutf("Scanning blobs...\n") + v.UI.Beginf("Scanning blobs...") } - blobCh := v.Storage.ListStream(v.ctx, "blobs/") - allBlobs := make(map[string]int64) + // Use prune's listing, so a file under blobs/ that prune would never + // delete is not counted as a blob, and so not as an orphaned one. + allBlobs, err := v.listAllRemoteBlobs() + if err != nil { + return err + } - for obj := range blobCh { - if obj.Err != nil { - return fmt.Errorf("listing blobs: %w", obj.Err) - } - - parts := strings.Split(obj.Key, "/") - if len(parts) < blobKeyParts { - continue - } - - hash := parts[3] - allBlobs[hash] = obj.Size + for _, blob := range allBlobs { result.TotalBlobCount++ - result.TotalBlobSize += obj.Size + result.TotalBlobSize += blob.Size } - for hash, size := range allBlobs { + // A blob named only by a manifest that could not be read, or by one + // under a skipped name, would be counted as orphaned, so the orphan + // figures stay unknown. + if len(result.UnreadableManifests) > 0 || result.SkippedManifestCount > 0 { + return nil + } + + var ( + orphanedCount int + orphanedSize int64 + ) + + for hash, blob := range allBlobs { if _, referenced := referencedBlobs[hash]; !referenced { - result.OrphanedBlobCount++ - result.OrphanedBlobSize += size + orphanedCount++ + orphanedSize += blob.Size } } + result.OrphanedBlobCount = &orphanedCount + result.OrphanedBlobSize = &orphanedSize + return nil } @@ -442,13 +513,23 @@ func (v *Vaultik) printRemoteInfoTable(result *RemoteInfoResult) { v.stdoutf("%s", separator) for _, info := range result.Snapshots { + blobCount := unknownText + if info.BlobCount != nil { + blobCount = humanize.Comma(int64(*info.BlobCount)) + } + + blobsSize := unknownText + if info.BlobsSize != nil { + blobsSize = ubytes(*info.BlobsSize) + } + v.stdoutf(rowFormat, truncateString(info.SnapshotID, snapshotIDColWidth), ubytes(info.ManifestSize), ubytes(info.DatabaseSize), ubytes(info.TotalSize), - humanize.Comma(int64(info.BlobCount)), - ubytes(info.BlobsSize), + blobCount, + blobsSize, ) } @@ -465,11 +546,21 @@ func (v *Vaultik) printRemoteInfoTable(result *RemoteInfoResult) { v.stdoutf("Referenced by snapshots: %s (%s)\n", humanize.Comma(int64(result.ReferencedBlobCount)), ubytes(result.ReferencedBlobSize)) - v.stdoutf("Orphaned (unreferenced): %s (%s)\n", - humanize.Comma(int64(result.OrphanedBlobCount)), - ubytes(result.OrphanedBlobSize)) - if result.OrphanedBlobCount > 0 { + if result.OrphanedBlobCount == nil { + v.stdoutf("Orphaned (unreferenced): unknown "+ + "(%d manifest(s) could not be read, "+ + "%d manifest(s) under a non-conforming name skipped)\n", + len(result.UnreadableManifests), result.SkippedManifestCount) + + return + } + + v.stdoutf("Orphaned (unreferenced): %s (%s)\n", + humanize.Comma(int64(*result.OrphanedBlobCount)), + ubytes(*result.OrphanedBlobSize)) + + if *result.OrphanedBlobCount > 0 { v.stdoutf("\nRun 'vaultik prune' to remove orphaned blobs.\n") } } diff --git a/internal/vaultik/integration_test.go b/internal/vaultik/integration_test.go index bf74e60..f9a90b7 100644 --- a/internal/vaultik/integration_test.go +++ b/internal/vaultik/integration_test.go @@ -155,6 +155,12 @@ func (m *MockStorer) ListStream( return ch } +// DeletePartialUploads has nothing to remove: Put stores each object +// under its key at once. +func (m *MockStorer) DeletePartialUploads(_ context.Context, _ string) error { + return nil +} + func (m *MockStorer) Info() storage.Info { return storage.Info{ Type: "mock", @@ -249,7 +255,7 @@ func verifyEndToEndBackupState( assert.Positive(t, blobUploads, "Should upload at least one blob") // Verify files in database - files, err := repos.Files.ListByPrefix(ctx, "/home/user") + files, err := repos.Files.ListUnderPath(ctx, "/home/user") require.NoError(t, err) // Count only regular files (not directories) regularFiles := 0 @@ -765,7 +771,7 @@ func TestEndToEndFileStorage(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -928,17 +934,17 @@ func setupDedupBackupEnv( } } -// runDedupSnapshot creates a "dedup" snapshot, scans dataDir into it, -// completes it, and exports its metadata, returning the snapshot ID and -// scan result. +// runDedupSnapshot creates a snapshot with the given name, scans dataDir +// into it, completes it, and exports its metadata, returning the snapshot +// ID and scan result. func runDedupSnapshot( ctx context.Context, t *testing.T, sm *snapshot.SnapshotManager, scanner *snapshot.Scanner, - hostname, dataDir, dbPath string, + hostname, name, dataDir, dbPath string, ) (string, *snapshot.ScanResult) { t.Helper() - id, err := sm.CreateSnapshotWithName(ctx, hostname, "dedup", "v", "g") + id, err := sm.CreateSnapshotWithName(ctx, hostname, name, "v", "g") require.NoError(t, err) result, err := scanner.Scan(ctx, dataDir, id) @@ -958,7 +964,7 @@ func TestDedupOnlySnapshotRestores(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -980,16 +986,15 @@ func TestDedupOnlySnapshotRestores(t *testing.T) { // First snapshot — uploads all blobs. _, r1 := runDedupSnapshot(ctx, t, sm, makeScanner(), - cfg.Hostname, dataDir, dbPath) + cfg.Hostname, "first", dataDir, dbPath) require.Positive(t, r1.BlobsCreated, "first snapshot should upload at least one blob") - // Second snapshot — same data, every chunk dedups. Sleep past the - // second-precision timestamp so the snapshot IDs differ. - time.Sleep(1100 * time.Millisecond) - + // Second snapshot — same data, every chunk dedups. Its own name gives + // it a different snapshot ID without waiting for the one-second + // timestamp in the ID to tick over. id2, r2 := runDedupSnapshot(ctx, t, sm, makeScanner(), - cfg.Hostname, dataDir, dbPath) + cfg.Hostname, "second", dataDir, dbPath) require.Equal(t, 0, r2.BlobsCreated, "second snapshot should upload zero new blobs (fully dedup'd)") diff --git a/internal/vaultik/missing_destination_test.go b/internal/vaultik/missing_destination_test.go new file mode 100644 index 0000000..3f3bfa2 --- /dev/null +++ b/internal/vaultik/missing_destination_test.go @@ -0,0 +1,300 @@ +package vaultik_test + +import ( + "bytes" + "context" + "io/fs" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/220: a +// file:// destination whose directory is missing, such as a USB stick +// that is not plugged in, cannot be listed. It is not an empty store, so +// no command may conclude from it that the local snapshots are gone. + +// newFileDestinationVaultik writes the fault source tree and returns a +// Vaultik that backs it up to a file:// destination at storeDir. +func newFileDestinationVaultik( + ctx context.Context, t *testing.T, storeDir string, +) (*vaultik.Vaultik, *database.Repositories) { + t.Helper() + + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + writeFaultSourceTree(t, afero.NewOsFs(), dataDir) + + return openFileDestinationVaultik(ctx, t, storeDir, dataDir, + filepath.Join(tempDir, "index.sqlite")) +} + +// openFileDestinationVaultik returns a Vaultik that backs up dataDir to a +// file:// destination at storeDir, with its local index at dbPath. The +// index is closed when the test ends. +func openFileDestinationVaultik( + ctx context.Context, t *testing.T, storeDir, dataDir, dbPath string, +) (*vaultik.Vaultik, *database.Repositories) { + t.Helper() + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + cfg := changedFileConfig(dataDir, dbPath) + + return newBackupVaultik(ctx, cfg, store, repos, db, afero.NewOsFs()), repos +} + +// firstBackup is one backup of the snapshot named "first" to a file:// +// destination. dir holds its source tree in src, its store in store and +// its closed local index in index/index.sqlite. The first test that +// needs it makes it, and TestMain removes it. Every test that copies it +// backs up the same source tree, so no test may change that tree. +// +//nolint:gochecknoglobals // made once and shared by the tests that copy it +var firstBackup struct { + once sync.Once + dir string + ready bool +} + +// TestMain removes firstBackup once every test has run. +func TestMain(m *testing.M) { + code := m.Run() + + _ = os.RemoveAll(firstBackup.dir) + + os.Exit(code) +} + +// makeFirstBackup writes the fault source tree and backs it up as the +// snapshot named "first", all in a new directory that it records in +// firstBackup. +func makeFirstBackup(ctx context.Context, t *testing.T) { + t.Helper() + + dir, err := os.MkdirTemp("", "vaultik-first-backup-") + require.NoError(t, err) + + firstBackup.dir = dir + storeDir := filepath.Join(dir, "store") + dataDir := filepath.Join(dir, "src") + indexDir := filepath.Join(dir, "index") + + require.NoError(t, os.Mkdir(storeDir, 0o750)) + require.NoError(t, os.Mkdir(indexDir, 0o750)) + writeFaultSourceTree(t, afero.NewOsFs(), dataDir) + + v, _ := openFileDestinationVaultik(ctx, t, storeDir, dataDir, + filepath.Join(indexDir, "index.sqlite")) + require.NoError(t, backUp(v, "first")) + require.NoError(t, v.DB.Close()) + + firstBackup.ready = true +} + +// backUpToFileDestination creates the directory storeDir, as a user must +// before the first backup, and returns a Vaultik whose file:// +// destination there holds a backup of the snapshot named "first". The +// store and the local index are copies of firstBackup's, which is faster +// than backing up in every test. The returned Vaultik backs up a source +// tree shared with every other caller, so no test may change that tree. +// Everything the returned Vaultik prints after the backup goes to the +// returned buffer. +func backUpToFileDestination( + ctx context.Context, t *testing.T, storeDir string, +) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer) { + t.Helper() + + firstBackup.once.Do(func() { makeFirstBackup(ctx, t) }) + require.True(t, firstBackup.ready, "another test failed to make firstBackup") + + require.NoError(t, os.MkdirAll(storeDir, 0o750)) + require.NoError(t, os.CopyFS(storeDir, + os.DirFS(filepath.Join(firstBackup.dir, "store")))) + + indexDir := t.TempDir() + require.NoError(t, os.CopyFS(indexDir, + os.DirFS(filepath.Join(firstBackup.dir, "index")))) + + v, repos := openFileDestinationVaultik(ctx, t, storeDir, + filepath.Join(firstBackup.dir, "src"), + filepath.Join(indexDir, "index.sqlite")) + + out := &bytes.Buffer{} + v.Stdout = out + v.UI = ui.NewWithColor(out, false) + + return v, repos, out +} + +// backUpThenUnplug backs up to a file:// destination, then moves the +// destination directory away, as unplugging the volume it lives on would. +func backUpThenUnplug( + ctx context.Context, t *testing.T, +) (*vaultik.Vaultik, *database.Repositories, *bytes.Buffer) { + t.Helper() + + storeDir := filepath.Join(t.TempDir(), "usbstick") + v, repos, out := backUpToFileDestination(ctx, t, storeDir) + + require.NoError(t, os.Rename(storeDir, storeDir+"-unplugged")) + + return v, repos, out +} + +// TestBackupFailsWhenDestinationDirectoryMissing checks that a backup to +// a file:// destination whose directory does not exist fails before it +// records a snapshot, and does not create the directory. +func TestBackupFailsWhenDestinationDirectoryMissing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + volume := filepath.Join(t.TempDir(), "volume") + v, repos := newFileDestinationVaultik(ctx, t, filepath.Join(volume, "backup")) + + err := backUp(v, "first") + require.ErrorIs(t, err, fs.ErrNotExist) + require.ErrorContains(t, err, "create it, or mount the volume it is on") + + _, err = os.Stat(volume) + require.ErrorIs(t, err, fs.ErrNotExist, + "the backup must not create the destination directory") + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Empty(t, snapshots) +} + +// TestListSnapshotsWarnsWhenDestinationMissing checks that snapshot list +// warns and shows the local index alone, without reporting the local +// snapshot as missing from the destination. +func TestListSnapshotsWarnsWhenDestinationMissing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out := backUpThenUnplug(ctx, t) + id := localSnapshotID(ctx, t, repos, "first") + + require.NoError(t, v.ListSnapshots(false)) + + assert.Contains(t, out.String(), "Could not list backup destination store") + assert.Contains(t, out.String(), "Showing snapshots from the local index only.") + assert.Contains(t, out.String(), id) + assert.NotContains(t, out.String(), "not found in backup destination store") +} + +// TestRemoveSnapshotWarnsWhenDestinationMissing checks that snapshot +// remove warns that the metadata could not be removed from the +// destination, instead of reporting that it was. +func TestRemoveSnapshotWarnsWhenDestinationMissing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out := backUpThenUnplug(ctx, t) + + result, err := v.RemoveSnapshot(localSnapshotID(ctx, t, repos, "first"), + &vaultik.RemoveOptions{Force: true}) + require.NoError(t, err) + + assert.False(t, result.RemoteRemoved) + assert.Contains(t, out.String(), + "Could not remove snapshot metadata from remote") + assert.NotContains(t, out.String(), + "Removed snapshot metadata from remote storage") +} + +// TestPruneKeepsLocalRecordsWhenDestinationMissing checks that prune +// fails on a destination it cannot list and deletes no local snapshot +// record. +func TestPruneKeepsLocalRecordsWhenDestinationMissing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, _ := backUpThenUnplug(ctx, t) + + err := v.Prune(&vaultik.PruneOptions{Force: true}) + require.ErrorIs(t, err, fs.ErrNotExist) + require.ErrorContains(t, err, "listing remote snapshots") + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "prune must delete no local snapshot record") +} + +// TestPurgeSaysListingFailedOnceWhenDestinationMissing checks that +// snapshot purge fails on a destination it cannot list, with an error +// that says "listing remote snapshots" once. +func TestPurgeSaysListingFailedOnceWhenDestinationMissing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, _, _ := backUpThenUnplug(ctx, t) + + err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + KeepLatest: true, + Force: true, + }) + require.ErrorIs(t, err, fs.ErrNotExist) + assert.Equal(t, 1, strings.Count(err.Error(), "listing remote snapshots"), + err.Error()) +} + +// TestNukeRemoteKeepsLocalIndexWhenDestinationMissing checks that remote +// nuke fails on a destination it cannot list, leaves the local index +// unchanged, and neither reports the destination empty nor advises +// running nuke again. +func TestNukeRemoteKeepsLocalIndexWhenDestinationMissing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + v, repos, out := backUpThenUnplug(ctx, t) + + filesBefore, err := repos.Files.ListAll(ctx) + require.NoError(t, err) + require.NotEmpty(t, filesBefore) + + blobsBefore, err := repos.Blobs.GetAll(ctx) + require.NoError(t, err) + require.NotEmpty(t, blobsBefore) + + err = v.NukeRemote(true) + require.ErrorIs(t, err, fs.ErrNotExist) + require.ErrorContains(t, err, "listing remote snapshots") + assert.NotContains(t, out.String(), "now empty") + assert.NotContains(t, out.String(), "vaultik remote nuke --force") + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "nuke must delete no local snapshot record") + + files, err := repos.Files.ListAll(ctx) + require.NoError(t, err) + assert.Len(t, files, len(filesBefore), "nuke must delete no local file record") + + blobs, err := repos.Blobs.GetAll(ctx) + require.NoError(t, err) + assert.Len(t, blobs, len(blobsBefore), "nuke must delete no local blob record") +} diff --git a/internal/vaultik/new_chunk_size_test.go b/internal/vaultik/new_chunk_size_test.go new file mode 100644 index 0000000..c9e9254 --- /dev/null +++ b/internal/vaultik/new_chunk_size_test.go @@ -0,0 +1,133 @@ +package vaultik_test + +import ( + "bytes" + "context" + "maps" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/chunker" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestNewChunkSizeOfChangedFileStaysFixed covers +// https://git.eeqj.de/sneak/vaultik/issues/311. A backup whose only change +// is a modified file lists the size of the chunks that change added as its +// NEW CHUNK SIZE, and a later backup that changes the file again leaves +// every earlier snapshot's figure as it was. The file's row in the local +// index is shared by all three snapshots and rewritten by each backup. +func TestNewChunkSizeOfChangedFileStaysFixed(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + dbPath := filepath.Join(tempDir, "index.sqlite") + changedPath := filepath.Join(dataDir, "changed.bin") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, dataDir) + cfg := changedFileConfig(dataDir, dbPath) + + appendRandomBytes(t, fs, files, changedPath, appendedFileSize) + + store, err := storage.NewFileStorer(t.TempDir()) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, "first")) + + firstFiles := maps.Clone(files) + firstID := localSnapshotID(ctx, t, repos, "first") + + appendRandomBytes(t, fs, files, changedPath, faultChunkSize) + require.NoError(t, backUp(v, "second")) + + secondID := localSnapshotID(ctx, t, repos, "second") + secondAdded := sizeOfNewChunks(t, files, firstFiles) + require.Positive(t, secondAdded) + assert.Equal(t, secondAdded, listedNewChunkSizes(t, v)[secondID], + "the second snapshot must count the chunks the change added") + + appendRandomBytes(t, fs, files, changedPath, faultChunkSize) + require.NoError(t, backUp(v, "third")) + + sizes := listedNewChunkSizes(t, v) + assert.Equal(t, sizeOfNewChunks(t, firstFiles, nil), sizes[firstID], + "a later backup must not change the first snapshot's figure") + assert.Equal(t, secondAdded, sizes[secondID], + "a later backup must not change the second snapshot's figure") +} + +// sizeOfNewChunks returns the total size of the distinct chunks of the +// files in after that no file in before has, cut the way the backup cuts +// them. +func sizeOfNewChunks(t *testing.T, after, before map[string][]byte) int64 { + t.Helper() + + known := make(map[string]bool) + for _, chunk := range chunksOf(t, before) { + known[chunk.Hash] = true + } + + var total int64 + + for _, chunk := range chunksOf(t, after) { + if !known[chunk.Hash] { + known[chunk.Hash] = true + total += chunk.Size + } + } + + return total +} + +// chunksOf returns the chunks of every file in files. +func chunksOf(t *testing.T, files map[string][]byte) []chunker.Chunk { + t.Helper() + + c := chunker.NewChunker(faultChunkSize) + + var all []chunker.Chunk + + for _, content := range files { + chunks, err := c.ChunkReader(bytes.NewReader(content)) + require.NoError(t, err) + + all = append(all, chunks...) + } + + return all +} + +// listedNewChunkSizes runs `snapshot list --json` and returns each listed +// snapshot's new_chunk_size by snapshot ID. +func listedNewChunkSizes(t *testing.T, v *vaultik.Vaultik) map[string]int64 { + t.Helper() + + var out bytes.Buffer + + v.Stdout = &out + require.NoError(t, v.ListSnapshots(true)) + + sizes := make(map[string]int64) + for _, row := range decodeListJSON(t, out.String()) { + sizes[row.ID] = row.NewChunkSize + } + + return sizes +} diff --git a/internal/vaultik/nuke_remote_test.go b/internal/vaultik/nuke_remote_test.go new file mode 100644 index 0000000..913f005 --- /dev/null +++ b/internal/vaultik/nuke_remote_test.go @@ -0,0 +1,201 @@ +package vaultik_test + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage/faultstore" +) + +// TestNukeRemoteLeavesNoFiles checks that remote nuke leaves no file +// under a file:// destination, including the `.partial` files uploads +// killed part-way leave next to a snapshot's metadata and next to where a +// blob would have been, a snapshot's database whose manifest was never +// uploaded, and a file under blobs/ whose name is not a blob hash. +func TestNukeRemoteLeavesNoFiles(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, repos, out := backUpToFileDestination(ctx, t, storeDir) + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1) + + snapshotKey := snapshot.RemoteSnapshotKey(snapshots[0].ID.String()) + hash := testBlobHashA + leftovers := []string{ + filepath.Join(storeDir, "metadata", snapshotKey, + "db.zst.age-123456.partial"), + filepath.Join(storeDir, "blobs", hash[:2], hash[2:4], + hash+"-123456.partial"), + filepath.Join(storeDir, "metadata", + snapshot.RemoteSnapshotKey("no-manifest"), "db.zst.age"), + filepath.Join(storeDir, "blobs", "0b", "01", ".DS_Store"), + } + + for _, leftover := range leftovers { + require.NoError(t, os.MkdirAll(filepath.Dir(leftover), 0o750)) + require.NoError(t, os.WriteFile(leftover, []byte("half an upload"), 0o600)) + } + + require.NoError(t, v.NukeRemote(true)) + + var files []string + + err = filepath.WalkDir(storeDir, + func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + + if !entry.IsDir() { + files = append(files, path) + } + + return nil + }) + require.NoError(t, err) + assert.Empty(t, files) + + // Nuke deletes the blobs itself, so advice to run prune is wrong. + assert.Contains(t, out.String(), "Backup destination store is now empty.") + assert.NotContains(t, out.String(), "vaultik prune") +} + +// TestNukeRemoteFailsWhenADeleteFails checks that remote nuke returns an +// error when a snapshot's metadata or a blob cannot be deleted, does not +// report the store empty, and advises running nuke again: prune deletes +// no snapshot metadata that has its manifest. +func TestNukeRemoteFailsWhenADeleteFails(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + for _, refusedPrefix := range []string{"metadata/", "blobs/"} { + t.Run(refusedPrefix, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + + store := faultstore.New(v.Storage) + store.OnDelete = func(key string) bool { + return strings.HasPrefix(key, refusedPrefix) + } + v.Storage = store + + require.Error(t, v.NukeRemote(true)) + + assert.NotContains(t, out.String(), "now empty") + assert.Contains(t, out.String(), "vaultik remote nuke --force") + assert.NotContains(t, out.String(), "vaultik prune") + }) + } +} + +// TestNukeRemoteKeepsLocalSnapshotWhoseMetadataIsNotDeleted checks that +// remote nuke keeps a snapshot in the local index while its metadata +// cannot be deleted from the destination store: dropped from the local +// index, it would be left there as a remote-only snapshot without its +// name. +func TestNukeRemoteKeepsLocalSnapshotWhoseMetadataIsNotDeleted(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + + store := faultstore.New(v.Storage) + store.OnDelete = func(key string) bool { + return strings.HasPrefix(key, "metadata/") + } + v.Storage = store + + require.Error(t, v.NukeRemote(true)) + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1) +} + +// TestNukeRemoteNamesWhatIsLeft checks that remote nuke, when an object +// it does not recognise cannot be deleted, does not report the store +// empty but names that object and fails. +func TestNukeRemoteNamesWhatIsLeft(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + + const leftKey = "blobs/0b/01/.DS_Store" + + leftPath := filepath.Join(storeDir, filepath.FromSlash(leftKey)) + require.NoError(t, os.MkdirAll(filepath.Dir(leftPath), 0o750)) + require.NoError(t, os.WriteFile(leftPath, []byte("finder"), 0o600)) + + store := faultstore.New(v.Storage) + store.OnDelete = func(key string) bool { return key == leftKey } + v.Storage = store + + require.Error(t, v.NukeRemote(true)) + + assert.Contains(t, out.String(), leftKey) + assert.NotContains(t, out.String(), "now empty") + assert.Contains(t, out.String(), "vaultik remote nuke --force") +} + +// TestNukeRemoteRefusesAnotherDestinationWithoutRetryAdvice checks that +// remote nuke, when the local index belongs to a different destination +// than the configured one, fails without advising to run nuke again: +// that run would fail the same way. +func TestNukeRemoteRefusesAnotherDestinationWithoutRetryAdvice(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + + v.Config.StorageURL = "file://" + filepath.Join(t.TempDir(), "elsewhere") + + err := v.NukeRemote(true) + + require.ErrorContains(t, err, "bound to a different backup destination") + assert.NotContains(t, out.String(), "vaultik remote nuke --force") +} + +// TestNukeRemoteFailsWhenALocalSnapshotCannotBeRemoved checks that a +// snapshot remote nuke cannot remove from the local index fails the +// run, and that nuke then does not report the destination store empty. +func TestNukeRemoteFailsWhenALocalSnapshotCannotBeRemoved(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + + _, err := v.DB.Conn().ExecContext(ctx, ` + CREATE TRIGGER refuse_snapshot_delete BEFORE DELETE ON snapshots + BEGIN SELECT RAISE(ABORT, 'simulated index error'); END`) + require.NoError(t, err) + + require.Error(t, v.NukeRemote(true)) + + assert.NotContains(t, out.String(), "now empty") + assert.Contains(t, out.String(), "vaultik remote nuke --force") +} diff --git a/internal/vaultik/prune.go b/internal/vaultik/prune.go index 38bb135..453f347 100644 --- a/internal/vaultik/prune.go +++ b/internal/vaultik/prune.go @@ -4,9 +4,13 @@ import ( "encoding/json" "errors" "fmt" + "sort" "strings" + "time" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage" ) // PruneOptions contains options for the prune command @@ -19,13 +23,39 @@ type PruneOptions struct { var errNukeRequiresForce = errors.New( "nuke requires --force (this deletes ALL remote snapshots and blobs)") +// errBlobDeleteFailed reports unreferenced blobs prune could not delete. +var errBlobDeleteFailed = errors.New("blob(s) could not be deleted") + +// errMetadataDirDeleteFailed reports directories under metadata/ with no +// manifest that prune could not delete. +var errMetadataDirDeleteFailed = errors.New( + "metadata director(ies) with no manifest could not be deleted") + +// errObjectsLeft reports objects remote nuke still finds on the backup +// destination store after deleting. +var errObjectsLeft = errors.New( + "object(s) still on the backup destination store") + +// nukeCommandHint is the command suggested when a remote nuke could not +// delete everything: running it again deletes what is left, which +// `vaultik prune` does not do for snapshot metadata that has its +// manifest. +const nukeCommandHint = "vaultik remote nuke --force" + // metadataDirName is the top-level remote directory holding snapshot // metadata. const metadataDirName = "metadata" -// NukeRemote deletes every snapshot's metadata and every blob from remote -// storage. After this returns successfully the bucket prefix is empty and -// the next backup starts from scratch. +// blobKeyParts is the "/"-separated segment count of a blob object key +// (blobs///). +const blobKeyParts = 4 + +// NukeRemote deletes every object under metadata/ and blobs/ in remote +// storage, whatever its name, along with any object an upload cut off +// part-way left under a temporary `.partial` name, and last the +// destination marker. It returns successfully only when a listing +// afterwards finds nothing left under metadata/ and blobs/, and the next +// backup then starts from scratch. // // Refuses to run unless force is true. The caller is responsible for // confirming with the user. @@ -34,6 +64,37 @@ func (v *Vaultik) NukeRemote(force bool) error { return errNukeRequiresForce } + // Checked before anything is deleted: running nuke again would fail + // the same way, so the advice below must not follow these errors. + // The listing also fails on a destination that answers that it has + // no marker while the local index holds snapshots. + err := v.checkStorageBinding() + if err != nil { + return err + } + + _, err = v.listAllRemoteSnapshotKeys() + if err != nil { + return err + } + + err = v.emptyDestinationStore() + if err != nil { + v.UI.Warningf("Run '%s' again to delete what is left on the "+ + "backup destination store.", nukeCommandHint) + + return err + } + + v.UI.Completef("Backup destination store is now empty.") + + return nil +} + +// emptyDestinationStore does the deleting for NukeRemote and stops at +// the first step that fails. It also fails when objects are still +// listed at the end, naming each one. +func (v *Vaultik) emptyDestinationStore() error { v.UI.Beginf("Removing all snapshot metadata from backup destination store.") _, err := v.RemoveAllSnapshots(&RemoveOptions{Force: true}) @@ -41,18 +102,69 @@ func (v *Vaultik) NukeRemote(force bool) error { return fmt.Errorf("removing all snapshots: %w", err) } - v.UI.Beginf("Removing any blobs still present in backup destination store.") + v.UI.Beginf("Removing everything still present in backup destination store.") - err = v.PruneBlobs(&PruneOptions{Force: true}) - if err != nil { - return fmt.Errorf("pruning blobs: %w", err) + var left []string + + for _, prefix := range []string{"metadata/", "blobs/"} { + keys, err := v.deleteEverythingUnder(prefix) + if err != nil { + return err + } + + left = append(left, keys...) } - v.UI.Completef("Backup destination store is now empty.") + for _, key := range left { + v.UI.Warningf("Still on the backup destination store: %s", key) + } + + if len(left) > 0 { + return fmt.Errorf("%d %w", len(left), errObjectsLeft) + } + + // Last, once the local snapshot records are gone: the next backup + // then has none and writes the marker again. + err = v.Storage.Delete(v.ctx, destinationMarkerKey) + if err != nil { + return fmt.Errorf("deleting %s: %w", destinationMarkerKey, err) + } return nil } +// deleteEverythingUnder deletes every object under prefix, whatever its +// name, and returns the keys a listing afterwards still finds. A delete +// that fails is logged and the others still run; that object then +// shows up in the listing afterwards. +func (v *Vaultik) deleteEverythingUnder(prefix string) ([]string, error) { + keys, err := v.Storage.List(v.ctx, prefix) + if err != nil { + return nil, fmt.Errorf("listing %s: %w", prefix, err) + } + + for _, key := range keys { + err = v.Storage.Delete(v.ctx, key) + if err != nil { + log.Error("Failed to delete object", "key", key, "error", err) + } + } + + // The file and rclone listings skip `.partial` objects, so the + // deletes above never reach them. + err = v.Storage.DeletePartialUploads(v.ctx, prefix) + if err != nil { + return nil, fmt.Errorf("deleting partial uploads: %w", err) + } + + left, err := v.Storage.List(v.ctx, prefix) + if err != nil { + return nil, fmt.Errorf("listing %s: %w", prefix, err) + } + + return left, nil +} + // PruneBlobsResult contains the result of a blob prune operation // //nolint:tagliatelle // snake_case is the established JSON output format @@ -61,16 +173,26 @@ type PruneBlobsResult struct { BlobsDeleted int `json:"blobs_deleted"` BlobsFailed int `json:"blobs_failed,omitempty"` BytesFreed int64 `json:"bytes_freed"` + // BlobsTooNew counts the unreferenced blobs kept because they are + // newer than the prune grace period, or of unknown age. BlobsFound + // does not include them. + BlobsTooNew int `json:"blobs_too_new"` + // MetadataDirsDeleted counts the directories under metadata/ with no + // manifest that prune deleted, and MetadataDirsFailed those it could + // not delete. + MetadataDirsDeleted int `json:"metadata_dirs_deleted"` + MetadataDirsFailed int `json:"metadata_dirs_failed,omitempty"` } -// Prune removes orphaned data from the local index database AND -// unreferenced blobs from the backup destination store. This is the -// single user-facing prune entry point — the split between local and -// remote cleanup is an implementation detail. Calling code should -// prefer this method over PruneDatabase or PruneBlobs individually -// unless it specifically wants one half. +// Prune removes orphaned data from the local index database AND, from the +// backup destination store, unreferenced blobs and the directories under +// metadata/ with no manifest. This is the single user-facing prune entry +// point — the split between local and remote cleanup is an +// implementation detail. Calling code should prefer this method over +// PruneDatabase or PruneBlobs individually unless it specifically wants +// one half. func (v *Vaultik) Prune(opts *PruneOptions) error { - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() if err != nil { return err } @@ -92,11 +214,17 @@ func (v *Vaultik) Prune(opts *PruneOptions) error { return v.PruneBlobs(opts) } -// PruneBlobs removes unreferenced blobs from storage +// PruneBlobs removes unreferenced blobs from storage, and each directory +// under metadata/ that a backup left with no manifest. func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { log.Info("Starting prune operation") - allBlobsReferenced, err := v.collectReferencedBlobs() + metadataObjects, err := v.listMetadataObjects() + if err != nil { + return err + } + + allBlobsReferenced, err := v.collectReferencedBlobs(metadataObjects) if err != nil { return err } @@ -106,81 +234,187 @@ func (v *Vaultik) PruneBlobs(opts *PruneOptions) error { return err } - unreferencedBlobs, totalSize := v.findUnreferencedBlobs(allBlobs, allBlobsReferenced) + unreferencedBlobs, totalSize, tooNew := v.findUnreferencedBlobs( + allBlobs, allBlobsReferenced) - result := &PruneBlobsResult{BlobsFound: len(unreferencedBlobs)} + dirsWithoutManifest, err := v.findMetadataDirsWithoutManifest(metadataObjects) + if err != nil { + return err + } - if len(unreferencedBlobs) == 0 { + result := &PruneBlobsResult{ + BlobsFound: len(unreferencedBlobs), + BlobsTooNew: tooNew, + } + + v.reportBlobsTooNew(tooNew, opts) + + if len(unreferencedBlobs) == 0 && len(dirsWithoutManifest) == 0 { log.Info("No unreferenced blobs found") if opts.JSON { return v.outputPruneBlobsJSON(result) } - v.printlnStdout("No unreferenced blobs to remove.") + v.UI.Infof("No unreferenced blobs to remove.") return nil } log.Info("Found unreferenced blobs", - "count", len(unreferencedBlobs), "total_size", ubytes(totalSize)) + "count", len(unreferencedBlobs), "total_size", ubytes(totalSize), + "metadata_dirs_without_manifest", len(dirsWithoutManifest)) - if !opts.JSON { - v.stdoutf("Found %d unreferenced blob(s) totaling %s\n", - len(unreferencedBlobs), ubytes(totalSize)) - } - - if !opts.Force && !opts.JSON { - v.stdoutf("\nDelete %d unreferenced blob(s)? [y/N] ", len(unreferencedBlobs)) - - var confirm string - - _, err = v.scanStdin(&confirm) - if err != nil { - v.printlnStdout("Cancelled") - - return nil //nolint:nilerr // read failure means no confirmation - } - - if strings.ToLower(confirm) != "y" { - v.printlnStdout("Cancelled") - - return nil - } + if !v.confirmPrune(opts, len(unreferencedBlobs), totalSize, + dirsWithoutManifest) { + return ErrNotConfirmed } v.deleteUnreferencedBlobs(unreferencedBlobs, allBlobs, result) + v.deleteMetadataDirs(dirsWithoutManifest, result) if opts.JSON { - return v.outputPruneBlobsJSON(result) + err = v.outputPruneBlobsJSON(result) + if err != nil { + return err + } + } else { + v.reportPruneDeletions(result, len(dirsWithoutManifest)) } - v.stdoutf("\nDeleted %d blob(s) totaling %s\n", - result.BlobsDeleted, ubytes(result.BytesFreed)) + var failures []error if result.BlobsFailed > 0 { - v.stdoutf("Failed to delete %d blob(s)\n", result.BlobsFailed) + failures = append(failures, + fmt.Errorf("%d %w", result.BlobsFailed, errBlobDeleteFailed)) } - return nil + if result.MetadataDirsFailed > 0 { + failures = append(failures, fmt.Errorf("%d %w", + result.MetadataDirsFailed, errMetadataDirDeleteFailed)) + } + + return errors.Join(failures...) } -// collectReferencedBlobs downloads all manifests and returns the set of -// referenced blob hashes. +// confirmPrune states what prune found to delete, unreferenced blobs and +// directories under metadata/ with no manifest, naming each directory by +// its remote key, and, unless --force is given, asks the operator to +// confirm. Under --json it prints nothing and does not ask. It reports +// whether to go ahead. +func (v *Vaultik) confirmPrune( + opts *PruneOptions, blobCount int, blobsSize int64, dirs []string, +) bool { + if opts.JSON { + return true + } + + dirCount := len(dirs) + blobsFound := fmt.Sprintf("Found %d unreferenced blob(s) totaling %s.", + blobCount, ubytes(blobsSize)) + dirsFound := fmt.Sprintf("Found %d metadata director(ies) left by "+ + "backups that stopped before their manifest:", dirCount) + + if opts.Force { + if blobCount > 0 { + v.UI.Infof("%s", blobsFound) + } + + if dirCount > 0 { + v.UI.Infof("%s", dirsFound) + + for _, remoteKey := range dirs { + v.UI.Detailf("metadata/%s/", remoteKey) + } + } + + return true + } + + // The counts, the names, the prompt and its answer bypass the UI: + // they are an interactive exchange the operator must see, so --quiet + // does not silence them. + if blobCount > 0 { + v.stdoutf("%s\n", blobsFound) + } + + if dirCount > 0 { + v.stdoutf("%s\n", dirsFound) + + for _, remoteKey := range dirs { + v.stdoutf(" metadata/%s/\n", remoteKey) + } + } + + switch { + case dirCount == 0: + v.stdoutf("\nDelete %d unreferenced blob(s)? [y/N] ", blobCount) + case blobCount == 0: + v.stdoutf("\nDelete %d metadata director(ies)? [y/N] ", dirCount) + default: + v.stdoutf("\nDelete %d unreferenced blob(s) and %d metadata "+ + "director(ies)? [y/N] ", blobCount, dirCount) + } + + var confirm string + + // A failure to read the answer means no confirmation. + _, err := v.scanStdin(&confirm) + if err != nil || strings.ToLower(confirm) != "y" { + v.printlnStdout("Cancelled") + + return false + } + + return true +} + +// reportPruneDeletions says how many blobs and metadata directories +// prune deleted, naming each kind only when it found some to delete. +func (v *Vaultik) reportPruneDeletions(result *PruneBlobsResult, dirCount int) { + if result.BlobsFound > 0 { + v.UI.Infof("Deleted %d blob(s) totaling %s.", + result.BlobsDeleted, ubytes(result.BytesFreed)) + } + + if dirCount > 0 { + v.UI.Infof("Deleted %d metadata director(ies) with no manifest.", + result.MetadataDirsDeleted) + } +} + +// listMetadataObjects lists every object under metadata/ on the +// destination store. +func (v *Vaultik) listMetadataObjects() ([]storage.ObjectInfo, error) { + log.Info("Listing remote snapshots") + + var objects []storage.ObjectInfo + + for object := range v.Storage.ListStream(v.ctx, "metadata/") { + if object.Err != nil { + return nil, fmt.Errorf("listing metadata objects: %w", object.Err) + } + + objects = append(objects, object) + } + + return objects, nil +} + +// collectReferencedBlobs downloads every manifest among the listed +// metadata objects and returns the set of referenced blob hashes. // // Every manifest must be read successfully. A manifest that cannot be // downloaded or decoded means its snapshot's blobs are unknown, so // treating them as unreferenced would let prune delete data a snapshot // still needs. Rather than risk that silent loss, any failure returns an // error naming the remote key and prune deletes nothing. -func (v *Vaultik) collectReferencedBlobs() (map[string]bool, error) { - log.Info("Listing remote snapshots") - // IDs returned by listUniqueSnapshotIDs are remote keys (hashed +func (v *Vaultik) collectReferencedBlobs( + metadataObjects []storage.ObjectInfo, +) (map[string]bool, error) { + // IDs returned by uniqueSnapshotIDs are remote keys (hashed // subdirectories under metadata/), not human snapshot IDs. - remoteKeys, err := v.listUniqueSnapshotIDs() - if err != nil { - return nil, fmt.Errorf("listing snapshot keys: %w", err) - } + remoteKeys := uniqueSnapshotIDs(metadataObjects) log.Info("Found manifests in remote storage", "count", len(remoteKeys)) @@ -205,18 +439,14 @@ func (v *Vaultik) collectReferencedBlobs() (map[string]bool, error) { return allBlobsReferenced, nil } -// listUniqueSnapshotIDs returns deduplicated snapshot IDs from remote metadata -func (v *Vaultik) listUniqueSnapshotIDs() ([]string, error) { - objectCh := v.Storage.ListStream(v.ctx, "metadata/") +// uniqueSnapshotIDs returns deduplicated snapshot IDs from the listed +// metadata objects. +func uniqueSnapshotIDs(metadataObjects []storage.ObjectInfo) []string { seen := make(map[string]bool) var snapshotIDs []string - for object := range objectCh { - if object.Err != nil { - return nil, fmt.Errorf("listing metadata objects: %w", object.Err) - } - + for _, object := range metadataObjects { parts := strings.Split(object.Key, "/") if len(parts) >= minSnapshotIDParts && parts[0] == metadataDirName && parts[1] != "" { @@ -231,14 +461,15 @@ func (v *Vaultik) listUniqueSnapshotIDs() ([]string, error) { } } - return snapshotIDs, nil + return snapshotIDs } -// listAllRemoteBlobs returns a map of all blob hashes to their sizes in remote storage -func (v *Vaultik) listAllRemoteBlobs() (map[string]int64, error) { +// listAllRemoteBlobs returns a map of all blob hashes in remote storage +// to their listing entries. +func (v *Vaultik) listAllRemoteBlobs() (map[string]storage.ObjectInfo, error) { log.Info("Listing all blobs in storage") - allBlobs := make(map[string]int64) + allBlobs := make(map[string]storage.ObjectInfo) blobObjectCh := v.Storage.ListStream(v.ctx, "blobs/") for object := range blobObjectCh { @@ -262,7 +493,7 @@ func (v *Vaultik) listAllRemoteBlobs() (map[string]int64, error) { continue } - allBlobs[parts[3]] = object.Size + allBlobs[parts[3]] = object } log.Info("Found blobs in storage", "count", len(allBlobs)) @@ -270,30 +501,135 @@ func (v *Vaultik) listAllRemoteBlobs() (map[string]int64, error) { return allBlobs, nil } -// findUnreferencedBlobs returns blob hashes not referenced by any -// manifest and their total size. +// findUnreferencedBlobs returns the hashes of the blobs no manifest +// references that are older than the prune grace period, and their total +// size. It also returns how many unreferenced blobs it left out for +// being newer than that, or of unknown age because the listing gave no +// time for them. func (v *Vaultik) findUnreferencedBlobs( - allBlobs map[string]int64, referenced map[string]bool, -) ([]string, int64) { + allBlobs map[string]storage.ObjectInfo, referenced map[string]bool, +) ([]string, int64, int) { var ( unreferenced []string totalSize int64 + tooNew int ) - for hash, size := range allBlobs { - if !referenced[hash] { - unreferenced = append(unreferenced, hash) - totalSize += size + cutoff := time.Now().UTC().Add(-v.Config.PruneGracePeriod) + + for hash, blob := range allBlobs { + if referenced[hash] { + continue + } + + if blob.ModTime.IsZero() || blob.ModTime.After(cutoff) { + tooNew++ + + continue + } + + unreferenced = append(unreferenced, hash) + totalSize += blob.Size + } + + return unreferenced, totalSize, tooNew +} + +// findMetadataDirsWithoutManifest returns the remote key of each +// directory under metadata/ that has no manifest.json.zst, such as one a +// backup leaves when its manifest upload fails after db.zst.age was +// uploaded. It leaves out a directory a local snapshot record claims, +// and one holding an object newer than the prune grace period, or of +// unknown age because the listing gave no time for it: a backup still +// running may be writing there. A name that is not a remote key is +// never returned. +func (v *Vaultik) findMetadataDirsWithoutManifest( + metadataObjects []storage.ObjectInfo, +) ([]string, error) { + localIDs, err := v.localSnapshotIDs() + if err != nil { + return nil, fmt.Errorf("listing local snapshots: %w", err) + } + + keep := make(map[string]bool, len(localIDs)) + for _, id := range localIDs { + keep[snapshot.RemoteSnapshotKey(id)] = true + } + + cutoff := time.Now().UTC().Add(-v.Config.PruneGracePeriod) + listed := make(map[string]bool) + + for _, object := range metadataObjects { + parts := strings.Split(object.Key, "/") + if len(parts) < metadataKeyParts || !isBlobHash(parts[1]) { + continue + } + + remoteKey := parts[1] + listed[remoteKey] = true + + if parts[2] == "manifest.json.zst" || + object.ModTime.IsZero() || object.ModTime.After(cutoff) { + keep[remoteKey] = true } } - return unreferenced, totalSize + var remoteKeys []string + + for remoteKey := range listed { + if !keep[remoteKey] { + remoteKeys = append(remoteKeys, remoteKey) + } + } + + sort.Strings(remoteKeys) + + return remoteKeys, nil +} + +// deleteMetadataDirs deletes everything in the given directories under +// metadata/ and counts in the result the directories deleted and those +// it could not delete. +func (v *Vaultik) deleteMetadataDirs( + remoteKeys []string, result *PruneBlobsResult, +) { + for _, remoteKey := range remoteKeys { + _, err := v.deleteRemoteSnapshotByKey(remoteKey) + if err != nil { + log.Error("Failed to delete metadata directory with no manifest", + "remote_key", remoteKey, "error", err) + + result.MetadataDirsFailed++ + + continue + } + + log.Info("Deleted metadata directory with no manifest", + "remote_key", remoteKey) + + result.MetadataDirsDeleted++ + } +} + +// reportBlobsTooNew says how many unreferenced blobs prune kept for being +// newer than the grace period or of unknown age. Under --json the +// document carries the count instead. +func (v *Vaultik) reportBlobsTooNew(tooNew int, opts *PruneOptions) { + if tooNew == 0 || opts.JSON { + return + } + + v.UI.Infof("Kept %d unreferenced blob(s) newer than "+ + "prune_grace_period (%s), or of unknown age: a backup still "+ + "running may need them.", + tooNew, v.Config.PruneGracePeriod) } // deleteUnreferencedBlobs deletes the given blobs from storage and // populates the result. func (v *Vaultik) deleteUnreferencedBlobs( - unreferencedBlobs []string, allBlobs map[string]int64, result *PruneBlobsResult, + unreferencedBlobs []string, allBlobs map[string]storage.ObjectInfo, + result *PruneBlobsResult, ) { log.Info("Deleting unreferenced blobs") @@ -308,7 +644,7 @@ func (v *Vaultik) deleteUnreferencedBlobs( } result.BlobsDeleted++ - result.BytesFreed += allBlobs[hash] + result.BytesFreed += allBlobs[hash].Size if (i+1)%progressLogEvery == 0 || i == len(unreferencedBlobs)-1 { log.Info("Deletion progress", diff --git a/internal/vaultik/prune_count_test.go b/internal/vaultik/prune_count_test.go index fbc3e5d..2009e01 100644 --- a/internal/vaultik/prune_count_test.go +++ b/internal/vaultik/prune_count_test.go @@ -1,23 +1,26 @@ package vaultik //nolint:testpackage // exercises unexported count helpers import ( + "bytes" "context" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/ui" ) // TestTableCountForReportSurfacesReadFailure is the regression guard for // the discarded-error bug: getTableCount for a table its query cannot // resolve must not silently become 0. A count that could not be read is // reported as unknown, which a reader can tell apart from an empty table. -// -//nolint:paralleltest // installs the global logger via log.Initialize func TestTableCountForReportSurfacesReadFailure(t *testing.T) { log.Initialize(log.Config{}) + t.Parallel() ctx := context.Background() @@ -43,7 +46,7 @@ func TestTableCountForReportSurfacesReadFailure(t *testing.T) { assert.Nil(t, missing, "a failed read is unknown, not a count") // The rendered count for a failed read must say unknown, never 0. - assert.Equal(t, countUnknown, countText(missing)) + assert.Equal(t, unknownText, countText(missing)) assert.NotEqual(t, "0", countText(missing)) } @@ -58,7 +61,7 @@ func TestCountTextDistinguishesEmptyFromUnknown(t *testing.T) { assert.Equal(t, "0", countText(&zero)) assert.Equal(t, "7", countText(&seven)) - assert.Equal(t, countUnknown, countText(nil)) + assert.Equal(t, unknownText, countText(nil)) } // TestCountDiffUnknownWhenEitherSideUnknown checks that a delta computed @@ -77,3 +80,59 @@ func TestCountDiffUnknownWhenEitherSideUnknown(t *testing.T) { assert.Nil(t, countDiff(&before, nil), "unknown after yields unknown delta") assert.Nil(t, countDiff(nil, nil)) } + +// TestPruneDatabaseSummaryLabelsTotals removes the only incomplete +// snapshot from an index that also holds a complete one. The figure in +// brackets is every snapshot left in the local index, so the line must +// say so rather than read as incomplete snapshots that remain. +func TestPruneDatabaseSummaryLabelsTotals(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + + db, err := database.New(ctx, ":memory:") + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + + startedAt := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + completedAt := startedAt.Add(time.Minute) + + require.NoError(t, repos.Snapshots.Create(ctx, nil, &database.Snapshot{ + ID: "host_complete_2026-01-02T03:04:05Z", + Hostname: "host", + StartedAt: startedAt, + CompletedAt: &completedAt, + })) + require.NoError(t, repos.Snapshots.Create(ctx, nil, &database.Snapshot{ + ID: "host_incomplete_2026-01-02T03:04:05Z", + Hostname: "host", + StartedAt: startedAt, + })) + + var out bytes.Buffer + + v := &Vaultik{ + DB: db, + Repositories: repos, + SnapshotManager: snapshot.NewSnapshotManager( + snapshot.SnapshotManagerParams{Repos: repos}), + UI: ui.NewWithColor(&out, false), + } + v.SetContext(ctx) + + result, err := v.PruneDatabase() + require.NoError(t, err) + require.Equal(t, int64(1), result.SnapshotsDeleted) + + assert.Contains(t, out.String(), "Incomplete snapshots: 1 removed "+ + "(total snapshots left in the local index: 1).") + assert.Contains(t, out.String(), "Orphaned files: 0 removed "+ + "(total files left in the local index: 0).") + assert.Contains(t, out.String(), "Orphaned chunks: 0 removed "+ + "(total chunks left in the local index: 0).") + assert.Contains(t, out.String(), "Orphaned blobs: 0 removed "+ + "(total blobs left in the local index: 0).") +} diff --git a/internal/vaultik/prune_delete_failure_test.go b/internal/vaultik/prune_delete_failure_test.go new file mode 100644 index 0000000..54fe788 --- /dev/null +++ b/internal/vaultik/prune_delete_failure_test.go @@ -0,0 +1,98 @@ +package vaultik_test + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// refuseBlobDeletes is an OnDelete hook that fails every blob delete. +func refuseBlobDeletes(key string) bool { + return strings.HasPrefix(key, "blobs/") +} + +// TestPruneBlobs_FailedDeleteReturnsError checks that prune returns an +// error, so the command exits non-zero, when an unreferenced blob cannot +// be deleted. +func TestPruneBlobs_FailedDeleteReturnsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + // The store holds no manifest, so nothing references this blob. + addBlob(t, env.store.testStorer, testBlobHashA) + + store := faultstore.New(env.store) + store.OnDelete = refuseBlobDeletes + env.v.Storage = store + + err := env.v.PruneBlobs(&vaultik.PruneOptions{Force: true}) + + require.ErrorContains(t, err, "1 blob(s) could not be deleted") +} + +// TestPruneBlobs_JSONFailedDeleteReturnsError checks that prune --json +// prints its document and then returns an error when an unreferenced +// blob cannot be deleted. +func TestPruneBlobs_JSONFailedDeleteReturnsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + addBlob(t, env.store.testStorer, testBlobHashA) + + store := faultstore.New(env.store) + store.OnDelete = refuseBlobDeletes + env.v.Storage = store + + err := env.v.PruneBlobs(&vaultik.PruneOptions{JSON: true}) + + require.Error(t, err, "prune must fail when a blob cannot be deleted") + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &result), + "stdout must hold the JSON document, got:\n%s", env.stdout.String()) + assert.Equal(t, 1, result.BlobsFailed) + assert.Equal(t, 0, result.BlobsDeleted) +} + +// TestCreateSnapshotPrune_FailedBlobDeleteReturnsError checks that the +// prune step of snapshot create --prune fails the run when an +// unreferenced blob cannot be deleted. +func TestCreateSnapshotPrune_FailedBlobDeleteReturnsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, _ := backUpToFileDestination(ctx, t, storeDir) + + // No snapshot references this blob, so the prune step deletes it. + orphan := filepath.Join(storeDir, "blobs", testBlobHashA[:2], + testBlobHashA[2:4], testBlobHashA) + require.NoError(t, os.MkdirAll(filepath.Dir(orphan), 0o750)) + require.NoError(t, os.WriteFile(orphan, []byte("orphan"), 0o600)) + + store := faultstore.New(v.Storage) + store.OnDelete = refuseBlobDeletes + v.Storage = store + + err := v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Cron: true, + Prune: true, + }) + + require.ErrorContains(t, err, "1 blob(s) could not be deleted") + assert.FileExists(t, orphan) +} diff --git a/internal/vaultik/prune_grace_period_test.go b/internal/vaultik/prune_grace_period_test.go new file mode 100644 index 0000000..d31d354 --- /dev/null +++ b/internal/vaultik/prune_grace_period_test.go @@ -0,0 +1,168 @@ +package vaultik_test + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestPruneDuringBackupKeepsItsBlobs runs a prune from another host +// sharing the destination store at the moment a backup has uploaded its +// blobs and its db.zst.age but not yet its manifest, so no manifest lists +// those blobs. The prune must leave the blobs and the db.zst.age, and the +// backup must then restore. +func TestPruneDuringBackupKeepsItsBlobs(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := t.TempDir() + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + cfg := faultTestConfig() + testFiles := writeFaultSourceTree(t, fs, dataDir) + + inner, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + otherHostCfg := faultTestConfig() + otherHostCfg.PruneGracePeriod = time.Hour + otherHost := newReaderVaultik(ctx, otherHostCfg, inner, nil, fs) + + var ( + pruned bool + pruneErr error + ) + + store := faultstore.New(inner) + store.OnPut = func(key string) faultstore.PutAction { + if strings.HasSuffix(key, "/manifest.json.zst") { + pruned = true + pruneErr = otherHost.PruneBlobs(&vaultik.PruneOptions{Force: true}) + } + + return faultstore.PutNormal + } + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + + id := fullFaultBackup(ctx, t, fs, store, cfg, repos, dataDir, dbPath, "shared") + require.NoError(t, db.Close()) + + require.True(t, pruned, "the prune must run before the manifest upload") + require.NoError(t, pruneErr) + + v := newReaderVaultik(ctx, cfg, inner, nil, fs) + require.NoError(t, v.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Verify: true, + }), "a prune during the backup must not delete the backup's blobs "+ + "or its db.zst.age") + + assertRestoredTree(t, fs, restoreDir, testFiles) +} + +// TestPruneKeepsUnreferencedBlobWithNoTime checks that a blob no +// manifest lists, whose listing gives no modification time (as an S3 +// listing entry without LastModified does), is kept and counted with +// the blobs too new to delete: its age is unknown. +func TestPruneKeepsUnreferencedBlobWithNoTime(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + // Written into the mock store's map directly rather than through + // Put, so its listing gives no time. + blobKey := "blobs/" + testBlobHashA[:2] + "/" + testBlobHashA[2:4] + + "/" + testBlobHashA + env.store.data[blobKey] = []byte("blob") + + require.NoError(t, env.v.PruneBlobs(&vaultik.PruneOptions{JSON: true})) + + assert.True(t, env.store.hasKey(blobKey), + "a blob of unknown age must be kept") + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &result)) + assert.Equal(t, 0, result.BlobsDeleted) + assert.Equal(t, 1, result.BlobsTooNew) +} + +// TestPruneDeletesUnreferencedBlobOlderThanGracePeriod checks that the +// grace period only delays deletion: a blob no manifest lists is deleted +// once it is older than the grace period, and kept and counted until +// then. +func TestPruneDeletesUnreferencedBlobOlderThanGracePeriod(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + oldKey := "blobs/" + testBlobHashA[:2] + "/" + testBlobHashA[2:4] + + "/" + testBlobHashA + newKey := "blobs/" + testBlobHashB[:2] + "/" + testBlobHashB[2:4] + + "/" + testBlobHashB + + for _, key := range []string{oldKey, newKey} { + require.NoError(t, store.Put(ctx, key, strings.NewReader("blob"))) + } + + gracePeriod := time.Hour + beforeGracePeriod := time.Now().Add(-gracePeriod - time.Minute) + require.NoError(t, os.Chtimes(filepath.Join(storeDir, oldKey), + beforeGracePeriod, beforeGracePeriod)) + + stdout := &bytes.Buffer{} + v := &vaultik.Vaultik{ + Config: &config.Config{PruneGracePeriod: gracePeriod}, + Storage: store, + Stdout: stdout, + UI: ui.NewWithColor(stdout, false), + } + v.SetContext(ctx) + + require.NoError(t, v.PruneBlobs(&vaultik.PruneOptions{JSON: true})) + + _, err = store.Stat(ctx, oldKey) + require.ErrorIs(t, err, storage.ErrNotFound, + "a blob older than the grace period must be deleted") + + _, err = store.Stat(ctx, newKey) + require.NoError(t, err, "a blob newer than the grace period must be kept") + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(stdout.Bytes(), &result)) + assert.Equal(t, 1, result.BlobsDeleted) + assert.Equal(t, 1, result.BlobsTooNew) +} diff --git a/internal/vaultik/prune_json_test.go b/internal/vaultik/prune_json_test.go new file mode 100644 index 0000000..96f6d01 --- /dev/null +++ b/internal/vaultik/prune_json_test.go @@ -0,0 +1,40 @@ +package vaultik_test + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestPruneBlobs_JSONDeletesWithoutAsking checks that prune with --json +// and without --force deletes an unreferenced blob without the +// confirmation prompt. Stdin is empty, so a prompt would read no answer +// and cancel, and its text would come before the JSON document. +func TestPruneBlobs_JSONDeletesWithoutAsking(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + // The store holds no manifest, so nothing references this blob. + addBlob(t, env.store.testStorer, testBlobHashA) + + err := env.v.PruneBlobs(&vaultik.PruneOptions{JSON: true}) + require.NoError(t, err) + + blobKey := "blobs/" + testBlobHashA[:2] + "/" + testBlobHashA[2:4] + + "/" + testBlobHashA + assert.False(t, env.store.hasKey(blobKey), + "the unreferenced blob must be deleted") + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &result), + "stdout must hold only the JSON document, got:\n%s", + env.stdout.String()) + assert.Equal(t, 1, result.BlobsDeleted) +} diff --git a/internal/vaultik/prune_metadata_dir_test.go b/internal/vaultik/prune_metadata_dir_test.go new file mode 100644 index 0000000..d21988d --- /dev/null +++ b/internal/vaultik/prune_metadata_dir_test.go @@ -0,0 +1,226 @@ +package vaultik_test + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// metadataObjectKey returns the key of the named file in the metadata +// directory of the snapshot with the given human ID. +func metadataObjectKey(snapshotID, name string) string { + return "metadata/" + snapshot.RemoteSnapshotKey(snapshotID) + "/" + name +} + +// TestPruneDeletesMetadataDirWithoutManifestOlderThanGracePeriod checks +// that prune deletes a directory under metadata/ holding only +// db.zst.age, as a backup leaves when its manifest upload fails, once it +// is older than the grace period, and keeps one newer than that. A +// directory with a manifest is never deleted, however old. +func TestPruneDeletesMetadataDirWithoutManifestOlderThanGracePeriod( + t *testing.T, +) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + const ( + oldID = "testhost_home_2026-01-01T00:00:00Z" + newID = "testhost_home_2026-01-02T00:00:00Z" + completeID = "testhost_home_2026-01-03T00:00:00Z" + ) + + oldDB := metadataObjectKey(oldID, "db.zst.age") + newDB := metadataObjectKey(newID, "db.zst.age") + completeDB := metadataObjectKey(completeID, "db.zst.age") + completeManifest := metadataObjectKey(completeID, "manifest.json.zst") + + manifest, err := snapshot.EncodeManifest(&snapshot.Manifest{ + SnapshotID: snapshot.RemoteSnapshotKey(completeID), + }, 3) + require.NoError(t, err) + + for _, key := range []string{oldDB, newDB, completeDB} { + require.NoError(t, store.Put(ctx, key, strings.NewReader("db"))) + } + + require.NoError(t, store.Put(ctx, completeManifest, + bytes.NewReader(manifest))) + + gracePeriod := time.Hour + beforeGracePeriod := time.Now().Add(-gracePeriod - time.Minute) + + for _, key := range []string{oldDB, completeDB, completeManifest} { + require.NoError(t, os.Chtimes(filepath.Join(storeDir, key), + beforeGracePeriod, beforeGracePeriod)) + } + + stdout := &bytes.Buffer{} + v := &vaultik.Vaultik{ + Config: &config.Config{PruneGracePeriod: gracePeriod}, + Storage: store, + Stdout: stdout, + UI: ui.NewWithColor(stdout, false), + } + v.SetContext(ctx) + + require.NoError(t, v.PruneBlobs(&vaultik.PruneOptions{JSON: true})) + + _, err = store.Stat(ctx, oldDB) + require.ErrorIs(t, err, storage.ErrNotFound, + "a directory with no manifest older than the grace period "+ + "must be deleted") + + for _, key := range []string{newDB, completeDB, completeManifest} { + _, err = store.Stat(ctx, key) + require.NoError(t, err, "%s must be kept", key) + } + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(stdout.Bytes(), &result)) + assert.Equal(t, 1, result.MetadataDirsDeleted) +} + +// TestPruneKeepsMetadataDirClaimedUnknownAgeOrNotRemoteKey checks that +// prune --force keeps a directory under metadata/ with no manifest when a +// local snapshot record claims it, when the listing gives no time for an +// object in it, or when its name is not a remote key. A fourth such +// directory is named, deleted and reported, although there are no +// unreferenced blobs to delete. +func TestPruneKeepsMetadataDirClaimedUnknownAgeOrNotRemoteKey(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + env := newListEnv(t) + + const ( + claimedID = "testhost_home_2026-01-01T00:00:00Z" + leftID = "testhost_home_2026-01-03T00:00:00Z" + ) + + env.addLocal(t, claimedID, time.Now().Add(-time.Hour)) + + claimedDB := metadataObjectKey(claimedID, "db.zst.age") + unknownAgeDB := metadataObjectKey("testhost_home_2026-01-02T00:00:00Z", + "db.zst.age") + leftDB := metadataObjectKey(leftID, "db.zst.age") + notRemoteKeyDB := "metadata/not-a-remote-key/db.zst.age" + + for _, key := range []string{claimedDB, leftDB, notRemoteKeyDB} { + require.NoError(t, env.store.Put(ctx, key, strings.NewReader("db"))) + } + + // Written into the mock store's map directly rather than through + // Put, so its listing gives no time. + env.store.data[unknownAgeDB] = []byte("db") + + require.NoError(t, env.v.PruneBlobs(&vaultik.PruneOptions{Force: true})) + + assert.True(t, env.store.hasKey(claimedDB), + "a directory a local snapshot record claims must be kept") + assert.True(t, env.store.hasKey(unknownAgeDB), + "a directory holding an object of unknown age must be kept") + assert.True(t, env.store.hasKey(notRemoteKeyDB), + "a directory whose name is not a remote key must be kept") + assert.False(t, env.store.hasKey(leftDB), + "a directory with no manifest, unclaimed and old, must be deleted") + + output := env.stdout.String() + + assert.Contains(t, output, "Found 1 metadata director(ies) left by "+ + "backups that stopped before their manifest:") + assert.Contains(t, output, + "metadata/"+snapshot.RemoteSnapshotKey(leftID)+"/") + assert.NotContains(t, output, "not-a-remote-key") + assert.Contains(t, output, + "Deleted 1 metadata director(ies) with no manifest.") + assert.NotContains(t, output, "No unreferenced blobs to remove.") +} + +// TestPruneDeclinedKeepsMetadataDirWithoutManifest checks that the prompt +// names a directory under metadata/ with no manifest that prune is about +// to delete, and that answering no keeps it. +func TestPruneDeclinedKeepsMetadataDirWithoutManifest(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + const leftID = "testhost_home_2026-01-01T00:00:00Z" + + leftDB := metadataObjectKey(leftID, "db.zst.age") + require.NoError(t, env.store.Put(context.Background(), leftDB, + strings.NewReader("db"))) + + env.v.Stdin = strings.NewReader("n\n") + + require.ErrorIs(t, env.v.PruneBlobs(&vaultik.PruneOptions{}), + vaultik.ErrNotConfirmed) + + assert.True(t, env.store.hasKey(leftDB), + "a declined prune must keep the directory") + + output := env.stdout.String() + + assert.Contains(t, output, + " metadata/"+snapshot.RemoteSnapshotKey(leftID)+"/\n") + assert.Contains(t, output, "Delete 1 metadata director(ies)? [y/N] ") + assert.Contains(t, output, "Cancelled") + assert.NotContains(t, output, "Deleted") +} + +// TestPruneFailedMetadataDirDeleteReturnsError checks that prune --json +// counts a directory under metadata/ with no manifest that it cannot +// delete, and then returns an error, so the command exits non-zero. +func TestPruneFailedMetadataDirDeleteReturnsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + leftDB := metadataObjectKey("testhost_home_2026-01-01T00:00:00Z", + "db.zst.age") + require.NoError(t, env.store.Put(context.Background(), leftDB, + strings.NewReader("db"))) + + store := faultstore.New(env.store) + store.OnDelete = func(key string) bool { + return strings.HasPrefix(key, "metadata/") + } + env.v.Storage = store + + err := env.v.PruneBlobs(&vaultik.PruneOptions{JSON: true}) + + require.ErrorContains(t, err, + "1 metadata director(ies) with no manifest could not be deleted") + assert.True(t, env.store.hasKey(leftDB)) + + var result vaultik.PruneBlobsResult + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &result), + "stdout must hold the JSON document, got:\n%s", env.stdout.String()) + assert.Equal(t, 1, result.MetadataDirsFailed) + assert.Equal(t, 0, result.MetadataDirsDeleted) +} diff --git a/internal/vaultik/purge_local_remote_consistency_test.go b/internal/vaultik/purge_local_remote_consistency_test.go index bf52b45..72dd91c 100644 --- a/internal/vaultik/purge_local_remote_consistency_test.go +++ b/internal/vaultik/purge_local_remote_consistency_test.go @@ -14,6 +14,7 @@ import ( "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/types" + "sneak.berlin/go/vaultik/internal/ui" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -34,6 +35,9 @@ func setupConsistencyTest( repos := database.NewRepositories(db) mockStorage := NewMockStorer() + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, mockStorage.Put(ctx, markerFile, strings.NewReader(""))) + for _, id := range snapshotIDs { parts := strings.Split(id, "_") startedAt, err := time.Parse(time.RFC3339, parts[len(parts)-1]) @@ -42,7 +46,7 @@ func setupConsistencyTest( completedAt := startedAt.Add(5 * time.Minute) snap := &database.Snapshot{ ID: types.SnapshotID(id), - Hostname: testHostname, + Hostname: snapHostname, VaultikVersion: testLabel, StartedAt: startedAt, CompletedAt: &completedAt, @@ -58,13 +62,16 @@ func setupConsistencyTest( require.NoError(t, err) } + stdout := &bytes.Buffer{} + v := &vaultik.Vaultik{ Storage: mockStorage, Repositories: repos, DB: db, - Stdout: &bytes.Buffer{}, + Stdout: stdout, Stderr: &bytes.Buffer{}, Stdin: &bytes.Buffer{}, + UI: ui.NewWithColor(stdout, false), } v.SetContext(ctx) diff --git a/internal/vaultik/purge_per_name_test.go b/internal/vaultik/purge_per_name_test.go index cfc343b..58c8af1 100644 --- a/internal/vaultik/purge_per_name_test.go +++ b/internal/vaultik/purge_per_name_test.go @@ -14,11 +14,14 @@ import ( "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/types" + "sneak.berlin/go/vaultik/internal/ui" "sneak.berlin/go/vaultik/internal/vaultik" ) -// Snapshot IDs reused across the purge tests. +// Snapshot IDs reused across the purge tests, and the hostname they were +// taken on. const ( + snapHostname = "testhost" snapSystemT0 = "testhost_system_2026-01-01T00:00:00Z" snapHomeT0 = "testhost_home_2026-01-01T00:00:00Z" snapHomeT1 = "testhost_home_2026-01-01T01:00:00Z" @@ -26,9 +29,12 @@ const ( ) // setupPurgeTest creates a Vaultik instance with an in-memory database and mock -// storage pre-populated with the given snapshot IDs. Each snapshot is marked as -// completed. Remote metadata stubs are created so syncWithRemote keeps them. -func setupPurgeTest(t *testing.T, snapshotIDs []string) *vaultik.Vaultik { +// storage pre-populated with the given snapshot IDs, all taken on hostname. +// Each snapshot is marked as completed. Remote metadata stubs are created so +// syncWithRemote keeps them. +func setupPurgeTest( + t *testing.T, hostname string, snapshotIDs []string, +) *vaultik.Vaultik { t.Helper() ctx := context.Background() @@ -39,6 +45,9 @@ func setupPurgeTest(t *testing.T, snapshotIDs []string) *vaultik.Vaultik { repos := database.NewRepositories(db) mockStorage := NewMockStorer() + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, mockStorage.Put(ctx, markerFile, strings.NewReader(""))) + // Insert each snapshot into the DB and create remote metadata stubs. // Use timestamps parsed from snapshot IDs for realistic ordering. for _, id := range snapshotIDs { @@ -51,7 +60,7 @@ func setupPurgeTest(t *testing.T, snapshotIDs []string) *vaultik.Vaultik { completedAt := startedAt.Add(5 * time.Minute) snap := &database.Snapshot{ ID: types.SnapshotID(id), - Hostname: "testhost", + Hostname: types.Hostname(hostname), VaultikVersion: testLabel, StartedAt: startedAt, CompletedAt: &completedAt, @@ -81,6 +90,7 @@ func setupPurgeTest(t *testing.T, snapshotIDs []string) *vaultik.Vaultik { Stdout: stdout, Stderr: stderr, Stdin: stdin, + UI: ui.NewWithColor(stdout, false), } v.SetContext(ctx) @@ -120,7 +130,7 @@ func TestPurgeKeepLatest_PerName(t *testing.T) { "testhost_system_2026-01-01T04:00:00Z", } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -148,7 +158,7 @@ func TestPurgeKeepLatest_SingleName(t *testing.T) { "testhost_home_2026-01-01T02:00:00Z", } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -176,7 +186,7 @@ func TestPurgeKeepLatest_WithNameFilter(t *testing.T) { "testhost_home_2026-01-01T04:00:00Z", } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -198,7 +208,7 @@ func TestPurgeKeepLatest_NoSnapshots(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() - v := setupPurgeTest(t, nil) + v := setupPurgeTest(t, snapHostname, nil) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -216,7 +226,7 @@ func TestPurgeKeepLatest_NameFilterNoMatch(t *testing.T) { "testhost_system_2026-01-01T01:00:00Z", } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -243,7 +253,7 @@ func TestPurgeOlderThan_WithNameFilter(t *testing.T) { snapHomeT0, } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) // Purge only "home" snapshots older than 365 days err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ @@ -262,6 +272,30 @@ func TestPurgeOlderThan_WithNameFilter(t *testing.T) { assert.Contains(t, remaining, snapHomeT0) } +func TestPurgeOlderThan_TooLargeDeletesNothing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + snapshotIDs := []string{snapHomeT0, snapHomeT1} + + v := setupPurgeTest(t, snapHostname, snapshotIDs) + + err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + OlderThan: "1000y", + Force: true, + }) + require.EqualError(t, err, + `invalid duration: "1000y" is longer than about 292 years`) + + err = v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + OlderThan: "292y", + Force: true, + }) + require.NoError(t, err) + + assert.ElementsMatch(t, snapshotIDs, listRemainingSnapshots(t, v)) +} + func TestPurgeKeepLatest_ThreeNames(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -277,7 +311,7 @@ func TestPurgeKeepLatest_ThreeNames(t *testing.T) { "testhost_home_2026-01-01T06:00:00Z", } - v := setupPurgeTest(t, snapshotIDs) + v := setupPurgeTest(t, snapHostname, snapshotIDs) err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ KeepLatest: true, @@ -291,3 +325,28 @@ func TestPurgeKeepLatest_ThreeNames(t *testing.T) { assert.Contains(t, remaining, "testhost_system_2026-01-01T04:00:00Z") assert.Contains(t, remaining, "testhost_media_2026-01-01T05:00:00Z") } + +// A hostname may contain underscores, so the snapshot name cannot be found +// by splitting the ID at them. A purge by name must still select "docs". +func TestPurgeKeepLatest_HostnameWithUnderscore(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const ( + system = "my_host_system_2026-01-01T00:00:00Z" + docsT1 = "my_host_docs_2026-01-01T01:00:00Z" + docsT2 = "my_host_docs_2026-01-01T02:00:00Z" + ) + + v := setupPurgeTest(t, "my_host", []string{system, docsT1, docsT2}) + + err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + KeepLatest: true, + Force: true, + Names: []string{"docs"}, + }) + require.NoError(t, err) + + assert.ElementsMatch(t, []string{system, docsT2}, + listRemainingSnapshots(t, v)) +} diff --git a/internal/vaultik/remote_info_test.go b/internal/vaultik/remote_info_test.go new file mode 100644 index 0000000..5d68a03 --- /dev/null +++ b/internal/vaultik/remote_info_test.go @@ -0,0 +1,283 @@ +package vaultik_test + +import ( + "bytes" + "context" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/ui" +) + +// testBlobHashB is a blob that the manifest written by addRemote does +// not reference. +const testBlobHashB = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + +// TestRemoteInfo_UnreadableManifestLeavesOrphansUnknown checks that a +// manifest remote info cannot read makes the orphan figures unknown. A +// blob referenced only by that snapshot would otherwise be counted as +// orphaned, and the report would advise running prune. +func TestRemoteInfo_UnreadableManifestLeavesOrphansUnknown(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + + // The readable manifest references blob A only. + env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + addBlob(t, env.store.testStorer, testBlobHashA) + addBlob(t, env.store.testStorer, testBlobHashB) + + // With every manifest readable, blob B is orphaned. + require.NoError(t, env.v.RemoteInfo(true)) + + var doc map[string]any + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc)) + assert.InDelta(t, 1, doc["orphaned_blob_count"], 0) + + // A second snapshot whose manifest cannot be decoded. Blob B may be + // one of its blobs. + unreadableKey := snapshot.RemoteSnapshotKey(listLocalID) + require.NoError(t, env.store.Put(context.Background(), + "metadata/"+unreadableKey+"/manifest.json.zst", + bytes.NewReader([]byte("not a valid manifest")))) + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(false)) + + text := env.stdout.String() + assert.Contains(t, text, "Orphaned (unreferenced): unknown "+ + "(1 manifest(s) could not be read, "+ + "0 manifest(s) under a non-conforming name skipped)") + assert.NotContains(t, text, "vaultik prune") + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(true)) + + doc = nil + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc)) + assert.Contains(t, doc, "orphaned_blob_count") + assert.Nil(t, doc["orphaned_blob_count"]) + assert.Contains(t, doc, "orphaned_blob_size") + assert.Nil(t, doc["orphaned_blob_size"]) + assert.Equal(t, []any{unreadableKey}, doc["unreadable_manifests"]) +} + +// TestRemoteInfo_UnreadableManifestLeavesSnapshotBlobsUnknown checks +// that the row of a snapshot whose manifest cannot be read gives its +// blob count and blob size as unknown in the table and as null in +// --json, not as 0. A directory without a manifest still shows 0: the +// orphan figures count its blobs as orphaned, so it references none. +func TestRemoteInfo_UnreadableManifestLeavesSnapshotBlobsUnknown(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + readableKey := env.addRemote(t, listRemoteID, + time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + + unreadableKey := snapshot.RemoteSnapshotKey(listLocalID) + require.NoError(t, env.store.Put(context.Background(), + "metadata/"+unreadableKey+"/manifest.json.zst", + bytes.NewReader([]byte("not a valid manifest")))) + + noManifestKey := snapshot.RemoteSnapshotKey("testhost_home_2026-03-03T10:00:00Z") + require.NoError(t, env.store.Put(context.Background(), + "metadata/"+noManifestKey+"/db.zst.age", + bytes.NewReader([]byte("not a valid database")))) + + require.NoError(t, env.v.RemoteInfo(false)) + + // The table truncates the remote key, so a row is found by a prefix. + wantUnknown := map[string]int{readableKey: 0, unreadableKey: 2, noManifestKey: 0} + for key, want := range wantUnknown { + var row string + + for line := range strings.SplitSeq(env.stdout.String(), "\n") { + if strings.HasPrefix(line, key[:16]) { + row = line + } + } + + require.NotEmpty(t, row, "no table row for %s", key) + assert.Equal(t, want, strings.Count(row, "unknown"), "row: %q", row) + } + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(true)) + + var doc struct { + Snapshots []map[string]any `json:"snapshots"` + } + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc)) + require.Len(t, doc.Snapshots, len(wantUnknown)) + + for _, entry := range doc.Snapshots { + switch entry["snapshot_id"] { + case readableKey: + assert.InDelta(t, 1, entry["blob_count"], 0) + assert.InDelta(t, fiveMegabytes, entry["blobs_size"], 0) + case noManifestKey: + assert.InDelta(t, 0, entry["blob_count"], 0) + assert.InDelta(t, 0, entry["blobs_size"], 0) + default: + assert.Equal(t, unreadableKey, entry["snapshot_id"]) + assert.Contains(t, entry, "blob_count") + assert.Nil(t, entry["blob_count"]) + assert.Contains(t, entry, "blobs_size") + assert.Nil(t, entry["blobs_size"]) + } + } +} + +// TestRemoteInfo_SkipsNonConformingMetadataName checks that a directory +// under metadata/ whose name is not a remote key is left out of the +// report, and that the orphan figures are unknown when it holds a +// manifest. The name comes from the destination store; printed raw, its +// control characters would reach the terminal. Its manifest is not +// read, so a blob only it references would otherwise be counted as +// orphaned. +func TestRemoteInfo_SkipsNonConformingMetadataName(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + addBlob(t, env.store.testStorer, testBlobHashA) + addBlob(t, env.store.testStorer, testBlobHashB) + require.NoError(t, env.store.Put(context.Background(), + "metadata/\x1b[31mred/manifest.json.zst", + bytes.NewReader([]byte("not a valid manifest")))) + + require.NoError(t, env.v.RemoteInfo(false)) + + text := env.stdout.String() + assert.NotContains(t, text, "\x1b") + assert.NotContains(t, text, "31mred") + assert.Contains(t, text, "Total (1 snapshots)") + assert.Contains(t, text, "Orphaned (unreferenced): unknown "+ + "(0 manifest(s) could not be read, "+ + "1 manifest(s) under a non-conforming name skipped)") + assert.NotContains(t, text, "vaultik prune") + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(true)) + + out := env.stdout.String() + assert.NotContains(t, out, "31mred") + + var doc map[string]any + + require.NoError(t, json.Unmarshal([]byte(out), &doc)) + assert.Contains(t, doc, "orphaned_blob_count") + assert.Nil(t, doc["orphaned_blob_count"]) + assert.Contains(t, doc, "orphaned_blob_size") + assert.Nil(t, doc["orphaned_blob_size"]) + assert.InDelta(t, 1, doc["skipped_manifest_count"], 0) + assert.NotContains(t, doc, "unreadable_manifests") +} + +// TestRemoteInfo_DoesNotCountNonBlobFileUnderBlobs checks that a file +// under blobs/ whose name is not a blob hash is not counted as a blob. +// prune never deletes such a file, so counting it as an orphaned blob +// would advise a prune that removes nothing. +func TestRemoteInfo_DoesNotCountNonBlobFileUnderBlobs(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + addBlob(t, env.store.testStorer, testBlobHashA) + require.NoError(t, env.store.Put(context.Background(), + "blobs/"+testBlobHashA[:2]+"/"+testBlobHashA[2:4]+"/.DS_Store", + bytes.NewReader([]byte("junk")))) + + require.NoError(t, env.v.RemoteInfo(false)) + + text := env.stdout.String() + assert.Contains(t, text, "Total blobs on remote: 1 (") + assert.Contains(t, text, "Orphaned (unreferenced): 0 (") + assert.NotContains(t, text, "vaultik prune") + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(true)) + + var doc map[string]any + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc)) + assert.InDelta(t, 1, doc["total_blob_count"], 0) + assert.InDelta(t, 0, doc["orphaned_blob_count"], 0) + assert.InDelta(t, 0, doc["orphaned_blob_size"], 0) +} + +// TestRemoteInfo_DirectoryWithoutManifestLeavesOrphansKnown checks that +// a directory under metadata/ holding no manifest.json.zst, such as one +// left by a backup interrupted before its manifest upload, leaves the +// orphan figures known. prune does not treat such a directory as a +// snapshot and deletes the blobs the report lists as orphaned. +func TestRemoteInfo_DirectoryWithoutManifestLeavesOrphansKnown(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + addBlob(t, env.store.testStorer, testBlobHashA) + addBlob(t, env.store.testStorer, testBlobHashB) + + // One directory under a remote key and one under a non-conforming + // name, each holding only a database. + names := []string{snapshot.RemoteSnapshotKey(listLocalID), "\x1b[31mred"} + for _, name := range names { + require.NoError(t, env.store.Put(context.Background(), + "metadata/"+name+"/db.zst.age", + bytes.NewReader([]byte("not a valid database")))) + } + + require.NoError(t, env.v.RemoteInfo(false)) + + text := env.stdout.String() + assert.NotContains(t, text, "\x1b") + assert.Contains(t, text, "Downloading 1 manifest(s)...") + assert.Contains(t, text, "Orphaned (unreferenced): 1 (") + assert.Contains(t, text, "Run 'vaultik prune' to remove orphaned blobs.") + + env.stdout.Reset() + require.NoError(t, env.v.RemoteInfo(true)) + + var doc map[string]any + + require.NoError(t, json.Unmarshal(env.stdout.Bytes(), &doc)) + assert.InDelta(t, 1, doc["orphaned_blob_count"], 0) + assert.NotContains(t, doc, "unreadable_manifests") + assert.NotContains(t, doc, "skipped_manifest_count") +} + +// TestRemoteInfo_StatusLineUsesUIMarker checks that the remote info +// status lines go through internal/ui: marker-prefixed, and silenced by +// --quiet. +func TestRemoteInfo_StatusLineUsesUIMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + env.addRemote(t, listRemoteID, time.Date(2026, 3, 2, 0, 0, 0, 0, time.UTC)) + + const statusLine = ui.Marker + " Scanning snapshot metadata...\n" + + require.NoError(t, env.v.RemoteInfo(false)) + assert.Contains(t, env.stdout.String(), statusLine) + + env.stdout.Reset() + env.v.UI.SetQuiet(true) + require.NoError(t, env.v.RemoteInfo(false)) + assert.NotContains(t, env.stdout.String(), "Scanning snapshot metadata") +} diff --git a/internal/vaultik/remove_quiet_test.go b/internal/vaultik/remove_quiet_test.go new file mode 100644 index 0000000..adfd465 --- /dev/null +++ b/internal/vaultik/remove_quiet_test.go @@ -0,0 +1,154 @@ +package vaultik_test + +import ( + "bytes" + "context" + "encoding/json" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestPurgeSnapshots_QuietSuppressesReport checks that `snapshot purge +// --keep-latest --force` under --quiet deletes the older snapshot and +// prints nothing. +func TestPurgeSnapshots_QuietSuppressesReport(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + v := setupPurgeTest(t, snapHostname, []string{snapHomeT0, snapHomeT1}) + + var out bytes.Buffer + + v.Stdout = &out + v.UI = ui.NewWithColor(&out, false) + v.UI.SetQuiet(true) + + require.NoError(t, v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + KeepLatest: true, + Force: true, + })) + + assert.Equal(t, []string{snapHomeT1}, listRemainingSnapshots(t, v)) + assert.Empty(t, out.String()) +} + +// TestPurgeSnapshots_QuietPromptListsSnapshots checks that `snapshot +// purge --keep-latest` without --force still lists the snapshots its +// prompt asks to delete under --quiet. +func TestPurgeSnapshots_QuietPromptListsSnapshots(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + v := setupPurgeTest(t, snapHostname, []string{snapHomeT0, snapHomeT1}) + + var out bytes.Buffer + + v.Stdout = &out + v.UI = ui.NewWithColor(&out, false) + v.UI.SetQuiet(true) + + // Stdin is empty, so the prompt reads no answer and cancels. + err := v.PurgeSnapshotsWithOptions(&vaultik.SnapshotPurgeOptions{ + KeepLatest: true, + }) + require.ErrorIs(t, err, vaultik.ErrNotConfirmed) + + assert.Contains(t, out.String(), snapHomeT0) + assert.Contains(t, out.String(), "Delete 1 snapshot(s)? [y/N]") + assert.Len(t, listRemainingSnapshots(t, v), 2) +} + +// TestPruneBlobs_QuietPromptShowsBlobTotal checks that `prune` without +// --force still states the count and total size of the blobs its prompt +// asks to delete under --quiet. +func TestPruneBlobs_QuietPromptShowsBlobTotal(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newListEnv(t) + env.v.UI.SetQuiet(true) + + // The store holds no manifest, so nothing references this blob. + addBlob(t, env.store.testStorer, testBlobHashA) + + // Stdin is empty, so the prompt reads no answer and cancels. + require.ErrorIs(t, env.v.PruneBlobs(&vaultik.PruneOptions{}), + vaultik.ErrNotConfirmed) + + assert.Contains(t, env.stdout.String(), + "Found 1 unreferenced blob(s) totaling") + assert.Contains(t, env.stdout.String(), + "Delete 1 unreferenced blob(s)? [y/N]") +} + +// TestRemoveSnapshot_QuietSuppressesReport checks that `snapshot remove` +// under --quiet prints nothing with --dry-run or with --force, and that +// the --json document still prints. +func TestRemoveSnapshot_QuietSuppressesReport(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + newQuietRemover := func() (*vaultik.TestVaultik, *testStorer) { + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") + tv.UI.SetQuiet(true) + + return tv, store + } + + tv, store := newQuietRemover() + + _, err := tv.RemoveSnapshot("snapshot-001", + &vaultik.RemoveOptions{DryRun: true}) + require.NoError(t, err) + assert.Empty(t, tv.Stdout.String(), + "--dry-run must print nothing under --quiet") + + _, err = tv.RemoveSnapshot("snapshot-001", + &vaultik.RemoveOptions{Force: true}) + require.NoError(t, err) + assert.False(t, store.hasKey(remoteKeyPath("snapshot-001"))) + assert.Empty(t, tv.Stdout.String(), + "--force must print nothing under --quiet") + + tv, _ = newQuietRemover() + + _, err = tv.RemoveSnapshot("snapshot-001", + &vaultik.RemoveOptions{JSON: true}) + require.NoError(t, err) + + var result vaultik.RemoveResult + + require.NoError(t, json.Unmarshal(tv.Stdout.Bytes(), &result), + "the --json document must still print under --quiet") + assert.True(t, result.RemoteRemoved) +} + +// TestNukeRemote_QuietSuppressesReport checks that `remote nuke --force` +// under --quiet prints nothing while it removes a snapshot's metadata +// and its blobs. +func TestNukeRemote_QuietSuppressesReport(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, _, out := backUpToFileDestination(ctx, t, storeDir) + v.UI.SetQuiet(true) + + require.NoError(t, v.NukeRemote(true)) + assert.Empty(t, out.String()) +} diff --git a/internal/vaultik/remove_snapshot_test.go b/internal/vaultik/remove_snapshot_test.go index bed9ace..df0f202 100644 --- a/internal/vaultik/remove_snapshot_test.go +++ b/internal/vaultik/remove_snapshot_test.go @@ -3,17 +3,22 @@ package vaultik_test import ( "bytes" "context" + "database/sql" "io" "strings" "sync" "testing" + "time" "github.com/klauspost/compress/zstd" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/types" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -21,11 +26,14 @@ import ( type testStorer struct { mu sync.Mutex data map[string][]byte + // putTimes holds when Put stored each object; ListStream reports it. + putTimes map[string]time.Time } func newTestStorer() *testStorer { return &testStorer{ - data: make(map[string][]byte), + data: make(map[string][]byte), + putTimes: make(map[string]time.Time), } } @@ -39,6 +47,7 @@ func (s *testStorer) Put(_ context.Context, key string, reader io.Reader) error } s.data[key] = data + s.putTimes[key] = time.Now().UTC() return nil } @@ -82,6 +91,7 @@ func (s *testStorer) Delete(_ context.Context, key string) error { defer s.mu.Unlock() delete(s.data, key) + delete(s.putTimes, key) return nil } @@ -115,8 +125,9 @@ func (s *testStorer) ListStream( for key, data := range s.data { if prefix == "" || strings.HasPrefix(key, prefix) { ch <- storage.ObjectInfo{ - Key: key, - Size: int64(len(data)), + Key: key, + Size: int64(len(data)), + ModTime: s.putTimes[key], } } } @@ -125,6 +136,12 @@ func (s *testStorer) ListStream( return ch } +// DeletePartialUploads has nothing to remove: Put stores each object +// under its key at once. +func (s *testStorer) DeletePartialUploads(_ context.Context, _ string) error { + return nil +} + func (s *testStorer) Info() storage.Info { return storage.Info{ Type: testLabel, @@ -208,6 +225,37 @@ func addBlob(t *testing.T, store *testStorer, hash string) { require.NoError(t, err) } +// newLocalIndex returns an in-memory local index holding a completed +// snapshot row for each of ids. +func newLocalIndex(t *testing.T, ids ...string) *database.Repositories { + t.Helper() + + ctx := context.Background() + + db, err := database.New(ctx, ":memory:") + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + + for _, id := range ids { + completedAt := time.Now().UTC() + snap := &database.Snapshot{ + ID: types.SnapshotID(id), + Hostname: snapHostname, + StartedAt: completedAt, + CompletedAt: &completedAt, + } + + err = repos.WithTx(ctx, func(ctx context.Context, tx *sql.Tx) error { + return repos.Snapshots.Create(ctx, tx, snap) + }) + require.NoError(t, err) + } + + return repos +} + // ============================================================================ // Unit Tests for RemoveSnapshot // ============================================================================ @@ -227,6 +275,7 @@ func TestRemoveSnapshot_LocalOnly_PreservesRemote(t *testing.T) { addBlob(t, store, blobA) tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") opts := &vaultik.RemoveOptions{Force: true, LocalOnly: true} result, err := tv.RemoveSnapshot("snapshot-001", opts) @@ -261,7 +310,12 @@ func TestRemoveSnapshot_DefaultRemovesMetadataNotBlobs(t *testing.T) { addBlob(t, store, blobUnique) addBlob(t, store, blobShared) + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001", "snapshot-002") opts := &vaultik.RemoveOptions{Force: true} result, err := tv.RemoveSnapshot("snapshot-001", opts) @@ -283,6 +337,27 @@ func TestRemoveSnapshot_DefaultRemovesMetadataNotBlobs(t *testing.T) { assert.Contains(t, out, "vaultik prune") } +// TestRemoveSnapshot_DeclinedIsError checks that answering no to the +// prompt keeps the snapshot and returns ErrNotConfirmed, so the command +// exits non-zero. +func TestRemoveSnapshot_DeclinedIsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") + tv.Stdin.WriteString("n\n") + + _, err := tv.RemoveSnapshot("snapshot-001", &vaultik.RemoveOptions{}) + + require.ErrorIs(t, err, vaultik.ErrNotConfirmed) + assert.True(t, store.hasKey(remoteKeyPath("snapshot-001"))) + assert.Contains(t, tv.Stdout.String(), "Cancelled") +} + func TestRemoveSnapshot_DryRun(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -307,7 +382,190 @@ func TestRemoveSnapshot_DryRun(t *testing.T) { assert.True(t, store.hasKey("blobs/aa/aa/"+blobA)) assert.True(t, store.hasKey(remoteKeyPath("snapshot-001"))) - assert.Contains(t, tv.Stdout.String(), "[Dry run - no changes made]") + assert.Contains(t, tv.Stdout.String(), "Dry run: no changes made.") +} + +// TestRemoveSnapshot_UnknownIDIsError checks that an ID naming no +// snapshot in the local index or on the destination store is an error +// under every option, and that nothing is reported as removed. +func TestRemoveSnapshot_UnknownIDIsError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + for name, opts := range map[string]vaultik.RemoveOptions{ + "force": {Force: true}, + "json": {JSON: true}, + "dry-run": {Force: true, DryRun: true}, + "local-only": {Force: true, LocalOnly: true}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") + + result, err := tv.RemoveSnapshot("snapshot-999", &opts) + + require.ErrorContains(t, err, "snapshot not found") + assert.False(t, result.RemoteRemoved) + assert.Empty(t, tv.Stdout.String()) + assert.True(t, store.hasKey(remoteKeyPath("snapshot-001"))) + }) + } +} + +// TestRemoveSnapshot_NoMetadataOnDestination checks that removing a +// snapshot whose metadata is not on the destination store does not +// report metadata removed from it. +func TestRemoveSnapshot_NoMetadataOnDestination(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + // A backup wrote to this destination, so it carries the marker. + store := newTestStorer() + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") + + result, err := tv.RemoveSnapshot("snapshot-001", + &vaultik.RemoveOptions{Force: true}) + + require.NoError(t, err) + assert.False(t, result.RemoteRemoved) + + out := tv.Stdout.String() + assert.Contains(t, out, "Removed snapshot 'snapshot-001' from local database") + assert.NotContains(t, out, "Removed snapshot metadata from remote storage") +} + +// TestRemoveSnapshot_NotInLocalIndex checks that removing a snapshot +// only the destination store holds removes its metadata there without +// reporting a removal from the local database. +func TestRemoveSnapshot_NotInLocalIndex(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t) + + result, err := tv.RemoveSnapshot("snapshot-001", + &vaultik.RemoveOptions{Force: true}) + + require.NoError(t, err) + assert.True(t, result.RemoteRemoved) + assert.False(t, store.hasKey(remoteKeyPath("snapshot-001"))) + + out := tv.Stdout.String() + assert.NotContains(t, out, "from local database") + assert.Contains(t, out, "Removed snapshot metadata from remote storage") +} + +// TestRemoveSnapshot_ByRemoteKey checks that a snapshot only the +// destination store holds can be removed by the remote key that +// `snapshot list` shows for it, or by a leading part of that key. +func TestRemoveSnapshot_ByRemoteKey(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + remoteKey := snapshot.RemoteSnapshotKey("snapshot-001") + + for name, identifier := range map[string]string{ + "full key": remoteKey, + "leading part": remoteKey[:8], + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t) + + result, err := tv.RemoveSnapshot(identifier, + &vaultik.RemoveOptions{Force: true}) + + require.NoError(t, err) + assert.True(t, result.RemoteRemoved) + assert.False(t, store.hasKey(remoteKeyPath("snapshot-001"))) + }) + } +} + +// TestRemoveSnapshot_ByRemoteKeyInLocalIndex checks that a snapshot the +// local index holds, named by its remote key, is removed from the local +// index as well as from the destination store. +func TestRemoveSnapshot_ByRemoteKeyInLocalIndex(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + + tv := vaultik.NewForTesting(store) + tv.Repositories = newLocalIndex(t, "snapshot-001") + + result, err := tv.RemoveSnapshot(snapshot.RemoteSnapshotKey("snapshot-001"), + &vaultik.RemoveOptions{Force: true}) + + require.NoError(t, err) + assert.True(t, result.RemoteRemoved) + assert.False(t, store.hasKey(remoteKeyPath("snapshot-001"))) + + snap, err := tv.Repositories.Snapshots.GetByID(context.Background(), + "snapshot-001") + require.NoError(t, err) + assert.Nil(t, snap) +} + +// TestRemoveSnapshot_NotInLocalIndexDeleteFails checks that removing a +// snapshot only the destination store holds fails when its metadata +// cannot be deleted there, under --force and under --json: nothing was +// removed, so the command must not succeed. +func TestRemoveSnapshot_NotInLocalIndexDeleteFails(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + for name, opts := range map[string]vaultik.RemoveOptions{ + "force": {Force: true}, + "json": {JSON: true}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + faulty := faultstore.New(store) + faulty.OnDelete = func(string) bool { return true } + + tv := vaultik.NewForTesting(faulty) + tv.Repositories = newLocalIndex(t) + + result, err := tv.RemoveSnapshot("snapshot-001", &opts) + + require.ErrorIs(t, err, faultstore.ErrInjectedDelete) + assert.False(t, result.RemoteRemoved) + assert.True(t, store.hasKey(remoteKeyPath("snapshot-001"))) + assert.Empty(t, tv.Stdout.String()) + }) + } } func TestRemoveAllSnapshots_RequiresForce(t *testing.T) { @@ -355,7 +613,8 @@ func TestRemoveAllSnapshots_WithForce(t *testing.T) { out := tv.Stdout.String() assert.Contains(t, out, "Removed 2 snapshot(s)") assert.Contains(t, out, "Removed snapshot metadata from remote storage") - assert.Contains(t, out, "vaultik prune") + // Remote nuke, the only caller, deletes the blobs next itself. + assert.NotContains(t, out, "vaultik prune") } func TestRemoveAllSnapshots_DryRun(t *testing.T) { @@ -382,7 +641,7 @@ func TestRemoveAllSnapshots_DryRun(t *testing.T) { assert.Equal(t, initialCount, store.keyCount()) - assert.Contains(t, tv.Stdout.String(), "[Dry run - no changes made]") + assert.Contains(t, tv.Stdout.String(), "Dry run: no changes made.") } func TestRemoveAllSnapshots_NoSnapshots(t *testing.T) { diff --git a/internal/vaultik/restore.go b/internal/vaultik/restore.go index 118a68b..8855aeb 100644 --- a/internal/vaultik/restore.go +++ b/internal/vaultik/restore.go @@ -10,11 +10,14 @@ import ( "math" "os" "path/filepath" + "slices" "strings" + "syscall" "time" "filippo.io/age" "github.com/spf13/afero" + "golang.org/x/sys/unix" "sneak.berlin/go/vaultik/internal/blobgen" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" @@ -25,9 +28,10 @@ import ( // Sentinel errors for restore failures. var ( errFilesFailedRestore = errors.New("file(s) failed to restore") + errPathsNotInSnapshot = errors.New("requested path(s) not in the snapshot") errFilesFailedVerify = errors.New("files failed verification") errDecryptionKeyRequired = errors.New( - "decryption key required for restore\n\n" + + "decryption key required\n\n" + "Set the VAULTIK_AGE_SECRET_KEY environment variable to your " + "age private key file:\n" + " export VAULTIK_AGE_SECRET_KEY=\"$(cat vaultik_backup_private_key.txt)\"") @@ -36,10 +40,14 @@ var ( // which is secret, so the message is safe to print and log. errInvalidAgeSecretKey = errors.New( "configured age secret key holds no usable age identity") + // errWrongPrivateKey is returned when the configured key parses but + // is not one of the keys the snapshot was encrypted to. + errWrongPrivateKey = errors.New("cannot decrypt this snapshot") errBlobMissingFromIndex = errors.New("blob hash missing from blob index") errChunkNotInAnyBlob = errors.New("chunk not found in any blob") errBlobIDNotInHashIndex = errors.New("blob id missing from hash index") errShortChunkRead = errors.New("short read") + errChunkRowMissing = errors.New("chunk has no row in the chunks table") errRestorePathEscapesTarget = errors.New( "refusing to restore path outside the target directory") errTrailingRestoreData = errors.New( @@ -63,6 +71,12 @@ const snapshotDBFilename = "snapshot.db" // directories themselves get their stored mode). const restoreDirMode = 0o755 +// restoreDirCreateMode is the owner-only mode a directory from the +// snapshot is created with during restore, so its contents can be written +// whatever its stored mode. The stored mode is applied after the restore +// loop, by applyDirectoryMetadata. +const restoreDirCreateMode = 0o700 + // restoreFileMode is the restrictive mode a regular file is created with // during restore. Content is written while the file holds this mode; the // stored mode is applied only after the file is fully written and closed, @@ -94,11 +108,17 @@ type RestoreResult struct { BlobsDownloaded int BytesDownloaded int64 Duration time.Duration + FilesFailed int + FailedFiles []string // Paths of files that failed to restore for their own reason + // Blobs that could not be downloaded, and the paths of the files + // skipped because they need one of them. Those files are counted in + // FilesFailed but not listed in the summary. + BlobsFailed int + FilesNeedingFailedBlob []string // Verification results (only populated if Verify option is set) - FilesVerified int - BytesVerified int64 - FilesFailed int - FailedFiles []string // Paths of files that failed verification + FilesVerified int + BytesVerified int64 + VerifyFailedFiles []string // Paths of restored files that failed verification } // Restore restores files from a snapshot to the target directory @@ -116,40 +136,42 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error { "paths", opts.Paths, ) + remoteKey, err := v.resolveSnapshotRemoteKey(opts.SnapshotID) + if err != nil { + return err + } + // Step 1: Download and decrypt the snapshot metadata database log.Info("Downloading snapshot metadata...") - tempDB, tempDir, err := v.downloadSnapshotDB(opts.SnapshotID, identities) + tempDB, tempDir, err := v.downloadSnapshotDB(opts.SnapshotID, remoteKey, identities) + if errors.Is(err, errWrongPrivateKey) { + return err + } + if err != nil { return fmt.Errorf("downloading snapshot database: %w", err) } - defer func() { - err := tempDB.Close() - if err != nil { - log.Debug("Failed to close temp database", "error", err) - } - // Remove the whole private directory, so the decrypted database - // and any SQLite side files it produced are gone on every path. - err = v.Fs.RemoveAll(tempDir) - if err != nil { - log.Debug("Failed to remove temp database directory", "error", err) - } - }() + defer v.closeSnapshotDB(tempDB, tempDir) repos := database.NewRepositories(tempDB) // Step 2: Get list of files to restore - files, err := v.getFilesToRestore(v.ctx, repos, opts.Paths) + files, unmatched, err := v.getFilesToRestore(v.ctx, repos, opts.Paths) if err != nil { return fmt.Errorf("getting files to restore: %w", err) } + // Named before anything is restored, so the names are shown even + // when the restore stops on an error. + unmatchedErr := v.reportUnmatchedPaths(unmatched) + if len(files) == 0 { log.Warn("No files found to restore") v.UI.Warningf("No files found to restore.") - return nil + return unmatchedErr } log.Info("Found files to restore", "count", len(files)) @@ -175,6 +197,20 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error { result.Duration = time.Since(startTime) + return v.finishRestore(repos, files, unmatchedErr, opts, result) +} + +// finishRestore prints the restore summary and the post-restore +// warnings, runs optional verification, and converts any failed-file +// count into an error. Otherwise it returns unmatchedErr, the error for +// the requested paths that matched nothing (nil when there are none). +func (v *Vaultik) finishRestore( + repos *database.Repositories, + files []*database.File, + unmatchedErr error, + opts *RestoreOptions, + result *RestoreResult, +) error { log.Info("Restore complete", "files_restored", result.FilesRestored, "bytes_restored", ubytes(result.BytesRestored), @@ -189,26 +225,18 @@ func (v *Vaultik) Restore(opts *RestoreOptions) error { v.UI.Duration(result.Duration), ) - return v.finishRestore(repos, files, opts, result) -} - -// finishRestore emits the post-restore warnings, runs optional -// verification, and converts any failed-file count into an error. -func (v *Vaultik) finishRestore( - repos *database.Repositories, - files []*database.File, - opts *RestoreOptions, - result *RestoreResult, -) error { if os.Geteuid() != 0 { - v.UI.Warningf("Restore did not preserve file ownership: chown(2) " + - "requires root. Re-run as root (e.g. with sudo) if you need " + - "original UID/GID preserved.") + v.warnIfOwnershipNotPreserved(files, opts.TargetDir) } if result.FilesFailed > 0 { v.UI.Warningf("%d file(s) failed to restore:", result.FilesFailed) + if result.BlobsFailed > 0 { + v.UI.Detailf("%d of them need a blob that could not be read (%d blob(s) in all).", + len(result.FilesNeedingFailedBlob), result.BlobsFailed) + } + for _, path := range result.FailedFiles { v.UI.Detailf("%s", v.UI.Path(path)) } @@ -226,16 +254,70 @@ func (v *Vaultik) finishRestore( return fmt.Errorf("%d %w", result.FilesFailed, errFilesFailedRestore) } - return nil + return unmatchedErr +} + +// warnIfOwnershipNotPreserved warns once if some entry restored under +// targetDir has another owner or group on disk than the snapshot +// records. It is meant for a restore by a normal user, which changes no +// owner or group: a new entry is owned by that user, and its group is +// that user's, or the group of the directory it is created in on macOS +// and in a setgid directory on Linux. An entry that is not on disk, or +// whose filesystem reports no owner, is skipped. +func (v *Vaultik) warnIfOwnershipNotPreserved( + files []*database.File, targetDir string, +) { + for _, file := range files { + targetPath, err := containedRestorePath( + v.Fs, targetDir, file.Path.String()) + if err != nil { + continue + } + + info, err := lstatIfPossible(v.Fs, targetPath) + if err != nil { + continue + } + + owner, ok := info.Sys().(*syscall.Stat_t) + if !ok { + continue + } + + if owner.Uid != file.UID || owner.Gid != file.GID { + v.UI.Warningf("Restore did not preserve file ownership: chown(2) " + + "requires root. Re-run as root (e.g. with sudo) if you need " + + "original UID/GID preserved.") + + return + } + } +} + +// reportUnmatchedPaths warns, by name, about each requested path that +// matched nothing in the snapshot, and returns an error counting them, +// or nil when there are none. +func (v *Vaultik) reportUnmatchedPaths(unmatched []string) error { + if len(unmatched) == 0 { + return nil + } + + for _, path := range unmatched { + log.Warn("Requested path matches nothing in the snapshot", "path", path) + v.UI.Warningf("%s matches nothing in the snapshot.", v.UI.Path(path)) + } + + return fmt.Errorf("%d %w", len(unmatched), errPathsNotInSnapshot) } // restoreIdentities parses the configured age secret key once into every // identity it contains. The value may be a single key line or a whole // age-keygen file with several identities; all of them are returned so // blobgen (via age.Decrypt) can read a blob encrypted to any of their -// recipients. This is the first step of both restore and deep verify, so -// a missing or unparseable key fails before anything is downloaded. The -// error names the configuration source but never the key value. +// recipients. This is the first step of restore, deep verify and +// `snapshot files`, so a missing or unparseable key fails before anything +// is downloaded. The error names the configuration source but never the +// key value. func (v *Vaultik) restoreIdentities() ([]age.Identity, error) { if v.Config.AgeSecretKey == "" { return nil, errDecryptionKeyRequired @@ -253,6 +335,28 @@ func (v *Vaultik) restoreIdentities() ([]age.Identity, error) { return identities, nil } +// newSnapshotDBReader opens the decrypting reader for a snapshot +// database. When none of the identities can decrypt it, the error says +// in plain words that the configured private key is the wrong one and +// names where it was configured. +func (v *Vaultik) newSnapshotDBReader( + r io.Reader, identities []age.Identity, +) (*blobgen.Reader, error) { + blobReader, err := blobgen.NewReader(r, identities...) + + if _, ok := errors.AsType[*age.NoIdentityMatchError](err); ok { + return nil, fmt.Errorf( + "%w: the private key in %s is not one of the keys the backup was encrypted to", + errWrongPrivateKey, v.Config.AgeSecretKeySourceName()) + } + + if err != nil { + return nil, err + } + + return blobReader, nil +} + // restoreAllFiles processes files in blob-locality order: drain every // file whose blob set is on disk, download the missing blobs for the // pending file with the smallest uncached count, repeat. This keeps @@ -289,22 +393,33 @@ func (v *Vaultik) restoreAllFiles( _ = blobCache.Close() }() - // Per-restore sweep state: every blob_size_limit/100 bytes written, - // scan the cache and delete any blob whose remaining file references - // are all already restored. - sweeper := newRestoreSweeper(v.ctx, repos, blobCache, - v.Config.BlobSizeLimit.Int64()/sweepIntervalDivisor) - blobByHash, blobIDToHash, err := v.buildBlobIndexes(repos) if err != nil { return nil, err } - plan, err := newRestorePlan(v.ctx, repos, files, chunkToBlobMap, blobIDToHash) + plan, unplanned, err := newRestorePlan( + v.ctx, repos, files, chunkToBlobMap, blobIDToHash) if err != nil { return nil, fmt.Errorf("building restore plan: %w", err) } + // Per-restore sweep state: every blob_size_limit/100 bytes written, + // scan the cache and delete any blob that no pending file in the + // plan references. + sweeper := newRestoreSweeper(plan, blobCache, + v.Config.BlobSizeLimit.Int64()/sweepIntervalDivisor) + + // Ranging over files rather than the map reports them in a stable order. + for _, file := range files { + if planErr, ok := unplanned[file.ID]; ok { + err = v.handleRestoreFileError(plan, opts, result, file, file.ID, planErr) + if err != nil { + return nil, err + } + } + } + filesByID, totalBytesExpected := indexRestoreFiles(files) v.UI.Beginf("Restoring %s files (%s) to %s.", @@ -332,6 +447,8 @@ func (v *Vaultik) restoreAllFiles( return nil, err } + session.applyDirectoryMetadata() + return result, nil } @@ -355,7 +472,7 @@ func (v *Vaultik) runRestoreLoop( fileID, ready := plan.popReady() if !ready { - downloaded, err := session.downloadNextBlobSet(plan) + downloaded, err := session.downloadNextBlobSet(plan, filesByID) if err != nil { return err } @@ -380,10 +497,8 @@ func (v *Vaultik) runRestoreLoop( continue } - // Record the file as restored so the sweeper can free blobs - // once all referencing files are done, and drop it from the - // plan's indexes so future picks ignore it. - session.sweeper.fileRestored(fileID.String()) + // Drop the file from the plan's indexes so future picks ignore + // it and the sweeper can free blobs no pending file needs. plan.finishFile(fileID) processed++ @@ -411,7 +526,13 @@ func (v *Vaultik) runRestoreLoop( // blob set and downloads its blobs; after each blob lands, the plan // moves any pending file whose set just emptied onto the ready queue. // Returns false when nothing is pending download (the caller stops). -func (s *restoreSession) downloadNextBlobSet(plan *restorePlan) (bool, error) { +// +// A blob that cannot be downloaded is reported through +// handleRestoreBlobError, so it aborts the restore unless --skip-errors +// is set. +func (s *restoreSession) downloadNextBlobSet( + plan *restorePlan, filesByID map[types.FileID]*database.File, +) (bool, error) { s.sweeper.sweep() next, ok := plan.pickNextDownload() @@ -433,7 +554,24 @@ func (s *restoreSession) downloadNextBlobSet(plan *restorePlan) (bool, error) { err := s.downloadBlobToCache(hash, blob.CompressedSize, blob.UncompressedSize) if err != nil { - return false, fmt.Errorf("downloading blob %s: %w", shortHash(hash), err) + err = fmt.Errorf("downloading blob %s: %w", shortHash(hash), err) + + // On cancel the error says nothing about the blob, so it ends + // the restore instead of failing the files that need it. + if s.ctx.Err() != nil { + return false, err + } + + blobErr := s.v.handleRestoreBlobError( + plan, s.opts, s.result, filesByID, + plan.filesReferencingBlob(hash), err) + if blobErr != nil { + return false, blobErr + } + + // next is among the failed files, so the rest of its blob set + // is left for any other file that still needs it. + return true, nil } s.result.BlobsDownloaded++ @@ -519,19 +657,19 @@ func (v *Vaultik) restoreProgressTick( // handleRestoreFileError records a per-file restore failure: fatal unless // --skip-errors is set, in which case the file is counted as failed and -// dropped from the plan. +// dropped from the plan. A fatal failure is not logged here: the returned +// error is printed as the command's ERROR: line. func (v *Vaultik) handleRestoreFileError( plan *restorePlan, opts *RestoreOptions, result *RestoreResult, file *database.File, fileID types.FileID, err error, ) error { - log.Error("Failed to restore file", "path", file.Path, "error", err) - if !opts.SkipErrors { return fmt.Errorf( "restoring %s: %w (pass --skip-errors to continue past "+ "restore failures)", file.Path, err) } + log.Error("Failed to restore file", "path", file.Path, "error", err) v.UI.Errorf("Failed to restore %s: %v. Skipping (--skip-errors).", v.UI.Path(file.Path.String()), err) @@ -543,6 +681,41 @@ func (v *Vaultik) handleRestoreFileError( return nil } +// handleRestoreBlobError records a blob that could not be downloaded. +// fileIDs are the pending files that need it, never empty. Without +// --skip-errors the first of them fails the restore. With it, the blob is +// reported once, and its files are counted as failed and dropped from +// the plan without being reported one by one. +func (v *Vaultik) handleRestoreBlobError( + plan *restorePlan, opts *RestoreOptions, result *RestoreResult, + filesByID map[types.FileID]*database.File, fileIDs []types.FileID, + err error, +) error { + if !opts.SkipErrors { + return v.handleRestoreFileError( + plan, opts, result, filesByID[fileIDs[0]], fileIDs[0], err) + } + + log.Error("Failed to restore files", "files", len(fileIDs), "error", err) + v.UI.Errorf("Failed to restore %d file(s): %v. Skipping them (--skip-errors).", + len(fileIDs), err) + + result.BlobsFailed++ + + for _, fileID := range fileIDs { + path := filesByID[fileID].Path.String() + + log.Debug("Skipped file that needs a failed blob", "path", path) + + result.FilesFailed++ + result.FilesNeedingFailedBlob = append(result.FilesNeedingFailedBlob, path) + + plan.finishFile(fileID) + } + + return nil +} + // printRestoreProgress emits a periodic restore-phase status line via // the UI writer, mirroring scanner.printProcessingProgress so the two // long-running commands have the same on-screen rhythm. @@ -612,20 +785,34 @@ func (v *Vaultik) handleRestoreVerification( opts *RestoreOptions, result *RestoreResult, ) error { - err := v.verifyRestoredFiles(v.ctx, repos, files, opts.TargetDir, result) + // A file that failed to restore was not written and is already + // reported as such, so it is not verified. + failedToRestore := make(map[string]bool, result.FilesFailed) + for _, path := range slices.Concat(result.FailedFiles, result.FilesNeedingFailedBlob) { + failedToRestore[path] = true + } + + restored := make([]*database.File, 0, len(files)) + for _, file := range files { + if !failedToRestore[file.Path.String()] { + restored = append(restored, file) + } + } + + err := v.verifyRestoredFiles(v.ctx, repos, restored, opts.TargetDir, result) if err != nil { return fmt.Errorf("verification failed: %w", err) } - if result.FilesFailed > 0 { + if len(result.VerifyFailedFiles) > 0 { v.UI.Errorf("Verification failed: %s files did not match expected checksums.", - v.UI.Count(result.FilesFailed)) + v.UI.Count(len(result.VerifyFailedFiles))) - for _, path := range result.FailedFiles { + for _, path := range result.VerifyFailedFiles { v.UI.Detailf("%s", v.UI.Path(path)) } - return fmt.Errorf("%d %w", result.FilesFailed, errFilesFailedVerify) + return fmt.Errorf("%d %w", len(result.VerifyFailedFiles), errFilesFailedVerify) } v.UI.Completef("Verified %s files (%s).", @@ -635,19 +822,12 @@ func (v *Vaultik) handleRestoreVerification( return nil } -// downloadSnapshotDB downloads and decrypts the snapshot metadata -// database. The identifier is resolved to the snapshot's remote key: a -// human ID is hashed, and a remote key (or its abbreviation, as printed -// for a remote-only snapshot) is used as-is, so a host with no local -// index can restore the snapshots it can only see on the store. +// downloadSnapshotDB downloads and decrypts the metadata database of the +// snapshot at remoteKey, which resolveSnapshotRemoteKey returned for +// snapshotID. func (v *Vaultik) downloadSnapshotDB( - snapshotID string, identities []age.Identity, + snapshotID, remoteKey string, identities []age.Identity, ) (*database.DB, string, error) { - remoteKey, err := v.resolveSnapshotRemoteKey(snapshotID) - if err != nil { - return nil, "", err - } - // Download encrypted database from storage dbKey := fmt.Sprintf("metadata/%s/db.zst.age", remoteKey) @@ -656,15 +836,17 @@ func (v *Vaultik) downloadSnapshotDB( return nil, "", fmt.Errorf("downloading %s: %w", dbKey, err) } + reader = newCloseOnCancelReader(v.ctx, reader) + defer func() { _ = reader.Close() }() // Decrypt and decompress straight from the storage stream, then stream // the plaintext to a temp file. Neither the encrypted bytes nor the // decrypted database is ever held whole in memory; a snapshot database // can be large. - blobReader, err := blobgen.NewReader(reader, identities...) + blobReader, err := v.newSnapshotDBReader(reader, identities) if err != nil { - return nil, "", fmt.Errorf("creating decryption reader: %w", err) + return nil, "", err } defer func() { _ = blobReader.Close() }() @@ -688,18 +870,34 @@ func (v *Vaultik) downloadSnapshotDB( return db, tempDir, nil } +// closeSnapshotDB closes a database returned by downloadSnapshotDB and +// removes its private directory, so the decrypted database and any SQLite +// side files it produced are gone. +func (v *Vaultik) closeSnapshotDB(db *database.DB, tempDir string) { + err := db.Close() + if err != nil { + log.Debug("Failed to close temp database", "error", err) + } + + err = v.Fs.RemoveAll(tempDir) + if err != nil { + log.Debug("Failed to remove temp database directory", "error", err) + } +} + // verifySnapshotDBIdentity confirms the decrypted metadata database really // is the snapshot named by remoteKey. age decryption proves the database // is readable, not that the object served at // metadata//db.zst.age is the snapshot that was requested: an // attacker who swaps in another valid db.zst.age (which needs no key -// material) would otherwise redirect restore and deep verify to a -// different snapshot's contents. The exported per-snapshot database holds -// exactly one snapshot row, and a snapshot's remote key is derived from -// that row's ID, so the database is the requested one exactly when its -// sole snapshot hashes back to remoteKey. Comparing the requested -// identifier directly would not do: it may be a remote-key prefix a -// recovery host uses in place of a human snapshot ID it cannot know. +// material) would otherwise redirect restore, deep verify and +// `snapshot files` to a different snapshot's contents. The exported +// per-snapshot database holds exactly one snapshot row, and a snapshot's +// remote key is derived from that row's ID, so the database is the +// requested one exactly when its sole snapshot hashes back to remoteKey. +// Comparing the requested identifier directly would not do: it may be a +// remote-key prefix a recovery host uses in place of a human snapshot ID +// it cannot know. func (v *Vaultik) verifySnapshotDBIdentity( db *database.DB, requested, remoteKey string, ) error { @@ -777,28 +975,34 @@ func (v *Vaultik) materializeSnapshotDB( return db, tempDir, nil } -// getFilesToRestore returns the list of files to restore based on path filters +// getFilesToRestore returns the list of files to restore based on path +// filters, and the filters, as given, that matched no file. func (v *Vaultik) getFilesToRestore( ctx context.Context, repos *database.Repositories, pathFilters []string, -) ([]*database.File, error) { +) ([]*database.File, []string, error) { // If no filters, get all files if len(pathFilters) == 0 { - return repos.Files.ListAll(ctx) + files, err := repos.Files.ListAll(ctx) + + return files, nil, err } // Get files matching the path filters - var result []*database.File + var ( + result []*database.File + unmatched []string + ) seen := make(map[string]bool) for _, filter := range pathFilters { - // Normalize the filter path - filter = filepath.Clean(filter) - - // Get files with this prefix - files, err := repos.Files.ListByPrefix(ctx, filter) + files, err := repos.Files.ListUnderPath(ctx, filepath.Clean(filter)) if err != nil { - return nil, fmt.Errorf("listing files with prefix %s: %w", filter, err) + return nil, nil, fmt.Errorf("listing files under %s: %w", filter, err) + } + + if len(files) == 0 { + unmatched = append(unmatched, filter) } for _, file := range files { @@ -809,7 +1013,7 @@ func (v *Vaultik) getFilesToRestore( } } - return result, nil + return result, unmatched, nil } // buildChunkToBlobMap creates a mapping from chunk hash to blob information @@ -874,9 +1078,13 @@ type restoreSession struct { // root can chown a file to an arbitrary UID/GID — non-root chown // always fails with EPERM. Attempting it anyway produces N // guaranteed-failed syscalls + N noisy debug lines, so we skip - // the call entirely as non-root and emit one warning at the end - // of the restore explaining that ownership was not preserved. + // the call entirely as non-root; warnIfOwnershipNotPreserved warns + // once at the end of the restore if that left any owner or group + // other than recorded. runningAsRoot bool + // directories holds every restored directory, for + // applyDirectoryMetadata to finish after the restore loop. + directories []*database.File } // containedRestorePath resolves rel — a path read from the snapshot @@ -983,6 +1191,8 @@ func (s *restoreSession) restoreSymlink(file *database.File, targetPath string) if err != nil { return fmt.Errorf("creating symlink: %w", err) } + + s.applySymlinkMetadata(file, targetPath) } else { log.Debug("Symlink creation not supported on this filesystem", "path", file.Path, "target", file.LinkTarget) @@ -995,35 +1205,90 @@ func (s *restoreSession) restoreSymlink(file *database.File, targetPath string) return nil } -// restoreDirectory restores a directory with its permissions, mtime, -// and (on real filesystems, with sufficient privileges) ownership. +// restoreDirectory creates a directory with restoreDirCreateMode. Its +// stored mode, owner and mtime are applied after the restore loop by +// applyDirectoryMetadata: a read-only stored mode would block writing +// its contents, and writing them changes its mtime. func (s *restoreSession) restoreDirectory( file *database.File, targetPath string, ) error { - err := s.v.Fs.MkdirAll(targetPath, os.FileMode(file.Mode)) + err := s.v.Fs.MkdirAll(targetPath, restoreDirCreateMode) if err != nil { return fmt.Errorf("creating directory: %w", err) } - // MkdirAll applies the process umask, so chmod to the exact stored - // mode. A failure here is non-fatal. - err = s.v.Fs.Chmod(targetPath, os.FileMode(file.Mode)) - if err != nil { - log.Debug("Failed to set permissions", "path", targetPath, "error", err) - } - - s.applyFileMetadata(file, targetPath) + s.directories = append(s.directories, file) s.result.FilesRestored++ return nil } +// applyDirectoryMetadata applies the stored owner, mtime and mode to every +// restored directory, each before its parent, so a parent whose stored +// mode denies search does not block its children. Failures are logged at +// debug level and do not abort the restore. +func (s *restoreSession) applyDirectoryMetadata() { + // A path sorts after its parent's, so reverse order puts every + // directory before its parent. + slices.SortFunc(s.directories, func(a, b *database.File) int { + return strings.Compare(b.Path.String(), a.Path.String()) + }) + + for _, dir := range s.directories { + targetPath, err := containedRestorePath( + s.v.Fs, s.opts.TargetDir, dir.Path.String()) + if err != nil { + log.Debug("Failed to set directory metadata", + "path", dir.Path, "error", err) + + continue + } + + // A later entry can have put a symlink in the directory's place, + // for example one stored as "/d/" next to the directory "/d". The + // calls below follow symlinks, so they would change its target. + info, err := lstatIfPossible(s.v.Fs, targetPath) + if err != nil || !info.IsDir() { + log.Debug("Not setting directory metadata: no longer a directory", + "path", targetPath, "error", err) + + continue + } + + s.applyFileMetadata(dir, targetPath) + + err = s.v.Fs.Chmod(targetPath, os.FileMode(dir.Mode)) + if err != nil { + log.Debug("Failed to set permissions", "path", targetPath, "error", err) + } + } +} + +// applySymlinkMetadata applies ownership (when running as root) and mtime +// to a restored symlink itself; os.Chown and Chtimes would follow it. +// Failures are logged at debug level and do not abort the restore. +func (s *restoreSession) applySymlinkMetadata(file *database.File, targetPath string) { + if s.runningAsRoot { + err := os.Lchown(targetPath, int(file.UID), int(file.GID)) + if err != nil { + log.Debug("Failed to set ownership", "path", targetPath, "error", err) + } + } + + mtime := unix.NsecToTimeval(file.MTime.UnixNano()) + + err := unix.Lutimes(targetPath, []unix.Timeval{mtime, mtime}) + if err != nil { + log.Debug("Failed to set mtime", "path", targetPath, "error", err) + } +} + // applyFileMetadata applies ownership (when running as root on a real -// filesystem) and mtime to a restored path. Permission mode is applied -// separately by each caller, with different failure handling, so it is -// not touched here. Failures are logged at debug level and do not abort -// the restore. +// filesystem) and mtime to a restored path. The caller applies the mode +// afterwards: on Linux a chown clears the setuid and setgid bits of a +// regular file. Failures are logged at debug level and do not abort the +// restore. func (s *restoreSession) applyFileMetadata(file *database.File, targetPath string) { if s.runningAsRoot { if _, ok := s.v.Fs.(*afero.OsFs); ok { @@ -1114,8 +1379,8 @@ func (s *restoreSession) restoreRegularFile( return fmt.Errorf("closing output file: %w", err) } - s.applyRestoredFileMode(file, targetPath) s.applyFileMetadata(file, targetPath) + s.applyRestoredFileMode(file, targetPath) s.result.FilesRestored++ s.result.BytesRestored += bytesWritten @@ -1173,7 +1438,7 @@ func (s *restoreSession) writeFileChunks( blobChunk, ok := s.chunkToBlobMap[chunkHashStr] if !ok { return bytesWritten, timings, fmt.Errorf( - "%w: %s", errChunkNotInAnyBlob, chunkHashStr[:16]) + "%w: %s", errChunkNotInAnyBlob, shortHash(chunkHashStr)) } blobHash, ok := s.blobIDToHash[blobChunk.BlobID.String()] @@ -1190,7 +1455,7 @@ func (s *restoreSession) writeFileChunks( if err != nil { return bytesWritten, timings, fmt.Errorf( "reading chunk %s from cached blob %s: %w", - fc.ChunkHash[:16], blobHash[:16], err) + shortHash(chunkHashStr), shortHash(blobHash), err) } t0 = time.Now() @@ -1326,8 +1591,8 @@ func (v *Vaultik) verifyRestoredFiles( if err != nil { log.Error("File verification failed", "path", file.Path, "error", err) - result.FilesFailed++ - result.FailedFiles = append(result.FailedFiles, file.Path.String()) + result.VerifyFailedFiles = append( + result.VerifyFailedFiles, file.Path.String()) } bytesProcessed += file.Size @@ -1343,7 +1608,7 @@ func (v *Vaultik) verifyRestoredFiles( log.Info("Verification complete", "files_verified", result.FilesVerified, "bytes_verified", ubytes(result.BytesVerified), - "files_failed", result.FilesFailed, + "files_failed", len(result.VerifyFailedFiles), ) return nil @@ -1388,33 +1653,44 @@ func (v *Vaultik) verifyFile( chunk, err := repos.Chunks.GetByHash(ctx, fc.ChunkHash.String()) if err != nil { return bytesVerified, fmt.Errorf("getting chunk %s: %w", - fc.ChunkHash.String()[:16], err) + shortHash(fc.ChunkHash.String()), err) } - // Read chunk data from file - chunkData := make([]byte, chunk.Size) - - n, err := io.ReadFull(f, chunkData) - if err != nil { - return bytesVerified, fmt.Errorf("reading chunk data: %w", err) + if chunk == nil { + return bytesVerified, fmt.Errorf("%w: %s", + errChunkRowMissing, shortHash(fc.ChunkHash.String())) } - if int64(n) != chunk.Size { + // chunk.Size comes from the snapshot database, which is not + // trusted: reject a negative size, and hash the chunk by + // streaming it rather than allocating that many bytes. + if chunk.Size < 0 { + return bytesVerified, fmt.Errorf("%w: chunk %d size %d", + errNegativeChunkLength, fc.Idx, chunk.Size) + } + + hasher := sha256.New() + + n, err := io.CopyN(hasher, f, chunk.Size) + if errors.Is(err, io.EOF) { return bytesVerified, fmt.Errorf("%w: expected %d bytes, got %d", errShortChunkRead, chunk.Size, n) } - // Calculate hash and compare - hash := sha256.Sum256(chunkData) - actualHash := hex.EncodeToString(hash[:]) + if err != nil { + return bytesVerified, fmt.Errorf("reading chunk data: %w", err) + } + + actualHash := hex.EncodeToString(hasher.Sum(nil)) expectedHash := fc.ChunkHash.String() if actualHash != expectedHash { return bytesVerified, fmt.Errorf("%w: chunk %d: expected %s, got %s", - errChunkHashMismatch, fc.Idx, expectedHash[:16], actualHash[:16]) + errChunkHashMismatch, fc.Idx, + shortHash(expectedHash), shortHash(actualHash)) } - bytesVerified += int64(n) + bytesVerified += n } // The stored chunks account for the whole file, so the reader must diff --git a/internal/vaultik/restore_another_machine_test.go b/internal/vaultik/restore_another_machine_test.go index 59268a4..3d0fde9 100644 --- a/internal/vaultik/restore_another_machine_test.go +++ b/internal/vaultik/restore_another_machine_test.go @@ -10,6 +10,7 @@ import ( "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/cli" "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" @@ -27,10 +28,12 @@ import ( // // The backup half writes a snapshot with one index and hostname. The // restore half throws that index away entirely: a fresh, empty index and -// a config that shares nothing with the original but the storage location -// and the secret key. If restore or verify needed the original local -// index — or the human snapshot ID that only that index holds — this test -// could not run, because the recovery host can know neither. +// a config written by `config init` and `config set storage_url`, as in +// the README's steps for restoring on another machine, which shares +// nothing with the original but the storage location and the secret key. +// If restore or verify needed the original local index — or +// the human snapshot ID that only that index holds — this test could not +// run, because the recovery host can know neither. func TestRestoreOnAnotherMachine(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -39,7 +42,7 @@ func TestRestoreOnAnotherMachine(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -58,7 +61,12 @@ func TestRestoreOnAnotherMachine(t *testing.T) { // Recovery host: a fresh empty index, a different hostname, and no // age_recipients — only the secret key and the same storage location. - recovery, stdout := newRecoveryHost(ctx, t, fs, storer) + configPath := filepath.Join(tempDir, "config.yml") + runVaultikCommand(t, "--config", configPath, "config", "init") + runVaultikCommand(t, "--config", configPath, + "config", "set", "storage_url", "file://"+storeDir) + + recovery, stdout := newRecoveryHost(ctx, t, fs, storer, configPath) // The recovery index really is empty. This is the assertion that makes // the test a guard against restore quietly depending on the original @@ -93,6 +101,10 @@ func TestRestoreOnAnotherMachine(t *testing.T) { remote.RemoteKey, &vaultik.VerifyOptions{Deep: true})) assertRestoredTreeMatches(t, fs, restoreDir, sourceFiles) + + // With no public key configured, a backup must refuse to start. + err = recovery.CreateSnapshot(&vaultik.SnapshotCreateOptions{Cron: true}) + require.ErrorContains(t, err, "age_recipients") } // writeRecoverySourceTree writes a small source tree spanning several @@ -118,14 +130,24 @@ func writeRecoverySourceTree( } // newRecoveryHost builds the Vaultik a replacement machine would run: an -// empty in-memory index, a hostname different from the backup host, no -// age_recipients, and only the secret key plus the shared storer. It -// returns the instance and the buffer its stdout is wired to. +// empty in-memory index, a hostname different from the backup host, and +// only the secret key plus the shared storer. Its config is read from +// configPath by config.Load, as every command reads it. It returns the +// instance and the buffer its stdout is wired to. func newRecoveryHost( ctx context.Context, t *testing.T, fs afero.Fs, storer storage.Storer, + configPath string, ) (*vaultik.Vaultik, *bytes.Buffer) { t.Helper() + cfg, err := config.Load(configPath) + require.NoError(t, err) + + // Set directly rather than through VAULTIK_AGE_SECRET_KEY, which a + // parallel test cannot change. + cfg.AgeSecretKey = testAgeSecretKey + cfg.Hostname = "recovery-host" + recoveryDB, err := database.New(ctx, ":memory:") require.NoError(t, err) t.Cleanup(func() { _ = recoveryDB.Close() }) @@ -133,10 +155,7 @@ func newRecoveryHost( stdout := &bytes.Buffer{} recovery := &vaultik.Vaultik{ - Config: &config.Config{ - AgeSecretKey: testAgeSecretKey, - Hostname: "recovery-host", - }, + Config: cfg, Storage: storer, Fs: fs, Repositories: database.NewRepositories(recoveryDB), @@ -150,6 +169,20 @@ func newRecoveryHost( return recovery, stdout } +// runVaultikCommand runs one vaultik command line in-process and fails the +// test if it returns an error. The command writes the cli package's global +// flag variables, so it must not be called from two tests that run at the +// same time. +func runVaultikCommand(t *testing.T, args ...string) { + t.Helper() + + cmd := cli.NewRootCommand() + cmd.SetArgs(args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + require.NoError(t, cmd.Execute()) +} + // assertRestoredTreeMatches byte-compares every restored file against its // source content. func assertRestoredTreeMatches( diff --git a/internal/vaultik/restore_interrupt_test.go b/internal/vaultik/restore_interrupt_test.go index ccf07a5..134e3f3 100644 --- a/internal/vaultik/restore_interrupt_test.go +++ b/internal/vaultik/restore_interrupt_test.go @@ -1,6 +1,7 @@ package vaultik //nolint:testpackage // sets ctx/cancel and inspects scratch files import ( + "bytes" "context" "io" "path/filepath" @@ -11,6 +12,7 @@ import ( "time" "github.com/spf13/afero" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/storage" @@ -63,7 +65,7 @@ func TestRestoreCleansTempDirOnInterrupt(t *testing.T) { root := t.TempDir() dataDir := filepath.Join(root, "source") - storeDir := filepath.Join(root, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(root, "restored") dbPath := filepath.Join(root, "index.sqlite") @@ -72,7 +74,8 @@ func TestRestoreCleansTempDirOnInterrupt(t *testing.T) { buildLocalityFixture(t, fs, dataDir) cfg, storer, snapshotID := setupLocalityBackup( - context.Background(), t, fs, dataDir, storeDir, dbPath) + context.Background(), t, fs, dataDir, storeDir, dbPath, + localitySourceBytes) // Point the "" temp paths (the blob cache directory and the // snapshot-database directory) at a private directory so the test can @@ -140,14 +143,14 @@ func TestRestoreCleansTempDirOnInterrupt(t *testing.T) { } // scratchEntries returns the vaultik blob-cache and snapshot-database -// scratch entries currently present in dir. +// scratch entries (restore's and deep verify's) currently present in dir. func scratchEntries(t *testing.T, dir string) []string { t.Helper() var matches []string for _, pattern := range []string{ - "vaultik-blobcache-*", "vaultik-restore-*", + "vaultik-blobcache-*", "vaultik-restore-*", "vaultik-verify-*", } { found, err := filepath.Glob(filepath.Join(dir, pattern)) require.NoError(t, err) @@ -157,3 +160,188 @@ func scratchEntries(t *testing.T, dir string) []string { return matches } + +// TestRestoreSkipErrorsCancelDuringBlobDownload cancels a SkipErrors +// restore while a blob download is in progress. The download fails only +// because of the cancel, so Restore must return context.Canceled without +// reporting the file that needs the blob as failed. +func TestRestoreSkipErrorsCancelDuringBlobDownload(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + cfg, storer, snapshotID, srcPath := backupOneFile(context.Background(), + t, fs, tempDir, "a.txt", []byte("hello vaultik"), 0o644) + + gate := newBlockingBlobStorer(storer) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var out bytes.Buffer + + v := newRestoreVaultik(ctx, cfg, gate, fs) + v.UI = ui.NewWithColor(&out, false) + + restoreErr := make(chan error, 1) + + go func() { + restoreErr <- v.Restore(&RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: filepath.Join(tempDir, "restored"), + SkipErrors: true, + }) + }() + + select { + case <-gate.entered: + case <-time.After(30 * time.Second): + t.Fatal("restore never reached the blob-download phase") + } + + cancel() + + require.ErrorIs(t, <-restoreErr, context.Canceled) + assert.NotContains(t, out.String(), srcPath, + "the cancel was reported as a failed file") +} + +// stallingStorer wraps a Storer so that each download of a key chosen by +// stalls hands over the first half of the object and then stalls, +// ignoring the context, as a file:// read on a hung USB stick or network +// share does. Only closing the returned reader ends the stall. +type stallingStorer struct { + storage.Storer + + stalls func(key string) bool + once sync.Once + stalled chan struct{} +} + +func newStallingStorer( + inner storage.Storer, stalls func(key string) bool, +) *stallingStorer { + return &stallingStorer{ + Storer: inner, + stalls: stalls, + stalled: make(chan struct{}), + } +} + +func (s *stallingStorer) Get( + ctx context.Context, key string, +) (io.ReadCloser, error) { + rc, err := s.Storer.Get(ctx, key) + if err != nil || !s.stalls(key) { + return rc, err + } + + object, err := io.ReadAll(rc) + _ = rc.Close() + + if err != nil { + return nil, err + } + + // The writer is never closed, so once the first half has been read + // the next Read blocks until the reader is closed. + pr, pw := io.Pipe() + + go func() { + _, _ = pw.Write(object[:len(object)/2]) + + s.once.Do(func() { close(s.stalled) }) + }() + + return pr, nil +} + +// TestInterruptDuringStalledReadCleansTempDir stops a restore and a deep +// verify while a read of a blob or of the snapshot database is stalled +// on a source that ignores the context. Stopping must end that read, so +// the operation unwinds and removes its decrypted scratch files well +// within the shutdown timeout (issues #325 and #356). +// +// Not parallel: it points TMPDIR at a private directory (via t.Setenv) +// so it can assert on exactly the scratch files the operation created. +func TestInterruptDuringStalledReadCleansTempDir(t *testing.T) { + log.Initialize(log.Config{}) + + stalledReads := map[string]func(key string) bool{ + "blob": func(key string) bool { + return strings.HasPrefix(key, "blobs/") + }, + "snapshot database": func(key string) bool { + return strings.HasSuffix(key, "/db.zst.age") + }, + } + + operations := map[string]func(v *Vaultik, snapshotID, targetDir string) error{ + "restore": func(v *Vaultik, snapshotID, targetDir string) error { + return v.Restore(&RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: targetDir, + }) + }, + "deep verify": func(v *Vaultik, snapshotID, _ string) error { + return v.RunDeepVerify(snapshotID, &VerifyOptions{Deep: true}) + }, + } + + for readName, stalls := range stalledReads { + for opName, op := range operations { + t.Run(readName+" read during "+opName, func(t *testing.T) { + fs := afero.NewOsFs() + root := t.TempDir() + + // Random content, so the blob stays large enough to stall + // part-way through its compressed, encrypted body. + cfg, storer, snapshotID, _ := backupOneFile(context.Background(), + t, fs, root, "a.bin", randomBytes(t, 256*1024), 0o644) + + scratch := filepath.Join(root, "scratch") + require.NoError(t, fs.MkdirAll(scratch, 0o755)) + t.Setenv("TMPDIR", scratch) + + stalling := newStallingStorer(storer, stalls) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + v := newRestoreVaultik(ctx, cfg, stalling, fs) + v.cancel = cancel + + var opErr error + + stop := v.StartOperation(func() { + opErr = op(v, snapshotID, filepath.Join(root, "restored")) + }) + + select { + case <-stalling.stalled: + case <-time.After(30 * time.Second): + t.Fatal("the operation never reached the stalled read") + } + + // The snapshot database's temp directory is created just + // after its read starts, so it can appear after the stall. + require.Eventually(t, func() bool { + return len(scratchEntries(t, scratch)) > 0 + }, 10*time.Second, 10*time.Millisecond, + "expected decrypted scratch files to exist mid-read") + + stopCtx, stopCancel := context.WithTimeout( + context.Background(), 10*time.Second) + defer stopCancel() + + require.True(t, stop(stopCtx), + "stop timed out; the stalled read was not interrupted") + require.ErrorIs(t, opErr, context.Canceled) + require.Empty(t, scratchEntries(t, scratch), + "decrypted scratch files remained after the interrupt") + }) + } + } +} diff --git a/internal/vaultik/restore_locality_test.go b/internal/vaultik/restore_locality_test.go index 67b1310..e57778e 100644 --- a/internal/vaultik/restore_locality_test.go +++ b/internal/vaultik/restore_locality_test.go @@ -46,11 +46,11 @@ import ( // slice out a few KB — currently the dominant cost in restore. // // The test deliberately constructs an adversarial scenario: three -// blobs A/B/C of ~6 MB each, nine files distributed across them, and -// path-ordered names that interleave the blobs (a1, b1, c1, a2, b2, -// c2, …) so naive path-order processing would touch every blob before -// finishing any of them. -// localitySource is one 1 MiB fixture file used by the locality test. +// blobs A/B/C of five 64 KiB chunks each, nine files distributed across +// them, and path-ordered names that interleave the blobs (a1, b1, c1, +// a2, b2, c2, …) so naive path-order processing would touch every blob +// before finishing any of them. +// localitySource is one 64 KiB fixture file used by the locality test. type localitySource struct { path string data []byte @@ -63,8 +63,12 @@ type localityCopy struct { data []byte } +// localitySourceBytes is the size of each source file of the locality +// fixture. +const localitySourceBytes = 64 * 1024 + // buildLocalityFixture writes the adversarial source layout described -// in TestRestoreLocalityAndReadAt: 15 sources of 1 MiB each (which the +// in TestRestoreLocalityAndReadAt: 15 sources of 64 KiB each (which the // backup packs into 3 blobs of 5 chunks) plus 9 interleaved-name copies // (3 per blob group). func buildLocalityFixture( @@ -73,7 +77,6 @@ func buildLocalityFixture( t.Helper() const ( - srcBytes = 1024 * 1024 srcCount = 15 blobsCount = 3 perBlob = srcCount / blobsCount @@ -83,7 +86,7 @@ func buildLocalityFixture( for i := range srcCount { s := &localitySource{ path: fmt.Sprintf("src-%03d.bin", i+1), - data: randomBytes(t, srcBytes), + data: randomBytes(t, localitySourceBytes), } sources[i] = s require.NoError(t, afero.WriteFile( @@ -115,19 +118,20 @@ func buildLocalityFixture( // setupLocalityBackup runs the backup half of the locality test: a // snapshot of dataDir into a file storer with sizes tuned so 15 one-chunk -// files pack into 3 blobs. The index database is closed before returning -// so the restore half runs from remote bytes only. +// files of srcBytes pack into 3 blobs. The index database is closed +// before returning so the restore half runs from remote bytes only. func setupLocalityBackup( ctx context.Context, t *testing.T, fs afero.Fs, - dataDir, storeDir, dbPath string, + dataDir, storeDir, dbPath string, srcBytes int64, ) (*config.Config, *storage.FileStorer, string) { t.Helper() - // chunkSize avg = 4 MiB makes minSize = 1 MiB, so a 1 MiB file - // becomes one chunk. maxBlobSize = 5 MiB packs exactly 5 chunks - // per blob, yielding 3 blobs from 15 source files. - chunkSize := int64(4 * 1024 * 1024) - maxBlobSize := int64(5 * 1024 * 1024) + // An average chunk size of four times srcBytes makes the minimum + // chunk srcBytes, so each source file becomes one chunk. A blob limit + // of five times srcBytes packs exactly 5 chunks per blob, yielding 3 + // blobs from 15 source files. + chunkSize := 4 * srcBytes + maxBlobSize := 5 * srcBytes storer, err := storage.NewFileStorer(storeDir) require.NoError(t, err) @@ -197,7 +201,7 @@ func TestRestoreLocalityAndReadAt(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -208,7 +212,7 @@ func TestRestoreLocalityAndReadAt(t *testing.T) { ctx := context.Background() cfg, storer, snapshotID := setupLocalityBackup( - ctx, t, fs, dataDir, storeDir, dbPath) + ctx, t, fs, dataDir, storeDir, dbPath, localitySourceBytes) // Wrap the storer so we can count downloads per blob key. counter := newCountingStorer(storer) diff --git a/internal/vaultik/restore_malformed_db_test.go b/internal/vaultik/restore_malformed_db_test.go new file mode 100644 index 0000000..661d18b --- /dev/null +++ b/internal/vaultik/restore_malformed_db_test.go @@ -0,0 +1,223 @@ +package vaultik //nolint:testpackage // drives unexported restore and verify steps + +import ( + "context" + "math" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/types" +) + +// These tests feed restore and --verify a snapshot database written by +// hand, as a damaged or hostile store could serve one. Each malformed row +// must end in an error, not a panic. + +// shortChunkHash is shorter than the hash prefix that error messages print. +const shortChunkHash = "abc" + +// restoredFileContent is the content of the restored file under verify. +const restoredFileContent = "xyz" + +// craftedSnapshotDB opens an empty snapshot database in a temp directory. +func craftedSnapshotDB(t *testing.T) (*database.DB, *database.Repositories) { + t.Helper() + + db, err := database.New(context.Background(), + filepath.Join(t.TempDir(), "snapshot.db")) + require.NoError(t, err) + + t.Cleanup(func() { _ = db.Close() }) + + return db, database.NewRepositories(db) +} + +// craftedFile adds a regular file whose only chunk has the given hash. +// Adding the chunks row, if any, is left to the caller. +func craftedFile( + t *testing.T, repos *database.Repositories, chunkHash string, +) *database.File { + t.Helper() + + ctx := context.Background() + file := &database.File{ + Path: "/src/f", + MTime: time.Now().UTC(), + Size: int64(len(restoredFileContent)), + Mode: 0o644, + } + require.NoError(t, repos.Files.Create(ctx, nil, file)) + require.NoError(t, repos.FileChunks.Create(ctx, nil, &database.FileChunk{ + FileID: file.ID, + ChunkHash: types.ChunkHash(chunkHash), + })) + + return file +} + +// TestRestoreShortChunkHashInNoBlob proves a file whose short chunk hash +// has no blob_chunks row is left out of the restore plan with an error, +// and fails the chunk write with an error. +func TestRestoreShortChunkHashInNoBlob(t *testing.T) { + t.Parallel() + + ctx := context.Background() + _, repos := craftedSnapshotDB(t) + require.NoError(t, repos.Chunks.Create(ctx, nil, + &database.Chunk{ChunkHash: shortChunkHash, Size: 3})) + file := craftedFile(t, repos, shortChunkHash) + + v := NewForTesting(nil) + + chunkToBlobMap, err := v.buildChunkToBlobMap(ctx, repos) + require.NoError(t, err) + + plan, unplanned, err := newRestorePlan(ctx, repos, []*database.File{file}, + chunkToBlobMap, map[string]string{}) + require.NoError(t, err) + require.ErrorIs(t, unplanned[file.ID], errPlanChunkMissing) + require.False(t, plan.hasPending()) + + fileChunks, err := repos.FileChunks.GetByFileID(ctx, file.ID) + require.NoError(t, err) + + out, err := afero.NewMemMapFs().Create("out") + require.NoError(t, err) + + session := &restoreSession{ + v: v.Vaultik, ctx: ctx, chunkToBlobMap: chunkToBlobMap, + } + + _, _, err = session.writeFileChunks(out, fileChunks) + require.ErrorIs(t, err, errChunkNotInAnyBlob) +} + +// TestRestoreShortChunkHashReadPastBlobEnd proves a short chunk hash +// whose blob_chunks row reads past the end of its blob fails the chunk +// write with an error. +func TestRestoreShortChunkHashReadPastBlobEnd(t *testing.T) { + t.Parallel() + + ctx := context.Background() + _, repos := craftedSnapshotDB(t) + + blobHash := strings.Repeat("b", blobHashHexLen) + blob := &database.Blob{ + ID: types.NewBlobID(), + Hash: types.BlobHash(blobHash), + CreatedTS: time.Now().UTC(), + } + require.NoError(t, repos.Blobs.Create(ctx, nil, blob)) + require.NoError(t, repos.Chunks.Create(ctx, nil, + &database.Chunk{ChunkHash: shortChunkHash, Size: 3})) + require.NoError(t, repos.BlobChunks.Create(ctx, nil, &database.BlobChunk{ + BlobID: blob.ID, + ChunkHash: shortChunkHash, + Length: 100, + })) + file := craftedFile(t, repos, shortChunkHash) + + cache, err := newBlobDiskCache(1 << 20) + require.NoError(t, err) + + t.Cleanup(func() { _ = cache.Close() }) + + require.NoError(t, cache.Put(blobHash, []byte("abc"))) + + v := NewForTesting(nil) + + chunkToBlobMap, err := v.buildChunkToBlobMap(ctx, repos) + require.NoError(t, err) + + _, blobIDToHash, err := v.buildBlobIndexes(repos) + require.NoError(t, err) + + fileChunks, err := repos.FileChunks.GetByFileID(ctx, file.ID) + require.NoError(t, err) + + out, err := afero.NewMemMapFs().Create("out") + require.NoError(t, err) + + session := &restoreSession{ + v: v.Vaultik, + ctx: ctx, + chunkToBlobMap: chunkToBlobMap, + blobIDToHash: blobIDToHash, + blobCache: cache, + } + + _, _, err = session.writeFileChunks(out, fileChunks) + require.ErrorIs(t, err, errCacheReadBeyondBlob) +} + +// TestVerifyFileMalformedChunkRow proves --verify returns an error for a +// chunk with no chunks row, a short chunk hash, and a chunk size from the +// database that is negative or larger than the restored file. +func TestVerifyFileMalformedChunkRow(t *testing.T) { + t.Parallel() + + fullHash := types.ChunkHash(strings.Repeat("c", blobHashHexLen)) + + tests := []struct { + name string + hash types.ChunkHash + chunk *database.Chunk // nil adds no chunks row + want error + }{ + { + name: "missing chunk row", + hash: fullHash, + want: errChunkRowMissing, + }, + { + name: "short hash", + hash: shortChunkHash, + chunk: &database.Chunk{ChunkHash: shortChunkHash, Size: 3}, + want: errChunkHashMismatch, + }, + { + name: "size larger than the file", + hash: fullHash, + chunk: &database.Chunk{ChunkHash: fullHash, Size: math.MaxInt64}, + want: errShortChunkRead, + }, + { + name: "negative size", + hash: fullHash, + chunk: &database.Chunk{ChunkHash: fullHash, Size: -1}, + want: errNegativeChunkLength, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + db, repos := craftedSnapshotDB(t) + + if tt.chunk == nil { + // A crafted database need not satisfy its foreign keys. + _, err := db.Conn().ExecContext(ctx, "PRAGMA foreign_keys = OFF") + require.NoError(t, err) + } else { + require.NoError(t, repos.Chunks.Create(ctx, nil, tt.chunk)) + } + + file := craftedFile(t, repos, tt.hash.String()) + + v := NewForTesting(nil) + v.Fs = afero.NewMemMapFs() + require.NoError(t, afero.WriteFile(v.Fs, "/restore/f", + []byte(restoredFileContent), 0o600)) + + _, err := v.verifyFile(ctx, repos, file, "/restore/f") + require.ErrorIs(t, err, tt.want) + }) + } +} diff --git a/internal/vaultik/restore_metadata_test.go b/internal/vaultik/restore_metadata_test.go new file mode 100644 index 0000000..3264e52 --- /dev/null +++ b/internal/vaultik/restore_metadata_test.go @@ -0,0 +1,349 @@ +package vaultik //nolint:testpackage // drives unexported restore internals + +import ( + "context" + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/types" +) + +// These tests check that restore applies each entry's owner, mode and +// mtime in an order that keeps them. + +const ( + readOnlyDirMode = uint32(os.ModeDir | 0o555) + unsearchableMode = uint32(os.ModeDir | 0o600) + plainDirMode = uint32(os.ModeDir | 0o755) + plainFileMode = uint32(0o644) + setuidFileMode = uint32(os.ModeSetuid | 0o755) + otherOwnerID = uint32(4321) + writableTestMode = 0o755 + symlinkTargetPath = "/nonexistent/target" + memTargetDir = "/restore" + + // Owner bits a normal user needs on a directory to create an entry + // in it, and to change an entry in it. + ownerWriteAndSearch = os.FileMode(0o300) + ownerSearch = os.FileMode(0o100) +) + +// normalUserFs refuses what the kernel refuses a normal user. make test +// runs as root, which a read-only or unsearchable directory does not +// stop, so without it the tests below could not fail there. Creating an +// entry needs owner write and search on the directory holding it; +// changing an entry's mode or times needs owner search. Only that one +// directory is checked, not every ancestor. +type normalUserFs struct { + afero.Fs +} + +//nolint:ireturn // afero.Fs.OpenFile is defined to return the interface +func (fs normalUserFs) OpenFile( + name string, flag int, perm os.FileMode, +) (afero.File, error) { + if flag&os.O_CREATE != 0 { + err := fs.checkParent(name, ownerWriteAndSearch) + if err != nil { + return nil, err + } + } + + return fs.Fs.OpenFile(name, flag, perm) +} + +func (fs normalUserFs) MkdirAll(path string, perm os.FileMode) error { + _, err := fs.Stat(path) + if err != nil { + err = fs.checkParent(path, ownerWriteAndSearch) + if err != nil { + return err + } + } + + return fs.Fs.MkdirAll(path, perm) +} + +func (fs normalUserFs) Chmod(name string, mode os.FileMode) error { + err := fs.checkParent(name, ownerSearch) + if err != nil { + return err + } + + return fs.Fs.Chmod(name, mode) +} + +func (fs normalUserFs) Chtimes(name string, atime, mtime time.Time) error { + err := fs.checkParent(name, ownerSearch) + if err != nil { + return err + } + + return fs.Fs.Chtimes(name, atime, mtime) +} + +// checkParent returns a permission error when the directory holding name +// exists and its owner bits lack any of need. +func (fs normalUserFs) checkParent(name string, need os.FileMode) error { + info, err := fs.Stat(filepath.Dir(name)) + if err == nil && info.Mode().Perm()&need != need { + return &os.PathError{Op: "access", Path: name, Err: os.ErrPermission} + } + + return nil +} + +// TestRestoreFillsReadOnlyDirectory checks that a read-only directory +// still receives the entries inside it, and ends with its stored mode. +func TestRestoreFillsReadOnlyDirectory(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + + rows, repos := makeFiles(ctx, t, []*database.File{ + {Path: "/ro", Mode: readOnlyDirMode}, + {Path: "/ro/file", Mode: plainFileMode}, + {Path: "/ro/sub", Mode: readOnlyDirMode}, + {Path: "/ro/sub/file", Mode: plainFileMode}, + }) + + fs := afero.NewMemMapFs() + v := newContainmentVaultik(ctx, normalUserFs{Fs: fs}) + _, err := v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: memTargetDir}, nil, nil) + require.NoError(t, err) + + for _, path := range []string{"/ro/file", "/ro/sub/file"} { + _, err := fs.Stat(filepath.Join(memTargetDir, path)) + require.NoErrorf(t, err, "file inside a read-only directory: %s", path) + } + + for _, dir := range []string{"/ro", "/ro/sub"} { + info, err := fs.Stat(filepath.Join(memTargetDir, dir)) + require.NoError(t, err) + assert.Equalf(t, os.FileMode(0o555), info.Mode().Perm(), "mode of %s", dir) + } +} + +// TestRestoreKeepsNonEmptyDirectoryMTime checks that a directory keeps +// its stored mtime although entries were written into it. It runs on the +// real filesystem, where writing an entry changes its directory's mtime. +func TestRestoreKeepsNonEmptyDirectoryMTime(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + targetDir := t.TempDir() + mtime := time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC) + + rows, repos := makeFiles(ctx, t, []*database.File{ + {Path: "/dir", Mode: plainDirMode, MTime: mtime}, + {Path: "/dir/file", Mode: plainFileMode, MTime: mtime}, + }) + + v := newContainmentVaultik(ctx, afero.NewOsFs()) + _, err := v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: targetDir}, nil, nil) + require.NoError(t, err) + + info, err := os.Stat(filepath.Join(targetDir, "dir")) + require.NoError(t, err) + assert.Truef(t, info.ModTime().Equal(mtime), + "directory mtime is %s, stored %s", info.ModTime(), mtime) +} + +// TestRestoreFinishesChildBeforeUnsearchableParent checks that a +// directory inside one whose stored mode denies search still gets its +// own stored mode and mtime. +func TestRestoreFinishesChildBeforeUnsearchableParent(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + mtime := time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC) + + rows, repos := makeFiles(ctx, t, []*database.File{ + {Path: "/locked", Mode: unsearchableMode, MTime: mtime}, + {Path: "/locked/sub", Mode: plainDirMode, MTime: mtime}, + }) + + fs := afero.NewMemMapFs() + v := newContainmentVaultik(ctx, normalUserFs{Fs: fs}) + _, err := v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: memTargetDir}, nil, nil) + require.NoError(t, err) + + info, err := fs.Stat(filepath.Join(memTargetDir, "locked")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + + info, err = fs.Stat(filepath.Join(memTargetDir, "locked", "sub")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o755), info.Mode().Perm()) + assert.Truef(t, info.ModTime().Equal(mtime), + "mtime of sub is %s, stored %s", info.ModTime(), mtime) +} + +// TestRestoreLeavesSymlinkedDirectoryTargetAlone checks that a directory +// whose place a later entry takes with a symlink does not hand its stored +// owner, mode and mtime to whatever the symlink points at. "/d" and "/d/" +// are different stored paths for the same place on disk. +func TestRestoreLeavesSymlinkedDirectoryTargetAlone(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + tempDir := t.TempDir() + targetDir := filepath.Join(tempDir, "target") + outsideDir := filepath.Join(tempDir, "outside") + require.NoError(t, os.Mkdir(outsideDir, writableTestMode)) + + before, err := os.Stat(outsideDir) + require.NoError(t, err) + + mtime := time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC) + + rows, repos := makeFiles(ctx, t, []*database.File{ + { + Path: "/d", + Mode: readOnlyDirMode, + UID: otherOwnerID, + GID: otherOwnerID, + MTime: mtime, + }, + {Path: "/d/", LinkTarget: types.FilePath(outsideDir), MTime: mtime}, + }) + + v := newContainmentVaultik(ctx, afero.NewOsFs()) + _, err = v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: targetDir}, nil, nil) + require.NoError(t, err) + + after, err := os.Stat(outsideDir) + require.NoError(t, err) + assert.Equal(t, before.Mode(), after.Mode()) + assert.Truef(t, after.ModTime().Equal(before.ModTime()), + "mtime changed from %s to %s", before.ModTime(), after.ModTime()) + + beforeOwner, ok := before.Sys().(*syscall.Stat_t) + require.True(t, ok) + + afterOwner, ok := after.Sys().(*syscall.Stat_t) + require.True(t, ok) + assert.Equal(t, beforeOwner.Uid, afterOwner.Uid) + assert.Equal(t, beforeOwner.Gid, afterOwner.Gid) +} + +// TestRestoreKeepsSetuidThroughChown checks that a setuid file keeps the +// bit when restore changes its owner. Linux clears setuid on any chown of +// a regular file, even one to its current owner, so the file is recorded +// with the current user as owner and the session is told it runs as +// root: the chown then needs no privilege. +func TestRestoreKeepsSetuidThroughChown(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + targetDir := t.TempDir() + + info, err := os.Stat(targetDir) + require.NoError(t, err) + + owner, ok := info.Sys().(*syscall.Stat_t) + require.True(t, ok) + + rows, repos := makeFiles(ctx, t, []*database.File{{ + Path: "/suid", + Mode: setuidFileMode, + UID: owner.Uid, + GID: owner.Gid, + MTime: time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC), + }}) + + session := &restoreSession{ + v: newContainmentVaultik(ctx, afero.NewOsFs()), + ctx: ctx, + repos: repos, + opts: &RestoreOptions{TargetDir: targetDir}, + result: &RestoreResult{}, + runningAsRoot: true, + } + require.NoError(t, session.restoreFile(rows[0])) + + info, err = os.Stat(filepath.Join(targetDir, "suid")) + require.NoError(t, err) + assert.Equal(t, os.FileMode(setuidFileMode), + info.Mode()&(os.ModeSetuid|os.ModePerm)) +} + +// TestRestoreSetsSymlinkMTime checks that a restored symlink gets its +// stored mtime on the link itself. The link dangles, so a call that +// follows it would fail. +func TestRestoreSetsSymlinkMTime(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + targetDir := t.TempDir() + mtime := time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC) + + rows, repos := makeFiles(ctx, t, []*database.File{{ + Path: "/link", + LinkTarget: types.FilePath(symlinkTargetPath), + MTime: mtime, + }}) + + v := newContainmentVaultik(ctx, afero.NewOsFs()) + _, err := v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: targetDir}, nil, nil) + require.NoError(t, err) + + info, err := os.Lstat(filepath.Join(targetDir, "link")) + require.NoError(t, err) + assert.Truef(t, info.ModTime().Equal(mtime), + "symlink mtime is %s, stored %s", info.ModTime(), mtime) +} + +// TestRestoreSetsSymlinkOwnerAsRoot checks that a symlink restored as +// root gets its stored owner on the link itself. +func TestRestoreSetsSymlinkOwnerAsRoot(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + if os.Geteuid() != 0 { + t.Skip("giving a file to another user needs root") + } + + ctx := context.Background() + targetDir := t.TempDir() + + rows, repos := makeFiles(ctx, t, []*database.File{{ + Path: "/link", + LinkTarget: types.FilePath(symlinkTargetPath), + UID: otherOwnerID, + GID: otherOwnerID, + MTime: time.Date(2001, time.February, 3, 4, 5, 6, 0, time.UTC), + }}) + + v := newContainmentVaultik(ctx, afero.NewOsFs()) + _, err := v.restoreAllFiles(rows, repos, + &RestoreOptions{TargetDir: targetDir}, nil, nil) + require.NoError(t, err) + + info, err := os.Lstat(filepath.Join(targetDir, "link")) + require.NoError(t, err) + + owner, ok := info.Sys().(*syscall.Stat_t) + require.True(t, ok) + assert.Equal(t, otherOwnerID, owner.Uid) + assert.Equal(t, otherOwnerID, owner.Gid) +} diff --git a/internal/vaultik/restore_ownership_warning_test.go b/internal/vaultik/restore_ownership_warning_test.go new file mode 100644 index 0000000..9c7353a --- /dev/null +++ b/internal/vaultik/restore_ownership_warning_test.go @@ -0,0 +1,131 @@ +package vaultik //nolint:testpackage // calls the unexported ownership check + +import ( + "bytes" + "context" + "os" + "strings" + "syscall" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/ui" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/316: a +// restore by a normal user warns that ownership was not preserved only +// when some restored entry has another owner or group on disk than the +// snapshot records. + +const ownershipWarning = "did not preserve file ownership" + +// TestOwnershipWarningSilentWhenEntriesMatch checks that a restore whose +// entries all end up with their recorded owner and group prints no +// warning. +func TestOwnershipWarningSilentWhenEntriesMatch(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + targetDir := t.TempDir() + owner := ownerOf(t, targetDir) + + out := restoreAsNormalUser(t, targetDir, []*database.File{ + {Path: "/a", Mode: plainFileMode, UID: owner.Uid, GID: owner.Gid}, + {Path: "/b", Mode: plainFileMode, UID: owner.Uid, GID: owner.Gid}, + }) + + assert.Empty(t, out) +} + +// TestOwnershipWarningWhenOwnerDiffers checks that the warning is printed +// when an entry recorded with another owner is restored owned by the +// restoring user, even though its group matches the recorded one. +func TestOwnershipWarningWhenOwnerDiffers(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + targetDir := t.TempDir() + owner := ownerOf(t, targetDir) + + out := restoreAsNormalUser(t, targetDir, []*database.File{ + {Path: "/a", Mode: plainFileMode, UID: otherOwnerID, GID: owner.Gid}, + }) + + assert.Equal(t, 1, strings.Count(out, ownershipWarning), out) +} + +// TestOwnershipWarningWhenDirectoryGivesItsGroup checks that the warning +// is printed, once, when entries recorded with the restoring user's +// owner and group take another group from the setgid directory they are +// restored into, as every new entry takes its directory's group on +// macOS. +func TestOwnershipWarningWhenDirectoryGivesItsGroup(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + if os.Geteuid() != 0 { + t.Skip("giving a directory to another group needs root") + } + + targetDir := t.TempDir() + user := ownerOf(t, targetDir) + + require.NoError(t, os.Chown(targetDir, -1, int(otherOwnerID))) + require.NoError(t, os.Chmod(targetDir, os.ModeSetgid|writableTestMode)) + + out := restoreAsNormalUser(t, targetDir, []*database.File{ + {Path: "/a", Mode: plainFileMode, UID: user.Uid, GID: user.Gid}, + {Path: "/b", Mode: plainFileMode, UID: user.Uid, GID: user.Gid}, + }) + + assert.Equal(t, 1, strings.Count(out, ownershipWarning), out) +} + +// ownerOf returns the owner and group path has on disk. +func ownerOf(t *testing.T, path string) *syscall.Stat_t { + t.Helper() + + info, err := os.Lstat(path) + require.NoError(t, err) + + owner, ok := info.Sys().(*syscall.Stat_t) + require.True(t, ok) + + return owner +} + +// restoreAsNormalUser restores rows, all empty regular files, into +// targetDir without changing any owner or group, as restore does for a +// normal user, and returns what warnIfOwnershipNotPreserved prints. +func restoreAsNormalUser( + t *testing.T, targetDir string, rows []*database.File, +) string { + t.Helper() + + ctx := context.Background() + rows, repos := makeFiles(ctx, t, rows) + + var out bytes.Buffer + + v := newContainmentVaultik(ctx, afero.NewOsFs()) + v.UI = ui.NewWithColor(&out, false) + + session := &restoreSession{ + v: v, + ctx: ctx, + repos: repos, + opts: &RestoreOptions{TargetDir: targetDir}, + result: &RestoreResult{}, + } + for _, row := range rows { + require.NoError(t, session.restoreFile(row)) + } + + v.warnIfOwnershipNotPreserved(rows, targetDir) + + return out.String() +} diff --git a/internal/vaultik/restore_perms_test.go b/internal/vaultik/restore_perms_test.go index 9dbcfc5..837aa8d 100644 --- a/internal/vaultik/restore_perms_test.go +++ b/internal/vaultik/restore_perms_test.go @@ -107,7 +107,7 @@ func backupOneFile( require.NoError(t, afero.WriteFile(fs, srcPath, content, mode)) require.NoError(t, fs.Chmod(srcPath, mode)) - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") storer, err := storage.NewFileStorer(storeDir) diff --git a/internal/vaultik/restore_plan.go b/internal/vaultik/restore_plan.go index 8ec0f1f..24b52d5 100644 --- a/internal/vaultik/restore_plan.go +++ b/internal/vaultik/restore_plan.go @@ -31,7 +31,8 @@ var ( // with no further downloads. // - blobFiles: for each blob, the set of pending files referencing // it. Used to short-circuit "when this blob lands, which files -// become ready" without a global scan. +// become ready" without a global scan, and by the sweeper to tell +// whether a cached blob is still needed. type restorePlan struct { fileBlobs map[types.FileID]map[string]struct{} blobFiles map[string]map[types.FileID]struct{} @@ -41,20 +42,25 @@ type restorePlan struct { // newRestorePlan builds the file→blob index for the given files. Files // whose chunks reference no blobs (symlinks, directories) start in the -// ready queue immediately. +// ready queue immediately. A file with a chunk that no blob holds cannot +// be restored: it is left out of the plan and returned, by ID, with the +// reason. func newRestorePlan( ctx context.Context, repos *database.Repositories, files []*database.File, chunkToBlobMap map[string]*database.BlobChunk, blobIDToHash map[string]string, -) (*restorePlan, error) { +) (*restorePlan, map[types.FileID]error, error) { p := &restorePlan{ fileBlobs: make(map[types.FileID]map[string]struct{}, len(files)), blobFiles: make(map[string]map[types.FileID]struct{}), ready: make([]types.FileID, 0, len(files)), cached: make(map[string]struct{}), } + unplanned := make(map[types.FileID]error) + +nextFile: for _, f := range files { if f.IsSymlink() || f.Mode&uint32(os.ModeDir) != 0 { // No chunks to fetch — restore can run immediately. @@ -66,7 +72,7 @@ func newRestorePlan( fileChunks, err := repos.FileChunks.GetByFileID(ctx, f.ID) if err != nil { - return nil, fmt.Errorf("planning %s: %w", f.Path, err) + return nil, nil, fmt.Errorf("planning %s: %w", f.Path, err) } blobs := make(map[string]struct{}) @@ -74,14 +80,18 @@ func newRestorePlan( for _, fc := range fileChunks { bc, ok := chunkToBlobMap[fc.ChunkHash.String()] if !ok { - return nil, fmt.Errorf("planning %s: %w: %s", - f.Path, errPlanChunkMissing, fc.ChunkHash.String()[:16]) + unplanned[f.ID] = fmt.Errorf("%w: %s", + errPlanChunkMissing, shortHash(fc.ChunkHash.String())) + + continue nextFile } hash, ok := blobIDToHash[bc.BlobID.String()] if !ok { - return nil, fmt.Errorf("planning %s: %w: %s", - f.Path, errPlanBlobIDMissing, bc.BlobID) + unplanned[f.ID] = fmt.Errorf("%w: %s", + errPlanBlobIDMissing, bc.BlobID) + + continue nextFile } blobs[hash] = struct{}{} @@ -103,7 +113,7 @@ func newRestorePlan( } } - return p, nil + return p, unplanned, nil } // markBlobCached records that the named blob is now resident in the @@ -214,6 +224,26 @@ func (p *restorePlan) blobsNeeded(fileID types.FileID) []string { return out } +// filesReferencingBlob returns the pending files that reference the +// named blob, in any order. The result is a copy, so the caller may +// finishFile each of them while ranging over it. +func (p *restorePlan) filesReferencingBlob(blobHash string) []types.FileID { + files := p.blobFiles[blobHash] + + out := make([]types.FileID, 0, len(files)) + for id := range files { + out = append(out, id) + } + + return out +} + +// pendingFileUsesBlob reports whether any pending file references the +// named blob, whether or not the blob is cached. +func (p *restorePlan) pendingFileUsesBlob(blobHash string) bool { + return len(p.blobFiles[blobHash]) > 0 +} + // hasPending reports whether any unfinished files remain. func (p *restorePlan) hasPending() bool { return len(p.fileBlobs) > 0 diff --git a/internal/vaultik/restore_plan_test.go b/internal/vaultik/restore_plan_test.go index ce23200..0306717 100644 --- a/internal/vaultik/restore_plan_test.go +++ b/internal/vaultik/restore_plan_test.go @@ -63,15 +63,6 @@ func TestRunRestoreLoopFailsOnAbandonedFiles(t *testing.T) { t.Cleanup(func() { _ = cache.Close() }) - v := &Vaultik{ctx: ctx} - session := &restoreSession{ - v: v, - ctx: ctx, - repos: repos, - sweeper: newRestoreSweeper(ctx, repos, cache, 1), - result: &RestoreResult{}, - } - // A file that is still pending but whose uncached-blob set is empty // and which was never queued as ready: the loop can neither restore // nor download it. This is the abandonment the guard must catch. @@ -83,6 +74,15 @@ func TestRunRestoreLoopFailsOnAbandonedFiles(t *testing.T) { cached: map[string]struct{}{}, } + v := &Vaultik{ctx: ctx} + session := &restoreSession{ + v: v, + ctx: ctx, + repos: repos, + sweeper: newRestoreSweeper(plan, cache, 1), + result: &RestoreResult{}, + } + err = v.runRestoreLoop(session, plan, map[types.FileID]*database.File{}, 0) require.ErrorIs(t, err, errRestoreIncomplete) } diff --git a/internal/vaultik/restore_skip_errors_test.go b/internal/vaultik/restore_skip_errors_test.go new file mode 100644 index 0000000..5de3e2b --- /dev/null +++ b/internal/vaultik/restore_skip_errors_test.go @@ -0,0 +1,485 @@ +package vaultik_test + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// A file no larger than the chunker's minimum chunk size (a quarter of +// faultChunkSize) is stored as one chunk, so it lives in exactly one blob. +// More of them than fit in faultMaxBlobSize make the snapshot span two +// blobs. +const ( + missingBlobFileBytes = int(faultChunkSize / 4) + missingBlobFileCount = 20 +) + +// missingBlobBackup is a snapshot of single-chunk files spread over two +// blobs, with one of those blobs lost: deleted from the store, or missing +// from the snapshot metadata. +type missingBlobBackup struct { + fs afero.Fs + cfg *config.Config + storer storage.Storer + snapshotID string + restoreDir string + // files holds the original content by source path. + files map[string][]byte + // lost holds the source paths whose chunk is in the lost blob. + lost map[string]bool +} + +// TestRestoreSkipErrorsSkipsFilesOfMissingBlob restores with SkipErrors +// after one blob of a two-blob snapshot was deleted from the store. +func TestRestoreSkipErrorsSkipsFilesOfMissingBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup := backupThenDeleteOneBlob(ctx, t) + out := assertRestoreSkipsLostFiles(ctx, t, backup) + + assertLostFilesCountedNotListed(t, backup, out) +} + +// TestRestoreSkipErrorsReportsUnreadableBlobOnce restores with SkipErrors +// after one blob of a two-blob snapshot was overwritten with other bytes +// of the same size. The blob must be reported once, by its hash, as not a +// valid age stream, without quoting its bytes, and its files must be +// counted, not listed. +func TestRestoreSkipErrorsReportsUnreadableBlobOnce(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup, lostBlob := backupThenOverwriteOneBlob(ctx, t) + out := assertRestoreSkipsLostFiles(ctx, t, backup) + + assert.Equal(t, 1, strings.Count(out, "not a valid age stream"), out) + assert.Contains(t, out, lostBlob[:16]) + assert.NotContains(t, out, overwriteBlobPattern) + assertLostFilesCountedNotListed(t, backup, out) +} + +// TestRestoreSkipErrorsSkipsFilesWithChunkInNoBlob restores with +// SkipErrors a snapshot whose metadata lists chunks that no blob holds, as +// earlier backup defects left behind. Each such file fails for its own +// reason, so each is listed. +func TestRestoreSkipErrorsSkipsFilesWithChunkInNoBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup := backupThenDropOneBlobFromMetadata(ctx, t) + out := assertRestoreSkipsLostFiles(ctx, t, backup) + + for path := range backup.lost { + assert.Containsf(t, out, path, "%s must be reported", path) + } +} + +// assertLostFilesCountedNotListed checks that the restore output out +// counts the files of the lost blob and names none of them. +func assertLostFilesCountedNotListed( + t *testing.T, backup *missingBlobBackup, out string, +) { + t.Helper() + + assert.Contains(t, out, fmt.Sprintf( + "%d of them need a blob that could not be read (1 blob(s) in all)", + len(backup.lost))) + + for path := range backup.lost { + assert.NotContainsf(t, out, path, + "%s needs the lost blob and must be counted, not listed", path) + } +} + +// assertRestoreSkipsLostFiles restores backup with SkipErrors and returns +// what it printed. Every file stored in the lost blob must be left +// absent, every other file must be restored intact, and Restore must +// still return an error. +func assertRestoreSkipsLostFiles( + ctx context.Context, t *testing.T, backup *missingBlobBackup, +) string { + t.Helper() + + var out bytes.Buffer + + v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, backup.fs) + v.UI = ui.NewWithColor(&out, false) + + err := v.Restore(&vaultik.RestoreOptions{ + SnapshotID: backup.snapshotID, + TargetDir: backup.restoreDir, + SkipErrors: true, + }) + + require.Error(t, err, "restore must fail when files were skipped") + assert.Contains(t, err.Error(), + fmt.Sprintf("%d file(s) failed to restore", len(backup.lost))) + + for path, content := range backup.files { + restored := filepath.Join(backup.restoreDir, path) + + if backup.lost[path] { + assert.NoFileExists(t, restored) + + continue + } + + got, err := afero.ReadFile(backup.fs, restored) + require.NoErrorf(t, err, "%s does not need the lost blob", path) + assert.Equalf(t, content, got, "%s restored with wrong content", path) + } + + return out.String() +} + +// TestRestoreSkipErrorsVerifyChecksOnlyRestoredFiles restores with +// SkipErrors and Verify after one blob of a two-blob snapshot was +// deleted. Verification must check only the files that were written, so +// a file of the deleted blob is reported as failed to restore and not +// also as failing verification, and Restore must still return an error. +func TestRestoreSkipErrorsVerifyChecksOnlyRestoredFiles(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup := backupThenDeleteOneBlob(ctx, t) + + var out bytes.Buffer + + v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, backup.fs) + v.UI = ui.NewWithColor(&out, false) + + err := v.Restore(&vaultik.RestoreOptions{ + SnapshotID: backup.snapshotID, + TargetDir: backup.restoreDir, + Verify: true, + SkipErrors: true, + }) + + require.Error(t, err, "restore must fail when files were skipped") + assert.Contains(t, err.Error(), + fmt.Sprintf("%d file(s) failed to restore", len(backup.lost))) + + written := len(backup.files) - len(backup.lost) + + assert.Contains(t, out.String(), fmt.Sprintf("Verifying %d files", written)) + assert.Contains(t, out.String(), fmt.Sprintf("Verified %d files", written)) + assert.NotContains(t, out.String(), "Verification failed") +} + +// TestRestoreSkipErrorsVerifyReportsFailuresApart restores with +// SkipErrors and Verify after one blob of a two-blob snapshot was +// deleted, while one file that does restore is written one byte too long. +// The restore warning must count the files of the deleted blob without +// listing them, the verification summary must list only the long file, +// once, and Restore must return an error. +func TestRestoreSkipErrorsVerifyReportsFailuresApart(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup := backupThenDeleteOneBlob(ctx, t) + + var long string + + for path := range backup.files { + if !backup.lost[path] { + long = path + + break + } + } + + var out bytes.Buffer + + fs := trailingByteFs{Fs: backup.fs, suffix: long} + v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, fs) + v.UI = ui.NewWithColor(&out, false) + + err := v.Restore(&vaultik.RestoreOptions{ + SnapshotID: backup.snapshotID, + TargetDir: backup.restoreDir, + Verify: true, + SkipErrors: true, + }) + require.Error(t, err, "restore must fail when files failed") + + _, afterWarning, found := strings.Cut(out.String(), + fmt.Sprintf("%d file(s) failed to restore:", len(backup.lost))) + require.Truef(t, found, "no restore warning in:\n%s", out.String()) + + warning, summary, found := strings.Cut(afterWarning, + "Verification failed: 1 files did not match") + require.Truef(t, found, "no verification summary in:\n%s", out.String()) + + assertLostFilesCountedNotListed(t, backup, warning) + + for path := range backup.lost { + assert.NotContainsf(t, summary, path, + "%s was not restored and must not fail verification", path) + } + + assert.NotContainsf(t, warning, long, + "%s was restored and must not be listed as failed to restore", long) + assert.Equalf(t, 1, strings.Count(summary, long), + "%s must be listed once as failing verification", long) +} + +// trailingByteFs appends one byte, on close, to the file it opens whose +// path ends in suffix, so that file is restored one byte too long and +// fails verification. +type trailingByteFs struct { + afero.Fs + + suffix string +} + +//nolint:ireturn // afero.Fs.OpenFile is defined to return the interface +func (fs trailingByteFs) OpenFile( + name string, flag int, perm os.FileMode, +) (afero.File, error) { + f, err := fs.Fs.OpenFile(name, flag, perm) + if err != nil || !strings.HasSuffix(name, fs.suffix) { + return f, err + } + + return trailingByteFile{File: f}, nil +} + +type trailingByteFile struct { + afero.File +} + +func (f trailingByteFile) Close() error { + _, _ = f.Write([]byte{'x'}) + + return f.File.Close() +} + +// TestRestoreMissingBlobAbortsWithoutSkipErrors checks that a deleted blob +// still ends the restore with an error when SkipErrors is not set, and +// that the error names the blob once. +func TestRestoreMissingBlobAbortsWithoutSkipErrors(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup := backupThenDeleteOneBlob(ctx, t) + + v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, backup.fs) + + err := v.Restore(&vaultik.RestoreOptions{ + SnapshotID: backup.snapshotID, + TargetDir: backup.restoreDir, + }) + + require.ErrorIs(t, err, storage.ErrNotFound) + assert.Equal(t, 1, strings.Count(err.Error(), "downloading blob"), + err.Error()) +} + +// TestRestoreChunkInNoBlobAbortsWithoutSkipErrors checks that a chunk held +// by no blob still ends the restore, before any file is written, when +// SkipErrors is not set. +func TestRestoreChunkInNoBlobAbortsWithoutSkipErrors(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + backup := backupThenDropOneBlobFromMetadata(ctx, t) + + v := newReaderVaultik(ctx, backup.cfg, backup.storer, nil, backup.fs) + + err := v.Restore(&vaultik.RestoreOptions{ + SnapshotID: backup.snapshotID, + TargetDir: backup.restoreDir, + }) + + require.ErrorContains(t, err, "chunk missing from blob map") + + for path := range backup.files { + assert.NoFileExists(t, filepath.Join(backup.restoreDir, path)) + } +} + +// backupThenDeleteOneBlob backs up missingBlobFileCount single-chunk +// files, then deletes from the store the blob holding the first of them. +func backupThenDeleteOneBlob( + ctx context.Context, t *testing.T, +) *missingBlobBackup { + t.Helper() + + backup, db, lostBlob := backupSingleChunkFiles(ctx, t) + require.NoError(t, db.Close()) + + require.NoError(t, backup.storer.Delete(ctx, fmt.Sprintf( + "blobs/%s/%s/%s", lostBlob[:2], lostBlob[2:4], lostBlob))) + + return backup +} + +// overwriteBlobPattern repeats, each time followed by a newline, through +// the bytes that backupThenOverwriteOneBlob writes over a blob. age's own +// error quotes the data's first line only when it reads a whole line. +const overwriteBlobPattern = "overwritten-blob-bytes-" + +// backupThenOverwriteOneBlob backs up missingBlobFileCount single-chunk +// files, then overwrites the blob holding the first of them with as many +// bytes of overwriteBlobPattern lines. It also returns that blob's hash. +func backupThenOverwriteOneBlob( + ctx context.Context, t *testing.T, +) (*missingBlobBackup, string) { + t.Helper() + + backup, db, lostBlob := backupSingleChunkFiles(ctx, t) + require.NoError(t, db.Close()) + + key := fmt.Sprintf("blobs/%s/%s/%s", lostBlob[:2], lostBlob[2:4], lostBlob) + + info, err := backup.storer.Stat(ctx, key) + require.NoError(t, err) + + line := overwriteBlobPattern + "\n" + pattern := bytes.Repeat([]byte(line), int(info.Size)/len(line)+1) + require.NoError(t, backup.storer.Put( + ctx, key, bytes.NewReader(pattern[:info.Size]))) + + return backup, lostBlob +} + +// backupThenDropOneBlobFromMetadata backs up missingBlobFileCount +// single-chunk files, then removes the blob holding the first of them from +// the snapshot and exports the snapshot metadata again. The exported +// metadata then lists chunks that no blob holds. +func backupThenDropOneBlobFromMetadata( + ctx context.Context, t *testing.T, +) *missingBlobBackup { + t.Helper() + + backup, db, lostBlob := backupSingleChunkFiles(ctx, t) + + // The uploads row refers to the blob row, so it would keep the export + // from deleting it. + for _, query := range []string{ + "DELETE FROM snapshot_blobs WHERE blob_hash = ?", + "DELETE FROM uploads WHERE blob_hash = ?", + } { + _, err := db.Conn().ExecContext(ctx, query, lostBlob) + require.NoError(t, err) + } + + sm := newFaultSnapshotManager( + backup.fs, backup.storer, backup.cfg, database.NewRepositories(db)) + require.NoError(t, + sm.ExportSnapshotMetadata(ctx, db.Path(), backup.snapshotID)) + require.NoError(t, db.Close()) + + return backup +} + +// backupSingleChunkFiles backs up missingBlobFileCount single-chunk files. +// It returns the backup, with lost naming the files stored in the same +// blob as the first of them, the still open local index, and the hash of +// that blob. +func backupSingleChunkFiles( + ctx context.Context, t *testing.T, +) (*missingBlobBackup, *database.DB, string) { + t.Helper() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + dbPath := filepath.Join(tempDir, "index.sqlite") + cfg := faultTestConfig() + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + + files := make(map[string][]byte, missingBlobFileCount) + + for i := range missingBlobFileCount { + path := filepath.Join(dataDir, fmt.Sprintf("file-%02d.bin", i)) + files[path] = bytesPattern( + fmt.Sprintf("file-%02d-", i), missingBlobFileBytes) + require.NoError(t, afero.WriteFile(fs, path, files[path], 0o644)) + } + + storer, err := storage.NewFileStorer(t.TempDir()) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + + id := fullFaultBackup( + ctx, t, fs, storer, cfg, repos, dataDir, dbPath, "missingblob") + + blobOfFile := make(map[string]string, len(files)) + for path := range files { + blobOfFile[path] = blobHashOfSingleChunkFile(ctx, t, repos, path) + } + + lostBlob := blobOfFile[filepath.Join(dataDir, "file-00.bin")] + lost := make(map[string]bool) + + for path, hash := range blobOfFile { + if hash == lostBlob { + lost[path] = true + } + } + + require.Less(t, len(lost), len(files), + "the snapshot must span more than one blob") + + return &missingBlobBackup{ + fs: fs, + cfg: cfg, + storer: storer, + snapshotID: id, + restoreDir: filepath.Join(tempDir, "restored"), + files: files, + lost: lost, + }, db, lostBlob +} + +// blobHashOfSingleChunkFile returns the hash of the blob holding the one +// chunk of the file at path, as recorded in the local index. +func blobHashOfSingleChunkFile( + ctx context.Context, t *testing.T, + repos *database.Repositories, path string, +) string { + t.Helper() + + chunks, err := repos.FileChunks.GetByPath(ctx, path) + require.NoError(t, err) + require.Lenf(t, chunks, 1, "%s must be a single chunk", path) + + blobChunk, err := repos.BlobChunks.GetByChunkHash( + ctx, chunks[0].ChunkHash.String()) + require.NoError(t, err) + require.NotNilf(t, blobChunk, "chunk of %s is in no blob", path) + + blob, err := repos.Blobs.GetByID(ctx, blobChunk.BlobID.String()) + require.NoError(t, err) + + return blob.Hash.String() +} diff --git a/internal/vaultik/restore_snapshot_identity_test.go b/internal/vaultik/restore_snapshot_identity_test.go index 5cdedd4..c7e6dea 100644 --- a/internal/vaultik/restore_snapshot_identity_test.go +++ b/internal/vaultik/restore_snapshot_identity_test.go @@ -29,7 +29,7 @@ func TestRestoreAndDeepVerifyRejectSwappedDatabase(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() chunkSize := int64(64 * 1024) @@ -100,7 +100,7 @@ func TestDeepVerifyRejectsSwappedDatabaseWithEmptyManifest(t *testing.T) { fs := afero.NewOsFs() tempDir := t.TempDir() - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() chunkSize := int64(64 * 1024) diff --git a/internal/vaultik/restore_sweeper.go b/internal/vaultik/restore_sweeper.go index 5659f6b..004a557 100644 --- a/internal/vaultik/restore_sweeper.go +++ b/internal/vaultik/restore_sweeper.go @@ -1,46 +1,30 @@ package vaultik -import ( - "context" - "fmt" - - "sneak.berlin/go/vaultik/internal/database" - "sneak.berlin/go/vaultik/internal/log" -) - -// restoreSweeper frees cached blobs once all files that reference any of -// their chunks have been restored. It works as follows: +// restoreSweeper frees cached blobs once no file still to be restored in +// this run needs them. It works as follows: // -// 1. Callers add a file's ID to an in-memory restored set via -// fileRestored once the file is fully written to disk. -// 2. After each chunk is restored, chunkRestored accumulates a running +// 1. After each chunk is restored, chunkRestored accumulates a running // byte count. -// 3. When the accumulator crosses a threshold (one hundredth of the +// 2. When the accumulator crosses a threshold (one hundredth of the // configured blob size — so a sweep runs about a hundred times per // blob's worth of restored bytes), the sweeper iterates every key in -// the cache. For each cached blob it asks the DB which files -// reference any chunk in that blob, then compares that list against -// the in-memory restored set. If any referencing file is missing -// from the set the blob is kept; otherwise the cache entry is -// deleted. +// the cache and deletes each blob that the restore plan no longer +// needs. // -// All DB reads happen against the snapshot's temporary metadata DB, -// which is local, indexed, and not under contention — the queries are -// cheap and run at most once per blob per sweep interval. +// The plan drops a file once it is restored or has failed, and holds +// only the files this run restores, so files outside the requested paths +// never keep a blob. type restoreSweeper struct { - ctx context.Context //nolint:containedctx // ctx bound at construction by design - repos *database.Repositories + plan *restorePlan cache *blobDiskCache threshold int64 bytesAccum int64 - restored map[string]struct{} } // newRestoreSweeper returns a sweeper that triggers eviction every // `threshold` bytes restored. Callers should pass blob_size_limit/100. func newRestoreSweeper( - ctx context.Context, - repos *database.Repositories, + plan *restorePlan, cache *blobDiskCache, threshold int64, ) *restoreSweeper { @@ -49,21 +33,12 @@ func newRestoreSweeper( } return &restoreSweeper{ - ctx: ctx, - repos: repos, + plan: plan, cache: cache, threshold: threshold, - restored: make(map[string]struct{}), } } -// fileRestored records a file as fully restored. After this call, any -// blob whose only remaining references come from files in the restored -// set may be evicted on the next sweep. -func (s *restoreSweeper) fileRestored(fileID string) { - s.restored[fileID] = struct{}{} -} - // chunkRestored accounts n bytes against the sweep threshold and runs a // sweep if the threshold has been crossed since the last sweep. func (s *restoreSweeper) chunkRestored(n int64) { @@ -76,60 +51,11 @@ func (s *restoreSweeper) chunkRestored(n int64) { s.sweep() } -// sweep deletes any cached blob whose chunks are no longer referenced -// by an unrestored file. Per-blob DB failures are logged and the blob -// is kept — we'd rather hold a blob longer than risk a re-download. +// sweep deletes every cached blob that no pending file references. func (s *restoreSweeper) sweep() { for _, blobHash := range s.cache.Keys() { - needed, err := s.blobStillNeeded(blobHash) - if err != nil { - log.Debug("sweeper referencing-files query failed", - "blob_hash", blobHash[:16], "error", err) - - continue - } - - if !needed { + if !s.plan.pendingFileUsesBlob(blobHash) { s.cache.Delete(blobHash) } } } - -// blobStillNeeded returns true if any file that references a chunk in -// this blob has not yet been restored. On any error the function -// returns true — keeping the blob is always the safe answer because we -// can't prove we're done with it. -func (s *restoreSweeper) blobStillNeeded(blobHash string) (bool, error) { - rows, err := s.repos.DB().Conn().QueryContext(s.ctx, ` - SELECT DISTINCT fc.file_id - FROM file_chunks fc - JOIN blob_chunks bc ON bc.chunk_hash = fc.chunk_hash - JOIN blobs b ON b.id = bc.blob_id - WHERE b.blob_hash = ? - `, blobHash) - if err != nil { - return true, fmt.Errorf("querying referencing files: %w", err) - } - - defer func() { _ = rows.Close() }() - - for rows.Next() { - var fileID string - - err := rows.Scan(&fileID) - if err != nil { - return true, fmt.Errorf("scanning file_id: %w", err) - } - - if _, ok := s.restored[fileID]; !ok { - return true, nil - } - } - - err = rows.Err() - if err != nil { - return true, err - } - - return false, nil -} diff --git a/internal/vaultik/restore_sweeper_integration_test.go b/internal/vaultik/restore_sweeper_integration_test.go index 13cc5cc..d723bef 100644 --- a/internal/vaultik/restore_sweeper_integration_test.go +++ b/internal/vaultik/restore_sweeper_integration_test.go @@ -27,10 +27,10 @@ import ( // TestRestoreSweeperEvictsBlobs exercises the reference-counted blob // disk cache eviction during restore. // -// The scenario: 30 unique 1 MB random files plus 10 duplicates of those -// (40 files total, 30 MB of unique content) get backed up with a 10 MB -// blob_size_limit. After backup the snapshot's encrypted blobs are -// restored through Vaultik.Restore, and per-key Get counts on the +// The scenario: 30 unique 128 KiB random files plus 10 duplicates of +// those (40 files total, 3.75 MiB of unique content) get backed up with +// a 1 MiB blob_size_limit. After backup the snapshot's encrypted blobs +// are restored through Vaultik.Restore, and per-key Get counts on the // storage layer are recorded. Each blob in the snapshot MUST be // downloaded exactly once — re-downloads would mean the sweeper either // evicted a blob that was still needed (LRU regression) or that the @@ -41,7 +41,7 @@ import ( // original AND every duplicate referencing its chunks have been // restored. // buildSweeperFixture writes the source layout for the sweeper test: 30 -// unique 1 MB random files plus 10 duplicates of a random subset. The +// unique 128 KiB random files plus 10 duplicates of a random subset. The // PRNG seed is fixed so failures are reproducible; the entropy is what // matters here — the FastCDC chunker needs realistic-looking data to // pick chunk boundaries naturally. Returns the expected content by @@ -51,7 +51,7 @@ func buildSweeperFixture( ) map[string][]byte { t.Helper() - const fileSize = 1 * 1024 * 1024 + const fileSize = 128 * 1024 rng := rand.New(rand.NewSource(42)) //nolint:gosec // G404: fixture data only @@ -159,7 +159,7 @@ func runSweeperBackup( require.NoError(t, err) require.Equal(t, uniqueFiles+duplicateFiles, scanResult.FilesScanned) require.Greater(t, scanResult.BlobsCreated, 1, - "30 MB of unique data at 10 MB blob size should yield multiple blobs") + "3.75 MiB of unique data at 1 MiB blob size should yield multiple blobs") require.NoError(t, sm.CompleteSnapshot(ctx, snapshotID)) require.NoError(t, sm.ExportSnapshotMetadata(ctx, dbPath, snapshotID)) @@ -186,7 +186,7 @@ func TestRestoreSweeperEvictsBlobs(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") @@ -199,8 +199,8 @@ func TestRestoreSweeperEvictsBlobs(t *testing.T) { expected := buildSweeperFixture(t, fs, dataDir, uniqueFiles, duplicateFiles) - chunkSize := int64(64 * 1024) - maxBlobSize := int64(10 * 1024 * 1024) + chunkSize := int64(16 * 1024) + maxBlobSize := int64(1024 * 1024) storer, err := storage.NewFileStorer(storeDir) require.NoError(t, err) diff --git a/internal/vaultik/restore_sweeper_test.go b/internal/vaultik/restore_sweeper_test.go new file mode 100644 index 0000000..1f767f3 --- /dev/null +++ b/internal/vaultik/restore_sweeper_test.go @@ -0,0 +1,163 @@ +package vaultik //nolint:testpackage // reads the restore blob cache's peak size + +import ( + "context" + "fmt" + "io" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/ui" +) + +// TestRestoreFreesBlobsNoPendingFileNeeds asserts that the restore cache +// frees a blob once no file still to be restored in this run needs it. +// Every original file has a copy with the same content, so every blob +// holds chunks of copies: a restore that leaves the copies out of its +// paths, or fails on them, must not keep the blobs for them. +func TestRestoreFreesBlobsNoPendingFileNeeds(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + // Small files keep the backup and both restores quick. + const fileBytes = 16 * 1024 + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + originalsDir := filepath.Join(dataDir, "originals") + copiesDir := filepath.Join(dataDir, "copies") + storeDir := t.TempDir() + dbPath := filepath.Join(tempDir, "index.sqlite") + + originals := writeFilesWithCopies(t, fs, originalsDir, copiesDir, fileBytes) + + ctx := context.Background() + + cfg, storer, snapshotID := setupLocalityBackup( + ctx, t, fs, dataDir, storeDir, dbPath, fileBytes) + + t.Run("restore by path", func(t *testing.T) { + t.Parallel() + + restoreDir := filepath.Join(tempDir, "by-path") + + peak, err := restorePeakCachedBlobs(ctx, t, fs, cfg, storer, + &RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: restoreDir, + Paths: []string{originalsDir}, + }) + require.NoError(t, err) + + requireRestoredFiles(t, fs, restoreDir, originals) + assert.LessOrEqualf(t, peak, 1, + "peak cached blobs was %d; blobs were kept for unselected files", + peak) + }) + + t.Run("restore with failed files", func(t *testing.T) { + t.Parallel() + + restoreDir := filepath.Join(tempDir, "with-failures") + + // A regular file where the copies directory belongs makes every + // copy fail to restore. + blocker := filepath.Join(restoreDir, copiesDir) + require.NoError(t, fs.MkdirAll(filepath.Dir(blocker), 0o755)) + require.NoError(t, afero.WriteFile(fs, blocker, nil, 0o644)) + + peak, err := restorePeakCachedBlobs(ctx, t, fs, cfg, storer, + &RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: restoreDir, + SkipErrors: true, + }) + require.ErrorIs(t, err, errFilesFailedRestore) + + requireRestoredFiles(t, fs, restoreDir, originals) + assert.LessOrEqualf(t, peak, 1, + "peak cached blobs was %d; blobs were kept for failed files", peak) + }) +} + +// writeFilesWithCopies writes 15 random files of fileBytes into +// originalsDir and a copy of each into copiesDir. With +// setupLocalityBackup given the same size, each file is one chunk and the +// 15 chunks fill 3 blobs. Returns the originals' content by path. +func writeFilesWithCopies( + t *testing.T, fs afero.Fs, originalsDir, copiesDir string, fileBytes int, +) map[string][]byte { + t.Helper() + + const fileCount = 15 + + require.NoError(t, fs.MkdirAll(originalsDir, 0o755)) + require.NoError(t, fs.MkdirAll(copiesDir, 0o755)) + + originals := make(map[string][]byte, fileCount) + + for i := range fileCount { + name := fmt.Sprintf("file-%02d.bin", i) + data := randomBytes(t, fileBytes) + original := filepath.Join(originalsDir, name) + originals[original] = data + + require.NoError(t, afero.WriteFile(fs, original, data, 0o644)) + require.NoError(t, afero.WriteFile( + fs, filepath.Join(copiesDir, name), data, 0o644)) + } + + return originals +} + +// requireRestoredFiles requires every file in want to have been restored +// under restoreDir with its content intact. +func requireRestoredFiles( + t *testing.T, fs afero.Fs, restoreDir string, want map[string][]byte, +) { + t.Helper() + + for path, data := range want { + got, err := afero.ReadFile(fs, filepath.Join(restoreDir, path)) + require.NoErrorf(t, err, "file missing after restore: %s", path) + require.Equalf(t, data, got, "byte mismatch for %s", path) + } +} + +// restorePeakCachedBlobs runs a restore and returns the most blobs its +// cache held at once, together with the restore's error. +func restorePeakCachedBlobs( + ctx context.Context, t *testing.T, fs afero.Fs, + cfg *config.Config, storer storage.Storer, opts *RestoreOptions, +) (int, error) { + t.Helper() + + var cache *blobDiskCache + + v := &Vaultik{ + Config: cfg, + Storage: storer, + Fs: fs, + Stdout: io.Discard, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + restoreCacheObserver: func(c *blobDiskCache) { + cache = c + }, + } + v.SetContext(ctx) + + err := v.Restore(opts) + + require.NotNil(t, cache, "restoreCacheObserver must fire during restore") + + return cache.PeakLen(), err +} diff --git a/internal/vaultik/restore_truncated_db_test.go b/internal/vaultik/restore_truncated_db_test.go index aeedd79..4b03715 100644 --- a/internal/vaultik/restore_truncated_db_test.go +++ b/internal/vaultik/restore_truncated_db_test.go @@ -33,7 +33,7 @@ func TestRestoreRejectsTruncatedMetadataDB(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() restoreDir := filepath.Join(tempDir, "restored") dbPath := filepath.Join(tempDir, "index.sqlite") diff --git a/internal/vaultik/restore_unmatched_path_test.go b/internal/vaultik/restore_unmatched_path_test.go new file mode 100644 index 0000000..c9da298 --- /dev/null +++ b/internal/vaultik/restore_unmatched_path_test.go @@ -0,0 +1,202 @@ +package vaultik_test + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/309: a path +// given to restore that matches nothing in the snapshot is named in a +// warning and makes the restore fail, after the paths that do match are +// restored. + +func TestRestoreNamesUnmatchedPathAndRestoresTheMatchingOne(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := t.TempDir() + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + cfg := faultTestConfig() + files := writeFaultSourceTree(t, fs, dataDir) + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + id := fullFaultBackup(ctx, t, fs, store, cfg, + database.NewRepositories(db), dataDir, dbPath, "unmatched") + require.NoError(t, db.Close()) + + matched := filepath.Join(dataDir, "small.txt") + unmatched := filepath.Join(dataDir, "typo.txt") + + var out bytes.Buffer + + v := newReaderVaultik(ctx, cfg, store, nil, fs) + v.UI = ui.NewWithColor(&out, false) + + err = v.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Paths: []string{matched, unmatched}, + }) + + require.Error(t, err, "a path that matches nothing must fail the restore") + assert.Contains(t, out.String(), unmatched, + "the path that matches nothing must be named") + assert.NotContains(t, out.String(), matched, + "the path that matches must not be reported") + + got, err := afero.ReadFile(fs, filepath.Join(restoreDir, matched)) + require.NoError(t, err, "the path that matches must still be restored") + assert.Equal(t, files[matched], got) +} + +// When no requested path matches, nothing is restored and each path is +// named. One path is relative. The other goes through the symlink that +// is the snapshot's configured path, while the entries are stored under +// the directory the symlink points to. +func TestRestoreNamesEveryPathWhenNothingMatches(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const snapshotName = "linked" + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + linkDir := filepath.Join(tempDir, "srclink") + storeDir := t.TempDir() + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + + writeFaultSourceTree(t, fs, dataDir) + require.NoError(t, os.Symlink(dataDir, linkDir)) + + cfg := faultTestConfig() + cfg.IndexPath = dbPath + cfg.ChunkSize = config.Size(faultChunkSize) + cfg.Snapshots = map[string]config.SnapshotConfig{ + snapshotName: {Paths: []string{linkDir}}, + } + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, snapshotName)) + + id := localSnapshotID(ctx, t, repos, snapshotName) + require.NoError(t, db.Close()) + + throughLink := filepath.Join(linkDir, "sub") + relative := strings.TrimPrefix(filepath.Join(dataDir, "small.txt"), "/") + + var out bytes.Buffer + + reader := newReaderVaultik(ctx, cfg, store, nil, fs) + reader.UI = ui.NewWithColor(&out, false) + + err = reader.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Paths: []string{throughLink, relative}, + }) + + require.Error(t, err, "a restore that matches nothing must fail") + assert.Contains(t, out.String(), throughLink, + "the path through the symlink must be named") + assert.Contains(t, out.String(), relative, + "the relative path must be named") + + _, err = fs.Stat(restoreDir) + assert.True(t, os.IsNotExist(err), "nothing must be restored") +} + +// Without --skip-errors a damaged blob stops the restore part way. The +// path that matches nothing must still be named. +func TestRestoreNamesUnmatchedPathWhenADamagedBlobStopsIt(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := t.TempDir() + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + cfg := faultTestConfig() + + writeFaultSourceTree(t, fs, dataDir) + + inner, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + id := fullFaultBackup(ctx, t, fs, inner, cfg, + database.NewRepositories(db), dataDir, dbPath, "damaged") + require.NoError(t, db.Close()) + + damaged := faultstore.New(inner) + damaged.OnGet = func(key string) faultstore.GetFault { + if strings.HasPrefix(key, "blobs/") { + return faultstore.GetCorrupt + } + + return faultstore.GetNormal + } + + matched := filepath.Join(dataDir, "small.txt") + unmatched := filepath.Join(dataDir, "typo.txt") + + var out bytes.Buffer + + v := newReaderVaultik(ctx, cfg, damaged, nil, fs) + v.UI = ui.NewWithColor(&out, false) + + err = v.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Paths: []string{matched, unmatched}, + }) + + require.Error(t, err, "a damaged blob must stop the restore") + assert.Contains(t, err.Error(), "blob", + "the restore must stop on the damaged blob") + assert.Contains(t, out.String(), unmatched, + "the path that matches nothing must be named") +} diff --git a/internal/vaultik/restore_wrong_key_test.go b/internal/vaultik/restore_wrong_key_test.go new file mode 100644 index 0000000..05d88ba --- /dev/null +++ b/internal/vaultik/restore_wrong_key_test.go @@ -0,0 +1,161 @@ +package vaultik_test + +import ( + "bytes" + "context" + "io" + "path" + "path/filepath" + "testing" + + "filippo.io/age" + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/blobgen" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestWrongPrivateKeyError checks that restore and deep verify, given a +// valid private key the backup was not encrypted to, fail with one plain +// sentence that names where the key was configured. +func TestWrongPrivateKeyError(t *testing.T) { + t.Parallel() + + ctx := context.Background() + store := NewMockStorer() + + const snapshotID = "test-host_2026-01-01T00:00:00Z" + + remoteKey := snapshot.RemoteSnapshotKey(snapshotID) + + manifest, err := snapshot.EncodeManifest( + &snapshot.Manifest{SnapshotID: remoteKey}, 3) + require.NoError(t, err) + require.NoError(t, store.Put(ctx, + "metadata/"+remoteKey+"/manifest.json.zst", bytes.NewReader(manifest))) + + // The database is encrypted to the test recipient only. + var db bytes.Buffer + + writer, err := blobgen.NewWriter(&db, 1, []string{testAgePublicKey}) + require.NoError(t, err) + + _, err = writer.Write([]byte("snapshot database")) + require.NoError(t, err) + require.NoError(t, writer.Close()) + require.NoError(t, store.Put(ctx, + "metadata/"+remoteKey+"/db.zst.age", &db)) + + otherKey, err := age.GenerateX25519Identity() + require.NoError(t, err) + + v := &vaultik.Vaultik{ + Config: &config.Config{AgeSecretKey: otherKey.String()}, + Storage: store, + Fs: afero.NewMemMapFs(), + Stdout: io.Discard, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + v.SetContext(ctx) + + // A Config built directly has no recorded source, so the error names + // the config-file field. + const want = "cannot decrypt this snapshot: the private key in " + + "age_secret_key is not one of the keys the backup was encrypted to" + + err = v.Restore(&vaultik.RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: t.TempDir(), + }) + require.EqualError(t, err, want) + + err = v.RunDeepVerify(snapshotID, &vaultik.VerifyOptions{Deep: true}) + require.EqualError(t, err, want) +} + +// TestWrongPrivateKeyForBlobError backs up a file, then backs it up again +// from an empty local index with a second recipient added. The second +// snapshot reuses the stored blob, which stays encrypted to the first +// recipient only. With only the added key configured, restore and deep +// verify read the database but fail on the blob with one plain sentence +// that names where the key was configured. +func TestWrongPrivateKeyForBlobError(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "source") + dataPath := filepath.Join(dataDir, "data.bin") + storeDir := t.TempDir() + secondDBPath := filepath.Join(tempDir, "second.sqlite") + + chunkSize := int64(64 * 1024) + maxBlobSize := int64(512 * 1024) + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, dataPath, + bytesPattern("key-", int(chunkSize)), 0o644)) + + ctx := context.Background() + + runFileStorageBackup(ctx, t, fs, dataDir, storeDir, + filepath.Join(tempDir, "first.sqlite"), chunkSize, maxBlobSize) + + env := setupDedupBackupEnv( + ctx, t, fs, storeDir, secondDBPath, chunkSize, maxBlobSize) + + defer func() { _ = env.db.Close() }() + + addedKey, err := age.GenerateX25519Identity() + require.NoError(t, err) + + env.cfg.AgeRecipients = append(env.cfg.AgeRecipients, + addedKey.Recipient().String()) + + snapshotID, result := runDedupSnapshot(ctx, t, env.sm, env.makeScanner(), + env.cfg.Hostname, "second", dataDir, secondDBPath) + require.Zero(t, result.BlobsUploaded, + "the second backup should reuse the stored blob") + + require.NoError(t, env.db.Close()) + + blobKeys, err := env.storer.List(ctx, "blobs/") + require.NoError(t, err) + require.Len(t, blobKeys, 1) + + blobHash := path.Base(blobKeys[0]) + + env.cfg.AgeSecretKey = addedKey.String() + + v := &vaultik.Vaultik{ + Config: env.cfg, + Storage: env.storer, + Fs: fs, + Stdout: io.Discard, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + v.SetContext(ctx) + + const sentence = "cannot decrypt this blob: the private key in " + + "age_secret_key is not one of the keys the blob was encrypted to" + + // Restore names the blob by the first 16 characters of its hash. + err = v.Restore(&vaultik.RestoreOptions{ + SnapshotID: snapshotID, + TargetDir: t.TempDir(), + }) + require.EqualError(t, err, "restoring "+dataPath+": downloading blob "+ + blobHash[:16]+": "+sentence+ + " (pass --skip-errors to continue past restore failures)") + + err = v.RunDeepVerify(snapshotID, &vaultik.VerifyOptions{Deep: true}) + require.EqualError(t, err, + "blob "+blobHash+" verification failed: "+sentence) +} diff --git a/internal/vaultik/reused_blob_verify_test.go b/internal/vaultik/reused_blob_verify_test.go new file mode 100644 index 0000000..f499e0e --- /dev/null +++ b/internal/vaultik/reused_blob_verify_test.go @@ -0,0 +1,83 @@ +package vaultik_test + +import ( + "context" + "io" + "path/filepath" + "testing" + + "filippo.io/age" + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestVerifyPassesWhenBackupReusesStoredBlob backs up a file, then backs it +// up again from an empty local index, as after `database delete`, with an +// extra age recipient. The second backup builds the same blob, finds it +// already stored and skips the upload, but its own copy is larger, because +// age writes a header entry for each recipient. The second snapshot must +// record the size of the stored object, so shallow and deep verify pass. +func TestVerifyPassesWhenBackupReusesStoredBlob(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + storeDir := t.TempDir() + secondDBPath := filepath.Join(tempDir, "second.sqlite") + + chunkSize := int64(64 * 1024) + maxBlobSize := int64(512 * 1024) + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, "data.bin"), + bytesPattern("reuse-", int(chunkSize*3)), 0o644)) + + ctx := context.Background() + + runFileStorageBackup(ctx, t, fs, dataDir, storeDir, + filepath.Join(tempDir, "first.sqlite"), chunkSize, maxBlobSize) + + env := setupDedupBackupEnv( + ctx, t, fs, storeDir, secondDBPath, chunkSize, maxBlobSize) + + defer func() { _ = env.db.Close() }() + + extra, err := age.GenerateX25519Identity() + require.NoError(t, err) + + env.cfg.AgeRecipients = append(env.cfg.AgeRecipients, + extra.Recipient().String()) + + snapshotID, result := runDedupSnapshot(ctx, t, env.sm, env.makeScanner(), + env.cfg.Hostname, "second", dataDir, secondDBPath) + require.Positive(t, result.BlobsCreated) + require.Zero(t, result.BlobsUploaded, + "the second backup should find every blob already stored") + + require.NoError(t, env.db.Close()) + + verifier := &vaultik.Vaultik{ + Config: env.cfg, + Storage: env.storer, + Fs: fs, + Stdout: io.Discard, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + verifier.SetContext(ctx) + + require.NoError(t, + verifier.VerifySnapshotWithOptions(snapshotID, &vaultik.VerifyOptions{}), + "shallow verify should pass") + require.NoError(t, + verifier.VerifySnapshotWithOptions(snapshotID, + &vaultik.VerifyOptions{Deep: true}), + "deep verify should pass") +} diff --git a/internal/vaultik/same_second_rewrite_test.go b/internal/vaultik/same_second_rewrite_test.go new file mode 100644 index 0000000..80464f0 --- /dev/null +++ b/internal/vaultik/same_second_rewrite_test.go @@ -0,0 +1,72 @@ +package vaultik_test + +import ( + "bytes" + "context" + "path/filepath" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// A file rewritten with its size unchanged and a new mtime in the same +// second as the mtime the index holds must still be backed up. See +// https://git.eeqj.de/sneak/vaultik/issues/226. +func TestBackupOfSameSecondRewriteRestoresNewContent(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + storeDir := t.TempDir() + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + rewrittenPath := filepath.Join(dataDir, "small.txt") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, dataDir) + cfg := changedFileConfig(dataDir, dbPath) + + firstMTime := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC). + Add(100 * time.Millisecond) + secondMTime := firstMTime.Add(800 * time.Millisecond) + + require.NoError(t, fs.Chtimes(rewrittenPath, firstMTime, firstMTime)) + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, "first")) + + // Upper-casing ASCII text keeps its size. + files[rewrittenPath] = bytes.ToUpper(files[rewrittenPath]) + require.NoError(t, afero.WriteFile(fs, rewrittenPath, files[rewrittenPath], 0o644)) + require.NoError(t, fs.Chtimes(rewrittenPath, secondMTime, secondMTime)) + + require.NoError(t, backUp(v, "second")) + + id := localSnapshotID(ctx, t, repos, "second") + require.NoError(t, db.Close()) + + reader := newReaderVaultik(ctx, cfg, store, nil, fs) + require.NoError(t, reader.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Verify: true, + })) + + assertRestoredTree(t, fs, restoreDir, files) +} diff --git a/internal/vaultik/shallow_verify_test.go b/internal/vaultik/shallow_verify_test.go index e4b56fd..ce5a294 100644 --- a/internal/vaultik/shallow_verify_test.go +++ b/internal/vaultik/shallow_verify_test.go @@ -4,15 +4,20 @@ import ( "bytes" "context" "encoding/json" + "errors" + "fmt" "io" "os" + "path" "path/filepath" + "slices" "testing" "github.com/spf13/afero" "github.com/stretchr/testify/require" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage" "sneak.berlin/go/vaultik/internal/ui" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -22,7 +27,7 @@ import ( // then grows one stored blob so its size no longer matches the manifest. // Shallow verify must then fail, count the grown blob as a size mismatch, // and drop it from the verified count rather than continuing to report it -// as checked. +// as checked, and its error must not repeat the cli layer's prefix. func TestShallowVerifyDetectsWrongBlobSize(t *testing.T) { log.Initialize(log.Config{}) t.Parallel() @@ -31,7 +36,7 @@ func TestShallowVerifyDetectsWrongBlobSize(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") chunkSize := int64(32 * 1024) @@ -91,6 +96,12 @@ func TestShallowVerifyDetectsWrongBlobSize(t *testing.T) { require.Equal(t, 1, bad.Mismatched) require.Equal(t, healthy.BlobCount-1, bad.Verified, "the wrong-sized blob must not be counted as verified") + + // The cli layer prints this error after its own "Verification failed:". + err = newVerifier(io.Discard).VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{}) + require.EqualError(t, err, + "problems found in storage: 1 blobs have the wrong size") } // TestShallowVerifyDetectsMissingDatabase backs up a real snapshot, @@ -105,7 +116,7 @@ func TestShallowVerifyDetectsMissingDatabase(t *testing.T) { tempDir := t.TempDir() dataDir := filepath.Join(tempDir, "source") - storeDir := filepath.Join(tempDir, "remote") + storeDir := t.TempDir() dbPath := filepath.Join(tempDir, "index.sqlite") chunkSize := int64(32 * 1024) @@ -151,6 +162,224 @@ func TestShallowVerifyDetectsMissingDatabase(t *testing.T) { "shallow verify must fail when db.zst.age is absent") } +// errStatDenied stands in for any storage error other than not-found: a +// permission error, an S3 403, a dropped connection. +var errStatDenied = errors.New("injected stat failure") + +// statFailingStorer fails Stat with errStatDenied for the keys in +// failKeys and passes every other call to the wrapped Storer. +type statFailingStorer struct { + storage.Storer + + failKeys []string +} + +func (s statFailingStorer) Stat( + ctx context.Context, key string, +) (*storage.ObjectInfo, error) { + if slices.Contains(s.failKeys, key) { + return nil, fmt.Errorf("stat %q: %w", key, errStatDenied) + } + + return s.Storer.Stat(ctx, key) +} + +// TestShallowVerifyReportsStatErrorsApartFromMissing backs up a real +// snapshot, deletes one blob, and makes storage fail Stat with an error +// other than not-found for a second blob and for the encrypted database. +// Only the deleted blob may be counted as missing. The second blob and +// the database must be reported as could not be checked, with the error +// storage returned, and verify must fail, in the text output and under +// --json. +func TestShallowVerifyReportsStatErrorsApartFromMissing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + storeDir := t.TempDir() + dbPath := filepath.Join(tempDir, "index.sqlite") + + chunkSize := int64(32 * 1024) + maxBlobSize := int64(128 * 1024) + + // Random content, so the snapshot spans several blobs. + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + appendRandomBytes(t, fs, map[string][]byte{}, + filepath.Join(dataDir, "data.bin"), maxBlobSize*4) + + ctx := context.Background() + + cfg, storer, snapshotID := runFileStorageBackup( + ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize) + + blobKeys := storedBlobKeys(t, storeDir) + require.GreaterOrEqual(t, len(blobKeys), 2, "expected at least two blobs") + + missingKey, uncheckedKey := blobKeys[0], blobKeys[1] + missingHash, uncheckedHash := path.Base(missingKey), path.Base(uncheckedKey) + + require.NoError(t, os.Remove(filepath.Join(storeDir, missingKey))) + + dbKey := "metadata/" + snapshot.RemoteSnapshotKey(snapshotID) + "/db.zst.age" + failing := statFailingStorer{ + Storer: storer, + failKeys: []string{uncheckedKey, dbKey}, + } + + newVerifier := func(out io.Writer) *vaultik.Vaultik { + v := &vaultik.Vaultik{ + Config: cfg, + Storage: failing, + Fs: fs, + Stdout: out, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + v.SetContext(ctx) + + return v + } + + var out bytes.Buffer + + err := newVerifier(&out).VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{JSON: true}) + require.Error(t, err) + + result := decodeVerifyResult(t, out.Bytes()) + require.Equal(t, "failed", result.Status) + require.Equal(t, 1, result.Missing, "only the deleted blob is missing") + require.Equal(t, result.BlobCount-2, result.Verified) + require.Len(t, result.Unchecked, 1) + require.Equal(t, uncheckedHash, result.Unchecked[0].Hash) + require.Contains(t, result.Unchecked[0].Error, errStatDenied.Error()) + require.False(t, result.DatabaseMissing, + "a database that could not be checked is not missing") + require.Contains(t, result.DatabaseCheckError, errStatDenied.Error()) + + out.Reset() + err = newVerifier(&out).VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{}) + require.Error(t, err) + + text := out.String() + require.Contains(t, text, "Missing: "+missingHash) + require.NotContains(t, text, "Missing: "+uncheckedHash) + require.Contains(t, text, "Could not check: "+uncheckedHash) + require.Contains(t, text, "Encrypted database: could not be checked") + require.Contains(t, text, errStatDenied.Error()) + require.Contains(t, text, "FAILED") +} + +// TestShallowVerifyQuietFailsOnStatErrorAlone backs up a healthy snapshot, +// then makes storage fail Stat, with an error other than not-found, for +// one blob alone and then for the encrypted database alone. Each run must +// fail verify, and under --quiet, which drops the report, the error +// storage returned must still reach stderr. +// +//nolint:paralleltest // captureProcessStderr replaces os.Stderr +func TestShallowVerifyQuietFailsOnStatErrorAlone(t *testing.T) { + log.Initialize(log.Config{}) + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + storeDir := t.TempDir() + dbPath := filepath.Join(tempDir, "index.sqlite") + + chunkSize := int64(32 * 1024) + maxBlobSize := int64(128 * 1024) + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, "data.bin"), + bytesPattern("shallow-quiet-", int(maxBlobSize*2)), 0o644)) + + ctx := context.Background() + + cfg, storer, snapshotID := runFileStorageBackup( + ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize) + + newQuietVerifier := func(s storage.Storer) *vaultik.Vaultik { + v := &vaultik.Vaultik{ + Config: cfg, + Storage: s, + Fs: fs, + Stdout: io.Discard, + Stderr: io.Discard, + UI: ui.NewWithColor(io.Discard, false), + } + v.SetContext(ctx) + v.UI.SetQuiet(true) + + return v + } + + require.NoError(t, + newQuietVerifier(storer).VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{}), + "shallow verify should pass on a healthy snapshot") + + blobKeys := storedBlobKeys(t, storeDir) + require.NotEmpty(t, blobKeys) + + dbKey := "metadata/" + snapshot.RemoteSnapshotKey(snapshotID) + "/db.zst.age" + + for _, failKey := range []string{blobKeys[0], dbKey} { + v := newQuietVerifier(statFailingStorer{ + Storer: storer, + failKeys: []string{failKey}, + }) + + var err error + + stderr := captureProcessStderr(t, func() { + err = v.VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{}) + }) + + require.Error(t, err, + "verify must fail when %s could not be checked", failKey) + require.Contains(t, stderr, errStatDenied.Error(), + "under --quiet the error for %s must still reach stderr", failKey) + } +} + +// storedBlobKeys returns the storage key of every blob file under +// storeDir, sorted. +func storedBlobKeys(t *testing.T, storeDir string) []string { + t.Helper() + + var keys []string + + err := filepath.Walk(filepath.Join(storeDir, "blobs"), + func(p string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + if info.IsDir() { + return nil + } + + rel, err := filepath.Rel(storeDir, p) + if err != nil { + return err + } + + keys = append(keys, filepath.ToSlash(rel)) + + return nil + }) + require.NoError(t, err) + + return keys +} + // growOneBlob appends bytes to the first blob file found under blobsDir, // changing its on-disk size so it no longer matches the manifest. func growOneBlob(t *testing.T, fs afero.Fs, blobsDir string) { diff --git a/internal/vaultik/snapshot.go b/internal/vaultik/snapshot.go index 9f76fdf..ae95c93 100644 --- a/internal/vaultik/snapshot.go +++ b/internal/vaultik/snapshot.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "sort" "strconv" "strings" @@ -14,6 +15,8 @@ import ( "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/types" ) // Sentinel errors for snapshot management. @@ -21,10 +24,46 @@ var ( errSnapshotNotInConfig = errors.New("snapshot not found in config") errNoSnapshotsInConfig = errors.New("no snapshots configured") errSnapshotVerifyFailed = errors.New("verification failed") + errProblemsInStorage = errors.New("problems found in storage") errRemoveAllNeedsForce = errors.New("--all requires --force") + errSnapshotNotFound = errors.New("snapshot not found") + errSnapshotRemoveFailed = errors.New("snapshot(s) could not be removed") errInvalidTableName = errors.New("invalid table name") + errNoAgeRecipients = errors.New( + "creating a snapshot needs at least one public key in " + + "age_recipients (generate a keypair with: age-keygen)") + errKeepNewerThanNeedsPrune = errors.New("--keep-newer-than requires --prune") ) +// ErrPostBackupPruneFailed wraps a failure of the post-backup prune, +// which runs only after every snapshot was created and uploaded, so the +// caller can report it apart from a failed backup. +var ErrPostBackupPruneFailed = errors.New("post-backup prune failed") + +// ErrFilesUnreadable is returned when --skip-errors skipped files or +// directories it could not read or list. The snapshot is complete and +// kept, so the caller can report it apart from a failed backup. +var ErrFilesUnreadable = errors.New("file(s) could not be read") + +// ErrSourcePathEmpty is returned when --prune skipped the post-backup +// prune because the scan found nothing in a configured path of a +// snapshot, as in the mount point of a volume that is not mounted. The +// snapshots are complete and kept, so the caller can report it apart +// from a failed backup. A run that also skipped unreadable files +// returns ErrFilesUnreadable instead. +var ErrSourcePathEmpty = errors.New("source path(s) were empty") + +// ErrVolumeNotMounted is returned when --prune skipped the post-backup +// prune because a directory that an earlier snapshot of the same name +// found as a mount point was not found as one in this run: the volume +// mounted there is not mounted, the run found no entry in it, or the +// directory is no longer backed up. The snapshots are complete and +// kept, so the caller can report it apart from a failed backup. A run +// that also skipped unreadable files or found a configured path empty +// returns ErrFilesUnreadable or ErrSourcePathEmpty instead. +var ErrVolumeNotMounted = errors.New( + "mount point(s) an earlier snapshot recorded were not found") + // listRecentLimit caps how many snapshot rows are fetched from the // local index for listing and purge operations. const listRecentLimit = 10000 @@ -40,8 +79,34 @@ type SnapshotCreateOptions struct { Snapshots []string // Optional list of snapshot names to process (empty = all) } +// Validate fails when KeepNewerThan is set without Prune or is not a +// valid duration. Only the post-backup prune reads KeepNewerThan, after +// the backup, so the caller checks it before starting one. +func (opts *SnapshotCreateOptions) Validate() error { + if opts.KeepNewerThan == "" { + return nil + } + + if !opts.Prune { + return errKeepNewerThanNeedsPrune + } + + _, err := parseDuration(opts.KeepNewerThan) + if err != nil { + return fmt.Errorf("--keep-newer-than: %w", err) + } + + return nil +} + // CreateSnapshot executes the snapshot creation operation func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { + // config.Load accepts an empty list, since listing, verifying and + // restoring need no public key. + if len(v.Config.AgeRecipients) == 0 { + return errNoAgeRecipients + } + overallStartTime := time.Now() log.Info("Starting snapshot creation", @@ -50,7 +115,9 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { "index_path", v.Config.IndexPath, ) - err := v.EnsureStorageBinding() + // Before PruneDatabase: it drops incomplete snapshots, which could + // leave the local index without one and so skip the marker check. + err := v.markDestination() if err != nil { return err } @@ -77,30 +144,15 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { return fmt.Errorf("prune database: %w", err) } - // Determine which snapshots to process - snapshotNames := opts.Snapshots - if len(snapshotNames) == 0 { - snapshotNames = v.Config.SnapshotNames() - } else { - // Validate requested snapshot names exist - for _, name := range snapshotNames { - if _, ok := v.Config.Snapshots[name]; !ok { - return fmt.Errorf("%w: %q", errSnapshotNotInConfig, name) - } - } + snapshotNames, err := v.snapshotNamesToCreate(opts.Snapshots) + if err != nil { + return err } - if len(snapshotNames) == 0 { - return errNoSnapshotsInConfig - } - - // Process each named snapshot - for snapIdx, snapName := range snapshotNames { - err = v.createNamedSnapshot( - opts, hostname, snapName, snapIdx+1, len(snapshotNames)) - if err != nil { - return err - } + filesUnreadable, emptyPaths, unmountedPaths, err := v.createNamedSnapshots( + opts, hostname, snapshotNames) + if err != nil { + return err } // Print overall summary if multiple snapshots @@ -109,13 +161,109 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { len(snapshotNames), v.UI.Duration(time.Since(overallStartTime))) } - if opts.Prune { + switch { + case opts.Prune && (filesUnreadable > 0 || len(emptyPaths) > 0 || + len(unmountedPaths) > 0): + return v.skipPostBackupPrune( + filesUnreadable, emptyPaths, unmountedPaths) + case opts.Prune: err = v.runPostBackupPrune(snapshotNames, opts.KeepNewerThan) if err != nil { - return fmt.Errorf("post-backup prune: %w", err) + return fmt.Errorf("%w: %w", ErrPostBackupPruneFailed, err) } } + return v.finishCreateSnapshot(filesUnreadable) +} + +// createNamedSnapshots creates each named snapshot in turn. It returns +// the number of entries --skip-errors skipped because it could not read +// or list them, each configured path in which the scan found nothing, +// and, under --prune, each directory where an earlier snapshot found a +// volume mounted and this run did not, the paths named with their +// snapshot. +func (v *Vaultik) createNamedSnapshots( + opts *SnapshotCreateOptions, hostname string, snapshotNames []string, +) (int, []string, []string, error) { + filesUnreadable := 0 + + var emptyPaths, unmountedPaths []string + + for snapIdx, snapName := range snapshotNames { + stats, err := v.createNamedSnapshot( + opts, hostname, snapName, snapIdx+1, len(snapshotNames)) + if err != nil { + return 0, nil, nil, err + } + + filesUnreadable += stats.totalFilesUnreadable + + for _, dir := range stats.emptyPaths { + emptyPaths = append(emptyPaths, dir+" of snapshot "+snapName) + } + + for _, dir := range stats.unmountedPaths { + unmountedPaths = append(unmountedPaths, + dir+" of snapshot "+snapName) + } + } + + return filesUnreadable, emptyPaths, unmountedPaths, nil +} + +// skipPostBackupPrune says why the post-backup prune does not run, naming +// every cause, and returns the error the run ends with. An older snapshot +// may be the only one that still holds a file this run could not read, +// or what an empty path or a volume that is not mounted held. The +// previous snapshot is no guide: after one such run it lacks them too. +func (v *Vaultik) skipPostBackupPrune( + filesUnreadable int, emptyPaths, unmountedPaths []string, +) error { + log.Warn("Skipping post-backup prune", + "files_unreadable", filesUnreadable, "empty_paths", emptyPaths, + "unmounted_paths", unmountedPaths) + + if len(emptyPaths) > 0 { + v.UI.Warningf("Skipped the post-backup prune because nothing was "+ + "found in %s; older snapshots are kept.", + strings.Join(emptyPaths, ", ")) + } + + if len(unmountedPaths) > 0 { + v.UI.Warningf("Skipped the post-backup prune because this backup "+ + "did not find a mount point at %s, where an earlier snapshot "+ + "found one: the volume is not mounted, this backup found no "+ + "entry in it, or the directory is no longer backed up. Older "+ + "snapshots are kept. Mount the volume again, or, if that is on "+ + "purpose, remove the older snapshots by hand with "+ + "'vaultik snapshot purge'.", + strings.Join(unmountedPaths, ", ")) + } + + if filesUnreadable > 0 { + v.UI.Warningf("Skipped the post-backup prune because %d file(s) "+ + "could not be read; older snapshots are kept.", filesUnreadable) + + return fmt.Errorf("%d %w", filesUnreadable, ErrFilesUnreadable) + } + + if len(emptyPaths) > 0 { + return fmt.Errorf("%d %w", len(emptyPaths), ErrSourcePathEmpty) + } + + return fmt.Errorf("%d %w", len(unmountedPaths), ErrVolumeNotMounted) +} + +// finishCreateSnapshot ends a run whose snapshots are all complete and +// kept. Like finishRestore, it returns an error when --skip-errors +// skipped anything it could not read or list; otherwise it prints the +// closing line. A file removed during the run is counted as failed in +// the summary but is not an error, with or without --skip-errors. +func (v *Vaultik) finishCreateSnapshot(filesUnreadable int) error { + if filesUnreadable > 0 { + return fmt.Errorf("%d %w", filesUnreadable, ErrFilesUnreadable) + } + // Terminus must obey the --cron invariant: silent on total // success only. UI.Complete is dropped in cron/quiet mode (that's // the success path), but if any warnings fired during the run we @@ -131,10 +279,33 @@ func (v *Vaultik) CreateSnapshot(opts *SnapshotCreateOptions) error { return nil } +// snapshotNamesToCreate returns the requested snapshot names, each checked +// against the config, or every configured name when none was requested. +func (v *Vaultik) snapshotNamesToCreate(requested []string) ([]string, error) { + snapshotNames := requested + if len(snapshotNames) == 0 { + snapshotNames = v.Config.SnapshotNames() + } else { + // Validate requested snapshot names exist + for _, name := range snapshotNames { + if _, ok := v.Config.Snapshots[name]; !ok { + return nil, fmt.Errorf("%w: %q", errSnapshotNotInConfig, name) + } + } + } + + if len(snapshotNames) == 0 { + return nil, errNoSnapshotsInConfig + } + + return snapshotNames, nil +} + // runPostBackupPrune drops older snapshots of the given names and removes -// orphan blobs from remote storage. If keepNewerThan is set (e.g. "4w"), -// snapshots newer than that duration are kept. Otherwise only the latest -// snapshot of each name is kept. +// from remote storage the orphan blobs and the directories under +// metadata/ with no manifest, as PruneBlobs does. If keepNewerThan is set +// (e.g. "4w"), snapshots newer than that duration are kept. Otherwise only +// the latest snapshot of each name is kept. func (v *Vaultik) runPostBackupPrune( snapshotNames []string, keepNewerThan string, ) error { @@ -161,7 +332,7 @@ func (v *Vaultik) runPostBackupPrune( err = v.PruneBlobs(&PruneOptions{Force: true}) if err != nil { - return fmt.Errorf("pruning orphaned blobs: %w", err) + return fmt.Errorf("pruning the destination store: %w", err) } return nil @@ -172,20 +343,39 @@ type snapshotStats struct { totalFiles int totalBytes int64 totalChunks int + newChunkSize int64 totalBlobs int totalBytesSkipped int64 totalFilesSkipped int + totalFilesFailed int totalFilesDeleted int totalBytesDeleted int64 totalBytesUploaded int64 totalBlobsUploaded int uploadDuration time.Duration + + // The part of totalFilesFailed that --skip-errors skipped because it + // could not be read or listed. + totalFilesUnreadable int + + // The configured paths in which the scan found nothing. + emptyPaths []string + + // Under --prune, the directories where an earlier snapshot of the + // same name found a volume mounted and this one did not. + unmountedPaths []string + + // The sizes of all blobs the snapshot references, set by + // finalizeSnapshotMetadata once snapshot_blobs is populated. + blobSize int64 + blobUncompressedSize int64 } -// createNamedSnapshot creates a single named snapshot +// createNamedSnapshot creates a single named snapshot and returns the +// statistics of its scan. func (v *Vaultik) createNamedSnapshot( opts *SnapshotCreateOptions, hostname, snapName string, idx, total int, -) error { +) (*snapshotStats, error) { snapshotStartTime := time.Now() if total > 1 { @@ -194,21 +384,27 @@ func (v *Vaultik) createNamedSnapshot( resolvedDirs, err := v.resolveSnapshotPaths(snapName) if err != nil { - return err + return nil, err + } + + previousSnapshotID, err := v.previousSnapshotID(snapName) + if err != nil { + return nil, err } scanner := v.ScannerFactory(snapshot.ScannerParams{ - EnableProgress: !opts.Cron, - UI: v.UI, - Fs: v.Fs, - Exclude: v.Config.GetExcludes(snapName), - SkipErrors: opts.SkipErrors, + EnableProgress: !opts.Cron, + UI: v.UI, + Fs: v.Fs, + Exclude: v.Config.GetExcludes(snapName), + SkipErrors: opts.SkipErrors, + PreviousSnapshotID: previousSnapshotID, }) snapshotID, err := v.SnapshotManager.CreateSnapshotWithName( v.ctx, hostname, snapName, v.Globals.Version, v.Globals.Commit) if err != nil { - return fmt.Errorf("creating snapshot: %w", err) + return nil, fmt.Errorf("creating snapshot: %w", err) } log.Info("Beginning snapshot", "snapshot_id", snapshotID, "name", snapName) @@ -216,14 +412,12 @@ func (v *Vaultik) createNamedSnapshot( stats, err := v.scanAllDirectories(scanner, resolvedDirs, snapshotID) if err != nil { - return err + return nil, err } - v.collectUploadStats(scanner, stats) - err = v.finalizeSnapshotMetadata(snapshotID, stats) if err != nil { - return err + return nil, err } log.Info("Snapshot complete", @@ -236,11 +430,78 @@ func (v *Vaultik) createNamedSnapshot( v.printSnapshotSummary(snapshotID, snapshotStartTime, stats) - return nil + if opts.Prune { + stats.unmountedPaths, err = v.findUnmountedPaths(snapName, snapshotID) + if err != nil { + return nil, err + } + } + + return stats, nil +} + +// findUnmountedPaths returns each directory that an earlier snapshot +// named snapName in the local index recorded as a mount point and +// snapshot snapshotID did not, as when the volume mounted there is not +// mounted. +func (v *Vaultik) findUnmountedPaths( + snapName, snapshotID string, +) ([]string, error) { + found, err := v.Repositories.Snapshots.GetMountPoints(v.ctx, snapshotID) + if err != nil { + return nil, err + } + + snapshots, err := v.Repositories.Snapshots.ListRecent(v.ctx, listRecentLimit) + if err != nil { + return nil, fmt.Errorf("listing snapshots: %w", err) + } + + var unmounted []string + + for _, s := range snapshots { + if s.ID.String() == snapshotID || + parseSnapshotName(s.ID.String(), s.Hostname.String()) != snapName { + continue + } + + recorded, err := v.Repositories.Snapshots.GetMountPoints( + v.ctx, s.ID.String()) + if err != nil { + return nil, err + } + + for _, dir := range recorded { + if !slices.Contains(found, dir) && !slices.Contains(unmounted, dir) { + unmounted = append(unmounted, dir) + } + } + } + + return unmounted, nil +} + +// previousSnapshotID returns the ID of the most recent completed snapshot +// named snapName in the local index, or "" when there is none. +func (v *Vaultik) previousSnapshotID(snapName string) (string, error) { + snapshots, err := v.Repositories.Snapshots.ListRecent(v.ctx, listRecentLimit) + if err != nil { + return "", fmt.Errorf("listing snapshots: %w", err) + } + + for _, s := range snapshots { + if s.CompletedAt != nil && + parseSnapshotName(s.ID.String(), s.Hostname.String()) == snapName { + return s.ID.String(), nil + } + } + + return "", nil } // resolveSnapshotPaths resolves source directories to absolute paths -// with symlink resolution. +// with symlink resolution. A path that is a symlink whose target does +// not exist is an error. func (v *Vaultik) resolveSnapshotPaths(snapName string) ([]string, error) { snapConfig := v.Config.Snapshots[snapName] resolvedDirs := make([]string, 0, len(snapConfig.Paths)) @@ -253,12 +514,18 @@ func (v *Vaultik) resolveSnapshotPaths(snapName string) ([]string, error) { resolvedPath, err := filepath.EvalSymlinks(absPath) if err != nil { - if os.IsNotExist(err) { - resolvedPath = absPath - } else { + // A path that does not exist is left for the scan to report. + // One that exists is a symlink whose target is gone, as one + // into a volume that is not mounted: the scan would record + // only the link, and --prune would then drop the older + // snapshots that hold the files. + _, lstatErr := os.Lstat(absPath) + if !os.IsNotExist(err) || lstatErr == nil { return nil, fmt.Errorf( "failed to resolve symlinks for %s: %w", absPath, err) } + + resolvedPath = absPath } resolvedDirs = append(resolvedDirs, resolvedPath) @@ -272,6 +539,11 @@ func (v *Vaultik) resolveSnapshotPaths(snapName string) ([]string, error) { func (v *Vaultik) scanAllDirectories( scanner *snapshot.Scanner, resolvedDirs []string, snapshotID string, ) (*snapshotStats, error) { + if progress := scanner.GetProgress(); progress != nil { + progress.Start() + defer progress.Stop() + } + stats := &snapshotStats{} for i, dir := range resolvedDirs { @@ -295,16 +567,27 @@ func (v *Vaultik) scanAllDirectories( stats.totalFiles += result.FilesScanned stats.totalBytes += result.BytesScanned stats.totalChunks += result.ChunksCreated + stats.newChunkSize += result.NewChunkSize stats.totalBlobs += result.BlobsCreated stats.totalFilesSkipped += result.FilesSkipped + stats.totalFilesFailed += result.FilesFailed + stats.totalFilesUnreadable += result.FilesUnreadable stats.totalBytesSkipped += result.BytesSkipped stats.totalFilesDeleted += result.FilesDeleted stats.totalBytesDeleted += result.BytesDeleted + stats.totalBlobsUploaded += result.BlobsUploaded + stats.totalBytesUploaded += result.BytesUploaded + stats.uploadDuration += result.UploadDuration + + if result.EntriesFound == 0 { + stats.emptyPaths = append(stats.emptyPaths, dir) + } log.Info("Directory scan complete", "path", dir, "files", result.FilesScanned, "files_skipped", result.FilesSkipped, + "files_failed", result.FilesFailed, "bytes", result.BytesScanned, "bytes_skipped", result.BytesSkipped, "chunks", result.ChunksCreated, @@ -315,18 +598,6 @@ func (v *Vaultik) scanAllDirectories( return stats, nil } -// collectUploadStats gathers upload statistics from the scanner's -// progress reporter. -func (v *Vaultik) collectUploadStats(scanner *snapshot.Scanner, stats *snapshotStats) { - if s := scanner.GetProgress(); s != nil { - progressStats := s.GetStats() - stats.totalBytesUploaded = progressStats.BytesUploaded.Load() - stats.totalBlobsUploaded = int(progressStats.BlobsUploaded.Load()) - stats.uploadDuration = time.Duration( - progressStats.UploadDurationMs.Load()) * time.Millisecond - } -} - // finalizeSnapshotMetadata updates stats, exports metadata, and only then // marks the snapshot complete. Recording completion last is deliberate: an // export interrupted by a crash leaves the snapshot incomplete rather than @@ -336,31 +607,42 @@ func (v *Vaultik) collectUploadStats(scanner *snapshot.Scanner, stats *snapshotS func (v *Vaultik) finalizeSnapshotMetadata( snapshotID string, stats *snapshotStats, ) error { + // snapshot_blobs must be populated before the blob sizes below, which + // total the snapshot's blobs, and before the export, which builds the + // manifest and the trimmed metadata database from it. + err := v.SnapshotManager.PopulateSnapshotBlobs(v.ctx, snapshotID) + if err != nil { + return fmt.Errorf("populating snapshot blobs: %w", err) + } + + stats.blobSize, stats.blobUncompressedSize, err = + v.Repositories.Snapshots.GetSnapshotBlobSizes(v.ctx, snapshotID) + if err != nil { + return fmt.Errorf("getting snapshot blob sizes: %w", err) + } + + // file_count and total_size leave out the files that could not be + // stored; stats.totalBytes already does. extStats := snapshot.ExtendedBackupStats{ BackupStats: snapshot.BackupStats{ - FilesScanned: stats.totalFiles, - BytesScanned: stats.totalBytes, + FilesScanned: stats.totalFiles - stats.totalFilesFailed, + TotalSize: stats.totalBytes + stats.totalBytesSkipped, ChunksCreated: stats.totalChunks, BlobsCreated: stats.totalBlobs, BytesUploaded: stats.totalBytesUploaded, }, - BlobUncompressedSize: 0, + BlobSize: stats.blobSize, + BlobUncompressedSize: stats.blobUncompressedSize, CompressionLevel: v.Config.CompressionLevel, UploadDurationMs: stats.uploadDuration.Milliseconds(), + NewChunkSize: stats.newChunkSize, } - err := v.SnapshotManager.UpdateSnapshotStatsExtended(v.ctx, snapshotID, extStats) + err = v.SnapshotManager.UpdateSnapshotStatsExtended(v.ctx, snapshotID, extStats) if err != nil { return fmt.Errorf("updating snapshot stats: %w", err) } - // snapshot_blobs must be populated before the export, which builds the - // manifest and the trimmed metadata database from it. - err = v.SnapshotManager.PopulateSnapshotBlobs(v.ctx, snapshotID) - if err != nil { - return fmt.Errorf("populating snapshot blobs: %w", err) - } - err = v.SnapshotManager.ExportSnapshotMetadata( v.ctx, v.Config.IndexPath, snapshotID) if err != nil { @@ -392,15 +674,14 @@ func (v *Vaultik) printSnapshotSummary( snapshotID string, startTime time.Time, stats *snapshotStats, ) { snapshotDuration := time.Since(startTime) - totalFilesChanged := stats.totalFiles - stats.totalFilesSkipped + totalFilesChanged := stats.totalFiles - stats.totalFilesSkipped - + stats.totalFilesFailed totalBytesAll := stats.totalBytes + stats.totalBytesSkipped - // Get total blob sizes from database - compressedSize, uncompressedSize := v.getSnapshotBlobSizes(snapshotID) - var compressionRatio float64 - if uncompressedSize > 0 { - compressionRatio = float64(compressedSize) / float64(uncompressedSize) + if stats.blobUncompressedSize > 0 { + compressionRatio = float64(stats.blobSize) / + float64(stats.blobUncompressedSize) } else { compressionRatio = 1.0 } @@ -411,6 +692,10 @@ func (v *Vaultik) printSnapshotSummary( v.UI.Count(stats.totalFiles), v.UI.Count(totalFilesChanged), v.UI.Count(stats.totalFilesSkipped)) + if stats.totalFilesFailed > 0 { + filesMsg += fmt.Sprintf(", %s failed", v.UI.Count(stats.totalFilesFailed)) + } + if stats.totalFilesDeleted > 0 { filesMsg += fmt.Sprintf(", %s deleted", v.UI.Count(stats.totalFilesDeleted)) } @@ -428,8 +713,8 @@ func (v *Vaultik) printSnapshotSummary( if stats.totalBlobsUploaded > 0 { v.UI.Detailf("Storage: %s compressed from %s (%.2fx ratio).", - v.UI.Size(compressedSize), - v.UI.Size(uncompressedSize), + v.UI.Size(stats.blobSize), + v.UI.Size(stats.blobUncompressedSize), compressionRatio) v.UI.Detailf("Upload: %d blobs, %s in %s (%s).", stats.totalBlobsUploaded, @@ -441,27 +726,6 @@ func (v *Vaultik) printSnapshotSummary( v.UI.Detailf("Snapshot create duration: %s.", v.UI.Duration(snapshotDuration)) } -// getSnapshotBlobSizes returns total compressed and uncompressed blob -// sizes for a snapshot. -func (v *Vaultik) getSnapshotBlobSizes(snapshotID string) (int64, int64) { - var compressed, uncompressed int64 - - blobHashes, err := v.Repositories.Snapshots.GetBlobHashes(v.ctx, snapshotID) - if err != nil { - return 0, 0 - } - - for _, hash := range blobHashes { - blob, err := v.Repositories.Blobs.GetByHash(v.ctx, hash) - if err == nil && blob != nil { - compressed += blob.CompressedSize - uncompressed += blob.UncompressedSize - } - } - - return compressed, uncompressed -} - // SnapshotPurgeOptions contains options for the snapshot purge command. type SnapshotPurgeOptions struct { KeepLatest bool // Keep only the most recent snapshot per name @@ -480,7 +744,7 @@ type SnapshotPurgeOptions struct { // snapshot name, not the latest globally. This prevents `home` and `system` // snapshots from cannibalizing each other. func (v *Vaultik) PurgeSnapshotsWithOptions(opts *SnapshotPurgeOptions) error { - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() if err != nil { return err } @@ -502,19 +766,23 @@ func (v *Vaultik) PurgeSnapshotsWithOptions(opts *SnapshotPurgeOptions) error { nameFilter[n] = struct{}{} } - // Collect completed snapshots, applying the name filter. + // Collect completed snapshots and their names, applying the name filter. snapshots := make([]SnapshotInfo, 0, len(dbSnapshots)) + names := make(map[types.SnapshotID]string, len(dbSnapshots)) + for _, s := range dbSnapshots { if s.CompletedAt == nil { continue } + name := parseSnapshotName(s.ID.String(), s.Hostname.String()) if len(nameFilter) > 0 { - if _, ok := nameFilter[parseSnapshotName(s.ID.String())]; !ok { + if _, ok := nameFilter[name]; !ok { continue } } + names[s.ID] = name snapshots = append(snapshots, SnapshotInfo{ ID: s.ID, Timestamp: s.StartedAt, @@ -527,14 +795,14 @@ func (v *Vaultik) PurgeSnapshotsWithOptions(opts *SnapshotPurgeOptions) error { return snapshots[i].Timestamp.After(snapshots[j].Timestamp) }) - toDelete, err := selectSnapshotsToPurge(snapshots, opts) + toDelete, err := selectSnapshotsToPurge(snapshots, names, opts) if err != nil { return err } if len(toDelete) == 0 { if !opts.Quiet { - v.printlnStdout("No snapshots to delete") + v.UI.Infof("No snapshots to delete.") } return nil @@ -545,9 +813,11 @@ func (v *Vaultik) PurgeSnapshotsWithOptions(opts *SnapshotPurgeOptions) error { // selectSnapshotsToPurge applies the purge retention criteria to the // newest-first sorted snapshot list and returns the deletion -// candidates. +// candidates. names maps each snapshot's ID to its snapshot name. func selectSnapshotsToPurge( - snapshots []SnapshotInfo, opts *SnapshotPurgeOptions, + snapshots []SnapshotInfo, + names map[types.SnapshotID]string, + opts *SnapshotPurgeOptions, ) ([]SnapshotInfo, error) { var toDelete []SnapshotInfo @@ -558,7 +828,7 @@ func selectSnapshotsToPurge( seen := make(map[string]bool) for _, snap := range snapshots { - name := parseSnapshotName(snap.ID.String()) + name := names[snap.ID] if seen[name] { toDelete = append(toDelete, snap) @@ -570,7 +840,7 @@ func selectSnapshotsToPurge( case opts.OlderThan != "": duration, err := parseDuration(opts.OlderThan) if err != nil { - return nil, fmt.Errorf("invalid duration: %w", err) + return nil, err } cutoff := time.Now().UTC().Add(-duration) @@ -589,37 +859,41 @@ func selectSnapshotsToPurge( func (v *Vaultik) confirmAndExecutePurge( toDelete []SnapshotInfo, force, quiet bool, ) error { - if !quiet { + // Confirm unless --force is used. The list, the prompt and its answer + // bypass the UI: they are an interactive exchange the operator must + // see, so --quiet does not silence them. + if !force { v.stdoutf("The following snapshots will be deleted:\n\n") for _, snap := range toDelete { v.stdoutf(" %s (%s, %s)\n", snap.ID, - snap.Timestamp.Format("2006-01-02 15:04:05"), - formatBytes(snap.CompressedSize)) + snap.Timestamp.Format(time.DateTime), + ubytes(snap.CompressedSize)) } - } - // Confirm unless --force is used - if !force { v.stdoutf("\nDelete %d snapshot(s)? [y/N] ", len(toDelete)) var confirm string + // A failure to read the answer means no confirmation. _, err := v.scanStdin(&confirm) - if err != nil { + if err != nil || strings.ToLower(confirm) != "y" { v.printlnStdout("Cancelled") - return nil //nolint:nilerr // treat EOF or read error as "no" - } - - if strings.ToLower(confirm) != "y" { - v.printlnStdout("Cancelled") - - return nil + return ErrNotConfirmed } } else if !quiet { - v.stdoutf("\nDeleting %d snapshot(s) (--force specified)\n", len(toDelete)) + v.UI.Infof("The following snapshots will be deleted:") + + for _, snap := range toDelete { + v.UI.Detailf("%s (%s, %s)", + v.UI.Snapshot(snap.ID.String()), + snap.Timestamp.Format(time.DateTime), + ubytes(snap.CompressedSize)) + } + + v.UI.Infof("Deleting %d snapshot(s) (--force specified).", len(toDelete)) } // Delete snapshots (both local and remote) @@ -627,13 +901,14 @@ func (v *Vaultik) confirmAndExecutePurge( snapshotID := snap.ID.String() log.Info("Deleting snapshot", "id", snapshotID) + // Stop before the remote delete, so a snapshot still in the local + // index keeps its metadata on the destination store. err := v.deleteSnapshotFromLocalDB(snapshotID) if err != nil { - log.Error("Failed to delete from local database", - "snapshot_id", snapshotID, "error", err) + return fmt.Errorf("deleting snapshot %s from local index: %w", snapshotID, err) } - err = v.deleteRemoteSnapshotByKey(snapshot.RemoteSnapshotKey(snapshotID)) + _, err = v.deleteRemoteSnapshotByKey(snapshot.RemoteSnapshotKey(snapshotID)) if err != nil { return fmt.Errorf("deleting snapshot %s from remote: %w", snapshotID, err) } @@ -651,9 +926,9 @@ func (v *Vaultik) confirmAndExecutePurge( } if !quiet { - v.stdoutf("Deleted %d snapshot(s)\n", len(toDelete)) - v.printlnStdout( - "\nNote: Run 'vaultik prune' to clean up unreferenced remote blobs.") + v.UI.Infof("Deleted %d snapshot(s).", len(toDelete)) + v.UI.Noticef("Run '%s' to clean up unreferenced remote blobs.", + pruneCommandHint) } return nil @@ -684,25 +959,22 @@ func (v *Vaultik) VerifySnapshotWithOptions( Mode: "shallow", } - v.printVerifyHeader(snapshotID, opts) - - // Resolve the identifier to the snapshot's remote key. A human ID is - // hashed; a remote key (or its abbreviation, as printed for a - // remote-only snapshot) is used as-is, so a host with no local index - // can verify a snapshot it can only see on the store. The key is kept - // so we can also check for the snapshot's encrypted database below. + // The key is kept so we can also check for the snapshot's encrypted + // database below. remoteKey, err := v.resolveSnapshotRemoteKey(snapshotID) if err != nil { if opts.JSON { result.Status = verifyStatusFailed - result.ErrorMessage = fmt.Sprintf("resolving snapshot identifier: %v", err) + result.ErrorMessage = err.Error() return v.outputVerifyJSON(result) } - return fmt.Errorf("resolving snapshot identifier: %w", err) + return err } + v.printVerifyHeader(snapshotID, opts) + manifest, err := v.downloadManifestByKey(remoteKey) if err != nil { if opts.JSON { @@ -718,7 +990,7 @@ func (v *Vaultik) VerifySnapshotWithOptions( result.BlobCount = manifest.BlobCount result.TotalSize = manifest.TotalCompressedSize - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Snapshot information:\n") v.stdoutf(" Blob count: %d\n", manifest.BlobCount) v.stdoutf(" Total size: %s\n", ubytes(manifest.TotalCompressedSize)) @@ -734,21 +1006,13 @@ func (v *Vaultik) VerifySnapshotWithOptions( v.printlnStdout() // Check each blob is present with the size the manifest records. - v.stdoutf("Checking blob presence and sizes...\n") + v.UI.Beginf("Checking blob presence and sizes...") } - // A snapshot is only restorable if its encrypted database is present - // alongside the blobs. Shallow verify checks that the object exists; it - // does not decrypt it (that is deep verify's job). - dbPath := fmt.Sprintf("metadata/%s/db.zst.age", remoteKey) + v.checkSnapshotDatabase(remoteKey, result) - _, dbErr := v.Storage.Stat(v.ctx, dbPath) - if dbErr != nil { - result.DatabaseMissing = true - } - - result.Verified, result.Missing, result.Mismatched, result.MissingSize, err = - v.verifyManifestBlobs(manifest, opts) + result.Verified, result.Missing, result.Mismatched, result.MissingSize, + result.Unchecked, err = v.verifyManifestBlobs(manifest, opts) if err != nil { if opts.JSON { result.Status = verifyStatusFailed @@ -773,7 +1037,7 @@ func (v *Vaultik) printVerifyHeader(snapshotID string, opts *VerifyOptions) { snapshotTime = t } - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Verifying snapshot %s\n", snapshotID) if !snapshotTime.IsZero() { @@ -785,25 +1049,46 @@ func (v *Vaultik) printVerifyHeader(snapshotID string, opts *VerifyOptions) { } } +// checkSnapshotDatabase records in result whether the snapshot's +// encrypted database is missing or could not be checked. A snapshot is +// only restorable if its database is present alongside the blobs. +// Shallow verify checks that the object exists; it does not decrypt it +// (that is deep verify's job). +func (v *Vaultik) checkSnapshotDatabase(remoteKey string, result *VerifyResult) { + dbPath := fmt.Sprintf("metadata/%s/db.zst.age", remoteKey) + + _, err := v.Storage.Stat(v.ctx, dbPath) + + switch { + case errors.Is(err, storage.ErrNotFound): + result.DatabaseMissing = true + case err != nil: + result.DatabaseCheckError = err.Error() + } +} + // verifyManifestBlobs checks that each blob in the manifest is present in // storage with the size the manifest records, returning the counts of // blobs that were present with the right size, absent, and present but the -// wrong size, plus the total bytes of the absent blobs. It does not read -// blob contents; deep verification (RunDeepVerify) does that. The size -// comparison matches the deep path (see verifyBlobExistenceFromDB). +// wrong size, the total bytes of the absent blobs, and the blobs it could +// not check because storage returned an error other than not-found. It +// does not read blob contents; deep verification (RunDeepVerify) does +// that. The size comparison matches the deep path (see +// verifyBlobExistenceFromDB). func (v *Vaultik) verifyManifestBlobs( manifest *snapshot.Manifest, opts *VerifyOptions, -) (int, int, int, int64, error) { +) (int, int, int, int64, []UncheckedBlob, error) { var ( verified, missing, mismatched int missingSize int64 + unchecked []UncheckedBlob ) for _, blob := range manifest.Blobs { // The manifest is unauthenticated, so its blob hashes are checked // before being spliced into a storage path. if !isBlobHash(blob.Hash) { - return 0, 0, 0, 0, fmt.Errorf("%w: %s", + return 0, 0, 0, 0, nil, fmt.Errorf("%w: %s", errInvalidBlobHash, shortHash(blob.Hash)) } @@ -812,16 +1097,23 @@ func (v *Vaultik) verifyManifestBlobs( stat, err := v.Storage.Stat(v.ctx, blobPath) switch { - case err != nil: - if !opts.JSON { + case errors.Is(err, storage.ErrNotFound): + if !opts.JSON && !v.UI.Quiet() { v.stdoutf(" Missing: %s (%s)\n", blob.Hash, ubytes(blob.CompressedSize)) } missing++ missingSize += blob.CompressedSize + case err != nil: + if !opts.JSON && !v.UI.Quiet() { + v.stdoutf(" Could not check: %s (%v)\n", blob.Hash, err) + } + + unchecked = append(unchecked, + UncheckedBlob{Hash: blob.Hash, Error: err.Error()}) case stat.Size != blob.CompressedSize: - if !opts.JSON { + if !opts.JSON && !v.UI.Quiet() { v.stdoutf(" Wrong size: %s (store has %s, manifest lists %s)\n", blob.Hash, ubytes(stat.Size), ubytes(blob.CompressedSize)) } @@ -832,7 +1124,7 @@ func (v *Vaultik) verifyManifestBlobs( } } - return verified, missing, mismatched, missingSize, nil + return verified, missing, mismatched, missingSize, unchecked, nil } // formatVerifyResult outputs the final verification results as JSON or @@ -853,6 +1145,34 @@ func (v *Vaultik) formatVerifyResult( return v.outputVerifyJSON(result) } + // --quiet drops the report but not the errors storage returned, which + // are logged on stderr. A failure is still returned either way, and + // the cli layer prints it on stderr. + if v.UI.Quiet() { + for _, blob := range result.Unchecked { + log.Warn("Could not check blob", "blob", blob.Hash, "error", blob.Error) + } + + if result.DatabaseCheckError != "" { + log.Warn("Could not check the encrypted database", + "snapshot", result.SnapshotID, "error", result.DatabaseCheckError) + } + } else { + v.printVerifySummary(result, failure) + } + + // Not errSnapshotVerifyFailed: the cli layer prints this after its own + // "Verification failed:". + if failure != "" { + return fmt.Errorf("%w: %s", errProblemsInStorage, failure) + } + + return nil +} + +// printVerifySummary prints the counts and the status line that end the +// human-readable shallow verify report. failure is empty when it passed. +func (v *Vaultik) printVerifySummary(result *VerifyResult, failure string) { v.stdoutf("\nVerification complete:\n") v.stdoutf(" Present with listed size: %d blobs\n", result.Verified) @@ -865,23 +1185,30 @@ func (v *Vaultik) formatVerifyResult( v.stdoutf(" Wrong size: %d blobs\n", result.Mismatched) } + if len(result.Unchecked) > 0 { + v.stdoutf(" Could not check: %d blobs\n", len(result.Unchecked)) + } + if result.DatabaseMissing { v.stdoutf(" Encrypted database: missing\n") } + if result.DatabaseCheckError != "" { + v.stdoutf(" Encrypted database: could not be checked (%s)\n", + result.DatabaseCheckError) + } + v.stdoutf(" Status: ") if failure != "" { v.stdoutf("FAILED - %s\n", failure) - return fmt.Errorf("%w: %s", errSnapshotVerifyFailed, failure) + return } // Report only what was actually checked: presence and size, not contents. v.stdoutf("OK - all %d blobs listed in the manifest are present with the "+ "listed size; contents not checked (use --deep)\n", result.Verified) - - return nil } // shallowVerifyFailure returns a human-readable description of everything @@ -898,10 +1225,19 @@ func shallowVerifyFailure(result *VerifyResult) string { fmt.Sprintf("%d blobs have the wrong size", result.Mismatched)) } + if len(result.Unchecked) > 0 { + parts = append(parts, fmt.Sprintf("%d blobs could not be checked", + len(result.Unchecked))) + } + if result.DatabaseMissing { parts = append(parts, "the encrypted database is missing") } + if result.DatabaseCheckError != "" { + parts = append(parts, "the encrypted database could not be checked") + } + return strings.Join(parts, "; ") } @@ -936,7 +1272,7 @@ func (v *Vaultik) outputVerifyJSON(result *VerifyResult) error { // jq` fail (issue #108). The narration is duplicated as log records, // which go to stderr and so cannot corrupt the document. func (v *Vaultik) CleanupLocalSnapshots(opts *PruneOptions) error { - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() if err != nil { return err } @@ -964,7 +1300,7 @@ func (v *Vaultik) CleanupLocalSnapshots(opts *PruneOptions) error { log.Info("Removing stale local snapshot record", "snapshot_id", id) if !opts.JSON { - v.stdoutf("Removing stale local record: %s\n", id) + v.UI.Infof("Removing stale local record: %s.", v.UI.Snapshot(id)) } err = v.deleteSnapshotFromLocalDB(id) @@ -987,9 +1323,9 @@ func (v *Vaultik) CleanupLocalSnapshots(opts *PruneOptions) error { } if removed == 0 { - v.printlnStdout("No stale local snapshots found.") + v.UI.Infof("No stale local snapshots found.") } else { - v.stdoutf("Removed %d stale local snapshot record(s).\n", removed) + v.UI.Infof("Removed %d stale local snapshot record(s).", removed) } return nil @@ -1038,7 +1374,7 @@ func (v *Vaultik) syncWithRemote() error { // every local snapshot record (issue #160). remoteKeys, err := v.listAllRemoteSnapshotKeys() if err != nil { - return fmt.Errorf("listing remote snapshots: %w", err) + return err } remoteKeySet := make(map[string]bool, len(remoteKeys)) @@ -1103,14 +1439,22 @@ type RemoveResult struct { // just-removed snapshot left behind on the destination store. const pruneCommandHint = "vaultik prune" +// snapshotRemoveCommandHint is the command suggested, with the +// snapshot's ID, when a remove could not reach the destination store: +// running it again removes the snapshot's metadata there, which +// `vaultik prune` never does while the manifest is there. +const snapshotRemoveCommandHint = "vaultik snapshot remove" + // RemoveSnapshot removes a snapshot from the local index database and, // unless LocalOnly is set, also strips the snapshot's metadata from the // destination store. Blobs are NOT touched: removing a snapshot's // blobs requires reading every remaining remote manifest (the remote // may hold snapshots this host doesn't know about), which is what -// `vaultik prune` is for — the command prints the prune invocation to -// run as a follow-up. When the remote is unreachable the command still -// completes the local-DB removal and warns. +// `vaultik prune` is for — when metadata was removed from the +// destination store, the text output names the prune invocation to run +// as a follow-up. When removing the metadata fails, a snapshot in the +// local index is still removed from it, with a warning; a snapshot +// only on the destination store is an error. func (v *Vaultik) RemoveSnapshot( snapshotID string, opts *RemoveOptions, ) (*RemoveResult, error) { @@ -1118,7 +1462,13 @@ func (v *Vaultik) RemoveSnapshot( SnapshotID: snapshotID, } - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() + if err != nil { + return result, err + } + + snapshotID, remoteKey, inLocalIndex, err := v.findSnapshotToRemove( + snapshotID, opts.LocalOnly) if err != nil { return result, err } @@ -1127,19 +1477,31 @@ func (v *Vaultik) RemoveSnapshot( return v.removeSnapshotDryRun(result, snapshotID, opts) } - if !opts.Force && !opts.JSON && !v.confirmRemoveSnapshot(snapshotID, opts) { - return result, nil - } - - log.Info("Removing snapshot from local database", "snapshot_id", snapshotID) - - err = v.deleteSnapshotFromLocalDB(snapshotID) - if err != nil { - return result, fmt.Errorf("removing from local database: %w", err) + if !v.confirmRemoveSnapshot(snapshotID, opts) { + return result, ErrNotConfirmed } + // Checked before the local record is deleted: it may be the last + // snapshot in the local index, and the check applies only while the + // local index holds one. + var markerErr error if !opts.LocalOnly { - result.RemoteRemoved = v.removeSnapshotRemote(snapshotID) + markerErr = v.checkDestinationMarker() + } + + if inLocalIndex { + log.Info("Removing snapshot from local database", "snapshot_id", snapshotID) + + err = v.deleteSnapshotFromLocalDB(snapshotID) + if err != nil { + return result, fmt.Errorf("removing from local database: %w", err) + } + } + + result.RemoteRemoved, err = v.removeSnapshotRemote( + snapshotID, remoteKey, inLocalIndex, markerErr, opts) + if err != nil { + return result, err } if v.SnapshotManager != nil { @@ -1154,18 +1516,105 @@ func (v *Vaultik) RemoveSnapshot( return result, v.outputRemoveJSON(result) } - v.stdoutf("Removed snapshot '%s' from local database\n", snapshotID) + if inLocalIndex { + v.UI.Infof("Removed snapshot '%s' from local database.", + v.UI.Snapshot(snapshotID)) + } - if !opts.LocalOnly && result.RemoteRemoved { - v.printlnStdout("Removed snapshot metadata from remote storage") - v.stdoutf("\nNote: The removed snapshot's blobs remain on the remote. "+ + if result.RemoteRemoved { + v.UI.Infof("Removed snapshot metadata from remote storage.") + v.UI.Noticef("The removed snapshot's blobs remain on the remote. "+ "Run '%s' to delete any blobs no longer referenced by any "+ - "remaining remote snapshot.\n", pruneCommandHint) + "remaining remote snapshot.", pruneCommandHint) } return result, nil } +// findSnapshotToRemove returns the ID of the snapshot that identifier +// names, its remote key, and whether the local index holds it. A remote +// key, or the leading part of one, is resolved on the destination store; +// when the local index holds the snapshot with that key, its ID is +// returned, so it is removed from both. +func (v *Vaultik) findSnapshotToRemove( + identifier string, localOnly bool, +) (string, string, bool, error) { + if !isRemoteKeyOrPrefix(identifier) || localOnly { + inLocalIndex, err := v.checkSnapshotExists(identifier, localOnly) + + return identifier, snapshot.RemoteSnapshotKey(identifier), + inLocalIndex, err + } + + remoteKey, err := v.resolveSnapshotRemoteKey(identifier) + if err != nil { + return "", "", false, err + } + + localIDs, err := v.localSnapshotIDs() + if err != nil { + return "", "", false, fmt.Errorf( + "looking up snapshot in local index: %w", err) + } + + for _, id := range localIDs { + if snapshot.RemoteSnapshotKey(id) == remoteKey { + return id, remoteKey, true, nil + } + } + + return identifier, remoteKey, false, nil +} + +// checkSnapshotExists returns errSnapshotNotFound when the local index +// has no row for snapshotID and, unless localOnly is set, the +// destination store has no metadata for it either. inLocalIndex reports +// whether the local index has that row. The destination store is +// consulted only when the local index has no row, so a snapshot in the +// local index can still be removed from it while the destination store +// is unreachable, and only after checkDestinationMarker passes, so an +// unplugged volume's empty mount point is not taken for a store without +// the snapshot. +// +//nolint:nonamedreturns // the result name says what the bool means +func (v *Vaultik) checkSnapshotExists( + snapshotID string, localOnly bool, +) (inLocalIndex bool, err error) { + if v.Repositories != nil { + snap, err := v.Repositories.Snapshots.GetByID(v.ctx, snapshotID) + if err != nil { + return false, fmt.Errorf("looking up snapshot in local index: %w", err) + } + + if snap != nil { + return true, nil + } + } + + if localOnly { + return false, fmt.Errorf("%w in the local index: %s", + errSnapshotNotFound, snapshotID) + } + + err = v.checkDestinationMarker() + if err != nil { + return false, err + } + + objects, err := v.remoteSnapshotObjects(snapshot.RemoteSnapshotKey(snapshotID)) + if err != nil { + return false, fmt.Errorf("looking up snapshot on destination store: %w", err) + } + + if len(objects) == 0 { + return false, fmt.Errorf( + "%w in the local index or on the destination store: %s", + errSnapshotNotFound, snapshotID) + } + + return false, nil +} + // removeSnapshotDryRun reports what RemoveSnapshot would do without // making changes. func (v *Vaultik) removeSnapshotDryRun( @@ -1177,22 +1626,28 @@ func (v *Vaultik) removeSnapshotDryRun( return result, v.outputRemoveJSON(result) } - v.stdoutf("Would remove snapshot: %s\n", snapshotID) + v.UI.Infof("Would remove snapshot: %s.", v.UI.Snapshot(snapshotID)) if !opts.LocalOnly { - v.printlnStdout("Would also remove snapshot metadata from " + - "remote storage (blobs untouched)") + v.UI.Infof("Would also remove snapshot metadata from " + + "remote storage (blobs untouched).") } - v.printlnStdout("[Dry run - no changes made]") + v.UI.Noticef("Dry run: no changes made.") return result, nil } // confirmRemoveSnapshot prompts for confirmation before removing a -// snapshot. Returns false (treating EOF/read errors as "no") unless the -// user answers "y". +// snapshot, unless --force or --json is set. Returns false (treating +// EOF/read errors as "no") unless the user answers "y". The prompt and +// its answer bypass the UI: they are an interactive exchange the +// operator must see, so --quiet does not silence them. func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) bool { + if opts.Force || opts.JSON { + return true + } + if opts.LocalOnly { v.stdoutf("Remove snapshot '%s' from local database "+ "(remote untouched)? [y/N] ", snapshotID) @@ -1219,41 +1674,70 @@ func (v *Vaultik) confirmRemoveSnapshot(snapshotID string, opts *RemoveOptions) return true } -// removeSnapshotRemote strips the snapshot's metadata from the -// destination store, warning and proceeding on failure: the local-DB -// removal has already happened, so the user is told the remote half -// didn't finish and can retry with `vaultik prune` once the destination -// store is reachable. Returns true when the remote removal succeeded. -func (v *Vaultik) removeSnapshotRemote(snapshotID string) bool { +// removeSnapshotRemote strips the snapshot's metadata, under remoteKey, +// from the destination store. It returns true only when the delete finished +// without an error and removed at least one object; under LocalOnly it +// does nothing. markerErr is the result of checkDestinationMarker; when +// it is set, nothing is deleted and it is the failure. When the snapshot +// is only on the destination store, a failure is returned as an error, +// because that removal is all the command does. When the snapshot was in +// the local index, its removal there has already happened, so a failure +// is only a warning telling the user to run `vaultik snapshot remove` +// for the snapshot again once the destination store is reachable +// (`vaultik prune` never removes snapshot metadata that has its +// manifest). +func (v *Vaultik) removeSnapshotRemote( + snapshotID, remoteKey string, inLocalIndex bool, markerErr error, + opts *RemoveOptions, +) (bool, error) { + if opts.LocalOnly { + return false, nil + } + log.Info("Removing snapshot metadata from remote storage", "snapshot_id", snapshotID) - remoteKey := snapshot.RemoteSnapshotKey(snapshotID) + var deleted int - err := v.deleteRemoteSnapshotByKey(remoteKey) - if err != nil { - log.Warn("Could not remove snapshot metadata from remote storage", - "error", err) - - if v.UI != nil { - v.UI.Warningf("Could not remove snapshot metadata from remote: "+ - "%v. Run '%s' once the remote is reachable to finish cleanup.", - err, pruneCommandHint) - } - - return false + err := markerErr + if err == nil { + deleted, err = v.deleteRemoteSnapshotByKey(remoteKey) } - return true + if err != nil && !inLocalIndex { + return false, fmt.Errorf( + "removing snapshot metadata from destination store: %w", err) + } + + if err != nil { + log.Warn("Could not remove snapshot metadata from remote storage; "+ + "run '"+snapshotRemoveCommandHint+"' with the snapshot's ID "+ + "again once the remote is reachable", + "snapshot_id", snapshotID, "error", err) + + // The UI writes to stdout, which under --json holds only the + // document; the log record above is the warning on stderr. + if v.UI != nil && !opts.JSON { + v.UI.Warningf("Could not remove snapshot metadata from remote: "+ + "%v. Run '%s %s' again once the remote is reachable.", + err, snapshotRemoveCommandHint, snapshotID) + } + + return false, nil + } + + return deleted > 0, nil } // RemoveAllSnapshots removes every snapshot known to the local // database from the local index, and (with --remote) every snapshot // metadata directory in remote storage. Both sides are processed so a // "remove --all" leaves nothing behind, even when the local DB and -// remote storage have diverged. +// remote storage have diverged. Unless LocalOnly is set, it fails +// before it removes anything when the destination store cannot be +// listed or is not present by checkDestinationMarker. func (v *Vaultik) RemoveAllSnapshots(opts *RemoveOptions) (*RemoveResult, error) { - err := v.EnsureStorageBinding() + err := v.checkStorageBinding() if err != nil { return nil, err } @@ -1264,11 +1748,15 @@ func (v *Vaultik) RemoveAllSnapshots(opts *RemoveOptions) (*RemoveResult, error) } // remoteKeys is the set of metadata// subdirectories on the - // destination store; failures are downgraded to a warning so a - // permission-denied or unreachable remote can't block a local-only - // remove. + // destination store. Only for a local-only remove is a failure + // downgraded to a warning, so a permission-denied or unreachable + // remote can't block it. remoteKeys, remoteErr := v.listAllRemoteSnapshotKeys() if remoteErr != nil { + if !opts.LocalOnly { + return nil, remoteErr + } + log.Warn("Could not list remote snapshots", "error", remoteErr) v.UI.Warningf("Could not list remote snapshots: %v.", remoteErr) } @@ -1291,7 +1779,7 @@ func (v *Vaultik) RemoveAllSnapshots(opts *RemoveOptions) (*RemoveResult, error) if len(localSnaps) == 0 && len(orphanRemoteKeys) == 0 { if !opts.JSON { - v.printlnStdout("No snapshots found") + v.UI.Infof("No snapshots found.") } return &RemoveResult{}, nil @@ -1330,8 +1818,7 @@ func (v *Vaultik) localSnapshotIDs() ([]string, error) { // listAllRemoteSnapshotKeys collects the hashed remote keys // (subdirectories under metadata/) currently present in the // destination store. Returns (nil, err) when the store cannot be -// listed; callers must treat that as "no remote info available," not -// fatal. +// listed, or is not present by checkDestinationMarker. func (v *Vaultik) listAllRemoteSnapshotKeys() ([]string, error) { log.Info("Listing all remote snapshots") @@ -1380,6 +1867,11 @@ func (v *Vaultik) listAllRemoteSnapshotKeys() ([]string, error) { } } + err := v.checkDestinationMarker() + if err != nil { + return nil, err + } + return keys, nil } @@ -1396,27 +1888,27 @@ func (v *Vaultik) handleRemoveAllDryRun( } if !opts.JSON { - v.stdoutf("Would remove %d local snapshot(s):\n", len(localSnaps)) + v.UI.Infof("Would remove %d local snapshot(s):", len(localSnaps)) for _, id := range localSnaps { - v.stdoutf(" %s\n", id) + v.UI.Detailf("%s", v.UI.Snapshot(id)) } if !opts.LocalOnly { if len(orphanRemoteKeys) > 0 { - v.stdoutf("Would also remove %d orphan remote snapshot key(s):\n", + v.UI.Infof("Would also remove %d orphan remote snapshot key(s):", len(orphanRemoteKeys)) for _, key := range orphanRemoteKeys { - v.stdoutf(" %s\n", key) + v.UI.Detailf("%s", key) } } else { - v.printlnStdout("Would also remove snapshot metadata from " + - "remote storage (blobs untouched)") + v.UI.Infof("Would also remove snapshot metadata from " + + "remote storage (blobs untouched).") } } - v.printlnStdout("[Dry run - no changes made]") + v.UI.Noticef("Dry run: no changes made.") } if opts.JSON { @@ -1428,8 +1920,8 @@ func (v *Vaultik) handleRemoveAllDryRun( // executeRemoveAll deletes every local snapshot and, unless LocalOnly // is set, every corresponding remote metadata directory plus any -// orphan remote keys. Blobs are not touched; the printed prune-command -// hint is the next step. +// orphan remote keys. Blobs are not touched. It returns an error when +// any snapshot could not be removed. func (v *Vaultik) executeRemoveAll( localSnaps, orphanRemoteKeys []string, opts *RemoveOptions, ) (*RemoveResult, error) { @@ -1443,18 +1935,11 @@ func (v *Vaultik) executeRemoveAll( result := &RemoveResult{} - remoteErrors := v.removeAllLocalSnapshots(localSnaps, opts, result) + failures := v.removeAllLocalSnapshots(localSnaps, opts, result) if !opts.LocalOnly { - remoteErrors += v.removeAllOrphanRemotes(orphanRemoteKeys, result) - - if remoteErrors == 0 { - result.RemoteRemoved = true - } else if v.UI != nil { - v.UI.Warningf("Some remote metadata deletions failed. Run '%s' "+ - "once the remote is healthy to clean up unreferenced blobs.", - pruneCommandHint) - } + failures += v.removeAllOrphanRemotes(orphanRemoteKeys, result) + result.RemoteRemoved = failures == 0 } if v.SnapshotManager != nil { @@ -1464,17 +1949,18 @@ func (v *Vaultik) executeRemoveAll( } } + if failures > 0 { + return result, fmt.Errorf("%d %w", failures, errSnapshotRemoveFailed) + } + if opts.JSON { return result, v.outputRemoveJSON(result) } - v.stdoutf("Removed %d snapshot(s)\n", len(result.SnapshotsRemoved)) + v.UI.Infof("Removed %d snapshot(s).", len(result.SnapshotsRemoved)) if !opts.LocalOnly && result.RemoteRemoved { - v.printlnStdout("Removed snapshot metadata from remote storage") - v.stdoutf("\nNote: Removed snapshots' blobs remain on the remote. "+ - "Run '%s' to delete any blobs no longer referenced by any "+ - "remaining remote snapshot.\n", pruneCommandHint) + v.UI.Infof("Removed snapshot metadata from remote storage.") } return result, nil @@ -1516,40 +2002,47 @@ func (v *Vaultik) deleteIncompleteSnapshot(snapshotIDStr string, id any) bool { return true } -// removeAllLocalSnapshots removes each known local snapshot (and, unless -// --local-only, its remote metadata), returning the number of remote -// deletion failures. +// removeAllLocalSnapshots removes each known local snapshot's remote +// metadata, unless --local-only, and then its local record, returning +// the number of snapshots it could not remove. The local record goes +// only once the metadata is deleted: dropped first, it would leave that +// metadata on the destination store as a remote-only snapshot whose name +// is lost. func (v *Vaultik) removeAllLocalSnapshots( localSnaps []string, opts *RemoveOptions, result *RemoveResult, ) int { - remoteErrors := 0 + failures := 0 for _, snapshotID := range localSnaps { log.Info("Removing snapshot", "snapshot_id", snapshotID) + if !opts.LocalOnly { + _, err := v.deleteRemoteSnapshotByKey( + snapshot.RemoteSnapshotKey(snapshotID)) + if err != nil { + log.Warn("Failed to remove snapshot metadata from remote", + "snapshot_id", snapshotID, "error", err) + + failures++ + + continue + } + } + err := v.deleteSnapshotFromLocalDB(snapshotID) if err != nil { log.Error("Failed to remove from local database", "snapshot_id", snapshotID, "error", err) + failures++ + continue } - if !opts.LocalOnly { - err = v.deleteRemoteSnapshotByKey( - snapshot.RemoteSnapshotKey(snapshotID)) - if err != nil { - log.Warn("Failed to remove snapshot metadata from remote", - "snapshot_id", snapshotID, "error", err) - - remoteErrors++ - } - } - result.SnapshotsRemoved = append(result.SnapshotsRemoved, snapshotID) } - return remoteErrors + return failures } // removeAllOrphanRemotes deletes remote snapshot metadata that has no @@ -1562,7 +2055,7 @@ func (v *Vaultik) removeAllOrphanRemotes( for _, key := range orphanRemoteKeys { log.Info("Removing orphan remote snapshot", "remote_key", key) - err := v.deleteRemoteSnapshotByKey(key) + _, err := v.deleteRemoteSnapshotByKey(key) if err != nil { log.Warn("Failed to remove orphan from remote", "remote_key", key, "error", err) @@ -1609,34 +2102,44 @@ func (v *Vaultik) deleteSnapshotFromLocalDB(snapshotID string) error { } // deleteRemoteSnapshotByKey removes everything under -// metadata// on the destination store. The argument is a -// remote key (double-SHA256 derivation), not a human snapshot ID; -// callers that have a human ID must hash via snapshot.RemoteSnapshotKey -// first. -func (v *Vaultik) deleteRemoteSnapshotByKey(remoteKey string) error { - prefix := fmt.Sprintf("metadata/%s/", remoteKey) - objectCh := v.Storage.ListStream(v.ctx, prefix) - - var objectsToDelete []string - - for object := range objectCh { - if object.Err != nil { - return fmt.Errorf("listing objects: %w", object.Err) - } - - objectsToDelete = append(objectsToDelete, object.Key) +// metadata// on the destination store and returns how many +// objects it deleted. The argument is a remote key (double-SHA256 +// derivation), not a human snapshot ID; callers that have a human ID +// must hash via snapshot.RemoteSnapshotKey first. +func (v *Vaultik) deleteRemoteSnapshotByKey(remoteKey string) (int, error) { + objectsToDelete, err := v.remoteSnapshotObjects(remoteKey) + if err != nil { + return 0, err } - for _, key := range objectsToDelete { - err := v.Storage.Delete(v.ctx, key) + for i, key := range objectsToDelete { + err = v.Storage.Delete(v.ctx, key) if err != nil { - return fmt.Errorf("removing %s: %w", key, err) + return i, fmt.Errorf("removing %s: %w", key, err) } log.Debug("Deleted remote object", "key", key) } - return nil + return len(objectsToDelete), nil +} + +// remoteSnapshotObjects lists the keys of every object under +// metadata// on the destination store. +func (v *Vaultik) remoteSnapshotObjects(remoteKey string) ([]string, error) { + prefix := fmt.Sprintf("metadata/%s/", remoteKey) + + var keys []string + + for object := range v.Storage.ListStream(v.ctx, prefix) { + if object.Err != nil { + return nil, fmt.Errorf("listing objects: %w", object.Err) + } + + keys = append(keys, object.Key) + } + + return keys, nil } // outputRemoveJSON outputs the removal result as JSON @@ -1718,21 +2221,25 @@ func (v *Vaultik) PruneDatabase() (*PruneResult, error) { snapshotsRemain := countDiff(snapshotCountBefore, &result.SnapshotsDeleted) v.UI.Completef("Pruned local index database.") - v.UI.Detailf("Incomplete snapshots: %s removed (%s remain).", + v.UI.Detailf("Incomplete snapshots: %s removed "+ + "(total snapshots left in the local index: %s).", countText(&result.SnapshotsDeleted), countText(snapshotsRemain)) - v.UI.Detailf("Orphaned files: %s removed (%s remain).", + v.UI.Detailf("Orphaned files: %s removed "+ + "(total files left in the local index: %s).", countText(result.FilesDeleted), countText(fileCountAfter)) - v.UI.Detailf("Orphaned chunks: %s removed (%s remain).", + v.UI.Detailf("Orphaned chunks: %s removed "+ + "(total chunks left in the local index: %s).", countText(result.ChunksDeleted), countText(chunkCountAfter)) - v.UI.Detailf("Orphaned blobs: %s removed (%s remain).", + v.UI.Detailf("Orphaned blobs: %s removed "+ + "(total blobs left in the local index: %s).", countText(result.BlobsDeleted), countText(blobCountAfter)) return result, nil } -// countUnknown is what a count reads as when its query could not be run, -// distinct from "0", which means the table really was empty. -const countUnknown = "unknown" +// unknownText is what a count or size reads as when it could not be +// determined, distinct from "0", which is a real zero. +const unknownText = "unknown" // tableCountForReport returns the row count of a table for the prune // summary, or nil if the count could not be read. A read failure is @@ -1769,7 +2276,7 @@ func countDiff(before, after *int64) *int64 { // one that could not be queried. func countText(count *int64) string { if count == nil { - return countUnknown + return unknownText } return strconv.FormatInt(*count, 10) diff --git a/internal/vaultik/snapshot_deleted_count_test.go b/internal/vaultik/snapshot_deleted_count_test.go new file mode 100644 index 0000000..24f78fd --- /dev/null +++ b/internal/vaultik/snapshot_deleted_count_test.go @@ -0,0 +1,251 @@ +package vaultik_test + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/304: a +// backup counts a file as deleted only when the previous snapshot of +// the same name had it and it is gone, and never counts an excluded +// file. + +// deletedCountEnv is a backup setup over the source directory src whose +// user-facing output is kept in out. Each test configures its snapshots +// with setSnapshot. +type deletedCountEnv struct { + v *vaultik.Vaultik + out *bytes.Buffer + src string +} + +// newDeletedCountEnv writes files, keyed by path relative to src. +func newDeletedCountEnv(t *testing.T, files map[string][]byte) *deletedCountEnv { + t.Helper() + + ctx := context.Background() + fs := afero.NewOsFs() + tempDir := t.TempDir() + srcDir := filepath.Join(tempDir, "src") + + for rel, content := range files { + path := filepath.Join(srcDir, rel) + require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, afero.WriteFile(fs, path, content, 0o644)) + } + + cfg := faultTestConfig() + cfg.IndexPath = filepath.Join(tempDir, "index.sqlite") + cfg.Snapshots = map[string]config.SnapshotConfig{} + + store, err := storage.NewFileStorer(t.TempDir()) + require.NoError(t, err) + + db, err := database.New(ctx, cfg.IndexPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + out := &bytes.Buffer{} + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + v.UI = ui.NewWithColor(out, false) + + return &deletedCountEnv{v: v, out: out, src: srcDir} +} + +// setSnapshot configures the snapshot name to back up the path rel +// beneath src, with the given excludes. +func (e *deletedCountEnv) setSnapshot(name, rel string, exclude ...string) { + e.v.Config.Snapshots[name] = config.SnapshotConfig{ + Paths: []string{filepath.Join(e.src, rel)}, + Exclude: exclude, + } +} + +// backUp runs a backup of the named snapshot and returns its output. +func (e *deletedCountEnv) backUp(t *testing.T, name string) string { + t.Helper() + + e.out.Reset() + require.NoError(t, e.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Snapshots: []string{name}, + })) + + return e.out.String() +} + +// A file this snapshot excludes is not counted as deleted: neither one +// that another snapshot backs up, nor one that the previous snapshot of +// this name had before the exclude was added. +func TestBackupDoesNotCountExcludedFileAsDeleted(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "top.txt": []byte("top"), + "cache/tmp.bin": []byte("cache"), + "photos/a.jpg": []byte("photo a"), + "photos/b.jpg": []byte("photo b"), + "photos/c.jpg": []byte("photo c"), + }) + env.setSnapshot("photos", "photos") + env.setSnapshot("home", "", "/photos") + + env.backUp(t, "photos") + assert.Contains(t, env.backUp(t, "home"), filesLine(2, 2, 0)) + + env.setSnapshot("home", "", "/photos", "/cache") + assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1)) +} + +// A file inside a directory that an exclude added after a backup +// matches is not counted as deleted, though the pattern matches only the +// directory and the directory is gone from disk. +func TestBackupDoesNotCountFileInExcludedDirectoryAsDeleted(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "top.txt": []byte("top"), + "user/.local/share/Trash/old.txt": []byte("old"), + }) + env.setSnapshot("home", "") + + assert.Contains(t, env.backUp(t, "home"), filesLine(2, 2, 0)) + + require.NoError(t, os.RemoveAll( + filepath.Join(env.src, "user/.local/share/Trash"))) + + env.setSnapshot("home", "", "*/.local/share/Trash") + assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1)) +} + +// A file whose directory was replaced by a regular file of the same name +// is counted as deleted. +func TestBackupCountsFileInDirectoryReplacedByFileAsDeleted(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "dir/inside.txt": []byte("inside"), + }) + env.setSnapshot("home", "") + + assert.Contains(t, env.backUp(t, "home"), filesLine(1, 1, 0)) + + dir := filepath.Join(env.src, "dir") + require.NoError(t, os.RemoveAll(dir)) + require.NoError(t, os.WriteFile(dir, []byte("now a file"), 0o600)) + + assert.Contains(t, env.backUp(t, "home"), + "Files: 1 examined, 1 backed up, 0 unchanged, 1 deleted.") +} + +// Under --skip-errors a file inside a directory that the walk cannot +// open is not counted as deleted: it is still on disk. +func TestBackupDoesNotCountFileInUnopenableDirectoryAsDeleted(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "open.txt": []byte("open"), + "locked/inside.txt": []byte("inside"), + }) + env.setSnapshot("work", "") + + assert.Contains(t, env.backUp(t, "work"), filesLine(2, 2, 0)) + + // A directory's mode does not lock out root, who runs the tests, so + // opening the directory is made to fail instead. + env.v.Fs = &openFailFs{ + path: filepath.Join(env.src, "locked"), + err: os.ErrPermission, + } + + env.out.Reset() + err := env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: true, + Snapshots: []string{"work"}, + }) + require.ErrorIs(t, err, vaultik.ErrFilesUnreadable) + assert.Contains(t, env.out.String(), + "Files: 2 examined, 0 backed up, 1 unchanged, 1 failed.") +} + +// A backup counts only files that the previous snapshot of its own name +// had, not one that a later snapshot of another name over the same path +// had and that is since removed. +func TestBackupIgnoresSnapshotOfAnotherName(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "kept.txt": []byte("kept"), + }) + env.setSnapshot("home", "") + env.setSnapshot("other", "") + + env.backUp(t, "home") + + // Snapshot start times are kept in whole seconds: wait so that other's + // snapshot is strictly the most recent. + time.Sleep(time.Second) + + extra := filepath.Join(env.src, "extra.txt") + require.NoError(t, os.WriteFile(extra, []byte("extra"), 0o600)) + env.backUp(t, "other") + require.NoError(t, os.Remove(extra)) + + assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1)) +} + +// A file removed from disk is counted as deleted by the next backup of +// the snapshot that had it, and not by any later backup of that +// snapshot, nor by the first backup of another name over the same path. +func TestBackupCountsDeletedFileOnce(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + aContent := bytes.Repeat([]byte("a"), 1000) + bContent := bytes.Repeat([]byte("b"), 2000) + keptContent := bytes.Repeat([]byte("k"), 500) + + env := newDeletedCountEnv(t, map[string][]byte{ + "a.txt": aContent, + "b.txt": bContent, + "kept.txt": keptContent, + }) + env.setSnapshot("home", "") + env.setSnapshot("other", "") + + assert.Contains(t, env.backUp(t, "home"), filesLine(3, 3, 0)) + + require.NoError(t, os.Remove(filepath.Join(env.src, "a.txt"))) + require.NoError(t, os.Remove(filepath.Join(env.src, "b.txt"))) + + summary := env.backUp(t, "home") + assert.Contains(t, summary, + "Files: 1 examined, 0 backed up, 1 unchanged, 2 deleted.") + assert.Contains(t, summary, + fmt.Sprintf("Data: %s total (%s backed up), %s deleted.", + env.v.UI.Size(int64(len(keptContent))), env.v.UI.Size(0), + env.v.UI.Size(int64(len(aContent)+len(bContent))))) + + assert.Contains(t, env.backUp(t, "home"), filesLine(1, 0, 1)) + assert.Contains(t, env.backUp(t, "other"), filesLine(1, 0, 1)) +} diff --git a/internal/vaultik/snapshot_failed_file_test.go b/internal/vaultik/snapshot_failed_file_test.go new file mode 100644 index 0000000..0c906fe --- /dev/null +++ b/internal/vaultik/snapshot_failed_file_test.go @@ -0,0 +1,130 @@ +package vaultik_test + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// openFailFs is the real filesystem, except that opening path fails +// with err. Phase 1 of a backup only lstats a file, so it still counts +// path; phase 2 is the first to open it. +type openFailFs struct { + afero.OsFs + + path string + err error +} + +//nolint:ireturn // afero.Fs.Open is defined to return the interface. +func (f *openFailFs) Open(name string) (afero.File, error) { + if name == f.path { + return nil, &os.PathError{Op: "open", Path: name, Err: f.err} + } + + return f.OsFs.Open(name) +} + +// A file that phase 2 cannot open is reported as failed, not as +// unchanged, and neither the summary's data total nor the snapshots row +// counts it. See https://git.eeqj.de/sneak/vaultik/issues/280. +func TestSnapshotSummaryCountsFileNotStoredAsFailed(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tests := []struct { + name string + openErr error + skipErrors bool + wantErr error // nil for none + }{ + // What a normal user gets opening a file with mode 000. + {name: "unopenable under skip-errors", + openErr: os.ErrPermission, skipErrors: true, + wantErr: vaultik.ErrFilesUnreadable}, + // What opening a file removed after phase 1 gives. + {name: "removed between the phases", + openErr: os.ErrNotExist, skipErrors: false}, + // A removal is not an error, so --skip-errors does not make the + // run fail. See https://git.eeqj.de/sneak/vaultik/issues/310. + {name: "removed between the phases under skip-errors", + openErr: os.ErrNotExist, skipErrors: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + + // The scan walks the source path with symlinks resolved, so + // failedPath must be spelled the same way to match. + tempDir, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + + srcDir := filepath.Join(tempDir, "src") + failedPath := filepath.Join(srcDir, "failed.txt") + storedContent := []byte("this file is backed up") + storedSize := int64(len(storedContent)) + + fs := &openFailFs{path: failedPath, err: tt.openErr} + require.NoError(t, fs.MkdirAll(srcDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(srcDir, "stored.txt"), storedContent, 0o644)) + require.NoError(t, afero.WriteFile(fs, + failedPath, []byte("this file cannot be opened"), 0o644)) + + cfg := faultTestConfig() + cfg.IndexPath = filepath.Join(tempDir, "index.sqlite") + cfg.Snapshots = map[string]config.SnapshotConfig{ + "src": {Paths: []string{srcDir}}, + } + + store, err := storage.NewFileStorer(t.TempDir()) + require.NoError(t, err) + + db, err := database.New(ctx, cfg.IndexPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + out := &bytes.Buffer{} + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + v.UI = ui.NewWithColor(out, false) + + err = v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: tt.skipErrors, + Snapshots: []string{"src"}, + }) + require.ErrorIs(t, err, tt.wantErr) + + summary := out.String() + assert.Contains(t, summary, + "Files: 2 examined, 1 backed up, 0 unchanged, 1 failed.") + assert.Contains(t, summary, + fmt.Sprintf("Data: %s total (%s backed up).", + v.UI.Size(storedSize), v.UI.Size(storedSize))) + + snap, err := repos.Snapshots.GetByID(ctx, + localSnapshotID(ctx, t, repos, "src")) + require.NoError(t, err) + require.NotNil(t, snap) + + assert.Equal(t, int64(1), snap.FileCount) + assert.Equal(t, storedSize, snap.TotalSize) + }) + } +} diff --git a/internal/vaultik/snapshot_files.go b/internal/vaultik/snapshot_files.go new file mode 100644 index 0000000..ec4dc46 --- /dev/null +++ b/internal/vaultik/snapshot_files.go @@ -0,0 +1,115 @@ +package vaultik + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "text/tabwriter" + "time" + + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/ui" +) + +// ListedFile is one entry printed by `snapshot files`. Mode is the Go +// file mode string, which shows the entry type and the permission bits +// (for example -rw-r--r-- or drwxr-xr-x). +type ListedFile struct { + Path string `json:"path"` + Size int64 `json:"size"` + Mode string `json:"mode"` + MTime time.Time `json:"mtime"` +} + +// ListSnapshotFiles prints the path, size, mode and modification time of +// every file the snapshot holds at or under path, or of every file when +// path is empty. The file list is only in the snapshot's encrypted +// database, so this downloads and decrypts it as restore does, and needs +// the private key. +func (v *Vaultik) ListSnapshotFiles(snapshotID, path string, jsonOutput bool) error { + identities, err := v.restoreIdentities() + if err != nil { + return err + } + + remoteKey, err := v.resolveSnapshotRemoteKey(snapshotID) + if err != nil { + return err + } + + db, tempDir, err := v.downloadSnapshotDB(snapshotID, remoteKey, identities) + if errors.Is(err, errWrongPrivateKey) { + return err + } + + if err != nil { + return fmt.Errorf("downloading snapshot database: %w", err) + } + + defer v.closeSnapshotDB(db, tempDir) + + repos := database.NewRepositories(db) + + var files []*database.File + + if path == "" { + files, err = repos.Files.ListAll(v.ctx) + } else { + files, err = repos.Files.ListUnderPath(v.ctx, filepath.Clean(path)) + } + + if err != nil { + return fmt.Errorf("listing files: %w", err) + } + + if path != "" && len(files) == 0 { + return fmt.Errorf("%w: %s", errPathsNotInSnapshot, path) + } + + entries := make([]ListedFile, 0, len(files)) + + for _, file := range files { + entries = append(entries, ListedFile{ + Path: file.Path.String(), + Size: file.Size, + Mode: os.FileMode(file.Mode).String(), + MTime: file.MTime, + }) + } + + if jsonOutput { + encoder := json.NewEncoder(v.Stdout) + encoder.SetIndent("", " ") + + return encoder.Encode(entries) + } + + if v.UI.Quiet() { + return nil + } + + return v.printListedFileTable(entries) +} + +// printListedFileTable writes the entries as a plain table to stdout. +func (v *Vaultik) printListedFileTable(entries []ListedFile) error { + w := tabwriter.NewWriter(v.Stdout, 0, 0, tabPadding, ' ', 0) + + _, err := fmt.Fprintln(w, "MODE\tSIZE\tMODIFIED\tPATH") + if err != nil { + return err + } + + for _, entry := range entries { + _, err = fmt.Fprintf(w, "%s\t%d\t%s\t%s\n", + entry.Mode, entry.Size, + entry.MTime.Format(time.RFC3339), ui.QuoteUnprintable(entry.Path)) + if err != nil { + return err + } + } + + return w.Flush() +} diff --git a/internal/vaultik/snapshot_files_test.go b/internal/vaultik/snapshot_files_test.go new file mode 100644 index 0000000..e23eafb --- /dev/null +++ b/internal/vaultik/snapshot_files_test.go @@ -0,0 +1,197 @@ +package vaultik_test + +import ( + "bytes" + "context" + "encoding/json" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/435: +// `snapshot files` lists what a snapshot holds without restoring it. + +// unprintableFileName is a file name holding a newline and an escape +// sequence, which the table must not print raw. +const unprintableFileName = "odd\nname\x1b[31m" + +// backUpForFileListing backs up the fault source tree, plus a file named +// unprintableFileName at its top, and returns a reader whose stdout is +// out, the snapshot ID, and the source directory. +func backUpForFileListing( + t *testing.T, out *bytes.Buffer, +) (*vaultik.Vaultik, string, string) { + t.Helper() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + cfg := faultTestConfig() + + writeFaultSourceTree(t, fs, dataDir) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, unprintableFileName), []byte("odd"), 0o644)) + + store, err := storage.NewFileStorer(t.TempDir()) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + id := fullFaultBackup(ctx, t, fs, store, cfg, + database.NewRepositories(db), dataDir, dbPath, "files") + require.NoError(t, db.Close()) + + v := newReaderVaultik(ctx, cfg, store, nil, fs) + v.Stdout = out + + return v, id, dataDir +} + +func TestSnapshotFilesJSONListsEveryFileWithItsMetadata(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, dataDir := backUpForFileListing(t, &out) + + require.NoError(t, v.ListSnapshotFiles(id, "", true)) + + var entries []vaultik.ListedFile + + require.NoError(t, json.Unmarshal(out.Bytes(), &entries)) + + byPath := make(map[string]vaultik.ListedFile, len(entries)) + for _, entry := range entries { + byPath[entry.Path] = entry + } + + for _, rel := range []string{"small.txt", "a.bin", "sub", "sub/b.bin", "sub/c.bin"} { + path := filepath.Join(dataDir, rel) + + entry, ok := byPath[path] + require.True(t, ok, "%s must be listed", path) + + info, err := afero.NewOsFs().Stat(path) + require.NoError(t, err) + + assert.Equal(t, info.Mode().String(), entry.Mode, path) + assert.True(t, info.ModTime().Equal(entry.MTime), + "%s: mtime %v, listed %v", path, info.ModTime(), entry.MTime) + + if !info.IsDir() { + assert.Equal(t, info.Size(), entry.Size, path) + } + } +} + +func TestSnapshotFilesListsOnlyWhatIsUnderThePath(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, dataDir := backUpForFileListing(t, &out) + + require.NoError(t, v.ListSnapshotFiles(id, filepath.Join(dataDir, "sub"), false)) + + text := out.String() + assert.Contains(t, text, filepath.Join(dataDir, "sub", "b.bin")) + assert.Contains(t, text, filepath.Join(dataDir, "sub", "c.bin")) + assert.NotContains(t, text, filepath.Join(dataDir, "small.txt")) + assert.True(t, strings.HasPrefix(text, "MODE"), "the table must have a header") +} + +// TestSnapshotFilesTableEscapesAnUnprintablePath checks that the table +// prints a path holding a newline and an escape sequence quoted and +// escaped on one row: the newline must not start a forged row, and the +// escape sequence must not reach the terminal. +func TestSnapshotFilesTableEscapesAnUnprintablePath(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, dataDir := backUpForFileListing(t, &out) + + require.NoError(t, v.ListSnapshotFiles(id, "", false)) + + text := out.String() + assert.Contains(t, text, + strconv.Quote(filepath.Join(dataDir, unprintableFileName))) + assert.NotContains(t, text, "\x1b", "no escape byte may reach the output") + + for line := range strings.SplitSeq(text, "\n") { + assert.False(t, strings.HasPrefix(line, "name"), + "the newline in the name must not start a row: %q", line) + } +} + +// TestSnapshotFilesQuietSuppressesTableNotJSON is the --quiet contract +// for `snapshot files`: the table is silenced, but the --json document a +// script depends on is still written. +func TestSnapshotFilesQuietSuppressesTableNotJSON(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, _ := backUpForFileListing(t, &out) + v.UI.SetQuiet(true) + + require.NoError(t, v.ListSnapshotFiles(id, "", false)) + require.Empty(t, out.String(), "the table must be silenced under --quiet") + + require.NoError(t, v.ListSnapshotFiles(id, "", true)) + + var entries []vaultik.ListedFile + + require.NoError(t, json.Unmarshal(out.Bytes(), &entries)) + assert.NotEmpty(t, entries, + "the --json document must still be written under --quiet") +} + +func TestSnapshotFilesFailsOnAPathThatMatchesNothing(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, dataDir := backUpForFileListing(t, &out) + missing := filepath.Join(dataDir, "typo.txt") + + err := v.ListSnapshotFiles(id, missing, false) + + require.Error(t, err) + assert.Contains(t, err.Error(), missing, "the error must name the path") + assert.Empty(t, out.String(), "nothing must be printed") +} + +func TestSnapshotFilesRequiresThePrivateKey(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + var out bytes.Buffer + + v, id, _ := backUpForFileListing(t, &out) + v.Config.AgeSecretKey = "" + + err := v.ListSnapshotFiles(id, "", false) + + require.Error(t, err) + assert.Contains(t, err.Error(), "VAULTIK_AGE_SECRET_KEY") +} diff --git a/internal/vaultik/snapshot_identifier.go b/internal/vaultik/snapshot_identifier.go index a65cf3f..5420168 100644 --- a/internal/vaultik/snapshot_identifier.go +++ b/internal/vaultik/snapshot_identifier.go @@ -28,8 +28,9 @@ var ( // Two forms are accepted, matching the two things a host can know: // // - A human snapshot ID (hostname_name_timestamp), which a host holding -// the local index has. It is hashed to its remote key; the store is -// not consulted. +// the local index has. It is hashed to its remote key. An ID that +// names no snapshot in the local index or on the destination store +// is an error (see checkSnapshotExists). // - A remote key, or the leading part of one, which is all a host with // no local index can know — it is exactly what `snapshot list` prints // for a remote-only snapshot (see formatRemoteOnlyID). It is resolved @@ -41,6 +42,11 @@ var ( // RFC3339 timestamp). func (v *Vaultik) resolveSnapshotRemoteKey(identifier string) (string, error) { if !isRemoteKeyOrPrefix(identifier) { + _, err := v.checkSnapshotExists(identifier, false) + if err != nil { + return "", err + } + return snapshot.RemoteSnapshotKey(identifier), nil } diff --git a/internal/vaultik/snapshot_list.go b/internal/vaultik/snapshot_list.go index f3a0269..0f2ca48 100644 --- a/internal/vaultik/snapshot_list.go +++ b/internal/vaultik/snapshot_list.go @@ -39,7 +39,8 @@ const maxRemoteOnlyRows = 1000 // manifest reads need throttling. const remoteManifestFetchConcurrency = 8 -// tabPadding is the tabwriter cell padding for the snapshot table. +// tabPadding is the tabwriter cell padding for the `snapshot list` and +// `snapshot files` tables. const tabPadding = 3 // ListSnapshots prints the table of snapshots known to this host: the @@ -61,7 +62,9 @@ const tabPadding = 3 // attempt is made to recover or fabricate the human ID. // // Snapshots in the local index with no counterpart on the destination -// store are reported as drift below the table. +// store are reported as drift below the table, unless the local index +// is bound to a different destination than the configured one: that is +// reported instead. // // If remote listing fails (unmounted volume, permission denied, // network), we degrade to local-only with a warning. List never fails @@ -103,7 +106,26 @@ func (v *Vaultik) ListSnapshots(jsonOutput bool) error { return snapshots[i].Timestamp.After(snapshots[j].Timestamp) }) + stored, configured, err := v.storageBinding() + if err != nil { + return err + } + + // A local index bound to another destination describes that one, so + // its records are expected to be missing here, and prune refuses to + // run. The binding is reported instead of advising prune. + boundElsewhere := stored != "" && stored != configured + if jsonOutput { + // stdout holds only the document, so this goes to the logger. + if boundElsewhere { + log.Warn("Local index is bound to a different backup "+ + "destination; to proceed, revert storage_url (or the s3.* "+ + "endpoint, bucket and prefix) to the bound destination, "+ + "or run 'vaultik database delete'", + "bound_to", stored, "configured", configured) + } + if remoteErr == nil { v.reportJSONListingLimits(listing) } @@ -125,8 +147,13 @@ func (v *Vaultik) ListSnapshots(jsonOutput bool) error { } } + if boundElsewhere { + v.UI.Warningf("%v\n%s", errStorageBindingMismatch, + buildBindingMismatchMessage(stored, configured)) + } + if remoteErr == nil { - v.reportListDrift(snapshots, listing) + v.reportListDrift(snapshots, listing, boundElsewhere) } return nil @@ -432,7 +459,9 @@ func (v *Vaultik) snapshotInfoFromLocal(ls *database.Snapshot) SnapshotInfo { // reportListDrift prints the reconciliation notes the merged table // cannot express on its own: local records with no counterpart on the // destination store, plus counts of remote snapshots that were -// unreadable or omitted. +// unreadable or omitted. Local records are not reported when +// boundElsewhere is set: ListSnapshots has already said why they are +// missing. // // This is what remains of the old reportRemoteDrift, and it no longer // touches the destination store. Its remote-only half collapsed into @@ -441,6 +470,7 @@ func (v *Vaultik) snapshotInfoFromLocal(ls *database.Snapshot) SnapshotInfo { // so `snapshot list` lists the destination exactly once per invocation. func (v *Vaultik) reportListDrift( snapshots []SnapshotInfo, listing *remoteSnapshotListing, + boundElsewhere bool, ) { var localOnly []string @@ -450,7 +480,7 @@ func (v *Vaultik) reportListDrift( } } - if len(localOnly) > 0 { + if len(localOnly) > 0 && !boundElsewhere { v.UI.Warningf("%d local snapshot record(s) not found in backup "+ "destination store:", len(localOnly)) @@ -553,8 +583,8 @@ func (v *Vaultik) printSnapshotTable(snapshots []SnapshotInfo) error { if snap.LocallyTracked { id = snap.ID.String() - uncompressed = formatBytes(snap.UncompressedSize) - newChunks = formatBytes(snap.NewChunkSize) + uncompressed = ubytes(snap.UncompressedSize) + newChunks = ubytes(snap.NewChunkSize) } else { id = formatRemoteOnlyID(snap.RemoteKey) uncompressed = remoteOnlyCell @@ -564,7 +594,7 @@ func (v *Vaultik) printSnapshotTable(snapshots []SnapshotInfo) error { _, err = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", id, snap.Timestamp.Format("2006-01-02 15:04:05"), - formatBytes(snap.CompressedSize), + ubytes(snap.CompressedSize), uncompressed, newChunks) if err != nil { diff --git a/internal/vaultik/snapshot_list_test.go b/internal/vaultik/snapshot_list_test.go index 030f545..0e468a0 100644 --- a/internal/vaultik/snapshot_list_test.go +++ b/internal/vaultik/snapshot_list_test.go @@ -122,6 +122,9 @@ func newListEnv(t *testing.T) *listEnv { store := newObservingStorer() stdout := &bytes.Buffer{} + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(ctx, markerFile, strings.NewReader(""))) + v := &vaultik.Vaultik{ Config: &config.Config{ AgeSecretKey: "", @@ -184,6 +187,17 @@ func (e *listEnv) addRemoteRawTimestamp( t.Helper() remoteKey := snapshot.RemoteSnapshotKey(snapshotID) + e.putRemoteManifest(t, remoteKey, + encodeRemoteManifest(t, remoteKey, timestamp)) + + return remoteKey +} + +// encodeRemoteManifest returns the encoded manifest of a one-blob +// snapshot whose remote key is remoteKey. +func encodeRemoteManifest(t *testing.T, remoteKey, timestamp string) []byte { + t.Helper() + manifest := &snapshot.Manifest{ // Note: the hashed key, never the human ID. That is precisely // why a remote-only snapshot cannot be named. @@ -199,11 +213,17 @@ func (e *listEnv) addRemoteRawTimestamp( data, err := snapshot.EncodeManifest(manifest, 3) require.NoError(t, err) - err = e.store.Put(context.Background(), + return data +} + +// putRemoteManifest stores an encoded manifest on the destination store +// under remoteKey. +func (e *listEnv) putRemoteManifest(t *testing.T, remoteKey string, data []byte) { + t.Helper() + + err := e.store.Put(context.Background(), "metadata/"+remoteKey+"/manifest.json.zst", bytes.NewReader(data)) require.NoError(t, err) - - return remoteKey } // Fixtures shared across the listing tests. @@ -212,8 +232,8 @@ const ( listConfiguredName = "home" listLocalID = "testhost_home_2026-03-01T10:00:00Z" listRemoteID = "otherhost_media_2026-03-02T11:22:33Z" - // fiveMegabytes formats as "5.0 MB" through formatBytes. - fiveMegabytes = 5 * 1024 * 1024 + // fiveMegabytes is printed as "5.0 MB" by every command. + fiveMegabytes = 5_000_000 ) // TestListSnapshots_RemoteWithoutSecretKey is the regression guard for @@ -306,6 +326,49 @@ func TestListSnapshots_RemoteOnlyRowRendering(t *testing.T) { "are not in the local index") } +// TestSnapshotListAndPurgePrintSizesLikeRemoteInfo checks that the +// `snapshot list` table and the purge listing print a byte count the way +// `remote info` does: in powers of 1000, as the MB label says. +func TestSnapshotListAndPurgePrintSizesLikeRemoteInfo(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const wantSize = "5.0 MB" // fiveMegabytes + + env := newListEnv(t) + + // A remote-only snapshot: `snapshot list` and `remote info` both take + // its size from the manifest. + remoteKey := env.addRemote(t, listRemoteID, + time.Date(2026, 3, 2, 11, 22, 33, 0, time.UTC)) + + // A locally tracked snapshot of the same size for the purge to list. + // The purge prints the snapshot's blob size, the last argument here. + start := time.Date(2026, 3, 1, 10, 0, 0, 0, time.UTC) + env.addLocal(t, listLocalID, start) + env.addRemote(t, listLocalID, start) + require.NoError(t, env.v.Repositories.Snapshots.UpdateCounts( + context.Background(), nil, listLocalID, 0, 0, 0, 0, fiveMegabytes)) + + require.NoError(t, env.v.RemoteInfo(false)) + assert.Contains(t, findTableRow(t, env.stdout.String(), remoteKey[:16]), + wantSize, "remote info") + + env.stdout.Reset() + require.NoError(t, env.v.ListSnapshots(false)) + assert.Contains(t, findTableRow(t, env.stdout.String(), + ""), wantSize, "snapshot list") + + // Without --force and with nothing on stdin the purge lists what it + // would delete, reads no confirmation, and deletes nothing. + env.stdout.Reset() + require.ErrorIs(t, env.v.PurgeSnapshotsWithOptions( + &vaultik.SnapshotPurgeOptions{OlderThan: "1d"}), + vaultik.ErrNotConfirmed) + assert.Contains(t, findTableRow(t, env.stdout.String(), listLocalID), + wantSize, "snapshot purge") +} + // findTableRow returns the single output line containing needle. func findTableRow(t *testing.T, out, needle string) string { t.Helper() @@ -379,6 +442,74 @@ func TestListSnapshots_LocalOnlyReportedAsDrift(t *testing.T) { assert.NotContains(t, out, "snapshot cleanup") } +// TestListSnapshots_BoundElsewhereDoesNotAdvisePrune covers a changed +// storage_url: the local index is still bound to the old destination, +// so its records are missing from the new one. prune refuses to run in +// that state, so the listing must give the choices prune gives instead +// of advising it. +func TestListSnapshots_BoundElsewhereDoesNotAdvisePrune(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const ( + oldURL = "file:///mnt/backups/old" + newURL = "file:///mnt/backups/new" + ) + + env := newListEnv(t) + env.v.Config.StorageURL = newURL + require.NoError(t, env.v.Repositories.LocalMeta.Set(context.Background(), + database.LocalMetaKeyStorageURL, oldURL)) + env.addLocal(t, listLocalID, time.Date(2026, 3, 1, 10, 0, 0, 0, time.UTC)) + + err := env.v.ListSnapshots(false) + require.NoError(t, err) + + out := env.stdout.String() + + assert.Contains(t, out, listLocalID) + assert.Contains(t, out, + "local index is bound to a different backup destination") + assert.Contains(t, out, oldURL) + assert.Contains(t, out, newURL) + assert.Contains(t, out, "revert storage_url") + assert.Contains(t, out, "vaultik database delete") + assert.NotContains(t, out, "vaultik prune") +} + +// TestListSnapshots_JSONReportsBoundElsewhere is the --json side of the +// test above. Every local row comes out with remote_present false, which +// a script reads as stale local records unless it is told, on stderr, +// that the local index is bound to a different destination. +// +//nolint:paralleltest // captureProcessStderr replaces os.Stderr +func TestListSnapshots_JSONReportsBoundElsewhere(t *testing.T) { + const ( + oldURL = "file:///mnt/backups/old" + newURL = "file:///mnt/backups/new" + ) + + env := newListEnv(t) + env.v.Config.StorageURL = newURL + require.NoError(t, env.v.Repositories.LocalMeta.Set(context.Background(), + database.LocalMetaKeyStorageURL, oldURL)) + env.addLocal(t, listLocalID, time.Date(2026, 3, 1, 10, 0, 0, 0, time.UTC)) + + stderr := captureProcessStderr(t, func() { + require.NoError(t, env.v.ListSnapshots(true)) + }) + + rows := decodeListJSON(t, env.stdout.String()) + require.Len(t, rows, 1) + assert.Equal(t, listLocalID, rows[0].ID) + + assert.Contains(t, stderr, "bound to a different backup destination") + assert.Contains(t, stderr, oldURL) + assert.Contains(t, stderr, newURL) + assert.Contains(t, stderr, "revert storage_url") + assert.Contains(t, stderr, "vaultik database delete") +} + // TestListSnapshots_UnreachableRemoteDegrades covers the promise in the // doc comment: an unreachable destination is a warning plus local-only // output, never a failure. @@ -441,12 +572,14 @@ func TestListSnapshots_UnreadableManifestDoesNotHideOthers(t *testing.T) { // //nolint:tagliatelle // snake_case is the established output format type listJSONRow struct { - ID string `json:"id"` - RemoteKey string `json:"remote_key"` - Timestamp string `json:"timestamp"` - CompressedSize int64 `json:"compressed_size"` - LocallyTracked bool `json:"locally_tracked"` - RemotePresent *bool `json:"remote_present"` + ID string `json:"id"` + RemoteKey string `json:"remote_key"` + Timestamp string `json:"timestamp"` + CompressedSize int64 `json:"compressed_size"` + UncompressedSize int64 `json:"uncompressed_size"` + NewChunkSize int64 `json:"new_chunk_size"` + LocallyTracked bool `json:"locally_tracked"` + RemotePresent *bool `json:"remote_present"` } // decodeListJSON parses the command's stdout, which must contain @@ -676,9 +809,17 @@ func TestListSnapshots_JSONReportsTruncation(t *testing.T) { timestamp := time.Date(2026, 3, 2, 11, 22, 33, 0, time.UTC) - // One past the cap, so exactly one snapshot is omitted. + // One past the cap, so exactly one snapshot is omitted. The listing + // names a snapshot by the key its manifest is stored under, never by + // the manifest's own ID. So all of them share one encoded manifest: + // encoding 1001 took seconds. + data := encodeRemoteManifest(t, + snapshot.RemoteSnapshotKey("otherhost_bulk"), + timestamp.Format(time.RFC3339)) + for i := range maxRemoteOnlyRowsForTest + 1 { - env.addRemote(t, fmt.Sprintf("otherhost_bulk_%04d", i), timestamp) + env.putRemoteManifest(t, snapshot.RemoteSnapshotKey( + fmt.Sprintf("otherhost_bulk_%04d", i)), data) } stderr := captureProcessStderr(t, func() { diff --git a/internal/vaultik/snapshot_prune_test.go b/internal/vaultik/snapshot_prune_test.go index 8b76a93..e0e2e49 100644 --- a/internal/vaultik/snapshot_prune_test.go +++ b/internal/vaultik/snapshot_prune_test.go @@ -1,8 +1,18 @@ package vaultik_test import ( + "context" + "os" + "path/filepath" + "syscall" "testing" + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" "sneak.berlin/go/vaultik/internal/vaultik" ) @@ -25,3 +35,379 @@ func TestSnapshotCreateOptions_PruneFlag(t *testing.T) { t.Error("Expected Prune to be false") } } + +// A backup under --prune that finds nothing in a configured path, as in +// the mount point of a volume that is not mounted, does not prune: run +// after run, the snapshot that holds the files is kept with everything +// it stored, and the run fails. That holds whether the empty path is the +// snapshot's only path or one of two. See +// https://git.eeqj.de/sneak/vaultik/issues/388. +func TestBackupWithEmptySourcePathDoesNotPrune(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + // emptied is the path, relative to the source directory, that is + // emptied after the first backup. + const ( + snapshotName = "media" + emptied = "music" + ) + + tests := []struct { + name string + paths []string // relative to the source directory + }{ + {name: "only path", paths: []string{emptied}}, + {name: "one of two paths", paths: []string{emptied, "docs"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + env := newDeletedCountEnv(t, map[string][]byte{ + emptied + "/a.mp3": []byte("song a"), + emptied + "/b.mp3": []byte("song b"), + "docs/notes.txt": []byte("notes"), + }) + + paths := make([]string, 0, len(tt.paths)) + + for _, rel := range tt.paths { + paths = append(paths, filepath.Join(env.src, rel)) + } + + env.v.Config.Snapshots[snapshotName] = config.SnapshotConfig{ + Paths: paths, + } + env.backUp(t, snapshotName) + + firstID := localSnapshotID(ctx, t, env.v.Repositories, snapshotName) + stored, err := env.v.Storage.List(ctx, "") + require.NoError(t, err) + + // A volume that is not mounted leaves its mount point behind + // as an empty directory. + emptiedDir := filepath.Join(env.src, emptied) + require.NoError(t, os.RemoveAll(emptiedDir)) + require.NoError(t, os.Mkdir(emptiedDir, 0o750)) + + for range 2 { + env.out.Reset() + + err := env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + Snapshots: []string{snapshotName}, + }) + require.ErrorIs(t, err, vaultik.ErrSourcePathEmpty) + assert.Contains(t, env.out.String(), + "Skipped the post-backup prune because nothing was found in ") + assert.Contains(t, env.out.String(), + emptied+" of snapshot "+snapshotName+";") + assert.NotContains(t, env.out.String(), "Running post-backup prune.") + } + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 3) + assert.Equal(t, firstID, snapshots[2].ID.String(), + "the snapshot that holds the files is kept") + + for _, key := range stored { + _, err := env.v.Storage.Stat(ctx, key) + require.NoError(t, err, "%s is kept", key) + } + }) + } +} + +// A backup under --prune of a configured path that is a symlink whose +// target is gone, as one into a volume that is not mounted, fails before +// anything is pruned: the snapshot that holds the files is kept with +// everything it stored. See https://git.eeqj.de/sneak/vaultik/issues/388. +func TestBackupThroughSymlinkWhoseTargetIsGoneDoesNotPrune(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const snapshotName = "photos" + + ctx := context.Background() + env := newDeletedCountEnv(t, map[string][]byte{ + "volume/a.jpg": []byte("photo a"), + "volume/b.jpg": []byte("photo b"), + }) + + target := filepath.Join(env.src, "volume") + link := filepath.Join(env.src, "photos") + require.NoError(t, os.Symlink(target, link)) + env.setSnapshot(snapshotName, "photos") + env.backUp(t, snapshotName) + + firstID := localSnapshotID(ctx, t, env.v.Repositories, snapshotName) + stored, err := env.v.Storage.List(ctx, "") + require.NoError(t, err) + + // The volume is not mounted, so the symlink points at nothing. + require.NoError(t, os.RemoveAll(target)) + + env.out.Reset() + err = env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + Snapshots: []string{snapshotName}, + }) + require.ErrorIs(t, err, os.ErrNotExist) + assert.Contains(t, err.Error(), link) + assert.NotContains(t, env.out.String(), "Running post-backup prune.") + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1) + assert.Equal(t, firstID, snapshots[0].ID.String(), + "the snapshot that holds the files is kept") + + for _, key := range stored { + _, err := env.v.Storage.Stat(ctx, key) + require.NoError(t, err, "%s is kept", key) + } +} + +// A backup under --skip-errors --prune that both skipped a file it could +// not read and found nothing in a configured path names the empty path +// too when it skips the prune. See +// https://git.eeqj.de/sneak/vaultik/issues/388. +func TestBackupWithEmptySourcePathAndUnreadableFileNamesBoth(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const snapshotName = "media" + + env := newDeletedCountEnv(t, map[string][]byte{ + "docs/notes.txt": []byte("notes"), + }) + require.NoError(t, os.Mkdir(filepath.Join(env.src, "music"), 0o750)) + env.v.Config.Snapshots[snapshotName] = config.SnapshotConfig{ + Paths: []string{ + filepath.Join(env.src, "docs"), + filepath.Join(env.src, "music"), + }, + } + + // A mode does not lock out root, who runs the tests, so opening the + // file is made to fail instead. + env.v.Fs = &openFailFs{ + path: filepath.Join(env.src, "docs", "notes.txt"), + err: os.ErrPermission, + } + + err := env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + SkipErrors: true, + Snapshots: []string{snapshotName}, + }) + require.ErrorIs(t, err, vaultik.ErrFilesUnreadable) + assert.Contains(t, env.out.String(), + "Skipped the post-backup prune because 1 file(s) could not be read") + assert.Contains(t, env.out.String(), + "Skipped the post-backup prune because nothing was found in ") + assert.Contains(t, env.out.String(), "music of snapshot "+snapshotName+";") + assert.NotContains(t, env.out.String(), "Running post-backup prune.") +} + +// A backup under --prune that finds something in each configured path +// prunes the previous snapshot, also when a path is a single file. See +// https://git.eeqj.de/sneak/vaultik/issues/388. +func TestBackupWithNoEmptySourcePathPrunes(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const ( + snapshotName = "album" + file = "pictures/one.jpg" // relative to the source directory + ) + + tests := []struct { + name string + path string // relative to the source directory + }{ + {name: "directory", path: filepath.Dir(file)}, + {name: "single file", path: file}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + env := newDeletedCountEnv(t, map[string][]byte{ + file: []byte("picture"), + }) + env.setSnapshot(snapshotName, tt.path) + env.backUp(t, snapshotName) + + firstID := localSnapshotID(ctx, t, env.v.Repositories, snapshotName) + + require.NoError(t, env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + Snapshots: []string{snapshotName}, + })) + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1, "the previous snapshot is pruned") + assert.NotEqual(t, firstID, snapshots[0].ID.String()) + }) + } +} + +// automountFs is the real filesystem with a volume at volumeDir that is +// mounted on first access, as by an autofs map that shows its mount +// points before mounting them: listing volumeDir mounts the volume or, +// while cannotMount, fails with "no such file or directory". +type automountFs struct { + afero.OsFs + + volumeDir string + cannotMount bool + mounted bool +} + +//nolint:ireturn // afero.Fs.Open is defined to return the interface. +func (f *automountFs) Open(name string) (afero.File, error) { + if name == f.volumeDir && f.cannotMount { + return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT} + } + + if name == f.volumeDir { + f.mounted = true + } + + return f.OsFs.Open(name) +} + +// A backup under --prune in which a volume that an earlier snapshot found +// mounted below the configured path is missing does not prune: run after +// run, the snapshot that holds the volume's files is kept with everything +// it stored, and the run fails. Once the volume is back, the prune runs. +// The volume is mounted on first access and every backup starts with it +// not mounted, so its directory is on its parent's device until the walk +// lists it. While the volume is missing, its directory is left empty, or +// listing it fails with "no such file or directory", as when an autofs +// volume cannot be mounted, which the walk counts as a directory removed +// during the backup. See https://git.eeqj.de/sneak/vaultik/issues/395. +func TestBackupWithVolumeNotMountedDoesNotPrune(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tests := []struct { + name string + listingFails bool + }{ + {name: "directory left empty", listingFails: false}, + {name: "listing fails", listingFails: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + backUpWithVolumeNotMounted(t, tt.listingFails) + }) + } +} + +// backUpWithVolumeNotMounted runs the backups of +// TestBackupWithVolumeNotMountedDoesNotPrune. While the volume is +// missing, listing its directory fails if listingFails; otherwise the +// directory is empty. +func backUpWithVolumeNotMounted(t *testing.T, listingFails bool) { + t.Helper() + + // volume is the directory, below the configured path, where the + // volume is mounted. + const ( + snapshotName = "data" + volume = "nas" + ) + + ctx := context.Background() + env := newDeletedCountEnv(t, map[string][]byte{ + volume + "/a.txt": []byte("file a"), + "notes.txt": []byte("notes"), + }) + env.setSnapshot(snapshotName, "") + prune := &vaultik.SnapshotCreateOptions{ + Prune: true, Snapshots: []string{snapshotName}, + } + + // The volume's directory is on the volume's device, 2, while the + // volume is mounted. Everything else is on device 1. + volumeDir := filepath.Join(env.src, volume) + fs := &automountFs{volumeDir: volumeDir} + newScanner := env.v.ScannerFactory + env.v.ScannerFactory = func(params snapshot.ScannerParams) *snapshot.Scanner { + fs.mounted = false + params.Fs = fs + params.DeviceNumber = func(info os.FileInfo) (uint64, bool) { + if info.Name() == volume && fs.mounted { + return 2, true + } + + return 1, true + } + + return newScanner(params) + } + + env.backUp(t, snapshotName) + + firstID := localSnapshotID(ctx, t, env.v.Repositories, snapshotName) + stored, err := env.v.Storage.List(ctx, "") + require.NoError(t, err) + + // The volume goes missing. + fs.cannotMount = listingFails + + if !listingFails { + require.NoError(t, os.RemoveAll(volumeDir)) + require.NoError(t, os.Mkdir(volumeDir, 0o750)) + } + + for range 2 { + env.out.Reset() + + err := env.v.CreateSnapshot(prune) + require.ErrorIs(t, err, vaultik.ErrVolumeNotMounted) + assert.Contains(t, env.out.String(), + "did not find a mount point at "+volumeDir+" of snapshot "+snapshotName) + assert.Contains(t, env.out.String(), "'vaultik snapshot purge'") + assert.NotContains(t, env.out.String(), "Running post-backup prune.") + } + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 3) + assert.Equal(t, firstID, snapshots[2].ID.String(), + "the snapshot that holds the volume's files is kept") + + for _, key := range stored { + _, err := env.v.Storage.Stat(ctx, key) + require.NoError(t, err, "%s is kept", key) + } + + // The volume is back. + fs.cannotMount = false + + require.NoError(t, os.WriteFile( + filepath.Join(volumeDir, "a.txt"), []byte("file a"), 0o600)) + require.NoError(t, env.v.CreateSnapshot(prune)) + + snapshots, err = env.v.Repositories.Snapshots.ListRecent( + ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1, "the older snapshots are pruned") +} diff --git a/internal/vaultik/snapshot_skip_errors_test.go b/internal/vaultik/snapshot_skip_errors_test.go new file mode 100644 index 0000000..0bf1ea3 --- /dev/null +++ b/internal/vaultik/snapshot_skip_errors_test.go @@ -0,0 +1,283 @@ +package vaultik_test + +import ( + "context" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// --skip-errors skips only a file that cannot be opened or read. A local +// index error while a directory is recorded stops the backup, and the +// snapshot is not recorded as complete. See +// https://git.eeqj.de/sneak/vaultik/issues/284. +func TestSkipErrorsBackupStopsOnIndexErrorRecordingDirectory(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + + // The scan walks the source path with symlinks resolved, so dirPath + // must be spelled the same way to match the row the scan inserts. + tempDir, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + + srcDir := filepath.Join(tempDir, "src") + dirPath := filepath.Join(srcDir, "dir") + + fs := afero.NewOsFs() + require.NoError(t, fs.MkdirAll(dirPath, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dirPath, "file.txt"), []byte("file content"), 0o644)) + + cfg := faultTestConfig() + cfg.IndexPath = filepath.Join(tempDir, "index.sqlite") + cfg.Snapshots = map[string]config.SnapshotConfig{ + "tree": {Paths: []string{srcDir}}, + } + + store, err := storage.NewFileStorer(t.TempDir()) + require.NoError(t, err) + + db, err := database.New(ctx, cfg.IndexPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + // The local index refuses the directory's files row. + _, err = db.Conn().ExecContext(ctx, fmt.Sprintf(` + CREATE TRIGGER refuse_directory BEFORE INSERT ON files + WHEN NEW.path = '%s' + BEGIN SELECT RAISE(ABORT, 'simulated index error'); END`, dirPath)) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + err = v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: true, + Snapshots: []string{"tree"}, + }) + require.ErrorContains(t, err, "simulated index error") + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1) + assert.Nil(t, snapshots[0].CompletedAt) +} + +// A backup under --skip-errors that skips a file it cannot open, or a +// directory it cannot list, keeps the snapshot, counts what it skipped +// as failed and returns an error instead of finishing successfully. See +// https://git.eeqj.de/sneak/vaultik/issues/310. +func TestSkipErrorsBackupKeepsSnapshotAndFailsWhenItSkips(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tests := []struct { + name string + skipped string // relative to the source directory + }{ + {name: "file it cannot open", skipped: "skipdir/file.txt"}, + {name: "directory it cannot list", skipped: "skipdir"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "stored.txt": []byte("stored"), + "skipdir/file.txt": []byte("in skipdir"), + }) + env.setSnapshot("work", "") + + // A mode does not lock out root, who runs the tests, so + // opening the skipped path is made to fail instead. + env.v.Fs = &openFailFs{ + path: filepath.Join(env.src, tt.skipped), + err: os.ErrPermission, + } + + err := env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: true, + Snapshots: []string{"work"}, + }) + require.ErrorIs(t, err, vaultik.ErrFilesUnreadable) + + assert.Contains(t, env.out.String(), + "Files: 2 examined, 1 backed up, 0 unchanged, 1 failed.") + assert.NotContains(t, env.out.String(), "Finished successfully.") + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + context.Background(), listRecentTestLimit) + require.NoError(t, err) + require.Len(t, snapshots, 1) + assert.NotNil(t, snapshots[0].CompletedAt, "the snapshot is kept") + }) + } +} + +// removeOnLookupFs is the real filesystem, except that path is removed +// just before it is looked up. The walk looks an entry up after listing +// its directory, so path is listed but gone when the walk reaches it. +type removeOnLookupFs struct { + afero.OsFs + + path string +} + +func (f *removeOnLookupFs) LstatIfPossible( + name string, +) (os.FileInfo, bool, error) { + if name == f.path { + _ = os.Remove(name) + } + + return f.OsFs.LstatIfPossible(name) +} + +// A file removed before the walk reaches it is counted once, as failed, +// like a file removed before its data is read, and the backup finishes +// successfully, with or without --skip-errors. See +// https://git.eeqj.de/sneak/vaultik/issues/310. +func TestBackupCountsFileRemovedBeforeWalkReachesItAsFailed(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tests := []struct { + name string + skipErrors bool + }{ + {name: "under skip-errors", skipErrors: true}, + {name: "without skip-errors", skipErrors: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "stays.txt": []byte("stays"), + "removed.txt": []byte("removed"), + }) + env.setSnapshot("walk", "") + + // The previous snapshot has the file, so a removal the walk + // also counted as deleted would show. + env.backUp(t, "walk") + + env.v.Fs = &removeOnLookupFs{ + path: filepath.Join(env.src, "removed.txt"), + } + + env.out.Reset() + require.NoError(t, env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: tt.skipErrors, + Snapshots: []string{"walk"}, + })) + assert.Contains(t, env.out.String(), + "Files: 2 examined, 0 backed up, 1 unchanged, 1 failed.") + assert.Contains(t, env.out.String(), "Finished successfully.") + }) + } +} + +// A file an exclude pattern matches is not counted when it is removed +// before the walk reaches it. See +// https://git.eeqj.de/sneak/vaultik/issues/310. +func TestBackupIgnoresExcludedFileRemovedBeforeWalkReachesIt(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "stays.txt": []byte("stays"), + "removed.tmp": []byte("removed"), + }) + env.setSnapshot("walk", "", "*.tmp") + env.v.Fs = &removeOnLookupFs{ + path: filepath.Join(env.src, "removed.tmp"), + } + + require.NoError(t, env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + SkipErrors: true, + Snapshots: []string{"walk"}, + })) + assert.Contains(t, env.out.String(), filesLine(1, 1, 0)) + assert.Contains(t, env.out.String(), "Finished successfully.") +} + +// A backup under --skip-errors --prune that skipped a file it could not +// read does not prune: the previous snapshot, the only one that holds +// the file, is kept, and the output says the prune was skipped. See +// https://git.eeqj.de/sneak/vaultik/issues/382. +func TestSkipErrorsBackupDoesNotPruneWhenItSkips(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "other.txt": []byte("other"), + "skipped.txt": []byte("skipped"), + }) + env.setSnapshot("photos", "") + env.backUp(t, "photos") + + // An unchanged file is not read again, so the file is changed before + // it becomes unreadable. + skipped := filepath.Join(env.src, "skipped.txt") + require.NoError(t, os.WriteFile(skipped, []byte("changed"), 0o600)) + env.v.Fs = &openFailFs{path: skipped, err: os.ErrPermission} + + env.out.Reset() + err := env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + SkipErrors: true, + Snapshots: []string{"photos"}, + }) + require.ErrorIs(t, err, vaultik.ErrFilesUnreadable) + assert.Contains(t, env.out.String(), + "Skipped the post-backup prune because 1 file(s) could not be read") + assert.NotContains(t, env.out.String(), "Running post-backup prune.") + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + context.Background(), listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 2, "the previous snapshot is kept") +} + +// A file removed during a backup under --skip-errors --prune is not a +// skipped file, so the backup prunes as usual. See +// https://git.eeqj.de/sneak/vaultik/issues/382. +func TestSkipErrorsBackupPrunesWhenAFileIsRemovedDuringIt(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newDeletedCountEnv(t, map[string][]byte{ + "other.txt": []byte("other"), + "removed.txt": []byte("removed"), + }) + env.setSnapshot("photos", "") + env.backUp(t, "photos") + + env.v.Fs = &removeOnLookupFs{path: filepath.Join(env.src, "removed.txt")} + + require.NoError(t, env.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Prune: true, + SkipErrors: true, + Snapshots: []string{"photos"}, + })) + + snapshots, err := env.v.Repositories.Snapshots.ListRecent( + context.Background(), listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "the previous snapshot is pruned") +} diff --git a/internal/vaultik/snapshot_summary_test.go b/internal/vaultik/snapshot_summary_test.go new file mode 100644 index 0000000..1385637 --- /dev/null +++ b/internal/vaultik/snapshot_summary_test.go @@ -0,0 +1,402 @@ +package vaultik_test + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/sys/unix" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// These tests cover https://git.eeqj.de/sneak/vaultik/issues/225: the +// summary printed after a backup, and the statistics stored in the +// snapshots table, count each file, byte and upload once, and a --cron +// run records its uploads. + +// summaryUploadDelay slows every blob upload, so a run's upload time is +// at least this long per blob even on a local store. +const summaryUploadDelay = 20 * time.Millisecond + +// summaryEnv is a backup setup whose user-facing output is kept in out. +type summaryEnv struct { + v *vaultik.Vaultik + db *database.DB + repos *database.Repositories + out *bytes.Buffer + + // aPath is a.bin, whose content copy.bin repeats; aSize is its size + // and totalSize the size of all three source files. + aPath string + aSize int64 + totalSize int64 +} + +// newSummaryEnv writes src/one/a.bin, src/one/small.txt and +// src/two/copy.bin, a copy of a.bin. Every chunk of copy.bin is therefore +// already stored by the time the backup reaches it. +// +// The snapshot names "first" and "second" back up src; "split" backs up +// src/one and src/two as two paths. +func newSummaryEnv(t *testing.T) *summaryEnv { + t.Helper() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + srcDir := filepath.Join(tempDir, "src") + dirOne := filepath.Join(srcDir, "one") + dirTwo := filepath.Join(srcDir, "two") + dbPath := filepath.Join(tempDir, "index.sqlite") + ctx := context.Background() + + aContent := bytesPattern("a-", int(3*faultChunkSize)) + smallContent := []byte("hello vaultik") + files := map[string][]byte{ + filepath.Join(dirOne, "a.bin"): aContent, + filepath.Join(dirOne, "small.txt"): smallContent, + filepath.Join(dirTwo, "copy.bin"): aContent, + } + + for path, content := range files { + require.NoError(t, fs.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, afero.WriteFile(fs, path, content, 0o644)) + } + + cfg := faultTestConfig() + cfg.IndexPath = dbPath + cfg.ChunkSize = config.Size(faultChunkSize) + cfg.Snapshots = map[string]config.SnapshotConfig{ + "first": {Paths: []string{srcDir}}, + "second": {Paths: []string{srcDir}}, + "split": {Paths: []string{dirOne, dirTwo}}, + } + + inner, err := storage.NewFileStorer(t.TempDir()) + require.NoError(t, err) + + store := faultstore.New(inner) + store.OnPut = func(key string) faultstore.PutAction { + if strings.HasPrefix(key, "blobs/") { + time.Sleep(summaryUploadDelay) + } + + return faultstore.PutNormal + } + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + out := &bytes.Buffer{} + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + v.UI = ui.NewWithColor(out, false) + + return &summaryEnv{ + v: v, + db: db, + repos: repos, + out: out, + aPath: filepath.Join(dirOne, "a.bin"), + aSize: int64(len(aContent)), + totalSize: int64(2*len(aContent) + len(smallContent)), + } +} + +// backUp runs a backup of the named snapshot and returns its output. +func (e *summaryEnv) backUp(t *testing.T, name string, cron bool) string { + t.Helper() + + e.out.Reset() + require.NoError(t, e.v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Cron: cron, + Snapshots: []string{name}, + })) + + return e.out.String() +} + +// snapshot returns the local snapshots row of the snapshot named name. +func (e *summaryEnv) snapshot(t *testing.T, name string) *database.Snapshot { + t.Helper() + + ctx := context.Background() + snap, err := e.repos.Snapshots.GetByID(ctx, + localSnapshotID(ctx, t, e.repos, name)) + require.NoError(t, err) + require.NotNil(t, snap) + + return snap +} + +// uploads returns how many blobs the snapshot uploaded and their +// total size, as recorded in the uploads table. +func (e *summaryEnv) uploads(t *testing.T, snapshotID string) (int64, int64) { + t.Helper() + + var count, size int64 + + err := e.db.Conn().QueryRowContext(context.Background(), ` + SELECT COUNT(*), COALESCE(SUM(size), 0) + FROM uploads WHERE snapshot_id = ?`, snapshotID).Scan(&count, &size) + require.NoError(t, err) + + return count, size +} + +// referencedBlobSizes returns the compressed and uncompressed sizes of +// all blobs the snapshot references. +func (e *summaryEnv) referencedBlobSizes( + t *testing.T, snapshotID string, +) (int64, int64) { + t.Helper() + + var compressed, uncompressed int64 + + err := e.db.Conn().QueryRowContext(context.Background(), ` + SELECT COALESCE(SUM(b.compressed_size), 0), + COALESCE(SUM(b.uncompressed_size), 0) + FROM snapshot_blobs sb JOIN blobs b ON b.blob_hash = sb.blob_hash + WHERE sb.snapshot_id = ?`, snapshotID).Scan(&compressed, &uncompressed) + require.NoError(t, err) + + return compressed, uncompressed +} + +// filesLine returns the summary's line of file counts. +func filesLine(examined, backedUp, unchanged int) string { + return fmt.Sprintf("Files: %d examined, %d backed up, %d unchanged.", + examined, backedUp, unchanged) +} + +// dataLine returns the summary's line of byte counts. +func (e *summaryEnv) dataLine(total, backedUp int64) string { + return fmt.Sprintf("Data: %s total (%s backed up).", + e.v.UI.Size(total), e.v.UI.Size(backedUp)) +} + +// enumeratedLine returns the line printed when the walk of a source path +// ends. +func (e *summaryEnv) enumeratedLine( + files int, total int64, toBackUp int, toBackUpSize int64, +) string { + return fmt.Sprintf( + "Enumerated %d snapshot source files (%s total), %d to back up (%s).", + files, e.v.UI.Size(total), toBackUp, e.v.UI.Size(toBackUpSize)) +} + +// snapshotPaths returns the paths the snapshot lists, sorted. +func (e *summaryEnv) snapshotPaths(t *testing.T, snapshotID string) []string { + t.Helper() + + rows, err := e.db.Conn().QueryContext(context.Background(), ` + SELECT f.path FROM snapshot_files sf JOIN files f ON f.id = sf.file_id + WHERE sf.snapshot_id = ? ORDER BY f.path`, snapshotID) + require.NoError(t, err) + + defer func() { _ = rows.Close() }() + + var paths []string + + for rows.Next() { + var path string + + require.NoError(t, rows.Scan(&path)) + + paths = append(paths, path) + } + + require.NoError(t, rows.Err()) + + return paths +} + +// A first backup stores copy.bin's chunks while backing up a.bin, so +// copy.bin's chunks are deduplicated within the run. Each file and byte +// is still counted once. +func TestSnapshotSummaryFirstRun(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newSummaryEnv(t) + + summary := env.backUp(t, "first", false) + + assert.Contains(t, summary, filesLine(3, 3, 0)) + assert.Contains(t, summary, env.dataLine(env.totalSize, env.totalSize)) + + snap := env.snapshot(t, "first") + uploadCount, uploadBytes := env.uploads(t, snap.ID.String()) + require.Positive(t, uploadCount) + + assert.Contains(t, summary, fmt.Sprintf("Upload: %d blobs, %s in ", + uploadCount, env.v.UI.Size(uploadBytes))) + + assert.Equal(t, int64(3), snap.FileCount) + assert.Equal(t, env.totalSize, snap.TotalSize) + assert.Equal(t, uploadCount, snap.BlobCount) + assert.Equal(t, uploadBytes, snap.UploadBytes) +} + +// An incremental backup where a.bin's mtime changed but its content did +// not: a.bin is backed up again and every one of its chunks is already +// stored. +func TestSnapshotSummaryIncrementalRunWithDeduplicatedChunks(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newSummaryEnv(t) + + env.backUp(t, "first", false) + + later := time.Now().Add(time.Hour) + require.NoError(t, os.Chtimes(env.aPath, later, later)) + + summary := env.backUp(t, "second", false) + + assert.Contains(t, summary, filesLine(3, 1, 2)) + assert.Contains(t, summary, env.dataLine(env.totalSize, env.aSize)) + assert.NotContains(t, summary, "Upload:") + + snap := env.snapshot(t, "second") + compressed, uncompressed := env.referencedBlobSizes(t, snap.ID.String()) + require.Positive(t, compressed) + + assert.Equal(t, env.totalSize, snap.TotalSize) + assert.Zero(t, snap.ChunkCount) + assert.Zero(t, snap.BlobCount) + assert.Zero(t, snap.UploadBytes) + assert.Equal(t, compressed, snap.BlobSize, + "blob_size must total the blobs the snapshot references") + assert.Equal(t, uncompressed, snap.BlobUncompressedSize) +} + +// A backup of a tree with directories and a symlink, none of which +// changed since the last backup, backs up nothing, and the snapshot +// still lists every one of them. Both sides of the line that ends the +// walk count the same entries, the files and the symlink, and no +// directory's size. See https://git.eeqj.de/sneak/vaultik/issues/305. +func TestSnapshotSummaryUnchangedRunWithDirectoriesAndSymlink(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newSummaryEnv(t) + + const linkTarget = "a.bin" + + require.NoError(t, os.Symlink(linkTarget, + filepath.Join(filepath.Dir(env.aPath), "link"))) + + // A symlink's size is the length of its target. + total := env.totalSize + int64(len(linkTarget)) + + first := env.backUp(t, "first", false) + assert.Contains(t, first, env.enumeratedLine(4, total, 4, total)) + assert.Contains(t, first, filesLine(4, 4, 0)) + + second := env.backUp(t, "second", false) + assert.Contains(t, second, env.enumeratedLine(4, total, 0, 0)) + assert.Contains(t, second, filesLine(4, 0, 4)) + assert.Contains(t, second, env.dataLine(total, 0)) + + assert.Equal(t, + env.snapshotPaths(t, env.snapshot(t, "first").ID.String()), + env.snapshotPaths(t, env.snapshot(t, "second").ID.String())) +} + +// A directory whose mtime changed and a symlink whose target changed are +// recorded again by the next backup, which counts only the symlink as +// backed up. +func TestSnapshotSummaryChangedDirectoryAndSymlink(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newSummaryEnv(t) + + // The local index keeps paths with symlinks resolved. + dir, err := filepath.EvalSymlinks(filepath.Dir(env.aPath)) + require.NoError(t, err) + + // The new link gets the old one's mtime, and a target, which need not + // exist, of the old target's length, a symlink's size: only the + // target differs. + linkTime := unix.NsecToTimeval( + time.Date(2029, time.March, 4, 5, 6, 7, 0, time.UTC).UnixNano()) + link := filepath.Join(dir, "link") + require.NoError(t, os.Symlink("a.bin", link)) + require.NoError(t, unix.Lutimes(link, []unix.Timeval{linkTime, linkTime})) + + env.backUp(t, "first", false) + + require.NoError(t, os.Remove(link)) + require.NoError(t, os.Symlink("b.bin", link)) + require.NoError(t, unix.Lutimes(link, []unix.Timeval{linkTime, linkTime})) + + mtime := time.Date(2030, time.January, 2, 3, 4, 5, 0, time.UTC) + require.NoError(t, os.Chtimes(dir, mtime, mtime)) + + assert.Contains(t, env.backUp(t, "second", false), filesLine(4, 1, 3)) + + ctx := context.Background() + + dirRow, err := env.repos.Files.GetByPath(ctx, dir) + require.NoError(t, err) + require.NotNil(t, dirRow) + assert.Equal(t, mtime.Unix(), dirRow.MTime.Unix()) + + linkRow, err := env.repos.Files.GetByPath(ctx, link) + require.NoError(t, err) + require.NotNil(t, linkRow) + assert.Equal(t, "b.bin", linkRow.LinkTarget.String()) +} + +// Under --cron the progress reporter is off; the upload figures must +// still reach the summary and the snapshots row. The snapshot has two +// paths, each backed up by its own scan. +func TestSnapshotSummaryCronRunRecordsUploads(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + env := newSummaryEnv(t) + + summary := env.backUp(t, "split", true) + + snap := env.snapshot(t, "split") + uploadCount, uploadBytes := env.uploads(t, snap.ID.String()) + require.Positive(t, uploadCount) + + assert.Contains(t, summary, filesLine(3, 3, 0)) + assert.Contains(t, summary, env.dataLine(env.totalSize, env.totalSize)) + assert.Contains(t, summary, fmt.Sprintf("Upload: %d blobs, %s in ", + uploadCount, env.v.UI.Size(uploadBytes))) + + assert.Equal(t, env.totalSize, snap.TotalSize) + assert.Equal(t, uploadCount, snap.BlobCount, + "blob_count must count each blob once, however many paths the "+ + "snapshot has") + assert.Equal(t, uploadBytes, snap.UploadBytes) + assert.GreaterOrEqual(t, snap.UploadDurationMs, + uploadCount*summaryUploadDelay.Milliseconds()) + + compressed, uncompressed := env.referencedBlobSizes(t, snap.ID.String()) + require.Positive(t, uncompressed) + + assert.Equal(t, compressed, snap.BlobSize) + assert.Equal(t, uncompressed, snap.BlobUncompressedSize) + assert.InDelta(t, float64(compressed)/float64(uncompressed), + snap.CompressionRatio, 1e-9) +} diff --git a/internal/vaultik/storage_bind.go b/internal/vaultik/storage_bind.go index 2570d48..878ed69 100644 --- a/internal/vaultik/storage_bind.go +++ b/internal/vaultik/storage_bind.go @@ -9,54 +9,58 @@ import ( ) // errStorageBindingMismatch is returned when the local index database is -// bound to a different destination than the configured storage_url. +// bound to a different destination than the configured one. var errStorageBindingMismatch = errors.New( "local index is bound to a different backup destination") -// EnsureStorageBinding guarantees that the local index database is -// bound to the currently-configured storage destination. Every mutating -// command must call this before touching either the local index or the -// destination store, because the two live in lockstep: the local index -// records which chunks/blobs already exist at the destination, and -// mismatched destination + local index produces silent corruption (the -// scanner sees "known" chunks and skips uploads, then writes snapshots -// whose manifests reference blobs that aren't on the new destination). +// checkStorageBinding refuses when the local index database is bound to +// a different destination than the configured one, with an error that +// tells the user how to recover (revert the config, or run `vaultik +// database delete`). Every mutating command calls it before touching +// either the local index or the destination store, because the two live +// in lockstep: the local index records which chunks/blobs already exist +// at the destination, and a mismatched pair produces silent corruption +// (the scanner sees "known" chunks and skips uploads, then writes +// snapshots whose manifests reference blobs that aren't on the new +// destination). // -// Behaviour: -// - On first use (empty stored value), record the configured -// storage_url and log the binding. -// - When the stored value matches the configured storage_url, do -// nothing and return nil. -// - When the two differ, refuse with an error that tells the user -// how to recover (revert the config, or run `vaultik database -// purge` to discard the local index and rebuild against the new -// destination on the next backup). +// It records nothing. Only a backup binds the local index, through +// EnsureStorageBinding, and it does so before adding anything to it. An +// unbound local index therefore holds nothing from any destination. // // Read-only inspection commands (remote info, snapshot list, etc.) // deliberately don't call this: they can be run against a bare // destination store without any binding state. -func (v *Vaultik) EnsureStorageBinding() error { +func (v *Vaultik) checkStorageBinding() error { if v.Repositories == nil || v.Config == nil { // NewForTesting builds a Vaultik with no DB or config; - // there's nothing to bind and no binding to check. Callers - // exercising the bind path use a real DB and populate Config - // explicitly (see storage_bind_test.go). + // there's no binding to check. Callers exercising the bind + // path use a real DB and populate Config explicitly (see + // storage_bind_test.go). return nil } - configured := v.Config.StorageURL - if configured == "" { - // Some legacy configs still use the split s3.* keys instead of - // storage_url. Falling back to a synthetic URL for those would - // hide the fact that the binding is loose. Instead, treat - // unset as "nothing to bind against" — the check is - // necessarily best-effort for those configs. - return nil - } - - stored, err := v.Repositories.LocalMeta.Get(v.ctx, database.LocalMetaKeyStorageURL) + stored, configured, err := v.storageBinding() if err != nil { - return fmt.Errorf("reading local storage binding: %w", err) + return err + } + + if stored == "" || stored == configured { + return nil + } + + return fmt.Errorf("%w\n%s", + errStorageBindingMismatch, buildBindingMismatchMessage(stored, configured)) +} + +// EnsureStorageBinding records the configured destination (storage_url, +// or the s3.* endpoint, bucket and prefix) as the binding of an unbound +// local index. It refuses as checkStorageBinding does when the local +// index is bound to a different destination. +func (v *Vaultik) EnsureStorageBinding() error { + stored, configured, err := v.storageBinding() + if err != nil { + return err } if stored == "" { @@ -71,12 +75,33 @@ func (v *Vaultik) EnsureStorageBinding() error { return nil } - if stored == configured { - return nil + if stored != configured { + return fmt.Errorf("%w\n%s", + errStorageBindingMismatch, buildBindingMismatchMessage(stored, configured)) } - return fmt.Errorf("%w\n%s", - errStorageBindingMismatch, buildBindingMismatchMessage(stored, configured)) + return nil +} + +// storageBinding returns the destination the local index is bound to +// ("" when no binding is recorded yet), then the configured destination +// written the same way. It records nothing, so a read-only command can +// call it. +func (v *Vaultik) storageBinding() (string, string, error) { + configured := v.Config.StorageURL + if configured == "" { + // The s3.* form: bind on its endpoint, bucket and prefix, + // written the way storage_url would name the same destination. + s3 := v.Config.S3 + configured = "s3://" + s3.Bucket + "/" + s3.Prefix + "?endpoint=" + s3.Endpoint + } + + stored, err := v.Repositories.LocalMeta.Get(v.ctx, database.LocalMetaKeyStorageURL) + if err != nil { + return "", "", fmt.Errorf("reading local storage binding: %w", err) + } + + return stored, configured, nil } // buildBindingMismatchMessage assembles the multi-line explanation @@ -96,7 +121,8 @@ func buildBindingMismatchMessage(stored, configured string) string { "future snapshots referencing blobs that don't exist at the new destination.\n" + "\n" + "To proceed, either:\n" + - " - revert storage_url in your config to the bound destination, or\n" + + " - revert storage_url (or the s3.* endpoint, bucket and prefix) in your\n" + + " config to the bound destination, or\n" + " - run 'vaultik database delete' to discard the local index and rebuild it\n" + " from a fresh full backup against the new destination" } diff --git a/internal/vaultik/storage_bind_test.go b/internal/vaultik/storage_bind_test.go index a2f8272..e517a9e 100644 --- a/internal/vaultik/storage_bind_test.go +++ b/internal/vaultik/storage_bind_test.go @@ -2,6 +2,7 @@ package vaultik_test import ( "context" + "path/filepath" "testing" "github.com/stretchr/testify/assert" @@ -9,9 +10,126 @@ import ( "sneak.berlin/go/vaultik/internal/config" "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/storage/faultstore" "sneak.berlin/go/vaultik/internal/vaultik" ) +// storageBindingOf returns the destination the local index is bound to, +// or "" when it is not bound. +func storageBindingOf( + ctx context.Context, t *testing.T, repos *database.Repositories, +) string { + t.Helper() + + got, err := repos.LocalMeta.Get(ctx, database.LocalMetaKeyStorageURL) + require.NoError(t, err) + + return got +} + +// TestFailedFirstBackupLeavesIndexUnbound checks that a first backup +// the destination refuses, as a mistyped bucket would, leaves the local +// index unbound, so a backup with the corrected destination succeeds. +func TestFailedFirstBackupLeavesIndexUnbound(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := t.TempDir() + v, repos := newFileDestinationVaultik(ctx, t, storeDir) + working := v.Storage + + refusing := faultstore.New(working) + refusing.OnPut = func(string) faultstore.PutAction { return faultstore.PutFail } + refusing.OnStat = func(string) bool { return true } + v.Storage = refusing + v.Config.StorageURL = "file://" + filepath.Join(t.TempDir(), "typo") + + require.ErrorIs(t, backUp(v, "first"), faultstore.ErrInjectedUpload) + assert.Empty(t, storageBindingOf(ctx, t, repos)) + + v.Storage = working + v.Config.StorageURL = "file://" + storeDir + + require.NoError(t, backUp(v, "first")) + assert.Equal(t, "file://"+storeDir, storageBindingOf(ctx, t, repos)) +} + +// TestBackupToOtherDestinationWritesNoMarker checks that a backup +// refuses a local index bound to a different destination before it +// writes the marker to the configured one. +func TestBackupToOtherDestinationWritesNoMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + firstDir := t.TempDir() + v, _ := newFileDestinationVaultik(ctx, t, firstDir) + v.Config.StorageURL = "file://" + firstDir + + require.NoError(t, backUp(v, "first")) + + secondDir := t.TempDir() + secondStore, err := storage.NewFileStorer(secondDir) + require.NoError(t, err) + + v.Storage = secondStore + v.Config.StorageURL = "file://" + secondDir + + require.ErrorContains(t, backUp(v, "first"), + "local index is bound to a different backup destination") + assert.NoFileExists(t, filepath.Join(secondDir, markerFile)) +} + +// TestCommandsOtherThanBackupLeaveIndexUnbound checks that commands +// other than a backup do not bind an unbound local index, whether or not +// they fail. Each runs on a fresh local index. +func TestCommandsOtherThanBackupLeaveIndexUnbound(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + tests := []struct { + name string + run func(v *vaultik.Vaultik) error + }{ + {"prune", func(v *vaultik.Vaultik) error { + return v.Prune(&vaultik.PruneOptions{Force: true}) + }}, + {"snapshot purge", func(v *vaultik.Vaultik) error { + return v.PurgeSnapshotsWithOptions( + &vaultik.SnapshotPurgeOptions{KeepLatest: true, Force: true}) + }}, + {"snapshot remove", func(v *vaultik.Vaultik) error { + _, err := v.RemoveSnapshot("host_first_2026-01-02T03:04:05Z", + &vaultik.RemoveOptions{Force: true}) + + return err + }}, + {"snapshot remove --all", func(v *vaultik.Vaultik) error { + _, err := v.RemoveAllSnapshots(&vaultik.RemoveOptions{Force: true}) + + return err + }}, + {"remote nuke", func(v *vaultik.Vaultik) error { + return v.NukeRemote(true) + }}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + v, repos := newFileDestinationVaultik(ctx, t, t.TempDir()) + + _ = tt.run(v) + + assert.Empty(t, storageBindingOf(ctx, t, repos)) + }) + } +} + // buildBindTestVaultik returns a minimal Vaultik wired with a real // in-memory DB and a config carrying the given StorageURL. Enough to // exercise EnsureStorageBinding without spinning up storage or fx. @@ -76,3 +194,51 @@ func TestEnsureStorageBinding_MismatchRefuses(t *testing.T) { assert.Contains(t, err.Error(), "file:///mnt/backups/new") assert.Contains(t, err.Error(), "vaultik database delete") } + +// A config with no storage_url names its destination with s3.endpoint, +// s3.bucket and s3.prefix; a change to any of them must be refused just +// as a changed storage_url is. +func TestEnsureStorageBinding_S3FieldsChangeRefuses(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + bound := config.S3Config{ + Endpoint: "https://s3.example.com", + Bucket: "bucket-a", + Prefix: "backups", + } + + tests := []struct { + name string + changed config.S3Config + }{ + {"bucket", config.S3Config{ + Endpoint: bound.Endpoint, Bucket: "bucket-b", Prefix: bound.Prefix, + }}, + {"prefix", config.S3Config{ + Endpoint: bound.Endpoint, Bucket: bound.Bucket, Prefix: "other", + }}, + {"endpoint", config.S3Config{ + Endpoint: "https://s3.other.com", Bucket: bound.Bucket, Prefix: bound.Prefix, + }}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + tv, _ := buildBindTestVaultik(t, "") + + tv.Config.S3 = bound + require.NoError(t, tv.EnsureStorageBinding(), "first use binds") + require.NoError(t, tv.EnsureStorageBinding(), "same destination passes") + + tv.Config.S3 = tt.changed + err := tv.EnsureStorageBinding() + require.Error(t, err) + assert.Contains(t, err.Error(), + "local index is bound to a different backup destination") + assert.Contains(t, err.Error(), "vaultik database delete") + }) + } +} diff --git a/internal/vaultik/symlinked_destination_test.go b/internal/vaultik/symlinked_destination_test.go new file mode 100644 index 0000000..934ca00 --- /dev/null +++ b/internal/vaultik/symlinked_destination_test.go @@ -0,0 +1,147 @@ +package vaultik_test + +import ( + "context" + "io/fs" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestPruneDeletesNothingThroughSymlinkedDirectory checks that prune keeps +// every blob and the local snapshot record when the metadata/ or blobs/ +// directory of a file:// destination is a symlink to a directory elsewhere +// (https://git.eeqj.de/sneak/vaultik/issues/296). A backup writes through +// such a link, so prune has to list through it too. +func TestPruneDeletesNothingThroughSymlinkedDirectory(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + for _, dir := range []string{"metadata", "blobs"} { + t.Run(dir, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + blobFiles := blobFilesIn(t, storeDir) + moveBehindSymlink(t, storeDir, dir) + + require.NoError(t, v.Prune(&vaultik.PruneOptions{Force: true})) + + // When blobs/ is the link, these paths run through it. + for _, blobFile := range blobFiles { + assert.FileExists(t, blobFile, "prune must delete no blob") + } + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "prune must delete no local snapshot record") + }) + } +} + +// TestPruneFailsOnSymlinkedDirectoryWithMissingTarget checks that prune +// fails, deleting no blob and keeping the local snapshot record, when the +// metadata/ or blobs/ directory of a file:// destination is a symlink +// whose target is missing, as a link to a volume that is not mounted is. +func TestPruneFailsOnSymlinkedDirectoryWithMissingTarget(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + for _, dir := range []string{"metadata", "blobs"} { + t.Run(dir, func(t *testing.T) { + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, repos, _ := backUpToFileDestination(ctx, t, storeDir) + blobFiles := blobFilesIn(t, storeDir) + targetPath := moveBehindSymlink(t, storeDir, dir) + + // Unmount the volume the link points to, and mount it again + // once prune has run. + unmountedPath := targetPath + "-unmounted" + require.NoError(t, os.Rename(targetPath, unmountedPath)) + + err := v.Prune(&vaultik.PruneOptions{Force: true}) + require.ErrorIs(t, err, fs.ErrNotExist) + + require.NoError(t, os.Rename(unmountedPath, targetPath)) + + // When blobs/ is the link, these paths run through it. + for _, blobFile := range blobFiles { + assert.FileExists(t, blobFile, "prune must delete no blob") + } + + snapshots, err := repos.Snapshots.ListRecent(ctx, listRecentTestLimit) + require.NoError(t, err) + assert.Len(t, snapshots, 1, "prune must delete no local snapshot record") + }) + } +} + +// TestRemoveSnapshotWarnsOnSymlinkedMetadataWithMissingTarget checks that +// snapshot remove warns that the metadata could not be removed from the +// destination when metadata/ is a symlink whose target is missing, as it +// does when the destination directory is missing, instead of finding no +// metadata to remove. +func TestRemoveSnapshotWarnsOnSymlinkedMetadataWithMissingTarget(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + ctx := context.Background() + storeDir := filepath.Join(t.TempDir(), "store") + v, repos, out := backUpToFileDestination(ctx, t, storeDir) + targetPath := moveBehindSymlink(t, storeDir, "metadata") + require.NoError(t, os.Rename(targetPath, targetPath+"-unmounted")) + + result, err := v.RemoveSnapshot(localSnapshotID(ctx, t, repos, "first"), + &vaultik.RemoveOptions{Force: true}) + require.NoError(t, err) + + assert.False(t, result.RemoteRemoved) + assert.Contains(t, out.String(), + "Could not remove snapshot metadata from remote") + assert.NotContains(t, out.String(), + "Removed snapshot metadata from remote storage") +} + +// blobFilesIn returns the paths of the blob files under storeDir/blobs, and +// fails the test when there are none. +func blobFilesIn(t *testing.T, storeDir string) []string { + t.Helper() + + var blobFiles []string + + err := filepath.WalkDir(filepath.Join(storeDir, "blobs"), + func(path string, entry fs.DirEntry, err error) error { + if err == nil && !entry.IsDir() { + blobFiles = append(blobFiles, path) + } + + return err + }) + require.NoError(t, err) + require.NotEmpty(t, blobFiles) + + return blobFiles +} + +// moveBehindSymlink moves storeDir/dir to a directory elsewhere, puts a +// symlink to it in its place, and returns where it went. +func moveBehindSymlink(t *testing.T, storeDir, dir string) string { + t.Helper() + + linkPath := filepath.Join(storeDir, dir) + targetPath := filepath.Join(t.TempDir(), dir) + require.NoError(t, os.Rename(linkPath, targetPath)) + require.NoError(t, os.Symlink(targetPath, linkPath)) + + return targetPath +} diff --git a/internal/vaultik/two_path_snapshot_test.go b/internal/vaultik/two_path_snapshot_test.go new file mode 100644 index 0000000..e6673c9 --- /dev/null +++ b/internal/vaultik/two_path_snapshot_test.go @@ -0,0 +1,70 @@ +package vaultik_test + +import ( + "context" + "maps" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// A backup without --cron runs the progress reporter while one scanner +// scans each path of the snapshot in turn. See +// https://git.eeqj.de/sneak/vaultik/issues/253. +func TestBackupWithoutCronOfTwoPathSnapshotRestoresBothPaths(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const snapshotName = "data" + + fs := afero.NewOsFs() + tempDir := t.TempDir() + firstDir := filepath.Join(tempDir, "first") + secondDir := filepath.Join(tempDir, "second") + storeDir := t.TempDir() + restoreDir := filepath.Join(tempDir, "restored") + dbPath := filepath.Join(tempDir, "index.sqlite") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, firstDir) + maps.Copy(files, writeFaultSourceTree(t, fs, secondDir)) + + cfg := faultTestConfig() + cfg.IndexPath = dbPath + cfg.ChunkSize = config.Size(faultChunkSize) + cfg.Snapshots = map[string]config.SnapshotConfig{ + snapshotName: {Paths: []string{firstDir, secondDir}}, + } + + store, err := storage.NewFileStorer(storeDir) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, v.CreateSnapshot(&vaultik.SnapshotCreateOptions{ + Snapshots: []string{snapshotName}, + })) + + id := localSnapshotID(ctx, t, repos, snapshotName) + require.NoError(t, db.Close()) + + reader := newReaderVaultik(ctx, cfg, store, nil, fs) + require.NoError(t, reader.Restore(&vaultik.RestoreOptions{ + SnapshotID: id, + TargetDir: restoreDir, + Verify: true, + })) + + assertRestoredTree(t, fs, restoreDir, files) +} diff --git a/internal/vaultik/uncompressed_size_test.go b/internal/vaultik/uncompressed_size_test.go new file mode 100644 index 0000000..9d8fd8e --- /dev/null +++ b/internal/vaultik/uncompressed_size_test.go @@ -0,0 +1,85 @@ +package vaultik_test + +import ( + "bytes" + "context" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/database" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/storage" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestUncompressedSizeOfChangedFileStaysFixed covers +// https://git.eeqj.de/sneak/vaultik/issues/360. A backup that changes a +// file leaves the earlier snapshot's UNCOMPRESSED SIZE as it was when that +// snapshot's backup completed. The file's row in the local index is shared +// by both snapshots and rewritten by the second backup. +func TestUncompressedSizeOfChangedFileStaysFixed(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + dataDir := filepath.Join(tempDir, "src") + dbPath := filepath.Join(tempDir, "index.sqlite") + changedPath := filepath.Join(dataDir, "changed.bin") + + ctx := context.Background() + files := writeFaultSourceTree(t, fs, dataDir) + cfg := changedFileConfig(dataDir, dbPath) + + appendRandomBytes(t, fs, files, changedPath, appendedFileSize) + + store, err := storage.NewFileStorer(t.TempDir()) + require.NoError(t, err) + + db, err := database.New(ctx, dbPath) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + repos := database.NewRepositories(db) + v := newBackupVaultik(ctx, cfg, store, repos, db, fs) + + require.NoError(t, backUp(v, "first")) + + // With nothing to compare against, sizeOfNewChunks totals every + // distinct chunk of the files. + firstID := localSnapshotID(ctx, t, repos, "first") + firstSize := sizeOfNewChunks(t, files, nil) + require.Equal(t, firstSize, listedUncompressedSizes(t, v)[firstID], + "the first snapshot must count the chunks of every file it holds") + + appendRandomBytes(t, fs, files, changedPath, faultChunkSize) + require.NoError(t, backUp(v, "second")) + + secondID := localSnapshotID(ctx, t, repos, "second") + sizes := listedUncompressedSizes(t, v) + assert.Equal(t, firstSize, sizes[firstID], + "a later backup must not change the first snapshot's figure") + assert.Equal(t, sizeOfNewChunks(t, files, nil), sizes[secondID], + "the second snapshot must count the changed file's chunks") +} + +// listedUncompressedSizes runs `snapshot list --json` and returns each +// listed snapshot's uncompressed_size by snapshot ID. +func listedUncompressedSizes(t *testing.T, v *vaultik.Vaultik) map[string]int64 { + t.Helper() + + var out bytes.Buffer + + v.Stdout = &out + require.NoError(t, v.ListSnapshots(true)) + + sizes := make(map[string]int64) + for _, row := range decodeListJSON(t, out.String()) { + sizes[row.ID] = row.UncompressedSize + } + + return sizes +} diff --git a/internal/vaultik/unknown_snapshot_test.go b/internal/vaultik/unknown_snapshot_test.go new file mode 100644 index 0000000..33246ef --- /dev/null +++ b/internal/vaultik/unknown_snapshot_test.go @@ -0,0 +1,62 @@ +package vaultik_test + +import ( + "bytes" + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/config" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestUnknownSnapshotID checks that restore and verify, given an ID that +// names no snapshot in the local index or on the destination store, say +// so in the words `snapshot remove` uses and print nothing else. +func TestUnknownSnapshotID(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + const unknownID = "host1_home_2026-01-01T00:00:00Z" + + commands := map[string]func(v *vaultik.Vaultik) error{ + "restore": func(v *vaultik.Vaultik) error { + return v.Restore(&vaultik.RestoreOptions{ + SnapshotID: unknownID, + TargetDir: t.TempDir(), + }) + }, + "verify": func(v *vaultik.Vaultik) error { + return v.VerifySnapshotWithOptions(unknownID, &vaultik.VerifyOptions{}) + }, + "verify --deep": func(v *vaultik.Vaultik) error { + return v.VerifySnapshotWithOptions(unknownID, + &vaultik.VerifyOptions{Deep: true}) + }, + } + + for name, run := range commands { + t.Run(name, func(t *testing.T) { + t.Parallel() + + store := newTestStorer() + addManifest(t, store, "snapshot-001", nil) + + // A backup wrote to this destination, so it carries the marker. + require.NoError(t, store.Put(context.Background(), markerFile, + bytes.NewReader(nil))) + + tv := vaultik.NewForTesting(store) + tv.Config = &config.Config{AgeSecretKey: testAgeSecretKey} + tv.Repositories = newLocalIndex(t, "snapshot-001") + + err := run(tv.Vaultik) + + require.EqualError(t, err, "snapshot not found in the local "+ + "index or on the destination store: "+unknownID) + assert.Empty(t, tv.Stdout.String()) + }) + } +} diff --git a/internal/vaultik/vaultik.go b/internal/vaultik/vaultik.go index 3105147..7e85218 100644 --- a/internal/vaultik/vaultik.go +++ b/internal/vaultik/vaultik.go @@ -5,6 +5,7 @@ package vaultik import ( "bytes" "context" + "errors" "fmt" "io" "os" @@ -184,6 +185,12 @@ func (v *Vaultik) printlnStdout(args ...any) { _, _ = fmt.Fprintln(v.Stdout, args...) } +// ErrNotConfirmed is returned when a confirmation prompt gets any answer +// but the one it asks for (`y` or `Y`, or `yes` for `database delete`), or +// stdin ends first. Nothing the prompt asked about is deleted, and the +// command exits non-zero. +var ErrNotConfirmed = errors.New("deletion not confirmed") + // scanStdin reads a line of input from stdin. func (v *Vaultik) scanStdin(a ...any) (int, error) { return fmt.Fscanln(v.Stdin, a...) diff --git a/internal/vaultik/verify.go b/internal/vaultik/verify.go index cf43c62..0284e4a 100644 --- a/internal/vaultik/verify.go +++ b/internal/vaultik/verify.go @@ -17,6 +17,7 @@ import ( "sneak.berlin/go/vaultik/internal/database" "sneak.berlin/go/vaultik/internal/log" "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/storage" ) // Sentinel errors for snapshot verification failures. @@ -32,7 +33,9 @@ var ( errManifestExtraBlob = errors.New("manifest contains blob not in database") errManifestMissingBlob = errors.New( "manifest omits blob present in database") - errBlobSizeMismatch = errors.New("blob size mismatch") + errBlobSizeMismatch = errors.New("blob size mismatch") + errBlobsNotInStorage = errors.New( + "blobs missing from storage or stored with the wrong size") ) // verifyStatusFailed is the JSON status value for a failed verification. @@ -57,11 +60,25 @@ type VerifyResult struct { Missing int `json:"missing"` MissingSize int64 `json:"missing_size,omitempty"` Mismatched int `json:"mismatched,omitempty"` + // Unchecked lists the blobs shallow verify could not check, because + // storage answered with an error other than not-found, so whether + // they are present is unknown. + Unchecked []UncheckedBlob `json:"unchecked,omitempty"` // DatabaseMissing is set by shallow verify when the snapshot's // encrypted database (metadata//db.zst.age) is absent, which // makes the snapshot unrestorable regardless of the blobs. - DatabaseMissing bool `json:"database_missing,omitempty"` - ErrorMessage string `json:"error,omitempty"` + DatabaseMissing bool `json:"database_missing,omitempty"` + // DatabaseCheckError is set by shallow verify to the error storage + // returned when the encrypted database could not be checked. + DatabaseCheckError string `json:"database_check_error,omitempty"` + ErrorMessage string `json:"error,omitempty"` +} + +// UncheckedBlob is a blob shallow verify could not check, with the error +// storage returned for it. +type UncheckedBlob struct { + Hash string `json:"hash"` + Error string `json:"error"` } // deepVerifyFailure records a failure in the result and returns it appropriately @@ -103,12 +120,17 @@ func (v *Vaultik) RunDeepVerify(snapshotID string, opts *VerifyOptions) error { log.Info("Starting snapshot verification", "snapshot_id", snapshotID, "mode", "deep") - if !opts.JSON { + remoteKey, err := v.resolveSnapshotRemoteKey(snapshotID) + if err != nil { + return v.deepVerifyFailure(result, opts, err.Error(), err) + } + + if !opts.JSON && !v.UI.Quiet() { v.stdoutf("Deep verification of snapshot: %s\n\n", snapshotID) } manifest, tempDB, dbBlobs, err := v.loadVerificationData( - snapshotID, opts, result, identities) + snapshotID, remoteKey, opts, result, identities) if err != nil { return err } @@ -135,7 +157,6 @@ func (v *Vaultik) RunDeepVerify(snapshotID string, opts *VerifyOptions) error { } result.Status = "ok" - result.Verified = len(dbBlobs) if opts.JSON { return v.outputVerifyJSON(result) @@ -143,35 +164,30 @@ func (v *Vaultik) RunDeepVerify(snapshotID string, opts *VerifyOptions) error { log.Info("✓ Verification completed successfully", "snapshot_id", snapshotID, "mode", "deep", "blobs_verified", len(dbBlobs)) - v.stdoutf("\n✓ Verification completed successfully\n") - v.stdoutf(" Snapshot: %s\n", snapshotID) - v.stdoutf(" Blobs verified: %d\n", len(dbBlobs)) - v.stdoutf(" Total size: %s\n", ubytes(totalSize)) + + if !v.UI.Quiet() { + v.stdoutf("\n✓ Verification completed successfully\n") + v.stdoutf(" Snapshot: %s\n", snapshotID) + v.stdoutf(" Blobs verified: %d\n", len(dbBlobs)) + v.stdoutf(" Total size: %s\n", ubytes(totalSize)) + } return nil } -// loadVerificationData downloads manifest, database, and blob list for verification +// loadVerificationData downloads manifest, database, and blob list for +// verification of the snapshot at remoteKey, which +// resolveSnapshotRemoteKey returned for snapshotID. func (v *Vaultik) loadVerificationData( - snapshotID string, opts *VerifyOptions, result *VerifyResult, + snapshotID, remoteKey string, opts *VerifyOptions, result *VerifyResult, identities []age.Identity, ) (*snapshot.Manifest, *tempDB, []snapshot.BlobInfo, error) { - // Resolve the identifier to the snapshot's remote key. A human ID is - // hashed; a remote key (or its abbreviation, as printed for a - // remote-only snapshot) is used as-is, so a host with no local index - // can verify a snapshot it can only see on the store. - remoteKey, err := v.resolveSnapshotRemoteKey(snapshotID) - if err != nil { - return nil, nil, nil, v.deepVerifyFailure(result, opts, - fmt.Sprintf("resolving snapshot identifier: %v", err), err) - } - // Download manifest. downloadManifestByKey is the single reader for // remote manifests; see its doc comment. log.Info("Downloading manifest", "remote_key", remoteKey) - if !opts.JSON { - v.stdoutf("Downloading manifest...\n") + if !opts.JSON && !v.UI.Quiet() { + v.UI.Beginf("Downloading manifest...") } manifest, err := v.downloadManifestByKey(remoteKey) @@ -185,10 +201,10 @@ func (v *Vaultik) loadVerificationData( "manifest_blob_count", manifest.BlobCount, "manifest_total_size", ubytes(manifest.TotalCompressedSize)) - if !opts.JSON { - v.stdoutf("Manifest loaded: %d blobs (%s)\n", + if !opts.JSON && !v.UI.Quiet() { + v.UI.Completef("Manifest loaded: %d blobs (%s)", manifest.BlobCount, ubytes(manifest.TotalCompressedSize)) - v.stdoutf("Downloading and decrypting database...\n") + v.UI.Beginf("Downloading and decrypting database...") } tdb, err := v.downloadVerifiedSnapshotDB( @@ -215,8 +231,8 @@ func (v *Vaultik) loadVerificationData( "db_blob_count", len(dbBlobs), "db_total_size", ubytes(dbTotalSize)) - if !opts.JSON { - v.stdoutf("Database loaded: %d blobs (%s)\n", + if !opts.JSON && !v.UI.Quiet() { + v.UI.Completef("Database loaded: %d blobs (%s)", len(dbBlobs), ubytes(dbTotalSize)) } @@ -243,9 +259,15 @@ func (v *Vaultik) downloadVerifiedSnapshotDB( fmt.Errorf("failed to download database: %w", err)) } + dbReader = newCloseOnCancelReader(v.ctx, dbReader) + defer func() { _ = dbReader.Close() }() tdb, err := v.decryptAndLoadDatabase(dbReader, identities) + if errors.Is(err, errWrongPrivateKey) { + return nil, v.deepVerifyFailure(result, opts, err.Error(), err) + } + if err != nil { return nil, v.deepVerifyFailure(result, opts, fmt.Sprintf("failed to decrypt database: %v", err), @@ -273,8 +295,8 @@ func (v *Vaultik) runVerificationSteps( totalSize int64, identities []age.Identity, ) error { - if !opts.JSON { - v.stdoutf("Verifying manifest against database...\n") + if !opts.JSON && !v.UI.Quiet() { + v.UI.Beginf("Verifying manifest against database...") } err := v.verifyManifestAgainstDatabase(manifest, dbBlobs) @@ -282,23 +304,24 @@ func (v *Vaultik) runVerificationSteps( return v.deepVerifyFailure(result, opts, err.Error(), err) } - if !opts.JSON { - v.stdoutf("Manifest verified.\n") - v.stdoutf("Checking blob existence in remote storage...\n") + if !opts.JSON && !v.UI.Quiet() { + v.UI.Completef("Manifest verified.") + v.UI.Beginf("Checking blob existence in remote storage...") } - err = v.verifyBlobExistenceFromDB(dbBlobs) + err = v.verifyBlobExistenceFromDB(dbBlobs, result) if err != nil { return v.deepVerifyFailure(result, opts, err.Error(), err) } - if !opts.JSON { - v.stdoutf("All blobs exist.\n") - v.stdoutf("Downloading and verifying blob contents (%d blobs, %s)...\n", + if !opts.JSON && !v.UI.Quiet() { + v.UI.Completef("All blobs exist.") + v.UI.Beginf("Downloading and verifying blob contents (%d blobs, %s)...", len(dbBlobs), ubytes(totalSize)) } - err = v.performDeepVerificationFromDB(dbBlobs, tdb.db.Conn(), opts, identities) + err = v.performDeepVerificationFromDB( + dbBlobs, tdb.db.Conn(), opts, result, identities) if err != nil { return v.deepVerifyFailure(result, opts, err.Error(), err) } @@ -329,9 +352,9 @@ func (v *Vaultik) decryptAndLoadDatabase( reader io.ReadCloser, identities []age.Identity, ) (*tempDB, error) { // Decrypt and decompress through the shared blobgen reader. - blobReader, err := blobgen.NewReader(reader, identities...) + blobReader, err := v.newSnapshotDBReader(reader, identities) if err != nil { - return nil, fmt.Errorf("failed to create decryption reader: %w", err) + return nil, err } defer func() { _ = blobReader.Close() }() @@ -404,7 +427,11 @@ func (v *Vaultik) verifyBlob( // the plaintext as it is read. A blob's hash — its remote name — is the // double SHA-256 of that plaintext (see blobgen.DoubleSHA256), not of the // encrypted bytes. - blobReader, err := blobgen.NewReader(reader, identities...) + blobReader, err := v.newBlobReader(reader, identities) + if errors.Is(err, errWrongPrivateKeyForBlob) { + return err + } + if err != nil { return fmt.Errorf("failed to create blob reader: %w", err) } @@ -650,9 +677,15 @@ func (v *Vaultik) verifyManifestAgainstDatabase( return nil } -// verifyBlobExistenceFromDB checks that all blobs from database exist in S3 -func (v *Vaultik) verifyBlobExistenceFromDB(blobs []snapshot.BlobInfo) error { - log.Info("Verifying blob existence in S3", "blob_count", len(blobs)) +// verifyBlobExistenceFromDB checks that every blob from the database is +// in storage with the size the database records. It checks them all, +// counting the missing and wrong-size blobs in result, and fails if it +// found any. Any storage error other than not found stops the check and +// fails with that error. +func (v *Vaultik) verifyBlobExistenceFromDB( + blobs []snapshot.BlobInfo, result *VerifyResult, +) error { + log.Info("Verifying blob existence in storage", "blob_count", len(blobs)) for i, blob := range blobs { // The hash is read from the snapshot database, which is not @@ -664,17 +697,23 @@ func (v *Vaultik) verifyBlobExistenceFromDB(blobs []snapshot.BlobInfo) error { // Construct blob path blobPath := fmt.Sprintf("blobs/%s/%s/%s", blob.Hash[:2], blob.Hash[2:4], blob.Hash) - // Check blob exists stat, err := v.Storage.Stat(v.ctx, blobPath) - if err != nil { - return fmt.Errorf("blob %s missing from storage: %w", blob.Hash, err) - } + switch { + case errors.Is(err, storage.ErrNotFound): + log.Warn("Blob missing from storage", "hash", blob.Hash) - // Verify size matches - if stat.Size != blob.CompressedSize { - return fmt.Errorf( - "%w: blob %s: S3 has %d bytes, database has %d bytes", - errBlobSizeMismatch, blob.Hash, stat.Size, blob.CompressedSize) + result.Missing++ + result.MissingSize += blob.CompressedSize + case err != nil: + return fmt.Errorf("could not check blob %s in storage: %w", + blob.Hash, err) + case stat.Size != blob.CompressedSize: + log.Warn("Blob has the wrong size in storage", + "hash", blob.Hash, + "storage_size", stat.Size, + "database_size", blob.CompressedSize) + + result.Mismatched++ } // Progress update every 100 blobs @@ -688,16 +727,22 @@ func (v *Vaultik) verifyBlobExistenceFromDB(blobs []snapshot.BlobInfo) error { } } + if result.Missing > 0 || result.Mismatched > 0 { + return fmt.Errorf("%w: %d missing, %d with the wrong size", + errBlobsNotInStorage, result.Missing, result.Mismatched) + } + log.Info("✓ All blobs exist in storage") return nil } // performDeepVerificationFromDB downloads and verifies the content of -// each blob using the database as source. +// each blob using the database as source, stopping at the first blob that +// fails. Each blob that passes is counted in result.Verified. func (v *Vaultik) performDeepVerificationFromDB( blobs []snapshot.BlobInfo, db *sql.DB, opts *VerifyOptions, - identities []age.Identity, + result *VerifyResult, identities []age.Identity, ) error { // Calculate total bytes for ETA var totalBytesExpected int64 @@ -720,6 +765,7 @@ func (v *Vaultik) performDeepVerificationFromDB( return fmt.Errorf("blob %s verification failed: %w", blobInfo.Hash, err) } + result.Verified++ bytesProcessed += blobInfo.CompressedSize elapsed := time.Since(startTime) remaining := len(blobs) - (i + 1) @@ -748,8 +794,8 @@ func (v *Vaultik) performDeepVerificationFromDB( "eta", eta.Round(time.Second), ) - if !opts.JSON { - v.stdoutf(" Verified %d/%d blobs (%d remaining) - %s/%s - elapsed %s, eta %s\n", + if !opts.JSON && !v.UI.Quiet() { + v.UI.Progressf("Verified %d/%d blobs (%d remaining) - %s/%s - elapsed %s, eta %s", i+1, len(blobs), remaining, ubytes(bytesProcessed), ubytes(totalBytesExpected), diff --git a/internal/vaultik/verify_quiet_test.go b/internal/vaultik/verify_quiet_test.go new file mode 100644 index 0000000..bc3b26e --- /dev/null +++ b/internal/vaultik/verify_quiet_test.go @@ -0,0 +1,150 @@ +package vaultik_test + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "testing" + + "github.com/spf13/afero" + "github.com/stretchr/testify/require" + "sneak.berlin/go/vaultik/internal/log" + "sneak.berlin/go/vaultik/internal/snapshot" + "sneak.berlin/go/vaultik/internal/ui" + "sneak.berlin/go/vaultik/internal/vaultik" +) + +// TestVerify_QuietSuppressesReport is the --quiet contract for +// `snapshot verify`: neither shallow nor deep verify writes its report, +// a failed verify still returns its error (which the cli layer prints +// on stderr), and the --json document still emits. +func TestVerify_QuietSuppressesReport(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + storeDir := t.TempDir() + dbPath := filepath.Join(tempDir, "index.sqlite") + + chunkSize := int64(32 * 1024) + maxBlobSize := int64(128 * 1024) + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, "data.bin"), + bytesPattern("quiet-", int(maxBlobSize*2)), 0o644)) + + ctx := context.Background() + + cfg, storer, snapshotID := runFileStorageBackup( + ctx, t, fs, dataDir, storeDir, dbPath, chunkSize, maxBlobSize) + + // The UI writes to the same buffer as Stdout, as both write to the + // process's stdout in production. + var stdout bytes.Buffer + + newQuietVerifier := func() *vaultik.Vaultik { + v := &vaultik.Vaultik{ + Config: cfg, + Storage: storer, + Fs: fs, + Stdout: &stdout, + Stderr: io.Discard, + UI: ui.NewWithColor(&stdout, false), + } + v.SetContext(ctx) + v.UI.SetQuiet(true) + + return v + } + + require.NoError(t, newQuietVerifier().VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{})) + require.Empty(t, stdout.String(), + "shallow verify must write no report under --quiet") + + require.NoError(t, newQuietVerifier().VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{Deep: true})) + require.Empty(t, stdout.String(), + "deep verify must write no report under --quiet") + + require.NoError(t, newQuietVerifier().VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{JSON: true})) + require.Equal(t, "ok", decodeVerifyResult(t, stdout.Bytes()).Status, + "the --json document must still emit under --quiet") + + // A snapshot without its encrypted database fails shallow verify. A + // failed report also lists each missing blob and each blob of the + // wrong size, so remove one blob and grow another. + require.NoError(t, os.Remove(filepath.Join(storeDir, "metadata", + snapshot.RemoteSnapshotKey(snapshotID), "db.zst.age"))) + + blobFiles, err := filepath.Glob( + filepath.Join(storeDir, "blobs", "*", "*", "*")) + require.NoError(t, err) + require.GreaterOrEqual(t, len(blobFiles), 2, + "the snapshot must span two blobs, one to remove and one to grow") + require.NoError(t, os.Remove(blobFiles[0])) + growOneBlob(t, fs, filepath.Join(storeDir, "blobs")) + + stdout.Reset() + + require.Error(t, newQuietVerifier().VerifySnapshotWithOptions( + snapshotID, &vaultik.VerifyOptions{}), + "--quiet must not change the outcome of a failed verify") + require.Empty(t, stdout.String(), + "a failed verify must write no report under --quiet") +} + +// TestVerify_DeepStatusLineUsesUIMarker checks that the deep verify +// status lines go through internal/ui: marker-prefixed, and silenced by +// --quiet. +func TestVerify_DeepStatusLineUsesUIMarker(t *testing.T) { + log.Initialize(log.Config{}) + t.Parallel() + + fs := afero.NewOsFs() + tempDir := t.TempDir() + + dataDir := filepath.Join(tempDir, "source") + storeDir := t.TempDir() + dbPath := filepath.Join(tempDir, "index.sqlite") + + require.NoError(t, fs.MkdirAll(dataDir, 0o755)) + require.NoError(t, afero.WriteFile(fs, + filepath.Join(dataDir, "data.bin"), + bytesPattern("marker-", 64*1024), 0o644)) + + ctx := context.Background() + + cfg, storer, snapshotID := runFileStorageBackup( + ctx, t, fs, dataDir, storeDir, dbPath, 32*1024, 128*1024) + + var stdout bytes.Buffer + + v := &vaultik.Vaultik{ + Config: cfg, + Storage: storer, + Fs: fs, + Stdout: &stdout, + Stderr: io.Discard, + UI: ui.NewWithColor(&stdout, false), + } + v.SetContext(ctx) + + opts := &vaultik.VerifyOptions{Deep: true} + + require.NoError(t, v.VerifySnapshotWithOptions(snapshotID, opts)) + require.Contains(t, stdout.String(), + "\n"+ui.Marker+" Downloading manifest...\n") + + stdout.Reset() + v.UI.SetQuiet(true) + require.NoError(t, v.VerifySnapshotWithOptions(snapshotID, opts)) + require.NotContains(t, stdout.String(), "Downloading manifest") +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..dc05cde --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "devDependencies": { + "prettier": "3.8.1" + } +} diff --git a/script/bootstrap b/script/bootstrap index 21862fe..db6dd65 100755 --- a/script/bootstrap +++ b/script/bootstrap @@ -3,11 +3,20 @@ # this repo. Idempotent: every install is guarded by a check so already # installed tools are skipped. Base tooling comes from nix, apt, brew, # or apk (detected in that order); assumes NOTHING is present (not git, -# make, or go). +# make, or go). Node is used directly if installed; otherwise it is +# installed at a pinned version via nvm (installing nvm itself first, +# from a hash-verified release archive, never curl | sh). set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +# Pinned versions, 2026-07-06 +NODE_VERSION="22.17.0" +NVM_VERSION="0.40.3" +# sha256 of https://github.com/nvm-sh/nvm/archive/refs/tags/v0.40.3.tar.gz +NVM_SHA256="5f4d6aaa04a177dc93c985e31dbc411ab6b8c6e1e21d8015dbc1372625fcd1d0" +YARN_VERSION="1.22.22" + PKGMGR="" SUDO="" @@ -48,12 +57,75 @@ missing() { ! command -v "$1" >/dev/null 2>&1 } -# Docker is a hard requirement, not a nice-to-have: script/lint lints by -# building Dockerfile.lint, whose digest-pinned golangci-lint image is -# the only place the linter runs, and script/check and script/precommit -# both run script/lint. A bootstrap that prints "bootstrap complete" on a -# machine where `make check` cannot run is a false success, so this fails -# instead. +# verify_sha256 +verify_sha256() { + if command -v sha256sum >/dev/null 2>&1; then + actual="$(sha256sum "$1" | cut -d' ' -f1)" + else + actual="$(shasum -a 256 "$1" | cut -d' ' -f1)" + fi + if [ "$actual" != "$2" ]; then + echo "bootstrap: sha256 mismatch for $1" >&2 + echo " expected: $2" >&2 + echo " actual: $actual" >&2 + exit 1 + fi +} + +# nvm is a bash script; run a command in a bash with nvm loaded +nvm_sh() { + bash -c ". \"\$HOME/.nvm/nvm.sh\" && $*" +} + +ensure_nvm() { + [ -s "$HOME/.nvm/nvm.sh" ] && return 0 + # nvm prerequisites; nvm itself requires bash + if missing bash; then pkg_install bash bash bash bash; fi + if missing curl; then pkg_install curl curl curl curl; fi + if missing git; then pkg_install git git git git; fi + tmp="$(mktemp -d)" + curl -fsSL -o "$tmp/nvm.tar.gz" \ + "https://github.com/nvm-sh/nvm/archive/refs/tags/v${NVM_VERSION}.tar.gz" + verify_sha256 "$tmp/nvm.tar.gz" "$NVM_SHA256" + mkdir -p "$HOME/.nvm" + tar -xzf "$tmp/nvm.tar.gz" -C "$HOME/.nvm" --strip-components=1 + rm -rf "$tmp" +} + +ensure_node() { + if ! missing node; then return 0; fi + ensure_nvm + nvm_sh "nvm install $NODE_VERSION" +} + +ensure_yarn() { + if ! missing yarn; then return 0; fi + if ! missing corepack; then + corepack enable + corepack prepare "yarn@$YARN_VERSION" --activate + elif [ -s "$HOME/.nvm/nvm.sh" ]; then + nvm_sh "nvm use $NODE_VERSION >/dev/null && corepack enable && \ + corepack prepare yarn@$YARN_VERSION --activate" + else + npm install -g "yarn@$YARN_VERSION" + fi +} + +install_js_deps() { + if missing yarn && [ -s "$HOME/.nvm/nvm.sh" ]; then + nvm_sh "nvm use $NODE_VERSION >/dev/null && cd \"$ROOT\" && \ + yarn install --frozen-lockfile" + else + yarn install --frozen-lockfile + fi +} + +# Docker is a hard requirement, not a nice-to-have: script/lint and +# script/test build the lint and test phases of the Dockerfile, the only +# place the linter and the tests run, and script/check and +# script/precommit both run them. A bootstrap that prints "bootstrap +# complete" on a machine where `make check` cannot run is a false +# success, so this fails instead. # # Installing docker from here was considered and rejected: it needs root, # a running daemon, and on macOS a GUI cask, so an attempt would itself @@ -80,15 +152,15 @@ bootstrap: FAILED - $reason. Docker is required to develop this repo. Without it these do not work: - script/lint builds Dockerfile.lint, which runs the linter as a - build step in a digest-pinned golangci-lint image. - That FROM line is the single source of truth for the - linter version - script/check runs script/lint + script/lint builds the lint phase of the Dockerfile, which runs + the linter as a build step in a digest-pinned + golangci-lint image + script/test builds the test phase of the Dockerfile + script/check runs script/test and script/lint script/precommit runs script/check, so commits are blocked by the pre-commit hook installed by script/setup - script/cibuild builds Dockerfile.lint and Dockerfile, which is what - CI runs + script/cibuild runs script/check and builds the image, which is + what CI runs Install docker (and start the daemon, checking DOCKER_HOST and your group membership), then re-run script/bootstrap. golangci-lint on PATH @@ -103,16 +175,25 @@ main() { # Base tooling (every repo) if missing git; then pkg_install git git git git; fi if missing make; then pkg_install gnumake make make make; fi + # script/install-go, script/install-goreleaser and nvm download with it. + if missing curl; then pkg_install curl curl curl curl; fi - # Go toolchain - if missing go; then pkg_install go golang go go; fi + # Go toolchain: the host's own, or else the version go.mod names, + # hash-verified, in .tool/go. That directory is not on the caller's + # PATH; this script, the Makefile, script/fmt, script/fmt-check, + # script/precommit and script/release add it to theirs. + if missing go; then + "$ROOT/script/install-go" + PATH="$PATH:$ROOT/.tool/go/bin" + fi # golangci-lint is deliberately NOT installed: script/lint lints by - # building Dockerfile.lint, whose digest-pinned image is the only - # place the linter runs, so whatever a package manager happens to - # ship would only be a shadow of the pinned version that could drift - # from CI. Nothing on the host is ever used as a linter, at any - # version, so installing one here would buy nothing. + # building the lint phase of the Dockerfile, whose digest-pinned + # image is the only place the linter runs, so whatever a package + # manager happens to ship would only be a shadow of the pinned + # version that could drift from CI. Nothing on the host is ever used + # as a linter, at any version, so installing one here would buy + # nothing. # goreleaser, at the version pinned by script/install-goreleaser and # verified against a hardcoded sha256. Package managers are not used @@ -124,6 +205,11 @@ main() { go mod download + # prettier, which script/fmt and script/fmt-check run on Markdown. + ensure_node + ensure_yarn + install_js_deps + # Last, so that everything installable is installed before the one # thing this script cannot install decides the outcome. require_docker diff --git a/script/check b/script/check index cc046f7..92875f7 100755 --- a/script/check +++ b/script/check @@ -1,7 +1,8 @@ #!/bin/sh # script/check: run all checks (test, lint, fmt-check). Our own -# extension to scripts-to-rule-them-all. Must not modify any files. -# Generic: usually needs no adaptation. +# extension to scripts-to-rule-them-all. test and lint are Docker +# phases; fmt-check is native, because a formatter writes the working +# tree. Must not modify any files. set -eu SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" diff --git a/script/cibuild b/script/cibuild index 339ee49..d8d3200 100755 --- a/script/cibuild +++ b/script/cibuild @@ -1,78 +1,28 @@ #!/bin/sh -# script/cibuild: run the CI build. This is the full gate, and it is two -# builds, in this order: -# -# Dockerfile.lint the linter, as a build step (a clean build IS a -# clean lint) -# Dockerfile `make fmt-check` and `make test` in the builder -# stage, then the product image -# -# Either one failing fails this script. Note what follows from the -# split: script/docker builds only the product image and so no longer -# lints -- this script and script/check (which runs script/lint) are the -# things that decide whether the tree is clean. -# -# Generic apart from the two Dockerfiles: the Gitea workflow runs this -# on push. +# script/cibuild: run the CI build. It bootstraps first: a CI runner +# checks out and runs this and nothing else, and script/fmt-check runs +# the formatter on the host, which a pristine checkout cannot do. +# --no-cache for the same reason as script/docker: the gate phases the +# final stage depends on are RUN steps, and a cached one is a check that +# did not run. set -eu -ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" +ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)" main() { cd "$ROOT" - # Both Dockerfiles key their check layers on CHECK_EPOCH, so a fresh - # value is what forces those layers to re-run: without it an - # unchanged tree replays them from cache, the checks never execute, - # and the build still exits 0. Each ARG sits immediately above the - # check RUNs, so dependency and module layers still cache. Both - # Dockerfiles also refuse to build at all when CHECK_EPOCH is empty, - # so a missing value fails loudly here rather than passing quietly. - # - # The value must be unique per invocation, not per second. `date +%s` - # is second-granular, so two concurrent invocations in the same - # second get identical epochs and the later one can be served from - # cache -- the original defect in miniature. `%N` alone does not fix - # it: busybox silently drops %N, exits 0, and hands back second - # granularity with no warning. `$$` is what makes this correct - # regardless, since concurrent invocations have different pids. - # - # Assign the epoch on its own line rather than inline in the - # argument. Under `set -eu` a command substitution that fails - # inside an argument does NOT abort the script: CHECK_EPOCH would - # become an empty string, an empty string is a constant, and a - # constant CHECK_EPOCH is exactly the cached-check false green this - # script exists to prevent -- so the guard would disarm itself and - # still exit 0. As a bare assignment, `set -e` catches a failing - # `date` and no build starts. - # - # A separate value per build, because they are separate builds: one - # `date` shared between them would still be fresh, but reusing it - # invites the two to be collapsed into a single value that is - # computed somewhere else and passed in. - epoch="$(date +%s%N)$$" - # cacheonly for the lint build: its verdict is the exit status and - # the image is never run, so exporting it is pure cost. See - # script/lint. - docker build --output=type=cacheonly \ - --build-arg CHECK_EPOCH="$epoch" -f Dockerfile.lint . - - # Version, commit and build date are computed here on the host, the - # same way script/docker does, and passed into the product build so - # the CI-built image reports its real source. The build context - # excludes .git (see .dockerignore), so the build cannot derive them - # itself; without these it would stamp the Dockerfile's dev/unknown - # fallbacks. VERSION comes from script/version, the source of truth - # shared with the Makefile. - version="$("$ROOT/script/version")" - commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" - commit_date="$(git show -s --format=%cs HEAD 2>/dev/null || echo unknown)" - - epoch="$(date +%s%N)$$" - docker build --build-arg CHECK_EPOCH="$epoch" \ + "$SCRIPT_DIR/bootstrap" + "$SCRIPT_DIR/check" + # Own line: a failing command substitution inside an argument does + # not trip `set -e`, so the inline form degrades silently to an + # empty constant. The VERSION build argument takes precedence over + # the version a build stage derives from the .git in the context. + version="$(git describe --tags --always --dirty 2>/dev/null || true)" + [ -n "$version" ] || version="unknown" + docker build --no-cache \ --build-arg VERSION="$version" \ - --build-arg COMMIT="$commit" \ - --build-arg COMMIT_DATE="$commit_date" \ - . + -t "$("$SCRIPT_DIR/projectname")" . } main "$@" diff --git a/script/docker b/script/docker index b7f29bd..07b626c 100755 --- a/script/docker +++ b/script/docker @@ -1,14 +1,8 @@ #!/bin/sh # script/docker: build the Docker image tagged with the project name. # Identical in all repos; the tag comes from script/projectname. -# Generic: needs no adaptation. -# -# This builds the PRODUCT image only, and the product Dockerfile has no -# lint stage: linting lives in Dockerfile.lint and is run by -# script/lint. So a green here means `make fmt-check` and `make test` -# passed and the image built -- it says nothing about lint. The gates -# are script/check (which runs script/lint) and script/cibuild (which -# builds both files). +# --no-cache because the gate phases the final stage depends on are RUN +# steps, and a cached one is a check that did not run. set -eu SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" @@ -16,32 +10,14 @@ ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)" main() { cd "$ROOT" - # Same CHECK_EPOCH contract as script/cibuild, for the same reason - # and with the same bare-assignment and `$$` requirements -- see the - # comments there. This script is not the CI gate, but a local build - # is almost always warm, so without this it would report a green the - # tree had not earned and the two entrypoints would disagree about - # whether the tree is clean. The Dockerfile now refuses to build - # without a non-empty value, so this is required, not optional. - epoch="$(date +%s%N)$$" - - # Version, commit and build date are computed here on the host, - # where .git exists, and passed into the build. The build context - # excludes .git (see .dockerignore), so the container cannot derive - # them itself -- it used to try and always got "unknown", giving - # every image a "commit: unknown" it could not be traced from. - # VERSION comes from script/version, the source of truth shared with - # the Makefile, so a Docker build reports the same string (tag, - # dev-, or a -dirty variant) that a local build of the same - # tree would. - version="$("$SCRIPT_DIR/version")" - commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" - commit_date="$(git show -s --format=%cs HEAD 2>/dev/null || echo unknown)" - - docker build --build-arg CHECK_EPOCH="$epoch" \ + # Own line: a failing command substitution inside an argument does + # not trip `set -e`, so the inline form degrades silently to an + # empty constant. The VERSION build argument takes precedence over + # the version a build stage derives from the .git in the context. + version="$(git describe --tags --always --dirty 2>/dev/null || true)" + [ -n "$version" ] || version="unknown" + docker build --no-cache \ --build-arg VERSION="$version" \ - --build-arg COMMIT="$commit" \ - --build-arg COMMIT_DATE="$commit_date" \ -t "$("$SCRIPT_DIR/projectname")" . } diff --git a/script/fmt b/script/fmt index e95d111..1f7ad98 100755 --- a/script/fmt +++ b/script/fmt @@ -4,9 +4,31 @@ set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +# Must match the pin in script/bootstrap. +NODE_VERSION="22.17.0" + +# script/bootstrap installs node and yarn under nvm and leaves neither +# on the PATH of the shell that called it, so resolve the pinned +# toolchain here the way bootstrap's own install step does. nvm is a +# bash script, hence the subshell. +run_yarn() { + if command -v yarn >/dev/null 2>&1; then + exec yarn "$@" + fi + if [ ! -s "$HOME/.nvm/nvm.sh" ]; then + echo "fmt: no yarn; run script/bootstrap first" >&2 + exit 1 + fi + exec bash -c '. "$HOME/.nvm/nvm.sh" && nvm use "$1" >/dev/null && + shift && exec yarn "$@"' bash "$NODE_VERSION" "$@" +} + main() { cd "$ROOT" + # Where script/bootstrap installs Go when the host has none. + PATH="$PATH:$ROOT/.tool/go/bin" go fmt ./... + run_yarn run prettier --write '**/*.md' --tab-width 4 --prose-wrap always } main "$@" diff --git a/script/fmt-check b/script/fmt-check index 57e8e5c..d0595ba 100755 --- a/script/fmt-check +++ b/script/fmt-check @@ -1,18 +1,48 @@ #!/bin/sh -# script/fmt-check: check formatting (read-only). Same scope as -# script/fmt, but fails instead of writing. +# script/fmt-check: check formatting (read-only). Fails instead of +# writing. It checks every Go file outside .tool, which is more than +# script/fmt formats: `go fmt ./...` skips `testdata` directories and +# files and directories whose names start with `.` or `_`. Fix a file +# only this reports with `gofmt -w`. Markdown is checked with prettier. set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +# Must match the pin in script/bootstrap. +NODE_VERSION="22.17.0" + +# script/bootstrap installs node and yarn under nvm and leaves neither +# on the PATH of the shell that called it, so resolve the pinned +# toolchain here the way bootstrap's own install step does. nvm is a +# bash script, hence the subshell. +run_yarn() { + if command -v yarn >/dev/null 2>&1; then + exec yarn "$@" + fi + if [ ! -s "$HOME/.nvm/nvm.sh" ]; then + echo "fmt-check: no yarn; run script/bootstrap first" >&2 + exit 1 + fi + exec bash -c '. "$HOME/.nvm/nvm.sh" && nvm use "$1" >/dev/null && + shift && exec yarn "$@"' bash "$NODE_VERSION" "$@" +} + main() { cd "$ROOT" - unformatted="$(gofmt -l .)" + # Where script/bootstrap installs Go when the host has none. + PATH="$PATH:$ROOT/.tool/go/bin" + # .tool/go holds that toolchain's own sources, which are not ours. + if ! unformatted="$(find . -path ./.tool -prune -o -name '*.go' -type f \ + -exec gofmt -l {} +)"; then + echo "fmt-check: gofmt failed" >&2 + exit 1 + fi if [ -n "$unformatted" ]; then echo "Files not formatted:" >&2 echo "$unformatted" >&2 exit 1 fi + run_yarn run prettier --check '**/*.md' --tab-width 4 --prose-wrap always } main "$@" diff --git a/script/install-go b/script/install-go index 38056dc..3442421 100755 --- a/script/install-go +++ b/script/install-go @@ -4,12 +4,13 @@ # own extension to scripts-to-rule-them-all. Idempotent: exits at once # when the pinned toolchain is already installed. # -# Only .gitea/workflows/release.yml calls this. goreleaser is not a +# .gitea/workflows/release.yml calls this, and so does script/bootstrap +# when the host has no Go, as on the check runner. goreleaser is not a # compiler: it shells out to `go` for the `before:` hook and for every # one of the four cross-compiles, so the release runner needs a Go -# toolchain on PATH. check.yml never does -- it builds inside the -# digest-pinned Dockerfile images -- so this is the release path's only -# host Go, and per REPO_POLICIES.md it must be pinned by hash. +# toolchain on PATH. The check runner compiles nothing on the host; it +# uses this Go only for bootstrap's `go mod download` and for gofmt in +# script/fmt-check. Per REPO_POLICIES.md a host Go is pinned by hash. # actions/setup-go exposes no checksum input, so Go is installed the way # script/install-goreleaser installs goreleaser: download the exact # archive from go.dev and refuse it unless its sha256 matches the value @@ -18,11 +19,11 @@ # The version is go.mod's `go` directive, the single source of truth for # the toolchain. GO_VERSION below MUST equal it, and this script fails # when they disagree -- so bumping Go is one reviewed change touching -# go.mod, the checksum here, and the Dockerfile golang digest together. +# go.mod, the checksums here, and the Dockerfile's two golang digests +# together. # -# Linux only, because that is what the release runner is. A darwin dev -# building a snapshot uses their own Go; supporting an OS means adding -# its checksums. +# Linux and macOS, each on amd64 and arm64: the four archives whose +# checksums are committed below. set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" @@ -33,6 +34,8 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" GO_VERSION="1.26.1" SHA256_LINUX_AMD64="031f088e5d955bab8657ede27ad4e3bc5b7c1ba281f05f245bcc304f327c987a" SHA256_LINUX_ARM64="a290581cfe4fe28ddd737dde3095f3dbeb7f2e4065cab4eae44dfc53b760c2f7" +SHA256_DARWIN_AMD64="65773dab2f8cc4cd23d93ba6d0a805de150ca0b78378879292be0b903b8cdd08" +SHA256_DARWIN_ARM64="353df43a7811ce284c8938b5f3c7df40b7bfb6f56cb165b150bc40b5e2dd541f" GOROOT_DIR="$ROOT/.tool/go" GOCMD="$GOROOT_DIR/bin/go" @@ -101,26 +104,28 @@ main() { arch="$(uname -m)" case "$os" in Linux) os="linux" ;; + Darwin) os="darwin" ;; *) - echo "install-go: unsupported OS $os (release runner is Linux)" >&2 + echo "install-go: unsupported OS $os" >&2 exit 1 ;; esac case "$arch" in - x86_64 | amd64) - arch="amd64" - sum="$SHA256_LINUX_AMD64" - ;; - arm64 | aarch64) - arch="arm64" - sum="$SHA256_LINUX_ARM64" - ;; + x86_64 | amd64) arch="amd64" ;; + arm64 | aarch64) arch="arm64" ;; *) - echo "install-go: no pinned checksum for architecture $arch" >&2 + echo "install-go: unsupported architecture $arch" >&2 exit 1 ;; esac + case "${os}-${arch}" in + linux-amd64) sum="$SHA256_LINUX_AMD64" ;; + linux-arm64) sum="$SHA256_LINUX_ARM64" ;; + darwin-amd64) sum="$SHA256_DARWIN_AMD64" ;; + darwin-arm64) sum="$SHA256_DARWIN_ARM64" ;; + esac + archive="go${GO_VERSION}.${os}-${arch}.tar.gz" url="https://go.dev/dl/${archive}" diff --git a/script/lint b/script/lint index 5499014..2d8b075 100755 --- a/script/lint +++ b/script/lint @@ -1,108 +1,23 @@ #!/bin/sh -# script/lint: run the linter. +# script/lint: run the linter. Linting is a phase of the Dockerfile and +# this builds that phase alone; the linter is never installed or run on +# a developer host, where a shared result cache and a host-global lock +# make its answer untrustworthy. # -# The linter runs inside the image built by Dockerfile.lint, and it runs -# there as a BUILD STEP: a successful build of that file IS a clean -# lint. Nothing lints on the host, at any version, ever. That FROM line -# is the single source of truth for the linter version in this repo, so -# a local run and a CI run of the same tree cannot disagree. -# -# One container per run means one lint cache and one golangci-lint lock -# per run, both private to that run and thrown away with it. That is -# what makes concurrent runs on a shared host safe, and it is why this -# script no longer carries per-worktree cache directories, a lock-retry -# loop, or an output audit: there is no shared state left for them to -# defend (issue https://git.eeqj.de/sneak/vaultik/issues/113). -# -# To watch the linter execute, set BUILDKIT_PROGRESS=plain, which docker -# honours directly: -# -# BUILDKIT_PROGRESS=plain script/lint -# -# The check layers -- `golangci-lint config verify` and then -# `golangci-lint run` -- must appear as executing rather than CACHED on -# every run; see the CHECK_EPOCH comment in Dockerfile.lint. +# The phase is not the last stage in the file, so it is built only when +# --target names it. --no-cache because a cached lint layer is a lint +# that did not run. The tag makes each build replace the previous image +# instead of leaving a dangling one behind. set -eu -ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" -DOCKERFILE="$ROOT/Dockerfile.lint" - -require_docker() { - if ! command -v docker >/dev/null 2>&1; then - cat >&2 </dev/null 2>&1; then - cat >&2 <&2 <&2 + echo "lint-fix: no FROM ... AS lint line found in $DOCKERFILE" >&2 exit 1 fi diff --git a/script/precommit b/script/precommit index 50f02ae..e55afea 100755 --- a/script/precommit +++ b/script/precommit @@ -9,6 +9,8 @@ ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)" main() { cd "$ROOT" + # Where script/bootstrap installs Go when the host has none. + PATH="$PATH:$ROOT/.tool/go/bin" go mod tidy go fmt ./... git diff --exit-code -- go.mod go.sum || { diff --git a/script/release b/script/release index a9e2056..cdc1b1c 100755 --- a/script/release +++ b/script/release @@ -21,10 +21,9 @@ goreleaser_version() { head -n 1 } -# Resolve the goreleaser to run, on the same rule script/lint uses for -# golangci-lint: a binary on PATH is accepted only when it is exactly -# the pinned version, because a differently versioned tool would -# produce a differently built release from the same tag. Anything else +# Resolve the goreleaser to run. A binary on PATH is accepted only when +# it is exactly the pinned version, because a differently versioned tool +# would produce a differently built release from the same tag. Anything else # comes from .tool/bin, and a missing one is a loud failure naming the # script that installs it rather than a silent fallback. resolve_goreleaser() { @@ -44,6 +43,8 @@ resolve_goreleaser() { main() { cd "$ROOT" + # Where script/bootstrap installs Go when the host has none. + PATH="$PATH:$ROOT/.tool/go/bin" if ! bin="$(resolve_goreleaser)"; then cat >&2 < (cached)`, and that line is -# indistinguishable -- to every check this repo performs -- from a -# package that actually ran. The whole suite reports its full set of -# `ok` lines in under half a second having executed nothing. That -# matters beyond the local inner loop: the Dockerfile's `RUN make test` -# is forced to re-execute by CHECK_EPOCH, but a GOCACHE baked into an -# earlier image layer survives into the re-executed step, so the step -# can re-run and still do no work. It is applied unconditionally rather -# than only in the containerised path because the pre-commit hook runs -# this same script; a gate that is honest only in CI is dishonest -# exactly where people lean on it most. -# -# -timeout is a hang backstop, not a performance budget: its job is to -# turn a deadlocked test into a stack dump instead of a wedged CI job, -# so it wants to sit far above the slowest legitimate runtime, not just -# above it. It is per test binary and covers test execution only -- the -# clock starts inside testing.M.Run, after compilation and linking, so -# build time is not charged against it. (Measured: a containerised run -# with an empty GOCACHE reports per-package durations within noise of a -# warm host run. A shell `timeout 30 go test ./...` would include -# compilation, but that is a different mechanism from this flag.) -# -# The 120s value DELIBERATELY DIVERGES from REPO_POLICIES.md:192, which -# mandates "Add a 30-second timeout", and from that file's canonical Go -# recipe at :212-214, which uses -timeout 30s. REPO_POLICIES.md is -# org-canonical and cannot be amended from this repo, so the divergence -# is recorded here instead, and issue #101 proposes amending the policy -# text upstream. Do not revert this to 30s without reading #101 first. -# -# Why it diverges: the slowest packages are internal/database and -# internal/vaultik, observed under -race at about 6.4s warm, 8.1s in a -# cold containerised run on a contended host, and 10.2s in an -# independent cold run on this same host. The worst case is not tightly -# characterised -- each fresh measurement has come in above the last -- -# which is itself an argument for generous headroom. Against the 10.2s -# observation, 30s is only 2.9x: not a safety margin but a flake -# waiting for a slow day, whose failure mode is a timeout that looks -# like a real defect. 120s leaves about 12x while still bounding a hung -# package -- including the verbose rerun below -- to a few minutes. The -# cost of that choice, also recorded on #101: because of the rerun, a -# hung package pays the timeout twice. -run_tests() { - go test -race -timeout 120s -count=1 "$@" ./... -} +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" +ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)" main() { cd "$ROOT" - run_tests || { - echo "--- Rerunning with -v for details ---" - run_tests -v - exit 1 - } + docker build --no-cache \ + --target test \ + -t "$("$SCRIPT_DIR/projectname")-test" . } main "$@" diff --git a/script/version b/script/version index 0df9b42..569ae5d 100755 --- a/script/version +++ b/script/version @@ -1,73 +1,28 @@ #!/bin/sh # script/version: output the version string to bake into the binary. -# Our own extension to scripts-to-rule-them-all, and the single source -# of truth for the version: the Makefile's LDFLAGS call this rather -# than carrying a hardcoded constant, which is what used to make every -# local build claim to be 1.0.0-rc.1 regardless of git state. +# Our own extension to scripts-to-rule-them-all. The Makefile's LDFLAGS +# call this rather than carrying a hardcoded constant, which is what used +# to make every local build claim to be 1.0.0-rc.1 regardless of git +# state. script/docker and script/cibuild run the same `git describe` +# themselves, and fall back to "unknown" rather than "dev". # -# The rules, in order: +# The version is `git describe --tags --always --dirty`: the tag on a +# tagged commit, tag-N-gHASH on a commit after one, the short commit +# when no tag is reachable, each with a "-dirty" suffix when tracked +# files have uncommitted changes. Untracked files are ignored: a stray +# scratch file does not change what was compiled. Outside a git checkout +# (such as an unpacked release tarball), or in one with no commits, it +# is "dev". # -# HEAD is exactly on an annotated or lightweight tag -# -> that tag, with a leading "v" stripped -# anything else -# -> "dev-<12 chars of HEAD>" -# not a git checkout at all (release tarball, `go install`) -# -> "dev" -# -# Either of the first two gains a "-dirty" suffix when tracked files -# have uncommitted changes, because a modified checkout of v1.0.0 is -# not v1.0.0. Untracked files are ignored, matching `git describe -# --dirty`: a stray scratch file does not change what was compiled. -# -# The "v" is stripped so that a `make` build and a goreleaser build of -# the same tagged commit report the *same* string: goreleaser's -# {{ .Version }} is the tag without the prefix, and the release archive -# names are built from it. A tag named `v1.0.0` therefore produces -# `vaultik 1.0.0`, matching `vaultik_1.0.0_linux_amd64.tar.gz`. -# -# Nothing here ever invents a version number. An untagged build says so -# and names the commit it was built from; it does not round up to the -# nearest plausible release. +# Nothing here ever invents a version number. set -eu ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" -# Length of the commit prefix in a dev version. Matches -# globals.ShortCommit, so `vaultik version` shows the same 12 chars in -# its version line and its commit line. -SHORT_LEN=12 - main() { cd "$ROOT" - - if ! git rev-parse --git-dir >/dev/null 2>&1; then - echo "dev" - return 0 - fi - - dirty="" - if [ -n "$(git status --porcelain --untracked-files=no 2>/dev/null)" ]; then - dirty="-dirty" - fi - - # --exact-match so a *descendant* of a tag is not reported as that - # tag. Plain `git describe --tags` would call a commit 40 patches - # past v1.0.0 "v1.0.0-40-gabc1234", and the leading token of that is - # a released version the build is not. - tag="$(git describe --tags --exact-match HEAD 2>/dev/null || true)" - if [ -n "$tag" ]; then - echo "${tag#v}${dirty}" - return 0 - fi - - sha="$(git rev-parse "--short=$SHORT_LEN" HEAD 2>/dev/null || true)" - if [ -z "$sha" ]; then - # A repo with no commits at all. - echo "dev" - return 0 - fi - - echo "dev-${sha}${dirty}" + version="$(git describe --tags --always --dirty 2>/dev/null || true)" + echo "${version:-dev}" } main "$@" diff --git a/test/config.yaml b/test/config.yaml index f67577f..cd0e303 100644 --- a/test/config.yaml +++ b/test/config.yaml @@ -19,7 +19,7 @@ s3: secret_access_key: test-secret-key region: us-east-1 use_ssl: true - part_size: 5242880 # 5MB + part_size: 5242880 # 5MiB index_path: /tmp/vaultik-test.sqlite chunk_size: 10MB blob_size_limit: 10GB diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 0000000..d846639 --- /dev/null +++ b/yarn.lock @@ -0,0 +1,8 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +prettier@3.8.1: + version "3.8.1" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.8.1.tgz#edf48977cf991558f4fcbd8a3ba6015ba2a3a173" + integrity sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==