vvauth 2.4.1 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/rc.go ADDED
@@ -0,0 +1,427 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "fmt"
7
+ "net/url"
8
+ "os"
9
+ "os/exec"
10
+ "path/filepath"
11
+ "regexp"
12
+ "strconv"
13
+ "strings"
14
+
15
+ "gopkg.in/yaml.v3"
16
+ )
17
+
18
+ // RC is the parsed .vauthrc, after $${env.X} expansion.
19
+ type RC struct {
20
+ VaultAddr string `yaml:"vault_addr"`
21
+ SSHAuth *SSHAuth `yaml:"ssh_auth"`
22
+ JWTAuth *JWTAuth `yaml:"jwt_auth"`
23
+ TokenCache *bool `yaml:"token_cache"`
24
+ AgentCrypt *AgentCrypt `yaml:"ssh-agent-crypt"`
25
+ Env *EnvConfig `yaml:"env"`
26
+
27
+ // authKey is the JSON of {ssh_auth, jwt_auth} in document order, as
28
+ // JSON.stringify would render them: it isolates the token cache.
29
+ authKey string
30
+ }
31
+
32
+ // AuthKey renders ssh_auth and jwt_auth as JSON members, in the order of the
33
+ // parsed document. Programmatic configurations are rendered from the structs.
34
+ func (rc *RC) AuthKey() string {
35
+ if rc.authKey != "" {
36
+ return rc.authKey
37
+ }
38
+ var members []string
39
+ if rc.SSHAuth != nil {
40
+ members = append(members, `"ssh_auth":`+jsonMembers([][2]string{{"path", rc.SSHAuth.Path}, {"role", rc.SSHAuth.Role}}))
41
+ }
42
+ if rc.JWTAuth != nil {
43
+ members = append(members, `"jwt_auth":`+jsonMembers([][2]string{{"path", rc.JWTAuth.Path}, {"jwt", rc.JWTAuth.JWT}, {"role", rc.JWTAuth.Role}}))
44
+ }
45
+ return strings.Join(members, ",")
46
+ }
47
+
48
+ func jsonMembers(pairs [][2]string) string {
49
+ var out bytes.Buffer
50
+ out.WriteByte('{')
51
+ for _, pair := range pairs {
52
+ if pair[1] == "" {
53
+ continue
54
+ }
55
+ if out.Len() > 1 {
56
+ out.WriteByte(',')
57
+ }
58
+ out.Write(jsonString(pair[0]))
59
+ out.WriteByte(':')
60
+ out.Write(jsonString(pair[1]))
61
+ }
62
+ out.WriteByte('}')
63
+ return out.String()
64
+ }
65
+
66
+ // SSHAuth configures the Vault ssh auth plugin (nonce challenge).
67
+ type SSHAuth struct {
68
+ Path string `yaml:"path"`
69
+ Role string `yaml:"role"`
70
+ }
71
+
72
+ // JWTAuth configures a Vault jwt login.
73
+ type JWTAuth struct {
74
+ Path string `yaml:"path"`
75
+ JWT string `yaml:"jwt"`
76
+ Role string `yaml:"role"`
77
+ }
78
+
79
+ // AgentCrypt points to a local ssh-agent-crypt armored JSON file whose keys
80
+ // feed $${secrets.X}.
81
+ type AgentCrypt struct {
82
+ Path string `yaml:"path"`
83
+ Identity string `yaml:"identity"`
84
+ }
85
+
86
+ // EnvConfig describes the environment to resolve.
87
+ type EnvConfig struct {
88
+ Map OrderedMap `yaml:"map"`
89
+ Paths []string `yaml:"paths"`
90
+ Path string `yaml:"path"`
91
+ Git bool `yaml:"git"`
92
+ GitLab bool `yaml:"gitlab"`
93
+ }
94
+
95
+ // OrderedMap keeps the YAML document order of a string mapping.
96
+ type OrderedMap struct {
97
+ Keys []string
98
+ Values map[string]string
99
+ }
100
+
101
+ // Set adds or replaces key.
102
+ func (m *OrderedMap) Set(key, value string) {
103
+ if m.Values == nil {
104
+ m.Values = map[string]string{}
105
+ }
106
+ if _, exists := m.Values[key]; !exists {
107
+ m.Keys = append(m.Keys, key)
108
+ }
109
+ m.Values[key] = value
110
+ }
111
+
112
+ // Get returns the value for key.
113
+ func (m *OrderedMap) Get(key string) (string, bool) {
114
+ value, ok := m.Values[key]
115
+ return value, ok
116
+ }
117
+
118
+ // Len returns the number of entries.
119
+ func (m *OrderedMap) Len() int { return len(m.Keys) }
120
+
121
+ // UnmarshalYAML decodes a mapping, scalars as strings.
122
+ func (m *OrderedMap) UnmarshalYAML(node *yaml.Node) error {
123
+ if node.Kind != yaml.MappingNode {
124
+ return fmt.Errorf("line %d: expected a mapping", node.Line)
125
+ }
126
+ for i := 0; i+1 < len(node.Content); i += 2 {
127
+ var key, value string
128
+ if err := node.Content[i].Decode(&key); err != nil {
129
+ return err
130
+ }
131
+ if err := node.Content[i+1].Decode(&value); err != nil {
132
+ return err
133
+ }
134
+ m.Set(key, value)
135
+ }
136
+ return nil
137
+ }
138
+
139
+ // MarshalJSON renders the entries in order.
140
+ func (m OrderedMap) MarshalJSON() ([]byte, error) {
141
+ var out bytes.Buffer
142
+ out.WriteByte('{')
143
+ for i, key := range m.Keys {
144
+ if i > 0 {
145
+ out.WriteByte(',')
146
+ }
147
+ out.Write(jsonString(key))
148
+ out.WriteByte(':')
149
+ out.Write(jsonString(m.Values[key]))
150
+ }
151
+ out.WriteByte('}')
152
+ return out.Bytes(), nil
153
+ }
154
+
155
+ // Lookup resolves dotted paths ($${env.X}) in nested string maps.
156
+ type Lookup map[string]any
157
+
158
+ func (dict Lookup) get(path string) (string, bool) {
159
+ var current any = map[string]any(dict)
160
+ for _, part := range strings.Split(path, ".") {
161
+ switch node := current.(type) {
162
+ case map[string]any:
163
+ value, ok := node[part]
164
+ if !ok {
165
+ return "", false
166
+ }
167
+ current = value
168
+ case map[string]string:
169
+ value, ok := node[part]
170
+ if !ok {
171
+ return "", false
172
+ }
173
+ current = value
174
+ case Lookup:
175
+ value, ok := node[part]
176
+ if !ok {
177
+ return "", false
178
+ }
179
+ current = value
180
+ default:
181
+ return "", false
182
+ }
183
+ }
184
+ return stringify(current)
185
+ }
186
+
187
+ func stringify(value any) (string, bool) {
188
+ switch v := value.(type) {
189
+ case nil:
190
+ return "", false
191
+ case string:
192
+ return v, true
193
+ case bool:
194
+ return strconv.FormatBool(v), true
195
+ case float64:
196
+ return strconv.FormatFloat(v, 'f', -1, 64), true
197
+ case json.Number:
198
+ return v.String(), true
199
+ }
200
+ body, err := json.Marshal(value)
201
+ if err != nil {
202
+ return "", false
203
+ }
204
+ return string(body), true
205
+ }
206
+
207
+ var macroPattern = regexp.MustCompile(`(?i)\$\$([a-z0-9._-]+)|\$\$\{([^}]+)\}`)
208
+
209
+ // ReplaceEnv expands $$key and $${key} macros against dict (nyks
210
+ // string/replaceEnv semantics): unknown keys stay, expansions recurse.
211
+ func ReplaceEnv(str string, dict Lookup) string {
212
+ for depth := 0; depth < 16; depth++ {
213
+ touched := false
214
+ str = macroPattern.ReplaceAllStringFunc(str, func(macro string) string {
215
+ match := macroPattern.FindStringSubmatch(macro)
216
+ key := match[1]
217
+ if key == "" {
218
+ key = match[2]
219
+ }
220
+ value, ok := dict.get(key)
221
+ if !ok {
222
+ return macro
223
+ }
224
+ touched = true
225
+ return value
226
+ })
227
+ if !touched {
228
+ break
229
+ }
230
+ }
231
+ return str
232
+ }
233
+
234
+ // walk expands every scalar string of a YAML tree in place.
235
+ func walk(node *yaml.Node, process func(string) string) {
236
+ if node.Kind == yaml.ScalarNode {
237
+ if node.Tag == "!!str" || node.Tag == "" {
238
+ node.Value = process(node.Value)
239
+ }
240
+ return
241
+ }
242
+ for _, child := range node.Content {
243
+ walk(child, process)
244
+ }
245
+ }
246
+
247
+ // jsonNode renders a YAML subtree as JSON.stringify would after yaml.parse.
248
+ func jsonNode(node *yaml.Node, out *bytes.Buffer) {
249
+ switch node.Kind {
250
+ case yaml.DocumentNode, yaml.AliasNode:
251
+ if node.Kind == yaml.AliasNode {
252
+ jsonNode(node.Alias, out)
253
+ } else if len(node.Content) > 0 {
254
+ jsonNode(node.Content[0], out)
255
+ }
256
+ case yaml.MappingNode:
257
+ out.WriteByte('{')
258
+ for i := 0; i+1 < len(node.Content); i += 2 {
259
+ if i > 0 {
260
+ out.WriteByte(',')
261
+ }
262
+ out.Write(jsonString(node.Content[i].Value))
263
+ out.WriteByte(':')
264
+ jsonNode(node.Content[i+1], out)
265
+ }
266
+ out.WriteByte('}')
267
+ case yaml.SequenceNode:
268
+ out.WriteByte('[')
269
+ for i, child := range node.Content {
270
+ if i > 0 {
271
+ out.WriteByte(',')
272
+ }
273
+ jsonNode(child, out)
274
+ }
275
+ out.WriteByte(']')
276
+ case yaml.ScalarNode:
277
+ switch node.Tag {
278
+ case "!!int", "!!float", "!!bool":
279
+ var value any
280
+ if node.Decode(&value) == nil {
281
+ if text, ok := stringify(value); ok {
282
+ out.WriteString(text)
283
+ return
284
+ }
285
+ }
286
+ out.Write(jsonString(node.Value))
287
+ case "!!null":
288
+ out.WriteString("null")
289
+ default:
290
+ out.Write(jsonString(node.Value))
291
+ }
292
+ }
293
+ }
294
+
295
+ // jsonString encodes like JSON.stringify (no HTML escaping).
296
+ func jsonString(value string) []byte {
297
+ var out bytes.Buffer
298
+ encoder := json.NewEncoder(&out)
299
+ encoder.SetEscapeHTML(false)
300
+ encoder.Encode(value)
301
+ return bytes.TrimRight(out.Bytes(), "\n")
302
+ }
303
+
304
+ func mappingValue(node *yaml.Node, key string) *yaml.Node {
305
+ if node == nil {
306
+ return nil
307
+ }
308
+ if node.Kind == yaml.DocumentNode && len(node.Content) > 0 {
309
+ node = node.Content[0]
310
+ }
311
+ if node.Kind != yaml.MappingNode {
312
+ return nil
313
+ }
314
+ for i := 0; i+1 < len(node.Content); i += 2 {
315
+ if node.Content[i].Value == key {
316
+ return node.Content[i+1]
317
+ }
318
+ }
319
+ return nil
320
+ }
321
+
322
+ // LocateRC returns the first existing configuration file among VAUTHRC,
323
+ // ./.vauthrc and ~/.vauthrc, or an empty string.
324
+ func LocateRC(environ map[string]string, cwd, home string) string {
325
+ candidates := []string{environ["VAUTHRC"], filepath.Join(cwd, ".vauthrc"), filepath.Join(home, ".vauthrc")}
326
+ for _, candidate := range candidates {
327
+ if candidate == "" {
328
+ continue
329
+ }
330
+ if _, err := os.Stat(candidate); err == nil {
331
+ return candidate
332
+ }
333
+ }
334
+ return ""
335
+ }
336
+
337
+ // ParseRC parses a .vauthrc body and expands its $${env.X} macros against
338
+ // environ. With env.gitlab outside CI, CI_PROJECT_* variables are derived
339
+ // from the git remote of the directory holding the file.
340
+ func ParseRC(body []byte, file string, environ map[string]string) (*RC, error) {
341
+ var document yaml.Node
342
+ if err := yaml.Unmarshal(body, &document); err != nil {
343
+ return nil, fmt.Errorf("Could not parse %s: %w", file, err)
344
+ }
345
+ if len(document.Content) == 0 {
346
+ return &RC{authKey: "{}"}, nil
347
+ }
348
+ if gitlab := mappingValue(mappingValue(&document, "env"), "gitlab"); gitlab != nil && truthy(gitlab) && environ["CI"] == "" {
349
+ environ = withGitLabProject(environ, filepath.Dir(file))
350
+ }
351
+ walk(&document, func(value string) string {
352
+ return ReplaceEnv(value, Lookup{"env": environ})
353
+ })
354
+ rc := RC{}
355
+ if err := document.Decode(&rc); err != nil {
356
+ return nil, fmt.Errorf("Could not parse %s: %w", file, err)
357
+ }
358
+ var key bytes.Buffer
359
+ for i, name := range []string{"ssh_auth", "jwt_auth"} {
360
+ node := mappingValue(&document, name)
361
+ if node == nil || node.Tag == "!!null" {
362
+ continue
363
+ }
364
+ if i > 0 && key.Len() > 0 {
365
+ key.WriteByte(',')
366
+ }
367
+ key.Write(jsonString(name))
368
+ key.WriteByte(':')
369
+ jsonNode(node, &key)
370
+ }
371
+ rc.authKey = key.String()
372
+ return &rc, nil
373
+ }
374
+
375
+ func truthy(node *yaml.Node) bool {
376
+ switch node.Kind {
377
+ case yaml.ScalarNode:
378
+ switch node.Tag {
379
+ case "!!null":
380
+ return false
381
+ case "!!bool":
382
+ return node.Value == "true"
383
+ case "!!int", "!!float":
384
+ return node.Value != "0" && node.Value != "0.0"
385
+ }
386
+ return node.Value != ""
387
+ }
388
+ return true
389
+ }
390
+
391
+ var scpRemote = regexp.MustCompile(`^[^@]+@[^:]+:(.+)$`)
392
+
393
+ func withGitLabProject(environ map[string]string, dir string) map[string]string {
394
+ cmd := exec.Command("git", "remote", "get-url", "origin")
395
+ cmd.Dir = dir
396
+ out, err := cmd.Output()
397
+ if err != nil {
398
+ return environ
399
+ }
400
+ remote := strings.TrimSpace(string(out))
401
+ var project string
402
+ if match := scpRemote.FindStringSubmatch(remote); match != nil {
403
+ project = match[1]
404
+ } else if parsed, err := url.Parse(remote); err == nil {
405
+ project = parsed.Path
406
+ }
407
+ project = strings.TrimSuffix(strings.Trim(project, "/"), ".git")
408
+ if project == "" {
409
+ return environ
410
+ }
411
+ parts := strings.Split(project, "/")
412
+ extended := make(map[string]string, len(environ)+4)
413
+ for k, v := range environ {
414
+ extended[k] = v
415
+ }
416
+ extended["CI_PROJECT_PATH"] = project
417
+ extended["CI_PROJECT_NAME"] = parts[len(parts)-1]
418
+ extended["CI_PROJECT_NAMESPACE"] = strings.Join(parts[:len(parts)-1], "/")
419
+ extended["CI_PROJECT_PATH_SLUG"] = slug(project)
420
+ return extended
421
+ }
422
+
423
+ var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
424
+
425
+ func slug(value string) string {
426
+ return strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(value), "-"), "-")
427
+ }
package/vault.go ADDED
@@ -0,0 +1,238 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/base64"
6
+ "encoding/json"
7
+ "errors"
8
+ "fmt"
9
+ "io"
10
+ "net/http"
11
+ "strings"
12
+
13
+ sshagentcrypt "github.com/131/ssh-agent-crypt"
14
+ "golang.org/x/crypto/ssh/agent"
15
+ )
16
+
17
+ // HTTPError reports an unexpected Vault status code.
18
+ type HTTPError struct {
19
+ Status int
20
+ Body string
21
+ }
22
+
23
+ func (e *HTTPError) Error() string {
24
+ return fmt.Sprintf("Unexpected status %d: %s", e.Status, e.Body)
25
+ }
26
+
27
+ // auth is the Vault auth block of a login or renewal response.
28
+ type auth struct {
29
+ ClientToken string `json:"client_token"`
30
+ LeaseDuration int64 `json:"lease_duration"`
31
+ Renewable bool `json:"renewable"`
32
+ }
33
+
34
+ // lookup is the relevant part of auth/token/lookup-self.
35
+ type lookup struct {
36
+ TTL float64 `json:"ttl"`
37
+ Renewable bool `json:"renewable"`
38
+ CreationTTL int64 `json:"creation_ttl"`
39
+ EntityID string `json:"entity_id"`
40
+ }
41
+
42
+ func (v *Vauth) vaultURL(path string) string {
43
+ return strings.TrimRight(v.VaultAddr, "/") + "/v1/" + strings.TrimLeft(path, "/")
44
+ }
45
+
46
+ // request performs a Vault API call. A JSON payload is sent when non-nil.
47
+ // With expect > 0, another status is returned as *HTTPError.
48
+ func (v *Vauth) request(method, path, token string, payload any, expect int) (int, []byte, error) {
49
+ var body io.Reader
50
+ if payload != nil {
51
+ encoded, err := json.Marshal(payload)
52
+ if err != nil {
53
+ return 0, nil, err
54
+ }
55
+ body = bytes.NewReader(encoded)
56
+ }
57
+ req, err := http.NewRequest(method, v.vaultURL(path), body)
58
+ if err != nil {
59
+ return 0, nil, err
60
+ }
61
+ if payload != nil {
62
+ req.Header.Set("Content-Type", "application/json")
63
+ }
64
+ if token != "" {
65
+ req.Header.Set("X-Vault-Token", token)
66
+ }
67
+ res, err := v.httpClient().Do(req)
68
+ if err != nil {
69
+ return 0, nil, err
70
+ }
71
+ defer res.Body.Close()
72
+ response, err := io.ReadAll(res.Body)
73
+ if err != nil {
74
+ return res.StatusCode, nil, err
75
+ }
76
+ if expect > 0 && res.StatusCode != expect {
77
+ return res.StatusCode, response, &HTTPError{res.StatusCode, string(response)}
78
+ }
79
+ return res.StatusCode, response, nil
80
+ }
81
+
82
+ func (v *Vauth) httpClient() *http.Client {
83
+ if v.HTTPClient != nil {
84
+ return v.HTTPClient
85
+ }
86
+ return http.DefaultClient
87
+ }
88
+
89
+ func parseAuth(response []byte, invalid string) (*auth, error) {
90
+ var parsed struct {
91
+ Auth *auth `json:"auth"`
92
+ }
93
+ if err := json.Unmarshal(response, &parsed); err != nil || parsed.Auth == nil || parsed.Auth.ClientToken == "" || parsed.Auth.LeaseDuration < 0 {
94
+ return nil, errors.New(invalid)
95
+ }
96
+ return parsed.Auth, nil
97
+ }
98
+
99
+ func (v *Vauth) loginVault(path string, payload any) (*auth, error) {
100
+ status, response, err := v.request("POST", "auth/"+path+"/login", "", payload, 0)
101
+ if err != nil {
102
+ return nil, err
103
+ }
104
+ if status != 200 {
105
+ return nil, fmt.Errorf("Could not login to vault : %s", response)
106
+ }
107
+ return parseAuth(response, "Invalid Vault login response")
108
+ }
109
+
110
+ func (v *Vauth) loginVaultSSH(config *SSHAuth) (*auth, error) {
111
+ path := config.Path
112
+ if path == "" {
113
+ path = "ssh"
114
+ }
115
+ v.debug("Trying to auth as '%s'", config.Role)
116
+ conn, err := sshagentcrypt.DialAgent(v.Agent)
117
+ if err != nil {
118
+ return nil, fmt.Errorf("Could not reach ssh-agent at %s: %w", v.Agent, err)
119
+ }
120
+ defer conn.Close()
121
+ client := agent.NewClient(conn)
122
+ keys, err := client.List()
123
+ if err != nil {
124
+ return nil, fmt.Errorf("Unable to list ssh-agent keys: %w", err)
125
+ }
126
+ for _, key := range keys {
127
+ _, response, err := v.request("GET", "auth/"+path+"/nonce", "", nil, 200)
128
+ if err != nil {
129
+ return nil, err
130
+ }
131
+ var challenge struct {
132
+ Data struct {
133
+ Nonce string `json:"nonce"`
134
+ } `json:"data"`
135
+ }
136
+ if err := json.Unmarshal(response, &challenge); err != nil {
137
+ return nil, fmt.Errorf("Invalid nonce response: %w", err)
138
+ }
139
+ nonce := []byte(challenge.Data.Nonce)
140
+ signature, err := client.Sign(key, nonce)
141
+ if err != nil {
142
+ v.debug("ssh : agent refused to sign with public key %s", key.Comment)
143
+ continue
144
+ }
145
+ payload := map[string]string{
146
+ "public_key": key.Type() + " " + base64.StdEncoding.EncodeToString(key.Marshal()),
147
+ "role": config.Role,
148
+ "nonce": base64.StdEncoding.EncodeToString(nonce),
149
+ "signature": base64.StdEncoding.EncodeToString(signature.Blob),
150
+ }
151
+ auth, err := v.loginVault(path, payload)
152
+ if err != nil {
153
+ v.debug("ssh : invalid challenge for public key %s", key.Comment)
154
+ continue
155
+ }
156
+ return auth, nil
157
+ }
158
+ return nil, errors.New("Could not login to vault")
159
+ }
160
+
161
+ func (v *Vauth) lookupToken(token string) (*lookup, int64, error) {
162
+ _, response, err := v.request("GET", "auth/token/lookup-self", token, nil, 200)
163
+ if err != nil {
164
+ return nil, 0, err
165
+ }
166
+ var parsed struct {
167
+ Data *lookup `json:"data"`
168
+ }
169
+ if err := json.Unmarshal(response, &parsed); err != nil || parsed.Data == nil || parsed.Data.TTL < 0 {
170
+ return nil, 0, errors.New("Invalid Vault token TTL")
171
+ }
172
+ lease := parsed.Data.CreationTTL
173
+ if cached := v.readTokenCache(); cached != nil && cached.Token == token {
174
+ lease = cached.LeaseDuration
175
+ }
176
+ return parsed.Data, lease, nil
177
+ }
178
+
179
+ func (v *Vauth) renewToken(token string) (*auth, error) {
180
+ _, response, err := v.request("POST", "auth/token/renew-self", token, map[string]any{}, 200)
181
+ if err != nil {
182
+ return nil, err
183
+ }
184
+ return parseAuth(response, "Invalid Vault token renewal response")
185
+ }
186
+
187
+ func (v *Vauth) lookupIdentity(token, id string) (map[string]any, error) {
188
+ _, response, err := v.request("GET", "identity/entity/id/"+id, token, nil, 200)
189
+ if err != nil {
190
+ return nil, err
191
+ }
192
+ var parsed struct {
193
+ Data struct {
194
+ Metadata map[string]any `json:"metadata"`
195
+ } `json:"data"`
196
+ }
197
+ if err := json.Unmarshal(response, &parsed); err != nil {
198
+ return nil, fmt.Errorf("Invalid identity response: %w", err)
199
+ }
200
+ return parsed.Data.Metadata, nil
201
+ }
202
+
203
+ // vaultRead returns the data of a kv2 secret.
204
+ func (v *Vauth) vaultRead(mount, secretPath string, optional bool) (map[string]any, error) {
205
+ secretPath = strings.Trim(secretPath, "/")
206
+ status, response, err := v.request("GET", mount+"/data/"+secretPath, v.VaultToken, nil, 0)
207
+ if err != nil {
208
+ return nil, err
209
+ }
210
+ if optional && status == 404 {
211
+ return map[string]any{}, nil
212
+ }
213
+ if status != 200 {
214
+ return nil, fmt.Errorf("Could not read vault secret '%s/%s' : %s", mount, secretPath, response)
215
+ }
216
+ var parsed struct {
217
+ Data struct {
218
+ Data map[string]any `json:"data"`
219
+ } `json:"data"`
220
+ }
221
+ if err := json.Unmarshal(response, &parsed); err != nil {
222
+ return nil, fmt.Errorf("Invalid secret response for '%s/%s': %w", mount, secretPath, err)
223
+ }
224
+ return parsed.Data.Data, nil
225
+ }
226
+
227
+ // vaultWrite replaces the data of a kv2 secret.
228
+ func (v *Vauth) vaultWrite(mount, secretPath string, data map[string]any) error {
229
+ secretPath = strings.Trim(secretPath, "/")
230
+ status, response, err := v.request("POST", mount+"/data/"+secretPath, v.VaultToken, map[string]any{"data": data}, 0)
231
+ if err != nil {
232
+ return err
233
+ }
234
+ if status != 200 {
235
+ return fmt.Errorf("Could not write vault secret '%s/%s' : %s", mount, secretPath, response)
236
+ }
237
+ return nil
238
+ }