Compare commits

..
1 Commits
Author SHA1 Message Date
sneak c0b02b3dcb Give each failure one error value (closes #113)
check / check (push) Failing after 3s
internal/cli's copies of vault.ErrSecretNotFound, ErrVaultNotFound,
ErrVersionNotFound and ErrSecretExists are removed; the commands wrap the
vault errors. errUnsupportedUnlockerType is removed for
errInvalidUnlockerType, which names the same failure. Every error of
secret.ReadPassphrase wraps ErrPassphraseNotRead, so its callers no longer
add those words. ResolveGPGKeyFingerprint returns ErrGPGKeyNotFound for a
key the keyring lacks, recognised by gpg's status line. storeInKeychain
returns errNilDataBuffer. bip85's ErrPasswordTooShort and
ErrEncodedTooShort go with their unreachable checks. Tests that matched
these errors' text use errors.Is.

Model: opus-5-5
2026-10-04 22:09:27 +00:00
96 changed files with 1129 additions and 1572 deletions
+19 -68
View File
@@ -1,78 +1,29 @@
# .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 # .git is sent without its config. Without a VERSION build argument the
# stage that compiles runs `git describe --tags --always` on .git, which # 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 # 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. # 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 .git/config
# 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. # Build artifacts
# Anchored because it occurs once where agents run at the repo root. secret
# KNOWN GAP: a repo running agents in subdirectories still ships coverage.out
# `services/api/.claude/` and must add its own anchored entry. *.test
.claude
# Environment files. `*.env` covers bare `.env` and the `prod.env` # IDE and editor files
# convention. Re-include a committed template with a negation if the .vscode
# build needs one: `!docs/example.env`. .idea
**/*.[eE][nN][vV] *.swp
**/.[eE][nN][vV].* *.swo
**/.[eE][nN][vV][rR][cC] *~
# Private keys and the bundles carrying them. Public certificates # Dependencies
# (*.crt, *.cer) are deliberately absent: they are legitimate inputs. node_modules
**/*.[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. # macOS
**/node_modules .DS_Store
# OS metadata. # Claude files
**/.DS_Store .claude/
**/Thumbs.db
# Editor state: never a build input, and it churns COPY. # Local settings
**/*.swp .claude/settings.local.json
**/*.swo
**/*~
**/*.bak
**/.idea
**/.vscode
**/*.sublime-*
# This repo's host-built artifacts: the binary script/build writes, test
# binaries and coverage output.
/secret
/*.test
/coverage.out
-3
View File
@@ -10,6 +10,3 @@ insert_final_newline = true
[Makefile] [Makefile]
indent_style = tab indent_style = tab
[*.go]
indent_style = tab
+1 -1
View File
@@ -4,6 +4,6 @@ jobs:
check: check:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
# actions/checkout v4.2.2, 2026-02-22 # actions/checkout v4.2.2, 2026-02-28
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
- run: script/cibuild - run: script/cibuild
+10 -30
View File
@@ -20,35 +20,15 @@ Thumbs.db
# Node # Node
node_modules/ node_modules/
# Secrets. Unanchored like every entry above, so each matches at every # Environment / secrets
# depth. Matching is case-sensitive on Linux, so names use character .env
# ranges rather than a lowercase form that misses `Server.Key`. .env.*
*.pem
*.key
# Environment files. `*.env` covers bare `.env` and the `prod.env` # This repo. /secret is the built binary, anchored so that it does not
# convention. Only the templates `example.env` and `sample.env` are # also match the internal/secret/ package directory.
# 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. /secret is the built binary, anchored so that it does not also match
# the internal/secret/ package directory.
*.log
*.out
*.test
/secret /secret
*.log
*.test
settings.local.json
-1
View File
@@ -17,7 +17,6 @@ linters:
disable: disable:
# Genuinely incompatible with project patterns # Genuinely incompatible with project patterns
- exhaustruct # Requires all struct fields - exhaustruct # Requires all struct fields
- exhaustruct_v5 # Requires all struct fields (successor to exhaustruct)
- godot # Requires comments to end with periods - godot # Requires comments to end with periods
- wrapcheck # Too verbose for internal packages - wrapcheck # Too verbose for internal packages
- varnamelen # Short names like db, id are idiomatic Go - varnamelen # Short names like db, id are idiomatic Go
+2 -21
View File
@@ -100,18 +100,6 @@ Version: 2025-06-08
are acceptable in the root, but source code and other files should be are acceptable in the root, but source code and other files should be
organized in appropriate subdirectories. organized in appropriate subdirectories.
13. Commit messages carry no author or co-author attribution for the coding
agent. The agent is an inanimate tool and the owner is the sole author of
the code it writes; such a line is advertising, not attribution.
14. Never run part of the test suite: always run the whole thing with
`make test`.
15. Do not stop working on a task until you have reached the definition of done
it gives. Do all of the work, not part or most of it.
16. After each commit, push to the remote.
## Python-Specific Guidelines ## Python-Specific Guidelines
1. **Type Annotations (UP006)**: Use built-in collection types directly for type 1. **Type Annotations (UP006)**: Use built-in collection types directly for type
@@ -166,17 +154,10 @@ Version: 2025-06-08
3. **Wrap errors** with `fmt.Errorf("context: %w", err)` for debuggability. 3. **Wrap errors** with `fmt.Errorf("context: %w", err)` for debuggability.
4. **Never modify linter config** (`.golangci.yml`) to suppress findings, and do 4. **Never modify linter config** (`.golangci.yml`) to suppress findings. Fix
not modify it at all unless specifically instructed. Fix the code. the code.
5. **All PRs must pass `make check` with zero failures.** No exceptions, no 5. **All PRs must pass `make check` with zero failures.** No exceptions, no
"pre-existing issue" excuses. "pre-existing issue" excuses.
6. **Pin external dependencies by commit hash**, not mutable tags. 6. **Pin external dependencies by commit hash**, not mutable tags.
7. **A program's `main.go` is `./cmd/<program_name>/main.go`** and only imports
and calls `<program_name>.CLIEntry()`; the implementation is in
`./internal/<program_name>/`. This keeps several programs in one repository
from cluttering the root directory.
8. **Log with `log/slog`.**
+95
View File
@@ -0,0 +1,95 @@
# IMPORTANT RULES
* 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.
* 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 and linter errors fixed before committing.
NEVER commit code that does not pass the linter. DO NOT modify the linter
config unless specifically instructed.
* The test suite is fast and local. When running tests, NEVER 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.
* When you complete each task, if the tests are passing and the code is
formatted and there are no linter errors, always commit and push your
work. Use a good commit message and don't mention any author or co-author
attribution.
* 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.
* Do not use 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.
* If you are fixing a bug, write a test first that reproduces the bug and
fails, and then fix the bug in the code, using the test to verify that the
fix worked.
* 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 when designing an
API.
* 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.
* When implementing programs, put the main.go in
./cmd/<program_name>/main.go and put the program's code in
./internal/<program_name>/. This allows for multiple programs to be
implemented in the same repository without cluttering the root directory.
main.go should simply import and call <program_name>.CLIEntry(). The
full implementation should be in ./internal/<program_name>/.
* 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.
* 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.
* 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. After each commit, push to the remote.
* 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.
* Always use structured logging. Log any relevant state/context with the
messages (but do not log secrets). If stdout is not a terminal, output
the structured logs in jsonl format. Use go's log/slog.
* 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.
+44 -55
View File
@@ -1,79 +1,68 @@
# Lint phase. The linter is invoked directly rather than through `make # Lint stage — fast feedback on formatting and lint issues
# lint` or `script/lint`, which are themselves a docker build. # golangci/golangci-lint:v2.12.2 (Debian-based), 2026-08-07
# golangci/golangci-lint:v2.14.0 (Debian-based), 2026-09-24 FROM golangci/golangci-lint:v2.12.2@sha256:5cceeef04e53efe1470638d4b4b4f5ceefd574955ab3941b2d9a68a8c9ad5240 AS lint
FROM golangci/golangci-lint@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f AS lint
WORKDIR /src WORKDIR /src
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN go mod download
# script/cibuild sets CHECK_EPOCH to the current time, so the RUN steps
# below run again on each build, an unchanged tree included, while the
# steps above stay cached. ARG is per stage: the build stage declares it too.
ARG CHECK_EPOCH
COPY . . COPY . .
RUN go vet ./...
RUN make fmt-check
# Not make lint or make lint-darwin: script/lint and script/lint-darwin are
# docker builds, which cannot run in here. These are their commands.
RUN golangci-lint run --config .golangci.yml ./... RUN golangci-lint run --config .golangci.yml ./...
# The same checks on the code as a macOS build compiles it, which a Linux
# build never compiles. Cgo is off, because compiling cgo code for macOS
# needs Apple's SDK headers. That leaves out the files built only with cgo
# on macOS: the keychain unlocker's calls into the keychain
# (keychainunlocker_cgo.go, and keychainunlocker_test.go) and the Secure
# Enclave bindings (internal/macse). Nothing on Linux checks those.
RUN GOOS=darwin CGO_ENABLED=0 go vet ./... RUN GOOS=darwin CGO_ENABLED=0 go vet ./...
RUN GOOS=darwin CGO_ENABLED=0 golangci-lint run --config .golangci.yml ./... RUN GOOS=darwin CGO_ENABLED=0 golangci-lint run --config .golangci.yml ./...
# Test phase. -race needs cgo and so a C compiler, which the Debian Go # Build stage — tests and compilation
# image ships and the alpine one does not. # golang 1.24.13-alpine (2026-03-10)
# golang:1.24.13-trixie, 2026-02-04
FROM golang@sha256:5835f052b784aa39f2fe9070def3568605c8bc3fcd810f10402066348b61e716 AS test
ENV CGO_ENABLED=1
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
# Go's build cache goes in a cache mount, not the image layer, which would
# take seconds longer to export. --no-cache, on every build in script/,
# starts the mount empty; -count=1 keeps a build without it from taking
# test results from there.
RUN --mount=type=cache,id=sneak/secret/go-build-test,target=/root/.cache/go-build \
go test -count=1 -timeout 90s -race -cover ./... || \
{ echo "--- Rerunning with -v for details ---"; \
go test -count=1 -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.24.13-alpine, 2026-03-10
FROM golang@sha256:8bee1901f1e530bfb4a7850aa7a479d17ae3a18beb6e09064ed54cfd245b7191 AS builder FROM golang@sha256:8bee1901f1e530bfb4a7850aa7a479d17ae3a18beb6e09064ed54cfd245b7191 AS builder
# Force BuildKit to run the lint stage
COPY --from=lint /src/go.sum /dev/null COPY --from=lint /src/go.sum /dev/null
COPY --from=test /src/go.sum /dev/null
# script/build compiles with cgo, so it needs a C compiler too. RUN apk add --no-cache gcc musl-dev make git gnupg
RUN apk add --no-cache gcc musl-dev make git
# A tar-stream context keeps the sender's file owners, which git refuses. WORKDIR /build
RUN git config --system --add safe.directory /src
WORKDIR /src
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN go mod download
# As in the lint stage: the RUN steps below run again on each script/cibuild.
ARG CHECK_EPOCH
COPY . . COPY . .
# The VERSION build arg when one is given, otherwise RUN make test
# `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; \
make build VERSION="${VERSION:-dev}"
# Runtime stage, and the last one # The version stamped into the binary: the VERSION build argument when one
# alpine 3.23, 2026-03-10 # is given, otherwise `git describe --tags --always` of the .git the build
# context carries: the tag on a tagged commit, tag-N-gHASH on a commit after
# one, the short commit when no tag is reachable. A context that carries .git
# and still yields no version fails the build.
ARG VERSION
RUN version="${VERSION:-$(git describe --tags --always)}"; \
if [ -e .git ] && { [ -z "$version" ] || [ "$version" = dev ] || \
[ "$version" = unknown ]; }; then \
echo "no version could be derived although the build context carries .git" >&2; \
exit 1; \
fi; \
make build VERSION="${version:-dev}"
# Runtime stage
# alpine 3.23 (2026-03-10)
FROM alpine@sha256:25109184c71bdad752c8312a8623239686a9a2071e8825f20acb8f2198c3f659 FROM alpine@sha256:25109184c71bdad752c8312a8623239686a9a2071e8825f20acb8f2198c3f659
RUN apk add --no-cache ca-certificates gnupg RUN apk add --no-cache ca-certificates gnupg
RUN adduser -D -s /bin/sh secret RUN adduser -D -s /bin/sh secret
COPY --from=builder /src/secret /usr/local/bin/secret COPY --from=builder /build/secret /usr/local/bin/secret
RUN chmod +x /usr/local/bin/secret RUN chmod +x /usr/local/bin/secret
USER secret USER secret
+29
View File
@@ -0,0 +1,29 @@
# Lint image, built by script/lint and script/lint-darwin: golangci-lint runs
# as a build step, so a successful build is a clean lint. Works where the
# docker daemon is remote and bind mounts are impossible.
# golangci/golangci-lint:v2.12.2 (Debian-based), 2026-08-07
FROM golangci/golangci-lint:v2.12.2@sha256:5cceeef04e53efe1470638d4b4b4f5ceefd574955ab3941b2d9a68a8c9ad5240 AS deps
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
# script/lint rebuilds this stage on every run, by this name; the module
# download above stays cached.
FROM deps AS lint
COPY . .
RUN golangci-lint run --config .golangci.yml ./...
# script/lint-darwin rebuilds this stage on every run, by this name. It
# checks the code as a macOS build compiles it, but with cgo off, which
# leaves out the files that need cgo on macOS (see script/lint-darwin).
FROM deps AS lint-darwin
COPY . .
RUN GOOS=darwin CGO_ENABLED=0 go vet ./...
RUN GOOS=darwin CGO_ENABLED=0 golangci-lint run --config .golangci.yml ./...
+6 -3
View File
@@ -1,7 +1,7 @@
export CGO_ENABLED=1 export CGO_ENABLED=1
.PHONY: default bootstrap setup build test lint fmt fmt-check check docker \ .PHONY: default bootstrap setup build test lint lint-darwin fmt fmt-check \
docker-run clean install hooks check docker docker-run clean install hooks
default: check default: check
@@ -21,10 +21,13 @@ test:
fmt: fmt:
@script/fmt @script/fmt
# Vets and lints the Linux build, then the macOS build
lint: lint:
@script/lint @script/lint
# Type-check and lint the macOS build from Linux (see script/lint-darwin)
lint-darwin:
@script/lint-darwin
check: check:
@script/check @script/check
+18 -20
View File
@@ -593,10 +593,8 @@ standard: normalized scripts in `script/` are the entrypoints for the
development workflow, and the Makefile targets are thin shims that call them. We development workflow, and the Makefile targets are thin shims that call them. We
provide: provide:
- `script/bootstrap` — install all dependencies (Go, Go module download, and - `script/bootstrap` — install all dependencies (Go, Go module download),
node, yarn and prettier for formatting markdown), idempotently; prettier is idempotently; golangci-lint is not installed, it runs in docker
pinned by hash in `package.json` and `yarn.lock`; golangci-lint is not
installed, it runs in docker
- `script/setup` — make a fresh clone ready for development: runs - `script/setup` — make a fresh clone ready for development: runs
`script/bootstrap`, then `script/install-precommit` `script/bootstrap`, then `script/install-precommit`
- `script/projectname` — output the project name (`secret`); used by other - `script/projectname` — output the project name (`secret`); used by other
@@ -604,24 +602,24 @@ provide:
- `script/build` — build the `secret` binary into the repo root, stamping the - `script/build` — build the `secret` binary into the repo root, stamping the
version (`VERSION` from the environment, else `git describe`) and the git version (`VERSION` from the environment, else `git describe`) and the git
commit commit
- `script/test` — build the `test` phase of the `Dockerfile`, which runs the - `script/test` — run `go vet` and the test suite (verbose rerun on failure)
test suite with the race detector, a 90-second timeout and coverage; on - `script/lint` — run `golangci-lint` in docker only: builds `Dockerfile.lint`,
failure it reruns the tests verbosely for the details and fails even when the where the linter is a build step that runs on every call, also on an unchanged
rerun passes tree
- `script/lint` — build the `lint` phase of the `Dockerfile`, which runs - `script/lint-darwin` — run `go vet` and `golangci-lint` in docker on the code
`go vet` and `golangci-lint`, then both again on the code as a macOS build as a macOS build compiles it (`GOOS=darwin`), which a Linux build never
compiles it (`GOOS=darwin`), which a Linux build never compiles; cgo is off compiles; cgo is off, so the keychain unlocker's calls into the keychain
there, so the keychain unlocker's calls into the keychain
(`internal/secret/keychainunlocker_cgo.go`, and `keychainunlocker_test.go`) (`internal/secret/keychainunlocker_cgo.go`, and `keychainunlocker_test.go`)
and the Secure Enclave bindings (`internal/macse`) are not checked and the Secure Enclave bindings (`internal/macse`) are not checked
- `script/fmt` — format all Go code with `go fmt` and every markdown file with - `script/fmt` — format all Go code (writes)
prettier (4-space tabs, `proseWrap: always`) (writes) - `script/fmt-check` — check formatting without writing
- `script/fmt-check` — check the same formatting without writing, on the host - `script/check` — run `script/test`, `script/lint`, `script/lint-darwin`, and
- `script/check` — run `script/test`, `script/lint` and `script/fmt-check` `script/fmt-check`
- `script/docker` — build the Docker image tagged with the project name; the - `script/docker` — build the Docker image tagged with the project name
build runs the `lint` and `test` phases first - `script/cibuild` — CI entrypoint: `docker build --ulimit memlock=-1:-1 .`
- `script/cibuild` — CI entrypoint: runs `script/bootstrap`, `script/check`, (memguard needs mlock; the Dockerfile runs the checks), with a new
then builds the image as `script/docker` does `CHECK_EPOCH` build argument on every run so the checks run again on an
unchanged tree
- `script/precommit` — pre-commit checks: `go mod tidy` verification, then - `script/precommit` — pre-commit checks: `go mod tidy` verification, then
`script/check` `script/check`
- `script/install-precommit` — install the git pre-commit hook that runs - `script/install-precommit` — install the git pre-commit hook that runs
+82 -353
View File
@@ -1,6 +1,6 @@
--- ---
title: Repository Policies title: Repository Policies
last_modified: 2026-10-04 last_modified: 2026-07-06
--- ---
This document covers repository structure, tooling, and workflow standards. Code This document covers repository structure, tooling, and workflow standards. Code
@@ -60,28 +60,17 @@ style conventions are in separate documents:
prerequisite since nvm requires bash. yarn is then pinned via prerequisite since nvm requires bash. yarn is then pinned via
`corepack prepare yarn@<version> --activate`. Never install "latest" or "lts"; `corepack prepare yarn@<version> --activate`. Never install "latest" or "lts";
always exact versions. `script/cibuild` runs the CI build: it changes to the always exact versions. `script/cibuild` runs the CI build: it changes to the
repo root, runs `script/bootstrap`, runs `script/check`, and builds the image repo root and runs `docker build .`; the Gitea workflow calls it. Four further
with the version; the Gitea workflow calls it. **`script/cibuild` runs scripts are our own extensions to the standard: `script/check` runs
`script/bootstrap` first**, because the workflow checks out the repo and runs `script/test`, `script/lint`, and `script/fmt-check`; `script/precommit` is
nothing else, while `script/fmt-check` runs the formatter on the host: on a what the git pre-commit hook runs, and it calls `script/check`;
pristine checkout with nothing installed the run dies there, after the `script/install-precommit` installs the git pre-commit hook (the `make hooks`
containerised gates have passed. **The bootstrap alone is not enough**: target shims to it); and `script/projectname` (literally that filename) simply
`script/bootstrap` installs node and yarn under nvm and leaves neither on the outputs the project's name. Scripts that need the name call
`PATH` of the shell that called it, so a bare `yarn` still exits 127. The host `script/projectname` — e.g. `script/docker` assembles its image tag from it —
entrypoints that need yarn — `script/fmt` and `script/fmt-check` — therefore so those scripts stay byte-identical across all repos. Repo-type-specific
source nvm for the pinned node version before invoking it, exactly as pre-commit extras (e.g. `go mod tidy` verification in Go repos) belong in
`script/bootstrap`'s own install step does. A runner carrying nothing but `script/precommit`, not in the hook itself. Model scripts are at
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/<name>`. The README `https://git.eeqj.de/sneak/prompts/raw/branch/main/script/<name>`. The README
must document the provided scripts in an **Entrypoints** section (see the must document the provided scripts in an **Entrypoints** section (see the
README requirements below). README requirements below).
@@ -100,198 +89,87 @@ style conventions are in separate documents:
contributor should be able to understand the entire development workflow by contributor should be able to understand the entire development workflow by
reading the Makefile. reading the Makefile.
- Every repo should have a `Dockerfile`, and it carries the repo's gates: a - Every repo should have a `Dockerfile`. All Dockerfiles must run `make check`
`lint` phase and a `test` phase, with the final stage depending on both so the as a build step so the build fails if the branch is not green. For non-server
image cannot be built unless they pass. For non-server repos the final stage repos, the Dockerfile should bring up a development environment and run
brings up a development environment; for server repos it is the runtime image. `make check`. For server repos, `make check` should run as an early build
The gate phases and the build stage start from their pinned base images and stage before the final image is assembled. Dockerfiles install development
install what those images lack either inline, as the canonical Go `Dockerfile` prerequisites by running `script/bootstrap` rather than duplicating installs
below does for `git`, or by running `script/bootstrap`, as the `prompts` inline; COPY `script/` and the dependency manifests (`package.json` +
repo's own `Dockerfile` does for its yarn packages. The development `yarn.lock`, `go.mod` + `go.sum`, etc.) before running it so the bootstrap
environment stage installs development prerequisites by running layer stays cached until dependencies change.
`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.
- **Linting and testing run in Docker, as phases of the `Dockerfile`.** There is - **Dockerfiles must use a separate lint stage for fail-fast feedback.** Go
no separate lint file. `script/lint` and `script/test` each build one phase repos use a multistage build where linting runs in an independent stage based
and nothing else: 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.
```sh The standard pattern for a Go repo Dockerfile is:
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 ```dockerfile
# Lint phase # Lint stage — fast feedback on formatting and lint issues
# golangci/golangci-lint:v2.x.x, YYYY-MM-DD # golangci/golangci-lint:v2.x.x, YYYY-MM-DD
FROM golangci/golangci-lint@sha256:... AS lint FROM golangci/golangci-lint@sha256:... AS lint
WORKDIR /src WORKDIR /src
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN go mod download
COPY . . COPY . .
RUN golangci-lint run --config .golangci.yml ./... RUN make fmt-check
RUN make lint
# Test phase. -race needs cgo and so a C compiler, which the Debian Go # Build stage
# image ships and the alpine one does not.
# golang:1.x, YYYY-MM-DD
FROM golang@sha256:... AS test
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
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.x-alpine, YYYY-MM-DD # golang:1.x-alpine, YYYY-MM-DD
FROM golang@sha256:... AS builder 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 WORKDIR /src
# Force BuildKit to run the lint stage before proceeding
COPY --from=lint /src/go.sum /dev/null
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN go mod download
COPY . . COPY . .
RUN make test
# The VERSION build arg when one is given, otherwise ARG VERSION=dev
# `git describe --tags --always` on the .git in the build context. With RUN CGO_ENABLED=0 go build -trimpath \
# .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}" \ -ldflags="-s -w -X main.Version=${VERSION}" \
-o /app ./cmd/app/ -o /app ./cmd/app/
# Runtime stage, and the last one # Runtime stage
FROM alpine@sha256:... FROM alpine@sha256:...
COPY --from=builder /app /usr/local/bin/app COPY --from=builder /app /usr/local/bin/app
ENTRYPOINT ["app"] ENTRYPOINT ["app"]
``` ```
Key points: Key points:
- The lint phase uses the `golangci/golangci-lint` image directly (it has - The lint stage uses the `golangci/golangci-lint` image directly (it
both Go and the linter), so nothing needs installing. includes both Go and the linter), so there is no need to install the
- `COPY --from=<phase> /src/go.sum /dev/null` is a no-op copy whose only linter separately.
purpose is the ordering edge. BuildKit runs stages in parallel by default, - `COPY --from=lint /src/go.sum /dev/null` is a no-op file copy that creates
and a stage nothing depends on is not built at all, so without these two a stage dependency. BuildKit runs stages in parallel by default; without
lines a red gate would not fail the build. this line, the build stage would not wait for lint to finish and a lint
- Keep the runtime stage last, and if you add a stage after it, give it the failure might not fail the overall build.
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 - If the project uses `//go:embed` directives that reference build artifacts
(e.g. a web frontend compiled in a separate stage), the lint phase must (e.g. a web frontend compiled in a separate stage), the lint stage must
create placeholder files so the embed directives resolve. Example: create placeholder files so the embed directives resolve. Example:
`RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css`. `RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css`.
- If the project requires CGO or system libraries for linting, install them The lint stage should not depend on the actual build output — it exists to
in the lint phase. The `golangci/golangci-lint` image is Debian-based and fail fast.
has no `apk`, so install with `apt-get` under the Debian package name - If the project requires CGO or system libraries for linting (e.g.
(`libvips-dev`, where alpine says `vips-dev`), and delete the package `vips-dev`), install them in the lint stage with `apk add`.
lists in the same `RUN`, so the layer does not keep them: - The build stage runs `make test` after compilation setup. Tests run in the
build stage, not the lint stage, because they may require compiled
```dockerfile artifacts or heavier dependencies.
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 - Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that
runs `script/cibuild` on push, and checks out the repo as its only other step. runs `script/cibuild` (which runs `docker build .`) on push. Since the
That script bootstraps, runs the gate phases, and then builds the image, so a Dockerfile already runs `make check`, a successful build implies all checks
successful run means every check passed; a bare `docker build .` does not pass.
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 - Use platform-standard formatters: `black` for Python, `prettier` for
JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with
@@ -311,21 +189,14 @@ style conventions are in separate documents:
module under test to verify it compiles/parses. There is no excuse for module under test to verify it compiles/parses. There is no excuse for
`make test` to be a no-op. `make test` to be a no-op.
- `make test` must complete in under 60 seconds. That is the hard cap, and a - `make test` must complete in under 20 seconds. Add a 30-second timeout in the
suite that exceeds it fails. Under 20 seconds is the target. A suite between Makefile.
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.
- **The test command should use the conditional verbose rerun pattern.** Run - **`make test` should use the conditional verbose rerun pattern.** Run tests
tests without `-v` (verbose) first. If tests fail, automatically rerun with without `-v` (verbose) first. If tests fail, automatically rerun with `-v` to
`-v` to show full output. This keeps CI logs and `docker build` output clean show full output. This keeps CI logs and `docker build` output clean on
on success (just package/suite summaries) while providing full diagnostic success (just package/suite summaries) while providing full diagnostic detail
detail on failure (every test case, every assertion). The command lives in the on failure (every test case, every assertion). The general shell pattern:
`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 ```makefile
test: test:
@@ -338,26 +209,11 @@ style conventions are in separate documents:
```makefile ```makefile
test: test:
@go test -count=1 -timeout 90s -race -cover ./... || \ @go test -timeout 30s -race -cover ./... || \
{ echo "--- Rerunning with -v for details ---"; \ { echo "--- Rerunning with -v for details ---"; \
go test -count=1 -timeout 90s -race -v ./...; exit 1; } go test -timeout 30s -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: Python example:
```makefile ```makefile
@@ -383,84 +239,10 @@ style conventions are in separate documents:
must be in `.gitignore`. No exceptions. must be in `.gitignore`. No exceptions.
- `.gitignore` should be comprehensive from the start: OS files (`.DS_Store`), - `.gitignore` should be comprehensive from the start: OS files (`.DS_Store`),
editor files (`.swp`, `*~`), in-repo agent scratch directories (`.claude/`), editor files (`.swp`, `*~`), language build artifacts, and `node_modules/`.
language build artifacts, and `node_modules/`. Fetch the standard `.gitignore` Fetch the standard `.gitignore` from
from `https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when `https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when setting up
setting up a new repo. These patterns are written to `.gitignore`'s own a new repo.
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 - **No build artifacts in version control.** Code-derived data (compiled
bundles, minified output, generated assets) must never be committed to the bundles, minified output, generated assets) must never be committed to the
@@ -476,56 +258,9 @@ style conventions are in separate documents:
- Make all changes on a feature branch. You can do whatever you want on a - Make all changes on a feature branch. You can do whatever you want on a
feature branch. feature branch.
- `.golangci.yml` is standardized. The vendored copy in a consuming repo must - `.golangci.yml` is standardized and must _NEVER_ be modified by an agent, only
_NEVER_ be modified by an agent: fetch it from manually by the user. Fetch from
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml` and keep it `https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml`.
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 <tool>; 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 <package>@<commit hash>`). 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 - When pinning images or packages by hash, add a comment above the reference
with the version and date (YYYY-MM-DD). with the version and date (YYYY-MM-DD).
@@ -639,14 +374,12 @@ style conventions are in separate documents:
settings. settings.
- Avoid putting files in the repo root unless necessary. Root should contain - Avoid putting files in the repo root unless necessary. Root should contain
only project-level config files (`README.md`, `AGENTS.md`, `Makefile`, only project-level config files (`README.md`, `Makefile`, `Dockerfile`,
`Dockerfile`, `LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`, `LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`, and
and language-specific config). Everything else goes in a subdirectory. language-specific config). Everything else goes in a subdirectory. Canonical
Canonical subdirectory names: subdirectory names:
- `bin/` — executable scripts and tools - `bin/` — executable scripts and tools
- `cmd/` — Go command entrypoints; thin only: one `main.go` per binary whose - `cmd/` — Go command entrypoints
body is a single call into `internal/` or `pkg/`, no project logic in
`cmd/`
- `configs/` — configuration templates and examples - `configs/` — configuration templates and examples
- `deploy/` — deployment manifests (k8s, compose, terraform) - `deploy/` — deployment manifests (k8s, compose, terraform)
- `docs/` — documentation and markdown (README.md stays in root) - `docs/` — documentation and markdown (README.md stays in root)
@@ -673,7 +406,3 @@ style conventions are in separate documents:
- Go: `go.mod`, `go.sum`, `.golangci.yml` - Go: `go.mod`, `go.sum`, `.golangci.yml`
- JS: `package.json`, `yarn.lock`, `.prettierrc`, `.prettierignore` - JS: `package.json`, `yarn.lock`, `.prettierrc`, `.prettierignore`
- Python: `pyproject.toml` - 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.
+380 -459
View File
@@ -18,515 +18,436 @@ https://git.eeqj.de/sneak/secret/milestone/12
# Completed Steps # Completed Steps
- 2026-10-07: The canonical files are re-vendored from `sneak/prompts` commit - 2026-10-04: A failure returns the same error value whichever command hits
`dd4027b` (https://git.eeqj.de/sneak/secret/issues/121), with golangci-lint it (https://git.eeqj.de/sneak/secret/issues/113). `internal/cli` no longer
v2.14.0 in the lint phase. Lint and test are phases of the `Dockerfile`, and keeps its own copies of `vault.ErrSecretNotFound`, `ErrVaultNotFound`,
`script/lint` and `script/test` each build one with `--no-cache`;
`Dockerfile.lint` and `script/lint-darwin` are gone, and the lint phase runs
`go vet` and checks the macOS build too. The tests run on the Debian Go image
with cgo and the race detector, with the policy's 90-second timeout.
`script/cibuild` bootstraps, runs `script/check` and builds the image;
`CHECK_EPOCH` and the memlock ulimit are gone. `--no-cache` starts Go's build
cache mount empty, so `make test` compiles everything on every run. The rules
in `CLAUDE.md` that `AGENTS.md` lacked are in `AGENTS.md`, and `CLAUDE.md` is
deleted.
- 2026-10-06: `script/test` runs the tests with the race detector, a 30-second
timeout per package and coverage, as `REPO_POLICIES.md` requires
(https://git.eeqj.de/sneak/secret/issues/32). When they fail, it reruns them
verbosely for the details and then fails anyway, so a test that fails once and
passes on the retry no longer gives a green build. `go vet` still runs first,
and every `go test` keeps `-count=1`. The tests that gave the `secret` binary
a minute now give it 10 seconds, and the PGP unlocker test's 30-second timer
is 10 seconds, so a test that hangs fails with its own message before the
package's 30-second timeout ends every test in it.
- 2026-10-06: `make test` in `script/cibuild` no longer compiles the standard
library and every dependency from nothing on every build
(https://git.eeqj.de/sneak/secret/issues/124). The `Dockerfile` runs it and
`make build` with Go's build cache in a BuildKit cache mount, which docker
keeps between builds, so each compiles only what changed since the last build.
The mount has an id of its own, so other repositories' builds do not share it.
`script/test` passes `-count=1`, so every test runs on every build and no
result comes from Go's test cache. A build with an empty cache, such as the
first after docker's build cache is cleared, compiles everything in
`make test` as before.
- 2026-10-06: `TestRemoveIgnoresTerminalOnStdout` and
`TestRemoveAsksAtTerminalOnStdin` no longer wait until Go's test timeout
(https://git.eeqj.de/sneak/secret/issues/126). On Linux, `pty.Open` of
`github.com/creack/pty` v1.1.24 passed the address of a local variable to the
`ioctl` system call as a plain number, through a function call; when Go moved
the goroutine's stack in between, the kernel wrote the terminal's number to
the old place, and `pty.Open` opened `/dev/pts/0` instead of the terminal it
had created. `secret rm` then wrote to that other terminal, and the test read
a terminal no program had open, which never ends. `go.mod` now requires the
commit on that library's main branch that passes a pointer instead; no release
has it yet. Both tests stop reading the terminal when their one-minute context
ends and fail saying so.
- 2026-10-06: The tests run quickly with the race detector on
(https://git.eeqj.de/sneak/secret/issues/120). Most of their time went to
deriving keys from passphrases with scrypt, which is slow on purpose. The new
`secret.ScryptWorkFactor`, when not zero, replaces age's scrypt work factor
when a passphrase encrypts; the tests of `internal/secret`, `internal/vault`
and `internal/cli` set it to 1 before any test runs, and the program never
sets it; `TestGetCommandOutputsToStdout` checks that the passphrase unlocker
the built binary's `secret init` writes names age's work factor, 18.
`TestRemovalAsksWithoutHoldingLock` and `TestFailedCommandReleasesLock` no
longer run in parallel with other tests: each waits at most 10 seconds for the
in-memory lock that every test in the package shares, and other tests'
commands held it longer. `TestConcurrentAddsKeepEveryVersion`, which times
nothing, and `TestGetCommandOutputsToStdout`, which no longer sets an
environment variable its commands do not read, now run in parallel. The
`script/cibuild` comment no longer says that tests are skipped without its
memlock ulimit.
- 2026-10-05: No test stores a secret larger than 1 MiB
(https://git.eeqj.de/sneak/secret/issues/52). The size tests for `secret add`,
`secret import` and the stdin buffer no longer try 2 MB, 10 MB, 99 MB, 100 MB
or 101 MB secrets, and nothing tests that a secret over the 100 MB limit is
rejected; the limit itself is unchanged. With nothing large left, the size
tests no longer skip a case for want of locked memory.
- 2026-10-05: The Go module path is `sneak.berlin/go/secret`, as
`REPO_POLICIES.md` requires, not `git.eeqj.de/sneak/secret`
(https://git.eeqj.de/sneak/secret/issues/43). Every import uses it, as do the
`-X` flags in `script/build` that stamp the version and commit shown by
`secret info`, and the examples in `pkg/agehd/README.md` and
`pkg/bip85/README.md`. `go mod tidy` now lists `github.com/dustin/go-humanize`
and `github.com/fatih/color`, which `internal/cli` imports, as direct
requirements. Code that imported the old path must switch to the new one.
- 2026-10-04: `make fmt` formats every markdown file with prettier (4-space
tabs, `proseWrap: always`) as well as the Go code, and `make fmt-check` checks
both, as the model scripts in the `prompts` repo do
(https://git.eeqj.de/sneak/secret/issues/110). Prettier is pinned by hash in
`package.json` and `yarn.lock`, and `script/bootstrap` installs node, yarn and
prettier. The `Dockerfile` lint stage copies node and yarn from a node image
pinned by hash and runs `script/bootstrap`, so its `make fmt-check` fails the
build on an unformatted markdown file. Every markdown file was formatted once,
wording unchanged.
- 2026-10-04: A mnemonic that cannot be read, in `secret init` and
`secret vault create`, gives an error that names the mnemonic only
(https://git.eeqj.de/sneak/secret/issues/115). It is read with
`secret.ReadMnemonic`, whose every error wraps the new
`secret.ErrMnemonicNotRead`; before, it was read with `ReadPassphrase`, so the
message said "failed to read mnemonic: failed to read passphrase:" and advised
setting `SB_UNLOCK_PASSPHRASE`. Without a terminal it now says "failed to read
mnemonic: stdin is not a terminal (piped input or script). Please set the
SB_SECRET_MNEMONIC environment variable or run interactively". The passphrase
messages no longer repeat "cannot read passphrase" after "failed to read
passphrase:", and empty input gives "nothing was entered".
- 2026-10-04: A failure returns the same error value whichever command hits it
(https://git.eeqj.de/sneak/secret/issues/113). `internal/cli` no longer keeps
its own copies of `vault.ErrSecretNotFound`, `ErrVaultNotFound`,
`ErrVersionNotFound` and `ErrSecretExists`: `secret mv`, `rm`, `decrypt`, `ErrVersionNotFound` and `ErrSecretExists`: `secret mv`, `rm`, `decrypt`,
`vault import`, `vault remove` and `version list`, `promote` and `rm` wrap the `vault import`, `vault remove` and `version list`, `promote` and `rm` wrap
`vault` errors. `errUnsupportedUnlockerType` is removed: `secret unlocker add` the `vault` errors. `errUnsupportedUnlockerType` is removed: `secret
gives `errInvalidUnlockerType` for an unknown type, whichever check rejects unlocker add` gives `errInvalidUnlockerType` for an unknown type, whichever
it. Off macOS, adding a keychain or Secure Enclave unlocker returns the check rejects it. Messages are unchanged, except that `secret decrypt`
`secret` package's error for it, not an `internal/cli` copy; on macOS, the of a missing secret says "not found", as `secret get` does, not "does not
check that the system is macOS is gone, as it could never fail. exist". Every error of `secret.ReadPassphrase` wraps
`secret vault import` gives `errInvalidMnemonicPhrase` for an invalid `secret.ErrPassphraseNotRead`, which supplies the words "failed to read
mnemonic, as `init` and `vault create` do. `secret generate secret` gives passphrase" that its callers used to add themselves; so two passphrases
`errLengthTooSmall` for a length below 1 wherever it is checked, and that differ now give only "passphrases do not match", the words now follow
`errUnsupportedSecretType` for `--type mnemonic` too. `secret import` of a "failed to read mnemonic:" and "failed to read passphrase confirmation:",
file over 100MB wraps `errSecretTooLarge`, as `secret add` returns it. and a terminal read error no longer repeats them. A GPG key the keyring
`vault.ErrNilValueBuffer` is replaced by `secret.ErrNilValueBuffer`, which does not hold gives `secret.ErrGPGKeyNotFound`, found by gpg's status line
`secret` already returned under another name. Messages are unchanged, except for "No public key"; before, the message repeated "failed to resolve GPG
that `secret decrypt` of a missing secret says "not found", as `secret get` key fingerprint" and ended in gpg's exit status. The keychain unlocker
does, not "does not exist"; `vault import` of an invalid mnemonic says returns `errNilDataBuffer` for nil data; this and its test build only on
"invalid BIP39 mnemonic phrase"; `--type mnemonic` says "unsupported type: macOS with cgo and were only read. `bip85.ErrPasswordTooShort` and
mnemonic (use 'secret generate mnemonic' instead)"; and a file too large to `ErrEncodedTooShort` are removed with their checks: 64 bytes of entropy
import says always give 86 Base64 or 80 Base85 characters, the most a password length
`failed to read secret from file <path>: secret too large: exceeds 100MB limit`. may ask for. Tests that matched these errors' text use `errors.Is`.
Every error of `secret.ReadPassphrase` wraps `secret.ErrPassphraseNotRead`, - 2026-10-04: Tests check which error a failure returns with `errors.Is`,
which supplies the words "failed to read passphrase" that its callers used to not by matching words of its message
add themselves; so two passphrases that differ now give only "passphrases do (https://git.eeqj.de/sneak/secret/issues/49). Every exported error that
not match", the words now follow "failed to read mnemonic:" and "failed to can be returned has a test that the function returns it, and errors
read passphrase confirmation:", and a terminal read error no longer repeats wrapping a cause are checked through the wrapping. Checks that still match
them. A GPG key the keyring does not hold gives `secret.ErrGPGKeyNotFound`, text, because the error has no exported value the test can name, are
found by gpg's status line for "No public key"; before, the message repeated listed on the issue.
"failed to resolve GPG key fingerprint" and ended in gpg's exit status. The
keychain unlocker returns `errNilDataBuffer` for nil data; this and its test
build only on macOS with cgo and were only read. `bip85.ErrPasswordTooShort`
and `ErrEncodedTooShort` are removed with their checks: 64 bytes of entropy
always give 86 Base64 or 80 Base85 characters, the most a password length may
ask for. Tests that matched these errors' text use `errors.Is`.
- 2026-10-04: Tests check which error a failure returns with `errors.Is`, not by
matching words of its message (https://git.eeqj.de/sneak/secret/issues/49).
Every exported error that can be returned has a test that the function returns
it, and errors wrapping a cause are checked through the wrapping. Checks that
still match text, because the error has no exported value the test can name,
are listed on the issue.
- 2026-10-04: When a vault cannot be opened through its current unlocker, - 2026-10-04: When a vault cannot be opened through its current unlocker,
because a file the unlocker needs is missing or damaged, its keychain item or because a file the unlocker needs is missing or damaged, its keychain item
Secure Enclave key is gone, or the passphrase is wrong, the error now ends by or Secure Enclave key is gone, or the passphrase is wrong, the error now
naming the vault, saying that it still opens with its mnemonic, and that ends by naming the vault, saying that it still opens with its mnemonic,
`secret unlocker add passphrase`, run with `SB_SECRET_MNEMONIC` set to it, and that `secret unlocker add passphrase`, run with `SB_SECRET_MNEMONIC`
gives the vault a new unlocker; for a vault that is not the current one, as in set to it, gives the vault a new unlocker; for a vault that is not the
`secret move` between vaults, it says to run `secret vault select` first current one, as in `secret move` between vaults, it says to run
(https://git.eeqj.de/sneak/secret/issues/47). Before, it ended with the bare `secret vault select` first (https://git.eeqj.de/sneak/secret/issues/47).
cause. The advice is given only when the vault metadata records the key the Before, it ended with the bare cause. The advice is given only when the
mnemonic derives, so not for a vault created without a mnemonic, and not when vault metadata records the key the mnemonic derives, so not for a vault
the passphrase could not be read at all. `secret vault import` is not named: created without a mnemonic, and not when the passphrase could not be read
it refuses a vault that has a long-term key. `secret encrypt` and at all. `secret vault import` is not named: it refuses a vault that has a
`secret decrypt` now read the key secret through `vault.GetSecret`, as long-term key. `secret encrypt` and `secret decrypt` now read the key
`secret get` does, so they give the same advice; `Secret.GetValue`, the other secret through `vault.GetSecret`, as `secret get` does, so they give the
way to get the long-term key, is removed. When a secret's `current` file same advice; `Secret.GetValue`, the other way to get the long-term key, is
cannot be read, the error says that `secret version list` lists its versions removed. When a secret's `current` file cannot be read, the error says
and `secret version promote` makes one current. The causes stay wrapped. that `secret version list` lists its versions and `secret version promote`
- 2026-10-04: An unlocker's ID is the name of its directory in `unlockers.d`, so makes one current. The causes stay wrapped.
no two unlockers of a vault share one - 2026-10-04: An unlocker's ID is the name of its directory in `unlockers.d`,
so no two unlockers of a vault share one
(https://git.eeqj.de/sneak/secret/issues/98). Before, a keychain or Secure (https://git.eeqj.de/sneak/secret/issues/98). Before, a keychain or Secure
Enclave unlocker's ID was its creation time to the minute and the host name, Enclave unlocker's ID was its creation time to the minute and the host name,
and a passphrase unlocker's the time to the minute, so two created within a and a passphrase unlocker's the time to the minute, so two created within a
minute shared an ID, and `unlocker select`, `unlocker remove` and the minute shared an ID, and `unlocker select`, `unlocker remove` and the
selection `unlocker add` makes acted on the older one. A PGP unlocker's ID was selection `unlocker add` makes acted on the older one. A PGP unlocker's ID
`pgp-` and its key's fingerprint; a second PGP unlocker for a key is still was `pgp-` and its key's fingerprint; a second PGP unlocker for a key is
refused, now by comparing the fingerprint in the other unlockers' metadata. still refused, now by comparing the fingerprint in the other unlockers'
`unlocker list` and the shell completion of `unlocker select` and metadata. `unlocker list` and the shell completion of `unlocker select` and
`unlocker remove` take each ID from the directory the unlocker was read from, `unlocker remove` take each ID from the directory the unlocker was read
no longer by matching metadata, so two unlockers with the same metadata are from, no longer by matching metadata, so two unlockers with the same
listed apart; an unlocker of an unknown type is listed under its directory metadata are listed apart; an unlocker of an unknown type is listed under
name, and completion now offers Secure Enclave unlockers too. The keychain and its directory name, and completion now offers Secure Enclave unlockers too.
Secure Enclave code was type-checked by `script/lint-darwin`, never run; a The keychain and Secure Enclave code was type-checked by
test on Linux lists, completes, selects and removes each of two passphrase `script/lint-darwin`, never run; a test on Linux lists, completes, selects
unlockers with the same metadata by its own ID. and removes each of two passphrase unlockers with the same metadata by its
- 2026-10-04: README's Storage Architecture, `secret version promote`, Technical own ID.
Details and Testing text matches the code - 2026-10-04: README's Storage Architecture, `secret version promote`,
(https://git.eeqj.de/sneak/secret/issues/102). `current` and `currentvault` Technical Details and Testing text matches the code
are plain files holding a name, not symbolic links; a version's metadata is (https://git.eeqj.de/sneak/secret/issues/102). `current` and
the encrypted `metadata.age`; the state directory is `berlin.sneak.pkg.secret` `currentvault` are plain files holding a name, not symbolic links; a
in the user's configuration directory, not `~/.local/share/secret`, and holds version's metadata is the encrypted `metadata.age`; the state directory is
the `lock` file. Also corrected: the code sets up no Touch ID for the keychain `berlin.sneak.pkg.secret` in the user's configuration directory, not
or Secure Enclave unlocker, and the Secure Enclave only decrypts; per-version `~/.local/share/secret`, and holds the `lock` file. Also corrected: the
keys give no forward secrecy; `pub.age` is not age-encrypted; vault metadata code sets up no Touch ID for the keychain or Secure Enclave unlocker, and
holds no vault name. Testing lists only `make test`. the Secure Enclave only decrypts; per-version keys give no forward
secrecy; `pub.age` is not age-encrypted; vault metadata holds no vault
name. Testing lists only `make test`.
- 2026-10-04: `secret init` and `secret vault create` create a vault whole or - 2026-10-04: `secret init` and `secret vault create` create a vault whole or
not at all (https://git.eeqj.de/sneak/secret/issues/105). `vault.CreateVault` not at all (https://git.eeqj.de/sneak/secret/issues/105).
now takes the unlocker passphrase too, writes the vault directory with its `vault.CreateVault` now takes the unlocker passphrase too, writes the vault
metadata, long-term public key and passphrase unlocker, `longterm.age` directory with its metadata, long-term public key and passphrase unlocker,
included, into a temporary directory, renames that into `vaults.d` once it is `longterm.age` included, into a temporary directory, renames that into
complete, and only then makes the vault current. Before, either command killed `vaults.d` once it is complete, and only then makes the vault current.
after the passphrase prompt but before the unlocker was written left a vault Before, either command killed after the passphrase prompt but before the
with no unlocker, which `vault create` had already made current and which unlocker was written left a vault with no unlocker, which `vault create` had
neither command would create again. Killed part-way now, it leaves no vault, already made current and which neither command would create again. Killed
and the next command that takes the lock deletes the temporary directory; or, part-way now, it leaves no vault, and the next command that takes the lock
killed between the rename and making the vault current, a complete vault that deletes the temporary directory; or, killed between the rename and making
is not current, which `secret vault select` makes current. the vault current, a complete vault that is not current, which
`secret vault select` makes current.
- 2026-10-04: A failed `secret unlocker add keychain` or - 2026-10-04: A failed `secret unlocker add keychain` or
`secret unlocker add secure-enclave` no longer leaves its keychain item or `secret unlocker add secure-enclave` no longer leaves its keychain item or
Secure Enclave key behind (https://git.eeqj.de/sneak/secret/issues/89). Secure Enclave key behind (https://git.eeqj.de/sneak/secret/issues/89).
`CreateSecureEnclaveUnlocker` gets the long-term key before it creates the `CreateSecureEnclaveUnlocker` gets the long-term key before it creates the
Secure Enclave key, so that a wrong passphrase creates none, and deletes the Secure Enclave key, so that a wrong passphrase creates none, and deletes the
key again if encrypting with it or writing the unlocker then fails. key again if encrypting with it or writing the unlocker then fails.
`macse.CreateKey` finds the new key's hash right after `sc_auth` creates it, `macse.CreateKey` finds the new key's hash right after `sc_auth` creates
and fails with an error naming the key's label if it cannot; it deletes the it, and fails with an error naming the key's label if it cannot; it deletes
key again if getting its public key then fails. The Objective-C was only read, the key again if getting its public key then fails. The Objective-C was only
never compiled or run, and so was `macse_darwin.go`, which is cgo only. read, never compiled or run, and so was `macse_darwin.go`, which is cgo only.
`CreateKeychainUnlocker` writes all of the unlocker's files, the metadata `CreateKeychainUnlocker` writes all of the unlocker's files, the metadata
among them, before it stores the item in the keychain, and deletes the item among them, before it stores the item in the keychain, and deletes the item
again if moving the unlocker into place then fails. A failure to delete is again if moving the unlocker into place then fails. A failure to delete is
reported along with the first error. The tests of this run only on macOS: the reported along with the first error. The tests of this run only on macOS:
Secure Enclave one in a build with cgo on a Mac with a Secure Enclave, the the Secure Enclave one in a build with cgo on a Mac with a Secure Enclave,
keychain one in a build with cgo. the keychain one in a build with cgo.
- 2026-10-04: What a command killed part-way left under a `.tmp-` name - 2026-10-04: What a command killed part-way left under a `.tmp-` name
(https://git.eeqj.de/sneak/secret/issues/75), the temporary directories of (https://git.eeqj.de/sneak/secret/issues/75), the temporary directories
`secret.TempDirFor` and the temporary files of `secret.WriteFileAtomic`, of `secret.TempDirFor` and the temporary files of
encrypted keys included, is deleted by the next command that takes the state `secret.WriteFileAtomic`, encrypted keys included, is deleted by the next
directory lock. Before, it stayed until deleted by hand. A command writes command that takes the state directory lock. Before, it stayed until
`finished` into the lock file just before it releases the lock; the next one deleted by hand. A command writes `finished` into the lock file just
to take the lock searches only when it does not find that, so after a command before it releases the lock; the next one to take the lock searches only
that finished nothing is searched, however many secrets and versions there when it does not find that, so after a command that finished nothing is
are. The search looks in the state directory, each vault, each secret and each searched, however many secrets and versions there are. The search looks
version, the only directories those helpers make them in. A command that only in the state directory, each vault, each secret and each version, the
reads takes no lock and deletes nothing. A failure to delete is warned about only directories those helpers make them in. A command that only reads
takes no lock and deletes nothing. A failure to delete is warned about
and the command goes on. An unlocker directory with no metadata file was and the command goes on. An unlocker directory with no metadata file was
already removed by `secret unlocker remove` given its directory name; a test already removed by `secret unlocker remove` given its directory name; a
now shows it. test now shows it.
- 2026-10-04: An age identity's private key goes into a locked buffer through - 2026-10-04: An age identity's private key goes into a locked buffer
`secret.IdentityToLockedBuffer` everywhere through `secret.IdentityToLockedBuffer` everywhere
(https://git.eeqj.de/sneak/secret/issues/38): the vault's long-term key when a (https://git.eeqj.de/sneak/secret/issues/38): the vault's long-term key
passphrase, PGP, keychain or Secure Enclave unlocker is created, the new when a passphrase, PGP, keychain or Secure Enclave unlocker is created,
unlocker's own key, a new secret version's key, and the key `secret encrypt` the new unlocker's own key, a new secret version's key, and the key
generates. Before, each place converted the string age returns to bytes and `secret encrypt` generates. Before, each place converted the string age
left the string in ordinary memory. The function moves the string's own bytes returns to bytes and left the string in ordinary memory. The function
into the buffer, which overwrites them; the copies age makes while writing the moves the string's own bytes into the buffer, which overwrites them; the
string remain, as its comment says. The 1.0 memory-security entry below no copies age makes while writing the string remain, as its comment says.
longer lists these places, `internal/cli/crypto.go` among them, nor The 1.0 memory-security entry below no longer lists these places,
`version.go:155`, which was `internal/secret/version.go`, not `internal/cli/crypto.go` among them, nor `version.go:155`, which was
`internal/cli/version.go`. `internal/secret/version.go`, not `internal/cli/version.go`.
- 2026-10-04: `script/lint-darwin` (`make lint-darwin`) runs `go vet` and - 2026-10-04: `script/lint-darwin` (`make lint-darwin`) runs `go vet` and
`golangci-lint` in docker on the code as a macOS build compiles it `golangci-lint` in docker on the code as a macOS build compiles it
(`GOOS=darwin`), with cgo off (https://git.eeqj.de/sneak/secret/issues/50). (`GOOS=darwin`), with cgo off
`script/check` runs it, and the `Dockerfile` lint stage runs its commands, so (https://git.eeqj.de/sneak/secret/issues/50). `script/check` runs it, and
`script/cibuild` does too. Before, CI on Linux never compiled the files built the `Dockerfile` lint stage runs its commands, so `script/cibuild` does too.
only for macOS. Compiling cgo code for macOS needs Apple's SDK headers, and Before, CI on Linux never compiled the files built only for macOS. Compiling
both `internal/macse` and `github.com/keybase/go-keychain` are cgo on macOS. cgo code for macOS needs Apple's SDK headers, and both `internal/macse` and
So the three functions that call `go-keychain` moved from `github.com/keybase/go-keychain` are cgo on macOS. So the three functions
`keychainunlocker.go` to `keychainunlocker_cgo.go`, built only with cgo on that call `go-keychain` moved from `keychainunlocker.go` to
macOS like `macse_darwin.go`. A macOS build without cgo, which before did not `keychainunlocker_cgo.go`, built only with cgo on macOS like
compile, gets `keychainunlocker_nocgo.go` and the `macse` stub instead, whose `macse_darwin.go`. A macOS build without cgo, which before did not compile,
errors say the keychain or Secure Enclave needs a macOS build with cgo. The gets `keychainunlocker_nocgo.go` and the `macse` stub instead, whose errors
check covers the rest of the keychain unlocker, the Secure Enclave unlocker say the keychain or Secure Enclave needs a macOS build with cgo. The check
and the macOS-only tests other than `keychainunlocker_test.go`, whose lint covers the rest of the keychain unlocker, the Secure Enclave unlocker and
the macOS-only tests other than `keychainunlocker_test.go`, whose lint
findings are fixed. For the length and complexity limits, parts of findings are fixed. For the length and complexity limits, parts of
`GetIdentity`, `getLongTermPrivateKey` and `CreateKeychainUnlocker` moved into `GetIdentity`, `getLongTermPrivateKey` and `CreateKeychainUnlocker` moved
functions of their own, and the Secure Enclave unlocker derives the long-term into functions of their own, and the Secure Enclave unlocker derives the
key from the mnemonic through the same function as the keychain unlocker long-term key from the mnemonic through the same function as the keychain
instead of a copy of it. Lines over 88 columns in the files the check cannot unlocker instead of a copy of it. Lines over 88 columns in the files the
see are wrapped. check cannot see are wrapped.
- 2026-10-04: `secret rm`, `secret version rm`, `secret vault remove` and - 2026-10-04: `secret rm`, `secret version rm`, `secret vault remove` and
`secret unlocker remove` ask `[y/N]` before removing anything `secret unlocker remove` ask `[y/N]` before removing anything
(https://git.eeqj.de/sneak/secret/issues/39), naming what they remove: the (https://git.eeqj.de/sneak/secret/issues/39), naming what they remove: the
secret, its vault and its version count; the version, secret and vault; the secret, its vault and its version count; the version, secret and vault; the
vault and its secret count; the unlocker, its vault and whether it is the vault and its secret count; the unlocker, its vault and whether it is the
last, and for the last the vault's secret count and that the vault then opens last, and for the last the vault's secret count and that the vault then
only with its mnemonic. Only `y` or `yes` goes ahead. Without `--force`, a opens only with its mnemonic. Only `y` or `yes` goes ahead. Without
command whose stdin is not a terminal fails at once. `--force` (now also on `--force`, a command whose stdin is not a terminal fails at once. `--force`
`rm` and `version rm`) removes without asking; it replaces the old refusals to (now also on `rm` and `version rm`) removes without asking; it replaces the
remove a vault with secrets or the last unlocker of one without `--force`, old refusals to remove a vault with secrets or the last unlocker of one
which the question now covers. The checks run, and the question is asked, without `--force`, which the question now covers. The checks run, and the
before the state directory lock is taken; under the lock the checks run again, question is asked, before the state directory lock is taken; under the
and if they would ask a different question, nothing is removed. `secret rm` lock the checks run again, and if they would ask a different question,
fails when it cannot count the versions. nothing is removed. `secret rm` fails when it cannot count the versions.
- 2026-10-04: A crash while an unlocker is being replaced no longer leaves a - 2026-10-04: A crash while an unlocker is being replaced no longer leaves a
current unlocker that cannot open the vault current unlocker that cannot open the vault
(https://git.eeqj.de/sneak/secret/issues/71). Every new unlocker gets a (https://git.eeqj.de/sneak/secret/issues/71). Every new unlocker gets a
directory of its own, named with the time to the nanosecond: directory of its own, named with the time to the nanosecond:
`passphrase-<time>`, `<host>-pgp-<time>`, and for a keychain or Secure Enclave `passphrase-<time>`, `<host>-pgp-<time>`, and for a keychain or Secure
unlocker the keychain item or Secure Enclave key, which names the directory, Enclave unlocker the keychain item or Secure Enclave key, which names the
carries the time instead of the day. `secret.WriteDir` fails on a directory directory, carries the time instead of the day. `secret.WriteDir` fails on a
that exists instead of writing into it. `unlocker add passphrase` writes the directory that exists instead of writing into it. `unlocker add passphrase`
new unlocker, makes it current, and only then removes the vault's other writes the new unlocker, makes it current, and only then removes the vault's
passphrase unlockers; a crash between the last two steps leaves the old one other passphrase unlockers; a crash between the last two steps leaves the old
beside the new, and the old passphrase still opens the vault through it until one beside the new, and the old passphrase still opens the vault through it
the next `unlocker add passphrase` or an `unlocker remove` removes it. A PGP, until the next `unlocker add passphrase` or an `unlocker remove` removes it.
keychain or Secure Enclave unlocker added on the same host and day as another A PGP, keychain or Secure Enclave unlocker added on the same host and day as
of its type is added beside it instead of replacing it. another of its type is added beside it instead of replacing it.
- 2026-10-04: `SB_SECRET_MNEMONIC` and `SB_UNLOCK_PASSPHRASE` are read once per - 2026-10-04: `SB_SECRET_MNEMONIC` and `SB_UNLOCK_PASSPHRASE` are read once
command, in its `RunE`, into locked buffers on the CLI `Instance`, and unset per command, in its `RunE`, into locked buffers on the CLI `Instance`, and
at once, so that no program the command runs, `gpg` included, inherits them unset at once, so that no program the command runs, `gpg` included,
(https://git.eeqj.de/sneak/secret/issues/60). Nothing below the command reads inherits them (https://git.eeqj.de/sneak/secret/issues/60). Nothing below
the environment; the buffers are passed down: `vault.CreateVault` takes the the command reads the environment; the buffers are passed down:
mnemonic (nil for none), a `Vault` derives its long-term key from its `vault.CreateVault` takes the mnemonic (nil for none), a `Vault` derives its
`Mnemonic` and gives its `UnlockPassphrase` to a passphrase unlocker, and the long-term key from its `Mnemonic` and gives its `UnlockPassphrase` to a
PGP, keychain and Secure Enclave unlocker constructors take both. passphrase unlocker, and the PGP, keychain and Secure Enclave unlocker
`CreatePGPUnlocker` sets both on the vault it loads, through `SetMnemonic` and constructors take both. `CreatePGPUnlocker` sets both on the vault it
`SetUnlockPassphrase`, now part of `VaultInterface`, before calling its loads, through `SetMnemonic` and `SetUnlockPassphrase`, now part of
`GetOrDeriveLongTermKey`. `init` and `vault create` no longer put the mnemonic `VaultInterface`, before calling its `GetOrDeriveLongTermKey`. `init` and
into the environment. Unsetting erases nothing: the starting environment `vault create` no longer put the mnemonic into the environment. Unsetting
(`/proc/<pid>/environ`) and memory still hold the value. The README warns erases nothing: the starting environment (`/proc/<pid>/environ`) and
against both variables. memory still hold the value. The README warns against both variables.
- 2026-10-04: `.golangci.yml` is again the canonical file from `sneak/prompts`, - 2026-10-04: `.golangci.yml` is again the canonical file from
byte for byte (https://git.eeqj.de/sneak/secret/issues/66). It runs `sneak/prompts`, byte for byte
`gomodguard_v2` in place of the deprecated `gomodguard`, so the lint no longer (https://git.eeqj.de/sneak/secret/issues/66). It runs `gomodguard_v2`
warns, and enables `depguard` with a rule that keeps `net/http/httptest` out in place of the deprecated `gomodguard`, so the lint no longer warns,
of non-test files. Neither raised a finding in this repo. and enables `depguard` with a rule that keeps `net/http/httptest` out of
non-test files. Neither raised a finding in this repo.
- 2026-10-04: `secret unlocker add pgp` works on Linux - 2026-10-04: `secret unlocker add pgp` works on Linux
(https://git.eeqj.de/sneak/secret/issues/88). `CreatePGPUnlocker` gets the (https://git.eeqj.de/sneak/secret/issues/88). `CreatePGPUnlocker` gets
vault's long-term key as adding a passphrase unlocker does, with the vault's the vault's long-term key as adding a passphrase unlocker does, with the
`GetOrDeriveLongTermKey`, now part of `VaultInterface`: from the mnemonic, vault's `GetOrDeriveLongTermKey`, now part of `VaultInterface`: from the
checked against the vault, or else from the current unlocker. Before, it used mnemonic, checked against the vault, or else from the current unlocker.
the keychain unlocker's helper, which on every platform but macOS always Before, it used the keychain unlocker's helper, which on every platform
failed. A test adds a PGP unlocker for a throwaway GPG key, getting the but macOS always failed. A test adds a PGP unlocker for a throwaway GPG
long-term key once from the mnemonic and once from a passphrase unlocker, and key, getting the long-term key once from the mnemonic and once from a
reads a secret through the new unlocker. passphrase unlocker, and reads a secret through the new unlocker.
- 2026-10-04: A vault name may use only lowercase ASCII letters, digits, `.`, - 2026-10-04: A vault name may use only lowercase ASCII letters, digits,
`-` and `_`, and must not be empty, `.` or `..` `.`, `-` and `_`, and must not be empty, `.` or `..`
(https://git.eeqj.de/sneak/secret/issues/68); the error and `README.md` state (https://git.eeqj.de/sneak/secret/issues/68); the error and `README.md`
the rule. `vault create`, `vault import`, `vault select`, `vault remove`, both state the rule. `vault create`, `vault import`, `vault select`,
vault names of `mv` and shell completion of a `vault:secret` argument check `vault remove`, both vault names of `mv` and shell completion of a
the name as typed with `vault.ValidateVaultName` before building any path from `vault:secret` argument check the name as typed with
it. Before, `vault import ..` wrote a long-term key and an unlocker into the `vault.ValidateVaultName` before building any path from it. Before,
state directory itself, and `vault select ..` made that the current vault. `vault import ..` wrote a long-term key and an unlocker into the state
- 2026-10-04: `script/cibuild` runs the checks again on an unchanged tree directory itself, and `vault select ..` made that the current vault.
(https://git.eeqj.de/sneak/secret/issues/54). It passes the current time as - 2026-10-04: `script/cibuild` runs the checks again on an unchanged
the `CHECK_EPOCH` build argument, which both the lint and the build stage of tree (https://git.eeqj.de/sneak/secret/issues/54). It passes the
the `Dockerfile` declare after their module download, so the `RUN` steps below current time as the `CHECK_EPOCH` build argument, which both the lint
the argument run again on each build while the base images and module and the build stage of the `Dockerfile` declare after their module
downloads stay cached. Before, a second run on the same tree took every check download, so the `RUN` steps below the argument run again on each
from the build cache and reported success having run nothing. build while the base images and module downloads stay cached. Before,
a second run on the same tree took every check from the build cache
and reported success having run nothing.
- 2026-10-04: A failed unlocker add no longer leaves a partial unlocker - 2026-10-04: A failed unlocker add no longer leaves a partial unlocker
directory (https://git.eeqj.de/sneak/secret/issues/48). directory (https://git.eeqj.de/sneak/secret/issues/48).
`secret unlocker add pgp` resolves the GPG key's fingerprint once, for its `secret unlocker add pgp` resolves the GPG key's fingerprint once, for
duplicate check, and passes it to `CreatePGPUnlocker` to record. its duplicate check, and passes it to `CreatePGPUnlocker` to record.
`CreatePGPUnlocker` and `CreateKeychainUnlocker` get the long-term key and `CreatePGPUnlocker` and `CreateKeychainUnlocker` get the long-term key
encrypt everything before writing anything. All four unlocker types write and encrypt everything before writing anything. All four unlocker
their files through `secret.WriteDir`: a new unlocker is built in a temporary types write their files through `secret.WriteDir`: a new unlocker is
directory, renamed into place when complete and removed on a failure. built in a temporary directory, renamed into place when complete and
- 2026-10-04: `secret unlocker select` and `secret unlocker remove` skip, with removed on a failure.
the warning `unlocker list` gives, an unlocker directory whose metadata file - 2026-10-04: `secret unlocker select` and `secret unlocker remove`
cannot be checked for, read or parsed, instead of failing when it sorts before skip, with the warning `unlocker list` gives, an unlocker directory
the unlocker asked for. Such a directory, or one without a metadata file, is whose metadata file cannot be checked for, read or parsed, instead of
removed by its directory name, the name the warning gives; only the directory failing when it sorts before the unlocker asked for. Such a directory,
is removed, since its type is unknown. Removing one whose metadata file is or one without a metadata file, is removed by its directory name, the
missing or corrupt never counts as removing the last unlocker. Removing one name the warning gives; only the directory is removed, since its type
whose metadata file cannot be checked for or read always does, since it may be is unknown. Removing one whose metadata file is missing or corrupt
the only working unlocker, so in a vault with secrets it needs `--force`. never counts as removing the last unlocker. Removing one whose metadata
- 2026-10-04: A failed command prints its error once, without the usage text file cannot be checked for or read always does, since it may be the
after it (https://git.eeqj.de/sneak/secret/issues/41). Usage is still printed only working unlocker, so in a vault with secrets it needs `--force`.
for a command called wrongly: wrong number of arguments, unknown flag, bad - 2026-10-04: A failed command prints its error once, without the usage
flag value, missing required flag, or flags that break a flag group (mutually text after it (https://git.eeqj.de/sneak/secret/issues/41). Usage is
exclusive, required together, one required). The root command's still printed for a command called wrongly: wrong number of arguments,
`PersistentPreRunE` turns usage off. Cobra checks arguments and flag values unknown flag, bad flag value, missing required flag, or flags that
before that hook but required flags and flag groups only after it, so the hook break a flag group (mutually exclusive, required together, one
checks those two first. Root `SilenceUsage` would have hidden usage for all of required). The root command's `PersistentPreRunE` turns usage off.
these. Cobra checks arguments and flag values before that hook but required
- 2026-10-04: `secret get` keeps the secret in locked memory until it writes it flags and flag groups only after it, so the hook checks those two
out (https://git.eeqj.de/sneak/secret/issues/37): `Vault.GetSecret` and first. Root `SilenceUsage` would have hidden usage for all of these.
`Vault.GetSecretVersion` return a `*memguard.LockedBuffer`, which every caller - 2026-10-04: `secret get` keeps the secret in locked memory until it
destroys, and `secret get` writes its bytes straight to stdout, still with no writes it out (https://git.eeqj.de/sneak/secret/issues/37):
trailing newline. Before, the value was copied into ordinary memory that `Vault.GetSecret` and `Vault.GetSecretVersion` return a
nothing wiped, and `get --version` also wrote it to the debug log. `*memguard.LockedBuffer`, which every caller destroys, and `secret get`
- 2026-10-04: The `Makefile` no longer sets `DOCKER_HOST`, so its docker targets writes its bytes straight to stdout, still with no trailing newline.
use the local docker daemon, or whatever `DOCKER_HOST` the environment sets. Before, the value was copied into ordinary memory that nothing wiped,
`make build` calls the new `script/build`, which stamps the version (`VERSION` and `get --version` also wrote it to the debug log.
from the environment, else `git describe`) and the git commit as before. - 2026-10-04: The `Makefile` no longer sets `DOCKER_HOST`, so its docker
`build`, `clean`, `install` and `docker-run` are in `.PHONY`; `make install` targets use the local docker daemon, or whatever `DOCKER_HOST` the
depends on `build`. The `vet` target is gone: `script/test` runs `go vet` environment sets. `make build` calls the new `script/build`, which
first. stamps the version (`VERSION` from the environment, else
- 2026-10-04: `.gitignore` is the org's standard file, which ignores `.env`, `git describe`) and the git commit as before. `build`, `clean`,
`.env.*`, `*.pem` and `*.key` and editor and OS files, plus this repo's `install` and `docker-run` are in `.PHONY`; `make install` depends on
`/secret`, `*.log`, `*.test` and `settings.local.json` `build`. The `vet` target is gone: `script/test` runs `go vet` first.
(https://git.eeqj.de/sneak/secret/issues/40). `.dockerignore` also leaves out - 2026-10-04: `.gitignore` is the org's standard file, which ignores
`node_modules`; `.git` stays in the build context for the version stamp. `.env`, `.env.*`, `*.pem` and `*.key` and editor and OS files, plus
this repo's `/secret`, `*.log`, `*.test` and `settings.local.json`
(https://git.eeqj.de/sneak/secret/issues/40). `.dockerignore` also
leaves out `node_modules`; `.git` stays in the build context for the
version stamp.
- 2026-10-04: `secret init` refuses when the default vault exists, and - 2026-10-04: `secret init` refuses when the default vault exists, and
`secret vault create NAME` when `NAME` does, with "vault NAME already exists", `secret vault create NAME` when `NAME` does, with "vault NAME already
before writing anything. The check is in `vault.CreateVault`, which both exists", before writing anything. The check is in `vault.CreateVault`,
commands call while holding the state directory lock, so two creates of one which both commands call while holding the state directory lock, so two
vault at once cannot both pass the check. Before, either command replaced the creates of one vault at once cannot both pass the check. Before, either
vault's metadata, passphrase unlocker and `longterm.age`, so none of its command replaced the vault's metadata, passphrase unlocker and
secrets could be decrypted any more. Both commands now ask for the unlocker `longterm.age`, so none of its secrets could be decrypted any more. Both
passphrase before creating the vault, so one stopped at that prompt leaves no commands now ask for the unlocker passphrase before creating the vault,
vault behind. so one stopped at that prompt leaves no vault behind.
- 2026-10-04: The `internal/cli` tests are back to about their time before the - 2026-10-04: The `internal/cli` tests are back to about their time
state directory lock (https://git.eeqj.de/sneak/secret/issues/80). The test before the state directory lock
that each changing command waits for the lock releases it as soon as it sees (https://git.eeqj.de/sneak/secret/issues/80). The test that each
the command waiting there, instead of after a fixed 100 ms. The two vaults changing command waits for the lock releases it as soon as it sees the
with passphrase unlockers that the path and move tests start from are made command waiting there, instead of after a fixed 100 ms. The two vaults
once and copied for each test. with passphrase unlockers that the path and move tests start from are
- 2026-10-04: `secret mv` rejects a move whose destination is the source under made once and copied for each test.
another name, such as `foo` for `Foo` on a case-insensitive filesystem (the - 2026-10-04: `secret mv` rejects a move whose destination is the source
macOS default) or a name reached through a symbolic link, before changing under another name, such as `foo` for `Foo` on a case-insensitive
anything, with or without `--force`, within a vault and between vaults; filesystem (the macOS default) or a name reached through a symbolic
before, `--force` removed the destination and so deleted the secret. A rename link, before changing anything, with or without `--force`, within a
that changes only letter case works on a case-sensitive filesystem as before. vault and between vaults; before, `--force` removed the destination and
- 2026-10-04: Lint runs only in docker: `script/lint` builds `Dockerfile.lint`, so deleted the secret. A rename that changes only letter case works on a
where golangci-lint is a build step rebuilt on every run case-sensitive filesystem as before.
(`--no-cache-filter`), so an unchanged tree is linted too; the module download - 2026-10-04: Lint runs only in docker: `script/lint` builds
stays cached. `script/bootstrap` no longer installs golangci-lint, and the `Dockerfile.lint`, where golangci-lint is a build step rebuilt on
`Dockerfile` lint stage calls it directly instead of `make lint`. every run (`--no-cache-filter`), so an unchanged tree is linted too;
`golangci-lint config verify` is not run: it fetches its schema live over the module download stays cached. `script/bootstrap` no longer
unpinned HTTPS. installs golangci-lint, and the `Dockerfile` lint stage calls it
- 2026-10-04: A PGP unlocker whose metadata has no usable GPG key ID no longer directly instead of `make lint`. `golangci-lint config verify` is not
panics: `GetID()` warns with the unlocker's directory and returns run: it fetches its schema live over unpinned HTTPS.
`pgp-unknown`. `ListUnlockers` skips, with a warning, an unlocker whose - 2026-10-04: A PGP unlocker whose metadata has no usable GPG key ID
metadata file cannot be checked for, read or parsed instead of failing, so no longer panics: `GetID()` warns with the unlocker's directory and
`secret unlocker list` still lists the others; the listing's ID lookup no returns `pgp-unknown`. `ListUnlockers` skips, with a warning, an
longer warns about that directory again. unlocker whose metadata file cannot be checked for, read or parsed
- 2026-10-03: `secret mv` rejects a move whose destination is the source instead of failing, so `secret unlocker list` still lists the others;
(`mv --force x x`, `mv --force work:x work:`, or an empty destination, which the listing's ID lookup no longer warns about that directory again.
defaults to the source name) before changing anything; before, `--force` - 2026-10-03: `secret mv` rejects a move whose destination is the
removed the destination first and so deleted the secret. Every vault name source (`mv --force x x`, `mv --force work:x work:`, or an empty
given with `vault:` must be one of the existing vaults by exact name, so destination, which defaults to the source name) before changing
`work:x work/:x` is rejected instead of being taken for a move between two anything; before, `--force` removed the destination first and so
vaults. A move within a named vault no longer makes that vault the current deleted the secret. Every vault name given with `vault:` must be one
one, whether it succeeds or fails. of the existing vaults by exact name, so `work:x work/:x` is rejected
- 2026-10-03: Commands that change the state directory hold one lock (`flock` on instead of being taken for a move between two vaults. A move within a
`lock` in the state directory; a mutex on the in-memory test filesystem), so named vault no longer makes that vault the current one, whether it
concurrent commands no longer lose versions or race on the current pointers. succeeds or fails.
Every file is written through `secret.WriteFileAtomic` (temporary file, sync, - 2026-10-03: Commands that change the state directory hold one lock
rename), so no file is ever half-written and `current`, `currentvault` and (`flock` on `lock` in the state directory; a mutex on the in-memory
`current-unlocker` never go missing. New versions, new secrets and cross-vault test filesystem), so concurrent commands no longer lose versions or
copies are built in a temporary directory and renamed into place, and removals race on the current pointers. Every file is written through
rename out of the way first, so a version or secret is never half-added and `secret.WriteFileAtomic` (temporary file, sync, rename), so no file
never half-removed. is ever half-written and `current`, `currentvault` and
- 2026-10-03: The checks run before changing a vault now stop with an error `current-unlocker` never go missing. New versions, new secrets and
naming the path and cause when they cannot read what they inspect, instead of cross-vault copies are built in a temporary directory and renamed
reading the failure as "nothing there": the duplicate check before into place, and removals rename out of the way first, so a version
`unlocker add pgp` (an unreadable `unlockers.d` or unlocker metadata file), or secret is never half-added and never half-removed.
the secret count that guards removing the last unlocker and removing a vault, - 2026-10-03: The checks run before changing a vault now stop with an
and the existing long-term key check before `vault import`. error naming the path and cause when they cannot read what they
- 2026-10-03: `version rm`, `version promote` and `get --version` accept a inspect, instead of reading the failure as "nothing there": the
version only if it is one of the versions `version list` lists for that duplicate check before `unlocker add pgp` (an unreadable
secret, compared as typed before any path is built (`secret.VersionExists`), `unlockers.d` or unlocker metadata file), the secret count that
and touch nothing otherwise. An empty `--version` is rejected instead of guards removing the last unlocker and removing a vault, and the
meaning the current version. Before, `secret version rm x ../../..` deleted existing long-term key check before `vault import`.
the whole vault, `secret version rm x ..` the secret, and `.` or `""` every - 2026-10-03: `version rm`, `version promote` and `get --version`
version. accept a version only if it is one of the versions `version list`
- 2026-10-03: Key material is wiped on every exit: `Entry()` returns the exit lists for that secret, compared as typed before any path is built
code after its deferred `memguard.Purge()` has run, and only `main` calls (`secret.VersionExists`), and touch nothing otherwise. An empty
`os.Exit`. SIGINT and SIGTERM go through memguard's handler, which wipes every `--version` is rejected instead of meaning the current version.
buffer before exiting; when the process is in the terminal's foreground Before, `secret version rm x ../../..` deleted the whole vault,
process group it first restores the terminal settings from startup, so an `secret version rm x ..` the secret, and `.` or `""` every version.
interrupted passphrase prompt no longer leaves echo off. - 2026-10-03: Key material is wiped on every exit: `Entry()` returns
- 2026-10-03: Every command that builds a path from a secret name checks the the exit code after its deferred `memguard.Purge()` has run, and only
name first with `vault.ValidateSecretName` and touches nothing when it is `main` calls `os.Exit`. SIGINT and SIGTERM go through memguard's
invalid: `rm`, `mv` (both names, within a vault and between vaults, before handler, which wipes every buffer before exiting; when the process is
switching the current vault), `import`, `version list`/`promote`/`rm`, in the terminal's foreground process group it first restores the
`encrypt` and `decrypt`. The error and `README.md` state the naming rule. terminal settings from startup, so an interrupted passphrase prompt no
Before, `secret rm ..` deleted the whole vault and `secret rm .` every secret longer leaves echo off.
in it. - 2026-10-03: Every command that builds a path from a secret name
- 2026-10-03: The keychain unlocker's age key passphrase stays in locked memory: checks the name first with `vault.ValidateSecretName` and touches
it is generated into a locked buffer, and the keychain JSON is written and nothing when it is invalid: `rm`, `mv` (both names, within a vault
read by `KeychainData` code in `internal/secret/keychaindata.go` (tested on and between vaults, before switching the current vault), `import`,
Linux) without `encoding/json` holding it; the JSON field names are unchanged. `version list`/`promote`/`rm`, `encrypt` and `decrypt`. The error
- 2026-10-02: A plain `docker build .` builds again: the size tests skip a case and `README.md` state the naming rule. Before, `secret rm ..`
that needs more locked memory than the process can lock, and run every case deleted the whole vault and `secret rm .` every secret in it.
under `script/cibuild`. The image stamps the `VERSION` build argument, else - 2026-10-03: The keychain unlocker's age key passphrase stays in
`git describe --tags --always`, into `Version`, and fails if `.git` is present locked memory: it is generated into a locked buffer, and the
but yields no version; `make build` stamps `git describe` too, not a fixed keychain JSON is written and read by `KeychainData` code in
`0.1.0`. `.dockerignore` keeps `.git/config` out; `script/docker` is the `internal/secret/keychaindata.go` (tested on Linux) without
`encoding/json` holding it; the JSON field names are unchanged.
- 2026-10-02: A plain `docker build .` builds again: the size tests
skip a case that needs more locked memory than the process can
lock, and run every case under `script/cibuild`. The image stamps the
`VERSION` build argument, else `git describe --tags --always`, into
`Version`, and fails if `.git` is present but yields no version;
`make build` stamps `git describe` too, not a fixed `0.1.0`.
`.dockerignore` keeps `.git/config` out; `script/docker` is the
canonical copy. canonical copy.
- 2026-08-07: Updated golangci-lint to v2.12.2 with the canonical - 2026-08-07: Updated golangci-lint to v2.12.2 with the canonical
`.golangci.yml` (all linters enabled minus the standard disable list, `lll` `.golangci.yml` (all linters enabled minus the standard disable
88, tests linted); bumped the `Dockerfile` lint-stage image to the tagged list, `lll` 88, tests linted); bumped the `Dockerfile` lint-stage
v2.12.2 Debian digest; fixed all ~1550 new findings across `internal/` and image to the tagged v2.12.2 Debian digest; fixed all ~1550 new
`pkg/` (line wrapping, `wsl_v5` blank lines, sentinel errors for `err113`, findings across `internal/` and `pkg/` (line wrapping, `wsl_v5`
`t.Parallel()` where safe, `_test` package conversions, complexity/`dupl` blank lines, sentinel errors for `err113`, `t.Parallel()` where
helper extraction) on branch `golangci-v2.12.2`. Reworked after review: the safe, `_test` package conversions, complexity/`dupl` helper
`err113` sentinels in `internal/vault`, `internal/secret`, `internal/cli` and extraction) on branch `golangci-v2.12.2`. Reworked after review:
`pkg/bip85` were reshaped so every composed error message is byte-identical to the `err113` sentinels in `internal/vault`, `internal/secret`,
`main`, and `findUnlockerIDByMetadata` now returns an error so `unlocker list` `internal/cli` and `pkg/bip85` were reshaped so every composed
skips an unreadable `unlockers.d` entry with a warning instead of emitting a error message is byte-identical to `main`, and
fabricated fallback ID. `findUnlockerIDByMetadata` now returns an error so `unlocker list`
skips an unreadable `unlockers.d` entry with a warning instead of
emitting a fabricated fallback ID.
- 2026-08-07: Added `.editorconfig` - 2026-08-07: Added `.editorconfig`
(https://git.eeqj.de/sneak/secret/issues/27). (https://git.eeqj.de/sneak/secret/issues/27).
- 2026-07-07 Adopted scripts-to-rule-them-all: `script/` entrypoints, Makefile - 2026-07-07 Adopted scripts-to-rule-them-all: `script/` entrypoints,
shims, README Entrypoints section Makefile shims, README Entrypoints section
- 2026-07-07: Added `REPO_POLICIES.md` and the `make hooks` target; - 2026-07-07: Added `REPO_POLICIES.md` and the `make hooks` target;
`.gitea/workflows/check.yml` now runs `script/cibuild`. `.gitea/workflows/check.yml` now runs `script/cibuild`.
- 2026-03-30: Added the `make fmt-check` target and - 2026-03-30: Added the `make fmt-check` target and
`.gitea/workflows/check.yml`, which runs `docker build` on every push; the `.gitea/workflows/check.yml`, which runs `docker build` on every push; the
`Dockerfile` base images are pinned by sha256. `Dockerfile` base images are pinned by sha256.
- 2026-03-11: Secure Enclave unlocker for hardware-backed secret protection, - 2026-03-11: Secure Enclave unlocker for hardware-backed secret
plus review fixes (stub panics, derivation index, tests, README) on branch protection, plus review fixes (stub panics, derivation index, tests,
secure-enclave-unlocker. README) on branch secure-enclave-unlocker.
- 2026-02-28: Repo cleanup, removed stale .cursorrules and coverage.out. - 2026-02-28: Repo cleanup, removed stale .cursorrules and coverage.out.
- Audit fix wave (issues #1, #2, #3, #13, #14): skip unlockers with missing - Audit fix wave (issues #1, #2, #3, #13, #14): skip unlockers with
metadata, allow uppercase secret names, fix hardcoded derivation index, missing metadata, allow uppercase secret names, fix hardcoded
validate names in GetSecretVersion against path traversal, return errors derivation index, validate names in GetSecretVersion against path
instead of panicking, add Warn() on silent anomalies. traversal, return errors instead of panicking, add Warn() on silent
- Memory security hardening: LockedBuffer used through encrypt/decrypt paths anomalies.
(Save/EncryptWithPassphrase/GetValue/gpg helpers), deprecated bare-[]byte APIs - Memory security hardening: LockedBuffer used through encrypt/decrypt
removed. paths (Save/EncryptWithPassphrase/GetValue/gpg helpers), deprecated
- Per-secret keypair architecture, vault package refactor, versioning with bare-[]byte APIs removed.
--version, comprehensive test suite with in-memory filesystem. - Per-secret keypair architecture, vault package refactor, versioning
with --version, comprehensive test suite with in-memory filesystem.
- Debug logging system (slog, GODEBUG flag, TTY-aware output). - Debug logging system (slog, GODEBUG flag, TTY-aware output).
- Renamed SEP unlocker to Keychain, reorganized import commands. - Renamed SEP unlocker to Keychain, reorganized import commands.
- 2025-05-28: Initial implementation (vault, age encryption, mnemonic, CLI). - 2025-05-28: Initial implementation (vault, age encryption, mnemonic,
CLI).
# Future Steps # Future Steps
- Implement version-number shell completion for the second arg of - Implement version-number shell completion for the second arg of
`secret version promote` and `secret version rm` (`internal/cli/version.go`; `secret version promote` and `secret version rm`
was an in-code TODO removed for godox). (`internal/cli/version.go`; was an in-code TODO removed for godox).
- Cover mnemonic-vs-xprv identity consistency in `pkg/agehd/agehd_test.go` - Cover mnemonic-vs-xprv identity consistency in
`TestMnemonicVsXPRVConsistency` (was an in-code FIXME removed for godox). `pkg/agehd/agehd_test.go` `TestMnemonicVsXPRVConsistency` (was an
- CI does not compile, lint or test the files built only with cgo on macOS, in-code FIXME removed for godox).
since compiling them needs Apple's SDK: - CI does not compile, lint or test the files built only with cgo on
macOS, since compiling them needs Apple's SDK:
`internal/secret/keychainunlocker_cgo.go` (the three functions that call `internal/secret/keychainunlocker_cgo.go` (the three functions that call
`go-keychain`) with `keychainunlocker_test.go`, and `internal/macse` `go-keychain`) with `keychainunlocker_test.go`, and `internal/macse`
(`macse_darwin.go`, `macse_test.go`, the Objective-C sources). Lint has never (`macse_darwin.go`, `macse_test.go`, the Objective-C sources). Lint has
run on them, so it would likely find more there than the line lengths. No never run on them, so it would likely find more there than the line
macOS test runs in CI. A macOS runner would cover all of it (asked on lengths. No macOS test runs in CI. A macOS runner would cover all of it
https://git.eeqj.de/sneak/secret/issues/50). (asked on https://git.eeqj.de/sneak/secret/issues/50).
- 1.0 critical security blockers (from repo TODO.md): - 1.0 critical security blockers (from repo TODO.md):
- Memory security: age writes an identity's private key out as a string in - Memory security: age writes an identity's private key out as a string in
ordinary memory, and the copies it makes on the way stay there ordinary memory, and the copies it makes on the way stay there
@@ -534,8 +455,8 @@ https://git.eeqj.de/sneak/secret/milestone/12
- Medium priority: - Medium priority:
- Standardize error messages; stop leaking internals. - Standardize error messages; stop leaking internals.
- Split oversized CLI functions. - Split oversized CLI functions.
- Cleanups: read statedir from environment or default instead of passing it - Cleanups: read statedir from environment or default instead of
around. passing it around.
- Enhancements: help examples, colored output, --quiet flag, name suggestions on - Enhancements: help examples, colored output, --quiet flag, name suggestions on
miss, audit logging, hardware integration tests (Keychain, GPG), naming miss, audit logging, hardware integration tests (Keychain, GPG), naming
consistency, vault export/import, batch operations, search, secret metadata consistency, vault export/import, batch operations, search, secret metadata
+1 -1
View File
@@ -4,7 +4,7 @@ package main
import ( import (
"os" "os"
"sneak.berlin/go/secret/internal/cli" "git.eeqj.de/sneak/secret/internal/cli"
) )
func main() { func main() {
+4 -4
View File
@@ -1,4 +1,4 @@
module sneak.berlin/go/secret module git.eeqj.de/sneak/secret
go 1.24.1 go 1.24.1
@@ -9,9 +9,7 @@ require (
github.com/btcsuite/btcd/btcec/v2 v2.1.3 github.com/btcsuite/btcd/btcec/v2 v2.1.3
github.com/btcsuite/btcd/btcutil v1.1.6 github.com/btcsuite/btcd/btcutil v1.1.6
github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d
github.com/creack/pty v1.1.25-0.20260601142114-9246436fffe8 // v1.1.24's Open can return another pty's terminal github.com/creack/pty v1.1.24
github.com/dustin/go-humanize v1.0.1
github.com/fatih/color v1.18.0
github.com/keybase/go-keychain v0.0.0-20230307172405-3e4884637dd1 github.com/keybase/go-keychain v0.0.0-20230307172405-3e4884637dd1
github.com/oklog/ulid/v2 v2.1.1 github.com/oklog/ulid/v2 v2.1.1
github.com/spf13/afero v1.14.0 github.com/spf13/afero v1.14.0
@@ -28,6 +26,8 @@ require (
github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect github.com/btcsuite/btcd/chaincfg/chainhash v1.1.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fatih/color v1.18.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
+2 -2
View File
@@ -35,8 +35,8 @@ github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg
github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY=
github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.25-0.20260601142114-9246436fffe8 h1:CY3gjC7naqYGLMiywvj3suPfa1i0p/QEr7o8ujxL/2M= github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.25-0.20260601142114-9246436fffe8/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+1 -1
View File
@@ -6,10 +6,10 @@ import (
"io" "io"
"os" "os"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sneak.berlin/go/secret/internal/secret"
) )
// Instance encapsulates all CLI functionality and state // Instance encapsulates all CLI functionality and state
+2 -2
View File
@@ -5,9 +5,9 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/cli"
"sneak.berlin/go/secret/internal/secret"
) )
func TestCLIInstanceStateDir(t *testing.T) { func TestCLIInstanceStateDir(t *testing.T) {
+1 -1
View File
@@ -5,9 +5,9 @@ import (
"slices" "slices"
"strings" "strings"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sneak.berlin/go/secret/internal/vault"
) )
// getSecretNamesCompletionFunc returns a completion function that provides // getSecretNamesCompletionFunc returns a completion function that provides
+1 -1
View File
@@ -8,9 +8,9 @@ import (
"os" "os"
"strings" "strings"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/term" "golang.org/x/term"
"sneak.berlin/go/secret/internal/vault"
) )
// Sentinel errors for asking the user to confirm a removal // Sentinel errors for asking the user to confirm a removal
+4 -4
View File
@@ -24,12 +24,12 @@ import (
"testing" "testing"
"time" "time"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
const ( const (
@@ -353,9 +353,9 @@ func TestRemovalWithoutTerminalFailsAtOnce(t *testing.T) {
// for its answer, another command can take the state directory lock and // for its answer, another command can take the state directory lock and
// change the secret, and that the removal then removes nothing, since the // change the secret, and that the removal then removes nothing, since the
// secret is no longer what the question named. // secret is no longer what the question named.
//
//nolint:paralleltest // times commands against the in-memory lock all tests share
func TestRemovalAsksWithoutHoldingLock(t *testing.T) { func TestRemovalAsksWithoutHoldingLock(t *testing.T) {
t.Parallel()
r := newRemoval(t, "rm") r := newRemoval(t, "rm")
answers, answerWriter := io.Pipe() answers, answerWriter := io.Pipe()
+3 -35
View File
@@ -5,18 +5,17 @@ import (
"io" "io"
"maps" "maps"
"os" "os"
"os/exec"
"slices" "slices"
"strings" "strings"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/cli"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
// TestCreateExistingVaultChangesNothing is a regression test for // TestCreateExistingVaultChangesNothing is a regression test for
@@ -195,37 +194,6 @@ func TestStopAtPassphrasePromptLeavesNothing(t *testing.T) {
} }
} }
// TestMnemonicNotReadNamesOnlyMnemonic is a regression test for
// https://git.eeqj.de/sneak/secret/issues/115: `secret init` without
// SB_SECRET_MNEMONIC and with a stdin that is not a terminal said "failed to
// read mnemonic: failed to read passphrase: ...". The error must wrap
// secret.ErrMnemonicNotRead and name the mnemonic only. The message is
// pinned on the built binary, whose stdin is surely not a terminal.
func TestMnemonicNotReadNamesOnlyMnemonic(t *testing.T) {
t.Parallel()
c := cli.NewCLIInstanceWithStateDir(afero.NewMemMapFs(), testStateDir)
require.ErrorIs(t, c.Init(discardCmd()), secret.ErrMnemonicNotRead)
stateDir := t.TempDir()
//nolint:gosec // G204: test executes the freshly built secret binary
cmd := exec.CommandContext(t.Context(), secretBinaryPath(t), "init")
cmd.Env = []string{
secret.EnvStateDir + "=" + stateDir,
"PATH=" + os.Getenv("PATH"),
"HOME=" + os.Getenv("HOME"),
}
output, err := cmd.CombinedOutput()
require.Error(t, err)
require.Equal(t, "Initialized secrets manager at: "+stateDir+"\n"+
"Error: failed to read mnemonic: stdin is not a terminal (piped input "+
"or script). Please set the SB_SECRET_MNEMONIC environment variable "+
"or run interactively\n", string(output))
}
// TestStopDuringCreateLeavesWholeVaultOrNone is a regression test for // TestStopDuringCreateLeavesWholeVaultOrNone is a regression test for
// https://git.eeqj.de/sneak/secret/issues/105: `secret init` or `secret vault // https://git.eeqj.de/sneak/secret/issues/105: `secret init` or `secret vault
// create` killed after the passphrase prompt but before the unlocker was // create` killed after the passphrase prompt but before the unlocker was
+2 -2
View File
@@ -7,10 +7,10 @@ import (
"os" "os"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
// Sentinel errors for encrypt/decrypt operations // Sentinel errors for encrypt/decrypt operations
+4 -3
View File
@@ -8,12 +8,13 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
"time"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/cli"
"sneak.berlin/go/secret/internal/secret"
) )
// Entry must return its exit code rather than exit, so that its deferred // Entry must return its exit code rather than exit, so that its deferred
@@ -51,7 +52,7 @@ func TestInterruptExitsThroughMemguard(t *testing.T) {
const waitingForValue = "Reading secret value from stdin" const waitingForValue = "Reading secret value from stdin"
ctx, cancel := context.WithTimeout(t.Context(), commandWait) ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
defer cancel() defer cancel()
wd, err := filepath.Abs("../..") wd, err := filepath.Abs("../..")
+2 -2
View File
@@ -3,9 +3,9 @@ package cli_test
import ( import (
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sneak.berlin/go/secret/internal/cli"
"sneak.berlin/go/secret/internal/vault"
) )
// TestMissingSecretOrVaultErrors checks that a command that finds no such // TestMissingSecretOrVaultErrors checks that a command that finds no such
+8 -5
View File
@@ -7,10 +7,10 @@ import (
"math/big" "math/big"
"os" "os"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/tyler-smith/go-bip39" "github.com/tyler-smith/go-bip39"
"sneak.berlin/go/secret/internal/vault"
) )
const ( const (
@@ -21,6 +21,10 @@ const (
// Sentinel errors for secret generation // Sentinel errors for secret generation
var ( var (
errLengthTooSmall = errors.New("length must be at least 1") errLengthTooSmall = errors.New("length must be at least 1")
errLengthNotPositive = errors.New("length must be positive")
errMnemonicTypeNotSupported = errors.New(
"mnemonic type not supported for secret generation, " +
"use 'secret generate mnemonic' instead")
errUnsupportedSecretType = errors.New("unsupported type") errUnsupportedSecretType = errors.New("unsupported type")
) )
@@ -144,8 +148,7 @@ func (cli *Instance) GenerateSecret(
case "alnum": case "alnum":
secretValue, err = generateRandomAlnum(length) secretValue, err = generateRandomAlnum(length)
case "mnemonic": case "mnemonic":
return fmt.Errorf("%w: mnemonic (use 'secret generate mnemonic' instead)", return errMnemonicTypeNotSupported
errUnsupportedSecretType)
default: default:
return fmt.Errorf("%w: %s (supported: base58, alnum)", return fmt.Errorf("%w: %s (supported: base58, alnum)",
errUnsupportedSecretType, secretType) errUnsupportedSecretType, secretType)
@@ -201,8 +204,8 @@ func generateRandomAlnum(length int) (string, error) {
// generateRandomString generates a random string of the specified length // generateRandomString generates a random string of the specified length
// using the given character set // using the given character set
func generateRandomString(length int, charset string) (string, error) { func generateRandomString(length int, charset string) (string, error) {
if length < 1 { if length <= 0 {
return "", errLengthTooSmall return "", errLengthNotPositive
} }
result := make([]byte, length) result := make([]byte, length)
+1 -1
View File
@@ -10,11 +10,11 @@ import (
"strings" "strings"
"time" "time"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/dustin/go-humanize" "github.com/dustin/go-humanize"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sneak.berlin/go/secret/internal/vault"
) )
// Version info - these are set at build time // Version info - these are set at build time
+1 -1
View File
@@ -4,8 +4,8 @@ import (
"path/filepath" "path/filepath"
"time" "time"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/secret"
) )
// vaultStats accumulates statistics while walking vault directories // vaultStats accumulates statistics while walking vault directories
+4 -4
View File
@@ -8,11 +8,11 @@ import (
"os" "os"
"strings" "strings"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/tyler-smith/go-bip39" "github.com/tyler-smith/go-bip39"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
// errPassphraseMismatch is returned when passphrase confirmation fails // errPassphraseMismatch is returned when passphrase confirmation fails
@@ -55,11 +55,11 @@ func (cli *Instance) promptMnemonic() (*memguard.LockedBuffer, func(), error) {
secret.Debug("Prompting user for mnemonic phrase") secret.Debug("Prompting user for mnemonic phrase")
// Read mnemonic securely without echo // Read mnemonic securely without echo
mnemonicBuffer, err := secret.ReadMnemonic("Enter your BIP39 mnemonic phrase: ") mnemonicBuffer, err := secret.ReadPassphrase("Enter your BIP39 mnemonic phrase: ")
if err != nil { if err != nil {
secret.Debug("Failed to read mnemonic from stdin", "error", err) secret.Debug("Failed to read mnemonic from stdin", "error", err)
return nil, nil, err return nil, nil, fmt.Errorf("failed to read mnemonic: %w", err)
} }
fmt.Fprintln(os.Stderr) // Add newline after hidden input fmt.Fprintln(os.Stderr) // Add newline after hidden input
-67
View File
@@ -1,67 +0,0 @@
//nolint:testpackage // white-box test of unexported internals
package cli
import (
"testing"
"github.com/awnumar/memguard"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/vault"
)
// TestInvalidMnemonicError checks that every command that takes a mnemonic
// returns errInvalidMnemonicPhrase for one that is not valid BIP39. The vault
// "other" has no long-term key, as vault import needs.
func TestInvalidMnemonicError(t *testing.T) {
t.Parallel()
tests := []struct {
command string
run func(c *Instance) error
}{
{"secret init", func(c *Instance) error { return c.Init(c.cmd) }},
{"secret vault create work", func(c *Instance) error {
return c.CreateVault(c.cmd, "work")
}},
{"secret vault import other", func(c *Instance) error {
return c.VaultImport(c.cmd, "other")
}},
}
for _, tt := range tests {
t.Run(tt.command, func(t *testing.T) {
t.Parallel()
fs := afero.NewMemMapFs()
_, err := vault.CreateVault(fs, listTestStateDir, "other", nil, nil)
require.NoError(t, err)
instance, _ := newTestInstance(fs)
instance.Mnemonic = memguard.NewBufferFromBytes([]byte("not a mnemonic"))
t.Cleanup(instance.Mnemonic.Destroy)
require.ErrorIs(t, tt.run(instance), errInvalidMnemonicPhrase)
})
}
}
// TestGenerateSecretErrors checks that `secret generate secret` gives one
// error for a length below 1 and one for a type it cannot generate.
func TestGenerateSecretErrors(t *testing.T) {
t.Parallel()
instance, cmd := newTestInstance(afero.NewMemMapFs())
err := instance.GenerateSecret(cmd, "x", 0, "base58", false)
require.ErrorIs(t, err, errLengthTooSmall)
_, err = generateRandomString(0, "ab")
require.ErrorIs(t, err, errLengthTooSmall)
err = instance.GenerateSecret(cmd, "x", defaultSecretLength, "mnemonic", false)
require.ErrorIs(t, err, errUnsupportedSecretType)
err = instance.GenerateSecret(cmd, "x", defaultSecretLength, "hex", false)
require.ErrorIs(t, err, errUnsupportedSecretType)
}
+12 -42
View File
@@ -17,27 +17,21 @@ import (
"testing" "testing"
"time" "time"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/creack/pty" "github.com/creack/pty"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/cli"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
"sneak.berlin/go/secret/pkg/agehd"
) )
const ( const (
// testMnemonic is a standard BIP39 mnemonic used for testing // testMnemonic is a standard BIP39 mnemonic used for testing
//nolint:dupword // BIP39 test mnemonic intentionally repeats a word //nolint:dupword // BIP39 test mnemonic intentionally repeats a word
testMnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about" testMnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
// commandWait is how long a test lets the secret binary run before it
// kills it and fails. It stays well under the 30 seconds script/test
// gives the whole package, so a command that hangs fails the test with
// the test's own message instead of Go's timeout panic.
commandWait = 10 * time.Second
) )
// errEmptyValue indicates a concurrent reader received an empty secret value. // errEmptyValue indicates a concurrent reader received an empty secret value.
@@ -58,12 +52,8 @@ func runSecretWithStdin(stdin string, env map[string]string, args ...string) (st
return cli.ExecuteCommandInProcess(args, stdin, env) return cli.ExecuteCommandInProcess(args, stdin, env)
} }
// TestMain runs before all tests and ensures the binary is built. It also // TestMain runs before all tests and ensures the binary is built
// makes passphrase encryption in the tests cheap (see
// secret.ScryptWorkFactor); the binary keeps age's work factor.
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
secret.ScryptWorkFactor = 1
// Get the current working directory // Get the current working directory
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { if err != nil {
@@ -2589,7 +2579,7 @@ func TestRemoveWithoutTerminalFailsAtOnce(t *testing.T) {
_ = stdin.Close() _ = stdin.Close()
}() }()
ctx, cancel := context.WithTimeout(t.Context(), commandWait) ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
defer cancel() defer cancel()
cmd, secretDir := secretRmCommand(ctx, t) cmd, secretDir := secretRmCommand(ctx, t)
@@ -2607,13 +2597,7 @@ func TestRemoveWithoutTerminalFailsAtOnce(t *testing.T) {
// and stderr, not both: whether it asks must depend on stdin alone, where // and stderr, not both: whether it asks must depend on stdin alone, where
// the answer is read from. pty.Open returns the two ends of a new terminal: // the answer is read from. pty.Open returns the two ends of a new terminal:
// tty is the end a program uses as its terminal, and ptmx the end the test // tty is the end a program uses as its terminal, and ptmx the end the test
// reads what the terminal shows from and types into. Reading ptmx stops at // reads what the terminal shows from and types into.
// the context's deadline, commandWait (10 seconds) after the test starts,
// when secret rm is killed too, so a terminal that stays open fails the test
// then with its own message instead of hanging it. The deadline works only
// while ptmx stays non-blocking, as pty.Open of the github.com/creack/pty
// commit in go.mod leaves it: calling ptmx.Fd() or going back to v1.1.24
// makes the read ignore the deadline, without any error.
// TestRemoveIgnoresTerminalOnStdout runs `echo y | secret rm x` at a // TestRemoveIgnoresTerminalOnStdout runs `echo y | secret rm x` at a
// terminal. stdin is a pipe, so nobody can answer there, and the command // terminal. stdin is a pipe, so nobody can answer there, and the command
@@ -2621,7 +2605,7 @@ func TestRemoveWithoutTerminalFailsAtOnce(t *testing.T) {
func TestRemoveIgnoresTerminalOnStdout(t *testing.T) { func TestRemoveIgnoresTerminalOnStdout(t *testing.T) {
t.Parallel() t.Parallel()
ctx, cancel := context.WithTimeout(t.Context(), commandWait) ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
defer cancel() defer cancel()
cmd, secretDir := secretRmCommand(ctx, t) cmd, secretDir := secretRmCommand(ctx, t)
@@ -2631,9 +2615,6 @@ func TestRemoveIgnoresTerminalOnStdout(t *testing.T) {
defer func() { _ = ptmx.Close() }() defer func() { _ = ptmx.Close() }()
deadline, _ := ctx.Deadline()
require.NoError(t, ptmx.SetReadDeadline(deadline))
cmd.Stdin = strings.NewReader("y\n") cmd.Stdin = strings.NewReader("y\n")
cmd.Stdout = tty cmd.Stdout = tty
cmd.Stderr = tty cmd.Stderr = tty
@@ -2643,16 +2624,9 @@ func TestRemoveIgnoresTerminalOnStdout(t *testing.T) {
_ = tty.Close() _ = tty.Close()
// The read ends once secret rm has exited and so closed the terminal. // The read ends once secret rm has exited and so closed the terminal.
shown, err := io.ReadAll(ptmx) shown, _ := io.ReadAll(ptmx)
require.NotErrorIs(t, err, os.ErrDeadlineExceeded,
"the terminal was still open %s after secret rm started: %s",
commandWait, shown)
err = cmd.Wait() require.Error(t, cmd.Wait())
require.NoError(t, ctx.Err(), "secret rm did not exit within %s",
commandWait)
require.Error(t, err)
assert.Contains(t, string(shown), "pass --force") assert.Contains(t, string(shown), "pass --force")
assert.DirExists(t, secretDir) assert.DirExists(t, secretDir)
} }
@@ -2662,7 +2636,7 @@ func TestRemoveIgnoresTerminalOnStdout(t *testing.T) {
func TestRemoveAsksAtTerminalOnStdin(t *testing.T) { func TestRemoveAsksAtTerminalOnStdin(t *testing.T) {
t.Parallel() t.Parallel()
ctx, cancel := context.WithTimeout(t.Context(), commandWait) ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
defer cancel() defer cancel()
cmd, secretDir := secretRmCommand(ctx, t) cmd, secretDir := secretRmCommand(ctx, t)
@@ -2672,9 +2646,6 @@ func TestRemoveAsksAtTerminalOnStdin(t *testing.T) {
defer func() { _ = ptmx.Close() }() defer func() { _ = ptmx.Close() }()
deadline, _ := ctx.Deadline()
require.NoError(t, ptmx.SetReadDeadline(deadline))
cmd.Stdin = tty cmd.Stdin = tty
// Not a file, so exec.Cmd connects stdout through a pipe. // Not a file, so exec.Cmd connects stdout through a pipe.
cmd.Stdout = io.Discard cmd.Stdout = io.Discard
@@ -2692,8 +2663,7 @@ func TestRemoveAsksAtTerminalOnStdin(t *testing.T) {
terminal := bufio.NewReader(ptmx) terminal := bufio.NewReader(ptmx)
for !bytes.HasSuffix(shown, []byte("[y/N] ")) { for !bytes.HasSuffix(shown, []byte("[y/N] ")) {
char, err = terminal.ReadByte() char, err = terminal.ReadByte()
require.NoError(t, err, "secret rm did not ask on the terminal: %s", require.NoError(t, err, "secret rm ended without asking: %s", shown)
shown)
shown = append(shown, char) shown = append(shown, char)
} }
+3 -3
View File
@@ -4,12 +4,12 @@ import (
"io" "io"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/cli"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
// TestLeftoversRemovedByNextChangingCommand is a regression test for // TestLeftoversRemovedByNextChangingCommand is a regression test for
+6 -8
View File
@@ -13,13 +13,13 @@ import (
"testing" "testing"
"time" "time"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
const ( const (
@@ -94,9 +94,9 @@ func numbered(prefix string, count int) []string {
// lock, adds of a new secret all find it absent and replace each other, and // lock, adds of a new secret all find it absent and replace each other, and
// forced adds read the same highest version number and overwrite each // forced adds read the same highest version number and overwrite each
// other's version. With it they behave as if run one after another. // other's version. With it they behave as if run one after another.
//
//nolint:paralleltest // times commands against the in-memory lock all tests share
func TestConcurrentAddsKeepEveryVersion(t *testing.T) { func TestConcurrentAddsKeepEveryVersion(t *testing.T) {
t.Parallel()
mnemonic := testMnemonicBuffer(t) mnemonic := testMnemonicBuffer(t)
const adds = 8 const adds = 8
@@ -110,8 +110,6 @@ func TestConcurrentAddsKeepEveryVersion(t *testing.T) {
{"real", afero.NewOsFs(), t.TempDir()}, {"real", afero.NewOsFs(), t.TempDir()},
} { } {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
t.Parallel()
_, err := vault.CreateVault(tc.fs, tc.stateDir, "default", mnemonic, nil) _, err := vault.CreateVault(tc.fs, tc.stateDir, "default", mnemonic, nil)
require.NoError(t, err) require.NoError(t, err)
@@ -237,9 +235,9 @@ func TestEncryptPipedIntoAdd(t *testing.T) {
// TestFailedCommandReleasesLock checks that a command failing after it // TestFailedCommandReleasesLock checks that a command failing after it
// took the state directory lock leaves the lock free for the next command. // took the state directory lock leaves the lock free for the next command.
//
//nolint:paralleltest // times commands against the in-memory lock all tests share
func TestFailedCommandReleasesLock(t *testing.T) { func TestFailedCommandReleasesLock(t *testing.T) {
t.Parallel()
fs := afero.NewMemMapFs() fs := afero.NewMemMapFs()
cli := NewCLIInstanceWithStateDir(fs, testStateDir) cli := NewCLIInstanceWithStateDir(fs, testStateDir)
+2 -2
View File
@@ -5,12 +5,12 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/cli"
"sneak.berlin/go/secret/internal/vault"
) )
// TestRejectedMoveWithinVaultLeavesStateUnchanged is a regression test for // TestRejectedMoveWithinVaultLeavesStateUnchanged is a regression test for
+3 -3
View File
@@ -9,13 +9,13 @@ import (
"sync" "sync"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/cli"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
const ( const (
+1 -1
View File
@@ -3,11 +3,11 @@ package cli
import ( import (
"os" "os"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
"golang.org/x/term" "golang.org/x/term"
"sneak.berlin/go/secret/internal/secret"
) )
// Entry runs the secret CLI and returns the process exit code. It wipes // Entry runs the secret CLI and returns the process exit code. It wipes
+8 -2
View File
@@ -11,11 +11,11 @@ import (
"slices" "slices"
"strings" "strings"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
const ( const (
@@ -33,6 +33,8 @@ const (
// Sentinel errors for secret operations // Sentinel errors for secret operations
var ( var (
errSecretTooLarge = errors.New("secret too large: exceeds 100MB limit") errSecretTooLarge = errors.New("secret too large: exceeds 100MB limit")
errSecretFileTooLarge = errors.New(
"secret file too large: exceeds 100MB limit")
errCrossVaultSourceUnqualified = errors.New( errCrossVaultSourceUnqualified = errors.New(
"source must specify vault (e.g., vault:secret) for cross-vault move") "source must specify vault (e.g., vault:secret) for cross-vault move")
errMoveOntoItself = errors.New("cannot be moved onto itself") errMoveOntoItself = errors.New("cannot be moved onto itself")
@@ -667,6 +669,10 @@ func (cli *Instance) ImportSecret(
buffers, totalSize, err := readSecretFromReader(file) buffers, totalSize, err := readSecretFromReader(file)
if err != nil { if err != nil {
if errors.Is(err, errSecretTooLarge) {
return errSecretFileTooLarge
}
return fmt.Errorf("failed to read secret from file %s: %w", sourceFile, err) return fmt.Errorf("failed to read secret from file %s: %w", sourceFile, err)
} }
defer destroyBuffers(buffers) defer destroyBuffers(buffers)
+106 -11
View File
@@ -10,17 +10,57 @@ import (
"strings" "strings"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/vault"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/vault" "golang.org/x/sys/unix"
"sneak.berlin/go/secret/pkg/agehd"
) )
// testVaultName is the vault name used by the size tests. // testVaultName is the vault name used by the size tests.
const testVaultName = "test-vault" const testVaultName = "test-vault"
// lockedBytesPerSecretByte bounds the locked memory that storing a secret
// holds at once: the buffers it is read into reach up to 1.5 times its
// size, and they are then copied into one more buffer of its size.
const lockedBytesPerSecretByte = 3
// skipIfLockedMemoryTooLow skips the test when this process cannot lock
// the memory a secret of size bytes needs, found by locking a buffer of
// that size and releasing it. memguard panics, ending the whole test run,
// when it cannot lock a buffer, and a plain `docker build .` runs the
// tests under an 8 MiB locked-memory limit (RLIMIT_MEMLOCK). A process
// allowed to lock past that limit runs every case.
func skipIfLockedMemoryTooLow(t *testing.T, size int) {
t.Helper()
need := lockedBytesPerSecretByte * size
buf, err := unix.Mmap(-1, 0, need,
unix.PROT_READ|unix.PROT_WRITE, unix.MAP_PRIVATE|unix.MAP_ANON)
require.NoError(t, err)
lockErr := unix.Mlock(buf)
// Unmapping the buffer also unlocks it.
err = unix.Munmap(buf)
require.NoError(t, err)
if lockErr != nil {
var limit unix.Rlimit
err = unix.Getrlimit(unix.RLIMIT_MEMLOCK, &limit)
require.NoError(t, err)
t.Skipf("a %d-byte secret needs up to %d bytes of locked memory, "+
"which could not be locked under the locked-memory limit "+
"(RLIMIT_MEMLOCK) of %d bytes: %v",
size, need, limit.Cur, lockErr)
}
}
// newSizeTestVault creates an in-memory vault unlocked with the test // newSizeTestVault creates an in-memory vault unlocked with the test
// mnemonic and returns the filesystem and vault. // mnemonic and returns the filesystem and vault.
// //
@@ -53,9 +93,10 @@ func newSizeTestVault(t *testing.T) (afero.Fs, *vault.Vault) {
} }
// runAddSecretSizeCase adds a secret of the given size through stdin and // runAddSecretSizeCase adds a secret of the given size through stdin and
// verifies that it is stored. // verifies the outcome: wantErr, or the secret stored when wantErr is nil.
func runAddSecretSizeCase(t *testing.T, size int) { func runAddSecretSizeCase(t *testing.T, size int, wantErr error) {
t.Helper() t.Helper()
skipIfLockedMemoryTooLow(t, size)
fs, vlt := newSizeTestVault(t) fs, vlt := newSizeTestVault(t)
@@ -86,6 +127,13 @@ func runAddSecretSizeCase(t *testing.T, size int) {
// Test adding the secret // Test adding the secret
secretName := fmt.Sprintf("test-secret-%d", size) secretName := fmt.Sprintf("test-secret-%d", size)
err = cli.AddSecret(secretName, false) err = cli.AddSecret(secretName, false)
if wantErr != nil {
require.ErrorIs(t, err, wantErr)
return
}
require.NoError(t, err) require.NoError(t, err)
// Verify the secret was stored correctly // Verify the secret was stored correctly
@@ -99,9 +147,10 @@ func runAddSecretSizeCase(t *testing.T, size int) {
} }
// runImportSecretSizeCase imports a secret file of the given size and // runImportSecretSizeCase imports a secret file of the given size and
// verifies that it is stored. // verifies the outcome: wantErr, or the secret stored when wantErr is nil.
func runImportSecretSizeCase(t *testing.T, size int) { func runImportSecretSizeCase(t *testing.T, size int, wantErr error) {
t.Helper() t.Helper()
skipIfLockedMemoryTooLow(t, size)
fs, vlt := newSizeTestVault(t) fs, vlt := newSizeTestVault(t)
@@ -130,6 +179,13 @@ func runImportSecretSizeCase(t *testing.T, size int) {
// Test importing the secret // Test importing the secret
secretName := fmt.Sprintf("imported-secret-%d", size) secretName := fmt.Sprintf("imported-secret-%d", size)
err = cli.ImportSecret(cmd, secretName, testFile, false) err = cli.ImportSecret(cmd, secretName, testFile, false)
if wantErr != nil {
require.ErrorIs(t, err, wantErr)
return
}
require.NoError(t, err) require.NoError(t, err)
// Verify the secret was stored correctly // Verify the secret was stored correctly
@@ -144,11 +200,12 @@ func runImportSecretSizeCase(t *testing.T, size int) {
// TestAddSecretVariousSizes tests adding secrets of various sizes through stdin // TestAddSecretVariousSizes tests adding secrets of various sizes through stdin
// //
//nolint:paralleltest // in parallel, size tests could exceed the memlock limit //nolint:paralleltest // together the subtests lock more than the memlock limit
func TestAddSecretVariousSizes(t *testing.T) { func TestAddSecretVariousSizes(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
size int size int
wantErr error
}{ }{
{ {
name: "1KB secret", name: "1KB secret",
@@ -166,22 +223,40 @@ func TestAddSecretVariousSizes(t *testing.T) {
name: "1MB secret", name: "1MB secret",
size: 1024 * 1024, size: 1024 * 1024,
}, },
{
name: "10MB secret",
size: 10 * 1024 * 1024,
},
{
name: "99MB secret",
size: 99 * 1024 * 1024,
},
{
name: "100MB secret minus 1 byte",
size: 100*1024*1024 - 1,
},
{
name: "101MB secret - should fail",
size: 101 * 1024 * 1024,
wantErr: errSecretTooLarge,
},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
runAddSecretSizeCase(t, tt.size) runAddSecretSizeCase(t, tt.size, tt.wantErr)
}) })
} }
} }
// TestImportSecretVariousSizes tests importing secrets of various sizes from files // TestImportSecretVariousSizes tests importing secrets of various sizes from files
// //
//nolint:paralleltest // in parallel, size tests could exceed the memlock limit //nolint:paralleltest // together the subtests lock more than the memlock limit
func TestImportSecretVariousSizes(t *testing.T) { func TestImportSecretVariousSizes(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
size int size int
wantErr error
}{ }{
{ {
name: "1KB file", name: "1KB file",
@@ -199,18 +274,35 @@ func TestImportSecretVariousSizes(t *testing.T) {
name: "1MB file", name: "1MB file",
size: 1024 * 1024, size: 1024 * 1024,
}, },
{
name: "10MB file",
size: 10 * 1024 * 1024,
},
{
name: "99MB file",
size: 99 * 1024 * 1024,
},
{
name: "100MB file",
size: 100 * 1024 * 1024,
},
{
name: "101MB file - should fail",
size: 101 * 1024 * 1024,
wantErr: errSecretFileTooLarge,
},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
runImportSecretSizeCase(t, tt.size) runImportSecretSizeCase(t, tt.size, tt.wantErr)
}) })
} }
} }
// TestAddSecretBufferGrowth tests that our buffer growth strategy works correctly // TestAddSecretBufferGrowth tests that our buffer growth strategy works correctly
// //
//nolint:paralleltest // in parallel, size tests could exceed the memlock limit //nolint:paralleltest // together the subtests lock more than the memlock limit
func TestAddSecretBufferGrowth(t *testing.T) { func TestAddSecretBufferGrowth(t *testing.T) {
// Test various sizes that should trigger buffer growth // Test various sizes that should trigger buffer growth
sizes := []int{ sizes := []int{
@@ -229,10 +321,13 @@ func TestAddSecretBufferGrowth(t *testing.T) {
131072, // 128KB 131072, // 128KB
524288, // 512KB 524288, // 512KB
1048576, // 1MB 1048576, // 1MB
2097152, // 2MB
} }
for _, size := range sizes { for _, size := range sizes {
t.Run(fmt.Sprintf("size_%d", size), func(t *testing.T) { t.Run(fmt.Sprintf("size_%d", size), func(t *testing.T) {
skipIfLockedMemoryTooLow(t, size)
fs, vlt := newSizeTestVault(t) fs, vlt := newSizeTestVault(t)
// Create test data of exactly the specified size // Create test data of exactly the specified size
+5 -17
View File
@@ -7,20 +7,20 @@ import (
"strings" "strings"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
) )
// TestGetCommandOutputsToStdout tests that 'secret get' outputs the secret // TestGetCommandOutputsToStdout tests that 'secret get' outputs the secret
// value to stdout, not stderr // value to stdout, not stderr
func TestGetCommandOutputsToStdout(t *testing.T) { func TestGetCommandOutputsToStdout(t *testing.T) {
t.Parallel() // Create a temporary directory for our vault
// Create a temporary directory for our vault; each command is given it
// in its environment
tempDir := t.TempDir() tempDir := t.TempDir()
// Set environment variables for the test
t.Setenv(secret.EnvStateDir, tempDir)
// Find the secret binary path // Find the secret binary path
wd, err := filepath.Abs("../..") wd, err := filepath.Abs("../..")
require.NoError(t, err, "should get working directory") require.NoError(t, err, "should get working directory")
@@ -41,18 +41,6 @@ func TestGetCommandOutputsToStdout(t *testing.T) {
output, err := cmd.CombinedOutput() output, err := cmd.CombinedOutput()
require.NoError(t, err, "init should succeed: %s", string(output)) require.NoError(t, err, "init should succeed: %s", string(output))
// The binary, unlike these tests, encrypts the passphrase unlocker's key
// at age's scrypt work factor, 18. age writes the work factor last on the
// second line of priv.age: "-> scrypt <salt> <work factor>".
vaultDir := filepath.Join(tempDir, "vaults.d", "default")
unlockerName := readFile(t, filepath.Join(vaultDir, "current-unlocker"))
unlockerDir := filepath.Join(vaultDir, "unlockers.d", string(unlockerName))
privAge := readFile(t, filepath.Join(unlockerDir, "priv.age"))
header := strings.SplitN(string(privAge), "\n", 3)
require.Len(t, header, 3, "priv.age should start with an age header")
assert.Regexp(t, `^-> scrypt \S+ 18$`, header[1],
"the passphrase unlocker should be encrypted at scrypt work factor 18")
// Add a secret // Add a secret
//nolint:gosec // G204: test executes the freshly built secret binary //nolint:gosec // G204: test executes the freshly built secret binary
cmd = exec.CommandContext(t.Context(), secretPath, "add", "test/secret") cmd = exec.CommandContext(t.Context(), secretPath, "add", "test/secret")
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"os" "os"
"strings" "strings"
"sneak.berlin/go/secret/internal/secret" "git.eeqj.de/sneak/secret/internal/secret"
) )
// ExecuteCommandInProcess executes a CLI command in-process for testing // ExecuteCommandInProcess executes a CLI command in-process for testing
+1 -1
View File
@@ -3,9 +3,9 @@ package cli_test
import ( import (
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/cli"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/cli"
) )
//nolint:paralleltest // executes the CLI in-process against shared state //nolint:paralleltest // executes the CLI in-process against shared state
+6 -6
View File
@@ -19,14 +19,14 @@ import (
"testing" "testing"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/cli"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
const ( const (
@@ -260,9 +260,9 @@ func TestPassphraseNotReadNamesNoMnemonic(t *testing.T) {
assert.Equal(t, "Error: failed to unlock vault: "+ assert.Equal(t, "Error: failed to unlock vault: "+
"failed to get long-term key: failed to get unlocker identity: "+ "failed to get long-term key: failed to get unlocker identity: "+
"failed to read passphrase: stdin is not a terminal (piped input or "+ "failed to read passphrase: cannot read passphrase from non-terminal "+
"script). Please set the SB_UNLOCK_PASSPHRASE environment variable or "+ "stdin (piped input or script). Please set the SB_UNLOCK_PASSPHRASE "+
"run interactively\n", string(output)) "environment variable or run interactively\n", string(output))
} }
// TestCryptoUnlockFailureNamesMnemonic checks that `secret encrypt` and // TestCryptoUnlockFailureNamesMnemonic checks that `secret encrypt` and
+14 -2
View File
@@ -15,10 +15,10 @@ import (
"strings" "strings"
"time" "time"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
// Unlocker type names and platform identifiers shared across the CLI // Unlocker type names and platform identifiers shared across the CLI
@@ -39,6 +39,10 @@ var (
errInvalidUnlockerType = errors.New("invalid unlocker type") errInvalidUnlockerType = errors.New("invalid unlocker type")
errKeyIDOnlyForPGP = errors.New( errKeyIDOnlyForPGP = errors.New(
"--keyid flag is only valid for PGP unlockers") "--keyid flag is only valid for PGP unlockers")
errKeychainMacOSOnly = errors.New(
"keychain unlockers are only supported on macOS")
errSecureEnclaveMacOSOnly = errors.New(
"secure enclave unlockers are only supported on macOS")
// errGPGKeyAlreadyUnlocker carries only the message tail; the caller // errGPGKeyAlreadyUnlocker carries only the message tail; the caller
// composes "GPG key <id> is already added as an unlocker". // composes "GPG key <id> is already added as an unlocker".
errGPGKeyAlreadyUnlocker = errors.New( errGPGKeyAlreadyUnlocker = errors.New(
@@ -489,6 +493,10 @@ func (cli *Instance) addPassphraseUnlocker(cmd *cobra.Command) error {
// addKeychainUnlocker creates a macOS Keychain unlocker in the current vault // addKeychainUnlocker creates a macOS Keychain unlocker in the current vault
func (cli *Instance) addKeychainUnlocker(cmd *cobra.Command) error { func (cli *Instance) addKeychainUnlocker(cmd *cobra.Command) error {
if runtime.GOOS != platformDarwin {
return errKeychainMacOSOnly
}
keychainUnlocker, err := secret.CreateKeychainUnlocker( keychainUnlocker, err := secret.CreateKeychainUnlocker(
cli.fs, cli.stateDir, cli.Mnemonic, cli.UnlockPassphrase) cli.fs, cli.stateDir, cli.Mnemonic, cli.UnlockPassphrase)
if err != nil { if err != nil {
@@ -516,6 +524,10 @@ func (cli *Instance) addKeychainUnlocker(cmd *cobra.Command) error {
// addSecureEnclaveUnlocker creates a Secure Enclave unlocker in the // addSecureEnclaveUnlocker creates a Secure Enclave unlocker in the
// current vault // current vault
func (cli *Instance) addSecureEnclaveUnlocker(cmd *cobra.Command) error { func (cli *Instance) addSecureEnclaveUnlocker(cmd *cobra.Command) error {
if runtime.GOOS != platformDarwin {
return errSecureEnclaveMacOSOnly
}
seUnlocker, err := secret.CreateSecureEnclaveUnlocker( seUnlocker, err := secret.CreateSecureEnclaveUnlocker(
cli.fs, cli.stateDir, cli.Mnemonic, cli.UnlockPassphrase) cli.fs, cli.stateDir, cli.Mnemonic, cli.UnlockPassphrase)
if err != nil { if err != nil {
+2 -2
View File
@@ -5,12 +5,12 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
// unknownTestGPGUserID is a GPG user ID that no key in the test keyring has. // unknownTestGPGUserID is a GPG user ID that no key in the test keyring has.
+1 -1
View File
@@ -17,10 +17,10 @@ import (
"strings" "strings"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/vault"
) )
// newCorruptUnlockerVault returns the two-unlocker test vault with the // newCorruptUnlockerVault returns the two-unlocker test vault with the
+2 -2
View File
@@ -7,11 +7,11 @@ import (
"testing" "testing"
"time" "time"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
// TestSameMetadataUnlockersHaveTheirOwnIDs writes two passphrase unlockers // TestSameMetadataUnlockersHaveTheirOwnIDs writes two passphrase unlockers
+1 -1
View File
@@ -21,11 +21,11 @@ import (
"testing" "testing"
"time" "time"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
) )
const ( const (
+1 -1
View File
@@ -28,11 +28,11 @@ import (
"testing" "testing"
"time" "time"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
) )
const ( const (
+2 -2
View File
@@ -4,10 +4,10 @@ import (
"strings" "strings"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/cli"
"sneak.berlin/go/secret/internal/secret"
) )
// usageHeading starts the usage text cobra prints after an error. // usageHeading starts the usage text cobra prints after an error.
+5 -4
View File
@@ -10,19 +10,20 @@ import (
"strings" "strings"
"time" "time"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/tyler-smith/go-bip39" "github.com/tyler-smith/go-bip39"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
"sneak.berlin/go/secret/pkg/agehd"
) )
// Sentinel errors for vault operations // Sentinel errors for vault operations
var ( var (
errMnemonicEmpty = errors.New("mnemonic cannot be empty") errMnemonicEmpty = errors.New("mnemonic cannot be empty")
errInvalidMnemonicPhrase = errors.New("invalid BIP39 mnemonic phrase") errInvalidMnemonicPhrase = errors.New("invalid BIP39 mnemonic phrase")
errInvalidMnemonic = errors.New("invalid BIP39 mnemonic")
errVaultHasLongTermKey = errors.New( errVaultHasLongTermKey = errors.New(
"already has a long-term key configured") "already has a long-term key configured")
errMnemonicEnvNotSet = errors.New( errMnemonicEnvNotSet = errors.New(
@@ -380,7 +381,7 @@ func (cli *Instance) vaultImportPreflight(
secret.Debug("Validating BIP39 mnemonic", "word_count", len(mnemonicWords)) secret.Debug("Validating BIP39 mnemonic", "word_count", len(mnemonicWords))
if !bip39.IsMnemonicValid(mnemonic) { if !bip39.IsMnemonicValid(mnemonic) {
return "", "", "", errInvalidMnemonicPhrase return "", "", "", errInvalidMnemonic
} }
return vaultDir, pubKeyPath, mnemonic, nil return vaultDir, pubKeyPath, mnemonic, nil
+2 -2
View File
@@ -11,10 +11,10 @@ import (
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
const ( const (
+3 -3
View File
@@ -26,13 +26,13 @@ import (
"time" "time"
"unicode/utf8" "unicode/utf8"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
"sneak.berlin/go/secret/pkg/agehd"
) )
const ( const (
+3 -3
View File
@@ -8,13 +8,13 @@ import (
"testing" "testing"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/macse"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/macse"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
var errInjected = errors.New("injected failure") var errInjected = errors.New("injected failure")
+18 -52
View File
@@ -17,28 +17,16 @@ import (
var ( var (
errNilPassphraseBuffer = errors.New("passphrase buffer is nil") errNilPassphraseBuffer = errors.New("passphrase buffer is nil")
errStdinNotTerminal = errors.New( errStdinNotTerminal = errors.New(
"stdin is not a terminal (piped input or script)") "cannot read passphrase from non-terminal stdin " +
"(piped input or script). Please set the SB_UNLOCK_PASSPHRASE " +
"environment variable or run interactively")
errStderrNotTerminal = errors.New( errStderrNotTerminal = errors.New(
"stderr is not a terminal (running in non-interactive mode)") "cannot prompt for passphrase: stderr is not a terminal " +
errNothingEntered = errors.New("nothing was entered") "(running in non-interactive mode). Please set the " +
"SB_UNLOCK_PASSPHRASE environment variable")
errEmptyPassphrase = errors.New("passphrase cannot be empty") errEmptyPassphrase = errors.New("passphrase cannot be empty")
) )
// ErrMnemonicNotRead is wrapped in every error of ReadMnemonic: there is no
// terminal to read the mnemonic from, reading it failed, or it was empty.
var ErrMnemonicNotRead = errors.New("failed to read mnemonic")
// ScryptWorkFactor is, when not zero, the scrypt work factor that
// EncryptWithPassphrase uses instead of age's, 18: log2 of scrypt's cost
// parameter N. Deriving a key with age's takes about a second and 256 MiB, on
// purpose, since so does every guess at the passphrase. Only tests set it,
// lower, before any test runs, so that the passphrase unlockers they create
// cost nothing; the program leaves it zero. Decryption takes the work factor
// from the encrypted data, so it needs no setting.
//
//nolint:gochecknoglobals // set by the tests of the packages that use this one
var ScryptWorkFactor int
// EncryptToRecipient encrypts data to a recipient using age // EncryptToRecipient encrypts data to a recipient using age
// The data parameter should be a LockedBuffer for secure memory handling // The data parameter should be a LockedBuffer for secure memory handling
func EncryptToRecipient( func EncryptToRecipient(
@@ -153,10 +141,6 @@ func EncryptWithPassphrase(
return nil, fmt.Errorf("failed to create scrypt recipient: %w", err) return nil, fmt.Errorf("failed to create scrypt recipient: %w", err)
} }
if ScryptWorkFactor != 0 {
recipient.SetWorkFactor(ScryptWorkFactor)
}
return EncryptToRecipient(data, recipient) return EncryptToRecipient(data, recipient)
} }
@@ -185,58 +169,40 @@ func DecryptWithPassphrase(
// Returns a LockedBuffer containing the passphrase for secure memory handling. // Returns a LockedBuffer containing the passphrase for secure memory handling.
// Every error it returns wraps ErrPassphraseNotRead. // Every error it returns wraps ErrPassphraseNotRead.
func ReadPassphrase(prompt string) (*memguard.LockedBuffer, error) { func ReadPassphrase(prompt string) (*memguard.LockedBuffer, error) {
return readFromTerminal(prompt, ErrPassphraseNotRead, EnvUnlockPassphrase)
}
// ReadMnemonic reads a mnemonic from the terminal as ReadPassphrase reads a
// passphrase. Every error it returns wraps ErrMnemonicNotRead.
func ReadMnemonic(prompt string) (*memguard.LockedBuffer, error) {
return readFromTerminal(prompt, ErrMnemonicNotRead, EnvMnemonic)
}
// readFromTerminal reads input from the terminal without echoing it. Every
// error it returns wraps notRead; without a terminal, the error says to set
// envVar instead.
func readFromTerminal(
prompt string, notRead error, envVar string,
) (*memguard.LockedBuffer, error) {
// Check if stdin is a terminal // Check if stdin is a terminal
if !term.IsTerminal(syscall.Stdin) { if !term.IsTerminal(syscall.Stdin) {
// Not a terminal - never read secrets from piped input // Not a terminal - never read passphrases from piped input
// for security reasons // for security reasons
return nil, fmt.Errorf( return nil, fmt.Errorf("%w: %w", ErrPassphraseNotRead, errStdinNotTerminal)
"%w: %w. Please set the %s environment variable or run interactively",
notRead, errStdinNotTerminal, envVar)
} }
// stdin is a terminal, check if stderr is also a terminal for // stdin is a terminal, check if stderr is also a terminal for
// interactive prompting // interactive prompting
if !term.IsTerminal(syscall.Stderr) { if !term.IsTerminal(syscall.Stderr) {
return nil, fmt.Errorf("%w: %w. Please set the %s environment variable", return nil, fmt.Errorf("%w: %w", ErrPassphraseNotRead, errStderrNotTerminal)
notRead, errStderrNotTerminal, envVar)
} }
// Both stdin and stderr are terminals - use secure password reading // Both stdin and stderr are terminals - use secure password reading
fmt.Fprint(os.Stderr, prompt) // Write prompt to stderr, not stdout fmt.Fprint(os.Stderr, prompt) // Write prompt to stderr, not stdout
input, err := term.ReadPassword(syscall.Stdin) passphrase, err := term.ReadPassword(syscall.Stdin)
if err != nil { if err != nil {
return nil, fmt.Errorf("%w: %w", notRead, err) return nil, fmt.Errorf("%w: %w", ErrPassphraseNotRead, err)
} }
// Print newline to stderr since ReadPassword doesn't echo // Print newline to stderr since ReadPassword doesn't echo
fmt.Fprintln(os.Stderr) fmt.Fprintln(os.Stderr)
if len(input) == 0 { if len(passphrase) == 0 {
return nil, fmt.Errorf("%w: %w", notRead, errNothingEntered) return nil, fmt.Errorf("%w: %w", ErrPassphraseNotRead, errEmptyPassphrase)
} }
// Create a secure buffer and copy the input // Create a secure buffer and copy the passphrase
secureBuffer := memguard.NewBufferFromBytes(input) secureBuffer := memguard.NewBufferFromBytes(passphrase)
// Clear the original input slice // Clear the original passphrase slice
for i := range input { for i := range passphrase {
input[i] = 0 passphrase[i] = 0
} }
return secureBuffer, nil return secureBuffer, nil
+1 -1
View File
@@ -4,9 +4,9 @@ import (
"testing" "testing"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
) )
// TestIdentityToLockedBuffer checks that the buffer holds the identity's // TestIdentityToLockedBuffer checks that the buffer holds the identity's
+1 -1
View File
@@ -10,11 +10,11 @@ import (
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/pkg/agehd"
) )
// realVault is a minimal VaultInterface backed by a real afero filesystem, // realVault is a minimal VaultInterface backed by a real afero filesystem,
+1 -1
View File
@@ -3,7 +3,7 @@ package secret_test
import ( import (
"testing" "testing"
"sneak.berlin/go/secret/internal/secret" "git.eeqj.de/sneak/secret/internal/secret"
) )
func TestDetermineStateDir_ErrorsWhenHomeDirUnavailable(t *testing.T) { func TestDetermineStateDir_ErrorsWhenHomeDirUnavailable(t *testing.T) {
+19 -1
View File
@@ -11,12 +11,13 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
"runtime"
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/pkg/agehd"
) )
const ( const (
@@ -38,6 +39,8 @@ const (
var keychainItemNameRegex = regexp.MustCompile(`^[A-Za-z0-9._-]+$`) var keychainItemNameRegex = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
var ( var (
errNotMacOS = errors.New(
"keychain unlockers are only supported on macOS")
errKeychainItemNameEmpty = errors.New("keychain item name cannot be empty") errKeychainItemNameEmpty = errors.New("keychain item name cannot be empty")
errInvalidKeychainItemName = errors.New("invalid keychain item name format") errInvalidKeychainItemName = errors.New("invalid keychain item name format")
errUnsupportedCurrentUnlocker = errors.New( errUnsupportedCurrentUnlocker = errors.New(
@@ -391,6 +394,12 @@ func deriveLongTermPrivateKey(
func CreateKeychainUnlocker( func CreateKeychainUnlocker(
fs afero.Fs, stateDir string, mnemonic, passphrase *memguard.LockedBuffer, fs afero.Fs, stateDir string, mnemonic, passphrase *memguard.LockedBuffer,
) (*KeychainUnlocker, error) { ) (*KeychainUnlocker, error) {
// Check if we're on macOS
err := checkMacOSAvailable()
if err != nil {
return nil, err
}
// Get current vault using the GetCurrentVault function from the same package // Get current vault using the GetCurrentVault function from the same package
vault, err := GetCurrentVault(fs, stateDir) vault, err := GetCurrentVault(fs, stateDir)
if err != nil { if err != nil {
@@ -546,6 +555,15 @@ func writeKeychainUnlocker(
}, nil }, nil
} }
// checkMacOSAvailable verifies that we're running on macOS
func checkMacOSAvailable() error {
if runtime.GOOS != "darwin" {
return fmt.Errorf("%w, current OS: %s", errNotMacOS, runtime.GOOS)
}
return nil
}
// validateKeychainItemName validates that a keychain item name is safe for // validateKeychainItemName validates that a keychain item name is safe for
// command execution // command execution
func validateKeychainItemName(itemName string) error { func validateKeychainItemName(itemName string) error {
+2 -2
View File
@@ -7,10 +7,10 @@ import (
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/pkg/agehd"
) )
// testMnemonic is the standard BIP39 test vector mnemonic. // testMnemonic is the standard BIP39 test vector mnemonic.
+5 -5
View File
@@ -17,11 +17,11 @@ import (
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
"sneak.berlin/go/secret/pkg/agehd"
) )
// pgpUnlockerType is the type of a PGP unlocker. // pgpUnlockerType is the type of a PGP unlocker.
@@ -317,8 +317,8 @@ func testCreatePGPUnlocker(
t.Helper() t.Helper()
// Set a limited test timeout to avoid hanging // Set a limited test timeout to avoid hanging
timer := time.AfterFunc(10*time.Second, func() { timer := time.AfterFunc(30*time.Second, func() {
t.Fatalf("Test timed out after 10 seconds") t.Fatalf("Test timed out after 30 seconds")
}) })
defer timer.Stop() defer timer.Stop()
+2 -2
View File
@@ -5,12 +5,12 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
// The GPG key ID and fingerprint passed to CreatePGPUnlocker. // The GPG key ID and fingerprint passed to CreatePGPUnlocker.
+1 -9
View File
@@ -9,9 +9,9 @@ import (
"testing" "testing"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/pkg/agehd"
) )
// testMnemonicValue is the standard BIP39 test vector mnemonic. // testMnemonicValue is the standard BIP39 test vector mnemonic.
@@ -25,14 +25,6 @@ var (
errNotImplementedInMock = errors.New("not implemented in mock") errNotImplementedInMock = errors.New("not implemented in mock")
) )
// TestMain makes passphrase encryption in the tests cheap; see
// ScryptWorkFactor.
func TestMain(m *testing.M) {
ScryptWorkFactor = 1
os.Exit(m.Run())
}
// MockVault is a test implementation of the VaultInterface // MockVault is a test implementation of the VaultInterface
type MockVault struct { type MockVault struct {
name string name string
+6 -1
View File
@@ -12,9 +12,9 @@ import (
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/macse"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/macse"
) )
const ( const (
@@ -216,6 +216,11 @@ func CreateSecureEnclaveUnlocker(
stateDir string, stateDir string,
mnemonic, passphrase *memguard.LockedBuffer, mnemonic, passphrase *memguard.LockedBuffer,
) (*SecureEnclaveUnlocker, error) { ) (*SecureEnclaveUnlocker, error) {
err := checkMacOSAvailable()
if err != nil {
return nil, err
}
vault, err := GetCurrentVault(fs, stateDir) vault, err := GetCurrentVault(fs, stateDir)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to get current vault: %w", err) return nil, fmt.Errorf("failed to get current vault: %w", err)
+5 -5
View File
@@ -22,10 +22,10 @@ const (
maxVersionsPerDay = 999 maxVersionsPerDay = 999
) )
var errMaxVersionsPerDay = errors.New("exceeded maximum versions per day (999)") var (
errMaxVersionsPerDay = errors.New("exceeded maximum versions per day (999)")
// ErrNilValueBuffer is returned when a secret's value is given as nil. errNilValueBuffer = errors.New("value buffer is nil")
var ErrNilValueBuffer = errors.New("value buffer is nil") )
// VersionMetadata contains information about a secret version // VersionMetadata contains information about a secret version
type VersionMetadata struct { type VersionMetadata struct {
@@ -138,7 +138,7 @@ func GenerateVersionName(fs afero.Fs, secretDir string) (string, error) {
// process dies part-way. // process dies part-way.
func (sv *Version) Save(value *memguard.LockedBuffer) error { func (sv *Version) Save(value *memguard.LockedBuffer) error {
if value == nil { if value == nil {
return ErrNilValueBuffer return errNilValueBuffer
} }
DebugWith("Saving secret version", DebugWith("Saving secret version",
+1 -1
View File
@@ -41,11 +41,11 @@ import (
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
) )
const ( const (
+3
View File
@@ -36,6 +36,9 @@ var (
// it unlocks. Composed as "vault <name> needs a mnemonic for an unlocker". // it unlocks. Composed as "vault <name> needs a mnemonic for an unlocker".
ErrUnlockerWithoutMnemonic = errors.New("needs a mnemonic for an unlocker") ErrUnlockerWithoutMnemonic = errors.New("needs a mnemonic for an unlocker")
// ErrNilValueBuffer indicates a nil value buffer was supplied.
ErrNilValueBuffer = errors.New("value buffer is nil")
// ErrInvalidSecretName indicates a secret name that breaks the naming // ErrInvalidSecretName indicates a secret name that breaks the naming
// rule: only ASCII letters, digits, '.', '-', '_' and '/'; not empty; // rule: only ASCII letters, digits, '.', '-', '_' and '/'; not empty;
// no leading '.' or '/', no trailing '/', no '//', no '..' path segment. // no leading '.' or '/', no trailing '/', no '//', no '..' path segment.
+3 -3
View File
@@ -4,11 +4,11 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
const ( const (
@@ -60,7 +60,7 @@ func TestVaultErrors(t *testing.T) {
}, vault.ErrVaultNotFound}, }, vault.ErrVaultNotFound},
{"add a nil value", func(vlt *vault.Vault) error { {"add a nil value", func(vlt *vault.Vault) error {
return vlt.AddSecret(missingName, nil, false) return vlt.AddSecret(missingName, nil, false)
}, secret.ErrNilValueBuffer}, }, vault.ErrNilValueBuffer},
{"get a missing secret", func(vlt *vault.Vault) error { {"get a missing secret", func(vlt *vault.Vault) error {
_, err := vlt.GetSecret(missingName) _, err := vlt.GetSecret(missingName)
+2 -2
View File
@@ -9,10 +9,10 @@ import (
"testing" "testing"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/vault"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/vault"
"sneak.berlin/go/secret/pkg/agehd"
) )
// deriveVaultIdentity derives the long-term identity for the given vault // deriveVaultIdentity derives the long-term identity for the given vault
+2 -2
View File
@@ -30,12 +30,12 @@ import (
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/pkg/agehd"
) )
// errUnexpectedValue is returned by concurrent readers when a secret value // errUnexpectedValue is returned by concurrent readers when a secret value
+1 -1
View File
@@ -8,8 +8,8 @@ import (
"sync" "sync"
"syscall" "syscall"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/secret"
) )
// lockFileName is the file in the state directory that LockStateDir locks. // lockFileName is the file in the state directory that LockStateDir locks.
+2 -2
View File
@@ -5,11 +5,11 @@ import (
"testing" "testing"
"time" "time"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
const ( const (
+2 -2
View File
@@ -9,10 +9,10 @@ import (
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/pkg/agehd"
) )
// Register the GetCurrentVault function with the secret package // Register the GetCurrentVault function with the secret package
+2 -2
View File
@@ -7,9 +7,9 @@ import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/pkg/agehd"
) )
// Metadata is an alias for secret.VaultMetadata // Metadata is an alias for secret.VaultMetadata
+2 -2
View File
@@ -5,9 +5,9 @@ import (
"strings" "strings"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/vault"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/vault"
"sneak.berlin/go/secret/pkg/agehd"
) )
//nolint:paralleltest // subtests share an in-memory filesystem sequentially //nolint:paralleltest // subtests share an in-memory filesystem sequentially
+1 -1
View File
@@ -3,10 +3,10 @@ package vault_test
import ( import (
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/vault"
) )
// TestGetSecretVersionRejectsPathTraversal verifies that GetSecretVersion // TestGetSecretVersionRejectsPathTraversal verifies that GetSecretVersion
+2 -2
View File
@@ -11,9 +11,9 @@ import (
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/secret"
) )
// ListSecrets returns a list of secret names in this vault // ListSecrets returns a list of secret names in this vault
@@ -130,7 +130,7 @@ func ValidateSecretName(name string) error {
// AddSecret adds a secret to this vault // AddSecret adds a secret to this vault
func (v *Vault) AddSecret(name string, value *memguard.LockedBuffer, force bool) error { func (v *Vault) AddSecret(name string, value *memguard.LockedBuffer, force bool) error {
if value == nil { if value == nil {
return secret.ErrNilValueBuffer return ErrNilValueBuffer
} }
secret.DebugWith("Adding secret to vault", secret.DebugWith("Adding secret to vault",
+2 -2
View File
@@ -27,12 +27,12 @@ import (
"testing" "testing"
"time" "time"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/pkg/agehd"
) )
// testMnemonic is the mnemonic used to derive the vault long-term key. // testMnemonic is the mnemonic used to derive the vault long-term key.
+1 -1
View File
@@ -11,9 +11,9 @@ import (
"time" "time"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/secret"
) )
// Unlocker metadata type strings. // Unlocker metadata type strings.
+2 -2
View File
@@ -7,10 +7,10 @@ import (
"path/filepath" "path/filepath"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/pkg/agehd"
) )
// Vault represents a secrets vault // Vault represents a secrets vault
+2 -2
View File
@@ -5,12 +5,12 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
) )
func TestAddSecretFailsWithMissingPublicKey(t *testing.T) { func TestAddSecretFailsWithMissingPublicKey(t *testing.T) {
+3 -12
View File
@@ -3,16 +3,15 @@ package vault_test
import ( import (
"bytes" "bytes"
"errors" "errors"
"os"
"path/filepath" "path/filepath"
"slices" "slices"
"testing" "testing"
"git.eeqj.de/sneak/secret/internal/secret"
"git.eeqj.de/sneak/secret/internal/vault"
"git.eeqj.de/sneak/secret/pkg/agehd"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/afero" "github.com/spf13/afero"
"sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault"
"sneak.berlin/go/secret/pkg/agehd"
) )
// testMnemonic is the shared BIP39 test mnemonic for tests in this package. // testMnemonic is the shared BIP39 test mnemonic for tests in this package.
@@ -29,14 +28,6 @@ const (
testPassphrase = "test-passphrase" testPassphrase = "test-passphrase"
) )
// TestMain makes passphrase encryption in the tests cheap; see
// secret.ScryptWorkFactor.
func TestMain(m *testing.M) {
secret.ScryptWorkFactor = 1
os.Exit(m.Run())
}
// testMnemonicBuffer returns testMnemonic in a locked buffer that is // testMnemonicBuffer returns testMnemonic in a locked buffer that is
// destroyed when the test ends. // destroyed when the test ends.
func testMnemonicBuffer(t *testing.T) *memguard.LockedBuffer { func testMnemonicBuffer(t *testing.T) *memguard.LockedBuffer {
-5
View File
@@ -1,5 +0,0 @@
{
"devDependencies": {
"prettier": "3.8.1"
}
}
+18 -35
View File
@@ -1,21 +1,14 @@
# agehd - Deterministic Age Identities from BIP85 # agehd - Deterministic Age Identities from BIP85
The `agehd` package derives deterministic X25519 age identities using BIP85 The `agehd` package derives deterministic X25519 age identities using BIP85 entropy derivation and a deterministic random number generator (DRNG). This package only supports proper BIP85 sources: BIP39 mnemonics and extended private keys (xprv).
entropy derivation and a deterministic random number generator (DRNG). This
package only supports proper BIP85 sources: BIP39 mnemonics and extended private
keys (xprv).
## Features ## Features
- **Deterministic key generation**: Same input always produces the same age - **Deterministic key generation**: Same input always produces the same age identity
identity
- **BIP85 compliance**: Uses the BIP85 standard for entropy derivation - **BIP85 compliance**: Uses the BIP85 standard for entropy derivation
- **Multiple key support**: Generate multiple keys from the same source using - **Multiple key support**: Generate multiple keys from the same source using different indices
different indices - **Two BIP85 input methods**: Support for BIP39 mnemonics and extended private keys (xprv)
- **Two BIP85 input methods**: Support for BIP39 mnemonics and extended private - **Vendor/application scoped**: Uses vendor-specific derivation paths to avoid conflicts
keys (xprv)
- **Vendor/application scoped**: Uses vendor-specific derivation paths to avoid
conflicts
## Derivation Path ## Derivation Path
@@ -26,7 +19,6 @@ m/83696968'/592366788'/733482323'/n'
``` ```
Where: Where:
- `83696968'` is the BIP85 root path ("bip" in ASCII) - `83696968'` is the BIP85 root path ("bip" in ASCII)
- `592366788'` is the vendor ID (sha256("berlin.sneak") & 0x7fffffff) - `592366788'` is the vendor ID (sha256("berlin.sneak") & 0x7fffffff)
- `733482323'` is the application ID (sha256("secret") & 0x7fffffff) - `733482323'` is the application ID (sha256("secret") & 0x7fffffff)
@@ -43,7 +35,7 @@ import (
"fmt" "fmt"
"log" "log"
"sneak.berlin/go/secret/pkg/agehd" "git.eeqj.de/sneak/secret/pkg/agehd"
) )
func main() { func main() {
@@ -69,7 +61,7 @@ import (
"fmt" "fmt"
"log" "log"
"sneak.berlin/go/secret/pkg/agehd" "git.eeqj.de/sneak/secret/pkg/agehd"
) )
func main() { func main() {
@@ -95,7 +87,7 @@ import (
"fmt" "fmt"
"log" "log"
"sneak.berlin/go/secret/pkg/agehd" "git.eeqj.de/sneak/secret/pkg/agehd"
) )
func main() { func main() {
@@ -122,7 +114,7 @@ import (
"fmt" "fmt"
"log" "log"
"sneak.berlin/go/secret/pkg/agehd" "git.eeqj.de/sneak/secret/pkg/agehd"
) )
func main() { func main() {
@@ -159,8 +151,7 @@ Derives a deterministic age identity from a BIP39 mnemonic and index.
#### `DeriveIdentityFromXPRV(xprv string, n uint32) (*age.X25519Identity, error)` #### `DeriveIdentityFromXPRV(xprv string, n uint32) (*age.X25519Identity, error)`
Derives a deterministic age identity from an extended private key (xprv) and Derives a deterministic age identity from an extended private key (xprv) and index.
index.
- `xprv`: A valid extended private key in xprv format - `xprv`: A valid extended private key in xprv format
- `n`: The derivation index (0, 1, 2, ...) - `n`: The derivation index (0, 1, 2, ...)
@@ -176,8 +167,7 @@ Derives 32 bytes of entropy from a BIP39 mnemonic and index using BIP85.
#### `DeriveEntropyFromXPRV(xprv string, n uint32) ([]byte, error)` #### `DeriveEntropyFromXPRV(xprv string, n uint32) ([]byte, error)`
Derives 32 bytes of entropy from an extended private key (xprv) and index using Derives 32 bytes of entropy from an extended private key (xprv) and index using BIP85.
BIP85.
- `xprv`: A valid extended private key in xprv format - `xprv`: A valid extended private key in xprv format
- `n`: The derivation index - `n`: The derivation index
@@ -192,27 +182,20 @@ Converts 32 bytes of entropy into an age X25519 identity.
## Implementation Details ## Implementation Details
1. **BIP85 Entropy Derivation**: The package uses the BIP85 standard to derive 1. **BIP85 Entropy Derivation**: The package uses the BIP85 standard to derive 64 bytes of entropy from the input source
64 bytes of entropy from the input source 2. **DRNG**: A BIP85 DRNG (Deterministic Random Number Generator) using SHAKE256 is seeded with the 64-byte entropy
2. **DRNG**: A BIP85 DRNG (Deterministic Random Number Generator) using SHAKE256 3. **Key Generation**: 32 bytes are read from the DRNG to generate the age private key
is seeded with the 64-byte entropy 4. **RFC-7748 Clamping**: The private key is clamped according to RFC-7748 for X25519
3. **Key Generation**: 32 bytes are read from the DRNG to generate the age 5. **Bech32 Encoding**: The key is encoded using Bech32 with the "age-secret-key-" prefix
private key
4. **RFC-7748 Clamping**: The private key is clamped according to RFC-7748 for
X25519
5. **Bech32 Encoding**: The key is encoded using Bech32 with the
"age-secret-key-" prefix
## Security Considerations ## Security Considerations
- The same mnemonic/xprv and index will always produce the same identity - The same mnemonic/xprv and index will always produce the same identity
- Different indices produce cryptographically independent identities - Different indices produce cryptographically independent identities
- The vendor/application scoping prevents conflicts with other BIP85 - The vendor/application scoping prevents conflicts with other BIP85 applications
applications
- The DRNG ensures high-quality randomness for key generation - The DRNG ensures high-quality randomness for key generation
- Private keys are properly clamped for X25519 usage - Private keys are properly clamped for X25519 usage
- Only accepts proper BIP85 sources (mnemonics and xprv keys), not arbitrary - Only accepts proper BIP85 sources (mnemonics and xprv keys), not arbitrary passphrases
passphrases
## Testing ## Testing
+1 -1
View File
@@ -14,11 +14,11 @@ import (
"strings" "strings"
"filippo.io/age" "filippo.io/age"
"git.eeqj.de/sneak/secret/pkg/bip85"
"github.com/btcsuite/btcd/btcutil/hdkeychain" "github.com/btcsuite/btcd/btcutil/hdkeychain"
"github.com/btcsuite/btcd/chaincfg" "github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcutil/bech32" "github.com/btcsuite/btcutil/bech32"
"github.com/tyler-smith/go-bip39" "github.com/tyler-smith/go-bip39"
"sneak.berlin/go/secret/pkg/bip85"
) )
const ( const (
+4 -11
View File
@@ -1,15 +1,10 @@
# BIP85 - Deterministic Entropy From BIP32 Keychains # BIP85 - Deterministic Entropy From BIP32 Keychains
This package implements This package implements [BIP85](https://github.com/bitcoin/bips/blob/master/bip-0085.mediawiki), which allows for deterministic derivation of entropy from a BIP32 master key. This enables a single seed to generate multiple wallet keys, mnemonics, and random values in a fully deterministic way.
[BIP85](https://github.com/bitcoin/bips/blob/master/bip-0085.mediawiki), which
allows for deterministic derivation of entropy from a BIP32 master key. This
enables a single seed to generate multiple wallet keys, mnemonics, and random
values in a fully deterministic way.
## Overview ## Overview
BIP85 enables a variety of use cases: BIP85 enables a variety of use cases:
- Generate multiple BIP39 mnemonic seeds from a single master key - Generate multiple BIP39 mnemonic seeds from a single master key
- Derive Bitcoin HD wallet seeds (WIF format) - Derive Bitcoin HD wallet seeds (WIF format)
- Create extended private keys (XPRV) - Create extended private keys (XPRV)
@@ -22,8 +17,8 @@ BIP85 enables a variety of use cases:
```go ```go
import ( import (
"fmt" "fmt"
"git.eeqj.de/sneak/secret/pkg/bip85"
"github.com/btcsuite/btcd/btcutil/hdkeychain" "github.com/btcsuite/btcd/btcutil/hdkeychain"
"sneak.berlin/go/secret/pkg/bip85"
) )
// Parse an existing master key // Parse an existing master key
@@ -119,7 +114,6 @@ m/83696968'/{app}'/{parameters}
``` ```
Where: Where:
- `83696968'` is the BIP85 root path (BIP in ASCII) - `83696968'` is the BIP85 root path (BIP in ASCII)
- `{app}'` is the application number: - `{app}'` is the application number:
- `39'` for BIP39 mnemonics - `39'` for BIP39 mnemonics
@@ -141,13 +135,12 @@ This implementation passes all the test vectors from the BIP85 specification:
- XPRV - XPRV
- SHAKE256 DRNG output - SHAKE256 DRNG output
The implementation is also compatible with the Python reference implementation's The implementation is also compatible with the Python reference implementation's test vectors for the DRNG functionality.
test vectors for the DRNG functionality.
Run the tests with verbose output to see the test vectors and results: Run the tests with verbose output to see the test vectors and results:
``` ```
go test -v sneak.berlin/go/secret/pkg/bip85 go test -v git.eeqj.de/sneak/secret/pkg/bip85
``` ```
## References ## References
+1 -1
View File
@@ -9,9 +9,9 @@ import (
"strings" "strings"
"testing" "testing"
"git.eeqj.de/sneak/secret/pkg/bip85"
"github.com/btcsuite/btcd/btcutil/hdkeychain" "github.com/btcsuite/btcd/btcutil/hdkeychain"
"github.com/tyler-smith/go-bip39" "github.com/tyler-smith/go-bip39"
"sneak.berlin/go/secret/pkg/bip85"
) )
const ( const (
+3 -4
View File
@@ -131,10 +131,9 @@ main() {
if missing make; then pkg_install gnumake make make make; fi if missing make; then pkg_install gnumake make make make; fi
# ---- JS / docs repos ---- # ---- JS / docs repos ----
# prettier, pinned in package.json and yarn.lock, formats the markdown # ensure_node
ensure_node # ensure_yarn
ensure_yarn # install_js_deps
install_js_deps
# ---- Go repos ---- # ---- Go repos ----
if missing go; then pkg_install go golang go go; fi if missing go; then pkg_install go golang go go; fi
+1 -1
View File
@@ -17,7 +17,7 @@ main() {
echo dev)" echo dev)"
fi fi
commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
pkg=sneak.berlin/go/secret/internal/cli pkg=git.eeqj.de/sneak/secret/internal/cli
# Build the file, not the package `./cmd/secret`: a package build # Build the file, not the package `./cmd/secret`: a package build
# also stamps git status into the binary and fails where git cannot # also stamps git status into the binary and fails where git cannot
# read the checkout, instead of falling back to `dev`/`unknown`. # read the checkout, instead of falling back to `dev`/`unknown`.
+3 -4
View File
@@ -1,8 +1,6 @@
#!/bin/sh #!/bin/sh
# script/check: run all checks (test, lint, fmt-check). Our own # script/check: run all checks (test, lint, lint-darwin, fmt-check). Our
# extension to scripts-to-rule-them-all. test and lint are Docker # own extension to scripts-to-rule-them-all. Must not modify any files.
# phases; fmt-check is native, because a formatter writes the working
# tree. Must not modify any files.
set -eu set -eu
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
@@ -10,6 +8,7 @@ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
main() { main() {
"$SCRIPT_DIR/test" "$SCRIPT_DIR/test"
"$SCRIPT_DIR/lint" "$SCRIPT_DIR/lint"
"$SCRIPT_DIR/lint-darwin"
"$SCRIPT_DIR/fmt-check" "$SCRIPT_DIR/fmt-check"
} }
+11 -19
View File
@@ -1,28 +1,20 @@
#!/bin/sh #!/bin/sh
# script/cibuild: run the CI build. It bootstraps first: a CI runner # script/cibuild: run the CI build. The Dockerfile runs script/check
# checks out and runs this and nothing else, and script/fmt-check runs # (via make check), so a successful build implies all checks pass.
# the formatter on the host, which a pristine checkout cannot do. # The Gitea workflow runs this on push. The memlock ulimit lets the tests
# --no-cache for the same reason as script/docker: the gate phases the # that lock large secrets in memory (memguard mlocks them) run; under the
# final stage depends on are RUN steps, and a cached one is a check that # lower limit of a plain `docker build .` they are skipped.
# did not run. # A cached build checks nothing: a new CHECK_EPOCH on every run makes the
# Dockerfile's check steps run again on an unchanged tree, while its base
# images and module downloads stay cached.
set -eu set -eu
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
main() { main() {
cd "$ROOT" cd "$ROOT"
"$SCRIPT_DIR/bootstrap" docker build --ulimit memlock=-1:-1 \
"$SCRIPT_DIR/check" --build-arg CHECK_EPOCH="$(date +%s)" .
# 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" \
-t "$("$SCRIPT_DIR/projectname")" .
} }
main "$@" main "$@"
+1 -22
View File
@@ -1,33 +1,12 @@
#!/bin/sh #!/bin/sh
# script/fmt: format all files (writes): Go with go fmt, markdown with # script/fmt: format all files (writes).
# prettier.
set -eu set -eu
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" 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() { main() {
cd "$ROOT" cd "$ROOT"
go fmt ./... go fmt ./...
run_yarn run prettier --write '**/*.md' --tab-width 4 --prose-wrap always
} }
main "$@" main "$@"
-20
View File
@@ -5,25 +5,6 @@ set -eu
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" 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() { main() {
cd "$ROOT" cd "$ROOT"
if [ -n "$(gofmt -l .)" ]; then if [ -n "$(gofmt -l .)" ]; then
@@ -31,7 +12,6 @@ main() {
gofmt -l . gofmt -l .
exit 1 exit 1
fi fi
run_yarn run prettier --check '**/*.md' --tab-width 4 --prose-wrap always
} }
main "$@" main "$@"
+13 -12
View File
@@ -1,23 +1,24 @@
#!/bin/sh #!/bin/sh
# script/lint: run the linter. Linting is a phase of the Dockerfile and # script/lint: run the linter, in docker only. Builds Dockerfile.lint,
# this builds that phase alone; the linter is never installed or run on # where golangci-lint runs as a build step.
# a developer host, where a shared result cache and a host-global lock
# make its answer untrustworthy.
# #
# The phase is not the last stage in the file, so it is built only when # A cached build lints nothing, so --no-cache-filter rebuilds the lint
# --target names it. --no-cache because a cached lint layer is a lint # stage on every run, an unchanged tree included. It ignores a stage name
# that did not run. The tag makes each build replace the previous image # that does not exist, so --target names the same stage: a rename then
# instead of leaving a dangling one behind. # fails the build instead of serving the lint from cache. cacheonly keeps
# no image; only the build's success matters.
set -eu set -eu
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
main() { main() {
cd "$ROOT" cd "$ROOT"
docker build --no-cache \ docker build \
--progress=plain \
--target lint \ --target lint \
-t "$("$SCRIPT_DIR/projectname")-lint" . --no-cache-filter=lint \
--output=type=cacheonly \
-f Dockerfile.lint .
} }
main "$@" main "$@"
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# script/lint-darwin: type-check (go vet) and lint the code as a macOS
# build compiles it, from Linux, in docker only. CI runs on Linux, which
# never compiles the files built only for macOS. Builds the lint-darwin
# stage of Dockerfile.lint, rebuilt on every run as script/lint does.
#
# Cgo is off: compiling cgo code for macOS needs Apple's SDK headers. That
# leaves out the files built only with cgo on macOS: the keychain unlocker's
# calls into the keychain (keychainunlocker_cgo.go, and
# keychainunlocker_test.go) and the Secure Enclave bindings (internal/macse).
# Nothing on Linux checks those.
set -eu
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
main() {
cd "$ROOT"
docker build \
--progress=plain \
--target lint-darwin \
--no-cache-filter=lint-darwin \
--output=type=cacheonly \
-f Dockerfile.lint .
}
main "$@"
+6 -10
View File
@@ -1,19 +1,15 @@
#!/bin/sh #!/bin/sh
# script/test: run the test suite. Testing is a phase of the Dockerfile # script/test: run the test suite (vet first, verbose rerun on failure).
# and this builds that phase alone, on the same terms as script/lint:
# --target because a phase that is not the last stage is built only when
# named, --no-cache because a cached test layer is a test that did not
# run, and a tag so each build replaces the previous image.
set -eu set -eu
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)" ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
main() { main() {
cd "$ROOT" cd "$ROOT"
docker build --no-cache \ # CGO is required (Makefile exports this too)
--target test \ export CGO_ENABLED=1
-t "$("$SCRIPT_DIR/projectname")-test" . go vet ./...
go test ./... || go test -v ./...
} }
main "$@" main "$@"
-8
View File
@@ -1,8 +0,0 @@
# 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==