-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration_test.go
More file actions
1084 lines (912 loc) · 41.4 KB
/
integration_test.go
File metadata and controls
1084 lines (912 loc) · 41.4 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 main_test
import (
"CodeSandboxAPI/config"
"CodeSandboxAPI/resourcemanager"
"CodeSandboxAPI/routes"
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/gin-gonic/gin"
)
const sampleCodeDir = "sample_code_for_tests"
type simpleExecuteRequest struct {
Language string `json:"language"`
Code string `json:"code"`
Timeout uint `json:"timeout,omitempty"`
MaxMemory uint `json:"max_memory,omitempty"`
Inputs []string `json:"inputs,omitempty"`
}
type simpleExecuteResponse struct {
Output string `json:"output"`
Error string `json:"error"`
MemoryUsed string `json:"memory_used"`
CPUTime string `json:"cpu_time"`
}
type integrationHarness struct {
baseURL string
apiPort int
}
var (
testServer *httptest.Server
httpClient = &http.Client{Timeout: 30 * time.Second}
)
func TestMain(m *testing.M) {
enforceRootAndCompiler()
gin.SetMode(gin.ReleaseMode)
router := gin.New()
routes.Setup(router)
testServer = httptest.NewServer(router)
exitCode := m.Run()
testServer.Close()
os.Exit(exitCode)
}
func enforceRootAndCompiler() {
if os.Geteuid() != 0 {
fmt.Fprintln(os.Stderr, "integration tests must run as root (sudo go test -v)")
os.Exit(1)
}
if _, err := exec.LookPath("gcc"); err != nil {
fmt.Fprintf(os.Stderr, "gcc is required for integration tests: %v\n", err)
os.Exit(1)
}
}
func TestContainerizationAPISecurityIntegration(t *testing.T) {
h := integrationHarness{baseURL: testServer.URL}
h.apiPort = mustExtractPort(t, h.baseURL)
cases := []struct {
name string
run func(*testing.T, integrationHarness)
}{
{name: "file privacy across request IDs", run: testFilesystemIsolation},
{name: "disk spammer is terminated and data is reclaimed", run: testDiskCleanup},
{name: "fork bomb does not poison subsequent requests", run: testForkBombContainment},
{name: "network namespace blocks localhost bridge", run: testNetworkIsolation},
{name: "memory hard limit triggers oom kill", run: testMemoryHardLimit},
{name: "io flood is bounded and returns before timeout", run: testIOFloodResilience},
{name: "signal trap cannot survive forced timeout", run: testSignalTrapTimeout},
{name: "orphan grandchild is reaped after request exits", run: testOrphanReaping},
{name: "inode bomb does not poison host temp filesystem", run: testInodeExhaustion},
{name: "privileged reboot syscall is denied", run: testPrivilegedSyscallDenied},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) { tc.run(t, h) })
}
}
func TestContainerizationAPISecurityIntegrationPython3(t *testing.T) {
h := integrationHarness{baseURL: testServer.URL}
h.apiPort = mustExtractPort(t, h.baseURL)
cases := []struct {
name string
run func(*testing.T, integrationHarness)
}{
{name: "file privacy across request IDs", run: testFilesystemIsolationPython3},
{name: "disk spammer is terminated and data is reclaimed", run: testDiskCleanupPython3},
{name: "fork bomb does not poison subsequent requests", run: testForkBombContainmentPython3},
{name: "network namespace blocks localhost bridge", run: testNetworkIsolationPython3},
{name: "memory hard limit triggers oom kill", run: testMemoryHardLimitPython3},
{name: "io flood is bounded and returns before timeout", run: testIOFloodResiliencePython3},
{name: "signal trap cannot survive forced timeout", run: testSignalTrapTimeoutPython3},
{name: "orphan grandchild is reaped after request exits", run: testOrphanReapingPython3},
{name: "inode bomb does not poison host temp filesystem", run: testInodeExhaustionPython3},
{name: "privileged reboot syscall is denied", run: testPrivilegedSyscallDeniedPython3},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) { tc.run(t, h) })
}
}
func TestContainerizationAPISecurityIntegrationCpp(t *testing.T) {
h := integrationHarness{baseURL: testServer.URL}
h.apiPort = mustExtractPort(t, h.baseURL)
runLanguageMirrorSuite(t, h, "cpp", "cpp")
}
func TestContainerizationAPISecurityIntegrationJava(t *testing.T) {
h := integrationHarness{baseURL: testServer.URL}
h.apiPort = mustExtractPort(t, h.baseURL)
runLanguageMirrorSuite(t, h, "java", "java")
}
func TestSandboxHardeningC(t *testing.T) {
h := integrationHarness{baseURL: testServer.URL}
h.apiPort = mustExtractPort(t, h.baseURL)
runSandboxHardeningSuite(t, h, "c", "c")
}
func TestSandboxHardeningPython3(t *testing.T) {
h := integrationHarness{baseURL: testServer.URL}
h.apiPort = mustExtractPort(t, h.baseURL)
runSandboxHardeningSuite(t, h, "python3", "py")
}
func TestOverloadedRejectsHalfRequestsUnderLoad(t *testing.T) {
baseURL := startOverloadLoadTestServer(t)
req := buildLanguageRequest("python", "import time;time.sleep(2)", 5, 131072)
requestCount := 10
results := runConcurrentSimpleExecuteRequests(baseURL, req, requestCount)
overloaded := 0
for i, result := range results {
if result.err != nil {
t.Fatalf("request %d failed unexpectedly: %v", i, result.err)
}
if result.response.Error == "Server is overloaded, please try again later" {
overloaded++
}
}
maxConcurrent := int(config.Config.Globals.RAM_LIMIT / req.MaxMemory)
if maxConcurrent > requestCount {
maxConcurrent = requestCount
}
expectedOverloaded := requestCount - maxConcurrent
if overloaded != expectedOverloaded {
t.Fatalf("expected exactly %d overloaded responses, got %d", expectedOverloaded, overloaded)
}
}
func runLanguageMirrorSuite(t *testing.T, h integrationHarness, language, ext string) {
t.Helper()
cases := []struct {
name string
run func(*testing.T, integrationHarness)
}{
{name: "file privacy across request IDs", run: func(t *testing.T, h integrationHarness) {
testFilesystemIsolationForLanguage(t, h, language, "file_privacy_write_read."+ext, "file_privacy_read_only."+ext)
}},
{name: "disk spammer is terminated and data is reclaimed", run: func(t *testing.T, h integrationHarness) {
testDiskCleanupForLanguage(t, h, language, "disk_spammer."+ext)
}},
{name: "fork bomb does not poison subsequent requests", run: func(t *testing.T, h integrationHarness) {
testForkBombContainmentForLanguage(t, h, language, "fork_bomb."+ext, "hello_world."+ext)
}},
{name: "network namespace blocks localhost bridge", run: func(t *testing.T, h integrationHarness) {
testNetworkIsolationForLanguage(t, h, language, "network_localhost_bridge."+ext)
}},
{name: "memory hard limit triggers oom kill", run: func(t *testing.T, h integrationHarness) {
testMemoryHardLimitForLanguage(t, h, language, "memory_bomb."+ext)
}},
{name: "io flood is bounded and returns before timeout", run: func(t *testing.T, h integrationHarness) {
testIOFloodResilienceForLanguage(t, h, language, "io_spam."+ext)
}},
{name: "signal trap cannot survive forced timeout", run: func(t *testing.T, h integrationHarness) {
testSignalTrapTimeoutForLanguage(t, h, language, "signal_trap."+ext)
}},
{name: "orphan grandchild is reaped after request exits", run: func(t *testing.T, h integrationHarness) {
name := "orphanmakergc"
if language == "python3" {
name = "orphanpygc"
}
if language == "java" {
name = "orphanjavagc"
}
testOrphanReapingForLanguage(t, h, language, "orphan_maker."+ext, name)
}},
{name: "inode bomb does not poison host temp filesystem", run: func(t *testing.T, h integrationHarness) {
testInodeExhaustionForLanguage(t, h, language, "inode_bomb."+ext)
}},
{name: "privileged reboot syscall is denied", run: func(t *testing.T, h integrationHarness) {
testPrivilegedSyscallDeniedForLanguage(t, h, language, "try_reboot."+ext)
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) { tc.run(t, h) })
}
}
func runSandboxHardeningSuite(t *testing.T, h integrationHarness, language, ext string) {
t.Helper()
cases := []struct {
name string
run func(*testing.T, integrationHarness)
}{
{name: "sandbox cannot write to host /etc/passwd", run: func(t *testing.T, h integrationHarness) {
testSandboxCannotWriteHostEtcPasswd(t, h, language, "etc_write_denied."+ext)
}},
{name: "remounting /etc read-write is denied", run: func(t *testing.T, h integrationHarness) {
testRemountingEtcReadWriteDenied(t, h, language, "remount_etc_rw_denied."+ext)
}},
{name: "sandbox process uid is not host root", run: func(t *testing.T, h integrationHarness) {
testSandboxProcessUIDIsNotHostRoot(t, h, language, "not_host_root."+ext)
}},
{name: "dangerous syscalls are blocked by seccomp", run: func(t *testing.T, h integrationHarness) {
testDangerousSyscallsBlockedBySeccomp(t, h, language, "dangerous_syscalls_seccomp."+ext)
}},
{name: "sandbox environment does not expose host", run: func(t *testing.T, h integrationHarness) {
testSandboxEnvironmentDoesNotExposeHost(t, h, language, "env_leak_probe."+ext)
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) { tc.run(t, h) })
}
}
func testFilesystemIsolation(t *testing.T, h integrationHarness) {
writeCode := mustLoadSampleCode(t, "file_privacy_write_read.c", nil)
writeResp := callSimpleExecute(t, h.baseURL, buildCRequest(writeCode, 4, 32768))
if !strings.Contains(writeResp.Output, "SecretData123") {
t.Fatalf("step A did not return secret in stdout; stdout=%q stderr=%q", writeResp.Output, writeResp.Error)
}
readCode := mustLoadSampleCode(t, "file_privacy_read_only.c", nil)
readResp := callSimpleExecute(t, h.baseURL, buildCRequest(readCode, 4, 32768))
if !strings.Contains(strings.ToLower(readResp.Error), "no such file or directory") {
t.Fatalf("step B unexpectedly accessed file from another sandbox; stdout=%q stderr=%q", readResp.Output, readResp.Error)
}
}
func testDiskCleanup(t *testing.T, h integrationHarness) {
beforeFree := mustFreeBytes(t, os.TempDir())
beforeCount := countSandboxTempDirs(t)
code := mustLoadSampleCode(t, "disk_spammer.c", nil)
resp := callSimpleExecute(t, h.baseURL, buildCRequest(code, 2, 32768))
stderrLower := strings.ToLower(resp.Error)
if !containsAny(stderrLower, []string{"execution timed out", "memory limit exceeded"}) {
t.Fatalf("disk spammer was not terminated as expected; stdout=%q stderr=%q", resp.Output, resp.Error)
}
time.Sleep(400 * time.Millisecond)
assertDiskReclaimed(t, beforeFree, mustFreeBytes(t, os.TempDir()))
assertNoSandboxLeak(t, beforeCount, countSandboxTempDirs(t))
}
func assertDiskReclaimed(t *testing.T, beforeFree, afterFree uint64) {
const maxResidual = uint64(20 * 1024 * 1024)
if beforeFree > afterFree && (beforeFree-afterFree) > maxResidual {
t.Fatalf("sandbox disk garbage appears to persist: free space dropped by %d bytes", beforeFree-afterFree)
}
}
func assertNoSandboxLeak(t *testing.T, beforeCount, afterCount int) {
if afterCount > beforeCount {
t.Fatalf("sandbox temp directories leaked: before=%d after=%d", beforeCount, afterCount)
}
}
func testForkBombContainment(t *testing.T, h integrationHarness) {
bombCode := mustLoadSampleCode(t, "fork_bomb.c", nil)
_ = callSimpleExecute(t, h.baseURL, buildCRequest(bombCode, 2, 32768))
helloCode := mustLoadSampleCode(t, "hello_world.c", nil)
helloResp := callSimpleExecute(t, h.baseURL, buildCRequest(helloCode, 4, 32768))
if !strings.Contains(helloResp.Output, "Hello World") {
t.Fatalf("follow-up request failed after fork bomb; stdout=%q stderr=%q", helloResp.Output, helloResp.Error)
}
if strings.Contains(strings.ToLower(helloResp.Error), "resource temporarily unavailable") {
t.Fatalf("follow-up request indicates host PID exhaustion; stderr=%q", helloResp.Error)
}
}
func testNetworkIsolation(t *testing.T, h integrationHarness) {
replacements := map[string]string{"__API_PORT__": strconv.Itoa(h.apiPort)}
code := mustLoadSampleCode(t, "network_localhost_bridge.c", replacements)
resp := callSimpleExecute(t, h.baseURL, buildCRequest(code, 3, 32768))
combined := strings.ToLower(resp.Output + "\n" + resp.Error)
if strings.Contains(combined, "connected") {
t.Fatalf("localhost bridge unexpectedly succeeded; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if !containsAny(combined, []string{"connection refused", "network is unreachable", "no route to host"}) {
t.Fatalf("network isolation did not produce expected connect error; stdout=%q stderr=%q", resp.Output, resp.Error)
}
}
func testMemoryHardLimit(t *testing.T, h integrationHarness) {
code := mustLoadSampleCode(t, "memory_bomb.c", nil)
resp := callSimpleExecute(t, h.baseURL, buildCRequest(code, 3, 16384))
if !containsAny(strings.ToLower(resp.Error), []string{"memory limit exceeded", "killed", "execution timed out"}) {
t.Fatalf("memory bomb did not terminate as expected; stdout=%q stderr=%q", resp.Output, resp.Error)
}
execDur, err := time.ParseDuration(resp.CPUTime)
if err != nil {
t.Fatalf("failed to parse cpu_time %q: %v", resp.CPUTime, err)
}
if execDur > 500*time.Millisecond {
t.Fatalf("memory enforcement was too slow: cpu_time=%s stderr=%q", resp.CPUTime, resp.Error)
}
}
func testIOFloodResilience(t *testing.T, h integrationHarness) {
code := mustLoadSampleCode(t, "io_spam.c", nil)
resp := callSimpleExecute(t, h.baseURL, buildCRequest(code, 1, 32768))
stderrLower := strings.ToLower(resp.Error)
if !containsAny(stderrLower, []string{"execution timed out", "killed", "memory limit exceeded"}) {
t.Fatalf("io flood did not terminate with expected error; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if strings.TrimSpace(resp.Error) == "" {
t.Fatalf("io flood returned empty stderr; expected bounded but non-empty error output")
}
const maxErrorBytes = (1 << 20) + 4096
if len(resp.Error) > maxErrorBytes {
t.Fatalf("stderr exceeded resilience cap: got=%d bytes cap=%d", len(resp.Error), maxErrorBytes)
}
assertDurationNotExcessive(t, resp.CPUTime, 3*time.Second, "io flood request")
}
func testSignalTrapTimeout(t *testing.T, h integrationHarness) {
code := mustLoadSampleCode(t, "signal_trap.c", nil)
resp := callSimpleExecute(t, h.baseURL, buildCRequest(code, 1, 32768))
if !strings.Contains(strings.ToLower(resp.Error), "execution timed out") {
t.Fatalf("signal trap did not timeout as expected; stdout=%q stderr=%q", resp.Output, resp.Error)
}
assertDurationWindow(t, resp.CPUTime, 900*time.Millisecond, 2500*time.Millisecond, "signal trap timeout")
}
func testOrphanReaping(t *testing.T, h integrationHarness) {
code := mustLoadSampleCode(t, "orphan_maker.c", nil)
resp := callSimpleExecute(t, h.baseURL, buildCRequest(code, 2, 32768))
assertDurationNotExcessive(t, resp.CPUTime, 3*time.Second, "orphan maker request")
time.Sleep(400 * time.Millisecond)
if cnt := countProcessesByComm(t, "orphanmakergc"); cnt > 0 {
t.Fatalf("orphan grandchild leaked to host after request completion: count=%d stderr=%q", cnt, resp.Error)
}
}
func testInodeExhaustion(t *testing.T, h integrationHarness) {
beforeFree := mustFreeBytes(t, os.TempDir())
beforeCount := countSandboxTempDirs(t)
code := mustLoadSampleCode(t, "inode_bomb.c", nil)
resp := callSimpleExecute(t, h.baseURL, buildCRequest(code, 4, 32768))
combinedLower := strings.ToLower(resp.Output + "\n" + resp.Error)
if !containsAny(combinedLower, []string{"inode bomb completed", "no space left", "disk quota exceeded"}) {
t.Fatalf("inode exhaustion test produced unexpected result; stdout=%q stderr=%q", resp.Output, resp.Error)
}
time.Sleep(400 * time.Millisecond)
assertDiskReclaimed(t, beforeFree, mustFreeBytes(t, os.TempDir()))
assertNoSandboxLeak(t, beforeCount, countSandboxTempDirs(t))
mustCreateAndDeleteTempFile(t)
}
func testPrivilegedSyscallDenied(t *testing.T, h integrationHarness) {
code := mustLoadSampleCode(t, "try_reboot.c", nil)
resp := callSimpleExecute(t, h.baseURL, buildCRequest(code, 3, 32768))
assertDurationNotExcessive(t, resp.CPUTime, 3*time.Second, "privileged reboot syscall")
combinedLower := strings.ToLower(resp.Output + "\n" + resp.Error)
if strings.Contains(combinedLower, "reboot succeeded unexpectedly") {
t.Fatalf("privileged reboot syscall unexpectedly succeeded; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if !containsAny(combinedLower, []string{"operation not permitted", "permission denied", "bad system call", "killed", "hangup"}) {
t.Fatalf("expected privileged syscall denial signal was not observed; stdout=%q stderr=%q", resp.Output, resp.Error)
}
}
func testFilesystemIsolationPython3(t *testing.T, h integrationHarness) {
writeCode := mustLoadSampleCode(t, "file_privacy_write_read.py", nil)
writeResp := callSimpleExecute(t, h.baseURL, buildPython3Request(writeCode, 4, 32768))
if !strings.Contains(writeResp.Output, "SecretData123") {
t.Fatalf("step A did not return secret in stdout; stdout=%q stderr=%q", writeResp.Output, writeResp.Error)
}
readCode := mustLoadSampleCode(t, "file_privacy_read_only.py", nil)
readResp := callSimpleExecute(t, h.baseURL, buildPython3Request(readCode, 4, 32768))
if !strings.Contains(strings.ToLower(readResp.Error), "no such file or directory") {
t.Fatalf("step B unexpectedly accessed file from another sandbox; stdout=%q stderr=%q", readResp.Output, readResp.Error)
}
}
func testDiskCleanupPython3(t *testing.T, h integrationHarness) {
beforeFree := mustFreeBytes(t, os.TempDir())
beforeCount := countSandboxTempDirs(t)
code := mustLoadSampleCode(t, "disk_spammer.py", nil)
resp := callSimpleExecute(t, h.baseURL, buildPython3Request(code, 2, 32768))
stderrLower := strings.ToLower(resp.Error)
if !containsAny(stderrLower, []string{"execution timed out", "memory limit exceeded"}) {
t.Fatalf("disk spammer was not terminated as expected; stdout=%q stderr=%q", resp.Output, resp.Error)
}
time.Sleep(400 * time.Millisecond)
assertDiskReclaimed(t, beforeFree, mustFreeBytes(t, os.TempDir()))
assertNoSandboxLeak(t, beforeCount, countSandboxTempDirs(t))
}
func testForkBombContainmentPython3(t *testing.T, h integrationHarness) {
bombCode := mustLoadSampleCode(t, "fork_bomb.py", nil)
_ = callSimpleExecute(t, h.baseURL, buildPython3Request(bombCode, 2, 32768))
helloCode := mustLoadSampleCode(t, "hello_world.py", nil)
helloResp := callSimpleExecute(t, h.baseURL, buildPython3Request(helloCode, 4, 32768))
if !strings.Contains(helloResp.Output, "Hello World") {
t.Fatalf("follow-up request failed after fork bomb; stdout=%q stderr=%q", helloResp.Output, helloResp.Error)
}
if strings.Contains(strings.ToLower(helloResp.Error), "resource temporarily unavailable") {
t.Fatalf("follow-up request indicates host PID exhaustion; stderr=%q", helloResp.Error)
}
}
func testNetworkIsolationPython3(t *testing.T, h integrationHarness) {
replacements := map[string]string{"__API_PORT__": strconv.Itoa(h.apiPort)}
code := mustLoadSampleCode(t, "network_localhost_bridge.py", replacements)
resp := callSimpleExecute(t, h.baseURL, buildPython3Request(code, 3, 32768))
combined := strings.ToLower(resp.Output + "\n" + resp.Error)
if strings.Contains(combined, "connected") {
t.Fatalf("localhost bridge unexpectedly succeeded; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if !containsAny(combined, []string{"connection refused", "network is unreachable", "no route to host"}) {
t.Fatalf("network isolation did not produce expected connect error; stdout=%q stderr=%q", resp.Output, resp.Error)
}
}
func testMemoryHardLimitPython3(t *testing.T, h integrationHarness) {
code := mustLoadSampleCode(t, "memory_bomb.py", nil)
resp := callSimpleExecute(t, h.baseURL, buildPython3Request(code, 3, 16384))
if !containsAny(strings.ToLower(resp.Error), []string{"memory limit exceeded", "killed", "execution timed out"}) {
t.Fatalf("memory bomb did not terminate as expected; stdout=%q stderr=%q", resp.Output, resp.Error)
}
execDur, err := time.ParseDuration(resp.CPUTime)
if err != nil {
t.Fatalf("failed to parse cpu_time %q: %v", resp.CPUTime, err)
}
if execDur > 500*time.Millisecond {
t.Fatalf("memory enforcement was too slow: cpu_time=%s stderr=%q", resp.CPUTime, resp.Error)
}
}
func testIOFloodResiliencePython3(t *testing.T, h integrationHarness) {
code := mustLoadSampleCode(t, "io_spam.py", nil)
resp := callSimpleExecute(t, h.baseURL, buildPython3Request(code, 1, 32768))
stderrLower := strings.ToLower(resp.Error)
if !containsAny(stderrLower, []string{"execution timed out", "killed", "memory limit exceeded"}) {
t.Fatalf("io flood did not terminate with expected error; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if strings.TrimSpace(resp.Error) == "" {
t.Fatalf("io flood returned empty stderr; expected bounded but non-empty error output")
}
const maxErrorBytes = (1 << 20) + 4096
if len(resp.Error) > maxErrorBytes {
t.Fatalf("stderr exceeded resilience cap: got=%d bytes cap=%d", len(resp.Error), maxErrorBytes)
}
assertDurationNotExcessive(t, resp.CPUTime, 3*time.Second, "io flood request")
}
func testSignalTrapTimeoutPython3(t *testing.T, h integrationHarness) {
code := mustLoadSampleCode(t, "signal_trap.py", nil)
resp := callSimpleExecute(t, h.baseURL, buildPython3Request(code, 1, 32768))
if !strings.Contains(strings.ToLower(resp.Error), "execution timed out") {
t.Fatalf("signal trap did not timeout as expected; stdout=%q stderr=%q", resp.Output, resp.Error)
}
assertDurationWindow(t, resp.CPUTime, 900*time.Millisecond, 2500*time.Millisecond, "signal trap timeout")
}
func testOrphanReapingPython3(t *testing.T, h integrationHarness) {
code := mustLoadSampleCode(t, "orphan_maker.py", nil)
resp := callSimpleExecute(t, h.baseURL, buildPython3Request(code, 2, 32768))
assertDurationNotExcessive(t, resp.CPUTime, 3*time.Second, "orphan maker request")
time.Sleep(400 * time.Millisecond)
if cnt := countProcessesByComm(t, "orphanpygc"); cnt > 0 {
t.Fatalf("orphan grandchild leaked to host after request completion: count=%d stderr=%q", cnt, resp.Error)
}
}
func testInodeExhaustionPython3(t *testing.T, h integrationHarness) {
beforeFree := mustFreeBytes(t, os.TempDir())
beforeCount := countSandboxTempDirs(t)
code := mustLoadSampleCode(t, "inode_bomb.py", nil)
resp := callSimpleExecute(t, h.baseURL, buildPython3Request(code, 4, 32768))
combinedLower := strings.ToLower(resp.Output + "\n" + resp.Error)
if !containsAny(combinedLower, []string{"inode bomb completed", "no space left", "disk quota exceeded"}) {
t.Fatalf("inode exhaustion test produced unexpected result; stdout=%q stderr=%q", resp.Output, resp.Error)
}
time.Sleep(400 * time.Millisecond)
assertDiskReclaimed(t, beforeFree, mustFreeBytes(t, os.TempDir()))
assertNoSandboxLeak(t, beforeCount, countSandboxTempDirs(t))
mustCreateAndDeleteTempFile(t)
}
func testPrivilegedSyscallDeniedPython3(t *testing.T, h integrationHarness) {
code := mustLoadSampleCode(t, "try_reboot.py", nil)
resp := callSimpleExecute(t, h.baseURL, buildPython3Request(code, 3, 32768))
assertDurationNotExcessive(t, resp.CPUTime, 3*time.Second, "privileged reboot syscall")
combinedLower := strings.ToLower(resp.Output + "\n" + resp.Error)
if strings.Contains(combinedLower, "reboot succeeded unexpectedly") {
t.Fatalf("privileged reboot syscall unexpectedly succeeded; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if !containsAny(combinedLower, []string{"operation not permitted", "permission denied", "bad system call", "killed", "hangup"}) {
t.Fatalf("expected privileged syscall denial signal was not observed; stdout=%q stderr=%q", resp.Output, resp.Error)
}
}
func testFilesystemIsolationForLanguage(t *testing.T, h integrationHarness, language, writeFile, readFile string) {
writeCode := mustLoadSampleCode(t, writeFile, nil)
writeResp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, writeCode, 4, 32768))
if !strings.Contains(writeResp.Output, "SecretData123") {
t.Fatalf("step A did not return secret in stdout; stdout=%q stderr=%q", writeResp.Output, writeResp.Error)
}
readCode := mustLoadSampleCode(t, readFile, nil)
readResp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, readCode, 4, 32768))
if !strings.Contains(strings.ToLower(readResp.Error), "no such file or directory") {
t.Fatalf("step B unexpectedly accessed file from another sandbox; stdout=%q stderr=%q", readResp.Output, readResp.Error)
}
}
func testDiskCleanupForLanguage(t *testing.T, h integrationHarness, language, payload string) {
beforeFree := mustFreeBytes(t, os.TempDir())
beforeCount := countSandboxTempDirs(t)
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 2, 32768))
stderrLower := strings.ToLower(resp.Error)
if !containsAny(stderrLower, []string{"execution timed out", "memory limit exceeded"}) {
t.Fatalf("disk spammer was not terminated as expected; stdout=%q stderr=%q", resp.Output, resp.Error)
}
time.Sleep(400 * time.Millisecond)
assertDiskReclaimed(t, beforeFree, mustFreeBytes(t, os.TempDir()))
assertNoSandboxLeak(t, beforeCount, countSandboxTempDirs(t))
}
func testForkBombContainmentForLanguage(t *testing.T, h integrationHarness, language, bombFile, helloFile string) {
bombCode := mustLoadSampleCode(t, bombFile, nil)
_ = callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, bombCode, 2, 32768))
helloCode := mustLoadSampleCode(t, helloFile, nil)
helloResp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, helloCode, 4, 32768))
if !strings.Contains(helloResp.Output, "Hello World") {
t.Fatalf("follow-up request failed after fork bomb; stdout=%q stderr=%q", helloResp.Output, helloResp.Error)
}
if strings.Contains(strings.ToLower(helloResp.Error), "resource temporarily unavailable") {
t.Fatalf("follow-up request indicates host PID exhaustion; stderr=%q", helloResp.Error)
}
}
func testNetworkIsolationForLanguage(t *testing.T, h integrationHarness, language, payload string) {
replacements := map[string]string{"__API_PORT__": strconv.Itoa(h.apiPort)}
code := mustLoadSampleCode(t, payload, replacements)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 3, 32768))
combined := strings.ToLower(resp.Output + "\n" + resp.Error)
if strings.Contains(combined, "connected") {
t.Fatalf("localhost bridge unexpectedly succeeded; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if !containsAny(combined, []string{"connection refused", "network is unreachable", "no route to host"}) {
t.Fatalf("network isolation did not produce expected connect error; stdout=%q stderr=%q", resp.Output, resp.Error)
}
}
func testMemoryHardLimitForLanguage(t *testing.T, h integrationHarness, language, payload string) {
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 3, 16384))
if !containsAny(strings.ToLower(resp.Error), []string{"memory limit exceeded", "killed", "execution timed out"}) {
t.Fatalf("memory bomb did not terminate as expected; stdout=%q stderr=%q", resp.Output, resp.Error)
}
execDur, err := time.ParseDuration(resp.CPUTime)
if err != nil {
t.Fatalf("failed to parse cpu_time %q: %v", resp.CPUTime, err)
}
if execDur > 500*time.Millisecond {
t.Fatalf("memory enforcement was too slow: cpu_time=%s stderr=%q", resp.CPUTime, resp.Error)
}
}
func testIOFloodResilienceForLanguage(t *testing.T, h integrationHarness, language, payload string) {
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 1, 32768))
stderrLower := strings.ToLower(resp.Error)
if !containsAny(stderrLower, []string{"execution timed out", "killed", "memory limit exceeded"}) {
t.Fatalf("io flood did not terminate with expected error; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if strings.TrimSpace(resp.Error) == "" {
t.Fatalf("io flood returned empty stderr; expected bounded but non-empty error output")
}
const maxErrorBytes = (1 << 20) + 4096
if len(resp.Error) > maxErrorBytes {
t.Fatalf("stderr exceeded resilience cap: got=%d bytes cap=%d", len(resp.Error), maxErrorBytes)
}
assertDurationNotExcessive(t, resp.CPUTime, 3*time.Second, "io flood request")
}
func testSignalTrapTimeoutForLanguage(t *testing.T, h integrationHarness, language, payload string) {
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 1, 32768))
if !strings.Contains(strings.ToLower(resp.Error), "execution timed out") {
t.Fatalf("signal trap did not timeout as expected; stdout=%q stderr=%q", resp.Output, resp.Error)
}
assertDurationWindow(t, resp.CPUTime, 900*time.Millisecond, 2500*time.Millisecond, "signal trap timeout")
}
func testOrphanReapingForLanguage(t *testing.T, h integrationHarness, language, payload, orphanName string) {
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 2, 32768))
assertDurationNotExcessive(t, resp.CPUTime, 3*time.Second, "orphan maker request")
time.Sleep(400 * time.Millisecond)
if cnt := countProcessesByComm(t, orphanName); cnt > 0 {
t.Fatalf("orphan grandchild leaked to host after request completion: count=%d stderr=%q", cnt, resp.Error)
}
}
func testInodeExhaustionForLanguage(t *testing.T, h integrationHarness, language, payload string) {
beforeFree := mustFreeBytes(t, os.TempDir())
beforeCount := countSandboxTempDirs(t)
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 4, 32768))
combinedLower := strings.ToLower(resp.Output + "\n" + resp.Error)
if !containsAny(combinedLower, []string{"inode bomb completed", "no space left", "disk quota exceeded"}) {
t.Fatalf("inode exhaustion test produced unexpected result; stdout=%q stderr=%q", resp.Output, resp.Error)
}
time.Sleep(400 * time.Millisecond)
assertDiskReclaimed(t, beforeFree, mustFreeBytes(t, os.TempDir()))
assertNoSandboxLeak(t, beforeCount, countSandboxTempDirs(t))
mustCreateAndDeleteTempFile(t)
}
func testPrivilegedSyscallDeniedForLanguage(t *testing.T, h integrationHarness, language, payload string) {
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 3, 32768))
assertDurationNotExcessive(t, resp.CPUTime, 3*time.Second, "privileged reboot syscall")
combinedLower := strings.ToLower(resp.Output + "\n" + resp.Error)
if strings.Contains(combinedLower, "reboot succeeded unexpectedly") {
t.Fatalf("privileged reboot syscall unexpectedly succeeded; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if !containsAny(combinedLower, []string{"operation not permitted", "permission denied", "bad system call", "killed", "hangup"}) {
t.Fatalf("expected privileged syscall denial signal was not observed; stdout=%q stderr=%q", resp.Output, resp.Error)
}
}
func testSandboxCannotWriteHostEtcPasswd(t *testing.T, h integrationHarness, language, payload string) {
beforeChecksum := mustFileSHA256(t, "/etc/passwd")
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 3, 32768))
afterChecksum := mustFileSHA256(t, "/etc/passwd")
if beforeChecksum != afterChecksum {
t.Fatalf("host /etc/passwd checksum changed unexpectedly; before=%s after=%s", beforeChecksum, afterChecksum)
}
combinedLower := strings.ToLower(resp.Output + "\n" + resp.Error)
if strings.Contains(combinedLower, "write succeeded") {
t.Fatalf("sandbox unexpectedly wrote to /etc/passwd; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if !strings.Contains(resp.Output, "write correctly denied") {
t.Fatalf("expected write denial marker in stdout; stdout=%q stderr=%q", resp.Output, resp.Error)
}
}
func testRemountingEtcReadWriteDenied(t *testing.T, h integrationHarness, language, payload string) {
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 3, 32768))
combinedLower := strings.ToLower(resp.Output + "\n" + resp.Error)
if strings.Contains(combinedLower, "remount succeeded") {
t.Fatalf("sandbox unexpectedly remounted /etc read-write; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if !strings.Contains(resp.Output, "remount correctly denied") {
t.Fatalf("expected remount denial marker in stdout; stdout=%q stderr=%q", resp.Output, resp.Error)
}
}
func testSandboxProcessUIDIsNotHostRoot(t *testing.T, h integrationHarness, language, payload string) {
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 3, 32768))
combinedLower := strings.ToLower(resp.Output + "\n" + resp.Error)
if strings.Contains(combinedLower, "is host root: bad") {
t.Fatalf("sandbox gained host-root-equivalent privileges; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if !strings.Contains(resp.Output, "not host root: ok") {
t.Fatalf("expected non-host-root marker in stdout; stdout=%q stderr=%q", resp.Output, resp.Error)
}
}
func testDangerousSyscallsBlockedBySeccomp(t *testing.T, h integrationHarness, language, payload string) {
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 3, 32768))
combinedLower := strings.ToLower(resp.Output + "\n" + resp.Error)
if strings.Contains(combinedLower, "syscall succeeded unexpectedly") {
t.Fatalf("dangerous syscall unexpectedly succeeded; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if strings.Contains(resp.Output, "syscall denied: ok") {
return
}
if containsAny(combinedLower, []string{"bad system call", "sigsys"}) {
return
}
t.Fatalf("expected syscall denial signal was not observed; stdout=%q stderr=%q", resp.Output, resp.Error)
}
func testSandboxEnvironmentDoesNotExposeHost(t *testing.T, h integrationHarness, language, payload string) {
t.Setenv("SANDBOX_SECRET_CANARY", "super-secret")
code := mustLoadSampleCode(t, payload, nil)
resp := callSimpleExecute(t, h.baseURL, buildLanguageRequest(language, code, 3, 32768))
stdoutLower := strings.ToLower(resp.Output)
stderrLower := strings.ToLower(resp.Error)
if strings.Contains(stdoutLower, "env_leak:sandbox_secret_canary") {
t.Fatalf("sandbox leaked sentinel env var; stdout=%q stderr=%q", resp.Output, resp.Error)
}
if strings.Contains(stdoutLower, "super-secret") || strings.Contains(stderrLower, "super-secret") {
t.Fatalf("sandbox leaked sentinel env var value; stdout=%q stderr=%q", resp.Output, resp.Error)
}
}
func mustFileSHA256(t *testing.T, path string) string {
t.Helper()
content, err := os.ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s: %v", path, err)
}
sum := sha256.Sum256(content)
return fmt.Sprintf("%x", sum)
}
func mustLoadSampleCode(t *testing.T, fileName string, replacements map[string]string) string {
t.Helper()
path := resolveSampleCodePath(fileName)
content, err := os.ReadFile(path)
if err != nil {
t.Fatalf("failed to read sample code %s: %v", path, err)
}
code := string(content)
for oldValue, newValue := range replacements {
code = strings.ReplaceAll(code, oldValue, newValue)
}
return code
}
func resolveSampleCodePath(fileName string) string {
ext := filepath.Ext(fileName)
stem := strings.TrimSuffix(fileName, ext)
entryName := "main" + ext
if ext == ".java" {
entryName = "Main.java"
}
return filepath.Join(sampleCodeDir, stem, entryName)
}
func buildCRequest(code string, timeoutSec, maxMemoryKB uint) simpleExecuteRequest {
return buildLanguageRequest("c", code, timeoutSec, maxMemoryKB)
}
func buildPython3Request(code string, timeoutSec, maxMemoryKB uint) simpleExecuteRequest {
return buildLanguageRequest("python3", code, timeoutSec, maxMemoryKB)
}
func buildCppRequest(code string, timeoutSec, maxMemoryKB uint) simpleExecuteRequest {
return buildLanguageRequest("cpp", code, timeoutSec, maxMemoryKB)
}
func buildJavaRequest(code string, timeoutSec, maxMemoryKB uint) simpleExecuteRequest {
return buildLanguageRequest("java", code, timeoutSec, maxMemoryKB)
}
func buildLanguageRequest(language, code string, timeoutSec, maxMemoryKB uint) simpleExecuteRequest {
return simpleExecuteRequest{Language: language, Code: code, Timeout: timeoutSec, MaxMemory: maxMemoryKB}
}
type concurrentSimpleExecuteResult struct {
response simpleExecuteResponse
elapsed time.Duration
err error
}
func startOverloadLoadTestServer(t *testing.T) string {
t.Helper()
t.Setenv("GLOBAL_RAM_LIMIT", "524288")
originalRAMLimit := config.Config.Globals.RAM_LIMIT
config.Config.Globals.RAM_LIMIT = 524288
resourcemanager.ResetRAMForTests(config.Config.Globals.RAM_LIMIT)
t.Cleanup(func() {
config.Config.Globals.RAM_LIMIT = originalRAMLimit
resourcemanager.ResetRAMForTests(config.Config.Globals.RAM_LIMIT)
})
gin.SetMode(gin.ReleaseMode)
router := gin.New()
routes.Setup(router)
server := httptest.NewServer(router)
t.Cleanup(server.Close)
return server.URL
}
func runConcurrentSimpleExecuteRequests(baseURL string, req simpleExecuteRequest, count int) []concurrentSimpleExecuteResult {
results := make([]concurrentSimpleExecuteResult, count)
start := make(chan struct{})
var wg sync.WaitGroup
wg.Add(count)
for i := 0; i < count; i++ {
go func(index int) {
defer wg.Done()
<-start
startedAt := time.Now()
resp, err := callSimpleExecuteRaw(baseURL, req)
results[index] = concurrentSimpleExecuteResult{
response: resp,
elapsed: time.Since(startedAt),
err: err,
}
}(i)
}
close(start)
wg.Wait()
return results
}
func callSimpleExecute(t *testing.T, baseURL string, req simpleExecuteRequest) simpleExecuteResponse {
t.Helper()
resp, err := callSimpleExecuteRaw(baseURL, req)
if err != nil {
t.Fatalf("request failed: %v", err)
}
return resp
}
func callSimpleExecuteRaw(baseURL string, req simpleExecuteRequest) (simpleExecuteResponse, error) {
body, err := json.Marshal(req)
if err != nil {
return simpleExecuteResponse{}, fmt.Errorf("failed to marshal request: %w", err)
}
httpReq, err := http.NewRequest(http.MethodPost, baseURL+"/execute", bytes.NewReader(body))
if err != nil {
return simpleExecuteResponse{}, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpResp, err := httpClient.Do(httpReq)
if err != nil {
return simpleExecuteResponse{}, fmt.Errorf("request failed: %w", err)
}
defer httpResp.Body.Close()
return decodeSimpleResponseRaw(httpResp)
}
func decodeSimpleResponse(t *testing.T, httpResp *http.Response) simpleExecuteResponse {
t.Helper()
resp, err := decodeSimpleResponseRaw(httpResp)
if err != nil {
t.Fatal(err)
}
return resp
}
func decodeSimpleResponseRaw(httpResp *http.Response) (simpleExecuteResponse, error) {
rawBody, err := io.ReadAll(httpResp.Body)
if err != nil {
return simpleExecuteResponse{}, fmt.Errorf("failed to read response body: %w", err)
}
if httpResp.StatusCode != http.StatusOK {
return simpleExecuteResponse{}, fmt.Errorf("unexpected HTTP status %d: %s", httpResp.StatusCode, strings.TrimSpace(string(rawBody)))
}
var parsed simpleExecuteResponse
if err := json.Unmarshal(rawBody, &parsed); err != nil {
return simpleExecuteResponse{}, fmt.Errorf("failed to decode response JSON: %w; body=%q", err, strings.TrimSpace(string(rawBody)))
}
return parsed, nil
}
func mustExtractPort(t *testing.T, serverURL string) int {
t.Helper()
hostPort := strings.TrimPrefix(serverURL, "http://")
_, portStr, err := net.SplitHostPort(hostPort)
if err != nil {
t.Fatalf("failed to parse test server URL %q: %v", serverURL, err)
}
port, err := strconv.Atoi(portStr)
if err != nil {
t.Fatalf("failed to parse server port %q: %v", portStr, err)
}
return port
}
func mustFreeBytes(t *testing.T, path string) uint64 {
t.Helper()
var stat syscall.Statfs_t
if err := syscall.Statfs(path, &stat); err != nil {
t.Fatalf("statfs failed for %s: %v", path, err)
}
return stat.Bavail * uint64(stat.Bsize)
}
func countSandboxTempDirs(t *testing.T) int {
t.Helper()
matches, err := filepath.Glob(filepath.Join(os.TempDir(), "codesandbox-c-*"))
if err != nil {
t.Fatalf("failed to glob sandbox temp dirs: %v", err)
}
return len(matches)