vvauth 2.6.1 → 2.7.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.
@@ -0,0 +1,230 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "io"
7
+ "net/http"
8
+ "os"
9
+ "os/exec"
10
+ "path/filepath"
11
+ "testing"
12
+ "time"
13
+
14
+ sshagentcrypt "github.com/131/ssh-agent-crypt"
15
+ )
16
+
17
+ // Fresh clients exercise encrypted disk hits; each issuer also repeats a late
18
+ // hit through its established parent. TestMain owns the disposable SSH agent.
19
+ const delegateInteropNode = `
20
+ const assert = require('assert/strict');
21
+ const fs = require('fs');
22
+ const Vauth = require('./index');
23
+ const input = JSON.parse(fs.readFileSync(0, 'utf8'));
24
+ let clock = input.now, lookups = 0, creates = 0;
25
+ Date.now = () => clock;
26
+ const v = new Vauth();
27
+ v.LookupSelf = async parent => {
28
+ assert.equal(parent, input.parent);
29
+ lookups++;
30
+ clock += 2000;
31
+ return {ttl: 10};
32
+ };
33
+ v.Request = async (method, route, parent, payload, status) => {
34
+ assert.equal(method, 'POST');
35
+ assert.equal(route, 'auth/token/create/' + input.role);
36
+ assert.equal(parent, input.parent);
37
+ assert.equal(status, 200);
38
+ assert.deepEqual(payload, {ttl: '8s', renewable: false, no_default_policy: true, type: 'service'});
39
+ creates++;
40
+ clock += 3000;
41
+ return {body: JSON.stringify({auth: {client_token: input.issued, lease_duration: 5}})};
42
+ };
43
+ (async () => {
44
+ const token = await v.Delegate(input.role, input.renew);
45
+ if(creates) {
46
+ clock = input.now + 6999;
47
+ assert.equal(await v.Delegate(input.role, false), token);
48
+ }
49
+ assert.equal(v.VAULT_TOKEN, input.parent);
50
+ process.stdout.write(JSON.stringify({token, lookups, creates}));
51
+ })().catch(err => { console.error(err.message); process.exitCode = 1; });
52
+ `
53
+
54
+ func TestDelegateEncryptedTTLInterop(t *testing.T) {
55
+ if _, err := exec.LookPath("node"); err != nil {
56
+ t.Fatal("encrypted Node/Go interop requires Node")
57
+ }
58
+ for _, direction := range []string{"Go-to-Node", "Node-to-Go"} {
59
+ t.Run(direction, func(t *testing.T) {
60
+ home := t.TempDir()
61
+ rc := filepath.Join(home, ".vauthrc")
62
+ for name, value := range map[string]string{
63
+ "HOME": home, "USERPROFILE": home, "VAUTHRC": rc,
64
+ "SSH_AUTH_SOCK": agentSocket, "VAULT_ADDR": "",
65
+ "SSH_AGENT_CRYPT_KEY": "", "VAUTH_USER_IDENTITY": "", "VAUTH_USER_MAIL": "",
66
+ } {
67
+ t.Setenv(name, value)
68
+ }
69
+ type namespace struct{ address, parent, role string }
70
+ base := namespace{"https://synthetic.invalid", "synthetic-parent", "vauth-profile-ro"}
71
+ type result struct {
72
+ Token string `json:"token"`
73
+ Lookups int `json:"lookups"`
74
+ Creates int `json:"creates"`
75
+ }
76
+ call := func(language string, ns namespace, now int64, issued string, renew bool, expected string, misses int) {
77
+ t.Helper()
78
+ document, err := json.Marshal(map[string]any{"vault_addr": ns.address, "token_cache": true})
79
+ if err != nil {
80
+ t.Fatal(err)
81
+ }
82
+ if err := os.WriteFile(rc, document, 0600); err != nil {
83
+ t.Fatal(err)
84
+ }
85
+ t.Setenv("VAULT_TOKEN", ns.parent)
86
+ var got result
87
+ if language == "Node" {
88
+ input, err := json.Marshal(map[string]any{
89
+ "parent": ns.parent, "role": ns.role, "now": now, "issued": issued, "renew": renew,
90
+ })
91
+ if err != nil {
92
+ t.Fatal(err)
93
+ }
94
+ node := exec.Command("node", "-e", delegateInteropNode)
95
+ node.Env = []string{
96
+ "PATH=" + os.Getenv("PATH"), "HOME=" + home, "USERPROFILE=" + home,
97
+ "VAUTHRC=" + rc, "VAULT_TOKEN=" + ns.parent, "SSH_AUTH_SOCK=" + agentSocket,
98
+ }
99
+ node.Stdin = bytes.NewReader(input)
100
+ var diagnostics bytes.Buffer
101
+ node.Stderr = &diagnostics
102
+ out, err := node.Output()
103
+ if err != nil {
104
+ t.Fatalf("Node interop failed: %v: %s", err, &diagnostics)
105
+ }
106
+ if err := json.Unmarshal(out, &got); err != nil {
107
+ t.Fatal(err)
108
+ }
109
+ } else {
110
+ v, err := New()
111
+ if err != nil {
112
+ t.Fatal(err)
113
+ }
114
+ clock := time.UnixMilli(now)
115
+ v.Now = func() time.Time { return clock }
116
+ v.Stderr = io.Discard
117
+ v.HTTPClient = &http.Client{Transport: delegateTransport(func(r *http.Request) (*http.Response, error) {
118
+ if r.Header.Get("X-Vault-Token") != ns.parent {
119
+ t.Error("wrong parent in request")
120
+ }
121
+ var body string
122
+ switch r.URL.Path {
123
+ case "/v1/auth/token/lookup-self":
124
+ got.Lookups++
125
+ clock = clock.Add(2 * time.Second)
126
+ body = `{"data":{"ttl":10}}`
127
+ case "/v1/auth/token/create/" + ns.role:
128
+ got.Creates++
129
+ var payload map[string]any
130
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
131
+ t.Fatal(err)
132
+ }
133
+ if r.Method != "POST" || len(payload) != 4 || payload["ttl"] != "8s" || payload["renewable"] != false || payload["no_default_policy"] != true || payload["type"] != "service" {
134
+ t.Error("incorrect child creation request")
135
+ }
136
+ clock = clock.Add(3 * time.Second)
137
+ body = `{"auth":{"client_token":"` + issued + `","lease_duration":5}}`
138
+ default:
139
+ t.Fatalf("unexpected route %s", r.URL.Path)
140
+ }
141
+ return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(bytes.NewBufferString(body))}, nil
142
+ })}
143
+ got.Token, err = v.Delegate(ns.role, renew)
144
+ if err != nil {
145
+ t.Fatal(err)
146
+ }
147
+ if got.Creates > 0 {
148
+ clock = time.UnixMilli(now + 6999)
149
+ hit, err := v.Delegate(ns.role, false)
150
+ if err != nil || hit != got.Token {
151
+ t.Fatal("established client did not reuse the full child TTL")
152
+ }
153
+ }
154
+ if v.VAULT_TOKEN() != ns.parent {
155
+ t.Fatal("delegation changed the parent")
156
+ }
157
+ }
158
+ if got.Token != expected || got.Lookups != misses || got.Creates != misses {
159
+ t.Fatalf("%s: incorrect token or lookup/create count at %d (renew=%v)", language, now, renew)
160
+ }
161
+ }
162
+ checkCache := func(ns namespace, token string, deadline float64) []byte {
163
+ t.Helper()
164
+ directory := filepath.Join(home, ".vauth", "delegates")
165
+ file := filepath.Join(directory, delegateKey(ns.address, ns.parent, ns.role)+".creds")
166
+ armor, err := os.ReadFile(file)
167
+ if err != nil {
168
+ t.Fatal(err)
169
+ }
170
+ if !bytes.HasPrefix(armor, []byte("ssh-agent-crypt:v3:")) || bytes.Contains(armor, []byte(token)) || bytes.Contains(armor, []byte(ns.parent)) {
171
+ t.Fatal("cache must be encrypted without plaintext credentials")
172
+ }
173
+ for name, mode := range map[string]os.FileMode{directory: 0700, file: 0600} {
174
+ info, err := os.Stat(name)
175
+ if err != nil || info.Mode().Perm() != mode {
176
+ t.Fatal("incorrect delegation cache permissions")
177
+ }
178
+ }
179
+ clear, err := sshagentcrypt.Decrypt(armor, "", &sshagentcrypt.Options{AgentSocket: agentSocket})
180
+ if err != nil {
181
+ t.Fatal(err)
182
+ }
183
+ var cache map[string]any
184
+ if err := json.Unmarshal(clear, &cache); err != nil {
185
+ t.Fatal(err)
186
+ }
187
+ if len(cache) != 2 || cache["token"] != token || cache["expires_at"] != deadline || bytes.Contains(clear, []byte(ns.parent)) {
188
+ t.Fatal("incorrect shared cache format or request-time deadline")
189
+ }
190
+ return armor
191
+ }
192
+ writer, reader := "Go", "Node"
193
+ if direction == "Node-to-Go" {
194
+ writer, reader = reader, writer
195
+ }
196
+ call(writer, base, 100000, "synthetic-writer-child", false, "synthetic-writer-child", 1)
197
+ original := checkCache(base, "synthetic-writer-child", 107000)
198
+ call(reader, base, 106999, "synthetic-unused", false, "synthetic-writer-child", 0)
199
+ slashes := base
200
+ slashes.address += "///"
201
+ call(reader, slashes, 106999, "synthetic-unused", false, "synthetic-writer-child", 0)
202
+ if !bytes.Equal(original, checkCache(base, "synthetic-writer-child", 107000)) {
203
+ t.Fatal("cache hits rewrote the encrypted cache")
204
+ }
205
+
206
+ // Each changed tuple component misses; the opposite language then
207
+ // finds its new encrypted entry under exactly the same namespace.
208
+ for name, ns := range map[string]namespace{
209
+ "parent": {base.address, "synthetic-other-parent", base.role},
210
+ "role": {base.address, base.parent, "project-ro"},
211
+ "address": {"https://other.invalid", base.parent, base.role},
212
+ } {
213
+ token := "synthetic-" + name + "-child"
214
+ call(reader, ns, 106999, token, false, token, 1)
215
+ checkCache(ns, token, 113999)
216
+ call(writer, ns, 113998, "synthetic-unused", false, token, 0)
217
+ }
218
+ call(reader, base, 107000, "synthetic-expiry-child", false, "synthetic-expiry-child", 1)
219
+ checkCache(base, "synthetic-expiry-child", 114000)
220
+ call(writer, base, 113999, "synthetic-unused", false, "synthetic-expiry-child", 0)
221
+ call(reader, base, 113999, "synthetic-renew-child", true, "synthetic-renew-child", 1)
222
+ checkCache(base, "synthetic-renew-child", 120999)
223
+ call(writer, base, 120998, "synthetic-unused", false, "synthetic-renew-child", 0)
224
+ entries, err := os.ReadDir(filepath.Join(home, ".vauth", "delegates"))
225
+ if err != nil || len(entries) != 4 {
226
+ t.Fatal("expected four isolated cache files, without temporary leftovers")
227
+ }
228
+ })
229
+ }
230
+ }
@@ -0,0 +1,435 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "fmt"
7
+ "io"
8
+ "net/http"
9
+ "os"
10
+ "os/exec"
11
+ "path/filepath"
12
+ "strings"
13
+ "testing"
14
+ "time"
15
+
16
+ sshagentcrypt "github.com/131/ssh-agent-crypt"
17
+ )
18
+
19
+ type delegateTransport func(*http.Request) (*http.Response, error)
20
+
21
+ func (f delegateTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
22
+
23
+ type delegateFixture struct {
24
+ lookupDeniedOnce bool
25
+ creates int
26
+ lookups int
27
+ logins int
28
+ ttl float64
29
+ auth any
30
+ status int
31
+ payload map[string]any
32
+ routes []string
33
+ }
34
+
35
+ func newDelegateClient(t *testing.T, f *delegateFixture, parent string) *Vauth {
36
+ t.Helper()
37
+ home := t.TempDir()
38
+ rc := filepath.Join(home, ".vauthrc")
39
+ body := `vault_addr: https://synthetic.invalid
40
+ jwt_auth:
41
+ role: project
42
+ jwt: synthetic-jwt
43
+ token_cache: false
44
+ delegate:
45
+ - vauth-profile-ro
46
+ - project-ro
47
+ env:
48
+ map:
49
+ VAULT_ROUTER_TOKEN: $${delegate.vauth-profile-ro}
50
+ PROJECT_TOKEN: $$delegate.project-ro
51
+ `
52
+ if err := os.WriteFile(rc, []byte(body), 0600); err != nil {
53
+ t.Fatal(err)
54
+ }
55
+ for name, value := range map[string]string{"VAUTHRC": rc, "HOME": home, "VAULT_TOKEN": parent, "VAULT_ADDR": "", "SSH_AUTH_SOCK": "", "SSH_AGENT_CRYPT_KEY": "", "VAUTH_USER_IDENTITY": "", "VAUTH_USER_MAIL": ""} {
56
+ t.Setenv(name, value)
57
+ }
58
+ v, err := New()
59
+ if err != nil {
60
+ t.Fatal(err)
61
+ }
62
+ v.Stderr = io.Discard
63
+ v.Now = func() time.Time { return time.UnixMilli(100000) }
64
+ v.HTTPClient = &http.Client{Transport: delegateTransport(func(r *http.Request) (*http.Response, error) {
65
+ status := 200
66
+ var response any
67
+ switch {
68
+ case r.URL.Path == "/v1/auth/token/lookup-self":
69
+ f.lookups++
70
+ if f.lookupDeniedOnce && f.lookups == 1 {
71
+ status = 403
72
+ }
73
+ response = map[string]any{"data": map[string]any{"ttl": f.ttl, "entity_id": "synthetic-entity"}}
74
+ case r.URL.Path == "/v1/auth/jwt/login":
75
+ f.logins++
76
+ response = map[string]any{"auth": map[string]any{"client_token": "synthetic-new-parent", "lease_duration": 2000}}
77
+ case r.URL.Path == "/v1/identity/entity/id/synthetic-entity":
78
+ response = map[string]any{"data": map[string]any{"metadata": map[string]any{}}}
79
+ case strings.HasPrefix(r.URL.Path, "/v1/auth/token/create/"):
80
+ f.creates++
81
+ f.routes = append(f.routes, r.URL.Path)
82
+ if r.Header.Get("X-Vault-Token") != v.VAULT_TOKEN() {
83
+ t.Error("wrong parent")
84
+ }
85
+ if err := json.NewDecoder(r.Body).Decode(&f.payload); err != nil {
86
+ t.Error(err)
87
+ }
88
+ auth := f.auth
89
+ if auth == nil {
90
+ auth = map[string]any{"client_token": fmt.Sprintf("synthetic-child-%d", f.creates), "lease_duration": 1000}
91
+ }
92
+ response = map[string]any{"auth": auth}
93
+ if f.status != 0 {
94
+ status = f.status
95
+ }
96
+ default:
97
+ t.Errorf("unexpected route %s", r.URL.Path)
98
+ }
99
+ body, err := json.Marshal(response)
100
+ return &http.Response{StatusCode: status, Body: io.NopCloser(bytes.NewReader(body)), Header: http.Header{}}, err
101
+ })}
102
+ return v
103
+ }
104
+
105
+ func TestDelegateNativeEnvironment(t *testing.T) {
106
+ f := &delegateFixture{ttl: 1234.5}
107
+ v := newDelegateClient(t, f, "synthetic-parent")
108
+ env, err := v.Env(false)
109
+ if err != nil {
110
+ t.Fatal(err)
111
+ }
112
+ if env.Values["VAULT_TOKEN"] != "synthetic-parent" || env.Values["VAULT_ROUTER_TOKEN"] == "synthetic-parent" || env.Values["VAULT_ROUTER_TOKEN"] == env.Values["PROJECT_TOKEN"] {
113
+ t.Fatal("incorrect delegation exports")
114
+ }
115
+ if env.Len() != 4 || f.creates != 2 || f.logins != 0 {
116
+ t.Fatal("unexpected exports/login count")
117
+ }
118
+ if len(f.payload) != 4 || f.payload["ttl"] != "1234.5s" || f.payload["renewable"] != false || f.payload["no_default_policy"] != true || f.payload["type"] != "service" {
119
+ t.Fatalf("incorrect creation payload: %v", f.payload)
120
+ }
121
+ v.Config.Env.Map = OrderedMap{}
122
+ env, err = v.Env(false)
123
+ if err != nil || env.Len() != 2 {
124
+ t.Fatal("implicit delegation export")
125
+ }
126
+ if _, err := os.Stat(filepath.Join(v.HomeDir, ".vauth")); !os.IsNotExist(err) {
127
+ t.Fatal("disk cache used when off")
128
+ }
129
+ }
130
+
131
+ func TestDelegateFullTTLAndIsolation(t *testing.T) {
132
+ f := &delegateFixture{ttl: 1234.5}
133
+ v := newDelegateClient(t, f, "synthetic-parent")
134
+ clock := time.UnixMilli(100000)
135
+ v.Now = func() time.Time { return clock }
136
+ first, err := v.Delegate("vauth-profile-ro", false)
137
+ if err != nil {
138
+ t.Fatal(err)
139
+ }
140
+ clock = clock.Add(1000*time.Second - time.Millisecond)
141
+ token, err := v.Delegate("vauth-profile-ro", false)
142
+ if err != nil || token != first || f.creates != 1 || f.lookups != 1 {
143
+ t.Fatal("cache hit did not use full TTL")
144
+ }
145
+ clock = clock.Add(time.Millisecond)
146
+ token, err = v.Delegate("vauth-profile-ro", false)
147
+ if err != nil || token == first {
148
+ t.Fatal("expiry did not emit")
149
+ }
150
+ if _, err := v.Delegate("vauth-profile-ro", true); err != nil {
151
+ t.Fatal(err)
152
+ }
153
+ if _, err := v.Delegate("project-ro", false); err != nil {
154
+ t.Fatal(err)
155
+ }
156
+ if f.creates != 4 || f.logins != 0 {
157
+ t.Fatal("renew must not login parent")
158
+ }
159
+ if _, err := v.Connect(true); err != nil {
160
+ t.Fatal(err)
161
+ }
162
+ if _, err := v.Delegate("vauth-profile-ro", false); err != nil {
163
+ t.Fatal(err)
164
+ }
165
+ if f.creates != 5 || f.logins != 1 {
166
+ t.Fatal("parent change did not isolate cache")
167
+ }
168
+ for key, cache := range v.delegates {
169
+ body, _ := json.Marshal(cache)
170
+ if strings.Contains(key, "synthetic") || strings.Contains(string(body), "parent") {
171
+ t.Fatal("parent in cache")
172
+ }
173
+ }
174
+ if delegateKey("https://other.invalid", "synthetic-parent", "vauth-profile-ro") == delegateKey(v.VAULT_ADDR(), "synthetic-parent", "vauth-profile-ro") {
175
+ t.Fatal("address not isolated")
176
+ }
177
+ }
178
+
179
+ func TestDelegateErrorsAndNoPartialOutput(t *testing.T) {
180
+ for _, auth := range []any{false, map[string]any{}, map[string]any{"client_token": "synthetic-parent", "lease_duration": 10}, map[string]any{"client_token": "child", "lease_duration": 0}, map[string]any{"client_token": "child", "lease_duration": 11}, map[string]any{"client_token": "child", "lease_duration": -1}, map[string]any{"client_token": "child", "lease_duration": "10"}} {
181
+ f := &delegateFixture{ttl: 10, auth: auth}
182
+ v := newDelegateClient(t, f, "synthetic-parent")
183
+ var output bytes.Buffer
184
+ v.Stdout = &output
185
+ if err := v.Dotenv(); err == nil || output.Len() != 0 {
186
+ t.Fatal("invalid response published")
187
+ }
188
+ }
189
+ for _, ttl := range []float64{0, -1} {
190
+ v := newDelegateClient(t, &delegateFixture{ttl: ttl}, "synthetic-parent")
191
+ if _, err := v.Delegate("role", false); err == nil {
192
+ t.Fatal("invalid parent TTL accepted")
193
+ }
194
+ }
195
+ v := newDelegateClient(t, &delegateFixture{ttl: 10, status: 403}, "synthetic-parent")
196
+ if _, err := v.Env(false); err == nil {
197
+ t.Fatal("issuance error ignored")
198
+ }
199
+ for _, macro := range []string{"$${delegate.unknown}", "$$delegate.unknown", "$${delegate}"} {
200
+ v := newDelegateClient(t, &delegateFixture{ttl: 1234.5}, "synthetic-parent")
201
+ v.Config.Env.Map.Set("OK", "value")
202
+ v.Config.Env.Map.Set("BAD", macro)
203
+ var output bytes.Buffer
204
+ v.Stdout = &output
205
+ if err := v.Dotenv(); err == nil || !strings.Contains(err.Error(), "Unknown Vault delegation") || output.Len() != 0 {
206
+ t.Fatal("unknown macro published")
207
+ }
208
+ }
209
+ v = newDelegateClient(t, &delegateFixture{ttl: 10}, "synthetic-parent")
210
+ for _, role := range []string{"", "../other", ".", ".."} {
211
+ if _, err := v.Delegate(role, false); err == nil {
212
+ t.Fatal("invalid role accepted")
213
+ }
214
+ }
215
+ for _, roles := range []string{"null", "{}", "[{}]"} {
216
+ if _, err := ParseConfig([]byte("delegate: "+roles), "test", nil); err == nil {
217
+ t.Fatal("invalid role config accepted")
218
+ }
219
+ }
220
+ }
221
+
222
+ // Runs under the existing TestMain agent, or skips in the socket-free recipe.
223
+ func TestDelegateEncryptedInterop(t *testing.T) {
224
+ agent := exec.Command("ssh-agent", "-s")
225
+ out, err := agent.Output()
226
+ if err != nil {
227
+ t.Skip("sandbox cannot start a synthetic ssh-agent")
228
+ }
229
+ socketMatch := strings.Split(strings.Split(string(out), "SSH_AUTH_SOCK=")[1], ";")[0]
230
+ pid := strings.Split(strings.Split(string(out), "SSH_AGENT_PID=")[1], ";")[0]
231
+ defer exec.Command("kill", pid).Run()
232
+ directory := t.TempDir()
233
+ key := filepath.Join(directory, "key")
234
+ if out, err := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", key).CombinedOutput(); err != nil {
235
+ t.Fatalf("keygen: %v %s", err, out)
236
+ }
237
+ f := &delegateFixture{ttl: 1234.5}
238
+ v := newDelegateClient(t, f, "synthetic-parent")
239
+ t.Setenv("SSH_AUTH_SOCK", socketMatch)
240
+ add := exec.Command("ssh-add", key)
241
+ if out, err := add.CombinedOutput(); err != nil {
242
+ t.Fatalf("ssh-add: %v %s", err, out)
243
+ }
244
+ v.Agent = socketMatch
245
+ v.TokenCache = true
246
+ v.Now = time.Now
247
+ token, err := v.Delegate("vauth-profile-ro", false)
248
+ if err != nil {
249
+ t.Fatal(err)
250
+ }
251
+ file := v.delegateFile(delegateKey(v.VAULT_ADDR(), v.VAULT_TOKEN(), "vauth-profile-ro"))
252
+ armor, err := os.ReadFile(file)
253
+ if err != nil {
254
+ t.Fatal(err)
255
+ }
256
+ if !bytes.HasPrefix(armor, []byte("ssh-agent-crypt:v3:")) || bytes.Contains(armor, []byte(token)) || bytes.Contains(armor, []byte(v.VAULT_TOKEN())) {
257
+ t.Fatal("cache not encrypted")
258
+ }
259
+ info, _ := os.Stat(file)
260
+ if info.Mode().Perm() != 0600 {
261
+ t.Fatal("cache permissions")
262
+ }
263
+ // Node reads Go's cache through the public Delegate API, then forces a new
264
+ // encrypted child; Go consumes that child without a Vault lookup.
265
+ script := `const fs=require('fs');const V=require('./index');const v=Object.create(V.prototype);
266
+ Object.defineProperties(v,{VAULT_ADDR:{value:'https://synthetic.invalid'},VAULT_TOKEN:{value:'synthetic-parent'},RC:{value:{token_cache:true}}});
267
+ v.Connect=async()=>v.VAULT_TOKEN;v.LookupSelf=async()=>({ttl:1234.5});
268
+ v.Request=async()=>({body:JSON.stringify({auth:{client_token:'synthetic-node-child',lease_duration:1000}})});
269
+ (async()=>{const t=await v.Delegate('vauth-profile-ro');if(t!==process.argv[1])throw Error('interop cache miss');await v.Delegate('vauth-profile-ro',true)})().catch(()=>process.exit(1));`
270
+ node := exec.Command("node", "-e", script, token)
271
+ node.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + v.HomeDir, "SSH_AUTH_SOCK=" + socketMatch}
272
+ if out, err := node.CombinedOutput(); err != nil {
273
+ t.Fatalf("Node interop: %v %s", err, out)
274
+ }
275
+ v.delegates = nil
276
+ before := f.lookups
277
+ next, err := v.Delegate("vauth-profile-ro", false)
278
+ if err != nil || next != "synthetic-node-child" || f.lookups != before {
279
+ t.Fatal("Node cache not reused by Go")
280
+ }
281
+ armor, _ = os.ReadFile(file)
282
+ clear, err := sshagentcrypt.Decrypt(armor, "", &sshagentcrypt.Options{AgentSocket: socketMatch})
283
+ if err != nil || bytes.Contains(clear, []byte("synthetic-parent")) {
284
+ t.Fatal("parent in decrypted cache")
285
+ }
286
+ }
287
+
288
+ func TestDelegateCacheKeyInterop(t *testing.T) {
289
+ script := `Date.now=()=>100000;const V=require('./index');const v=Object.create(V.prototype);
290
+ Object.defineProperties(v,{VAULT_ADDR:{value:process.argv[1]},VAULT_TOKEN:{value:'synthetic-parent'},RC:{value:{token_cache:false}}});
291
+ v.Connect=async()=>{};v.LookupSelf=async()=>({ttl:100});v.Request=async()=>({body:JSON.stringify({auth:{client_token:'child',lease_duration:100}})});
292
+ v.Delegate('role.with-dots').then(()=>process.stdout.write([...v._delegates.keys()][0])).catch(()=>process.exit(1));`
293
+ for _, address := range []string{"https://synthetic.invalid/", "https://synthetic.invalid/<é>&"} {
294
+ node := exec.Command("node", "-e", script, address)
295
+ node.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + t.TempDir()}
296
+ out, err := node.Output()
297
+ if err != nil {
298
+ t.Fatal(err)
299
+ }
300
+ if string(out) != delegateKey(address, "synthetic-parent", "role.with-dots") {
301
+ t.Fatal("Node/Go cache hash mismatch")
302
+ }
303
+ }
304
+ }
305
+
306
+ func TestDelegateApprovedConfig(t *testing.T) {
307
+ config, err := ParseConfig([]byte(`vault_addr: https://vault.elipsdev.net
308
+ ssh_auth:
309
+ role: $${env.VAUTH_USER_LOGIN}
310
+ delegate:
311
+ - vauth-profile-ro
312
+ env:
313
+ map:
314
+ VAULT_ROUTER_TOKEN: $${delegate.vauth-profile-ro}
315
+ `), "test", map[string]string{"VAUTH_USER_LOGIN": "synthetic-user"})
316
+ if err != nil {
317
+ t.Fatal(err)
318
+ }
319
+ if len(config.Delegate) != 1 || config.Delegate[0] != "vauth-profile-ro" || config.Env.Map.Values["VAULT_ROUTER_TOKEN"] != "$${delegate.vauth-profile-ro}" {
320
+ t.Fatal("native config not preserved")
321
+ }
322
+ }
323
+
324
+ func TestDelegateExpiredParentLogin(t *testing.T) {
325
+ f := &delegateFixture{ttl: 1000, lookupDeniedOnce: true}
326
+ v := newDelegateClient(t, f, "synthetic-parent")
327
+ if _, err := v.Delegate("vauth-profile-ro", true); err != nil {
328
+ t.Fatal(err)
329
+ }
330
+ if f.lookups != 2 || f.logins != 1 || f.creates != 1 || v.VAULT_TOKEN() != "synthetic-new-parent" {
331
+ t.Fatal("invalid parent was not replaced exactly once")
332
+ }
333
+ }
334
+
335
+ func delayDelegateResponses(v *Vauth, clock *time.Time, lookupDelay, createDelay time.Duration) {
336
+ transport := v.HTTPClient.Transport
337
+ v.HTTPClient.Transport = delegateTransport(func(r *http.Request) (*http.Response, error) {
338
+ response, err := transport.RoundTrip(r)
339
+ switch {
340
+ case r.URL.Path == "/v1/auth/token/lookup-self":
341
+ *clock = clock.Add(lookupDelay)
342
+ case strings.HasPrefix(r.URL.Path, "/v1/auth/token/create/"):
343
+ *clock = clock.Add(createDelay)
344
+ }
345
+ return response, err
346
+ })
347
+ }
348
+
349
+ func TestDelegateDelayedResponseDeadline(t *testing.T) {
350
+ f := &delegateFixture{ttl: 10, auth: map[string]any{"client_token": "synthetic-delayed-child", "lease_duration": 5}}
351
+ v := newDelegateClient(t, f, "synthetic-parent")
352
+ clock := time.UnixMilli(100000)
353
+ v.Now = func() time.Time { return clock }
354
+ delayDelegateResponses(v, &clock, 2*time.Second, 3*time.Second)
355
+ token, err := v.Delegate("role", false)
356
+ if err != nil {
357
+ t.Fatal(err)
358
+ }
359
+ if f.payload["ttl"] != "8s" {
360
+ t.Fatal("elapsed lookup time not deducted")
361
+ }
362
+ key := delegateKey(v.VAULT_ADDR(), v.VAULT_TOKEN(), "role")
363
+ if v.delegates[key].ExpiresAt != 107000 {
364
+ t.Fatal("response time extended the child deadline")
365
+ }
366
+ clock = time.UnixMilli(106999)
367
+ hit, err := v.Delegate("role", false)
368
+ if err != nil || hit != token || f.creates != 1 || f.lookups != 1 {
369
+ t.Fatal("child not reusable until its deadline")
370
+ }
371
+ clock = time.UnixMilli(107000)
372
+ if _, err := v.Delegate("role", false); err != nil {
373
+ t.Fatal(err)
374
+ }
375
+ if f.creates != 2 || f.logins != 0 {
376
+ t.Fatal("deadline did not trigger child-only issuance")
377
+ }
378
+ }
379
+
380
+ func TestDelegateExpiredOnArrival(t *testing.T) {
381
+ for _, delay := range []time.Duration{5 * time.Second, 6 * time.Second} {
382
+ f := &delegateFixture{ttl: 10, auth: map[string]any{"client_token": "synthetic-delayed-child", "lease_duration": 5}}
383
+ v := newDelegateClient(t, f, "synthetic-parent")
384
+ clock := time.UnixMilli(100000)
385
+ v.Now = func() time.Time { return clock }
386
+ delayDelegateResponses(v, &clock, 0, delay)
387
+ var output bytes.Buffer
388
+ v.Stdout = &output
389
+ if err := v.Dotenv(); err == nil {
390
+ t.Fatal("expired child returned")
391
+ }
392
+ if len(v.delegates) != 0 || output.Len() != 0 {
393
+ t.Fatal("expired child cached or published")
394
+ }
395
+ }
396
+ }
397
+
398
+ func TestDelegateParentTTLConsumedByLookup(t *testing.T) {
399
+ for _, delay := range []time.Duration{10 * time.Second, 11 * time.Second} {
400
+ f := &delegateFixture{ttl: 10}
401
+ v := newDelegateClient(t, f, "synthetic-parent")
402
+ clock := time.UnixMilli(100000)
403
+ v.Now = func() time.Time { return clock }
404
+ delayDelegateResponses(v, &clock, delay, 0)
405
+ if _, err := v.Delegate("role", false); err == nil {
406
+ t.Fatal("exhausted parent TTL accepted")
407
+ }
408
+ if f.creates != 0 || f.logins != 0 {
409
+ t.Fatal("exhausted TTL caused issuance or login")
410
+ }
411
+ }
412
+ }
413
+
414
+ func TestDelegateRetryResetsLookupAnchor(t *testing.T) {
415
+ f := &delegateFixture{ttl: 10, lookupDeniedOnce: true, auth: map[string]any{"client_token": "synthetic-child", "lease_duration": 5}}
416
+ v := newDelegateClient(t, f, "synthetic-parent")
417
+ clock := time.UnixMilli(100000)
418
+ v.Now = func() time.Time { return clock }
419
+ transport := v.HTTPClient.Transport
420
+ v.HTTPClient.Transport = delegateTransport(func(r *http.Request) (*http.Response, error) {
421
+ response, err := transport.RoundTrip(r)
422
+ if r.URL.Path == "/v1/auth/token/lookup-self" && f.lookups == 2 {
423
+ clock = clock.Add(2 * time.Second)
424
+ } else if r.URL.Path == "/v1/auth/token/lookup-self" || r.URL.Path == "/v1/auth/jwt/login" {
425
+ clock = clock.Add(100 * time.Second)
426
+ }
427
+ return response, err
428
+ })
429
+ if _, err := v.Delegate("role", false); err != nil {
430
+ t.Fatal(err)
431
+ }
432
+ if f.payload["ttl"] != "8s" || f.logins != 1 {
433
+ t.Fatal("lookup anchor not reset after normal login retry")
434
+ }
435
+ }
package/go.mod CHANGED
@@ -1,12 +1,12 @@
1
1
  module github.com/131/vvauth/v2
2
2
 
3
- // version: 2.6.1
3
+ // version: 2.7.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.7
9
+ github.com/131/vauth-login v1.1.8
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
@@ -4,6 +4,8 @@ github.com/131/ssh-agent-crypt v1.4.4 h1:6MlDUao1Yq6iNY4Bgin/iZp2q3X/g6qD6H1X4ad
4
4
  github.com/131/ssh-agent-crypt v1.4.4/go.mod h1:/THxpIdVrEAHxNoc6t6lVYBsSEd1zkCROPZepDe8QTI=
5
5
  github.com/131/vauth-login v1.1.7 h1:i256JyHP05WKqIrLv18ThfitGipH4oKnN7zpQESzV7U=
6
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=
7
9
  github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
8
10
  github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
9
11
  github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=