Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd6c5df1a8 | ||
|
|
2d6675a452 | ||
|
|
ef0ae90768 | ||
|
|
2c6fe7c368 | ||
|
|
ed6af50ea5 |
+68
-19
@@ -1,29 +1,78 @@
|
|||||||
|
# .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.
|
||||||
.git/config
|
# Each submodule keeps a config with the same exposure in its git directory
|
||||||
|
# under .git/modules/, nested again for a submodule's own submodules, or in
|
||||||
|
# its own .git directory when it keeps one.
|
||||||
|
# KNOWN GAP: a submodule whose name has a `config` segment (`config`,
|
||||||
|
# `deploy/config`, `config/lib`) loses its whole git directory, because
|
||||||
|
# `**/.git/modules/**/config` also matches that segment's directory
|
||||||
|
# under .git/modules/. Go's version stamping then fails the build;
|
||||||
|
# nothing leaks. Name such a submodule without that segment:
|
||||||
|
# `git submodule add --name`.
|
||||||
|
**/.git/config
|
||||||
|
**/.git/modules/**/config
|
||||||
|
|
||||||
# Build artifacts
|
# Agent scratch: one full checkout of the repo per in-flight agent.
|
||||||
secret
|
# Anchored because it occurs once where agents run at the repo root.
|
||||||
coverage.out
|
# KNOWN GAP: a repo running agents in subdirectories still ships
|
||||||
*.test
|
# `services/api/.claude/` and must add its own anchored entry.
|
||||||
|
.claude
|
||||||
|
|
||||||
# IDE and editor files
|
# Environment files. `*.env` covers bare `.env` and the `prod.env`
|
||||||
.vscode
|
# convention. Re-include a committed template with a negation if the
|
||||||
.idea
|
# build needs one: `!docs/example.env`.
|
||||||
*.swp
|
**/*.[eE][nN][vV]
|
||||||
*.swo
|
**/.[eE][nN][vV].*
|
||||||
*~
|
**/.[eE][nN][vV][rR][cC]
|
||||||
|
|
||||||
# Dependencies
|
# Private keys and the bundles carrying them. Public certificates
|
||||||
node_modules
|
# (*.crt, *.cer) are deliberately absent: they are legitimate inputs.
|
||||||
|
**/*.[pP][eE][mM]
|
||||||
|
**/*.[kK][eE][yY]
|
||||||
|
**/*.[pP]12
|
||||||
|
**/*.[pP][fF][xX]
|
||||||
|
**/[iI][dD]_[rR][sS][aA]
|
||||||
|
**/[iI][dD]_[dD][sS][aA]
|
||||||
|
**/[iI][dD]_[eE][cC][dD][sS][aA]
|
||||||
|
**/[iI][dD]_[eE][cC][dD][sS][aA]_[sS][kK]
|
||||||
|
**/[iI][dD]_[eE][dD]25519
|
||||||
|
**/[iI][dD]_[eE][dD]25519_[sS][kK]
|
||||||
|
|
||||||
# macOS
|
# Dependencies: restored inside the image, never copied in.
|
||||||
.DS_Store
|
**/node_modules
|
||||||
|
|
||||||
# Claude files
|
# OS metadata.
|
||||||
.claude/
|
**/.DS_Store
|
||||||
|
**/Thumbs.db
|
||||||
|
|
||||||
# Local settings
|
# Editor state: never a build input, and it churns COPY.
|
||||||
.claude/settings.local.json
|
**/*.swp
|
||||||
|
**/*.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
|
||||||
|
|||||||
@@ -10,3 +10,6 @@ insert_final_newline = true
|
|||||||
|
|
||||||
[Makefile]
|
[Makefile]
|
||||||
indent_style = tab
|
indent_style = tab
|
||||||
|
|
||||||
|
[*.go]
|
||||||
|
indent_style = tab
|
||||||
|
|||||||
@@ -4,6 +4,6 @@ jobs:
|
|||||||
check:
|
check:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
# actions/checkout v4.2.2, 2026-02-28
|
# actions/checkout v4.2.2, 2026-02-22
|
||||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||||
- run: script/cibuild
|
- run: script/cibuild
|
||||||
|
|||||||
+29
-9
@@ -20,15 +20,35 @@ Thumbs.db
|
|||||||
# Node
|
# Node
|
||||||
node_modules/
|
node_modules/
|
||||||
|
|
||||||
# Environment / secrets
|
# Secrets. Unanchored like every entry above, so each matches at every
|
||||||
.env
|
# depth. Matching is case-sensitive on Linux, so names use character
|
||||||
.env.*
|
# ranges rather than a lowercase form that misses `Server.Key`.
|
||||||
*.pem
|
|
||||||
*.key
|
|
||||||
|
|
||||||
# This repo. /secret is the built binary, anchored so that it does not
|
# Environment files. `*.env` covers bare `.env` and the `prod.env`
|
||||||
# also match the internal/secret/ package directory.
|
# convention. Only the templates `example.env` and `sample.env` are
|
||||||
/secret
|
# 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
|
*.log
|
||||||
|
*.out
|
||||||
*.test
|
*.test
|
||||||
settings.local.json
|
/secret
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ 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
|
||||||
|
|||||||
@@ -100,6 +100,18 @@ 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
|
||||||
@@ -154,10 +166,17 @@ 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. Fix
|
4. **Never modify linter config** (`.golangci.yml`) to suppress findings, and do
|
||||||
the code.
|
not modify it at all unless specifically instructed. Fix 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`.**
|
||||||
|
|||||||
@@ -1,93 +0,0 @@
|
|||||||
# 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.
|
|
||||||
+53
-63
@@ -1,86 +1,76 @@
|
|||||||
# node and yarn, copied into the lint stage for prettier, which checks the
|
# Lint phase. The linter is invoked directly rather than through `make
|
||||||
# markdown formatting: node of the version script/bootstrap pins, built on
|
# lint` or `script/lint`, which are themselves a docker build.
|
||||||
# Debian as the lint stage's image is.
|
# golangci/golangci-lint:v2.14.0 (Debian-based), 2026-09-24
|
||||||
# node:22.17.0-bookworm-slim, 2025-07-08
|
FROM golangci/golangci-lint@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f AS lint
|
||||||
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 script/ script/
|
COPY go.mod go.sum ./
|
||||||
COPY go.mod go.sum package.json yarn.lock ./
|
RUN go mod download
|
||||||
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.
|
||||||
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 ./...
|
||||||
|
|
||||||
# Build stage — tests and compilation
|
# Test phase. -race needs cgo and so a C compiler, which the Debian Go
|
||||||
# golang 1.24.13-alpine (2026-03-10)
|
# image ships and the alpine one does not.
|
||||||
FROM golang@sha256:8bee1901f1e530bfb4a7850aa7a479d17ae3a18beb6e09064ed54cfd245b7191 AS builder
|
# golang:1.24.13-trixie, 2026-02-04
|
||||||
|
FROM golang@sha256:5835f052b784aa39f2fe9070def3568605c8bc3fcd810f10402066348b61e716 AS test
|
||||||
# Force BuildKit to run the lint stage
|
ENV CGO_ENABLED=1
|
||||||
COPY --from=lint /src/go.sum /dev/null
|
WORKDIR /src
|
||||||
|
|
||||||
RUN apk add --no-cache gcc musl-dev make git gnupg
|
|
||||||
|
|
||||||
WORKDIR /build
|
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
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; }
|
||||||
|
|
||||||
# As in the lint stage: the RUN steps below run again on each script/cibuild.
|
# Build stage. Nothing is wanted from either phase above; the copies are
|
||||||
ARG CHECK_EPOCH
|
# 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
|
||||||
|
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
|
||||||
|
# A tar-stream context keeps the sender's file owners, which git refuses.
|
||||||
|
RUN git config --system --add safe.directory /src
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# This cache mount keeps Go's build cache between builds for make test and
|
# The VERSION build arg when one is given, otherwise
|
||||||
# make build; -count=1 in script/test keeps test results out of it. Go's cache
|
# `git describe --tags --always` on the .git in the build context. With
|
||||||
# does not notice C header changes, so the mount has its own id: change the id
|
# .git present, a version that is still empty, dev or unknown fails the
|
||||||
# when the C packages installed above change.
|
# build: git is missing or could not read the checkout.
|
||||||
RUN --mount=type=cache,id=sneak/secret/go-build,target=/root/.cache/go-build \
|
|
||||||
make test
|
|
||||||
|
|
||||||
# The version stamped into the binary: the VERSION build argument when one
|
|
||||||
# is given, otherwise `git describe --tags --always` of the .git the build
|
|
||||||
# context carries: the tag on a tagged commit, tag-N-gHASH on a commit after
|
|
||||||
# one, the short commit when no tag is reachable. A context that carries .git
|
|
||||||
# and still yields no version fails the build.
|
|
||||||
ARG VERSION
|
ARG VERSION
|
||||||
RUN --mount=type=cache,id=sneak/secret/go-build,target=/root/.cache/go-build \
|
RUN VERSION="${VERSION:-$(git describe --tags --always)}"; \
|
||||||
version="${VERSION:-$(git describe --tags --always)}"; \
|
if [ -e .git ]; then \
|
||||||
if [ -e .git ] && { [ -z "$version" ] || [ "$version" = dev ] || \
|
case "$VERSION" in ""|dev|unknown) \
|
||||||
[ "$version" = unknown ]; }; then \
|
echo "version is '$VERSION' although .git is present" >&2; \
|
||||||
echo "no version could be derived although the build context carries .git" >&2; \
|
exit 1 ;; \
|
||||||
exit 1; \
|
esac; \
|
||||||
fi; \
|
fi; \
|
||||||
make build VERSION="${version:-dev}"
|
make build VERSION="${VERSION:-dev}"
|
||||||
|
|
||||||
# Runtime stage
|
# Runtime stage, and the last one
|
||||||
# alpine 3.23 (2026-03-10)
|
# 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 /build/secret /usr/local/bin/secret
|
COPY --from=builder /src/secret /usr/local/bin/secret
|
||||||
RUN chmod +x /usr/local/bin/secret
|
RUN chmod +x /usr/local/bin/secret
|
||||||
|
|
||||||
USER secret
|
USER secret
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
# 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 ./...
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
export CGO_ENABLED=1
|
export CGO_ENABLED=1
|
||||||
|
|
||||||
.PHONY: default bootstrap setup build test lint lint-darwin fmt fmt-check \
|
.PHONY: default bootstrap setup build test lint fmt fmt-check check docker \
|
||||||
check docker docker-run clean install hooks
|
docker-run clean install hooks
|
||||||
|
|
||||||
default: check
|
default: check
|
||||||
|
|
||||||
@@ -21,13 +21,10 @@ 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
|
||||||
|
|
||||||
|
|||||||
@@ -223,8 +223,6 @@ Creates a new unlocker of the specified type:
|
|||||||
|
|
||||||
- `passphrase`: Traditional passphrase-protected unlocker
|
- `passphrase`: Traditional passphrase-protected unlocker
|
||||||
- `pgp`: Uses an existing GPG key for encryption/decryption
|
- `pgp`: Uses an existing GPG key for encryption/decryption
|
||||||
- `keychain`: macOS Keychain integration (macOS only)
|
|
||||||
- `secure-enclave`: Hardware-backed Secure Enclave protection (macOS only)
|
|
||||||
|
|
||||||
**Options:**
|
**Options:**
|
||||||
|
|
||||||
@@ -345,21 +343,6 @@ Unlockers provide different authentication methods to access the long-term keys:
|
|||||||
- Leverages existing key management workflows
|
- Leverages existing key management workflows
|
||||||
- Strong authentication through GPG
|
- Strong authentication through GPG
|
||||||
|
|
||||||
3. **Keychain Unlockers** (macOS only):
|
|
||||||
- Stores unlock keys in macOS Keychain
|
|
||||||
- Kept on this Mac only: the keychain item is never synced to other devices
|
|
||||||
- Automatic unlocking when Keychain is unlocked
|
|
||||||
- Cross-application integration
|
|
||||||
|
|
||||||
4. **Secure Enclave Unlockers** (macOS):
|
|
||||||
- Hardware-backed key storage using Apple Secure Enclave
|
|
||||||
- Uses `sc_auth` / CryptoTokenKit for SE key management (no Apple Developer
|
|
||||||
Program required)
|
|
||||||
- ECIES encryption: the vault long-term key is encrypted directly to the SE
|
|
||||||
key, and only the SE can decrypt it
|
|
||||||
- The SE key cannot leave this Mac; using it asks for no Touch ID or
|
|
||||||
password
|
|
||||||
|
|
||||||
Each vault maintains its own set of unlockers and one long-term key. The
|
Each vault maintains its own set of unlockers and one long-term key. The
|
||||||
long-term key is encrypted to each unlocker, allowing any authorized unlocker to
|
long-term key is encrypted to each unlocker, allowing any authorized unlocker to
|
||||||
access vault secrets.
|
access vault secrets.
|
||||||
@@ -412,9 +395,6 @@ variables.
|
|||||||
### Hardware Integration
|
### Hardware Integration
|
||||||
|
|
||||||
- Hardware token support via PGP/GPG integration
|
- Hardware token support via PGP/GPG integration
|
||||||
- macOS Keychain integration for system-level security
|
|
||||||
- Secure Enclave integration for hardware-backed key protection (macOS, via
|
|
||||||
`sc_auth` / CryptoTokenKit)
|
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
@@ -468,8 +448,6 @@ secret vault remove personal --force
|
|||||||
# Add multiple unlock methods
|
# Add multiple unlock methods
|
||||||
secret unlocker add passphrase # Password-based
|
secret unlocker add passphrase # Password-based
|
||||||
secret unlocker add pgp --keyid ABCD1234 # GPG key
|
secret unlocker add pgp --keyid ABCD1234 # GPG key
|
||||||
secret unlocker add keychain # macOS Keychain (macOS only)
|
|
||||||
secret unlocker add secure-enclave # macOS Secure Enclave (macOS only)
|
|
||||||
|
|
||||||
# List unlockers
|
# List unlockers
|
||||||
secret unlocker list
|
secret unlocker list
|
||||||
@@ -538,12 +516,8 @@ secret decrypt encryption/mykey --input document.txt.age --output document.txt
|
|||||||
|
|
||||||
### Cross-Platform Support
|
### Cross-Platform Support
|
||||||
|
|
||||||
- **macOS**: Full support including Keychain and Secure Enclave integration
|
- **macOS**: Full support
|
||||||
- **Linux**: Full support (excluding macOS-specific features)
|
- **Linux**: Full support
|
||||||
|
|
||||||
The keychain and Secure Enclave unlockers need a macOS build with cgo. A macOS
|
|
||||||
build without cgo, such as one cross-compiled from Linux, offers them but fails
|
|
||||||
to add or use them.
|
|
||||||
|
|
||||||
## Security Considerations
|
## Security Considerations
|
||||||
|
|
||||||
@@ -556,7 +530,7 @@ to add or use them.
|
|||||||
### Best Practices
|
### Best Practices
|
||||||
|
|
||||||
1. Use strong, unique passphrases for unlockers
|
1. Use strong, unique passphrases for unlockers
|
||||||
2. Enable hardware authentication (Keychain, hardware tokens) when available
|
2. Enable hardware authentication (hardware tokens) when available
|
||||||
3. Regularly audit unlockers and remove unused ones
|
3. Regularly audit unlockers and remove unused ones
|
||||||
4. Keep mnemonic phrases securely backed up offline
|
4. Keep mnemonic phrases securely backed up offline
|
||||||
5. Use separate vaults for different security contexts
|
5. Use separate vaults for different security contexts
|
||||||
@@ -565,7 +539,6 @@ to add or use them.
|
|||||||
|
|
||||||
- Requires access to unlockers for secret retrieval
|
- Requires access to unlockers for secret retrieval
|
||||||
- Mnemonic phrases must be securely stored and backed up
|
- Mnemonic phrases must be securely stored and backed up
|
||||||
- Hardware features limited to supported platforms
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
@@ -604,31 +577,21 @@ 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` — run `go vet`, then the test suite with the race detector, a
|
- `script/test` — build the `test` phase of the `Dockerfile`, which runs the
|
||||||
30-second timeout per package and coverage, every test on every run, never a
|
test suite with the race detector, a 90-second timeout and coverage; on
|
||||||
result from Go's test cache; on failure it reruns the tests verbosely for the
|
failure it reruns the tests verbosely for the details and fails even when the
|
||||||
details and fails even when the rerun passes
|
rerun passes
|
||||||
- `script/lint` — run `golangci-lint` in docker only: builds `Dockerfile.lint`,
|
- `script/lint` — build the `lint` phase of the `Dockerfile`, which runs
|
||||||
where the linter is a build step that runs on every call, also on an unchanged
|
`go vet` and `golangci-lint`, then both again on the code as a macOS build
|
||||||
tree
|
compiles it (`GOOS=darwin`, with cgo off), which a Linux build never compiles
|
||||||
- `script/lint-darwin` — run `go vet` and `golangci-lint` in docker on the code
|
|
||||||
as a macOS build compiles it (`GOOS=darwin`), which a Linux build never
|
|
||||||
compiles; cgo is off, so the keychain unlocker's calls into the keychain
|
|
||||||
(`internal/secret/keychainunlocker_cgo.go`, and `keychainunlocker_test.go`)
|
|
||||||
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; the
|
- `script/fmt-check` — check the same formatting without writing, on the host
|
||||||
`Dockerfile` lint stage runs it, so an unformatted Go or markdown file fails
|
- `script/check` — run `script/test`, `script/lint` and `script/fmt-check`
|
||||||
the build
|
- `script/docker` — build the Docker image tagged with the project name; the
|
||||||
- `script/check` — run `script/test`, `script/lint`, `script/lint-darwin`, and
|
build runs the `lint` and `test` phases first
|
||||||
`script/fmt-check`
|
- `script/cibuild` — CI entrypoint: runs `script/bootstrap`, `script/check`,
|
||||||
- `script/docker` — build the Docker image tagged with the project name
|
then builds the image as `script/docker` does
|
||||||
- `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
|
||||||
@@ -636,8 +599,7 @@ provide:
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Multiple Authentication Methods**: Supports passphrase, PGP, macOS Keychain,
|
- **Multiple Authentication Methods**: Supports passphrase and PGP unlockers
|
||||||
and Secure Enclave unlockers
|
|
||||||
- **Vault Isolation**: Complete separation between different vaults
|
- **Vault Isolation**: Complete separation between different vaults
|
||||||
- **Per-Secret Encryption**: Each secret has its own encryption key
|
- **Per-Secret Encryption**: Each secret has its own encryption key
|
||||||
- **BIP39 Mnemonic Support**: Keyless operation using mnemonic phrases
|
- **BIP39 Mnemonic Support**: Keyless operation using mnemonic phrases
|
||||||
|
|||||||
+357
-86
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
title: Repository Policies
|
title: Repository Policies
|
||||||
last_modified: 2026-07-06
|
last_modified: 2026-10-04
|
||||||
---
|
---
|
||||||
|
|
||||||
This document covers repository structure, tooling, and workflow standards. Code
|
This document covers repository structure, tooling, and workflow standards. Code
|
||||||
@@ -60,17 +60,28 @@ style conventions are in separate documents:
|
|||||||
prerequisite since nvm requires bash. yarn is then pinned via
|
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 and runs `docker build .`; the Gitea workflow calls it. Four further
|
repo root, runs `script/bootstrap`, runs `script/check`, and builds the image
|
||||||
scripts are our own extensions to the standard: `script/check` runs
|
with the version; the Gitea workflow calls it. **`script/cibuild` runs
|
||||||
`script/test`, `script/lint`, and `script/fmt-check`; `script/precommit` is
|
`script/bootstrap` first**, because the workflow checks out the repo and runs
|
||||||
what the git pre-commit hook runs, and it calls `script/check`;
|
nothing else, while `script/fmt-check` runs the formatter on the host: on a
|
||||||
`script/install-precommit` installs the git pre-commit hook (the `make hooks`
|
pristine checkout with nothing installed the run dies there, after the
|
||||||
target shims to it); and `script/projectname` (literally that filename) simply
|
containerised gates have passed. **The bootstrap alone is not enough**:
|
||||||
outputs the project's name. Scripts that need the name call
|
`script/bootstrap` installs node and yarn under nvm and leaves neither on the
|
||||||
`script/projectname` — e.g. `script/docker` assembles its image tag from it —
|
`PATH` of the shell that called it, so a bare `yarn` still exits 127. The host
|
||||||
so those scripts stay byte-identical across all repos. Repo-type-specific
|
entrypoints that need yarn — `script/fmt` and `script/fmt-check` — therefore
|
||||||
pre-commit extras (e.g. `go mod tidy` verification in Go repos) belong in
|
source nvm for the pinned node version before invoking it, exactly as
|
||||||
`script/precommit`, not in the hook itself. Model scripts are at
|
`script/bootstrap`'s own install step does. A runner carrying nothing but
|
||||||
|
docker and git then gets through `script/check`. Four further scripts are our
|
||||||
|
own extensions to the standard: `script/check` runs `script/test`,
|
||||||
|
`script/lint` and `script/fmt-check`; `script/precommit` is what the git
|
||||||
|
pre-commit hook runs, and it calls `script/check`; `script/install-precommit`
|
||||||
|
installs the git pre-commit hook (the `make hooks` target shims to it); and
|
||||||
|
`script/projectname` (literally that filename) simply outputs the project's
|
||||||
|
name. Scripts that need the name call `script/projectname` — e.g.
|
||||||
|
`script/docker` assembles its image tag from it — so those scripts stay
|
||||||
|
byte-identical across all repos. Repo-type-specific pre-commit extras (e.g.
|
||||||
|
`go mod tidy` verification in Go repos) belong in `script/precommit`, not in
|
||||||
|
the hook itself. Model scripts are at
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/script/<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).
|
||||||
@@ -89,87 +100,198 @@ 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`. All Dockerfiles must run `make check`
|
- Every repo should have a `Dockerfile`, and it carries the repo's gates: a
|
||||||
as a build step so the build fails if the branch is not green. For non-server
|
`lint` phase and a `test` phase, with the final stage depending on both so the
|
||||||
repos, the Dockerfile should bring up a development environment and run
|
image cannot be built unless they pass. For non-server repos the final stage
|
||||||
`make check`. For server repos, `make check` should run as an early build
|
brings up a development environment; for server repos it is the runtime image.
|
||||||
stage before the final image is assembled. Dockerfiles install development
|
The gate phases and the build stage start from their pinned base images and
|
||||||
prerequisites by running `script/bootstrap` rather than duplicating installs
|
install what those images lack either inline, as the canonical Go `Dockerfile`
|
||||||
inline; COPY `script/` and the dependency manifests (`package.json` +
|
below does for `git`, or by running `script/bootstrap`, as the `prompts`
|
||||||
`yarn.lock`, `go.mod` + `go.sum`, etc.) before running it so the bootstrap
|
repo's own `Dockerfile` does for its yarn packages. The development
|
||||||
layer stays cached until dependencies change.
|
environment stage installs development prerequisites by running
|
||||||
|
`script/bootstrap` rather than duplicating its installs inline. A stage that
|
||||||
|
runs `script/bootstrap` COPYs `script/` and the dependency manifests
|
||||||
|
(`package.json` + `yarn.lock`, `go.mod` + `go.sum`, etc.) before running it.
|
||||||
|
|
||||||
- **Dockerfiles must use a separate lint stage for fail-fast feedback.** Go
|
- **Linting and testing run in Docker, as phases of the `Dockerfile`.** There is
|
||||||
repos use a multistage build where linting runs in an independent stage based
|
no separate lint file. `script/lint` and `script/test` each build one phase
|
||||||
on the `golangci/golangci-lint` image (pinned by hash). This stage runs
|
and nothing else:
|
||||||
`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.
|
|
||||||
|
|
||||||
The standard pattern for a Go repo Dockerfile is:
|
```sh
|
||||||
|
docker build --no-cache --target lint -t "$(script/projectname)-lint" .
|
||||||
|
docker build --no-cache --target test -t "$(script/projectname)-test" .
|
||||||
|
```
|
||||||
|
|
||||||
|
**A stage that is not the last one in the file is built only when the final
|
||||||
|
stage's chain depends on it, or when `--target` names it.** That is why the
|
||||||
|
two gates are always invoked by name here, and why the final stage carries a
|
||||||
|
`COPY --from=` of a harmless file from each of them: without that edge a
|
||||||
|
plain `docker build .` builds the last stage alone and exits 0 having linted
|
||||||
|
and tested nothing.
|
||||||
|
|
||||||
|
**Every `docker build` in `script/` is tagged**, here and in
|
||||||
|
`script/cibuild` and `script/docker`. An untagged build leaves a dangling
|
||||||
|
image behind on every invocation, on every developer host and every CI
|
||||||
|
runner; a tagged one replaces the previous image.
|
||||||
|
|
||||||
|
Inside a phase the tool is invoked directly — `golangci-lint`, `go test`,
|
||||||
|
`eslint`, `prettier` — never through `make lint` or `script/test`, which are
|
||||||
|
themselves a `docker build` and would recurse into a daemon that does not
|
||||||
|
exist in a build step. Formatting is the exception and stays on the host:
|
||||||
|
`script/fmt` writes the working tree, and `script/fmt-check` is its
|
||||||
|
read-only twin.
|
||||||
|
|
||||||
|
**No lint verdict may come from a host invocation of the linter.** On a
|
||||||
|
shared host golangci-lint reads a result cache keyed on file content rather
|
||||||
|
than location, so a second checkout of the same content is served the first
|
||||||
|
one's findings, and a host-global lock in `$TMPDIR` makes concurrent runs
|
||||||
|
exit non-zero with `parallel golangci-lint is running` — a status a caller
|
||||||
|
cannot tell from real findings. Both have produced wrong verdicts in this
|
||||||
|
org, in both directions. A container has its own cache, its own `TMPDIR` and
|
||||||
|
a digest-pinned binary, so neither is reachable.
|
||||||
|
|
||||||
|
- **Any build that runs checks is built with `--no-cache`.** Docker invalidates
|
||||||
|
a `COPY` layer only when the copied content changes, so on an unchanged tree
|
||||||
|
the check `RUN` is served from cache, nothing executes, and the build still
|
||||||
|
exits 0. Every `docker build` in `script/` therefore passes `--no-cache`:
|
||||||
|
`script/lint`, `script/test`, `script/cibuild` and `script/docker` are the
|
||||||
|
four, and there is no fifth — `script/check` runs the two gate phases and
|
||||||
|
`script/fmt-check`, and builds no image of its own. A bare `docker build .` is
|
||||||
|
not evidence that anything ran: a sub-second build reporting success is a
|
||||||
|
cache hit, not a result. Never invalidate by pruning — `docker builder prune`
|
||||||
|
and friends destroy a build cache shared with every other build on the host.
|
||||||
|
When a check is added or changed, prove it works by planting a defect it must
|
||||||
|
catch and watching the run fail on it, then revert the defect. A green run
|
||||||
|
alone shows neither that the check ran nor that it covers what it should.
|
||||||
|
|
||||||
|
- **The gate phases are separate stages, and the build stage depends on both.**
|
||||||
|
The lint phase is based on the `golangci/golangci-lint` image (pinned by
|
||||||
|
hash), so lint failures surface in seconds rather than after a full compile,
|
||||||
|
and the test phase is based on the Debian Go image. The canonical Go repo
|
||||||
|
`Dockerfile`:
|
||||||
|
|
||||||
```dockerfile
|
```dockerfile
|
||||||
# Lint stage — fast feedback on formatting and lint issues
|
# Lint phase
|
||||||
# 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 make fmt-check
|
RUN golangci-lint run --config .golangci.yml ./...
|
||||||
RUN make lint
|
|
||||||
|
|
||||||
# Build stage
|
# Test phase. -race needs cgo and so a C compiler, which the Debian Go
|
||||||
# golang:1.x-alpine, YYYY-MM-DD
|
# image ships and the alpine one does not.
|
||||||
FROM golang@sha256:... AS builder
|
# golang:1.x, YYYY-MM-DD
|
||||||
|
FROM golang@sha256:... AS test
|
||||||
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
|
RUN go test -timeout 90s -race -cover ./... || \
|
||||||
|
{ echo "--- Rerunning with -v for details ---"; \
|
||||||
|
go test -timeout 90s -race -v ./...; exit 1; }
|
||||||
|
|
||||||
ARG VERSION=dev
|
# Build stage. Nothing is wanted from either phase above; the copies
|
||||||
RUN CGO_ENABLED=0 go build -trimpath \
|
# are what make BuildKit build them first, so this stage cannot run
|
||||||
-ldflags="-s -w -X main.Version=${VERSION}" \
|
# unless lint and test passed.
|
||||||
-o /app ./cmd/app/
|
# golang:1.x-alpine, YYYY-MM-DD
|
||||||
|
FROM golang@sha256:... AS builder
|
||||||
|
COPY --from=lint /src/go.sum /dev/null
|
||||||
|
COPY --from=test /src/go.sum /dev/null
|
||||||
|
RUN apk add --no-cache git
|
||||||
|
# A tar-stream context keeps the sender's file owners, which git refuses.
|
||||||
|
RUN git config --system --add safe.directory /src
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
|
||||||
# Runtime stage
|
# The VERSION build arg when one is given, otherwise
|
||||||
|
# `git describe --tags --always` on the .git in the build context. With
|
||||||
|
# .git present, a version that is still empty, dev or unknown fails the
|
||||||
|
# build: git is missing or could not read the checkout.
|
||||||
|
ARG VERSION
|
||||||
|
RUN VERSION="${VERSION:-$(git describe --tags --always)}"; \
|
||||||
|
if [ -e .git ]; then \
|
||||||
|
case "$VERSION" in ""|dev|unknown) \
|
||||||
|
echo "version is '$VERSION' although .git is present" >&2; \
|
||||||
|
exit 1 ;; \
|
||||||
|
esac; \
|
||||||
|
fi; \
|
||||||
|
CGO_ENABLED=0 go build -trimpath \
|
||||||
|
-ldflags="-s -w -X main.Version=${VERSION}" \
|
||||||
|
-o /app ./cmd/app/
|
||||||
|
|
||||||
|
# Runtime stage, and the last one
|
||||||
FROM alpine@sha256:...
|
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 stage uses the `golangci/golangci-lint` image directly (it
|
- The lint phase uses the `golangci/golangci-lint` image directly (it has
|
||||||
includes both Go and the linter), so there is no need to install the
|
both Go and the linter), so nothing needs installing.
|
||||||
linter separately.
|
- `COPY --from=<phase> /src/go.sum /dev/null` is a no-op copy whose only
|
||||||
- `COPY --from=lint /src/go.sum /dev/null` is a no-op file copy that creates
|
purpose is the ordering edge. BuildKit runs stages in parallel by default,
|
||||||
a stage dependency. BuildKit runs stages in parallel by default; without
|
and a stage nothing depends on is not built at all, so without these two
|
||||||
this line, the build stage would not wait for lint to finish and a lint
|
lines a red gate would not fail the build.
|
||||||
failure might not fail the overall build.
|
- Keep the runtime stage last, and if you add a stage after it, give it the
|
||||||
|
same two copies. A plain `docker build .` builds the last stage's chain
|
||||||
|
and nothing else.
|
||||||
- If the project uses `//go:embed` directives that reference build artifacts
|
- If the project uses `//go:embed` directives that reference build artifacts
|
||||||
(e.g. a web frontend compiled in a separate stage), the lint stage must
|
(e.g. a web frontend compiled in a separate stage), the lint phase must
|
||||||
create placeholder files so the embed directives resolve. Example:
|
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`.
|
||||||
The lint stage should not depend on the actual build output — it exists to
|
- If the project requires CGO or system libraries for linting, install them
|
||||||
fail fast.
|
in the lint phase. The `golangci/golangci-lint` image is Debian-based and
|
||||||
- If the project requires CGO or system libraries for linting (e.g.
|
has no `apk`, so install with `apt-get` under the Debian package name
|
||||||
`vips-dev`), install them in the lint stage with `apk add`.
|
(`libvips-dev`, where alpine says `vips-dev`), and delete the package
|
||||||
- The build stage runs `make test` after compilation setup. Tests run in the
|
lists in the same `RUN`, so the layer does not keep them:
|
||||||
build stage, not the lint stage, because they may require compiled
|
|
||||||
artifacts or heavier dependencies.
|
```dockerfile
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends libvips-dev \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
```
|
||||||
|
|
||||||
|
- `.dockerignore` lets `.git` into the build context. It keeps out every git
|
||||||
|
`config` at any depth (`**/.git/config`, `**/.git/modules/**/config`): the
|
||||||
|
repository's own, each submodule's under `.git/modules/`, and that of a
|
||||||
|
submodule keeping its own `.git` directory. `git describe` does not need
|
||||||
|
them, and each can hold a credential: a password in a remote URL, or the
|
||||||
|
token the CI checkout step stores there. A submodule whose name has a
|
||||||
|
`config` segment (`config`, `deploy/config`, `config/lib`) loses its whole
|
||||||
|
git directory to `**/.git/modules/**/config`, and Go's version stamping
|
||||||
|
then fails the build: give it a name without that segment
|
||||||
|
(`git submodule add --name`). The stage that compiles has `git` (the
|
||||||
|
Debian Go image has it; an alpine one needs `apk add --no-cache git`) and
|
||||||
|
takes the version from the `VERSION` build argument when one is given,
|
||||||
|
otherwise from `git describe --tags --always`. That gives the tag on a
|
||||||
|
tagged commit; on a later commit, the tag, the number of commits since it
|
||||||
|
and the short commit (`v1.2.3-4-gabc1234`); and the short commit when no
|
||||||
|
tag is reachable. The stage that compiles also marks its working directory
|
||||||
|
safe for git (`git config --system --add safe.directory /src`): a context
|
||||||
|
sent as a tar stream keeps the sender's file owners, and git refuses a
|
||||||
|
checkout owned by another user, so the version would come out empty.
|
||||||
|
`ARG VERSION` has no default, and the build fails if the context carries
|
||||||
|
`.git` and the version still comes out empty, `dev` or `unknown`. A plain
|
||||||
|
`docker build .` with no build arguments must succeed; a Dockerfile that
|
||||||
|
refuses an empty build argument drops that refusal and keeps the argument.
|
||||||
|
|
||||||
- Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that
|
- Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that
|
||||||
runs `script/cibuild` (which runs `docker build .`) on push. Since the
|
runs `script/cibuild` on push, and checks out the repo as its only other step.
|
||||||
Dockerfile already runs `make check`, a successful build implies all checks
|
That script bootstraps, runs the gate phases, and then builds the image, so a
|
||||||
pass.
|
successful run means every check passed; a bare `docker build .` does not
|
||||||
|
carry the same guarantee, because its gate phases may come from the cache. The
|
||||||
|
image build is uncached and so runs the gate phases a second time. That is the
|
||||||
|
price of the rule above, and it is worth paying: the image that ships is built
|
||||||
|
from a run of its own gates rather than from a cache entry. A separate
|
||||||
|
workflow limited to `main` by a `branches` list under `on: push` cannot be
|
||||||
|
checked by review: to try a change to it, add the feature branch to that list
|
||||||
|
and push, then remove the branch from the list again before merging. Keep any
|
||||||
|
job in it that publishes behind `if: github.ref_name == 'main'`, so the run
|
||||||
|
from the feature branch publishes nothing.
|
||||||
|
|
||||||
- Use platform-standard formatters: `black` for Python, `prettier` for
|
- 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
|
||||||
@@ -189,14 +311,21 @@ 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 20 seconds. Add a 30-second timeout in the
|
- `make test` must complete in under 60 seconds. That is the hard cap, and a
|
||||||
Makefile.
|
suite that exceeds it fails. Under 20 seconds is the target. A suite between
|
||||||
|
20 and 60 seconds is still green, but the overage must be filed as an
|
||||||
|
improvement bug against that repo. Add a 90-second timeout to the test
|
||||||
|
invocation (`go test -timeout 90s`). The backstop deliberately sits above the
|
||||||
|
hard cap so that it catches a genuinely hung test rather than a merely slow
|
||||||
|
one.
|
||||||
|
|
||||||
- **`make test` should use the conditional verbose rerun pattern.** Run tests
|
- **The test command should use the conditional verbose rerun pattern.** Run
|
||||||
without `-v` (verbose) first. If tests fail, automatically rerun with `-v` to
|
tests without `-v` (verbose) first. If tests fail, automatically rerun with
|
||||||
show full output. This keeps CI logs and `docker build` output clean on
|
`-v` to show full output. This keeps CI logs and `docker build` output clean
|
||||||
success (just package/suite summaries) while providing full diagnostic detail
|
on success (just package/suite summaries) while providing full diagnostic
|
||||||
on failure (every test case, every assertion). The general shell pattern:
|
detail on failure (every test case, every assertion). The command lives in the
|
||||||
|
`test` phase of the `Dockerfile`, since `script/test` builds that phase; the
|
||||||
|
Makefile form below is the same pattern for any repo-local invocation:
|
||||||
|
|
||||||
```makefile
|
```makefile
|
||||||
test:
|
test:
|
||||||
@@ -209,11 +338,26 @@ style conventions are in separate documents:
|
|||||||
|
|
||||||
```makefile
|
```makefile
|
||||||
test:
|
test:
|
||||||
@go test -timeout 30s -race -cover ./... || \
|
@go test -count=1 -timeout 90s -race -cover ./... || \
|
||||||
{ echo "--- Rerunning with -v for details ---"; \
|
{ echo "--- Rerunning with -v for details ---"; \
|
||||||
go test -timeout 30s -race -v ./...; exit 1; }
|
go test -count=1 -timeout 90s -race -v ./...; exit 1; }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`-count=1` is required on both invocations: it defeats Go's test _result_
|
||||||
|
cache, so neither run can report a stored pass in place of running the
|
||||||
|
tests. It leaves the build cache alone, so it costs the runtime of the suite
|
||||||
|
and no recompilation.
|
||||||
|
|
||||||
|
That cache is Go's own, separate from Docker's layer cache. Go stores a
|
||||||
|
passing result in its cache directory (`GOCACHE`), and when the same tests
|
||||||
|
run again on unchanged code it prints that result, marked `(cached)`,
|
||||||
|
without running them. That matters on a developer's machine, where this
|
||||||
|
target runs and the directory lasts from one run to the next. The `test`
|
||||||
|
phase of the `Dockerfile` needs no `-count=1`: its base image holds no
|
||||||
|
result for this repo's tests and nothing before its `go test` step runs a
|
||||||
|
test, so there is nothing to replay. `--no-cache` (above) is what makes that
|
||||||
|
step run on an unchanged tree.
|
||||||
|
|
||||||
Python example:
|
Python example:
|
||||||
|
|
||||||
```makefile
|
```makefile
|
||||||
@@ -239,10 +383,84 @@ 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`, `*~`), language build artifacts, and `node_modules/`.
|
editor files (`.swp`, `*~`), in-repo agent scratch directories (`.claude/`),
|
||||||
Fetch the standard `.gitignore` from
|
language build artifacts, and `node_modules/`. Fetch the standard `.gitignore`
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when setting up
|
from `https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when
|
||||||
a new repo.
|
setting up a new repo. These patterns are written to `.gitignore`'s own
|
||||||
|
semantics, in which an unanchored pattern already matches at every depth; they
|
||||||
|
are not a `.dockerignore` and must not be transplanted into one unmodified.
|
||||||
|
|
||||||
|
- **`.dockerignore` does not use `.gitignore` semantics, and copying patterns
|
||||||
|
across unmodified leaves secrets in the build context.** Docker matches with
|
||||||
|
`moby/patternmatcher`: `filepath.Match` semantics plus a `**` extension, so
|
||||||
|
`*` does not cross `/` and a pattern without a leading `**/` is anchored at
|
||||||
|
the build-context root. A `.dockerignore` listing `.env`, `*.pem` and `*.key`
|
||||||
|
therefore excludes only the copies at the repository root, while `config/.env`
|
||||||
|
and `certs/server.key` still reach the context and can land in an image layer
|
||||||
|
— which is more dangerous than a short file with no secret patterns at all,
|
||||||
|
because it reads as solved and stops anyone looking. Give every
|
||||||
|
depth-independent pattern the `**/` prefix and leave only genuinely
|
||||||
|
root-anchored entries unprefixed: `.claude`, and the repo's own host-built
|
||||||
|
binary, written `/myapp` and never `**/myapp`, which would also match
|
||||||
|
`cmd/myapp/` and delete the package directory from the context. Matching is
|
||||||
|
case-sensitive, and an ALL-CAPS twin per pattern still misses `Server.Key`, so
|
||||||
|
secret names use character ranges — `**/*.[kK][eE][yY]`, `**/*.[pP][eE][mM]`,
|
||||||
|
and likewise for `.envrc` and the extensionless SSH keys. Where such a pattern
|
||||||
|
also catches something the build needs, re-include it with a negation
|
||||||
|
(`!docs/example.env`); deleting the pattern reopens the exposure for every
|
||||||
|
other file it covers. Fetch the standard `.dockerignore` from
|
||||||
|
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.dockerignore` and extend
|
||||||
|
it with the repo's own artifacts.
|
||||||
|
|
||||||
|
- **In-repo agent scratch belongs in both files, written to each file's own
|
||||||
|
semantics.** `.claude/` holds one worktree per in-flight agent — an entire
|
||||||
|
additional checkout of the repo — so under `COPY . .` the build context
|
||||||
|
inflates by a multiple of the repo and another session's unreviewed work can
|
||||||
|
be copied into an image layer. In `.gitignore` the entry is `.claude/`,
|
||||||
|
unanchored. In `.dockerignore` it is `.claude`, anchored and with **no** `**/`
|
||||||
|
prefix, because the prefixed form would also delete any nested directory of
|
||||||
|
that name from the build. Anchoring carries a known gap that the canonical
|
||||||
|
`.dockerignore` states in its own comment, since consuming repos receive the
|
||||||
|
file and not the tracker: the directory is created in the agent's working
|
||||||
|
directory, so a repo running agents in subdirectories still ships
|
||||||
|
`services/api/.claude/` and must add its own anchored entry there.
|
||||||
|
|
||||||
|
- **A plain `docker build .` of a clone stamps the version that
|
||||||
|
`git describe --tags --always` gives**, derived from the `.git` in the build
|
||||||
|
context as the canonical `Dockerfile` above shows. Without its failure check,
|
||||||
|
a missing `git` or an unreadable checkout would leave `-X main.Version=` empty
|
||||||
|
and the build would still exit 0. `script/docker` and `script/cibuild` pass
|
||||||
|
the version they compute on the host; it takes precedence. They do this
|
||||||
|
byte-identically across repos:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Own line: a failing command substitution inside an argument does not
|
||||||
|
# trip `set -e`, so the inline form degrades to an empty constant.
|
||||||
|
version="$(git describe --tags --always --dirty 2>/dev/null || true)"
|
||||||
|
[ -n "$version" ] || version="unknown"
|
||||||
|
docker build --no-cache \
|
||||||
|
--build-arg VERSION="$version" \
|
||||||
|
-t "$(script/projectname)" .
|
||||||
|
```
|
||||||
|
|
||||||
|
`--always` makes an untagged repo yield an abbreviated commit hash rather
|
||||||
|
than failing, and the `[ -n "$version" ]` line is the single place the
|
||||||
|
fallback is applied — a live check that fires on a build from an export with
|
||||||
|
no `.git` and on a repository with no commits yet. Do not fold it into the
|
||||||
|
substitution as `|| echo unknown`, which makes the guard unreachable. The
|
||||||
|
Dockerfile's side is `ARG VERSION` in the stage that compiles, declared
|
||||||
|
there because `ARG` is stage-scoped; passing `VERSION` to a repo whose
|
||||||
|
Dockerfile declares no such `ARG` is ignored and costs nothing, which is why
|
||||||
|
the scripts stay byte-identical. One consequence for CI: the standard
|
||||||
|
checkout action clones shallow and fetches no tags, so a repo that embeds a
|
||||||
|
tag-derived version must set `fetch-depth: 0` on its checkout step.
|
||||||
|
|
||||||
|
- **Verify `.dockerignore` by enumerating the image, not by reading the
|
||||||
|
patterns.** Plant files at the root _and_ at least two directories deep, build
|
||||||
|
a probe image that does `COPY . .`, and list what actually landed
|
||||||
|
(`docker run --rm --entrypoint find IMAGE /app`). The `transferring context`
|
||||||
|
size is not a substitute: a nested secret is a few bytes, and BuildKit
|
||||||
|
transfers only the delta from the previous build.
|
||||||
|
|
||||||
- **No build artifacts in version control.** Code-derived data (compiled
|
- **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
|
||||||
@@ -258,9 +476,56 @@ style conventions are in separate documents:
|
|||||||
- Make all changes on a feature branch. You can do whatever you want on a
|
- Make all changes on a feature branch. You can do whatever you want on a
|
||||||
feature branch.
|
feature branch.
|
||||||
|
|
||||||
- `.golangci.yml` is standardized and must _NEVER_ be modified by an agent, only
|
- `.golangci.yml` is standardized. The vendored copy in a consuming repo must
|
||||||
manually by the user. Fetch from
|
_NEVER_ be modified by an agent: fetch it from
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml`.
|
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml` and keep it
|
||||||
|
byte-identical, so that no repo can quietly loosen its own linting. Linter
|
||||||
|
configuration changes are made to the canonical copy in the `prompts` repo and
|
||||||
|
reach consuming repos by re-vendoring; an agent may open a PR against
|
||||||
|
canonical, which only the user merges. One list is exempt from byte-identity,
|
||||||
|
because it cannot be written once for every repo: the `deny` list of the
|
||||||
|
`test-support` depguard rule, where a repo names its own test-support packages
|
||||||
|
by full import path. A repo adds entries there and changes nothing else, and a
|
||||||
|
re-vendor carries its entries forward. The canonical golangci-lint version is
|
||||||
|
v2.14.0 (released 2026-09-24), pinned as the digest of the lint phase's base
|
||||||
|
image
|
||||||
|
(`golangci/golangci-lint@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f`,
|
||||||
|
which reports `2.14.0 built with go1.27.0 from 114493f9`). A module's `go`
|
||||||
|
directive must not name a newer Go minor version than the one golangci-lint
|
||||||
|
was built with, or golangci-lint refuses to lint it: this release lints
|
||||||
|
`go 1.27.1` but not `go 1.28`. That digest is the only pin, since no repo
|
||||||
|
installs golangci-lint on the host. A repo sets the lint phase digest to the
|
||||||
|
one named here and re-vendors `.golangci.yml` in the same commit, whichever of
|
||||||
|
the two prompted the change: the canonical copy can name linters that an older
|
||||||
|
golangci-lint rejects, and a newer golangci-lint can add linters that
|
||||||
|
`default: all` switches on until the canonical copy disables them.
|
||||||
|
|
||||||
|
- **`script/bootstrap` installs a pinned tool by comparing versions, never by
|
||||||
|
testing presence.** An `if ! command -v <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).
|
||||||
@@ -374,12 +639,14 @@ 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`, `Makefile`, `Dockerfile`,
|
only project-level config files (`README.md`, `AGENTS.md`, `Makefile`,
|
||||||
`LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`, and
|
`Dockerfile`, `LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`,
|
||||||
language-specific config). Everything else goes in a subdirectory. Canonical
|
and language-specific config). Everything else goes in a subdirectory.
|
||||||
subdirectory names:
|
Canonical subdirectory names:
|
||||||
- `bin/` — executable scripts and tools
|
- `bin/` — executable scripts and tools
|
||||||
- `cmd/` — Go command entrypoints
|
- `cmd/` — Go command entrypoints; thin only: one `main.go` per binary whose
|
||||||
|
body is a single call into `internal/` or `pkg/`, no project logic in
|
||||||
|
`cmd/`
|
||||||
- `configs/` — configuration templates and examples
|
- `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)
|
||||||
@@ -406,3 +673,7 @@ 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.
|
||||||
|
|||||||
@@ -18,6 +18,38 @@ https://git.eeqj.de/sneak/secret/milestone/12
|
|||||||
|
|
||||||
# Completed Steps
|
# Completed Steps
|
||||||
|
|
||||||
|
- 2026-10-12: A mnemonic typed with extra spaces, tabs or line breaks gives the
|
||||||
|
same long-term key as its words separated by single spaces
|
||||||
|
(https://git.eeqj.de/sneak/secret/issues/135). The key was derived from the
|
||||||
|
text exactly as typed, so a vault made with a double or trailing space did not
|
||||||
|
open with the same words typed normally. `agehd.DeriveEntropy`, which every
|
||||||
|
use of the mnemonic goes through, now joins the words with single spaces and
|
||||||
|
puts them in Unicode NFKD, as BIP39 defines, before making the seed.
|
||||||
|
- 2026-10-12: The keychain and Secure Enclave unlockers are gone from the code
|
||||||
|
and the documents (https://git.eeqj.de/sneak/secret/issues/132). They were
|
||||||
|
research: neither works without macOS code signing and entitlements, which
|
||||||
|
`secret` does not have. The last commit that has them is `ef0ae90`, tagged
|
||||||
|
`v1.0.0-rc1`. `secret unlocker add` takes only `passphrase` and `pgp` on every
|
||||||
|
platform, `internal/macse` and those unlockers' files in `internal/secret` are
|
||||||
|
deleted, and `github.com/keybase/go-keychain` left `go.mod` and `go.sum`.
|
||||||
|
`secret` still builds and runs on macOS.
|
||||||
|
- 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
|
- 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
|
timeout per package and coverage, as `REPO_POLICIES.md` requires
|
||||||
(https://git.eeqj.de/sneak/secret/issues/32). When they fail, it reruns them
|
(https://git.eeqj.de/sneak/secret/issues/32). When they fail, it reruns them
|
||||||
|
|||||||
@@ -12,15 +12,14 @@ require (
|
|||||||
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.25-0.20260601142114-9246436fffe8 // v1.1.24's Open can return another pty's terminal
|
||||||
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/oklog/ulid/v2 v2.1.1
|
github.com/oklog/ulid/v2 v2.1.1
|
||||||
github.com/spf13/afero v1.14.0
|
github.com/spf13/afero v1.14.0
|
||||||
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
|
||||||
|
golang.org/x/text v0.25.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -33,6 +32,5 @@ require (
|
|||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/spf13/pflag v1.0.6 // indirect
|
github.com/spf13/pflag v1.0.6 // indirect
|
||||||
golang.org/x/text v0.25.0 // indirect
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -69,8 +69,6 @@ github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLf
|
|||||||
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||||
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
|
||||||
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
|
github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ=
|
||||||
github.com/keybase/go-keychain v0.0.0-20230307172405-3e4884637dd1 h1:yi1W8qcFJ2plmaGJFN1npm0KQviWPMCtQOYuwDT6Swk=
|
|
||||||
github.com/keybase/go-keychain v0.0.0-20230307172405-3e4884637dd1/go.mod h1:qDHUvIjGZJUtdPtuP4WMu5/U4aVWbFw1MhlkJqCGmCQ=
|
|
||||||
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
|
github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4=
|
||||||
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
|
||||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||||
@@ -107,8 +105,6 @@ 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=
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
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.
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
// 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
|
||||||
|
}
|
||||||
@@ -0,0 +1,456 @@
|
|||||||
|
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
@@ -0,0 +1,19 @@
|
|||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
|
|
||||||
"github.com/awnumar/memguard"
|
"github.com/awnumar/memguard"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"github.com/tyler-smith/go-bip39"
|
"sneak.berlin/go/secret/internal/bip39"
|
||||||
"sneak.berlin/go/secret/internal/vault"
|
"sneak.berlin/go/secret/internal/vault"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
|
|
||||||
"github.com/awnumar/memguard"
|
"github.com/awnumar/memguard"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"github.com/tyler-smith/go-bip39"
|
"sneak.berlin/go/secret/internal/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"
|
||||||
)
|
)
|
||||||
|
|||||||
+4
-102
@@ -10,7 +10,6 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -21,14 +20,10 @@ import (
|
|||||||
"sneak.berlin/go/secret/internal/vault"
|
"sneak.berlin/go/secret/internal/vault"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Unlocker type names and platform identifiers shared across the CLI
|
// Unlocker type names shared across the CLI
|
||||||
const (
|
const (
|
||||||
unlockerTypePassphrase = "passphrase"
|
unlockerTypePassphrase = "passphrase"
|
||||||
unlockerTypeKeychain = "keychain"
|
unlockerTypePGP = "pgp"
|
||||||
unlockerTypePGP = "pgp"
|
|
||||||
unlockerTypeSecureEnclave = "secure-enclave"
|
|
||||||
|
|
||||||
platformDarwin = "darwin"
|
|
||||||
|
|
||||||
cmdUseList = "list"
|
cmdUseList = "list"
|
||||||
)
|
)
|
||||||
@@ -143,9 +138,8 @@ func newUnlockerListCmd() *cobra.Command {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// unlockerAddHelp returns the supported unlocker types list and their
|
// unlockerAddHelp returns the supported unlocker types list and their
|
||||||
// descriptions for the current platform
|
// descriptions
|
||||||
func unlockerAddHelp() (string, string) {
|
func unlockerAddHelp() (string, string) {
|
||||||
// Build the supported types list based on platform
|
|
||||||
supportedTypes := "passphrase, pgp"
|
supportedTypes := "passphrase, pgp"
|
||||||
typeDescriptions := "Available unlocker types:\n" +
|
typeDescriptions := "Available unlocker types:\n" +
|
||||||
"\n" +
|
"\n" +
|
||||||
@@ -162,43 +156,6 @@ func unlockerAddHelp() (string, string) {
|
|||||||
" Use --keyid to specify a particular key, " +
|
" Use --keyid to specify a particular key, " +
|
||||||
"otherwise uses your default GPG key."
|
"otherwise uses your default GPG key."
|
||||||
|
|
||||||
if runtime.GOOS == platformDarwin {
|
|
||||||
supportedTypes = "passphrase, keychain, pgp, secure-enclave"
|
|
||||||
typeDescriptions = "Available unlocker types:\n" +
|
|
||||||
"\n" +
|
|
||||||
" passphrase - Traditional password-based encryption\n" +
|
|
||||||
" Prompts for a passphrase that will be " +
|
|
||||||
"used to encrypt/decrypt the vault's master key.\n" +
|
|
||||||
" The passphrase is never stored in " +
|
|
||||||
"plaintext.\n" +
|
|
||||||
"\n" +
|
|
||||||
" keychain - macOS Keychain integration (macOS only)\n" +
|
|
||||||
" Stores the vault's master key in the " +
|
|
||||||
"macOS Keychain, protected by your login password.\n" +
|
|
||||||
" Automatically unlocks when your Keychain " +
|
|
||||||
"is unlocked (e.g., after login).\n" +
|
|
||||||
" Provides seamless integration with macOS " +
|
|
||||||
"security features like Touch ID.\n" +
|
|
||||||
"\n" +
|
|
||||||
" pgp - GNU Privacy Guard (GPG) key-based " +
|
|
||||||
"encryption\n" +
|
|
||||||
" Uses your existing GPG key to " +
|
|
||||||
"encrypt/decrypt the vault's master key.\n" +
|
|
||||||
" Requires gpg to be installed and " +
|
|
||||||
"configured with at least one secret key.\n" +
|
|
||||||
" Use --keyid to specify a particular key, " +
|
|
||||||
"otherwise uses your default GPG key.\n" +
|
|
||||||
"\n" +
|
|
||||||
" secure-enclave - Apple Secure Enclave hardware protection " +
|
|
||||||
"(macOS only)\n" +
|
|
||||||
" Stores the vault's master key encrypted " +
|
|
||||||
"by a non-exportable P-256 key\n" +
|
|
||||||
" held in the Secure Enclave. The key " +
|
|
||||||
"never leaves the hardware.\n" +
|
|
||||||
" Uses ECIES encryption; decryption is " +
|
|
||||||
"performed inside the SE."
|
|
||||||
}
|
|
||||||
|
|
||||||
return supportedTypes, typeDescriptions
|
return supportedTypes, typeDescriptions
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -420,18 +377,10 @@ func (cli *Instance) UnlockersAdd(unlockerType string, cmd *cobra.Command) error
|
|||||||
switch unlockerType {
|
switch unlockerType {
|
||||||
case unlockerTypePassphrase:
|
case unlockerTypePassphrase:
|
||||||
return cli.addPassphraseUnlocker(cmd)
|
return cli.addPassphraseUnlocker(cmd)
|
||||||
case unlockerTypeKeychain:
|
|
||||||
return cli.addKeychainUnlocker(cmd)
|
|
||||||
case unlockerTypeSecureEnclave:
|
|
||||||
return cli.addSecureEnclaveUnlocker(cmd)
|
|
||||||
case unlockerTypePGP:
|
case unlockerTypePGP:
|
||||||
return cli.addPGPUnlocker(cmd)
|
return cli.addPGPUnlocker(cmd)
|
||||||
default:
|
default:
|
||||||
// Build the supported types list based on platform
|
|
||||||
supportedTypes := "passphrase, pgp"
|
supportedTypes := "passphrase, pgp"
|
||||||
if runtime.GOOS == platformDarwin {
|
|
||||||
supportedTypes = "passphrase, keychain, pgp, secure-enclave"
|
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Errorf("%w: %s (supported: %s)",
|
return fmt.Errorf("%w: %s (supported: %s)",
|
||||||
errInvalidUnlockerType, unlockerType, supportedTypes)
|
errInvalidUnlockerType, unlockerType, supportedTypes)
|
||||||
@@ -487,53 +436,6 @@ func (cli *Instance) addPassphraseUnlocker(cmd *cobra.Command) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// addKeychainUnlocker creates a macOS Keychain unlocker in the current vault
|
|
||||||
func (cli *Instance) addKeychainUnlocker(cmd *cobra.Command) error {
|
|
||||||
keychainUnlocker, err := secret.CreateKeychainUnlocker(
|
|
||||||
cli.fs, cli.stateDir, cli.Mnemonic, cli.UnlockPassphrase)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to create macOS Keychain unlocker: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd.Printf("Created macOS Keychain unlocker: %s\n", keychainUnlocker.GetID())
|
|
||||||
|
|
||||||
keyName, err := keychainUnlocker.GetKeychainItemName()
|
|
||||||
if err == nil {
|
|
||||||
cmd.Printf("Keychain Item Name: %s\n", keyName)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Auto-select the newly created unlocker
|
|
||||||
vlt, err := vault.GetCurrentVault(cli.fs, cli.stateDir)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to get current vault: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
autoSelectUnlocker(cmd, vlt, keychainUnlocker.GetID())
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// addSecureEnclaveUnlocker creates a Secure Enclave unlocker in the
|
|
||||||
// current vault
|
|
||||||
func (cli *Instance) addSecureEnclaveUnlocker(cmd *cobra.Command) error {
|
|
||||||
seUnlocker, err := secret.CreateSecureEnclaveUnlocker(
|
|
||||||
cli.fs, cli.stateDir, cli.Mnemonic, cli.UnlockPassphrase)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to create Secure Enclave unlocker: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd.Printf("Created Secure Enclave unlocker: %s\n", seUnlocker.GetID())
|
|
||||||
|
|
||||||
vlt, err := vault.GetCurrentVault(cli.fs, cli.stateDir)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to get current vault: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
autoSelectUnlocker(cmd, vlt, seUnlocker.GetID())
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// addPGPUnlocker creates a PGP unlocker in the current vault
|
// addPGPUnlocker creates a PGP unlocker in the current vault
|
||||||
func (cli *Instance) addPGPUnlocker(cmd *cobra.Command) error {
|
func (cli *Instance) addPGPUnlocker(cmd *cobra.Command) error {
|
||||||
// Get GPG key ID from flag, environment, or default key
|
// Get GPG key ID from flag, environment, or default key
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package cli
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/awnumar/memguard"
|
"github.com/awnumar/memguard"
|
||||||
@@ -104,3 +105,40 @@ func TestAddPGPUnlockerUnknownKey(t *testing.T) {
|
|||||||
filepath.Join(testVaultDir(listTestVaultName), listTestUnlockersDirName),
|
filepath.Join(testVaultDir(listTestVaultName), listTestUnlockersDirName),
|
||||||
listTestUnlockerDirOne)
|
listTestUnlockerDirOne)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestUnlockerAddKnowsOnlyPassphraseAndPGP is a regression test for
|
||||||
|
// https://git.eeqj.de/sneak/secret/issues/132: `secret unlocker add` takes
|
||||||
|
// only passphrase and pgp, on every platform. keychain and secure-enclave
|
||||||
|
// fail as unknown types, and neither --help nor shell completion offers
|
||||||
|
// them.
|
||||||
|
//
|
||||||
|
//nolint:paralleltest // executes the CLI in-process and sets the environment
|
||||||
|
func TestUnlockerAddKnowsOnlyPassphraseAndPGP(t *testing.T) {
|
||||||
|
env := map[string]string{secret.EnvStateDir: t.TempDir()}
|
||||||
|
removedTypes := []string{"keychain", "secure-enclave"}
|
||||||
|
|
||||||
|
for _, unlockerType := range removedTypes {
|
||||||
|
_, err := ExecuteCommandInProcess(
|
||||||
|
[]string{"unlocker", "add", unlockerType}, "", env)
|
||||||
|
require.ErrorIs(t, err, errInvalidUnlockerType)
|
||||||
|
|
||||||
|
instance, cmd := newTestInstance(newListTestVault(t, 1))
|
||||||
|
require.ErrorIs(t, instance.UnlockersAdd(unlockerType, cmd),
|
||||||
|
errInvalidUnlockerType)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --help prints the command's Long text, and shell completion offers
|
||||||
|
// its ValidArgs.
|
||||||
|
addCmd := newUnlockerAddCmd()
|
||||||
|
help := addCmd.Long
|
||||||
|
completions := strings.Join(addCmd.ValidArgs, " ")
|
||||||
|
|
||||||
|
for _, offered := range []string{help, completions} {
|
||||||
|
assert.Contains(t, offered, unlockerTypePassphrase)
|
||||||
|
assert.Contains(t, offered, unlockerTypePGP)
|
||||||
|
|
||||||
|
for _, unlockerType := range removedTypes {
|
||||||
|
assert.NotContains(t, offered, unlockerType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -19,8 +19,7 @@ import (
|
|||||||
// copying an unlocker directory leaves them. It asserts that `unlocker
|
// copying an unlocker directory leaves them. It asserts that `unlocker
|
||||||
// list` and the shell completion of `unlocker select` and `unlocker remove`
|
// list` and the shell completion of `unlocker select` and `unlocker remove`
|
||||||
// give each its own ID, and that each is selected and removed by its ID
|
// give each its own ID, and that each is selected and removed by its ID
|
||||||
// alone. Keychain and Secure Enclave unlockers, which only macOS can add,
|
// alone.
|
||||||
// get their IDs the same way.
|
|
||||||
func TestSameMetadataUnlockersHaveTheirOwnIDs(t *testing.T) {
|
func TestSameMetadataUnlockersHaveTheirOwnIDs(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|||||||
@@ -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"
|
||||||
"github.com/tyler-smith/go-bip39"
|
"sneak.berlin/go/secret/internal/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"
|
||||||
|
|||||||
@@ -1,152 +0,0 @@
|
|||||||
//go:build darwin
|
|
||||||
|
|
||||||
// Package macse provides Go bindings for macOS Secure Enclave operations
|
|
||||||
// using CryptoTokenKit identities created via sc_auth.
|
|
||||||
// Key creation and deletion shell out to sc_auth (which has SE entitlements).
|
|
||||||
// Encrypt/decrypt use Security.framework ECIES directly (works unsigned).
|
|
||||||
package macse
|
|
||||||
|
|
||||||
/*
|
|
||||||
#cgo CFLAGS: -x objective-c -fobjc-arc
|
|
||||||
#cgo LDFLAGS: -framework Security -framework Foundation -framework CoreFoundation
|
|
||||||
#include <stdlib.h>
|
|
||||||
#include "secure_enclave.h"
|
|
||||||
*/
|
|
||||||
import "C"
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"unsafe"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// p256UncompressedKeySize is the size of an uncompressed P-256 public key.
|
|
||||||
p256UncompressedKeySize = 65
|
|
||||||
|
|
||||||
// errorBufferSize is the size of the C error message buffer.
|
|
||||||
errorBufferSize = 512
|
|
||||||
|
|
||||||
// hashBufferSize is the size of the hash output buffer.
|
|
||||||
hashBufferSize = 128
|
|
||||||
|
|
||||||
// maxCiphertextSize is the max buffer for ECIES ciphertext.
|
|
||||||
// ECIES overhead for P-256: 65 (ephemeral pub) + 16 (GCM tag) + 16 (IV) + plaintext.
|
|
||||||
maxCiphertextSize = 8192
|
|
||||||
|
|
||||||
// maxPlaintextSize is the max buffer for decrypted plaintext.
|
|
||||||
maxPlaintextSize = 8192
|
|
||||||
)
|
|
||||||
|
|
||||||
// CreateKey creates a new P-256 non-exportable key in the Secure Enclave via sc_auth.
|
|
||||||
// Returns the uncompressed public key bytes (65 bytes) and the identity hash
|
|
||||||
// (for deletion). If getting the public key fails, CreateKey deletes the key
|
|
||||||
// again; a failure to delete is returned along with the first error.
|
|
||||||
func CreateKey(label string) (publicKey []byte, hash string, err error) {
|
|
||||||
var hashBuf [hashBufferSize]C.char
|
|
||||||
var errBuf [errorBufferSize]C.char
|
|
||||||
|
|
||||||
cLabel := C.CString(label)
|
|
||||||
defer C.free(unsafe.Pointer(cLabel)) //nolint:nlreturn // CGo free pattern
|
|
||||||
|
|
||||||
result := C.se_create_key(cLabel,
|
|
||||||
&hashBuf[0], C.int(hashBufferSize),
|
|
||||||
&errBuf[0], C.int(errorBufferSize))
|
|
||||||
|
|
||||||
if result != 0 {
|
|
||||||
return nil, "", fmt.Errorf("secure enclave: %s", C.GoString(&errBuf[0]))
|
|
||||||
}
|
|
||||||
|
|
||||||
h := C.GoString(&hashBuf[0])
|
|
||||||
|
|
||||||
pubKeyBuf := make([]C.uint8_t, p256UncompressedKeySize)
|
|
||||||
pubKeyLen := C.int(p256UncompressedKeySize)
|
|
||||||
|
|
||||||
result = C.se_copy_public_key(cLabel,
|
|
||||||
&pubKeyBuf[0], &pubKeyLen,
|
|
||||||
&errBuf[0], C.int(errorBufferSize))
|
|
||||||
|
|
||||||
if result != 0 {
|
|
||||||
err = fmt.Errorf("secure enclave: %s", C.GoString(&errBuf[0]))
|
|
||||||
|
|
||||||
deleteErr := DeleteKey(h)
|
|
||||||
if deleteErr != nil {
|
|
||||||
err = errors.Join(err,
|
|
||||||
fmt.Errorf("failed to delete key %s: %w", label, deleteErr))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
//nolint:nlreturn // CGo result extraction
|
|
||||||
pk := C.GoBytes(unsafe.Pointer(&pubKeyBuf[0]), pubKeyLen)
|
|
||||||
|
|
||||||
return pk, h, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encrypt encrypts plaintext using the SE-backed public key via ECIES
|
|
||||||
// (eciesEncryptionStandardVariableIVX963SHA256AESGCM).
|
|
||||||
// Encryption uses only the public key; no SE interaction required.
|
|
||||||
func Encrypt(label string, plaintext []byte) ([]byte, error) {
|
|
||||||
ciphertextBuf := make([]C.uint8_t, maxCiphertextSize)
|
|
||||||
ciphertextLen := C.int(maxCiphertextSize)
|
|
||||||
var errBuf [errorBufferSize]C.char
|
|
||||||
|
|
||||||
cLabel := C.CString(label)
|
|
||||||
defer C.free(unsafe.Pointer(cLabel)) //nolint:nlreturn // CGo free pattern
|
|
||||||
|
|
||||||
result := C.se_encrypt(cLabel,
|
|
||||||
(*C.uint8_t)(unsafe.Pointer(&plaintext[0])), C.int(len(plaintext)),
|
|
||||||
&ciphertextBuf[0], &ciphertextLen,
|
|
||||||
&errBuf[0], C.int(errorBufferSize))
|
|
||||||
|
|
||||||
if result != 0 {
|
|
||||||
return nil, fmt.Errorf("secure enclave: %s", C.GoString(&errBuf[0]))
|
|
||||||
}
|
|
||||||
|
|
||||||
//nolint:nlreturn // CGo result extraction
|
|
||||||
out := C.GoBytes(unsafe.Pointer(&ciphertextBuf[0]), ciphertextLen)
|
|
||||||
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decrypt decrypts ECIES ciphertext using the SE-backed private key.
|
|
||||||
// The ECDH portion of decryption is performed inside the Secure Enclave.
|
|
||||||
func Decrypt(label string, ciphertext []byte) ([]byte, error) {
|
|
||||||
plaintextBuf := make([]C.uint8_t, maxPlaintextSize)
|
|
||||||
plaintextLen := C.int(maxPlaintextSize)
|
|
||||||
var errBuf [errorBufferSize]C.char
|
|
||||||
|
|
||||||
cLabel := C.CString(label)
|
|
||||||
defer C.free(unsafe.Pointer(cLabel)) //nolint:nlreturn // CGo free pattern
|
|
||||||
|
|
||||||
result := C.se_decrypt(cLabel,
|
|
||||||
(*C.uint8_t)(unsafe.Pointer(&ciphertext[0])), C.int(len(ciphertext)),
|
|
||||||
&plaintextBuf[0], &plaintextLen,
|
|
||||||
&errBuf[0], C.int(errorBufferSize))
|
|
||||||
|
|
||||||
if result != 0 {
|
|
||||||
return nil, fmt.Errorf("secure enclave: %s", C.GoString(&errBuf[0]))
|
|
||||||
}
|
|
||||||
|
|
||||||
//nolint:nlreturn // CGo result extraction
|
|
||||||
out := C.GoBytes(unsafe.Pointer(&plaintextBuf[0]), plaintextLen)
|
|
||||||
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteKey removes a CTK identity from the Secure Enclave via sc_auth.
|
|
||||||
func DeleteKey(hash string) error {
|
|
||||||
var errBuf [errorBufferSize]C.char
|
|
||||||
|
|
||||||
cHash := C.CString(hash)
|
|
||||||
defer C.free(unsafe.Pointer(cHash)) //nolint:nlreturn // CGo free pattern
|
|
||||||
|
|
||||||
result := C.se_delete_key(cHash, &errBuf[0], C.int(errorBufferSize))
|
|
||||||
|
|
||||||
if result != 0 {
|
|
||||||
return fmt.Errorf("secure enclave: %s", C.GoString(&errBuf[0]))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
//go:build !darwin || !cgo
|
|
||||||
|
|
||||||
// Package macse provides Go bindings for macOS Secure Enclave operations.
|
|
||||||
package macse
|
|
||||||
|
|
||||||
import "errors"
|
|
||||||
|
|
||||||
var errNotSupported = errors.New("secure enclave needs a macOS build with cgo")
|
|
||||||
|
|
||||||
// CreateKey fails: the Secure Enclave needs a macOS build with cgo.
|
|
||||||
func CreateKey(_ string) ([]byte, string, error) {
|
|
||||||
return nil, "", errNotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encrypt fails: the Secure Enclave needs a macOS build with cgo.
|
|
||||||
func Encrypt(_ string, _ []byte) ([]byte, error) {
|
|
||||||
return nil, errNotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decrypt fails: the Secure Enclave needs a macOS build with cgo.
|
|
||||||
func Decrypt(_ string, _ []byte) ([]byte, error) {
|
|
||||||
return nil, errNotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteKey fails: the Secure Enclave needs a macOS build with cgo.
|
|
||||||
func DeleteKey(_ string) error {
|
|
||||||
return errNotSupported
|
|
||||||
}
|
|
||||||
@@ -1,164 +0,0 @@
|
|||||||
//go:build darwin && cgo
|
|
||||||
|
|
||||||
package macse
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
const testKeyLabel = "berlin.sneak.app.secret.test.se-key"
|
|
||||||
|
|
||||||
// testKeyHash stores the hash of the created test key for cleanup.
|
|
||||||
var testKeyHash string //nolint:gochecknoglobals
|
|
||||||
|
|
||||||
// skipIfNoSecureEnclave skips the test if SE access is unavailable.
|
|
||||||
func skipIfNoSecureEnclave(t *testing.T) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
probeLabel := "berlin.sneak.app.secret.test.se-probe"
|
|
||||||
_, hash, err := CreateKey(probeLabel)
|
|
||||||
if err != nil {
|
|
||||||
t.Skipf("Secure Enclave unavailable (skipping): %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if hash != "" {
|
|
||||||
_ = DeleteKey(hash)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCreateAndDeleteKey(t *testing.T) {
|
|
||||||
skipIfNoSecureEnclave(t)
|
|
||||||
|
|
||||||
if testKeyHash != "" {
|
|
||||||
_ = DeleteKey(testKeyHash)
|
|
||||||
}
|
|
||||||
|
|
||||||
pubKey, hash, err := CreateKey(testKeyLabel)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("CreateKey failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
testKeyHash = hash
|
|
||||||
t.Logf("Created key with hash: %s", hash)
|
|
||||||
|
|
||||||
// Verify valid uncompressed P-256 public key
|
|
||||||
if len(pubKey) != p256UncompressedKeySize {
|
|
||||||
t.Fatalf("expected public key length %d, got %d",
|
|
||||||
p256UncompressedKeySize, len(pubKey))
|
|
||||||
}
|
|
||||||
|
|
||||||
if pubKey[0] != 0x04 {
|
|
||||||
t.Fatalf("expected uncompressed point prefix 0x04, got 0x%02x", pubKey[0])
|
|
||||||
}
|
|
||||||
|
|
||||||
if hash == "" {
|
|
||||||
t.Fatal("expected non-empty hash")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete the key
|
|
||||||
if err := DeleteKey(hash); err != nil {
|
|
||||||
t.Fatalf("DeleteKey failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
testKeyHash = ""
|
|
||||||
t.Log("Key created, verified, and deleted successfully")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEncryptDecryptRoundTrip(t *testing.T) {
|
|
||||||
skipIfNoSecureEnclave(t)
|
|
||||||
|
|
||||||
_, hash, err := CreateKey(testKeyLabel)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("CreateKey failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
testKeyHash = hash
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
if testKeyHash != "" {
|
|
||||||
_ = DeleteKey(testKeyHash)
|
|
||||||
testKeyHash = ""
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Test data simulating an age private key
|
|
||||||
plaintext := []byte("AGE-SECRET-KEY-1" +
|
|
||||||
"QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ")
|
|
||||||
|
|
||||||
// Encrypt
|
|
||||||
ciphertext, err := Encrypt(testKeyLabel, plaintext)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Encrypt failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Logf("Plaintext: %d bytes, Ciphertext: %d bytes", len(plaintext), len(ciphertext))
|
|
||||||
|
|
||||||
if bytes.Equal(ciphertext, plaintext) {
|
|
||||||
t.Fatal("ciphertext should differ from plaintext")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decrypt
|
|
||||||
decrypted, err := Decrypt(testKeyLabel, ciphertext)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Decrypt failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !bytes.Equal(decrypted, plaintext) {
|
|
||||||
t.Fatalf("decrypted data does not match original plaintext")
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Log("ECIES encrypt/decrypt round-trip successful")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEncryptProducesDifferentCiphertexts(t *testing.T) {
|
|
||||||
skipIfNoSecureEnclave(t)
|
|
||||||
|
|
||||||
_, hash, err := CreateKey(testKeyLabel)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("CreateKey failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
testKeyHash = hash
|
|
||||||
|
|
||||||
defer func() {
|
|
||||||
if testKeyHash != "" {
|
|
||||||
_ = DeleteKey(testKeyHash)
|
|
||||||
testKeyHash = ""
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
plaintext := []byte("test-secret-data")
|
|
||||||
|
|
||||||
ct1, err := Encrypt(testKeyLabel, plaintext)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("first Encrypt failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ct2, err := Encrypt(testKeyLabel, plaintext)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("second Encrypt failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ECIES uses a random ephemeral key each time, so ciphertexts should differ
|
|
||||||
if bytes.Equal(ct1, ct2) {
|
|
||||||
t.Fatal("two encryptions of same plaintext should produce different ciphertexts")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Both should decrypt to the same plaintext
|
|
||||||
dec1, err := Decrypt(testKeyLabel, ct1)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("first Decrypt failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dec2, err := Decrypt(testKeyLabel, ct2)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("second Decrypt failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !bytes.Equal(dec1, plaintext) || !bytes.Equal(dec2, plaintext) {
|
|
||||||
t.Fatal("both ciphertexts should decrypt to original plaintext")
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Log("ECIES correctly produces different ciphertexts that decrypt to same plaintext")
|
|
||||||
}
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
//go:build darwin
|
|
||||||
|
|
||||||
#ifndef SECURE_ENCLAVE_H
|
|
||||||
#define SECURE_ENCLAVE_H
|
|
||||||
|
|
||||||
#include <stdint.h>
|
|
||||||
|
|
||||||
// se_create_key creates a new P-256 key in the Secure Enclave via sc_auth and
|
|
||||||
// finds its identity hash. If the hash cannot be found, the key exists but
|
|
||||||
// se_create_key fails, with an error naming the label.
|
|
||||||
// label: unique identifier for the CTK identity (UTF-8 C string)
|
|
||||||
// hash_out: output buffer for the identity hash (for deletion)
|
|
||||||
// hash_out_len: size of hash_out buffer
|
|
||||||
// error_out: output buffer for error message
|
|
||||||
// error_out_len: size of error_out buffer
|
|
||||||
// Returns 0 on success, -1 on failure.
|
|
||||||
int se_create_key(const char *label,
|
|
||||||
char *hash_out, int hash_out_len,
|
|
||||||
char *error_out, int error_out_len);
|
|
||||||
|
|
||||||
// se_copy_public_key copies the public key of a CTK identity.
|
|
||||||
// label: label of the CTK identity
|
|
||||||
// pub_key_out: output buffer for the uncompressed public key (65 bytes for P-256)
|
|
||||||
// pub_key_len: on input, size of pub_key_out; on output, actual size written
|
|
||||||
// error_out: output buffer for error message
|
|
||||||
// error_out_len: size of error_out buffer
|
|
||||||
// Returns 0 on success, -1 on failure.
|
|
||||||
int se_copy_public_key(const char *label,
|
|
||||||
uint8_t *pub_key_out, int *pub_key_len,
|
|
||||||
char *error_out, int error_out_len);
|
|
||||||
|
|
||||||
// se_encrypt encrypts data using the SE-backed public key (ECIES).
|
|
||||||
// label: label of the CTK identity whose public key to use
|
|
||||||
// plaintext: data to encrypt
|
|
||||||
// plaintext_len: length of plaintext
|
|
||||||
// ciphertext_out: output buffer for the ECIES ciphertext
|
|
||||||
// ciphertext_len: on input, size of buffer; on output, actual size written
|
|
||||||
// error_out: output buffer for error message
|
|
||||||
// error_out_len: size of error_out buffer
|
|
||||||
// Returns 0 on success, -1 on failure.
|
|
||||||
int se_encrypt(const char *label,
|
|
||||||
const uint8_t *plaintext, int plaintext_len,
|
|
||||||
uint8_t *ciphertext_out, int *ciphertext_len,
|
|
||||||
char *error_out, int error_out_len);
|
|
||||||
|
|
||||||
// se_decrypt decrypts ECIES ciphertext using the SE-backed private key.
|
|
||||||
// The ECDH portion of decryption is performed inside the Secure Enclave.
|
|
||||||
// label: label of the CTK identity whose private key to use
|
|
||||||
// ciphertext: ECIES ciphertext produced by se_encrypt
|
|
||||||
// ciphertext_len: length of ciphertext
|
|
||||||
// plaintext_out: output buffer for decrypted data
|
|
||||||
// plaintext_len: on input, size of buffer; on output, actual size written
|
|
||||||
// error_out: output buffer for error message
|
|
||||||
// error_out_len: size of error_out buffer
|
|
||||||
// Returns 0 on success, -1 on failure.
|
|
||||||
int se_decrypt(const char *label,
|
|
||||||
const uint8_t *ciphertext, int ciphertext_len,
|
|
||||||
uint8_t *plaintext_out, int *plaintext_len,
|
|
||||||
char *error_out, int error_out_len);
|
|
||||||
|
|
||||||
// se_delete_key removes a CTK identity from the Secure Enclave via sc_auth.
|
|
||||||
// hash: the identity hash returned by se_create_key
|
|
||||||
// error_out: output buffer for error message
|
|
||||||
// error_out_len: size of error_out buffer
|
|
||||||
// Returns 0 on success, -1 on failure.
|
|
||||||
int se_delete_key(const char *hash,
|
|
||||||
char *error_out, int error_out_len);
|
|
||||||
|
|
||||||
#endif // SECURE_ENCLAVE_H
|
|
||||||
@@ -1,317 +0,0 @@
|
|||||||
//go:build darwin
|
|
||||||
|
|
||||||
#import <Foundation/Foundation.h>
|
|
||||||
#import <Security/Security.h>
|
|
||||||
#include "secure_enclave.h"
|
|
||||||
#include <string.h>
|
|
||||||
|
|
||||||
// snprintf_error writes an error message string to the output buffer.
|
|
||||||
static void snprintf_error(char *error_out, int error_out_len, NSString *msg) {
|
|
||||||
if (error_out && error_out_len > 0) {
|
|
||||||
snprintf(error_out, error_out_len, "%s", msg.UTF8String);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// lookup_ctk_identity finds a CTK identity by label and returns the private key.
|
|
||||||
static SecKeyRef lookup_ctk_private_key(const char *label, char *error_out, int error_out_len) {
|
|
||||||
NSDictionary *query = @{
|
|
||||||
(id)kSecClass: (id)kSecClassIdentity,
|
|
||||||
(id)kSecAttrLabel: [NSString stringWithUTF8String:label],
|
|
||||||
(id)kSecMatchLimit: (id)kSecMatchLimitOne,
|
|
||||||
(id)kSecReturnRef: @YES,
|
|
||||||
};
|
|
||||||
|
|
||||||
SecIdentityRef identity = NULL;
|
|
||||||
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&identity);
|
|
||||||
|
|
||||||
if (status != errSecSuccess || !identity) {
|
|
||||||
NSString *msg = [NSString stringWithFormat:@"CTK identity '%s' not found: OSStatus %d",
|
|
||||||
label, (int)status];
|
|
||||||
snprintf_error(error_out, error_out_len, msg);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
SecKeyRef privateKey = NULL;
|
|
||||||
status = SecIdentityCopyPrivateKey(identity, &privateKey);
|
|
||||||
CFRelease(identity);
|
|
||||||
|
|
||||||
if (status != errSecSuccess || !privateKey) {
|
|
||||||
NSString *msg = [NSString stringWithFormat:
|
|
||||||
@"failed to get private key from CTK identity '%s': OSStatus %d",
|
|
||||||
label, (int)status];
|
|
||||||
snprintf_error(error_out, error_out_len, msg);
|
|
||||||
return NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
return privateKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
int se_create_key(const char *label,
|
|
||||||
char *hash_out, int hash_out_len,
|
|
||||||
char *error_out, int error_out_len) {
|
|
||||||
@autoreleasepool {
|
|
||||||
NSString *labelStr = [NSString stringWithUTF8String:label];
|
|
||||||
|
|
||||||
// Shell out to sc_auth (which has SE entitlements) to create the key
|
|
||||||
NSTask *task = [[NSTask alloc] init];
|
|
||||||
task.executableURL = [NSURL fileURLWithPath:@"/usr/sbin/sc_auth"];
|
|
||||||
task.arguments = @[
|
|
||||||
@"create-ctk-identity",
|
|
||||||
@"-k", @"p-256-ne",
|
|
||||||
@"-t", @"none",
|
|
||||||
@"-l", labelStr,
|
|
||||||
];
|
|
||||||
|
|
||||||
NSPipe *stderrPipe = [NSPipe pipe];
|
|
||||||
task.standardOutput = [NSPipe pipe];
|
|
||||||
task.standardError = stderrPipe;
|
|
||||||
|
|
||||||
NSError *nsError = nil;
|
|
||||||
if (![task launchAndReturnError:&nsError]) {
|
|
||||||
NSString *msg = [NSString stringWithFormat:@"failed to launch sc_auth: %@",
|
|
||||||
nsError.localizedDescription];
|
|
||||||
snprintf_error(error_out, error_out_len, msg);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
[task waitUntilExit];
|
|
||||||
|
|
||||||
if (task.terminationStatus != 0) {
|
|
||||||
NSData *stderrData = [stderrPipe.fileHandleForReading readDataToEndOfFile];
|
|
||||||
NSString *stderrStr = [[NSString alloc] initWithData:stderrData
|
|
||||||
encoding:NSUTF8StringEncoding];
|
|
||||||
NSString *msg = [NSString stringWithFormat:@"sc_auth failed: %@",
|
|
||||||
stderrStr ?: @"unknown error"];
|
|
||||||
snprintf_error(error_out, error_out_len, msg);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the identity hash, which deleting the key needs, by parsing
|
|
||||||
// sc_auth list output
|
|
||||||
hash_out[0] = '\0';
|
|
||||||
NSTask *listTask = [[NSTask alloc] init];
|
|
||||||
listTask.executableURL = [NSURL fileURLWithPath:@"/usr/sbin/sc_auth"];
|
|
||||||
listTask.arguments = @[@"list-ctk-identities"];
|
|
||||||
|
|
||||||
NSPipe *listPipe = [NSPipe pipe];
|
|
||||||
listTask.standardOutput = listPipe;
|
|
||||||
listTask.standardError = [NSPipe pipe];
|
|
||||||
|
|
||||||
if ([listTask launchAndReturnError:&nsError]) {
|
|
||||||
[listTask waitUntilExit];
|
|
||||||
NSData *listData = [listPipe.fileHandleForReading readDataToEndOfFile];
|
|
||||||
NSString *listStr = [[NSString alloc] initWithData:listData
|
|
||||||
encoding:NSUTF8StringEncoding];
|
|
||||||
|
|
||||||
for (NSString *line in [listStr componentsSeparatedByString:@"\n"]) {
|
|
||||||
if ([line containsString:labelStr]) {
|
|
||||||
NSMutableArray *tokens = [NSMutableArray array];
|
|
||||||
for (NSString *part in [line componentsSeparatedByCharactersInSet:
|
|
||||||
[NSCharacterSet whitespaceCharacterSet]]) {
|
|
||||||
if (part.length > 0) {
|
|
||||||
[tokens addObject:part];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (tokens.count > 1) {
|
|
||||||
snprintf(hash_out, hash_out_len, "%s", [tokens[1] UTF8String]);
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hash_out[0] == '\0') {
|
|
||||||
NSString *msg = [NSString stringWithFormat:
|
|
||||||
@"created key '%s' but found no hash for it in sc_auth list-ctk-identities",
|
|
||||||
label];
|
|
||||||
snprintf_error(error_out, error_out_len, msg);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int se_copy_public_key(const char *label,
|
|
||||||
uint8_t *pub_key_out, int *pub_key_len,
|
|
||||||
char *error_out, int error_out_len) {
|
|
||||||
@autoreleasepool {
|
|
||||||
SecKeyRef privateKey = lookup_ctk_private_key(label, error_out, error_out_len);
|
|
||||||
if (!privateKey) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
SecKeyRef publicKey = SecKeyCopyPublicKey(privateKey);
|
|
||||||
CFRelease(privateKey);
|
|
||||||
|
|
||||||
if (!publicKey) {
|
|
||||||
snprintf_error(error_out, error_out_len, @"failed to get public key");
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
CFErrorRef cfError = NULL;
|
|
||||||
CFDataRef pubKeyData = SecKeyCopyExternalRepresentation(publicKey, &cfError);
|
|
||||||
CFRelease(publicKey);
|
|
||||||
|
|
||||||
if (!pubKeyData) {
|
|
||||||
NSError *err = (__bridge_transfer NSError *)cfError;
|
|
||||||
NSString *msg = [NSString stringWithFormat:@"failed to export public key: %@",
|
|
||||||
err.localizedDescription];
|
|
||||||
snprintf_error(error_out, error_out_len, msg);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
const UInt8 *bytes = CFDataGetBytePtr(pubKeyData);
|
|
||||||
CFIndex length = CFDataGetLength(pubKeyData);
|
|
||||||
|
|
||||||
if (length > *pub_key_len) {
|
|
||||||
CFRelease(pubKeyData);
|
|
||||||
snprintf_error(error_out, error_out_len, @"public key buffer too small");
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
memcpy(pub_key_out, bytes, length);
|
|
||||||
*pub_key_len = (int)length;
|
|
||||||
CFRelease(pubKeyData);
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int se_encrypt(const char *label,
|
|
||||||
const uint8_t *plaintext, int plaintext_len,
|
|
||||||
uint8_t *ciphertext_out, int *ciphertext_len,
|
|
||||||
char *error_out, int error_out_len) {
|
|
||||||
@autoreleasepool {
|
|
||||||
SecKeyRef privateKey = lookup_ctk_private_key(label, error_out, error_out_len);
|
|
||||||
if (!privateKey) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
SecKeyRef publicKey = SecKeyCopyPublicKey(privateKey);
|
|
||||||
CFRelease(privateKey);
|
|
||||||
|
|
||||||
if (!publicKey) {
|
|
||||||
snprintf_error(error_out, error_out_len, @"failed to get public key for encryption");
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSData *plaintextData = [NSData dataWithBytes:plaintext length:plaintext_len];
|
|
||||||
|
|
||||||
CFErrorRef cfError = NULL;
|
|
||||||
CFDataRef encrypted = SecKeyCreateEncryptedData(
|
|
||||||
publicKey,
|
|
||||||
kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA256AESGCM,
|
|
||||||
(__bridge CFDataRef)plaintextData,
|
|
||||||
&cfError
|
|
||||||
);
|
|
||||||
CFRelease(publicKey);
|
|
||||||
|
|
||||||
if (!encrypted) {
|
|
||||||
NSError *nsError = (__bridge_transfer NSError *)cfError;
|
|
||||||
NSString *msg = [NSString stringWithFormat:@"ECIES encryption failed: %@",
|
|
||||||
nsError.localizedDescription];
|
|
||||||
snprintf_error(error_out, error_out_len, msg);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
const UInt8 *encBytes = CFDataGetBytePtr(encrypted);
|
|
||||||
CFIndex encLength = CFDataGetLength(encrypted);
|
|
||||||
|
|
||||||
if (encLength > *ciphertext_len) {
|
|
||||||
CFRelease(encrypted);
|
|
||||||
snprintf_error(error_out, error_out_len, @"ciphertext buffer too small");
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
memcpy(ciphertext_out, encBytes, encLength);
|
|
||||||
*ciphertext_len = (int)encLength;
|
|
||||||
CFRelease(encrypted);
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int se_decrypt(const char *label,
|
|
||||||
const uint8_t *ciphertext, int ciphertext_len,
|
|
||||||
uint8_t *plaintext_out, int *plaintext_len,
|
|
||||||
char *error_out, int error_out_len) {
|
|
||||||
@autoreleasepool {
|
|
||||||
SecKeyRef privateKey = lookup_ctk_private_key(label, error_out, error_out_len);
|
|
||||||
if (!privateKey) {
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSData *ciphertextData = [NSData dataWithBytes:ciphertext length:ciphertext_len];
|
|
||||||
|
|
||||||
CFErrorRef cfError = NULL;
|
|
||||||
CFDataRef decrypted = SecKeyCreateDecryptedData(
|
|
||||||
privateKey,
|
|
||||||
kSecKeyAlgorithmECIESEncryptionStandardVariableIVX963SHA256AESGCM,
|
|
||||||
(__bridge CFDataRef)ciphertextData,
|
|
||||||
&cfError
|
|
||||||
);
|
|
||||||
CFRelease(privateKey);
|
|
||||||
|
|
||||||
if (!decrypted) {
|
|
||||||
NSError *nsError = (__bridge_transfer NSError *)cfError;
|
|
||||||
NSString *msg = [NSString stringWithFormat:@"ECIES decryption failed: %@",
|
|
||||||
nsError.localizedDescription];
|
|
||||||
snprintf_error(error_out, error_out_len, msg);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
const UInt8 *decBytes = CFDataGetBytePtr(decrypted);
|
|
||||||
CFIndex decLength = CFDataGetLength(decrypted);
|
|
||||||
|
|
||||||
if (decLength > *plaintext_len) {
|
|
||||||
CFRelease(decrypted);
|
|
||||||
snprintf_error(error_out, error_out_len, @"plaintext buffer too small");
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
memcpy(plaintext_out, decBytes, decLength);
|
|
||||||
*plaintext_len = (int)decLength;
|
|
||||||
CFRelease(decrypted);
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int se_delete_key(const char *hash,
|
|
||||||
char *error_out, int error_out_len) {
|
|
||||||
@autoreleasepool {
|
|
||||||
NSTask *task = [[NSTask alloc] init];
|
|
||||||
task.executableURL = [NSURL fileURLWithPath:@"/usr/sbin/sc_auth"];
|
|
||||||
task.arguments = @[
|
|
||||||
@"delete-ctk-identity",
|
|
||||||
@"-h", [NSString stringWithUTF8String:hash],
|
|
||||||
];
|
|
||||||
|
|
||||||
NSPipe *stderrPipe = [NSPipe pipe];
|
|
||||||
task.standardOutput = [NSPipe pipe];
|
|
||||||
task.standardError = stderrPipe;
|
|
||||||
|
|
||||||
NSError *nsError = nil;
|
|
||||||
if (![task launchAndReturnError:&nsError]) {
|
|
||||||
NSString *msg = [NSString stringWithFormat:@"failed to launch sc_auth: %@",
|
|
||||||
nsError.localizedDescription];
|
|
||||||
snprintf_error(error_out, error_out_len, msg);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
[task waitUntilExit];
|
|
||||||
|
|
||||||
if (task.terminationStatus != 0) {
|
|
||||||
NSData *stderrData = [stderrPipe.fileHandleForReading readDataToEndOfFile];
|
|
||||||
NSString *stderrStr = [[NSString alloc] initWithData:stderrData
|
|
||||||
encoding:NSUTF8StringEncoding];
|
|
||||||
NSString *msg = [NSString stringWithFormat:@"sc_auth delete failed: %@",
|
|
||||||
stderrStr ?: @"unknown error"];
|
|
||||||
snprintf_error(error_out, error_out_len, msg);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -12,7 +12,6 @@ import (
|
|||||||
"github.com/spf13/afero"
|
"github.com/spf13/afero"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"sneak.berlin/go/secret/internal/macse"
|
|
||||||
"sneak.berlin/go/secret/internal/secret"
|
"sneak.berlin/go/secret/internal/secret"
|
||||||
"sneak.berlin/go/secret/internal/vault"
|
"sneak.berlin/go/secret/internal/vault"
|
||||||
)
|
)
|
||||||
@@ -900,42 +899,3 @@ func TestWriteDirRefusesExistingDir(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSecureEnclaveUnlockerFailureDeletesKey makes moving a new Secure
|
|
||||||
// Enclave unlocker into place fail after its Secure Enclave key is created:
|
|
||||||
// the key must be deleted again. Skipped when the add fails before that, as
|
|
||||||
// it does everywhere but in a macOS build with cgo on a Mac with a Secure
|
|
||||||
// Enclave.
|
|
||||||
func TestSecureEnclaveUnlockerFailureDeletesKey(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
mnemonic := testMnemonicBuffer(t)
|
|
||||||
base := afero.NewMemMapFs()
|
|
||||||
_, err := vault.CreateVault(base, testVaultStateDir, testVaultName, mnemonic, nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// The unlocker's directory is named se-<label of its Secure Enclave key>
|
|
||||||
var seKeyLabel string
|
|
||||||
|
|
||||||
fs := hookFs{Fs: base, before: func(op, path string) error {
|
|
||||||
if op == opRename && filepath.Base(filepath.Dir(path)) == "unlockers.d" {
|
|
||||||
seKeyLabel = strings.TrimPrefix(filepath.Base(path), "se-")
|
|
||||||
|
|
||||||
return errInjected
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}}
|
|
||||||
|
|
||||||
_, err = secret.CreateSecureEnclaveUnlocker(fs, testVaultStateDir, mnemonic,
|
|
||||||
nil)
|
|
||||||
|
|
||||||
if seKeyLabel == "" {
|
|
||||||
t.Skipf("the add failed before moving the unlocker into place: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
require.ErrorIs(t, err, errInjected)
|
|
||||||
|
|
||||||
_, err = macse.Encrypt(seKeyLabel, []byte("test"))
|
|
||||||
assert.Error(t, err, "Secure Enclave key left behind")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -18,9 +18,9 @@ const (
|
|||||||
EnvGPGKeyID = "SB_GPG_KEY_ID"
|
EnvGPGKeyID = "SB_GPG_KEY_ID"
|
||||||
|
|
||||||
// UnlockerTimeFormat is the layout of the time, in UTC, in the name of a
|
// UnlockerTimeFormat is the layout of the time, in UTC, in the name of a
|
||||||
// new unlocker's directory, keychain item and Secure Enclave key. It runs
|
// new unlocker's directory. It runs to the nanosecond, so that every new
|
||||||
// to the nanosecond, so that every new unlocker, even one added right
|
// unlocker, even one added right after another, gets a directory of its
|
||||||
// after another, gets a directory of its own.
|
// own.
|
||||||
UnlockerTimeFormat = "2006-01-02.15.04.05.000000000"
|
UnlockerTimeFormat = "2006-01-02.15.04.05.000000000"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -20,8 +20,7 @@ var (
|
|||||||
"stdin is not a terminal (piped input or script)")
|
"stdin is not a terminal (piped input or script)")
|
||||||
errStderrNotTerminal = errors.New(
|
errStderrNotTerminal = errors.New(
|
||||||
"stderr is not a terminal (running in non-interactive mode)")
|
"stderr is not a terminal (running in non-interactive mode)")
|
||||||
errNothingEntered = errors.New("nothing was entered")
|
errNothingEntered = errors.New("nothing was entered")
|
||||||
errEmptyPassphrase = errors.New("passphrase cannot be empty")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// ErrMnemonicNotRead is wrapped in every error of ReadMnemonic: there is no
|
// ErrMnemonicNotRead is wrapped in every error of ReadMnemonic: there is no
|
||||||
|
|||||||
@@ -1,118 +0,0 @@
|
|||||||
//go:build darwin
|
|
||||||
|
|
||||||
//nolint:testpackage // white-box test of unexported getLongTermPrivateKey
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"filippo.io/age"
|
|
||||||
"github.com/awnumar/memguard"
|
|
||||||
"github.com/spf13/afero"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"sneak.berlin/go/secret/pkg/agehd"
|
|
||||||
)
|
|
||||||
|
|
||||||
// realVault is a minimal VaultInterface backed by a real afero filesystem,
|
|
||||||
// using the same directory layout as vault.Vault.
|
|
||||||
type realVault struct {
|
|
||||||
name string
|
|
||||||
stateDir string
|
|
||||||
fs afero.Fs
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *realVault) GetDirectory() (string, error) {
|
|
||||||
return filepath.Join(v.stateDir, "vaults.d", v.name), nil
|
|
||||||
}
|
|
||||||
func (v *realVault) GetName() string { return v.name }
|
|
||||||
|
|
||||||
//nolint:ireturn // implements VaultInterface
|
|
||||||
func (v *realVault) GetFilesystem() afero.Fs { return v.fs }
|
|
||||||
|
|
||||||
// Unused by getLongTermPrivateKey — these satisfy VaultInterface.
|
|
||||||
func (v *realVault) AddSecret(string, *memguard.LockedBuffer, bool) error {
|
|
||||||
panic("not used")
|
|
||||||
}
|
|
||||||
|
|
||||||
//nolint:ireturn // implements VaultInterface
|
|
||||||
func (v *realVault) GetCurrentUnlocker() (Unlocker, error) {
|
|
||||||
panic("not used")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *realVault) GetOrDeriveLongTermKey() (*age.X25519Identity, error) {
|
|
||||||
panic("not used")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *realVault) SetMnemonic(*memguard.LockedBuffer) {
|
|
||||||
panic("not used")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *realVault) SetUnlockPassphrase(*memguard.LockedBuffer) {
|
|
||||||
panic("not used")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *realVault) CreatePassphraseUnlocker(
|
|
||||||
*memguard.LockedBuffer,
|
|
||||||
) (*PassphraseUnlocker, error) {
|
|
||||||
panic("not used")
|
|
||||||
}
|
|
||||||
|
|
||||||
// createRealVault sets up a complete vault directory structure on an in-memory
|
|
||||||
// filesystem, identical to what vault.CreateVault produces.
|
|
||||||
func createRealVault(
|
|
||||||
t *testing.T, fs afero.Fs, stateDir, name string, derivationIndex uint32,
|
|
||||||
) *realVault {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
vaultDir := filepath.Join(stateDir, "vaults.d", name)
|
|
||||||
require.NoError(t, fs.MkdirAll(filepath.Join(vaultDir, "secrets.d"), DirPerms))
|
|
||||||
require.NoError(t, fs.MkdirAll(filepath.Join(vaultDir, "unlockers.d"), DirPerms))
|
|
||||||
|
|
||||||
metadata := VaultMetadata{
|
|
||||||
CreatedAt: time.Now(),
|
|
||||||
DerivationIndex: derivationIndex,
|
|
||||||
}
|
|
||||||
metaBytes, err := json.Marshal(metadata)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.NoError(t, afero.WriteFile(fs,
|
|
||||||
filepath.Join(vaultDir, "vault-metadata.json"), metaBytes, FilePerms))
|
|
||||||
|
|
||||||
return &realVault{name: name, stateDir: stateDir, fs: fs}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGetLongTermPrivateKeyUsesVaultDerivationIndex(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
//nolint:dupword // BIP39 test mnemonic repeats words by design
|
|
||||||
const testMnemonic = "abandon abandon abandon abandon abandon abandon " +
|
|
||||||
"abandon abandon abandon abandon abandon about"
|
|
||||||
|
|
||||||
// Derive expected keys at two different indices to prove they differ.
|
|
||||||
key0, err := agehd.DeriveIdentity(testMnemonic, 0)
|
|
||||||
require.NoError(t, err)
|
|
||||||
key5, err := agehd.DeriveIdentity(testMnemonic, 5)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.NotEqual(t, key0.String(), key5.String(),
|
|
||||||
"sanity check: different derivation indices must produce different keys")
|
|
||||||
|
|
||||||
// Build a real vault with DerivationIndex=5 on an in-memory filesystem.
|
|
||||||
fs := afero.NewMemMapFs()
|
|
||||||
vault := createRealVault(t, fs, "/state", "test-vault", 5)
|
|
||||||
|
|
||||||
mnemonic := memguard.NewBufferFromBytes([]byte(testMnemonic))
|
|
||||||
defer mnemonic.Destroy()
|
|
||||||
|
|
||||||
result, err := getLongTermPrivateKey(fs, vault, mnemonic, nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
defer result.Destroy()
|
|
||||||
|
|
||||||
assert.Equal(t, key5.String(), string(result.Bytes()),
|
|
||||||
"getLongTermPrivateKey should derive at vault's DerivationIndex (5)")
|
|
||||||
assert.NotEqual(t, key0.String(), string(result.Bytes()),
|
|
||||||
"getLongTermPrivateKey must not use hardcoded index 0")
|
|
||||||
}
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/awnumar/memguard"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
errPassphraseLength = errors.New(
|
|
||||||
"passphrase length must be a positive even number")
|
|
||||||
errPassphraseNotHex = errors.New(
|
|
||||||
"keychain passphrase must be lowercase hex")
|
|
||||||
errNoKeychainPassphrase = errors.New(
|
|
||||||
"keychain data has no agePrivKeyPassphrase string")
|
|
||||||
)
|
|
||||||
|
|
||||||
// KeychainData is what a keychain unlocker stores in the macOS keychain.
|
|
||||||
// It is stored as JSON, but encode and decodeKeychainData keep the
|
|
||||||
// passphrase out of encoding/json, which would leave copies of it in
|
|
||||||
// ordinary memory.
|
|
||||||
type KeychainData struct {
|
|
||||||
AgePublicKey string
|
|
||||||
AgePrivKeyPassphrase *memguard.LockedBuffer
|
|
||||||
EncryptedLongtermKey string
|
|
||||||
}
|
|
||||||
|
|
||||||
// generateRandomPassphrase returns length random lowercase hex characters
|
|
||||||
// in a locked buffer. The caller must destroy it.
|
|
||||||
func generateRandomPassphrase(length int) (*memguard.LockedBuffer, error) {
|
|
||||||
// Each random byte becomes two hex characters.
|
|
||||||
randomBytes := hex.DecodedLen(length)
|
|
||||||
if length <= 0 || hex.EncodedLen(randomBytes) != length {
|
|
||||||
return nil, errPassphraseLength
|
|
||||||
}
|
|
||||||
|
|
||||||
random := memguard.NewBufferRandom(randomBytes)
|
|
||||||
defer random.Destroy()
|
|
||||||
|
|
||||||
passphrase := memguard.NewBuffer(length)
|
|
||||||
hex.Encode(passphrase.Bytes(), random.Bytes())
|
|
||||||
passphrase.Freeze()
|
|
||||||
|
|
||||||
return passphrase, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// encode returns d as JSON in a locked buffer:
|
|
||||||
// {"agePublicKey":"...","agePrivKeyPassphrase":"...","encryptedLongtermKey":"..."}.
|
|
||||||
// The passphrase is copied straight into the buffer, so it must be hex,
|
|
||||||
// which JSON does not escape. The caller must destroy the returned buffer.
|
|
||||||
func (d *KeychainData) encode() (*memguard.LockedBuffer, error) {
|
|
||||||
if d.AgePrivKeyPassphrase == nil {
|
|
||||||
return nil, errNilPassphraseBuffer
|
|
||||||
}
|
|
||||||
|
|
||||||
if d.AgePrivKeyPassphrase.Size() == 0 {
|
|
||||||
return nil, errEmptyPassphrase
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, c := range d.AgePrivKeyPassphrase.Bytes() {
|
|
||||||
if strings.IndexByte("0123456789abcdef", c) < 0 {
|
|
||||||
return nil, errPassphraseNotHex
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
publicKey, err := json.Marshal(d.AgePublicKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to encode age public key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
longtermKey, err := json.Marshal(d.EncryptedLongtermKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to encode long-term key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
parts := [][]byte{
|
|
||||||
[]byte(`{"agePublicKey":`), publicKey,
|
|
||||||
[]byte(`,"agePrivKeyPassphrase":"`), d.AgePrivKeyPassphrase.Bytes(),
|
|
||||||
[]byte(`","encryptedLongtermKey":`), longtermKey,
|
|
||||||
[]byte(`}`),
|
|
||||||
}
|
|
||||||
|
|
||||||
size := 0
|
|
||||||
for _, part := range parts {
|
|
||||||
size += len(part)
|
|
||||||
}
|
|
||||||
|
|
||||||
encoded := memguard.NewBuffer(size)
|
|
||||||
|
|
||||||
written := 0
|
|
||||||
for _, part := range parts {
|
|
||||||
written += copy(encoded.Bytes()[written:], part)
|
|
||||||
}
|
|
||||||
|
|
||||||
encoded.Freeze()
|
|
||||||
|
|
||||||
return encoded, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// decodeKeychainData parses keychain data written by encode. The caller
|
|
||||||
// must destroy the returned AgePrivKeyPassphrase.
|
|
||||||
func decodeKeychainData(data *memguard.LockedBuffer) (*KeychainData, error) {
|
|
||||||
if data == nil {
|
|
||||||
return nil, errNilDataBuffer
|
|
||||||
}
|
|
||||||
|
|
||||||
// json.Unmarshal gives a json.RawMessage field the field's JSON text
|
|
||||||
// unchanged, in the one copy RawMessage makes; it is wiped on return.
|
|
||||||
var fields struct {
|
|
||||||
AgePublicKey string `json:"agePublicKey"`
|
|
||||||
AgePrivKeyPassphrase json.RawMessage `json:"agePrivKeyPassphrase"`
|
|
||||||
EncryptedLongtermKey string `json:"encryptedLongtermKey"`
|
|
||||||
}
|
|
||||||
|
|
||||||
defer func() { memguard.WipeBytes(fields.AgePrivKeyPassphrase) }()
|
|
||||||
|
|
||||||
err := json.Unmarshal(data.Bytes(), &fields)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to parse keychain data: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// json.Unmarshal accepted the JSON, so text that starts with a quote is
|
|
||||||
// a whole string. The passphrase is hex, so it is the text between the
|
|
||||||
// quotes.
|
|
||||||
quoted := fields.AgePrivKeyPassphrase
|
|
||||||
if !bytes.HasPrefix(quoted, []byte(`"`)) {
|
|
||||||
return nil, errNoKeychainPassphrase
|
|
||||||
}
|
|
||||||
|
|
||||||
return &KeychainData{
|
|
||||||
AgePublicKey: fields.AgePublicKey,
|
|
||||||
// NewBufferFromBytes wipes the bytes it copies.
|
|
||||||
AgePrivKeyPassphrase: memguard.NewBufferFromBytes(
|
|
||||||
quoted[1 : len(quoted)-1]),
|
|
||||||
EncryptedLongtermKey: fields.EncryptedLongtermKey,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
//nolint:testpackage // white-box test of unexported internals
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/awnumar/memguard"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestGenerateRandomPassphrase(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
first, err := generateRandomPassphrase(64)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
defer first.Destroy()
|
|
||||||
|
|
||||||
second, err := generateRandomPassphrase(64)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
defer second.Destroy()
|
|
||||||
|
|
||||||
assert.Regexp(t, `^[0-9a-f]{64}$`, first.String())
|
|
||||||
assert.NotEqual(t, first.String(), second.String())
|
|
||||||
assert.False(t, first.IsMutable())
|
|
||||||
|
|
||||||
for _, length := range []int{0, -2, 63} {
|
|
||||||
_, err := generateRandomPassphrase(length)
|
|
||||||
require.ErrorIs(t, err, errPassphraseLength, "length %d", length)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestKeychainDataEncodeDecode(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
passphrase := memguard.NewBufferFromBytes([]byte("0a1b2c3d"))
|
|
||||||
defer passphrase.Destroy()
|
|
||||||
|
|
||||||
data := KeychainData{
|
|
||||||
AgePublicKey: "age1example",
|
|
||||||
AgePrivKeyPassphrase: passphrase,
|
|
||||||
EncryptedLongtermKey: "beef",
|
|
||||||
}
|
|
||||||
|
|
||||||
encoded, err := data.encode()
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
defer encoded.Destroy()
|
|
||||||
|
|
||||||
assert.JSONEq(t,
|
|
||||||
`{"agePublicKey":"age1example",`+
|
|
||||||
`"agePrivKeyPassphrase":"0a1b2c3d",`+
|
|
||||||
`"encryptedLongtermKey":"beef"}`,
|
|
||||||
encoded.String())
|
|
||||||
assert.False(t, encoded.IsMutable())
|
|
||||||
|
|
||||||
decoded, err := decodeKeychainData(encoded)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
defer decoded.AgePrivKeyPassphrase.Destroy()
|
|
||||||
|
|
||||||
assert.Equal(t, "age1example", decoded.AgePublicKey)
|
|
||||||
assert.Equal(t, "0a1b2c3d", decoded.AgePrivKeyPassphrase.String())
|
|
||||||
assert.Equal(t, "beef", decoded.EncryptedLongtermKey)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestKeychainDataEncodeRejectsBadPassphrase(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
passphrase *memguard.LockedBuffer
|
|
||||||
wantErr error
|
|
||||||
}{
|
|
||||||
{"nil", nil, errNilPassphraseBuffer},
|
|
||||||
{"empty", memguard.NewBuffer(0), errEmptyPassphrase},
|
|
||||||
{
|
|
||||||
"not hex",
|
|
||||||
memguard.NewBufferFromBytes([]byte(`abc"def`)),
|
|
||||||
errPassphraseNotHex,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
data := KeychainData{AgePrivKeyPassphrase: tt.passphrase}
|
|
||||||
_, err := data.encode()
|
|
||||||
require.ErrorIs(t, err, tt.wantErr)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDecodeKeychainDataRejectsBadData(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
for _, text := range []string{
|
|
||||||
`{"agePublicKey":"age1example"}`,
|
|
||||||
`{"agePrivKeyPassphrase":42}`,
|
|
||||||
} {
|
|
||||||
data := memguard.NewBufferFromBytes([]byte(text))
|
|
||||||
_, err := decodeKeychainData(data)
|
|
||||||
data.Destroy()
|
|
||||||
require.ErrorIs(t, err, errNoKeychainPassphrase, text)
|
|
||||||
}
|
|
||||||
|
|
||||||
notJSON := memguard.NewBufferFromBytes([]byte(`{"agePrivKeyPassphrase":`))
|
|
||||||
defer notJSON.Destroy()
|
|
||||||
|
|
||||||
_, err := decodeKeychainData(notJSON)
|
|
||||||
|
|
||||||
var syntaxError *json.SyntaxError
|
|
||||||
require.ErrorAs(t, err, &syntaxError)
|
|
||||||
}
|
|
||||||
@@ -1,561 +0,0 @@
|
|||||||
//go:build darwin
|
|
||||||
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"regexp"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"filippo.io/age"
|
|
||||||
"github.com/awnumar/memguard"
|
|
||||||
"github.com/spf13/afero"
|
|
||||||
"sneak.berlin/go/secret/pkg/agehd"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
agePrivKeyPassphraseLength = 64
|
|
||||||
// KEYCHAIN_APP_IDENTIFIER is the service name used for keychain items
|
|
||||||
//
|
|
||||||
//nolint:revive // ALL_CAPS is intentional for this constant
|
|
||||||
KEYCHAIN_APP_IDENTIFIER = "berlin.sneak.app.secret"
|
|
||||||
|
|
||||||
// keychainUnlockerType is the metadata type string for keychain unlockers.
|
|
||||||
keychainUnlockerType = "keychain"
|
|
||||||
|
|
||||||
// macOSFlag is the unlocker metadata flag of the macOS-only unlockers.
|
|
||||||
macOSFlag = "macos"
|
|
||||||
)
|
|
||||||
|
|
||||||
// keychainItemNameRegex validates keychain item names
|
|
||||||
// Allows alphanumeric characters, dots, hyphens, and underscores only
|
|
||||||
var keychainItemNameRegex = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
|
|
||||||
|
|
||||||
var (
|
|
||||||
errKeychainItemNameEmpty = errors.New("keychain item name cannot be empty")
|
|
||||||
errInvalidKeychainItemName = errors.New("invalid keychain item name format")
|
|
||||||
errUnsupportedCurrentUnlocker = errors.New(
|
|
||||||
"unsupported current unlocker type for keychain unlocker creation")
|
|
||||||
)
|
|
||||||
|
|
||||||
// KeychainUnlockerMetadata extends UnlockerMetadata with keychain-specific data
|
|
||||||
type KeychainUnlockerMetadata struct {
|
|
||||||
UnlockerMetadata
|
|
||||||
|
|
||||||
// Keychain item name
|
|
||||||
KeychainItemName string `json:"keychainItemName"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// KeychainUnlocker represents a macOS Keychain-protected unlocker
|
|
||||||
type KeychainUnlocker struct {
|
|
||||||
Directory string
|
|
||||||
Metadata UnlockerMetadata
|
|
||||||
fs afero.Fs
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewKeychainUnlocker creates a new KeychainUnlocker instance
|
|
||||||
func NewKeychainUnlocker(
|
|
||||||
fs afero.Fs, directory string, metadata UnlockerMetadata,
|
|
||||||
) *KeychainUnlocker {
|
|
||||||
return &KeychainUnlocker{
|
|
||||||
Directory: directory,
|
|
||||||
Metadata: metadata,
|
|
||||||
fs: fs,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIdentity implements Unlocker interface for Keychain-based unlockers
|
|
||||||
func (k *KeychainUnlocker) GetIdentity() (*age.X25519Identity, error) {
|
|
||||||
DebugWith("Getting keychain unlocker identity",
|
|
||||||
slog.String("unlocker_id", k.GetID()),
|
|
||||||
slog.String("unlocker_type", k.GetType()),
|
|
||||||
)
|
|
||||||
|
|
||||||
keychainData, err := k.readKeychainData()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer keychainData.AgePrivKeyPassphrase.Destroy()
|
|
||||||
|
|
||||||
// Step 4: Read the encrypted age private key from filesystem
|
|
||||||
agePrivKeyPath := filepath.Join(k.Directory, "priv.age")
|
|
||||||
Debug("Reading encrypted age private key", "path", agePrivKeyPath)
|
|
||||||
|
|
||||||
encryptedAgePrivKeyData, err := afero.ReadFile(k.fs, agePrivKeyPath)
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to read encrypted age private key",
|
|
||||||
"error", err, "path", agePrivKeyPath)
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("failed to read encrypted age private key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
DebugWith("Read encrypted age private key",
|
|
||||||
slog.String("unlocker_id", k.GetID()),
|
|
||||||
slog.Int("encrypted_length", len(encryptedAgePrivKeyData)),
|
|
||||||
)
|
|
||||||
|
|
||||||
// Step 5: Decrypt the age private key using the passphrase from keychain
|
|
||||||
Debug("Decrypting age private key with keychain passphrase",
|
|
||||||
"unlocker_id", k.GetID())
|
|
||||||
|
|
||||||
agePrivKeyBuffer, err := DecryptWithPassphrase(
|
|
||||||
encryptedAgePrivKeyData, keychainData.AgePrivKeyPassphrase)
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to decrypt age private key with keychain passphrase",
|
|
||||||
"error", err, "unlocker_id", k.GetID())
|
|
||||||
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"failed to decrypt age private key with keychain passphrase: %w", err)
|
|
||||||
}
|
|
||||||
defer agePrivKeyBuffer.Destroy()
|
|
||||||
|
|
||||||
DebugWith("Successfully decrypted age private key with keychain passphrase",
|
|
||||||
slog.String("unlocker_id", k.GetID()),
|
|
||||||
slog.Int("decrypted_length", agePrivKeyBuffer.Size()),
|
|
||||||
)
|
|
||||||
|
|
||||||
// Step 6: Parse the decrypted age private key
|
|
||||||
Debug("Parsing decrypted age private key", "unlocker_id", k.GetID())
|
|
||||||
|
|
||||||
ageIdentity, err := age.ParseX25519Identity(agePrivKeyBuffer.String())
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to parse age private key", "error", err, "unlocker_id", k.GetID())
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("failed to parse age private key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
DebugWith("Successfully parsed keychain age identity",
|
|
||||||
slog.String("unlocker_id", k.GetID()),
|
|
||||||
slog.String("public_key", ageIdentity.Recipient().String()),
|
|
||||||
)
|
|
||||||
|
|
||||||
return ageIdentity, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetType implements Unlocker interface
|
|
||||||
func (k *KeychainUnlocker) GetType() string {
|
|
||||||
return keychainUnlockerType
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetMetadata implements Unlocker interface
|
|
||||||
func (k *KeychainUnlocker) GetMetadata() UnlockerMetadata {
|
|
||||||
return k.Metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetDirectory implements Unlocker interface
|
|
||||||
func (k *KeychainUnlocker) GetDirectory() string {
|
|
||||||
return k.Directory
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID implements Unlocker interface: the name of the unlocker's directory
|
|
||||||
func (k *KeychainUnlocker) GetID() string {
|
|
||||||
return filepath.Base(k.Directory)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove implements Unlocker interface - removes the keychain unlocker
|
|
||||||
func (k *KeychainUnlocker) Remove() error {
|
|
||||||
// Step 1: Get keychain item name
|
|
||||||
keychainItemName, err := k.GetKeychainItemName()
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to get keychain item name during removal",
|
|
||||||
"error", err, "unlocker_id", k.GetID())
|
|
||||||
|
|
||||||
return fmt.Errorf("failed to get keychain item name: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 2: Remove from keychain
|
|
||||||
Debug("Removing keychain item", "keychain_item", keychainItemName)
|
|
||||||
|
|
||||||
err = deleteFromKeychain(keychainItemName)
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to remove keychain item",
|
|
||||||
"error", err, "keychain_item", keychainItemName)
|
|
||||||
|
|
||||||
return fmt.Errorf("failed to remove keychain item: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 3: Remove directory
|
|
||||||
Debug("Removing keychain unlocker directory", "directory", k.Directory)
|
|
||||||
|
|
||||||
err = RemoveDirAtomic(k.fs, k.Directory)
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to remove keychain unlocker directory",
|
|
||||||
"error", err, "directory", k.Directory)
|
|
||||||
|
|
||||||
return fmt.Errorf("failed to remove keychain unlocker directory: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
Debug("Successfully removed keychain unlocker",
|
|
||||||
"unlocker_id", k.GetID(), "keychain_item", keychainItemName)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetKeychainItemName returns the keychain item name from metadata
|
|
||||||
func (k *KeychainUnlocker) GetKeychainItemName() (string, error) {
|
|
||||||
// Load the metadata
|
|
||||||
metadataPath := filepath.Join(k.Directory, "unlocker-metadata.json")
|
|
||||||
|
|
||||||
metadataData, err := afero.ReadFile(k.fs, metadataPath)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to read keychain metadata: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var keychainMetadata KeychainUnlockerMetadata
|
|
||||||
|
|
||||||
err = json.Unmarshal(metadataData, &keychainMetadata)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to parse keychain metadata: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return keychainMetadata.KeychainItemName, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// readKeychainData reads and parses the data this unlocker keeps in the
|
|
||||||
// keychain (steps 1 to 3 of GetIdentity). The caller must destroy the
|
|
||||||
// returned AgePrivKeyPassphrase.
|
|
||||||
func (k *KeychainUnlocker) readKeychainData() (*KeychainData, error) {
|
|
||||||
// Step 1: Get keychain item name
|
|
||||||
keychainItemName, err := k.GetKeychainItemName()
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to get keychain item name", "error", err, "unlocker_id", k.GetID())
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("failed to get keychain item name: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 2: Retrieve data from keychain
|
|
||||||
Debug("Retrieving data from macOS keychain", "keychain_item", keychainItemName)
|
|
||||||
|
|
||||||
keychainDataBytes, err := retrieveFromKeychain(keychainItemName)
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to retrieve data from keychain",
|
|
||||||
"error", err, "keychain_item", keychainItemName)
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("failed to retrieve data from keychain: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
DebugWith("Retrieved data from keychain",
|
|
||||||
slog.String("unlocker_id", k.GetID()),
|
|
||||||
slog.Int("data_length", len(keychainDataBytes)),
|
|
||||||
)
|
|
||||||
|
|
||||||
// Move the keychain data into locked memory; this wipes keychainDataBytes
|
|
||||||
keychainDataBuffer := memguard.NewBufferFromBytes(keychainDataBytes)
|
|
||||||
defer keychainDataBuffer.Destroy()
|
|
||||||
|
|
||||||
// Step 3: Parse keychain data
|
|
||||||
keychainData, err := decodeKeychainData(keychainDataBuffer)
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to parse keychain data", "error", err, "unlocker_id", k.GetID())
|
|
||||||
|
|
||||||
return nil, fmt.Errorf("failed to parse keychain data: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
Debug("Parsed keychain data successfully", "unlocker_id", k.GetID())
|
|
||||||
|
|
||||||
return keychainData, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// generateKeychainUnlockerName generates a unique name for the keychain unlocker
|
|
||||||
func generateKeychainUnlockerName(vaultName string) (string, error) {
|
|
||||||
hostname, err := os.Hostname()
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to get hostname: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Format: secret-<vault>-<hostname>-<time>
|
|
||||||
enrollmentTime := time.Now().UTC().Format(UnlockerTimeFormat)
|
|
||||||
|
|
||||||
return fmt.Sprintf("secret-%s-%s-%s", vaultName, hostname, enrollmentTime), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// getLongTermPrivateKey derives the long-term private key from mnemonic when
|
|
||||||
// it is not nil, else gets it through the current unlocker, which is given
|
|
||||||
// passphrase when it is a passphrase unlocker.
|
|
||||||
// Returns a LockedBuffer to ensure the private key is protected in memory
|
|
||||||
func getLongTermPrivateKey(
|
|
||||||
fs afero.Fs, vault VaultInterface, mnemonic, passphrase *memguard.LockedBuffer,
|
|
||||||
) (*memguard.LockedBuffer, error) {
|
|
||||||
if mnemonic != nil {
|
|
||||||
return deriveLongTermPrivateKey(fs, vault, mnemonic)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the vault to access current unlocker
|
|
||||||
currentUnlocker, err := vault.GetCurrentUnlocker()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get current unlocker: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if passphraseUnlocker, ok := currentUnlocker.(*PassphraseUnlocker); ok {
|
|
||||||
passphraseUnlocker.Passphrase = passphrase
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the current unlocker identity
|
|
||||||
currentUnlockerIdentity, err := currentUnlocker.GetIdentity()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get current unlocker identity: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get encrypted long-term key from current unlocker, handling different types
|
|
||||||
var encryptedLtPrivKey []byte
|
|
||||||
|
|
||||||
switch currentUnlocker := currentUnlocker.(type) {
|
|
||||||
case *PassphraseUnlocker:
|
|
||||||
// Read the encrypted long-term private key from passphrase unlocker
|
|
||||||
encryptedLtPrivKey, err = afero.ReadFile(fs,
|
|
||||||
filepath.Join(currentUnlocker.GetDirectory(), "longterm.age"))
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to read encrypted long-term key "+
|
|
||||||
"from current passphrase unlocker: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
case *PGPUnlocker:
|
|
||||||
// Read the encrypted long-term private key from PGP unlocker
|
|
||||||
encryptedLtPrivKey, err = afero.ReadFile(fs,
|
|
||||||
filepath.Join(currentUnlocker.GetDirectory(), "longterm.age"))
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to read encrypted long-term key "+
|
|
||||||
"from current PGP unlocker: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
case *KeychainUnlocker:
|
|
||||||
// Read the encrypted long-term private key from another keychain
|
|
||||||
// unlocker
|
|
||||||
encryptedLtPrivKey, err = afero.ReadFile(fs,
|
|
||||||
filepath.Join(currentUnlocker.GetDirectory(), "longterm.age"))
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to read encrypted long-term key "+
|
|
||||||
"from current keychain unlocker: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
return nil, errUnsupportedCurrentUnlocker
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decrypt long-term private key using current unlocker
|
|
||||||
ltPrivKeyBuffer, err := DecryptWithIdentity(
|
|
||||||
encryptedLtPrivKey, currentUnlockerIdentity)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to decrypt long-term private key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return the decrypted key buffer
|
|
||||||
return ltPrivKeyBuffer, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// deriveLongTermPrivateKey derives the long-term private key from mnemonic at
|
|
||||||
// the vault's derivation index, for getLongTermPrivateKey and
|
|
||||||
// getLongTermKeyForSE.
|
|
||||||
func deriveLongTermPrivateKey(
|
|
||||||
fs afero.Fs, vault VaultInterface, mnemonic *memguard.LockedBuffer,
|
|
||||||
) (*memguard.LockedBuffer, error) {
|
|
||||||
// Read vault metadata to get the correct derivation index
|
|
||||||
vaultDir, err := vault.GetDirectory()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get vault directory: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
metadataPath := filepath.Join(vaultDir, "vault-metadata.json")
|
|
||||||
|
|
||||||
metadataBytes, err := afero.ReadFile(fs, metadataPath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to read vault metadata: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var metadata VaultMetadata
|
|
||||||
|
|
||||||
err = json.Unmarshal(metadataBytes, &metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to parse vault metadata: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use mnemonic with the vault's actual derivation index
|
|
||||||
ltIdentity, err := agehd.DeriveIdentity(mnemonic.String(), metadata.DerivationIndex)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"failed to derive long-term key from mnemonic: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return IdentityToLockedBuffer(ltIdentity), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateKeychainUnlocker creates a new keychain unlocker and stores it in the
|
|
||||||
// vault. The long-term key comes from mnemonic when it is not nil, else from
|
|
||||||
// the current unlocker, as getLongTermPrivateKey describes.
|
|
||||||
func CreateKeychainUnlocker(
|
|
||||||
fs afero.Fs, stateDir string, mnemonic, passphrase *memguard.LockedBuffer,
|
|
||||||
) (*KeychainUnlocker, error) {
|
|
||||||
// Get current vault using the GetCurrentVault function from the same package
|
|
||||||
vault, err := GetCurrentVault(fs, stateDir)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get current vault: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate the keychain item name
|
|
||||||
keychainItemName, err := generateKeychainUnlockerName(vault.GetName())
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to generate keychain item name: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The unlocker directory is named after the keychain item
|
|
||||||
vaultDir, err := vault.GetDirectory()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get vault directory: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
unlockerDir := filepath.Join(vaultDir, "unlockers.d", keychainItemName)
|
|
||||||
|
|
||||||
// Step 1: Generate a new age keypair for the keychain unlocker
|
|
||||||
ageIdentity, err := age.GenerateX25519Identity()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to generate age keypair: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ageRecipient := ageIdentity.Recipient().String()
|
|
||||||
|
|
||||||
// Step 2: Generate a random passphrase for encrypting the age private key
|
|
||||||
agePrivKeyPassphrase, err := generateRandomPassphrase(agePrivKeyPassphraseLength)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to generate age private key passphrase: %w", err)
|
|
||||||
}
|
|
||||||
defer agePrivKeyPassphrase.Destroy()
|
|
||||||
|
|
||||||
// Step 3: Encrypt age private key with the generated passphrase
|
|
||||||
agePrivKeyBuffer := IdentityToLockedBuffer(ageIdentity)
|
|
||||||
defer agePrivKeyBuffer.Destroy()
|
|
||||||
|
|
||||||
encryptedAgePrivKey, err := EncryptWithPassphrase(
|
|
||||||
agePrivKeyBuffer, agePrivKeyPassphrase)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to encrypt age private key with passphrase: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 4: Get or derive the long-term private key
|
|
||||||
ltPrivKeyData, err := getLongTermPrivateKey(fs, vault, mnemonic, passphrase)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer ltPrivKeyData.Destroy()
|
|
||||||
|
|
||||||
// Step 5: Encrypt long-term private key to the new age unlocker
|
|
||||||
encryptedLtPrivKeyToAge, err := EncryptToRecipient(
|
|
||||||
ltPrivKeyData, ageIdentity.Recipient())
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"failed to encrypt long-term private key to age unlocker: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 6: Prepare keychain data
|
|
||||||
keychainData := KeychainData{
|
|
||||||
AgePublicKey: ageRecipient,
|
|
||||||
AgePrivKeyPassphrase: agePrivKeyPassphrase,
|
|
||||||
EncryptedLongtermKey: hex.EncodeToString(encryptedLtPrivKeyToAge),
|
|
||||||
}
|
|
||||||
|
|
||||||
keychainDataBuffer, err := keychainData.encode()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to encode keychain data: %w", err)
|
|
||||||
}
|
|
||||||
defer keychainDataBuffer.Destroy()
|
|
||||||
|
|
||||||
return writeKeychainUnlocker(fs, unlockerDir, keychainItemName, ageRecipient,
|
|
||||||
encryptedAgePrivKey, encryptedLtPrivKeyToAge, keychainDataBuffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
// writeKeychainUnlocker writes a new keychain unlocker into unlockerDir and
|
|
||||||
// stores its data in the keychain (steps 7 and 8 of CreateKeychainUnlocker).
|
|
||||||
// The data is stored after the unlocker's files are written, and the keychain
|
|
||||||
// item is deleted again if moving the unlocker into place then fails.
|
|
||||||
func writeKeychainUnlocker(
|
|
||||||
fs afero.Fs, unlockerDir, keychainItemName, ageRecipient string,
|
|
||||||
encryptedAgePrivKey, encryptedLtPrivKey []byte,
|
|
||||||
keychainDataBuffer *memguard.LockedBuffer,
|
|
||||||
) (*KeychainUnlocker, error) {
|
|
||||||
// Step 7: Prepare enhanced metadata
|
|
||||||
keychainMetadata := KeychainUnlockerMetadata{
|
|
||||||
UnlockerMetadata: UnlockerMetadata{
|
|
||||||
Type: keychainUnlockerType,
|
|
||||||
CreatedAt: time.Now(),
|
|
||||||
Flags: []string{keychainUnlockerType, macOSFlag},
|
|
||||||
},
|
|
||||||
KeychainItemName: keychainItemName,
|
|
||||||
}
|
|
||||||
|
|
||||||
metadataBytes, err := json.MarshalIndent(keychainMetadata, "", " ")
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to marshal unlocker metadata: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 8: Write the unlocker's files, the metadata last, then store the
|
|
||||||
// data in the keychain
|
|
||||||
stored := false
|
|
||||||
|
|
||||||
err = WriteDir(fs, unlockerDir, func(dir string) error {
|
|
||||||
err := WriteFileAtomic(fs, filepath.Join(dir, "pub.txt"), []byte(ageRecipient))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to write age recipient: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = WriteFileAtomic(fs, filepath.Join(dir, "priv.age"), encryptedAgePrivKey)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to write encrypted age private key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = WriteFileAtomic(fs, filepath.Join(dir, "longterm.age"), encryptedLtPrivKey)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to write encrypted long-term private key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = WriteFileAtomic(fs, filepath.Join(dir, "unlocker-metadata.json"),
|
|
||||||
metadataBytes)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to write unlocker metadata: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = storeInKeychain(keychainItemName, keychainDataBuffer)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to store data in keychain: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
stored = true
|
|
||||||
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil && stored {
|
|
||||||
deleteErr := deleteFromKeychain(keychainItemName)
|
|
||||||
if deleteErr != nil {
|
|
||||||
err = errors.Join(err, fmt.Errorf(
|
|
||||||
"failed to delete keychain item %s: %w", keychainItemName, deleteErr))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &KeychainUnlocker{
|
|
||||||
Directory: unlockerDir,
|
|
||||||
Metadata: keychainMetadata.UnlockerMetadata,
|
|
||||||
fs: fs,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// validateKeychainItemName validates that a keychain item name is safe for
|
|
||||||
// command execution
|
|
||||||
func validateKeychainItemName(itemName string) error {
|
|
||||||
if itemName == "" {
|
|
||||||
return errKeychainItemNameEmpty
|
|
||||||
}
|
|
||||||
|
|
||||||
if !keychainItemNameRegex.MatchString(itemName) {
|
|
||||||
return fmt.Errorf("%w: %s", errInvalidKeychainItemName, itemName)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
//go:build darwin && cgo
|
|
||||||
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/awnumar/memguard"
|
|
||||||
keychain "github.com/keybase/go-keychain"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The keychain unlocker's only calls into go-keychain, which is cgo on macOS.
|
|
||||||
// A macOS build without cgo gets keychainunlocker_nocgo.go instead.
|
|
||||||
|
|
||||||
// storeInKeychain stores data in the macOS keychain using keybase/go-keychain
|
|
||||||
func storeInKeychain(itemName string, data *memguard.LockedBuffer) error {
|
|
||||||
if data == nil {
|
|
||||||
return errNilDataBuffer
|
|
||||||
}
|
|
||||||
if err := validateKeychainItemName(itemName); err != nil {
|
|
||||||
return fmt.Errorf("invalid keychain item name: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
item := keychain.NewItem()
|
|
||||||
item.SetSecClass(keychain.SecClassGenericPassword)
|
|
||||||
item.SetService(KEYCHAIN_APP_IDENTIFIER)
|
|
||||||
item.SetAccount(itemName)
|
|
||||||
item.SetLabel(fmt.Sprintf("%s - %s", KEYCHAIN_APP_IDENTIFIER, itemName))
|
|
||||||
item.SetDescription("Secret vault keychain data")
|
|
||||||
item.SetData(data.Bytes())
|
|
||||||
item.SetSynchronizable(keychain.SynchronizableNo)
|
|
||||||
// Use AccessibleWhenUnlockedThisDeviceOnly for better security and to trigger auth
|
|
||||||
item.SetAccessible(keychain.AccessibleWhenUnlockedThisDeviceOnly)
|
|
||||||
|
|
||||||
// First try to delete any existing item
|
|
||||||
deleteItem := keychain.NewItem()
|
|
||||||
deleteItem.SetSecClass(keychain.SecClassGenericPassword)
|
|
||||||
deleteItem.SetService(KEYCHAIN_APP_IDENTIFIER)
|
|
||||||
deleteItem.SetAccount(itemName)
|
|
||||||
_ = keychain.DeleteItem(deleteItem) // Ignore error as item might not exist
|
|
||||||
|
|
||||||
// Add the new item
|
|
||||||
if err := keychain.AddItem(item); err != nil {
|
|
||||||
return fmt.Errorf("failed to store item in keychain: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// retrieveFromKeychain retrieves data from the macOS keychain using keybase/go-keychain
|
|
||||||
func retrieveFromKeychain(itemName string) ([]byte, error) {
|
|
||||||
if err := validateKeychainItemName(itemName); err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid keychain item name: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
query := keychain.NewItem()
|
|
||||||
query.SetSecClass(keychain.SecClassGenericPassword)
|
|
||||||
query.SetService(KEYCHAIN_APP_IDENTIFIER)
|
|
||||||
query.SetAccount(itemName)
|
|
||||||
query.SetMatchLimit(keychain.MatchLimitOne)
|
|
||||||
query.SetReturnData(true)
|
|
||||||
|
|
||||||
results, err := keychain.QueryItem(query)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to retrieve item from keychain: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(results) == 0 {
|
|
||||||
return nil, fmt.Errorf("keychain item not found: %s", itemName)
|
|
||||||
}
|
|
||||||
|
|
||||||
return results[0].Data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// deleteFromKeychain removes an item from the macOS keychain using keybase/go-keychain
|
|
||||||
// If the item doesn't exist, this function returns nil (not an error) since the goal
|
|
||||||
// is to ensure the item is gone, and it already being gone satisfies that goal.
|
|
||||||
func deleteFromKeychain(itemName string) error {
|
|
||||||
if err := validateKeychainItemName(itemName); err != nil {
|
|
||||||
return fmt.Errorf("invalid keychain item name: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
item := keychain.NewItem()
|
|
||||||
item.SetSecClass(keychain.SecClassGenericPassword)
|
|
||||||
item.SetService(KEYCHAIN_APP_IDENTIFIER)
|
|
||||||
item.SetAccount(itemName)
|
|
||||||
|
|
||||||
if err := keychain.DeleteItem(item); err != nil {
|
|
||||||
// If the item doesn't exist, that's not an error - the goal is to ensure
|
|
||||||
// the item is gone, and it already being gone satisfies that goal.
|
|
||||||
// This is important for cleaning up unlocker directories when the keychain
|
|
||||||
// item has already been removed (e.g., manually by user, or synced vault
|
|
||||||
// from a different machine).
|
|
||||||
if err == keychain.ErrorItemNotFound {
|
|
||||||
Debug("Keychain item not found during deletion, ignoring", "item_name", itemName)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return fmt.Errorf("failed to delete item from keychain: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
//go:build darwin && !cgo
|
|
||||||
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"github.com/awnumar/memguard"
|
|
||||||
)
|
|
||||||
|
|
||||||
// In a macOS build without cgo, these take the place of the functions in
|
|
||||||
// keychainunlocker_cgo.go: go-keychain is cgo on macOS, so they can only fail.
|
|
||||||
|
|
||||||
var errKeychainNotSupported = errors.New(
|
|
||||||
"keychain unlockers need a macOS build with cgo")
|
|
||||||
|
|
||||||
// storeInKeychain fails: the keychain needs a macOS build with cgo.
|
|
||||||
func storeInKeychain(_ string, _ *memguard.LockedBuffer) error {
|
|
||||||
return errKeychainNotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
// retrieveFromKeychain fails: the keychain needs a macOS build with cgo.
|
|
||||||
func retrieveFromKeychain(_ string) ([]byte, error) {
|
|
||||||
return nil, errKeychainNotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
// deleteFromKeychain fails: the keychain needs a macOS build with cgo.
|
|
||||||
func deleteFromKeychain(_ string) error {
|
|
||||||
return errKeychainNotSupported
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
//go:build !darwin
|
|
||||||
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"path/filepath"
|
|
||||||
|
|
||||||
"filippo.io/age"
|
|
||||||
"github.com/awnumar/memguard"
|
|
||||||
"github.com/spf13/afero"
|
|
||||||
)
|
|
||||||
|
|
||||||
// KeychainUnlockerMetadata is a stub for non-Darwin platforms
|
|
||||||
type KeychainUnlockerMetadata struct {
|
|
||||||
UnlockerMetadata
|
|
||||||
|
|
||||||
KeychainItemName string `json:"keychainItemName"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// KeychainUnlocker is a stub for non-Darwin platforms
|
|
||||||
type KeychainUnlocker struct {
|
|
||||||
Directory string
|
|
||||||
Metadata UnlockerMetadata
|
|
||||||
fs afero.Fs
|
|
||||||
}
|
|
||||||
|
|
||||||
var errKeychainNotSupported = errors.New(
|
|
||||||
"keychain unlockers are only supported on macOS")
|
|
||||||
|
|
||||||
// NewKeychainUnlocker creates a stub KeychainUnlocker on non-Darwin
|
|
||||||
// platforms. The returned instance's methods that require macOS
|
|
||||||
// functionality will return errors.
|
|
||||||
func NewKeychainUnlocker(
|
|
||||||
fs afero.Fs, directory string, metadata UnlockerMetadata,
|
|
||||||
) *KeychainUnlocker {
|
|
||||||
return &KeychainUnlocker{
|
|
||||||
Directory: directory,
|
|
||||||
Metadata: metadata,
|
|
||||||
fs: fs,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIdentity returns an error on non-Darwin platforms
|
|
||||||
func (k *KeychainUnlocker) GetIdentity() (*age.X25519Identity, error) {
|
|
||||||
return nil, errKeychainNotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetType returns the unlocker type
|
|
||||||
func (k *KeychainUnlocker) GetType() string {
|
|
||||||
return "keychain"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetMetadata returns the unlocker metadata
|
|
||||||
func (k *KeychainUnlocker) GetMetadata() UnlockerMetadata {
|
|
||||||
return k.Metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetDirectory returns the unlocker directory
|
|
||||||
func (k *KeychainUnlocker) GetDirectory() string {
|
|
||||||
return k.Directory
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the unlocker ID, the name of the unlocker's directory
|
|
||||||
func (k *KeychainUnlocker) GetID() string {
|
|
||||||
return filepath.Base(k.Directory)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetKeychainItemName returns an error on non-Darwin platforms
|
|
||||||
func (k *KeychainUnlocker) GetKeychainItemName() (string, error) {
|
|
||||||
return "", errKeychainNotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove returns an error on non-Darwin platforms
|
|
||||||
func (k *KeychainUnlocker) Remove() error {
|
|
||||||
return errKeychainNotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateKeychainUnlocker returns an error on non-Darwin platforms
|
|
||||||
func CreateKeychainUnlocker(
|
|
||||||
_ afero.Fs, _ string, _, _ *memguard.LockedBuffer,
|
|
||||||
) (*KeychainUnlocker, error) {
|
|
||||||
return nil, errKeychainNotSupported
|
|
||||||
}
|
|
||||||
@@ -1,215 +0,0 @@
|
|||||||
//go:build darwin && cgo
|
|
||||||
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/hex"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/awnumar/memguard"
|
|
||||||
"github.com/spf13/afero"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestKeychainStoreRetrieveDelete(t *testing.T) {
|
|
||||||
// Skip test if not on macOS
|
|
||||||
if runtime.GOOS != "darwin" {
|
|
||||||
t.Skip("Keychain tests only run on macOS")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test data
|
|
||||||
testItemName := "test-secret-keychain-item"
|
|
||||||
testData := "test-secret-data-12345"
|
|
||||||
testBuffer := memguard.NewBufferFromBytes([]byte(testData))
|
|
||||||
defer testBuffer.Destroy()
|
|
||||||
|
|
||||||
// Clean up any existing item first
|
|
||||||
_ = deleteFromKeychain(testItemName)
|
|
||||||
|
|
||||||
// Test 1: Store data in keychain
|
|
||||||
err := storeInKeychain(testItemName, testBuffer)
|
|
||||||
require.NoError(t, err, "Failed to store data in keychain")
|
|
||||||
|
|
||||||
// Test 2: Retrieve data from keychain
|
|
||||||
retrievedData, err := retrieveFromKeychain(testItemName)
|
|
||||||
require.NoError(t, err, "Failed to retrieve data from keychain")
|
|
||||||
assert.Equal(t, testData, string(retrievedData),
|
|
||||||
"Retrieved data doesn't match stored data")
|
|
||||||
|
|
||||||
// Test 3: Update existing item (store again with different data)
|
|
||||||
newTestData := "updated-test-data-67890"
|
|
||||||
newTestBuffer := memguard.NewBufferFromBytes([]byte(newTestData))
|
|
||||||
defer newTestBuffer.Destroy()
|
|
||||||
|
|
||||||
err = storeInKeychain(testItemName, newTestBuffer)
|
|
||||||
require.NoError(t, err, "Failed to update data in keychain")
|
|
||||||
|
|
||||||
// Verify updated data
|
|
||||||
retrievedData, err = retrieveFromKeychain(testItemName)
|
|
||||||
require.NoError(t, err, "Failed to retrieve updated data from keychain")
|
|
||||||
assert.Equal(t, newTestData, string(retrievedData),
|
|
||||||
"Retrieved data doesn't match updated data")
|
|
||||||
|
|
||||||
// Test 4: Delete from keychain
|
|
||||||
err = deleteFromKeychain(testItemName)
|
|
||||||
require.NoError(t, err, "Failed to delete data from keychain")
|
|
||||||
|
|
||||||
// Test 5: Verify item is deleted (should fail to retrieve)
|
|
||||||
_, err = retrieveFromKeychain(testItemName)
|
|
||||||
assert.Error(t, err, "Expected error when retrieving deleted item")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestKeychainInvalidItemName(t *testing.T) {
|
|
||||||
// Skip test if not on macOS
|
|
||||||
if runtime.GOOS != "darwin" {
|
|
||||||
t.Skip("Keychain tests only run on macOS")
|
|
||||||
}
|
|
||||||
|
|
||||||
testData := memguard.NewBufferFromBytes([]byte("test"))
|
|
||||||
defer testData.Destroy()
|
|
||||||
|
|
||||||
// Test an empty item name
|
|
||||||
err := storeInKeychain("", testData)
|
|
||||||
require.ErrorIs(t, err, errKeychainItemNameEmpty)
|
|
||||||
|
|
||||||
// Test invalid item names
|
|
||||||
invalidNames := []string{
|
|
||||||
"test space", // Contains space
|
|
||||||
"test/slash", // Contains slash
|
|
||||||
"test\\backslash", // Contains backslash
|
|
||||||
"test:colon", // Contains colon
|
|
||||||
"test;semicolon", // Contains semicolon
|
|
||||||
"test|pipe", // Contains pipe
|
|
||||||
"test@at", // Contains @
|
|
||||||
"test#hash", // Contains #
|
|
||||||
"test$dollar", // Contains $
|
|
||||||
"test&ersand", // Contains &
|
|
||||||
"test*asterisk", // Contains *
|
|
||||||
"test?question", // Contains ?
|
|
||||||
"test!exclamation", // Contains !
|
|
||||||
"test'quote", // Contains single quote
|
|
||||||
"test\"doublequote", // Contains double quote
|
|
||||||
"test(paren", // Contains parenthesis
|
|
||||||
"test[bracket", // Contains bracket
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, name := range invalidNames {
|
|
||||||
err := storeInKeychain(name, testData)
|
|
||||||
require.ErrorIs(t, err, errInvalidKeychainItemName,
|
|
||||||
"Expected error for invalid name: %s", name)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test valid names (should not error on validation)
|
|
||||||
validNames := []string{
|
|
||||||
"test-name",
|
|
||||||
"test_name",
|
|
||||||
"test.name",
|
|
||||||
"TestName123",
|
|
||||||
"TEST_NAME_123",
|
|
||||||
"com.example.test",
|
|
||||||
"secret-vault-hostname-2024-01-01",
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, name := range validNames {
|
|
||||||
err := validateKeychainItemName(name)
|
|
||||||
assert.NoError(t, err, "Expected no error for valid name: %s", name)
|
|
||||||
// Clean up
|
|
||||||
_ = deleteFromKeychain(name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestKeychainNilData(t *testing.T) {
|
|
||||||
// Skip test if not on macOS
|
|
||||||
if runtime.GOOS != "darwin" {
|
|
||||||
t.Skip("Keychain tests only run on macOS")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test storing nil data
|
|
||||||
err := storeInKeychain("test-item", nil)
|
|
||||||
require.ErrorIs(t, err, errNilDataBuffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestKeychainLargeData(t *testing.T) {
|
|
||||||
// Skip test if not on macOS
|
|
||||||
if runtime.GOOS != "darwin" {
|
|
||||||
t.Skip("Keychain tests only run on macOS")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test with larger hex-encoded data (512 bytes of binary data = 1KB hex)
|
|
||||||
largeData := make([]byte, 512)
|
|
||||||
for i := range largeData {
|
|
||||||
largeData[i] = byte(i % 256)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert to hex string for storage
|
|
||||||
hexData := hex.EncodeToString(largeData)
|
|
||||||
|
|
||||||
testItemName := "test-large-data"
|
|
||||||
testBuffer := memguard.NewBufferFromBytes([]byte(hexData))
|
|
||||||
defer testBuffer.Destroy()
|
|
||||||
|
|
||||||
// Clean up first
|
|
||||||
_ = deleteFromKeychain(testItemName)
|
|
||||||
|
|
||||||
// Store hex data
|
|
||||||
err := storeInKeychain(testItemName, testBuffer)
|
|
||||||
require.NoError(t, err, "Failed to store large data")
|
|
||||||
|
|
||||||
// Retrieve and verify
|
|
||||||
retrievedData, err := retrieveFromKeychain(testItemName)
|
|
||||||
require.NoError(t, err, "Failed to retrieve large data")
|
|
||||||
|
|
||||||
// Decode hex and compare
|
|
||||||
decodedData, err := hex.DecodeString(string(retrievedData))
|
|
||||||
require.NoError(t, err, "Failed to decode hex data")
|
|
||||||
assert.Equal(t, largeData, decodedData, "Large data mismatch")
|
|
||||||
|
|
||||||
// Clean up
|
|
||||||
_ = deleteFromKeychain(testItemName)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDeleteNonExistentKeychainItem(t *testing.T) {
|
|
||||||
// Skip test if not on macOS
|
|
||||||
if runtime.GOOS != "darwin" {
|
|
||||||
t.Skip("Keychain tests only run on macOS")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure item doesn't exist
|
|
||||||
testItemName := "test-nonexistent-keychain-item-12345"
|
|
||||||
_ = deleteFromKeychain(testItemName)
|
|
||||||
|
|
||||||
// Deleting a non-existent item should NOT return an error
|
|
||||||
// This is important for cleaning up unlocker directories when the keychain item
|
|
||||||
// has already been removed (e.g., manually by user, or on a different machine)
|
|
||||||
err := deleteFromKeychain(testItemName)
|
|
||||||
assert.NoError(t, err,
|
|
||||||
"Deleting non-existent keychain item should not return an error")
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestWriteKeychainUnlockerFailureDeletesItem makes moving a new keychain
|
|
||||||
// unlocker into place fail after its data is stored in the keychain: the
|
|
||||||
// keychain item must be deleted again.
|
|
||||||
func TestWriteKeychainUnlockerFailureDeletesItem(t *testing.T) {
|
|
||||||
testItemName := "test-secret-keychain-unlocker-cleanup"
|
|
||||||
_ = deleteFromKeychain(testItemName)
|
|
||||||
|
|
||||||
// Moving the unlocker into a read-only directory fails
|
|
||||||
unlockersDir := filepath.Join(t.TempDir(), "unlockers.d")
|
|
||||||
require.NoError(t, os.Mkdir(unlockersDir, 0o500))
|
|
||||||
|
|
||||||
testBuffer := memguard.NewBufferFromBytes([]byte("test-keychain-data"))
|
|
||||||
defer testBuffer.Destroy()
|
|
||||||
|
|
||||||
_, err := writeKeychainUnlocker(afero.NewOsFs(),
|
|
||||||
filepath.Join(unlockersDir, testItemName), testItemName, "age1test",
|
|
||||||
[]byte("test-priv"), []byte("test-longterm"), testBuffer)
|
|
||||||
require.ErrorIs(t, err, os.ErrPermission,
|
|
||||||
"moving the unlocker into place should fail")
|
|
||||||
|
|
||||||
_, err = retrieveFromKeychain(testItemName)
|
|
||||||
assert.Error(t, err, "keychain item left behind")
|
|
||||||
}
|
|
||||||
@@ -17,7 +17,7 @@ type VaultMetadata struct {
|
|||||||
|
|
||||||
// UnlockerMetadata contains information about an unlocker
|
// UnlockerMetadata contains information about an unlocker
|
||||||
type UnlockerMetadata struct {
|
type UnlockerMetadata struct {
|
||||||
Type string `json:"type"` // passphrase, pgp, keychain
|
Type string `json:"type"` // passphrase or pgp
|
||||||
CreatedAt time.Time `json:"createdAt"`
|
CreatedAt time.Time `json:"createdAt"`
|
||||||
Flags []string `json:"flags,omitempty"`
|
Flags []string `json:"flags,omitempty"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -128,7 +128,6 @@ func (p *PassphraseUnlocker) Remove() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// For passphrase unlockers, we just need to remove the directory
|
// For passphrase unlockers, we just need to remove the directory
|
||||||
// No external resources (like keychain items) to clean up
|
|
||||||
err := RemoveDirAtomic(p.fs, p.Directory)
|
err := RemoveDirAtomic(p.fs, p.Directory)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to remove passphrase unlocker directory: %w", err)
|
return fmt.Errorf("failed to remove passphrase unlocker directory: %w", err)
|
||||||
|
|||||||
@@ -171,7 +171,6 @@ func (p *PGPUnlocker) GetID() string {
|
|||||||
// Remove implements Unlocker interface - removes the PGP unlocker
|
// Remove implements Unlocker interface - removes the PGP unlocker
|
||||||
func (p *PGPUnlocker) Remove() error {
|
func (p *PGPUnlocker) Remove() error {
|
||||||
// For PGP unlockers, we just need to remove the directory
|
// For PGP unlockers, we just need to remove the directory
|
||||||
// No external resources (like keychain items) to clean up
|
|
||||||
err := RemoveDirAtomic(p.fs, p.Directory)
|
err := RemoveDirAtomic(p.fs, p.Directory)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to remove PGP unlocker directory: %w", err)
|
return fmt.Errorf("failed to remove PGP unlocker directory: %w", err)
|
||||||
|
|||||||
@@ -1,397 +0,0 @@
|
|||||||
//go:build darwin
|
|
||||||
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"filippo.io/age"
|
|
||||||
"github.com/awnumar/memguard"
|
|
||||||
"github.com/spf13/afero"
|
|
||||||
"sneak.berlin/go/secret/internal/macse"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// seKeyLabelPrefix is the prefix for Secure Enclave CTK identity labels.
|
|
||||||
seKeyLabelPrefix = "berlin.sneak.app.secret.se"
|
|
||||||
|
|
||||||
// seUnlockerType is the metadata type string for Secure Enclave unlockers.
|
|
||||||
seUnlockerType = "secure-enclave"
|
|
||||||
|
|
||||||
// seLongtermFilename is the filename for the SE-encrypted vault long-term private key.
|
|
||||||
seLongtermFilename = "longterm.age.se"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SecureEnclaveUnlockerMetadata extends UnlockerMetadata with SE-specific data.
|
|
||||||
type SecureEnclaveUnlockerMetadata struct {
|
|
||||||
UnlockerMetadata
|
|
||||||
|
|
||||||
SEKeyLabel string `json:"seKeyLabel"`
|
|
||||||
SEKeyHash string `json:"seKeyHash"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SecureEnclaveUnlocker represents a Secure Enclave-protected unlocker.
|
|
||||||
type SecureEnclaveUnlocker struct {
|
|
||||||
Directory string
|
|
||||||
Metadata UnlockerMetadata
|
|
||||||
fs afero.Fs
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewSecureEnclaveUnlocker creates a new SecureEnclaveUnlocker instance.
|
|
||||||
func NewSecureEnclaveUnlocker(
|
|
||||||
fs afero.Fs,
|
|
||||||
directory string,
|
|
||||||
metadata UnlockerMetadata,
|
|
||||||
) *SecureEnclaveUnlocker {
|
|
||||||
return &SecureEnclaveUnlocker{
|
|
||||||
Directory: directory,
|
|
||||||
Metadata: metadata,
|
|
||||||
fs: fs,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIdentity implements Unlocker interface for SE-based unlockers.
|
|
||||||
// Decrypts the vault's long-term private key directly using the Secure Enclave.
|
|
||||||
func (s *SecureEnclaveUnlocker) GetIdentity() (*age.X25519Identity, error) {
|
|
||||||
DebugWith("Getting SE unlocker identity",
|
|
||||||
slog.String("unlocker_id", s.GetID()),
|
|
||||||
)
|
|
||||||
|
|
||||||
// Get SE key label from metadata
|
|
||||||
seKeyLabel, _, err := s.getSEKeyInfo()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get SE key info: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read ECIES-encrypted long-term private key from disk
|
|
||||||
encryptedPath := filepath.Join(s.Directory, seLongtermFilename)
|
|
||||||
|
|
||||||
encryptedData, err := afero.ReadFile(s.fs, encryptedPath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"failed to read SE-encrypted long-term key: %w",
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
DebugWith("Read SE-encrypted long-term key",
|
|
||||||
slog.Int("encrypted_length", len(encryptedData)),
|
|
||||||
)
|
|
||||||
|
|
||||||
// Decrypt using the Secure Enclave (ECDH happens inside SE hardware)
|
|
||||||
decryptedData, err := macse.Decrypt(seKeyLabel, encryptedData)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"failed to decrypt long-term key with SE: %w",
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse the decrypted long-term private key
|
|
||||||
ltIdentity, err := age.ParseX25519Identity(string(decryptedData))
|
|
||||||
|
|
||||||
// Clear sensitive data immediately
|
|
||||||
for i := range decryptedData {
|
|
||||||
decryptedData[i] = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"failed to parse long-term private key: %w",
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
DebugWith("Successfully decrypted long-term key via SE",
|
|
||||||
slog.String("unlocker_id", s.GetID()),
|
|
||||||
)
|
|
||||||
|
|
||||||
return ltIdentity, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetType implements Unlocker interface.
|
|
||||||
func (s *SecureEnclaveUnlocker) GetType() string {
|
|
||||||
return seUnlockerType
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetMetadata implements Unlocker interface.
|
|
||||||
func (s *SecureEnclaveUnlocker) GetMetadata() UnlockerMetadata {
|
|
||||||
return s.Metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetDirectory implements Unlocker interface.
|
|
||||||
func (s *SecureEnclaveUnlocker) GetDirectory() string {
|
|
||||||
return s.Directory
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID implements Unlocker interface: the name of the unlocker's directory.
|
|
||||||
func (s *SecureEnclaveUnlocker) GetID() string {
|
|
||||||
return filepath.Base(s.Directory)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove implements Unlocker interface.
|
|
||||||
func (s *SecureEnclaveUnlocker) Remove() error {
|
|
||||||
_, seKeyHash, err := s.getSEKeyInfo()
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to get SE key info during removal", "error", err)
|
|
||||||
|
|
||||||
return fmt.Errorf("failed to get SE key info: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if seKeyHash != "" {
|
|
||||||
Debug("Deleting SE key", "hash", seKeyHash)
|
|
||||||
|
|
||||||
err = macse.DeleteKey(seKeyHash)
|
|
||||||
if err != nil {
|
|
||||||
Debug("Failed to delete SE key", "error", err, "hash", seKeyHash)
|
|
||||||
|
|
||||||
return fmt.Errorf("failed to delete SE key: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Debug("Removing SE unlocker directory", "directory", s.Directory)
|
|
||||||
|
|
||||||
err = RemoveDirAtomic(s.fs, s.Directory)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to remove SE unlocker directory: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
Debug("Successfully removed SE unlocker", "unlocker_id", s.GetID())
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// getSEKeyInfo reads the SE key label and hash from metadata.
|
|
||||||
func (s *SecureEnclaveUnlocker) getSEKeyInfo() (string, string, error) {
|
|
||||||
metadataPath := filepath.Join(s.Directory, "unlocker-metadata.json")
|
|
||||||
|
|
||||||
metadataData, err := afero.ReadFile(s.fs, metadataPath)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", fmt.Errorf("failed to read SE metadata: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var seMetadata SecureEnclaveUnlockerMetadata
|
|
||||||
|
|
||||||
err = json.Unmarshal(metadataData, &seMetadata)
|
|
||||||
if err != nil {
|
|
||||||
return "", "", fmt.Errorf("failed to parse SE metadata: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return seMetadata.SEKeyLabel, seMetadata.SEKeyHash, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// generateSEKeyLabel generates a unique label for the SE CTK identity.
|
|
||||||
func generateSEKeyLabel(vaultName string) (string, error) {
|
|
||||||
hostname, err := os.Hostname()
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("failed to get hostname: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
enrollmentTime := time.Now().UTC().Format(UnlockerTimeFormat)
|
|
||||||
|
|
||||||
return fmt.Sprintf(
|
|
||||||
"%s.%s-%s-%s",
|
|
||||||
seKeyLabelPrefix,
|
|
||||||
vaultName,
|
|
||||||
hostname,
|
|
||||||
enrollmentTime,
|
|
||||||
), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateSecureEnclaveUnlocker creates a new SE unlocker.
|
|
||||||
// The vault's long-term private key is encrypted directly by the Secure Enclave
|
|
||||||
// using ECIES. No intermediate age keypair is used.
|
|
||||||
// The long-term key comes from mnemonic when it is not nil, else from the
|
|
||||||
// current unlocker, as getLongTermKeyForSE describes.
|
|
||||||
// The SE key is created once the long-term key is in hand and the unlocker's
|
|
||||||
// path is known, and is deleted again if a later step fails.
|
|
||||||
func CreateSecureEnclaveUnlocker(
|
|
||||||
fs afero.Fs,
|
|
||||||
stateDir string,
|
|
||||||
mnemonic, passphrase *memguard.LockedBuffer,
|
|
||||||
) (*SecureEnclaveUnlocker, error) {
|
|
||||||
vault, err := GetCurrentVault(fs, stateDir)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get current vault: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate SE key label
|
|
||||||
seKeyLabel, err := generateSEKeyLabel(vault.GetName())
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to generate SE key label: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 1: Get the vault's long-term private key
|
|
||||||
ltPrivKeyData, err := getLongTermKeyForSE(fs, vault, mnemonic, passphrase)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"failed to get long-term private key: %w",
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
defer ltPrivKeyData.Destroy()
|
|
||||||
|
|
||||||
// Step 2: Prepare the unlocker directory's path
|
|
||||||
vaultDir, err := vault.GetDirectory()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get vault directory: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
unlockerDirName := "se-" + filepath.Base(seKeyLabel)
|
|
||||||
unlockerDir := filepath.Join(vaultDir, "unlockers.d", unlockerDirName)
|
|
||||||
|
|
||||||
// Step 3: Create P-256 key in the Secure Enclave via sc_auth
|
|
||||||
Debug("Creating Secure Enclave key", "label", seKeyLabel)
|
|
||||||
|
|
||||||
_, seKeyHash, err := macse.CreateKey(seKeyLabel)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to create SE key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
Debug("Created SE key", "label", seKeyLabel, "hash", seKeyHash)
|
|
||||||
|
|
||||||
// Steps 4 and 5: Write the unlocker, or delete the SE key if that fails
|
|
||||||
unlocker, err := writeSEUnlocker(fs, unlockerDir, seKeyLabel, seKeyHash,
|
|
||||||
ltPrivKeyData)
|
|
||||||
if err != nil {
|
|
||||||
deleteErr := macse.DeleteKey(seKeyHash)
|
|
||||||
if deleteErr != nil {
|
|
||||||
err = errors.Join(err, fmt.Errorf(
|
|
||||||
"failed to delete SE key %s: %w", seKeyLabel, deleteErr))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return unlocker, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// writeSEUnlocker encrypts the long-term key with the SE key and writes the
|
|
||||||
// new unlocker into unlockerDir (steps 4 and 5 of
|
|
||||||
// CreateSecureEnclaveUnlocker).
|
|
||||||
func writeSEUnlocker(
|
|
||||||
fs afero.Fs, unlockerDir, seKeyLabel, seKeyHash string,
|
|
||||||
ltPrivKeyData *memguard.LockedBuffer,
|
|
||||||
) (*SecureEnclaveUnlocker, error) {
|
|
||||||
// Step 4: Encrypt the long-term key directly with the SE (ECIES), and
|
|
||||||
// prepare the metadata
|
|
||||||
encryptedLtKey, err := macse.Encrypt(seKeyLabel, ltPrivKeyData.Bytes())
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"failed to encrypt long-term key with SE: %w",
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
seMetadata := SecureEnclaveUnlockerMetadata{
|
|
||||||
UnlockerMetadata: UnlockerMetadata{
|
|
||||||
Type: seUnlockerType,
|
|
||||||
CreatedAt: time.Now().UTC(),
|
|
||||||
Flags: []string{seUnlockerType, macOSFlag},
|
|
||||||
},
|
|
||||||
SEKeyLabel: seKeyLabel,
|
|
||||||
SEKeyHash: seKeyHash,
|
|
||||||
}
|
|
||||||
|
|
||||||
metadataBytes, err := json.MarshalIndent(seMetadata, "", " ")
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to marshal metadata: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 5: Write the SE-encrypted long-term key, then the metadata
|
|
||||||
err = WriteDir(fs, unlockerDir, func(dir string) error {
|
|
||||||
return writeSEUnlockerFiles(fs, dir, encryptedLtKey, metadataBytes)
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return &SecureEnclaveUnlocker{
|
|
||||||
Directory: unlockerDir,
|
|
||||||
Metadata: seMetadata.UnlockerMetadata,
|
|
||||||
fs: fs,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// writeSEUnlockerFiles writes the files of a new SE unlocker into dir: the
|
|
||||||
// SE-encrypted long-term key, then the metadata.
|
|
||||||
func writeSEUnlockerFiles(
|
|
||||||
fs afero.Fs, dir string, encryptedLtKey, metadataBytes []byte,
|
|
||||||
) error {
|
|
||||||
err := WriteFileAtomic(fs, filepath.Join(dir, seLongtermFilename),
|
|
||||||
encryptedLtKey)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf(
|
|
||||||
"failed to write SE-encrypted long-term key: %w",
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
err = WriteFileAtomic(fs,
|
|
||||||
filepath.Join(dir, "unlocker-metadata.json"), metadataBytes)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to write metadata: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// getLongTermKeyForSE retrieves the vault's long-term private key, derived
|
|
||||||
// from mnemonic when it is not nil, else through the current unlocker, which
|
|
||||||
// is given passphrase when it is a passphrase unlocker.
|
|
||||||
func getLongTermKeyForSE(
|
|
||||||
fs afero.Fs,
|
|
||||||
vault VaultInterface,
|
|
||||||
mnemonic, passphrase *memguard.LockedBuffer,
|
|
||||||
) (*memguard.LockedBuffer, error) {
|
|
||||||
if mnemonic != nil {
|
|
||||||
return deriveLongTermPrivateKey(fs, vault, mnemonic)
|
|
||||||
}
|
|
||||||
|
|
||||||
currentUnlocker, err := vault.GetCurrentUnlocker()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to get current unlocker: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if passphraseUnlocker, ok := currentUnlocker.(*PassphraseUnlocker); ok {
|
|
||||||
passphraseUnlocker.Passphrase = passphrase
|
|
||||||
}
|
|
||||||
|
|
||||||
currentIdentity, err := currentUnlocker.GetIdentity()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"failed to get current unlocker identity: %w",
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// All unlocker types store longterm.age in their directory
|
|
||||||
longtermPath := filepath.Join(
|
|
||||||
currentUnlocker.GetDirectory(),
|
|
||||||
"longterm.age",
|
|
||||||
)
|
|
||||||
|
|
||||||
encryptedLtKey, err := afero.ReadFile(fs, longtermPath)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"failed to read encrypted long-term key: %w",
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
ltPrivKeyBuffer, err := DecryptWithIdentity(
|
|
||||||
encryptedLtKey,
|
|
||||||
currentIdentity,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to decrypt long-term key: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return ltPrivKeyBuffer, nil
|
|
||||||
}
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
//go:build !darwin
|
|
||||||
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"path/filepath"
|
|
||||||
|
|
||||||
"filippo.io/age"
|
|
||||||
"github.com/awnumar/memguard"
|
|
||||||
"github.com/spf13/afero"
|
|
||||||
)
|
|
||||||
|
|
||||||
// seUnlockerType is the type string for Secure Enclave unlockers.
|
|
||||||
const seUnlockerType = "secure-enclave"
|
|
||||||
|
|
||||||
var errSENotSupported = errors.New(
|
|
||||||
"secure enclave unlockers are only supported on macOS",
|
|
||||||
)
|
|
||||||
|
|
||||||
// SecureEnclaveUnlockerMetadata is a stub for non-Darwin platforms.
|
|
||||||
type SecureEnclaveUnlockerMetadata struct {
|
|
||||||
UnlockerMetadata
|
|
||||||
|
|
||||||
SEKeyLabel string `json:"seKeyLabel"`
|
|
||||||
SEKeyHash string `json:"seKeyHash"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SecureEnclaveUnlocker is a stub for non-Darwin platforms.
|
|
||||||
type SecureEnclaveUnlocker struct {
|
|
||||||
Directory string
|
|
||||||
Metadata UnlockerMetadata
|
|
||||||
fs afero.Fs
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewSecureEnclaveUnlocker creates a stub SecureEnclaveUnlocker on
|
|
||||||
// non-Darwin platforms. The returned instance's methods that require
|
|
||||||
// macOS functionality will return errors.
|
|
||||||
func NewSecureEnclaveUnlocker(
|
|
||||||
fs afero.Fs,
|
|
||||||
directory string,
|
|
||||||
metadata UnlockerMetadata,
|
|
||||||
) *SecureEnclaveUnlocker {
|
|
||||||
return &SecureEnclaveUnlocker{
|
|
||||||
Directory: directory,
|
|
||||||
Metadata: metadata,
|
|
||||||
fs: fs,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIdentity returns an error on non-Darwin platforms.
|
|
||||||
func (s *SecureEnclaveUnlocker) GetIdentity() (*age.X25519Identity, error) {
|
|
||||||
return nil, errSENotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetType returns the unlocker type.
|
|
||||||
func (s *SecureEnclaveUnlocker) GetType() string {
|
|
||||||
return seUnlockerType
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetMetadata returns the unlocker metadata.
|
|
||||||
func (s *SecureEnclaveUnlocker) GetMetadata() UnlockerMetadata {
|
|
||||||
return s.Metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetDirectory returns the unlocker directory.
|
|
||||||
func (s *SecureEnclaveUnlocker) GetDirectory() string {
|
|
||||||
return s.Directory
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetID returns the unlocker ID, the name of the unlocker's directory.
|
|
||||||
func (s *SecureEnclaveUnlocker) GetID() string {
|
|
||||||
return filepath.Base(s.Directory)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove returns an error on non-Darwin platforms.
|
|
||||||
func (s *SecureEnclaveUnlocker) Remove() error {
|
|
||||||
return errSENotSupported
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateSecureEnclaveUnlocker returns an error on non-Darwin platforms.
|
|
||||||
func CreateSecureEnclaveUnlocker(
|
|
||||||
_ afero.Fs,
|
|
||||||
_ string,
|
|
||||||
_, _ *memguard.LockedBuffer,
|
|
||||||
) (*SecureEnclaveUnlocker, error) {
|
|
||||||
return nil, errSENotSupported
|
|
||||||
}
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
//go:build !darwin
|
|
||||||
|
|
||||||
//nolint:testpackage // white-box test asserting unexported sentinel errors
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/spf13/afero"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewSecureEnclaveUnlocker(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fs := afero.NewMemMapFs()
|
|
||||||
dir := "/tmp/test-se-unlocker"
|
|
||||||
metadata := UnlockerMetadata{
|
|
||||||
Type: seUnlockerType,
|
|
||||||
CreatedAt: time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC),
|
|
||||||
Flags: []string{seUnlockerType, "macos"},
|
|
||||||
}
|
|
||||||
|
|
||||||
unlocker := NewSecureEnclaveUnlocker(fs, dir, metadata)
|
|
||||||
require.NotNil(t, unlocker, "NewSecureEnclaveUnlocker should return a valid instance")
|
|
||||||
|
|
||||||
// Test GetType returns correct type
|
|
||||||
assert.Equal(t, seUnlockerType, unlocker.GetType())
|
|
||||||
|
|
||||||
// Test GetMetadata returns the metadata we passed in
|
|
||||||
assert.Equal(t, metadata, unlocker.GetMetadata())
|
|
||||||
|
|
||||||
// Test GetDirectory returns the directory we passed in
|
|
||||||
assert.Equal(t, dir, unlocker.GetDirectory())
|
|
||||||
|
|
||||||
// Test GetID returns the name of the unlocker's directory
|
|
||||||
assert.Equal(t, "test-se-unlocker", unlocker.GetID())
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSecureEnclaveUnlockerGetIdentityReturnsError(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fs := afero.NewMemMapFs()
|
|
||||||
metadata := UnlockerMetadata{
|
|
||||||
Type: seUnlockerType,
|
|
||||||
CreatedAt: time.Now().UTC(),
|
|
||||||
}
|
|
||||||
|
|
||||||
unlocker := NewSecureEnclaveUnlocker(fs, "/tmp/test", metadata)
|
|
||||||
|
|
||||||
identity, err := unlocker.GetIdentity()
|
|
||||||
assert.Nil(t, identity)
|
|
||||||
require.Error(t, err)
|
|
||||||
require.ErrorIs(t, err, errSENotSupported)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSecureEnclaveUnlockerRemoveReturnsError(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fs := afero.NewMemMapFs()
|
|
||||||
metadata := UnlockerMetadata{
|
|
||||||
Type: seUnlockerType,
|
|
||||||
CreatedAt: time.Now().UTC(),
|
|
||||||
}
|
|
||||||
|
|
||||||
unlocker := NewSecureEnclaveUnlocker(fs, "/tmp/test", metadata)
|
|
||||||
|
|
||||||
err := unlocker.Remove()
|
|
||||||
require.Error(t, err)
|
|
||||||
require.ErrorIs(t, err, errSENotSupported)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCreateSecureEnclaveUnlockerReturnsError(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fs := afero.NewMemMapFs()
|
|
||||||
|
|
||||||
unlocker, err := CreateSecureEnclaveUnlocker(fs, "/tmp/test", nil, nil)
|
|
||||||
assert.Nil(t, unlocker)
|
|
||||||
require.Error(t, err)
|
|
||||||
require.ErrorIs(t, err, errSENotSupported)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSecureEnclaveUnlockerImplementsInterface(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fs := afero.NewMemMapFs()
|
|
||||||
metadata := UnlockerMetadata{
|
|
||||||
Type: seUnlockerType,
|
|
||||||
CreatedAt: time.Now().UTC(),
|
|
||||||
}
|
|
||||||
|
|
||||||
unlocker := NewSecureEnclaveUnlocker(fs, "/tmp/test", metadata)
|
|
||||||
|
|
||||||
// Verify the stub implements the Unlocker interface
|
|
||||||
var _ Unlocker = unlocker
|
|
||||||
}
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
//go:build darwin
|
|
||||||
|
|
||||||
//nolint:testpackage // white-box test of unexported Secure Enclave helpers
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/spf13/afero"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewSecureEnclaveUnlocker(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fs := afero.NewMemMapFs()
|
|
||||||
dir := "/tmp/test-se-unlocker"
|
|
||||||
metadata := UnlockerMetadata{
|
|
||||||
Type: seUnlockerType,
|
|
||||||
CreatedAt: time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC),
|
|
||||||
Flags: []string{seUnlockerType, "macos"},
|
|
||||||
}
|
|
||||||
|
|
||||||
unlocker := NewSecureEnclaveUnlocker(fs, dir, metadata)
|
|
||||||
require.NotNil(t, unlocker, "NewSecureEnclaveUnlocker should return a valid instance")
|
|
||||||
|
|
||||||
// Test GetType returns correct type
|
|
||||||
assert.Equal(t, seUnlockerType, unlocker.GetType())
|
|
||||||
|
|
||||||
// Test GetMetadata returns the metadata we passed in
|
|
||||||
assert.Equal(t, metadata, unlocker.GetMetadata())
|
|
||||||
|
|
||||||
// Test GetDirectory returns the directory we passed in
|
|
||||||
assert.Equal(t, dir, unlocker.GetDirectory())
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSecureEnclaveUnlockerImplementsInterface(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fs := afero.NewMemMapFs()
|
|
||||||
metadata := UnlockerMetadata{
|
|
||||||
Type: seUnlockerType,
|
|
||||||
CreatedAt: time.Now().UTC(),
|
|
||||||
}
|
|
||||||
|
|
||||||
unlocker := NewSecureEnclaveUnlocker(fs, "/tmp/test", metadata)
|
|
||||||
|
|
||||||
// Verify the darwin implementation implements the Unlocker interface
|
|
||||||
var _ Unlocker = unlocker
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSecureEnclaveUnlockerGetIDFormat(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fs := afero.NewMemMapFs()
|
|
||||||
metadata := UnlockerMetadata{
|
|
||||||
Type: seUnlockerType,
|
|
||||||
CreatedAt: time.Date(2026, 3, 10, 14, 30, 0, 0, time.UTC),
|
|
||||||
}
|
|
||||||
|
|
||||||
unlocker := NewSecureEnclaveUnlocker(fs, "/tmp/test", metadata)
|
|
||||||
|
|
||||||
// The ID is the name of the unlocker's directory
|
|
||||||
assert.Equal(t, "test", unlocker.GetID())
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGenerateSEKeyLabel(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
label, err := generateSEKeyLabel("test-vault")
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
// Label should contain the prefix and vault name
|
|
||||||
assert.Contains(t, label, seKeyLabelPrefix)
|
|
||||||
assert.Contains(t, label, "test-vault")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSecureEnclaveUnlockerGetIdentityMissingFile(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
fs := afero.NewMemMapFs()
|
|
||||||
dir := "/tmp/test-se-unlocker-missing"
|
|
||||||
|
|
||||||
// Create unlocker directory with metadata but no encrypted key file
|
|
||||||
require.NoError(t, fs.MkdirAll(dir, DirPerms))
|
|
||||||
|
|
||||||
metadataJSON := `{
|
|
||||||
"type": "secure-enclave",
|
|
||||||
"createdAt": "2026-01-15T10:30:00Z",
|
|
||||||
"seKeyLabel": "berlin.sneak.app.secret.se.test",
|
|
||||||
"seKeyHash": "abc123"
|
|
||||||
}`
|
|
||||||
require.NoError(t, afero.WriteFile(
|
|
||||||
fs, dir+"/unlocker-metadata.json", []byte(metadataJSON), FilePerms,
|
|
||||||
))
|
|
||||||
|
|
||||||
metadata := UnlockerMetadata{
|
|
||||||
Type: seUnlockerType,
|
|
||||||
CreatedAt: time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC),
|
|
||||||
}
|
|
||||||
|
|
||||||
unlocker := NewSecureEnclaveUnlocker(fs, dir, metadata)
|
|
||||||
|
|
||||||
// GetIdentity should fail because the encrypted longterm key file is missing
|
|
||||||
identity, err := unlocker.GetIdentity()
|
|
||||||
assert.Nil(t, identity)
|
|
||||||
|
|
||||||
var cause *os.PathError
|
|
||||||
|
|
||||||
require.ErrorAs(t, err, &cause)
|
|
||||||
require.ErrorIs(t, err, os.ErrNotExist)
|
|
||||||
assert.Equal(t, filepath.Join(dir, seLongtermFilename), cause.Path)
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
//go:build darwin
|
|
||||||
|
|
||||||
//nolint:testpackage // white-box test of unexported validateKeychainItemName
|
|
||||||
package secret
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestValidateKeychainItemName(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
itemName string
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
// Valid cases
|
|
||||||
{name: "valid simple name", itemName: "my-secret-key", wantErr: false},
|
|
||||||
{name: "valid name with dots", itemName: "com.example.app.key", wantErr: false},
|
|
||||||
{name: "valid name with underscores", itemName: "my_secret_key_123", wantErr: false},
|
|
||||||
{name: "valid alphanumeric", itemName: "Secret123Key", wantErr: false},
|
|
||||||
{name: "valid with hyphen at start", itemName: "-my-key", wantErr: false},
|
|
||||||
{name: "valid with dot at start", itemName: ".hidden-key", wantErr: false},
|
|
||||||
|
|
||||||
// Invalid cases
|
|
||||||
{name: "empty item name", itemName: "", wantErr: true},
|
|
||||||
{name: "item name with spaces", itemName: "my secret key", wantErr: true},
|
|
||||||
{name: "item name with semicolon", itemName: "key;rm -rf /", wantErr: true},
|
|
||||||
{name: "item name with pipe", itemName: "key|cat /etc/passwd", wantErr: true},
|
|
||||||
{name: "item name with backticks", itemName: "key`whoami`", wantErr: true},
|
|
||||||
{name: "item name with dollar sign", itemName: "key$(whoami)", wantErr: true},
|
|
||||||
{name: "item name with quotes", itemName: "key\"name", wantErr: true},
|
|
||||||
{name: "item name with single quotes", itemName: "key'name", wantErr: true},
|
|
||||||
{name: "item name with backslash", itemName: "key\\name", wantErr: true},
|
|
||||||
{name: "item name with newline", itemName: "key\nname", wantErr: true},
|
|
||||||
{name: "item name with carriage return", itemName: "key\rname", wantErr: true},
|
|
||||||
{name: "item name with ampersand", itemName: "key&echo test", wantErr: true},
|
|
||||||
{name: "item name with redirect", itemName: "key>/tmp/test", wantErr: true},
|
|
||||||
{name: "item name with null byte", itemName: "key\x00name", wantErr: true},
|
|
||||||
{name: "item name with parentheses", itemName: "key(test)", wantErr: true},
|
|
||||||
{name: "item name with brackets", itemName: "key[test]", wantErr: true},
|
|
||||||
{name: "item name with asterisk", itemName: "key*", wantErr: true},
|
|
||||||
{name: "item name with question mark", itemName: "key?", wantErr: true},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
err := validateKeychainItemName(tt.itemName)
|
|
||||||
if (err != nil) != tt.wantErr {
|
|
||||||
t.Errorf("validateKeychainItemName() error = %v, wantErr %v", err, tt.wantErr)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -18,8 +18,7 @@ import (
|
|||||||
|
|
||||||
// Unlocker metadata type strings.
|
// Unlocker metadata type strings.
|
||||||
const (
|
const (
|
||||||
unlockerTypePassphrase = "passphrase"
|
unlockerTypePassphrase = "passphrase"
|
||||||
unlockerTypeSecureEnclave = "secure-enclave"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetCurrentUnlocker returns the current unlocker for this vault
|
// GetCurrentUnlocker returns the current unlocker for this vault
|
||||||
@@ -79,15 +78,6 @@ func (v *Vault) GetCurrentUnlocker() (secret.Unlocker, error) {
|
|||||||
secret.Debug("Creating PGP unlocker instance", "unlocker_type", metadata.Type)
|
secret.Debug("Creating PGP unlocker instance", "unlocker_type", metadata.Type)
|
||||||
|
|
||||||
unlocker = secret.NewPGPUnlocker(v.fs, unlockerDir, metadata)
|
unlocker = secret.NewPGPUnlocker(v.fs, unlockerDir, metadata)
|
||||||
case "keychain":
|
|
||||||
secret.Debug("Creating keychain unlocker instance", "unlocker_type", metadata.Type)
|
|
||||||
|
|
||||||
unlocker = secret.NewKeychainUnlocker(v.fs, unlockerDir, metadata)
|
|
||||||
case unlockerTypeSecureEnclave:
|
|
||||||
secret.Debug("Creating secure enclave unlocker instance",
|
|
||||||
"unlocker_type", metadata.Type)
|
|
||||||
|
|
||||||
unlocker = secret.NewSecureEnclaveUnlocker(v.fs, unlockerDir, metadata)
|
|
||||||
default:
|
default:
|
||||||
secret.Debug("Unsupported unlocker type", "type", metadata.Type)
|
secret.Debug("Unsupported unlocker type", "type", metadata.Type)
|
||||||
|
|
||||||
@@ -171,10 +161,6 @@ func (v *Vault) findUnlockerByID(
|
|||||||
tempUnlocker = secret.NewPassphraseUnlocker(v.fs, unlockerDirPath, metadata)
|
tempUnlocker = secret.NewPassphraseUnlocker(v.fs, unlockerDirPath, metadata)
|
||||||
case "pgp":
|
case "pgp":
|
||||||
tempUnlocker = secret.NewPGPUnlocker(v.fs, unlockerDirPath, metadata)
|
tempUnlocker = secret.NewPGPUnlocker(v.fs, unlockerDirPath, metadata)
|
||||||
case "keychain":
|
|
||||||
tempUnlocker = secret.NewKeychainUnlocker(v.fs, unlockerDirPath, metadata)
|
|
||||||
case unlockerTypeSecureEnclave:
|
|
||||||
tempUnlocker = secret.NewSecureEnclaveUnlocker(v.fs, unlockerDirPath, metadata)
|
|
||||||
default:
|
default:
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-17
@@ -109,9 +109,8 @@ func (v *Vault) GetOrDeriveLongTermKey() (*age.X25519Identity, error) {
|
|||||||
slog.String("unlocker_id", unlocker.GetID()),
|
slog.String("unlocker_id", unlocker.GetID()),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Get the long-term key via the unlocker.
|
// Get the long-term key via the unlocker: its identity decrypts
|
||||||
// SE unlockers return the long-term key directly from GetIdentity().
|
// longterm.age.
|
||||||
// Other unlockers return their own identity, used to decrypt longterm.age.
|
|
||||||
ltIdentity, err := v.unlockLongTermKey(unlocker)
|
ltIdentity, err := v.unlockLongTermKey(unlocker)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, v.withMnemonicAdvice(err)
|
return nil, v.withMnemonicAdvice(err)
|
||||||
@@ -254,23 +253,10 @@ func (v *Vault) deriveLongTermKeyFromMnemonic(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// unlockLongTermKey extracts the vault's long-term key using the given
|
// unlockLongTermKey extracts the vault's long-term key using the given
|
||||||
// unlocker. SE unlockers decrypt the long-term key directly; other unlockers
|
// unlocker's identity.
|
||||||
// use an intermediate identity.
|
|
||||||
func (v *Vault) unlockLongTermKey(
|
func (v *Vault) unlockLongTermKey(
|
||||||
unlocker secret.Unlocker,
|
unlocker secret.Unlocker,
|
||||||
) (*age.X25519Identity, error) {
|
) (*age.X25519Identity, error) {
|
||||||
if unlocker.GetType() == unlockerTypeSecureEnclave {
|
|
||||||
secret.Debug("SE unlocker: decrypting long-term key directly via Secure Enclave")
|
|
||||||
|
|
||||||
ltIdentity, err := unlocker.GetIdentity()
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to decrypt long-term key via SE: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return ltIdentity, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Standard unlockers: get unlocker identity, then decrypt longterm.age
|
|
||||||
unlockerIdentity, err := unlocker.GetIdentity()
|
unlockerIdentity, err := unlocker.GetIdentity()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to get unlocker identity: %w", err)
|
return nil, fmt.Errorf("failed to get unlocker identity: %w", err)
|
||||||
|
|||||||
+8
-3
@@ -17,7 +17,8 @@ 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"
|
||||||
"github.com/tyler-smith/go-bip39"
|
"golang.org/x/text/unicode/norm"
|
||||||
|
"sneak.berlin/go/secret/internal/bip39"
|
||||||
"sneak.berlin/go/secret/pkg/bip85"
|
"sneak.berlin/go/secret/pkg/bip85"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -73,8 +74,12 @@ func IdentityFromEntropy(ent []byte) (*age.X25519Identity, error) {
|
|||||||
// DeriveEntropy derives 32 bytes of application-scoped entropy from the
|
// DeriveEntropy derives 32 bytes of application-scoped entropy from the
|
||||||
// supplied BIP-39 mnemonic and index n using BIP85.
|
// supplied BIP-39 mnemonic and index n using BIP85.
|
||||||
func DeriveEntropy(mnemonic string, n uint32) ([]byte, error) {
|
func DeriveEntropy(mnemonic string, n uint32) ([]byte, error) {
|
||||||
// Convert mnemonic to seed
|
// BIP-39 makes the seed from the words joined by single spaces, in
|
||||||
seed := bip39.NewSeed(mnemonic, "")
|
// Unicode NFKD. NewSeed hashes its input as given, so the mnemonic is
|
||||||
|
// brought to that form first: the same words, however they were
|
||||||
|
// typed, then give the same seed.
|
||||||
|
sentence := norm.NFKD.String(strings.Join(strings.Fields(mnemonic), " "))
|
||||||
|
seed := bip39.NewSeed(sentence, "")
|
||||||
|
|
||||||
// Create master key from seed
|
// Create master key from seed
|
||||||
masterKey, err := hdkeychain.NewMaster(seed, &chaincfg.MainNetParams)
|
masterKey, err := hdkeychain.NewMaster(seed, &chaincfg.MainNetParams)
|
||||||
|
|||||||
+29
-1
@@ -11,7 +11,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"filippo.io/age"
|
"filippo.io/age"
|
||||||
"github.com/tyler-smith/go-bip39"
|
"sneak.berlin/go/secret/internal/bip39"
|
||||||
)
|
)
|
||||||
|
|
||||||
//nolint:dupword // BIP39 test mnemonics repeat words by design
|
//nolint:dupword // BIP39 test mnemonics repeat words by design
|
||||||
@@ -175,6 +175,34 @@ func TestDeterministicDerivation(t *testing.T) {
|
|||||||
t.Logf("Index 1: %s", id3.String())
|
t.Logf("Index 1: %s", id3.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestDeriveIdentityIgnoresExtraWhitespace checks that the same words give
|
||||||
|
// the same identity however they are spaced, as when a mnemonic is typed or
|
||||||
|
// pasted with a double space or a trailing newline.
|
||||||
|
func TestDeriveIdentityIgnoresExtraWhitespace(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
want, err := DeriveIdentity(mnemonic, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("derive: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
typedMnemonics := []string{
|
||||||
|
strings.Replace(mnemonic, " ", " ", 1) + " ",
|
||||||
|
"\t" + strings.ReplaceAll(mnemonic, " ", "\n") + "\n",
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, typed := range typedMnemonics {
|
||||||
|
got, err := DeriveIdentity(typed, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("derive from %q: %v", typed, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if got.String() != want.String() {
|
||||||
|
t.Errorf("%q derives a different identity from %q", typed, mnemonic)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestDeterministicXPRVDerivation(t *testing.T) {
|
func TestDeterministicXPRVDerivation(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/btcsuite/btcd/btcutil/hdkeychain"
|
"github.com/btcsuite/btcd/btcutil/hdkeychain"
|
||||||
"github.com/tyler-smith/go-bip39"
|
"sneak.berlin/go/secret/internal/bip39"
|
||||||
"sneak.berlin/go/secret/pkg/bip85"
|
"sneak.berlin/go/secret/pkg/bip85"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+4
-3
@@ -1,6 +1,8 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/check: run all checks (test, lint, lint-darwin, fmt-check). Our
|
# script/check: run all checks (test, lint, fmt-check). Our own
|
||||||
# own extension to scripts-to-rule-them-all. Must not modify any files.
|
# extension to scripts-to-rule-them-all. test and lint are Docker
|
||||||
|
# phases; fmt-check is native, because a formatter writes the working
|
||||||
|
# tree. Must not modify any files.
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
@@ -8,7 +10,6 @@ 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"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+19
-12
@@ -1,21 +1,28 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/cibuild: run the CI build. The Dockerfile runs script/check
|
# script/cibuild: run the CI build. It bootstraps first: a CI runner
|
||||||
# (via make check), so a successful build implies all checks pass.
|
# checks out and runs this and nothing else, and script/fmt-check runs
|
||||||
# The Gitea workflow runs this on push. The memlock ulimit lifts the limit
|
# the formatter on the host, which a pristine checkout cannot do.
|
||||||
# on memory the tests lock (memguard mlocks secrets); they also pass under
|
# --no-cache for the same reason as script/docker: the gate phases the
|
||||||
# the lower limit of a plain `docker build .`.
|
# final stage depends on are RUN steps, and a cached one is a check that
|
||||||
# A cached build checks nothing: a new CHECK_EPOCH on every run makes the
|
# did not run.
|
||||||
# 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
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
|
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
docker build --ulimit memlock=-1:-1 \
|
"$SCRIPT_DIR/bootstrap"
|
||||||
--build-arg CHECK_EPOCH="$(date +%s)" .
|
"$SCRIPT_DIR/check"
|
||||||
|
# Own line: a failing command substitution inside an argument does
|
||||||
|
# not trip `set -e`, so the inline form degrades silently to an
|
||||||
|
# empty constant. The VERSION build argument takes precedence over
|
||||||
|
# the version a build stage derives from the .git in the context.
|
||||||
|
version="$(git describe --tags --always --dirty 2>/dev/null || true)"
|
||||||
|
[ -n "$version" ] || version="unknown"
|
||||||
|
docker build --no-cache \
|
||||||
|
--build-arg VERSION="$version" \
|
||||||
|
-t "$("$SCRIPT_DIR/projectname")" .
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
+12
-13
@@ -1,24 +1,23 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/lint: run the linter, in docker only. Builds Dockerfile.lint,
|
# script/lint: run the linter. Linting is a phase of the Dockerfile and
|
||||||
# where golangci-lint runs as a build step.
|
# this builds that phase alone; the linter is never installed or run on
|
||||||
|
# a developer host, where a shared result cache and a host-global lock
|
||||||
|
# make its answer untrustworthy.
|
||||||
#
|
#
|
||||||
# A cached build lints nothing, so --no-cache-filter rebuilds the lint
|
# The phase is not the last stage in the file, so it is built only when
|
||||||
# stage on every run, an unchanged tree included. It ignores a stage name
|
# --target names it. --no-cache because a cached lint layer is a lint
|
||||||
# that does not exist, so --target names the same stage: a rename then
|
# that did not run. The tag makes each build replace the previous image
|
||||||
# fails the build instead of serving the lint from cache. cacheonly keeps
|
# instead of leaving a dangling one behind.
|
||||||
# no image; only the build's success matters.
|
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
|
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
docker build \
|
docker build --no-cache \
|
||||||
--progress=plain \
|
|
||||||
--target lint \
|
--target lint \
|
||||||
--no-cache-filter=lint \
|
-t "$("$SCRIPT_DIR/projectname")-lint" .
|
||||||
--output=type=cacheonly \
|
|
||||||
-f Dockerfile.lint .
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
#!/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 "$@"
|
|
||||||
+10
-13
@@ -1,22 +1,19 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/test: run the test suite (vet first, then the tests with the race
|
# script/test: run the test suite. Testing is a phase of the Dockerfile
|
||||||
# detector; a 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
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
|
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
# CGO is required (Makefile exports this too)
|
docker build --no-cache \
|
||||||
export CGO_ENABLED=1
|
--target test \
|
||||||
go vet ./...
|
-t "$("$SCRIPT_DIR/projectname")-test" .
|
||||||
# -count=1: run every test, never take a result from Go's test cache,
|
|
||||||
# which the Dockerfile keeps between builds. The rerun only prints
|
|
||||||
# details: `exit 1` keeps the script failing even if a flaky test
|
|
||||||
# passes on the second attempt.
|
|
||||||
go test -count=1 -timeout 30s -race -cover ./... || \
|
|
||||||
{ echo "--- Rerunning with -v for details ---"; \
|
|
||||||
go test -count=1 -timeout 30s -race -v ./...; exit 1; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
Reference in New Issue
Block a user