package coderunner import ( "bytes" "crypto/sha256" "crypto/tls" "encoding/pem" "io" "net/http" "net/http/httptest" "strconv" "strings" "sync" "testing" "time" "lincodex/backend/internal/adapter/secondary/code_runner/api" "lincodex/backend/internal/port/outbound" "github.com/google/uuid" ) const ( testToken = "test-token-0123456789abcdef0123456789abcdef" testRunKey = "test-run-key-0123456789abcdef0123456789abcdef" ) // recordedRequest is what the fixture saw on the wire. type recordedRequest struct { Method string Path string Header http.Header Body []byte } // fixtureRunner is a local stand-in for the runner that speaks the protocol // of api/runner over TLS 1.3: bearer token, PUT and GET of /v1/runs/{id}, // idempotency by payload fingerprint, and the busy answer. type fixtureRunner struct { server *httptest.Server mu sync.Mutex runs map[string]*fixtureRun requests []recordedRequest started int // busy makes PUT of a new run answer 503 runner_busy. busy bool // pollsBeforeFinish is the number of GET calls that still see running. pollsBeforeFinish int // evaluate produces the result of a started run. evaluate func(request api.RunRequest) api.RunResult // override, when set, answers before the protocol does; it reports whether // it handled the request. override func(writer http.ResponseWriter, request *http.Request) bool } type fixtureRun struct { fingerprint [sha256.Size]byte result api.RunResult polls int } func newFixtureRunner(t *testing.T) *fixtureRunner { t.Helper() fixture := &fixtureRunner{ runs: make(map[string]*fixtureRun), evaluate: func(request api.RunRequest) api.RunResult { return resultFor(request, nil) }, } fixture.server = httptest.NewUnstartedServer(http.HandlerFunc(fixture.serve)) fixture.server.TLS = &tls.Config{MinVersion: tls.VersionTLS13} fixture.server.StartTLS() t.Cleanup(fixture.server.Close) return fixture } func (fixture *fixtureRunner) caPEM() []byte { return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: fixture.server.Certificate().Raw}) } func (fixture *fixtureRunner) settings() Settings { return Settings{ BaseURL: fixture.server.URL, Token: testToken, RunKey: testRunKey, CAPEM: fixture.caPEM(), RequestTimeout: 2 * time.Second, } } func (fixture *fixtureRunner) client(t *testing.T) *Client { t.Helper() client, err := NewClient(fixture.settings()) if err != nil { t.Fatalf("NewClient() error = %v", err) } return client } func (fixture *fixtureRunner) startedRuns() int { fixture.mu.Lock() defer fixture.mu.Unlock() return fixture.started } func (fixture *fixtureRunner) seen() []recordedRequest { fixture.mu.Lock() defer fixture.mu.Unlock() return append([]recordedRequest(nil), fixture.requests...) } func (fixture *fixtureRunner) serve(writer http.ResponseWriter, request *http.Request) { body, _ := io.ReadAll(request.Body) fixture.mu.Lock() fixture.requests = append(fixture.requests, recordedRequest{ Method: request.Method, Path: request.URL.Path, Header: request.Header.Clone(), Body: body, }) override := fixture.override fixture.mu.Unlock() if override != nil && override(writer, request) { return } if request.Header.Get("Authorization") != "Bearer "+testToken { writeProblem(writer, http.StatusUnauthorized, api.ProblemCodeUnauthenticated, nil) return } runID := strings.TrimPrefix(request.URL.Path, "/v1/runs/") switch request.Method { case http.MethodPut: fixture.put(writer, runID, body) case http.MethodGet: fixture.get(writer, runID) default: writeProblem(writer, http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed, nil) } } func (fixture *fixtureRunner) put(writer http.ResponseWriter, runID string, body []byte) { var payload api.RunRequest if err := payload.UnmarshalJSON(body); err != nil { writeProblem(writer, http.StatusBadRequest, api.ProblemCodeValidationFailed, nil) return } fingerprint := sha256.Sum256(body) fixture.mu.Lock() defer fixture.mu.Unlock() if existing, ok := fixture.runs[runID]; ok { if existing.fingerprint != fingerprint { writeProblem(writer, http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused, nil) return } writeStatus(writer, http.StatusOK, existing.status(runID, fixture.pollsBeforeFinish)) return } if fixture.busy { writeProblem(writer, http.StatusServiceUnavailable, api.ProblemCodeRunnerBusy, http.Header{"Retry-After": {"3"}}) return } run := &fixtureRun{fingerprint: fingerprint, result: fixture.evaluate(payload)} fixture.runs[runID] = run fixture.started++ parsed := uuid.MustParse(runID) writeStatus(writer, http.StatusAccepted, api.RunStatus{RunID: parsed, State: api.RunStateRunning}) } func (fixture *fixtureRunner) get(writer http.ResponseWriter, runID string) { fixture.mu.Lock() defer fixture.mu.Unlock() run, ok := fixture.runs[runID] if !ok { writeProblem(writer, http.StatusNotFound, api.ProblemCodeNotFound, nil) return } run.polls++ writeStatus(writer, http.StatusOK, run.status(runID, fixture.pollsBeforeFinish)) } func (run *fixtureRun) status(runID string, pollsBeforeFinish int) api.RunStatus { status := api.RunStatus{RunID: uuid.MustParse(runID), State: api.RunStateRunning} if run.polls >= pollsBeforeFinish { status.State = api.RunStateFinished status.Result = api.NewOptRunResult(run.result) } return status } func writeStatus(writer http.ResponseWriter, code int, status api.RunStatus) { // The generated types encode themselves; json.Marshal cannot encode an // unset optional field. body, err := status.MarshalJSON() if err != nil { panic(err) } writeJSON(writer, code, "application/json", body, nil) } func writeProblem(writer http.ResponseWriter, code int, problem api.ProblemCode, header http.Header) { body, err := (&api.Problem{ Type: "urn:lincodex:problem:" + string(problem), Title: "Problem", Status: int32(code), Code: problem, }).MarshalJSON() if err != nil { panic(err) } writeJSON(writer, code, "application/problem+json", body, header) } func writeJSON(writer http.ResponseWriter, code int, contentType string, body []byte, header http.Header) { for name, values := range header { for _, value := range values { writer.Header().Add(name, value) } } writer.Header().Set("Content-Type", contentType) writer.Header().Set("Content-Length", strconv.Itoa(len(body))) writer.WriteHeader(code) _, _ = writer.Write(body) } // resultFor builds the runner result for a request. failures maps a group ID // to the outcome of its first test; other groups pass. func resultFor(request api.RunRequest, failures map[string]api.RunOutcome) api.RunResult { result := api.RunResult{Outcome: api.RunOutcomeAccepted, DurationMs: 42} for _, group := range request.Groups { groupResult := api.GroupResult{ ID: group.ID, Visibility: group.Visibility, Outcome: api.RunOutcomeAccepted, TotalTests: int32(len(group.Tests)), } failure, failed := failures[string(group.ID)] for index, test := range group.Tests { testResult := api.TestResult{ID: test.ID, Outcome: api.RunOutcomeAccepted, TimeMs: 5, WallTimeMs: 7, MemoryKB: 2048} if failed && index == 0 { testResult.Outcome = failure if group.Visibility == api.TestVisibilityPublic { testResult.Diagnostic = api.NewOptString("stderr excerpt") } groupResult.Outcome = failure groupResult.Tests = append(groupResult.Tests, testResult) break } groupResult.PassedTests++ groupResult.Tests = append(groupResult.Tests, testResult) } if result.Outcome == api.RunOutcomeAccepted { result.Outcome = groupResult.Outcome } result.Groups = append(result.Groups, groupResult) } return result } // uniformResult gives every group the outcome of a run that stopped early. func uniformResult(request api.RunRequest, outcome api.RunOutcome) api.RunResult { result := api.RunResult{Outcome: outcome, DurationMs: 3} for _, group := range request.Groups { result.Groups = append(result.Groups, api.GroupResult{ ID: group.ID, Visibility: group.Visibility, Outcome: outcome, TotalTests: int32(len(group.Tests)), Tests: []api.TestResult{}, }) } return result } func compileErrorResult(request api.RunRequest) api.RunResult { result := uniformResult(request, api.RunOutcomeCompileError) result.Compile = api.NewOptCompileResult(api.CompileResult{ Outcome: api.RunOutcomeCompileError, Diagnostic: api.NewOptString("syntax error on line 1"), }) return result } func testRequest() outbound.CodeRunRequest { return outbound.CodeRunRequest{ Key: outbound.CodeRunKey{ AttemptItemID: uuid.MustParse("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"), SubmissionID: uuid.MustParse("5f4e3d2c-1b0a-4f9e-8d7c-6b5a49382716"), }, Language: outbound.CodeLanguagePython3, Source: "print(sum(map(int, input().split())))", Limits: outbound.CodeRunLimits{TimeLimitMs: 1000, MemoryLimitMB: 128, OutputLimitKB: 64}, Groups: []outbound.CodeTestGroup{ { ID: "public", Visibility: outbound.CodeTestPublic, Checker: outbound.CodeChecker{Kind: outbound.CodeCheckerExact}, Tests: []outbound.CodeTest{ {ID: "1", Input: "1 2\n", ExpectedOutput: "3\n"}, {ID: "2", Input: "5 7\n", ExpectedOutput: "12\n"}, }, }, { ID: "hidden-1", Visibility: outbound.CodeTestHidden, Checker: outbound.CodeChecker{Kind: outbound.CodeCheckerTokens}, Tests: []outbound.CodeTest{ {ID: "1", Input: "100 200\n", ExpectedOutput: "300\n"}, {ID: "2", Input: "-4 4\n", ExpectedOutput: "0\n"}, }, }, }, } } func containsBytes(haystack []byte, needle string) bool { return bytes.Contains(haystack, []byte(needle)) }