-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
127 lines (100 loc) · 2.48 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package vaulty
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
hashiVault "github.com/hashicorp/vault/api"
)
var (
// ErrSecretNotFound is returned when a secret is not found.
ErrSecretNotFound = hashiVault.ErrSecretNotFound
// ErrInvalidClient is returned when the client is nil.
ErrInvalidClient = errors.New("client is nil")
// ErrInvalidAuth is returned when the auth method is nil.
ErrInvalidAuth = errors.New("auth method is nil")
)
type ClientHandler interface {
Client() *hashiVault.Client
}
type Client interface {
ClientHandler
// Path returns the secret path for the given name.
Path(name string, opts ...PathOption) Repository
}
type (
RenewalFunc func() (*hashiVault.Secret, error)
loginFunc func(v *hashiVault.Client) (*hashiVault.Secret, error)
)
type client struct {
ctx context.Context
l *slog.Logger
kvv2Mount string
auth loginFunc
config *hashiVault.Config
// Below are set on initialization
v *hashiVault.Client
authCreds *hashiVault.Secret
}
func NewClient(opts ...ClientOption) (Client, error) {
c := &client{
ctx: context.Background(),
l: slog.Default(),
kvv2Mount: "",
auth: nil,
config: hashiVault.DefaultConfig(),
v: nil,
authCreds: nil,
}
for _, opt := range opts {
opt(c)
}
if c.ctx == nil {
c.ctx = context.Background()
}
vc, err := hashiVault.NewClient(c.config)
if err != nil {
return nil, fmt.Errorf("unable to create vault client: %w", err)
} else if vc == nil {
return nil, ErrInvalidClient
}
c.v = vc
if c.auth == nil {
return nil, ErrInvalidAuth
}
authCreds, err := c.auth(c.v)
if err != nil {
return nil, fmt.Errorf("unable to authenticate with Vault: %w", err)
}
c.authCreds = authCreds
return c, nil
}
func (c *client) renewAuthInfo() {
err := RenewLease(c.ctx, c.l, c, "auth", c.authCreds, func() (*hashiVault.Secret, error) {
authInfo, err := c.auth(c.v)
if err != nil {
return nil, fmt.Errorf("unable to renew auth info: %w", err)
}
c.authCreds = authInfo
return authInfo, nil
})
if err != nil { // nolint:revive // Traditional error handling
c.l.Error("unable to renew auth info", slog.String(loggingKeyError, err.Error()))
os.Exit(1)
}
}
func (c *client) Client() *hashiVault.Client {
return c.v
}
func (c *client) Path(name string, opts ...PathOption) Repository {
p := &SecretPath{
r: c,
mount: c.kvv2Mount, // Default to kvv2
name: name,
}
for _, opt := range opts {
opt(p)
}
return p
}