Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 39 additions & 12 deletions pkg/gpg/gpg_forwarding.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,16 @@
return gpgOwnerTrustCmd.Run()
}

// gpgConfDirectives are the gpg.conf options required for agent forwarding.
// no-autostart is essential: without it, any gpg invocation made while the
// forwarded socket is momentarily unavailable starts a local gpg-agent, which
// replaces the forwarded-socket symlink with an empty local socket and
// permanently breaks forwarding for the session.
var gpgConfDirectives = []string{"use-agent", "no-autostart"}

func (g *GPGConf) SetupGpgConf() error {
_, err := os.Stat(g.getConfigPath())
if err != nil {
_, err = os.Create(g.getConfigPath())
if err != nil {
if _, err := os.Stat(g.getConfigPath()); err != nil {
if _, err = os.Create(g.getConfigPath()); err != nil {
return err
}
}
Expand All @@ -110,22 +115,44 @@
return err
}

if !strings.Contains(string(gpgConfig), "use-agent") {
f, err := os.OpenFile(g.getConfigPath(),
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
f, err := os.OpenFile(g.getConfigPath(), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return err
}
defer func() { _ = f.Close() }()

// Avoid concatenating onto a final line that lacks a trailing newline.
needsLeadingNewline := len(gpgConfig) > 0 && !strings.HasSuffix(string(gpgConfig), "\n")

if _, err := f.WriteString("use-agent\n"); err != nil {
for _, directive := range gpgConfDirectives {
if containsDirective(string(gpgConfig), directive) {
continue
}
line := directive + "\n"
if needsLeadingNewline {
line = "\n" + line
needsLeadingNewline = false
}
if _, err := f.WriteString(line); err != nil {
return err
}
}

return nil
}

// containsDirective reports whether the gpg.conf contents already enable the
// given directive on its own line (ignoring surrounding whitespace), so we do
// not append duplicates.
func containsDirective(config, directive string) bool {
for _, line := range strings.Split(config, "\n") {

Check failure on line 148 in pkg/gpg/gpg_forwarding.go

View workflow job for this annotation

GitHub Actions / Lint

stringsseq: Ranging over SplitSeq is more efficient (modernize)
if strings.TrimSpace(line) == directive {
return true
}
}
return false
}

func (g *GPGConf) SetupRemoteSocketDirTree() error {
err := exec.Command("sudo", "mkdir", "-p", "/run/user", filepath.Dir(g.SocketPath)).Run()
if err != nil {
Expand Down
80 changes: 80 additions & 0 deletions pkg/gpg/gpg_forwarding_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package gpg

import (
"os"
"path/filepath"
"strings"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestSetupGpgConf_WritesRequiredDirectives(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
require.NoError(t, os.MkdirAll(filepath.Join(home, ".gnupg"), 0o700))

g := &GPGConf{}
require.NoError(t, g.SetupGpgConf())

got := readConf(t, g.getConfigPath())
for _, d := range gpgConfDirectives {
assert.Contains(t, got, d, "gpg.conf must enable %q for forwarding", d)
}
assert.Contains(t, gpgConfDirectives, "no-autostart",

Check failure on line 25 in pkg/gpg/gpg_forwarding_test.go

View workflow job for this annotation

GitHub Actions / Lint

File is not properly formatted (golines)
"no-autostart is required to stop gpg spawning a local agent that clobbers the forwarded socket")
}

func TestSetupGpgConf_Idempotent(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
require.NoError(t, os.MkdirAll(filepath.Join(home, ".gnupg"), 0o700))

g := &GPGConf{}
require.NoError(t, g.SetupGpgConf())
require.NoError(t, g.SetupGpgConf())

for _, d := range gpgConfDirectives {
assert.Equal(t, 1, strings.Count(readConf(t, g.getConfigPath()), d+"\n"),
"directive %q should not be duplicated on repeated setup", d)
}
}

func TestSetupGpgConf_PreservesExistingDirectives(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
require.NoError(t, os.MkdirAll(filepath.Join(home, ".gnupg"), 0o700))

g := &GPGConf{}
require.NoError(t, os.WriteFile(g.getConfigPath(), []byte("use-agent\n"), 0o600))
require.NoError(t, g.SetupGpgConf())

got := readConf(t, g.getConfigPath())
assert.Equal(t, 1, strings.Count(got, "use-agent\n"))
assert.Contains(t, got, "no-autostart")
}

func TestSetupGpgConf_ExistingFileWithoutTrailingNewline(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
require.NoError(t, os.MkdirAll(filepath.Join(home, ".gnupg"), 0o700))

g := &GPGConf{}
// no trailing newline on the existing directive
require.NoError(t, os.WriteFile(g.getConfigPath(), []byte("use-agent"), 0o600))
require.NoError(t, g.SetupGpgConf())

got := readConf(t, g.getConfigPath())
assert.NotContains(t, got, "use-agentno-autostart", "directives must not be concatenated")
for _, line := range []string{"use-agent", "no-autostart"} {
assert.True(t, containsDirective(got, line), "expected %q on its own line, got:\n%s", line, got)
}
}

func readConf(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path)

Check failure on line 77 in pkg/gpg/gpg_forwarding_test.go

View workflow job for this annotation

GitHub Actions / Lint

G304: Potential file inclusion via variable (gosec)
require.NoError(t, err)
return string(b)
}
Loading