1
0
mirror of https://github.com/getsops/sops.git synced 2026-02-05 12:45:21 +01:00

Added SOPS_AGE_KEY_CMD option to age, fixes #1323

Signed-off-by: Danilo Bürger <danilo.buerger@helsing.ai>
This commit is contained in:
Danilo Bürger
2025-03-24 15:16:50 +01:00
parent 0057d3de82
commit eea4b7bb76
6 changed files with 51 additions and 3 deletions

View File

@@ -4,10 +4,10 @@ import (
"bufio"
"bytes"
"errors"
"filippo.io/age/plugin"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
@@ -15,9 +15,11 @@ import (
"filippo.io/age"
"filippo.io/age/agessh"
"filippo.io/age/armor"
"filippo.io/age/plugin"
"github.com/sirupsen/logrus"
"github.com/getsops/sops/v3/logging"
"github.com/kballard/go-shellquote"
)
const (
@@ -27,6 +29,9 @@ const (
// SopsAgeKeyFileEnv can be set as an environment variable pointing to an
// age keys file.
SopsAgeKeyFileEnv = "SOPS_AGE_KEY_FILE"
// SopsAgeKeyCmdEnv can be set as an environment variable with a command
// to execute that returns the age keys.
SopsAgeKeyCmdEnv = "SOPS_AGE_KEY_CMD"
// SopsAgeSshPrivateKeyFileEnv can be set as an environment variable pointing to
// a private SSH key file.
SopsAgeSshPrivateKeyFileEnv = "SOPS_AGE_SSH_PRIVATE_KEY_FILE"
@@ -310,6 +315,18 @@ func (key *MasterKey) loadIdentities() (ParsedIdentities, error) {
readers[SopsAgeKeyFileEnv] = f
}
if ageKeyCmd, ok := os.LookupEnv(SopsAgeKeyCmdEnv); ok {
args, err := shellquote.Split(ageKeyCmd)
if err != nil {
return nil, fmt.Errorf("failed to parse command %s: %w", ageKeyCmd, err)
}
out, err := exec.Command(args[0], args[1:]...).Output()
if err != nil {
return nil, fmt.Errorf("failed to execute command %s: %w", ageKeyCmd, err)
}
readers[SopsAgeKeyCmdEnv] = bytes.NewReader(out)
}
userConfigDir, err := getUserConfigDir()
if err != nil && len(readers) == 0 && len(identities) == 0 {
return nil, fmt.Errorf("user config directory could not be determined: %w", err)

View File

@@ -485,6 +485,33 @@ func TestMasterKey_loadIdentities(t *testing.T) {
assert.ErrorContains(t, err, fmt.Sprintf("failed to parse '%s' age identities", SopsAgeKeyEnv))
assert.Nil(t, got)
})
t.Run(SopsAgeKeyCmdEnv, func(t *testing.T) {
tmpDir := t.TempDir()
// Overwrite to ensure local config is not picked up by tests
overwriteUserConfigDir(t, tmpDir)
t.Setenv(SopsAgeKeyCmdEnv, "echo '"+mockIdentity+"'")
key := &MasterKey{}
got, err := key.loadIdentities()
assert.NoError(t, err)
assert.Len(t, got, 1)
})
t.Run("cmd error", func(t *testing.T) {
tmpDir := t.TempDir()
// Overwrite to ensure local config is not picked up by tests
overwriteUserConfigDir(t, tmpDir)
t.Setenv(SopsAgeKeyCmdEnv, "meow")
key := &MasterKey{}
got, err := key.loadIdentities()
assert.Error(t, err)
assert.ErrorContains(t, err, "failed to execute command meow")
assert.Nil(t, got)
})
}
// overwriteUserConfigDir sets the user config directory and the user home directory