-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patharchive_test.go
1125 lines (1029 loc) · 31.2 KB
/
archive_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
package archive
import (
"archive/tar"
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/moby/sys/user"
"github.com/moby/sys/userns"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/skip"
"github.com/moby/go-archive/compression"
)
var defaultArchiver = NewDefaultArchiver()
func defaultTarUntar(src, dst string) error {
return defaultArchiver.TarUntar(src, dst)
}
func defaultUntarPath(src, dst string) error {
return defaultArchiver.UntarPath(src, dst)
}
func defaultCopyFileWithTar(src, dst string) (err error) {
return defaultArchiver.CopyFileWithTar(src, dst)
}
func defaultCopyWithTar(src, dst string) error {
return defaultArchiver.CopyWithTar(src, dst)
}
// toUnixPath converts the given path to a unix-path, using forward-slashes, and
// with the drive-letter replaced (e.g. "C:\temp\file.txt" becomes "/c/temp/file.txt").
// It is a no-op on non-Windows platforms.
func toUnixPath(p string) string {
if runtime.GOOS != "windows" {
return p
}
p = filepath.ToSlash(p)
// This should probably be more generic, but this suits our needs for now.
if pth, ok := strings.CutPrefix(p, "C:/"); ok {
return "/c/" + pth
}
if pth, ok := strings.CutPrefix(p, "D:/"); ok {
return "/d/" + pth
}
return p
}
func TestIsArchivePathDir(t *testing.T) {
tmp := t.TempDir()
cmd := exec.Command("sh", "-c", fmt.Sprintf("mkdir -p %s/archivedir", toUnixPath(tmp)))
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Failed to create directory (%v): %s", err, output)
}
if IsArchivePath(filepath.Join(tmp, "archivedir")) {
t.Fatalf("Incorrectly recognised directory as an archive")
}
}
func TestIsArchivePathInvalidFile(t *testing.T) {
tmp := t.TempDir()
cmd := exec.Command("sh", "-c", fmt.Sprintf("dd if=/dev/zero bs=1024 count=1 of=%[1]s/archive && gzip --stdout %[1]s/archive > %[1]s/archive.gz", toUnixPath(tmp)))
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Failed to create archive file (%v): %s", err, output)
}
if IsArchivePath(filepath.Join(tmp, "archive")) {
t.Fatalf("Incorrectly recognised invalid tar path as archive")
}
if IsArchivePath(filepath.Join(tmp, "archive.gz")) {
t.Fatalf("Incorrectly recognised invalid compressed tar path as archive")
}
}
func TestIsArchivePathTar(t *testing.T) {
tmp := t.TempDir()
cmdStr := fmt.Sprintf("touch %[1]s/archivedata && tar -cf %[1]s/archive %[1]s/archivedata && gzip --stdout %[1]s/archive > %[1]s/archive.gz", toUnixPath(tmp))
cmd := exec.Command("sh", "-c", cmdStr)
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Failed to create archive file (%v):\ncommand: %s\noutput: %s", err, cmd.String(), output)
}
if !IsArchivePath(filepath.Join(tmp, "/archive")) {
t.Fatalf("Did not recognise valid tar path as archive")
}
if !IsArchivePath(filepath.Join(tmp, "archive.gz")) {
t.Fatalf("Did not recognise valid compressed tar path as archive")
}
}
func TestUntarPathWithInvalidDest(t *testing.T) {
tempFolder := t.TempDir()
invalidDestFolder := filepath.Join(tempFolder, "invalidDest")
// Create a src file
srcFile := filepath.Join(tempFolder, "src")
tarFile := filepath.Join(tempFolder, "src.tar")
f, err := os.Create(srcFile)
if assert.Check(t, err) {
_ = f.Close()
}
d, err := os.Create(invalidDestFolder) // being a file (not dir) should cause an error
if assert.Check(t, err) {
_ = d.Close()
}
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := toUnixPath(srcFile)
tarFileU := toUnixPath(tarFile)
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
output, err := cmd.CombinedOutput()
assert.NilError(t, err, "command: %s\noutput: %s", cmd.String(), output)
err = defaultUntarPath(tarFile, invalidDestFolder)
if err == nil {
t.Fatalf("UntarPath with invalid destination path should throw an error.")
}
}
func TestUntarPathWithInvalidSrc(t *testing.T) {
err := defaultUntarPath("/invalid/path", t.TempDir())
if err == nil {
t.Fatalf("UntarPath with invalid src path should throw an error.")
}
}
func TestUntarPath(t *testing.T) {
skip.If(t, runtime.GOOS != "windows" && os.Getuid() != 0, "skipping test that requires root")
tmpFolder := t.TempDir()
srcFile := filepath.Join(tmpFolder, "src")
tarFile := filepath.Join(tmpFolder, "src.tar")
f, err := os.Create(filepath.Join(tmpFolder, "src"))
if assert.Check(t, err) {
_ = f.Close()
}
destFolder := filepath.Join(tmpFolder, "dest")
err = os.MkdirAll(destFolder, 0o740)
if err != nil {
t.Fatalf("Fail to create the destination file")
}
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := toUnixPath(srcFile)
tarFileU := toUnixPath(tarFile)
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
output, err := cmd.CombinedOutput()
assert.NilError(t, err, "command: %s\noutput: %s", cmd.String(), output)
err = defaultUntarPath(tarFile, destFolder)
if err != nil {
t.Fatalf("UntarPath shouldn't throw an error, %s.", err)
}
expectedFile := filepath.Join(destFolder, srcFileU)
_, err = os.Stat(expectedFile)
if err != nil {
t.Fatalf("Destination folder should contain the source file but did not.")
}
}
// Do the same test as above but with the destination as file, it should fail
func TestUntarPathWithDestinationFile(t *testing.T) {
tmpFolder := t.TempDir()
srcFile := filepath.Join(tmpFolder, "src")
tarFile := filepath.Join(tmpFolder, "src.tar")
f, err := os.Create(filepath.Join(tmpFolder, "src"))
if assert.Check(t, err) {
_ = f.Close()
}
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := toUnixPath(srcFile)
tarFileU := toUnixPath(tarFile)
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Failed to create archive file (%v):\ncommand: %s\noutput: %s", err, cmd.String(), output)
}
destFile := filepath.Join(tmpFolder, "dest")
f, err = os.Create(destFile)
if assert.Check(t, err) {
_ = f.Close()
}
err = defaultUntarPath(tarFile, destFile)
if err == nil {
t.Fatalf("UntarPath should throw an error if the destination if a file")
}
}
// Do the same test as above but with the destination folder already exists
// and the destination file is a directory
// It's working, see https://github.com/docker/docker/issues/10040
func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) {
tmpFolder := t.TempDir()
srcFile := filepath.Join(tmpFolder, "src")
tarFile := filepath.Join(tmpFolder, "src.tar")
f, err := os.Create(srcFile)
if assert.Check(t, err) {
_ = f.Close()
}
// Translate back to Unix semantics as next exec.Command is run under sh
srcFileU := toUnixPath(srcFile)
tarFileU := toUnixPath(tarFile)
cmd := exec.Command("sh", "-c", "tar cf "+tarFileU+" "+srcFileU)
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("Failed to create archive file (%v):\ncommand: %s\noutput: %s", err, cmd.String(), output)
}
destFolder := filepath.Join(tmpFolder, "dest")
err = os.MkdirAll(destFolder, 0o740)
if err != nil {
t.Fatalf("Fail to create the destination folder")
}
// Let's create a folder that will has the same path as the extracted file (from tar)
destSrcFileAsFolder := filepath.Join(destFolder, srcFileU)
err = os.MkdirAll(destSrcFileAsFolder, 0o740)
if err != nil {
t.Fatal(err)
}
err = defaultUntarPath(tarFile, destFolder)
if err != nil {
t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder")
}
}
func TestCopyWithTarInvalidSrc(t *testing.T) {
tempFolder := t.TempDir()
destFolder := filepath.Join(tempFolder, "dest")
invalidSrc := filepath.Join(tempFolder, "doesnotexists")
err := os.MkdirAll(destFolder, 0o740)
if err != nil {
t.Fatal(err)
}
err = defaultCopyWithTar(invalidSrc, destFolder)
if err == nil {
t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
}
}
func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) {
skip.If(t, runtime.GOOS != "windows" && os.Getuid() != 0, "skipping test that requires root")
tempFolder := t.TempDir()
srcFolder := filepath.Join(tempFolder, "src")
inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
err := os.MkdirAll(srcFolder, 0o740)
if err != nil {
t.Fatal(err)
}
err = defaultCopyWithTar(srcFolder, inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
}
_, err = os.Stat(inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder should create it.")
}
}
// Test CopyWithTar with a file as src
func TestCopyWithTarSrcFile(t *testing.T) {
folder := t.TempDir()
dest := filepath.Join(folder, "dest")
srcFolder := filepath.Join(folder, "src")
src := filepath.Join(folder, filepath.Join("src", "src"))
if err := os.MkdirAll(srcFolder, 0o740); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(dest, 0o740); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(src, []byte("content"), 0o777); err != nil {
t.Fatal(err)
}
if err := defaultCopyWithTar(src, dest); err != nil {
t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
}
// FIXME Check the content
if _, err := os.Stat(dest); err != nil {
t.Fatalf("Destination file should be the same as the source.")
}
}
// Test CopyWithTar with a folder as src
func TestCopyWithTarSrcFolder(t *testing.T) {
folder := t.TempDir()
dest := filepath.Join(folder, "dest")
src := filepath.Join(folder, filepath.Join("src", "folder"))
if err := os.MkdirAll(src, 0o740); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(dest, 0o740); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(src, "file"), []byte("content"), 0o777); err != nil {
t.Fatal(err)
}
if err := defaultCopyWithTar(src, dest); err != nil {
t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err)
}
// FIXME Check the content (the file inside)
if _, err := os.Stat(dest); err != nil {
t.Fatalf("Destination folder should contain the source file but did not.")
}
}
func TestCopyFileWithTarInvalidSrc(t *testing.T) {
tempFolder := t.TempDir()
destFolder := filepath.Join(tempFolder, "dest")
err := os.MkdirAll(destFolder, 0o740)
if err != nil {
t.Fatal(err)
}
invalidFile := filepath.Join(tempFolder, "doesnotexists")
err = defaultCopyFileWithTar(invalidFile, destFolder)
if err == nil {
t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.")
}
}
func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) {
tempFolder := t.TempDir()
srcFile := filepath.Join(tempFolder, "src")
inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists")
f, err := os.Create(srcFile)
if assert.Check(t, err) {
_ = f.Close()
}
err = defaultCopyFileWithTar(srcFile, inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.")
}
_, err = os.Stat(inexistentDestFolder)
if err != nil {
t.Fatalf("CopyWithTar with an inexistent folder should create it.")
}
// FIXME Test the src file and content
}
func TestCopyFileWithTarSrcFolder(t *testing.T) {
folder := t.TempDir()
dest := filepath.Join(folder, "dest")
src := filepath.Join(folder, "srcfolder")
err := os.MkdirAll(src, 0o740)
if err != nil {
t.Fatal(err)
}
err = os.MkdirAll(dest, 0o740)
if err != nil {
t.Fatal(err)
}
err = defaultCopyFileWithTar(src, dest)
if err == nil {
t.Fatalf("CopyFileWithTar should throw an error with a folder.")
}
}
func TestCopyFileWithTarSrcFile(t *testing.T) {
folder := t.TempDir()
dest := filepath.Join(folder, "dest")
srcFolder := filepath.Join(folder, "src")
src := filepath.Join(folder, filepath.Join("src", "src"))
if err := os.MkdirAll(srcFolder, 0o740); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(dest, 0o740); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(src, []byte("content"), 0o777); err != nil {
t.Fatal(err)
}
if err := defaultCopyWithTar(src, dest+"/"); err != nil {
t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err)
}
if _, err := os.Stat(dest); err != nil {
t.Fatalf("Destination folder should contain the source file but did not.")
}
}
func TestTarFiles(t *testing.T) {
// try without hardlinks
if err := checkNoChanges(t, 1000, false); err != nil {
t.Fatal(err)
}
// try with hardlinks
if err := checkNoChanges(t, 1000, true); err != nil {
t.Fatal(err)
}
}
func checkNoChanges(t *testing.T, fileNum int, hardlinks bool) error {
srcDir, err := os.MkdirTemp(t.TempDir(), "srcDir")
if err != nil {
return err
}
destDir, err := os.MkdirTemp(t.TempDir(), "destDir")
if err != nil {
return err
}
_, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks)
if err != nil {
return err
}
err = defaultTarUntar(srcDir, destDir)
if err != nil {
return err
}
changes, err := ChangesDirs(destDir, srcDir)
if err != nil {
return err
}
if len(changes) > 0 {
return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes))
}
return nil
}
func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) {
archive, err := TarWithOptions(origin, options)
if err != nil {
t.Fatal(err)
}
defer archive.Close()
buf := make([]byte, 10)
if _, err := io.ReadFull(archive, buf); err != nil {
return nil, err
}
wrap := io.MultiReader(bytes.NewReader(buf), archive)
detectedCompression := compression.Detect(buf)
expected := options.Compression
if detectedCompression.Extension() != expected.Extension() {
return nil, fmt.Errorf("wrong compression detected; expected: %s, got: %s", expected.Extension(), detectedCompression.Extension())
}
tmp := t.TempDir()
if err := Untar(wrap, tmp, nil); err != nil {
return nil, err
}
if _, err := os.Stat(tmp); err != nil {
return nil, err
}
return ChangesDirs(origin, tmp)
}
func TestTarUntar(t *testing.T) {
origin := t.TempDir()
if err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0o700); err != nil {
t.Fatal(err)
}
for _, c := range []compression.Compression{
compression.None,
compression.Gzip,
} {
changes, err := tarUntar(t, origin, &TarOptions{
Compression: c,
ExcludePatterns: []string{"3"},
})
if err != nil {
t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
}
if len(changes) != 1 || changes[0].Path != string(filepath.Separator)+"3" {
t.Fatalf("Unexpected differences after tarUntar: %v", changes)
}
}
}
func TestTarWithOptionsChownOptsAlwaysOverridesIdPair(t *testing.T) {
filePath := filepath.Join(t.TempDir(), "1")
err := os.WriteFile(filePath, []byte("hello world"), 0o700)
assert.NilError(t, err)
idMaps := []user.IDMap{
0: {
ID: 0,
ParentID: 0,
Count: 65536,
},
1: {
ID: 0,
ParentID: 100000,
Count: 65536,
},
}
tests := []struct {
opts *TarOptions
expectedUID int
expectedGID int
}{
{&TarOptions{ChownOpts: &ChownOpts{UID: 1337, GID: 42}}, 1337, 42},
{&TarOptions{ChownOpts: &ChownOpts{UID: 100001, GID: 100001}, IDMap: user.IdentityMapping{UIDMaps: idMaps, GIDMaps: idMaps}}, 100001, 100001},
{&TarOptions{ChownOpts: &ChownOpts{UID: 0, GID: 0}, NoLchown: false}, 0, 0},
{&TarOptions{ChownOpts: &ChownOpts{UID: 1, GID: 1}, NoLchown: true}, 1, 1},
{&TarOptions{ChownOpts: &ChownOpts{UID: 1000, GID: 1000}, NoLchown: true}, 1000, 1000},
}
for _, tc := range tests {
t.Run("", func(t *testing.T) {
reader, err := TarWithOptions(filePath, tc.opts)
assert.NilError(t, err)
tr := tar.NewReader(reader)
defer reader.Close()
for {
hdr, err := tr.Next()
if errors.Is(err, io.EOF) {
// end of tar archive
break
}
assert.NilError(t, err)
assert.Check(t, is.Equal(hdr.Uid, tc.expectedUID), "Uid equals expected value")
assert.Check(t, is.Equal(hdr.Gid, tc.expectedGID), "Gid equals expected value")
}
})
}
}
func TestTarWithOptions(t *testing.T) {
origin := t.TempDir()
if _, err := os.MkdirTemp(origin, "folder"); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0o700); err != nil {
t.Fatal(err)
}
tests := []struct {
opts *TarOptions
numChanges int
}{
{&TarOptions{IncludeFiles: []string{"1"}}, 2},
{&TarOptions{ExcludePatterns: []string{"2"}}, 1},
{&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2},
{&TarOptions{IncludeFiles: []string{"1", "1"}}, 2},
{&TarOptions{IncludeFiles: []string{"1"}, RebaseNames: map[string]string{"1": "test"}}, 4},
}
for _, tc := range tests {
changes, err := tarUntar(t, origin, tc.opts)
if err != nil {
t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err)
}
if len(changes) != tc.numChanges {
t.Errorf("Expected %d changes, got %d for %+v:",
tc.numChanges, len(changes), tc.opts)
}
}
}
// Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz
// use PAX Global Extended Headers.
// Failing prevents the archives from being uncompressed during ADD
func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) {
hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader}
tmpDir := t.TempDir()
err := createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, nil)
if err != nil {
t.Fatal(err)
}
}
// Some tar have both GNU specific (huge uid) and Ustar specific (long name) things.
// Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work.
func TestUntarUstarGnuConflict(t *testing.T) {
f, err := os.Open("testdata/broken.tar")
if err != nil {
t.Fatal(err)
}
defer f.Close()
found := false
tr := tar.NewReader(f)
// Iterate through the files in the archive.
for {
hdr, err := tr.Next()
if errors.Is(err, io.EOF) {
// end of tar archive
break
}
if err != nil {
t.Fatal(err)
}
if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" {
found = true
break
}
}
if !found {
t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm")
}
}
func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) {
fileData := []byte("fooo")
for n := 0; n < numberOfFiles; n++ {
fileName := fmt.Sprintf("file-%d", n)
if err := os.WriteFile(filepath.Join(targetPath, fileName), fileData, 0o700); err != nil {
return 0, err
}
if makeLinks {
if err := os.Link(filepath.Join(targetPath, fileName), filepath.Join(targetPath, fileName+"-link")); err != nil {
return 0, err
}
}
}
totalSize := numberOfFiles * len(fileData)
return totalSize, nil
}
func BenchmarkTarUntar(b *testing.B) {
origin, err := os.MkdirTemp(b.TempDir(), "docker-test-untar-origin")
if err != nil {
b.Fatal(err)
}
tempDir, err := os.MkdirTemp(b.TempDir(), "docker-test-untar-destination")
if err != nil {
b.Fatal(err)
}
target := filepath.Join(tempDir, "dest")
n, err := prepareUntarSourceDirectory(100, origin, false)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
b.SetBytes(int64(n))
for n := 0; n < b.N; n++ {
err := defaultTarUntar(origin, target)
if err != nil {
b.Fatal(err)
}
os.RemoveAll(target)
}
}
func BenchmarkTarUntarWithLinks(b *testing.B) {
origin, err := os.MkdirTemp(b.TempDir(), "docker-test-untar-origin")
if err != nil {
b.Fatal(err)
}
tempDir, err := os.MkdirTemp(b.TempDir(), "docker-test-untar-destination")
if err != nil {
b.Fatal(err)
}
target := filepath.Join(tempDir, "dest")
n, err := prepareUntarSourceDirectory(100, origin, true)
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
b.SetBytes(int64(n))
for n := 0; n < b.N; n++ {
err := defaultTarUntar(origin, target)
if err != nil {
b.Fatal(err)
}
os.RemoveAll(target)
}
}
func TestUntarInvalidFilenames(t *testing.T) {
for i, headers := range [][]*tar.Header{
{
{
Name: "../victim/dotdot",
Typeflag: tar.TypeReg,
Mode: 0o644,
},
},
{
{
// Note the leading slash
Name: "/../victim/slash-dotdot",
Typeflag: tar.TypeReg,
Mode: 0o644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestUntarHardlinkToSymlink(t *testing.T) {
skip.If(t, runtime.GOOS != "windows" && os.Getuid() != 0, "skipping test that requires root")
for i, headers := range [][]*tar.Header{
{
{
Name: "symlink1",
Typeflag: tar.TypeSymlink,
Linkname: "regfile",
Mode: 0o644,
},
{
Name: "symlink2",
Typeflag: tar.TypeLink,
Linkname: "symlink1",
Mode: 0o644,
},
{
Name: "regfile",
Typeflag: tar.TypeReg,
Mode: 0o644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarHardlinkToSymlink", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestUntarInvalidHardlink(t *testing.T) {
for i, headers := range [][]*tar.Header{
{ // try reading victim/hello (../)
{
Name: "dotdot",
Typeflag: tar.TypeLink,
Linkname: "../victim/hello",
Mode: 0o644,
},
},
{ // try reading victim/hello (/../)
{
Name: "slash-dotdot",
Typeflag: tar.TypeLink,
// Note the leading slash
Linkname: "/../victim/hello",
Mode: 0o644,
},
},
{ // try writing victim/file
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0o755,
},
{
Name: "loophole-victim/file",
Typeflag: tar.TypeReg,
Mode: 0o644,
},
},
{ // try reading victim/hello (hardlink, symlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0o755,
},
{
Name: "symlink",
Typeflag: tar.TypeSymlink,
Linkname: "loophole-victim/hello",
Mode: 0o644,
},
},
{ // Try reading victim/hello (hardlink, hardlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0o755,
},
{
Name: "hardlink",
Typeflag: tar.TypeLink,
Linkname: "loophole-victim/hello",
Mode: 0o644,
},
},
{ // Try removing victim directory (hardlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeLink,
Linkname: "../victim",
Mode: 0o755,
},
{
Name: "loophole-victim",
Typeflag: tar.TypeReg,
Mode: 0o644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestUntarInvalidSymlink(t *testing.T) {
for i, headers := range [][]*tar.Header{
{ // try reading victim/hello (../)
{
Name: "dotdot",
Typeflag: tar.TypeSymlink,
Linkname: "../victim/hello",
Mode: 0o644,
},
},
{ // try reading victim/hello (/../)
{
Name: "slash-dotdot",
Typeflag: tar.TypeSymlink,
// Note the leading slash
Linkname: "/../victim/hello",
Mode: 0o644,
},
},
{ // try writing victim/file
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0o755,
},
{
Name: "loophole-victim/file",
Typeflag: tar.TypeReg,
Mode: 0o644,
},
},
{ // try reading victim/hello (symlink, symlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0o755,
},
{
Name: "symlink",
Typeflag: tar.TypeSymlink,
Linkname: "loophole-victim/hello",
Mode: 0o644,
},
},
{ // try reading victim/hello (symlink, hardlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0o755,
},
{
Name: "hardlink",
Typeflag: tar.TypeLink,
Linkname: "loophole-victim/hello",
Mode: 0o644,
},
},
{ // try removing victim directory (symlink)
{
Name: "loophole-victim",
Typeflag: tar.TypeSymlink,
Linkname: "../victim",
Mode: 0o755,
},
{
Name: "loophole-victim",
Typeflag: tar.TypeReg,
Mode: 0o644,
},
},
{ // try writing to victim/newdir/newfile with a symlink in the path
{
// this header needs to be before the next one, or else there is an error
Name: "dir/loophole",
Typeflag: tar.TypeSymlink,
Linkname: "../../victim",
Mode: 0o755,
},
{
Name: "dir/loophole/newdir/newfile",
Typeflag: tar.TypeReg,
Mode: 0o644,
},
},
} {
if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil {
t.Fatalf("i=%d. %v", i, err)
}
}
}
func TestTempArchiveCloseMultipleTimes(t *testing.T) {
reader := io.NopCloser(strings.NewReader("hello"))
tmpArchive, err := newTempArchive(reader, "")
assert.NilError(t, err)
buf := make([]byte, 10)
n, err := tmpArchive.Read(buf)
assert.NilError(t, err)
if n != 5 {
t.Fatalf("Expected to read 5 bytes. Read %d instead", n)
}
for i := 0; i < 3; i++ {
if err = tmpArchive.Close(); err != nil {
t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err)
}
}
}
// TestXGlobalNoParent is a regression test to check parent directories are not created for PAX headers
func TestXGlobalNoParent(t *testing.T) {
buf := &bytes.Buffer{}
w := tar.NewWriter(buf)
err := w.WriteHeader(&tar.Header{
Name: "foo/bar",
Typeflag: tar.TypeXGlobalHeader,
})
assert.NilError(t, err)
tmpDir := t.TempDir()
err = Untar(buf, tmpDir, nil)
assert.NilError(t, err)
_, err = os.Lstat(filepath.Join(tmpDir, "foo"))
assert.Check(t, err != nil)
assert.Check(t, is.ErrorIs(err, os.ErrNotExist))
}
// TestImpliedDirectoryPermissions ensures that directories implied by paths in the tar file, but without their own
// header entries are created recursively with the default mode (permissions) stored in ImpliedDirectoryMode. This test
// also verifies that the permissions of explicit directories are respected.
func TestImpliedDirectoryPermissions(t *testing.T) {
skip.If(t, os.Getuid() != 0, "skipping test that requires root")
skip.If(t, runtime.GOOS == "windows", "skipping test that requires Unix permissions")
buf := &bytes.Buffer{}
headers := []tar.Header{{
Name: "deeply/nested/and/implied",
}, {
Name: "explicit/",
Mode: 0o644,
}, {
Name: "explicit/permissions/",
Mode: 0o600,
}, {
Name: "explicit/permissions/specified",
Mode: 0o400,
}}
w := tar.NewWriter(buf)
for _, header := range headers {
err := w.WriteHeader(&header)
assert.NilError(t, err)
}
tmpDir := t.TempDir()
err := Untar(buf, tmpDir, nil)
assert.NilError(t, err)
assertMode := func(path string, expected uint32) {
t.Helper()
stat, err := os.Lstat(filepath.Join(tmpDir, path))
assert.Check(t, err)
assert.Check(t, is.Equal(stat.Mode().Perm(), fs.FileMode(expected)))
}
assertMode("deeply", ImpliedDirectoryMode)
assertMode("deeply/nested", ImpliedDirectoryMode)
assertMode("deeply/nested/and", ImpliedDirectoryMode)
assertMode("explicit", 0o644)
assertMode("explicit/permissions", 0o600)