-
Notifications
You must be signed in to change notification settings - Fork 281
Expand file tree
/
Copy pathtestutil.go
More file actions
2369 lines (2221 loc) · 68.1 KB
/
testutil.go
File metadata and controls
2369 lines (2221 loc) · 68.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
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 The containerd Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Copyright 2019 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
package estargz
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/rand"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"time"
"github.com/containerd/stargz-snapshotter/estargz/errorutil"
"github.com/klauspost/compress/zstd"
digest "github.com/opencontainers/go-digest"
)
// TestingController is Compression with some helper methods necessary for testing.
type TestingController interface {
Compression
TestStreams(t *testing.T, b []byte, streams []int64)
DiffIDOf(*testing.T, []byte) string
String() string
}
// CompressionTestSuite tests this pkg with controllers can build valid eStargz blobs and parse them.
func CompressionTestSuite(t *testing.T, controllers ...TestingControllerFactory) {
t.Run("testBuild", func(t *testing.T) { t.Parallel(); testBuild(t, controllers...) })
t.Run("testDigestAndVerify", func(t *testing.T) { t.Parallel(); testDigestAndVerify(t, controllers...) })
t.Run("testWriteAndOpen", func(t *testing.T) { t.Parallel(); testWriteAndOpen(t, controllers...) })
}
type TestingControllerFactory func() TestingController
const (
uncompressedType int = iota
gzipType
zstdType
)
var srcCompressions = []int{
uncompressedType,
gzipType,
zstdType,
}
var allowedPrefix = [4]string{"", "./", "/", "../"}
// testBuild tests the resulting stargz blob built by this pkg has the same
// contents as the normal stargz blob.
func testBuild(t *testing.T, controllers ...TestingControllerFactory) {
tests := []struct {
name string
chunkSize int
minChunkSize []int
in []tarEntry
}{
{
name: "regfiles and directories",
chunkSize: 4,
in: tarOf(
file("foo", "test1"),
dir("foo2/"),
file("foo2/bar", "test2", xAttr(map[string]string{"test": "sample"})),
),
},
{
name: "empty files",
chunkSize: 4,
in: tarOf(
file("foo", "tttttt"),
file("foo_empty", ""),
file("foo2", "tttttt"),
file("foo_empty2", ""),
file("foo3", "tttttt"),
file("foo_empty3", ""),
file("foo4", "tttttt"),
file("foo_empty4", ""),
file("foo5", "tttttt"),
file("foo_empty5", ""),
file("foo6", "tttttt"),
),
},
{
name: "various files",
chunkSize: 4,
minChunkSize: []int{0, 64000},
in: tarOf(
file("baz.txt", "bazbazbazbazbazbazbaz"),
file("foo1.txt", "a"),
file("bar/foo2.txt", "b"),
file("foo3.txt", "c"),
symlink("barlink", "test/bar.txt"),
dir("test/"),
dir("dev/"),
blockdev("dev/testblock", 3, 4),
fifo("dev/testfifo"),
chardev("dev/testchar1", 5, 6),
file("test/bar.txt", "testbartestbar", xAttr(map[string]string{"test2": "sample2"})),
dir("test2/"),
link("test2/bazlink", "baz.txt"),
chardev("dev/testchar2", 1, 2),
),
},
{
name: "no contents",
chunkSize: 4,
in: tarOf(
file("baz.txt", ""),
symlink("barlink", "test/bar.txt"),
dir("test/"),
dir("dev/"),
blockdev("dev/testblock", 3, 4),
fifo("dev/testfifo"),
chardev("dev/testchar1", 5, 6),
file("test/bar.txt", "", xAttr(map[string]string{"test2": "sample2"})),
dir("test2/"),
link("test2/bazlink", "baz.txt"),
chardev("dev/testchar2", 1, 2),
),
},
}
for _, tt := range tests {
if len(tt.minChunkSize) == 0 {
tt.minChunkSize = []int{0}
}
for _, srcCompression := range srcCompressions {
srcCompression := srcCompression
for _, newCL := range controllers {
newCL := newCL
for _, srcTarFormat := range []tar.Format{tar.FormatUSTAR, tar.FormatPAX, tar.FormatGNU} {
srcTarFormat := srcTarFormat
for _, prefix := range allowedPrefix {
prefix := prefix
for _, minChunkSize := range tt.minChunkSize {
minChunkSize := minChunkSize
t.Run(tt.name+"-"+fmt.Sprintf("compression=%v,prefix=%q,src=%d,format=%s,minChunkSize=%d", newCL(), prefix, srcCompression, srcTarFormat, minChunkSize), func(t *testing.T) {
tarBlob := buildTar(t, tt.in, prefix, srcTarFormat)
// Test divideEntries()
entries, err := sortEntries(tarBlob, nil, nil) // identical order
if err != nil {
t.Fatalf("failed to parse tar: %v", err)
}
var merged []*entry
for _, part := range divideEntries(entries, 4) {
merged = append(merged, part...)
}
if !reflect.DeepEqual(entries, merged) {
for _, e := range entries {
t.Logf("Original: %v", e.header)
}
for _, e := range merged {
t.Logf("Merged: %v", e.header)
}
t.Errorf("divided entries couldn't be merged")
return
}
// Prepare sample data
cl1 := newCL()
wantBuf := new(bytes.Buffer)
sw := NewWriterWithCompressor(wantBuf, cl1)
sw.MinChunkSize = minChunkSize
sw.ChunkSize = tt.chunkSize
if err := sw.AppendTar(tarBlob); err != nil {
t.Fatalf("failed to append tar to want stargz: %v", err)
}
if _, err := sw.Close(); err != nil {
t.Fatalf("failed to prepare want stargz: %v", err)
}
wantData := wantBuf.Bytes()
want, err := Open(io.NewSectionReader(
bytes.NewReader(wantData), 0, int64(len(wantData))),
WithDecompressors(cl1),
)
if err != nil {
t.Fatalf("failed to parse the want stargz: %v", err)
}
// Prepare testing data
var opts []Option
if minChunkSize > 0 {
opts = append(opts, WithMinChunkSize(minChunkSize))
}
cl2 := newCL()
rc, err := Build(compressBlob(t, tarBlob, srcCompression),
append(opts, WithChunkSize(tt.chunkSize), WithCompression(cl2))...)
if err != nil {
t.Fatalf("failed to build stargz: %v", err)
}
defer rc.Close()
gotBuf := new(bytes.Buffer)
if _, err := io.Copy(gotBuf, rc); err != nil {
t.Fatalf("failed to copy built stargz blob: %v", err)
}
gotData := gotBuf.Bytes()
got, err := Open(io.NewSectionReader(
bytes.NewReader(gotBuf.Bytes()), 0, int64(len(gotData))),
WithDecompressors(cl2),
)
if err != nil {
t.Fatalf("failed to parse the got stargz: %v", err)
}
// Check DiffID is properly calculated
rc.Close()
diffID := rc.DiffID()
wantDiffID := cl2.DiffIDOf(t, gotData)
if diffID.String() != wantDiffID {
t.Errorf("DiffID = %q; want %q", diffID, wantDiffID)
}
// Compare as stargz
if !isSameVersion(t, cl1, wantData, cl2, gotData) {
t.Errorf("built stargz hasn't same json")
return
}
if !isSameEntries(t, want, got) {
t.Errorf("built stargz isn't same as the original")
return
}
// Compare as tar.gz
if !isSameTarGz(t, cl1, wantData, cl2, gotData) {
t.Errorf("built stargz isn't same tar.gz")
return
}
})
}
}
}
}
}
}
}
func isSameTarGz(t *testing.T, cla TestingController, a []byte, clb TestingController, b []byte) bool {
aGz, err := cla.Reader(bytes.NewReader(a))
if err != nil {
t.Fatalf("failed to read A")
}
defer aGz.Close()
bGz, err := clb.Reader(bytes.NewReader(b))
if err != nil {
t.Fatalf("failed to read B")
}
defer bGz.Close()
// Same as tar's Next() method but ignores landmarks and TOCJSON file
next := func(r *tar.Reader) (h *tar.Header, err error) {
for {
if h, err = r.Next(); err != nil {
return
}
if h.Name != PrefetchLandmark &&
h.Name != NoPrefetchLandmark &&
h.Name != TOCTarName {
return
}
}
}
aTar := tar.NewReader(aGz)
bTar := tar.NewReader(bGz)
for {
// Fetch and parse next header.
aH, aErr := next(aTar)
bH, bErr := next(bTar)
if aErr != nil || bErr != nil {
if aErr == io.EOF && bErr == io.EOF {
break
}
t.Fatalf("Failed to parse tar file: A: %v, B: %v", aErr, bErr)
}
if !reflect.DeepEqual(aH, bH) {
t.Logf("different header (A = %v; B = %v)", aH, bH)
return false
}
aFile, err := io.ReadAll(aTar)
if err != nil {
t.Fatal("failed to read tar payload of A")
}
bFile, err := io.ReadAll(bTar)
if err != nil {
t.Fatal("failed to read tar payload of B")
}
if !bytes.Equal(aFile, bFile) {
t.Logf("different tar payload (A = %q; B = %q)", string(a), string(b))
return false
}
}
return true
}
func isSameVersion(t *testing.T, cla TestingController, a []byte, clb TestingController, b []byte) bool {
aJTOC, _, err := parseStargz(io.NewSectionReader(bytes.NewReader(a), 0, int64(len(a))), cla)
if err != nil {
t.Fatalf("failed to parse A: %v", err)
}
bJTOC, _, err := parseStargz(io.NewSectionReader(bytes.NewReader(b), 0, int64(len(b))), clb)
if err != nil {
t.Fatalf("failed to parse B: %v", err)
}
t.Logf("A: TOCJSON: %v", dumpTOCJSON(t, aJTOC))
t.Logf("B: TOCJSON: %v", dumpTOCJSON(t, bJTOC))
return aJTOC.Version == bJTOC.Version
}
func isSameEntries(t *testing.T, a, b *Reader) bool {
aroot, ok := a.Lookup("")
if !ok {
t.Fatalf("failed to get root of A")
}
broot, ok := b.Lookup("")
if !ok {
t.Fatalf("failed to get root of B")
}
aEntry := stargzEntry{aroot, a}
bEntry := stargzEntry{broot, b}
return contains(t, aEntry, bEntry) && contains(t, bEntry, aEntry)
}
func compressBlob(t *testing.T, src *io.SectionReader, srcCompression int) *io.SectionReader {
buf := new(bytes.Buffer)
var w io.WriteCloser
var err error
if srcCompression == gzipType {
w = gzip.NewWriter(buf)
} else if srcCompression == zstdType {
w, err = zstd.NewWriter(buf)
if err != nil {
t.Fatalf("failed to init zstd writer: %v", err)
}
} else {
return src
}
src.Seek(0, io.SeekStart)
if _, err := io.Copy(w, src); err != nil {
t.Fatalf("failed to compress source")
}
if err := w.Close(); err != nil {
t.Fatalf("failed to finalize compress source")
}
data := buf.Bytes()
return io.NewSectionReader(bytes.NewReader(data), 0, int64(len(data)))
}
type stargzEntry struct {
e *TOCEntry
r *Reader
}
// contains checks if all child entries in "b" are also contained in "a".
// This function also checks if the files/chunks contain the same contents among "a" and "b".
func contains(t *testing.T, a, b stargzEntry) bool {
ae, ar := a.e, a.r
be, br := b.e, b.r
t.Logf("Comparing: %q vs %q", ae.Name, be.Name)
if !equalEntry(ae, be) {
t.Logf("%q != %q: entry: a: %v, b: %v", ae.Name, be.Name, ae, be)
return false
}
if ae.Type == "dir" {
t.Logf("Directory: %q vs %q: %v vs %v", ae.Name, be.Name,
allChildrenName(ae), allChildrenName(be))
iscontain := true
ae.ForeachChild(func(aBaseName string, aChild *TOCEntry) bool {
// Walk through all files on this stargz file.
if aChild.Name == PrefetchLandmark ||
aChild.Name == NoPrefetchLandmark {
return true // Ignore landmarks
}
// Ignore a TOCEntry of "./" (formated as "" by stargz lib) on root directory
// because this points to the root directory itself.
if aChild.Name == "" && ae.Name == "" {
return true
}
bChild, ok := be.LookupChild(aBaseName)
if !ok {
t.Logf("%q (base: %q): not found in b: %v",
ae.Name, aBaseName, allChildrenName(be))
iscontain = false
return false
}
childcontain := contains(t, stargzEntry{aChild, a.r}, stargzEntry{bChild, b.r})
if !childcontain {
t.Logf("%q != %q: non-equal dir", ae.Name, be.Name)
iscontain = false
return false
}
return true
})
return iscontain
} else if ae.Type == "reg" {
af, err := ar.OpenFile(ae.Name)
if err != nil {
t.Fatalf("failed to open file %q on A: %v", ae.Name, err)
}
bf, err := br.OpenFile(be.Name)
if err != nil {
t.Fatalf("failed to open file %q on B: %v", be.Name, err)
}
var nr int64
for nr < ae.Size {
abytes, anext, aok := readOffset(t, af, nr, a)
bbytes, bnext, bok := readOffset(t, bf, nr, b)
if !aok && !bok {
break
} else if !(aok && bok) || anext != bnext {
t.Logf("%q != %q (offset=%d): chunk existence a=%v vs b=%v, anext=%v vs bnext=%v",
ae.Name, be.Name, nr, aok, bok, anext, bnext)
return false
}
nr = anext
if !bytes.Equal(abytes, bbytes) {
t.Logf("%q != %q: different contents %v vs %v",
ae.Name, be.Name, string(abytes), string(bbytes))
return false
}
}
return true
}
return true
}
func allChildrenName(e *TOCEntry) (children []string) {
e.ForeachChild(func(baseName string, _ *TOCEntry) bool {
children = append(children, baseName)
return true
})
return
}
func equalEntry(a, b *TOCEntry) bool {
// Here, we selectively compare fileds that we are interested in.
return a.Name == b.Name &&
a.Type == b.Type &&
a.Size == b.Size &&
a.ModTime3339 == b.ModTime3339 &&
a.Stat().ModTime().Equal(b.Stat().ModTime()) && // modTime time.Time
a.LinkName == b.LinkName &&
a.Mode == b.Mode &&
a.UID == b.UID &&
a.GID == b.GID &&
a.Uname == b.Uname &&
a.Gname == b.Gname &&
(a.Offset >= 0) == (b.Offset >= 0) &&
(a.NextOffset() > 0) == (b.NextOffset() > 0) &&
a.DevMajor == b.DevMajor &&
a.DevMinor == b.DevMinor &&
a.NumLink == b.NumLink &&
reflect.DeepEqual(a.Xattrs, b.Xattrs) &&
// chunk-related infomations aren't compared in this function.
// ChunkOffset int64 `json:"chunkOffset,omitempty"`
// ChunkSize int64 `json:"chunkSize,omitempty"`
// children map[string]*TOCEntry
a.Digest == b.Digest
}
func readOffset(t *testing.T, r *io.SectionReader, offset int64, e stargzEntry) ([]byte, int64, bool) {
ce, ok := e.r.ChunkEntryForOffset(e.e.Name, offset)
if !ok {
return nil, 0, false
}
data := make([]byte, ce.ChunkSize)
t.Logf("Offset: %v, NextOffset: %v", ce.Offset, ce.NextOffset())
n, err := r.ReadAt(data, ce.ChunkOffset)
if err != nil {
t.Fatalf("failed to read file payload of %q (offset:%d,size:%d): %v",
e.e.Name, ce.ChunkOffset, ce.ChunkSize, err)
}
if int64(n) != ce.ChunkSize {
t.Fatalf("unexpected copied data size %d; want %d",
n, ce.ChunkSize)
}
return data[:n], offset + ce.ChunkSize, true
}
func dumpTOCJSON(t *testing.T, tocJSON *JTOC) string {
jtocData, err := json.Marshal(*tocJSON)
if err != nil {
t.Fatalf("failed to marshal TOC JSON: %v", err)
}
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, bytes.NewReader(jtocData)); err != nil {
t.Fatalf("failed to read toc json blob: %v", err)
}
return buf.String()
}
const chunkSize = 3
// type check func(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, compressionLevel int)
type check func(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory)
// testDigestAndVerify runs specified checks against sample stargz blobs.
func testDigestAndVerify(t *testing.T, controllers ...TestingControllerFactory) {
tests := []struct {
name string
tarInit func(t *testing.T, dgstMap map[string]digest.Digest) (blob []tarEntry)
checks []check
minChunkSize []int
}{
{
name: "no-regfile",
tarInit: func(t *testing.T, dgstMap map[string]digest.Digest) (blob []tarEntry) {
return tarOf(
dir("test/"),
)
},
checks: []check{
checkStargzTOC,
checkVerifyTOC,
checkVerifyInvalidStargzFail(buildTar(t, tarOf(
dir("test2/"), // modified
), allowedPrefix[0])),
},
},
{
name: "small-files",
tarInit: func(t *testing.T, dgstMap map[string]digest.Digest) (blob []tarEntry) {
return tarOf(
regDigest(t, "baz.txt", "", dgstMap),
regDigest(t, "foo.txt", "a", dgstMap),
dir("test/"),
regDigest(t, "test/bar.txt", "bbb", dgstMap),
)
},
minChunkSize: []int{0, 64000},
checks: []check{
checkStargzTOC,
checkVerifyTOC,
checkVerifyInvalidStargzFail(buildTar(t, tarOf(
file("baz.txt", ""),
file("foo.txt", "M"), // modified
dir("test/"),
file("test/bar.txt", "bbb"),
), allowedPrefix[0])),
// checkVerifyInvalidTOCEntryFail("foo.txt"), // TODO
checkVerifyBrokenContentFail("foo.txt"),
},
},
{
name: "big-files",
tarInit: func(t *testing.T, dgstMap map[string]digest.Digest) (blob []tarEntry) {
return tarOf(
regDigest(t, "baz.txt", "bazbazbazbazbazbazbaz", dgstMap),
regDigest(t, "foo.txt", "a", dgstMap),
dir("test/"),
regDigest(t, "test/bar.txt", "testbartestbar", dgstMap),
)
},
checks: []check{
checkStargzTOC,
checkVerifyTOC,
checkVerifyInvalidStargzFail(buildTar(t, tarOf(
file("baz.txt", "bazbazbazMMMbazbazbaz"), // modified
file("foo.txt", "a"),
dir("test/"),
file("test/bar.txt", "testbartestbar"),
), allowedPrefix[0])),
checkVerifyInvalidTOCEntryFail("test/bar.txt"),
checkVerifyBrokenContentFail("test/bar.txt"),
},
},
{
name: "with-non-regfiles",
minChunkSize: []int{0, 64000},
tarInit: func(t *testing.T, dgstMap map[string]digest.Digest) (blob []tarEntry) {
return tarOf(
regDigest(t, "baz.txt", "bazbazbazbazbazbazbaz", dgstMap),
regDigest(t, "foo.txt", "a", dgstMap),
regDigest(t, "bar/foo2.txt", "b", dgstMap),
regDigest(t, "foo3.txt", "c", dgstMap),
symlink("barlink", "test/bar.txt"),
dir("test/"),
regDigest(t, "test/bar.txt", "testbartestbar", dgstMap),
dir("test2/"),
link("test2/bazlink", "baz.txt"),
)
},
checks: []check{
checkStargzTOC,
checkVerifyTOC,
checkVerifyInvalidStargzFail(buildTar(t, tarOf(
file("baz.txt", "bazbazbazbazbazbazbaz"),
file("foo.txt", "a"),
file("bar/foo2.txt", "b"),
file("foo3.txt", "c"),
symlink("barlink", "test/bar.txt"),
dir("test/"),
file("test/bar.txt", "testbartestbar"),
dir("test2/"),
link("test2/bazlink", "foo.txt"), // modified
), allowedPrefix[0])),
checkVerifyInvalidTOCEntryFail("test/bar.txt"),
checkVerifyBrokenContentFail("test/bar.txt"),
},
},
}
for _, tt := range tests {
if len(tt.minChunkSize) == 0 {
tt.minChunkSize = []int{0}
}
for _, srcCompression := range srcCompressions {
srcCompression := srcCompression
for _, newCL := range controllers {
newCL := newCL
for _, prefix := range allowedPrefix {
prefix := prefix
for _, srcTarFormat := range []tar.Format{tar.FormatUSTAR, tar.FormatPAX, tar.FormatGNU} {
srcTarFormat := srcTarFormat
for _, minChunkSize := range tt.minChunkSize {
minChunkSize := minChunkSize
t.Run(tt.name+"-"+fmt.Sprintf("compression=%v,prefix=%q,format=%s,minChunkSize=%d", newCL(), prefix, srcTarFormat, minChunkSize), func(t *testing.T) {
// Get original tar file and chunk digests
dgstMap := make(map[string]digest.Digest)
tarBlob := buildTar(t, tt.tarInit(t, dgstMap), prefix, srcTarFormat)
cl := newCL()
rc, err := Build(compressBlob(t, tarBlob, srcCompression),
WithChunkSize(chunkSize), WithCompression(cl))
if err != nil {
t.Fatalf("failed to convert stargz: %v", err)
}
tocDigest := rc.TOCDigest()
defer rc.Close()
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, rc); err != nil {
t.Fatalf("failed to copy built stargz blob: %v", err)
}
newStargz := buf.Bytes()
// NoPrefetchLandmark is added during `Bulid`, which is expected behaviour.
dgstMap[chunkID(NoPrefetchLandmark, 0, int64(len([]byte{landmarkContents})))] = digest.FromBytes([]byte{landmarkContents})
for _, check := range tt.checks {
check(t, newStargz, tocDigest, dgstMap, cl, newCL)
}
})
}
}
}
}
}
}
}
// checkStargzTOC checks the TOC JSON of the passed stargz has the expected
// digest and contains valid chunks. It walks all entries in the stargz and
// checks all chunk digests stored to the TOC JSON match the actual contents.
func checkStargzTOC(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) {
sgz, err := Open(
io.NewSectionReader(bytes.NewReader(sgzData), 0, int64(len(sgzData))),
WithDecompressors(controller),
)
if err != nil {
t.Errorf("failed to parse converted stargz: %v", err)
return
}
digestMapTOC, err := listDigests(io.NewSectionReader(
bytes.NewReader(sgzData), 0, int64(len(sgzData))),
controller,
)
if err != nil {
t.Fatalf("failed to list digest: %v", err)
}
found := make(map[string]bool)
for id := range dgstMap {
found[id] = false
}
zr, err := controller.Reader(bytes.NewReader(sgzData))
if err != nil {
t.Fatalf("failed to decompress converted stargz: %v", err)
}
defer zr.Close()
tr := tar.NewReader(zr)
for {
h, err := tr.Next()
if err != nil {
if err != io.EOF {
t.Errorf("failed to read tar entry: %v", err)
return
}
break
}
if h.Name == TOCTarName {
// Check the digest of TOC JSON based on the actual contents
// It's sure that TOC JSON exists in this archive because
// Open succeeded.
dgstr := digest.Canonical.Digester()
if _, err := io.Copy(dgstr.Hash(), tr); err != nil {
t.Fatalf("failed to calculate digest of TOC JSON: %v",
err)
}
if dgstr.Digest() != tocDigest {
t.Errorf("invalid TOC JSON %q; want %q", tocDigest, dgstr.Digest())
}
continue
}
if _, ok := sgz.Lookup(h.Name); !ok {
t.Errorf("lost stargz entry %q in the converted TOC", h.Name)
return
}
var n int64
for n < h.Size {
ce, ok := sgz.ChunkEntryForOffset(h.Name, n)
if !ok {
t.Errorf("lost chunk %q(offset=%d) in the converted TOC",
h.Name, n)
return
}
// Get the original digest to make sure the file contents are kept unchanged
// from the original tar, during the whole conversion steps.
id := chunkID(h.Name, n, ce.ChunkSize)
want, ok := dgstMap[id]
if !ok {
t.Errorf("Unexpected chunk %q(offset=%d,size=%d): %v",
h.Name, n, ce.ChunkSize, dgstMap)
return
}
found[id] = true
// Check the file contents
dgstr := digest.Canonical.Digester()
if _, err := io.CopyN(dgstr.Hash(), tr, ce.ChunkSize); err != nil {
t.Fatalf("failed to calculate digest of %q (offset=%d,size=%d)",
h.Name, n, ce.ChunkSize)
}
if want != dgstr.Digest() {
t.Errorf("Invalid contents in converted stargz %q: %q; want %q",
h.Name, dgstr.Digest(), want)
return
}
// Check the digest stored in TOC JSON
dgstTOC, ok := digestMapTOC[ce.Offset]
if !ok {
t.Errorf("digest of %q(offset=%d,size=%d,chunkOffset=%d) isn't registered",
h.Name, ce.Offset, ce.ChunkSize, ce.ChunkOffset)
}
if want != dgstTOC {
t.Errorf("Invalid digest in TOCEntry %q: %q; want %q",
h.Name, dgstTOC, want)
return
}
n += ce.ChunkSize
}
}
for id, ok := range found {
if !ok {
t.Errorf("required chunk %q not found in the converted stargz: %v", id, found)
}
}
}
// checkVerifyTOC checks the verification works for the TOC JSON of the passed
// stargz. It walks all entries in the stargz and checks the verifications for
// all chunks work.
func checkVerifyTOC(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) {
sgz, err := Open(
io.NewSectionReader(bytes.NewReader(sgzData), 0, int64(len(sgzData))),
WithDecompressors(controller),
)
if err != nil {
t.Errorf("failed to parse converted stargz: %v", err)
return
}
ev, err := sgz.VerifyTOC(tocDigest)
if err != nil {
t.Errorf("failed to verify stargz: %v", err)
return
}
found := make(map[string]bool)
for id := range dgstMap {
found[id] = false
}
zr, err := controller.Reader(bytes.NewReader(sgzData))
if err != nil {
t.Fatalf("failed to decompress converted stargz: %v", err)
}
defer zr.Close()
tr := tar.NewReader(zr)
for {
h, err := tr.Next()
if err != nil {
if err != io.EOF {
t.Errorf("failed to read tar entry: %v", err)
return
}
break
}
if h.Name == TOCTarName {
continue
}
if _, ok := sgz.Lookup(h.Name); !ok {
t.Errorf("lost stargz entry %q in the converted TOC", h.Name)
return
}
var n int64
for n < h.Size {
ce, ok := sgz.ChunkEntryForOffset(h.Name, n)
if !ok {
t.Errorf("lost chunk %q(offset=%d) in the converted TOC",
h.Name, n)
return
}
v, err := ev.Verifier(ce)
if err != nil {
t.Errorf("failed to get verifier for %q(offset=%d)", h.Name, n)
}
found[chunkID(h.Name, n, ce.ChunkSize)] = true
// Check the file contents
if _, err := io.CopyN(v, tr, ce.ChunkSize); err != nil {
t.Fatalf("failed to get chunk of %q (offset=%d,size=%d)",
h.Name, n, ce.ChunkSize)
}
if !v.Verified() {
t.Errorf("Invalid contents in converted stargz %q (should be succeeded)",
h.Name)
return
}
n += ce.ChunkSize
}
}
for id, ok := range found {
if !ok {
t.Errorf("required chunk %q not found in the converted stargz: %v", id, found)
}
}
}
// checkVerifyInvalidTOCEntryFail checks if misconfigured TOC JSON can be
// detected during the verification and the verification returns an error.
func checkVerifyInvalidTOCEntryFail(filename string) check {
return func(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) {
funcs := map[string]rewriteFunc{
"lost digest in a entry": func(t *testing.T, toc *JTOC, sgz *io.SectionReader) {
var found bool
for _, e := range toc.Entries {
if cleanEntryName(e.Name) == filename {
if e.Type != "reg" && e.Type != "chunk" {
t.Fatalf("entry %q to break must be regfile or chunk", filename)
}
if e.ChunkDigest == "" {
t.Fatalf("entry %q is already invalid", filename)
}
e.ChunkDigest = ""
found = true
}
}
if !found {
t.Fatalf("rewrite target not found")
}
},
"duplicated entry offset": func(t *testing.T, toc *JTOC, sgz *io.SectionReader) {
var (
sampleEntry *TOCEntry
targetEntry *TOCEntry
)
for _, e := range toc.Entries {
if e.Type == "reg" || e.Type == "chunk" {
if cleanEntryName(e.Name) == filename {
targetEntry = e
} else {
sampleEntry = e
}
}
}
if sampleEntry == nil {
t.Fatalf("TOC must contain at least one regfile or chunk entry other than the rewrite target")
return
}
if targetEntry == nil {
t.Fatalf("rewrite target not found")
return
}
targetEntry.Offset = sampleEntry.Offset
},
}
for name, rFunc := range funcs {
t.Run(name, func(t *testing.T) {
newSgz, newTocDigest := rewriteTOCJSON(t, io.NewSectionReader(bytes.NewReader(sgzData), 0, int64(len(sgzData))), rFunc, controller)
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, newSgz); err != nil {
t.Fatalf("failed to get converted stargz")
}
isgz := buf.Bytes()
sgz, err := Open(
io.NewSectionReader(bytes.NewReader(isgz), 0, int64(len(isgz))),
WithDecompressors(controller),
)
if err != nil {
t.Fatalf("failed to parse converted stargz: %v", err)
return
}
_, err = sgz.VerifyTOC(newTocDigest)
if err == nil {
t.Errorf("must fail for invalid TOC")
return
}
})
}
}
}
// checkVerifyInvalidStargzFail checks if the verification detects that the
// given stargz file doesn't match to the expected digest and returns error.
func checkVerifyInvalidStargzFail(invalid *io.SectionReader) check {
return func(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) {
cl := newController()
rc, err := Build(invalid, WithChunkSize(chunkSize), WithCompression(cl))
if err != nil {
t.Fatalf("failed to convert stargz: %v", err)
}
defer rc.Close()
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, rc); err != nil {
t.Fatalf("failed to copy built stargz blob: %v", err)
}
mStargz := buf.Bytes()
sgz, err := Open(
io.NewSectionReader(bytes.NewReader(mStargz), 0, int64(len(mStargz))),
WithDecompressors(cl),
)
if err != nil {
t.Fatalf("failed to parse converted stargz: %v", err)
return
}
_, err = sgz.VerifyTOC(tocDigest)
if err == nil {
t.Errorf("must fail for invalid TOC")
return
}
}
}
// checkVerifyBrokenContentFail checks if the verifier detects broken contents
// that doesn't match to the expected digest and returns error.
func checkVerifyBrokenContentFail(filename string) check {
return func(t *testing.T, sgzData []byte, tocDigest digest.Digest, dgstMap map[string]digest.Digest, controller TestingController, newController TestingControllerFactory) {
// Parse stargz file
sgz, err := Open(
io.NewSectionReader(bytes.NewReader(sgzData), 0, int64(len(sgzData))),
WithDecompressors(controller),
)
if err != nil {
t.Fatalf("failed to parse converted stargz: %v", err)
return