vvauth 2.4.1 → 2.6.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/vault.go ADDED
@@ -0,0 +1,46 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "encoding/json"
5
+ "fmt"
6
+ "strings"
7
+
8
+ vauthlogin "github.com/131/vauth-login"
9
+ )
10
+
11
+ // vaultRead returns the data of a kv2 secret.
12
+ func (v *Vauth) vaultRead(mount, secretPath string, optional bool) (map[string]any, error) {
13
+ secretPath = strings.Trim(secretPath, "/")
14
+ status, response, err := v.Request("GET", mount+"/data/"+secretPath, v.VAULT_TOKEN(), nil, 0)
15
+ if err != nil {
16
+ return nil, err
17
+ }
18
+ if optional && status == 404 {
19
+ return map[string]any{}, nil
20
+ }
21
+ if status != 200 {
22
+ return nil, &vauthlogin.HTTPError{Status: status, Body: string(response)}
23
+ }
24
+ var parsed struct {
25
+ Data struct {
26
+ Data map[string]any `json:"data"`
27
+ } `json:"data"`
28
+ }
29
+ if err := json.Unmarshal(response, &parsed); err != nil {
30
+ return nil, fmt.Errorf("Invalid secret response for '%s/%s': %w", mount, secretPath, err)
31
+ }
32
+ return parsed.Data.Data, nil
33
+ }
34
+
35
+ // vaultWrite replaces the data of a kv2 secret.
36
+ func (v *Vauth) vaultWrite(mount, secretPath string, data map[string]any) error {
37
+ secretPath = strings.Trim(secretPath, "/")
38
+ status, response, err := v.Request("POST", mount+"/data/"+secretPath, v.VAULT_TOKEN(), map[string]any{"data": data}, 0)
39
+ if err != nil {
40
+ return err
41
+ }
42
+ if status != 200 {
43
+ return &vauthlogin.HTTPError{Status: status, Body: string(response)}
44
+ }
45
+ return nil
46
+ }
package/vauth.go ADDED
@@ -0,0 +1,399 @@
1
+ // Package vvauth resolves the environment and profile declared by .vauthrc.
2
+ // Authentication, token caching and HTTP transport belong to vauth-login.
3
+ package vvauth
4
+
5
+ import (
6
+ "bufio"
7
+ "encoding/json"
8
+ "errors"
9
+ "fmt"
10
+ "io"
11
+ "os"
12
+ "os/exec"
13
+ "path/filepath"
14
+ "regexp"
15
+ "strings"
16
+
17
+ sshagentcrypt "github.com/131/ssh-agent-crypt"
18
+ vauthlogin "github.com/131/vauth-login"
19
+ "github.com/Masterminds/semver/v3"
20
+ )
21
+
22
+ // PackageName is the npm name a project uses to pin vauth:
23
+ // `"dependencies": {"vvauth": "^2.5.0"}` in its package.json.
24
+ const PackageName = "vvauth"
25
+
26
+ // Version is the running version (ldflags -X or debug.ReadBuildInfo), checked
27
+ // by New against the current directory's package.json; empty or non-semver
28
+ // values ("(devel)") skip the check.
29
+ var Version string
30
+
31
+ // FunctionName is the shell function installed by Install.
32
+ const FunctionName = "venv"
33
+
34
+ // FunctionDecl is the bash declaration of FunctionName.
35
+ const FunctionDecl = `function ` + FunctionName + `() { source <(/usr/bin/env vauth env --source "$@"); }`
36
+
37
+ // Vauth is a configured client. New builds one from the process environment;
38
+ // fields may be set directly for programmatic use.
39
+ type Vauth struct {
40
+ *vauthlogin.Vauth
41
+ Config Config
42
+ Stdout io.Writer
43
+ Stdin io.Reader
44
+ }
45
+
46
+ // CheckProjectVersion fails when manifest (a package.json) declares a
47
+ // dependency on PackageName that version does not satisfy. A missing manifest,
48
+ // dependency or unparseable version is not an error.
49
+ func CheckProjectVersion(manifest, version string) error {
50
+ body, err := os.ReadFile(manifest)
51
+ if err != nil {
52
+ return nil
53
+ }
54
+ var pkg struct {
55
+ Dependencies map[string]string `json:"dependencies"`
56
+ }
57
+ if json.Unmarshal(body, &pkg) != nil {
58
+ return nil
59
+ }
60
+ required, ok := pkg.Dependencies[PackageName]
61
+ if !ok || required == "" {
62
+ return nil
63
+ }
64
+ current, err := semver.NewVersion(version)
65
+ if err != nil {
66
+ return nil
67
+ }
68
+ constraint, err := semver.NewConstraint(required)
69
+ if err != nil {
70
+ return fmt.Errorf("Invalid %s version requirement '%s' in %s", PackageName, required, manifest)
71
+ }
72
+ if !constraint.Check(current) {
73
+ return fmt.Errorf("Unsupported %s version %s (project requires %s)", PackageName, version, required)
74
+ }
75
+ return nil
76
+ }
77
+
78
+ // New loads authentication through vauth-login, then the environment/profile
79
+ // configuration from the same selected .vauthrc.
80
+ func New() (*Vauth, error) {
81
+ cwd, err := os.Getwd()
82
+ if err != nil {
83
+ return nil, err
84
+ }
85
+ if err := CheckProjectVersion(filepath.Join(cwd, "package.json"), Version); err != nil {
86
+ return nil, err
87
+ }
88
+ login, err := vauthlogin.New()
89
+ if err != nil {
90
+ return nil, err
91
+ }
92
+ v := &Vauth{Vauth: login}
93
+ config, err := configFromRC(login.RC(), cwd, login.Environ)
94
+ if err != nil {
95
+ return nil, err
96
+ }
97
+ v.Config = *config
98
+ if v.VAULT_ADDR() == "" {
99
+ fmt.Fprintln(v.stderr(), "Not bound to any vault")
100
+ }
101
+ return v, nil
102
+ }
103
+
104
+ func (v *Vauth) stdout() io.Writer {
105
+ if v.Stdout != nil {
106
+ return v.Stdout
107
+ }
108
+ return os.Stdout
109
+ }
110
+
111
+ func (v *Vauth) stderr() io.Writer {
112
+ if v.Stderr != nil {
113
+ return v.Stderr
114
+ }
115
+ return os.Stderr
116
+ }
117
+
118
+ func (v *Vauth) stdin() io.Reader {
119
+ if v.Stdin != nil {
120
+ return v.Stdin
121
+ }
122
+ return os.Stdin
123
+ }
124
+
125
+ // Profile is the Vault identity of the token: entity metadata and the
126
+ // private .vauth_database of VAUTH_USER_LOGIN.
127
+ type Profile struct {
128
+ EntityID string
129
+ Metadata map[string]any
130
+ Database map[string]any
131
+ }
132
+
133
+ // Merged returns the metadata over the database.
134
+ func (p *Profile) Merged() map[string]any {
135
+ merged := map[string]any{}
136
+ for k, val := range p.Database {
137
+ merged[k] = val
138
+ }
139
+ for k, val := range p.Metadata {
140
+ merged[k] = val
141
+ }
142
+ return merged
143
+ }
144
+
145
+ // GetProfile connects and reads the identity profile. Without token, the
146
+ // profile is empty.
147
+ func (v *Vauth) GetProfile(renew bool) (*Profile, error) {
148
+ if _, err := v.Connect(renew); err != nil {
149
+ return nil, err
150
+ }
151
+ profile := &Profile{Metadata: map[string]any{}, Database: map[string]any{}}
152
+ if v.VAULT_TOKEN() == "" || v.VAULT_ADDR() == "" {
153
+ return profile, nil
154
+ }
155
+ info, err := v.LookupSelf(v.VAULT_TOKEN())
156
+ if err != nil {
157
+ return nil, err
158
+ }
159
+ _, response, err := v.Request("GET", "identity/entity/id/"+info.EntityID, v.VAULT_TOKEN(), nil, 200)
160
+ if err != nil {
161
+ return nil, err
162
+ }
163
+ var identity struct {
164
+ Data struct {
165
+ Metadata map[string]any `json:"metadata"`
166
+ } `json:"data"`
167
+ }
168
+ if err := json.Unmarshal(response, &identity); err != nil {
169
+ return nil, fmt.Errorf("Invalid identity response: %w", err)
170
+ }
171
+ profile.EntityID = info.EntityID
172
+ if identity.Data.Metadata != nil {
173
+ profile.Metadata = identity.Data.Metadata
174
+ }
175
+ if login, _ := stringify(profile.Metadata["VAUTH_USER_LOGIN"]); login != "" {
176
+ database, err := v.vaultRead("private/"+login, ".vauth_database", true)
177
+ if err != nil {
178
+ return nil, err
179
+ }
180
+ if database != nil {
181
+ profile.Database = database
182
+ }
183
+ }
184
+ return profile, nil
185
+ }
186
+
187
+ // Set stores an upper-cased key in the user's .vauth_database.
188
+ func (v *Vauth) Set(key, value string) error {
189
+ return v.update(strings.ToUpper(key), value, true)
190
+ }
191
+
192
+ // Unset removes a key from the user's .vauth_database.
193
+ func (v *Vauth) Unset(key string) error {
194
+ return v.update(strings.ToUpper(key), "", false)
195
+ }
196
+
197
+ func (v *Vauth) update(key, value string, set bool) error {
198
+ profile, err := v.GetProfile(false)
199
+ if err != nil {
200
+ return err
201
+ }
202
+ login, _ := stringify(profile.Metadata["VAUTH_USER_LOGIN"])
203
+ if login == "" {
204
+ return errors.New("Could not resolve VAUTH_USER_LOGIN from vault identity")
205
+ }
206
+ if set {
207
+ profile.Database[key] = value
208
+ } else {
209
+ delete(profile.Database, key)
210
+ }
211
+ return v.vaultWrite("private/"+login, ".vauth_database", profile.Database)
212
+ }
213
+
214
+ // Show returns the merged profile.
215
+ func (v *Vauth) Show() (map[string]any, error) {
216
+ profile, err := v.GetProfile(false)
217
+ if err != nil {
218
+ return nil, err
219
+ }
220
+ return profile.Merged(), nil
221
+ }
222
+
223
+ // Env resolves the environment declared by .vauthrc: VAULT_TOKEN and
224
+ // VAULT_ADDR, then env.map with $${env|profile|secrets.X} expanded.
225
+ func (v *Vauth) Env(renew bool) (*OrderedMap, error) {
226
+ config := v.Config.Env
227
+ if config == nil {
228
+ config = &EnvConfig{}
229
+ }
230
+ profile := &Profile{Metadata: map[string]any{}, Database: map[string]any{}}
231
+ rc := v.RC()
232
+ localCredentials := v.Config.AgentCrypt != nil && rc["ssh_auth"] == nil && rc["jwt_auth"] == nil
233
+ if localCredentials {
234
+ if _, err := v.Connect(renew); err != nil {
235
+ return nil, err
236
+ }
237
+ } else {
238
+ var err error
239
+ profile, err = v.GetProfile(renew)
240
+ if err != nil {
241
+ return nil, err
242
+ }
243
+ }
244
+ env := &OrderedMap{}
245
+ if v.VAULT_TOKEN() != "" {
246
+ env.Set("VAULT_TOKEN", v.VAULT_TOKEN())
247
+ }
248
+ if v.VAULT_ADDR() != "" {
249
+ env.Set("VAULT_ADDR", v.VAULT_ADDR())
250
+ }
251
+
252
+ secrets := map[string]any{}
253
+ if v.Config.AgentCrypt != nil {
254
+ armor, err := os.ReadFile(v.Config.AgentCrypt.Path)
255
+ if err != nil {
256
+ return nil, err
257
+ }
258
+ body, err := sshagentcrypt.Decrypt(armor, v.Config.AgentCrypt.Identity, &sshagentcrypt.Options{AgentSocket: v.Agent})
259
+ if err != nil {
260
+ return nil, err
261
+ }
262
+ if err := json.Unmarshal(body, &secrets); err != nil {
263
+ return nil, fmt.Errorf("Invalid ssh-agent-crypt payload %s: %w", v.Config.AgentCrypt.Path, err)
264
+ }
265
+ }
266
+
267
+ mapping := OrderedMap{}
268
+ for _, key := range config.Map.Keys {
269
+ mapping.Set(key, config.Map.Values[key])
270
+ }
271
+ merged := profile.Merged()
272
+ if config.Git {
273
+ mapping.Set("GIT_COMMITTER_NAME", "$${profile.VAUTH_USER_NAME}")
274
+ mapping.Set("GIT_COMMITTER_EMAIL", "$${profile.VAUTH_USER_MAIL}")
275
+ mapping.Set("GIT_AUTHOR_EMAIL", "$${profile.VAUTH_USER_MAIL}")
276
+ mapping.Set("GIT_AUTHOR_NAME", "$${profile.VAUTH_USER_NAME}")
277
+ mapping.Set("GIT_USER_LOGIN", "$${profile.VAUTH_USER_LOGIN}")
278
+ }
279
+ mount := config.Path
280
+ if mount == "" {
281
+ mount = "secrets"
282
+ }
283
+ for _, secretPath := range config.Paths {
284
+ fmt.Fprintln(v.stderr(), "reaching paths", secretPath)
285
+ data, err := v.vaultRead(mount, secretPath, false)
286
+ if err != nil {
287
+ return nil, err
288
+ }
289
+ for k, val := range data {
290
+ secrets[k] = val
291
+ }
292
+ }
293
+ dict := Lookup{"env": v.Environ, "profile": merged, "secrets": secrets}
294
+ for _, key := range mapping.Keys {
295
+ if !envName.MatchString(key) {
296
+ return nil, fmt.Errorf("Invalid environment variable name '%s' in env.map", key)
297
+ }
298
+ env.Set(key, ReplaceEnv(mapping.Values[key], dict))
299
+ }
300
+ return env, nil
301
+ }
302
+
303
+ // envName is the only shape of key that reaches `export KEY=...` unescaped;
304
+ // .vauthrc may come from an untrusted working directory.
305
+ var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
306
+
307
+ // Login connects, and with source publishes VAULT_TOKEN as shell exports.
308
+ func (v *Vauth) Login(source, renew bool) error {
309
+ if _, err := v.Connect(renew); err != nil {
310
+ return err
311
+ }
312
+ if source {
313
+ env := &OrderedMap{}
314
+ env.Set("VAULT_TOKEN", v.VAULT_TOKEN())
315
+ v.PublishEnv(env)
316
+ }
317
+ return nil
318
+ }
319
+
320
+ // PublishEnv writes `export K='v'` lines to stdout, each followed by an echo
321
+ // of the redacted assignment to stderr for the sourcing shell.
322
+ func (v *Vauth) PublishEnv(env *OrderedMap) {
323
+ var lines []string
324
+ for _, key := range env.Keys {
325
+ lines = append(lines, fmt.Sprintf("export %s=%s", key, ShellEscape(env.Values[key])))
326
+ lines = append(lines, fmt.Sprintf(`echo export %s="[redacted]" >&2`, key))
327
+ }
328
+ fmt.Fprint(v.stdout(), strings.Join(lines, "\n")+"\n")
329
+ }
330
+
331
+ // ShellEscape single-quotes a value for bash.
332
+ func ShellEscape(value string) string {
333
+ return "'" + strings.ReplaceAll(value, "'", `'"'"'`) + "'"
334
+ }
335
+
336
+ // Dotenv writes `K=v` lines to stdout and redacted exports to stderr.
337
+ func (v *Vauth) Dotenv() error {
338
+ env, err := v.Env(false)
339
+ if err != nil {
340
+ return err
341
+ }
342
+ for _, key := range env.Keys {
343
+ fmt.Fprintf(v.stdout(), "%s=%s\n", key, env.Values[key])
344
+ fmt.Fprintf(v.stderr(), "export %s=[redacted]\n", key)
345
+ }
346
+ return nil
347
+ }
348
+
349
+ // Run executes a command with the resolved environment merged over the
350
+ // process environment and returns its exit code.
351
+ func (v *Vauth) Run(command string, args ...string) (int, error) {
352
+ env, err := v.Env(false)
353
+ if err != nil {
354
+ return 1, err
355
+ }
356
+ cmd := exec.Command(command, args...)
357
+ cmd.Env = os.Environ()
358
+ for _, key := range env.Keys {
359
+ cmd.Env = append(cmd.Env, key+"="+env.Values[key])
360
+ }
361
+ cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
362
+ err = cmd.Run()
363
+ var exit *exec.ExitError
364
+ if errors.As(err, &exit) {
365
+ return exit.ExitCode(), nil
366
+ }
367
+ if err != nil {
368
+ return 1, fmt.Errorf("run failure : %w", err)
369
+ }
370
+ return 0, nil
371
+ }
372
+
373
+ // FunctionExists reports whether a bash login shell already defines alias.
374
+ func FunctionExists(alias string) bool {
375
+ return exec.Command("bash", "-lc", "declare -F "+alias).Run() == nil
376
+ }
377
+
378
+ var yes = regexp.MustCompile(`(?i)^y(es)?$`)
379
+
380
+ // Install appends FunctionDecl to ~/.bashrc, asking before overriding an
381
+ // existing definition.
382
+ func (v *Vauth) Install() error {
383
+ bashrcPath := filepath.Join(v.HomeDir, ".bashrc")
384
+ body, _ := os.ReadFile(bashrcPath)
385
+ bashrc := strings.TrimSpace(string(body))
386
+ if FunctionExists(FunctionName) {
387
+ fmt.Fprint(v.stdout(), "Function already defined, override current definition? [y/N] ")
388
+ answer, _ := bufio.NewReader(v.stdin()).ReadString('\n')
389
+ if !yes.MatchString(strings.TrimSpace(answer)) {
390
+ return nil
391
+ }
392
+ }
393
+ fmt.Fprintf(v.stderr(), "Installing function %s in %s\n", FunctionName, bashrcPath)
394
+ if err := os.WriteFile(bashrcPath, []byte(bashrc+"\n"+FunctionDecl+"\n"), 0o644); err != nil {
395
+ return err
396
+ }
397
+ fmt.Fprintf(v.stderr(), "Installation ok, please \nsource %s\n", bashrcPath)
398
+ return nil
399
+ }