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.
package/API_and_tests.md CHANGED
@@ -15,8 +15,7 @@ venv --gitlab
15
15
 
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
- `vauth env --source "$@"`; renewal forces authentication. GitLab initialization
19
- publishes only four `CI_PROJECT_*` exports, without login, cache or file writes.
18
+ `vauth env --source "$@"`; renewal forces authentication.
20
19
 
21
20
  ## Node CLI — cnyks
22
21
 
@@ -94,17 +93,12 @@ check required CI variables when `env.gitlab` is true; explicit initialization
94
93
  bypasses that prerequisite. There is no Git inference at construction.
95
94
 
96
95
  RC is the complete raw configuration; environment sections are copied before
97
- macro expansion. Go snapshot maps do not retain YAML key order. Both support
96
+ macro expansion. Both support
98
97
  SSH-agent-backed local secret decryption, inherited tokens and forced renewal.
99
98
  `env.map` names must be valid environment names. Values become strings; null
100
99
  becomes empty, and objects/arrays are rejected, including macro results. Raw RC
101
100
  values retain their JSON types. Missing Git identity fields export empty values.
102
101
 
103
- Go macro expansion and value walking come from `github.com/131/nyks/v6`.
104
- Configuration operates on JSON-compatible values rather than round-tripping
105
- RC through a YAML tree. Walking preserves keys and the raw RC snapshot;
106
- `env.map` validation and scalar-to-string conversion remain in vvauth.
107
-
108
102
  ## Configuration trust boundary
109
103
 
110
104
  The selected configuration controls exported variable names/values and which
@@ -130,4 +124,40 @@ Vault fixtures; they do not require real credentials. Differential checks cover
130
124
  profile/KV operations, renewal, trust refusal, local secrets, configuration,
131
125
  JSON environment output and the shared armor/cache. Linux/Windows builds and
132
126
  Node 16 parsing/loading are checked separately. Release CI publishes npm,
133
- Go tags and signed Windows/Linux binaries; verify asset checksums independently.
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
@@ -24,8 +24,14 @@ venv
24
24
  venv --renew
25
25
  ```
26
26
 
27
- `venv` sources the exports produced by `vauth env --source`. `--renew` forces
28
- fresh authentication. For a machine-readable result:
27
+ `vauth install` defines the Bash function `venv` in `~/.bashrc`:
28
+
29
+ ```bash
30
+ function venv() { source <(/usr/bin/env vauth env --source "$@"); }
31
+ ```
32
+
33
+ `source ~/.bashrc` loads it in the current shell. `--renew` forces fresh
34
+ authentication. For a machine-readable result:
29
35
 
30
36
  ```bash
31
37
  vauth env --ir://json
@@ -39,6 +45,8 @@ stderr. Node uses cnyks for its CLI; Go has a native command interface.
39
45
 
40
46
  The first existing configuration is selected: `VAUTHRC`, `./.vauthrc`, then
41
47
  `~/.vauthrc`. It is YAML; `VAULT_ADDR` supplies the address fallback.
48
+ The resolved SSH role is normalized to lowercase by vauth-login in both
49
+ implementations; the source configuration, other fields and JWT roles are unchanged.
42
50
 
43
51
  ```yaml
44
52
  vault_addr: https://vault.example.test
@@ -66,9 +74,6 @@ Initialize them explicitly from `origin`:
66
74
  venv --gitlab
67
75
  ```
68
76
 
69
- This exports only `CI_PROJECT_PATH`, `CI_PROJECT_NAME`, `CI_PROJECT_NAMESPACE`
70
- and `CI_PROJECT_PATH_SLUG`. It does not authenticate or modify configuration.
71
-
72
77
  ## Tokens and trust
73
78
 
74
79
  An inherited `VAULT_TOKEN` is reused offline. Otherwise, vauth-login handles
@@ -84,6 +89,58 @@ is not a sandbox for hostile configuration files.
84
89
  Tokens and resolved secrets are credentials: do not log them or store plaintext
85
90
  exports. Neither implementation prompts to trust an unknown project Vault.
86
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
+
87
144
  ## Security assessments
88
145
 
89
146
  [Claude](SECURITY_AUDIT_claude-opus-5-5.md) and
@@ -93,6 +150,12 @@ checks and limitations. They are independent source reviews, not certification.
93
150
  reviewer limitations from host validation; [provenance](SECURITY_AUDIT_PROVENANCE.json)
94
151
  records the exact source, models and prompt/report hashes.
95
152
 
153
+ | Criterion | Claude Opus 5.5 | GPT 6.1 Sol |
154
+ | --- | ---: | ---: |
155
+ | ✨ **Coolness** | 15/20 | 17/20 |
156
+ | Robustness | 13/20 | 13/20 |
157
+ | Safety | 13/20 | 12/20 |
158
+
96
159
  ## Credits
97
160
 
98
161
  - [Francois Leurent](https://github.com/131)
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
+ };