Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2823d93cc3 | ||
|
|
62967f28d0 |
+1
-4
@@ -14,11 +14,8 @@ ARG CHECK_EPOCH
|
||||
COPY . .
|
||||
|
||||
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.
|
||||
# Not make lint: script/lint is a docker build, which cannot run in here.
|
||||
RUN golangci-lint run --config .golangci.yml ./...
|
||||
RUN GOOS=darwin CGO_ENABLED=0 go vet ./...
|
||||
RUN GOOS=darwin CGO_ENABLED=0 golangci-lint run --config .golangci.yml ./...
|
||||
|
||||
# Build stage — tests and compilation
|
||||
# golang 1.24.13-alpine (2026-03-10)
|
||||
|
||||
+3
-13
@@ -1,6 +1,6 @@
|
||||
# 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.
|
||||
# Lint image, built by script/lint: 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
|
||||
@@ -17,13 +17,3 @@ 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
|
||||
|
||||
.PHONY: default bootstrap setup build test lint lint-darwin fmt fmt-check \
|
||||
check docker docker-run clean install hooks
|
||||
.PHONY: default bootstrap setup build test lint fmt fmt-check check docker \
|
||||
docker-run clean install hooks
|
||||
|
||||
default: check
|
||||
|
||||
@@ -24,10 +24,6 @@ fmt:
|
||||
lint:
|
||||
@script/lint
|
||||
|
||||
# Type-check and lint the macOS build from Linux (see script/lint-darwin)
|
||||
lint-darwin:
|
||||
@script/lint-darwin
|
||||
|
||||
check:
|
||||
@script/check
|
||||
|
||||
|
||||
@@ -197,6 +197,9 @@ Creates a new unlocker of the specified type:
|
||||
**Options:**
|
||||
- `--keyid <id>`: GPG key ID (optional for PGP type, uses default key if not specified)
|
||||
|
||||
A vault has one passphrase unlocker: adding one replaces the one the vault
|
||||
has, which is removed only once the new one is the current unlocker.
|
||||
|
||||
#### `secret unlocker remove <unlocker-id> [--force]` / `secret unlocker rm` ⚠️ 🛑
|
||||
|
||||
**DANGER**: Permanently removes an unlocker. Like Unix `rm`, this command
|
||||
@@ -243,8 +246,8 @@ Decrypts data using an Age key stored as a secret.
|
||||
├── vaults.d/
|
||||
│ ├── default/
|
||||
│ │ ├── unlockers.d/
|
||||
│ │ │ ├── passphrase/ # Passphrase unlocker
|
||||
│ │ │ └── pgp/ # PGP unlocker
|
||||
│ │ │ ├── passphrase-<time>/ # Passphrase unlocker
|
||||
│ │ │ └── <host>-pgp-<time>/ # PGP unlocker
|
||||
│ │ ├── secrets.d/
|
||||
│ │ │ ├── api%key/ # Secret: api/key
|
||||
│ │ │ │ ├── versions/
|
||||
@@ -260,7 +263,7 @@ Decrypts data using an Age key stored as a secret.
|
||||
│ │ │ └── current -> versions/20231215.001
|
||||
│ │ ├── vault-metadata.json # Vault metadata
|
||||
│ │ ├── pub.age # Long-term public key
|
||||
│ │ └── current-unlocker -> ../unlockers.d/passphrase
|
||||
│ │ └── current-unlocker # Current unlocker's directory name
|
||||
│ └── work/
|
||||
│ ├── unlockers.d/
|
||||
│ ├── secrets.d/
|
||||
@@ -519,15 +522,10 @@ them. We provide:
|
||||
- `script/lint` — run `golangci-lint` in docker only: builds
|
||||
`Dockerfile.lint`, where the linter is a build step that runs on every
|
||||
call, also on an unchanged tree
|
||||
- `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
|
||||
(`internal/secret/keychainunlocker.go` and its tests) and the Secure
|
||||
Enclave bindings (`internal/macse`) are not checked
|
||||
- `script/fmt` — format all Go code (writes)
|
||||
- `script/fmt-check` — check formatting without writing
|
||||
- `script/check` — run `script/test`, `script/lint`,
|
||||
`script/lint-darwin`, and `script/fmt-check`
|
||||
- `script/check` — run `script/test`, `script/lint`, and
|
||||
`script/fmt-check`
|
||||
- `script/docker` — build the Docker image tagged with the project name
|
||||
- `script/cibuild` — CI entrypoint: `docker build --ulimit
|
||||
memlock=-1:-1 .` (memguard needs mlock; the Dockerfile runs the
|
||||
|
||||
@@ -25,22 +25,31 @@ Bring the repo into policy compliance in one commit:
|
||||
|
||||
# Completed Steps
|
||||
|
||||
- 2026-10-04: `script/lint-darwin` (`make lint-darwin`) runs `go vet` and
|
||||
`golangci-lint` in docker on the code as a macOS build compiles it
|
||||
(`GOOS=darwin`), with cgo off
|
||||
(https://git.eeqj.de/sneak/secret/issues/50). `script/check` runs it,
|
||||
and the `Dockerfile` lint stage runs its commands, so `script/cibuild`
|
||||
does too. Before, CI on Linux never compiled the files built only for
|
||||
macOS. Compiling cgo code for macOS needs Apple's SDK headers, and both
|
||||
`internal/macse` and `github.com/keybase/go-keychain`, which
|
||||
`keychainunlocker.go` uses, are cgo on macOS. So `keychainunlocker.go`
|
||||
and its tests are now built only with cgo on macOS, like
|
||||
`macse_darwin.go`, and the keychain and `macse` stubs serve a macOS
|
||||
build without cgo, which before did not compile. `checkMacOSAvailable`
|
||||
moved to `seunlocker_darwin.go`. The check covers the Secure Enclave
|
||||
unlocker and the macOS-only tests `seunlocker_test.go` and
|
||||
`pgpunlock_test.go`, whose lint findings are fixed; lines over 88
|
||||
columns in the macOS files it cannot check are wrapped.
|
||||
- 2026-10-04: A crash while an unlocker is being replaced no longer
|
||||
leaves a current unlocker that cannot open the vault
|
||||
(https://git.eeqj.de/sneak/secret/issues/71). Every new unlocker gets
|
||||
a directory of its own, named with the time to the nanosecond:
|
||||
`passphrase-<time>`, `<host>-pgp-<time>`, and for a keychain or Secure
|
||||
Enclave unlocker the keychain item or Secure Enclave key, which names
|
||||
the directory, carries the time instead of the day. `secret.WriteDir`
|
||||
fails on a directory that exists instead of writing into it.
|
||||
`unlocker add passphrase` writes the new unlocker, makes it current,
|
||||
and only then removes the vault's other passphrase unlockers; a crash
|
||||
between the last two steps leaves the old one beside the new, and the
|
||||
old passphrase still opens the vault through it until the next
|
||||
`unlocker add passphrase` or an `unlocker remove` removes it. A PGP,
|
||||
keychain or
|
||||
Secure Enclave unlocker added on the same host and day as another of
|
||||
its type is added beside it instead of replacing it.
|
||||
- 2026-10-04: `secret unlocker add pgp` works on Linux
|
||||
(https://git.eeqj.de/sneak/secret/issues/88). `CreatePGPUnlocker` gets
|
||||
the vault's long-term key as adding a passphrase unlocker does, with the
|
||||
vault's `GetOrDeriveLongTermKey`, now part of `VaultInterface`: from the
|
||||
mnemonic, checked against the vault, or else from the current unlocker.
|
||||
Before, it used the keychain unlocker's helper, which on every platform
|
||||
but macOS always failed. A test adds a PGP unlocker for a throwaway GPG
|
||||
key, getting the long-term key once from the mnemonic and once from a
|
||||
passphrase unlocker, and reads a secret through the new unlocker.
|
||||
- 2026-10-04: A vault name may use only lowercase ASCII letters, digits,
|
||||
`.`, `-` and `_`, and must not be empty, `.` or `..`
|
||||
(https://git.eeqj.de/sneak/secret/issues/68); the error and `README.md`
|
||||
@@ -66,9 +75,7 @@ Bring the repo into policy compliance in one commit:
|
||||
and encrypt everything before writing anything. All four unlocker
|
||||
types write their files through `secret.WriteDir`: a new unlocker is
|
||||
built in a temporary directory, renamed into place when complete and
|
||||
removed on a failure. One added under the directory name of an
|
||||
existing unlocker is still written into that directory in place
|
||||
(https://git.eeqj.de/sneak/secret/issues/71).
|
||||
removed on a failure.
|
||||
- 2026-10-04: `secret unlocker select` and `secret unlocker remove`
|
||||
skip, with the warning `unlocker list` gives, an unlocker directory
|
||||
whose metadata file cannot be checked for, read or parsed, instead of
|
||||
@@ -164,12 +171,6 @@ Bring the repo into policy compliance in one commit:
|
||||
into place, and removals rename out of the way first, so a version
|
||||
or secret is never half-added and never half-removed. An
|
||||
interrupted command can still leave:
|
||||
- a broken unlocker, when it was replacing one: an unlocker added
|
||||
under the directory name of an existing one is rewritten file by
|
||||
file. That happens to a passphrase unlocker added to a vault that
|
||||
has one, and to a PGP, keychain or Secure Enclave unlocker added
|
||||
on the same host and day as another of its type
|
||||
(https://git.eeqj.de/sneak/secret/issues/71);
|
||||
- from `init` or `vault create` killed after the passphrase prompt
|
||||
but before the unlocker is written, a vault with no unlocker,
|
||||
which `vault create` has already made the current vault;
|
||||
@@ -264,15 +265,11 @@ Bring the repo into policy compliance in one commit:
|
||||
- Cover mnemonic-vs-xprv identity consistency in
|
||||
`pkg/agehd/agehd_test.go` `TestMnemonicVsXPRVConsistency` (was an
|
||||
in-code FIXME removed for godox).
|
||||
- CI does not compile, lint or test the files built only with cgo on
|
||||
macOS, since compiling them needs Apple's SDK:
|
||||
`internal/secret/keychainunlocker.go` with `keychainunlocker_test.go`,
|
||||
`validation_darwin_test.go` and `derivation_index_test.go`, and
|
||||
`internal/macse` (`macse_darwin.go`, `macse_test.go`, the Objective-C
|
||||
sources). Lint has never run on them, so it would likely find more
|
||||
there than the line lengths. No macOS test runs in CI. A macOS runner
|
||||
would cover all of it (asked on
|
||||
https://git.eeqj.de/sneak/secret/issues/50).
|
||||
- Darwin-gated files (`internal/secret/keychainunlocker.go`,
|
||||
`seunlocker_darwin.go`, `internal/macse/macse_darwin.go`, related
|
||||
tests) are not linted on the Linux CI runner and still contain lines
|
||||
over the new 88-column limit; they will surface if lint ever runs on
|
||||
macOS.
|
||||
- Merge secure-enclave-unlocker to main once review is done.
|
||||
- 1.0 critical security blockers (from repo TODO.md):
|
||||
- Command injection: GPG key IDs passed unescaped to exec.Command
|
||||
|
||||
@@ -366,8 +366,15 @@ func test01Initialize(t *testing.T, tempDir, testMnemonic, testPassphrase string
|
||||
unlockersDir := filepath.Join(defaultVaultDir, "unlockers.d")
|
||||
verifyFileExists(t, unlockersDir)
|
||||
|
||||
// Check current-unlocker file names the unlocker's directory
|
||||
currentUnlockerFile := filepath.Join(defaultVaultDir, "current-unlocker")
|
||||
verifyFileExists(t, currentUnlockerFile)
|
||||
|
||||
currentUnlockerContent := readFile(t, currentUnlockerFile)
|
||||
assert.Contains(t, string(currentUnlockerContent), "passphrase", "current unlocker should point to passphrase type")
|
||||
|
||||
// Verify passphrase unlocker was created
|
||||
passphraseUnlockerDir := filepath.Join(unlockersDir, "passphrase")
|
||||
passphraseUnlockerDir := filepath.Join(unlockersDir, string(currentUnlockerContent))
|
||||
verifyFileExists(t, passphraseUnlockerDir)
|
||||
|
||||
// Check unlocker metadata
|
||||
@@ -382,13 +389,6 @@ func test01Initialize(t *testing.T, tempDir, testMnemonic, testPassphrase string
|
||||
encryptedLTPubKey := filepath.Join(passphraseUnlockerDir, "pub.age")
|
||||
verifyFileExists(t, encryptedLTPubKey)
|
||||
|
||||
// Check current-unlocker file contains the relative path
|
||||
currentUnlockerFile := filepath.Join(defaultVaultDir, "current-unlocker")
|
||||
verifyFileExists(t, currentUnlockerFile)
|
||||
|
||||
currentUnlockerContent := readFile(t, currentUnlockerFile)
|
||||
assert.Contains(t, string(currentUnlockerContent), "passphrase", "current unlocker should point to passphrase type")
|
||||
|
||||
// Verify vault-metadata.json in vault
|
||||
vaultMetadata := filepath.Join(defaultVaultDir, "vault-metadata.json")
|
||||
verifyFileExists(t, vaultMetadata)
|
||||
@@ -537,7 +537,8 @@ func test04ImportMnemonic(t *testing.T, tempDir, testMnemonic, testPassphrase st
|
||||
verifyFileExists(t, pubKeyFile)
|
||||
|
||||
// Verify passphrase unlocker was created
|
||||
passphraseUnlockerDir := filepath.Join(workVaultDir, "unlockers.d", "passphrase")
|
||||
currentUnlocker := readFile(t, filepath.Join(workVaultDir, "current-unlocker"))
|
||||
passphraseUnlockerDir := filepath.Join(workVaultDir, "unlockers.d", string(currentUnlocker))
|
||||
verifyFileExists(t, passphraseUnlockerDir)
|
||||
|
||||
// Check unlocker files
|
||||
|
||||
@@ -171,7 +171,7 @@ func TestInvalidSecretNameLeavesVaultsUnchanged(t *testing.T) {
|
||||
|
||||
vaultDir := testStateDir + "/vaults.d/default"
|
||||
require.Contains(t, before, vaultDir+"/secrets.d/x/")
|
||||
require.Contains(t, before, vaultDir+"/unlockers.d/passphrase/")
|
||||
require.Contains(t, before, vaultDir+"/current-unlocker")
|
||||
require.Equal(t, "default", before[testStateDir+"/currentvault"])
|
||||
|
||||
cmd := &cobra.Command{}
|
||||
|
||||
@@ -5,18 +5,88 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.eeqj.de/sneak/secret/internal/secret"
|
||||
"git.eeqj.de/sneak/secret/internal/vault"
|
||||
"github.com/awnumar/memguard"
|
||||
"github.com/spf13/afero"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// unknownTestGPGUserID is a GPG user ID that no key in the test keyring has.
|
||||
const unknownTestGPGUserID = "not-in-keyring@example.com"
|
||||
|
||||
// The secret TestAddPGPUnlocker stores, then reads through the new unlocker.
|
||||
const (
|
||||
addTestSecretName = "api-key"
|
||||
addTestSecretValue = "value"
|
||||
)
|
||||
|
||||
// TestAddPGPUnlocker adds a PGP unlocker for a throwaway GPG key to a vault
|
||||
// with a passphrase unlocker, getting the vault's long-term key from the
|
||||
// mnemonic or, with the mnemonic unset, from the passphrase unlocker. It
|
||||
// then reads a secret with neither the mnemonic nor the passphrase set, so
|
||||
// through the new unlocker, which the add selects.
|
||||
func TestAddPGPUnlocker(t *testing.T) {
|
||||
newTestGPGKey(t)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
// mnemonic is the mnemonic set while the unlocker is added.
|
||||
mnemonic string
|
||||
}{
|
||||
{"long-term key from the mnemonic", testMnemonic},
|
||||
{"long-term key from the current unlocker", ""},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Setenv(secret.EnvMnemonic, testMnemonic)
|
||||
t.Setenv(secret.EnvUnlockPassphrase, testPassphrase)
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
vlt, err := vault.CreateVault(fs, listTestStateDir, listTestVaultName)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = vlt.AddSecret(addTestSecretName,
|
||||
memguard.NewBufferFromBytes([]byte(addTestSecretValue)), false)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = vlt.CreatePassphraseUnlocker(
|
||||
memguard.NewBufferFromBytes([]byte(testPassphrase)))
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Setenv(secret.EnvMnemonic, test.mnemonic)
|
||||
|
||||
instance, cmd := newTestInstance(fs)
|
||||
cmd.Flags().String("keyid", unreadableTestGPGUserID, "")
|
||||
require.NoError(t, instance.UnlockersAdd(unlockerTypePGP, cmd))
|
||||
|
||||
t.Setenv(secret.EnvMnemonic, "")
|
||||
t.Setenv(secret.EnvUnlockPassphrase, "")
|
||||
|
||||
reopened := vault.NewVault(fs, listTestStateDir, listTestVaultName)
|
||||
|
||||
current, err := reopened.GetCurrentUnlocker()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, unlockerTypePGP, current.GetType())
|
||||
|
||||
value, err := reopened.GetSecret(addTestSecretName)
|
||||
require.NoError(t, err)
|
||||
|
||||
defer value.Destroy()
|
||||
|
||||
assert.Equal(t, addTestSecretValue, value.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAddPGPUnlockerUnknownKey asserts that adding a PGP unlocker for a key
|
||||
// the keyring does not hold fails at looking up the key's fingerprint and
|
||||
// leaves no new unlocker directory. The error must come from the lookup: a
|
||||
// lookup moved after anything is written would also come after getting the
|
||||
// vault's long-term key, which fails first on every platform but macOS
|
||||
// (https://git.eeqj.de/sneak/secret/issues/88).
|
||||
// vault's long-term key, which fails first here: this vault's unlockers hold
|
||||
// no keys.
|
||||
//
|
||||
//nolint:paralleltest // t.Setenv (GNUPGHOME) forbids parallel tests
|
||||
func TestAddPGPUnlockerUnknownKey(t *testing.T) {
|
||||
|
||||
@@ -122,7 +122,8 @@ func assertDirEntries(t *testing.T, fs afero.Fs, dir string, want ...string) {
|
||||
}
|
||||
|
||||
// newTestGPGKey points GNUPGHOME at a fresh directory, generates a GPG key
|
||||
// without a passphrase there, and returns the key's fingerprint.
|
||||
// without a passphrase there, with a subkey for encryption, and returns the
|
||||
// key's fingerprint.
|
||||
func newTestGPGKey(t *testing.T) string {
|
||||
t.Helper()
|
||||
|
||||
@@ -151,6 +152,14 @@ func newTestGPGKey(t *testing.T) string {
|
||||
fingerprint, err := secret.ResolveGPGKeyFingerprint(unreadableTestGPGUserID)
|
||||
require.NoError(t, err)
|
||||
|
||||
//nolint:gosec // G204: fingerprint is the test key's, as gpg printed it
|
||||
output, err = exec.CommandContext(t.Context(), "gpg", "--batch",
|
||||
"--pinentry-mode", "loopback", "--passphrase", "",
|
||||
"--quick-add-key", fingerprint, "cv25519", "encr", "never",
|
||||
).CombinedOutput()
|
||||
require.NoError(t, err, "adding the test GPG key's encryption subkey: %s",
|
||||
output)
|
||||
|
||||
return fingerprint
|
||||
}
|
||||
|
||||
|
||||
@@ -38,8 +38,7 @@ const (
|
||||
)
|
||||
|
||||
// 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).
|
||||
// Returns the uncompressed public key bytes (65 bytes) and the identity hash (for deletion).
|
||||
func CreateKey(label string) (publicKey []byte, hash string, err error) {
|
||||
pubKeyBuf := make([]C.uint8_t, p256UncompressedKeySize)
|
||||
pubKeyLen := C.int(p256UncompressedKeySize)
|
||||
@@ -58,8 +57,7 @@ func CreateKey(label string) (publicKey []byte, hash string, err error) {
|
||||
return nil, "", fmt.Errorf("secure enclave: %s", C.GoString(&errBuf[0]))
|
||||
}
|
||||
|
||||
//nolint:nlreturn // CGo result extraction
|
||||
pk := C.GoBytes(unsafe.Pointer(&pubKeyBuf[0]), pubKeyLen)
|
||||
pk := C.GoBytes(unsafe.Pointer(&pubKeyBuf[0]), pubKeyLen) //nolint:nlreturn // CGo result extraction
|
||||
h := C.GoString(&hashBuf[0])
|
||||
|
||||
return pk, h, nil
|
||||
@@ -85,8 +83,7 @@ func Encrypt(label string, plaintext []byte) ([]byte, error) {
|
||||
return nil, fmt.Errorf("secure enclave: %s", C.GoString(&errBuf[0]))
|
||||
}
|
||||
|
||||
//nolint:nlreturn // CGo result extraction
|
||||
out := C.GoBytes(unsafe.Pointer(&ciphertextBuf[0]), ciphertextLen)
|
||||
out := C.GoBytes(unsafe.Pointer(&ciphertextBuf[0]), ciphertextLen) //nolint:nlreturn // CGo result extraction
|
||||
|
||||
return out, nil
|
||||
}
|
||||
@@ -110,8 +107,7 @@ func Decrypt(label string, ciphertext []byte) ([]byte, error) {
|
||||
return nil, fmt.Errorf("secure enclave: %s", C.GoString(&errBuf[0]))
|
||||
}
|
||||
|
||||
//nolint:nlreturn // CGo result extraction
|
||||
out := C.GoBytes(unsafe.Pointer(&plaintextBuf[0]), plaintextLen)
|
||||
out := C.GoBytes(unsafe.Pointer(&plaintextBuf[0]), plaintextLen) //nolint:nlreturn // CGo result extraction
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build !darwin || !cgo
|
||||
//go:build !darwin
|
||||
|
||||
// Package macse provides Go bindings for macOS Secure Enclave operations.
|
||||
package macse
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//go:build darwin && cgo
|
||||
//go:build darwin
|
||||
// +build darwin
|
||||
|
||||
package macse
|
||||
|
||||
@@ -44,8 +45,7 @@ func TestCreateAndDeleteKey(t *testing.T) {
|
||||
|
||||
// Verify valid uncompressed P-256 public key
|
||||
if len(pubKey) != p256UncompressedKeySize {
|
||||
t.Fatalf("expected public key length %d, got %d",
|
||||
p256UncompressedKeySize, len(pubKey))
|
||||
t.Fatalf("expected public key length %d, got %d", p256UncompressedKeySize, len(pubKey))
|
||||
}
|
||||
|
||||
if pubKey[0] != 0x04 {
|
||||
@@ -83,8 +83,7 @@ func TestEncryptDecryptRoundTrip(t *testing.T) {
|
||||
}()
|
||||
|
||||
// Test data simulating an age private key
|
||||
plaintext := []byte("AGE-SECRET-KEY-1" +
|
||||
"QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ")
|
||||
plaintext := []byte("AGE-SECRET-KEY-1QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ")
|
||||
|
||||
// Encrypt
|
||||
ciphertext, err := Encrypt(testKeyLabel, plaintext)
|
||||
|
||||
@@ -3,6 +3,7 @@ package secret
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
@@ -62,13 +63,12 @@ func TempDirFor(fs afero.Fs, target string) (string, error) {
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
// WriteDir calls write to write the files of the directory dir. When dir does
|
||||
// not exist yet, write writes them into a temporary directory from TempDirFor,
|
||||
// which is then renamed to dir, so that neither a failure nor a crash leaves
|
||||
// dir half-written; on a failure the temporary directory is removed, and a
|
||||
// failure to remove it is returned along with the first. A directory cannot be
|
||||
// renamed over one that has files in it, so when dir already exists, write
|
||||
// writes into it in place; dir is then never removed.
|
||||
// WriteDir calls write to write the files of the new directory dir into a
|
||||
// temporary directory from TempDirFor, which is then renamed to dir, so that
|
||||
// neither a failure nor a crash leaves dir half-written; on a failure the
|
||||
// temporary directory is removed, and a failure to remove it is returned
|
||||
// along with the first. A directory cannot be replaced in one rename, so if
|
||||
// dir already exists, WriteDir fails without calling write.
|
||||
func WriteDir(fs afero.Fs, dir string, write func(dir string) error) error {
|
||||
exists, err := afero.Exists(fs, dir)
|
||||
if err != nil {
|
||||
@@ -76,7 +76,7 @@ func WriteDir(fs afero.Fs, dir string, write func(dir string) error) error {
|
||||
}
|
||||
|
||||
if exists {
|
||||
return write(dir)
|
||||
return fmt.Errorf("failed to create %s: %w", dir, os.ErrExist)
|
||||
}
|
||||
|
||||
// Create the directory the finished one is renamed into
|
||||
|
||||
+137
-17
@@ -191,6 +191,22 @@ func dirNames(t *testing.T, fs afero.Fs, dir string) []string {
|
||||
return names
|
||||
}
|
||||
|
||||
// dirFiles returns the contents of the files in dir, by name.
|
||||
func dirFiles(t *testing.T, fs afero.Fs, dir string) map[string]string {
|
||||
t.Helper()
|
||||
|
||||
files := map[string]string{}
|
||||
|
||||
for _, name := range dirNames(t, fs, dir) {
|
||||
data, err := afero.ReadFile(fs, filepath.Join(dir, name))
|
||||
require.NoError(t, err)
|
||||
|
||||
files[name] = string(data)
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
// writeLongTermKey gives the test vault under stateDir a new long-term key
|
||||
// and returns it.
|
||||
func writeLongTermKey(
|
||||
@@ -666,14 +682,14 @@ func TestPassphraseUnlockerIsWholeOrAbsent(t *testing.T) {
|
||||
vaultDir, err := vlt.GetDirectory()
|
||||
require.NoError(t, err)
|
||||
|
||||
unlockerDir := filepath.Join(vaultDir, "unlockers.d", "passphrase")
|
||||
// The vault has no unlocker yet, so any directory in here is
|
||||
// the new one
|
||||
unlockersDir := filepath.Join(vaultDir, "unlockers.d")
|
||||
|
||||
fs := hookFs{Fs: base, before: func(string, string) error {
|
||||
exists, err := afero.DirExists(base, unlockerDir)
|
||||
require.NoError(t, err)
|
||||
|
||||
if exists {
|
||||
assert.ElementsMatch(t, files, dirNames(t, base, unlockerDir),
|
||||
for _, name := range dirNames(t, base, unlockersDir) {
|
||||
assert.ElementsMatch(t, files,
|
||||
dirNames(t, base, filepath.Join(unlockersDir, name)),
|
||||
"unlocker directory visible before it was complete")
|
||||
}
|
||||
|
||||
@@ -683,14 +699,118 @@ func TestPassphraseUnlockerIsWholeOrAbsent(t *testing.T) {
|
||||
passphrase := memguard.NewBufferFromBytes([]byte(unlockerPassphrase))
|
||||
defer passphrase.Destroy()
|
||||
|
||||
_, err = vault.NewVault(fs, stateDir, testVaultName).
|
||||
unlocker, err := vault.NewVault(fs, stateDir, testVaultName).
|
||||
CreatePassphraseUnlocker(passphrase)
|
||||
require.NoError(t, err)
|
||||
assert.ElementsMatch(t, files, dirNames(t, base, unlockerDir))
|
||||
assert.ElementsMatch(t, files, dirNames(t, base, unlocker.GetDirectory()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPassphraseUnlockerReplacementKeepsVaultOpen replaces the vault's
|
||||
// passphrase unlocker, failing at each change the replacement makes in turn,
|
||||
// until an attempt makes all of its changes; each attempt starts from what
|
||||
// the one before left. Both at the change that fails, which is where a crash
|
||||
// would leave the vault, and after the attempt returns, the vault must open
|
||||
// with the passphrase through its current unlocker. Once an attempt
|
||||
// succeeds, the vault must have one passphrase unlocker left.
|
||||
func TestPassphraseUnlockerReplacementKeepsVaultOpen(t *testing.T) {
|
||||
t.Setenv(secret.EnvMnemonic, testMnemonic)
|
||||
t.Setenv(secret.EnvUnlockPassphrase, unlockerPassphrase)
|
||||
|
||||
for _, tfs := range testFilesystems {
|
||||
t.Run(tfs.name, func(t *testing.T) {
|
||||
base, stateDir := tfs.open(t)
|
||||
vlt, err := vault.CreateVault(base, stateDir, testVaultName)
|
||||
require.NoError(t, err)
|
||||
|
||||
ltIdentity, err := vlt.GetOrDeriveLongTermKey()
|
||||
require.NoError(t, err)
|
||||
|
||||
passphrase := memguard.NewBufferFromBytes([]byte(unlockerPassphrase))
|
||||
defer passphrase.Destroy()
|
||||
|
||||
_, err = vlt.CreatePassphraseUnlocker(passphrase)
|
||||
require.NoError(t, err)
|
||||
|
||||
// From here on only the current unlocker opens the vault
|
||||
t.Setenv(secret.EnvMnemonic, "")
|
||||
|
||||
assertOpens := vaultOpensCheck(t, base, stateDir, ltIdentity)
|
||||
|
||||
for failAt := 1; ; failAt++ {
|
||||
changes := 0
|
||||
fs := hookFs{Fs: base, before: func(string, string) error {
|
||||
changes++
|
||||
if changes != failAt {
|
||||
return nil
|
||||
}
|
||||
|
||||
assertOpens()
|
||||
|
||||
return errInjected
|
||||
}}
|
||||
|
||||
replacing := vault.NewVault(fs, stateDir, testVaultName)
|
||||
replacing.Unlock(ltIdentity)
|
||||
|
||||
_, err = replacing.CreatePassphraseUnlocker(passphrase)
|
||||
|
||||
assertOpens()
|
||||
|
||||
if changes < failAt {
|
||||
require.NoError(t, err)
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
require.ErrorIs(t, err, errInjected)
|
||||
}
|
||||
|
||||
unlockers, err := vlt.ListUnlockers()
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, unlockers, 1)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// vaultOpensCheck returns a function that checks that the test vault under
|
||||
// stateDir opens through its current unlocker, with the test passphrase, to
|
||||
// the long-term key ltIdentity. Opening it takes a second, so an unlocker
|
||||
// directory it has opened through before is not opened again: it must hold
|
||||
// the same files as then.
|
||||
func vaultOpensCheck(
|
||||
t *testing.T, fs afero.Fs, stateDir string, ltIdentity *age.X25519Identity,
|
||||
) func() {
|
||||
t.Helper()
|
||||
|
||||
vaultDir := filepath.Join(stateDir, "vaults.d", testVaultName)
|
||||
|
||||
// The files of each unlocker directory the vault has opened through
|
||||
opened := map[string]map[string]string{}
|
||||
|
||||
return func() {
|
||||
t.Helper()
|
||||
|
||||
current, err := afero.ReadFile(fs, filepath.Join(vaultDir, "current-unlocker"))
|
||||
require.NoError(t, err)
|
||||
|
||||
files := dirFiles(t, fs, filepath.Join(vaultDir, "unlockers.d", string(current)))
|
||||
|
||||
if before, ok := opened[string(current)]; ok {
|
||||
assert.Equal(t, before, files, "unlocker changed since it opened the vault")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
key, err := vault.NewVault(fs, stateDir, testVaultName).UnlockVault()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, ltIdentity.Recipient().String(), key.Recipient().String())
|
||||
|
||||
opened[string(current)] = files
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteDirFailureLeavesNothing makes writing a new directory fail after
|
||||
// a file has been written in it, and checks that neither the directory nor
|
||||
// its temporary directory is left behind; and, when the temporary directory
|
||||
@@ -736,10 +856,10 @@ func TestWriteDirFailureLeavesNothing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteDirKeepsExistingDir makes writing into a directory that already
|
||||
// exists fail, and checks that the directory, with what was in it, is still
|
||||
// there: WriteDir writes into it in place and never removes it.
|
||||
func TestWriteDirKeepsExistingDir(t *testing.T) {
|
||||
// TestWriteDirRefusesExistingDir checks that WriteDir fails, without calling
|
||||
// write, when the directory already exists, and leaves the directory as it
|
||||
// was: it never writes into a directory in place.
|
||||
func TestWriteDirRefusesExistingDir(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, tfs := range testFilesystems {
|
||||
@@ -747,17 +867,17 @@ func TestWriteDirKeepsExistingDir(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs, dir := tfs.open(t)
|
||||
target := filepath.Join(dir, "unlockers.d", "passphrase")
|
||||
target := filepath.Join(dir, "unlockers.d", "existing")
|
||||
require.NoError(t, fs.MkdirAll(target, secret.DirPerms))
|
||||
require.NoError(t, secret.WriteFileAtomic(fs,
|
||||
filepath.Join(target, unlockerMetadataFile), []byte("{}")))
|
||||
|
||||
err := secret.WriteDir(fs, target, func(got string) error {
|
||||
assert.Equal(t, target, got)
|
||||
err := secret.WriteDir(fs, target, func(string) error {
|
||||
t.Error("write called for a directory that exists")
|
||||
|
||||
return errInjected
|
||||
return nil
|
||||
})
|
||||
require.ErrorIs(t, err, errInjected)
|
||||
require.ErrorIs(t, err, os.ErrExist)
|
||||
assert.Equal(t, []string{unlockerMetadataFile}, dirNames(t, fs, target))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -16,6 +16,12 @@ const (
|
||||
EnvUnlockPassphrase = "SB_UNLOCK_PASSPHRASE"
|
||||
// EnvGPGKeyID is the environment variable for providing the GPG key ID
|
||||
EnvGPGKeyID = "SB_GPG_KEY_ID"
|
||||
|
||||
// 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
|
||||
// to the nanosecond, so that every new unlocker, even one added right
|
||||
// after another, gets a directory of its own.
|
||||
UnlockerTimeFormat = "2006-01-02.15.04.05.000000000"
|
||||
)
|
||||
|
||||
// File system permission constants
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build darwin && cgo
|
||||
//go:build darwin
|
||||
|
||||
package secret
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"filippo.io/age"
|
||||
"git.eeqj.de/sneak/secret/pkg/agehd"
|
||||
"github.com/awnumar/memguard"
|
||||
"github.com/spf13/afero"
|
||||
@@ -30,25 +31,16 @@ func (v *realVault) GetName() string { return v.name }
|
||||
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")
|
||||
}
|
||||
|
||||
func (v *realVault) GetCurrentUnlocker() (Unlocker, error) {
|
||||
panic("not used")
|
||||
}
|
||||
|
||||
func (v *realVault) CreatePassphraseUnlocker(
|
||||
*memguard.LockedBuffer,
|
||||
) (*PassphraseUnlocker, error) {
|
||||
func (v *realVault) AddSecret(string, *memguard.LockedBuffer, bool) error { panic("not used") }
|
||||
func (v *realVault) GetCurrentUnlocker() (Unlocker, error) { panic("not used") }
|
||||
func (v *realVault) GetOrDeriveLongTermKey() (*age.X25519Identity, error) { 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 {
|
||||
func createRealVault(t *testing.T, fs afero.Fs, stateDir, name string, derivationIndex uint32) *realVault {
|
||||
t.Helper()
|
||||
|
||||
vaultDir := filepath.Join(stateDir, "vaults.d", name)
|
||||
@@ -61,15 +53,13 @@ func createRealVault(
|
||||
}
|
||||
metaBytes, err := json.Marshal(metadata)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, afero.WriteFile(fs,
|
||||
filepath.Join(vaultDir, "vault-metadata.json"), metaBytes, FilePerms))
|
||||
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) {
|
||||
const testMnemonic = "abandon abandon abandon abandon abandon abandon " +
|
||||
"abandon abandon abandon abandon abandon about"
|
||||
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)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//go:build darwin && cgo
|
||||
//go:build darwin
|
||||
// +build darwin
|
||||
|
||||
package secret
|
||||
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"filippo.io/age"
|
||||
@@ -22,9 +24,7 @@ import (
|
||||
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"
|
||||
KEYCHAIN_APP_IDENTIFIER = "berlin.sneak.app.secret" //nolint:revive // ALL_CAPS is intentional for this constant
|
||||
)
|
||||
|
||||
// keychainItemNameRegex validates keychain item names
|
||||
@@ -64,8 +64,7 @@ func (k *KeychainUnlocker) GetIdentity() (*age.X25519Identity, error) {
|
||||
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)
|
||||
Debug("Failed to retrieve data from keychain", "error", err, "keychain_item", keychainItemName)
|
||||
|
||||
return nil, fmt.Errorf("failed to retrieve data from keychain: %w", err)
|
||||
}
|
||||
@@ -96,8 +95,7 @@ func (k *KeychainUnlocker) GetIdentity() (*age.X25519Identity, error) {
|
||||
|
||||
encryptedAgePrivKeyData, err := afero.ReadFile(k.fs, agePrivKeyPath)
|
||||
if err != nil {
|
||||
Debug("Failed to read encrypted age private key",
|
||||
"error", err, "path", agePrivKeyPath)
|
||||
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)
|
||||
}
|
||||
@@ -108,16 +106,12 @@ func (k *KeychainUnlocker) GetIdentity() (*age.X25519Identity, error) {
|
||||
)
|
||||
|
||||
// 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)
|
||||
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())
|
||||
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)
|
||||
return nil, fmt.Errorf("failed to decrypt age private key with keychain passphrase: %w", err)
|
||||
}
|
||||
defer agePrivKeyBuffer.Destroy()
|
||||
|
||||
@@ -180,8 +174,7 @@ 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())
|
||||
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)
|
||||
}
|
||||
@@ -189,8 +182,7 @@ func (k *KeychainUnlocker) Remove() error {
|
||||
// Step 2: Remove from keychain
|
||||
Debug("Removing keychain item", "keychain_item", keychainItemName)
|
||||
if err := deleteFromKeychain(keychainItemName); err != nil {
|
||||
Debug("Failed to remove keychain item",
|
||||
"error", err, "keychain_item", keychainItemName)
|
||||
Debug("Failed to remove keychain item", "error", err, "keychain_item", keychainItemName)
|
||||
|
||||
return fmt.Errorf("failed to remove keychain item: %w", err)
|
||||
}
|
||||
@@ -198,22 +190,18 @@ func (k *KeychainUnlocker) Remove() error {
|
||||
// Step 3: Remove directory
|
||||
Debug("Removing keychain unlocker directory", "directory", k.Directory)
|
||||
if err := RemoveDirAtomic(k.fs, k.Directory); err != nil {
|
||||
Debug("Failed to remove keychain unlocker directory",
|
||||
"error", err, "directory", k.Directory)
|
||||
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)
|
||||
Debug("Successfully removed keychain unlocker", "unlocker_id", k.GetID(), "keychain_item", keychainItemName)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewKeychainUnlocker creates a new KeychainUnlocker instance
|
||||
func NewKeychainUnlocker(
|
||||
fs afero.Fs, directory string, metadata UnlockerMetadata,
|
||||
) *KeychainUnlocker {
|
||||
func NewKeychainUnlocker(fs afero.Fs, directory string, metadata UnlockerMetadata) *KeychainUnlocker {
|
||||
return &KeychainUnlocker{
|
||||
Directory: directory,
|
||||
Metadata: metadata,
|
||||
@@ -245,18 +233,15 @@ func generateKeychainUnlockerName(vaultName string) (string, error) {
|
||||
return "", fmt.Errorf("failed to get hostname: %w", err)
|
||||
}
|
||||
|
||||
// Format: secret-<vault>-<hostname>-<date>
|
||||
enrollmentDate := time.Now().Format("2006-01-02")
|
||||
// Format: secret-<vault>-<hostname>-<time>
|
||||
enrollmentTime := time.Now().UTC().Format(UnlockerTimeFormat)
|
||||
|
||||
return fmt.Sprintf("secret-%s-%s-%s", vaultName, hostname, enrollmentDate), nil
|
||||
return fmt.Sprintf("secret-%s-%s-%s", vaultName, hostname, enrollmentTime), nil
|
||||
}
|
||||
|
||||
// getLongTermPrivateKey retrieves the long-term private key either from
|
||||
// environment or current unlocker
|
||||
// getLongTermPrivateKey retrieves the long-term private key either from environment or current unlocker
|
||||
// Returns a LockedBuffer to ensure the private key is protected in memory
|
||||
func getLongTermPrivateKey(
|
||||
fs afero.Fs, vault VaultInterface,
|
||||
) (*memguard.LockedBuffer, error) {
|
||||
func getLongTermPrivateKey(fs afero.Fs, vault VaultInterface) (*memguard.LockedBuffer, error) {
|
||||
// Check if mnemonic is available in environment variable
|
||||
envMnemonic := os.Getenv(EnvMnemonic)
|
||||
if envMnemonic != "" {
|
||||
@@ -280,8 +265,7 @@ func getLongTermPrivateKey(
|
||||
// Use mnemonic with the vault's actual derivation index
|
||||
ltIdentity, err := agehd.DeriveIdentity(envMnemonic, metadata.DerivationIndex)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"failed to derive long-term key from mnemonic: %w", err)
|
||||
return nil, fmt.Errorf("failed to derive long-term key from mnemonic: %w", err)
|
||||
}
|
||||
|
||||
// Return the private key in a secure buffer
|
||||
@@ -305,40 +289,31 @@ func getLongTermPrivateKey(
|
||||
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"))
|
||||
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)
|
||||
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"))
|
||||
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)
|
||||
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"))
|
||||
// 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)
|
||||
return nil, fmt.Errorf("failed to read encrypted long-term key from current keychain unlocker: %w", err)
|
||||
}
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf(
|
||||
"unsupported current unlocker type for keychain unlocker creation")
|
||||
return nil, fmt.Errorf("unsupported current unlocker type for keychain unlocker creation")
|
||||
}
|
||||
|
||||
// Decrypt long-term private key using current unlocker
|
||||
ltPrivKeyBuffer, err := DecryptWithIdentity(
|
||||
encryptedLtPrivKey, currentUnlockerIdentity)
|
||||
ltPrivKeyBuffer, err := DecryptWithIdentity(encryptedLtPrivKey, currentUnlockerIdentity)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decrypt long-term private key: %w", err)
|
||||
}
|
||||
@@ -395,8 +370,7 @@ func CreateKeychainUnlocker(fs afero.Fs, stateDir string) (*KeychainUnlocker, er
|
||||
agePrivKeyBuffer := memguard.NewBufferFromBytes([]byte(agePrivKeyStr))
|
||||
defer agePrivKeyBuffer.Destroy()
|
||||
|
||||
encryptedAgePrivKey, err := EncryptWithPassphrase(
|
||||
agePrivKeyBuffer, agePrivKeyPassphrase)
|
||||
encryptedAgePrivKey, err := EncryptWithPassphrase(agePrivKeyBuffer, agePrivKeyPassphrase)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to encrypt age private key with passphrase: %w", err)
|
||||
}
|
||||
@@ -409,11 +383,9 @@ func CreateKeychainUnlocker(fs afero.Fs, stateDir string) (*KeychainUnlocker, er
|
||||
defer ltPrivKeyData.Destroy()
|
||||
|
||||
// Step 5: Encrypt long-term private key to the new age unlocker
|
||||
encryptedLtPrivKeyToAge, err := EncryptToRecipient(
|
||||
ltPrivKeyData, ageIdentity.Recipient())
|
||||
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)
|
||||
return nil, fmt.Errorf("failed to encrypt long-term private key to age unlocker: %w", err)
|
||||
}
|
||||
|
||||
// Step 6: Prepare keychain data
|
||||
@@ -484,8 +456,16 @@ func CreateKeychainUnlocker(fs afero.Fs, stateDir string) (*KeychainUnlocker, er
|
||||
}, nil
|
||||
}
|
||||
|
||||
// validateKeychainItemName validates that a keychain item name is safe for
|
||||
// command execution
|
||||
// checkMacOSAvailable verifies that we're running on macOS
|
||||
func checkMacOSAvailable() error {
|
||||
if runtime.GOOS != "darwin" {
|
||||
return fmt.Errorf("keychain unlockers are only supported on macOS, current OS: %s", runtime.GOOS)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateKeychainItemName validates that a keychain item name is safe for command execution
|
||||
func validateKeychainItemName(itemName string) error {
|
||||
if itemName == "" {
|
||||
return fmt.Errorf("keychain item name cannot be empty")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build !darwin || !cgo
|
||||
//go:build !darwin
|
||||
|
||||
package secret
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"errors"
|
||||
|
||||
"filippo.io/age"
|
||||
"github.com/awnumar/memguard"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
@@ -79,10 +78,3 @@ func (k *KeychainUnlocker) Remove() error {
|
||||
func CreateKeychainUnlocker(_ afero.Fs, _ string) (*KeychainUnlocker, error) {
|
||||
return nil, errKeychainNotSupported
|
||||
}
|
||||
|
||||
// getLongTermPrivateKey returns an error on non-Darwin platforms
|
||||
func getLongTermPrivateKey(
|
||||
_ afero.Fs, _ VaultInterface,
|
||||
) (*memguard.LockedBuffer, error) {
|
||||
return nil, errKeychainNotSupported
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//go:build darwin && cgo
|
||||
//go:build darwin
|
||||
// +build darwin
|
||||
|
||||
package secret
|
||||
|
||||
@@ -34,8 +35,7 @@ func TestKeychainStoreRetrieveDelete(t *testing.T) {
|
||||
// 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")
|
||||
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"
|
||||
@@ -48,8 +48,7 @@ func TestKeychainStoreRetrieveDelete(t *testing.T) {
|
||||
// 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")
|
||||
assert.Equal(t, newTestData, string(retrievedData), "Retrieved data doesn't match updated data")
|
||||
|
||||
// Test 4: Delete from keychain
|
||||
err = deleteFromKeychain(testItemName)
|
||||
@@ -94,8 +93,7 @@ func TestKeychainInvalidItemName(t *testing.T) {
|
||||
for _, name := range invalidNames {
|
||||
err := storeInKeychain(name, testData)
|
||||
assert.Error(t, err, "Expected error for invalid name: %s", name)
|
||||
assert.Contains(t, err.Error(), "invalid keychain item name",
|
||||
"Error should mention invalid name for: %s", name)
|
||||
assert.Contains(t, err.Error(), "invalid keychain item name", "Error should mention invalid name for: %s", name)
|
||||
}
|
||||
|
||||
// Test valid names (should not error on validation)
|
||||
@@ -182,6 +180,5 @@ func TestDeleteNonExistentKeychainItem(t *testing.T) {
|
||||
// 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")
|
||||
assert.NoError(t, err, "Deleting non-existent keychain item should not return an error")
|
||||
}
|
||||
|
||||
+322
-452
@@ -4,9 +4,7 @@ package secret_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -24,24 +22,23 @@ import (
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// pgpUnlockerType is the type of a PGP unlocker.
|
||||
const pgpUnlockerType = "pgp"
|
||||
|
||||
var errNilDataBuffer = errors.New("data buffer is nil")
|
||||
// Register vault with secret package for testing
|
||||
func init() {
|
||||
// Register the vault.GetCurrentVault function with the secret package
|
||||
secret.RegisterGetCurrentVaultFunc(func(fs afero.Fs, stateDir string) (secret.VaultInterface, error) {
|
||||
return vault.GetCurrentVault(fs, stateDir)
|
||||
})
|
||||
}
|
||||
|
||||
// setupNonInteractiveGPG creates a custom GPG environment for testing
|
||||
func setupNonInteractiveGPG(t *testing.T, _, passphrase, gnupgHomeDir string) {
|
||||
t.Helper()
|
||||
|
||||
// Create GPG config file for non-interactive operation
|
||||
gpgConfPath := filepath.Join(gnupgHomeDir, "gpg.conf")
|
||||
gpgConfContent := `batch
|
||||
no-tty
|
||||
pinentry-mode loopback
|
||||
`
|
||||
|
||||
err := os.WriteFile(gpgConfPath, []byte(gpgConfContent), 0o600)
|
||||
if err != nil {
|
||||
if err := os.WriteFile(gpgConfPath, []byte(gpgConfContent), 0o600); err != nil {
|
||||
t.Fatalf("Failed to write GPG config file: %v", err)
|
||||
}
|
||||
|
||||
@@ -50,15 +47,11 @@ pinentry-mode loopback
|
||||
origDecryptFunc := secret.GPGDecryptFunc
|
||||
|
||||
// Set custom GPG functions for this test
|
||||
secret.GPGEncryptFunc = func(
|
||||
data *memguard.LockedBuffer, keyID string,
|
||||
) ([]byte, error) {
|
||||
secret.GPGEncryptFunc = func(data *memguard.LockedBuffer, keyID string) ([]byte, error) {
|
||||
if data == nil {
|
||||
return nil, errNilDataBuffer
|
||||
return nil, fmt.Errorf("data buffer is nil")
|
||||
}
|
||||
|
||||
//nolint:gosec // G204: test runs gpg with test-controlled arguments
|
||||
cmd := exec.CommandContext(t.Context(), "gpg",
|
||||
cmd := exec.Command("gpg",
|
||||
"--homedir", gnupgHomeDir,
|
||||
"--batch",
|
||||
"--yes",
|
||||
@@ -70,13 +63,11 @@ pinentry-mode loopback
|
||||
"-r", keyID)
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
cmd.Stdin = bytes.NewReader(data.Bytes())
|
||||
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
if err := cmd.Run(); err != nil {
|
||||
return nil, fmt.Errorf("GPG encryption failed: %w\nStderr: %s", err, stderr.String())
|
||||
}
|
||||
|
||||
@@ -84,8 +75,7 @@ pinentry-mode loopback
|
||||
}
|
||||
|
||||
secret.GPGDecryptFunc = func(encryptedData []byte) (*memguard.LockedBuffer, error) {
|
||||
//nolint:gosec // G204: test runs gpg with test-controlled arguments
|
||||
cmd := exec.CommandContext(t.Context(), "gpg",
|
||||
cmd := exec.Command("gpg",
|
||||
"--homedir", gnupgHomeDir,
|
||||
"--batch",
|
||||
"--yes",
|
||||
@@ -95,13 +85,11 @@ pinentry-mode loopback
|
||||
"--decrypt")
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
cmd.Stdin = bytes.NewReader(encryptedData)
|
||||
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
if err := cmd.Run(); err != nil {
|
||||
return nil, fmt.Errorf("GPG decryption failed: %w\nStderr: %s", err, stderr.String())
|
||||
}
|
||||
|
||||
@@ -117,24 +105,20 @@ pinentry-mode loopback
|
||||
}
|
||||
|
||||
// runGPGWithPassphrase executes a GPG command with the specified passphrase
|
||||
func runGPGWithPassphrase(
|
||||
ctx context.Context,
|
||||
gnupgHome, passphrase string, args []string, input io.Reader,
|
||||
) ([]byte, error) {
|
||||
cmdArgs := append([]string{
|
||||
func runGPGWithPassphrase(gnupgHome, passphrase string, args []string, input io.Reader) ([]byte, error) {
|
||||
cmdArgs := []string{
|
||||
"--homedir=" + gnupgHome,
|
||||
"--batch",
|
||||
"--yes",
|
||||
"--pinentry-mode", "loopback",
|
||||
"--passphrase", passphrase,
|
||||
}, args...)
|
||||
}
|
||||
cmdArgs = append(cmdArgs, args...)
|
||||
|
||||
//nolint:gosec // G204: test runs gpg with test-controlled arguments
|
||||
cmd := exec.CommandContext(ctx, "gpg", cmdArgs...)
|
||||
cmd := exec.Command("gpg", cmdArgs...)
|
||||
cmd.Stdin = input
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
|
||||
@@ -146,96 +130,14 @@ func runGPGWithPassphrase(
|
||||
return stdout.Bytes(), nil
|
||||
}
|
||||
|
||||
// generateTestGPGKey generates a GPG key protected by passphrase in
|
||||
// gnupgHomeDir and returns its key ID and fingerprint.
|
||||
func generateTestGPGKey(
|
||||
t *testing.T, tempDir, gnupgHomeDir, passphrase string,
|
||||
) (string, string) {
|
||||
t.Helper()
|
||||
|
||||
// Create GPG batch file for key generation
|
||||
batchFile := filepath.Join(tempDir, "gen-key-batch")
|
||||
batchContent := `%echo Generating a test key
|
||||
Key-Type: RSA
|
||||
Key-Length: 2048
|
||||
Name-Real: Test User
|
||||
Name-Email: test@example.com
|
||||
Expire-Date: 0
|
||||
Passphrase: ` + passphrase + `
|
||||
%commit
|
||||
%echo Key generation completed
|
||||
`
|
||||
|
||||
err := os.WriteFile(batchFile, []byte(batchContent), 0o600)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to write batch file: %v", err)
|
||||
}
|
||||
|
||||
// Generate GPG key with batch mode
|
||||
t.Log("Generating GPG key...")
|
||||
|
||||
_, err = runGPGWithPassphrase(t.Context(), gnupgHomeDir, passphrase,
|
||||
[]string{"--gen-key", batchFile}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate GPG key: %v", err)
|
||||
}
|
||||
|
||||
t.Log("GPG key generated successfully")
|
||||
|
||||
// Get the key ID and fingerprint
|
||||
output, err := runGPGWithPassphrase(t.Context(), gnupgHomeDir, passphrase,
|
||||
[]string{"--list-secret-keys", "--with-colons", "--fingerprint"}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to list GPG keys: %v", err)
|
||||
}
|
||||
|
||||
// Parse output to get key ID and fingerprint
|
||||
var keyID, fingerprint string
|
||||
|
||||
for line := range strings.SplitSeq(string(output), "\n") {
|
||||
if strings.HasPrefix(line, "sec:") {
|
||||
fields := strings.Split(line, ":")
|
||||
if len(fields) >= 5 {
|
||||
keyID = fields[4]
|
||||
}
|
||||
} else if strings.HasPrefix(line, "fpr:") {
|
||||
fields := strings.Split(line, ":")
|
||||
if len(fields) >= 10 && fields[9] != "" {
|
||||
fingerprint = fields[9]
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if keyID == "" {
|
||||
t.Fatalf("Failed to find GPG key ID in output: %s", output)
|
||||
}
|
||||
|
||||
if fingerprint == "" {
|
||||
t.Fatalf("Failed to find GPG fingerprint in output: %s", output)
|
||||
}
|
||||
|
||||
t.Logf("Generated GPG key ID: %s", keyID)
|
||||
t.Logf("Generated GPG fingerprint: %s", fingerprint)
|
||||
|
||||
return keyID, fingerprint
|
||||
}
|
||||
|
||||
//nolint:paralleltest // t.Setenv forbids parallel subtests
|
||||
func TestPGPUnlockerWithRealFS(t *testing.T) {
|
||||
// Check if gpg is available
|
||||
_, err := exec.LookPath("gpg")
|
||||
if err != nil {
|
||||
if _, err := exec.LookPath("gpg"); err != nil {
|
||||
t.Log("GPG not available, PGP unlock key tests may not fully function")
|
||||
// Continue anyway to test what we can
|
||||
}
|
||||
|
||||
// Create a temporary directory for our tests. Not t.TempDir: its longer
|
||||
// path would put gpg-agent's socket in GNUPGHOME past the 104-byte limit
|
||||
// macOS sets on socket paths.
|
||||
//
|
||||
//nolint:usetesting // see the comment above
|
||||
// Create a temporary directory for our tests
|
||||
tempDir, err := os.MkdirTemp("", "secret-pgp-test-")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
@@ -244,9 +146,7 @@ func TestPGPUnlockerWithRealFS(t *testing.T) {
|
||||
|
||||
// Create a temporary GNUPGHOME
|
||||
gnupgHomeDir := filepath.Join(tempDir, "gnupg")
|
||||
|
||||
err = os.MkdirAll(gnupgHomeDir, 0o700)
|
||||
if err != nil {
|
||||
if err := os.MkdirAll(gnupgHomeDir, 0o700); err != nil {
|
||||
t.Fatalf("Failed to create GNUPGHOME: %v", err)
|
||||
}
|
||||
|
||||
@@ -259,7 +159,64 @@ func TestPGPUnlockerWithRealFS(t *testing.T) {
|
||||
// Setup non-interactive GPG with custom functions
|
||||
setupNonInteractiveGPG(t, tempDir, testPassphrase, gnupgHomeDir)
|
||||
|
||||
keyID, fingerprint := generateTestGPGKey(t, tempDir, gnupgHomeDir, testPassphrase)
|
||||
// Create GPG batch file for key generation
|
||||
batchFile := filepath.Join(tempDir, "gen-key-batch")
|
||||
batchContent := `%echo Generating a test key
|
||||
Key-Type: RSA
|
||||
Key-Length: 2048
|
||||
Name-Real: Test User
|
||||
Name-Email: test@example.com
|
||||
Expire-Date: 0
|
||||
Passphrase: ` + testPassphrase + `
|
||||
%commit
|
||||
%echo Key generation completed
|
||||
`
|
||||
if err := os.WriteFile(batchFile, []byte(batchContent), 0o600); err != nil {
|
||||
t.Fatalf("Failed to write batch file: %v", err)
|
||||
}
|
||||
|
||||
// Generate GPG key with batch mode
|
||||
t.Log("Generating GPG key...")
|
||||
_, err = runGPGWithPassphrase(gnupgHomeDir, testPassphrase,
|
||||
[]string{"--gen-key", batchFile}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate GPG key: %v", err)
|
||||
}
|
||||
t.Log("GPG key generated successfully")
|
||||
|
||||
// Get the key ID and fingerprint
|
||||
output, err := runGPGWithPassphrase(gnupgHomeDir, testPassphrase,
|
||||
[]string{"--list-secret-keys", "--with-colons", "--fingerprint"}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to list GPG keys: %v", err)
|
||||
}
|
||||
|
||||
// Parse output to get key ID and fingerprint
|
||||
var keyID, fingerprint string
|
||||
lines := strings.Split(string(output), "\n")
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, "sec:") {
|
||||
fields := strings.Split(line, ":")
|
||||
if len(fields) >= 5 {
|
||||
keyID = fields[4]
|
||||
}
|
||||
} else if strings.HasPrefix(line, "fpr:") {
|
||||
fields := strings.Split(line, ":")
|
||||
if len(fields) >= 10 && fields[9] != "" {
|
||||
fingerprint = fields[9]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if keyID == "" {
|
||||
t.Fatalf("Failed to find GPG key ID in output: %s", output)
|
||||
}
|
||||
if fingerprint == "" {
|
||||
t.Fatalf("Failed to find GPG fingerprint in output: %s", output)
|
||||
}
|
||||
t.Logf("Generated GPG key ID: %s", keyID)
|
||||
t.Logf("Generated GPG fingerprint: %s", fingerprint)
|
||||
|
||||
// Set the GPG_AGENT_INFO to empty to ensure gpg-agent doesn't interfere
|
||||
t.Setenv("GPG_AGENT_INFO", "")
|
||||
@@ -267,6 +224,9 @@ func TestPGPUnlockerWithRealFS(t *testing.T) {
|
||||
// Use the real filesystem
|
||||
fs := afero.NewOsFs()
|
||||
|
||||
// Test data
|
||||
testMnemonic := "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
|
||||
|
||||
// Set test environment variables
|
||||
t.Setenv(secret.EnvMnemonic, testMnemonic)
|
||||
t.Setenv(secret.EnvGPGKeyID, keyID)
|
||||
@@ -277,20 +237,162 @@ func TestPGPUnlockerWithRealFS(t *testing.T) {
|
||||
|
||||
// Test creation of a PGP unlock key through a vault
|
||||
t.Run("CreatePGPUnlocker", func(t *testing.T) {
|
||||
testCreatePGPUnlocker(t, fs, stateDir, vaultName, keyID, fingerprint)
|
||||
// Set a limited test timeout to avoid hanging
|
||||
timer := time.AfterFunc(30*time.Second, func() {
|
||||
t.Fatalf("Test timed out after 30 seconds")
|
||||
})
|
||||
defer timer.Stop()
|
||||
|
||||
// Create a test vault directory structure
|
||||
vlt, err := vault.CreateVault(fs, stateDir, vaultName)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create vault: %v", err)
|
||||
}
|
||||
|
||||
// Set the current vault
|
||||
err = vault.SelectVault(fs, stateDir, vaultName)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to select vault: %v", err)
|
||||
}
|
||||
|
||||
// Derive long-term key from mnemonic
|
||||
ltIdentity, err := agehd.DeriveIdentity(testMnemonic, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to derive long-term key: %v", err)
|
||||
}
|
||||
|
||||
// Get the vault directory
|
||||
vaultDir, err := vlt.GetDirectory()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get vault directory: %v", err)
|
||||
}
|
||||
|
||||
// Write long-term public key
|
||||
ltPubKeyPath := filepath.Join(vaultDir, "pub.age")
|
||||
if err := afero.WriteFile(fs, ltPubKeyPath, []byte(ltIdentity.Recipient().String()), secret.FilePerms); err != nil {
|
||||
t.Fatalf("Failed to write long-term public key: %v", err)
|
||||
}
|
||||
|
||||
// Unlock the vault
|
||||
vlt.Unlock(ltIdentity)
|
||||
|
||||
// Create a passphrase unlocker first (to have current unlocker)
|
||||
passphraseBuffer := memguard.NewBufferFromBytes([]byte("test-passphrase"))
|
||||
defer passphraseBuffer.Destroy()
|
||||
passUnlocker, err := vlt.CreatePassphraseUnlocker(passphraseBuffer)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create passphrase unlocker: %v", err)
|
||||
}
|
||||
|
||||
// Verify passphrase unlocker was created
|
||||
if passUnlocker == nil {
|
||||
t.Fatal("Passphrase unlocker is nil")
|
||||
}
|
||||
|
||||
// Now create a PGP unlock key (this will use our custom GPGEncryptFunc)
|
||||
pgpUnlocker, err := secret.CreatePGPUnlocker(fs, stateDir, keyID, fingerprint)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create PGP unlock key: %v", err)
|
||||
}
|
||||
|
||||
// Verify the PGP unlock key was created
|
||||
if pgpUnlocker == nil {
|
||||
t.Fatal("PGP unlock key is nil")
|
||||
}
|
||||
|
||||
// Check if the key has the correct type
|
||||
if pgpUnlocker.GetType() != "pgp" {
|
||||
t.Errorf("Expected PGP unlock key type 'pgp', got '%s'", pgpUnlocker.GetType())
|
||||
}
|
||||
|
||||
// Check if the key ID includes the GPG fingerprint
|
||||
if !strings.Contains(pgpUnlocker.GetID(), fingerprint) {
|
||||
t.Errorf("PGP unlock key ID '%s' does not contain GPG fingerprint '%s'", pgpUnlocker.GetID(), fingerprint)
|
||||
}
|
||||
|
||||
// Check if the key directory exists
|
||||
unlockerDir := pgpUnlocker.GetDirectory()
|
||||
keyExists, err := afero.DirExists(fs, unlockerDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if PGP key directory exists: %v", err)
|
||||
}
|
||||
if !keyExists {
|
||||
t.Errorf("PGP unlock key directory does not exist: %s", unlockerDir)
|
||||
}
|
||||
|
||||
// Check if required files exist
|
||||
recipientPath := filepath.Join(unlockerDir, "pub.txt")
|
||||
recipientExists, err := afero.Exists(fs, recipientPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if recipient file exists: %v", err)
|
||||
}
|
||||
if !recipientExists {
|
||||
t.Errorf("PGP unlock key recipient file does not exist: %s", recipientPath)
|
||||
}
|
||||
|
||||
privKeyPath := filepath.Join(unlockerDir, "priv.age.gpg")
|
||||
privKeyExists, err := afero.Exists(fs, privKeyPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if private key file exists: %v", err)
|
||||
}
|
||||
if !privKeyExists {
|
||||
t.Errorf("PGP unlock key private key file does not exist: %s", privKeyPath)
|
||||
}
|
||||
|
||||
metadataPath := filepath.Join(unlockerDir, "unlocker-metadata.json")
|
||||
metadataExists, err := afero.Exists(fs, metadataPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if metadata file exists: %v", err)
|
||||
}
|
||||
if !metadataExists {
|
||||
t.Errorf("PGP unlock key metadata file does not exist: %s", metadataPath)
|
||||
}
|
||||
|
||||
longtermPath := filepath.Join(unlockerDir, "longterm.age")
|
||||
longtermExists, err := afero.Exists(fs, longtermPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if longterm key file exists: %v", err)
|
||||
}
|
||||
if !longtermExists {
|
||||
t.Errorf("PGP unlock key longterm key file does not exist: %s", longtermPath)
|
||||
}
|
||||
|
||||
// Read and verify metadata
|
||||
metadataBytes, err := afero.ReadFile(fs, metadataPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read metadata: %v", err)
|
||||
}
|
||||
|
||||
var metadata struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Flags []string `json:"flags"`
|
||||
GPGKeyID string `json:"gpgKeyId"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(metadataBytes, &metadata); err != nil {
|
||||
t.Fatalf("Failed to parse metadata: %v", err)
|
||||
}
|
||||
|
||||
if metadata.Type != "pgp" {
|
||||
t.Errorf("Expected metadata type 'pgp', got '%s'", metadata.Type)
|
||||
}
|
||||
|
||||
if metadata.GPGKeyID != fingerprint {
|
||||
t.Errorf("Expected GPG fingerprint '%s', got '%s'", fingerprint, metadata.GPGKeyID)
|
||||
}
|
||||
})
|
||||
|
||||
// Set up key directory for individual tests
|
||||
unlockerDir := filepath.Join(tempDir, "unlocker")
|
||||
|
||||
err = os.MkdirAll(unlockerDir, secret.DirPerms)
|
||||
if err != nil {
|
||||
if err := os.MkdirAll(unlockerDir, secret.DirPerms); err != nil {
|
||||
t.Fatalf("Failed to create unlocker directory: %v", err)
|
||||
}
|
||||
|
||||
// Set up test metadata
|
||||
metadata := secret.UnlockerMetadata{
|
||||
Type: pgpUnlockerType,
|
||||
Type: "pgp",
|
||||
CreatedAt: time.Now(),
|
||||
Flags: []string{"gpg", "encrypted"},
|
||||
}
|
||||
@@ -300,337 +402,105 @@ func TestPGPUnlockerWithRealFS(t *testing.T) {
|
||||
|
||||
// Test getting GPG key ID
|
||||
t.Run("GetGPGKeyID", func(t *testing.T) {
|
||||
testGetGPGKeyID(t, fs, unlocker, unlockerDir, metadata, fingerprint)
|
||||
// Create PGP metadata with GPG key ID
|
||||
type PGPUnlockerMetadata struct {
|
||||
secret.UnlockerMetadata
|
||||
GPGKeyID string `json:"gpgKeyId"`
|
||||
}
|
||||
|
||||
pgpMetadata := PGPUnlockerMetadata{
|
||||
UnlockerMetadata: metadata,
|
||||
GPGKeyID: fingerprint,
|
||||
}
|
||||
|
||||
// Write metadata file
|
||||
metadataPath := filepath.Join(unlockerDir, "unlocker-metadata.json")
|
||||
metadataBytes, err := json.MarshalIndent(pgpMetadata, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal metadata: %v", err)
|
||||
}
|
||||
if err := afero.WriteFile(fs, metadataPath, metadataBytes, secret.FilePerms); err != nil {
|
||||
t.Fatalf("Failed to write metadata: %v", err)
|
||||
}
|
||||
|
||||
// Get GPG key ID
|
||||
retrievedKeyID, err := unlocker.GetGPGKeyID()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get GPG key ID: %v", err)
|
||||
}
|
||||
|
||||
// Verify key ID (should be the fingerprint)
|
||||
if retrievedKeyID != fingerprint {
|
||||
t.Errorf("Expected GPG fingerprint '%s', got '%s'", fingerprint, retrievedKeyID)
|
||||
}
|
||||
})
|
||||
|
||||
// Test getting identity from PGP unlocker
|
||||
t.Run("GetIdentity", func(t *testing.T) {
|
||||
testPGPUnlockerGetIdentity(t, fs, unlocker, unlockerDir, keyID)
|
||||
// Generate an age identity for testing
|
||||
ageIdentity, err := age.GenerateX25519Identity()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate age identity: %v", err)
|
||||
}
|
||||
|
||||
// Write the recipient
|
||||
recipientPath := filepath.Join(unlockerDir, "pub.txt")
|
||||
if err := afero.WriteFile(fs, recipientPath, []byte(ageIdentity.Recipient().String()), secret.FilePerms); err != nil {
|
||||
t.Fatalf("Failed to write recipient: %v", err)
|
||||
}
|
||||
|
||||
// GPG encrypt the private key using our custom encrypt function
|
||||
privKeyBuffer := memguard.NewBufferFromBytes([]byte(ageIdentity.String()))
|
||||
defer privKeyBuffer.Destroy()
|
||||
encryptedOutput, err := secret.GPGEncryptFunc(privKeyBuffer, keyID)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to encrypt with GPG: %v", err)
|
||||
}
|
||||
|
||||
// Write the encrypted data to a file
|
||||
encryptedPath := filepath.Join(unlockerDir, "priv.age.gpg")
|
||||
if err := afero.WriteFile(fs, encryptedPath, encryptedOutput, secret.FilePerms); err != nil {
|
||||
t.Fatalf("Failed to write encrypted private key: %v", err)
|
||||
}
|
||||
|
||||
// Now try to get the identity - this will use our custom GPGDecryptFunc
|
||||
identity, err := unlocker.GetIdentity()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get identity: %v", err)
|
||||
}
|
||||
|
||||
// Verify the identity matches
|
||||
expectedPubKey := ageIdentity.Recipient().String()
|
||||
actualPubKey := identity.Recipient().String()
|
||||
if actualPubKey != expectedPubKey {
|
||||
t.Errorf("Expected public key '%s', got '%s'", expectedPubKey, actualPubKey)
|
||||
}
|
||||
})
|
||||
|
||||
// Test removing the unlocker
|
||||
t.Run("RemoveUnlocker", func(t *testing.T) {
|
||||
testRemovePGPUnlocker(t, fs, unlocker, unlockerDir)
|
||||
// Ensure unlocker directory exists before removal
|
||||
keyExists, err := afero.DirExists(fs, unlockerDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if unlocker directory exists: %v", err)
|
||||
}
|
||||
if !keyExists {
|
||||
t.Fatalf("Unlocker directory does not exist: %s", unlockerDir)
|
||||
}
|
||||
|
||||
// Remove unlocker
|
||||
err = unlocker.Remove()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to remove unlocker: %v", err)
|
||||
}
|
||||
|
||||
// Verify directory is gone
|
||||
keyExists, err = afero.DirExists(fs, unlockerDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if unlocker directory exists: %v", err)
|
||||
}
|
||||
if keyExists {
|
||||
t.Errorf("Unlocker directory still exists after removal: %s", unlockerDir)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// testCreatePGPUnlocker creates a vault with a passphrase unlocker, then a
|
||||
// PGP unlocker for the GPG key keyID, and checks the PGP unlocker's files
|
||||
// and metadata.
|
||||
func testCreatePGPUnlocker(
|
||||
t *testing.T, fs afero.Fs, stateDir, vaultName, keyID, fingerprint string,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
// Set a limited test timeout to avoid hanging
|
||||
timer := time.AfterFunc(30*time.Second, func() {
|
||||
t.Fatalf("Test timed out after 30 seconds")
|
||||
})
|
||||
defer timer.Stop()
|
||||
|
||||
// Create a test vault directory structure
|
||||
vlt, err := vault.CreateVault(fs, stateDir, vaultName)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create vault: %v", err)
|
||||
}
|
||||
|
||||
// Set the current vault
|
||||
err = vault.SelectVault(fs, stateDir, vaultName)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to select vault: %v", err)
|
||||
}
|
||||
|
||||
// Derive long-term key from mnemonic
|
||||
ltIdentity, err := agehd.DeriveIdentity(testMnemonic, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to derive long-term key: %v", err)
|
||||
}
|
||||
|
||||
// Get the vault directory
|
||||
vaultDir, err := vlt.GetDirectory()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get vault directory: %v", err)
|
||||
}
|
||||
|
||||
// Write long-term public key
|
||||
ltPubKeyPath := filepath.Join(vaultDir, "pub.age")
|
||||
|
||||
err = afero.WriteFile(fs, ltPubKeyPath,
|
||||
[]byte(ltIdentity.Recipient().String()), secret.FilePerms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to write long-term public key: %v", err)
|
||||
}
|
||||
|
||||
// Unlock the vault
|
||||
vlt.Unlock(ltIdentity)
|
||||
|
||||
// Create a passphrase unlocker first (to have current unlocker)
|
||||
passphraseBuffer := memguard.NewBufferFromBytes([]byte("test-passphrase"))
|
||||
defer passphraseBuffer.Destroy()
|
||||
|
||||
passUnlocker, err := vlt.CreatePassphraseUnlocker(passphraseBuffer)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create passphrase unlocker: %v", err)
|
||||
}
|
||||
|
||||
// Verify passphrase unlocker was created
|
||||
if passUnlocker == nil {
|
||||
t.Fatal("Passphrase unlocker is nil")
|
||||
}
|
||||
|
||||
// Now create a PGP unlock key (this will use our custom GPGEncryptFunc)
|
||||
pgpUnlocker, err := secret.CreatePGPUnlocker(fs, stateDir, keyID, fingerprint)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create PGP unlock key: %v", err)
|
||||
}
|
||||
|
||||
// Verify the PGP unlock key was created
|
||||
if pgpUnlocker == nil {
|
||||
t.Fatal("PGP unlock key is nil")
|
||||
}
|
||||
|
||||
// Check if the key has the correct type
|
||||
if pgpUnlocker.GetType() != pgpUnlockerType {
|
||||
t.Errorf("Expected PGP unlock key type 'pgp', got '%s'", pgpUnlocker.GetType())
|
||||
}
|
||||
|
||||
// Check if the key ID includes the GPG fingerprint
|
||||
if !strings.Contains(pgpUnlocker.GetID(), fingerprint) {
|
||||
t.Errorf("PGP unlock key ID '%s' does not contain GPG fingerprint '%s'",
|
||||
pgpUnlocker.GetID(), fingerprint)
|
||||
}
|
||||
|
||||
checkPGPUnlockerFiles(t, fs, pgpUnlocker.GetDirectory())
|
||||
checkPGPUnlockerMetadata(t, fs, pgpUnlocker.GetDirectory(), fingerprint)
|
||||
}
|
||||
|
||||
// checkPGPUnlockerFiles checks that the PGP unlocker in unlockerDir has all
|
||||
// its files.
|
||||
func checkPGPUnlockerFiles(t *testing.T, fs afero.Fs, unlockerDir string) {
|
||||
t.Helper()
|
||||
|
||||
// Check if the key directory exists
|
||||
keyExists, err := afero.DirExists(fs, unlockerDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if PGP key directory exists: %v", err)
|
||||
}
|
||||
|
||||
if !keyExists {
|
||||
t.Errorf("PGP unlock key directory does not exist: %s", unlockerDir)
|
||||
}
|
||||
|
||||
// Check if required files exist
|
||||
recipientPath := filepath.Join(unlockerDir, "pub.txt")
|
||||
|
||||
recipientExists, err := afero.Exists(fs, recipientPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if recipient file exists: %v", err)
|
||||
}
|
||||
|
||||
if !recipientExists {
|
||||
t.Errorf("PGP unlock key recipient file does not exist: %s", recipientPath)
|
||||
}
|
||||
|
||||
privKeyPath := filepath.Join(unlockerDir, "priv.age.gpg")
|
||||
|
||||
privKeyExists, err := afero.Exists(fs, privKeyPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if private key file exists: %v", err)
|
||||
}
|
||||
|
||||
if !privKeyExists {
|
||||
t.Errorf("PGP unlock key private key file does not exist: %s", privKeyPath)
|
||||
}
|
||||
|
||||
metadataPath := filepath.Join(unlockerDir, unlockerMetadataFile)
|
||||
|
||||
metadataExists, err := afero.Exists(fs, metadataPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if metadata file exists: %v", err)
|
||||
}
|
||||
|
||||
if !metadataExists {
|
||||
t.Errorf("PGP unlock key metadata file does not exist: %s", metadataPath)
|
||||
}
|
||||
|
||||
longtermPath := filepath.Join(unlockerDir, "longterm.age")
|
||||
|
||||
longtermExists, err := afero.Exists(fs, longtermPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if longterm key file exists: %v", err)
|
||||
}
|
||||
|
||||
if !longtermExists {
|
||||
t.Errorf("PGP unlock key longterm key file does not exist: %s", longtermPath)
|
||||
}
|
||||
}
|
||||
|
||||
// checkPGPUnlockerMetadata checks that the metadata of the PGP unlocker in
|
||||
// unlockerDir names its type and the GPG key by fingerprint.
|
||||
func checkPGPUnlockerMetadata(
|
||||
t *testing.T, fs afero.Fs, unlockerDir, fingerprint string,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
// Read and verify metadata
|
||||
metadataPath := filepath.Join(unlockerDir, unlockerMetadataFile)
|
||||
|
||||
metadataBytes, err := afero.ReadFile(fs, metadataPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read metadata: %v", err)
|
||||
}
|
||||
|
||||
var metadata struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Flags []string `json:"flags"`
|
||||
GPGKeyID string `json:"gpgKeyId"`
|
||||
}
|
||||
|
||||
err = json.Unmarshal(metadataBytes, &metadata)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to parse metadata: %v", err)
|
||||
}
|
||||
|
||||
if metadata.Type != pgpUnlockerType {
|
||||
t.Errorf("Expected metadata type 'pgp', got '%s'", metadata.Type)
|
||||
}
|
||||
|
||||
if metadata.GPGKeyID != fingerprint {
|
||||
t.Errorf("Expected GPG fingerprint '%s', got '%s'", fingerprint, metadata.GPGKeyID)
|
||||
}
|
||||
}
|
||||
|
||||
// testGetGPGKeyID writes PGP unlocker metadata holding the GPG fingerprint
|
||||
// into unlockerDir and checks that unlocker reads it back.
|
||||
func testGetGPGKeyID(
|
||||
t *testing.T, fs afero.Fs, unlocker *secret.PGPUnlocker,
|
||||
unlockerDir string, metadata secret.UnlockerMetadata, fingerprint string,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
// Create PGP metadata with GPG key ID
|
||||
type PGPUnlockerMetadata struct {
|
||||
secret.UnlockerMetadata
|
||||
|
||||
GPGKeyID string `json:"gpgKeyId"`
|
||||
}
|
||||
|
||||
pgpMetadata := PGPUnlockerMetadata{
|
||||
UnlockerMetadata: metadata,
|
||||
GPGKeyID: fingerprint,
|
||||
}
|
||||
|
||||
// Write metadata file
|
||||
metadataPath := filepath.Join(unlockerDir, unlockerMetadataFile)
|
||||
|
||||
metadataBytes, err := json.MarshalIndent(pgpMetadata, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal metadata: %v", err)
|
||||
}
|
||||
|
||||
err = afero.WriteFile(fs, metadataPath, metadataBytes, secret.FilePerms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to write metadata: %v", err)
|
||||
}
|
||||
|
||||
// Get GPG key ID
|
||||
retrievedKeyID, err := unlocker.GetGPGKeyID()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get GPG key ID: %v", err)
|
||||
}
|
||||
|
||||
// Verify key ID (should be the fingerprint)
|
||||
if retrievedKeyID != fingerprint {
|
||||
t.Errorf("Expected GPG fingerprint '%s', got '%s'", fingerprint, retrievedKeyID)
|
||||
}
|
||||
}
|
||||
|
||||
// testPGPUnlockerGetIdentity writes an age identity encrypted to the GPG key
|
||||
// keyID into unlockerDir and checks that unlocker decrypts it.
|
||||
func testPGPUnlockerGetIdentity(
|
||||
t *testing.T, fs afero.Fs, unlocker *secret.PGPUnlocker,
|
||||
unlockerDir, keyID string,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
// Generate an age identity for testing
|
||||
ageIdentity, err := age.GenerateX25519Identity()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate age identity: %v", err)
|
||||
}
|
||||
|
||||
// Write the recipient
|
||||
recipientPath := filepath.Join(unlockerDir, "pub.txt")
|
||||
|
||||
err = afero.WriteFile(fs, recipientPath,
|
||||
[]byte(ageIdentity.Recipient().String()), secret.FilePerms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to write recipient: %v", err)
|
||||
}
|
||||
|
||||
// GPG encrypt the private key using our custom encrypt function
|
||||
privKeyBuffer := memguard.NewBufferFromBytes([]byte(ageIdentity.String()))
|
||||
defer privKeyBuffer.Destroy()
|
||||
|
||||
encryptedOutput, err := secret.GPGEncryptFunc(privKeyBuffer, keyID)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to encrypt with GPG: %v", err)
|
||||
}
|
||||
|
||||
// Write the encrypted data to a file
|
||||
encryptedPath := filepath.Join(unlockerDir, "priv.age.gpg")
|
||||
|
||||
err = afero.WriteFile(fs, encryptedPath, encryptedOutput, secret.FilePerms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to write encrypted private key: %v", err)
|
||||
}
|
||||
|
||||
// Now try to get the identity - this will use our custom GPGDecryptFunc
|
||||
identity, err := unlocker.GetIdentity()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get identity: %v", err)
|
||||
}
|
||||
|
||||
// Verify the identity matches
|
||||
expectedPubKey := ageIdentity.Recipient().String()
|
||||
actualPubKey := identity.Recipient().String()
|
||||
|
||||
if actualPubKey != expectedPubKey {
|
||||
t.Errorf("Expected public key '%s', got '%s'", expectedPubKey, actualPubKey)
|
||||
}
|
||||
}
|
||||
|
||||
// testRemovePGPUnlocker removes unlocker and checks that unlockerDir is gone.
|
||||
func testRemovePGPUnlocker(
|
||||
t *testing.T, fs afero.Fs, unlocker *secret.PGPUnlocker, unlockerDir string,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
// Ensure unlocker directory exists before removal
|
||||
keyExists, err := afero.DirExists(fs, unlockerDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if unlocker directory exists: %v", err)
|
||||
}
|
||||
|
||||
if !keyExists {
|
||||
t.Fatalf("Unlocker directory does not exist: %s", unlockerDir)
|
||||
}
|
||||
|
||||
// Remove unlocker
|
||||
err = unlocker.Remove()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to remove unlocker: %v", err)
|
||||
}
|
||||
|
||||
// Verify directory is gone
|
||||
keyExists, err = afero.DirExists(fs, unlockerDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to check if unlocker directory exists: %v", err)
|
||||
}
|
||||
|
||||
if keyExists {
|
||||
t.Errorf("Unlocker directory still exists after removal: %s", unlockerDir)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,21 +209,20 @@ func (p *PGPUnlocker) GetGPGKeyID() (string, error) {
|
||||
}
|
||||
|
||||
// generatePGPUnlockerName generates a unique name for the PGP unlocker
|
||||
// based on hostname and date
|
||||
// based on hostname and time
|
||||
func generatePGPUnlockerName() (string, error) {
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get hostname: %w", err)
|
||||
}
|
||||
|
||||
// Format: hostname-pgp-YYYY-MM-DD
|
||||
enrollmentDate := time.Now().Format("2006-01-02")
|
||||
enrollmentTime := time.Now().UTC().Format(UnlockerTimeFormat)
|
||||
|
||||
return fmt.Sprintf("%s-pgp-%s", hostname, enrollmentDate), nil
|
||||
return fmt.Sprintf("%s-pgp-%s", hostname, enrollmentTime), nil
|
||||
}
|
||||
|
||||
// pgpUnlockerDir returns the current vault and the directory in it for a
|
||||
// new PGP unlocker, named after the host and the day.
|
||||
// new PGP unlocker, named after the host and the time.
|
||||
//
|
||||
//nolint:ireturn // the vault is only available behind VaultInterface
|
||||
func pgpUnlockerDir(
|
||||
@@ -277,7 +276,7 @@ func CreatePGPUnlocker(
|
||||
// Step 2: Encrypt the long-term private key to the new keypair, and the
|
||||
// keypair's private key to the GPG key
|
||||
encryptedLtPrivKey, encryptedAgePrivKey, err := encryptPGPUnlockerKeys(
|
||||
fs, vault, ageIdentity, gpgKeyID)
|
||||
vault, ageIdentity, gpgKeyID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -316,14 +315,15 @@ func CreatePGPUnlocker(
|
||||
// to the new PGP unlocker's age keypair, and that keypair's private key
|
||||
// encrypted to the GPG key gpgKeyID.
|
||||
func encryptPGPUnlockerKeys(
|
||||
fs afero.Fs, vault VaultInterface,
|
||||
ageIdentity *age.X25519Identity, gpgKeyID string,
|
||||
vault VaultInterface, ageIdentity *age.X25519Identity, gpgKeyID string,
|
||||
) ([]byte, []byte, error) {
|
||||
// Get or derive the long-term private key
|
||||
ltPrivKeyData, err := getLongTermPrivateKey(fs, vault)
|
||||
// From the mnemonic or the current unlocker, as for a passphrase unlocker
|
||||
ltIdentity, err := vault.GetOrDeriveLongTermKey()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, fmt.Errorf("failed to get long-term key: %w", err)
|
||||
}
|
||||
|
||||
ltPrivKeyData := memguard.NewBufferFromBytes([]byte(ltIdentity.String()))
|
||||
defer ltPrivKeyData.Destroy()
|
||||
|
||||
encryptedLtPrivKey, err := EncryptToRecipient(
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"git.eeqj.de/sneak/secret/internal/secret"
|
||||
"git.eeqj.de/sneak/secret/internal/vault"
|
||||
"github.com/awnumar/memguard"
|
||||
"github.com/spf13/afero"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -40,9 +41,7 @@ func installFakeGPG(t *testing.T) {
|
||||
// TestCreatePGPUnlockerFailureWritesNothing makes CreatePGPUnlocker fail at
|
||||
// getting the vault's long-term key, which used to come after part of the
|
||||
// unlocker was written, and asserts that nothing is written. Getting the key
|
||||
// fails because on macOS there is no mnemonic and no current unlocker, and
|
||||
// on every other platform it always fails
|
||||
// (https://git.eeqj.de/sneak/secret/issues/88).
|
||||
// fails because there is no mnemonic and no current unlocker.
|
||||
func TestCreatePGPUnlockerFailureWritesNothing(t *testing.T) {
|
||||
installFakeGPG(t)
|
||||
t.Setenv(secret.EnvMnemonic, "")
|
||||
@@ -65,3 +64,38 @@ func TestCreatePGPUnlockerFailureWritesNothing(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, dirNames(t, base, filepath.Join(vaultDir, "unlockers.d")))
|
||||
}
|
||||
|
||||
// TestPGPUnlockerAddedTwiceKeepsFirst adds two PGP unlockers one right after
|
||||
// the other, so on the same host and day, and checks that the second gets a
|
||||
// directory of its own and leaves the first one's files as they were.
|
||||
// CreatePGPUnlocker does not check whether the GPG key already has an
|
||||
// unlocker, so the test key serves for both.
|
||||
func TestPGPUnlockerAddedTwiceKeepsFirst(t *testing.T) {
|
||||
installFakeGPG(t)
|
||||
t.Setenv(secret.EnvMnemonic, testMnemonic)
|
||||
|
||||
original := secret.GPGEncryptFunc
|
||||
|
||||
t.Cleanup(func() { secret.GPGEncryptFunc = original })
|
||||
|
||||
// Stands in for gpg, which the test does not have: "encrypts" by copying
|
||||
secret.GPGEncryptFunc = func(data *memguard.LockedBuffer, _ string) ([]byte, error) {
|
||||
return []byte(data.String()), nil
|
||||
}
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
_, err := vault.CreateVault(fs, testVaultStateDir, testVaultName)
|
||||
require.NoError(t, err)
|
||||
|
||||
first, err := secret.CreatePGPUnlocker(
|
||||
fs, testVaultStateDir, testGPGKeyID, testGPGFingerprint)
|
||||
require.NoError(t, err)
|
||||
|
||||
firstFiles := dirFiles(t, fs, first.GetDirectory())
|
||||
|
||||
second, err := secret.CreatePGPUnlocker(
|
||||
fs, testVaultStateDir, testGPGKeyID, testGPGFingerprint)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, first.GetDirectory(), second.GetDirectory())
|
||||
assert.Equal(t, firstFiles, dirFiles(t, fs, first.GetDirectory()))
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ type VaultInterface interface {
|
||||
GetName() string
|
||||
GetFilesystem() afero.Fs
|
||||
GetCurrentUnlocker() (Unlocker, error)
|
||||
GetOrDeriveLongTermKey() (*age.X25519Identity, error)
|
||||
CreatePassphraseUnlocker(
|
||||
passphrase *memguard.LockedBuffer) (*PassphraseUnlocker, error)
|
||||
}
|
||||
|
||||
@@ -107,6 +107,10 @@ func (m *MockVault) GetCurrentUnlocker() (Unlocker, error) {
|
||||
return nil, errNotImplementedInMock
|
||||
}
|
||||
|
||||
func (m *MockVault) GetOrDeriveLongTermKey() (*age.X25519Identity, error) {
|
||||
return nil, errNotImplementedInMock
|
||||
}
|
||||
|
||||
func (m *MockVault) CreatePassphraseUnlocker(
|
||||
_ *memguard.LockedBuffer,
|
||||
) (*PassphraseUnlocker, error) {
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
//go:build darwin
|
||||
// +build darwin
|
||||
|
||||
package secret
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"filippo.io/age"
|
||||
@@ -30,12 +29,9 @@ const (
|
||||
seLongtermFilename = "longterm.age.se"
|
||||
)
|
||||
|
||||
var errNotMacOS = errors.New("keychain unlockers are only supported on macOS")
|
||||
|
||||
// SecureEnclaveUnlockerMetadata extends UnlockerMetadata with SE-specific data.
|
||||
type SecureEnclaveUnlockerMetadata struct {
|
||||
UnlockerMetadata
|
||||
|
||||
SEKeyLabel string `json:"seKeyLabel"`
|
||||
SEKeyHash string `json:"seKeyHash"`
|
||||
}
|
||||
@@ -47,19 +43,6 @@ type SecureEnclaveUnlocker struct {
|
||||
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) {
|
||||
@@ -75,7 +58,6 @@ func (s *SecureEnclaveUnlocker) GetIdentity() (*age.X25519Identity, error) {
|
||||
|
||||
// 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(
|
||||
@@ -158,9 +140,7 @@ func (s *SecureEnclaveUnlocker) Remove() error {
|
||||
|
||||
if seKeyHash != "" {
|
||||
Debug("Deleting SE key", "hash", seKeyHash)
|
||||
|
||||
err = macse.DeleteKey(seKeyHash)
|
||||
if err != nil {
|
||||
if err := macse.DeleteKey(seKeyHash); err != nil {
|
||||
Debug("Failed to delete SE key", "error", err, "hash", seKeyHash)
|
||||
|
||||
return fmt.Errorf("failed to delete SE key: %w", err)
|
||||
@@ -168,9 +148,7 @@ func (s *SecureEnclaveUnlocker) Remove() error {
|
||||
}
|
||||
|
||||
Debug("Removing SE unlocker directory", "directory", s.Directory)
|
||||
|
||||
err = RemoveDirAtomic(s.fs, s.Directory)
|
||||
if err != nil {
|
||||
if err := RemoveDirAtomic(s.fs, s.Directory); err != nil {
|
||||
return fmt.Errorf("failed to remove SE unlocker directory: %w", err)
|
||||
}
|
||||
|
||||
@@ -180,24 +158,34 @@ func (s *SecureEnclaveUnlocker) Remove() error {
|
||||
}
|
||||
|
||||
// getSEKeyInfo reads the SE key label and hash from metadata.
|
||||
func (s *SecureEnclaveUnlocker) getSEKeyInfo() (string, string, error) {
|
||||
func (s *SecureEnclaveUnlocker) getSEKeyInfo() (label string, hash string, err 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 {
|
||||
if err := json.Unmarshal(metadataData, &seMetadata); err != nil {
|
||||
return "", "", fmt.Errorf("failed to parse SE metadata: %w", err)
|
||||
}
|
||||
|
||||
return seMetadata.SEKeyLabel, seMetadata.SEKeyHash, nil
|
||||
}
|
||||
|
||||
// NewSecureEnclaveUnlocker creates a new SecureEnclaveUnlocker instance.
|
||||
func NewSecureEnclaveUnlocker(
|
||||
fs afero.Fs,
|
||||
directory string,
|
||||
metadata UnlockerMetadata,
|
||||
) *SecureEnclaveUnlocker {
|
||||
return &SecureEnclaveUnlocker{
|
||||
Directory: directory,
|
||||
Metadata: metadata,
|
||||
fs: fs,
|
||||
}
|
||||
}
|
||||
|
||||
// generateSEKeyLabel generates a unique label for the SE CTK identity.
|
||||
func generateSEKeyLabel(vaultName string) (string, error) {
|
||||
hostname, err := os.Hostname()
|
||||
@@ -205,27 +193,17 @@ func generateSEKeyLabel(vaultName string) (string, error) {
|
||||
return "", fmt.Errorf("failed to get hostname: %w", err)
|
||||
}
|
||||
|
||||
enrollmentDate := time.Now().UTC().Format("2006-01-02")
|
||||
enrollmentTime := time.Now().UTC().Format(UnlockerTimeFormat)
|
||||
|
||||
return fmt.Sprintf(
|
||||
"%s.%s-%s-%s",
|
||||
seKeyLabelPrefix,
|
||||
vaultName,
|
||||
hostname,
|
||||
enrollmentDate,
|
||||
enrollmentTime,
|
||||
), nil
|
||||
}
|
||||
|
||||
// checkMacOSAvailable verifies that we're running on macOS. The keychain
|
||||
// unlocker uses it too.
|
||||
func checkMacOSAvailable() error {
|
||||
if runtime.GOOS != "darwin" {
|
||||
return fmt.Errorf("%w, current OS: %s", errNotMacOS, runtime.GOOS)
|
||||
}
|
||||
|
||||
return 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.
|
||||
@@ -233,8 +211,7 @@ func CreateSecureEnclaveUnlocker(
|
||||
fs afero.Fs,
|
||||
stateDir string,
|
||||
) (*SecureEnclaveUnlocker, error) {
|
||||
err := checkMacOSAvailable()
|
||||
if err != nil {
|
||||
if err := checkMacOSAvailable(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -251,7 +228,6 @@ func CreateSecureEnclaveUnlocker(
|
||||
|
||||
// Step 1: 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)
|
||||
@@ -284,7 +260,7 @@ func CreateSecureEnclaveUnlocker(
|
||||
return nil, fmt.Errorf("failed to get vault directory: %w", err)
|
||||
}
|
||||
|
||||
unlockerDirName := "se-" + filepath.Base(seKeyLabel)
|
||||
unlockerDirName := fmt.Sprintf("se-%s", filepath.Base(seKeyLabel))
|
||||
unlockerDir := filepath.Join(vaultDir, "unlockers.d", unlockerDirName)
|
||||
|
||||
seMetadata := SecureEnclaveUnlockerMetadata{
|
||||
@@ -304,7 +280,20 @@ func CreateSecureEnclaveUnlocker(
|
||||
|
||||
// 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)
|
||||
ltKeyPath := filepath.Join(dir, seLongtermFilename)
|
||||
if err := WriteFileAtomic(fs, ltKeyPath, encryptedLtKey); err != nil {
|
||||
return fmt.Errorf(
|
||||
"failed to write SE-encrypted long-term key: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
metadataPath := filepath.Join(dir, "unlocker-metadata.json")
|
||||
if err := WriteFileAtomic(fs, metadataPath, metadataBytes); err != nil {
|
||||
return fmt.Errorf("failed to write metadata: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -317,29 +306,6 @@ func CreateSecureEnclaveUnlocker(
|
||||
}, 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
|
||||
// either from the mnemonic env var or by unlocking via the current unlocker.
|
||||
func getLongTermKeyForSE(
|
||||
@@ -355,16 +321,13 @@ func getLongTermKeyForSE(
|
||||
}
|
||||
|
||||
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 {
|
||||
if err := json.Unmarshal(metadataBytes, &metadata); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse vault metadata: %w", err)
|
||||
}
|
||||
|
||||
@@ -373,6 +336,7 @@ func getLongTermKeyForSE(
|
||||
envMnemonic,
|
||||
metadata.DerivationIndex,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"failed to derive long-term key from mnemonic: %w",
|
||||
@@ -401,7 +365,6 @@ func getLongTermKeyForSE(
|
||||
currentUnlocker.GetDirectory(),
|
||||
"longterm.age",
|
||||
)
|
||||
|
||||
encryptedLtKey, err := afero.ReadFile(fs, longtermPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//go:build darwin
|
||||
// +build darwin
|
||||
|
||||
//nolint:testpackage // white-box test of unexported Secure Enclave helpers
|
||||
package secret
|
||||
|
||||
import (
|
||||
@@ -13,14 +13,12 @@ import (
|
||||
)
|
||||
|
||||
func TestNewSecureEnclaveUnlocker(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
dir := "/tmp/test-se-unlocker"
|
||||
metadata := UnlockerMetadata{
|
||||
Type: seUnlockerType,
|
||||
Type: "secure-enclave",
|
||||
CreatedAt: time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC),
|
||||
Flags: []string{seUnlockerType, "macos"},
|
||||
Flags: []string{"secure-enclave", "macos"},
|
||||
}
|
||||
|
||||
unlocker := NewSecureEnclaveUnlocker(fs, dir, metadata)
|
||||
@@ -37,11 +35,9 @@ func TestNewSecureEnclaveUnlocker(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSecureEnclaveUnlockerImplementsInterface(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
metadata := UnlockerMetadata{
|
||||
Type: seUnlockerType,
|
||||
Type: "secure-enclave",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
@@ -52,11 +48,9 @@ func TestSecureEnclaveUnlockerImplementsInterface(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSecureEnclaveUnlockerGetIDFormat(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
metadata := UnlockerMetadata{
|
||||
Type: seUnlockerType,
|
||||
Type: "secure-enclave",
|
||||
CreatedAt: time.Date(2026, 3, 10, 14, 30, 0, 0, time.UTC),
|
||||
}
|
||||
|
||||
@@ -69,8 +63,6 @@ func TestSecureEnclaveUnlockerGetIDFormat(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGenerateSEKeyLabel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
label, err := generateSEKeyLabel("test-vault")
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -80,8 +72,6 @@ func TestGenerateSEKeyLabel(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSecureEnclaveUnlockerGetIdentityMissingFile(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
dir := "/tmp/test-se-unlocker-missing"
|
||||
|
||||
@@ -94,12 +84,10 @@ func TestSecureEnclaveUnlockerGetIdentityMissingFile(t *testing.T) {
|
||||
"seKeyLabel": "berlin.sneak.app.secret.se.test",
|
||||
"seKeyHash": "abc123"
|
||||
}`
|
||||
require.NoError(t, afero.WriteFile(
|
||||
fs, dir+"/unlocker-metadata.json", []byte(metadataJSON), FilePerms,
|
||||
))
|
||||
require.NoError(t, afero.WriteFile(fs, dir+"/unlocker-metadata.json", []byte(metadataJSON), FilePerms))
|
||||
|
||||
metadata := UnlockerMetadata{
|
||||
Type: seUnlockerType,
|
||||
Type: "secure-enclave",
|
||||
CreatedAt: time.Date(2026, 1, 15, 10, 30, 0, 0, time.UTC),
|
||||
}
|
||||
|
||||
@@ -108,6 +96,6 @@ func TestSecureEnclaveUnlockerGetIdentityMissingFile(t *testing.T) {
|
||||
// GetIdentity should fail because the encrypted longterm key file is missing
|
||||
identity, err := unlocker.GetIdentity()
|
||||
assert.Nil(t, identity)
|
||||
require.Error(t, err)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "failed to read SE-encrypted long-term key")
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build darwin && cgo
|
||||
//go:build darwin
|
||||
|
||||
package secret
|
||||
|
||||
|
||||
@@ -87,6 +87,10 @@ func (m *MockVersionVault) GetCurrentUnlocker() (secret.Unlocker, error) {
|
||||
return nil, errNotImplementedInMock
|
||||
}
|
||||
|
||||
func (m *MockVersionVault) GetOrDeriveLongTermKey() (*age.X25519Identity, error) {
|
||||
return nil, errNotImplementedInMock
|
||||
}
|
||||
|
||||
func (m *MockVersionVault) CreatePassphraseUnlocker(
|
||||
_ *memguard.LockedBuffer,
|
||||
) (*secret.PassphraseUnlocker, error) {
|
||||
|
||||
+63
-10
@@ -2,8 +2,10 @@ package vault
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -101,7 +103,7 @@ func (v *Vault) GetCurrentUnlocker() (secret.Unlocker, error) {
|
||||
|
||||
// resolveUnlockerDirectory reads the current-unlocker file to get the
|
||||
// unlocker directory path
|
||||
// The file contains just the unlocker name (e.g., "passphrase")
|
||||
// The file contains just the name of the unlocker's directory in unlockers.d
|
||||
func (v *Vault) resolveUnlockerDirectory(currentUnlockerPath string) (string, error) {
|
||||
secret.Debug("Reading current-unlocker file", "path", currentUnlockerPath)
|
||||
|
||||
@@ -339,7 +341,10 @@ func (v *Vault) SelectUnlocker(unlockerID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreatePassphraseUnlocker creates a new passphrase-protected unlocker
|
||||
// CreatePassphraseUnlocker creates a new passphrase-protected unlocker in a
|
||||
// directory of its own, makes it the current unlocker, and only then removes
|
||||
// the vault's other passphrase unlockers: a vault keeps one. A crash at any
|
||||
// point leaves a complete current unlocker, the old one or the new.
|
||||
// The passphrase must be provided as a LockedBuffer for security
|
||||
func (v *Vault) CreatePassphraseUnlocker(
|
||||
passphrase *memguard.LockedBuffer,
|
||||
@@ -351,13 +356,23 @@ func (v *Vault) CreatePassphraseUnlocker(
|
||||
|
||||
// We need to get the long-term key (either from memory if unlocked, or
|
||||
// derive it). Getting it before anything is written means failing to
|
||||
// get it changes nothing, even when replacing the current unlocker.
|
||||
// get it changes nothing.
|
||||
ltIdentity, err := v.GetOrDeriveLongTermKey()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get long-term key: %w", err)
|
||||
}
|
||||
|
||||
unlockerDir := filepath.Join(vaultDir, "unlockers.d", unlockerTypePassphrase)
|
||||
unlockersDir := filepath.Join(vaultDir, "unlockers.d")
|
||||
|
||||
// The passphrase unlockers the new one replaces
|
||||
oldDirs, err := v.passphraseUnlockerDirs(unlockersDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
createdAt := time.Now()
|
||||
unlockerDir := filepath.Join(unlockersDir, unlockerTypePassphrase+"-"+
|
||||
createdAt.UTC().Format(secret.UnlockerTimeFormat))
|
||||
|
||||
// Generate new age keypair for unlocker
|
||||
unlockerIdentity, err := age.GenerateX25519Identity()
|
||||
@@ -377,7 +392,7 @@ func (v *Vault) CreatePassphraseUnlocker(
|
||||
|
||||
metadata := UnlockerMetadata{
|
||||
Type: unlockerTypePassphrase,
|
||||
CreatedAt: time.Now(),
|
||||
CreatedAt: createdAt,
|
||||
Flags: []string{},
|
||||
}
|
||||
|
||||
@@ -395,16 +410,54 @@ func (v *Vault) CreatePassphraseUnlocker(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create the unlocker instance
|
||||
unlocker := secret.NewPassphraseUnlocker(v.fs, unlockerDir, metadata)
|
||||
// Select the new unlocker by its directory, not by its ID: an old
|
||||
// passphrase unlocker created in the same minute has the same ID.
|
||||
currentUnlockerPath := filepath.Join(vaultDir, "current-unlocker")
|
||||
|
||||
// Select this unlocker as current
|
||||
err = v.SelectUnlocker(unlocker.GetID())
|
||||
err = secret.WriteFileAtomic(v.fs, currentUnlockerPath,
|
||||
[]byte(filepath.Base(unlockerDir)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to select new unlocker: %w", err)
|
||||
}
|
||||
|
||||
return unlocker, nil
|
||||
for _, oldDir := range oldDirs {
|
||||
err = secret.RemoveDirAtomic(v.fs, oldDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"created and selected the new passphrase unlocker: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return secret.NewPassphraseUnlocker(v.fs, unlockerDir, metadata), nil
|
||||
}
|
||||
|
||||
// passphraseUnlockerDirs returns the directories in unlockersDir that hold
|
||||
// passphrase unlockers. A directory ListUnlockers skips is left out, with the
|
||||
// same warning.
|
||||
func (v *Vault) passphraseUnlockerDirs(unlockersDir string) ([]string, error) {
|
||||
files, err := afero.ReadDir(v.fs, unlockersDir)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read unlockers directory: %w", err)
|
||||
}
|
||||
|
||||
var dirs []string
|
||||
|
||||
for _, file := range files {
|
||||
if !file.IsDir() {
|
||||
continue
|
||||
}
|
||||
|
||||
metadata, ok := v.readUnlockerMetadataOrWarn(unlockersDir, file.Name())
|
||||
if ok && metadata.Type == unlockerTypePassphrase {
|
||||
dirs = append(dirs, filepath.Join(unlockersDir, file.Name()))
|
||||
}
|
||||
}
|
||||
|
||||
return dirs, nil
|
||||
}
|
||||
|
||||
// readUnlockerMetadata reads and parses the unlocker-metadata.json file in
|
||||
|
||||
+3
-3
@@ -1,6 +1,7 @@
|
||||
#!/bin/sh
|
||||
# script/check: run all checks (test, lint, lint-darwin, fmt-check). Our
|
||||
# own extension to scripts-to-rule-them-all. Must not modify any files.
|
||||
# script/check: run all checks (test, lint, fmt-check). Our own
|
||||
# extension to scripts-to-rule-them-all. Must not modify any files.
|
||||
# Generic: usually needs no adaptation.
|
||||
set -eu
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||
@@ -8,7 +9,6 @@ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||
main() {
|
||||
"$SCRIPT_DIR/test"
|
||||
"$SCRIPT_DIR/lint"
|
||||
"$SCRIPT_DIR/lint-darwin"
|
||||
"$SCRIPT_DIR/fmt-check"
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +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
|
||||
# (keychainunlocker.go and its tests) 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 "$@"
|
||||
Reference in New Issue
Block a user