-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
520 lines (459 loc) · 13.1 KB
/
main.go
File metadata and controls
520 lines (459 loc) · 13.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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
// nillsec – encrypted project-secret vault.
//
// Usage:
//
// nillsec init create a new vault
// nillsec add <key> <value> add a secret (fails if key exists)
// nillsec set <key> <value> add or overwrite a secret
// nillsec get <key> print a secret value
// nillsec list list secret keys
// nillsec remove <key> delete a secret
// nillsec edit open vault in $EDITOR
// nillsec env export secrets as shell variables
// nillsec exec [--] <cmd> [args...] run a command with secrets injected
// nillsec upgrade upgrade nillsec to the latest release
//
// The vault file is secrets.vault in the current directory unless
// NILLSEC_VAULT is set.
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"syscall"
"github.com/403-html/nillsec/vault"
"golang.org/x/term"
)
// version is set at build time via -ldflags "-X main.version=<tag>".
var version = "dev"
// osExitFn exits the process with the given code; overridable in tests.
var osExitFn = os.Exit
// validKeyRe matches valid POSIX shell identifier names (used as env var names).
var validKeyRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
func main() {
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
func run(args []string) error {
if len(args) == 0 {
printUsage()
return nil
}
cmd, rest := args[0], args[1:]
switch cmd {
case "init":
return cmdInit(rest)
case "add":
return cmdAdd(rest, false)
case "set":
return cmdAdd(rest, true)
case "get":
return cmdGet(rest)
case "list":
return cmdList(rest)
case "remove", "rm":
return cmdRemove(rest)
case "edit":
return cmdEdit(rest)
case "env":
return cmdEnv(rest)
case "exec":
return cmdExec(rest)
case "upgrade":
return cmdUpgrade()
case "version", "--version", "-v":
fmt.Println("nillsec", version)
return nil
case "help", "-h", "--help":
printUsage()
return nil
default:
printUsage()
return fmt.Errorf("unknown command: %q", cmd)
}
}
// ---------------------------------------------------------------------------
// Command implementations
// ---------------------------------------------------------------------------
func cmdInit(args []string) error {
path := vaultPath(args)
pw, err := promptPasswordConfirm()
if err != nil {
return err
}
defer wipeBytes(pw)
if err := vault.Init(path, pw); err != nil {
return err
}
fmt.Println("Vault created:", path)
return nil
}
// cmdAdd handles both "add" (overwrite=false) and "set" (overwrite=true).
func cmdAdd(args []string, overwrite bool) error {
if len(args) < 2 {
return fmt.Errorf("usage: nillsec %s <key> <value>", map[bool]string{true: "set", false: "add"}[overwrite])
}
key, value := args[0], args[1]
if !validKeyRe.MatchString(key) {
return fmt.Errorf("invalid key %q: must be a valid POSIX identifier ([A-Za-z_][A-Za-z0-9_]*)", key)
}
path := vaultPath(nil)
pw, err := promptPassword("Master password: ")
if err != nil {
return err
}
defer wipeBytes(pw)
v, err := vault.Load(path, pw)
if err != nil {
return err
}
if !overwrite {
if _, exists := v.Get(key); exists {
return fmt.Errorf("key %q already exists; use 'set' to overwrite", key)
}
}
v.Set(key, value)
return vault.Save(path, pw, v)
}
func cmdGet(args []string) error {
if len(args) < 1 {
return fmt.Errorf("usage: nillsec get <key>")
}
key := args[0]
path := vaultPath(nil)
pw, err := promptPassword("Master password: ")
if err != nil {
return err
}
defer wipeBytes(pw)
v, err := vault.Load(path, pw)
if err != nil {
return err
}
val, ok := v.Get(key)
if !ok {
return fmt.Errorf("key not found: %q", key)
}
fmt.Println(val)
return nil
}
func cmdList(_ []string) error {
path := vaultPath(nil)
pw, err := promptPassword("Master password: ")
if err != nil {
return err
}
defer wipeBytes(pw)
v, err := vault.Load(path, pw)
if err != nil {
return err
}
for _, k := range v.Keys() {
fmt.Println(k)
}
return nil
}
func cmdRemove(args []string) error {
if len(args) < 1 {
return fmt.Errorf("usage: nillsec remove <key>")
}
key := args[0]
path := vaultPath(nil)
pw, err := promptPassword("Master password: ")
if err != nil {
return err
}
defer wipeBytes(pw)
v, err := vault.Load(path, pw)
if err != nil {
return err
}
if !v.Delete(key) {
return fmt.Errorf("key not found: %q", key)
}
return vault.Save(path, pw, v)
}
func cmdEdit(_ []string) error {
path := vaultPath(nil)
pw, err := promptPassword("Master password: ")
if err != nil {
return err
}
defer wipeBytes(pw)
v, err := vault.Load(path, pw)
if err != nil {
return err
}
text, err := v.MarshalText()
if err != nil {
return err
}
defer wipeBytes(text)
ef, err := newEditorFile(text)
if err != nil {
return err
}
defer ef.discard()
// Open in editor.
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vi"
}
editorCmd := exec.Command(editor, ef.path()) //nolint:gosec
editorCmd.Stdin = os.Stdin
editorCmd.Stdout = os.Stdout
editorCmd.Stderr = os.Stderr
if err := editorCmd.Run(); err != nil {
return fmt.Errorf("editor exited with error: %w", err)
}
edited, err := ef.readAndClose()
if err != nil {
return err
}
defer wipeBytes(edited)
if err := v.UnmarshalText(edited); err != nil {
return err
}
return vault.Save(path, pw, v)
}
func cmdEnv(_ []string) error {
path := vaultPath(nil)
pw, err := promptPassword("Master password: ")
if err != nil {
return err
}
defer wipeBytes(pw)
v, err := vault.Load(path, pw)
if err != nil {
return err
}
for _, k := range v.Keys() {
val, _ := v.Get(k)
envKey := strings.ToUpper(k)
// Single-quote the value and escape any embedded single quotes.
safeVal := strings.ReplaceAll(val, "'", "'\\''")
fmt.Printf("export %s='%s'\n", envKey, safeVal)
}
return nil
}
func cmdExec(args []string) error {
// Strip a leading "--" separator so that both
// nillsec exec -- npm run dev
// nillsec exec npm run dev
// work correctly. Only the very first argument is checked; any subsequent
// "--" is left in place and passed through to the child command as-is.
cmdArgs := args
if len(args) > 0 && args[0] == "--" {
cmdArgs = args[1:]
}
if len(cmdArgs) == 0 {
return fmt.Errorf("usage: nillsec exec [--] <command> [args...]")
}
path := vaultPath(nil)
pw, err := promptPassword("Master password: ")
if err != nil {
return err
}
defer wipeBytes(pw)
v, err := vault.Load(path, pw)
if err != nil {
return err
}
// Build the child's environment: inherit the current environment, then
// overlay vault secrets so they take precedence over any existing values.
// On Windows, env-var keys are case-insensitive, so we normalize them to
// upper-case to ensure vault values reliably override inherited ones.
env := buildChildEnv(os.Environ(), v, runtime.GOOS == "windows")
// Resolve the executable against the child's PATH so that a vault-provided
// PATH override takes effect at lookup time rather than the current process PATH.
resolvedCmd, err := lookPathInEnv(cmdArgs[0], env)
if err != nil {
return fmt.Errorf("exec: %w", err)
}
cmd := exec.Command(resolvedCmd, cmdArgs[1:]...) //nolint:gosec
cmd.Env = env
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
osExitFn(exitErr.ExitCode())
return nil
}
return fmt.Errorf("exec: %w", err)
}
return nil
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
// buildChildEnv merges an inherited environment slice with vault secrets.
// Vault values are always upper-cased and take precedence over any inherited
// entry with the same name. When normalizeKeys is true (Windows), inherited
// keys are upper-cased before the merge so that mixed-case names such as
// "Path" do not survive alongside the upper-cased vault key "PATH".
func buildChildEnv(inherited []string, v *vault.Vault, normalizeKeys bool) []string {
envMap := make(map[string]string, len(inherited))
for _, e := range inherited {
k, val, _ := strings.Cut(e, "=")
if normalizeKeys {
k = strings.ToUpper(k)
}
envMap[k] = val
}
for _, k := range v.Keys() {
val, _ := v.Get(k)
envMap[strings.ToUpper(k)] = val
}
env := make([]string, 0, len(envMap))
for k, val := range envMap {
env = append(env, k+"="+val)
}
return env
}
// lookPathInEnv resolves an executable name against the PATH entry found in
// childEnv, so that a vault-provided PATH override is honoured at lookup time
// rather than the current process PATH. If name contains a path separator it
// is returned unchanged. Falls back to exec.LookPath when childEnv has no PATH.
func lookPathInEnv(name string, childEnv []string) (string, error) {
// Explicit or relative path – no directory search needed.
if strings.ContainsRune(name, os.PathSeparator) || (runtime.GOOS == "windows" && strings.ContainsRune(name, '/')) {
return name, nil
}
// Extract PATH from the child environment.
for _, e := range childEnv {
k, v, ok := strings.Cut(e, "=")
if !ok {
continue
}
keyMatches := k == "PATH"
if runtime.GOOS == "windows" {
keyMatches = strings.EqualFold(k, "PATH")
}
if !keyMatches {
continue
}
// Search each directory in the child PATH for an executable.
for _, dir := range filepath.SplitList(v) {
if dir == "" {
dir = "."
}
candidate := filepath.Join(dir, name)
fi, err := os.Stat(candidate)
if err != nil || fi.IsDir() {
continue
}
if runtime.GOOS != "windows" && fi.Mode()&0111 == 0 {
continue // not executable on Unix
}
return candidate, nil
}
return "", &exec.Error{Name: name, Err: exec.ErrNotFound}
}
// No PATH in child env; fall back to current process PATH.
return exec.LookPath(name)
}
// vaultPath returns the vault file path from args, NILLSEC_VAULT env var,
// or the default "secrets.vault".
func vaultPath(args []string) string {
if len(args) > 0 {
return args[0]
}
if p := os.Getenv("NILLSEC_VAULT"); p != "" {
return p
}
return "secrets.vault"
}
// stdinReader is a shared buffered reader for non-TTY password input.
// Using a package-level reader prevents data loss when promptPassword is
// called multiple times.
var stdinReader *bufio.Reader
func init() {
stdinReader = bufio.NewReader(os.Stdin)
}
// promptPassword reads a password.
// Priority: NILLSEC_PASSWORD env var → TTY (no echo) → stdin line.
func promptPassword(prompt string) ([]byte, error) {
// Allow override via environment variable (useful in CI / scripts).
if pw := os.Getenv("NILLSEC_PASSWORD"); pw != "" {
return []byte(pw), nil
}
// If stdin is a real terminal, read without echo.
if term.IsTerminal(int(syscall.Stdin)) {
fmt.Fprint(os.Stderr, prompt)
pw, err := term.ReadPassword(int(syscall.Stdin))
fmt.Fprintln(os.Stderr)
if err != nil {
return nil, fmt.Errorf("cannot read password: %w", err)
}
if len(pw) == 0 {
return nil, fmt.Errorf("password must not be empty")
}
return pw, nil
}
// Non-TTY (piped) – read a line from the shared stdin reader.
line, err := stdinReader.ReadString('\n')
if err != nil && line == "" {
return nil, fmt.Errorf("cannot read password from stdin: %w", err)
}
pw := strings.TrimRight(line, "\r\n")
if pw == "" {
return nil, fmt.Errorf("password must not be empty")
}
return []byte(pw), nil
}
// promptPasswordConfirm reads a password twice and ensures they match.
// When stdin is not a TTY the two passwords are expected on separate lines.
func promptPasswordConfirm() ([]byte, error) {
pw1, err := promptPassword("Master password: ")
if err != nil {
return nil, err
}
pw2, err := promptPassword("Confirm password: ")
if err != nil {
wipeBytes(pw1)
return nil, err
}
defer wipeBytes(pw2)
if !bytes.Equal(pw1, pw2) {
wipeBytes(pw1)
return nil, fmt.Errorf("passwords do not match")
}
return pw1, nil
}
// wipeBytes overwrites a byte slice.
func wipeBytes(b []byte) {
for i := range b {
b[i] = 0
}
}
func printUsage() {
fmt.Fprint(os.Stderr, `nillsec – encrypted project-secret vault
Usage:
nillsec init create a new vault (secrets.vault)
nillsec add <key> <value> add a secret (error if key already exists)
nillsec set <key> <value> add or overwrite a secret
nillsec get <key> print a secret value
nillsec list list secret keys (no values)
nillsec remove <key> delete a secret
nillsec edit open vault contents in $EDITOR
nillsec env print secrets as export statements
nillsec exec [--] <cmd> ... run a command with secrets injected as env vars
nillsec upgrade upgrade nillsec to the latest release
nillsec version print version
Environment:
NILLSEC_VAULT vault file path (default: secrets.vault)
NILLSEC_PASSWORD master password (optional; if set, prompts may be skipped)
EDITOR editor used by 'edit' command (default: vi)
`)
}