-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
583 lines (497 loc) · 18.4 KB
/
main_test.go
File metadata and controls
583 lines (497 loc) · 18.4 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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
package main
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/403-html/nillsec/vault"
)
const editTestPassword = "edit-test-password"
// makeTestVault initialises a vault at path and optionally seeds it with secrets.
func makeTestVault(t *testing.T, path string, secrets map[string]string) {
t.Helper()
if err := vault.Init(path, []byte(editTestPassword)); err != nil {
t.Fatalf("vault.Init: %v", err)
}
if len(secrets) == 0 {
return
}
v, err := vault.Load(path, []byte(editTestPassword))
if err != nil {
t.Fatalf("vault.Load: %v", err)
}
for k, val := range secrets {
v.Set(k, val)
}
if err := vault.Save(path, []byte(editTestPassword), v); err != nil {
t.Fatalf("vault.Save: %v", err)
}
}
// fakeEditor writes a shell script that replaces its first argument with
// the content of newContentFile, and then records the path it was given in
// pathRecordFile (if non-empty). Returns the path to the script.
func fakeEditor(t *testing.T, dir, newContentFile, pathRecordFile string) string {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("shell-script fake editor not supported on Windows")
}
var sb strings.Builder
sb.WriteString("#!/bin/sh\n")
if pathRecordFile != "" {
sb.WriteString("echo \"$1\" > \"" + pathRecordFile + "\"\n")
}
sb.WriteString("cp \"" + newContentFile + "\" \"$1\"\n")
script := filepath.Join(dir, "fake-editor.sh")
if err := os.WriteFile(script, []byte(sb.String()), 0700); err != nil {
t.Fatalf("write fake editor: %v", err)
}
return script
}
// TestCmdEditRoundTrip verifies that cmdEdit reads the vault, passes it to the
// editor, and re-encrypts the edited content back into the vault file.
func TestCmdEditRoundTrip(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script fake editor not supported on Windows")
}
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, map[string]string{"existing": "original"})
// New content the fake editor will write.
newContent := `{"version":1,"secrets":{"existing":"original","added_key":"added_value"}}`
newContentFile := filepath.Join(dir, "new-content.json")
if err := os.WriteFile(newContentFile, []byte(newContent), 0600); err != nil {
t.Fatalf("write new content file: %v", err)
}
editor := fakeEditor(t, dir, newContentFile, "")
t.Setenv("NILLSEC_VAULT", vaultFile)
t.Setenv("NILLSEC_PASSWORD", editTestPassword)
t.Setenv("EDITOR", editor)
if err := cmdEdit(nil); err != nil {
t.Fatalf("cmdEdit: %v", err)
}
v, err := vault.Load(vaultFile, []byte(editTestPassword))
if err != nil {
t.Fatalf("vault.Load after edit: %v", err)
}
if val, ok := v.Get("added_key"); !ok || val != "added_value" {
t.Errorf("added_key = %q, %v; want %q, true", val, ok, "added_value")
}
if val, ok := v.Get("existing"); !ok || val != "original" {
t.Errorf("existing = %q, %v; want %q, true", val, ok, "original")
}
}
// TestCmdEditCleansUpEditorFile verifies that the editor file is removed once
// cmdEdit returns after a successful edit.
func TestCmdEditCleansUpEditorFile(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script fake editor not supported on Windows")
}
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, nil)
newContent := `{"version":1,"secrets":{"k":"v"}}`
newContentFile := filepath.Join(dir, "new-content.json")
if err := os.WriteFile(newContentFile, []byte(newContent), 0600); err != nil {
t.Fatalf("write new content file: %v", err)
}
pathRecordFile := filepath.Join(dir, "editor-path.txt")
editor := fakeEditor(t, dir, newContentFile, pathRecordFile)
t.Setenv("NILLSEC_VAULT", vaultFile)
t.Setenv("NILLSEC_PASSWORD", editTestPassword)
t.Setenv("EDITOR", editor)
if err := cmdEdit(nil); err != nil {
t.Fatalf("cmdEdit: %v", err)
}
raw, err := os.ReadFile(pathRecordFile)
if err != nil {
t.Fatalf("read path record file: %v", err)
}
editorPath := strings.TrimRight(string(raw), "\n\r")
if _, err := os.Stat(editorPath); !os.IsNotExist(err) {
t.Errorf("editor file %q still exists after cmdEdit completed; expected it to be removed", editorPath)
}
}
// TestCmdEditCleansUpEditorFileOnEditorError verifies that the editor file is
// removed even when the editor exits with a non-zero status.
func TestCmdEditCleansUpEditorFileOnEditorError(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script fake editor not supported on Windows")
}
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, nil)
pathRecordFile := filepath.Join(dir, "editor-path.txt")
// A script that records the editor-file path but exits with an error.
script := filepath.Join(dir, "fail-editor.sh")
scriptContent := "#!/bin/sh\necho \"$1\" > \"" + pathRecordFile + "\"\nexit 1\n"
if err := os.WriteFile(script, []byte(scriptContent), 0700); err != nil {
t.Fatalf("write fail editor: %v", err)
}
t.Setenv("NILLSEC_VAULT", vaultFile)
t.Setenv("NILLSEC_PASSWORD", editTestPassword)
t.Setenv("EDITOR", script)
if err := cmdEdit(nil); err == nil {
t.Fatal("cmdEdit: expected error from failing editor, got nil")
}
raw, err := os.ReadFile(pathRecordFile)
if err != nil {
t.Fatalf("read path record file: %v", err)
}
editorPath := strings.TrimRight(string(raw), "\n\r")
if _, err := os.Stat(editorPath); !os.IsNotExist(err) {
t.Errorf("editor file %q still exists after cmdEdit returned error; expected it to be removed", editorPath)
}
}
// TestCmdEditUsesDevShm verifies that on Linux (where /dev/shm is available)
// the editor file is placed in /dev/shm so that the plaintext never reaches a
// physical disk.
func TestCmdEditUsesDevShm(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("Linux-only: /dev/shm memory-backed storage test")
}
if _, err := os.Stat("/dev/shm"); err != nil {
t.Skip("/dev/shm not available on this system")
}
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, nil)
newContent := `{"version":1,"secrets":{"k":"v"}}`
newContentFile := filepath.Join(dir, "new-content.json")
if err := os.WriteFile(newContentFile, []byte(newContent), 0600); err != nil {
t.Fatalf("write new content file: %v", err)
}
pathRecordFile := filepath.Join(dir, "editor-path.txt")
editor := fakeEditor(t, dir, newContentFile, pathRecordFile)
t.Setenv("NILLSEC_VAULT", vaultFile)
t.Setenv("NILLSEC_PASSWORD", editTestPassword)
t.Setenv("EDITOR", editor)
if err := cmdEdit(nil); err != nil {
t.Fatalf("cmdEdit: %v", err)
}
raw, err := os.ReadFile(pathRecordFile)
if err != nil {
t.Fatalf("read path record file: %v", err)
}
editorPath := strings.TrimRight(string(raw), "\n\r")
if !strings.HasPrefix(editorPath, "/dev/shm/") {
t.Errorf("editor file path %q does not start with /dev/shm/; plaintext may have been written to disk", editorPath)
}
}
// TestBuildChildEnvWindowsNormalization verifies that when normalizeKeys is
// true (simulating Windows), inherited env keys are upper-cased before the
// merge so that vault values deterministically override mixed-case entries
// (e.g. "Path" from Windows' os.Environ() is overridden by vault key "path"
// which is stored as "PATH").
func TestBuildChildEnvWindowsNormalization(t *testing.T) {
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, map[string]string{
"path": "/vault/bin",
"foo": "vaultfoo",
})
v, err := vault.Load(vaultFile, []byte(editTestPassword))
if err != nil {
t.Fatalf("vault.Load: %v", err)
}
// Simulate Windows inherited env: mixed-case keys.
inherited := []string{
"Path=C:\\Windows\\System32",
"Foo=inheritfoo",
"TEMP=C:\\Temp",
}
env := buildChildEnv(inherited, v, true /* normalizeKeys = Windows */)
got := make(map[string]string, len(env))
for _, e := range env {
k, val, _ := strings.Cut(e, "=")
got[k] = val
}
// Vault "path" (→ "PATH") must override inherited "Path".
if got["PATH"] != "/vault/bin" {
t.Errorf("PATH = %q; want %q", got["PATH"], "/vault/bin")
}
// Mixed-case key must not survive; only upper-case form exists.
if _, exists := got["Path"]; exists {
t.Error("envMap still contains mixed-case key 'Path'; expected it to be normalized to 'PATH'")
}
// Vault "foo" (→ "FOO") must override inherited "Foo".
if got["FOO"] != "vaultfoo" {
t.Errorf("FOO = %q; want %q", got["FOO"], "vaultfoo")
}
if _, exists := got["Foo"]; exists {
t.Error("envMap still contains mixed-case key 'Foo'; expected it to be normalized to 'FOO'")
}
// Non-conflicting inherited key normalized to upper.
if got["TEMP"] != "C:\\Temp" {
t.Errorf("TEMP = %q; want %q", got["TEMP"], "C:\\Temp")
}
}
// TestBuildChildEnvNoNormalization verifies that when normalizeKeys is false
// (non-Windows), mixed-case inherited keys are preserved as-is, and vault
// values are stored under their upper-cased names without affecting other keys.
func TestBuildChildEnvNoNormalization(t *testing.T) {
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, map[string]string{"secret": "vaultval"})
v, err := vault.Load(vaultFile, []byte(editTestPassword))
if err != nil {
t.Fatalf("vault.Load: %v", err)
}
inherited := []string{
"existing=inherit",
"SECRET=will-be-overridden",
}
env := buildChildEnv(inherited, v, false /* normalizeKeys = non-Windows */)
got := make(map[string]string, len(env))
for _, e := range env {
k, val, _ := strings.Cut(e, "=")
got[k] = val
}
// "existing" preserved with original case.
if got["existing"] != "inherit" {
t.Errorf("existing = %q; want %q", got["existing"], "inherit")
}
// Vault "secret" (→ "SECRET") overrides inherited "SECRET".
if got["SECRET"] != "vaultval" {
t.Errorf("SECRET = %q; want %q", got["SECRET"], "vaultval")
}
}
// TestLookPathInEnvUsesChildPath verifies that lookPathInEnv finds an
// executable in a directory listed in the child env's PATH rather than in
// the current process PATH.
func TestLookPathInEnvUsesChildPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("executable permission bits not applicable on Windows")
}
dir := t.TempDir()
exe := filepath.Join(dir, "myfakeexe")
if err := os.WriteFile(exe, []byte("#!/bin/sh\n"), 0755); err != nil {
t.Fatalf("write executable: %v", err)
}
childEnv := []string{"PATH=" + dir}
got, err := lookPathInEnv("myfakeexe", childEnv)
if err != nil {
t.Fatalf("lookPathInEnv: %v", err)
}
if got != exe {
t.Errorf("resolved path = %q; want %q", got, exe)
}
}
// TestLookPathInEnvExplicitPath verifies that a name containing a path
// separator is returned as-is without performing a directory search.
func TestLookPathInEnvExplicitPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("path separator semantics differ on Windows")
}
name := "/usr/bin/env"
childEnv := []string{"PATH=/some/dir"}
got, err := lookPathInEnv(name, childEnv)
if err != nil {
t.Fatalf("lookPathInEnv: %v", err)
}
if got != name {
t.Errorf("got %q; want %q", got, name)
}
}
// TestLookPathInEnvFallback verifies that when childEnv contains no PATH
// entry, lookPathInEnv falls back to the current process PATH via exec.LookPath.
func TestLookPathInEnvFallback(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("sh not available on Windows")
}
// "sh" must be resolvable via the current process PATH on any Unix host.
got, err := lookPathInEnv("sh", nil /* no PATH entry */)
if err != nil {
t.Fatalf("lookPathInEnv fallback: %v", err)
}
if got == "" {
t.Error("expected a non-empty resolved path for 'sh'")
}
}
// TestLookPathInEnvNotFound verifies that an error is returned when the
// executable is not found in the child env PATH.
func TestLookPathInEnvNotFound(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("executable permission bits not applicable on Windows")
}
childEnv := []string{"PATH=/nonexistent/directory"}
_, err := lookPathInEnv("no-such-binary", childEnv)
if err == nil {
t.Fatal("expected error for missing executable, got nil")
}
}
// TestCmdExecUsesVaultPath verifies that cmdExec resolves the command name
// using the vault-provided PATH rather than the current process PATH.
func TestCmdExecUsesVaultPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script subprocess not supported on Windows")
}
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
// Create a fake executable named "myapp" reachable only via binDir.
binDir := filepath.Join(dir, "bin")
if err := os.Mkdir(binDir, 0755); err != nil {
t.Fatalf("mkdir bin: %v", err)
}
outFile := filepath.Join(dir, "out.txt")
fakeExe := filepath.Join(binDir, "myapp")
scriptContent := "#!/bin/sh\necho ran > \"" + outFile + "\"\n"
if err := os.WriteFile(fakeExe, []byte(scriptContent), 0755); err != nil {
t.Fatalf("write fake exe: %v", err)
}
// Store binDir as the vault PATH so cmdExec can resolve "myapp" by name.
makeTestVault(t, vaultFile, map[string]string{"path": binDir})
t.Setenv("NILLSEC_VAULT", vaultFile)
t.Setenv("NILLSEC_PASSWORD", editTestPassword)
// "myapp" is not on the current process PATH; only the vault PATH has it.
if err := cmdExec([]string{"myapp"}); err != nil {
t.Fatalf("cmdExec: %v", err)
}
raw, err := os.ReadFile(outFile)
if err != nil {
t.Fatalf("read out file: %v", err)
}
if got := strings.TrimRight(string(raw), "\n\r"); got != "ran" {
t.Errorf("output = %q; want %q", got, "ran")
}
}
// TestCmdExecInjectsSecrets verifies that cmdExec injects vault secrets as
// environment variables into the child process.
func TestCmdExecInjectsSecrets(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script subprocess not supported on Windows")
}
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, map[string]string{
"my_secret": "hunter2",
"api_token": "tok-abc",
})
// Script that writes the value of MY_SECRET to a file.
outFile := filepath.Join(dir, "out.txt")
script := filepath.Join(dir, "check-env.sh")
scriptContent := "#!/bin/sh\necho \"$MY_SECRET\" > \"" + outFile + "\"\n"
if err := os.WriteFile(script, []byte(scriptContent), 0700); err != nil {
t.Fatalf("write script: %v", err)
}
t.Setenv("NILLSEC_VAULT", vaultFile)
t.Setenv("NILLSEC_PASSWORD", editTestPassword)
if err := cmdExec([]string{"--", script}); err != nil {
t.Fatalf("cmdExec: %v", err)
}
raw, err := os.ReadFile(outFile)
if err != nil {
t.Fatalf("read out file: %v", err)
}
got := strings.TrimRight(string(raw), "\n\r")
if got != "hunter2" {
t.Errorf("MY_SECRET = %q; want %q", got, "hunter2")
}
}
// TestCmdExecWithoutDoubleDash verifies that the "--" separator is optional.
func TestCmdExecWithoutDoubleDash(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script subprocess not supported on Windows")
}
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, map[string]string{"token": "secret-value"})
outFile := filepath.Join(dir, "out.txt")
script := filepath.Join(dir, "check-env.sh")
scriptContent := "#!/bin/sh\necho \"$TOKEN\" > \"" + outFile + "\"\n"
if err := os.WriteFile(script, []byte(scriptContent), 0700); err != nil {
t.Fatalf("write script: %v", err)
}
t.Setenv("NILLSEC_VAULT", vaultFile)
t.Setenv("NILLSEC_PASSWORD", editTestPassword)
// No "--" separator.
if err := cmdExec([]string{script}); err != nil {
t.Fatalf("cmdExec: %v", err)
}
raw, err := os.ReadFile(outFile)
if err != nil {
t.Fatalf("read out file: %v", err)
}
got := strings.TrimRight(string(raw), "\n\r")
if got != "secret-value" {
t.Errorf("TOKEN = %q; want %q", got, "secret-value")
}
}
// TestCmdExecDoubleDashPassthrough verifies that a "--" that is NOT the first
// argument is passed through to the child command unchanged. For example:
//
// nillsec exec some-tool -- --flag
//
// should invoke some-tool with the arguments ["--", "--flag"], not strip the
// "--" and try to run "--flag" as the command.
func TestCmdExecDoubleDashPassthrough(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script subprocess not supported on Windows")
}
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, nil)
// Script that writes its first argument to a file so we can verify it
// received "--" intact.
outFile := filepath.Join(dir, "out.txt")
script := filepath.Join(dir, "record-arg.sh")
scriptContent := "#!/bin/sh\necho \"$1\" > \"" + outFile + "\"\n"
if err := os.WriteFile(script, []byte(scriptContent), 0700); err != nil {
t.Fatalf("write script: %v", err)
}
t.Setenv("NILLSEC_VAULT", vaultFile)
t.Setenv("NILLSEC_PASSWORD", editTestPassword)
// Pass "--" as an argument to the script, not as a separator.
if err := cmdExec([]string{script, "--", "--flag"}); err != nil {
t.Fatalf("cmdExec: %v", err)
}
raw, err := os.ReadFile(outFile)
if err != nil {
t.Fatalf("read out file: %v", err)
}
got := strings.TrimRight(string(raw), "\n\r")
if got != "--" {
t.Errorf("first arg = %q; want %q (-- should not be consumed when not the first arg)", got, "--")
}
}
// TestCmdExecNoArgs verifies that an error is returned when no command is given.
func TestCmdExecNoArgs(t *testing.T) {
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, nil)
t.Setenv("NILLSEC_VAULT", vaultFile)
t.Setenv("NILLSEC_PASSWORD", editTestPassword)
if err := cmdExec([]string{"--"}); err == nil {
t.Fatal("cmdExec with no command: expected error, got nil")
}
if err := cmdExec([]string{}); err == nil {
t.Fatal("cmdExec with empty args: expected error, got nil")
}
}
// TestCmdExecExitCodePropagation verifies that a non-zero exit from the child
// process causes osExitFn to be called with the matching code.
func TestCmdExecExitCodePropagation(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script subprocess not supported on Windows")
}
dir := t.TempDir()
vaultFile := filepath.Join(dir, "test.vault")
makeTestVault(t, vaultFile, nil)
// Script that exits with code 42.
script := filepath.Join(dir, "fail.sh")
if err := os.WriteFile(script, []byte("#!/bin/sh\nexit 42\n"), 0700); err != nil {
t.Fatalf("write script: %v", err)
}
t.Setenv("NILLSEC_VAULT", vaultFile)
t.Setenv("NILLSEC_PASSWORD", editTestPassword)
var capturedCode int
origOsExitFn := osExitFn
t.Cleanup(func() { osExitFn = origOsExitFn })
osExitFn = func(code int) { capturedCode = code }
if err := cmdExec([]string{"--", script}); err != nil {
t.Fatalf("cmdExec: unexpected error: %v", err)
}
if capturedCode != 42 {
t.Errorf("exit code = %d; want 42", capturedCode)
}
}