Skip to content

Commit

Permalink
Merge pull request #1286 from makkes/better-import-error
Browse files Browse the repository at this point in the history
Better error reporting for missing gpg binary
  • Loading branch information
hiddeco authored Oct 9, 2023
2 parents 511046d + d021b6b commit 8c89d14
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
15 changes: 14 additions & 1 deletion pgp/keysource.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ package pgp //import "github.com/getsops/sops/v3/pgp"
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -133,7 +134,19 @@ func (d GnuPGHome) Import(armoredKey []byte) error {
args := []string{"--batch", "--import"}
_, stderr, err := gpgExec(d.String(), args, bytes.NewReader(armoredKey))
if err != nil {
return fmt.Errorf("failed to import armored key data into GnuPG keyring: %s", strings.TrimSpace(stderr.String()))
stderrStr := strings.TrimSpace(stderr.String())
errStr := err.Error()
var sb strings.Builder
sb.WriteString("failed to import armored key data into GnuPG keyring")
if len(stderrStr) > 0 {
if len(errStr) > 0 {
fmt.Fprintf(&sb, " (%s)", errStr)
}
fmt.Fprintf(&sb, ": %s", stderrStr)
} else if len(errStr) > 0 {
fmt.Fprintf(&sb, ": %s", errStr)
}
return errors.New(sb.String())
}
return nil
}
Expand Down
19 changes: 18 additions & 1 deletion pgp/keysource_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,27 @@ func TestGnuPGHome_Import(t *testing.T) {
_, stderr, err = gpgExec(gnuPGHome.String(), []string{"--list-secret-keys", mockFingerprint}, nil)
assert.NoErrorf(t, err, stderr.String())

assert.Error(t, gnuPGHome.Import([]byte("invalid armored data")))
err = gnuPGHome.Import([]byte("invalid armored data"))
assert.Error(t, err)
assert.ErrorContains(t, err, "(exit status 2): gpg: no valid OpenPGP data found.\ngpg: Total number processed: 0")
assert.Error(t, GnuPGHome("").Import(b))
}

func TestGnuPGHome_Import_With_Missing_Binary(t *testing.T) {
t.Setenv(SopsGpgExecEnv, "/does/not/exist")

gnuPGHome, err := NewGnuPGHome()
assert.NoError(t, err)
t.Cleanup(func() {
_ = os.RemoveAll(gnuPGHome.String())
})

b, err := os.ReadFile(mockPublicKey)
assert.NoError(t, err)
err = gnuPGHome.Import(b)
assert.ErrorContains(t, err, "failed to import armored key data into GnuPG keyring: fork/exec /does/not/exist: no such file or directory")
}

func TestGnuPGHome_ImportFile(t *testing.T) {
gnuPGHome, err := NewGnuPGHome()
assert.NoError(t, err)
Expand Down

0 comments on commit 8c89d14

Please sign in to comment.