vvauth 2.7.1 → 2.8.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/API_and_tests.md CHANGED
@@ -16,6 +16,11 @@ venv --gitlab
16
16
  `env --ir://json` writes one JSON object to stdout, with diagnostics on stderr.
17
17
  JSON key order and final whitespace are not significant. `venv` sources
18
18
  `vauth env --source "$@"`; renewal forces authentication.
19
+ On ordinary configuration/authentication/profile/macro errors, `env --source`
20
+ writes exactly `return 1\n` to stdout, preserves diagnostics on stderr and exits
21
+ nonzero. Sourcing that output returns 1 without exiting the caller or publishing
22
+ partial exports. Successful output and non-source error output are unchanged;
23
+ this does not cover crashes or a missing executable.
19
24
 
20
25
  ## Node CLI — cnyks
21
26
 
@@ -86,6 +91,30 @@ err = client.Unset(key)
86
91
  err = client.Gitlab()
87
92
  ```
88
93
 
94
+ ### Go embedding with an in-memory vauthrc
95
+
96
+ ```go
97
+ client, err := vvauth.NewFromRC(rcBody, environ)
98
+ // Check err before proceeding.
99
+ exports, err := client.Env(false)
100
+ // exports.Values is map[string]string; exports.Keys preserves declaration order.
101
+ ```
102
+
103
+ `NewFromRC(body []byte, environ map[string]string) (*Vauth, error)` passes the
104
+ YAML/JSON RC to vauth-login's constructor of the same name, then compiles the
105
+ parent SDK's sections from its complete raw snapshot, just like `New()`.
106
+ It preserves the authentication constructor's contract: nil environment
107
+ inherits, non-nil environment is copied, configuration is not discovered or
108
+ merged from RC files, and the native home `~/.vauthrc` still authorizes Vault
109
+ addresses. The inline RC cannot authorize its own Vault. Home/cache/agent
110
+ behavior and all network destination checks stay owned by vauth-login.
111
+
112
+ `env.map`, local secrets, profile/KV, delegation and `env.gitlab` validation
113
+ use their existing SDK semantics. `Env` returns exports and errors without
114
+ publishing them to stdout or changing the process environment. Only explicitly
115
+ calling `PublishEnv` performs shell publication. No RC temporary file is used.
116
+ The Node constructor and both CLIs retain their existing entry points.
117
+
89
118
  `Connect`, `LookupSelf`, `Request`, immutable `RC` and address/token readers
90
119
  belong to vauth-login. vvauth owns `Config`/`config`, profiles, KV operations,
91
120
  macro expansion, shell publication and GitLab initialization. Constructors
@@ -119,6 +148,12 @@ go test -race ./...
119
148
  GOOS=windows GOARCH=amd64 go build ./cmd/vauth
120
149
  ```
121
150
 
151
+ `test/env-source.js` checks exact failure stdout, nonzero CLI status, Bash
152
+ process-substitution sourcing and continued execution, plus successful exports,
153
+ renewal flags and non-source failures. It uses temporary homes/configurations
154
+ and a loopback Vault. `cmd/vauth/main_test.go` builds the native Go CLI and runs
155
+ the same checks against that executable (requires Node and Bash).
156
+
122
157
  Tests use disposable SSH keys/agents, temporary configuration and loopback
123
158
  Vault fixtures; they do not require real credentials. Differential checks cover
124
159
  profile/KV operations, renewal, trust refusal, local secrets, configuration,
package/README.md CHANGED
@@ -30,6 +30,11 @@ venv --renew
30
30
  function venv() { source <(/usr/bin/env vauth env --source "$@"); }
31
31
  ```
32
32
 
33
+ For ordinary configuration, authentication, profile or macro failures,
34
+ `env --source` writes only `return 1` to stdout and exits nonzero; diagnostics
35
+ remain on stderr. `venv` therefore returns 1 without closing the calling shell
36
+ or applying partial exports. This is a CLI error protocol, not crash handling.
37
+
33
38
  `source ~/.bashrc` loads it in the current shell. `--renew` forces fresh
34
39
  authentication. For a machine-readable result:
35
40
 
package/cmd/vauth/main.go CHANGED
@@ -95,7 +95,7 @@ func main() {
95
95
  }
96
96
  }
97
97
 
98
- func run(argv []string) error {
98
+ func run(argv []string) (err error) {
99
99
  args, dict := parseArgs(argv)
100
100
  if len(args) > 1 && args[0] == "env" && args[1] == "gitlab" {
101
101
  args = []string{"gitlab"}
@@ -111,6 +111,14 @@ func run(argv []string) error {
111
111
  os.Exit(1)
112
112
  }
113
113
  command, args := args[0], args[1:]
114
+ if command == "env" && truthy(param(args, dict, 0, "source")) {
115
+ defer func() {
116
+ if err != nil {
117
+ // Fail the sourced helper, not the shell that called it.
118
+ fmt.Fprintln(os.Stdout, "return 1")
119
+ }
120
+ }()
121
+ }
114
122
  _, jsonOutput := dict["ir://json"]
115
123
  if command == "version" || command == "--version" {
116
124
  fmt.Println(strings.TrimPrefix(buildVersion(), "v"))
@@ -0,0 +1,35 @@
1
+ package main
2
+
3
+ import (
4
+ "os"
5
+ "os/exec"
6
+ "path/filepath"
7
+ "testing"
8
+ )
9
+
10
+ func TestEnvSource(t *testing.T) {
11
+ if _, err := exec.LookPath("node"); err != nil {
12
+ t.Skip("shared CLI checks require Node")
13
+ }
14
+ if _, err := exec.LookPath("bash"); err != nil {
15
+ t.Skip("source checks require Bash")
16
+ }
17
+ root, err := filepath.Abs("../..")
18
+ if err != nil {
19
+ t.Fatal(err)
20
+ }
21
+ binary := filepath.Join(t.TempDir(), "vauth")
22
+ build := exec.Command("go", "build", "-o", binary, "./cmd/vauth")
23
+ build.Dir = root
24
+ if output, err := build.CombinedOutput(); err != nil {
25
+ t.Fatalf("build CLI: %v\n%s", err, output)
26
+ }
27
+ checks := exec.Command("node", "--test", "test/env-source.js")
28
+ checks.Dir = root
29
+ checks.Env = append(os.Environ(), "VAUTH_TEST_BINARY="+binary)
30
+ output, err := checks.CombinedOutput()
31
+ t.Logf("%s", output)
32
+ if err != nil {
33
+ t.Fatal(err)
34
+ }
35
+ }
package/cmd/vauth.js CHANGED
@@ -9,4 +9,17 @@ const options = command ? [`--ir://run=${command}`] : [];
9
9
  if(command === 'env' && !dict['ir://json'])
10
10
  options.push('--ir://raw');
11
11
 
12
- cnyks(Vvauth, 'vauth', options);
12
+ if(command === 'env' && dict.source) {
13
+ (async () => {
14
+ try {
15
+ await new Vvauth().Env(dict.source, dict.renew, dict.gitlab);
16
+ } catch(err) {
17
+ // Fail the sourced helper, not the shell that called it.
18
+ process.stdout.write('return 1\n');
19
+ console.error(err, err && err.stack || '');
20
+ process.exitCode = 1;
21
+ }
22
+ })();
23
+ } else {
24
+ cnyks(Vvauth, 'vauth', options);
25
+ }
package/go.mod CHANGED
@@ -1,12 +1,12 @@
1
1
  module github.com/131/vvauth/v2
2
2
 
3
- // version: 2.7.1
3
+ // version: 2.8.0
4
4
 
5
5
  go 1.22
6
6
 
7
7
  require (
8
8
  github.com/131/ssh-agent-crypt v1.4.4
9
- github.com/131/vauth-login v1.1.8
9
+ github.com/131/vauth-login v1.3.0
10
10
  github.com/Masterminds/semver/v3 v3.5.0
11
11
  gopkg.in/yaml.v3 v3.0.1
12
12
  )
package/go.sum CHANGED
@@ -2,10 +2,8 @@ github.com/131/nyks/v6 v6.18.0 h1:xpjRJk2YAyoqqgSvWrox0eIGZ1AY4IkEvqETavcwcQk=
2
2
  github.com/131/nyks/v6 v6.18.0/go.mod h1:ckNI5ql4USp+kQyrG1c35tl/PrPSgpoNXktcnQGJpdk=
3
3
  github.com/131/ssh-agent-crypt v1.4.4 h1:6MlDUao1Yq6iNY4Bgin/iZp2q3X/g6qD6H1X4ad8ukY=
4
4
  github.com/131/ssh-agent-crypt v1.4.4/go.mod h1:/THxpIdVrEAHxNoc6t6lVYBsSEd1zkCROPZepDe8QTI=
5
- github.com/131/vauth-login v1.1.7 h1:i256JyHP05WKqIrLv18ThfitGipH4oKnN7zpQESzV7U=
6
- github.com/131/vauth-login v1.1.7/go.mod h1:Dch6CZkaAxnYCD1V83h0g0xPQORjQoZarOOVt4mhNv8=
7
- github.com/131/vauth-login v1.1.8 h1:ElE+HTirBMmZNUPu788ndmAH844EnmWGFtCeHpi2WHs=
8
- github.com/131/vauth-login v1.1.8/go.mod h1:t7h0e1phy9sBHfsHlK2jXFstlS7VszU5gcTS4mDSnMQ=
5
+ github.com/131/vauth-login v1.3.0 h1:zRrsL4/TkFFCQCYxuDdnQFXmUNWi6CJjWKra1S0Nn/Q=
6
+ github.com/131/vauth-login v1.3.0/go.mod h1:bwMDCmFn3YVxT5Rc+Ip8zxl5XiDllp1ClV8JtqJhnMs=
9
7
  github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
10
8
  github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
11
9
  github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
@@ -0,0 +1,170 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "bytes"
5
+ "io"
6
+ "net/http"
7
+ "os"
8
+ "path/filepath"
9
+ "strings"
10
+ "testing"
11
+ )
12
+
13
+ func memoryHome(t *testing.T) string {
14
+ t.Helper()
15
+ home := t.TempDir()
16
+ t.Setenv("HOME", home)
17
+ t.Setenv("USERPROFILE", home)
18
+ return home
19
+ }
20
+
21
+ func TestNewFromRCExportsToParent(t *testing.T) {
22
+ home := memoryHome(t)
23
+ f := newFixture(t, fixtureOptions{
24
+ metadata: map[string]any{"VAUTH_USER_LOGIN": "alice", "WHO": "profile"},
25
+ database: map[string]any{"KEY": "private"},
26
+ secrets: map[string]any{"APP_KEY": "fixture-secret"},
27
+ })
28
+ body := []byte(`vault_addr: $${env.SELECTED_VAULT}
29
+ jwt_auth: {jwt: fixture-jwt, role: fixture-role}
30
+ token_cache: false
31
+ env:
32
+ paths: [app]
33
+ map:
34
+ WHO: $${profile.WHO}
35
+ KEY: $${profile.KEY}
36
+ APP_KEY: $${secrets.APP_KEY}
37
+ INPUT: $${env.INPUT}
38
+ BOOL: true
39
+ `)
40
+ environ := map[string]string{"SELECTED_VAULT": f.server.URL, "VAULT_ADDR": f.server.URL, "INPUT": "caller-value", "SSH_AUTH_SOCK": agentSocket}
41
+ v, err := NewFromRC(body, environ)
42
+ if err != nil {
43
+ t.Fatal(err)
44
+ }
45
+ v.Stderr = io.Discard
46
+ var output bytes.Buffer
47
+ v.Stdout = &output
48
+ environ["INPUT"] = "changed"
49
+ exports, err := v.Env(false)
50
+ if err != nil {
51
+ t.Fatal(err)
52
+ }
53
+ for key, want := range map[string]string{
54
+ "VAULT_ADDR": f.server.URL, "VAULT_TOKEN": "fresh-token", "WHO": "profile",
55
+ "KEY": "private", "APP_KEY": "fixture-secret", "INPUT": "caller-value", "BOOL": "true",
56
+ } {
57
+ got, ok := exports.Get(key)
58
+ if !ok || got != want {
59
+ t.Fatalf("incorrect export %s", key)
60
+ }
61
+ }
62
+ equal(t, output.Len(), 0)
63
+ equal(t, v.HomeDir, home)
64
+ equal(t, v.RC()["vault_addr"], "$${env.SELECTED_VAULT}")
65
+ equal(t, v.RC()["env"].(map[string]any)["map"].(map[string]any)["INPUT"], "$${env.INPUT}")
66
+ equal(t, v.RC()["env"].(map[string]any)["map"].(map[string]any)["BOOL"], true)
67
+ entries, err := os.ReadDir(home)
68
+ if err != nil {
69
+ t.Fatal(err)
70
+ }
71
+ equal(t, len(entries), 0)
72
+ }
73
+
74
+ func TestNewFromRCUsesHomeVaultTrust(t *testing.T) {
75
+ for _, trusted := range []bool{false, true} {
76
+ t.Run(map[bool]string{false: "unknown", true: "known"}[trusted], func(t *testing.T) {
77
+ home := memoryHome(t)
78
+ f := newFixture(t, fixtureOptions{})
79
+ if trusted {
80
+ if err := os.WriteFile(filepath.Join(home, ".vauthrc"), []byte("known_vaults: ['"+f.server.URL+"']"), 0600); err != nil {
81
+ t.Fatal(err)
82
+ }
83
+ }
84
+ body := []byte("vault_addr: " + f.server.URL + "\nknown_vaults: ['" + f.server.URL + "']\nenv: {map: {VALUE: local}}")
85
+ v, err := NewFromRC(body, map[string]string{"VAULT_TOKEN": "inherited-fixture-token"})
86
+ if err != nil {
87
+ t.Fatal(err)
88
+ }
89
+ v.Stderr = io.Discard
90
+ exports, err := v.Env(false)
91
+ if trusted {
92
+ if err != nil {
93
+ t.Fatal(err)
94
+ }
95
+ value, _ := exports.Get("VALUE")
96
+ equal(t, value, "local")
97
+ } else {
98
+ if err == nil || !strings.Contains(err.Error(), "known_vaults") || exports != nil {
99
+ t.Fatalf("unknown inline Vault accepted: %v", err)
100
+ }
101
+ equal(t, len(f.requests), 0)
102
+ }
103
+ })
104
+ }
105
+ }
106
+
107
+ func TestNewFromRCValidatesParentSections(t *testing.T) {
108
+ memoryHome(t)
109
+ for _, body := range []string{"vault_addr: [", "delegate: [invalid/role]", "env: {map: {VALUE: [not-a-scalar]}}"} {
110
+ if v, err := NewFromRC([]byte(body), map[string]string{}); err == nil || v != nil {
111
+ t.Fatal("invalid inline RC accepted")
112
+ }
113
+ }
114
+ body := []byte("env: {gitlab: true, map: {PROJECT: '$${env.CI_PROJECT_PATH}'}}")
115
+ if v, err := NewFromRC(body, map[string]string{}); err == nil || v != nil || !strings.Contains(err.Error(), "CI_PROJECT_PATH") {
116
+ t.Fatalf("GitLab prerequisite not checked: %v", err)
117
+ }
118
+ environ := map[string]string{"CI_PROJECT_PATH": "team/project", "CI_PROJECT_NAME": "project", "CI_PROJECT_NAMESPACE": "team", "CI_PROJECT_PATH_SLUG": "team-project"}
119
+ v, err := NewFromRC(body, environ)
120
+ if err != nil {
121
+ t.Fatal(err)
122
+ }
123
+ v.Stderr = io.Discard
124
+ exports, err := v.Env(false)
125
+ if err != nil {
126
+ t.Fatal(err)
127
+ }
128
+ value, _ := exports.Get("PROJECT")
129
+ equal(t, value, "team/project")
130
+ }
131
+
132
+ func TestNewFromRCDelegatedExports(t *testing.T) {
133
+ memoryHome(t)
134
+ body := []byte(`vault_addr: https://synthetic.invalid
135
+ token_cache: false
136
+ delegate: [client-ro]
137
+ env:
138
+ map:
139
+ ROUTER_TOKEN: $${delegate.client-ro}
140
+ `)
141
+ v, err := NewFromRC(body, map[string]string{"VAULT_ADDR": "https://synthetic.invalid", "VAULT_TOKEN": "fixture-parent"})
142
+ if err != nil {
143
+ t.Fatal(err)
144
+ }
145
+ v.Stderr = io.Discard
146
+ creates := 0
147
+ v.HTTPClient = &http.Client{Transport: delegateTransport(func(r *http.Request) (*http.Response, error) {
148
+ response := `{"data":{"ttl":2000,"entity_id":"synthetic-entity"}}`
149
+ switch r.URL.Path {
150
+ case "/v1/identity/entity/id/synthetic-entity":
151
+ response = `{"data":{"metadata":{}}}`
152
+ case "/v1/auth/token/create/client-ro":
153
+ creates++
154
+ response = `{"auth":{"client_token":"fixture-child","lease_duration":1000}}`
155
+ case "/v1/auth/token/lookup-self":
156
+ default:
157
+ t.Fatalf("unexpected request %s", r.URL.Path)
158
+ }
159
+ return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(response))}, nil
160
+ })}
161
+ for i := 0; i < 2; i++ {
162
+ exports, err := v.Env(false)
163
+ if err != nil {
164
+ t.Fatal(err)
165
+ }
166
+ equal(t, exports.Values["VAULT_TOKEN"], "fixture-parent")
167
+ equal(t, exports.Values["ROUTER_TOKEN"], "fixture-child")
168
+ }
169
+ equal(t, creates, 1) // In-memory delegation reuse remains available without disk cache.
170
+ }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "vvauth",
3
- "version": "2.7.1",
3
+ "version": "2.8.0",
4
4
  "description": "Vault Auth helper",
5
5
  "main": "index.js",
6
6
  "bin": {
7
7
  "vauth": "./cmd/vauth.js"
8
8
  },
9
9
  "scripts": {
10
- "test": "node --test test/token-cache.js test/delegate.js",
10
+ "test": "node --test test/token-cache.js test/delegate.js test/env-source.js",
11
11
  "eslint": "eslint ."
12
12
  },
13
13
  "author": "",
@@ -0,0 +1,166 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const {test} = require('node:test');
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+ const http = require('http');
9
+ const {execFile} = require('child_process');
10
+ const {promisify} = require('util');
11
+ const exec = promisify(execFile);
12
+ const binary = process.env.VAUTH_TEST_BINARY;
13
+ const command = binary ? [binary] : [process.execPath, path.resolve(__dirname, '../cmd/vauth.js')];
14
+
15
+ async function fixture(t, rc, handler) {
16
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'vvauth-source-'));
17
+ t.after(() => fs.rmSync(home, {recursive : true, force : true}));
18
+ const file = path.join(home, '.vauthrc');
19
+ const bin = path.join(home, 'bin');
20
+ fs.mkdirSync(bin);
21
+ fs.symlinkSync(binary || command[1], path.join(bin, 'vauth'));
22
+ // Only synthetic credentials/configuration reach either CLI, never the user's environment.
23
+ const env = {PATH : `${bin}:${process.env.PATH}`, HOME : home, USERPROFILE : home, VAUTHRC : file};
24
+ if(handler) {
25
+ const server = http.createServer(handler);
26
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
27
+ t.after(() => new Promise(resolve => server.close(resolve)));
28
+ env.VAULT_ADDR = `http://127.0.0.1:${server.address().port}`;
29
+ rc.vault_addr = env.VAULT_ADDR;
30
+ rc.token_cache = false;
31
+ }
32
+ fs.writeFileSync(file, typeof rc === 'string' ? rc : JSON.stringify(rc));
33
+ const run = async (program, args) => {
34
+ try {
35
+ return {...await exec(program, args, {cwd : home, env}), code : 0};
36
+ } catch(err) {
37
+ return err;
38
+ }
39
+ };
40
+ return {
41
+ env,
42
+ cli : (...args) => run(command[0], [...command.slice(1), ...args]),
43
+ shell : (script, ...args) => run('bash', ['--noprofile', '--norc', '-c', script, '_', ...args]),
44
+ };
45
+ }
46
+
47
+ const failureShell = `
48
+ function venv() { source <(/usr/bin/env vauth env --source "$@"); }
49
+ OK=caller
50
+ unset BAD
51
+ initial_token=\${VAULT_TOKEN-unset}
52
+ venv
53
+ status=$?
54
+ if [ "\${VAULT_TOKEN-unset}" = "$initial_token" ]; then token=unchanged; else token=changed; fi
55
+ printf '%s|continued|%s|%s|%s\\n' "$status" "$OK" "\${BAD-unset}" "$token"
56
+ `;
57
+ const map = {OK : 'synthetic-secret', BAD : '$${delegate.unknown}'};
58
+ const cases = [
59
+ ['malformed configuration', 'env: [\n', /parse|YAML|flow|end/i],
60
+ ['invalid delegation configuration', {delegate : {}, env : {map}}, /Invalid Vault delegation/],
61
+ ['invalid variable name', {env : {map : {OK : 'synthetic-secret', 'BAD-NAME' : 'value'}}}, /Invalid environment variable name/],
62
+ ['invalid map value', {env : {map : {OK : 'synthetic-secret', BAD : {nested : true}}}}, /Invalid environment value/],
63
+ ['unknown macro', {env : {map}}, /Unknown Vault delegation/],
64
+ ['missing GitLab prerequisite', {env : {gitlab : true, map}}, /Missing CI_PROJECT/],
65
+ ['missing local secret file', {'ssh-agent-crypt' : {path : 'missing-synthetic-file'}, env : {map}}, /no such file|ENOENT/i],
66
+ ['authentication denied', {jwt_auth : {role : 'synthetic-role', jwt : 'synthetic-jwt'}, env : {map}}, /403/,
67
+ (req, res) => { res.writeHead(403); res.end('{"errors":["synthetic-denied"]}'); }],
68
+ ['profile denied', {env : {map}}, /403/, (req, res) => {
69
+ if(req.url.endsWith('/auth/token/lookup-self')) {
70
+ res.end(JSON.stringify({data : {entity_id : 'synthetic-entity', ttl : 3600}}));
71
+ } else {
72
+ res.writeHead(403); res.end('{"errors":["synthetic-denied"]}');
73
+ }
74
+ }],
75
+ ['secret path denied', {env : {paths : ['synthetic-path'], map}}, /403/, (req, res) => {
76
+ if(req.url.endsWith('/auth/token/lookup-self')) {
77
+ res.end(JSON.stringify({data : {entity_id : 'synthetic-entity', ttl : 3600}}));
78
+ } else if(req.url.includes('/identity/entity/id/')) {
79
+ res.end('{"data":{"metadata":{}}}');
80
+ } else {
81
+ res.writeHead(403); res.end('{"errors":["synthetic-denied"]}');
82
+ }
83
+ }],
84
+ ];
85
+
86
+ for(const [name, rc, diagnostic, handler] of cases) {
87
+ test(`${binary ? 'Go' : 'Node'} env --source: ${name}`, async t => {
88
+ const f = await fixture(t, rc, handler);
89
+ if(['profile denied', 'secret path denied'].includes(name))
90
+ f.env.VAULT_TOKEN = 'synthetic-parent';
91
+ const result = await f.cli('env', '--source');
92
+ assert.equal(result.code, 1);
93
+ assert.equal(result.stdout, 'return 1\n');
94
+ assert.match(result.stderr, diagnostic);
95
+ assert.ok(!result.stderr.includes('synthetic-secret'));
96
+ assert.ok(!result.stderr.includes('synthetic-parent'));
97
+ const shell = await f.shell(failureShell);
98
+ assert.equal(shell.code, 0);
99
+ assert.equal(shell.stdout, '1|continued|caller|unset|unchanged\n');
100
+ assert.match(shell.stderr, diagnostic);
101
+ });
102
+ }
103
+
104
+ test('non-source failures keep stdout empty', async t => {
105
+ const f = await fixture(t, {env : {map}});
106
+ for(const args of [['env', '--ir://json'], ['env', '--source=0', '--ir://json']]) {
107
+ const result = await f.cli(...args);
108
+ assert.equal(result.code, 1);
109
+ assert.equal(result.stdout, '');
110
+ assert.match(result.stderr, /Unknown Vault delegation/);
111
+ }
112
+ });
113
+
114
+ test('successful exports, JSON and source flags are unchanged', async t => {
115
+ const values = {OK : "spaces ' quotes\nnew line", COUNT : 42, FLAG : false, EMPTY : null};
116
+ const f = await fixture(t, {env : {map : values}});
117
+ const exports = {
118
+ OK : `export OK='spaces '"'"' quotes\nnew line'\necho export OK="[redacted]" >&2\n`,
119
+ COUNT : `export COUNT='42'\necho export COUNT="[redacted]" >&2\n`,
120
+ FLAG : `export FLAG='false'\necho export FLAG="[redacted]" >&2\n`,
121
+ EMPTY : `export EMPTY=''\necho export EMPTY="[redacted]" >&2\n`,
122
+ };
123
+ // Go's configuration clone already sorts map keys; Node retains insertion order.
124
+ const keys = binary ? Object.keys(values).sort() : Object.keys(values);
125
+ const expected = keys.map(key => exports[key]).join('');
126
+ for(const flags of [['--source'], ['--source', '--renew'], ['--source', '--renew=0'],
127
+ ['--source', '--ir://json'], ['--source=1']]) {
128
+ const result = await f.cli('env', ...flags);
129
+ assert.equal(result.code, 0);
130
+ assert.equal(result.stdout, expected);
131
+ }
132
+ const json = await f.cli('env', '--ir://json');
133
+ assert.equal(json.code, 0);
134
+ assert.deepEqual(JSON.parse(json.stdout), {...values, COUNT : '42', FLAG : 'false', EMPTY : ''});
135
+ const shell = await f.shell(`
136
+ function venv() { source <(/usr/bin/env vauth env --source "$@"); }
137
+ venv "$@"
138
+ status=$?
139
+ printf '%s|continued|%s|%s|%s|%s\\n' "$status" "$OK" "$COUNT" "$FLAG" "$EMPTY"
140
+ `, '--renew=0');
141
+ assert.equal(shell.code, 0);
142
+ assert.equal(shell.stdout, `0|continued|${values.OK}|42|false|\n`);
143
+ });
144
+
145
+ test('renew flag still forces login instead of the inherited token', async t => {
146
+ let logins = 0;
147
+ const f = await fixture(t, {jwt_auth : {role : 'synthetic-role', jwt : 'synthetic-jwt'}}, (req, res) => {
148
+ if(req.url.endsWith('/auth/jwt/login')) {
149
+ logins++;
150
+ res.end('{"auth":{"client_token":"synthetic-issued","lease_duration":3600,"renewable":false}}');
151
+ } else if(req.url.endsWith('/auth/token/lookup-self')) {
152
+ res.end('{"data":{"entity_id":"synthetic-entity","ttl":3600}}');
153
+ } else {
154
+ res.end('{"data":{"metadata":{}}}');
155
+ }
156
+ });
157
+ f.env.VAULT_TOKEN = 'synthetic-parent';
158
+ const reused = await f.cli('env', '--source', '--renew=0');
159
+ assert.equal(reused.code, 0);
160
+ assert.match(reused.stdout, /export VAULT_TOKEN='synthetic-parent'/);
161
+ assert.equal(logins, 0);
162
+ const renewed = await f.cli('env', '--source', '--renew');
163
+ assert.equal(renewed.code, 0);
164
+ assert.match(renewed.stdout, /export VAULT_TOKEN='synthetic-issued'/);
165
+ assert.equal(logins, 1);
166
+ });
package/vauth.go CHANGED
@@ -80,17 +80,40 @@ func CheckProjectVersion(manifest, version string) error {
80
80
  // New loads authentication through vauth-login, then the environment/profile
81
81
  // configuration from the same selected .vauthrc.
82
82
  func New() (*Vauth, error) {
83
- cwd, err := os.Getwd()
83
+ if err := checkProjectVersion(); err != nil {
84
+ return nil, err
85
+ }
86
+ login, err := vauthlogin.New()
84
87
  if err != nil {
85
88
  return nil, err
86
89
  }
87
- if err := CheckProjectVersion(filepath.Join(cwd, "package.json"), Version); err != nil {
90
+ return newClient(login)
91
+ }
92
+
93
+ // NewFromRC constructs from a YAML/JSON RC supplied in memory. The environment
94
+ // is copied (nil inherits the process environment); native home Vault trust and
95
+ // cache handling remain owned by vauth-login. Env returns exports to the caller.
96
+ func NewFromRC(body []byte, environ map[string]string) (*Vauth, error) {
97
+ if err := checkProjectVersion(); err != nil {
88
98
  return nil, err
89
99
  }
90
- login, err := vauthlogin.New()
100
+ login, err := vauthlogin.NewFromRC(body, environ)
91
101
  if err != nil {
92
102
  return nil, err
93
103
  }
104
+ return newClient(login)
105
+ }
106
+
107
+ func checkProjectVersion() error {
108
+ cwd, err := os.Getwd()
109
+ if err != nil {
110
+ return err
111
+ }
112
+ return CheckProjectVersion(filepath.Join(cwd, "package.json"), Version)
113
+ }
114
+
115
+ // newClient compiles only the parent SDK's sections from the login RC snapshot.
116
+ func newClient(login *vauthlogin.Vauth) (*Vauth, error) {
94
117
  v := &Vauth{Vauth: login}
95
118
  config, err := configFromRC(login.RC(), login.Environ)
96
119
  if err != nil {