213 lines
7.1 KiB
Go
213 lines
7.1 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"}, BoxDir: "/work/run-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:/box") {
|
|
t.Errorf("the box is not mounted at /box: %q", args)
|
|
}
|
|
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)
|
|
}
|
|
for _, writable := range writableMounts(args) {
|
|
if writable != "/dev/null" {
|
|
t.Errorf("unexpected writable bind mount %q", writable)
|
|
}
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|
|
}
|
|
|
|
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)"))
|
|
if err != nil {
|
|
t.Fatalf("CreateBox: %v", err)
|
|
}
|
|
info, err := os.Stat(filepath.Join(box.Dir(), "main.py"))
|
|
if err != nil || info.Mode().Perm() != boxFileMode {
|
|
t.Fatalf("source file mode = %v, %v", info.Mode(), 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); err == nil {
|
|
t.Errorf("CreateBox accepted file name %q", name)
|
|
}
|
|
}
|
|
}
|