-
Notifications
You must be signed in to change notification settings - Fork 17
/
slug_test.go
1396 lines (1222 loc) · 31.8 KB
/
slug_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package slug
import (
"archive/tar"
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
"io/fs"
"io/ioutil"
"os"
"path"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"github.com/hashicorp/go-slug/internal/unpackinfo"
)
func TestPack(t *testing.T) {
slug := bytes.NewBuffer(nil)
meta, err := Pack("testdata/archive-dir", slug, true)
if err != nil {
t.Fatalf("err: %v", err)
}
assertArchiveFixture(t, slug, meta)
}
func TestPack_defaultRulesOnly(t *testing.T) {
slug := bytes.NewBuffer(nil)
meta, err := Pack("testdata/archive-dir-defaults-only", slug, true)
if err != nil {
t.Fatalf("err: %v", err)
}
// Make sure .terraform/modules/** are included.
subModuleDir := false
// Make sure .terraform/plugins are excluded.
pluginsDir := false
for _, file := range meta.Files {
if strings.HasPrefix(file, filepath.Clean(".terraform/modules/subdir/README")) {
subModuleDir = true
continue
}
if strings.HasPrefix(file, filepath.Clean(".terraform/plugins/")) {
pluginsDir = true
continue
}
}
if !subModuleDir {
t.Fatal("expected to include .terraform/modules/subdir/README")
}
if pluginsDir {
t.Fatal("expected to exclude .terraform/plugins")
}
}
func TestPack_rootIsSymlink(t *testing.T) {
for _, path := range []string{
"testdata/archive-dir",
"./testdata/archive-dir",
} {
t.Run(fmt.Sprintf("target is path: %s", path), func(t *testing.T) {
symlinkPath := path + "-symlink"
err := os.Symlink(path, symlinkPath)
if err != nil {
t.Fatalf("Failed creating dir %s symlink: %v", path, err)
}
t.Cleanup(func() {
err = os.Remove(symlinkPath)
if err != nil {
t.Fatalf("failed removing %s: %v", symlinkPath, err)
}
})
slug := bytes.NewBuffer(nil)
meta, err := Pack(symlinkPath, slug, true)
if err != nil {
t.Fatalf("err: %v", err)
}
assertArchiveFixture(t, slug, meta)
})
}
}
func TestPack_absoluteSrcRelativeSymlinks(t *testing.T) {
var path string
var err error
// In instances we run within CI, we want to fetch
// the absolute path where our test is located
if workDir, ok := os.LookupEnv("GITHUB_WORKSPACE"); ok {
path = workDir
} else {
path, err = os.Getwd()
if err != nil {
t.Fatalf("could not determine the working dir: %v", err)
}
}
// One last check, if this variable is empty we'll error
// since we need the absolute path for the source
if path == "" {
t.Fatal("Home directory could not be determined")
}
path = filepath.Join(path, "testdata/archive-dir-absolute/dev")
slug := bytes.NewBuffer(nil)
_, err = Pack(path, slug, true)
if err != nil {
// We simply want to ensure paths can be resolved while
// traversing the source directory
t.Fatalf("err: %v", err)
}
// Cannot pack without dereferencing
_, err = Pack(path, slug, false)
if !strings.HasPrefix(err.Error(), "illegal slug error:") {
t.Fatalf("expected illegal slug error, got %q", err)
}
}
func TestPackWithoutIgnoring(t *testing.T) {
slug := bytes.NewBuffer(nil)
// By default NewPacker() creates a Packer that does not use
// .terraformignore or dereference symlinks.
p, err := NewPacker()
if err != nil {
t.Fatalf("err: %v", err)
}
meta, err := p.Pack("testdata/archive-dir-no-external", slug)
if err != nil {
t.Fatalf("err: %v", err)
}
gzipR, err := gzip.NewReader(slug)
if err != nil {
t.Fatalf("err: %v", err)
}
tarR := tar.NewReader(gzipR)
var (
fileList []string
slugSize int64
)
for {
hdr, err := tarR.Next()
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("err: %v", err)
}
fileList = append(fileList, hdr.Name)
if hdr.Typeflag == tar.TypeReg || hdr.Typeflag == tar.TypeRegA {
slugSize += hdr.Size
}
}
// baz.txt would normally be ignored, but should not be
var bazFound bool
for _, file := range fileList {
if file == "baz.txt" {
bazFound = true
}
}
if !bazFound {
t.Fatal("expected file baz.txt to be present, but not found")
}
// .terraform/file.txt would normally be ignored, but should not be
var dotTerraformFileFound bool
for _, file := range fileList {
if file == ".terraform/file.txt" {
dotTerraformFileFound = true
}
}
if !dotTerraformFileFound {
t.Fatal("expected file .terraform/file.txt to be present, but not found")
}
// Check the metadata
expect := &Meta{
Files: fileList,
Size: slugSize,
}
if !reflect.DeepEqual(meta, expect) {
t.Fatalf("\nexpect:\n%#v\n\nactual:\n%#v", expect, meta)
}
}
func TestPack_symlinks(t *testing.T) {
type tcase struct {
absolute bool
external bool
targetExists bool
dereference bool
}
var tcases []tcase
for _, absolute := range []bool{true, false} {
for _, external := range []bool{true, false} {
for _, targetExists := range []bool{true, false} {
for _, dereference := range []bool{true, false} {
tcases = append(tcases, tcase{
absolute: absolute,
external: external,
targetExists: targetExists,
dereference: dereference,
})
}
}
}
}
for _, tc := range tcases {
desc := fmt.Sprintf(
"absolute:%v external:%v targetExists:%v dereference:%v",
tc.absolute, tc.external, tc.targetExists, tc.dereference)
t.Run(desc, func(t *testing.T) {
td, err := ioutil.TempDir("", "go-slug")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(td)
internal := filepath.Join(td, "internal")
if err := os.MkdirAll(internal, 0700); err != nil {
t.Fatal(err)
}
external := filepath.Join(td, "external")
if err := os.MkdirAll(external, 0700); err != nil {
t.Fatal(err)
}
// Make the symlink in a subdirectory. This will help ensure that
// a proper relative link gets created, even when the relative
// path requires upward directory traversal.
symPath := filepath.Join(internal, "sub", "sym")
if err := os.MkdirAll(filepath.Join(internal, "sub"), 0700); err != nil {
t.Fatal(err)
}
// Get an absolute path within the temp dir and an absolute target.
// We place the target into a subdir to ensure the link is created
// properly within a nested structure.
var targetPath string
if tc.external {
targetPath = filepath.Join(external, "foo", "bar")
} else {
targetPath = filepath.Join(internal, "foo", "bar")
}
if tc.targetExists {
if err := os.MkdirAll(filepath.Dir(targetPath), 0700); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(targetPath, []byte("foo"), 0644); err != nil {
t.Fatal(err)
}
}
if !tc.absolute {
targetPath, err = filepath.Rel(filepath.Dir(symPath), targetPath)
if err != nil {
t.Fatal(err)
}
}
// Make the symlink.
if err := os.Symlink(targetPath, symPath); err != nil {
t.Fatal(err)
}
var expectErr string
if tc.external && !tc.dereference {
expectErr = "has external target"
}
if tc.external && tc.dereference && !tc.targetExists {
expectErr = "no such file or directory"
}
var expectTypeflag byte
if tc.external && tc.dereference {
expectTypeflag = tar.TypeReg
} else {
expectTypeflag = tar.TypeSymlink
}
// Pack up the temp dir.
slug := bytes.NewBuffer(nil)
_, err = Pack(internal, slug, tc.dereference)
if expectErr != "" {
if err != nil {
if strings.Contains(err.Error(), expectErr) {
return
}
t.Fatalf("expected error %q, got %v", expectErr, err)
}
t.Fatal("expected error, got nil")
} else if err != nil {
t.Fatal(err)
}
// Inspect the result.
gzipR, err := gzip.NewReader(slug)
if err != nil {
t.Fatalf("err: %v", err)
}
tarR := tar.NewReader(gzipR)
symFound := false
for {
hdr, err := tarR.Next()
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("err: %v", err)
}
if hdr.Name == "sub/sym" {
symFound = true
if hdr.Typeflag != expectTypeflag {
t.Fatalf("unexpected file type in slug: %q", hdr.Typeflag)
}
if expectTypeflag == tar.TypeSymlink && hdr.Linkname != targetPath {
t.Fatalf("unexpected link target in slug: %q", hdr.Linkname)
}
}
}
if !symFound {
t.Fatal("did not find symlink in archive")
}
})
}
}
func TestAllowSymlinkTarget(t *testing.T) {
tcases := []struct {
desc string
allow string
target string
err string
}{
{
desc: "absolute symlink, exact match",
allow: "/foo/bar/baz",
target: "/foo/bar/baz",
},
{
desc: "relative symlink, exact match",
allow: "../foo/bar",
target: "../foo/bar",
},
{
desc: "absolute symlink, prefix match",
allow: "/foo/",
target: "/foo/bar/baz",
},
{
desc: "relative symlink, prefix match",
allow: "../foo/",
target: "../foo/bar/baz",
},
{
desc: "absolute symlink, non-match",
allow: "/zip",
target: "/foo/bar/baz",
err: "has external target",
},
{
desc: "relative symlink, non-match",
allow: "../zip/",
target: "../foo/bar/baz",
err: "has external target",
},
{
desc: "absolute symlink, embedded traversal, non-match",
allow: "/foo/",
target: "/foo/../../zip",
err: "has external target",
},
{
desc: "relative symlink, embedded traversal, non-match",
allow: "../foo/",
target: "../foo/../../zip",
err: "has external target",
},
{
desc: "absolute symlink, embedded traversal, match",
allow: "/foo/",
target: "/foo/bar/../baz",
},
{
desc: "relative symlink, embedded traversal, match",
allow: "../foo/",
target: "../foo/bar/../baz",
},
{
desc: "external target with embedded upward path traversal",
allow: "foo/bar/",
target: "foo/bar/../../../lol",
err: "has external target",
},
{
desc: "similar file path, non-match",
allow: "/foo",
target: "/foobar",
err: "has external target",
},
}
for _, tc := range tcases {
t.Run("Pack: "+tc.desc, func(t *testing.T) {
td, err := ioutil.TempDir("", "go-slug")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(td)
// Make the symlink.
if err := os.Symlink(tc.target, filepath.Join(td, "sym")); err != nil {
t.Fatal(err)
}
// Pack up the temp dir.
slug := bytes.NewBuffer(nil)
p, err := NewPacker(AllowSymlinkTarget(tc.allow))
if err != nil {
t.Fatal(err)
}
_, err = p.Pack(td, slug)
if tc.err != "" {
if err != nil {
if strings.Contains(err.Error(), tc.err) {
return
}
t.Fatalf("expected error %q, got %v", tc.err, err)
}
t.Fatal("expected error, got nil")
} else if err != nil {
t.Fatal(err)
}
// Inspect the result.
gzipR, err := gzip.NewReader(slug)
if err != nil {
t.Fatalf("err: %v", err)
}
tarR := tar.NewReader(gzipR)
symFound := false
for {
hdr, err := tarR.Next()
if err == io.EOF {
break
}
if err != nil {
t.Fatalf("err: %v", err)
}
if hdr.Name == "sym" {
symFound = true
if hdr.Typeflag != tar.TypeSymlink {
t.Fatalf("unexpected file type in slug: %q", hdr.Typeflag)
}
if hdr.Linkname != tc.target {
t.Fatalf("unexpected link target in slug: %q", hdr.Linkname)
}
}
}
if !symFound {
t.Fatal("did not find symlink in archive")
}
})
t.Run("Unpack: "+tc.desc, func(t *testing.T) {
dir, err := ioutil.TempDir("", "slug")
if err != nil {
t.Fatalf("err:%v", err)
}
defer os.RemoveAll(dir)
in := filepath.Join(dir, "slug.tar.gz")
// Create the output file
wfh, err := os.Create(in)
if err != nil {
t.Fatalf("err: %v", err)
}
// Gzip compress all the output data
gzipW := gzip.NewWriter(wfh)
// Tar the file contents
tarW := tar.NewWriter(gzipW)
// Write the header.
tarW.WriteHeader(&tar.Header{
Name: "l",
Linkname: tc.target,
Typeflag: tar.TypeSymlink,
})
tarW.Close()
gzipW.Close()
wfh.Close()
// Open the slug file for reading.
fh, err := os.Open(in)
if err != nil {
t.Fatalf("err: %v", err)
}
// Create a dir to unpack into.
dst, err := ioutil.TempDir(dir, "")
if err != nil {
t.Fatalf("err: %v", err)
}
defer os.RemoveAll(dst)
// Unpack.
p, err := NewPacker(AllowSymlinkTarget(tc.allow))
if err != nil {
t.Fatal(err)
}
if err := p.Unpack(fh, dst); err != nil {
if tc.err != "" {
if !strings.Contains(err.Error(), tc.err) {
t.Fatalf("expected error %q, got %v", tc.err, err)
}
} else {
t.Fatal(err)
}
} else if tc.err != "" {
t.Fatalf("expected error %q, got nil", tc.err)
}
})
}
}
func TestUnpack(t *testing.T) {
// First create the slug file so we can try to unpack it.
slug := bytes.NewBuffer(nil)
if _, err := Pack("testdata/archive-dir-no-external", slug, true); err != nil {
t.Fatalf("err: %v", err)
}
// Create a dir to unpack into.
dst, err := ioutil.TempDir("", "slug")
if err != nil {
t.Fatalf("err: %v", err)
}
defer os.RemoveAll(dst)
// Now try unpacking it.
if err := Unpack(slug, dst); err != nil {
t.Fatalf("err: %v", err)
}
// Verify all the files
verifyFile(t, filepath.Join(dst, "bar.txt"), 0, "bar\n")
verifyFile(t, filepath.Join(dst, "sub/bar.txt"), os.ModeSymlink, "../bar.txt")
verifyFile(t, filepath.Join(dst, "sub/zip.txt"), 0, "zip\n")
// Verify timestamps for files
verifyTimestamps(t, "testdata/archive-dir-no-external/bar.txt", filepath.Join(dst, "bar.txt"))
verifyTimestamps(t, "testdata/archive-dir-no-external/sub/zip.txt", filepath.Join(dst, "sub/zip.txt"))
verifyTimestamps(t, "testdata/archive-dir-no-external/sub2/zip.txt", filepath.Join(dst, "sub2/zip.txt"))
// Verify timestamps for symlinks
if unpackinfo.CanMaintainSymlinkTimestamps() {
verifyTimestamps(t, "testdata/archive-dir-no-external/sub/bar.txt", filepath.Join(dst, "sub/bar.txt"))
}
// Verify timestamps for directories
verifyTimestamps(t, "testdata/archive-dir-no-external/foo.terraform", filepath.Join(dst, "foo.terraform"))
verifyTimestamps(t, "testdata/archive-dir-no-external/sub", filepath.Join(dst, "sub"))
verifyTimestamps(t, "testdata/archive-dir-no-external/sub2", filepath.Join(dst, "sub2"))
// Check that we can set permissions properly
verifyPerms(t, filepath.Join(dst, "bar.txt"), 0644)
verifyPerms(t, filepath.Join(dst, "sub/zip.txt"), 0644)
verifyPerms(t, filepath.Join(dst, "sub/bar.txt"), 0644)
verifyPerms(t, filepath.Join(dst, "exe"), 0755)
}
func TestUnpack_HeaderOrdering(t *testing.T) {
// Tests that when a tar file has subdirectories ordered before parent directories, the
// timestamps get restored correctly in the plaform where the tests are run.
// This file is created by the go program found in `testdata/subdir-ordering`
f, err := os.Open("testdata/subdir-appears-first.tar.gz")
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
packer, err := NewPacker()
if err != nil {
t.Fatalf("expected no error, got %s", err)
}
err = packer.Unpack(f, dir)
if err != nil {
t.Fatalf("expected no error, got %s", err)
}
// These times were recorded when the archive was created
testCases := []struct {
Path string
TS time.Time
}{
{TS: time.Unix(0, 1698787142347461403).Round(time.Second), Path: path.Join(dir, "super/duper")},
{TS: time.Unix(0, 1698780461367973574).Round(time.Second), Path: path.Join(dir, "super")},
{TS: time.Unix(0, 1698787142347461286).Round(time.Second), Path: path.Join(dir, "super/duper/trooper")},
{TS: time.Unix(0, 1698780470254368545).Round(time.Second), Path: path.Join(dir, "super/duper/trooper/foo.txt")},
}
for _, tc := range testCases {
info, err := os.Stat(tc.Path)
if err != nil {
t.Fatalf("error when stat %q: %s", tc.Path, err)
}
if info.ModTime() != tc.TS {
t.Errorf("timestamp of file %q (%d) did not match expected value %d", tc.Path, info.ModTime().UnixNano(), tc.TS.UnixNano())
}
}
}
func TestUnpackDuplicateNoWritePerm(t *testing.T) {
dir, err := ioutil.TempDir("", "slug")
if err != nil {
t.Fatalf("err:%v", err)
}
defer os.RemoveAll(dir)
in := filepath.Join(dir, "slug.tar.gz")
// Create the output file
wfh, err := os.Create(in)
if err != nil {
t.Fatalf("err: %v", err)
}
// Gzip compress all the output data
gzipW := gzip.NewWriter(wfh)
// Tar the file contents
tarW := tar.NewWriter(gzipW)
var hdr tar.Header
data := "this is a\n"
hdr.Name = "a"
hdr.Mode = 0100000 | 0400
hdr.Size = int64(len(data))
tarW.WriteHeader(&hdr)
tarW.Write([]byte(data))
// write it twice
tarW.WriteHeader(&hdr)
tarW.Write([]byte(data))
tarW.Close()
gzipW.Close()
wfh.Close()
// Open the slug file for reading.
fh, err := os.Open(in)
if err != nil {
t.Fatalf("err: %v", err)
}
// Create a dir to unpack into.
dst, err := ioutil.TempDir(dir, "")
if err != nil {
t.Fatalf("err: %v", err)
}
defer os.RemoveAll(dst)
// Now try unpacking it.
if err := Unpack(fh, dst); err != nil {
t.Fatalf("err: %v", err)
}
// Verify all the files
verifyFile(t, filepath.Join(dst, "a"), 0, "this is a\n")
// Check that we can set permissions properly
verifyPerms(t, filepath.Join(dst, "a"), 0400)
}
func TestUnpackPaxHeaders(t *testing.T) {
tcases := []struct {
desc string
headers []*tar.Header
}{
{
desc: "extended pax header",
headers: []*tar.Header{
{
Name: "h",
Typeflag: tar.TypeXHeader,
},
},
},
{
desc: "global pax header",
headers: []*tar.Header{
{
Name: "h",
Typeflag: tar.TypeXGlobalHeader,
},
},
},
}
for _, tc := range tcases {
t.Run(tc.desc, func(t *testing.T) {
dir, err := ioutil.TempDir("", "slug")
if err != nil {
t.Fatalf("err:%v", err)
}
defer os.RemoveAll(dir)
in := filepath.Join(dir, "slug.tar.gz")
// Create the output file
wfh, err := os.Create(in)
if err != nil {
t.Fatalf("err: %v", err)
}
// Gzip compress all the output data
gzipW := gzip.NewWriter(wfh)
// Tar the file contents
tarW := tar.NewWriter(gzipW)
for _, hdr := range tc.headers {
tarW.WriteHeader(hdr)
}
tarW.Close()
gzipW.Close()
wfh.Close()
// Open the slug file for reading.
fh, err := os.Open(in)
if err != nil {
t.Fatalf("err: %v", err)
}
// Create a dir to unpack into.
dst, err := ioutil.TempDir(dir, "")
if err != nil {
t.Fatalf("err: %v", err)
}
defer os.RemoveAll(dst)
// Now try unpacking it.
if err := Unpack(fh, dst); err != nil {
t.Fatalf("err: %v", err)
}
// Verify no file was created.
path := filepath.Join(dst, "h")
fh, err = os.Open(path)
if err == nil {
t.Fatalf("expected file not to exist: %q", path)
}
defer fh.Close()
})
}
}
// ensure Unpack returns an error when an unsupported file type is encountered
// in an archive, rather than silently discarding the data.
func TestUnpackErrorOnUnhandledType(t *testing.T) {
dir, err := ioutil.TempDir("", "slug")
if err != nil {
t.Fatalf("err:%v", err)
}
defer os.RemoveAll(dir)
in := filepath.Join(dir, "slug.tar.gz")
// Create the output file
wfh, err := os.Create(in)
if err != nil {
t.Fatalf("err: %v", err)
}
// Gzip compress all the output data
gzipW := gzip.NewWriter(wfh)
// Tar the file contents
tarW := tar.NewWriter(gzipW)
var hdr tar.Header
hdr.Typeflag = tar.TypeFifo // we're unlikely to support FIFOs :-)
hdr.Name = "l"
hdr.Size = int64(0)
tarW.WriteHeader(&hdr)
tarW.Close()
gzipW.Close()
wfh.Close()
// Open the slug file for reading.
fh, err := os.Open(in)
if err != nil {
t.Fatalf("err: %v", err)
}
// Create a dir to unpack into.
dst, err := ioutil.TempDir(dir, "")
if err != nil {
t.Fatalf("err: %v", err)
}
defer os.RemoveAll(dst)
// Now try unpacking it, which should fail
if err := Unpack(fh, dst); err == nil {
t.Fatalf("should have gotten error unpacking slug with fifo, got none")
}
}
func TestUnpackMaliciousSymlinks(t *testing.T) {
tcases := []struct {
desc string
headers []*tar.Header
err string
}{
{
desc: "symlink with absolute path",
headers: []*tar.Header{
&tar.Header{
Name: "l",
Linkname: "/etc/shadow",
Typeflag: tar.TypeSymlink,
},
},
err: "has external target",
},
{
desc: "symlink with external target",
headers: []*tar.Header{
&tar.Header{
Name: "l",
Linkname: "../../../../../etc/shadow",
Typeflag: tar.TypeSymlink,
},
},
err: "has external target",
},
{
desc: "symlink with nested external target",
headers: []*tar.Header{
&tar.Header{
Name: "l",
Linkname: "foo/bar/baz/../../../../../../../../etc/shadow",
Typeflag: tar.TypeSymlink,
},
},
err: "has external target",
},
{
desc: "zipslip vulnerability",
headers: []*tar.Header{
&tar.Header{
Name: "subdir/parent",
Linkname: "..",
Typeflag: tar.TypeSymlink,
},
&tar.Header{
Name: "subdir/parent/escapes",
Linkname: "..",
Typeflag: tar.TypeSymlink,
},
},
err: `cannot extract "subdir/parent/escapes" through symlink`,
},
{
desc: "nested symlinks within symlinked dir",
headers: []*tar.Header{
&tar.Header{
Name: "subdir/parent",
Linkname: "..",
Typeflag: tar.TypeSymlink,
},
&tar.Header{
Name: "subdir/parent/otherdir/escapes",
Linkname: "../..",
Typeflag: tar.TypeSymlink,
},
},
err: `cannot extract "subdir/parent/otherdir/escapes" through symlink`,
},
{
desc: "regular file through symlink",
headers: []*tar.Header{
&tar.Header{
Name: "subdir/parent",
Linkname: "..",
Typeflag: tar.TypeSymlink,
},
&tar.Header{
Name: "subdir/parent/file",
Typeflag: tar.TypeReg,
},
},
err: `cannot extract "subdir/parent/file" through symlink`,
},
{
desc: "directory through symlink",
headers: []*tar.Header{
&tar.Header{
Name: "subdir/parent",
Linkname: "..",
Typeflag: tar.TypeSymlink,
},
&tar.Header{
Name: "subdir/parent/dir",
Typeflag: tar.TypeDir,
},
},
err: `cannot extract "subdir/parent/dir" through symlink`,
},
}
for _, tc := range tcases {
t.Run(tc.desc, func(t *testing.T) {
dir, err := ioutil.TempDir("", "slug")
if err != nil {
t.Fatalf("err:%v", err)
}
defer os.RemoveAll(dir)
in := filepath.Join(dir, "slug.tar.gz")
// Create the output file
wfh, err := os.Create(in)
if err != nil {
t.Fatalf("err: %v", err)
}
// Gzip compress all the output data
gzipW := gzip.NewWriter(wfh)
// Tar the file contents
tarW := tar.NewWriter(gzipW)
for _, hdr := range tc.headers {
tarW.WriteHeader(hdr)
}
tarW.Close()
gzipW.Close()
wfh.Close()
// Open the slug file for reading.
fh, err := os.Open(in)
if err != nil {
t.Fatalf("err: %v", err)
}
// Create a dir to unpack into.
dst, err := ioutil.TempDir(dir, "")
if err != nil {
t.Fatalf("err: %v", err)
}
defer os.RemoveAll(dst)
// Now try unpacking it, which should fail
var e *IllegalSlugError
err = Unpack(fh, dst)