Compare commits

..
1 Commits
Author SHA1 Message Date
sneak c995ee45fb Keep Go's build cache between builds (closes #124)
check / check (push) Successful in 1m43s
The Dockerfile runs make test and make build with Go's build cache in a
BuildKit cache mount, so a build compiles only what changed since the
last one instead of the standard library and every dependency from
nothing. The mount has an id of its own, so builds of other repositories,
compiled against other C headers, do not share it. script/test passes
-count=1, so no test result is taken from the cache.

Model: opus-5-5
2026-10-06 12:05:07 +00:00
35 changed files with 423 additions and 3559 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`.**
+93
View File
@@ -0,0 +1,93 @@
# 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.
+69 -57
View File
@@ -1,79 +1,91 @@
# Lint phase. The linter is invoked directly rather than through `make # node and yarn, copied into the lint stage for prettier, which checks the
# lint` or `script/lint`, which are themselves a docker build. # markdown formatting: node of the version script/bootstrap pins, built on
# golangci/golangci-lint:v2.14.0 (Debian-based), 2026-09-24 # Debian as the lint stage's image is.
FROM golangci/golangci-lint@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f AS lint # node:22.17.0-bookworm-slim, 2025-07-08
FROM node@sha256:b04ce4ae4e95b522112c2e5c52f781471a5cbc3b594527bcddedee9bc48c03a0 AS node
# Lint stage — fast feedback on formatting and lint issues
# golangci/golangci-lint:v2.12.2 (Debian-based), 2026-08-07
FROM golangci/golangci-lint:v2.12.2@sha256:5cceeef04e53efe1470638d4b4b4f5ceefd574955ab3941b2d9a68a8c9ad5240 AS lint
COPY --from=node /usr/local/bin/node /usr/local/bin/node
COPY --from=node /opt/yarn-v1.22.22 /opt/yarn-v1.22.22
ENV PATH="/opt/yarn-v1.22.22/bin:${PATH}"
# script/bootstrap downloads the Go modules and installs prettier
WORKDIR /src WORKDIR /src
COPY go.mod go.sum ./ COPY script/ script/
RUN go mod download COPY go.mod go.sum package.json yarn.lock ./
RUN script/bootstrap
# 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 # Go's build cache is kept between builds in this cache mount, which make test
# `git describe --tags --always` on the .git in the build context. With # and make build both use, so each compiles only what changed since the last
# .git present, a version that is still empty, dev or unknown fails the # build, not the standard library and every dependency from nothing.
# build: git is missing or could not read the checkout. # script/test passes -count=1, so test results are never taken from it.
ARG VERSION # The mount has its own id because the default id, its path, is shared with
RUN VERSION="${VERSION:-$(git describe --tags --always)}"; \ # other repositories' builds, and Go's cache does not notice changes to C
if [ -e .git ]; then \ # libraries: an entry compiled there against other C headers could be reused
case "$VERSION" in ""|dev|unknown) \ # here. It does not notice a change of this image's own C headers either.
echo "version is '$VERSION' although .git is present" >&2; \ RUN --mount=type=cache,id=sneak/secret/go-build,target=/root/.cache/go-build \
exit 1 ;; \ make test
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. make build uses the same Go
# build cache mount as make test.
ARG VERSION
RUN --mount=type=cache,id=sneak/secret/go-build,target=/root/.cache/go-build \
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
+19 -14
View File
@@ -604,24 +604,29 @@ 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 every test on every run, never a result from Go's test cache
failure it reruns the tests verbosely for the details and fails even when the - `script/lint` — run `golangci-lint` in docker only: builds `Dockerfile.lint`,
rerun passes where the linter is a build step that runs on every call, also on an unchanged
- `script/lint` — build the `lint` phase of the `Dockerfile`, which runs tree
`go vet` and `golangci-lint`, then both again on the code as a macOS build - `script/lint-darwin` — run `go vet` and `golangci-lint` in docker on the code
compiles it (`GOOS=darwin`), which a Linux build never compiles; cgo is off as a macOS build compiles it (`GOOS=darwin`), which a Linux build never
there, so the keychain unlocker's calls into the keychain compiles; cgo is off, 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 with `go fmt` and every markdown file with
prettier (4-space tabs, `proseWrap: always`) (writes) prettier (4-space tabs, `proseWrap: always`) (writes)
- `script/fmt-check` — check the same formatting without writing, on the host - `script/fmt-check` — check the same formatting without writing; the
- `script/check` — run `script/test`, `script/lint` and `script/fmt-check` `Dockerfile` lint stage runs it, so an unformatted Go or markdown file fails
- `script/docker` — build the Docker image tagged with the project name; the the build
build runs the `lint` and `test` phases first - `script/check` — run `script/test`, `script/lint`, `script/lint-darwin`, and
- `script/cibuild` — CI entrypoint: runs `script/bootstrap`, `script/check`, `script/fmt-check`
then builds the image as `script/docker` does - `script/docker` — build the Docker image tagged with the project name
- `script/cibuild` — CI entrypoint: `docker build --ulimit memlock=-1:-1 .`
(memguard needs mlock; the Dockerfile runs the checks), with a new
`CHECK_EPOCH` build argument on every run so the checks run again on an
unchanged tree; the `Dockerfile` keeps Go's build cache between builds, so
`make test` and `make build` compile only what changed
- `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.
+6 -44
View File
@@ -18,54 +18,16 @@ https://git.eeqj.de/sneak/secret/milestone/12
# Completed Steps # Completed Steps
- 2026-10-07: The part of `github.com/tyler-smith/go-bip39` v1.1.0 that `secret`
uses is copied into `internal/bip39`, with upstream's `LICENSE` beside it,
because its repository no longer exists
(https://git.eeqj.de/sneak/secret/issues/122). Every import moved there, and
the module left `go.mod` and `go.sum`. No derived key or mnemonic changes.
- 2026-10-07: The canonical files are re-vendored from `sneak/prompts` commit
`dd4027b` (https://git.eeqj.de/sneak/secret/issues/121), with golangci-lint
v2.14.0 in the lint phase. Lint and test are phases of the `Dockerfile`, and
`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 - 2026-10-06: `make test` in `script/cibuild` no longer compiles the standard
library and every dependency from nothing on every build library and every dependency from nothing on every build
(https://git.eeqj.de/sneak/secret/issues/124). The `Dockerfile` runs it and (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 `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. keeps between builds, locally and on the Gitea runner alike, so each compiles
The mount has an id of its own, so other repositories' builds do not share it. only what changed since the last build. The mount has an id of its own, so
`script/test` passes `-count=1`, so every test runs on every build and no other repositories' builds do not share it. `script/test` passes `-count=1`,
result comes from Go's test cache. A build with an empty cache, such as the so every test runs on every build and no result comes from Go's test cache. A
first after docker's build cache is cleared, compiles everything in build with an empty cache, such as the first after docker's build cache is
`make test` as before. 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 - 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 (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 deriving keys from passphrases with scrypt, which is slow on purpose. The new
+2 -1
View File
@@ -9,7 +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/dustin/go-humanize v1.0.1
github.com/fatih/color v1.18.0 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
@@ -17,6 +17,7 @@ require (
github.com/spf13/afero v1.14.0 github.com/spf13/afero v1.14.0
github.com/spf13/cobra v1.9.1 github.com/spf13/cobra v1.9.1
github.com/stretchr/testify v1.8.4 github.com/stretchr/testify v1.8.4
github.com/tyler-smith/go-bip39 v1.1.0
golang.org/x/crypto v0.38.0 golang.org/x/crypto v0.38.0
golang.org/x/sys v0.33.0 golang.org/x/sys v0.33.0
golang.org/x/term v0.32.0 golang.org/x/term v0.32.0
+4 -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=
@@ -107,6 +107,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc=
github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8=
github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U=
golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
-21
View File
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014-2018 Tyler Smith and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-285
View File
@@ -1,285 +0,0 @@
// Package bip39 is the Golang implementation of the BIP39 spec.
//
// The official BIP39 spec can be found at
// https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
//
// It is a copy of github.com/tyler-smith/go-bip39 v1.1.0, trimmed to what
// secret uses.
//
//nolint:mnd // the numbers are BIP-39's own, written as upstream writes them
package bip39
import (
"crypto/rand"
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
"errors"
"fmt"
"math/big"
"strings"
"golang.org/x/crypto/pbkdf2"
)
var (
// ErrInvalidMnemonic is returned when trying to use a malformed mnemonic.
ErrInvalidMnemonic = errors.New("invalid mnenomic")
// ErrEntropyLengthInvalid is returned when trying to use an entropy set with
// an invalid size.
ErrEntropyLengthInvalid = errors.New(
"entropy length must be [128, 256] and a multiple of 32",
)
// ErrChecksumIncorrect is returned when entropy has the incorrect checksum.
ErrChecksumIncorrect = errors.New("checksum incorrect")
)
// NewEntropy will create random entropy bytes
// so long as the requested size bitSize is an appropriate size.
//
// bitSize has to be a multiple 32 and be within the inclusive range of {128, 256}
func NewEntropy(bitSize int) ([]byte, error) {
err := validateEntropyBitSize(bitSize)
if err != nil {
return nil, err
}
entropy := make([]byte, bitSize/8)
_, err = rand.Read(entropy)
return entropy, err
}
// EntropyFromMnemonic takes a mnemonic generated by this library,
// and returns the input entropy used to generate the given mnemonic.
// An error is returned if the given mnemonic is invalid.
func EntropyFromMnemonic(mnemonic string) ([]byte, error) {
mnemonicSlice, isValid := splitMnemonicWords(mnemonic)
if !isValid {
return nil, ErrInvalidMnemonic
}
// Some bitwise operands for working with big.Ints
shift11BitsMask := big.NewInt(2048)
bigOne := big.NewInt(1)
// used to isolate the checksum bits from the entropy+checksum byte array
wordLengthChecksumMasksMapping := map[int]*big.Int{
12: big.NewInt(15),
15: big.NewInt(31),
18: big.NewInt(63),
21: big.NewInt(127),
24: big.NewInt(255),
}
// used to use only the desired x of 8 available checksum bits.
// 256 bit (word length 24) requires all 8 bits of the checksum,
// and thus no shifting is needed for it (we would get a divByZero crash if we did)
wordLengthChecksumShiftMapping := map[int]*big.Int{
12: big.NewInt(16),
15: big.NewInt(8),
18: big.NewInt(4),
21: big.NewInt(2),
}
// wordMap is a reverse lookup map for the word list
wordMap := map[string]int{}
for i, v := range English() {
wordMap[v] = i
}
// Decode the words into a big.Int.
b := big.NewInt(0)
for _, v := range mnemonicSlice {
index, found := wordMap[v]
if !found {
return nil, fmt.Errorf(
"%w: word `%v` not found in reverse map", ErrInvalidMnemonic, v,
)
}
var wordBytes [2]byte
//nolint:gosec // the index of a word in the list is below 2048
binary.BigEndian.PutUint16(wordBytes[:], uint16(index))
b = b.Mul(b, shift11BitsMask)
b = b.Or(b, big.NewInt(0).SetBytes(wordBytes[:]))
}
// Build and add the checksum to the big.Int.
checksum := big.NewInt(0)
checksumMask := wordLengthChecksumMasksMapping[len(mnemonicSlice)]
checksum = checksum.And(b, checksumMask)
b.Div(b, big.NewInt(0).Add(checksumMask, bigOne))
// The entropy is the underlying bytes of the big.Int. Any upper bytes of
// all 0's are not returned so we pad the beginning of the slice with empty
// bytes if necessary.
entropy := b.Bytes()
entropy = padByteSlice(entropy, len(mnemonicSlice)/3*4)
// Generate the checksum and compare with the one we got from the mneomnic.
entropyChecksumBytes := computeChecksum(entropy)
entropyChecksum := big.NewInt(int64(entropyChecksumBytes[0]))
if l := len(mnemonicSlice); l != 24 {
checksumShift := wordLengthChecksumShiftMapping[l]
entropyChecksum.Div(entropyChecksum, checksumShift)
}
if checksum.Cmp(entropyChecksum) != 0 {
return nil, ErrChecksumIncorrect
}
return entropy, nil
}
// NewMnemonic will return a string consisting of the mnemonic words for
// the given entropy.
// If the provide entropy is invalid, an error will be returned.
func NewMnemonic(entropy []byte) (string, error) {
// Compute some lengths for convenience.
entropyBitLength := len(entropy) * 8
checksumBitLength := entropyBitLength / 32
sentenceLength := (entropyBitLength + checksumBitLength) / 11
// Validate that the requested size is supported.
err := validateEntropyBitSize(entropyBitLength)
if err != nil {
return "", err
}
// Some bitwise operands for working with big.Ints
last11BitsMask := big.NewInt(2047)
shift11BitsMask := big.NewInt(2048)
// wordList is the set of words to use
wordList := English()
// Add checksum to entropy.
entropy = addChecksum(entropy)
// Break entropy up into sentenceLength chunks of 11 bits.
// For each word AND mask the rightmost 11 bits and find the word at that index.
// Then bitshift entropy 11 bits right and repeat.
// Add to the last empty slot so we can work with LSBs instead of MSB.
// Entropy as an int so we can bitmask without worrying about bytes slices.
entropyInt := new(big.Int).SetBytes(entropy)
// Slice to hold words in.
words := make([]string, sentenceLength)
// Throw away big.Int for AND masking.
word := big.NewInt(0)
for i := sentenceLength - 1; i >= 0; i-- {
// Get 11 right most bits and bitshift 11 to the right for next time.
word.And(entropyInt, last11BitsMask)
entropyInt.Div(entropyInt, shift11BitsMask)
// Get the bytes representing the 11 bits as a 2 byte slice.
wordBytes := padByteSlice(word.Bytes(), 2)
// Convert bytes to an index and add that word to the list.
words[i] = wordList[binary.BigEndian.Uint16(wordBytes)]
}
return strings.Join(words, " "), nil
}
// NewSeed creates a hashed seed output given a provided string and password.
// No checking is performed to validate that the string provided is a valid mnemonic.
func NewSeed(mnemonic string, password string) []byte {
return pbkdf2.Key([]byte(mnemonic), []byte("mnemonic"+password), 2048, 64, sha512.New)
}
// IsMnemonicValid attempts to verify that the provided mnemonic is valid.
// Validity is determined by both the number of words being appropriate,
// and that all the words in the mnemonic are present in the word list.
func IsMnemonicValid(mnemonic string) bool {
_, err := EntropyFromMnemonic(mnemonic)
return err == nil
}
// Appends to data the first (len(data) / 32)bits of the result of sha256(data)
// Currently only supports data up to 32 bytes
func addChecksum(data []byte) []byte {
// Some bitwise operands for working with big.Ints
bigOne := big.NewInt(1)
bigTwo := big.NewInt(2)
// Get first byte of sha256
hash := computeChecksum(data)
firstChecksumByte := hash[0]
// len() is in bytes so we divide by 4
checksumBitLength := uint(len(data) / 4)
// For each bit of check sum we want we shift the data one the left
// and then set the (new) right most bit equal to checksum bit at that index
// staring from the left
dataBigInt := new(big.Int).SetBytes(data)
for i := range checksumBitLength {
// Bitshift 1 left
dataBigInt.Mul(dataBigInt, bigTwo)
// Set rightmost bit if leftmost checksum bit is set
if firstChecksumByte&(1<<(7-i)) > 0 {
dataBigInt.Or(dataBigInt, bigOne)
}
}
return dataBigInt.Bytes()
}
func computeChecksum(data []byte) []byte {
hasher := sha256.New()
hasher.Write(data)
return hasher.Sum(nil)
}
// validateEntropyBitSize ensures that entropy is the correct size for being a
// mnemonic.
func validateEntropyBitSize(bitSize int) error {
if (bitSize%32) != 0 || bitSize < 128 || bitSize > 256 {
return ErrEntropyLengthInvalid
}
return nil
}
// padByteSlice returns a byte slice of the given size with contents of the
// given slice left padded and any empty spaces filled with 0's.
func padByteSlice(slice []byte, length int) []byte {
offset := length - len(slice)
if offset <= 0 {
return slice
}
newSlice := make([]byte, length)
copy(newSlice[offset:], slice)
return newSlice
}
func splitMnemonicWords(mnemonic string) ([]string, bool) {
// Create a list of all the words in the mnemonic sentence
words := strings.Fields(mnemonic)
// Get num of words
numOfWords := len(words)
// The number of words should be 12, 15, 18, 21 or 24
if numOfWords%3 != 0 || numOfWords < 12 || numOfWords > 24 {
return nil, false
}
return words, true
}
-456
View File
@@ -1,456 +0,0 @@
package bip39
import (
"encoding/hex"
"testing"
)
type vector struct {
entropy string
mnemonic string
seed string
}
func TestNewMnemonic(t *testing.T) {
t.Parallel()
for _, vector := range testVectors() {
entropy, err := hex.DecodeString(vector.entropy)
assertNil(t, err)
mnemonic, err := NewMnemonic(entropy)
assertNil(t, err)
assertEqualString(t, vector.mnemonic, mnemonic)
seed := NewSeed(mnemonic, "TREZOR")
assertEqualString(t, vector.seed, hex.EncodeToString(seed))
}
}
func TestNewMnemonicInvalidEntropy(t *testing.T) {
t.Parallel()
_, err := NewMnemonic([]byte{})
assertNotNil(t, err)
}
func TestIsMnemonicValid(t *testing.T) {
t.Parallel()
for _, vector := range badMnemonicSentences() {
assertFalse(t, IsMnemonicValid(vector.mnemonic))
}
for _, vector := range testVectors() {
assertTrue(t, IsMnemonicValid(vector.mnemonic))
}
}
func TestNewEntropy(t *testing.T) {
t.Parallel()
// Good tests.
for i := 128; i <= 256; i += 32 {
_, err := NewEntropy(i)
assertNil(t, err)
}
// Bad Values
for i := range 257 {
if i%8 != 0 {
_, err := NewEntropy(i)
assertNotNil(t, err)
}
}
}
func TestPadByteSlice(t *testing.T) {
t.Parallel()
assertEqualByteSlices(t, []byte{0}, padByteSlice([]byte{}, 1))
assertEqualByteSlices(t, []byte{0, 1}, padByteSlice([]byte{1}, 2))
assertEqualByteSlices(t, []byte{1, 1}, padByteSlice([]byte{1, 1}, 2))
assertEqualByteSlices(t, []byte{1, 1, 1}, padByteSlice([]byte{1, 1, 1}, 2))
}
//nolint:funlen // the test vectors, kept as upstream wrote them
func TestMnemonicToByteArrayForZeroLeadingSeeds(t *testing.T) {
t.Parallel()
ms := []string{
"00000000000000000000000000000000",
"00a84c51041d49acca66e6160c1fa999",
"00ca45df1673c76537a2020bfed1dafd",
"0019d5871c7b81fd83d474ef1c1e1dae",
"00dcb021afb35ffcdd1d032d2056fc86",
"0062be7bd09a27288b6cf0eb565ec739",
"00dc705b5efa0adf25b9734226ba60d4",
"0017747418d54c6003fa64fade83374b",
"000d44d3ee7c3dfa45e608c65384431b",
"008241c1ef976b0323061affe5bf24b9",
"00a6aec77e4d16bea80b50a34991aaba",
"0011527b8c6ddecb9d0c20beccdeb58d",
"001c938c503c8f5a2bba2248ff621546",
"0002f90aaf7a8327698f0031b6317c36",
"00bff43071ed7e07f77b14f615993bac",
"00da143e00ef17fc63b6fb22dcc2c326",
"00ffc6764fb32a354cab1a3ddefb015d",
"0062ef47e0985e8953f24760b7598cdd",
"003bf9765064f71d304908d906c065f5",
"00993851503471439d154b3613947474",
"007ad0ffe9eae753a483a76af06dfa67",
"00091824db9ec19e663bee51d64c83cc",
"00f48ac621f7e3cb39b2012ac3121543",
"0072917415cdca24dfa66c4a92c885b4",
"0027ced2b279ea8a91d29364487cdbf4",
"00b9c0d37fb10ba272e55842ad812583",
"004b3d0d2b9285946c687a5350479c8c",
"00c7c12a37d3a7f8c1532b17c89b724c",
"00f400c5545f06ae17ad00f3041e4e26",
"001e290be10df4d209f247ac5878662b",
"00bf0f74568e582a7dd1ee64f792ec8b",
"00d2e43ecde6b72b847db1539ed89e23",
"00cecba6678505bb7bfec8ed307251f6",
"000aeed1a9edcbb4bc88f610d3ce84eb",
"00d06206aadfc25c2b21805d283f15ae",
"00a31789a2ab2d54f8fadd5331010287",
"003493c5f520e8d5c0483e895a121dc9",
"004706112800b76001ece2e268bc830e",
"00ab31e28bb5305be56e38337dbfa486",
"006872fe85df6b0fa945248e6f9379d1",
"00717e5e375da6934e3cfdf57edaf3bd",
"007f1b46e7b9c4c76e77c434b9bccd6b",
"00dc93735aa35def3b9a2ff676560205",
"002cd5dcd881a49c7b87714c6a570a76",
"0013b5af9e13fac87e0c505686cfb6bf",
"007ab1ec9526b0bc04b64ae65fd42631",
"00abb4e11d8385c1cca905a6a65e9144",
"00574fc62a0501ad8afada2e246708c3",
"005207e0a815bb2da6b4c35ec1f2bf52",
"00f3460f136fb9700080099cbd62bc18",
"007a591f204c03ca7b93981237112526",
"00cfe0befd428f8e5f83a5bfc801472e",
"00987551ac7a879bf0c09b8bc474d9af",
"00cadd3ce3d78e49fbc933a85682df3f",
"00bfbf2e346c855ccc360d03281455a1",
"004cdf55d429d028f715544ce22d4f31",
"0075c84a7d15e0ac85e1e41025eed23b",
"00807dddd61f71725d336cab844d2cb5",
"00422f21b77fe20e367467ed98c18410",
"00b44d0ac622907119c626c850a462fd",
"00363f5e7f22fc49f3cd662a28956563",
"000fe5837e68397bbf58db9f221bdc4e",
"0056af33835c888ef0c22599686445d3",
"00790a8647fd3dfb38b7e2b6f578f2c6",
"00da8d9009675cb7beec930e263014fb",
"00d4b384540a5bb54aa760edaa4fb2fe",
"00be9b1479ed680fdd5d91a41eb926d0",
"009182347502af97077c40a6e74b4b5c",
"00f5c90ee1c67fa77fd821f8e9fab4f1",
"005568f9a2dd6b0c0cc2f5ba3d9cac38",
"008b481f8678577d9cf6aa3f6cd6056b",
"00c4323ece5e4fe3b6cd4c5c932931af",
"009791f7550c3798c5a214cb2d0ea773",
"008a7baab22481f0ad8167dd9f90d55c",
"00f0e601519aafdc8ff94975e64c946d",
"0083b61e0daa9219df59d697c270cd31",
}
for _, m := range ms {
seed, _ := hex.DecodeString(m)
mnemonic, err := NewMnemonic(seed)
if err != nil {
t.Errorf("%v", err)
}
_, err = EntropyFromMnemonic(mnemonic)
if err != nil {
t.Errorf("Failed for %x - %v", seed, mnemonic)
}
}
}
func TestEntropyFromMnemonic128(t *testing.T) {
t.Parallel()
testEntropyFromMnemonic(t, 128)
}
func TestEntropyFromMnemonic160(t *testing.T) {
t.Parallel()
testEntropyFromMnemonic(t, 160)
}
func TestEntropyFromMnemonic192(t *testing.T) {
t.Parallel()
testEntropyFromMnemonic(t, 192)
}
func TestEntropyFromMnemonic224(t *testing.T) {
t.Parallel()
testEntropyFromMnemonic(t, 224)
}
func TestEntropyFromMnemonic256(t *testing.T) {
t.Parallel()
testEntropyFromMnemonic(t, 256)
}
//nolint:dupword,lll // the test vector, kept as upstream wrote it
func TestEntropyFromMnemonicInvalidChecksum(t *testing.T) {
t.Parallel()
_, err := EntropyFromMnemonic("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon yellow")
assertEqual(t, ErrChecksumIncorrect, err)
}
//nolint:dupword // the test vectors, kept as upstream wrote them
func TestEntropyFromMnemonicInvalidMnemonicSize(t *testing.T) {
t.Parallel()
for _, mnemonic := range []string{
"a a a a a a a a a a a a a a a a a a a a a a a a a", // Too many words
"a", // Too few
"a a a a a a a a a a a a a a", // Not multiple of 3
} {
_, err := EntropyFromMnemonic(mnemonic)
assertEqual(t, ErrInvalidMnemonic, err)
}
}
func testEntropyFromMnemonic(t *testing.T, bitSize int) {
t.Helper()
for range 512 {
expectedEntropy, err := NewEntropy(bitSize)
assertNil(t, err)
assertTrue(t, len(expectedEntropy) != 0)
mnemonic, err := NewMnemonic(expectedEntropy)
assertNil(t, err)
assertTrue(t, len(mnemonic) != 0)
actualEntropy, err := EntropyFromMnemonic(mnemonic)
assertNil(t, err)
assertEqualByteSlices(t, expectedEntropy, actualEntropy)
}
}
//nolint:dupword,funlen,lll // the BIP-39 test vectors, kept as upstream wrote them
func testVectors() []vector {
return []vector{
{
entropy: "00000000000000000000000000000000",
mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
seed: "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04",
},
{
entropy: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
mnemonic: "legal winner thank year wave sausage worth useful legal winner thank yellow",
seed: "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607",
},
{
entropy: "80808080808080808080808080808080",
mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice cage above",
seed: "d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f12eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8",
},
{
entropy: "ffffffffffffffffffffffffffffffff",
mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong",
seed: "ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a13332572917f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069",
},
{
entropy: "000000000000000000000000000000000000000000000000",
mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent",
seed: "035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9a565181599b79f53b844d8a71dd9f439c52a3d7b3e8a79c906ac845fa",
},
{
entropy: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
mnemonic: "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will",
seed: "f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c392d168748f2d4a612bada0753b52a1c7ac53c1e93abd5c6320b9e95dd",
},
{
entropy: "808080808080808080808080808080808080808080808080",
mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always",
seed: "107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913ffb796f841c49b1d33b610cf0e91d3aa239027f5e99fe4ce9e5088cd65",
},
{
entropy: "ffffffffffffffffffffffffffffffffffffffffffffffff",
mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when",
seed: "0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43348d952e2265b4cd129090758b3e3c2c49103b5051aac2eaeb890a528",
},
{
entropy: "0000000000000000000000000000000000000000000000000000000000000000",
mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art",
seed: "bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8",
},
{
entropy: "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f",
mnemonic: "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title",
seed: "bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146ad717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87",
},
{
entropy: "8080808080808080808080808080808080808080808080808080808080808080",
mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless",
seed: "c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61af0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f",
},
{
entropy: "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote",
seed: "dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad",
},
{
entropy: "77c2b00716cec7213839159e404db50d",
mnemonic: "jelly better achieve collect unaware mountain thought cargo oxygen act hood bridge",
seed: "b5b6d0127db1a9d2226af0c3346031d77af31e918dba64287a1b44b8ebf63cdd52676f672a290aae502472cf2d602c051f3e6f18055e84e4c43897fc4e51a6ff",
},
{
entropy: "b63a9c59a6e641f288ebc103017f1da9f8290b3da6bdef7b",
mnemonic: "renew stay biology evidence goat welcome casual join adapt armor shuffle fault little machine walk stumble urge swap",
seed: "9248d83e06f4cd98debf5b6f010542760df925ce46cf38a1bdb4e4de7d21f5c39366941c69e1bdbf2966e0f6e6dbece898a0e2f0a4c2b3e640953dfe8b7bbdc5",
},
{
entropy: "3e141609b97933b66a060dcddc71fad1d91677db872031e85f4c015c5e7e8982",
mnemonic: "dignity pass list indicate nasty swamp pool script soccer toe leaf photo multiply desk host tomato cradle drill spread actor shine dismiss champion exotic",
seed: "ff7f3184df8696d8bef94b6c03114dbee0ef89ff938712301d27ed8336ca89ef9635da20af07d4175f2bf5f3de130f39c9d9e8dd0472489c19b1a020a940da67",
},
{
entropy: "0460ef47585604c5660618db2e6a7e7f",
mnemonic: "afford alter spike radar gate glance object seek swamp infant panel yellow",
seed: "65f93a9f36b6c85cbe634ffc1f99f2b82cbb10b31edc7f087b4f6cb9e976e9faf76ff41f8f27c99afdf38f7a303ba1136ee48a4c1e7fcd3dba7aa876113a36e4",
},
{
entropy: "72f60ebac5dd8add8d2a25a797102c3ce21bc029c200076f",
mnemonic: "indicate race push merry suffer human cruise dwarf pole review arch keep canvas theme poem divorce alter left",
seed: "3bbf9daa0dfad8229786ace5ddb4e00fa98a044ae4c4975ffd5e094dba9e0bb289349dbe2091761f30f382d4e35c4a670ee8ab50758d2c55881be69e327117ba",
},
{
entropy: "2c85efc7f24ee4573d2b81a6ec66cee209b2dcbd09d8eddc51e0215b0b68e416",
mnemonic: "clutch control vehicle tonight unusual clog visa ice plunge glimpse recipe series open hour vintage deposit universe tip job dress radar refuse motion taste",
seed: "fe908f96f46668b2d5b37d82f558c77ed0d69dd0e7e043a5b0511c48c2f1064694a956f86360c93dd04052a8899497ce9e985ebe0c8c52b955e6ae86d4ff4449",
},
{
entropy: "eaebabb2383351fd31d703840b32e9e2",
mnemonic: "turtle front uncle idea crush write shrug there lottery flower risk shell",
seed: "bdfb76a0759f301b0b899a1e3985227e53b3f51e67e3f2a65363caedf3e32fde42a66c404f18d7b05818c95ef3ca1e5146646856c461c073169467511680876c",
},
{
entropy: "7ac45cfe7722ee6c7ba84fbc2d5bd61b45cb2fe5eb65aa78",
mnemonic: "kiss carry display unusual confirm curtain upgrade antique rotate hello void custom frequent obey nut hole price segment",
seed: "ed56ff6c833c07982eb7119a8f48fd363c4a9b1601cd2de736b01045c5eb8ab4f57b079403485d1c4924f0790dc10a971763337cb9f9c62226f64fff26397c79",
},
{
entropy: "4fa1a8bc3e6d80ee1316050e862c1812031493212b7ec3f3bb1b08f168cabeef",
mnemonic: "exile ask congress lamp submit jacket era scheme attend cousin alcohol catch course end lucky hurt sentence oven short ball bird grab wing top",
seed: "095ee6f817b4c2cb30a5a797360a81a40ab0f9a4e25ecd672a3f58a0b5ba0687c096a6b14d2c0deb3bdefce4f61d01ae07417d502429352e27695163f7447a8c",
},
{
entropy: "18ab19a9f54a9274f03e5209a2ac8a91",
mnemonic: "board flee heavy tunnel powder denial science ski answer betray cargo cat",
seed: "6eff1bb21562918509c73cb990260db07c0ce34ff0e3cc4a8cb3276129fbcb300bddfe005831350efd633909f476c45c88253276d9fd0df6ef48609e8bb7dca8",
},
{
entropy: "18a2e1d81b8ecfb2a333adcb0c17a5b9eb76cc5d05db91a4",
mnemonic: "board blade invite damage undo sun mimic interest slam gaze truly inherit resist great inject rocket museum chief",
seed: "f84521c777a13b61564234bf8f8b62b3afce27fc4062b51bb5e62bdfecb23864ee6ecf07c1d5a97c0834307c5c852d8ceb88e7c97923c0a3b496bedd4e5f88a9",
},
{
entropy: "15da872c95a13dd738fbf50e427583ad61f18fd99f628c417a61cf8343c90419",
mnemonic: "beyond stage sleep clip because twist token leaf atom beauty genius food business side grid unable middle armed observe pair crouch tonight away coconut",
seed: "b15509eaa2d09d3efd3e006ef42151b30367dc6e3aa5e44caba3fe4d3e352e65101fbdb86a96776b91946ff06f8eac594dc6ee1d3e82a42dfe1b40fef6bcc3fd",
},
}
}
//nolint:dupword,lll // the test vectors, kept as upstream wrote them
func badMnemonicSentences() []vector {
return []vector{
{mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon"},
{mnemonic: "legal winner thank year wave sausage worth useful legal winner thank yellow yellow"},
{mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice caged above"},
{mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo, wrong"},
{mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon"},
{mnemonic: "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will will will"},
{mnemonic: "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always."},
{mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo why"},
{mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art art"},
{mnemonic: "legal winner thank year wave sausage worth useful legal winner thanks year wave worth useful legal winner thank year wave sausage worth title"},
{mnemonic: "letter advice cage absurd amount doctor acoustic avoid letters advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless"},
{mnemonic: "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo voted"},
{mnemonic: "jello better achieve collect unaware mountain thought cargo oxygen act hood bridge"},
{mnemonic: "renew, stay, biology, evidence, goat, welcome, casual, join, adapt, armor, shuffle, fault, little, machine, walk, stumble, urge, swap"},
{mnemonic: "dignity pass list indicate nasty"},
// From issue 32
{mnemonic: "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon letter"},
}
}
func assertNil(t *testing.T, object any) {
t.Helper()
if object != nil {
t.Errorf("Expected nil, got %v", object)
}
}
func assertNotNil(t *testing.T, object any) {
t.Helper()
if object == nil {
t.Error("Expected not nil")
}
}
func assertTrue(t *testing.T, a bool) {
t.Helper()
if !a {
t.Error("Expected true, got false")
}
}
func assertFalse(t *testing.T, a bool) {
t.Helper()
if a {
t.Error("Expected false, got true")
}
}
func assertEqual(t *testing.T, a, b any) {
t.Helper()
if a != b {
t.Errorf("Objects not equal, expected `%s` and got `%s`", a, b)
}
}
func assertEqualString(t *testing.T, a, b string) {
t.Helper()
if a != b {
t.Errorf("Strings not equal, expected `%s` and got `%s`", a, b)
}
}
func assertEqualByteSlices(t *testing.T, a, b []byte) {
t.Helper()
if len(a) != len(b) {
t.Errorf("Byte slices not equal, expected %v and got %v", a, b)
return
}
for i := range a {
if a[i] != b[i] {
t.Errorf("Byte slices not equal, expected %v and got %v", a, b)
return
}
}
}
File diff suppressed because it is too large Load Diff
-19
View File
@@ -1,19 +0,0 @@
package bip39
import (
"hash/crc32"
"testing"
)
func TestEnglishChecksum(t *testing.T) {
t.Parallel()
// Ensure word list is correct
// $ wget https://raw.githubusercontent.com/bitcoin/bips/master/bip-0039/english.txt
// $ crc32 english.txt
// c1dbd296
checksum := crc32.ChecksumIEEE([]byte(english))
if checksum != 0xc1dbd296 {
t.Error("english checksum invalid")
}
}
-30
View File
@@ -1,30 +0,0 @@
package bip39_test
import (
"encoding/hex"
"fmt"
"sneak.berlin/go/secret/internal/bip39"
)
//nolint:lll // the test vector and its output, kept as upstream wrote them
func ExampleNewMnemonic() {
// the entropy can be any byte slice, generated how pleased,
// as long its bit size is a multiple of 32 and is within
// the inclusive range of {128,256}
entropy, _ := hex.DecodeString("066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad")
// generate a mnemomic
mnemomic, _ := bip39.NewMnemonic(entropy)
fmt.Println(mnemomic)
// output:
// all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform
}
//nolint:lll // the test vector and its output, kept as upstream wrote them
func ExampleNewSeed() {
seed := bip39.NewSeed("all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform", "TREZOR")
fmt.Println(hex.EncodeToString(seed))
// output:
// 26e975ec644423f4a4c4f4215ef09b4bd7ef924e85d1d17c4cf3f136c2863cf6df0a475045652c57eb5fb41513ca2a2d67722b77e954b4b3fc11f7590449191d
}
+2 -1
View File
@@ -8,6 +8,7 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
"time"
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@@ -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("../..")
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sneak.berlin/go/secret/internal/bip39" "github.com/tyler-smith/go-bip39"
"sneak.berlin/go/secret/internal/vault" "sneak.berlin/go/secret/internal/vault"
) )
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"github.com/awnumar/memguard" "github.com/awnumar/memguard"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"sneak.berlin/go/secret/internal/bip39" "github.com/tyler-smith/go-bip39"
"sneak.berlin/go/secret/internal/secret" "sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault" "sneak.berlin/go/secret/internal/vault"
) )
+7 -33
View File
@@ -32,12 +32,6 @@ 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.
@@ -2589,7 +2583,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 +2601,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 +2609,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 +2619,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 +2628,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 +2640,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 +2650,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 +2667,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)
} }
+1 -1
View File
@@ -13,7 +13,7 @@ import (
"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/bip39" "github.com/tyler-smith/go-bip39"
"sneak.berlin/go/secret/internal/secret" "sneak.berlin/go/secret/internal/secret"
"sneak.berlin/go/secret/internal/vault" "sneak.berlin/go/secret/internal/vault"
"sneak.berlin/go/secret/pkg/agehd" "sneak.berlin/go/secret/pkg/agehd"
+2 -2
View File
@@ -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()
+1 -1
View File
@@ -17,7 +17,7 @@ import (
"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"
"sneak.berlin/go/secret/internal/bip39" "github.com/tyler-smith/go-bip39"
"sneak.berlin/go/secret/pkg/bip85" "sneak.berlin/go/secret/pkg/bip85"
) )
+1 -1
View File
@@ -11,7 +11,7 @@ import (
"testing" "testing"
"filippo.io/age" "filippo.io/age"
"sneak.berlin/go/secret/internal/bip39" "github.com/tyler-smith/go-bip39"
) )
//nolint:dupword // BIP39 test mnemonics repeat words by design //nolint:dupword // BIP39 test mnemonics repeat words by design
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"testing" "testing"
"github.com/btcsuite/btcd/btcutil/hdkeychain" "github.com/btcsuite/btcd/btcutil/hdkeychain"
"sneak.berlin/go/secret/internal/bip39" "github.com/tyler-smith/go-bip39"
"sneak.berlin/go/secret/pkg/bip85" "sneak.berlin/go/secret/pkg/bip85"
) )
+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"
} }
+12 -19
View File
@@ -1,28 +1,21 @@
#!/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 lifts the limit
# --no-cache for the same reason as script/docker: the gate phases the # on memory the tests lock (memguard mlocks secrets); they also pass under
# final stage depends on are RUN steps, and a cached one is a check that # the lower limit of a plain `docker build .`.
# 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, module downloads and the Go build cache that make test and make
# build use 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 "$@"
+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 "$@"
+8 -10
View File
@@ -1,19 +1,17 @@
#!/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 ./...
# -count=1: run every test, never take a result from Go's test cache,
# which the Dockerfile keeps between builds
go test -count=1 ./... || go test -count=1 -v ./...
} }
main "$@" main "$@"