vvauth 2.6.2 → 2.7.1

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,267 @@
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 {spawnSync} = require('child_process');
9
+ const {createHash} = require('crypto');
10
+ const Vvauth = require('../index');
11
+
12
+ function client(options = {}) {
13
+ const v = Object.create(Vvauth.prototype);
14
+ Object.defineProperties(v, {
15
+ VAULT_TOKEN : {value : options.parent || 'synthetic-parent', writable : true},
16
+ VAULT_ADDR : {value : 'https://synthetic.invalid'},
17
+ RC : {value : {token_cache : false}},
18
+ });
19
+ v.config = {delegate : ['vauth-profile-ro', 'project-ro'], env : {map : {
20
+ VAULT_ROUTER_TOKEN : '$${delegate.vauth-profile-ro}', PROJECT_TOKEN : '$$delegate.project-ro',
21
+ }}};
22
+ v.calls = [];
23
+ v.Connect = async renew => { v.calls.push(['connect', renew]); return v.VAULT_TOKEN; };
24
+ v.GetProfile = async renew => { await v.Connect(renew); return {profile : {}, database : {}}; };
25
+ v.LookupSelf = async token => { v.calls.push(['lookup', token]); return {ttl : options.ttl === undefined ? 1234.5 : options.ttl}; };
26
+ v.Request = async (method, route, token, payload) => {
27
+ v.calls.push(['create', route, token, payload]);
28
+ if(options.error) throw new Error('synthetic issuance denied');
29
+ if(options.body !== undefined) return {body : options.body};
30
+ return {body : JSON.stringify({auth : options.auth === undefined ? {client_token : `synthetic-child-${v.calls.length}`, lease_duration : 1000} : options.auth})};
31
+ };
32
+ return v;
33
+ }
34
+
35
+ const creations = v => v.calls.filter(call => call[0] === 'create');
36
+
37
+ test('native config, multiple roles and explicit exports retain the human token', async t => {
38
+ t.mock.method(Date, 'now', () => 100000);
39
+ const v = client();
40
+ const env = await v.Env();
41
+ assert.equal(env.VAULT_TOKEN, 'synthetic-parent');
42
+ assert.notEqual(env.VAULT_ROUTER_TOKEN, env.VAULT_TOKEN);
43
+ assert.notEqual(env.PROJECT_TOKEN, env.VAULT_ROUTER_TOKEN);
44
+ assert.deepEqual(Object.keys(env), ['VAULT_TOKEN', 'VAULT_ADDR', 'VAULT_ROUTER_TOKEN', 'PROJECT_TOKEN']);
45
+ assert.deepEqual(creations(v)[0].slice(1), ['auth/token/create/vauth-profile-ro', 'synthetic-parent', {
46
+ ttl : '1234.5s', renewable : false, no_default_policy : true, type : 'service',
47
+ }]);
48
+ v.config.env.map = {};
49
+ assert.deepEqual(Object.keys(await v.Env()), ['VAULT_TOKEN', 'VAULT_ADDR']);
50
+ });
51
+
52
+ test('full TTL memory reuse, expiry, renew, parent and role isolation with disk off', async () => {
53
+ const v = client();
54
+ const now = Date.now;
55
+ let clock = 100000;
56
+ Date.now = () => clock;
57
+ try {
58
+ const first = await v.Delegate('vauth-profile-ro');
59
+ clock += 999999;
60
+ assert.equal(await v.Delegate('vauth-profile-ro'), first);
61
+ assert.equal(creations(v).length, 1);
62
+ assert.equal(v.calls.filter(call => call[0] === 'lookup').length, 1);
63
+ clock++;
64
+ assert.notEqual(await v.Delegate('vauth-profile-ro'), first);
65
+ assert.notEqual(await v.Delegate('vauth-profile-ro', true), first);
66
+ await v.Delegate('project-ro');
67
+ v.VAULT_TOKEN = 'synthetic-other-parent';
68
+ await v.Delegate('vauth-profile-ro');
69
+ assert.equal(creations(v).length, 5);
70
+ assert.ok(v.calls.filter(call => call[0] === 'connect').every(call => call[1] === false));
71
+ assert.ok([...v._delegates.keys()].every(key => !key.includes('synthetic')));
72
+ assert.ok([...v._delegates.values()].every(cache => !JSON.stringify(cache).includes('parent')));
73
+ } finally { Date.now = now; }
74
+ });
75
+
76
+ test('unknown macros, issuance and invalid responses fail without partial output', async () => {
77
+ for(const options of [{error : true}, {body : '{malformed'}, {body : 'null'}, {auth : null}, {auth : {}},
78
+ {auth : {client_token : 'synthetic-parent', lease_duration : 10}},
79
+ {auth : {client_token : 'synthetic-child', lease_duration : 0}},
80
+ {auth : {client_token : 'synthetic-child', lease_duration : 2000}},
81
+ {auth : {client_token : 'synthetic-child', lease_duration : '10'}}, {ttl : 0}, {ttl : -1}]) {
82
+ const v = client(options);
83
+ let published = false;
84
+ v.PublishEnv = () => { published = true; };
85
+ await assert.rejects(v.Env(true));
86
+ assert.equal(published, false);
87
+ }
88
+ for(const macro of ['$${delegate.unknown}', '$$delegate.unknown', '$${delegate}']) {
89
+ const v = client();
90
+ v.config.env.map = {OK : 'value', BAD : macro};
91
+ let published = false;
92
+ v.PublishEnv = () => { published = true; };
93
+ await assert.rejects(v.Env(true), /Unknown Vault delegation/);
94
+ assert.equal(published, false);
95
+ }
96
+ const v = client();
97
+ delete v.config.delegate;
98
+ v.config.env.map = {OK : 'value'};
99
+ assert.equal((await v.Env()).OK, 'value');
100
+ assert.equal(creations(v).length, 0);
101
+ for(const role of ['', '../other', '.', '..', {}])
102
+ await assert.rejects(v.Delegate(role));
103
+ });
104
+
105
+ test('encrypted disk cache reuse uses no child or parent lookup', async t => {
106
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'vvauth-delegate-'));
107
+ t.after(() => fs.rmSync(directory, {recursive : true, force : true}));
108
+ const agent = spawnSync('ssh-agent', ['-s'], {encoding : 'utf8'});
109
+ if(agent.status !== 0) {
110
+ t.skip('sandbox cannot start a synthetic ssh-agent');
111
+ return;
112
+ }
113
+ const socket = agent.stdout.match(/SSH_AUTH_SOCK=([^;]+)/)[1];
114
+ const pid = Number(agent.stdout.match(/SSH_AGENT_PID=(\d+)/)[1]);
115
+ t.after(() => process.kill(pid));
116
+ const previous = {};
117
+ for(const key of ['HOME', 'USERPROFILE', 'SSH_AUTH_SOCK', 'SSH_AGENT_CRYPT_KEY', 'VAUTH_USER_IDENTITY', 'VAUTH_USER_MAIL']) {
118
+ previous[key] = process.env[key];
119
+ delete process.env[key];
120
+ }
121
+ Object.assign(process.env, {HOME : directory, USERPROFILE : directory, SSH_AUTH_SOCK : socket});
122
+ t.after(() => {
123
+ for(const [key, value] of Object.entries(previous)) {
124
+ if(value === undefined) delete process.env[key];
125
+ else process.env[key] = value;
126
+ }
127
+ });
128
+ const key = path.join(directory, 'key');
129
+ assert.equal(spawnSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-f', key]).status, 0);
130
+ assert.equal(spawnSync('ssh-add', [key]).status, 0);
131
+ const v = client();
132
+ v.RC.token_cache = true;
133
+ const token = await v.Delegate('vauth-profile-ro');
134
+ const hash = createHash('sha256').update(JSON.stringify([v.VAULT_ADDR, v.VAULT_TOKEN, 'vauth-profile-ro'])).digest('hex');
135
+ const file = path.join(directory, '.vauth', 'delegates', hash + '.creds');
136
+ const armor = fs.readFileSync(file, 'utf8');
137
+ assert.ok(armor.startsWith('ssh-agent-crypt:v3:'));
138
+ assert.ok(!armor.includes(token) && !armor.includes(v.VAULT_TOKEN));
139
+ assert.equal(fs.statSync(file).mode & 0o777, 0o600);
140
+ const next = client();
141
+ next.RC.token_cache = true;
142
+ assert.equal(await next.Delegate('vauth-profile-ro'), token);
143
+ assert.equal(next.calls.filter(call => call[0] !== 'connect').length, 0);
144
+ });
145
+
146
+ test('approved YAML loads root role list without auth defaults or policy assertions', t => {
147
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'vvauth-native-'));
148
+ t.after(() => fs.rmSync(directory, {recursive : true, force : true}));
149
+ const file = path.join(directory, '.vauthrc');
150
+ fs.writeFileSync(file, `vault_addr: https://vault.elipsdev.net
151
+ ssh_auth:
152
+ role: $\u0024{env.VAUTH_USER_LOGIN}
153
+ delegate:
154
+ - vauth-profile-ro
155
+ env:
156
+ map:
157
+ VAULT_ROUTER_TOKEN: $\u0024{delegate.vauth-profile-ro}
158
+ `);
159
+ const script = `const assert=require('assert/strict');const V=require('./index');const v=new V();
160
+ assert.deepEqual(v.config.delegate,['vauth-profile-ro']);
161
+ assert.equal(v.config.env.map.VAULT_ROUTER_TOKEN,'$\u0024{delegate.vauth-profile-ro}');
162
+ assert.deepEqual(Object.keys(v.RC),['vault_addr','ssh_auth','delegate','env']);`;
163
+ const child = spawnSync('node', ['-e', script], {encoding : 'utf8', env : {
164
+ PATH : process.env.PATH, HOME : directory, VAUTHRC : file, VAUTH_USER_LOGIN : 'synthetic-user',
165
+ }});
166
+ assert.equal(child.status, 0, child.stderr);
167
+ });
168
+
169
+ test('only an invalid parent triggers one normal login retry, never issuance denial', async t => {
170
+ t.mock.method(Date, 'now', () => 100000);
171
+ const v = client();
172
+ let lookups = 0;
173
+ v.LookupSelf = async () => {
174
+ if(++lookups === 1) throw new (require('vauth-login').HTTPError)(403, 'synthetic denial');
175
+ return {ttl : 1000};
176
+ };
177
+ v.Connect = async renew => {
178
+ v.calls.push(['connect', renew]);
179
+ if(renew) v.VAULT_TOKEN = 'synthetic-new-parent';
180
+ };
181
+ await v.Delegate('vauth-profile-ro', true);
182
+ assert.equal(v.calls.filter(call => call[0] === 'connect' && call[1]).length, 1);
183
+ assert.equal(creations(v)[0][2], 'synthetic-new-parent');
184
+ });
185
+
186
+ test('delayed responses consume parent TTL and keep the child request-time deadline', async t => {
187
+ let clock = 100000;
188
+ t.mock.method(Date, 'now', () => clock);
189
+ const v = client({ttl : 10, auth : {client_token : 'synthetic-delayed-child', lease_duration : 5}});
190
+ const lookup = v.LookupSelf.bind(v), create = v.Request.bind(v);
191
+ v.LookupSelf = async token => {
192
+ const info = await lookup(token);
193
+ clock += 2000;
194
+ return info;
195
+ };
196
+ v.Request = async (...args) => {
197
+ const response = await create(...args);
198
+ clock += 3000;
199
+ return response;
200
+ };
201
+ const token = await v.Delegate('role');
202
+ assert.equal(creations(v)[0][3].ttl, '8s');
203
+ assert.equal([...v._delegates.values()][0].expires_at, 107000);
204
+ clock = 106999;
205
+ assert.equal(await v.Delegate('role'), token);
206
+ assert.equal(creations(v).length, 1);
207
+ assert.equal(v.calls.filter(call => call[0] === 'lookup').length, 1);
208
+ clock = 107000;
209
+ await v.Delegate('role');
210
+ assert.equal(creations(v).length, 2);
211
+ assert.ok(v.calls.filter(call => call[0] === 'connect').every(call => call[1] === false));
212
+ });
213
+
214
+ test('a child expired on arrival is never cached or published', async t => {
215
+ let clock = 100000;
216
+ t.mock.method(Date, 'now', () => clock);
217
+ for(const delay of [5000, 6000]) {
218
+ const v = client({ttl : 10, auth : {client_token : 'synthetic-delayed-child', lease_duration : 5}});
219
+ const create = v.Request.bind(v);
220
+ v.Request = async (...args) => {
221
+ const response = await create(...args);
222
+ clock += delay;
223
+ return response;
224
+ };
225
+ let published = false;
226
+ v.PublishEnv = () => { published = true; };
227
+ await assert.rejects(v.Env(true), /delegation/);
228
+ assert.equal(v._delegates.size, 0);
229
+ assert.equal(published, false);
230
+ }
231
+ });
232
+
233
+ test('parent lifetime consumed by lookup prevents issuance without another login', async t => {
234
+ let clock = 100000;
235
+ t.mock.method(Date, 'now', () => clock);
236
+ for(const delay of [10000, 11000]) {
237
+ const v = client({ttl : 10});
238
+ v.LookupSelf = async () => { clock += delay; return {ttl : 10}; };
239
+ await assert.rejects(v.Delegate('role'), /parent delegation TTL/);
240
+ assert.equal(creations(v).length, 0);
241
+ assert.deepEqual(v.calls, [['connect', false]]);
242
+ }
243
+ });
244
+
245
+ test('parent lookup anchor resets only after the existing login retry', async t => {
246
+ let clock = 100000, lookups = 0;
247
+ t.mock.method(Date, 'now', () => clock);
248
+ const v = client({auth : {client_token : 'synthetic-child', lease_duration : 5}});
249
+ v.LookupSelf = async () => {
250
+ if(++lookups === 1) {
251
+ clock += 100000;
252
+ throw new (require('vauth-login').HTTPError)(403, 'synthetic denial');
253
+ }
254
+ clock += 2000;
255
+ return {ttl : 10};
256
+ };
257
+ v.Connect = async renew => {
258
+ v.calls.push(['connect', renew]);
259
+ if(renew) {
260
+ clock += 100000;
261
+ v.VAULT_TOKEN = 'synthetic-new-parent';
262
+ }
263
+ };
264
+ await v.Delegate('role');
265
+ assert.equal(creations(v)[0][3].ttl, '8s');
266
+ assert.equal(v.calls.filter(call => call[0] === 'connect' && call[1]).length, 1);
267
+ });
package/vauth.go CHANGED
@@ -39,9 +39,10 @@ const FunctionDecl = `function ` + FunctionName + `() { source <(/usr/bin/env va
39
39
  // fields may be set directly for programmatic use.
40
40
  type Vauth struct {
41
41
  *vauthlogin.Vauth
42
- Config Config
43
- Stdout io.Writer
44
- Stdin io.Reader
42
+ Config Config
43
+ Stdout io.Writer
44
+ Stdin io.Reader
45
+ delegates map[string]delegateCache
45
46
  }
46
47
 
47
48
  // CheckProjectVersion fails when manifest (a package.json) declares a
@@ -310,15 +311,31 @@ func (v *Vauth) Env(renew bool) (*OrderedMap, error) {
310
311
  secrets[k] = val
311
312
  }
312
313
  }
314
+ delegate := map[string]string{}
315
+ for _, role := range v.Config.Delegate {
316
+ token, err := v.Delegate(role, renew)
317
+ if err != nil {
318
+ return nil, err
319
+ }
320
+ delegate[role] = token
321
+ }
313
322
  dict := map[string]any{"env": v.Environ, "profile": merged, "secrets": secrets}
314
323
  for _, key := range mapping.Keys {
315
324
  if !envName.MatchString(key) {
316
325
  return nil, fmt.Errorf("Invalid environment variable name '%s' in env.map", key)
317
326
  }
318
- value, err := envValue(nyksstring.ReplaceEnv(mapping.Values[key], dict))
327
+ expanded, err := replaceDelegates(mapping.Values[key], delegate)
328
+ if err != nil {
329
+ return nil, err
330
+ }
331
+ value, err := envValue(nyksstring.ReplaceEnv(expanded, dict))
319
332
  if err != nil {
320
333
  return nil, fmt.Errorf("Invalid environment value '%s' in env.map: %w", key, err)
321
334
  }
335
+ value, err = replaceDelegates(value, delegate)
336
+ if err != nil {
337
+ return nil, err
338
+ }
322
339
  env.Set(key, value)
323
340
  }
324
341
  return env, nil