diff --git a/CLAUDE.md b/CLAUDE.md index 7a5e8c2..f27f470 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -58,9 +58,11 @@ The container must run in **privileged mode** (required for nsjail to create Lin ### Request Flow ``` +startup → cmd/serve.go runs the sandbox self-check (a bash script through nsjail) and exits if it fails + POST /v1/run → main.go → cmd/serve.go (Cobra CLI, Echo v5 router) → internal/handler/handler.go (validate runtime, reject restricted files, optional base64 decode of files/stdin, validate filenames, write to tmpdir) - → internal/sandbox/sandbox.go (invoke nsjail with the selected runtime; stdin piped to the run step only) + → internal/sandbox/sandbox.go (invoke nsjail with the selected runtime; stdin piped to the run step only; nsjail's own failure → HTTP 500) → Response: {compile, run} where each contains {stdout, stderr, output, exit_code, status, signal, duration_ms} (stdout/stderr/output are base64-encoded) ``` diff --git a/cmd/serve.go b/cmd/serve.go index 018a031..ff68257 100644 --- a/cmd/serve.go +++ b/cmd/serve.go @@ -98,8 +98,16 @@ func runServe(_ *cobra.Command, _ []string) error { OutputLimit: flagOutputLimit, } + runner := sandbox.NewRunner(cfg) + // Refuse to serve when nsjail cannot run a program on this host: + // every request would fail, and the failure is only visible here. + if err := runner.SelfCheck(context.Background()); err != nil { + slog.Error("sandbox self-check failed", "error", err) + return err + } + h := &handler.Handler{ - Runner: sandbox.NewRunner(cfg), + Runner: runner, MaxFiles: flagMaxFiles, MaxFileSize: flagMaxFileSize, MaxStdinSize: flagMaxStdinSize, diff --git a/internal/sandbox/CLAUDE.md b/internal/sandbox/CLAUDE.md index 4091554..e34e458 100644 --- a/internal/sandbox/CLAUDE.md +++ b/internal/sandbox/CLAUDE.md @@ -1,10 +1,11 @@ # internal/sandbox -Core sandbox execution engine, split across three files: +Core sandbox execution engine, split across four files: - **sandbox.go** — `Runner` orchestrates the full execution lifecycle: applies default files, runs compilation (if needed) and execution steps, and collects results. - **runtime.go** — `Runtime` interface and concrete implementations for each supported language. `CompiledRuntime` extends it for languages requiring a build step. Defines `Rlimits` (per-process resource limits via nsjail `--rlimit_*`), `Cgroups` (cgroup-based limits via `--cgroup_pids_max`, `--cgroup_mem_max`, `--cgroup_mem_swap_max`, `--cgroup_cpu_ms_per_sec`), and `Limits` (combines both). -- **execution.go** — Handles a single nsjail invocation: loads the static nsjail config file, assembles per-invocation CLI arguments, manages pipes (stdout, stderr, nsjail log), drains output via `poll(2)`, and enforces limits. +- **execution.go** — Handles a single nsjail invocation: loads the static nsjail config file, assembles per-invocation CLI arguments, manages pipes (stdout, stderr, nsjail log), drains output via `poll(2)`, and enforces limits. Reads the nsjail log to tell a timeout, a signal kill and nsjail's own failure (it could not set up the jail or launch the program) apart; nsjail's own failure is returned as an error, never as the program's exit code. +- **selfcheck.go** — `Runner.SelfCheck` runs a one-line bash script through nsjail at server startup; `serve` refuses to start when it fails, so a host where nsjail cannot run programs never takes traffic. - **configs/nsjail.cfg** — Static protobuf-format nsjail configuration loaded via `-C /etc/nsjail/nsjail.cfg`. Defines execution mode (`ONCE`), Seccomp-BPF policy file reference, logging (`log_fd: 3`), working directory, static rlimits, and filesystem mounts (system libraries, device nodes, tmpfs, procfs, symlinks). Per-invocation settings (runtime bind mounts, resource limits, timeout, env vars) are passed as CLI flags. - **configs/seccomp.kafel** — Seccomp-BPF syscall filtering policy written in Kafel. Uses a blacklist approach (DEFAULT ALLOW) blocking dangerous syscalls (io_uring, bpf, userfaultfd, mount, ptrace, etc.) as a defense-in-depth layer. Referenced from nsjail.cfg via `seccomp_policy_file` and copied to `/etc/nsjail/seccomp.kafel` in Docker. - **defaults/go/** — Embedded `go.mod.tmpl` and `go.sum.tmpl` templates applied as default files for Go runtime execution. diff --git a/internal/sandbox/execution.go b/internal/sandbox/execution.go index 95d7e60..adb0d88 100644 --- a/internal/sandbox/execution.go +++ b/internal/sandbox/execution.go @@ -125,6 +125,7 @@ func (e *execution) openPipes() (retErr error) { // child is killed by a signal (WIFSIGNALED), letting us report the // signal name and distinguish genuine kills from user code that // voluntarily exits with a signal-like exit code. + // 3. nsjail's own failure: see nsjailFailed. e.logR, e.logW, err = os.Pipe() if err != nil { return fmt.Errorf("failed to create log pipe: %w", err) @@ -210,6 +211,11 @@ func (e *execution) collectResult(waitErr error, logStr string, durationMs int64 if !errors.As(waitErr, &exitErr) { return Result{}, fmt.Errorf("sandbox execution failed: %w", waitErr) } + if nsjailFailed(logStr) { + // Until nsjail has read the config that sets log_fd, it logs to + // stderr; the program never ran, so stderr holds only nsjail's lines. + return Result{}, fmt.Errorf("nsjail failed (%w): %s", waitErr, nsjailErrorLines(e.stderrBuf.String()+logStr)) + } result.ExitCode = exitErr.ExitCode() result.Signal = resolveSignal(result.ExitCode, logStr) if timedOut { @@ -222,6 +228,41 @@ func (e *execution) collectResult(waitErr error, logStr string, durationMs int64 return result, nil } +// nsjailFailed reports whether nsjail failed on its own rather than running +// the program to an end, judged from its log (see nsjail/nsjail.cc and +// nsjail/subproc.cc). Either way nsjail exits non-zero, typically 255, which +// a program can also exit with, so the exit status alone cannot tell them +// apart. +// +// - Launching the program failed (a mount, a limit, execve, a namespace): +// nsjail logs "Couldn't launch the child process". It then still logs +// the child as "exited with status: 255" or "terminated with signal: +// SIGKILL", so those lines are not proof the program ran. +// - nsjail failed before launching it (an invalid argument or config, the +// cgroup) or was killed from outside: it logs neither "exited with +// status" nor "terminated with signal". +func nsjailFailed(logStr string) bool { + if strings.Contains(logStr, "Couldn't launch the child process") { + return true + } + return !strings.Contains(logStr, "exited with status: ") && !strings.Contains(logStr, "terminated with signal: ") +} + +// nsjailErrorLines returns the error and fatal lines ("[E]" / "[F]") of +// nsjail's output, joined into one line, as the reason nsjail failed. +func nsjailErrorLines(logStr string) string { + var lines []string + for line := range strings.Lines(logStr) { + if strings.HasPrefix(line, "[E]") || strings.HasPrefix(line, "[F]") { + lines = append(lines, strings.TrimRight(line, "\n")) + } + } + if len(lines) == 0 { + return "no error lines in the nsjail log" + } + return strings.Join(lines, " | ") +} + type pipe struct { file *os.File buf *bytes.Buffer diff --git a/internal/sandbox/selfcheck.go b/internal/sandbox/selfcheck.go new file mode 100644 index 0000000..3b664f7 --- /dev/null +++ b/internal/sandbox/selfcheck.go @@ -0,0 +1,64 @@ +package sandbox + +import ( + "context" + "encoding/base64" + "fmt" + "os" + "path/filepath" +) + +const ( + selfCheckScript = "echo 'sandbox self-check'\n" + selfCheckOutput = "sandbox self-check\n" +) + +// runFunc is the signature of Runner.Run, taken by selfCheck so the check +// can be tested without nsjail. +type runFunc func(ctx context.Context, rt Runtime, tmpDir, entryFile string, stdin []byte) (RunOutput, error) + +// SelfCheck runs one small bash program through nsjail and returns an error +// unless it prints the expected output and exits 0. nsjail refuses to start +// a program when the host does not let it set up the jail (for example when +// a namespace, rlimit or no_new_privs cannot be applied), and every request +// would then fail; checking once at startup turns that into a server that +// does not start, with nsjail's reason in the error. +func (r *Runner) SelfCheck(ctx context.Context) error { + return selfCheck(ctx, r.Run) +} + +func selfCheck(ctx context.Context, run runFunc) error { + rt, err := LookupRuntime(RuntimeBash) + if err != nil { + return fmt.Errorf("self-check: %w", err) + } + + tmpDir, err := os.MkdirTemp("", "sandbox-self-check-*") + if err != nil { + return fmt.Errorf("self-check: failed to create temp directory: %w", err) + } + defer func() { _ = os.RemoveAll(tmpDir) }() + + const entryFile = "self-check.sh" + if err := os.WriteFile(filepath.Join(tmpDir, entryFile), []byte(selfCheckScript), 0644); err != nil { + return fmt.Errorf("self-check: failed to write script: %w", err) + } + + output, err := run(ctx, rt, tmpDir, entryFile, nil) + if err != nil { + return fmt.Errorf("self-check: %w", err) + } + + result := output.Run + if result.Status != StatusOK || result.ExitCode != 0 { + return fmt.Errorf("self-check: program ended with status %s, exit code %d", result.Status, result.ExitCode) + } + stdout, err := base64.StdEncoding.DecodeString(result.Stdout) + if err != nil { + return fmt.Errorf("self-check: failed to decode stdout: %w", err) + } + if string(stdout) != selfCheckOutput { + return fmt.Errorf("self-check: unexpected output %q, want %q", stdout, selfCheckOutput) + } + return nil +} diff --git a/internal/sandbox/selfcheck_test.go b/internal/sandbox/selfcheck_test.go new file mode 100644 index 0000000..ab1ef06 --- /dev/null +++ b/internal/sandbox/selfcheck_test.go @@ -0,0 +1,81 @@ +package sandbox + +import ( + "context" + "encoding/base64" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func Test_selfCheck(t *testing.T) { + t.Parallel() + + b64 := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) } + + tests := []struct { + name string + output RunOutput + runErr error + wantErr bool + wantInErr string + }{ + { + name: "passes", + output: RunOutput{Run: &Result{Stdout: b64("sandbox self-check\n"), Status: StatusOK}}, + }, + { + name: "run fails", + runErr: errors.New("run: nsjail failed (exit status 255): [E] Couldn't launch the child process"), + wantErr: true, + wantInErr: "Couldn't launch the child process", + }, + { + name: "unexpected output", + output: RunOutput{Run: &Result{Stdout: b64("something else\n"), Status: StatusOK}}, + wantErr: true, + wantInErr: "something else", + }, + { + name: "non-zero exit", + output: RunOutput{Run: &Result{Stdout: b64("sandbox self-check\n"), ExitCode: 1, Status: StatusOK}}, + wantErr: true, + wantInErr: "exit code 1", + }, + { + name: "timeout", + output: RunOutput{Run: &Result{Status: StatusTimeout, ExitCode: 137}}, + wantErr: true, + wantInErr: string(StatusTimeout), + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + var sawScript string + run := func(_ context.Context, rt Runtime, tmpDir, entryFile string, stdin []byte) (RunOutput, error) { + assert.Equal(t, RuntimeBash, rt.Name()) + assert.Empty(t, stdin) + b, err := os.ReadFile(filepath.Join(tmpDir, entryFile)) + require.NoError(t, err) + sawScript = string(b) + return tc.output, tc.runErr + } + + err := selfCheck(context.Background(), run) + assert.NotEmpty(t, sawScript, "the check script is written before running") + if !tc.wantErr { + require.NoError(t, err) + return + } + require.Error(t, err) + assert.Contains(t, err.Error(), tc.wantInErr) + }) + } +} diff --git a/internal/sandbox/signal_test.go b/internal/sandbox/signal_test.go index c340c10..03e8d17 100644 --- a/internal/sandbox/signal_test.go +++ b/internal/sandbox/signal_test.go @@ -182,3 +182,116 @@ func Test_collectResult(t *testing.T) { }) } } + +// Test_collectResult_nsjailFailure covers nsjail failing on its own instead of +// running the program to an end. The logs are what nsjail wrote in each case, +// trimmed to the lines that matter; nsjail exits 255 in all of them. +func Test_collectResult_nsjailFailure(t *testing.T) { + t.Parallel() + + waitErr := exec.Command("/bin/sh", "-c", "exit 255").Run() + require.Error(t, waitErr) + + tests := []struct { + name string + logStr string + stderr string + wantInErr []string + }{ + { + // nsjail still logs the child as exited with status 255. + name: "mount failure", + logStr: "[I][2026-12-01T02:01:33+0000] Mode: STANDALONE_ONCE\n" + + "[W][2026-12-01T02:01:33+0000][1] mountSinglePoint():299 mount('/mise/ruby' -> '/run/user/nsjail.0.root//mise/ruby'): No such file or directory\n" + + "[E][2026-12-01T02:01:33+0000][1] buildMountTree():480 Failed to mount mandatory point: '/mise/ruby'\n" + + "[E][2026-12-01T02:01:33+0000][1] initCloneNs():263 Failed to build mount tree\n" + + "[F][2026-12-01T02:01:33+0000][1] runChild():561 Launching child process failed\n" + + "[W][2026-12-01T02:01:33+0000][9702] runChild():581 Received error message from the child process before it has been executed\n" + + "[E][2026-12-01T02:01:33+0000][9702] standaloneMode():299 Couldn't launch the child process\n" + + "[I][2026-12-01T02:01:33+0000] pid=9703 ([STANDALONE MODE]) exited with status: 255, (PIDs left: 0)\n", + wantInErr: []string{ + "exit status 255", + "buildMountTree():480 Failed to mount mandatory point: '/mise/ruby'", + "standaloneMode():299 Couldn't launch the child process", + }, + }, + { + name: "execve failure", + logStr: "[E][2026-12-01T01:48:14+0000][1] newProc():262 execve('/bin/bash') failed: Not a directory\n" + + "[E][2026-12-01T01:48:14+0000][2288] standaloneMode():299 Couldn't launch the child process\n" + + "[I][2026-12-01T01:48:14+0000] pid=2289 ([STANDALONE MODE]) exited with status: 255, (PIDs left: 0)\n", + wantInErr: []string{ + "exit status 255", + "newProc():262 execve('/bin/bash') failed: Not a directory", + }, + }, + { + // nsjail fails before starting the child and logs no exit line. + name: "fatal argument error", + logStr: "[F][2026-12-01T01:50:54+0000][3179] parseRLimitType():378 RLIMIT RLIMIT_AS (9) needs a numeric value or 'max'/'hard'/'def'/'soft'/'inf' value ('4096x' provided)\n", + wantInErr: []string{ + "exit status 255", + "parseRLimitType():378 RLIMIT RLIMIT_AS (9) needs a numeric value", + }, + }, + { + name: "cgroup setup failure", + logStr: "[E][2026-12-01T02:06:43+0000][19480] main():380 Couldn't setup parent cgroup (cgroupv2)\n", + wantInErr: []string{ + "exit status 255", + "main():380 Couldn't setup parent cgroup (cgroupv2)", + }, + }, + { + // Until nsjail has read the config that sets log_fd, it logs to + // stderr, so the log pipe stays empty. + name: "unreadable config", + logStr: "", + stderr: "[W][2026-12-01T02:06:43+0000][19479] readFromFileToStr():184 Couldn't open file '/nonexistent.cfg': No such file or directory\n" + + "[E][2026-12-01T02:06:43+0000][19479] parseFile():176 Couldn't read config file '/nonexistent.cfg'\n" + + "[F][2026-12-01T02:06:43+0000][19479] parseArgs():574 Couldn't parse configuration from '/nonexistent.cfg' file\n", + wantInErr: []string{ + "exit status 255", + "parseFile():176 Couldn't read config file '/nonexistent.cfg'", + "parseArgs():574 Couldn't parse configuration from '/nonexistent.cfg' file", + }, + }, + { + name: "no error lines", + logStr: "", + wantInErr: []string{"exit status 255", "no error lines in the nsjail log"}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + e := &execution{} + e.stderrBuf.WriteString(tc.stderr) + _, err := e.collectResult(waitErr, tc.logStr, 0) + require.Error(t, err) + for _, want := range tc.wantInErr { + assert.Contains(t, err.Error(), want) + } + assert.NotContains(t, err.Error(), "[I]", "informational lines are not part of the reason") + assert.NotContains(t, err.Error(), "[W]", "warnings are not part of the reason") + }) + } +} + +// Test_collectResult_programExits255 locks in that a program which itself +// exits 255 is still reported as a result, not as an nsjail failure. +func Test_collectResult_programExits255(t *testing.T) { + t.Parallel() + + waitErr := exec.Command("/bin/sh", "-c", "exit 255").Run() + require.Error(t, waitErr) + + e := &execution{} + result, err := e.collectResult(waitErr, "[I][2026-12-01T02:00:28+0000] pid=4955 ([STANDALONE MODE]) exited with status: 255, (PIDs left: 0)\n", 0) + require.NoError(t, err) + assert.Equal(t, 255, result.ExitCode) + assert.Equal(t, StatusOK, result.Status) + assert.Nil(t, result.Signal) +}