vvauth 2.5.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,95 +4,37 @@ import (
4
4
  "bytes"
5
5
  "encoding/json"
6
6
  "fmt"
7
- "net/url"
8
- "os"
9
- "os/exec"
10
- "path/filepath"
11
- "regexp"
12
7
  "strconv"
13
- "strings"
14
8
 
9
+ nyksobject "github.com/131/nyks/v6/object"
10
+ nyksstring "github.com/131/nyks/v6/string"
15
11
  "gopkg.in/yaml.v3"
16
12
  )
17
13
 
18
- // RC is the parsed .vauthrc, after $${env.X} expansion.
19
- type RC struct {
20
- VaultAddr string `yaml:"vault_addr"`
21
- SSHAuth *SSHAuth `yaml:"ssh_auth"`
22
- JWTAuth *JWTAuth `yaml:"jwt_auth"`
23
- TokenCache *bool `yaml:"token_cache"`
24
- AgentCrypt *AgentCrypt `yaml:"ssh-agent-crypt"`
25
- Env *EnvConfig `yaml:"env"`
26
-
27
- // authKey is the JSON of {ssh_auth, jwt_auth} in document order, as
28
- // JSON.stringify would render them: it isolates the token cache.
29
- authKey string
30
- }
31
-
32
- // AuthKey renders ssh_auth and jwt_auth as JSON members, in the order of the
33
- // parsed document. Programmatic configurations are rendered from the structs.
34
- func (rc *RC) AuthKey() string {
35
- if rc.authKey != "" {
36
- return rc.authKey
37
- }
38
- var members []string
39
- if rc.SSHAuth != nil {
40
- members = append(members, `"ssh_auth":`+jsonMembers([][2]string{{"path", rc.SSHAuth.Path}, {"role", rc.SSHAuth.Role}}))
41
- }
42
- if rc.JWTAuth != nil {
43
- members = append(members, `"jwt_auth":`+jsonMembers([][2]string{{"path", rc.JWTAuth.Path}, {"jwt", rc.JWTAuth.JWT}, {"role", rc.JWTAuth.Role}}))
44
- }
45
- return strings.Join(members, ",")
46
- }
47
-
48
- func jsonMembers(pairs [][2]string) string {
49
- var out bytes.Buffer
50
- out.WriteByte('{')
51
- for _, pair := range pairs {
52
- if pair[1] == "" {
53
- continue
54
- }
55
- if out.Len() > 1 {
56
- out.WriteByte(',')
57
- }
58
- out.Write(jsonString(pair[0]))
59
- out.WriteByte(':')
60
- out.Write(jsonString(pair[1]))
61
- }
62
- out.WriteByte('}')
63
- return out.String()
64
- }
65
-
66
- // SSHAuth configures the Vault ssh auth plugin (nonce challenge).
67
- type SSHAuth struct {
68
- Path string `yaml:"path"`
69
- Role string `yaml:"role"`
70
- }
71
-
72
- // JWTAuth configures a Vault jwt login.
73
- type JWTAuth struct {
74
- Path string `yaml:"path"`
75
- JWT string `yaml:"jwt"`
76
- Role string `yaml:"role"`
14
+ // Config contains only environment/profile settings; authentication is
15
+ // parsed and owned by vauth-login.
16
+ type Config struct {
17
+ AgentCrypt *AgentCrypt `json:"ssh-agent-crypt" yaml:"ssh-agent-crypt"`
18
+ Env *EnvConfig `json:"env" yaml:"env"`
77
19
  }
78
20
 
79
21
  // AgentCrypt points to a local ssh-agent-crypt armored JSON file whose keys
80
22
  // feed $${secrets.X}.
81
23
  type AgentCrypt struct {
82
- Path string `yaml:"path"`
83
- Identity string `yaml:"identity"`
24
+ Path string `json:"path" yaml:"path"`
25
+ Identity string `json:"identity" yaml:"identity"`
84
26
  }
85
27
 
86
28
  // EnvConfig describes the environment to resolve.
87
29
  type EnvConfig struct {
88
- Map OrderedMap `yaml:"map"`
89
- Paths []string `yaml:"paths"`
90
- Path string `yaml:"path"`
91
- Git bool `yaml:"git"`
92
- 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"`
93
35
  }
94
36
 
95
- // OrderedMap keeps the YAML document order of a string mapping.
37
+ // OrderedMap keeps the decoded JSON order of a string mapping.
96
38
  type OrderedMap struct {
97
39
  Keys []string
98
40
  Values map[string]string
@@ -118,22 +60,34 @@ func (m *OrderedMap) Get(key string) (string, bool) {
118
60
  // Len returns the number of entries.
119
61
  func (m *OrderedMap) Len() int { return len(m.Keys) }
120
62
 
121
- // UnmarshalYAML decodes a mapping, scalars as strings.
122
- func (m *OrderedMap) UnmarshalYAML(node *yaml.Node) error {
123
- if node.Kind != yaml.MappingNode {
124
- 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
125
69
  }
126
- for i := 0; i+1 < len(node.Content); i += 2 {
127
- var key, value string
128
- if err := node.Content[i].Decode(&key); err != nil {
70
+ if token != json.Delim('{') {
71
+ return fmt.Errorf("expected a mapping")
72
+ }
73
+ for decoder.More() {
74
+ token, err := decoder.Token()
75
+ if err != nil {
129
76
  return err
130
77
  }
131
- 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 {
132
81
  return err
133
82
  }
134
- 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)
135
88
  }
136
- return nil
89
+ _, err = decoder.Token()
90
+ return err
137
91
  }
138
92
 
139
93
  // MarshalJSON renders the entries in order.
@@ -152,38 +106,6 @@ func (m OrderedMap) MarshalJSON() ([]byte, error) {
152
106
  return out.Bytes(), nil
153
107
  }
154
108
 
155
- // Lookup resolves dotted paths ($${env.X}) in nested string maps.
156
- type Lookup map[string]any
157
-
158
- func (dict Lookup) get(path string) (string, bool) {
159
- var current any = map[string]any(dict)
160
- for _, part := range strings.Split(path, ".") {
161
- switch node := current.(type) {
162
- case map[string]any:
163
- value, ok := node[part]
164
- if !ok {
165
- return "", false
166
- }
167
- current = value
168
- case map[string]string:
169
- value, ok := node[part]
170
- if !ok {
171
- return "", false
172
- }
173
- current = value
174
- case Lookup:
175
- value, ok := node[part]
176
- if !ok {
177
- return "", false
178
- }
179
- current = value
180
- default:
181
- return "", false
182
- }
183
- }
184
- return stringify(current)
185
- }
186
-
187
109
  func stringify(value any) (string, bool) {
188
110
  switch v := value.(type) {
189
111
  case nil:
@@ -204,92 +126,32 @@ func stringify(value any) (string, bool) {
204
126
  return string(body), true
205
127
  }
206
128
 
207
- var macroPattern = regexp.MustCompile(`(?i)\$\$([a-z0-9._-]+)|\$\$\{([^}]+)\}`)
208
-
209
- // ReplaceEnv expands $$key and $${key} macros against dict (nyks
210
- // string/replaceEnv semantics): unknown keys stay, expansions recurse.
211
- func ReplaceEnv(str string, dict Lookup) string {
212
- for depth := 0; depth < 16; depth++ {
213
- touched := false
214
- str = macroPattern.ReplaceAllStringFunc(str, func(macro string) string {
215
- match := macroPattern.FindStringSubmatch(macro)
216
- key := match[1]
217
- if key == "" {
218
- key = match[2]
219
- }
220
- value, ok := dict.get(key)
221
- if !ok {
222
- return macro
223
- }
224
- touched = true
225
- return value
226
- })
227
- if !touched {
228
- break
229
- }
230
- }
231
- return str
232
- }
233
-
234
- // walk expands every scalar string of a YAML tree in place.
235
- func walk(node *yaml.Node, process func(string) string) {
236
- if node.Kind == yaml.ScalarNode {
237
- if node.Tag == "!!str" || node.Tag == "" {
238
- node.Value = process(node.Value)
239
- }
240
- return
241
- }
242
- for _, child := range node.Content {
243
- walk(child, process)
244
- }
245
- }
246
-
247
- // jsonNode renders a YAML subtree as JSON.stringify would after yaml.parse.
248
- func jsonNode(node *yaml.Node, out *bytes.Buffer) {
249
- switch node.Kind {
250
- case yaml.DocumentNode, yaml.AliasNode:
251
- if node.Kind == yaml.AliasNode {
252
- jsonNode(node.Alias, out)
253
- } else if len(node.Content) > 0 {
254
- jsonNode(node.Content[0], out)
255
- }
256
- case yaml.MappingNode:
257
- out.WriteByte('{')
258
- for i := 0; i+1 < len(node.Content); i += 2 {
259
- if i > 0 {
260
- out.WriteByte(',')
261
- }
262
- out.Write(jsonString(node.Content[i].Value))
263
- out.WriteByte(':')
264
- jsonNode(node.Content[i+1], out)
265
- }
266
- out.WriteByte('}')
267
- case yaml.SequenceNode:
268
- out.WriteByte('[')
269
- for i, child := range node.Content {
270
- if i > 0 {
271
- out.WriteByte(',')
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
272
147
  }
273
- jsonNode(child, out)
274
- }
275
- out.WriteByte(']')
276
- case yaml.ScalarNode:
277
- switch node.Tag {
278
- case "!!int", "!!float", "!!bool":
279
- var value any
280
- if node.Decode(&value) == nil {
281
- if text, ok := stringify(value); ok {
282
- out.WriteString(text)
283
- return
284
- }
148
+ body, err = json.Marshal(number)
149
+ if err == nil {
150
+ return string(body), nil
285
151
  }
286
- out.Write(jsonString(node.Value))
287
- case "!!null":
288
- out.WriteString("null")
289
- default:
290
- out.Write(jsonString(node.Value))
291
152
  }
292
153
  }
154
+ return "", fmt.Errorf("expected a scalar")
293
155
  }
294
156
 
295
157
  // jsonString encodes like JSON.stringify (no HTML escaping).
@@ -301,127 +163,46 @@ func jsonString(value string) []byte {
301
163
  return bytes.TrimRight(out.Bytes(), "\n")
302
164
  }
303
165
 
304
- func mappingValue(node *yaml.Node, key string) *yaml.Node {
305
- if node == nil {
306
- return nil
307
- }
308
- if node.Kind == yaml.DocumentNode && len(node.Content) > 0 {
309
- node = node.Content[0]
310
- }
311
- if node.Kind != yaml.MappingNode {
312
- return nil
313
- }
314
- for i := 0; i+1 < len(node.Content); i += 2 {
315
- if node.Content[i].Value == key {
316
- return node.Content[i+1]
317
- }
166
+ // ParseConfig expands environment/profile sections from a standalone YAML body.
167
+ func ParseConfig(body []byte, file string, environ map[string]string) (*Config, error) {
168
+ var rc map[string]any
169
+ if err := yaml.Unmarshal(body, &rc); err != nil {
170
+ return nil, fmt.Errorf("Could not parse %s: %w", file, err)
318
171
  }
319
- return nil
172
+ return compileConfig(rc, file, environ)
320
173
  }
321
174
 
322
- // LocateRC returns the first existing configuration file among VAUTHRC,
323
- // ./.vauthrc and ~/.vauthrc, or an empty string.
324
- func LocateRC(environ map[string]string, cwd, home string) string {
325
- candidates := []string{environ["VAUTHRC"], filepath.Join(cwd, ".vauthrc"), filepath.Join(home, ".vauthrc")}
326
- for _, candidate := range candidates {
327
- if candidate == "" {
328
- continue
329
- }
330
- if _, err := os.Stat(candidate); err == nil {
331
- return candidate
332
- }
333
- }
334
- return ""
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)
335
178
  }
336
179
 
337
- // ParseRC parses a .vauthrc body and expands its $${env.X} macros against
338
- // environ. With env.gitlab outside CI, CI_PROJECT_* variables are derived
339
- // from the git remote of the directory holding the file.
340
- func ParseRC(body []byte, file string, environ map[string]string) (*RC, error) {
341
- var document yaml.Node
342
- if err := yaml.Unmarshal(body, &document); err != nil {
343
- return nil, fmt.Errorf("Could not parse %s: %w", file, err)
344
- }
345
- if len(document.Content) == 0 {
346
- return &RC{authKey: "{}"}, nil
347
- }
348
- if gitlab := mappingValue(mappingValue(&document, "env"), "gitlab"); gitlab != nil && truthy(gitlab) && environ["CI"] == "" {
349
- environ = withGitLabProject(environ, filepath.Dir(file))
350
- }
351
- walk(&document, func(value string) string {
352
- return ReplaceEnv(value, Lookup{"env": environ})
353
- })
354
- rc := RC{}
355
- if err := document.Decode(&rc); err != nil {
356
- return nil, fmt.Errorf("Could not parse %s: %w", file, err)
357
- }
358
- var key bytes.Buffer
359
- for i, name := range []string{"ssh_auth", "jwt_auth"} {
360
- node := mappingValue(&document, name)
361
- if node == nil || node.Tag == "!!null" {
362
- continue
363
- }
364
- if i > 0 && key.Len() > 0 {
365
- key.WriteByte(',')
366
- }
367
- key.Write(jsonString(name))
368
- key.WriteByte(':')
369
- jsonNode(node, &key)
370
- }
371
- rc.authKey = key.String()
372
- return &rc, nil
373
- }
374
-
375
- func truthy(node *yaml.Node) bool {
376
- switch node.Kind {
377
- case yaml.ScalarNode:
378
- switch node.Tag {
379
- case "!!null":
380
- return false
381
- case "!!bool":
382
- return node.Value == "true"
383
- case "!!int", "!!float":
384
- return node.Value != "0" && node.Value != "0.0"
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
385
185
  }
386
- return node.Value != ""
387
186
  }
388
- return true
389
- }
390
-
391
- var scpRemote = regexp.MustCompile(`^[^@]+@[^:]+:(.+)$`)
392
-
393
- func withGitLabProject(environ map[string]string, dir string) map[string]string {
394
- cmd := exec.Command("git", "remote", "get-url", "origin")
395
- cmd.Dir = dir
396
- out, err := cmd.Output()
187
+ // Clone the selected sections before Walk, preserving the raw RC snapshot.
188
+ body, err := json.Marshal(selected)
397
189
  if err != nil {
398
- return environ
190
+ return nil, fmt.Errorf("Could not parse %s: %w", file, err)
399
191
  }
400
- remote := strings.TrimSpace(string(out))
401
- var project string
402
- if match := scpRemote.FindStringSubmatch(remote); match != nil {
403
- project = match[1]
404
- } else if parsed, err := url.Parse(remote); err == nil {
405
- project = parsed.Path
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)
406
195
  }
407
- project = strings.TrimSuffix(strings.Trim(project, "/"), ".git")
408
- if project == "" {
409
- return environ
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)
410
202
  }
411
- parts := strings.Split(project, "/")
412
- extended := make(map[string]string, len(environ)+4)
413
- for k, v := range environ {
414
- extended[k] = v
203
+ var config Config
204
+ if err := json.Unmarshal(body, &config); err != nil {
205
+ return nil, fmt.Errorf("Could not parse %s: %w", file, err)
415
206
  }
416
- extended["CI_PROJECT_PATH"] = project
417
- extended["CI_PROJECT_NAME"] = parts[len(parts)-1]
418
- extended["CI_PROJECT_NAMESPACE"] = strings.Join(parts[:len(parts)-1], "/")
419
- extended["CI_PROJECT_PATH_SLUG"] = slug(project)
420
- return extended
421
- }
422
-
423
- var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
424
-
425
- func slug(value string) string {
426
- return strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(value), "-"), "-")
207
+ return &config, nil
427
208
  }