Repository navigation
Expand file tree
/
Copy pathinstall_linux_test.go
More file actions
1336 lines (1262 loc) · 54.7 KB
/
Copy pathinstall_linux_test.go
File metadata and controls
1336 lines (1262 loc) · 54.7 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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package nodkey
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"io/fs"
"maps"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"syscall"
"testing"
"time"
)
// The tests of install.sh run it with /bin/sh against fakes, and never use
// the network:
//
// - a fake curl, first in PATH, serves https://HOST/PATH from the file
// web/HOST/PATH of the test, and writes down each call;
// - a fake uname says which system and CPU this is;
// - a fake gh, given with --gh, writes down its arguments and its
// environment, and says that the attestation is valid or not.
//
// After a run that fails, the bin directory must be as before, and the
// temporary directory of the script must be gone.
//
// As root, the script runs only the programs of the system, so the fakes
// in PATH would not count, and curl would use the network. So these tests
// do not run as root. The checks that only root makes are tested with the
// functions of the script (TestInstallChecksAsRoot).
// Paths on the fake GitHub, without "https://".
const (
latestPath = "api.github.com/repos/code6x/nodkey/releases/latest"
releasePath = "github.com/code6x/nodkey/releases/download/v" // and VERSION/FILE
ghPath = "github.com/cli/cli/releases/download/v" // and VERSION/FILE
)
// certIdentity is the identity of the release workflow (docs/releasing.md).
const certIdentity = "https://github.com/code6x/nodkey/.github/workflows/release.yml@refs/heads/main"
// tokenVars are the variables that must not reach gh.
var tokenVars = []string{"GH_TOKEN", "GITHUB_TOKEN", "GH_HOST", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"}
// unsafeVars are variables that change what the programs of the script do.
// The script removes them (clean_env). LD_PRELOAD and LD_AUDIT are on the
// list of the script too, but the dynamic loader would complain about the
// made-up values here, so the tests leave them out.
var unsafeVars = []string{"GZIP", "POSIXLY_CORRECT", "CURL_HOME", "CURL_CA_BUNDLE", "SSL_CERT_FILE", "SSL_CERT_DIR",
"SSLKEYLOGFILE", "OPENSSL_CONF", "OPENSSL_MODULES", "OPENSSL_ENGINES", "LD_LIBRARY_PATH", "GCONV_PATH", "CDPATH"}
// The size limits of the downloads in install.sh.
const (
maxSmall = "1048576" // the answer of the API, SHA256SUMS, the bundle
maxBig = "67108864" // the tarballs
)
const fakeCurl = `#!/bin/sh
# A fake curl. It serves https://HOST/PATH from $FAKE_WEB/HOST/PATH into the
# file of --output, at most --max-filesize bytes. It writes down its
# arguments: one call, one line.
printf '%s\n' "$*" >>"$FAKE_LOGS/curl"
out=
max=
url=
while [ "$#" -gt 0 ]; do
case $1 in
--output)
out=$2
shift
;;
--max-filesize)
max=$2
shift
;;
esac
url=$1
shift
done
case $url in
https://*) ;;
*)
echo "fake curl: not HTTPS: $url" >&2
exit 1
;;
esac
file=$FAKE_WEB/${url#https://}
if [ ! -f "$file" ]; then
echo "curl: (22) The requested URL returned error: 404" >&2
exit 22
fi
if [ -n "$max" ] && [ "$(wc -c <"$file")" -gt "$max" ]; then
echo "curl: (63) Maximum file size exceeded" >&2
exit 63
fi
cp "$file" "$out"
`
const fakeUname = `#!/bin/sh
# A fake uname: the system and the CPU of the test.
case $1 in
-s) echo "${FAKE_UNAME_S:-Linux}" ;;
-m) echo "${FAKE_UNAME_M:-x86_64}" ;;
*) exit 1 ;;
esac
`
const fakeGh = `#!/bin/sh
# A fake gh. It writes down each call, one a line, its own path, and the
# environment of each kind of call. For --version, it prints the version
# $FAKE_GH_VERSION, or exits with $FAKE_GH_VERSION_EXIT. For attestation
# verify, it writes down its arguments, keeps a copy of the file and of the
# bundle to check, and exits with $FAKE_GH_EXIT. With $FAKE_GH_WAIT, it
# makes that file instead, and waits.
printf '%s\n' "$*" >>"$FAKE_LOGS/gh"
printf '%s\n' "$0" >"$FAKE_LOGS/gh-path"
env >"$FAKE_LOGS/gh-env-$1"
if [ "$1" = --version ]; then
if [ -n "${FAKE_GH_VERSION_EXIT:-}" ]; then
exit "$FAKE_GH_VERSION_EXIT"
fi
echo "gh version ${FAKE_GH_VERSION:-2.102.0} (2026-09-30)"
echo "https://github.com/cli/cli/releases/tag/v${FAKE_GH_VERSION:-2.102.0}"
exit 0
fi
printf '%s\n' "$@" >"$FAKE_LOGS/gh-args"
cp "$3" "$FAKE_LOGS/gh-file" || exit 2
cp "$5" "$FAKE_LOGS/gh-bundle" || exit 2
if [ -n "${FAKE_GH_WAIT:-}" ]; then
: >"$FAKE_GH_WAIT"
exec sleep 60
fi
exit "${FAKE_GH_EXIT:-0}"
`
// fakeNodkey returns a fake nodkey. "nodkey version" prints the lines.
// The note tells copies apart, such as the CPU of a tarball. Each run
// writes the note to $FAKE_LOGS/nodkey-runs, so a test can see which
// copies ran.
func fakeNodkey(note string, lines ...string) []byte {
return fmt.Appendf(nil, "#!/bin/sh\n# A fake nodkey (%s).\necho '%s' >>\"$FAKE_LOGS/nodkey-runs\"\n"+
"if [ \"$1\" = version ]; then\n\tprintf '%%s\\n' '%s'\nfi\n",
note, note, strings.Join(lines, "' '"))
}
// failingNodkey is a fake nodkey that does not run.
var failingNodkey = []byte("#!/bin/sh\necho 'cannot run' >&2\nexit 1\n")
// says returns the fake nodkey of each CPU of a release, for
// installer.release.
func says(lines ...string) func(arch string) []byte {
return func(arch string) []byte { return fakeNodkey(arch, lines...) }
}
// tarFile is a file in a tarball of tarGz.
type tarFile struct {
name string
mode int64
data []byte
}
// tarGz returns a tar.gz file with these files.
func tarGz(t *testing.T, files ...tarFile) []byte {
t.Helper()
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
tw := tar.NewWriter(gz)
for _, f := range files {
hdr := &tar.Header{Name: f.name, Mode: f.mode, Size: int64(len(f.data)), ModTime: time.Unix(1_760_000_000, 0)}
if err := tw.WriteHeader(hdr); err != nil {
t.Fatal(err)
}
if _, err := tw.Write(f.data); err != nil {
t.Fatal(err)
}
}
if err := tw.Close(); err != nil {
t.Fatal(err)
}
if err := gz.Close(); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
// installer runs install.sh against fakes.
type installer struct {
t *testing.T
dir string // the working directory of the script
script string // the path of the script
web string // the files of the fake GitHub
bin string // the directory of --bin-dir
tmp string // TMPDIR of the script: it must be empty after each run
logs string // what the fake programs write down
fakes string // the fake curl and uname, first in PATH
gh string // the fake gh, for --gh
binArg string // the value of --bin-dir, if it is not bin
env []string // more environment for the script
}
func newInstaller(t *testing.T) *installer {
t.Helper()
if os.Geteuid() == 0 {
t.Skip("as root, install.sh runs only the programs of the system, not the fakes of the test")
}
for _, name := range []string{"sed", "tar", "gzip", "sha256sum", "install", "mktemp", "id", "stat", "cp", "env", "wc", "sleep"} {
if _, err := exec.LookPath(name); err != nil {
skipOrFail(t, "%s is not installed", name)
}
}
script, err := filepath.Abs("install.sh")
if err != nil {
t.Fatal(err)
}
// The script refuses a directory that group or others can write to.
// Under a umask such as 002, t.TempDir is one.
dir := privateDir(t)
in := &installer{
t: t,
dir: dir,
script: script,
web: filepath.Join(dir, "web"),
bin: filepath.Join(dir, "bin"),
tmp: filepath.Join(dir, "tmp"),
logs: filepath.Join(dir, "logs"),
fakes: filepath.Join(dir, "fakes"),
gh: filepath.Join(dir, "gh"),
}
for _, d := range []string{in.web, in.bin, in.tmp, in.logs, in.fakes} {
mkdir(t, d, 0o700)
}
writeFile(t, filepath.Join(in.fakes, "curl"), []byte(fakeCurl), 0o700)
writeFile(t, filepath.Join(in.fakes, "uname"), []byte(fakeUname), 0o700)
writeFile(t, in.gh, []byte(fakeGh), 0o700)
if exec.CommandContext(t.Context(), filepath.Join(in.fakes, "uname"), "-s").Run() != nil { //nolint:gosec // G204: a program that the test wrote.
skipOrFail(t, "a program in the temporary directory %s cannot run", dir)
}
return in
}
// privateDir returns a new temporary directory with mode 0700, by its path
// without links: the script prints such paths.
func privateDir(t *testing.T) string {
t.Helper()
dir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
if err := os.Chmod(dir, 0o700); err != nil { //nolint:gosec // G302: a directory, private to its owner.
t.Fatal(err)
}
return dir
}
// mkdir makes the directory path with exactly mode.
func mkdir(t *testing.T, path string, mode os.FileMode) {
t.Helper()
if err := os.Mkdir(path, 0o700); err != nil {
t.Fatal(err)
}
if err := os.Chmod(path, mode); err != nil {
t.Fatal(err)
}
}
// latest makes the answer of the fake GitHub API for the newest release,
// in the form of the real one.
func (in *installer) latest(tag string) {
in.serve(latestPath, fmt.Appendf(nil, "{\n \"url\": \"https://api.github.com/repos/code6x/nodkey/releases/1\",\n"+
" \"tag_name\": %q,\n \"name\": %q,\n \"draft\": false\n}\n", tag, tag))
}
// release puts a release on the fake GitHub: for each CPU a tarball with
// nodkey, LICENSE and README.md, and SHA256SUMS and the bundle. nodkey
// returns the file nodkey of each CPU. release returns the tarballs.
func (in *installer) release(version string, nodkey func(arch string) []byte) map[string][]byte {
tarballs := map[string][]byte{}
var sums strings.Builder
for _, arch := range []string{"amd64", "arm64"} {
name := "nodkey_" + version + "_linux_" + arch + ".tar.gz"
tarballs[arch] = tarGz(in.t,
tarFile{"nodkey", 0o755, nodkey(arch)},
tarFile{"LICENSE", 0o644, []byte("a made-up license\n")},
tarFile{"README.md", 0o644, []byte("# a made-up readme\n")})
in.serve(releasePath+version+"/"+name, tarballs[arch])
fmt.Fprintf(&sums, "%x %s\n", sha256.Sum256(tarballs[arch]), name)
}
in.serve(releasePath+version+"/SHA256SUMS", []byte(sums.String()))
in.serve(releasePath+version+"/nodkey_"+version+".sigstore.json", []byte(bundle(version)))
return tarballs
}
// bundle is the made-up bundle of a release.
func bundle(version string) string {
return `{"mediaType": "application/vnd.dev.sigstore.bundle.v0.3+json", "release": "` + version + `"}` + "\n"
}
// ghRelease puts a tarball of gh 2.102.0 for amd64 on the fake GitHub,
// with the fake gh in it. It returns the SHA-256 of the tarball, in hex.
func (in *installer) ghRelease() string {
data := tarGz(in.t,
tarFile{"gh_2.102.0_linux_amd64/LICENSE", 0o644, []byte("a made-up license\n")},
tarFile{"gh_2.102.0_linux_amd64/bin/gh", 0o755, []byte(fakeGh)})
in.serve(ghPath+"2.102.0/gh_2.102.0_linux_amd64.tar.gz", data)
return fmt.Sprintf("%x", sha256.Sum256(data))
}
// serve puts a file at https://path on the fake GitHub.
func (in *installer) serve(path string, data []byte) {
in.t.Helper()
file := filepath.Join(in.web, filepath.FromSlash(path))
if err := os.MkdirAll(filepath.Dir(file), 0o700); err != nil {
in.t.Fatal(err)
}
writeFile(in.t, file, data, 0o600)
}
// unserve removes the file at https://path from the fake GitHub.
func (in *installer) unserve(path string) {
in.t.Helper()
if err := os.Remove(filepath.Join(in.web, filepath.FromSlash(path))); err != nil {
in.t.Fatal(err)
}
}
// installed makes data the installed nodkey.
func (in *installer) installed(data []byte) {
writeFile(in.t, filepath.Join(in.bin, "nodkey"), data, 0o755)
}
// result is the end of a run of the script.
type result struct {
code int
stdout, stderr string
}
// run runs the script with the arguments.
func (in *installer) run(args ...string) result {
in.t.Helper()
return runCmd(in.t, in.command(args...))
}
// runCmd runs cmd, and returns its exit code and output.
func runCmd(t *testing.T, cmd *exec.Cmd) result {
t.Helper()
var stdout, stderr bytes.Buffer
cmd.Stdout, cmd.Stderr = &stdout, &stderr
err := cmd.Run()
var exit *exec.ExitError
if err != nil && !errors.As(err, &exit) {
t.Fatalf("cannot run %s: %v", cmd.Path, err)
}
return result{cmd.ProcessState.ExitCode(), stdout.String(), stderr.String()}
}
// command returns the command that runs the script with --bin-dir of the
// test and then args, with stdin from /dev/null. A --bin-dir in args
// comes later, so it counts.
func (in *installer) command(args ...string) *exec.Cmd {
bin := in.bin
if in.binArg != "" {
bin = in.binArg
}
cmd := exec.CommandContext(in.t.Context(), "/bin/sh", append([]string{in.script, "--bin-dir", bin}, args...)...) //nolint:gosec // G204: the test runs install.sh with its own arguments.
cmd.Dir = in.dir
cmd.Env = append([]string{
"PATH=" + in.fakes + string(os.PathListSeparator) + os.Getenv("PATH"),
"HOME=" + in.dir,
"TMPDIR=" + in.tmp,
"FAKE_WEB=" + in.web,
"FAKE_LOGS=" + in.logs,
}, in.env...)
return cmd
}
// files returns the mode and the content of each file in dir, by name: a
// link has its target, and a directory or another kind of file has only
// its mode.
func files(t *testing.T, dir string) map[string]string {
t.Helper()
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
got := map[string]string{}
for _, e := range entries {
info, err := e.Info()
if err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, e.Name())
got[e.Name()] = info.Mode().String()
switch {
case info.Mode().IsRegular():
got[e.Name()] += " " + string(readFile(t, path))
case info.Mode()&fs.ModeSymlink != 0:
target, err := os.Readlink(path)
if err != nil {
t.Fatal(err)
}
got[e.Name()] += " -> " + target
}
}
return got
}
// checkTmpGone checks that the temporary directory of the script is gone.
func (in *installer) checkTmpGone() {
in.t.Helper()
if left := files(in.t, in.tmp); len(left) != 0 {
in.t.Errorf("the temporary directory is still there: %v", slices.Sorted(maps.Keys(left)))
}
}
// checkFailed checks a run that must fail with code and a last line that
// holds want, and that it changed nothing in the bin directory.
func (in *installer) checkFailed(r result, code int, want string, before map[string]string) {
in.t.Helper()
end := " (exit " + strconv.Itoa(code) + ")\n"
if code == 1 {
end = "; nothing was installed" + end
}
last := lastLine(r.stderr)
if r.code != code || !strings.HasPrefix(last, "nodkey: ") || !strings.Contains(last, want) || !strings.HasSuffix(last, end) {
in.t.Errorf("exit code %d, last line %q; want %d and a line with %q and %q\nstdout:\n%s\nstderr:\n%s",
r.code, last, code, want, end, r.stdout, r.stderr)
}
if after := files(in.t, in.bin); !maps.Equal(after, before) {
in.t.Errorf("the bin directory changed: %v, before %v", slices.Sorted(maps.Keys(after)), slices.Sorted(maps.Keys(before)))
}
in.checkTmpGone()
}
// curlCalls returns the arguments of each call of curl.
func (in *installer) curlCalls() [][]string {
in.t.Helper()
var calls [][]string
for _, line := range in.log("curl") {
calls = append(calls, strings.Fields(line))
}
return calls
}
// urls returns the URL of each call of curl, in order.
func (in *installer) urls() []string {
in.t.Helper()
var urls []string
for _, call := range in.curlCalls() {
urls = append(urls, call[len(call)-1])
}
return urls
}
// log returns the lines that a fake wrote to the log name, or none.
func (in *installer) log(name string) []string {
in.t.Helper()
data, err := os.ReadFile(filepath.Join(in.logs, name)) //nolint:gosec // G304: a file in the test's own directory.
if errors.Is(err, fs.ErrNotExist) {
return nil
}
if err != nil {
in.t.Fatal(err)
}
return strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
}
// ghChecked reports whether gh attestation verify ran.
func (in *installer) ghChecked() bool {
return in.log("gh-args") != nil
}
// releaseURLs are the URLs of the files of a release, for amd64.
func releaseURLs(version string) []string {
base := "https://" + releasePath + version + "/"
return []string{base + "nodkey_" + version + "_linux_amd64.tar.gz", base + "SHA256SUMS", base + "nodkey_" + version + ".sigstore.json"}
}
const latestURL = "https://" + latestPath
// TestInstall installs a release where no nodkey is, and checks how the
// script ran curl and gh.
func TestInstall(t *testing.T) {
in := newInstaller(t)
in.latest("v0.2.0")
in.release("0.2.0", says("nodkey 0.2.0"))
// Tokens, a host and other places for the config of gh: none of them
// may reach gh.
token := "made-up-token-" + rand.Text()
for _, name := range tokenVars {
in.env = append(in.env, name+"="+token)
}
in.env = append(in.env, "GH_CONFIG_DIR=/nonexistent/gh", "XDG_CONFIG_HOME=/nonexistent/config",
"XDG_CACHE_HOME=/nonexistent/cache", "XDG_DATA_HOME=/nonexistent/data", "XDG_STATE_HOME=/nonexistent/state")
// Variables that change what the programs do: the script removes
// them. Through TAR_OPTIONS, tar would run a command.
ran := filepath.Join(in.dir, "tar-ran-a-command")
in.env = append(in.env, "TAR_OPTIONS=--checkpoint=1 --checkpoint-action=exec=touch "+ran, "LC_ALL=de_DE.UTF-8")
for _, name := range unsafeVars {
in.env = append(in.env, name+"=/nonexistent/made-up")
}
r := in.run("--gh", in.gh)
if r.code != 0 {
t.Fatalf("exit code %d\nstdout:\n%s\nstderr:\n%s", r.code, r.stdout, r.stderr)
}
// Only nodkey of amd64 is in the bin directory, with mode 0755.
want := map[string]string{"nodkey": "-rwxr-xr-x " + string(fakeNodkey("amd64", "nodkey 0.2.0"))}
if got := files(t, in.bin); !maps.Equal(got, want) {
t.Errorf("the bin directory holds %q, want %q", got, want)
}
in.checkTmpGone()
for _, s := range []string{"Installing nodkey 0.2.0 as " + in.bin + "/nodkey.", "version says: nodkey 0.2.0",
"systemctl restart nodkey", "A restart ends all grants", "each nodkey ssh-agent"} {
if !strings.Contains(r.stdout, s) {
t.Errorf("stdout does not say %q:\n%s", s, r.stdout)
}
}
if _, err := os.Lstat(ran); err == nil {
t.Error("tar ran the command of TAR_OPTIONS")
}
// curl: the newest release, then the files of the release, each with
// no .curlrc, over HTTPS only, with TLS 1.2 or newer, failing on an
// HTTP error, with retries, a time limit and a size limit.
wantURLs := append([]string{latestURL}, releaseURLs("0.2.0")...)
if got := in.urls(); !slices.Equal(got, wantURLs) {
t.Errorf("curl got the URLs\n%q\nwant\n%q", got, wantURLs)
}
for i, call := range in.curlCalls() {
if call[0] != "-q" {
t.Errorf("a call of curl does not start with -q, so curl reads .curlrc: %q", call)
}
limit := maxSmall
if strings.HasSuffix(call[len(call)-1], ".tar.gz") {
limit = maxBig
}
for _, want := range [][]string{{"--proto", "=https"}, {"--proto-redir", "=https"}, {"--tlsv1.2"}, {"--fail"},
{"--retry", "3"}, {"--max-time", "600"}, {"--max-filesize", limit}} {
if !slices.ContainsFunc(windows(call, len(want)), func(w []string) bool { return slices.Equal(w, want) }) {
t.Errorf("call %d of curl has no %q: %q", i, want, call)
}
}
}
// gh: its version, then the check with the identity of
// docs/releasing.md, of the file that the script downloaded.
if got, want := in.log("gh"), []string{"--version", "attestation verify"}; len(got) != 2 || got[0] != want[0] || !strings.HasPrefix(got[1], want[1]) {
t.Fatalf("calls of gh: %q, want --version and then attestation verify", got)
}
args := in.log("gh-args")
if len(args) < 3 {
t.Fatalf("gh got %q", args)
}
tmp := filepath.Dir(args[2]) // the temporary directory of the script
if filepath.Dir(tmp) != in.tmp || !strings.HasPrefix(filepath.Base(tmp), "nodkey-install.") {
t.Errorf("gh checked %s, not a file in a new directory in TMPDIR %s", args[2], in.tmp)
}
wantArgs := []string{"attestation", "verify", filepath.Join(tmp, "nodkey_0.2.0_linux_amd64.tar.gz"),
"--bundle", filepath.Join(tmp, "nodkey_0.2.0.sigstore.json"),
"--repo", "code6x/nodkey", "--cert-identity", certIdentity, "--deny-self-hosted-runners"}
if !slices.Equal(args, wantArgs) {
t.Errorf("gh got the arguments\n%q\nwant\n%q", args, wantArgs)
}
served := readFile(t, filepath.Join(in.web, releasePath+"0.2.0", "nodkey_0.2.0_linux_amd64.tar.gz"))
if checked := readFile(t, filepath.Join(in.logs, "gh-file")); !bytes.Equal(checked, served) {
t.Error("gh checked another file than the tarball of the release")
}
if checked := readFile(t, filepath.Join(in.logs, "gh-bundle")); string(checked) != bundle("0.2.0") {
t.Errorf("gh checked with the bundle %q, want %q", checked, bundle("0.2.0"))
}
// The environment of gh, for both calls: no token and no host, its
// home, config and XDG directories in the temporary directory, no
// update notices, prompts or telemetry, LC_ALL=C, and none of the
// unsafe variables.
for _, call := range []string{"--version", "attestation"} {
env := readEnv(t, filepath.Join(in.logs, "gh-env-"+call))
for _, name := range append(slices.Clone(tokenVars), append([]string{"TAR_OPTIONS"}, unsafeVars...)...) {
if v, ok := env[name]; ok {
t.Errorf("gh %s got %s (%d bytes)", call, name, len(v))
}
}
for name, value := range env {
if strings.Contains(value, token) {
t.Errorf("gh %s got the token in %s", call, name)
}
}
if env["HOME"] != filepath.Join(tmp, "home") {
t.Errorf("gh %s got HOME=%q, want %q", call, env["HOME"], filepath.Join(tmp, "home"))
}
for _, name := range []string{"GH_CONFIG_DIR", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME"} {
if !strings.HasPrefix(env[name], tmp+"/") {
t.Errorf("gh %s got %s=%q, want a directory in %s", call, name, env[name], tmp)
}
}
for name, want := range map[string]string{"GH_NO_UPDATE_NOTIFIER": "1", "GH_NO_EXTENSION_UPDATE_NOTIFIER": "1",
"GH_PROMPT_DISABLED": "1", "GH_TELEMETRY": "false", "LC_ALL": "C"} {
if env[name] != want {
t.Errorf("gh %s got %s=%q, want %q", call, name, env[name], want)
}
}
}
}
// TestInstallReplaces replaces an installed nodkey: an older version, one
// whose version is not known, the same one with --reinstall, and with
// --version an older one. It also installs with paths that the script
// takes as safe.
func TestInstallReplaces(t *testing.T) {
all := append([]string{latestURL}, releaseURLs("0.2.0")...)
for _, tt := range []struct {
name string
installed []byte // the nodkey that is installed before
setup func(in *installer) // more changes before the run
args []string // after --gh
arch string // the CPU of the tarball that must be installed
say string // a part of stdout
urls []string // what curl gets
}{
{name: "an older version", installed: fakeNodkey("installed", "nodkey 0.1.0"), arch: "amd64",
say: "Updating BIN/nodkey from nodkey 0.1.0 to nodkey 0.2.0.", urls: all},
{name: "a build from the source", installed: fakeNodkey("installed", "nodkey dev"), arch: "amd64",
say: "BIN/nodkey has an unknown version. nodkey 0.2.0 will replace it.", urls: all},
{name: "a build of a commit", installed: fakeNodkey("installed", "nodkey 1a2b3c4"), arch: "amd64",
say: "has an unknown version", urls: all},
{name: "a file that does not run", installed: failingNodkey, arch: "amd64", say: "has an unknown version", urls: all},
{name: "the same version, with --reinstall", installed: fakeNodkey("installed", "nodkey 0.2.0"),
args: []string{"--reinstall"}, arch: "amd64",
say: "Installing nodkey 0.2.0 again as BIN/nodkey, as --reinstall asks.", urls: all},
{name: "a newer version, with --version", installed: fakeNodkey("installed", "nodkey 0.3.0"),
args: []string{"--version", "0.2.0"}, arch: "amd64",
say: "Replacing nodkey 0.3.0 with the older nodkey 0.2.0, as --version asks.", urls: releaseURLs("0.2.0")},
{name: "on arm64", setup: env("FAKE_UNAME_M=aarch64"), arch: "arm64", say: "Installing nodkey 0.2.0",
urls: []string{latestURL, "https://" + releasePath + "0.2.0/nodkey_0.2.0_linux_arm64.tar.gz",
"https://" + releasePath + "0.2.0/SHA256SUMS", "https://" + releasePath + "0.2.0/nodkey_0.2.0.sigstore.json"}},
{name: "on amd64, when uname -m says amd64", setup: env("FAKE_UNAME_M=amd64"), arch: "amd64",
say: "Installing nodkey 0.2.0", urls: all},
{name: "with gh 2.93.0, the oldest that counts", setup: env("FAKE_GH_VERSION=2.93.0"), arch: "amd64",
say: "with gh 2.93.0.", urls: all},
// A directory with the sticky bit, as /tmp, may let others write.
{name: "a TMPDIR with the sticky bit", setup: func(in *installer) {
in.tmp = filepath.Join(in.dir, "shared-tmp")
mkdir(in.t, in.tmp, 0o777|os.ModeSticky)
}, arch: "amd64", say: "Installing nodkey 0.2.0", urls: all},
{name: "a bin directory in a directory with the sticky bit", setup: func(in *installer) {
mkdir(in.t, filepath.Join(in.dir, "shared"), 0o777|os.ModeSticky)
in.bin = filepath.Join(in.dir, "shared", "bin")
mkdir(in.t, in.bin, 0o755)
}, arch: "amd64", say: "Installing nodkey 0.2.0", urls: all},
// A link in the path of the bin directory is followed once, and the
// script uses the real path from then on.
{name: "a bin directory behind a link", setup: func(in *installer) {
in.binArg = filepath.Join(in.dir, "bin-link")
if err := os.Symlink(in.bin, in.binArg); err != nil {
in.t.Fatal(err)
}
}, arch: "amd64", say: "Installing nodkey 0.2.0 as BIN/nodkey.", urls: all},
} {
t.Run(tt.name, func(t *testing.T) {
in := newInstaller(t)
in.latest("v0.2.0")
in.release("0.2.0", says("nodkey 0.2.0"))
if tt.installed != nil {
in.installed(tt.installed)
}
if tt.setup != nil {
tt.setup(in)
}
r := in.run(append([]string{"--gh", in.gh}, tt.args...)...)
if r.code != 0 {
t.Fatalf("exit code %d\nstdout:\n%s\nstderr:\n%s", r.code, r.stdout, r.stderr)
}
want := map[string]string{"nodkey": "-rwxr-xr-x " + string(fakeNodkey(tt.arch, "nodkey 0.2.0"))}
if got := files(t, in.bin); !maps.Equal(got, want) {
t.Errorf("the bin directory holds %q, want %q", got, want)
}
if say := strings.ReplaceAll(tt.say, "BIN", in.bin); !strings.Contains(r.stdout, say) {
t.Errorf("stdout does not say %q:\n%s", say, r.stdout)
}
if got := in.urls(); !slices.Equal(got, tt.urls) {
t.Errorf("curl got the URLs\n%q\nwant\n%q", got, tt.urls)
}
in.checkTmpGone()
})
}
}
// TestInstallNothingToDo: the version is installed already, or the
// installed one is newer and --version does not ask for the older one.
// The script exits with 0, downloads no release and changes nothing. It
// says that it did not check the installed file.
func TestInstallNothingToDo(t *testing.T) {
for _, tt := range []struct {
name string
installed string
args []string
say string
urls []string
}{
{"the newest release", "0.2.0", nil, "BIN/nodkey says that it is nodkey 0.2.0 already. Nothing to do.\n" +
"This did not check the installed file. To replace it with a checked copy, run this again with --reinstall.",
[]string{latestURL}},
{"the version of --version", "0.2.0", []string{"--version", "0.2.0"}, "says that it is nodkey 0.2.0 already", nil},
{"a newer version", "0.3.0", nil,
"BIN/nodkey says that it is nodkey 0.3.0, which is newer than 0.2.0, the newest release. Nothing to do.\n" +
"This did not check the installed file. To install 0.2.0 anyway, run this again with --version 0.2.0.",
[]string{latestURL}},
{"a newer version in the second number", "0.10.0", nil, "which is newer than 0.2.0", []string{latestURL}},
{"a newer version in the first number", "1.0.0", nil, "which is newer than 0.2.0", []string{latestURL}},
{"a newer version, with --reinstall", "0.3.0", []string{"--reinstall"}, "which is newer than 0.2.0", []string{latestURL}},
} {
t.Run(tt.name, func(t *testing.T) {
in := newInstaller(t)
in.latest("v0.2.0")
in.release("0.2.0", says("nodkey 0.2.0"))
in.installed(fakeNodkey("installed", "nodkey "+tt.installed))
before := files(t, in.bin)
r := in.run(append([]string{"--gh", in.gh}, tt.args...)...)
if r.code != 0 || r.stderr != "" {
t.Errorf("exit code %d, stderr %q; want 0 and nothing", r.code, r.stderr)
}
if say := strings.ReplaceAll(tt.say, "BIN", in.bin); !strings.Contains(r.stdout, say) {
t.Errorf("stdout does not say %q:\n%s", say, r.stdout)
}
if got := in.urls(); !slices.Equal(got, tt.urls) {
t.Errorf("curl got the URLs %q, want %q", got, tt.urls)
}
if in.ghChecked() {
t.Error("gh checked an attestation")
}
if after := files(t, in.bin); !maps.Equal(after, before) {
t.Errorf("the bin directory changed")
}
in.checkTmpGone()
})
}
}
// TestInstallDenies: each failed step stops the script with exit code 1
// and a last line that says why. Nothing is installed: the old nodkey
// stays, and no new file is left next to it.
func TestInstallDenies(t *testing.T) {
const tarball = "nodkey_0.2.0_linux_amd64.tar.gz"
sums := func(lines ...string) func(in *installer) {
return func(in *installer) {
in.serve(releasePath+"0.2.0/SHA256SUMS", []byte(strings.Join(lines, "")))
}
}
sumOf := func(in *installer, arch string) string {
data := readFile(in.t, filepath.Join(in.web, releasePath+"0.2.0", "nodkey_0.2.0_linux_"+arch+".tar.gz"))
return fmt.Sprintf("%x", sha256.Sum256(data))
}
for _, tt := range []struct {
name string
setup func(in *installer) // after the newest release 0.2.0 is on the fake GitHub
args []string // nil: --gh with the fake gh
want string // a part of the last line
checked bool // whether gh attestation verify ran
noCurl bool // whether the script must stop before any download
noRun bool // whether the script must run no nodkey and no gh
}{
{name: "another system", setup: env("FAKE_UNAME_S=Darwin"), noCurl: true, want: "nodkey runs on Linux only, and this is Darwin"},
{name: "another CPU", setup: env("FAKE_UNAME_M=riscv64"), noCurl: true, want: "amd64 and arm64 only, and this machine is riscv64"},
// The paths that the script runs programs from and writes to.
{name: "no bin directory", args: []string{"--bin-dir", "/nonexistent/bin"}, noCurl: true, noRun: true,
want: "/nonexistent/bin is not a directory"},
{name: "a bin directory that cannot be written", setup: func(in *installer) { chmod(in.t, in.bin, 0o500) },
noCurl: true, noRun: true, want: "cannot write to BIN; run this as root"},
{name: "a bin directory that others can write to", setup: func(in *installer) { chmod(in.t, in.bin, 0o777) },
noCurl: true, noRun: true, want: "group or others can write to BIN; only root or user"},
{name: "a bin directory that its group can write to", setup: func(in *installer) { chmod(in.t, in.bin, 0o770) },
noCurl: true, noRun: true, want: "group or others can write to BIN;"},
{name: "a bin directory with the sticky bit", setup: func(in *installer) { chmod(in.t, in.bin, 0o777|os.ModeSticky) },
noCurl: true, noRun: true, want: "group or others can write to BIN;"},
{name: "a bin directory in a directory that others can write to", setup: func(in *installer) {
open := filepath.Join(in.dir, "open")
mkdir(in.t, open, 0o777)
in.bin = filepath.Join(open, "bin")
mkdir(in.t, in.bin, 0o700)
in.installed(fakeNodkey("installed", "nodkey 0.1.0"))
}, noCurl: true, noRun: true, want: "group or others can write to DIR/open;"},
{name: "an old file that others can write to", setup: func(in *installer) { chmod(in.t, filepath.Join(in.bin, "nodkey"), 0o777) },
noCurl: true, noRun: true, want: "group or others can write to BIN/nodkey;"},
{name: "an old file that is a link", setup: func(in *installer) {
mkdir(in.t, filepath.Join(in.dir, "elsewhere"), 0o700)
writeFile(in.t, filepath.Join(in.dir, "elsewhere", "nodkey"), fakeNodkey("elsewhere", "nodkey 0.1.0"), 0o755)
replace(in.t, filepath.Join(in.bin, "nodkey"), func(path string) error {
return os.Symlink(filepath.Join(in.dir, "elsewhere", "nodkey"), path)
})
}, noCurl: true, noRun: true, want: "BIN/nodkey is a link; the script replaces only a file"},
{name: "an old file that is a directory", setup: func(in *installer) {
replace(in.t, filepath.Join(in.bin, "nodkey"), func(path string) error { return os.Mkdir(path, 0o700) })
}, noCurl: true, noRun: true, want: "BIN/nodkey is not a file"},
{name: "an old file that is a pipe", setup: func(in *installer) {
replace(in.t, filepath.Join(in.bin, "nodkey"), func(path string) error { return syscall.Mkfifo(path, 0o600) })
}, noCurl: true, noRun: true, want: "BIN/nodkey is not a file"},
{name: "a TMPDIR that others can write to", setup: func(in *installer) {
in.tmp = filepath.Join(in.dir, "open-tmp")
mkdir(in.t, in.tmp, 0o777)
}, noCurl: true, noRun: true, want: "group or others can write to DIR/open-tmp;"},
{name: "a TMPDIR in a directory that others can write to", setup: func(in *installer) {
mkdir(in.t, filepath.Join(in.dir, "open"), 0o777)
in.tmp = filepath.Join(in.dir, "open", "tmp")
mkdir(in.t, in.tmp, 0o700)
}, noCurl: true, noRun: true, want: "group or others can write to DIR/open;"},
{name: "no TMPDIR", setup: env("TMPDIR=/nonexistent/tmp"), noCurl: true, noRun: true,
want: "cannot find the directory /nonexistent/tmp"},
{name: "a gh that others can write to", setup: func(in *installer) { chmod(in.t, in.gh, 0o777) },
noCurl: true, noRun: true, want: "group or others can write to DIR/gh;"},
{name: "a gh in a directory that others can write to", setup: func(in *installer) {
mkdir(in.t, filepath.Join(in.dir, "open"), 0o777)
in.gh = filepath.Join(in.dir, "open", "gh")
writeFile(in.t, in.gh, []byte(fakeGh), 0o700)
}, noCurl: true, noRun: true, want: "group or others can write to DIR/open;"},
{name: "a gh that is a link", setup: func(in *installer) {
link := filepath.Join(in.dir, "gh-link")
if err := os.Symlink(in.gh, link); err != nil {
in.t.Fatal(err)
}
in.gh = link
}, noCurl: true, noRun: true, want: "--gh DIR/gh-link is not a program file; name the file itself, not a link"},
{name: "a gh that is not there", args: []string{"--gh", "/nonexistent/gh"}, noCurl: true, noRun: true,
want: "--gh /nonexistent/gh is not a program file"},
// The newest release, and the files of the release.
{name: "no answer from the API", setup: func(in *installer) { in.unserve(latestPath) }, want: "cannot ask GitHub for the newest release"},
{name: "an answer of the API that is too big", setup: func(in *installer) {
in.serve(latestPath, bytes.Repeat([]byte(" "), 1<<20+1))
}, want: "cannot ask GitHub for the newest release"},
{name: "a tag without v", setup: latest("0.2.0"), want: "GitHub does not name the newest release in the form vX.Y.Z"},
{name: "a tag with two numbers", setup: latest("v0.2"), want: "in the form vX.Y.Z"},
{name: "a tag with four numbers", setup: latest("v0.2.0.1"), want: "in the form vX.Y.Z"},
{name: "a tag with a leading zero", setup: latest("v0.02.0"), want: "in the form vX.Y.Z"},
{name: "a tag of a pre-release", setup: latest("v0.2.0-rc.1"), want: "in the form vX.Y.Z"},
{name: "a tag with a long number", setup: latest("v0.2.1234567890"), want: "in the form vX.Y.Z"},
{name: "a tag with a space", setup: latest("v0.2.0 "), want: "in the form vX.Y.Z"},
{name: "two tags", setup: func(in *installer) {
in.serve(latestPath, []byte("{\n \"tag_name\": \"v0.2.0\",\n \"tag_name\": \"v0.3.0\"\n}\n"))
}, want: "in the form vX.Y.Z"},
{name: "no tag", setup: func(in *installer) {
in.serve(latestPath, []byte("{\n \"name\": \"v0.2.0\"\n}\n"))
}, want: "in the form vX.Y.Z"},
{name: "no tarball", setup: func(in *installer) { in.unserve(releasePath + "0.2.0/" + tarball) },
want: "cannot download https://" + releasePath + "0.2.0/" + tarball},
{name: "no SHA256SUMS", setup: func(in *installer) { in.unserve(releasePath + "0.2.0/SHA256SUMS") },
want: "cannot download https://" + releasePath + "0.2.0/SHA256SUMS"},
{name: "a SHA256SUMS that is too big", setup: func(in *installer) {
sums(sumOf(in, "amd64")+" "+tarball+"\n", strings.Repeat("#", 1<<20))(in)
}, want: "cannot download https://" + releasePath + "0.2.0/SHA256SUMS"},
{name: "no bundle", setup: func(in *installer) { in.unserve(releasePath + "0.2.0/nodkey_0.2.0.sigstore.json") },
want: "cannot download https://" + releasePath + "0.2.0/nodkey_0.2.0.sigstore.json (0.1.0 has no such file"},
{name: "a bad checksum", setup: func(in *installer) {
sums(sumOf(in, "arm64")+" "+tarball+"\n", sumOf(in, "arm64")+" nodkey_0.2.0_linux_arm64.tar.gz\n")(in)
}, want: "the SHA-256 of " + tarball + " is not the one in SHA256SUMS"},
{name: "no line in SHA256SUMS", setup: func(in *installer) {
sums(sumOf(in, "arm64") + " nodkey_0.2.0_linux_arm64.tar.gz\n")(in)
}, want: "SHA256SUMS has no line for " + tarball},
{name: "a line for a longer name", setup: func(in *installer) {
sums(sumOf(in, "amd64") + " " + tarball + ".old\n")(in)
}, want: "SHA256SUMS has no line for " + tarball},
{name: "two lines in SHA256SUMS", setup: func(in *installer) {
sums(sumOf(in, "amd64")+" "+tarball+"\n", sumOf(in, "amd64")+" *"+tarball+"\n")(in)
}, want: "SHA256SUMS has more than one line for " + tarball},
// gh and the attestation.
{name: "a failed check of the attestation", setup: env("FAKE_GH_EXIT=1"), checked: true,
want: "gh attestation verify failed, so it is not proven that the release workflow built " + tarball},
{name: "a gh that is too old", setup: env("FAKE_GH_VERSION=2.92.0"), want: " is gh 2.92.0; it must be gh 2.93.0 or newer"},
{name: "a gh of a pre-release", setup: env("FAKE_GH_VERSION=2.93.0-rc.1"), want: "cannot tell the version of "},
{name: "a gh of a version with more", setup: env("FAKE_GH_VERSION=2.102.0+ds1"), want: "cannot tell the version of "},
{name: "a gh of no version", setup: env("FAKE_GH_VERSION=DEV"), want: "cannot tell the version of "},
{name: "a gh whose --version fails", setup: env("FAKE_GH_VERSION_EXIT=1"), want: "/gh --version; nothing"},
{name: "a downloaded gh with another SHA-256", setup: func(in *installer) { in.ghRelease() }, args: []string{},
want: "the SHA-256 of gh_2.102.0_linux_amd64.tar.gz is not the one in this script"},
{name: "no gh to download", args: []string{}, want: "cannot download gh_2.102.0_linux_amd64.tar.gz"},
// The new nodkey. The attestation proves which workflow built a
// file, not which version it is. A release 0.3.0 with an attested
// build of 0.2.0 passes the checksum and the attestation, and must
// still fail.
{name: "an attested older build under a newer name", setup: func(in *installer) {
in.latest("v0.3.0")
in.release("0.3.0", says("nodkey 0.2.0"))
}, checked: true, want: "the new nodkey does not say that it is nodkey 0.3.0"},
{name: "a new nodkey of another version", setup: rel(says("nodkey 0.1.0")), checked: true,
want: "the new nodkey does not say that it is nodkey 0.2.0"},
{name: "a new nodkey with more output", setup: rel(says("nodkey 0.2.0", "nodkey 0.3.0")), checked: true,
want: "the new nodkey does not say that it is nodkey 0.2.0"},
{name: "a new nodkey with a v", setup: rel(says("nodkey v0.2.0")), checked: true,
want: "the new nodkey does not say that it is nodkey 0.2.0"},
{name: "a new nodkey that does not run", setup: rel(func(string) []byte { return failingNodkey }), checked: true,
want: "the new nodkey does not run"},
{name: "a tarball without nodkey", setup: func(in *installer) {
data := tarGz(in.t, tarFile{"LICENSE", 0o644, []byte("a made-up license\n")})
in.serve(releasePath+"0.2.0/"+tarball, data)
sums(fmt.Sprintf("%x %s\n", sha256.Sum256(data), tarball))(in)
}, checked: true, want: "cannot take nodkey out of " + tarball},
} {
t.Run(tt.name, func(t *testing.T) {
in := newInstaller(t)
in.latest("v0.2.0")
in.release("0.2.0", says("nodkey 0.2.0"))
in.installed(fakeNodkey("installed", "nodkey 0.1.0"))
if tt.setup != nil {
tt.setup(in)
}
args := tt.args
if args == nil {
args = []string{"--gh", in.gh}
}
before := files(t, in.bin)
r := in.run(args...)
want := strings.NewReplacer("BIN", in.bin, "DIR", in.dir).Replace(tt.want)
in.checkFailed(r, 1, want, before)
if in.ghChecked() != tt.checked {
t.Errorf("gh attestation verify ran: %v, want %v", in.ghChecked(), tt.checked)
}
if urls := in.urls(); tt.noCurl && len(urls) != 0 {
t.Errorf("curl got %q, want no call", urls)
}
if runs := append(in.log("nodkey-runs"), in.log("gh")...); tt.noRun && len(runs) != 0 {
t.Errorf("the script ran a nodkey or a gh: %q", runs)
}
// The new nodkey runs only after the attestation passed.
if ranNew := slices.ContainsFunc(in.log("nodkey-runs"), func(s string) bool { return s == "amd64" }); ranNew && !tt.checked {
t.Error("the new nodkey ran, but the attestation was not checked")
}
})
}
}
// TestInstallRunsNoNewFileBeforeTheCheck: when the attestation fails, the
// new nodkey never runs, not even for its version.
func TestInstallRunsNoNewFileBeforeTheCheck(t *testing.T) {
in := newInstaller(t)
in.latest("v0.2.0")
in.release("0.2.0", says("nodkey 0.2.0"))
in.installed(fakeNodkey("installed", "nodkey 0.1.0"))
in.env = append(in.env, "FAKE_GH_EXIT=1")
before := files(t, in.bin)
r := in.run("--gh", in.gh)
in.checkFailed(r, 1, "gh attestation verify failed", before)
// Only the installed nodkey ran, for its version.
if runs := in.log("nodkey-runs"); !slices.Equal(runs, []string{"installed"}) {
t.Errorf("these copies of nodkey ran: %q, want only the installed one", runs)
}
}
// env returns a setup that adds the variables to the environment of the
// script.
func env(vars ...string) func(in *installer) {
return func(in *installer) { in.env = append(in.env, vars...) }
}
// latest returns a setup that makes tag the newest release.
func latest(tag string) func(in *installer) {
return func(in *installer) { in.latest(tag) }
}
// rel returns a setup that makes the release 0.2.0 again, with these
// files nodkey.
func rel(nodkey func(arch string) []byte) func(in *installer) {
return func(in *installer) { in.release("0.2.0", nodkey) }
}
// chmod sets the mode of path, and sets it back to 0700 at the end of the
// test, so that the temporary directory can be removed.
func chmod(t *testing.T, path string, mode os.FileMode) {
t.Helper()
if err := os.Chmod(path, mode); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chmod(path, 0o700) }) //nolint:gosec // G302: back to private, so that the test can remove it.
}
// replace removes the file path and makes something else there with
// create.
func replace(t *testing.T, path string, create func(path string) error) {
t.Helper()
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
if err := create(path); err != nil {
t.Fatal(err)
}
}
// TestInstallUsage: wrong arguments stop the script with exit code 64,
// before it downloads anything.