vvauth 2.5.0 → 2.6.1

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 CHANGED
@@ -1,6 +1,5 @@
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.
1
+ // Package vvauth resolves the environment and profile declared by .vauthrc.
2
+ // Authentication, token caching and HTTP transport belong to vauth-login.
4
3
  package vvauth
5
4
 
6
5
  import (
@@ -9,17 +8,27 @@ import (
9
8
  "errors"
10
9
  "fmt"
11
10
  "io"
12
- "net/http"
13
11
  "os"
14
12
  "os/exec"
15
13
  "path/filepath"
16
14
  "regexp"
17
15
  "strings"
18
- "time"
19
16
 
17
+ nyksstring "github.com/131/nyks/v6/string"
20
18
  sshagentcrypt "github.com/131/ssh-agent-crypt"
19
+ vauthlogin "github.com/131/vauth-login"
20
+ "github.com/Masterminds/semver/v3"
21
21
  )
22
22
 
23
+ // PackageName is the npm name a project uses to pin vauth:
24
+ // `"dependencies": {"vvauth": "^2.5.0"}` in its package.json.
25
+ const PackageName = "vvauth"
26
+
27
+ // Version is the running version (ldflags -X or debug.ReadBuildInfo), checked
28
+ // by New against the current directory's package.json; empty or non-semver
29
+ // values ("(devel)") skip the check.
30
+ var Version string
31
+
23
32
  // FunctionName is the shell function installed by Install.
24
33
  const FunctionName = "venv"
25
34
 
@@ -29,83 +38,76 @@ const FunctionDecl = `function ` + FunctionName + `() { source <(/usr/bin/env va
29
38
  // Vauth is a configured client. New builds one from the process environment;
30
39
  // fields may be set directly for programmatic use.
31
40
  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
41
+ *vauthlogin.Vauth
42
+ Config Config
43
+ Stdout io.Writer
44
+ Stdin io.Reader
60
45
  }
61
46
 
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
- }
47
+ // CheckProjectVersion fails when manifest (a package.json) declares a
48
+ // dependency on PackageName that version does not satisfy. A missing manifest,
49
+ // dependency or unparseable version is not an error.
50
+ func CheckProjectVersion(manifest, version string) error {
51
+ body, err := os.ReadFile(manifest)
52
+ if err != nil {
53
+ return nil
69
54
  }
70
- return environ
55
+ var pkg struct {
56
+ Dependencies map[string]string `json:"dependencies"`
57
+ }
58
+ if json.Unmarshal(body, &pkg) != nil {
59
+ return nil
60
+ }
61
+ required, ok := pkg.Dependencies[PackageName]
62
+ if !ok || required == "" {
63
+ return nil
64
+ }
65
+ current, err := semver.NewVersion(version)
66
+ if err != nil {
67
+ return nil
68
+ }
69
+ constraint, err := semver.NewConstraint(required)
70
+ if err != nil {
71
+ return fmt.Errorf("Invalid %s version requirement '%s' in %s", PackageName, required, manifest)
72
+ }
73
+ if !constraint.Check(current) {
74
+ return fmt.Errorf("Unsupported %s version %s (project requires %s)", PackageName, version, required)
75
+ }
76
+ return nil
71
77
  }
72
78
 
73
- // New loads the configuration from the environment and the first .vauthrc
74
- // found (VAUTHRC, ./.vauthrc, ~/.vauthrc).
79
+ // New loads authentication through vauth-login, then the environment/profile
80
+ // configuration from the same selected .vauthrc.
75
81
  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
82
+ cwd, err := os.Getwd()
83
+ if err != nil {
84
+ return nil, err
96
85
  }
97
- if v.RC.TokenCache != nil && !*v.RC.TokenCache {
98
- v.TokenCache = false
86
+ if err := CheckProjectVersion(filepath.Join(cwd, "package.json"), Version); err != nil {
87
+ return nil, err
99
88
  }
100
- if v.Agent == "" {
101
- v.TokenCache = false
89
+ login, err := vauthlogin.New()
90
+ if err != nil {
91
+ return nil, err
102
92
  }
103
- v.VaultAddr = v.RC.VaultAddr
104
- if v.VaultAddr == "" {
105
- v.VaultAddr = environ["VAULT_ADDR"]
93
+ v := &Vauth{Vauth: login}
94
+ config, err := configFromRC(login.RC(), login.Environ)
95
+ if err != nil {
96
+ return nil, err
97
+ }
98
+ v.Config = *config
99
+ if v.Config.Env != nil && v.Config.Env.GitLab {
100
+ var missing []string
101
+ for _, key := range []string{"CI_PROJECT_PATH", "CI_PROJECT_NAME", "CI_PROJECT_NAMESPACE", "CI_PROJECT_PATH_SLUG"} {
102
+ if v.Environ[key] == "" {
103
+ missing = append(missing, key)
104
+ }
105
+ }
106
+ if len(missing) != 0 {
107
+ return nil, fmt.Errorf("Missing %s. Run venv --gitlab first.", strings.Join(missing, ", "))
108
+ }
106
109
  }
107
- v.VaultToken = environ["VAULT_TOKEN"]
108
- if v.VaultAddr == "" {
110
+ if v.VAULT_ADDR() == "" {
109
111
  fmt.Fprintln(v.stderr(), "Not bound to any vault")
110
112
  }
111
113
  return v, nil
@@ -132,140 +134,6 @@ func (v *Vauth) stdin() io.Reader {
132
134
  return os.Stdin
133
135
  }
134
136
 
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
137
  // Profile is the Vault identity of the token: entity metadata and the
270
138
  // private .vauth_database of VAUTH_USER_LOGIN.
271
139
  type Profile struct {
@@ -293,22 +161,30 @@ func (v *Vauth) GetProfile(renew bool) (*Profile, error) {
293
161
  return nil, err
294
162
  }
295
163
  profile := &Profile{Metadata: map[string]any{}, Database: map[string]any{}}
296
- if v.VaultToken == "" {
164
+ if v.VAULT_TOKEN() == "" || v.VAULT_ADDR() == "" {
297
165
  return profile, nil
298
166
  }
299
- info, _, err := v.lookupToken(v.VaultToken)
167
+ info, err := v.LookupSelf(v.VAULT_TOKEN())
300
168
  if err != nil {
301
169
  return nil, err
302
170
  }
303
- metadata, err := v.lookupIdentity(v.VaultToken, info.EntityID)
171
+ _, response, err := v.Request("GET", "identity/entity/id/"+info.EntityID, v.VAULT_TOKEN(), nil, 200)
304
172
  if err != nil {
305
173
  return nil, err
306
174
  }
175
+ var identity struct {
176
+ Data struct {
177
+ Metadata map[string]any `json:"metadata"`
178
+ } `json:"data"`
179
+ }
180
+ if err := json.Unmarshal(response, &identity); err != nil {
181
+ return nil, fmt.Errorf("Invalid identity response: %w", err)
182
+ }
307
183
  profile.EntityID = info.EntityID
308
- if metadata != nil {
309
- profile.Metadata = metadata
184
+ if identity.Data.Metadata != nil {
185
+ profile.Metadata = identity.Data.Metadata
310
186
  }
311
- if login, _ := stringify(metadata["VAUTH_USER_LOGIN"]); login != "" {
187
+ if login, _ := stringify(profile.Metadata["VAUTH_USER_LOGIN"]); login != "" {
312
188
  database, err := v.vaultRead("private/"+login, ".vauth_database", true)
313
189
  if err != nil {
314
190
  return nil, err
@@ -359,34 +235,44 @@ func (v *Vauth) Show() (map[string]any, error) {
359
235
  // Env resolves the environment declared by .vauthrc: VAULT_TOKEN and
360
236
  // VAULT_ADDR, then env.map with $${env|profile|secrets.X} expanded.
361
237
  func (v *Vauth) Env(renew bool) (*OrderedMap, error) {
362
- profile, err := v.GetProfile(renew)
363
- if err != nil {
364
- return nil, err
238
+ config := v.Config.Env
239
+ if config == nil {
240
+ config = &EnvConfig{}
241
+ }
242
+ profile := &Profile{Metadata: map[string]any{}, Database: map[string]any{}}
243
+ rc := v.RC()
244
+ localCredentials := v.Config.AgentCrypt != nil && rc["ssh_auth"] == nil && rc["jwt_auth"] == nil
245
+ if localCredentials {
246
+ if _, err := v.Connect(renew); err != nil {
247
+ return nil, err
248
+ }
249
+ } else {
250
+ var err error
251
+ profile, err = v.GetProfile(renew)
252
+ if err != nil {
253
+ return nil, err
254
+ }
365
255
  }
366
256
  env := &OrderedMap{}
367
- if v.VaultToken != "" {
368
- env.Set("VAULT_TOKEN", v.VaultToken)
257
+ if v.VAULT_TOKEN() != "" {
258
+ env.Set("VAULT_TOKEN", v.VAULT_TOKEN())
369
259
  }
370
- if v.VaultAddr != "" {
371
- env.Set("VAULT_ADDR", v.VaultAddr)
260
+ if v.VAULT_ADDR() != "" {
261
+ env.Set("VAULT_ADDR", v.VAULT_ADDR())
372
262
  }
373
263
 
374
- config := v.RC.Env
375
- if config == nil {
376
- config = &EnvConfig{}
377
- }
378
264
  secrets := map[string]any{}
379
- if v.RC.AgentCrypt != nil {
380
- armor, err := os.ReadFile(v.RC.AgentCrypt.Path)
265
+ if v.Config.AgentCrypt != nil {
266
+ armor, err := os.ReadFile(v.Config.AgentCrypt.Path)
381
267
  if err != nil {
382
268
  return nil, err
383
269
  }
384
- body, err := sshagentcrypt.Decrypt(armor, v.RC.AgentCrypt.Identity, v.agentOptions())
270
+ body, err := sshagentcrypt.Decrypt(armor, v.Config.AgentCrypt.Identity, &sshagentcrypt.Options{AgentSocket: v.Agent})
385
271
  if err != nil {
386
272
  return nil, err
387
273
  }
388
274
  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)
275
+ return nil, fmt.Errorf("Invalid ssh-agent-crypt payload %s: %w", v.Config.AgentCrypt.Path, err)
390
276
  }
391
277
  }
392
278
 
@@ -396,11 +282,19 @@ func (v *Vauth) Env(renew bool) (*OrderedMap, error) {
396
282
  }
397
283
  merged := profile.Merged()
398
284
  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}")
285
+ for _, field := range [][2]string{
286
+ {"GIT_COMMITTER_NAME", "VAUTH_USER_NAME"},
287
+ {"GIT_COMMITTER_EMAIL", "VAUTH_USER_MAIL"},
288
+ {"GIT_AUTHOR_EMAIL", "VAUTH_USER_MAIL"},
289
+ {"GIT_AUTHOR_NAME", "VAUTH_USER_NAME"},
290
+ {"GIT_USER_LOGIN", "VAUTH_USER_LOGIN"},
291
+ } {
292
+ value, err := envValue(merged[field[1]])
293
+ if err != nil {
294
+ return nil, fmt.Errorf("Invalid environment value '%s' in env.map: %w", field[0], err)
295
+ }
296
+ mapping.Set(field[0], value)
297
+ }
404
298
  }
405
299
  mount := config.Path
406
300
  if mount == "" {
@@ -416,13 +310,24 @@ func (v *Vauth) Env(renew bool) (*OrderedMap, error) {
416
310
  secrets[k] = val
417
311
  }
418
312
  }
419
- dict := Lookup{"env": v.Environ, "profile": merged, "secrets": secrets}
313
+ dict := map[string]any{"env": v.Environ, "profile": merged, "secrets": secrets}
420
314
  for _, key := range mapping.Keys {
421
- env.Set(key, ReplaceEnv(mapping.Values[key], dict))
315
+ if !envName.MatchString(key) {
316
+ return nil, fmt.Errorf("Invalid environment variable name '%s' in env.map", key)
317
+ }
318
+ value, err := envValue(nyksstring.ReplaceEnv(mapping.Values[key], dict))
319
+ if err != nil {
320
+ return nil, fmt.Errorf("Invalid environment value '%s' in env.map: %w", key, err)
321
+ }
322
+ env.Set(key, value)
422
323
  }
423
324
  return env, nil
424
325
  }
425
326
 
327
+ // envName is the only shape of key that reaches `export KEY=...` unescaped;
328
+ // .vauthrc may come from an untrusted working directory.
329
+ var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
330
+
426
331
  // Login connects, and with source publishes VAULT_TOKEN as shell exports.
427
332
  func (v *Vauth) Login(source, renew bool) error {
428
333
  if _, err := v.Connect(renew); err != nil {
@@ -430,7 +335,7 @@ func (v *Vauth) Login(source, renew bool) error {
430
335
  }
431
336
  if source {
432
337
  env := &OrderedMap{}
433
- env.Set("VAULT_TOKEN", v.VaultToken)
338
+ env.Set("VAULT_TOKEN", v.VAULT_TOKEN())
434
339
  v.PublishEnv(env)
435
340
  }
436
341
  return nil
@@ -465,30 +370,6 @@ func (v *Vauth) Dotenv() error {
465
370
  return nil
466
371
  }
467
372
 
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
373
  // FunctionExists reports whether a bash login shell already defines alias.
493
374
  func FunctionExists(alias string) bool {
494
375
  return exec.Command("bash", "-lc", "declare -F "+alias).Run() == nil