forked from BinSquare/envmap
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
502 lines (479 loc) · 14.1 KB
/
main.go
File metadata and controls
502 lines (479 loc) · 14.1 KB
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/binsquare/envmap/provider"
"github.com/spf13/cobra"
)
// projectConfigPath can be set via --project flag to point to a specific .envmap.yaml.
var projectConfigPath string
func main() {
root := newRootCmd()
if err := root.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func newRootCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "envmap",
Short: "envMap replaces .env files with secure secret injection",
Long: "envMap fetches secrets from configured backends and injects them into processes without writing .env files.",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
cmd.SetContext(context.Background())
return nil
},
SilenceUsage: true,
SilenceErrors: true,
}
cmd.CompletionOptions.DisableDefaultCmd = true
cmd.PersistentFlags().StringVar(&projectConfigPath, "project", "", "path to .envmap.yaml (auto-detects by walking up from cwd if not set)")
cmd.AddCommand(
newInitCmd(),
newRunCmd(),
newExportCmd(),
newSetCmd(),
newGetCmd(),
newSyncCmd(),
newImportCmd(),
newKeygenCmd(),
newValidateCmd(),
)
return cmd
}
func newInitCmd() *cobra.Command {
var globalOnly bool
c := &cobra.Command{
Use: "init",
Short: "Interactively configure envMap",
RunE: func(cmd *cobra.Command, args []string) error {
if globalOnly {
return runInteractiveGlobalSetup(cmd.Context())
}
return runInteractiveInit(cmd.Context())
},
}
c.Flags().BoolVar(&globalOnly, "global", false, "configure ~/.envmap/config.yaml (providers)")
return c
}
func newRunCmd() *cobra.Command {
var envName string
c := &cobra.Command{
Use: "run [--env ENV] -- COMMAND [ARGS...]",
Short: "Run a command with secrets injected into the environment",
Long: `Run a command with secrets fetched from your configured provider and injected
as environment variables. This allows running applications without .env files.
The command and its arguments must come after a -- separator.
Examples:
envmap run -- node server.js
envmap run --env prod -- ./my-app
envmap run --env dev -- npm start
envmap run -- docker compose up`,
Args: cobra.MinimumNArgs(1),
DisableFlagParsing: false,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("no command specified; usage: envmap run -- COMMAND [ARGS...]")
}
projectCfg, _, err := loadProjectConfig()
if err != nil {
return err
}
globalCfg, err := LoadGlobalConfig("")
if err != nil {
return err
}
envToUse, err := ResolveEnv(projectCfg, envName)
if err != nil {
return err
}
secretEnv, err := CollectEnv(cmd.Context(), projectCfg, globalCfg, envToUse)
if err != nil {
return err
}
fmt.Fprintf(os.Stderr, "envmap: injecting %d secrets from env %q\n", len(secretEnv), envToUse)
return SpawnWithEnv(cmd.Context(), args[0], args[1:], secretEnv)
},
}
c.Flags().StringVar(&envName, "env", "", "environment name to use (defaults to project default_env)")
return c
}
func newExportCmd() *cobra.Command {
var envName string
var format string
c := &cobra.Command{
Use: "export",
Short: "Export secrets to stdout for shell eval or tooling",
Long: `Export secrets in machine-readable format to stdout.
Formats:
plain KEY=VAL lines, suitable for shell eval or direnv
json JSON object, suitable for tooling
Examples:
eval $(envmap export --env dev)
envmap export --env dev --format json | jq .`,
RunE: func(cmd *cobra.Command, args []string) error {
projectCfg, _, err := loadProjectConfig()
if err != nil {
return err
}
globalCfg, err := LoadGlobalConfig("")
if err != nil {
return err
}
envToUse, err := ResolveEnv(projectCfg, envName)
if err != nil {
return err
}
secretEnv, err := CollectEnv(cmd.Context(), projectCfg, globalCfg, envToUse)
if err != nil {
return err
}
switch format {
case "plain", "":
keys := make([]string, 0, len(secretEnv))
for k := range secretEnv {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("%s=%s\n", k, secretEnv[k])
}
case "json":
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(secretEnv)
default:
return fmt.Errorf("unknown format %q (use plain or json)", format)
}
return nil
},
}
c.Flags().StringVar(&envName, "env", "", "environment name to use (defaults to project default_env)")
c.Flags().StringVar(&format, "format", "plain", "output format: plain or json")
return c
}
func newSetCmd() *cobra.Command {
var envName string
var fromFile string
var promptSecret bool
var deleteKey bool
c := &cobra.Command{
Use: "set --env ENV KEY [--file PATH|--prompt]",
Short: "Set a secret key/value in the configured backend without exposing value on the command line",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if envName == "" {
return errors.New("provide --env to select which environment to target")
}
key := args[0]
var value string
if deleteKey {
value = ""
} else {
if fromFile != "" && promptSecret {
return errors.New("use only one of --file or --prompt")
}
if fromFile != "" {
valueBytes, err := os.ReadFile(fromFile)
if err != nil {
return fmt.Errorf("read secret file: %w", err)
}
value = strings.TrimSpace(string(valueBytes))
} else if promptSecret {
v, err := readSecretFromPrompt("Secret value: ")
if err != nil {
return err
}
value = v
} else {
return errors.New("provide --file or --prompt to supply the secret without shell history leakage")
}
}
projectCfg, _, err := loadProjectConfig()
if err != nil {
return err
}
globalCfg, err := LoadGlobalConfig("")
if err != nil {
return err
}
if deleteKey {
return DeleteSecret(cmd.Context(), projectCfg, globalCfg, envName, key)
}
return WriteSecret(cmd.Context(), projectCfg, globalCfg, envName, key, value)
},
}
c.Flags().StringVar(&envName, "env", "", "environment name to target")
c.Flags().StringVar(&fromFile, "file", "", "path to file containing the secret value")
c.Flags().BoolVar(&promptSecret, "prompt", false, "prompt for the secret (no echo)")
c.Flags().BoolVar(&deleteKey, "delete", false, "delete the specified key from the backend")
return c
}
func newGetCmd() *cobra.Command {
var envName string
var raw bool
var all bool
var globalAll bool
c := &cobra.Command{
Use: "get --env ENV KEY",
Short: "Get a secret from the configured backend",
Args: cobra.RangeArgs(0, 1),
RunE: func(cmd *cobra.Command, args []string) error {
if globalAll && !all {
return errors.New("use --global together with --all")
}
projectCfg, _, err := loadProjectConfig()
if err != nil {
return err
}
globalCfg, err := LoadGlobalConfig("")
if err != nil {
return err
}
if globalAll {
for envNameIter := range projectCfg.Envs {
if err := printEnvSecrets(cmd.Context(), projectCfg, globalCfg, envNameIter, raw); err != nil {
return err
}
}
return nil
}
if envName == "" {
return errors.New("provide --env to select which environment to target")
}
envToUse := envName
if all {
return printEnvSecrets(cmd.Context(), projectCfg, globalCfg, envToUse, raw)
}
if len(args) != 1 {
return errors.New("provide KEY or use --all")
}
key := args[0]
value, err := FetchSecret(cmd.Context(), projectCfg, globalCfg, envToUse, key)
if err != nil {
return err
}
if raw {
fmt.Printf("%s\n", value)
return nil
}
fmt.Printf("%s\n", MaskValue(value))
return nil
},
}
c.Flags().StringVar(&envName, "env", "", "environment name to target")
c.Flags().BoolVar(&raw, "raw", false, "print raw secret value (use with care)")
c.Flags().BoolVar(&all, "all", false, "print all secrets for the environment (masked by default)")
c.Flags().BoolVar(&globalAll, "global", false, "with --all, list secrets for all environments")
return c
}
func newImportCmd() *cobra.Command {
var envName string
var deleteAfter bool
c := &cobra.Command{
Use: "import PATH --env ENV",
Short: "Import secrets from a .env file into a provider",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if envName == "" {
return errors.New("provide --env to select which environment to import into")
}
path := args[0]
entries, err := parseDotEnv(path)
if err != nil {
return err
}
if len(entries) == 0 {
return fmt.Errorf("no entries found in %s", path)
}
projectCfg, _, err := loadProjectConfig()
if err != nil {
return err
}
globalCfg, err := LoadGlobalConfig("")
if err != nil {
return err
}
fmt.Printf("Importing %d keys into env %s from %s\n", len(entries), envName, path)
for k := range entries {
fmt.Printf(" - %s\n", k)
}
for k, v := range entries {
if err := WriteSecret(cmd.Context(), projectCfg, globalCfg, envName, k, v); err != nil {
return err
}
}
if deleteAfter {
if err := os.Remove(path); err != nil {
return fmt.Errorf("import succeeded but failed to delete %s: %w", path, err)
}
fmt.Printf("Deleted %s\n", path)
}
return nil
},
}
c.Flags().StringVar(&envName, "env", "", "environment name to import into")
c.Flags().BoolVar(&deleteAfter, "delete", false, "delete the source .env file after successful import")
return c
}
func newSyncCmd() *cobra.Command {
var envName string
var outPath string
var merge bool
var keepLocal bool
var force bool
var backup bool
var checkOnly bool
c := &cobra.Command{
Use: "sync",
Short: "Sync provider secrets to a .env-style file",
RunE: func(cmd *cobra.Command, args []string) error {
if envName == "" {
return errors.New("provide --env to select which environment to sync")
}
projectCfg, _, err := loadProjectConfig()
if err != nil {
return err
}
globalCfg, err := LoadGlobalConfig("")
if err != nil {
return err
}
envToUse, err := ResolveEnv(projectCfg, envName)
if err != nil {
return err
}
dest := outPath
if dest == "" {
dest = ".env"
}
records, err := CollectEnvWithMetadata(cmd.Context(), projectCfg, globalCfg, envToUse)
if err != nil {
return err
}
if checkOnly {
return checkEnvDrift(dest, records)
}
return syncEnvFile(dest, records, merge, keepLocal, force, backup)
},
}
c.Flags().StringVar(&envName, "env", "", "environment name to sync from")
c.Flags().StringVar(&outPath, "out", ".env", "path to output .env file")
c.Flags().BoolVar(&merge, "merge", false, "preserve keys that only exist in the existing file (provider still wins on conflicts)")
c.Flags().BoolVar(&keepLocal, "keep-local", false, "on conflicts, keep existing file values instead of provider values (use with care)")
c.Flags().BoolVar(&force, "force", false, "skip confirmation even if file is tracked or will be overwritten")
c.Flags().BoolVar(&backup, "backup", true, "write a .bak file before overwriting")
c.Flags().BoolVar(&checkOnly, "check", false, "only report drift; do not write")
return c
}
func newKeygenCmd() *cobra.Command {
var output string
c := &cobra.Command{
Use: "keygen",
Short: "Generate a local-store encryption key",
RunE: func(cmd *cobra.Command, args []string) error {
if output == "" {
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("get home dir: %w", err)
}
output = filepath.Join(home, ".envmap", "key")
}
if _, err := os.Stat(output); err == nil {
return fmt.Errorf("key file %s already exists; remove it first if you want to regenerate", output)
}
if err := provider.GenerateKeyFile(output); err != nil {
return err
}
fmt.Printf("Generated encryption key: %s\n", output)
fmt.Println("Keep this file secure and backed up. Do not commit to version control.")
return nil
},
}
c.Flags().StringVarP(&output, "output", "o", "", "output path (default: ~/.envmap/key)")
return c
}
func newValidateCmd() *cobra.Command {
return &cobra.Command{
Use: "validate",
Short: "Validate configuration",
RunE: func(cmd *cobra.Command, args []string) error {
projectCfg, _, err := loadProjectConfig()
if err != nil {
return err
}
globalCfg, err := LoadGlobalConfig("")
if err != nil {
return err
}
fmt.Printf("Project: %s\n", projectCfg.Project)
fmt.Printf("Envs: %d (default: %s)\n", len(projectCfg.Envs), projectCfg.DefaultEnv)
providers := globalCfg.GetProviders()
missing := []string{}
for envName, envCfg := range projectCfg.Envs {
providerName := envCfg.GetProvider()
if _, ok := providers[providerName]; !ok {
missing = append(missing, fmt.Sprintf("%s → %s", envName, providerName))
}
}
if len(missing) > 0 {
fmt.Println("\nMissing providers in ~/.envmap/config.yaml:")
for _, m := range missing {
fmt.Printf(" %s\n", m)
}
return fmt.Errorf("missing providers")
}
fmt.Println("Configuration looks good.")
return nil
},
}
}
func printEnvSecrets(ctx context.Context, projectCfg ProjectConfig, globalCfg GlobalConfig, envName string, raw bool) error {
records, err := CollectEnvWithMetadata(ctx, projectCfg, globalCfg, envName)
if err != nil {
return err
}
keys := make([]string, 0, len(records))
for k := range records {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Fprintf(os.Stderr, "# env: %s (%d secrets)\n", envName, len(keys))
for _, k := range keys {
rec := records[k]
val := rec.Value
if !raw {
val = MaskValue(val)
}
fmt.Printf("%s=%s", k, val)
if !rec.CreatedAt.IsZero() {
fmt.Printf(" # created %s", rec.CreatedAt.UTC().Format(time.RFC3339))
}
fmt.Println()
}
return nil
}
func loadProjectConfig() (ProjectConfig, string, error) {
var path string
if projectConfigPath != "" {
path = projectConfigPath
} else {
found, err := FindProjectConfig("")
if err != nil {
return ProjectConfig{}, "", err
}
path = found
}
cfg, err := LoadProjectConfig(path)
if err != nil {
return ProjectConfig{}, "", err
}
return cfg, path, nil
}