vvauth 2.4.1 → 2.6.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/rc.go ADDED
@@ -0,0 +1,320 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "fmt"
7
+ "net/url"
8
+ "os/exec"
9
+ "path/filepath"
10
+ "regexp"
11
+ "strconv"
12
+ "strings"
13
+
14
+ "gopkg.in/yaml.v3"
15
+ )
16
+
17
+ // Config contains only environment/profile settings; authentication is
18
+ // parsed and owned by vauth-login.
19
+ type Config struct {
20
+ AgentCrypt *AgentCrypt `yaml:"ssh-agent-crypt"`
21
+ Env *EnvConfig `yaml:"env"`
22
+ }
23
+
24
+ // AgentCrypt points to a local ssh-agent-crypt armored JSON file whose keys
25
+ // feed $${secrets.X}.
26
+ type AgentCrypt struct {
27
+ Path string `yaml:"path"`
28
+ Identity string `yaml:"identity"`
29
+ }
30
+
31
+ // EnvConfig describes the environment to resolve.
32
+ 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"`
38
+ }
39
+
40
+ // OrderedMap keeps the YAML document order of a string mapping.
41
+ type OrderedMap struct {
42
+ Keys []string
43
+ Values map[string]string
44
+ }
45
+
46
+ // Set adds or replaces key.
47
+ func (m *OrderedMap) Set(key, value string) {
48
+ if m.Values == nil {
49
+ m.Values = map[string]string{}
50
+ }
51
+ if _, exists := m.Values[key]; !exists {
52
+ m.Keys = append(m.Keys, key)
53
+ }
54
+ m.Values[key] = value
55
+ }
56
+
57
+ // Get returns the value for key.
58
+ func (m *OrderedMap) Get(key string) (string, bool) {
59
+ value, ok := m.Values[key]
60
+ return value, ok
61
+ }
62
+
63
+ // Len returns the number of entries.
64
+ func (m *OrderedMap) Len() int { return len(m.Keys) }
65
+
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)
70
+ }
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 {
74
+ return err
75
+ }
76
+ if err := node.Content[i+1].Decode(&value); err != nil {
77
+ return err
78
+ }
79
+ m.Set(key, value)
80
+ }
81
+ return nil
82
+ }
83
+
84
+ // MarshalJSON renders the entries in order.
85
+ func (m OrderedMap) MarshalJSON() ([]byte, error) {
86
+ var out bytes.Buffer
87
+ out.WriteByte('{')
88
+ for i, key := range m.Keys {
89
+ if i > 0 {
90
+ out.WriteByte(',')
91
+ }
92
+ out.Write(jsonString(key))
93
+ out.WriteByte(':')
94
+ out.Write(jsonString(m.Values[key]))
95
+ }
96
+ out.WriteByte('}')
97
+ return out.Bytes(), nil
98
+ }
99
+
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
+ func stringify(value any) (string, bool) {
133
+ switch v := value.(type) {
134
+ case nil:
135
+ return "", false
136
+ case string:
137
+ return v, true
138
+ case bool:
139
+ return strconv.FormatBool(v), true
140
+ case float64:
141
+ return strconv.FormatFloat(v, 'f', -1, 64), true
142
+ case json.Number:
143
+ return v.String(), true
144
+ }
145
+ body, err := json.Marshal(value)
146
+ if err != nil {
147
+ return "", false
148
+ }
149
+ return string(body), true
150
+ }
151
+
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]
164
+ }
165
+ value, ok := dict.get(key)
166
+ if !ok {
167
+ return macro
168
+ }
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
+ }
185
+ return
186
+ }
187
+ for _, child := range node.Content {
188
+ walk(child, process)
189
+ }
190
+ }
191
+
192
+ // jsonString encodes like JSON.stringify (no HTML escaping).
193
+ func jsonString(value string) []byte {
194
+ var out bytes.Buffer
195
+ encoder := json.NewEncoder(&out)
196
+ encoder.SetEscapeHTML(false)
197
+ encoder.Encode(value)
198
+ return bytes.TrimRight(out.Bytes(), "\n")
199
+ }
200
+
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
+ // 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
+ 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 {
224
+ return nil, fmt.Errorf("Could not parse %s: %w", file, err)
225
+ }
226
+ return compileConfig(&document, file, filepath.Dir(file), environ)
227
+ }
228
+
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)
236
+ }
237
+
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
243
+ }
244
+ root = root.Content[0]
245
+ }
246
+ if root.Kind != yaml.MappingNode {
247
+ return nil, fmt.Errorf("Could not parse %s: expected a mapping", file)
248
+ }
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
+ }
255
+ }
256
+ root.Content = content
257
+ if gitlab := mappingValue(mappingValue(document, "env"), "gitlab"); gitlab != nil && truthy(gitlab) && environ["CI"] == "" {
258
+ environ = withGitLabProject(environ, dir)
259
+ }
260
+ walk(document, func(value string) string { return ReplaceEnv(value, Lookup{"env": environ}) })
261
+ var config Config
262
+ if err := document.Decode(&config); err != nil {
263
+ return nil, fmt.Errorf("Could not parse %s: %w", file, err)
264
+ }
265
+ return &config, nil
266
+ }
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
+ }