vvauth 2.6.0 → 2.6.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.
package/rc.go CHANGED
@@ -4,40 +4,37 @@ import (
4
4
  "bytes"
5
5
  "encoding/json"
6
6
  "fmt"
7
- "net/url"
8
- "os/exec"
9
- "path/filepath"
10
- "regexp"
11
7
  "strconv"
12
- "strings"
13
8
 
9
+ nyksobject "github.com/131/nyks/v6/object"
10
+ nyksstring "github.com/131/nyks/v6/string"
14
11
  "gopkg.in/yaml.v3"
15
12
  )
16
13
 
17
14
  // Config contains only environment/profile settings; authentication is
18
15
  // parsed and owned by vauth-login.
19
16
  type Config struct {
20
- AgentCrypt *AgentCrypt `yaml:"ssh-agent-crypt"`
21
- Env *EnvConfig `yaml:"env"`
17
+ AgentCrypt *AgentCrypt `json:"ssh-agent-crypt" yaml:"ssh-agent-crypt"`
18
+ Env *EnvConfig `json:"env" yaml:"env"`
22
19
  }
23
20
 
24
21
  // AgentCrypt points to a local ssh-agent-crypt armored JSON file whose keys
25
22
  // feed $${secrets.X}.
26
23
  type AgentCrypt struct {
27
- Path string `yaml:"path"`
28
- Identity string `yaml:"identity"`
24
+ Path string `json:"path" yaml:"path"`
25
+ Identity string `json:"identity" yaml:"identity"`
29
26
  }
30
27
 
31
28
  // EnvConfig describes the environment to resolve.
32
29
  type EnvConfig struct {
33
- Map OrderedMap `yaml:"map"`
34
- Paths []string `yaml:"paths"`
35
- Path string `yaml:"path"`
36
- Git bool `yaml:"git"`
37
- GitLab bool `yaml:"gitlab"`
30
+ Map OrderedMap `json:"map" yaml:"map"`
31
+ Paths []string `json:"paths" yaml:"paths"`
32
+ Path string `json:"path" yaml:"path"`
33
+ Git bool `json:"git" yaml:"git"`
34
+ GitLab bool `json:"gitlab" yaml:"gitlab"`
38
35
  }
39
36
 
40
- // OrderedMap keeps the YAML document order of a string mapping.
37
+ // OrderedMap keeps the decoded JSON order of a string mapping.
41
38
  type OrderedMap struct {
42
39
  Keys []string
43
40
  Values map[string]string
@@ -63,22 +60,34 @@ func (m *OrderedMap) Get(key string) (string, bool) {
63
60
  // Len returns the number of entries.
64
61
  func (m *OrderedMap) Len() int { return len(m.Keys) }
65
62
 
66
- // UnmarshalYAML decodes a mapping, scalars as strings.
67
- func (m *OrderedMap) UnmarshalYAML(node *yaml.Node) error {
68
- if node.Kind != yaml.MappingNode {
69
- return fmt.Errorf("line %d: expected a mapping", node.Line)
63
+ // UnmarshalJSON decodes scalar values while retaining their JSON key order.
64
+ func (m *OrderedMap) UnmarshalJSON(body []byte) error {
65
+ decoder := json.NewDecoder(bytes.NewReader(body))
66
+ token, err := decoder.Token()
67
+ if err != nil {
68
+ return err
69
+ }
70
+ if token != json.Delim('{') {
71
+ return fmt.Errorf("expected a mapping")
70
72
  }
71
- for i := 0; i+1 < len(node.Content); i += 2 {
72
- var key, value string
73
- if err := node.Content[i].Decode(&key); err != nil {
73
+ for decoder.More() {
74
+ token, err := decoder.Token()
75
+ if err != nil {
74
76
  return err
75
77
  }
76
- if err := node.Content[i+1].Decode(&value); err != nil {
78
+ key := token.(string)
79
+ var value any
80
+ if err := decoder.Decode(&value); err != nil {
77
81
  return err
78
82
  }
79
- m.Set(key, value)
83
+ text, err := envValue(value)
84
+ if err != nil {
85
+ return fmt.Errorf("Invalid environment value '%s' in env.map: %w", key, err)
86
+ }
87
+ m.Set(key, text)
80
88
  }
81
- return nil
89
+ _, err = decoder.Token()
90
+ return err
82
91
  }
83
92
 
84
93
  // MarshalJSON renders the entries in order.
@@ -97,38 +106,6 @@ func (m OrderedMap) MarshalJSON() ([]byte, error) {
97
106
  return out.Bytes(), nil
98
107
  }
99
108
 
100
- // Lookup resolves dotted paths ($${env.X}) in nested string maps.
101
- type Lookup map[string]any
102
-
103
- func (dict Lookup) get(path string) (string, bool) {
104
- var current any = map[string]any(dict)
105
- for _, part := range strings.Split(path, ".") {
106
- switch node := current.(type) {
107
- case map[string]any:
108
- value, ok := node[part]
109
- if !ok {
110
- return "", false
111
- }
112
- current = value
113
- case map[string]string:
114
- value, ok := node[part]
115
- if !ok {
116
- return "", false
117
- }
118
- current = value
119
- case Lookup:
120
- value, ok := node[part]
121
- if !ok {
122
- return "", false
123
- }
124
- current = value
125
- default:
126
- return "", false
127
- }
128
- }
129
- return stringify(current)
130
- }
131
-
132
109
  func stringify(value any) (string, bool) {
133
110
  switch v := value.(type) {
134
111
  case nil:
@@ -149,44 +126,32 @@ func stringify(value any) (string, bool) {
149
126
  return string(body), true
150
127
  }
151
128
 
152
- var macroPattern = regexp.MustCompile(`(?i)\$\$([a-z0-9._-]+)|\$\$\{([^}]+)\}`)
153
-
154
- // ReplaceEnv expands $$key and $${key} macros against dict (nyks
155
- // string/replaceEnv semantics): unknown keys stay, expansions recurse.
156
- func ReplaceEnv(str string, dict Lookup) string {
157
- for depth := 0; depth < 16; depth++ {
158
- touched := false
159
- str = macroPattern.ReplaceAllStringFunc(str, func(macro string) string {
160
- match := macroPattern.FindStringSubmatch(macro)
161
- key := match[1]
162
- if key == "" {
163
- key = match[2]
129
+ // envValue accepts only JSON scalars, rendering numbers like JavaScript String.
130
+ func envValue(value any) (string, error) {
131
+ switch value := value.(type) {
132
+ case nil:
133
+ return "", nil
134
+ case string:
135
+ return value, nil
136
+ case bool:
137
+ return strconv.FormatBool(value), nil
138
+ case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, json.Number:
139
+ body, err := json.Marshal(value)
140
+ var number float64
141
+ if err == nil {
142
+ err = json.Unmarshal(body, &number)
143
+ }
144
+ if err == nil {
145
+ if number == 0 {
146
+ return "0", nil
164
147
  }
165
- value, ok := dict.get(key)
166
- if !ok {
167
- return macro
148
+ body, err = json.Marshal(number)
149
+ if err == nil {
150
+ return string(body), nil
168
151
  }
169
- touched = true
170
- return value
171
- })
172
- if !touched {
173
- break
174
- }
175
- }
176
- return str
177
- }
178
-
179
- // walk expands every scalar string of a YAML tree in place.
180
- func walk(node *yaml.Node, process func(string) string) {
181
- if node.Kind == yaml.ScalarNode {
182
- if node.Tag == "!!str" || node.Tag == "" {
183
- node.Value = process(node.Value)
184
152
  }
185
- return
186
- }
187
- for _, child := range node.Content {
188
- walk(child, process)
189
153
  }
154
+ return "", fmt.Errorf("expected a scalar")
190
155
  }
191
156
 
192
157
  // jsonString encodes like JSON.stringify (no HTML escaping).
@@ -198,123 +163,46 @@ func jsonString(value string) []byte {
198
163
  return bytes.TrimRight(out.Bytes(), "\n")
199
164
  }
200
165
 
201
- func mappingValue(node *yaml.Node, key string) *yaml.Node {
202
- if node == nil {
203
- return nil
204
- }
205
- if node.Kind == yaml.DocumentNode && len(node.Content) > 0 {
206
- node = node.Content[0]
207
- }
208
- if node.Kind != yaml.MappingNode {
209
- return nil
210
- }
211
- for i := 0; i+1 < len(node.Content); i += 2 {
212
- if node.Content[i].Value == key {
213
- return node.Content[i+1]
214
- }
215
- }
216
- return nil
217
- }
218
-
219
166
  // ParseConfig expands environment/profile sections from a standalone YAML body.
220
- // With env.gitlab outside CI, CI_PROJECT_* comes from the file's Git repository.
221
167
  func ParseConfig(body []byte, file string, environ map[string]string) (*Config, error) {
222
- var document yaml.Node
223
- if err := yaml.Unmarshal(body, &document); err != nil {
168
+ var rc map[string]any
169
+ if err := yaml.Unmarshal(body, &rc); err != nil {
224
170
  return nil, fmt.Errorf("Could not parse %s: %w", file, err)
225
171
  }
226
- return compileConfig(&document, file, filepath.Dir(file), environ)
172
+ return compileConfig(rc, file, environ)
227
173
  }
228
174
 
229
- // configFromRC consumes the independent JSON snapshot without reopening its file.
230
- func configFromRC(rc map[string]any, dir string, environ map[string]string) (*Config, error) {
231
- var document yaml.Node
232
- if err := document.Encode(rc); err != nil {
233
- return nil, fmt.Errorf("Could not read RC: %w", err)
234
- }
235
- return compileConfig(&document, "RC", dir, environ)
175
+ // configFromRC consumes the independent JSON snapshot without a YAML roundtrip.
176
+ func configFromRC(rc map[string]any, environ map[string]string) (*Config, error) {
177
+ return compileConfig(rc, "RC", environ)
236
178
  }
237
179
 
238
- func compileConfig(document *yaml.Node, file, dir string, environ map[string]string) (*Config, error) {
239
- root := document
240
- if root.Kind == yaml.DocumentNode {
241
- if len(root.Content) == 0 {
242
- return &Config{}, nil
180
+ func compileConfig(rc map[string]any, file string, environ map[string]string) (*Config, error) {
181
+ selected := map[string]any{}
182
+ for _, key := range []string{"env", "ssh-agent-crypt"} {
183
+ if value, ok := rc[key]; ok {
184
+ selected[key] = value
243
185
  }
244
- root = root.Content[0]
245
186
  }
246
- if root.Kind != yaml.MappingNode {
247
- return nil, fmt.Errorf("Could not parse %s: expected a mapping", file)
187
+ // Clone the selected sections before Walk, preserving the raw RC snapshot.
188
+ body, err := json.Marshal(selected)
189
+ if err != nil {
190
+ return nil, fmt.Errorf("Could not parse %s: %w", file, err)
248
191
  }
249
- var content []*yaml.Node
250
- for i := 0; i+1 < len(root.Content); i += 2 {
251
- switch root.Content[i].Value {
252
- case "env", "ssh-agent-crypt":
253
- content = append(content, root.Content[i], root.Content[i+1])
254
- }
192
+ var document map[string]any
193
+ if err := json.Unmarshal(body, &document); err != nil {
194
+ return nil, fmt.Errorf("Could not parse %s: %w", file, err)
255
195
  }
256
- root.Content = content
257
- if gitlab := mappingValue(mappingValue(document, "env"), "gitlab"); gitlab != nil && truthy(gitlab) && environ["CI"] == "" {
258
- environ = withGitLabProject(environ, dir)
196
+ nyksobject.Walk(document, func(value string) any {
197
+ return nyksstring.ReplaceEnv(value, map[string]any{"env": environ})
198
+ })
199
+ body, err = json.Marshal(document)
200
+ if err != nil {
201
+ return nil, fmt.Errorf("Could not parse %s: %w", file, err)
259
202
  }
260
- walk(document, func(value string) string { return ReplaceEnv(value, Lookup{"env": environ}) })
261
203
  var config Config
262
- if err := document.Decode(&config); err != nil {
204
+ if err := json.Unmarshal(body, &config); err != nil {
263
205
  return nil, fmt.Errorf("Could not parse %s: %w", file, err)
264
206
  }
265
207
  return &config, nil
266
208
  }
267
-
268
- func truthy(node *yaml.Node) bool {
269
- switch node.Kind {
270
- case yaml.ScalarNode:
271
- switch node.Tag {
272
- case "!!null":
273
- return false
274
- case "!!bool":
275
- return node.Value == "true"
276
- case "!!int", "!!float":
277
- return node.Value != "0" && node.Value != "0.0"
278
- }
279
- return node.Value != ""
280
- }
281
- return true
282
- }
283
-
284
- var scpRemote = regexp.MustCompile(`^[^@]+@[^:]+:(.+)$`)
285
-
286
- func withGitLabProject(environ map[string]string, dir string) map[string]string {
287
- cmd := exec.Command("git", "remote", "get-url", "origin")
288
- cmd.Dir = dir
289
- out, err := cmd.Output()
290
- if err != nil {
291
- return environ
292
- }
293
- remote := strings.TrimSpace(string(out))
294
- var project string
295
- if match := scpRemote.FindStringSubmatch(remote); match != nil {
296
- project = match[1]
297
- } else if parsed, err := url.Parse(remote); err == nil {
298
- project = parsed.Path
299
- }
300
- project = strings.TrimSuffix(strings.Trim(project, "/"), ".git")
301
- if project == "" {
302
- return environ
303
- }
304
- parts := strings.Split(project, "/")
305
- extended := make(map[string]string, len(environ)+4)
306
- for k, v := range environ {
307
- extended[k] = v
308
- }
309
- extended["CI_PROJECT_PATH"] = project
310
- extended["CI_PROJECT_NAME"] = parts[len(parts)-1]
311
- extended["CI_PROJECT_NAMESPACE"] = strings.Join(parts[:len(parts)-1], "/")
312
- extended["CI_PROJECT_PATH_SLUG"] = slug(project)
313
- return extended
314
- }
315
-
316
- var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
317
-
318
- func slug(value string) string {
319
- return strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(value), "-"), "-")
320
- }
@@ -345,7 +345,7 @@ for(const flag of ['renew']) {
345
345
  cwd : home,
346
346
  env : {...process.env, HOME : home, VAUTHRC : rc, VAULT_TOKEN : 'environment-token', SSH_AUTH_SOCK : process.env.SSH_AUTH_SOCK},
347
347
  };
348
- const cli = path.resolve(__dirname, '..', 'index.js');
348
+ const cli = path.resolve(__dirname, '..', 'cmd', 'vauth.js');
349
349
  const output = await exec(process.execPath, [cli, command, '--source', `--${flag}`], options);
350
350
  assert.ok(output.stdout.includes("export VAULT_TOKEN='fresh-token'"));
351
351
  assert.ok(!output.stdout.includes('Vauth token: '));
@@ -386,7 +386,7 @@ test('installed venv forwards --renew through the real CLI', async t => {
386
386
  assert.ok(declaration.includes('vauth env --source "$@"'));
387
387
  const bin = path.join(home, 'bin');
388
388
  fs.mkdirSync(bin);
389
- fs.symlinkSync(path.resolve(__dirname, '..', 'index.js'), path.join(bin, 'vauth'));
389
+ fs.symlinkSync(path.resolve(__dirname, '..', 'cmd', 'vauth.js'), path.join(bin, 'vauth'));
390
390
  const rc = path.join(home, '.vauthrc');
391
391
  fs.writeFileSync(rc, JSON.stringify({vault_addr : instance.VAULT_ADDR, ...instance.RC}));
392
392
  const options = {
@@ -621,7 +621,7 @@ test('real CLI reads token_cache false from .vauthrc', async t => {
621
621
  const home = path.dirname(path.dirname(path.dirname(file)));
622
622
  const rc = path.join(home, '.vauthrc');
623
623
  fs.writeFileSync(rc, JSON.stringify({vault_addr : instance.VAULT_ADDR, ...instance.RC, token_cache : false}));
624
- const cli = path.resolve(__dirname, '..', 'index.js');
624
+ const cli = path.resolve(__dirname, '..', 'cmd', 'vauth.js');
625
625
  for(let i = 0; i < 2; i++) {
626
626
  const output = await exec(process.execPath, [cli, 'login', '--source'], {
627
627
  cwd : home,
@@ -845,21 +845,21 @@ test('a project package.json may pin vvauth; other dependencies are ignored', as
845
845
  const {version} = require('../package.json');
846
846
  const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'vvauth-project-'));
847
847
  t.after(() => fs.rmSync(cwd, {recursive : true, force : true}));
848
- const cli = path.resolve(__dirname, '..', 'index.js');
848
+ const cli = path.resolve(__dirname, '..', 'cmd', 'vauth.js');
849
849
  const options = {cwd, env : {...process.env, HOME : cwd, VAUTHRC : path.join(cwd, 'none'), VAULT_ADDR : '', VAULT_TOKEN : '', SSH_AUTH_SOCK : ''}};
850
850
 
851
851
  fs.writeFileSync(path.join(cwd, 'package.json'), JSON.stringify({dependencies : {vvauth : `^${version}`, 'not-installed-anywhere' : '^9'}}));
852
- assert.equal((await exec(process.execPath, [cli, 'version'], options)).stdout.trim(), version);
852
+ assert.equal(JSON.parse((await exec(process.execPath, [cli, 'version', '--ir://json'], options)).stdout), version);
853
853
 
854
854
  fs.writeFileSync(path.join(cwd, 'package.json'), JSON.stringify({dependencies : {vvauth : '<0.0.1'}}));
855
- await assert.rejects(exec(process.execPath, [cli, 'connect'], options), /Unsupported vvauth version .* \(project requires <0.0.1\)/);
855
+ await assert.rejects(exec(process.execPath, [cli, 'vauth:Connect', '--ir://json'], options), /Unsupported vvauth version .* \(project requires <0.0.1\)/);
856
856
  });
857
857
 
858
858
 
859
859
  test('profile, KV and environment use the inherited vauth-login transport', async t => {
860
860
  const Login = require('vauth-login');
861
861
  assert.equal(Object.getPrototypeOf(Vauth.prototype), Login.prototype);
862
- for(const name of ['Connect', 'LookupSelf', 'Request']) {
862
+ for(const name of ['LookupSelf', 'Request']) {
863
863
  assert.equal(Object.hasOwn(Vauth.prototype, name), false);
864
864
  assert.equal(Vauth.prototype[name], Login.prototype[name]);
865
865
  }
@@ -891,8 +891,8 @@ test('an unknown project Vault cannot receive inherited credentials through env
891
891
  fs.mkdirSync(project);
892
892
  fs.writeFileSync(path.join(project, '.vauthrc'), JSON.stringify({vault_addr : f.client().VAULT_ADDR, env : {map : {LOGIN : '$${profile.VAUTH_USER_LOGIN}'}}}));
893
893
  const options = {cwd : project, env : {...process.env, HOME : home, VAUTHRC : '', VAULT_ADDR : '', VAULT_TOKEN : 'inherited-token'}};
894
- const cli = path.resolve(__dirname, '..', 'index.js');
895
- assert.equal((await exec(process.execPath, [cli, 'connect'], options)).stdout, 'inherited-token');
894
+ const cli = path.resolve(__dirname, '..', 'cmd', 'vauth.js');
895
+ assert.equal(JSON.parse((await exec(process.execPath, [cli, 'vauth:Connect', '--ir://json'], options)).stdout), 'inherited-token');
896
896
  for(const command of ['env', 'show']) {
897
897
  await assert.rejects(exec(process.execPath, [cli, command, '--ir://json'], options), err => {
898
898
  assert.equal(err.stdout, '');
@@ -901,8 +901,17 @@ test('an unknown project Vault cannot receive inherited credentials through env
901
901
  return true;
902
902
  });
903
903
  }
904
- for(const command of ['Request', 'LookupSelf', 'request', 'lookupSelf'])
905
- await assert.rejects(exec(process.execPath, [cli, command], options), /Usage:/);
904
+ for(const args of [
905
+ ['Request', '--method=GET', '--apiPath=identity/entity/id/test', '--token=inherited-token', '--ir://json'],
906
+ ['LookupSelf', '--token=inherited-token', '--ir://json'],
907
+ ]) {
908
+ await assert.rejects(exec(process.execPath, [cli, ...args], options), err => {
909
+ assert.equal(err.stdout, '');
910
+ assert.match(err.stderr, /Unknown vault/);
911
+ assert.ok(!err.stderr.includes('inherited-token'));
912
+ return true;
913
+ });
914
+ }
906
915
  assert.deepEqual(f.requests, []);
907
916
  });
908
917
 
@@ -935,7 +944,7 @@ test('constructor consumes one frozen RC snapshot without reopening the selected
935
944
  assert.equal(v.rc_file, undefined);
936
945
  });
937
946
 
938
- test('env.gitlab uses the working repository when VAUTHRC lives elsewhere', async t => {
947
+ test('env.gitlab no longer infers Git metadata in the constructor', async t => {
939
948
  const project = fs.mkdtempSync(path.join(os.tmpdir(), 'vvauth-git-project-'));
940
949
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'vvauth-git-config-'));
941
950
  t.after(() => fs.rmSync(project, {recursive : true, force : true}));
@@ -947,8 +956,107 @@ test('env.gitlab uses the working repository when VAUTHRC lives elsewhere', asyn
947
956
  const script = `const V = require(${JSON.stringify(path.resolve(__dirname, '..', 'index.js'))}); process.stdout.write(JSON.stringify(new V().config));`;
948
957
  for(const CI of ['', '1']) {
949
958
  const {stdout} = await exec(process.execPath, ['-e', script], {
950
- cwd : project, env : {...process.env, HOME : home, VAUTHRC : file, VAULT_TOKEN : '', VAULT_ADDR : '', CI, CI_PROJECT_PATH : 'pipeline/project'},
959
+ cwd : project, env : {...process.env, HOME : home, VAUTHRC : file, VAULT_TOKEN : '', VAULT_ADDR : '', CI, CI_PROJECT_PATH : 'pipeline/project', CI_PROJECT_NAME : 'project', CI_PROJECT_NAMESPACE : 'pipeline', CI_PROJECT_PATH_SLUG : 'pipeline-project'},
951
960
  });
952
- assert.equal(JSON.parse(stdout).env.map.PROJECT, CI ? 'pipeline/project' : 'Team/app');
961
+ assert.equal(JSON.parse(stdout).env.map.PROJECT, 'pipeline/project');
962
+ }
963
+ });
964
+
965
+ test('gitlab publishes only CI exports without authentication or config writes', async t => {
966
+ const project = fs.mkdtempSync(path.join(os.tmpdir(), 'vvauth-gitlab-'));
967
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'vvauth-gitlab-home-'));
968
+ t.after(() => fs.rmSync(project, {recursive : true, force : true}));
969
+ t.after(() => fs.rmSync(home, {recursive : true, force : true}));
970
+ assert.equal(spawnSync('git', ['init', '-q', project]).status, 0);
971
+ assert.equal(spawnSync('git', ['-C', project, 'remote', 'add', 'origin', 'ssh://git@git.example.test:2222/Team/sub/App.git']).status, 0);
972
+ let requests = 0;
973
+ const server = http.createServer((req, res) => { requests++; res.end('{}'); });
974
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
975
+ t.after(() => new Promise(resolve => server.close(resolve)));
976
+ const file = path.join(home, 'selected.vauthrc');
977
+ const document = {vault_addr : `http://127.0.0.1:${server.address().port}`, jwt_auth : {jwt : 'fixture-jwt'}, env : {gitlab : true, map : {KEEP : 'literal'}}};
978
+ const body = JSON.stringify(document);
979
+ fs.writeFileSync(file, body);
980
+ const env = {...process.env, HOME : home, VAUTHRC : file, VAULT_TOKEN : '', VAULT_ADDR : '', SSH_AUTH_SOCK : ''};
981
+ const expected = {CI_PROJECT_PATH : 'Team/sub/App', CI_PROJECT_NAME : 'App', CI_PROJECT_NAMESPACE : 'Team/sub', CI_PROJECT_PATH_SLUG : 'team-sub-app'};
982
+ for(const cli of [path.resolve(__dirname, '..', 'cmd', 'vauth.js')]) {
983
+ for(const args of [['gitlab'], ['env', '--source', '--gitlab']]) {
984
+ const output = await exec(process.execPath, [cli, ...args], {cwd : project, env});
985
+ const names = [...output.stdout.matchAll(/^export ([A-Z_]+)=/gm)].map(match => match[1]);
986
+ assert.deepEqual(names, Object.keys(expected));
987
+ for(const [key, value] of Object.entries(expected)) assert.ok(output.stdout.includes(`export ${key}='${value}'`));
988
+ if(args[0] === 'gitlab') assert.match(output.stderr, /commands list/);
989
+ else assert.equal(output.stderr, '');
990
+ assert.equal(fs.readFileSync(file, 'utf8'), body);
991
+ assert.equal(fs.existsSync(path.join(project, '.vauthrc')), false);
992
+ }
993
+ }
994
+ assert.equal(requests, 0);
995
+ });
996
+
997
+ test('constructor with env.gitlab rejects missing CI variables before authentication', async t => {
998
+ const {client, requests} = await fixture(t);
999
+ const keys = ['CI_PROJECT_PATH', 'CI_PROJECT_NAME', 'CI_PROJECT_NAMESPACE', 'CI_PROJECT_PATH_SLUG'];
1000
+ const previous = Object.fromEntries(keys.map(key => [key, process.env[key]]));
1001
+ try {
1002
+ for(const key of keys) delete process.env[key];
1003
+ assert.throws(() => client({rc : {env : {gitlab : true, map : {KEEP : 'literal'}}}}), /Run venv --gitlab first/);
1004
+ assert.deepEqual(requests, []);
1005
+ for(const key of keys) process.env[key] = 'provided';
1006
+ const v = client({rc : {env : {gitlab : true, map : {KEEP : 'literal'}}}});
1007
+ const env = await v.Env();
1008
+ assert.equal(env.KEEP, 'literal');
1009
+ assert.ok(requests.length > 0);
1010
+ } finally {
1011
+ for(const [key, value] of Object.entries(previous)) {
1012
+ if(value === undefined) delete process.env[key];
1013
+ else process.env[key] = value;
1014
+ }
1015
+ }
1016
+ });
1017
+
1018
+ test('env.map scalar strings leave the raw RC types untouched', async t => {
1019
+ const map = {TEXT : 'hello', BOOL : true, NUMBER : 42, NULL : null, LARGE : 1e20, SMALL : 1e-7, ZERO : -0};
1020
+ const v = configuredClient(t, {env : {map}});
1021
+ assert.deepEqual(await v.Env(), {TEXT : 'hello', BOOL : 'true', NUMBER : '42', NULL : '', LARGE : '100000000000000000000', SMALL : '1e-7', ZERO : '0'});
1022
+ assert.equal(v.RC.env.map.BOOL, true);
1023
+ assert.equal(v.RC.env.map.NUMBER, 42);
1024
+ assert.equal(v.RC.env.map.NULL, null);
1025
+ assert.ok(Object.isFrozen(v.RC.env.map));
1026
+ });
1027
+
1028
+ test('env.map rejects objects and arrays before and after macro expansion', async t => {
1029
+ const f = await fixture(t, {metadata : {SCALAR : 42, BOOL : false, NULL : null, OBJECT : {x : 1}, ARRAY : ['x']}});
1030
+ const v = f.client();
1031
+ for(const value of [{x : 1}, ['x'], ['$${profile.SCALAR}'], '$${profile.OBJECT}', '$${profile.ARRAY}', '$${profile}']) {
1032
+ v.config = {env : {map : {VALUE : value}}};
1033
+ await assert.rejects(v.Env(), /Invalid environment value 'VALUE' in env.map: expected a scalar/);
1034
+ }
1035
+ v.config = {env : {map : {NUMBER : '$${profile.SCALAR}', BOOL : '$${profile.BOOL}', NULL : '$${profile.NULL}'}, git : true}};
1036
+ const env = await v.Env();
1037
+ assert.equal(env.NUMBER, '42');
1038
+ assert.equal(env.BOOL, 'false');
1039
+ assert.equal(env.NULL, '');
1040
+ assert.equal(env.GIT_AUTHOR_EMAIL, '');
1041
+ assert.equal(env.GIT_COMMITTER_EMAIL, '');
1042
+ });
1043
+
1044
+
1045
+ test('gitlab decodes URL paths like Go while preserving scp paths', async t => {
1046
+ const project = fs.mkdtempSync(path.join(os.tmpdir(), 'vvauth-gitlab-url-'));
1047
+ t.after(() => fs.rmSync(project, {recursive : true, force : true}));
1048
+ assert.equal(spawnSync('git', ['init', '-q', project]).status, 0);
1049
+ const rc = path.join(project, 'fixture.json');
1050
+ fs.writeFileSync(rc, '{}');
1051
+ const cli = path.resolve(__dirname, '..', 'cmd', 'vauth.js');
1052
+ for(const [origin, expected] of [
1053
+ ['ssh://git@git.example.test/Team/my%2Dapp.git', 'Team/my-app'],
1054
+ ['https://git.example.test/Team/my%20app.git', 'Team/my app'],
1055
+ ['git@git.example.test:Team/my%2Dapp.git', 'Team/my%2Dapp'],
1056
+ ]) {
1057
+ spawnSync('git', ['-C', project, 'remote', 'remove', 'origin']);
1058
+ assert.equal(spawnSync('git', ['-C', project, 'remote', 'add', 'origin', origin]).status, 0);
1059
+ const output = await exec(process.execPath, [cli, 'gitlab'], {cwd : project, env : {...process.env, VAUTHRC : rc}});
1060
+ assert.ok(output.stdout.includes(`export CI_PROJECT_PATH='${expected}'`));
953
1061
  }
954
1062
  });
package/vauth.go CHANGED
@@ -14,6 +14,7 @@ import (
14
14
  "regexp"
15
15
  "strings"
16
16
 
17
+ nyksstring "github.com/131/nyks/v6/string"
17
18
  sshagentcrypt "github.com/131/ssh-agent-crypt"
18
19
  vauthlogin "github.com/131/vauth-login"
19
20
  "github.com/Masterminds/semver/v3"
@@ -90,11 +91,22 @@ func New() (*Vauth, error) {
90
91
  return nil, err
91
92
  }
92
93
  v := &Vauth{Vauth: login}
93
- config, err := configFromRC(login.RC(), cwd, login.Environ)
94
+ config, err := configFromRC(login.RC(), login.Environ)
94
95
  if err != nil {
95
96
  return nil, err
96
97
  }
97
98
  v.Config = *config
99
+ if v.Config.Env != nil && v.Config.Env.GitLab {
100
+ var missing []string
101
+ for _, key := range []string{"CI_PROJECT_PATH", "CI_PROJECT_NAME", "CI_PROJECT_NAMESPACE", "CI_PROJECT_PATH_SLUG"} {
102
+ if v.Environ[key] == "" {
103
+ missing = append(missing, key)
104
+ }
105
+ }
106
+ if len(missing) != 0 {
107
+ return nil, fmt.Errorf("Missing %s. Run venv --gitlab first.", strings.Join(missing, ", "))
108
+ }
109
+ }
98
110
  if v.VAULT_ADDR() == "" {
99
111
  fmt.Fprintln(v.stderr(), "Not bound to any vault")
100
112
  }
@@ -270,11 +282,19 @@ func (v *Vauth) Env(renew bool) (*OrderedMap, error) {
270
282
  }
271
283
  merged := profile.Merged()
272
284
  if config.Git {
273
- mapping.Set("GIT_COMMITTER_NAME", "$${profile.VAUTH_USER_NAME}")
274
- mapping.Set("GIT_COMMITTER_EMAIL", "$${profile.VAUTH_USER_MAIL}")
275
- mapping.Set("GIT_AUTHOR_EMAIL", "$${profile.VAUTH_USER_MAIL}")
276
- mapping.Set("GIT_AUTHOR_NAME", "$${profile.VAUTH_USER_NAME}")
277
- mapping.Set("GIT_USER_LOGIN", "$${profile.VAUTH_USER_LOGIN}")
285
+ for _, field := range [][2]string{
286
+ {"GIT_COMMITTER_NAME", "VAUTH_USER_NAME"},
287
+ {"GIT_COMMITTER_EMAIL", "VAUTH_USER_MAIL"},
288
+ {"GIT_AUTHOR_EMAIL", "VAUTH_USER_MAIL"},
289
+ {"GIT_AUTHOR_NAME", "VAUTH_USER_NAME"},
290
+ {"GIT_USER_LOGIN", "VAUTH_USER_LOGIN"},
291
+ } {
292
+ value, err := envValue(merged[field[1]])
293
+ if err != nil {
294
+ return nil, fmt.Errorf("Invalid environment value '%s' in env.map: %w", field[0], err)
295
+ }
296
+ mapping.Set(field[0], value)
297
+ }
278
298
  }
279
299
  mount := config.Path
280
300
  if mount == "" {
@@ -290,12 +310,16 @@ func (v *Vauth) Env(renew bool) (*OrderedMap, error) {
290
310
  secrets[k] = val
291
311
  }
292
312
  }
293
- dict := Lookup{"env": v.Environ, "profile": merged, "secrets": secrets}
313
+ dict := map[string]any{"env": v.Environ, "profile": merged, "secrets": secrets}
294
314
  for _, key := range mapping.Keys {
295
315
  if !envName.MatchString(key) {
296
316
  return nil, fmt.Errorf("Invalid environment variable name '%s' in env.map", key)
297
317
  }
298
- env.Set(key, ReplaceEnv(mapping.Values[key], dict))
318
+ value, err := envValue(nyksstring.ReplaceEnv(mapping.Values[key], dict))
319
+ if err != nil {
320
+ return nil, fmt.Errorf("Invalid environment value '%s' in env.map: %w", key, err)
321
+ }
322
+ env.Set(key, value)
299
323
  }
300
324
  return env, nil
301
325
  }
@@ -346,30 +370,6 @@ func (v *Vauth) Dotenv() error {
346
370
  return nil
347
371
  }
348
372
 
349
- // Run executes a command with the resolved environment merged over the
350
- // process environment and returns its exit code.
351
- func (v *Vauth) Run(command string, args ...string) (int, error) {
352
- env, err := v.Env(false)
353
- if err != nil {
354
- return 1, err
355
- }
356
- cmd := exec.Command(command, args...)
357
- cmd.Env = os.Environ()
358
- for _, key := range env.Keys {
359
- cmd.Env = append(cmd.Env, key+"="+env.Values[key])
360
- }
361
- cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
362
- err = cmd.Run()
363
- var exit *exec.ExitError
364
- if errors.As(err, &exit) {
365
- return exit.ExitCode(), nil
366
- }
367
- if err != nil {
368
- return 1, fmt.Errorf("run failure : %w", err)
369
- }
370
- return 0, nil
371
- }
372
-
373
373
  // FunctionExists reports whether a bash login shell already defines alias.
374
374
  func FunctionExists(alias string) bool {
375
375
  return exec.Command("bash", "-lc", "declare -F "+alias).Run() == nil