Skip to content

Commit c4dbcf7

Browse files
committed
Vault secret calls should return an error if they fail
1 parent ec88608 commit c4dbcf7

File tree

3 files changed

+30
-16
lines changed

3 files changed

+30
-16
lines changed

internal/world/vault.go

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"fmt"
55
"os"
66

7+
"github.com/pkg/errors"
8+
79
"github.com/Sirupsen/logrus"
810
vault "github.com/hashicorp/vault/api"
911
)
@@ -52,9 +54,9 @@ type Vault struct {
5254
KeyMapping map[string]string
5355
}
5456

55-
func (v *Vault) Secret(path, field string) string {
57+
func (v *Vault) Secret(path, field string) (string, error) {
5658
if v.client == nil {
57-
return ""
59+
return "", errors.New("no vault client available")
5860
}
5961
prefixPath := fmt.Sprintf("%s%s", v.Prefix, path)
6062
mapped, ok := v.KeyMapping[prefixPath]
@@ -63,23 +65,14 @@ func (v *Vault) Secret(path, field string) string {
6365
}
6466
sec, err := v.client.Logical().Read(mapped)
6567
if err != nil {
66-
if v.logger != nil {
67-
v.logger.WithError(err).Errorf("Failed to access Vault path %s", mapped)
68-
}
69-
return ""
68+
return "", errors.Wrapf(err, "failed to access Vault path %s", mapped)
7069
}
7170
if sec == nil {
72-
if v.logger != nil {
73-
v.logger.Errorf("Vault path %s contained no secret", mapped)
74-
}
75-
return ""
71+
return "", errors.Errorf("Vault path %s contained no secret", mapped)
7672
}
7773
raw, ok := sec.Data[field]
7874
if !ok {
79-
if v.logger != nil {
80-
v.logger.Errorf("%s has no field named '%s'", mapped, field)
81-
}
82-
return ""
75+
return "", errors.Errorf("%s has no field named '%s'", mapped, field)
8376
}
84-
return fmt.Sprintf("%s", raw)
77+
return fmt.Sprintf("%s", raw), nil
8578
}

internal/world/vault_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package world_test
2+
3+
import (
4+
"bytes"
5+
"os"
6+
"testing"
7+
8+
"github.com/stretchr/testify/require"
9+
"github.com/zerok/tpl/internal/world"
10+
)
11+
12+
func TestVaultSecret(t *testing.T) {
13+
w := world.New(nil)
14+
os.Setenv("VAULT_ADDR", "http://127.0.0.1:54000")
15+
os.Setenv("VAULT_TOKEN", "")
16+
var out bytes.Buffer
17+
in := bytes.NewBufferString("{{ .Vault.Secret \"secret/path\" \"value\" }}")
18+
err := w.Render(&out, in)
19+
t.Logf("[[[ %s ]]]", out.String())
20+
require.Error(t, err)
21+
}

internal/world/world.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ func (w *World) Render(out io.Writer, in io.Reader) error {
8080

8181
func (w *World) Funcs() template.FuncMap {
8282
funcs := template.FuncMap(sprig.FuncMap())
83-
funcs["vault"] = func(path, field string) string {
83+
funcs["vault"] = func(path, field string) (string, error) {
8484
return w.Vault().Secret(path, field)
8585
}
8686

0 commit comments

Comments
 (0)