-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhostapp_test.go
More file actions
1783 lines (1596 loc) · 58.2 KB
/
Copy pathhostapp_test.go
File metadata and controls
1783 lines (1596 loc) · 58.2 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 hostapp
import (
"bytes"
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"golang.org/x/sys/unix"
)
var rootdir = flag.String("rootdir", "", "Path to root directory with Docker/balena containers")
var repeatedLabelsCount = flag.Int("repLabels", 0, "Number of containers with the same repeated label")
// TestMountContainersByID tests mounting a container by its ID.
// This test requires root and performs an actual overlay mount.
func TestMountContainersByID(t *testing.T) {
if os.Getuid() != 0 {
t.Skip("requires root to perform overlay mount")
}
if *rootdir == "" {
t.Skip("This test requires a --rootdir flag")
}
// Create mount namespace for isolation
if err := unix.Unshare(unix.CLONE_NEWNS); err != nil {
t.Fatalf("failed to create mount namespace: %v", err)
}
if err := unix.Mount("", "/", "", unix.MS_PRIVATE|unix.MS_REC, ""); err != nil {
t.Fatalf("failed to make mounts private: %v", err)
}
current, err := os.Readlink(filepath.Join(*rootdir, "current"))
if err != nil {
t.Fatalf("Could not get container ID: %v", err)
}
cid := filepath.Base(current)
containers, err := Mount(*rootdir, cid)
if err != nil {
t.Fatalf("Mount by ID failed: %v", err)
}
if len(containers) != 1 {
t.Errorf("Expected 1 container, got %d", len(containers))
}
if len(containers) > 0 {
if containers[0].MountPath == "" {
t.Error("Container should have MountPath set")
}
// Verify we can read from the mounted filesystem
entries, err := os.ReadDir(containers[0].MountPath)
if err != nil {
t.Errorf("Failed to read mounted path: %v", err)
}
if len(entries) == 0 {
t.Error("Mounted filesystem appears empty")
}
t.Logf("Mounted %s at %s with %d entries", containers[0].Name, containers[0].MountPath, len(entries))
}
}
// TestMountContainersByLabel tests mounting containers by label.
func TestMountContainersByLabel(t *testing.T) {
if os.Getuid() != 0 {
t.Skip("requires root to perform overlay mount")
}
if *rootdir == "" {
t.Skip("This test requires a --rootdir flag")
}
if *repeatedLabelsCount == 0 {
t.Skip("This test requires a --repLabels flag")
}
// Create mount namespace for isolation
if err := unix.Unshare(unix.CLONE_NEWNS); err != nil {
t.Fatalf("failed to create mount namespace: %v", err)
}
if err := unix.Mount("", "/", "", unix.MS_PRIVATE|unix.MS_REC, ""); err != nil {
t.Fatalf("failed to make mounts private: %v", err)
}
// Create symlink for testing
linkRootDir := "/tmp/testlink"
os.Remove(linkRootDir)
if err := os.Symlink(*rootdir, linkRootDir); err != nil {
t.Fatalf("error creating rootdir symlink: %v", err)
}
defer os.Remove(linkRootDir)
// Create temp file for testing invalid path
fileRootDir, err := os.CreateTemp("", "testHostAppFile")
if err != nil {
t.Fatal("Unable to create temporary file")
}
defer os.Remove(fileRootDir.Name())
var tests = []struct {
name string
rootdir string
label string
expectFailure bool
expectCount int
}{
{"non-existent path", "/does/not/exist", "None", true, 0},
{"symlinked rootdir", linkRootDir, "unique-label", false, 1},
{"file as rootdir", fileRootDir.Name(), "None", true, 0},
{"unique label", *rootdir, "unique-label", false, 1},
{"nonsense label", *rootdir, "nonsense", false, 0},
{"repeated label", *rootdir, "repeated-label", false, *repeatedLabelsCount},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
containers, err := Mount(test.rootdir, test.label)
if test.expectFailure && err == nil {
t.Errorf("Test should have failed")
}
if !test.expectFailure && err != nil {
t.Errorf("Test should have passed: %v", err)
}
if !test.expectFailure && len(containers) != test.expectCount {
t.Errorf("Expected %d containers, got %d", test.expectCount, len(containers))
}
// Verify mounted containers have MountPath set
for _, c := range containers {
if c.MountPath == "" {
t.Errorf("Container %s should have MountPath set", c.Name)
}
}
})
}
}
// TestMountRealHostapp tests mounting an actual balena hostapp container.
func TestMountRealHostapp(t *testing.T) {
if os.Getuid() != 0 {
t.Skip("requires root to perform overlay mount")
}
if *rootdir == "" {
t.Skip("This test requires a --rootdir flag")
}
// Create mount namespace for isolation
if err := unix.Unshare(unix.CLONE_NEWNS); err != nil {
t.Fatalf("failed to create mount namespace: %v", err)
}
if err := unix.Mount("", "/", "", unix.MS_PRIVATE|unix.MS_REC, ""); err != nil {
t.Fatalf("failed to make mounts private: %v", err)
}
// Check for hostapp-current symlink (created by setup script for real hostapp)
hostappCurrent := filepath.Join(*rootdir, "hostapp-current")
current, err := os.Readlink(hostappCurrent)
if err != nil {
t.Skip("No real hostapp available (hostapp-current symlink missing)")
}
cid := filepath.Base(current)
containers, err := Mount(*rootdir, cid)
if err != nil {
t.Fatalf("Mount real hostapp failed: %v", err)
}
if len(containers) != 1 {
t.Fatalf("Expected 1 container, got %d", len(containers))
}
container := containers[0]
if container.MountPath == "" {
t.Error("Real hostapp should have MountPath set")
}
// Verify the mounted filesystem looks like a root filesystem
entries, err := os.ReadDir(container.MountPath)
if err != nil {
t.Fatalf("Failed to read mounted path: %v", err)
}
// Check for expected root filesystem directories
entryNames := make(map[string]bool)
for _, e := range entries {
entryNames[e.Name()] = true
}
expectedDirs := []string{"bin", "etc", "usr"}
for _, dir := range expectedDirs {
if !entryNames[dir] {
t.Errorf("Expected /%s in mounted hostapp", dir)
}
}
t.Logf("Real hostapp %s mounted at %s with %d entries", container.Name, container.MountPath, len(entries))
}
// TestMountOSBlocksByLabel tests finding and mounting containers with io.balena.image.class=overlay.
func TestMountOSBlocksByLabel(t *testing.T) {
if os.Getuid() != 0 {
t.Skip("requires root to perform overlay mount")
}
if *rootdir == "" {
t.Skip("This test requires a --rootdir flag")
}
// Create mount namespace for isolation
if err := unix.Unshare(unix.CLONE_NEWNS); err != nil {
t.Fatalf("failed to create mount namespace: %v", err)
}
if err := unix.Mount("", "/", "", unix.MS_PRIVATE|unix.MS_REC, ""); err != nil {
t.Fatalf("failed to make mounts private: %v", err)
}
containers, err := Mount(*rootdir, "io.balena.image.class")
if err != nil {
t.Fatalf("Mount OS blocks failed: %v", err)
}
if len(containers) == 0 {
t.Skip("No OS block containers available")
}
t.Logf("Found %d OS block containers", len(containers))
for _, c := range containers {
if c.Labels["io.balena.image.class"] != "overlay" {
t.Errorf("Container %s missing io.balena.image.class=overlay label", c.Name)
}
if c.MountPath == "" {
t.Errorf("Container %s should have MountPath set", c.Name)
}
if c.Driver != "overlay2" {
t.Errorf("Container %s has unexpected driver: %s", c.Name, c.Driver)
}
}
}
// TestMountVerifiesOverlayWorks is the critical integration test.
// It verifies the kernel accepts our overlay mount by actually performing it.
func TestMountVerifiesOverlayWorks(t *testing.T) {
if os.Getuid() != 0 {
t.Skip("requires root to perform overlay mount")
}
if *rootdir == "" {
t.Skip("This test requires a --rootdir flag")
}
// Create mount namespace for isolation
if err := unix.Unshare(unix.CLONE_NEWNS); err != nil {
t.Fatalf("failed to create mount namespace: %v", err)
}
if err := unix.Mount("", "/", "", unix.MS_PRIVATE|unix.MS_REC, ""); err != nil {
t.Fatalf("failed to make mounts private: %v", err)
}
// Get the hostapp container
hostappCurrent := filepath.Join(*rootdir, "current")
current, err := os.Readlink(hostappCurrent)
if err != nil {
hostappCurrent = filepath.Join(*rootdir, "hostapp-current")
current, err = os.Readlink(hostappCurrent)
if err != nil {
t.Skip("No hostapp available (current/hostapp-current symlink missing)")
}
}
cid := filepath.Base(current)
// Mount() performs the actual overlay mount - this catches layer issues!
containers, err := Mount(*rootdir, cid)
if err != nil {
t.Fatalf("Mount failed (overlay mount rejected by kernel): %v", err)
}
if len(containers) == 0 {
t.Fatal("No containers found")
}
container := containers[0]
if container.MountPath == "" {
t.Fatal("Container has no MountPath - mount may have failed silently")
}
// Verify we can actually read from the overlay
entries, err := os.ReadDir(container.MountPath)
if err != nil {
t.Fatalf("Failed to read from overlay mount: %v", err)
}
if len(entries) == 0 {
t.Error("Overlay mount appears empty - may indicate mount failure")
}
t.Logf("Overlay mount verified: %s at %s with %d entries", container.Name, container.MountPath, len(entries))
}
// fakeOverlay2Layer creates an overlay2 layer directory <overlay2Dir>/<id>
// with a diff/ subdir, a link file naming its short id, and the matching
// l/<short> -> ../<id>/diff symlink the engine maintains. It returns the
// short id so callers can wire up lower chains.
func fakeOverlay2Layer(t *testing.T, overlay2Dir, id, short string) string {
t.Helper()
layerDir := filepath.Join(overlay2Dir, id)
if err := os.MkdirAll(filepath.Join(layerDir, "diff"), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(layerDir, "link"), []byte(short), 0644); err != nil {
t.Fatal(err)
}
lDir := filepath.Join(overlay2Dir, "l")
if err := os.MkdirAll(lDir, 0755); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join("..", id, "diff"), filepath.Join(lDir, short)); err != nil {
t.Fatal(err)
}
return short
}
// TestBuildLowerDirs verifies the lowerdir list references every layer by the
// engine's compact overlay2/l/<short> symlink rather than the resolved
// overlay2/<64-hex>/diff path.
func TestBuildLowerDirs(t *testing.T) {
overlay2Dir := t.TempDir()
topID := strings.Repeat("a", 64)
parentID := strings.Repeat("b", 64)
initID := strings.Repeat("c", 64)
fakeOverlay2Layer(t, overlay2Dir, topID, "TOPSHORTLINKAAAAAAAAAAAAAA")
fakeOverlay2Layer(t, overlay2Dir, parentID, "PARENTSHORTLINKBBBBBBBBBBB")
// The init layer's directory carries the -init suffix; its short link
// target is what classifies it, without resolving the full path.
fakeOverlay2Layer(t, overlay2Dir, initID+"-init", "INITSHORTLINKCCCCCCCCCCCCC")
topLayerDir := filepath.Join(overlay2Dir, topID)
// lower lists the immediate parent (the init layer) first, then image layers.
lower := "l/INITSHORTLINKCCCCCCCCCCCCC:l/PARENTSHORTLINKBBBBBBBBBBB"
if err := os.WriteFile(filepath.Join(topLayerDir, "lower"), []byte(lower), 0644); err != nil {
t.Fatal(err)
}
got, err := buildLowerDirs(overlay2Dir, topLayerDir)
if err != nil {
t.Fatalf("buildLowerDirs: %v", err)
}
want := []string{
filepath.Join(overlay2Dir, "l", "TOPSHORTLINKAAAAAAAAAAAAAA"),
filepath.Join(overlay2Dir, "l", "PARENTSHORTLINKBBBBBBBBBBB"),
}
if !reflect.DeepEqual(got, want) {
t.Errorf("buildLowerDirs = %v, want %v", got, want)
}
// The compact form must not carry any resolved /diff path: that is the
// whole point of the page-budget fix.
for _, d := range got {
if strings.HasSuffix(d, "/diff") {
t.Errorf("lowerdir %q is a resolved diff path, expected compact l/<short> form", d)
}
}
}
// TestBuildLowerDirsSingleLayer covers an image with no lower file (one layer):
// only the top layer's compact reference is returned.
func TestBuildLowerDirsSingleLayer(t *testing.T) {
overlay2Dir := t.TempDir()
topID := strings.Repeat("a", 64)
fakeOverlay2Layer(t, overlay2Dir, topID, "TOPSHORTLINKAAAAAAAAAAAAAA")
got, err := buildLowerDirs(overlay2Dir, filepath.Join(overlay2Dir, topID))
if err != nil {
t.Fatalf("buildLowerDirs: %v", err)
}
want := []string{filepath.Join(overlay2Dir, "l", "TOPSHORTLINKAAAAAAAAAAAAAA")}
if !reflect.DeepEqual(got, want) {
t.Errorf("buildLowerDirs = %v, want %v", got, want)
}
}
// TestBuildLowerDirsMountsUnderKernel proves the kernel accepts the compact
// l/<short> symlink lowerdir that buildLowerDirs produces.
func TestBuildLowerDirsMountsUnderKernel(t *testing.T) {
if os.Getuid() != 0 {
t.Skip("requires root (or unshare -rm) to perform overlay mount")
}
runtime.LockOSThread()
defer runtime.UnlockOSThread()
if err := unix.Unshare(unix.CLONE_NEWNS); err != nil {
t.Fatalf("unshare: %v", err)
}
if err := unix.Mount("", "/", "", unix.MS_PRIVATE|unix.MS_REC, ""); err != nil {
t.Fatalf("make mounts private: %v", err)
}
overlay2Dir := t.TempDir()
topID := strings.Repeat("a", 64)
parentID := strings.Repeat("b", 64)
initID := strings.Repeat("c", 64)
fakeOverlay2Layer(t, overlay2Dir, topID, "TOPSHORTLINKAAAAAAAAAAAAAA")
fakeOverlay2Layer(t, overlay2Dir, parentID, "PARENTSHORTLINKBBBBBBBBBBB")
fakeOverlay2Layer(t, overlay2Dir, initID+"-init", "INITSHORTLINKCCCCCCCCCCCCC")
// Distinct content per layer so the merged view proves each was stacked.
write := func(id, name, content string) {
if err := os.WriteFile(filepath.Join(overlay2Dir, id, "diff", name), []byte(content), 0644); err != nil {
t.Fatal(err)
}
}
write(topID, "top.txt", "from-top")
write(parentID, "parent.txt", "from-parent")
// The init layer ships a file that must NOT appear: it is dropped.
write(initID+"-init", ".dockerenv", "")
topLayerDir := filepath.Join(overlay2Dir, topID)
lower := "l/INITSHORTLINKCCCCCCCCCCCCC:l/PARENTSHORTLINKBBBBBBBBBBB"
if err := os.WriteFile(filepath.Join(topLayerDir, "lower"), []byte(lower), 0644); err != nil {
t.Fatal(err)
}
lowerDirs, err := buildLowerDirs(overlay2Dir, topLayerDir)
if err != nil {
t.Fatalf("buildLowerDirs: %v", err)
}
mnt := t.TempDir()
opts := "lowerdir=" + strings.Join(lowerDirs, ":")
if err := unix.Mount("overlay", mnt, "overlay", 0, opts); err != nil {
t.Fatalf("overlay mount rejected by kernel with compact symlink lowerdir %q: %v", opts, err)
}
defer unix.Unmount(mnt, unix.MNT_DETACH)
for name, want := range map[string]string{"top.txt": "from-top", "parent.txt": "from-parent"} {
got, err := os.ReadFile(filepath.Join(mnt, name))
if err != nil {
t.Errorf("reading %s from merged overlay: %v", name, err)
continue
}
if string(got) != want {
t.Errorf("%s = %q, want %q", name, got, want)
}
}
// The init layer was dropped, so its .dockerenv must not surface.
if _, err := os.Lstat(filepath.Join(mnt, ".dockerenv")); !os.IsNotExist(err) {
t.Errorf(".dockerenv leaked from init layer into merged overlay (err=%v)", err)
}
}
// TestBuildOverlayOptions tests the flat mount options string construction.
func TestBuildOverlayOptions(t *testing.T) {
tests := []struct {
name string
baseLayers []string
leftExtensions []Extension
rightExtensions []Extension
expected string
}{
{
name: "base only",
baseLayers: []string{"/b1", "/b2"},
expected: "lowerdir=/b1:/b2",
},
{
name: "rights only",
baseLayers: []string{"/base"},
rightExtensions: []Extension{
{Layers: []string{"/n1a", "/n1b"}, Name: "right1"},
{Layers: []string{"/n2"}, Name: "right2"},
},
expected: "lowerdir=/base:/n1a:/n1b:/n2",
},
{
name: "single left multi-layer",
baseLayers: []string{"/base"},
leftExtensions: []Extension{
{Layers: []string{"/o1a", "/o1b"}, Name: "left1", Priority: 10},
},
expected: "lowerdir=/o1a:/o1b:/base",
},
{
name: "left sorting",
baseLayers: []string{"/base"},
leftExtensions: []Extension{
{Layers: []string{"/o2"}, Name: "left2", Priority: 50},
{Layers: []string{"/o1"}, Name: "left1", Priority: 10},
},
expected: "lowerdir=/o1:/o2:/base",
},
{
name: "equal priority tie-break by name",
baseLayers: []string{"/base"},
leftExtensions: []Extension{
{Layers: []string{"/zz"}, Name: "zulu", Priority: 10},
{Layers: []string{"/aa"}, Name: "alpha", Priority: 10},
},
expected: "lowerdir=/aa:/zz:/base",
},
{
name: "both sides",
baseLayers: []string{"/base"},
leftExtensions: []Extension{
{Layers: []string{"/o1"}, Name: "left1", Priority: 10},
},
rightExtensions: []Extension{
{Layers: []string{"/n1"}, Name: "right1"},
{Layers: []string{"/n2"}, Name: "right2"},
},
expected: "lowerdir=/o1:/base:/n1:/n2",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := BuildOverlayOptions(tt.baseLayers, tt.leftExtensions, tt.rightExtensions)
if result != tt.expected {
t.Errorf("expected %q, got %q", tt.expected, result)
}
})
}
}
// TestBuildOverlayOptionsTruncation verifies page-size behavior: extensions
// are dropped as WHOLE chains (a partial chain would compose a partial
// image), rights before lefts, and the base chain is always present.
func TestBuildOverlayOptionsTruncation(t *testing.T) {
pageSize := os.Getpagesize()
baseLayers := []string{"/" + strings.Repeat("b", pageSize/3)}
left := Extension{
Layers: []string{"/" + strings.Repeat("o", pageSize/3)},
Name: "left",
Priority: 10,
}
rightLong := Extension{
Layers: []string{"/" + strings.Repeat("n", pageSize/3)},
Name: "right",
}
result := BuildOverlayOptions(baseLayers, []Extension{left}, []Extension{rightLong})
if !strings.Contains(result, left.Layers[0]) {
t.Error("left extension chain missing from result")
}
if !strings.Contains(result, baseLayers[0]) {
t.Error("base chain missing from result")
}
if strings.Contains(result, rightLong.Layers[0]) {
t.Error("right extension should have been dropped due to page size limit")
}
if len(result) >= pageSize-1 {
t.Errorf("result length %d exceeds page size limit %d", len(result), pageSize-1)
}
// A left extension whose chain does not fit is dropped whole, base stays.
hugeLeft := Extension{
Layers: []string{"/" + strings.Repeat("x", pageSize)},
Name: "huge",
Priority: 1,
}
degraded := BuildOverlayOptions([]string{"/base"}, []Extension{hugeLeft}, nil)
if degraded != "lowerdir=/base" {
t.Errorf("expected bare base chain, got %q", degraded)
}
// Whole-chain semantics: an extension with two layers where only the
// first would fit must contribute NEITHER layer.
half := pageSize / 2
twoLayer := Extension{
Layers: []string{"/" + strings.Repeat("p", half/4), "/" + strings.Repeat("q", half)},
Name: "two-layer",
Priority: 1,
}
partial := BuildOverlayOptions([]string{"/" + strings.Repeat("z", half)}, []Extension{twoLayer}, nil)
if strings.Contains(partial, twoLayer.Layers[0]) || strings.Contains(partial, twoLayer.Layers[1]) {
t.Errorf("partially-fitting chain must be dropped whole, got %q", partial)
}
// Rights are dropped before lefts.
bigLeft := Extension{
Layers: []string{"/" + strings.Repeat("o", pageSize/2)},
Name: "big-left",
Priority: 1,
}
mediumBase := []string{"/" + strings.Repeat("b", pageSize/4)}
rightExt := Extension{
Layers: []string{"/" + strings.Repeat("n", pageSize/4)},
Name: "right",
}
mixed := BuildOverlayOptions(mediumBase, []Extension{bigLeft}, []Extension{rightExt})
if !strings.Contains(mixed, bigLeft.Layers[0]) {
t.Error("left extension should be present")
}
if !strings.Contains(mixed, mediumBase[0]) {
t.Error("base chain must always be present")
}
if strings.Contains(mixed, rightExt.Layers[0]) {
t.Error("right extension should have been dropped since left + base already near limit")
}
}
// TestOverlayStacking tests overlay stacking with checksum verification.
// It verifies that:
// 1. All files from hostapp and OS blocks appear in the stacked mount
// 2. File checksums match their fingerprints
// 3. No unexpected files appear in the stacked mount
func TestOverlayStacking(t *testing.T) {
if os.Getuid() != 0 {
t.Skip("requires root to perform overlay mount")
}
if *rootdir == "" {
t.Skip("This test requires a --rootdir flag")
}
// Create mount namespace for isolation
if err := unix.Unshare(unix.CLONE_NEWNS); err != nil {
t.Fatalf("failed to create mount namespace: %v", err)
}
if err := unix.Mount("", "/", "", unix.MS_PRIVATE|unix.MS_REC, ""); err != nil {
t.Fatalf("failed to make mounts private: %v", err)
}
// Step 1: Mount fingerprinted hostapp container
hostappCurrent := filepath.Join(*rootdir, "fingerprint-current")
current, err := os.Readlink(hostappCurrent)
if err != nil {
t.Skip("No fingerprinted hostapp available (fingerprint-current symlink missing)")
}
cid := filepath.Base(current)
hostappContainers, err := Mount(*rootdir, cid)
if err != nil {
t.Fatalf("Mount hostapp failed: %v", err)
}
if len(hostappContainers) != 1 {
t.Fatalf("Expected 1 hostapp container, got %d", len(hostappContainers))
}
hostappPath := hostappContainers[0].MountPath
t.Logf("Fingerprinted hostapp mounted at %s", hostappPath)
// Step 2: Mount OS block containers
osBlocks, err := Mount(*rootdir, "io.balena.image.class")
if err != nil {
t.Fatalf("Mount OS blocks failed: %v", err)
}
if len(osBlocks) == 0 {
t.Skip("No OS block containers available")
}
t.Logf("Found %d OS block containers", len(osBlocks))
// Step 3: Create stacked overlay mount
stackedMount := t.TempDir()
rightExtensions := make([]Extension, len(osBlocks))
for i, c := range osBlocks {
rightExtensions[i] = Extension{Name: c.Name, Layers: c.Layers}
t.Logf("OS block %d: %s at %s", i, c.Name, c.MountPath)
}
opts := BuildOverlayOptions(hostappContainers[0].Layers, nil, rightExtensions)
t.Logf("Mount options: %s", opts)
if err := unix.Mount("overlay", stackedMount, "overlay", 0, opts); err != nil {
t.Fatalf("Stacked overlay mount failed: %v", err)
}
defer unix.Unmount(stackedMount, unix.MNT_DETACH)
// Step 4: Load all fingerprints and build expected checksums map
// In overlay fs, lowerdir=A:B:C means A is topmost (takes precedence).
// Our mount is: lowerdir=hostapp:osblock1:osblock2:osblock3
// So precedence is: hostapp > osblock1 > osblock2 > osblock3
// Load in reverse order so higher precedence layers overwrite lower ones.
expectedChecksums := make(map[string]string) // path -> md5sum
// Load OS block fingerprints in reverse order (lowest precedence first)
for i := len(osBlocks); i >= 1; i-- {
fp := filepath.Join(stackedMount, fmt.Sprintf(".fingerprint-osblock-%d", i))
countBefore := len(expectedChecksums)
if err := loadFingerprint(fp, expectedChecksums); err != nil {
t.Fatalf("Failed to load OS block %d fingerprint: %v", i, err)
}
t.Logf("Loaded OS block %d fingerprint with %d new files (total: %d)", i, len(expectedChecksums)-countBefore, len(expectedChecksums))
}
// Load hostapp fingerprint last (highest precedence - will overwrite duplicates)
hostappFingerprint := filepath.Join(stackedMount, ".fingerprint-hostapp")
countBefore := len(expectedChecksums)
if err := loadFingerprint(hostappFingerprint, expectedChecksums); err != nil {
t.Fatalf("Failed to load hostapp fingerprint: %v", err)
}
t.Logf("Loaded hostapp fingerprint with %d new files (total: %d)", len(expectedChecksums)-countBefore, len(expectedChecksums))
// Step 5: Verify all fingerprinted files exist and have correct checksums
// Skip broken symlinks (absolute symlinks pointing outside the mount)
checksumErrors := 0
skippedFiles := 0
verifiedFiles := 0
for relPath, expectedMD5 := range expectedChecksums {
actualPath := filepath.Join(stackedMount, relPath)
actualMD5, err := computeMD5(actualPath)
if err != nil {
// Skip broken symlinks silently
skippedFiles++
continue
}
verifiedFiles++
if actualMD5 != expectedMD5 {
t.Errorf("Checksum mismatch for %s: expected %s, got %s", relPath, expectedMD5, actualMD5)
checksumErrors++
}
}
t.Logf("Verified %d files, skipped %d broken symlinks, %d errors", verifiedFiles, skippedFiles, checksumErrors)
// Step 6: Check for unexpected files (not in any fingerprint)
// Skip broken symlinks and fingerprint files
unexpectedFiles := []string{}
err = filepath.Walk(stackedMount, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil // Skip broken symlinks and unreadable paths
}
if info.IsDir() {
return nil
}
if info.Mode()&os.ModeSymlink != 0 {
return nil // Skip symlinks
}
// Get path relative to mount (without leading slash to match fingerprint format)
relPath := strings.TrimPrefix(strings.TrimPrefix(path, stackedMount), "/")
// Skip fingerprint files themselves
if strings.HasPrefix(relPath, ".fingerprint-") {
return nil
}
if _, ok := expectedChecksums[relPath]; !ok {
unexpectedFiles = append(unexpectedFiles, relPath)
}
return nil
})
if err != nil {
t.Fatalf("Failed to walk stacked mount: %v", err)
}
if len(unexpectedFiles) > 0 {
t.Errorf("Found %d unexpected files not in any fingerprint:", len(unexpectedFiles))
for _, f := range unexpectedFiles {
t.Errorf(" - %s", f)
}
}
if checksumErrors > 0 {
t.Fatalf("Overlay stacking failed: %d checksum errors", checksumErrors)
}
// Step 7: Verify .dockerenv does not exist (would cause systemd to think it's in a container)
dockerenvPath := filepath.Join(stackedMount, ".dockerenv")
if _, err := os.Lstat(dockerenvPath); err == nil {
t.Errorf(".dockerenv exists in stacked mount - this will cause systemd to detect container mode")
} else if !os.IsNotExist(err) {
t.Errorf("Error checking .dockerenv: %v", err)
}
t.Logf("Overlay stacking verified: %d files, %d skipped, %d unexpected",
verifiedFiles, skippedFiles, len(unexpectedFiles))
}
// TestNoDockerenvInOverlay verifies that .dockerenv does not exist in container mounts.
// Docker creates .dockerenv when containers are created (docker create/run), which
// causes systemd to detect container mode and skip hardware initialization.
func TestNoDockerenvInOverlay(t *testing.T) {
if os.Getuid() != 0 {
t.Skip("requires root to perform overlay mount")
}
if *rootdir == "" {
t.Skip("This test requires a --rootdir flag")
}
// Create mount namespace for isolation
if err := unix.Unshare(unix.CLONE_NEWNS); err != nil {
t.Fatalf("failed to create mount namespace: %v", err)
}
if err := unix.Mount("", "/", "", unix.MS_PRIVATE|unix.MS_REC, ""); err != nil {
t.Fatalf("failed to make mounts private: %v", err)
}
// Mount hostapp container
hostappCurrent := filepath.Join(*rootdir, "current")
current, err := os.Readlink(hostappCurrent)
if err != nil {
t.Skip("No hostapp available (current symlink missing)")
}
cid := filepath.Base(current)
containers, err := Mount(*rootdir, cid)
if err != nil {
t.Fatalf("Mount hostapp failed: %v", err)
}
if len(containers) != 1 {
t.Fatalf("Expected 1 container, got %d", len(containers))
}
// Check hostapp for .dockerenv
dockerenvPath := filepath.Join(containers[0].MountPath, ".dockerenv")
if _, err := os.Lstat(dockerenvPath); err == nil {
t.Errorf("Hostapp container has .dockerenv at %s - this will cause systemd to detect container mode", dockerenvPath)
}
// Mount and check OS block containers
osBlocks, err := Mount(*rootdir, "io.balena.image.class")
if err != nil {
t.Logf("No OS blocks to check: %v", err)
return
}
for _, c := range osBlocks {
dockerenvPath := filepath.Join(c.MountPath, ".dockerenv")
if _, err := os.Lstat(dockerenvPath); err == nil {
t.Errorf("OS block %s has .dockerenv at %s - this will cause systemd to detect container mode", c.Name, dockerenvPath)
}
}
}
// loadFingerprint reads a fingerprint file and adds entries to the checksums map.
// Fingerprint format: "md5sum /path/to/file" (standard md5sum output)
// Paths are stored without leading slash to allow proper path joining.
func loadFingerprint(path string, checksums map[string]string) error {
content, err := os.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// md5sum output format: "checksum filename" (two spaces)
parts := strings.SplitN(line, " ", 2)
if len(parts) != 2 {
continue
}
md5sum := parts[0]
filePath := strings.TrimPrefix(parts[1], "/") // Remove leading slash for proper joining
checksums[filePath] = md5sum
}
return nil
}
// computeMD5 calculates the MD5 checksum of a file
func computeMD5(path string) (string, error) {
content, err := os.ReadFile(path)
if err != nil {
return "", err
}
sum := md5.Sum(content)
return fmt.Sprintf("%x", sum), nil
}
// makeTestContainer builds a Container for table-driven filter tests.
func makeTestContainer(name string, labels map[string]string) Container {
return Container{
Config: Config{
HostConfig: HostConfig{Labels: labels},
Name: name,
},
}
}
func TestGetKernelRelease(t *testing.T) {
release, err := GetKernelRelease()
if err != nil {
t.Fatalf("GetKernelRelease failed: %v", err)
}
if release == "" {
t.Fatal("expected non-empty release")
}
if strings.ContainsRune(release, 0) {
t.Errorf("release contains NUL byte: %q", release)
}
}
func TestKernelVersionFromRelease(t *testing.T) {
tests := []struct {
release string
want string
}{
{"6.8.0-100-generic", "6.8.0"},
{"6.1.0-v8+", "6.1.0"},
{"5.15.0", "5.15.0"},
{"", ""},
}
for _, tt := range tests {
if got := kernelVersionFromRelease(tt.release); got != tt.want {
t.Errorf("kernelVersionFromRelease(%q) = %q, want %q", tt.release, got, tt.want)
}
}
}
func TestFilterByKernelVersion(t *testing.T) {
tests := []struct {
name string
containers []Container
kernelVersion string
expectNames []string
}{
{
name: "no label passes through",
containers: []Container{
makeTestContainer("no-label", map[string]string{"io.balena.image.class": "overlay"}),
},
kernelVersion: "6.1.0",
expectNames: []string{"no-label"},
},
{
name: "matching label passes",
containers: []Container{
makeTestContainer("match", map[string]string{HOSTOS_BLOCKS_KERNEL_VERSION: "6.1.0"}),
},
kernelVersion: "6.1.0",
expectNames: []string{"match"},
},
{
name: "mismatched label filtered",
containers: []Container{
makeTestContainer("old", map[string]string{HOSTOS_BLOCKS_KERNEL_VERSION: "5.15.0"}),
},
kernelVersion: "6.1.0",
expectNames: nil,
},
{
name: "mixed: keep matching and unlabelled, skip mismatched",
containers: []Container{
makeTestContainer("match", map[string]string{HOSTOS_BLOCKS_KERNEL_VERSION: "6.1.0"}),
makeTestContainer("old", map[string]string{HOSTOS_BLOCKS_KERNEL_VERSION: "5.15.0"}),
makeTestContainer("unlabelled", map[string]string{"io.balena.image.class": "overlay"}),
},
kernelVersion: "6.1.0",
expectNames: []string{"match", "unlabelled"},
},
{
name: "empty kernel version passes all",
containers: []Container{
makeTestContainer("a", map[string]string{HOSTOS_BLOCKS_KERNEL_VERSION: "6.1.0"}),
makeTestContainer("b", map[string]string{HOSTOS_BLOCKS_KERNEL_VERSION: "5.15.0"}),
},
kernelVersion: "",
expectNames: []string{"a", "b"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := FilterByKernelVersion(tt.containers, tt.kernelVersion)
var gotNames []string
for _, c := range result {
gotNames = append(gotNames, c.Name)
}
if !reflect.DeepEqual(gotNames, tt.expectNames) {
t.Errorf("expected %v, got %v", tt.expectNames, gotNames)
}
})
}
}
func TestComputeABIID(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "Module.symvers")
content := []byte("0xdeadbeef\tsome_symbol\tvmlinux\tEXPORT_SYMBOL\n")
if err := os.WriteFile(path, content, 0644); err != nil {
t.Fatalf("writing fixture: %v", err)
}
expected := sha256.Sum256(content)