//go:build sandbox && linux package isolationtest import ( "bufio" "encoding/json" "fmt" "log/slog" "os" "path/filepath" "strconv" "strings" "testing" "time" "lincodex/runner/internal/app" "lincodex/runner/internal/checker" "lincodex/runner/internal/config" "lincodex/runner/internal/judge" "lincodex/runner/internal/sandbox" ) const ( fixturesEnv = "RUNNER_HOSTILE_FIXTURES" defaultFixtures = "../../testdata/hostile" // seriesRepeats runs the whole manifest this many times before the final // cleanup check. seriesRepeats = 2 ) type manifest struct { Schema string `json:"schema"` DefaultLimits limits `json:"default_limits"` Cases []struct { Name string `json:"name"` Language string `json:"language"` Source string `json:"source"` Input string `json:"input"` ExpectedOutput string `json:"expected_output"` Limits *limits `json:"limits"` Expect struct { Outcome judge.Outcome `json:"outcome"` Limit sandbox.Termination `json:"limit"` } `json:"expect"` } `json:"cases"` } type limits struct { TimeLimitMs int64 `json:"time_limit_ms"` MemoryLimitMB int64 `json:"memory_limit_mb"` OutputLimitKB int64 `json:"output_limit_kb"` } func fixturesDir() string { if dir := os.Getenv(fixturesEnv); dir != "" { return dir } return defaultFixtures } func loadManifest(t *testing.T) manifest { t.Helper() content, err := os.ReadFile(filepath.Join(fixturesDir(), "manifest.json")) if err != nil { t.Fatalf("read manifest: %v", err) } var loaded manifest if err := json.Unmarshal(content, &loaded); err != nil { t.Fatalf("decode manifest: %v", err) } if loaded.Schema != "lincodex.runner-hostile-fixtures/v1" || len(loaded.Cases) == 0 { t.Fatalf("unexpected manifest %q with %d cases", loaded.Schema, len(loaded.Cases)) } return loaded } // newRunner builds the sandbox from the production configuration path. func newRunner(t *testing.T) (*sandbox.Executor, *judge.Judge) { t.Helper() t.Setenv("RUNNER_API_TOKEN", strings.Repeat("t", config.MinTokenLength)) t.Setenv("RUNNER_DEV_ALLOW_PLAINTEXT_HTTP", "true") cfg, err := config.Load() if err != nil { t.Fatalf("config: %v", err) } executor, err := sandbox.New(app.SandboxConfig(cfg)) if err != nil { t.Fatalf("sandbox: %v", err) } logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelWarn})) return executor, judge.New(executor, logger, app.Languages(cfg)...) } func TestHostileProgramsAreStoppedByTheRightLimit(t *testing.T) { loaded := loadManifest(t) executor, evaluator := newRunner(t) for round := range seriesRepeats { for _, tc := range loaded.Cases { source, err := os.ReadFile(filepath.Join(fixturesDir(), tc.Source)) if err != nil { t.Fatalf("read %s: %v", tc.Source, err) } caseLimits := loaded.DefaultLimits if tc.Limits != nil { caseLimits = *tc.Limits } request := judge.Request{ Language: tc.Language, Source: string(source), Limits: judge.Limits{ TimeLimit: time.Duration(caseLimits.TimeLimitMs) * time.Millisecond, MemoryBytes: caseLimits.MemoryLimitMB << 20, OutputBytes: caseLimits.OutputLimitKB << 10, }, Groups: []judge.Group{{ ID: "public", Visibility: judge.Public, Checker: checker.Spec{Kind: checker.Exact}, Tests: []judge.Test{{ID: "t1", Input: tc.Input, ExpectedOutput: tc.ExpectedOutput}}, }}, } result := evaluator.Run(t.Context(), request) if result.Outcome != tc.Expect.Outcome { t.Errorf("round %d %s: outcome %s, want %s (%s)", round, tc.Name, result.Outcome, tc.Expect.Outcome, describe(result)) continue } if tc.Expect.Outcome == judge.CompileError { if result.Compile == nil || result.Compile.Diagnostic == "" { t.Errorf("round %d %s: compile error without a diagnostic", round, tc.Name) } continue } test := result.Groups[0].Tests[0] if test.Limit != tc.Expect.Limit { t.Errorf("round %d %s: limit %q, want %q (%s)", round, tc.Name, test.Limit, tc.Expect.Limit, describe(result)) } if test.CPUTime <= 0 || test.WallTime <= 0 || test.MemoryKB <= 0 { t.Errorf("round %d %s: usage not recorded: cpu %v wall %v memory %d KiB", round, tc.Name, test.CPUTime, test.WallTime, test.MemoryKB) } t.Logf("round %d %-16s %-22s limit=%-9q cpu=%v wall=%v memory=%dKiB", round, tc.Name, test.Outcome, test.Limit, test.CPUTime, test.WallTime, test.MemoryKB) assertNothingLeft(t, executor, tc.Name) } } assertNothingLeft(t, executor, "series") } func describe(result judge.Result) string { return fmt.Sprintf("%+v", result) } // assertNothingLeft checks that the work directory and the run cgroups are // gone and that no process of the sandbox user is alive. func assertNothingLeft(t *testing.T, executor *sandbox.Executor, label string) { t.Helper() boxes, cgroups, err := executor.Leftovers() if err != nil { t.Fatalf("%s: leftovers: %v", label, err) } if len(boxes) != 0 || len(cgroups) != 0 { t.Fatalf("%s: left boxes %q and cgroups %q", label, boxes, cgroups) } if pids := sandboxUserProcesses(t, config.DefaultSandboxUID); len(pids) != 0 { t.Fatalf("%s: sandbox user processes still alive: %v", label, pids) } } func sandboxUserProcesses(t *testing.T, uid int) []string { t.Helper() entries, err := os.ReadDir("/proc") if err != nil { t.Fatalf("list /proc: %v", err) } wanted := "\t" + strconv.Itoa(uid) + "\t" var pids []string for _, entry := range entries { if !entry.IsDir() || strings.Trim(entry.Name(), "0123456789") != "" { continue } file, err := os.Open(filepath.Join("/proc", entry.Name(), "status")) if err != nil { continue // The process exited meanwhile. } scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, "Uid:") && strings.Contains(line+"\t", wanted) { pids = append(pids, entry.Name()) } } _ = file.Close() } return pids }