Files
lincodex/runner/internal/sandbox/sandbox_test.go
T

251 lines
9.0 KiB
Go

package sandbox
import (
"bytes"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
)
func testConfig() Config {
return Config{
NsjailPath: "/usr/bin/nsjail",
SandboxUID: 99999,
SandboxGID: 99999,
MaxProcesses: 16,
TmpfsBytes: 16 << 20,
FileSizeBytes: 8 << 20,
OpenFiles: 64,
StderrCaptureBytes: 1024,
ReadOnlyMounts: []string{"/usr", "/lib"},
Env: []string{"LANG=C.UTF-8"},
PollInterval: time.Millisecond,
}
}
// flagValue returns the value after the first occurrence of flag.
func flagValue(t *testing.T, args []string, flag string) string {
t.Helper()
index := slices.Index(args, flag)
if index < 0 || index+1 >= len(args) {
t.Fatalf("flag %s is missing in %q", flag, args)
}
return args[index+1]
}
func TestNsjailArgsKeepEveryIsolationSwitch(t *testing.T) {
t.Parallel()
spec := Spec{
Argv: []string{"/usr/local/bin/python3", "-I", "/box/main.py"},
Mounts: []Mount{{Source: "/work/run-1/src", Target: BoxPath}, {Source: "/work/run-1/out", Target: OutPath}},
Env: []string{"GOMAXPROCS=1"},
}
limits := Limits{CPUTime: 1500 * time.Millisecond, WallTime: 3500 * time.Millisecond, MemoryBytes: 64 << 20, OutputBytes: 1 << 16}
args := nsjailArgs(testConfig(), spec, limits, "POLICY")
for _, forbidden := range []string{
"--disable_clone_newnet", "-N", "--disable_clone_newuser", "--disable_clone_newns", "--disable_clone_newpid",
"--keep_caps", "--cap", "--disable_no_new_privs", "--rw", "--keep_env", "--chroot", "--proc_rw", "--use_pasta",
} {
if slices.Contains(args, forbidden) {
t.Errorf("args contain %s: %q", forbidden, args)
}
}
checks := map[string]string{
"--mode": "o",
"--user": "99999:99999:1",
"--group": "99999:99999:1",
"--cwd": ScratchPath,
"--rlimit_cpu": "3",
"--rlimit_fsize": "8",
"--rlimit_nofile": "64",
"--rlimit_core": "0",
"--time_limit": "6",
"--seccomp_string": "POLICY",
"--mount": "none:/tmp:tmpfs:size=16777216",
}
for flag, want := range checks {
if got := flagValue(t, args, flag); got != want {
t.Errorf("%s = %q, want %q", flag, got, want)
}
}
for _, required := range []string{"--disable_proc", "--iface_no_lo"} {
if !slices.Contains(args, required) {
t.Errorf("args miss %s", required)
}
}
if !slices.Contains(args, "/work/run-1/src:/box") || !slices.Contains(args, "/work/run-1/out:/out") {
t.Errorf("the box is not mounted read-only: %q", args)
}
if !slices.Contains(args, "GOMAXPROCS=1") || !slices.Contains(args, "LANG=C.UTF-8") {
t.Errorf("args miss the environment: %q", args)
}
compile := spec
compile.WorkDir = BoxPath
compile.Mounts = []Mount{{Source: "/work/run-1/out", Target: OutPath, Writable: true}}
compileArgs := nsjailArgs(testConfig(), compile, Limits{CPUTime: time.Second, WallTime: time.Second, FileSizeBytes: 64 << 20}, "POLICY")
if got := flagValue(t, compileArgs, "--cwd"); got != BoxPath {
t.Errorf("compile --cwd = %q", got)
}
if got := flagValue(t, compileArgs, "--rlimit_fsize"); got != "64" {
t.Errorf("compile --rlimit_fsize = %q", got)
}
if got := writableMounts(compileArgs); !slices.Equal(got, []string{"/work/run-1/out:/out", "/dev/null"}) {
t.Errorf("compile writable mounts = %q", got)
}
separator := slices.Index(args, "--")
if separator < 0 || !slices.Equal(args[separator+1:], spec.Argv) {
t.Errorf("command after -- = %q, want %q", args[separator+1:], spec.Argv)
}
if got := writableMounts(args); !slices.Equal(got, []string{"/dev/null"}) {
t.Errorf("unexpected writable bind mounts %q", got)
}
}
func writableMounts(args []string) []string {
var mounts []string
for index, arg := range args {
if arg == "--bindmount" && index+1 < len(args) {
mounts = append(mounts, args[index+1])
}
}
return mounts
}
func TestSeccompPolicyKillsNamespaceAndDebugSyscalls(t *testing.T) {
t.Parallel()
policy := seccompPolicy()
for _, fragment := range []string{"ptrace", "unshare", "setns", "mount", "bpf", "io_uring_setup", "clone(flags)", "ERRNO(38) { clone3 }", "socket(domain)", "USE runner DEFAULT ALLOW"} {
if !strings.Contains(policy, fragment) {
t.Errorf("policy misses %q", fragment)
}
}
// Kafel knows umount2 only as "umount" on amd64 and arm64; the name
// umount2 makes nsjail reject the whole policy, so every run would fail.
if !strings.Contains(policy, "umount,") || strings.Contains(policy, "umount2") {
t.Errorf("policy must kill umount2 under its kafel name umount:\n%s", policy)
}
}
func TestParseNsjailLog(t *testing.T) {
t.Parallel()
exited := parseNsjailLog([]byte("[I][2026] Executing '/usr/local/bin/python3'\n[I][2026] pid=12 ([STANDALONE MODE]) exited with status: 3, (PIDs left: 0)\n"))
if !exited.reported || exited.exitCode != 3 || exited.signal != 0 || exited.failure != "" {
t.Fatalf("exited report = %+v", exited)
}
signaled := parseNsjailLog([]byte("[W][2026][11] seccompViolation():291 pid=12 committed a syscall/seccomp violation\n[I][2026] pid=12 ([STANDALONE MODE]) terminated with signal: Bad system call (31), (PIDs left: 0)\n"))
if !signaled.reported || signaled.signal != 31 || signaled.exitCode != -1 || signaled.failure != "" {
t.Fatalf("signaled report = %+v", signaled)
}
failed := parseNsjailLog([]byte("[E][2026-10-10T23:37:27+0000][1] initNsInternal():361 chdir('/tmp'): No such file or directory\n[F][2026][1] runChild():506 Launching child process failed\n"))
if failed.failure != "initNsInternal():361 chdir('/tmp'): No such file or directory" {
t.Fatalf("failure = %q", failed.failure)
}
}
func TestApplyExitStatusSeparatesSandboxFailures(t *testing.T) {
t.Parallel()
var result Result
if err := applyExitStatus(&result, nsjailReport{failure: "execve failed", reported: true, signal: 9}, nil); err == nil {
t.Fatal("a launch failure must be an error")
}
stopped := Result{Termination: TerminationWallTime}
if err := applyExitStatus(&stopped, nsjailReport{}, nil); err != nil || stopped.Signal != signalKill {
t.Fatalf("stopped run = %+v, %v; want SIGKILL without an error", stopped, err)
}
}
func TestReadersBoundWhatTheyKeep(t *testing.T) {
t.Parallel()
exceeded := 0
kept := readLimited(bytes.NewReader(bytes.Repeat([]byte("a"), 100_000)), 10, func() { exceeded++ })
if len(kept) != 10 || exceeded != 1 {
t.Fatalf("readLimited kept %d bytes and reported %d times", len(kept), exceeded)
}
tail := readTail(strings.NewReader(strings.Repeat("x", 100_000)+"END"), 8)
if string(tail) != "xxxxxEND" {
t.Fatalf("readTail = %q", tail)
}
}
func TestCgroupStatsAndTermination(t *testing.T) {
t.Parallel()
dir := t.TempDir()
files := map[string]string{
"cpu.stat": "usage_usec 1500000\nuser_usec 1400000\n",
"memory.events": "low 0\nhigh 0\nmax 4\noom 1\noom_kill 1\noom_group_kill 0\n",
"pids.events": "max 0\n",
}
for name, content := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
stats, err := (&runCgroup{path: dir}).stats()
if err != nil {
t.Fatalf("stats: %v", err)
}
if stats.cpuUsage != 1500*time.Millisecond || stats.oomKills != 1 || stats.pidsLimits != 0 {
t.Fatalf("stats = %+v", stats)
}
limits := Limits{CPUTime: time.Second}
if got := terminationFromStats(stats, limits); got != TerminationMemory {
t.Fatalf("termination = %q, want memory before CPU time", got)
}
if got := terminationFromStats(cgroupStats{pidsLimits: 1}, limits); got != TerminationProcesses {
t.Fatalf("termination = %q, want processes", got)
}
if got := terminationFromStats(cgroupStats{cpuUsage: 2 * time.Second}, limits); got != TerminationCPUTime {
t.Fatalf("termination = %q, want cpu_time", got)
}
}
func TestBoxIsReadOnlyAndRemovable(t *testing.T) {
t.Parallel()
root := t.TempDir()
box, err := CreateBox(root, "main.py", []byte("print(1)"), Owner{UID: -1, GID: -1})
if err != nil {
t.Fatalf("CreateBox: %v", err)
}
info, err := os.Stat(filepath.Join(box.Dir(), "src", "main.py"))
if err != nil || info.Mode().Perm() != boxFileMode {
t.Fatalf("source file mode = %v, %v", info, err)
}
mounts := box.Mounts(false)
if mounts[0].Target != BoxPath || mounts[0].Writable || mounts[1].Target != OutPath || mounts[1].Writable {
t.Fatalf("mounts = %+v", mounts)
}
check, remove, err := box.AddCheckFiles(map[string][]byte{"actual": []byte("1")})
if err != nil || check.Target != CheckPath || check.Writable {
t.Fatalf("AddCheckFiles = %+v, %v", check, err)
}
if err := remove(); err != nil {
t.Fatalf("remove check files: %v", err)
}
if _, err := os.Stat(check.Source); !os.IsNotExist(err) {
t.Fatalf("check files remain: %v", err)
}
if err := box.Remove(); err != nil {
t.Fatalf("Remove: %v", err)
}
if entries, err := os.ReadDir(root); err != nil || len(entries) != 0 {
t.Fatalf("root after Remove = %v, %v", entries, err)
}
for _, name := range []string{"", "../main.py", ".hidden", "dir/main.py"} {
if _, err := CreateBox(root, name, nil, Owner{UID: -1, GID: -1}); err == nil {
t.Errorf("CreateBox accepted file name %q", name)
}
}
}