forked from cyberark/summon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaction.go
313 lines (263 loc) · 7.77 KB
/
action.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package command
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"syscall"
prov "github.com/cyberark/summon/provider"
"github.com/cyberark/summon/secretsyml"
"github.com/urfave/cli"
)
// ActionConfig is an object that holds all the info needed to run
// a Summon instance
type ActionConfig struct {
Args []string
Provider string
Filepath string
YamlInline string
Subs map[string]string
Ignores []string
IgnoreAll bool
Environment string
RecurseUp bool
ShowProviderVersions bool
}
const ENV_FILE_MAGIC = "@SUMMONENVFILE"
const SUMMON_ENV_KEY_NAME = "SUMMON_ENV"
// Action is the runner for the main program logic
var Action = func(c *cli.Context) {
if !c.Args().Present() && !c.Bool("all-provider-versions") {
fmt.Println("Enter a subprocess to run!")
os.Exit(127)
}
provider, err := prov.Resolve(c.String("provider"))
// It's okay to not throw this error here, because `Resolve()` throws an
// error if there are multiple unspecified providers. `all-provider-versions`
// doesn't care about this and just looks in the default provider dir
if err != nil && !c.Bool("all-provider-versions") {
fmt.Println(err.Error())
os.Exit(127)
}
err = runAction(&ActionConfig{
Args: c.Args(),
Provider: provider,
Environment: c.String("environment"),
Filepath: c.String("f"),
YamlInline: c.String("yaml"),
Ignores: c.StringSlice("ignore"),
IgnoreAll: c.Bool("ignore-all"),
RecurseUp: c.Bool("up"),
ShowProviderVersions: c.Bool("all-provider-versions"),
Subs: convertSubsToMap(c.StringSlice("D")),
})
code, err := returnStatusOfError(err)
if err != nil {
fmt.Println(err.Error())
os.Exit(127)
}
os.Exit(code)
}
// runAction encapsulates the logic of Action without cli Context for easier testing
func runAction(ac *ActionConfig) error {
var (
secrets secretsyml.SecretsMap
err error
)
if ac.ShowProviderVersions {
output, err := printProviderVersions(prov.DefaultPath)
if err != nil {
return err
}
fmt.Print(output)
return nil
}
if ac.RecurseUp {
currentDir, err := os.Getwd()
ac.Filepath, err = findInParentTree(ac.Filepath, currentDir)
if err != nil {
return err
}
}
switch ac.YamlInline {
case "":
secrets, err = secretsyml.ParseFromFile(ac.Filepath, ac.Environment, ac.Subs)
default:
secrets, err = secretsyml.ParseFromString(ac.YamlInline, ac.Environment, ac.Subs)
}
if err != nil {
return err
}
env := make(map[string]string)
tempFactory := NewTempFactory("")
defer tempFactory.Cleanup()
type Result struct {
key string
value string
error
}
// Run provider calls concurrently
results := make(chan Result, len(secrets))
var wg sync.WaitGroup
for key, spec := range secrets {
wg.Add(1)
go func(key string, spec secretsyml.SecretSpec) {
var value string
if spec.IsVar() {
value, err = prov.Call(ac.Provider, spec.Path)
if err != nil {
results <- Result{key, "", err}
wg.Done()
return
}
} else {
// If the spec isn't a variable, use its value as-is
value = spec.Path
}
// Set a default value if the provider didn't return one for the item
if value == "" && spec.DefaultValue != "" {
value = spec.DefaultValue
}
k, v := formatForEnv(key, value, spec, &tempFactory)
results <- Result{k, v, nil}
wg.Done()
}(key, spec)
}
wg.Wait()
close(results)
EnvLoop:
for envvar := range results {
if envvar.error == nil {
env[envvar.key] = envvar.value
} else {
if ac.IgnoreAll {
continue EnvLoop
}
for i := range ac.Ignores {
if ac.Ignores[i] == fmt.Sprintf("%s=%s", envvar.key, envvar.value) {
continue EnvLoop
}
}
return fmt.Errorf("Error fetching variable %v: %v", envvar.key, envvar.error.Error())
}
}
// Append environment variable if one is specified
if ac.Environment != "" {
env[SUMMON_ENV_KEY_NAME] = ac.Environment
}
setupEnvFile(ac.Args, env, &tempFactory)
var e []string
for k, v := range env {
e = append(e, fmt.Sprintf("%s=%s", k, v))
}
return runSubcommand(ac.Args, append(os.Environ(), e...))
}
// formatForEnv returns a string in %k=%v format, where %k=namespace of the secret and
// %v=the secret value or path to a temporary file containing the secret
func formatForEnv(key string, value string, spec secretsyml.SecretSpec, tempFactory *TempFactory) (string, string) {
if spec.IsFile() {
fname := tempFactory.Push(value)
value = fname
}
return key, value
}
func joinEnv(env map[string]string) string {
var envs []string
for k, v := range env {
envs = append(envs, fmt.Sprintf("%s=%s", k, v))
}
// Sort to ensure predictable results
sort.Strings(envs)
return strings.Join(envs, "\n") + "\n"
}
// findInParentTree recursively searches for secretsFile starting at leafDir and in the
// directories above leafDir until it is found or the root of the file system is reached.
// If found, returns the absolute path to the file.
func findInParentTree(secretsFile string, leafDir string) (string, error) {
if filepath.IsAbs(secretsFile) {
return "", fmt.Errorf(
"file specified (%s) is an absolute path: will not recurse up", secretsFile)
}
for {
joinedPath := filepath.Join(leafDir, secretsFile)
_, err := os.Stat(joinedPath)
if err != nil {
// If the file is not present, we just move up one level and run the next loop
// iteration
if os.IsNotExist(err) {
upOne := filepath.Dir(leafDir)
if upOne == leafDir {
return "", fmt.Errorf(
"unable to locate file specified (%s): reached root of file system", secretsFile)
}
leafDir = upOne
continue
}
// If we have an unexpected error, we fail-fast
return "", fmt.Errorf("unable to locate file specified (%s): %s", secretsFile, err)
}
// If there's no error, we found the file so we return it
return joinedPath, nil
}
}
// scans arguments for the magic string; if found,
// creates a tempfile to which all the environment mappings are dumped
// and replaces the magic string with its path.
// Returns the path if so, returns an empty string otherwise.
func setupEnvFile(args []string, env map[string]string, tempFactory *TempFactory) string {
var envFile = ""
for i, arg := range args {
idx := strings.Index(arg, ENV_FILE_MAGIC)
if idx >= 0 {
if envFile == "" {
envFile = tempFactory.Push(joinEnv(env))
}
args[i] = strings.Replace(arg, ENV_FILE_MAGIC, envFile, -1)
}
}
return envFile
}
// convertSubsToMap converts the list of substitutions passed in via
// command line to a map
func convertSubsToMap(subs []string) map[string]string {
out := make(map[string]string)
for _, sub := range subs {
s := strings.SplitN(sub, "=", 2)
key, val := s[0], s[1]
out[key] = val
}
return out
}
func returnStatusOfError(err error) (int, error) {
if eerr, ok := err.(*exec.ExitError); ok {
if ws, ok := eerr.Sys().(syscall.WaitStatus); ok {
if ws.Exited() {
return ws.ExitStatus(), nil
}
}
}
return 0, err
}
// printProviderVersions returns a string of all provider versions
func printProviderVersions(providerPath string) (string, error) {
var providerVersions bytes.Buffer
providers, err := prov.GetAllProviders(providerPath)
if err != nil {
return "", err
}
for _, provider := range providers {
version, err := exec.Command(filepath.Join(providerPath, provider), "--version").Output()
if err != nil {
providerVersions.WriteString(fmt.Sprintf("%s: unknown version\n", provider))
continue
}
versionString := fmt.Sprintf("%s", version)
versionString = strings.TrimSpace(versionString)
providerVersions.WriteString(fmt.Sprintf("%s version %s\n", provider, versionString))
}
return providerVersions.String(), nil
}