vvauth 2.4.0 → 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/vauth.go ADDED
@@ -0,0 +1,518 @@
1
+ // Package vvauth logs into HashiCorp Vault (ssh-agent challenge or jwt),
2
+ // caches the token with ssh-agent-crypt and resolves the environment
3
+ // declared by .vauthrc. It is the Go counterpart of the vvauth npm package.
4
+ package vvauth
5
+
6
+ import (
7
+ "bufio"
8
+ "encoding/json"
9
+ "errors"
10
+ "fmt"
11
+ "io"
12
+ "net/http"
13
+ "os"
14
+ "os/exec"
15
+ "path/filepath"
16
+ "regexp"
17
+ "strings"
18
+ "time"
19
+
20
+ sshagentcrypt "github.com/131/ssh-agent-crypt"
21
+ )
22
+
23
+ // FunctionName is the shell function installed by Install.
24
+ const FunctionName = "venv"
25
+
26
+ // FunctionDecl is the bash declaration of FunctionName.
27
+ const FunctionDecl = `function ` + FunctionName + `() { source <(/usr/bin/env vauth env --source "$@"); }`
28
+
29
+ // Vauth is a configured client. New builds one from the process environment;
30
+ // fields may be set directly for programmatic use.
31
+ type Vauth struct {
32
+ RC RC
33
+ VaultAddr string
34
+ VaultToken string
35
+ // Agent is the ssh-agent address; empty disables ssh authentication.
36
+ Agent string
37
+ // TokenCache enables the on-disk token cache in CacheDir.
38
+ TokenCache bool
39
+ CacheDir string
40
+ HomeDir string
41
+ // Environ is the process environment snapshot used for macros.
42
+ Environ map[string]string
43
+ // Stdout/Stderr/Stdin default to the process streams.
44
+ Stdout io.Writer
45
+ Stderr io.Writer
46
+ Stdin io.Reader
47
+ HTTPClient *http.Client
48
+ // Now overrides the clock (tests).
49
+ Now func() time.Time
50
+
51
+ connected bool
52
+ }
53
+
54
+ // token is an established token with its remaining validity.
55
+ type token struct {
56
+ Value string
57
+ TTL float64 // seconds; 0 means unlimited
58
+ LeaseDuration int64
59
+ Renewable bool
60
+ }
61
+
62
+ // Environ converts os.Environ() into a map.
63
+ func Environ() map[string]string {
64
+ environ := map[string]string{}
65
+ for _, entry := range os.Environ() {
66
+ if key, value, ok := strings.Cut(entry, "="); ok {
67
+ environ[key] = value
68
+ }
69
+ }
70
+ return environ
71
+ }
72
+
73
+ // New loads the configuration from the environment and the first .vauthrc
74
+ // found (VAUTHRC, ./.vauthrc, ~/.vauthrc).
75
+ func New() (*Vauth, error) {
76
+ environ := Environ()
77
+ home, _ := os.UserHomeDir()
78
+ cwd, _ := os.Getwd()
79
+ v := &Vauth{
80
+ Agent: sshagentcrypt.DefaultAgentAddress(),
81
+ TokenCache: true,
82
+ HomeDir: home,
83
+ CacheDir: filepath.Join(home, ".vauth", "tokens"),
84
+ Environ: environ,
85
+ }
86
+ if file := LocateRC(environ, cwd, home); file != "" {
87
+ body, err := os.ReadFile(file)
88
+ if err != nil {
89
+ return nil, err
90
+ }
91
+ rc, err := ParseRC(body, file, environ)
92
+ if err != nil {
93
+ return nil, err
94
+ }
95
+ v.RC = *rc
96
+ }
97
+ if v.RC.TokenCache != nil && !*v.RC.TokenCache {
98
+ v.TokenCache = false
99
+ }
100
+ if v.Agent == "" {
101
+ v.TokenCache = false
102
+ }
103
+ v.VaultAddr = v.RC.VaultAddr
104
+ if v.VaultAddr == "" {
105
+ v.VaultAddr = environ["VAULT_ADDR"]
106
+ }
107
+ v.VaultToken = environ["VAULT_TOKEN"]
108
+ if v.VaultAddr == "" {
109
+ fmt.Fprintln(v.stderr(), "Not bound to any vault")
110
+ }
111
+ return v, nil
112
+ }
113
+
114
+ func (v *Vauth) stdout() io.Writer {
115
+ if v.Stdout != nil {
116
+ return v.Stdout
117
+ }
118
+ return os.Stdout
119
+ }
120
+
121
+ func (v *Vauth) stderr() io.Writer {
122
+ if v.Stderr != nil {
123
+ return v.Stderr
124
+ }
125
+ return os.Stderr
126
+ }
127
+
128
+ func (v *Vauth) stdin() io.Reader {
129
+ if v.Stdin != nil {
130
+ return v.Stdin
131
+ }
132
+ return os.Stdin
133
+ }
134
+
135
+ func (v *Vauth) now() time.Time {
136
+ if v.Now != nil {
137
+ return v.Now()
138
+ }
139
+ return time.Now()
140
+ }
141
+
142
+ func (v *Vauth) debug(format string, args ...any) {
143
+ if strings.Contains(v.Environ["DEBUG"], "vvauth") {
144
+ fmt.Fprintf(v.stderr(), "vvauth "+format+"\n", args...)
145
+ }
146
+ }
147
+
148
+ func (v *Vauth) tokenStatus(operation string, token *token) {
149
+ validity := "valid indefinitely"
150
+ if token.TTL != 0 {
151
+ validity = HumanDiff(token.TTL, 2)
152
+ }
153
+ fmt.Fprintf(v.stderr(), "Vauth token: %s · %s · %s\n", operation, v.VaultAddr, validity)
154
+ }
155
+
156
+ // Connect establishes VaultToken: the environment token, then the cached one
157
+ // (renewed in the last third of its lease), then a new login. With renew, a
158
+ // new login is forced. Without an authentication method, no token is used.
159
+ func (v *Vauth) Connect(renew bool) (string, error) {
160
+ if v.RC.SSHAuth == nil && v.RC.JWTAuth == nil {
161
+ v.VaultToken = ""
162
+ return "", nil
163
+ }
164
+ if v.connected && !renew {
165
+ return v.VaultToken, nil
166
+ }
167
+ v.connected = false
168
+
169
+ cached := v.readTokenCache()
170
+ current := v.VaultToken
171
+ if current == "" && cached != nil {
172
+ current = cached.Token
173
+ }
174
+ hadToken := current != ""
175
+ operation := "reused"
176
+ now := v.now().UnixMilli()
177
+ if renew || (cached != nil && current == cached.Token && cached.ExpiresAt != nil && *cached.ExpiresAt <= now) {
178
+ current = ""
179
+ }
180
+
181
+ var established *token
182
+ if current != "" {
183
+ established = &token{Value: current}
184
+ if cached != nil && cached.Token == current {
185
+ established.LeaseDuration, established.Renewable = cached.LeaseDuration, cached.Renewable
186
+ if cached.ExpiresAt != nil {
187
+ established.TTL = float64(*cached.ExpiresAt-now) / 1000
188
+ }
189
+ } else {
190
+ info, lease, err := v.lookupToken(current)
191
+ if err := reauthenticable(err); err != nil {
192
+ return "", err
193
+ }
194
+ if err != nil {
195
+ established = nil
196
+ } else {
197
+ established.TTL, established.Renewable, established.LeaseDuration = info.TTL, info.Renewable, lease
198
+ }
199
+ }
200
+ if established != nil && established.TTL > 0 && established.TTL <= float64(established.LeaseDuration)/3 {
201
+ if established.Renewable {
202
+ renewed, err := v.renewToken(current)
203
+ if err := reauthenticable(err); err != nil {
204
+ return "", err
205
+ }
206
+ if err != nil {
207
+ established = nil
208
+ } else {
209
+ established = fromAuth(renewed)
210
+ operation = "renewed"
211
+ }
212
+ } else {
213
+ established = nil
214
+ }
215
+ }
216
+ }
217
+
218
+ if established == nil {
219
+ var granted *auth
220
+ var err error
221
+ if v.RC.SSHAuth != nil && v.Agent != "" {
222
+ granted, err = v.loginVaultSSH(v.RC.SSHAuth)
223
+ } else if v.RC.JWTAuth != nil && v.RC.JWTAuth.JWT != "" {
224
+ path := v.RC.JWTAuth.Path
225
+ if path == "" {
226
+ path = "jwt"
227
+ }
228
+ granted, err = v.loginVault(path, map[string]string{"jwt": v.RC.JWTAuth.JWT, "role": v.RC.JWTAuth.Role})
229
+ }
230
+ if err != nil {
231
+ return "", err
232
+ }
233
+ if granted == nil {
234
+ if renew || hadToken {
235
+ return "", errors.New("Could not login to vault: no authentication method available")
236
+ }
237
+ } else {
238
+ established = fromAuth(granted)
239
+ }
240
+ operation = "generated"
241
+ }
242
+
243
+ v.VaultToken = ""
244
+ if established != nil {
245
+ if operation != "reused" || cached == nil || cached.Token != established.Value {
246
+ v.saveTokenCache(established)
247
+ }
248
+ v.tokenStatus(operation, established)
249
+ v.VaultToken = established.Value
250
+ }
251
+ v.connected = true
252
+ return v.VaultToken, nil
253
+ }
254
+
255
+ // reauthenticable returns err unless it is an invalid token (400/403), in
256
+ // which case a new login is appropriate.
257
+ func reauthenticable(err error) error {
258
+ var failure *HTTPError
259
+ if err == nil || (errors.As(err, &failure) && (failure.Status == 400 || failure.Status == 403)) {
260
+ return nil
261
+ }
262
+ return err
263
+ }
264
+
265
+ func fromAuth(granted *auth) *token {
266
+ return &token{Value: granted.ClientToken, TTL: float64(granted.LeaseDuration), LeaseDuration: granted.LeaseDuration, Renewable: granted.Renewable}
267
+ }
268
+
269
+ // Profile is the Vault identity of the token: entity metadata and the
270
+ // private .vauth_database of VAUTH_USER_LOGIN.
271
+ type Profile struct {
272
+ EntityID string
273
+ Metadata map[string]any
274
+ Database map[string]any
275
+ }
276
+
277
+ // Merged returns the metadata over the database.
278
+ func (p *Profile) Merged() map[string]any {
279
+ merged := map[string]any{}
280
+ for k, val := range p.Database {
281
+ merged[k] = val
282
+ }
283
+ for k, val := range p.Metadata {
284
+ merged[k] = val
285
+ }
286
+ return merged
287
+ }
288
+
289
+ // GetProfile connects and reads the identity profile. Without token, the
290
+ // profile is empty.
291
+ func (v *Vauth) GetProfile(renew bool) (*Profile, error) {
292
+ if _, err := v.Connect(renew); err != nil {
293
+ return nil, err
294
+ }
295
+ profile := &Profile{Metadata: map[string]any{}, Database: map[string]any{}}
296
+ if v.VaultToken == "" {
297
+ return profile, nil
298
+ }
299
+ info, _, err := v.lookupToken(v.VaultToken)
300
+ if err != nil {
301
+ return nil, err
302
+ }
303
+ metadata, err := v.lookupIdentity(v.VaultToken, info.EntityID)
304
+ if err != nil {
305
+ return nil, err
306
+ }
307
+ profile.EntityID = info.EntityID
308
+ if metadata != nil {
309
+ profile.Metadata = metadata
310
+ }
311
+ if login, _ := stringify(metadata["VAUTH_USER_LOGIN"]); login != "" {
312
+ database, err := v.vaultRead("private/"+login, ".vauth_database", true)
313
+ if err != nil {
314
+ return nil, err
315
+ }
316
+ if database != nil {
317
+ profile.Database = database
318
+ }
319
+ }
320
+ return profile, nil
321
+ }
322
+
323
+ // Set stores an upper-cased key in the user's .vauth_database.
324
+ func (v *Vauth) Set(key, value string) error {
325
+ return v.update(strings.ToUpper(key), value, true)
326
+ }
327
+
328
+ // Unset removes a key from the user's .vauth_database.
329
+ func (v *Vauth) Unset(key string) error {
330
+ return v.update(strings.ToUpper(key), "", false)
331
+ }
332
+
333
+ func (v *Vauth) update(key, value string, set bool) error {
334
+ profile, err := v.GetProfile(false)
335
+ if err != nil {
336
+ return err
337
+ }
338
+ login, _ := stringify(profile.Metadata["VAUTH_USER_LOGIN"])
339
+ if login == "" {
340
+ return errors.New("Could not resolve VAUTH_USER_LOGIN from vault identity")
341
+ }
342
+ if set {
343
+ profile.Database[key] = value
344
+ } else {
345
+ delete(profile.Database, key)
346
+ }
347
+ return v.vaultWrite("private/"+login, ".vauth_database", profile.Database)
348
+ }
349
+
350
+ // Show returns the merged profile.
351
+ func (v *Vauth) Show() (map[string]any, error) {
352
+ profile, err := v.GetProfile(false)
353
+ if err != nil {
354
+ return nil, err
355
+ }
356
+ return profile.Merged(), nil
357
+ }
358
+
359
+ // Env resolves the environment declared by .vauthrc: VAULT_TOKEN and
360
+ // VAULT_ADDR, then env.map with $${env|profile|secrets.X} expanded.
361
+ func (v *Vauth) Env(renew bool) (*OrderedMap, error) {
362
+ profile, err := v.GetProfile(renew)
363
+ if err != nil {
364
+ return nil, err
365
+ }
366
+ env := &OrderedMap{}
367
+ if v.VaultToken != "" {
368
+ env.Set("VAULT_TOKEN", v.VaultToken)
369
+ }
370
+ if v.VaultAddr != "" {
371
+ env.Set("VAULT_ADDR", v.VaultAddr)
372
+ }
373
+
374
+ config := v.RC.Env
375
+ if config == nil {
376
+ config = &EnvConfig{}
377
+ }
378
+ secrets := map[string]any{}
379
+ if v.RC.AgentCrypt != nil {
380
+ armor, err := os.ReadFile(v.RC.AgentCrypt.Path)
381
+ if err != nil {
382
+ return nil, err
383
+ }
384
+ body, err := sshagentcrypt.Decrypt(armor, v.RC.AgentCrypt.Identity, v.agentOptions())
385
+ if err != nil {
386
+ return nil, err
387
+ }
388
+ if err := json.Unmarshal(body, &secrets); err != nil {
389
+ return nil, fmt.Errorf("Invalid ssh-agent-crypt payload %s: %w", v.RC.AgentCrypt.Path, err)
390
+ }
391
+ }
392
+
393
+ mapping := OrderedMap{}
394
+ for _, key := range config.Map.Keys {
395
+ mapping.Set(key, config.Map.Values[key])
396
+ }
397
+ merged := profile.Merged()
398
+ if config.Git {
399
+ mapping.Set("GIT_COMMITTER_NAME", "$${profile.VAUTH_USER_NAME}")
400
+ mapping.Set("GIT_COMMITTER_EMAIL", "$${profile.VAUTH_USER_MAIL}")
401
+ mapping.Set("GIT_AUTHOR_EMAIL", "$${profile.VAUTH_USER_MAIL}")
402
+ mapping.Set("GIT_AUTHOR_NAME", "$${profile.VAUTH_USER_NAME}")
403
+ mapping.Set("GIT_USER_LOGIN", "$${profile.VAUTH_USER_LOGIN}")
404
+ }
405
+ mount := config.Path
406
+ if mount == "" {
407
+ mount = "secrets"
408
+ }
409
+ for _, secretPath := range config.Paths {
410
+ fmt.Fprintln(v.stderr(), "reaching paths", secretPath)
411
+ data, err := v.vaultRead(mount, secretPath, false)
412
+ if err != nil {
413
+ return nil, err
414
+ }
415
+ for k, val := range data {
416
+ secrets[k] = val
417
+ }
418
+ }
419
+ dict := Lookup{"env": v.Environ, "profile": merged, "secrets": secrets}
420
+ for _, key := range mapping.Keys {
421
+ env.Set(key, ReplaceEnv(mapping.Values[key], dict))
422
+ }
423
+ return env, nil
424
+ }
425
+
426
+ // Login connects, and with source publishes VAULT_TOKEN as shell exports.
427
+ func (v *Vauth) Login(source, renew bool) error {
428
+ if _, err := v.Connect(renew); err != nil {
429
+ return err
430
+ }
431
+ if source {
432
+ env := &OrderedMap{}
433
+ env.Set("VAULT_TOKEN", v.VaultToken)
434
+ v.PublishEnv(env)
435
+ }
436
+ return nil
437
+ }
438
+
439
+ // PublishEnv writes `export K='v'` lines to stdout, each followed by an echo
440
+ // of the redacted assignment to stderr for the sourcing shell.
441
+ func (v *Vauth) PublishEnv(env *OrderedMap) {
442
+ var lines []string
443
+ for _, key := range env.Keys {
444
+ lines = append(lines, fmt.Sprintf("export %s=%s", key, ShellEscape(env.Values[key])))
445
+ lines = append(lines, fmt.Sprintf(`echo export %s="[redacted]" >&2`, key))
446
+ }
447
+ fmt.Fprint(v.stdout(), strings.Join(lines, "\n")+"\n")
448
+ }
449
+
450
+ // ShellEscape single-quotes a value for bash.
451
+ func ShellEscape(value string) string {
452
+ return "'" + strings.ReplaceAll(value, "'", `'"'"'`) + "'"
453
+ }
454
+
455
+ // Dotenv writes `K=v` lines to stdout and redacted exports to stderr.
456
+ func (v *Vauth) Dotenv() error {
457
+ env, err := v.Env(false)
458
+ if err != nil {
459
+ return err
460
+ }
461
+ for _, key := range env.Keys {
462
+ fmt.Fprintf(v.stdout(), "%s=%s\n", key, env.Values[key])
463
+ fmt.Fprintf(v.stderr(), "export %s=[redacted]\n", key)
464
+ }
465
+ return nil
466
+ }
467
+
468
+ // Run executes a command with the resolved environment merged over the
469
+ // process environment and returns its exit code.
470
+ func (v *Vauth) Run(command string, args ...string) (int, error) {
471
+ env, err := v.Env(false)
472
+ if err != nil {
473
+ return 1, err
474
+ }
475
+ cmd := exec.Command(command, args...)
476
+ cmd.Env = os.Environ()
477
+ for _, key := range env.Keys {
478
+ cmd.Env = append(cmd.Env, key+"="+env.Values[key])
479
+ }
480
+ cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
481
+ err = cmd.Run()
482
+ var exit *exec.ExitError
483
+ if errors.As(err, &exit) {
484
+ return exit.ExitCode(), nil
485
+ }
486
+ if err != nil {
487
+ return 1, fmt.Errorf("run failure : %w", err)
488
+ }
489
+ return 0, nil
490
+ }
491
+
492
+ // FunctionExists reports whether a bash login shell already defines alias.
493
+ func FunctionExists(alias string) bool {
494
+ return exec.Command("bash", "-lc", "declare -F "+alias).Run() == nil
495
+ }
496
+
497
+ var yes = regexp.MustCompile(`(?i)^y(es)?$`)
498
+
499
+ // Install appends FunctionDecl to ~/.bashrc, asking before overriding an
500
+ // existing definition.
501
+ func (v *Vauth) Install() error {
502
+ bashrcPath := filepath.Join(v.HomeDir, ".bashrc")
503
+ body, _ := os.ReadFile(bashrcPath)
504
+ bashrc := strings.TrimSpace(string(body))
505
+ if FunctionExists(FunctionName) {
506
+ fmt.Fprint(v.stdout(), "Function already defined, override current definition? [y/N] ")
507
+ answer, _ := bufio.NewReader(v.stdin()).ReadString('\n')
508
+ if !yes.MatchString(strings.TrimSpace(answer)) {
509
+ return nil
510
+ }
511
+ }
512
+ fmt.Fprintf(v.stderr(), "Installing function %s in %s\n", FunctionName, bashrcPath)
513
+ if err := os.WriteFile(bashrcPath, []byte(bashrc+"\n"+FunctionDecl+"\n"), 0o644); err != nil {
514
+ return err
515
+ }
516
+ fmt.Fprintf(v.stderr(), "Installation ok, please \nsource %s\n", bashrcPath)
517
+ return nil
518
+ }