vvauth 2.6.2 → 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.
package/API_and_tests.md CHANGED
@@ -125,3 +125,39 @@ profile/KV operations, renewal, trust refusal, local secrets, configuration,
125
125
  JSON environment output and the shared armor/cache. Linux/Windows builds and
126
126
  Node 16 parsing/loading are checked separately. Release CI publishes npm,
127
127
  Go tags and Linux/signed Windows binaries; verify asset checksums independently.
128
+
129
+ ## Delegation verification
130
+
131
+ The public SDK operation is `Delegate(role, renew)`: Node returns a promise of a
132
+ string; Go returns `(string, error)`. `renew` forces only the child. `Env` keeps
133
+ its existing parent-renew flag behavior and passes the flag to child issuance
134
+ without logging in the parent again. No new CLI flag is needed.
135
+
136
+ `test/delegate.js` and `delegate_test.go` use synthetic parent/child credentials
137
+ and in-memory transport for roles, macros, TTL boundary reuse, renewal, parent
138
+ changes, invalid responses, unknown references, disk-off memory reuse and
139
+ failure-before-output. Go also verifies cache-key composition against Node.
140
+ SSH-agent tests verify encrypted persistence and bidirectional Node/Go cache
141
+ reuse; they need a throwaway SSH agent, not a real Vault or personal key.
142
+ `delegate_interop_test.go` exercises both languages' real parent `Connect`,
143
+ fresh-client disk reuse through the full TTL, exact expiry, request latency,
144
+ renewal and parent/role/address isolation. It runs in `go test ./...`.
145
+
146
+ Run the new tests without network or dependency changes:
147
+
148
+ ```bash
149
+ node test/delegate.js
150
+ GOPROXY=off GOFLAGS=-mod=readonly go test -v delegate.go delegate_test.go vauth.go rc.go vault.go gitlab.go
151
+ ```
152
+
153
+ The explicit Go file list avoids the historical suite's unconditional agent
154
+ `TestMain`; encrypted-cache tests skip if a synthetic agent cannot start. Full
155
+ regressions remain `npm test` and `GOPROXY=off GOFLAGS=-mod=readonly go test ./...`.
156
+ A restricted host that cannot bind SSH-agent sockets cannot validate the full
157
+ suite or encrypted interop. The socket-free recipe does not establish that
158
+ those skipped checks passed.
159
+
160
+ Server role ACLs, entity/group grants and JWT/OIDC authority configuration are
161
+ not simulated or applied here. `Env` needs its parent's existing profile-read
162
+ grants; `Delegate` does not. These tests do not establish production grants or
163
+ permission to issue a child under a particular authentication method.
package/README.md CHANGED
@@ -89,6 +89,58 @@ is not a sandbox for hostile configuration files.
89
89
  Tokens and resolved secrets are credentials: do not log them or store plaintext
90
90
  exports. Neither implementation prompts to trust an unknown project Vault.
91
91
 
92
+ ## Role-scoped delegation
93
+
94
+ Declare Vault token roles at the root and export their children only where needed:
95
+
96
+ ```yaml
97
+ vault_addr: https://vault.elipsdev.net
98
+ ssh_auth:
99
+ role: $${env.VAUTH_USER_LOGIN}
100
+ delegate:
101
+ - vauth-profile-ro
102
+ env:
103
+ map:
104
+ VAULT_ROUTER_TOKEN: $${delegate.vauth-profile-ro}
105
+ ```
106
+
107
+ Each entry names a server token role directly. `$${delegate.<role>}` resolves to
108
+ its child token string. Multiple roles are supported; declaring a role does not
109
+ export it automatically. `VAULT_TOKEN` remains the human/login token.
110
+
111
+ Node `await client.Delegate(role, renew = false)` and Go
112
+ `client.Delegate(role, renew)` return a token string (with native errors).
113
+ They reuse the established parent and call `auth/token/create/<role>` on a miss.
114
+ The request asks for a non-renewable service child without the default policy;
115
+ the role must be non-orphan and owns the ACL. No policies or entity alias are
116
+ overridden or checked by the client. A new child requests the parent's current
117
+ positive, finite remaining TTL, obtained from lookup-self, not its original
118
+ lease duration. A parent with TTL zero has no usable bounded delegation lifetime
119
+ and is rejected. A child TTL exceeding that requested remaining lifetime is
120
+ also rejected rather than capped. A rejected parent lookup (400/403) permits one normal login
121
+ retry; issuance errors never cause a human-token fallback.
122
+
123
+ The separate SSH-agent-encrypted cache lives in `~/.vauth/delegates`, using the
124
+ same encryption dependency in Node and Go. Its filename hashes the JSON tuple
125
+ `[Vault address without surrounding slashes, parent token, role]`; plaintext
126
+ cache content contains only the child and its expiration time in Unix
127
+ milliseconds. The parent lookup and child creation TTLs are anchored at each
128
+ request start: elapsed lookup time is deducted from the requested parent
129
+ lifetime, and response/processing time never extends the child deadline. A child
130
+ already expired on arrival is rejected. Children remain reusable until that
131
+ deadline, without online lookup on a cache hit. Expiry, a changed
132
+ parent/role/address or explicit child renewal emits a new child. `token_cache: false` disables disk access, not in-memory reuse.
133
+ Unavailable persistence leaves the child usable in memory; it never substitutes
134
+ the human token. An unknown delegation macro, invalid response or issuance error
135
+ fails environment resolution before any exports are published.
136
+
137
+ `Env` calls `GetProfile`: entity metadata and, when a login metadata field
138
+ exists, the personal `.vauth_database`. Its parent therefore needs those read
139
+ permissions. `Delegate` itself performs neither profile read; its parent only
140
+ needs permission to use the selected token role. JWT/SSH/OIDC grants and child
141
+ issuance permissions are decided by the Vault authority, not by this client.
142
+ Delegation does not add permissions to the parent.
143
+
92
144
  ## Security assessments
93
145
 
94
146
  [Claude](SECURITY_AUDIT_claude-opus-5-5.md) and
package/delegate.go ADDED
@@ -0,0 +1,213 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "bytes"
5
+ "crypto/sha256"
6
+ "encoding/hex"
7
+ "encoding/json"
8
+ "errors"
9
+ "fmt"
10
+ "math"
11
+ "os"
12
+ "path/filepath"
13
+ "regexp"
14
+ "strconv"
15
+ "strings"
16
+ "time"
17
+
18
+ sshagentcrypt "github.com/131/ssh-agent-crypt"
19
+ vauthlogin "github.com/131/vauth-login"
20
+ )
21
+
22
+ var delegateRole = regexp.MustCompile(`^[A-Za-z0-9_.-]+$`)
23
+ var delegateMacro = regexp.MustCompile(`(?i)\$\$\{([^}]+)\}|\$\$([a-z0-9._-]+)`)
24
+
25
+ type delegateCache struct {
26
+ Token string `json:"token"`
27
+ ExpiresAt float64 `json:"expires_at"`
28
+ }
29
+
30
+ func (c delegateCache) valid(parent string, now float64) bool {
31
+ return c.Token != "" && c.Token != parent && !math.IsNaN(c.ExpiresAt) && !math.IsInf(c.ExpiresAt, 0) && c.ExpiresAt > now
32
+ }
33
+
34
+ func (v *Vauth) delegateNow() float64 {
35
+ now := time.Now()
36
+ if v.Now != nil {
37
+ now = v.Now()
38
+ }
39
+ return float64(now.UnixMilli())
40
+ }
41
+
42
+ // delegateKey hashes a shared JSON tuple: no parent credential in filenames.
43
+ func delegateKey(address, parent, role string) string {
44
+ var body bytes.Buffer
45
+ encoder := json.NewEncoder(&body)
46
+ encoder.SetEscapeHTML(false)
47
+ encoder.Encode([]string{strings.Trim(address, "/"), parent, role})
48
+ hash := sha256.Sum256(bytes.TrimSuffix(body.Bytes(), []byte("\n")))
49
+ return hex.EncodeToString(hash[:])
50
+ }
51
+
52
+ func (v *Vauth) delegateFile(key string) string {
53
+ return filepath.Join(v.HomeDir, ".vauth", "delegates", key+".creds")
54
+ }
55
+
56
+ // Delegate emits or reuses a role-scoped child. renew forces child issuance,
57
+ // not another parent login. The server role owns the ACL.
58
+ func (v *Vauth) Delegate(role string, renew bool) (string, error) {
59
+ if !delegateRole.MatchString(role) || role == "." || role == ".." {
60
+ return "", errors.New("Invalid Vault delegation role")
61
+ }
62
+ if _, err := v.Connect(false); err != nil {
63
+ return "", err
64
+ }
65
+ parent := v.VAULT_TOKEN()
66
+ if parent == "" || v.VAULT_ADDR() == "" {
67
+ return "", errors.New("Vault delegation requires a parent token and address")
68
+ }
69
+ key := delegateKey(v.VAULT_ADDR(), parent, role)
70
+ if v.delegates == nil {
71
+ v.delegates = map[string]delegateCache{}
72
+ }
73
+ cache := v.delegates[key]
74
+ if !renew && !cache.valid(parent, v.delegateNow()) && v.TokenCache {
75
+ if armor, err := os.ReadFile(v.delegateFile(key)); err == nil {
76
+ if body, err := sshagentcrypt.Decrypt(armor, "", &sshagentcrypt.Options{AgentSocket: v.Agent}); err == nil {
77
+ // Invalid cache content is a miss, never a human-token fallback.
78
+ if json.Unmarshal(body, &cache) != nil {
79
+ cache = delegateCache{}
80
+ }
81
+ }
82
+ }
83
+ }
84
+ if !renew && cache.valid(parent, v.delegateNow()) {
85
+ v.delegates[key] = cache
86
+ return cache.Token, nil
87
+ }
88
+ lookupStarted := v.delegateNow()
89
+ info, err := v.LookupSelf(parent)
90
+ if err != nil {
91
+ var httpErr *vauthlogin.HTTPError
92
+ if !errors.As(err, &httpErr) || (httpErr.Status != 400 && httpErr.Status != 403) {
93
+ return "", err
94
+ }
95
+ if _, err := v.Connect(true); err != nil {
96
+ return "", err
97
+ }
98
+ parent = v.VAULT_TOKEN()
99
+ if parent == "" {
100
+ return "", errors.New("Vault delegation requires a parent token")
101
+ }
102
+ key = delegateKey(v.VAULT_ADDR(), parent, role)
103
+ lookupStarted = v.delegateNow()
104
+ info, err = v.LookupSelf(parent)
105
+ if err != nil {
106
+ return "", err
107
+ }
108
+ }
109
+ // Anchor server TTLs at request start; response time is not extra life.
110
+ createStarted := v.delegateNow()
111
+ ttl := info.TTL - (createStarted-lookupStarted)/1000
112
+ if ttl <= 0 || math.IsNaN(ttl) || math.IsInf(ttl, 0) {
113
+ return "", errors.New("Invalid Vault parent delegation TTL")
114
+ }
115
+ _, body, err := v.Request("POST", "auth/token/create/"+role, parent, map[string]any{
116
+ "ttl": strconv.FormatFloat(ttl, 'f', -1, 64) + "s", "renewable": false, "no_default_policy": true, "type": "service",
117
+ }, 200)
118
+ if err != nil {
119
+ return "", err
120
+ }
121
+ var response struct {
122
+ Auth *struct {
123
+ Token string `json:"client_token"`
124
+ TTL float64 `json:"lease_duration"`
125
+ } `json:"auth"`
126
+ }
127
+ if err := json.Unmarshal(body, &response); err != nil {
128
+ return "", err
129
+ }
130
+ if response.Auth == nil || response.Auth.Token == "" || response.Auth.Token == parent || response.Auth.TTL <= 0 || response.Auth.TTL > ttl {
131
+ return "", errors.New("Invalid Vault delegation response")
132
+ }
133
+ cache = delegateCache{Token: response.Auth.Token, ExpiresAt: createStarted + response.Auth.TTL*1000}
134
+ if !cache.valid(parent, v.delegateNow()) {
135
+ return "", errors.New("Invalid Vault delegation TTL")
136
+ }
137
+ v.delegates[key] = cache
138
+ if v.TokenCache {
139
+ v.saveDelegate(key, cache)
140
+ }
141
+ if !cache.valid(parent, v.delegateNow()) {
142
+ return "", errors.New("Expired Vault delegation response")
143
+ }
144
+ return cache.Token, nil
145
+ }
146
+
147
+ func (v *Vauth) saveDelegate(key string, cache delegateCache) {
148
+ // Persistence is best effort; memory reuse remains available without disk.
149
+ err := v.writeDelegate(key, cache)
150
+ if err != nil {
151
+ fmt.Fprintln(v.stderr(), "Could not encrypt/write delegation cache; token not persisted")
152
+ }
153
+ }
154
+
155
+ func (v *Vauth) writeDelegate(key string, cache delegateCache) error {
156
+ body, err := json.Marshal(cache)
157
+ if err != nil {
158
+ return err
159
+ }
160
+ identity := v.Environ["SSH_AGENT_CRYPT_KEY"]
161
+ if identity == "" {
162
+ identity = v.Environ["VAUTH_USER_IDENTITY"]
163
+ }
164
+ if identity == "" {
165
+ identity = v.Environ["VAUTH_USER_MAIL"]
166
+ }
167
+ armor, err := sshagentcrypt.Encrypt(body, identity, &sshagentcrypt.Options{AgentSocket: v.Agent})
168
+ if err != nil {
169
+ return err
170
+ }
171
+ file := v.delegateFile(key)
172
+ if err := os.MkdirAll(filepath.Dir(file), 0700); err != nil {
173
+ return err
174
+ }
175
+ temporary, err := os.CreateTemp(filepath.Dir(file), ".delegate-*.next")
176
+ if err != nil {
177
+ return err
178
+ }
179
+ defer os.Remove(temporary.Name())
180
+ _, err = temporary.WriteString(armor)
181
+ closeErr := temporary.Close()
182
+ if err != nil {
183
+ return err
184
+ }
185
+ if closeErr != nil {
186
+ return closeErr
187
+ }
188
+ return os.Rename(temporary.Name(), file)
189
+ }
190
+
191
+ func replaceDelegates(value string, delegates map[string]string) (string, error) {
192
+ var err error
193
+ expanded := delegateMacro.ReplaceAllStringFunc(value, func(macro string) string {
194
+ parts := delegateMacro.FindStringSubmatch(macro)
195
+ key := parts[1]
196
+ if key == "" {
197
+ key = parts[2]
198
+ }
199
+ if strings.ToLower(key) != "delegate" && !strings.HasPrefix(strings.ToLower(key), "delegate.") {
200
+ return macro
201
+ }
202
+ role := ""
203
+ if len(key) > len("delegate.") {
204
+ role = key[len("delegate."):]
205
+ }
206
+ token, ok := delegates[role]
207
+ if !ok {
208
+ err = fmt.Errorf("Unknown Vault delegation '%s'", role)
209
+ }
210
+ return token
211
+ })
212
+ return expanded, err
213
+ }
package/delegate.js ADDED
@@ -0,0 +1,85 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const {createHash, randomUUID} = require('crypto');
7
+ const VauthLogin = require('vauth-login');
8
+ const {encrypt, decrypt} = require('ssh-agent-crypt');
9
+
10
+ const roleName = /^[A-Za-z0-9_.-]+$/;
11
+ const valid = (cache, parent, now) => cache && typeof cache.token === 'string' && cache.token && cache.token !== parent && Number.isFinite(cache.expires_at) && cache.expires_at > now;
12
+
13
+ module.exports = {
14
+ async Delegate(role, renew = false) {
15
+ if(typeof role !== 'string' || !roleName.test(role) || ['.', '..'].includes(role))
16
+ throw new Error('Invalid Vault delegation role');
17
+ // Renewal belongs to the child; reuse the established parent login.
18
+ await this.Connect(false);
19
+ let parent = this.VAULT_TOKEN;
20
+ if(!parent || !this.VAULT_ADDR)
21
+ throw new Error('Vault delegation requires a parent token and address');
22
+ let key = createHash('sha256').update(JSON.stringify([this.VAULT_ADDR.replace(/^\/+|\/+$/g, ''), parent, role])).digest('hex');
23
+ let file = path.join(os.homedir(), '.vauth', 'delegates', key + '.creds');
24
+ this._delegates ||= new Map();
25
+ const disk = this.RC.token_cache !== false && (process.env.SSH_AUTH_SOCK || process.platform === 'win32');
26
+ let cache = this._delegates.get(key);
27
+ if(!renew && !valid(cache, parent, Date.now()) && disk)
28
+ try { cache = JSON.parse(await decrypt(fs.readFileSync(file))); } catch(err) {}
29
+ if(!renew && valid(cache, parent, Date.now())) {
30
+ this._delegates.set(key, cache);
31
+ return cache.token;
32
+ }
33
+ let info;
34
+ let lookupStarted = Date.now();
35
+ try {
36
+ info = await this.LookupSelf(parent);
37
+ } catch(err) {
38
+ if(!(err instanceof VauthLogin.HTTPError) || ![400, 403].includes(err.status))
39
+ throw err;
40
+ await this.Connect(true);
41
+ parent = this.VAULT_TOKEN;
42
+ if(!parent)
43
+ throw new Error('Vault delegation requires a parent token');
44
+ key = createHash('sha256').update(JSON.stringify([this.VAULT_ADDR.replace(/^\/+|\/+$/g, ''), parent, role])).digest('hex');
45
+ file = path.join(os.homedir(), '.vauth', 'delegates', key + '.creds');
46
+ lookupStarted = Date.now();
47
+ info = await this.LookupSelf(parent);
48
+ }
49
+ // Anchor server TTLs at request start; response time is not extra life.
50
+ const createStarted = Date.now();
51
+ const ttl = info.ttl - (createStarted - lookupStarted) / 1000;
52
+ if(!Number.isFinite(ttl) || ttl <= 0)
53
+ throw new Error('Invalid Vault parent delegation TTL');
54
+ const {body} = await this.Request('POST', `auth/token/create/${role}`, parent, {
55
+ ttl : `${ttl}s`, renewable : false, no_default_policy : true, type : 'service',
56
+ }, 200);
57
+ let response;
58
+ try { response = JSON.parse(body); } catch(err) {
59
+ throw new Error('Invalid Vault delegation response');
60
+ }
61
+ const auth = response && response.auth;
62
+ if(!auth || typeof auth.client_token !== 'string' || !auth.client_token || auth.client_token === parent || !Number.isFinite(auth.lease_duration) || auth.lease_duration <= 0 || auth.lease_duration > ttl)
63
+ throw new Error('Invalid Vault delegation response');
64
+ cache = {token : auth.client_token, expires_at : createStarted + auth.lease_duration * 1000};
65
+ if(!valid(cache, parent, Date.now()))
66
+ throw new Error('Invalid Vault delegation TTL');
67
+ this._delegates.set(key, cache);
68
+ if(disk) {
69
+ const temporary = file + '.' + randomUUID() + '.next';
70
+ try {
71
+ const armor = await encrypt(JSON.stringify(cache));
72
+ fs.mkdirSync(path.dirname(file), {recursive : true, mode : 0o700});
73
+ fs.writeFileSync(temporary, armor, {mode : 0o600, flag : 'wx'});
74
+ fs.renameSync(temporary, file);
75
+ } catch(err) {
76
+ console.error('Could not encrypt/write delegation cache; token not persisted');
77
+ } finally {
78
+ try { fs.unlinkSync(temporary); } catch(err) {}
79
+ }
80
+ }
81
+ if(!valid(cache, parent, Date.now()))
82
+ throw new Error('Expired Vault delegation response');
83
+ return cache.token;
84
+ },
85
+ };
@@ -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
+ }