Compare commits
2
Commits
4737f97e52
...
4a6e30f9bf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a6e30f9bf | ||
|
|
2adc588ace |
No files matched your search
@@ -18,6 +18,31 @@ https://git.eeqj.de/sneak/secret/milestone/12
|
||||
|
||||
# Completed Steps
|
||||
|
||||
- 2026-10-04: Tests check which error a failure returns with `errors.Is`,
|
||||
not by matching words of its message
|
||||
(https://git.eeqj.de/sneak/secret/issues/49). Every exported error that
|
||||
can be returned has a test that the function returns it, and errors
|
||||
wrapping a cause are checked through the wrapping. Checks that still match
|
||||
text, because the error has no exported value the test can name, are
|
||||
listed on the issue.
|
||||
- 2026-10-04: When a vault cannot be opened through its current unlocker,
|
||||
because a file the unlocker needs is missing or damaged, its keychain item
|
||||
or Secure Enclave key is gone, or the passphrase is wrong, the error now
|
||||
ends by naming the vault, saying that it still opens with its mnemonic,
|
||||
and that `secret unlocker add passphrase`, run with `SB_SECRET_MNEMONIC`
|
||||
set to it, gives the vault a new unlocker; for a vault that is not the
|
||||
current one, as in `secret move` between vaults, it says to run
|
||||
`secret vault select` first (https://git.eeqj.de/sneak/secret/issues/47).
|
||||
Before, it ended with the bare cause. The advice is given only when the
|
||||
vault metadata records the key the mnemonic derives, so not for a vault
|
||||
created without a mnemonic, and not when the passphrase could not be read
|
||||
at all. `secret vault import` is not named: it refuses a vault that has a
|
||||
long-term key. `secret encrypt` and `secret decrypt` now read the key
|
||||
secret through `vault.GetSecret`, as `secret get` does, so they give the
|
||||
same advice; `Secret.GetValue`, the other way to get the long-term key, is
|
||||
removed. When a secret's `current` file cannot be read, the error says
|
||||
that `secret version list` lists its versions and `secret version promote`
|
||||
makes one current. The causes stay wrapped.
|
||||
- 2026-10-04: An unlocker's ID is the name of its directory in `unlockers.d`,
|
||||
so no two unlockers of a vault share one
|
||||
(https://git.eeqj.de/sneak/secret/issues/98). Before, a keychain or Secure
|
||||
@@ -406,8 +431,6 @@ https://git.eeqj.de/sneak/secret/milestone/12
|
||||
(`secret.IdentityToLockedBuffer` overwrites only the string itself).
|
||||
- Medium priority:
|
||||
- Standardize error messages; stop leaking internals.
|
||||
- Graceful handling of corrupted or missing key files with recovery
|
||||
suggestions.
|
||||
- Split oversized CLI functions.
|
||||
- Cleanups: read statedir from environment or default instead of
|
||||
passing it around.
|
||||
|
||||
@@ -66,22 +66,18 @@ func TestCreateExistingVaultChangesNothing(t *testing.T) {
|
||||
|
||||
tests := []struct {
|
||||
command string
|
||||
want string
|
||||
run func(c *cli.Instance) error
|
||||
}{
|
||||
{
|
||||
"init",
|
||||
"failed to create default vault: vault default already exists",
|
||||
func(c *cli.Instance) error { return c.Init(cmd) },
|
||||
},
|
||||
{
|
||||
"vault create default",
|
||||
"vault default already exists",
|
||||
func(c *cli.Instance) error { return c.CreateVault(cmd, "default") },
|
||||
},
|
||||
{
|
||||
"vault create work",
|
||||
"vault work already exists",
|
||||
func(c *cli.Instance) error { return c.CreateVault(cmd, "work") },
|
||||
},
|
||||
}
|
||||
@@ -92,7 +88,7 @@ func TestCreateExistingVaultChangesNothing(t *testing.T) {
|
||||
|
||||
err := tt.run(newCLI(fs))
|
||||
|
||||
require.EqualError(t, err, tt.want)
|
||||
require.ErrorIs(t, err, vault.ErrVaultExists)
|
||||
require.Equal(t, before, snapshotStateDir(t, fs))
|
||||
})
|
||||
}
|
||||
@@ -227,9 +223,7 @@ func TestStopDuringCreateLeavesWholeVaultOrNone(t *testing.T) {
|
||||
fs := afero.NewMemMapFs()
|
||||
require.NoError(t, fs.MkdirAll(testStateDir, secret.DirPerms))
|
||||
|
||||
requireStopsLeaveWholeVaultOrNone(t, fs, "default",
|
||||
"failed to create default vault: vault default already exists",
|
||||
mnemonic, passphrase,
|
||||
requireStopsLeaveWholeVaultOrNone(t, fs, "default", mnemonic, passphrase,
|
||||
func(c *cli.Instance) error { return c.Init(cmd) })
|
||||
})
|
||||
|
||||
@@ -239,8 +233,7 @@ func TestStopDuringCreateLeavesWholeVaultOrNone(t *testing.T) {
|
||||
_, err := vault.CreateVault(fs, testStateDir, "default", mnemonic, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
requireStopsLeaveWholeVaultOrNone(t, fs, "work", "vault work already exists",
|
||||
mnemonic, passphrase,
|
||||
requireStopsLeaveWholeVaultOrNone(t, fs, "work", mnemonic, passphrase,
|
||||
func(c *cli.Instance) error { return c.CreateVault(cmd, "work") })
|
||||
})
|
||||
}
|
||||
@@ -248,9 +241,10 @@ func TestStopDuringCreateLeavesWholeVaultOrNone(t *testing.T) {
|
||||
// requireStopsLeaveWholeVaultOrNone checks, as
|
||||
// TestStopDuringCreateLeavesWholeVaultOrNone describes, the stops of the
|
||||
// command run, creating the vault name on fs with mnemonic and passphrase.
|
||||
// Run again where the vault is there, the command must fail with exists.
|
||||
// Run again where the vault is there, the command must fail with
|
||||
// vault.ErrVaultExists.
|
||||
func requireStopsLeaveWholeVaultOrNone(
|
||||
t *testing.T, fs afero.Fs, name, exists string,
|
||||
t *testing.T, fs afero.Fs, name string,
|
||||
mnemonic, passphrase *memguard.LockedBuffer,
|
||||
run func(c *cli.Instance) error,
|
||||
) {
|
||||
@@ -312,7 +306,7 @@ func requireStopsLeaveWholeVaultOrNone(
|
||||
c.UnlockPassphrase = passphrase
|
||||
|
||||
if _, there := state[vaultDir+"/"]; there {
|
||||
require.EqualError(t, run(c), exists)
|
||||
require.ErrorIs(t, run(c), vault.ErrVaultExists)
|
||||
} else {
|
||||
require.NoError(t, run(c))
|
||||
}
|
||||
|
||||
+2
-19
@@ -130,7 +130,7 @@ func (cli *Instance) resolveEncryptionKey(
|
||||
}
|
||||
|
||||
// Secret exists, get the age secret key from it
|
||||
secretBuffer, err := cli.getSecretValue(vlt, secretObj)
|
||||
secretBuffer, err := vlt.GetSecret(secretName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get secret value: %w", err)
|
||||
}
|
||||
@@ -249,7 +249,7 @@ func (cli *Instance) Decrypt(secretName, inputFile, outputFile string) error {
|
||||
}
|
||||
|
||||
// Get the age secret key from the secret
|
||||
secretBuffer, err := cli.getSecretValue(vlt, secretObj)
|
||||
secretBuffer, err := vlt.GetSecret(secretName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get secret value: %w", err)
|
||||
}
|
||||
@@ -313,20 +313,3 @@ func isValidAgeSecretKey(key string) bool {
|
||||
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// getSecretValue retrieves the value of a secret with the vault's mnemonic
|
||||
// when it has one, else with the current unlocker
|
||||
func (cli *Instance) getSecretValue(
|
||||
vlt *vault.Vault, secretObj *secret.Secret,
|
||||
) (*memguard.LockedBuffer, error) {
|
||||
if vlt.Mnemonic != nil {
|
||||
return secretObj.GetValue(nil, vlt.Mnemonic)
|
||||
}
|
||||
|
||||
unlocker, err := vlt.GetCurrentUnlocker()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get current unlocker: %w", err)
|
||||
}
|
||||
|
||||
return secretObj.GetValue(unlocker, nil)
|
||||
}
|
||||
@@ -680,10 +680,10 @@ func test06GetSecret(t *testing.T, testMnemonic string, runSecret func(...string
|
||||
require.NoError(t, err, "get secret should succeed")
|
||||
assert.Equal(t, "password123", strings.TrimSpace(output), "should return correct secret value")
|
||||
|
||||
// Test that without mnemonic, we get an error
|
||||
output, err = runSecret("get", "database/password")
|
||||
require.Error(t, err, "get should fail without unlock method")
|
||||
assert.Contains(t, output, "failed to unlock vault", "should indicate unlock failure")
|
||||
// Test that without mnemonic, we get an error: the passphrase unlocker
|
||||
// cannot ask for its passphrase, as the tests have no terminal
|
||||
_, err = runSecret("get", "database/password")
|
||||
require.ErrorIs(t, err, secret.ErrPassphraseNotRead, "get should fail without unlock method")
|
||||
}
|
||||
|
||||
func test07AddSecretVersion(t *testing.T, tempDir, testMnemonic string, runSecret func(...string) (string, error), runSecretWithEnv func(map[string]string, ...string) (string, error), runSecretWithStdin func(string, map[string]string, ...string) (string, error)) {
|
||||
@@ -839,12 +839,11 @@ func test09GetSpecificVersion(t *testing.T, tempDir, testMnemonic string, runSec
|
||||
assert.Equal(t, "newpassword456", strings.TrimSpace(output), "should return new secret value without --version")
|
||||
|
||||
// An empty --version is not a version; it does not mean the current one
|
||||
output, err = runSecretWithEnv(map[string]string{
|
||||
_, err = runSecretWithEnv(map[string]string{
|
||||
secret.EnvMnemonic: testMnemonic,
|
||||
}, "get", "--version", "", "database/password")
|
||||
|
||||
require.Error(t, err, "get with an empty version should fail")
|
||||
assert.Contains(t, output, "version '' not found", "should reject the empty version")
|
||||
require.ErrorIs(t, err, vault.ErrVersionNotFound, "should reject the empty version")
|
||||
}
|
||||
|
||||
func test10PromoteVersion(t *testing.T, tempDir, testMnemonic string, runSecret func(...string) (string, error), runSecretWithEnv func(map[string]string, ...string) (string, error)) {
|
||||
@@ -1158,11 +1157,7 @@ func testInvalidSecretNames(t *testing.T, testMnemonic string, runSecretWithStdi
|
||||
shouldFail := slices.Contains(definitelyInvalid, invalidName)
|
||||
|
||||
if shouldFail {
|
||||
require.Error(t, err, "add '%s' should fail", invalidName)
|
||||
|
||||
if err != nil {
|
||||
assert.Contains(t, output, "invalid secret name", "should indicate invalid name for '%s'", invalidName)
|
||||
}
|
||||
require.ErrorIs(t, err, vault.ErrInvalidSecretName, "add '%s' should fail", invalidName)
|
||||
} else {
|
||||
// For the slash cases and .hidden, they might succeed
|
||||
// Just log what happened
|
||||
@@ -1310,9 +1305,8 @@ func test12cCrossVaultMove(t *testing.T, testMnemonic string, runSecretWithEnv f
|
||||
require.NoError(t, err, "add force/test in work should succeed")
|
||||
|
||||
// Move without force should fail
|
||||
output, err = runSecretWithEnv(env, "move", "work:force/test", "default")
|
||||
require.Error(t, err, "move without force should fail when dest exists")
|
||||
assert.Contains(t, output, "already exists", "should indicate destination exists")
|
||||
_, err = runSecretWithEnv(env, "move", "work:force/test", "default")
|
||||
require.ErrorIs(t, err, vault.ErrSecretExists, "move without force should fail when dest exists")
|
||||
|
||||
// Move with force should succeed
|
||||
output, err = runSecretWithEnv(env, "move", "--force", "work:force/test", "default")
|
||||
@@ -1427,9 +1421,8 @@ func test14SwitchVault(t *testing.T, tempDir string, runSecret func(...string) (
|
||||
require.NoError(t, err, "vault select default should succeed")
|
||||
|
||||
// Test selecting non-existent vault
|
||||
output, err := runSecret("vault", "select", "nonexistent")
|
||||
require.Error(t, err, "selecting non-existent vault should fail")
|
||||
assert.Contains(t, output, "does not exist", "should indicate vault doesn't exist")
|
||||
_, err = runSecret("vault", "select", "nonexistent")
|
||||
require.ErrorIs(t, err, vault.ErrVaultNotFound, "selecting non-existent vault should fail")
|
||||
}
|
||||
|
||||
func test15VaultIsolation(t *testing.T, testMnemonic string, runSecret func(...string) (string, error), runSecretWithEnv func(map[string]string, ...string) (string, error), runSecretWithStdin func(string, map[string]string, ...string) (string, error)) {
|
||||
@@ -1450,11 +1443,10 @@ func test15VaultIsolation(t *testing.T, testMnemonic string, runSecret func(...s
|
||||
require.NoError(t, err, "vault select work should succeed")
|
||||
|
||||
// Try to get the default-only secret (should fail)
|
||||
output, err := runSecretWithEnv(map[string]string{
|
||||
_, err = runSecretWithEnv(map[string]string{
|
||||
secret.EnvMnemonic: testMnemonic,
|
||||
}, "get", "default-only/secret")
|
||||
require.Error(t, err, "should not be able to get default vault secret from work vault")
|
||||
assert.Contains(t, output, "not found", "should indicate secret not found")
|
||||
require.ErrorIs(t, err, vault.ErrSecretNotFound, "should not be able to get default vault secret from work vault")
|
||||
|
||||
// Add a unique secret to work vault
|
||||
_, err = runSecretWithStdin("work-vault-secret", map[string]string{
|
||||
@@ -1467,14 +1459,13 @@ func test15VaultIsolation(t *testing.T, testMnemonic string, runSecret func(...s
|
||||
require.NoError(t, err, "vault select default should succeed")
|
||||
|
||||
// Try to get the work-only secret (should fail)
|
||||
output, err = runSecretWithEnv(map[string]string{
|
||||
_, err = runSecretWithEnv(map[string]string{
|
||||
secret.EnvMnemonic: testMnemonic,
|
||||
}, "get", "work-only/secret")
|
||||
require.Error(t, err, "should not be able to get work vault secret from default vault")
|
||||
assert.Contains(t, output, "not found", "should indicate secret not found")
|
||||
require.ErrorIs(t, err, vault.ErrSecretNotFound, "should not be able to get work vault secret from default vault")
|
||||
|
||||
// Verify we can still get the default-only secret
|
||||
output, err = runSecretWithEnv(map[string]string{
|
||||
output, err := runSecretWithEnv(map[string]string{
|
||||
secret.EnvMnemonic: testMnemonic,
|
||||
}, "get", "default-only/secret")
|
||||
require.NoError(t, err, "get default-only secret should succeed")
|
||||
@@ -1586,11 +1577,10 @@ func test17ImportFromFile(t *testing.T, tempDir, testMnemonic string, runSecretW
|
||||
// Just verify the import succeeded
|
||||
|
||||
// Test importing non-existent file
|
||||
output, err = runSecretWithEnv(map[string]string{
|
||||
_, err = runSecretWithEnv(map[string]string{
|
||||
secret.EnvMnemonic: testMnemonic,
|
||||
}, "import", "imported/nonexistent", "--source", "/nonexistent/file")
|
||||
require.Error(t, err, "importing non-existent file should fail")
|
||||
assert.Contains(t, output, "failed", "should indicate failure")
|
||||
require.ErrorIs(t, err, os.ErrNotExist, "importing non-existent file should fail")
|
||||
|
||||
// Verify filesystem structure
|
||||
defaultVaultDir := filepath.Join(tempDir, "vaults.d", "default")
|
||||
@@ -1905,11 +1895,10 @@ func test23ErrorHandling(t *testing.T, tempDir, secretPath, testMnemonic string,
|
||||
t.Helper()
|
||||
|
||||
// Get non-existent secret
|
||||
output, err := runSecretWithEnv(map[string]string{
|
||||
_, err := runSecretWithEnv(map[string]string{
|
||||
secret.EnvMnemonic: testMnemonic,
|
||||
}, "get", "nonexistent/secret")
|
||||
require.Error(t, err, "get non-existent secret should fail")
|
||||
assert.Contains(t, output, "not found", "should indicate secret not found")
|
||||
require.ErrorIs(t, err, vault.ErrSecretNotFound, "get non-existent secret should fail")
|
||||
|
||||
// Add secret without mnemonic or unlocker
|
||||
unsetMnemonic := os.Getenv(secret.EnvMnemonic)
|
||||
@@ -1939,13 +1928,12 @@ func test23ErrorHandling(t *testing.T, tempDir, secretPath, testMnemonic string,
|
||||
// Invalid secret names (already tested in test 12)
|
||||
|
||||
// Non-existent vault operations
|
||||
output, err = runSecret("vault", "select", "nonexistent")
|
||||
require.Error(t, err, "select non-existent vault should fail")
|
||||
assert.Contains(t, output, "does not exist", "should indicate vault doesn't exist")
|
||||
_, err = runSecret("vault", "select", "nonexistent")
|
||||
require.ErrorIs(t, err, vault.ErrVaultNotFound, "select non-existent vault should fail")
|
||||
|
||||
// Import to non-existent vault with test passphrase
|
||||
testPassphrase := "test-passphrase-123" // Define testPassphrase locally
|
||||
output, err = runSecretWithEnv(map[string]string{
|
||||
output, err := runSecretWithEnv(map[string]string{
|
||||
secret.EnvMnemonic: testMnemonic,
|
||||
secret.EnvUnlockPassphrase: testPassphrase,
|
||||
}, "vault", "import", "nonexistent")
|
||||
@@ -1953,11 +1941,10 @@ func test23ErrorHandling(t *testing.T, tempDir, secretPath, testMnemonic string,
|
||||
assert.Contains(t, output, "does not exist", "should indicate vault doesn't exist")
|
||||
|
||||
// Get specific version that doesn't exist
|
||||
output, err = runSecretWithEnv(map[string]string{
|
||||
_, err = runSecretWithEnv(map[string]string{
|
||||
secret.EnvMnemonic: testMnemonic,
|
||||
}, "get", "--version", "99999999.999", "database/password")
|
||||
require.Error(t, err, "get non-existent version should fail")
|
||||
assert.Contains(t, output, "not found", "should indicate version not found")
|
||||
require.ErrorIs(t, err, vault.ErrVersionNotFound, "get non-existent version should fail")
|
||||
|
||||
// Promote non-existent version
|
||||
output, err = runSecretWithEnv(map[string]string{
|
||||
@@ -2367,11 +2354,10 @@ func test30BackupRestore(t *testing.T, tempDir, secretPath, testMnemonic string,
|
||||
assert.NotEmpty(t, output, "restored secret should have value")
|
||||
|
||||
// Verify post-backup secret is gone
|
||||
output, err = runSecretWithEnv(map[string]string{
|
||||
_, err = runSecretWithEnv(map[string]string{
|
||||
secret.EnvMnemonic: testMnemonic,
|
||||
}, "get", "post-backup/secret")
|
||||
require.Error(t, err, "post-backup secret should not exist after restore")
|
||||
assert.Contains(t, output, "not found", "should indicate secret not found")
|
||||
require.ErrorIs(t, err, vault.ErrSecretNotFound, "post-backup secret should not exist after restore")
|
||||
|
||||
t.Log("Backup and restore completed successfully")
|
||||
}
|
||||
@@ -2436,8 +2422,7 @@ func test31EnvMnemonicUsesVaultDerivationIndex(t *testing.T, tempDir, secretPath
|
||||
t.Logf("Output: %s", getOutput)
|
||||
|
||||
// This is the expected behavior with the current bug
|
||||
require.Error(t, err, "get should fail due to wrong derivation index")
|
||||
assert.Contains(t, getOutput, "derived public key does not match vault", "should indicate key derivation failure")
|
||||
require.ErrorIs(t, err, vault.ErrMnemonicMismatch, "get should fail due to wrong derivation index")
|
||||
|
||||
// Document what should happen when the bug is fixed
|
||||
t.Log("When the bug is fixed, GetValue should read vault metadata and use derivation index 1")
|
||||
|
||||
@@ -154,11 +154,10 @@ func newFsFromSnapshot(t *testing.T, tree map[string]string) afero.Fs {
|
||||
}
|
||||
|
||||
// requireRejectedAndUnchanged runs a command on a copy of the state
|
||||
// directory recorded in before. It requires an error with exactly the
|
||||
// message of want, so that a later check rejecting the argument does not
|
||||
// count, and everything under the state directory as it was: the error
|
||||
// alone proves nothing, since it could come after the vault had already
|
||||
// been deleted.
|
||||
// directory recorded in before. It requires the error want, so that a later
|
||||
// check rejecting the argument does not count, and everything under the
|
||||
// state directory as it was: the error alone proves nothing, since it could
|
||||
// come after the vault had already been deleted.
|
||||
func requireRejectedAndUnchanged(
|
||||
t *testing.T, before map[string]string, want error,
|
||||
run func(c *cli.Instance) error,
|
||||
@@ -170,7 +169,7 @@ func requireRejectedAndUnchanged(
|
||||
err := run(cli.NewCLIInstanceWithStateDir(fs, testStateDir))
|
||||
|
||||
require.Equal(t, before, snapshotStateDir(t, fs))
|
||||
require.EqualError(t, err, want.Error())
|
||||
require.ErrorIs(t, err, want)
|
||||
}
|
||||
|
||||
// TestInvalidSecretNameLeavesVaultsUnchanged is a regression test for
|
||||
@@ -193,77 +192,76 @@ func TestInvalidSecretNameLeavesVaultsUnchanged(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
|
||||
tests := []struct {
|
||||
command string
|
||||
rejected string // the secret name the command must reject
|
||||
run func(c *cli.Instance) error
|
||||
command string
|
||||
run func(c *cli.Instance) error
|
||||
}{
|
||||
{"rm --force ..", "..", func(c *cli.Instance) error {
|
||||
{"rm --force ..", func(c *cli.Instance) error {
|
||||
return c.RemoveSecret(cmd, "..", true)
|
||||
}},
|
||||
{"rm --force .", ".", func(c *cli.Instance) error {
|
||||
{"rm --force .", func(c *cli.Instance) error {
|
||||
return c.RemoveSecret(cmd, ".", true)
|
||||
}},
|
||||
{`rm --force ""`, "", func(c *cli.Instance) error {
|
||||
{`rm --force ""`, func(c *cli.Instance) error {
|
||||
return c.RemoveSecret(cmd, "", true)
|
||||
}},
|
||||
{"rm --force ../../etc", "../../etc", func(c *cli.Instance) error {
|
||||
{"rm --force ../../etc", func(c *cli.Instance) error {
|
||||
return c.RemoveSecret(cmd, "../../etc", true)
|
||||
}},
|
||||
{"mv --force .. x", "..", func(c *cli.Instance) error {
|
||||
{"mv --force .. x", func(c *cli.Instance) error {
|
||||
return c.MoveSecret(cmd, "..", "x", true)
|
||||
}},
|
||||
{"mv --force x ..", "..", func(c *cli.Instance) error {
|
||||
{"mv --force x ..", func(c *cli.Instance) error {
|
||||
return c.MoveSecret(cmd, "x", "..", true)
|
||||
}},
|
||||
{`mv --force x ""`, "", func(c *cli.Instance) error {
|
||||
{`mv --force x ""`, func(c *cli.Instance) error {
|
||||
return c.MoveSecret(cmd, "x", "", true)
|
||||
}},
|
||||
// "work" is not the current vault: a move within it must not
|
||||
// select it when a name is rejected.
|
||||
{"mv --force work:.. work:x", "..", func(c *cli.Instance) error {
|
||||
{"mv --force work:.. work:x", func(c *cli.Instance) error {
|
||||
return c.MoveSecret(cmd, "work:..", "work:x", true)
|
||||
}},
|
||||
{"mv --force work:x work:..", "..", func(c *cli.Instance) error {
|
||||
{"mv --force work:x work:..", func(c *cli.Instance) error {
|
||||
return c.MoveSecret(cmd, "work:x", "work:..", true)
|
||||
}},
|
||||
{"mv --force default:.. work", "..", func(c *cli.Instance) error {
|
||||
{"mv --force default:.. work", func(c *cli.Instance) error {
|
||||
return c.MoveSecret(cmd, "default:..", "work", true)
|
||||
}},
|
||||
{"mv --force default:.. work:y", "..", func(c *cli.Instance) error {
|
||||
{"mv --force default:.. work:y", func(c *cli.Instance) error {
|
||||
return c.MoveSecret(cmd, "default:..", "work:y", true)
|
||||
}},
|
||||
{"mv --force default:x work:..", "..", func(c *cli.Instance) error {
|
||||
{"mv --force default:x work:..", func(c *cli.Instance) error {
|
||||
return c.MoveSecret(cmd, "default:x", "work:..", true)
|
||||
}},
|
||||
{"import --force ..", "..", func(c *cli.Instance) error {
|
||||
{"import --force ..", func(c *cli.Instance) error {
|
||||
return c.ImportSecret(cmd, "..", missingFile, true)
|
||||
}},
|
||||
{"import --force .", ".", func(c *cli.Instance) error {
|
||||
{"import --force .", func(c *cli.Instance) error {
|
||||
return c.ImportSecret(cmd, ".", missingFile, true)
|
||||
}},
|
||||
{"import --force ../../etc", "../../etc", func(c *cli.Instance) error {
|
||||
{"import --force ../../etc", func(c *cli.Instance) error {
|
||||
return c.ImportSecret(cmd, "../../etc", missingFile, true)
|
||||
}},
|
||||
{"version list ..", "..", func(c *cli.Instance) error {
|
||||
{"version list ..", func(c *cli.Instance) error {
|
||||
return c.ListVersions(cmd, "..")
|
||||
}},
|
||||
{"version promote ..", "..", func(c *cli.Instance) error {
|
||||
{"version promote ..", func(c *cli.Instance) error {
|
||||
return c.PromoteVersion(cmd, "..", testVersion)
|
||||
}},
|
||||
{"version rm --force ..", "..", func(c *cli.Instance) error {
|
||||
{"version rm --force ..", func(c *cli.Instance) error {
|
||||
return c.RemoveVersion(cmd, "..", testVersion, true)
|
||||
}},
|
||||
{"encrypt ..", "..", func(c *cli.Instance) error {
|
||||
{"encrypt ..", func(c *cli.Instance) error {
|
||||
return c.Encrypt("..", "", "")
|
||||
}},
|
||||
{"decrypt ..", "..", func(c *cli.Instance) error {
|
||||
{"decrypt ..", func(c *cli.Instance) error {
|
||||
return c.Decrypt("..", "", "")
|
||||
}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.command, func(t *testing.T) {
|
||||
requireRejectedAndUnchanged(t, before, vault.ValidateSecretName(tt.rejected), tt.run)
|
||||
requireRejectedAndUnchanged(t, before, vault.ErrInvalidSecretName, tt.run)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -299,10 +297,18 @@ func TestInvalidVersionLeavesVaultsUnchanged(t *testing.T) {
|
||||
for _, tt := range commands {
|
||||
for _, version := range []string{"", ".", "..", "../../..", "a/b"} {
|
||||
t.Run(fmt.Sprintf("%s %q", tt.command, version), func(t *testing.T) {
|
||||
fs := newFsFromSnapshot(t, before)
|
||||
|
||||
err := tt.run(cli.NewCLIInstanceWithStateDir(fs, testStateDir), version)
|
||||
|
||||
require.Equal(t, before, snapshotStateDir(t, fs))
|
||||
|
||||
// Compared as text: `version rm` and `version promote` return
|
||||
// internal/cli's own error of this text, which errors.Is does
|
||||
// not match to vault.ErrVersionNotFound.
|
||||
want := fmt.Errorf("version '%s' %w '%s'",
|
||||
version, vault.ErrVersionNotFound, "x")
|
||||
requireRejectedAndUnchanged(t, before, want,
|
||||
func(c *cli.Instance) error { return tt.run(c, version) })
|
||||
require.EqualError(t, err, want.Error())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -355,7 +361,7 @@ func TestInvalidVaultNameLeavesStateUnchanged(t *testing.T) {
|
||||
for _, tt := range commands {
|
||||
for _, name := range []string{"", ".", "..", "a/b"} {
|
||||
t.Run(fmt.Sprintf(tt.command, name), func(t *testing.T) {
|
||||
requireRejectedAndUnchanged(t, before, vault.ValidateVaultName(name),
|
||||
requireRejectedAndUnchanged(t, before, vault.ErrInvalidVaultName,
|
||||
func(c *cli.Instance) error {
|
||||
c.Mnemonic = mnemonic
|
||||
c.UnlockPassphrase = passphrase
|
||||
|
||||
@@ -93,8 +93,8 @@ func newSizeTestVault(t *testing.T) (afero.Fs, *vault.Vault) {
|
||||
}
|
||||
|
||||
// runAddSecretSizeCase adds a secret of the given size through stdin and
|
||||
// verifies the outcome.
|
||||
func runAddSecretSizeCase(t *testing.T, size int, wantErr bool, errMsg string) {
|
||||
// verifies the outcome: wantErr, or the secret stored when wantErr is nil.
|
||||
func runAddSecretSizeCase(t *testing.T, size int, wantErr error) {
|
||||
t.Helper()
|
||||
skipIfLockedMemoryTooLow(t, size)
|
||||
|
||||
@@ -128,9 +128,8 @@ func runAddSecretSizeCase(t *testing.T, size int, wantErr bool, errMsg string) {
|
||||
secretName := fmt.Sprintf("test-secret-%d", size)
|
||||
err = cli.AddSecret(secretName, false)
|
||||
|
||||
if wantErr {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), errMsg)
|
||||
if wantErr != nil {
|
||||
require.ErrorIs(t, err, wantErr)
|
||||
|
||||
return
|
||||
}
|
||||
@@ -148,8 +147,8 @@ func runAddSecretSizeCase(t *testing.T, size int, wantErr bool, errMsg string) {
|
||||
}
|
||||
|
||||
// runImportSecretSizeCase imports a secret file of the given size and
|
||||
// verifies the outcome.
|
||||
func runImportSecretSizeCase(t *testing.T, size int, wantErr bool, errMsg string) {
|
||||
// verifies the outcome: wantErr, or the secret stored when wantErr is nil.
|
||||
func runImportSecretSizeCase(t *testing.T, size int, wantErr error) {
|
||||
t.Helper()
|
||||
skipIfLockedMemoryTooLow(t, size)
|
||||
|
||||
@@ -181,9 +180,8 @@ func runImportSecretSizeCase(t *testing.T, size int, wantErr bool, errMsg string
|
||||
secretName := fmt.Sprintf("imported-secret-%d", size)
|
||||
err = cli.ImportSecret(cmd, secretName, testFile, false)
|
||||
|
||||
if wantErr {
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), errMsg)
|
||||
if wantErr != nil {
|
||||
require.ErrorIs(t, err, wantErr)
|
||||
|
||||
return
|
||||
}
|
||||
@@ -205,57 +203,48 @@ func runImportSecretSizeCase(t *testing.T, size int, wantErr bool, errMsg string
|
||||
//nolint:paralleltest // together the subtests lock more than the memlock limit
|
||||
func TestAddSecretVariousSizes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
size int
|
||||
shouldError bool
|
||||
errorMsg string
|
||||
name string
|
||||
size int
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "1KB secret",
|
||||
size: 1024,
|
||||
shouldError: false,
|
||||
name: "1KB secret",
|
||||
size: 1024,
|
||||
},
|
||||
{
|
||||
name: "10KB secret",
|
||||
size: 10 * 1024,
|
||||
shouldError: false,
|
||||
name: "10KB secret",
|
||||
size: 10 * 1024,
|
||||
},
|
||||
{
|
||||
name: "100KB secret",
|
||||
size: 100 * 1024,
|
||||
shouldError: false,
|
||||
name: "100KB secret",
|
||||
size: 100 * 1024,
|
||||
},
|
||||
{
|
||||
name: "1MB secret",
|
||||
size: 1024 * 1024,
|
||||
shouldError: false,
|
||||
name: "1MB secret",
|
||||
size: 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "10MB secret",
|
||||
size: 10 * 1024 * 1024,
|
||||
shouldError: false,
|
||||
name: "10MB secret",
|
||||
size: 10 * 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "99MB secret",
|
||||
size: 99 * 1024 * 1024,
|
||||
shouldError: false,
|
||||
name: "99MB secret",
|
||||
size: 99 * 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "100MB secret minus 1 byte",
|
||||
size: 100*1024*1024 - 1,
|
||||
shouldError: false,
|
||||
name: "100MB secret minus 1 byte",
|
||||
size: 100*1024*1024 - 1,
|
||||
},
|
||||
{
|
||||
name: "101MB secret - should fail",
|
||||
size: 101 * 1024 * 1024,
|
||||
shouldError: true,
|
||||
errorMsg: "secret too large: exceeds 100MB limit",
|
||||
name: "101MB secret - should fail",
|
||||
size: 101 * 1024 * 1024,
|
||||
wantErr: errSecretTooLarge,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
runAddSecretSizeCase(t, tt.size, tt.shouldError, tt.errorMsg)
|
||||
runAddSecretSizeCase(t, tt.size, tt.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -265,57 +254,48 @@ func TestAddSecretVariousSizes(t *testing.T) {
|
||||
//nolint:paralleltest // together the subtests lock more than the memlock limit
|
||||
func TestImportSecretVariousSizes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
size int
|
||||
shouldError bool
|
||||
errorMsg string
|
||||
name string
|
||||
size int
|
||||
wantErr error
|
||||
}{
|
||||
{
|
||||
name: "1KB file",
|
||||
size: 1024,
|
||||
shouldError: false,
|
||||
name: "1KB file",
|
||||
size: 1024,
|
||||
},
|
||||
{
|
||||
name: "10KB file",
|
||||
size: 10 * 1024,
|
||||
shouldError: false,
|
||||
name: "10KB file",
|
||||
size: 10 * 1024,
|
||||
},
|
||||
{
|
||||
name: "100KB file",
|
||||
size: 100 * 1024,
|
||||
shouldError: false,
|
||||
name: "100KB file",
|
||||
size: 100 * 1024,
|
||||
},
|
||||
{
|
||||
name: "1MB file",
|
||||
size: 1024 * 1024,
|
||||
shouldError: false,
|
||||
name: "1MB file",
|
||||
size: 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "10MB file",
|
||||
size: 10 * 1024 * 1024,
|
||||
shouldError: false,
|
||||
name: "10MB file",
|
||||
size: 10 * 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "99MB file",
|
||||
size: 99 * 1024 * 1024,
|
||||
shouldError: false,
|
||||
name: "99MB file",
|
||||
size: 99 * 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "100MB file",
|
||||
size: 100 * 1024 * 1024,
|
||||
shouldError: false,
|
||||
name: "100MB file",
|
||||
size: 100 * 1024 * 1024,
|
||||
},
|
||||
{
|
||||
name: "101MB file - should fail",
|
||||
size: 101 * 1024 * 1024,
|
||||
shouldError: true,
|
||||
errorMsg: "secret file too large: exceeds 100MB limit",
|
||||
name: "101MB file - should fail",
|
||||
size: 101 * 1024 * 1024,
|
||||
wantErr: errSecretFileTooLarge,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
runImportSecretSizeCase(t, tt.size, tt.shouldError, tt.errorMsg)
|
||||
runImportSecretSizeCase(t, tt.size, tt.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
// Unlock Failure Tests
|
||||
//
|
||||
// When a vault cannot be opened through its current unlocker, because a
|
||||
// file the unlocker needs is missing or the passphrase is wrong, the error
|
||||
// keeps its cause and ends by saying that the mnemonic still opens that
|
||||
// vault, but only for a vault that the mnemonic does open, and not when the
|
||||
// passphrase could not be read at all. When a secret's current file is
|
||||
// missing, the error says how to make a version current again. Each test
|
||||
// that pins such advice also follows it.
|
||||
|
||||
package cli_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"filippo.io/age"
|
||||
"git.eeqj.de/sneak/secret/internal/cli"
|
||||
"git.eeqj.de/sneak/secret/internal/secret"
|
||||
"git.eeqj.de/sneak/secret/internal/vault"
|
||||
"github.com/awnumar/memguard"
|
||||
"github.com/spf13/afero"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
// mnemonicAdvice ends the error when the current vault "default", which
|
||||
// its mnemonic opens, cannot be opened through its current unlocker.
|
||||
mnemonicAdvice = "; the vault 'default' still opens with its mnemonic: " +
|
||||
"run 'secret unlocker add passphrase' with SB_SECRET_MNEMONIC set " +
|
||||
"to the mnemonic to give it a new unlocker"
|
||||
|
||||
// versionAdvice ends the error when a secret's current file cannot be
|
||||
// read.
|
||||
versionAdvice = "; this file only names the current version: " +
|
||||
"'secret version list' lists the secret's versions, and " +
|
||||
"'secret version promote' makes one of them current"
|
||||
|
||||
// unlockTestVaultDir is the directory of the vault "default" of
|
||||
// newTwoVaultFs, the current vault, whose secret "x" is "value".
|
||||
unlockTestVaultDir = testStateDir + "/vaults.d/default"
|
||||
)
|
||||
|
||||
// currentUnlockerDir returns the directory of the current unlocker of the
|
||||
// vault in vaultDir on fs.
|
||||
func currentUnlockerDir(t *testing.T, fs afero.Fs, vaultDir string) string {
|
||||
t.Helper()
|
||||
|
||||
unlockerName, err := afero.ReadFile(fs,
|
||||
filepath.Join(vaultDir, "current-unlocker"))
|
||||
require.NoError(t, err)
|
||||
|
||||
return filepath.Join(vaultDir, "unlockers.d", string(unlockerName))
|
||||
}
|
||||
|
||||
// newUnlockTestCLI returns the directory of the current unlocker of the
|
||||
// vault "default" on fs, a copy of the vaults of newTwoVaultFs, and a CLI
|
||||
// instance on fs that has the unlock passphrase, as from the environment,
|
||||
// but not the mnemonic.
|
||||
func newUnlockTestCLI(t *testing.T, fs afero.Fs) (string, *cli.Instance) {
|
||||
t.Helper()
|
||||
|
||||
c := cli.NewCLIInstanceWithStateDir(fs, testStateDir)
|
||||
c.UnlockPassphrase = memguard.NewBufferFromBytes([]byte(testPassphrase))
|
||||
t.Cleanup(c.UnlockPassphrase.Destroy)
|
||||
|
||||
return currentUnlockerDir(t, fs, unlockTestVaultDir), c
|
||||
}
|
||||
|
||||
// discardCmd returns a command whose output is discarded.
|
||||
func discardCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{}
|
||||
cmd.SetOut(io.Discard)
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
// getSecret returns what `secret get name` prints.
|
||||
func getSecret(t *testing.T, c *cli.Instance, name string) string {
|
||||
t.Helper()
|
||||
|
||||
var out bytes.Buffer
|
||||
|
||||
cmd := &cobra.Command{}
|
||||
cmd.SetOut(&out)
|
||||
require.NoError(t, c.GetSecret(cmd, name))
|
||||
|
||||
return out.String()
|
||||
}
|
||||
|
||||
// TestUnlockFailureNamesMnemonic checks the error of `secret get` when a
|
||||
// file that opening the vault through its current unlocker needs is
|
||||
// missing: it keeps the cause, which names the file, and ends with the
|
||||
// advice that the mnemonic still opens the vault. The test then follows
|
||||
// that advice: `secret unlocker add passphrase`, with the mnemonic, gives
|
||||
// the vault a new unlocker, which opens it.
|
||||
func TestUnlockFailureNamesMnemonic(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
file string // the file removed
|
||||
inVaultDir bool // the file is the vault's, not the unlocker's
|
||||
want string // the message before the cause
|
||||
}{
|
||||
{
|
||||
file: "current-unlocker",
|
||||
inVaultDir: true,
|
||||
want: "failed to unlock vault: failed to get long-term key: " +
|
||||
"failed to get current unlocker: " +
|
||||
"failed to read current unlocker: ",
|
||||
},
|
||||
{
|
||||
file: "priv.age",
|
||||
want: "failed to unlock vault: failed to get long-term key: " +
|
||||
"failed to get unlocker identity: " +
|
||||
"failed to read unlocker private key: ",
|
||||
},
|
||||
{
|
||||
file: "longterm.age",
|
||||
want: "failed to unlock vault: failed to get long-term key: " +
|
||||
"failed to read encrypted long-term private key: ",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.file, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := newTwoVaultFs(t)
|
||||
unlockerDir, c := newUnlockTestCLI(t, fs)
|
||||
|
||||
path := filepath.Join(unlockerDir, tt.file)
|
||||
|
||||
if tt.inVaultDir {
|
||||
path = filepath.Join(unlockTestVaultDir, tt.file)
|
||||
}
|
||||
|
||||
require.NoError(t, fs.Remove(path))
|
||||
|
||||
err := c.GetSecret(discardCmd(), "x")
|
||||
|
||||
var cause *os.PathError
|
||||
|
||||
require.ErrorAs(t, err, &cause)
|
||||
require.ErrorIs(t, err, os.ErrNotExist)
|
||||
assert.Equal(t, path, cause.Path)
|
||||
|
||||
require.EqualError(t, err, tt.want+cause.Error()+mnemonicAdvice)
|
||||
|
||||
c.Mnemonic = testMnemonicBuffer(t)
|
||||
require.NoError(t, c.UnlockersAdd("passphrase", discardCmd()))
|
||||
|
||||
c.Mnemonic = nil
|
||||
assert.Equal(t, "value", getSecret(t, c, "x"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestWrongPassphraseNamesMnemonic checks the error of `secret get` given a
|
||||
// passphrase that does not decrypt the passphrase unlocker: it keeps age's
|
||||
// error and ends with the advice that the mnemonic still opens the vault.
|
||||
func TestWrongPassphraseNamesMnemonic(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, c := newUnlockTestCLI(t, newTwoVaultFs(t))
|
||||
c.UnlockPassphrase = memguard.NewBufferFromBytes([]byte("wrong passphrase"))
|
||||
t.Cleanup(c.UnlockPassphrase.Destroy)
|
||||
|
||||
err := c.GetSecret(discardCmd(), "x")
|
||||
|
||||
var noMatch *age.NoIdentityMatchError
|
||||
|
||||
require.ErrorAs(t, err, &noMatch)
|
||||
|
||||
require.EqualError(t, err, "failed to unlock vault: "+
|
||||
"failed to get long-term key: failed to get unlocker identity: "+
|
||||
"failed to decrypt unlocker private key: failed to create decryptor: "+
|
||||
noMatch.Error()+mnemonicAdvice)
|
||||
}
|
||||
|
||||
// TestMoveUnlockFailureNamesVault checks the error of `secret move` into
|
||||
// the vault "work", which is not the current vault, when "work" cannot be
|
||||
// opened through its current unlocker: the advice names "work" and says to
|
||||
// select it first, since `secret unlocker add` acts on the current vault.
|
||||
// The test then follows that advice, and the move succeeds.
|
||||
func TestMoveUnlockFailureNamesVault(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := newTwoVaultFs(t)
|
||||
_, c := newUnlockTestCLI(t, fs)
|
||||
|
||||
path := filepath.Join(
|
||||
currentUnlockerDir(t, fs, testStateDir+"/vaults.d/work"), "priv.age")
|
||||
require.NoError(t, fs.Remove(path))
|
||||
|
||||
err := c.MoveSecret(discardCmd(), "default:x", "work:y", false)
|
||||
|
||||
var cause *os.PathError
|
||||
|
||||
require.ErrorAs(t, err, &cause)
|
||||
assert.Equal(t, path, cause.Path)
|
||||
|
||||
require.EqualError(t, err, "failed to unlock destination vault 'work': "+
|
||||
"failed to get unlocker identity: failed to read unlocker private key: "+
|
||||
cause.Error()+"; the vault 'work' still opens with its mnemonic: "+
|
||||
"run 'secret vault select work', then 'secret unlocker add passphrase' "+
|
||||
"with SB_SECRET_MNEMONIC set to the mnemonic to give it a new unlocker")
|
||||
|
||||
require.NoError(t, c.SelectVault(discardCmd(), "work"))
|
||||
|
||||
c.Mnemonic = testMnemonicBuffer(t)
|
||||
require.NoError(t, c.UnlockersAdd("passphrase", discardCmd()))
|
||||
|
||||
c.Mnemonic = nil
|
||||
require.NoError(t, c.MoveSecret(discardCmd(), "default:x", "work:y", false))
|
||||
assert.Equal(t, "value", getSecret(t, c, "y"))
|
||||
}
|
||||
|
||||
// TestPassphraseNotReadNamesNoMnemonic runs `secret get x` on the built
|
||||
// binary without SB_UNLOCK_PASSPHRASE and with a stdin that is not a
|
||||
// terminal, so the passphrase cannot be read. The unlocker was not tried,
|
||||
// and adding one would need a passphrase read the same way, so the error
|
||||
// is the cause alone, without the advice to use the mnemonic.
|
||||
func TestPassphraseNotReadNamesNoMnemonic(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
stateDir := t.TempDir()
|
||||
|
||||
mnemonic := memguard.NewBufferFromBytes([]byte(testMnemonic))
|
||||
defer mnemonic.Destroy()
|
||||
|
||||
passphrase := memguard.NewBufferFromBytes([]byte(testPassphrase))
|
||||
defer passphrase.Destroy()
|
||||
|
||||
vlt, err := vault.CreateVault(
|
||||
afero.NewOsFs(), stateDir, "default", mnemonic, passphrase)
|
||||
require.NoError(t, err)
|
||||
|
||||
value := memguard.NewBufferFromBytes([]byte("value"))
|
||||
defer value.Destroy()
|
||||
|
||||
require.NoError(t, vlt.AddSecret("x", value, false))
|
||||
|
||||
//nolint:gosec // G204: test executes the freshly built secret binary
|
||||
cmd := exec.CommandContext(t.Context(), secretBinaryPath(t), "get", "x")
|
||||
cmd.Env = []string{
|
||||
secret.EnvStateDir + "=" + stateDir,
|
||||
"PATH=" + os.Getenv("PATH"),
|
||||
"HOME=" + os.Getenv("HOME"),
|
||||
}
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
require.Error(t, err)
|
||||
|
||||
assert.Equal(t, "Error: failed to unlock vault: "+
|
||||
"failed to get long-term key: failed to get unlocker identity: "+
|
||||
"failed to read passphrase: cannot read passphrase from non-terminal "+
|
||||
"stdin (piped input or script). Please set the SB_UNLOCK_PASSPHRASE "+
|
||||
"environment variable or run interactively\n", string(output))
|
||||
}
|
||||
|
||||
// TestCryptoUnlockFailureNamesMnemonic checks that `secret encrypt` and
|
||||
// `secret decrypt`, reading the key secret, end with the same advice as
|
||||
// `secret get` when the vault cannot be opened through its current
|
||||
// unlocker.
|
||||
func TestCryptoUnlockFailureNamesMnemonic(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
command string
|
||||
run func(c *cli.Instance) error
|
||||
}{
|
||||
{"encrypt", func(c *cli.Instance) error { return c.Encrypt("x", "", "") }},
|
||||
{"decrypt", func(c *cli.Instance) error { return c.Decrypt("x", "", "") }},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.command, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := newTwoVaultFs(t)
|
||||
unlockerDir, c := newUnlockTestCLI(t, fs)
|
||||
|
||||
path := filepath.Join(unlockerDir, "priv.age")
|
||||
require.NoError(t, fs.Remove(path))
|
||||
|
||||
err := tt.run(c)
|
||||
|
||||
var cause *os.PathError
|
||||
|
||||
require.ErrorAs(t, err, &cause)
|
||||
assert.Equal(t, path, cause.Path)
|
||||
|
||||
require.EqualError(t, err, "failed to get secret value: "+
|
||||
"failed to unlock vault: failed to get long-term key: "+
|
||||
"failed to get unlocker identity: "+
|
||||
"failed to read unlocker private key: "+cause.Error()+
|
||||
mnemonicAdvice)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestMissingCurrentFileNamesVersionCommands checks the error of `secret
|
||||
// get` when the secret's current file is missing: it keeps the cause, which
|
||||
// names the file, and ends with the advice that says how to make a version
|
||||
// current again. The test then follows that advice.
|
||||
func TestMissingCurrentFileNamesVersionCommands(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := newTwoVaultFs(t)
|
||||
_, c := newUnlockTestCLI(t, fs)
|
||||
|
||||
secretDir := filepath.Join(unlockTestVaultDir, "secrets.d", "x")
|
||||
path := filepath.Join(secretDir, "current")
|
||||
require.NoError(t, fs.Remove(path))
|
||||
|
||||
err := c.GetSecret(discardCmd(), "x")
|
||||
|
||||
var cause *os.PathError
|
||||
|
||||
require.ErrorAs(t, err, &cause)
|
||||
require.ErrorIs(t, err, os.ErrNotExist)
|
||||
assert.Equal(t, path, cause.Path)
|
||||
|
||||
require.EqualError(t, err, "failed to get current version: "+
|
||||
"failed to read current version file: "+cause.Error()+versionAdvice)
|
||||
|
||||
versions, err := afero.ReadDir(fs, filepath.Join(secretDir, "versions"))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, versions, 1)
|
||||
|
||||
var out bytes.Buffer
|
||||
|
||||
cmd := &cobra.Command{}
|
||||
cmd.SetOut(&out)
|
||||
require.NoError(t, c.ListVersions(cmd, "x"))
|
||||
assert.Contains(t, out.String(), versions[0].Name())
|
||||
|
||||
require.NoError(t, c.PromoteVersion(cmd, "x", versions[0].Name()))
|
||||
assert.Equal(t, "value", getSecret(t, c, "x"))
|
||||
}
|
||||
|
||||
// TestUnlockFailureWithoutLongTermKeyNamesNoMnemonic checks that a vault
|
||||
// created without a mnemonic, which no mnemonic opens, gets no advice to
|
||||
// use one: `secret unlocker add passphrase` there fails with the cause
|
||||
// alone.
|
||||
func TestUnlockFailureWithoutLongTermKeyNamesNoMnemonic(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
|
||||
_, err := vault.CreateVault(fs, testStateDir, "keyless", nil, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
c := cli.NewCLIInstanceWithStateDir(fs, testStateDir)
|
||||
c.UnlockPassphrase = memguard.NewBufferFromBytes([]byte(testPassphrase))
|
||||
t.Cleanup(c.UnlockPassphrase.Destroy)
|
||||
|
||||
err = c.UnlockersAdd("passphrase", discardCmd())
|
||||
|
||||
var cause *os.PathError
|
||||
|
||||
require.ErrorAs(t, err, &cause)
|
||||
|
||||
require.EqualError(t, err, "failed to get long-term key: "+
|
||||
"failed to get current unlocker: failed to read current unlocker: "+
|
||||
cause.Error())
|
||||
}
|
||||
@@ -171,8 +171,7 @@ func TestListVersionsNonExistentSecret(t *testing.T) {
|
||||
|
||||
// Try to list versions of non-existent secret
|
||||
err := cli.ListVersions(cmd, "nonexistent/secret")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "not found")
|
||||
require.ErrorIs(t, err, errSecretNotFound)
|
||||
}
|
||||
|
||||
func TestPromoteVersionCommand(t *testing.T) {
|
||||
@@ -266,8 +265,7 @@ func TestPromoteNonExistentVersion(t *testing.T) {
|
||||
|
||||
// Try to promote non-existent version
|
||||
err = cli.PromoteVersion(cmd, "test/secret", "20991231.999")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "not found")
|
||||
require.ErrorIs(t, err, errVersionNotFound)
|
||||
}
|
||||
|
||||
func TestGetSecretWithVersion(t *testing.T) {
|
||||
|
||||
@@ -72,9 +72,12 @@ func TestKeychainInvalidItemName(t *testing.T) {
|
||||
testData := memguard.NewBufferFromBytes([]byte("test"))
|
||||
defer testData.Destroy()
|
||||
|
||||
// Test an empty item name
|
||||
err := storeInKeychain("", testData)
|
||||
require.ErrorIs(t, err, errKeychainItemNameEmpty)
|
||||
|
||||
// Test invalid item names
|
||||
invalidNames := []string{
|
||||
"", // Empty name
|
||||
"test space", // Contains space
|
||||
"test/slash", // Contains slash
|
||||
"test\\backslash", // Contains backslash
|
||||
@@ -96,9 +99,8 @@ 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)
|
||||
require.ErrorIs(t, err, errInvalidKeychainItemName,
|
||||
"Expected error for invalid name: %s", name)
|
||||
}
|
||||
|
||||
// Test valid names (should not error on validation)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package secret
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
@@ -10,6 +11,11 @@ import (
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// ErrPassphraseNotRead is wrapped in the error of a passphrase unlocker
|
||||
// that could not read its passphrase from the terminal, for example because
|
||||
// there is none. The unlocker itself was not tried.
|
||||
var ErrPassphraseNotRead = errors.New("failed to read passphrase")
|
||||
|
||||
// PassphraseUnlocker represents a passphrase-protected unlocker
|
||||
type PassphraseUnlocker struct {
|
||||
Directory string
|
||||
@@ -149,7 +155,7 @@ func (p *PassphraseUnlocker) getPassphrase() (*memguard.LockedBuffer, error) {
|
||||
if err != nil {
|
||||
Debug("Failed to read passphrase", "error", err, "unlocker_id", p.GetID())
|
||||
|
||||
return nil, fmt.Errorf("failed to read passphrase: %w", err)
|
||||
return nil, fmt.Errorf("%w: %w", ErrPassphraseNotRead, err)
|
||||
}
|
||||
|
||||
return secureBuffer, nil
|
||||
|
||||
@@ -1,26 +1,18 @@
|
||||
package secret
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"filippo.io/age"
|
||||
"git.eeqj.de/sneak/secret/pkg/agehd"
|
||||
"github.com/awnumar/memguard"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
var (
|
||||
// errSecretNotFound carries only the message tail; callers compose
|
||||
// "secret <name> not found" around it so the emitted text is
|
||||
// unchanged.
|
||||
errSecretNotFound = errors.New("not found")
|
||||
errUnlockerRequired = errors.New("unlocker required to decrypt secret")
|
||||
errGetEncryptedDataDeprecated = errors.New(
|
||||
"GetEncryptedData is deprecated - use version-specific methods")
|
||||
errGetCurrentVaultNotRegistered = errors.New(
|
||||
@@ -81,73 +73,6 @@ func NewSecret(vault VaultInterface, name string) *Secret {
|
||||
}
|
||||
}
|
||||
|
||||
// GetValue retrieves and decrypts the current version's value, with the
|
||||
// vault's long-term key derived from mnemonic when it is not nil, else
|
||||
// obtained through unlocker
|
||||
func (s *Secret) GetValue(
|
||||
unlocker Unlocker, mnemonic *memguard.LockedBuffer,
|
||||
) (*memguard.LockedBuffer, error) {
|
||||
DebugWith("Getting secret value",
|
||||
slog.String("secret_name", s.Name),
|
||||
slog.String("vault_name", s.vault.GetName()),
|
||||
)
|
||||
|
||||
// Check if secret exists
|
||||
exists, err := s.Exists()
|
||||
if err != nil {
|
||||
Debug("Failed to check if secret exists during GetValue",
|
||||
"error", err, "secret_name", s.Name)
|
||||
|
||||
return nil, fmt.Errorf("failed to check if secret exists: %w", err)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
Debug("Secret not found during GetValue",
|
||||
"secret_name", s.Name, "vault_name", s.vault.GetName())
|
||||
|
||||
return nil, fmt.Errorf("secret %s %w", s.Name, errSecretNotFound)
|
||||
}
|
||||
|
||||
Debug("Secret exists, getting current version", "secret_name", s.Name)
|
||||
|
||||
// Get current version
|
||||
currentVersion, err := GetCurrentVersion(s.vault.GetFilesystem(), s.Directory)
|
||||
if err != nil {
|
||||
Debug("Failed to get current version", "error", err, "secret_name", s.Name)
|
||||
|
||||
return nil, fmt.Errorf("failed to get current version: %w", err)
|
||||
}
|
||||
|
||||
// Create version object
|
||||
version := NewVersion(s.vault, s.Name, currentVersion)
|
||||
|
||||
if mnemonic != nil {
|
||||
return s.getValueViaMnemonic(version, mnemonic.String())
|
||||
}
|
||||
|
||||
Debug("Using unlocker for vault access", "secret_name", s.Name)
|
||||
|
||||
// Use the provided unlocker to get the vault's long-term private key
|
||||
if unlocker == nil {
|
||||
Debug("No unlocker provided for secret decryption", "secret_name", s.Name)
|
||||
|
||||
return nil, errUnlockerRequired
|
||||
}
|
||||
|
||||
ltIdentity, err := s.getLongTermIdentityFromUnlocker(unlocker)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
DebugWith("Successfully obtained vault's long-term key",
|
||||
slog.String("secret_name", s.Name),
|
||||
slog.String("public_key", ltIdentity.Recipient().String()),
|
||||
)
|
||||
|
||||
// Use the long-term key to decrypt the version
|
||||
return version.GetValue(ltIdentity)
|
||||
}
|
||||
|
||||
// LoadMetadata is deprecated - metadata is now per-version and encrypted
|
||||
func (s *Secret) LoadMetadata() error {
|
||||
Debug("LoadMetadata called but is deprecated in versioned model",
|
||||
@@ -215,124 +140,6 @@ func (s *Secret) Exists() (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// getValueViaMnemonic derives the vault's long-term key from the
|
||||
// mnemonic and decrypts the version value with it.
|
||||
func (s *Secret) getValueViaMnemonic(
|
||||
version *Version, mnemonic string,
|
||||
) (*memguard.LockedBuffer, error) {
|
||||
Debug("Using mnemonic for direct long-term key derivation",
|
||||
"secret_name", s.Name)
|
||||
|
||||
// Get vault directory to read metadata
|
||||
vaultDir, err := s.vault.GetDirectory()
|
||||
if err != nil {
|
||||
Debug("Failed to get vault directory", "error", err, "secret_name", s.Name)
|
||||
|
||||
return nil, fmt.Errorf("failed to get vault directory: %w", err)
|
||||
}
|
||||
|
||||
// Load vault metadata to get the correct derivation index
|
||||
metadataPath := filepath.Join(vaultDir, "vault-metadata.json")
|
||||
|
||||
metadataBytes, err := afero.ReadFile(s.vault.GetFilesystem(), metadataPath)
|
||||
if err != nil {
|
||||
Debug("Failed to read vault metadata", "error", err, "path", metadataPath)
|
||||
|
||||
return nil, fmt.Errorf("failed to read vault metadata: %w", err)
|
||||
}
|
||||
|
||||
var metadata VaultMetadata
|
||||
|
||||
err = json.Unmarshal(metadataBytes, &metadata)
|
||||
if err != nil {
|
||||
Debug("Failed to parse vault metadata", "error", err, "secret_name", s.Name)
|
||||
|
||||
return nil, fmt.Errorf("failed to parse vault metadata: %w", err)
|
||||
}
|
||||
|
||||
DebugWith("Using vault derivation index from metadata",
|
||||
slog.String("secret_name", s.Name),
|
||||
slog.String("vault_name", s.vault.GetName()),
|
||||
slog.Uint64("derivation_index", uint64(metadata.DerivationIndex)),
|
||||
)
|
||||
|
||||
// Use mnemonic with the vault's derivation index from metadata
|
||||
ltIdentity, err := agehd.DeriveIdentity(mnemonic, metadata.DerivationIndex)
|
||||
if err != nil {
|
||||
Debug("Failed to derive long-term key from mnemonic for secret",
|
||||
"error", err, "secret_name", s.Name)
|
||||
|
||||
return nil, fmt.Errorf(
|
||||
"failed to derive long-term key from mnemonic: %w", err)
|
||||
}
|
||||
|
||||
Debug("Successfully derived long-term key from mnemonic", "secret_name", s.Name)
|
||||
|
||||
// Use the long-term key to decrypt the version
|
||||
return version.GetValue(ltIdentity)
|
||||
}
|
||||
|
||||
// getLongTermIdentityFromUnlocker uses the unlocker to obtain and parse
|
||||
// the vault's long-term private key.
|
||||
func (s *Secret) getLongTermIdentityFromUnlocker(
|
||||
unlocker Unlocker,
|
||||
) (*age.X25519Identity, error) {
|
||||
DebugWith("Getting vault's long-term key using unlocker",
|
||||
slog.String("secret_name", s.Name),
|
||||
slog.String("unlocker_type", unlocker.GetType()),
|
||||
slog.String("unlocker_id", unlocker.GetID()),
|
||||
)
|
||||
|
||||
// Step 1: Use the unlocker to get the vault's long-term private key
|
||||
unlockIdentity, err := unlocker.GetIdentity()
|
||||
if err != nil {
|
||||
Debug("Failed to get unlocker identity",
|
||||
"error", err, "secret_name", s.Name,
|
||||
"unlocker_type", unlocker.GetType())
|
||||
|
||||
return nil, fmt.Errorf("failed to get unlocker identity: %w", err)
|
||||
}
|
||||
|
||||
// Read the encrypted long-term private key from the unlocker directory
|
||||
encryptedLtPrivKeyPath := filepath.Join(unlocker.GetDirectory(), "longterm.age")
|
||||
Debug("Reading encrypted long-term private key", "path", encryptedLtPrivKeyPath)
|
||||
|
||||
encryptedLtPrivKey, err := afero.ReadFile(
|
||||
s.vault.GetFilesystem(), encryptedLtPrivKeyPath)
|
||||
if err != nil {
|
||||
Debug("Failed to read encrypted long-term private key",
|
||||
"error", err, "path", encryptedLtPrivKeyPath)
|
||||
|
||||
return nil, fmt.Errorf(
|
||||
"failed to read encrypted long-term private key: %w", err)
|
||||
}
|
||||
|
||||
// Decrypt the encrypted long-term private key using the unlocker
|
||||
Debug("Decrypting long-term private key using unlocker", "secret_name", s.Name)
|
||||
|
||||
ltPrivKeyBuffer, err := DecryptWithIdentity(encryptedLtPrivKey, unlockIdentity)
|
||||
if err != nil {
|
||||
Debug("Failed to decrypt long-term private key",
|
||||
"error", err, "secret_name", s.Name)
|
||||
|
||||
return nil, fmt.Errorf("failed to decrypt long-term private key: %w", err)
|
||||
}
|
||||
defer ltPrivKeyBuffer.Destroy()
|
||||
|
||||
// Parse the long-term private key
|
||||
Debug("Parsing long-term private key", "secret_name", s.Name)
|
||||
|
||||
ltIdentity, err := age.ParseX25519Identity(ltPrivKeyBuffer.String())
|
||||
if err != nil {
|
||||
Debug("Failed to parse long-term private key",
|
||||
"error", err, "secret_name", s.Name)
|
||||
|
||||
return nil, fmt.Errorf("failed to parse long-term private key: %w", err)
|
||||
}
|
||||
|
||||
return ltIdentity, nil
|
||||
}
|
||||
|
||||
// GetCurrentVault gets the current vault from the file system
|
||||
// This function is a wrapper around the actual implementation in the vault package
|
||||
// and exists to break the import cycle.
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
package secret
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -13,7 +12,6 @@ import (
|
||||
"git.eeqj.de/sneak/secret/pkg/agehd"
|
||||
"github.com/awnumar/memguard"
|
||||
"github.com/spf13/afero"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// testMnemonicValue is the standard BIP39 test vector mnemonic.
|
||||
@@ -321,46 +319,3 @@ func TestPerSecretKeyFunctionality(t *testing.T) {
|
||||
t.Logf("Secret.Exists() works correctly")
|
||||
})
|
||||
}
|
||||
|
||||
// TestSecretGetValueWithMnemonicUsesVaultDerivationIndex checks that
|
||||
// GetValue, given the mnemonic, derives the long-term key at the derivation
|
||||
// index in the vault's metadata. At index 0 it could not decrypt the secret,
|
||||
// which was encrypted to the key at index 1.
|
||||
func TestSecretGetValueWithMnemonicUsesVaultDerivationIndex(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
vaultDir := "/test-config/vaults.d/test-vault"
|
||||
|
||||
mnemonic := memguard.NewBufferFromBytes([]byte(testMnemonicValue))
|
||||
defer mnemonic.Destroy()
|
||||
|
||||
vlt := &MockVault{
|
||||
name: "test-vault",
|
||||
fs: fs,
|
||||
directory: vaultDir,
|
||||
derivationIndex: 1,
|
||||
mnemonic: mnemonic,
|
||||
}
|
||||
|
||||
metadata, err := json.Marshal(VaultMetadata{DerivationIndex: vlt.derivationIndex})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, fs.MkdirAll(vaultDir, DirPerms))
|
||||
|
||||
err = afero.WriteFile(
|
||||
fs, filepath.Join(vaultDir, "vault-metadata.json"), metadata, FilePerms)
|
||||
require.NoError(t, err)
|
||||
|
||||
secretName, secretValue := "x", "value"
|
||||
|
||||
err = vlt.AddSecret(secretName,
|
||||
memguard.NewBufferFromBytes([]byte(secretValue)), false)
|
||||
require.NoError(t, err)
|
||||
|
||||
value, err := NewSecret(vlt, secretName).GetValue(nil, mnemonic)
|
||||
require.NoError(t, err)
|
||||
|
||||
defer value.Destroy()
|
||||
|
||||
require.Equal(t, secretValue, value.String())
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
package secret
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -106,6 +107,5 @@ 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.Contains(t, err.Error(), "failed to read SE-encrypted long-term key")
|
||||
require.ErrorIs(t, err, os.ErrNotExist)
|
||||
}
|
||||
@@ -557,13 +557,18 @@ func VersionExists(fs afero.Fs, secretDir string, version string) (bool, error)
|
||||
}
|
||||
|
||||
// GetCurrentVersion returns the version that the "current" file points to
|
||||
// The file contains just the version name (e.g., "20231215.001")
|
||||
// The file contains just the version name (e.g., "20231215.001"). If it
|
||||
// cannot be read, the error says how to make a version current again: the
|
||||
// versions themselves are not in the file.
|
||||
func GetCurrentVersion(fs afero.Fs, secretDir string) (string, error) {
|
||||
currentPath := filepath.Join(secretDir, "current")
|
||||
|
||||
fileData, err := afero.ReadFile(fs, currentPath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read current version file: %w", err)
|
||||
return "", fmt.Errorf("failed to read current version file: %w; "+
|
||||
"this file only names the current version: 'secret version list' "+
|
||||
"lists the secret's versions, and 'secret version promote' makes "+
|
||||
"one of them current", err)
|
||||
}
|
||||
|
||||
version := strings.TrimSpace(string(fileData))
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package secret
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGenerateVersionNameMaxSerial(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
secretDir := "/test/secret"
|
||||
versionsDir := filepath.Join(secretDir, "versions")
|
||||
|
||||
// Create 999 versions
|
||||
today := time.Now().Format("20060102")
|
||||
for i := 1; i <= 999; i++ {
|
||||
versionName := fmt.Sprintf("%s.%03d", today, i)
|
||||
err := fs.MkdirAll(filepath.Join(versionsDir, versionName), 0o755)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Try to create one more - should fail
|
||||
_, err := GenerateVersionName(fs, secretDir)
|
||||
require.ErrorIs(t, err, errMaxVersionsPerDay)
|
||||
}
|
||||
@@ -36,7 +36,6 @@ package secret_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -127,27 +126,6 @@ func TestGenerateVersionName(t *testing.T) {
|
||||
assert.NotEqual(t, version1, version2)
|
||||
}
|
||||
|
||||
func TestGenerateVersionNameMaxSerial(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := afero.NewMemMapFs()
|
||||
secretDir := testSecretDir
|
||||
versionsDir := filepath.Join(secretDir, "versions")
|
||||
|
||||
// Create 999 versions
|
||||
today := time.Now().Format("20060102")
|
||||
for i := 1; i <= 999; i++ {
|
||||
versionName := fmt.Sprintf("%s.%03d", today, i)
|
||||
err := fs.MkdirAll(filepath.Join(versionsDir, versionName), 0o755)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Try to create one more - should fail
|
||||
_, err := secret.GenerateVersionName(fs, secretDir)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "exceeded maximum versions per day")
|
||||
}
|
||||
|
||||
func TestNewVersion(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package vault_test
|
||||
|
||||
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/require"
|
||||
)
|
||||
|
||||
const (
|
||||
// otherMnemonic is a valid BIP39 mnemonic other than testMnemonic.
|
||||
otherMnemonic = "legal winner thank year wave sausage worth useful " +
|
||||
"legal winner thank yellow"
|
||||
|
||||
// missingName names no vault, secret or unlocker.
|
||||
missingName = "missing"
|
||||
)
|
||||
|
||||
// newErrorTestVault creates the vault testVaultName, with the secret
|
||||
// testSecretName in it, on a new in-memory filesystem.
|
||||
func newErrorTestVault(t *testing.T) *vault.Vault {
|
||||
t.Helper()
|
||||
|
||||
vlt, err := vault.CreateVault(afero.NewMemMapFs(), testStateDir,
|
||||
testVaultName, testMnemonicBuffer(t), nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
value := memguard.NewBufferFromBytes([]byte("value"))
|
||||
t.Cleanup(value.Destroy)
|
||||
|
||||
require.NoError(t, vlt.AddSecret(testSecretName, value, false))
|
||||
|
||||
return vlt
|
||||
}
|
||||
|
||||
// TestVaultErrors checks that each failure returns its exported error,
|
||||
// wrapped or not, so that errors.Is tells it apart from the others.
|
||||
func TestVaultErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
vaultDir := filepath.Join(testStateDir, "vaults.d", testVaultName)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
run func(vlt *vault.Vault) error
|
||||
want error
|
||||
}{
|
||||
{"create an existing vault", func(vlt *vault.Vault) error {
|
||||
_, err := vault.CreateVault(vlt.GetFilesystem(), testStateDir,
|
||||
testVaultName, nil, nil)
|
||||
|
||||
return err
|
||||
}, vault.ErrVaultExists},
|
||||
{"select a missing vault", func(vlt *vault.Vault) error {
|
||||
return vault.SelectVault(vlt.GetFilesystem(), testStateDir, missingName)
|
||||
}, vault.ErrVaultNotFound},
|
||||
{"add a nil value", func(vlt *vault.Vault) error {
|
||||
return vlt.AddSecret(missingName, nil, false)
|
||||
}, vault.ErrNilValueBuffer},
|
||||
{"get a missing secret", func(vlt *vault.Vault) error {
|
||||
_, err := vlt.GetSecret(missingName)
|
||||
|
||||
return err
|
||||
}, vault.ErrSecretNotFound},
|
||||
{"copy onto an existing secret", func(vlt *vault.Vault) error {
|
||||
return vlt.CopySecretAllVersions(vlt, testSecretName, testSecretName, false)
|
||||
}, vault.ErrSecretExists},
|
||||
{"copy a secret without versions", func(vlt *vault.Vault) error {
|
||||
err := vlt.GetFilesystem().MkdirAll(
|
||||
filepath.Join(vaultDir, "secrets.d", missingName), secret.DirPerms)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return vlt.CopySecretAllVersions(vlt, missingName, "copy", false)
|
||||
}, vault.ErrNoVersions},
|
||||
{"remove a missing unlocker", func(vlt *vault.Vault) error {
|
||||
return vlt.RemoveUnlocker(missingName)
|
||||
}, vault.ErrUnlockerNotFound},
|
||||
{"select a missing unlocker", func(vlt *vault.Vault) error {
|
||||
return vlt.SelectUnlocker(missingName)
|
||||
}, vault.ErrUnlockerNotFound},
|
||||
{"unlocker of an unknown type", func(vlt *vault.Vault) error {
|
||||
fs := vlt.GetFilesystem()
|
||||
|
||||
err := afero.WriteFile(fs,
|
||||
filepath.Join(vaultDir, "unlockers.d", "odd", "unlocker-metadata.json"),
|
||||
[]byte(`{"type":"odd"}`), secret.FilePerms)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = afero.WriteFile(fs, filepath.Join(vaultDir, "current-unlocker"),
|
||||
[]byte("odd"), secret.FilePerms)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = vlt.GetCurrentUnlocker()
|
||||
|
||||
return err
|
||||
}, vault.ErrUnsupportedUnlockerType},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
require.ErrorIs(t, tt.run(newErrorTestVault(t)), tt.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetSecretWithWrongMnemonic checks that getting a secret that exists,
|
||||
// from a vault the given mnemonic does not open, fails with
|
||||
// ErrMnemonicMismatch through GetSecret's wrapping, and not with
|
||||
// ErrSecretNotFound.
|
||||
func TestGetSecretWithWrongMnemonic(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
created := newErrorTestVault(t)
|
||||
|
||||
mnemonic := memguard.NewBufferFromBytes([]byte(otherMnemonic))
|
||||
t.Cleanup(mnemonic.Destroy)
|
||||
|
||||
vlt := vault.NewVault(created.GetFilesystem(), testStateDir, testVaultName)
|
||||
vlt.SetMnemonic(mnemonic)
|
||||
|
||||
_, err := vlt.GetSecret(testSecretName)
|
||||
require.ErrorIs(t, err, vault.ErrMnemonicMismatch)
|
||||
require.NotErrorIs(t, err, vault.ErrSecretNotFound)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package vault_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
@@ -341,9 +342,9 @@ func testVaultNameValidation(t *testing.T, fs afero.Fs, tempDir string) {
|
||||
|
||||
for _, name := range invalidNames {
|
||||
_, err := vault.CreateVault(fs, stateDir, name, testMnemonicBuffer(t), nil)
|
||||
if err == nil {
|
||||
t.Errorf("Expected error creating vault with invalid name %q, "+
|
||||
"but got none", name)
|
||||
if !errors.Is(err, vault.ErrInvalidVaultName) {
|
||||
t.Errorf("Expected ErrInvalidVaultName creating vault with "+
|
||||
"invalid name %q, got %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,10 +320,10 @@ func testVersionSerialLimits(
|
||||
err = fs.MkdirAll(filepath.Join(secretDir, versionName), 0o755)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Should fail to create 1000th version
|
||||
// Should fail to create 1000th version. The error is unexported in
|
||||
// package secret, whose own test checks that it is the one returned.
|
||||
_, err = secret.GenerateVersionName(fs, filepath.Dir(secretDir))
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "exceeded maximum versions per day")
|
||||
}
|
||||
|
||||
func testVersionErrorCases(t *testing.T, vault *Vault, secretName string) {
|
||||
@@ -331,20 +331,18 @@ func testVersionErrorCases(t *testing.T, vault *Vault, secretName string) {
|
||||
|
||||
// Try to get non-existent version
|
||||
_, err := vault.GetSecretVersion(secretName, "99991231.999")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "not found")
|
||||
require.ErrorIs(t, err, ErrVersionNotFound)
|
||||
|
||||
// Try to get version of non-existent secret
|
||||
_, err = vault.GetSecretVersion("nonexistent/secret", "")
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, ErrSecretNotFound)
|
||||
|
||||
// Try to add secret without force when it exists
|
||||
failBuffer := memguard.NewBufferFromBytes([]byte("should-fail"))
|
||||
defer failBuffer.Destroy()
|
||||
|
||||
err = vault.AddSecret(secretName, failBuffer, false)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "already exists")
|
||||
require.ErrorIs(t, err, ErrSecretExists)
|
||||
}
|
||||
|
||||
// TestVersionConcurrency tests concurrent version operations
|
||||
|
||||
@@ -41,10 +41,8 @@ func TestGetSecretVersionRejectsPathTraversal(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := vlt.GetSecretVersion(name, "")
|
||||
require.Error(t, err,
|
||||
require.ErrorIs(t, err, vault.ErrInvalidSecretName,
|
||||
"GetSecretVersion should reject malicious name: %s", name)
|
||||
require.Contains(t, err.Error(), "invalid secret name",
|
||||
"error should indicate invalid name for: %s", name)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -61,8 +59,7 @@ func TestGetSecretRejectsPathTraversal(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = vlt.GetSecret("../../../etc/passwd")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "invalid secret name")
|
||||
require.ErrorIs(t, err, vault.ErrInvalidSecretName)
|
||||
}
|
||||
|
||||
// TestGetSecretObjectRejectsPathTraversal verifies GetSecretObject
|
||||
@@ -87,8 +84,8 @@ func TestGetSecretObjectRejectsPathTraversal(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := vlt.GetSecretObject(name)
|
||||
require.Error(t, err, "GetSecretObject should reject: %s", name)
|
||||
require.Contains(t, err.Error(), "invalid secret name")
|
||||
require.ErrorIs(t, err, vault.ErrInvalidSecretName,
|
||||
"GetSecretObject should reject: %s", name)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -143,8 +143,7 @@ func TestVaultAddSecretMultipleVersions(t *testing.T) {
|
||||
defer failBuffer.Destroy()
|
||||
|
||||
err := vault.AddSecret(testSecretPath, failBuffer, false)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "already exists")
|
||||
require.ErrorIs(t, err, ErrSecretExists)
|
||||
|
||||
// Add with force - should create new version
|
||||
addTestSecretToVault(t, vault, testSecretPath, []byte("version-2"), true)
|
||||
@@ -309,8 +308,7 @@ func TestVaultGetNonExistentVersion(t *testing.T) {
|
||||
|
||||
// Try to get non-existent version
|
||||
_, err := vault.GetSecretVersion(testSecretPath, "20991231.999")
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "not found")
|
||||
require.ErrorIs(t, err, ErrVersionNotFound)
|
||||
}
|
||||
|
||||
func TestUpdateVersionMetadata(t *testing.T) {
|
||||
|
||||
+37
-2
@@ -1,6 +1,7 @@
|
||||
package vault
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
@@ -98,7 +99,8 @@ func (v *Vault) GetOrDeriveLongTermKey() (*age.X25519Identity, error) {
|
||||
if err != nil {
|
||||
secret.Debug("Failed to get current unlocker", "error", err, "vault_name", v.Name)
|
||||
|
||||
return nil, fmt.Errorf("failed to get current unlocker: %w", err)
|
||||
return nil, v.withMnemonicAdvice(
|
||||
fmt.Errorf("failed to get current unlocker: %w", err))
|
||||
}
|
||||
|
||||
secret.DebugWith("Retrieved current unlocker for vault unlock",
|
||||
@@ -112,7 +114,7 @@ func (v *Vault) GetOrDeriveLongTermKey() (*age.X25519Identity, error) {
|
||||
// Other unlockers return their own identity, used to decrypt longterm.age.
|
||||
ltIdentity, err := v.unlockLongTermKey(unlocker)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, v.withMnemonicAdvice(err)
|
||||
}
|
||||
|
||||
secret.DebugWith("Successfully obtained long-term identity via unlocker",
|
||||
@@ -295,3 +297,36 @@ func (v *Vault) unlockLongTermKey(
|
||||
|
||||
return ltIdentity, nil
|
||||
}
|
||||
|
||||
// withMnemonicAdvice returns err, a failure to get the long-term key through
|
||||
// the current unlocker, with advice added: that the mnemonic still opens the
|
||||
// vault, and how to give it a new unlocker. The advice is added only when the
|
||||
// vault metadata records the key that the mnemonic derives; a vault created
|
||||
// without a mnemonic records none, and without its metadata the key cannot
|
||||
// be derived. It is not added when the passphrase could not be read: the
|
||||
// unlocker was not tried, and adding one would need a passphrase read the
|
||||
// same way.
|
||||
func (v *Vault) withMnemonicAdvice(err error) error {
|
||||
if errors.Is(err, secret.ErrPassphraseNotRead) {
|
||||
return err
|
||||
}
|
||||
|
||||
vaultDir, _ := v.GetDirectory()
|
||||
|
||||
metadata, metadataErr := LoadVaultMetadata(v.fs, vaultDir)
|
||||
if metadataErr != nil || metadata.PublicKeyHash == "" {
|
||||
return err
|
||||
}
|
||||
|
||||
// 'secret unlocker add' acts on the current vault only.
|
||||
steps := "'secret unlocker add passphrase'"
|
||||
|
||||
current, currentErr := GetCurrentVault(v.fs, v.stateDir)
|
||||
if currentErr != nil || current.Name != v.Name {
|
||||
steps = fmt.Sprintf("'secret vault select %s', then %s", v.Name, steps)
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w; the vault '%s' still opens with its mnemonic: run "+
|
||||
"%s with %s set to the mnemonic to give it a new unlocker",
|
||||
err, v.Name, steps, secret.EnvMnemonic)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package vault_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
@@ -36,8 +37,8 @@ func TestAddSecretFailsWithMissingPublicKey(t *testing.T) {
|
||||
defer value.Destroy()
|
||||
|
||||
err := vlt.AddSecret(testSecretName, value, false)
|
||||
require.Error(t, err, "AddSecret should fail when public key is missing")
|
||||
assert.Contains(t, err.Error(), "failed to read long-term public key")
|
||||
require.ErrorIs(t, err, os.ErrNotExist,
|
||||
"AddSecret should fail when public key is missing")
|
||||
|
||||
// Verify that the secret directory was NOT created
|
||||
secretDir := filepath.Join(vaultDir, "secrets.d", testSecretName)
|
||||
|
||||
+5
-18
@@ -38,7 +38,6 @@ const (
|
||||
testMessageLargePattern = "A"
|
||||
|
||||
// Error messages for validation
|
||||
errorMsgNeed32Bytes = "need 32-byte scalar, got"
|
||||
errorMsgInvalidXPRV = "invalid-xprv"
|
||||
|
||||
// Test constants for various scenarios
|
||||
@@ -330,24 +329,17 @@ func TestClampFunction(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// requireIdentityError asserts that identity derivation failed with an
|
||||
// error containing errorMsg and returned no identity.
|
||||
// requireIdentityError asserts that identity derivation failed with
|
||||
// errInvalidScalarSize and returned no identity.
|
||||
func requireIdentityError(
|
||||
t *testing.T,
|
||||
identity *age.X25519Identity,
|
||||
err error,
|
||||
errorMsg string,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
if err == nil {
|
||||
t.Errorf("expected error but got none")
|
||||
} else if !strings.Contains(err.Error(), errorMsg) {
|
||||
t.Errorf(
|
||||
"expected error containing %q, got %q",
|
||||
errorMsg,
|
||||
err.Error(),
|
||||
)
|
||||
if !errors.Is(err, errInvalidScalarSize) {
|
||||
t.Errorf("expected errInvalidScalarSize, got %v", err)
|
||||
}
|
||||
|
||||
if identity != nil {
|
||||
@@ -363,31 +355,26 @@ func TestIdentityFromEntropyEdgeCases(t *testing.T) {
|
||||
name string
|
||||
entropy []byte
|
||||
expectError bool
|
||||
errorMsg string
|
||||
}{
|
||||
{
|
||||
name: "nil entropy",
|
||||
entropy: nil,
|
||||
expectError: true,
|
||||
errorMsg: errorMsgNeed32Bytes + " 0",
|
||||
},
|
||||
{
|
||||
name: "empty entropy",
|
||||
entropy: []byte{},
|
||||
expectError: true,
|
||||
errorMsg: errorMsgNeed32Bytes + " 0",
|
||||
},
|
||||
{
|
||||
name: "too short entropy",
|
||||
entropy: make([]byte, 31),
|
||||
expectError: true,
|
||||
errorMsg: errorMsgNeed32Bytes + " 31",
|
||||
},
|
||||
{
|
||||
name: "too long entropy",
|
||||
entropy: make([]byte, 33),
|
||||
expectError: true,
|
||||
errorMsg: errorMsgNeed32Bytes + " 33",
|
||||
},
|
||||
{
|
||||
name: "valid 32-byte entropy",
|
||||
@@ -419,7 +406,7 @@ func TestIdentityFromEntropyEdgeCases(t *testing.T) {
|
||||
identity, err := IdentityFromEntropy(tt.entropy)
|
||||
|
||||
if tt.expectError {
|
||||
requireIdentityError(t, identity, err, tt.errorMsg)
|
||||
requireIdentityError(t, identity, err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
+35
-9
@@ -4,6 +4,7 @@ package bip85_test
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -1013,14 +1014,13 @@ func TestHexDerivation(t *testing.T) {
|
||||
func TestInvalidParameters(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
logTestVector(t, "Invalid Parameters")
|
||||
|
||||
masterKey := mustParseTestMasterKey(t)
|
||||
|
||||
// Test cases for parameter validation
|
||||
testCases := []struct {
|
||||
name string
|
||||
testFunc func() error
|
||||
want error
|
||||
}{
|
||||
{
|
||||
name: "BIP39 invalid word count",
|
||||
@@ -1030,6 +1030,7 @@ func TestInvalidParameters(t *testing.T) {
|
||||
|
||||
return err
|
||||
},
|
||||
want: bip85.ErrInvalidWordCount,
|
||||
},
|
||||
{
|
||||
name: "Base64 password too short",
|
||||
@@ -1039,6 +1040,7 @@ func TestInvalidParameters(t *testing.T) {
|
||||
|
||||
return err
|
||||
},
|
||||
want: bip85.ErrInvalidBase64PwdLen,
|
||||
},
|
||||
{
|
||||
name: "Base64 password too long",
|
||||
@@ -1048,6 +1050,7 @@ func TestInvalidParameters(t *testing.T) {
|
||||
|
||||
return err
|
||||
},
|
||||
want: bip85.ErrInvalidBase64PwdLen,
|
||||
},
|
||||
{
|
||||
name: "Base85 password too short",
|
||||
@@ -1057,6 +1060,7 @@ func TestInvalidParameters(t *testing.T) {
|
||||
|
||||
return err
|
||||
},
|
||||
want: bip85.ErrInvalidBase85PwdLen,
|
||||
},
|
||||
{
|
||||
name: "Base85 password too long",
|
||||
@@ -1066,6 +1070,7 @@ func TestInvalidParameters(t *testing.T) {
|
||||
|
||||
return err
|
||||
},
|
||||
want: bip85.ErrInvalidBase85PwdLen,
|
||||
},
|
||||
{
|
||||
name: "Hex data too small",
|
||||
@@ -1075,6 +1080,7 @@ func TestInvalidParameters(t *testing.T) {
|
||||
|
||||
return err
|
||||
},
|
||||
want: bip85.ErrInvalidNumBytes,
|
||||
},
|
||||
{
|
||||
name: "Hex data too large",
|
||||
@@ -1084,23 +1090,43 @@ func TestInvalidParameters(t *testing.T) {
|
||||
|
||||
return err
|
||||
},
|
||||
want: bip85.ErrInvalidNumBytes,
|
||||
},
|
||||
}
|
||||
|
||||
// Run all validation test cases
|
||||
for _, tc := range testCases {
|
||||
t.Logf("Testing: %s", tc.name)
|
||||
|
||||
err := tc.testFunc()
|
||||
if err == nil {
|
||||
t.Errorf("Expected error for %s, but got nil", tc.name)
|
||||
} else {
|
||||
t.Logf("Got expected error: %v", err)
|
||||
t.Logf("RESULT: PASS")
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Errorf("Expected %v for %s, got %v", tc.want, tc.name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeriveBIP85EntropyErrors checks that DeriveBIP85Entropy returns
|
||||
// ErrNotPrivateKey for a public master key, and ErrInvalidPathComponent,
|
||||
// wrapped, for a path component that is not a number.
|
||||
func TestDeriveBIP85EntropyErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
masterKey := mustParseTestMasterKey(t)
|
||||
|
||||
publicKey, err := masterKey.Neuter()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to get the public key of the master key: %v", err)
|
||||
}
|
||||
|
||||
_, err = bip85.DeriveBIP85Entropy(publicKey, testCase1Path)
|
||||
if !errors.Is(err, bip85.ErrNotPrivateKey) {
|
||||
t.Errorf("Expected ErrNotPrivateKey, got %v", err)
|
||||
}
|
||||
|
||||
_, err = bip85.DeriveBIP85Entropy(masterKey, bip85.BIP85_MASTER_PATH+"/x'")
|
||||
if !errors.Is(err, bip85.ErrInvalidPathComponent) {
|
||||
t.Errorf("Expected ErrInvalidPathComponent, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdditionalDeriveHex tests additional hex derivation scenarios
|
||||
func TestAdditionalDeriveHex(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
Reference in new issue
Block a user