package server import ( "bytes" "context" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" "github.com/google/uuid" "lincodex/runner/internal/jobs" "lincodex/runner/internal/judge" ) const ( testToken = "test-token-0123456789abcdefghijklmnop" // Markers that must never reach a log line. secretSource = "print('source-marker-7f3a')" secretInput = "input-marker-91c2" maxBody = 64 << 10 ) // blockingRunner holds runs until release is closed. type blockingRunner struct { release chan struct{} } func (r blockingRunner) Run(ctx context.Context, _ judge.Request) judge.Result { select { case <-r.release: case <-ctx.Done(): } exit := 0 return judge.Result{ Outcome: judge.Accepted, Groups: []judge.GroupResult{{ ID: "public", Visibility: judge.Public, Outcome: judge.Accepted, Passed: 1, Total: 1, MaxCPUTime: 25 * time.Millisecond, MaxMemoryKB: 9000, Tests: []judge.TestResult{{ID: "t1", Outcome: judge.Accepted, CPUTime: 25 * time.Millisecond, WallTime: 40 * time.Millisecond, MemoryKB: 9000, ExitCode: &exit}}, }}, Duration: 50 * time.Millisecond, } } type syncBuffer struct { mu sync.Mutex buf bytes.Buffer } func (b *syncBuffer) Write(p []byte) (int, error) { b.mu.Lock() defer b.mu.Unlock() return b.buf.Write(p) } func (b *syncBuffer) String() string { b.mu.Lock() defer b.mu.Unlock() return b.buf.String() } type testServer struct { url string logs *syncBuffer // release lets every held run finish; it may be called more than once. release func() } func startServer(t *testing.T) *testServer { t.Helper() logs := &syncBuffer{} logger := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug})) release := make(chan struct{}) manager, err := jobs.NewManager(jobs.Config{MaxConcurrent: 1, ResultTTL: time.Minute, MaxRetained: 8}, blockingRunner{release: release}, logger) if err != nil { t.Fatalf("NewManager: %v", err) } supports := func(language string) bool { return language == "python3" || language == "go" } handler := NewHandler(manager, supports, func() bool { return !manager.Draining() }, 3*time.Second, logger) httpHandler, err := New(handler, testToken, maxBody, logger) if err != nil { t.Fatalf("New: %v", err) } server := httptest.NewServer(httpHandler) var releaseOnce sync.Once releaseRuns := func() { releaseOnce.Do(func() { close(release) }) } t.Cleanup(func() { releaseRuns() server.Close() ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _ = manager.Close(ctx) }) return &testServer{url: server.URL, logs: logs, release: releaseRuns} } func runBody(source string) map[string]any { return map[string]any{ "language": "python3", "source": source, "limits": map[string]any{"time_limit_ms": 1000, "memory_limit_mb": 64, "output_limit_kb": 64}, "groups": []any{map[string]any{ "id": "public", "visibility": "public", "checker": map[string]any{"kind": "exact"}, "tests": []any{map[string]any{"id": "t1", "input": secretInput, "expected_output": "3\n"}}, }}, } } // reply is a response with its decoded JSON body; the body is already closed. type reply struct { StatusCode int Header http.Header } func (s *testServer) do(t *testing.T, method, path, token string, body any) (reply, map[string]any) { t.Helper() var reader io.Reader = http.NoBody if body != nil { encoded, err := json.Marshal(body) if err != nil { t.Fatalf("encode body: %v", err) } reader = bytes.NewReader(encoded) } request, err := http.NewRequestWithContext(t.Context(), method, s.url+path, reader) if err != nil { t.Fatalf("new request: %v", err) } if body != nil { request.Header.Set("Content-Type", "application/json") } if token != "" { request.Header.Set("Authorization", "Bearer "+token) } response, err := http.DefaultClient.Do(request) if err != nil { t.Fatalf("do request: %v", err) } defer response.Body.Close() var decoded map[string]any raw, err := io.ReadAll(response.Body) if err != nil { t.Fatalf("read body: %v", err) } if len(raw) > 0 { if err := json.Unmarshal(raw, &decoded); err != nil { t.Fatalf("decode %s: %v", raw, err) } } return reply{StatusCode: response.StatusCode, Header: response.Header}, decoded } func runPath(id uuid.UUID) string { return "/v1/runs/" + id.String() } func TestRunOperationsRequireTheBearerToken(t *testing.T) { t.Parallel() server := startServer(t) id := uuid.New() for _, token := range []string{"", "wrong-token-0123456789abcdefghijklmnop", testToken + "x"} { response, body := server.do(t, http.MethodPut, runPath(id), token, runBody(secretSource)) if response.StatusCode != http.StatusUnauthorized || body["code"] != "unauthenticated" { t.Fatalf("PUT with token %q = %d %v, want 401 unauthenticated", token, response.StatusCode, body) } response, _ = server.do(t, http.MethodGet, runPath(id), token, nil) if response.StatusCode != http.StatusUnauthorized { t.Fatalf("GET with token %q = %d, want 401", token, response.StatusCode) } } response, body := server.do(t, http.MethodGet, "/healthz", "", nil) if response.StatusCode != http.StatusOK || body["status"] != "ok" { t.Fatalf("healthz = %d %v", response.StatusCode, body) } response, body = server.do(t, http.MethodGet, "/readyz", "", nil) if response.StatusCode != http.StatusOK || body["status"] != "ready" { t.Fatalf("readyz = %d %v", response.StatusCode, body) } } func TestSubmitRunIsIdempotentAndAnswersBusy(t *testing.T) { t.Parallel() server := startServer(t) id := uuid.New() response, body := server.do(t, http.MethodPut, runPath(id), testToken, runBody(secretSource)) if response.StatusCode != http.StatusAccepted || body["state"] != "running" || body["run_id"] != id.String() { t.Fatalf("first PUT = %d %v, want 202 running", response.StatusCode, body) } response, body = server.do(t, http.MethodPut, runPath(id), testToken, runBody(secretSource)) if response.StatusCode != http.StatusOK || body["state"] != "running" { t.Fatalf("repeated PUT = %d %v, want 200 running", response.StatusCode, body) } response, body = server.do(t, http.MethodPut, runPath(id), testToken, runBody("print(2)")) if response.StatusCode != http.StatusUnprocessableEntity || body["code"] != "idempotency_key_reused" { t.Fatalf("PUT with another payload = %d %v, want 422", response.StatusCode, body) } response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, runBody(secretSource)) if response.StatusCode != http.StatusServiceUnavailable || body["code"] != "runner_busy" || response.Header.Get("Retry-After") != "3" { t.Fatalf("PUT while busy = %d %v %q, want 503 runner_busy with Retry-After 3", response.StatusCode, body, response.Header.Get("Retry-After")) } server.release() deadline := time.Now().Add(5 * time.Second) for { response, body = server.do(t, http.MethodGet, runPath(id), testToken, nil) if body["state"] == "finished" || time.Now().After(deadline) { break } time.Sleep(5 * time.Millisecond) } result, ok := body["result"].(map[string]any) if response.StatusCode != http.StatusOK || !ok || result["outcome"] != "accepted" { t.Fatalf("GET finished run = %d %v", response.StatusCode, body) } group := result["groups"].([]any)[0].(map[string]any) test := group["tests"].([]any)[0].(map[string]any) if group["passed_tests"] != float64(1) || test["time_ms"] != float64(25) || test["memory_kb"] != float64(9000) { t.Fatalf("group result = %v, want the recorded time and memory", group) } logs := server.logs.String() if strings.Contains(logs, "source-marker") || strings.Contains(logs, secretInput) || strings.Contains(logs, testToken) { t.Fatalf("logs contain request data: %s", logs) } } func TestSubmitRunAcceptsParameterizedCheckers(t *testing.T) { t.Parallel() server := startServer(t) body := runBody(secretSource) groups := body["groups"].([]any) numbers := map[string]any{ "id": "hidden-1", "visibility": "hidden", "checker": map[string]any{"kind": "numbers", "abs_tolerance": 1e-6}, "tests": []any{map[string]any{"id": "t1", "input": "1", "expected_output": "0.5"}}, } custom := map[string]any{ "id": "hidden-2", "visibility": "hidden", "checker": map[string]any{"kind": "custom", "program": map[string]any{"language": "python3", "source": "raise SystemExit(0)"}}, "tests": []any{map[string]any{"id": "t1", "input": "1", "expected_output": "1"}}, } body["groups"] = append(groups, numbers, custom) body["language"] = "go" response, decoded := server.do(t, http.MethodPut, runPath(uuid.New()), testToken, body) if response.StatusCode != http.StatusAccepted { t.Fatalf("PUT = %d %v, want 202", response.StatusCode, decoded) } } func TestSubmitRunValidatesTheRequest(t *testing.T) { t.Parallel() server := startServer(t) duplicate := runBody(secretSource) group := duplicate["groups"].([]any)[0] duplicate["groups"] = []any{group, group} response, body := server.do(t, http.MethodPut, runPath(uuid.New()), testToken, duplicate) if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" { t.Fatalf("duplicate group IDs = %d %v, want 400", response.StatusCode, body) } pointer := body["errors"].([]any)[0].(map[string]any)["pointer"] if pointer != "/groups/1/id" { t.Fatalf("pointer = %v, want /groups/1/id", pointer) } unknown := runBody(secretSource) unknown["candidate_id"] = "c-1" response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, unknown) if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" { t.Fatalf("unknown field = %d %v, want 400", response.StatusCode, body) } tooLarge := runBody(strings.Repeat("x", maxBody)) response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, tooLarge) if response.StatusCode != http.StatusRequestEntityTooLarge || body["code"] != "payload_too_large" { t.Fatalf("large body = %d %v, want 413", response.StatusCode, body) } response, body = server.do(t, http.MethodPut, "/v1/runs/not-a-uuid", testToken, runBody(secretSource)) if response.StatusCode != http.StatusBadRequest || body["code"] != "validation_failed" { t.Fatalf("invalid run ID = %d %v, want 400", response.StatusCode, body) } for name, checkerValue := range map[string]map[string]any{ "numbers without tolerance": {"kind": "numbers"}, "exact with tolerance": {"kind": "exact", "abs_tolerance": 0.1}, "custom without program": {"kind": "custom"}, "tokens with program": {"kind": "tokens", "program": map[string]any{"language": "python3", "source": "x"}}, } { invalid := runBody(secretSource) invalid["groups"].([]any)[0].(map[string]any)["checker"] = checkerValue response, body = server.do(t, http.MethodPut, runPath(uuid.New()), testToken, invalid) if response.StatusCode != http.StatusBadRequest || body["errors"].([]any)[0].(map[string]any)["pointer"] != "/groups/0/checker" { t.Fatalf("%s = %d %v, want 400 at /groups/0/checker", name, response.StatusCode, body) } } response, body = server.do(t, http.MethodGet, runPath(uuid.New()), testToken, nil) if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" { t.Fatalf("unknown run = %d %v, want 404", response.StatusCode, body) } response, body = server.do(t, http.MethodGet, "/v1/unknown", testToken, nil) if response.StatusCode != http.StatusNotFound || body["code"] != "not_found" { t.Fatalf("unknown route = %d %v, want 404", response.StatusCode, body) } }