476 lines
15 KiB
Go
476 lines
15 KiB
Go
//go:build sandbox && linux
|
|
|
|
package isolationtest
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"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"
|
|
reportEnv = "RUNNER_A16_REPORT"
|
|
defaultFixtures = "../../testdata/hostile"
|
|
manifestSchema = "lincodex.runner-hostile-fixtures/v2"
|
|
reportSchema = "lincodex.runner-a16-report/v1"
|
|
// weakenedProcesses replaces the process limit in the weakened config.
|
|
weakenedProcesses = 4096
|
|
// leftoverGrace bounds the wait of the weakened-limit check for killed
|
|
// sandbox processes to finish exiting; leftoverPoll is its poll step.
|
|
leftoverGrace = 2 * time.Second
|
|
leftoverPoll = 20 * time.Millisecond
|
|
apkDatabase = "/lib/apk/db/installed"
|
|
)
|
|
|
|
// runnerVersion is set with -ldflags -X by the Make targets.
|
|
var runnerVersion = "unknown"
|
|
|
|
type manifest struct {
|
|
Schema string `json:"schema"`
|
|
DefaultLimits limits `json:"default_limits"`
|
|
Categories map[string]string `json:"categories"`
|
|
Cases []hostileCase `json:"cases"`
|
|
}
|
|
|
|
type limits struct {
|
|
TimeLimitMs int64 `json:"time_limit_ms"`
|
|
MemoryLimitMB int64 `json:"memory_limit_mb"`
|
|
OutputLimitKB int64 `json:"output_limit_kb"`
|
|
}
|
|
|
|
type hostileCase struct {
|
|
Name string `json:"name"`
|
|
Category string `json:"category"`
|
|
Language string `json:"language"`
|
|
Source string `json:"source"`
|
|
Input string `json:"input"`
|
|
ExpectedOutput string `json:"expected_output"`
|
|
Expect expect `json:"expect"`
|
|
}
|
|
|
|
type expect struct {
|
|
Outcome judge.Outcome `json:"outcome"`
|
|
Limit sandbox.Termination `json:"limit"`
|
|
Signal int `json:"signal,omitempty"`
|
|
}
|
|
|
|
type observed struct {
|
|
Outcome judge.Outcome `json:"outcome"`
|
|
Limit sandbox.Termination `json:"limit"`
|
|
Signal int `json:"signal,omitempty"`
|
|
ExitCode *int `json:"exit_code,omitempty"`
|
|
CPUMs int64 `json:"cpu_ms"`
|
|
WallMs int64 `json:"wall_ms"`
|
|
MemoryKB int64 `json:"memory_kb"`
|
|
}
|
|
|
|
type caseReport struct {
|
|
Name string `json:"name"`
|
|
Category string `json:"category"`
|
|
Language string `json:"language"`
|
|
Expected expect `json:"expected"`
|
|
Observed observed `json:"observed"`
|
|
Passed bool `json:"passed"`
|
|
Problem string `json:"problem,omitempty"`
|
|
}
|
|
|
|
type report struct {
|
|
Schema string `json:"schema"`
|
|
GeneratedAt string `json:"generated_at"`
|
|
RunnerVersion string `json:"runner_version"`
|
|
Kernel map[string]string `json:"kernel"`
|
|
CgroupControllers string `json:"cgroup_controllers"`
|
|
NsjailPackage string `json:"nsjail_package,omitempty"`
|
|
Profile sandbox.Profile `json:"profile"`
|
|
Limits limits `json:"limits"`
|
|
Categories map[string]string `json:"categories"`
|
|
Cases []caseReport `json:"cases"`
|
|
NothingLeftAfterRuns bool `json:"nothing_left_after_runs"`
|
|
Passed int `json:"passed"`
|
|
Failed int `json:"failed"`
|
|
Verdict string `json:"verdict"`
|
|
PracticeMayBeEnabled bool `json:"practice_may_be_enabled"`
|
|
VerdictRule string `json:"verdict_rule"`
|
|
}
|
|
|
|
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 != manifestSchema || len(loaded.Cases) == 0 {
|
|
t.Fatalf("unexpected manifest %q with %d cases", loaded.Schema, len(loaded.Cases))
|
|
}
|
|
return loaded
|
|
}
|
|
|
|
// loadConfig reads the runner configuration the way the service does, so
|
|
// the suite tests the deployed settings, including any RUNNER_* override.
|
|
func loadConfig(t *testing.T) config.Config {
|
|
t.Helper()
|
|
if os.Getenv("RUNNER_API_TOKEN") == "" && os.Getenv("RUNNER_API_TOKEN_FILE") == "" {
|
|
t.Setenv("RUNNER_API_TOKEN", strings.Repeat("t", config.MinTokenLength))
|
|
}
|
|
if os.Getenv("RUNNER_TLS_CERT_FILE") == "" {
|
|
t.Setenv("RUNNER_DEV_ALLOW_PLAINTEXT_HTTP", "true")
|
|
}
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
t.Fatalf("config: %v", err)
|
|
}
|
|
return cfg
|
|
}
|
|
|
|
func newRunner(t *testing.T, cfg config.Config) (*sandbox.Executor, *judge.Judge) {
|
|
t.Helper()
|
|
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 (m manifest) request(t *testing.T, tc hostileCase) judge.Request {
|
|
t.Helper()
|
|
source, err := os.ReadFile(filepath.Join(fixturesDir(), tc.Source))
|
|
if err != nil {
|
|
t.Fatalf("read %s: %v", tc.Source, err)
|
|
}
|
|
return judge.Request{
|
|
Language: tc.Language,
|
|
Source: string(source),
|
|
Limits: judge.Limits{
|
|
TimeLimit: time.Duration(m.DefaultLimits.TimeLimitMs) * time.Millisecond,
|
|
MemoryBytes: m.DefaultLimits.MemoryLimitMB << 20,
|
|
OutputBytes: m.DefaultLimits.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}},
|
|
}},
|
|
}
|
|
}
|
|
|
|
// evaluate runs one case and compares it with its expectation.
|
|
func evaluate(t *testing.T, evaluator *judge.Judge, m manifest, tc hostileCase) caseReport {
|
|
t.Helper()
|
|
result := evaluator.Run(t.Context(), m.request(t, tc))
|
|
entry := caseReport{Name: tc.Name, Category: tc.Category, Language: tc.Language, Expected: tc.Expect}
|
|
entry.Observed.Outcome = result.Outcome
|
|
var problems []string
|
|
if result.Outcome != tc.Expect.Outcome {
|
|
problems = append(problems, fmt.Sprintf("outcome %s, want %s", result.Outcome, tc.Expect.Outcome))
|
|
}
|
|
if len(result.Groups) == 1 && len(result.Groups[0].Tests) == 1 {
|
|
test := result.Groups[0].Tests[0]
|
|
entry.Observed = observed{
|
|
Outcome: result.Outcome,
|
|
Limit: test.Limit,
|
|
ExitCode: test.ExitCode,
|
|
CPUMs: test.CPUTime.Milliseconds(),
|
|
WallMs: test.WallTime.Milliseconds(),
|
|
MemoryKB: test.MemoryKB,
|
|
}
|
|
if test.Signal != nil {
|
|
entry.Observed.Signal = *test.Signal
|
|
}
|
|
if test.Limit != tc.Expect.Limit {
|
|
problems = append(problems, fmt.Sprintf("limit %q, want %q", test.Limit, tc.Expect.Limit))
|
|
}
|
|
if tc.Expect.Signal != 0 && entry.Observed.Signal != tc.Expect.Signal {
|
|
problems = append(problems, fmt.Sprintf("signal %d, want %d", entry.Observed.Signal, tc.Expect.Signal))
|
|
}
|
|
if result.Outcome != tc.Expect.Outcome && test.Diagnostic != "" {
|
|
problems = append(problems, "stderr: "+firstLine(test.Diagnostic))
|
|
}
|
|
} else if tc.Expect.Outcome != judge.CompileError {
|
|
problems = append(problems, "the test did not run")
|
|
}
|
|
entry.Passed = len(problems) == 0
|
|
entry.Problem = strings.Join(problems, "; ")
|
|
return entry
|
|
}
|
|
|
|
func TestA16HostileProgramsAreRefused(t *testing.T) {
|
|
loaded := loadManifest(t)
|
|
cfg := loadConfig(t)
|
|
executor, evaluator := newRunner(t, cfg)
|
|
|
|
result := report{
|
|
Schema: reportSchema,
|
|
GeneratedAt: time.Now().UTC().Format(time.RFC3339),
|
|
RunnerVersion: runnerVersion,
|
|
Kernel: kernel(),
|
|
Limits: loaded.DefaultLimits,
|
|
Categories: loaded.Categories,
|
|
NsjailPackage: apkPackageVersion("nsjail"),
|
|
VerdictRule: "Any failed case blocks enabling code practice.",
|
|
}
|
|
if controllers, err := os.ReadFile(filepath.Join(cfg.CgroupRoot, "cgroup.controllers")); err == nil {
|
|
result.CgroupControllers = strings.TrimSpace(string(controllers))
|
|
}
|
|
profile, err := executor.Profile(sandbox.Limits{
|
|
CPUTime: time.Duration(loaded.DefaultLimits.TimeLimitMs) * time.Millisecond,
|
|
WallTime: 2*time.Duration(loaded.DefaultLimits.TimeLimitMs)*time.Millisecond + 500*time.Millisecond,
|
|
MemoryBytes: loaded.DefaultLimits.MemoryLimitMB << 20,
|
|
OutputBytes: loaded.DefaultLimits.OutputLimitKB << 10,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("profile: %v", err)
|
|
}
|
|
result.Profile = profile
|
|
|
|
result.NothingLeftAfterRuns = true
|
|
for _, tc := range loaded.Cases {
|
|
_, zombiesBefore := userProcesses(cfg.SandboxUID)
|
|
zombiesBefore = append([]string{}, zombiesBefore...) // Non-nil: check zombies.
|
|
entry := evaluate(t, evaluator, loaded, tc)
|
|
if leftover := nothingLeft(executor, cfg.SandboxUID, zombiesBefore); leftover != "" {
|
|
entry.Passed = false
|
|
entry.Problem = strings.TrimPrefix(entry.Problem+"; "+leftover, "; ")
|
|
result.NothingLeftAfterRuns = false
|
|
}
|
|
if entry.Passed {
|
|
result.Passed++
|
|
} else {
|
|
result.Failed++
|
|
t.Errorf("%s (%s, %s): %s", tc.Name, tc.Category, tc.Language, entry.Problem)
|
|
}
|
|
t.Logf("%-22s %-17s %-8s %-22s limit=%-9q signal=%-2d cpu=%dms wall=%dms memory=%dKiB passed=%v",
|
|
tc.Name, tc.Category, tc.Language, entry.Observed.Outcome, entry.Observed.Limit, entry.Observed.Signal,
|
|
entry.Observed.CPUMs, entry.Observed.WallMs, entry.Observed.MemoryKB, entry.Passed)
|
|
result.Cases = append(result.Cases, entry)
|
|
}
|
|
|
|
result.Verdict = "fail"
|
|
if result.Failed == 0 && result.NothingLeftAfterRuns {
|
|
result.Verdict = "pass"
|
|
result.PracticeMayBeEnabled = true
|
|
}
|
|
t.Logf("A16 verdict: %s (%d passed, %d failed); practice may be enabled: %v", result.Verdict, result.Passed, result.Failed, result.PracticeMayBeEnabled)
|
|
writeReport(t, result)
|
|
}
|
|
|
|
// TestA16WeakenedProcessLimitIsDetected weakens one limit in a test copy of
|
|
// the configuration and checks that the cases guarding it fail, so a
|
|
// regression of that limit cannot pass the suite.
|
|
func TestA16WeakenedProcessLimitIsDetected(t *testing.T) {
|
|
loaded := loadManifest(t)
|
|
cfg := loadConfig(t)
|
|
cfg.MaxProcesses = weakenedProcesses
|
|
executor, evaluator := newRunner(t, cfg)
|
|
|
|
guarded := 0
|
|
for _, tc := range loaded.Cases {
|
|
if tc.Category != "processes" {
|
|
continue
|
|
}
|
|
guarded++
|
|
entry := evaluate(t, evaluator, loaded, tc)
|
|
t.Logf("weakened %-16s observed %s limit=%q: detected=%v", tc.Name, entry.Observed.Outcome, entry.Observed.Limit, !entry.Passed)
|
|
if entry.Passed {
|
|
t.Errorf("%s still passes with a process limit of %d", tc.Name, weakenedProcesses)
|
|
}
|
|
// Under the weakened limit an OOM kill may hit nsjail itself and
|
|
// leave a dead, unreaped process to the container's PID 1; only live
|
|
// processes count here. A process killed with its cgroup can still
|
|
// be exiting when the run returns, so the check waits for the
|
|
// kernel to finish it before it reports a leftover.
|
|
if leftover := nothingLeftWithin(executor, cfg.SandboxUID, leftoverGrace); leftover != "" {
|
|
t.Fatalf("%s: %s", tc.Name, leftover)
|
|
}
|
|
}
|
|
if guarded == 0 {
|
|
t.Fatal("the manifest has no process limit case")
|
|
}
|
|
}
|
|
|
|
// nothingLeftWithin repeats the live-process check of nothingLeft until it
|
|
// passes or the grace period ends, and returns the last finding.
|
|
func nothingLeftWithin(executor *sandbox.Executor, uid int, grace time.Duration) string {
|
|
deadline := time.Now().Add(grace)
|
|
for {
|
|
leftover := nothingLeft(executor, uid, nil)
|
|
if leftover == "" || time.Now().After(deadline) {
|
|
return leftover
|
|
}
|
|
time.Sleep(leftoverPoll)
|
|
}
|
|
}
|
|
|
|
// nothingLeft reports run directories, run cgroups, or sandbox user
|
|
// processes that outlived a run, or an empty string. With a baseline of
|
|
// earlier zombies, a new exited but unreaped process also counts: the suite
|
|
// runs without an init, so it proves that nsjail reaps every jailed
|
|
// process. A nil baseline checks live processes only.
|
|
func nothingLeft(executor *sandbox.Executor, uid int, zombiesBefore []string) string {
|
|
boxes, cgroups, err := executor.Leftovers()
|
|
if err != nil {
|
|
return "leftovers: " + err.Error()
|
|
}
|
|
if len(boxes) != 0 || len(cgroups) != 0 {
|
|
return fmt.Sprintf("left boxes %q and cgroups %q", boxes, cgroups)
|
|
}
|
|
live, dead := userProcesses(uid)
|
|
if len(live) != 0 {
|
|
return fmt.Sprintf("sandbox user processes alive: %v", live)
|
|
}
|
|
if zombiesBefore != nil {
|
|
var added []string
|
|
for _, pid := range dead {
|
|
if !containsLine(zombiesBefore, pid) {
|
|
added = append(added, pid)
|
|
}
|
|
}
|
|
if len(added) != 0 {
|
|
return fmt.Sprintf("unreaped sandbox user processes: %v", added)
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// userProcesses lists processes of uid, split into live and zombie ones.
|
|
func userProcesses(uid int) (live, zombies []string) {
|
|
entries, err := os.ReadDir("/proc")
|
|
if err != nil {
|
|
return []string{"cannot list /proc: " + err.Error()}, nil
|
|
}
|
|
wanted := "\t" + strconv.Itoa(uid) + "\t"
|
|
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.
|
|
}
|
|
zombie, owned := false, false
|
|
scanner := bufio.NewScanner(file)
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
if strings.HasPrefix(line, "State:") && strings.Contains(line, "zombie") {
|
|
zombie = true
|
|
}
|
|
if strings.HasPrefix(line, "Uid:") && strings.Contains(line+"\t", wanted) {
|
|
owned = true
|
|
}
|
|
}
|
|
_ = file.Close()
|
|
switch {
|
|
case owned && zombie:
|
|
zombies = append(zombies, entry.Name())
|
|
case owned:
|
|
live = append(live, entry.Name())
|
|
}
|
|
}
|
|
return live, zombies
|
|
}
|
|
|
|
func kernel() map[string]string {
|
|
var name syscall.Utsname
|
|
if err := syscall.Uname(&name); err != nil {
|
|
return map[string]string{"error": err.Error()}
|
|
}
|
|
return map[string]string{
|
|
"sysname": utsString(name.Sysname[:]),
|
|
"release": utsString(name.Release[:]),
|
|
"version": utsString(name.Version[:]),
|
|
"machine": utsString(name.Machine[:]),
|
|
"goarch": runtime.GOARCH,
|
|
}
|
|
}
|
|
|
|
func utsString[T int8 | uint8](field []T) string {
|
|
var text strings.Builder
|
|
for _, value := range field {
|
|
if value == 0 {
|
|
break
|
|
}
|
|
text.WriteByte(byte(value))
|
|
}
|
|
return text.String()
|
|
}
|
|
|
|
// apkPackageVersion reads a package version from the Alpine database, which
|
|
// exists in the runner image; other hosts record only the nsjail digest.
|
|
func apkPackageVersion(name string) string {
|
|
content, err := os.ReadFile(apkDatabase)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
for record := range bytes.SplitSeq(content, []byte("\n\n")) {
|
|
lines := strings.Split(string(record), "\n")
|
|
if !containsLine(lines, "P:"+name) {
|
|
continue
|
|
}
|
|
for _, line := range lines {
|
|
if version, ok := strings.CutPrefix(line, "V:"); ok {
|
|
return name + " " + version
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func containsLine(lines []string, wanted string) bool {
|
|
for _, line := range lines {
|
|
if line == wanted {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func firstLine(text string) string {
|
|
line, _, _ := strings.Cut(strings.TrimSpace(text), "\n")
|
|
return line
|
|
}
|
|
|
|
func writeReport(t *testing.T, result report) {
|
|
t.Helper()
|
|
path := os.Getenv(reportEnv)
|
|
if path == "" {
|
|
return
|
|
}
|
|
encoded, err := json.MarshalIndent(result, "", " ")
|
|
if err != nil {
|
|
t.Fatalf("encode report: %v", err)
|
|
}
|
|
if err := os.WriteFile(path, append(encoded, '\n'), 0o600); err != nil {
|
|
t.Fatalf("write report: %v", err)
|
|
}
|
|
t.Logf("A16 report written to %s", path)
|
|
}
|