688 lines
26 KiB
Go
688 lines
26 KiB
Go
package coderunner
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"lincodex/backend/internal/adapter/secondary/code_runner/api"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
// submitAndPoll runs the normal flow against the fixture and returns the
|
|
// final status.
|
|
func submitAndPoll(t *testing.T, client *Client, request outbound.CodeRunRequest) outbound.CodeRunStatus {
|
|
t.Helper()
|
|
started, err := client.Submit(context.Background(), request)
|
|
if err != nil {
|
|
t.Fatalf("Submit() error = %v", err)
|
|
}
|
|
if started.State != outbound.CodeRunRunning {
|
|
t.Fatalf("Submit() state = %q, want running", started.State)
|
|
}
|
|
finished, err := client.Poll(context.Background(), request)
|
|
if err != nil {
|
|
t.Fatalf("Poll() error = %v", err)
|
|
}
|
|
return finished
|
|
}
|
|
|
|
func TestClientAcceptedRunSendsOnlyCodeTestsAndLimits(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
request := testRequest()
|
|
|
|
status := submitAndPoll(t, fixture.client(t), request)
|
|
|
|
if status.State != outbound.CodeRunFinished || status.Result == nil {
|
|
t.Fatalf("status = %+v, want finished with a result", status)
|
|
}
|
|
result := status.Result
|
|
if result.Outcome != outbound.CodeOutcomeAccepted || len(result.Groups) != 2 || result.Duration != 42*time.Millisecond {
|
|
t.Fatalf("result = %+v, want accepted over two groups", result)
|
|
}
|
|
for _, group := range result.Groups {
|
|
if group.Outcome != outbound.CodeOutcomeAccepted || group.PassedTests != 2 || group.TotalTests != 2 || len(group.Tests) != 2 {
|
|
t.Fatalf("group = %+v, want two of two tests accepted", group)
|
|
}
|
|
}
|
|
|
|
requests := fixture.seen()
|
|
if len(requests) != 2 || requests[0].Method != http.MethodPut || requests[1].Method != http.MethodGet {
|
|
t.Fatalf("requests = %d, want PUT then GET", len(requests))
|
|
}
|
|
var payload map[string]json.RawMessage
|
|
if err := json.Unmarshal(requests[0].Body, &payload); err != nil {
|
|
t.Fatalf("PUT body is not JSON: %v", err)
|
|
}
|
|
if len(payload) != 4 || payload["language"] == nil || payload["source"] == nil || payload["limits"] == nil || payload["groups"] == nil {
|
|
t.Fatalf("PUT body fields = %v, want language, source, limits, groups only", keysOf(payload))
|
|
}
|
|
for _, seen := range requests {
|
|
for _, identifier := range []string{
|
|
request.Key.AttemptItemID.String(), request.Key.SubmissionID.String(),
|
|
strings.ReplaceAll(request.Key.AttemptItemID.String(), "-", ""),
|
|
} {
|
|
if strings.Contains(seen.Path, identifier) || containsBytes(seen.Body, identifier) || strings.Contains(headerText(seen.Header), identifier) {
|
|
t.Fatalf("request %s %s carries an attempt or submission identifier", seen.Method, seen.Path)
|
|
}
|
|
}
|
|
if got := seen.Header.Get("Authorization"); got != "Bearer "+testToken {
|
|
t.Fatalf("Authorization header = %q, want the bearer token", got)
|
|
}
|
|
}
|
|
wantPath := "/v1/runs/" + deriveRunID([]byte(testRunKey), request.Key).String()
|
|
if requests[0].Path != wantPath || requests[1].Path != wantPath {
|
|
t.Fatalf("paths = %q and %q, want the derived opaque run ID %q", requests[0].Path, requests[1].Path, wantPath)
|
|
}
|
|
if status.RunID != wantPath[len("/v1/runs/"):] {
|
|
t.Fatalf("status.RunID = %q, want the derived run ID", status.RunID)
|
|
}
|
|
}
|
|
|
|
func keysOf(values map[string]json.RawMessage) []string {
|
|
keys := make([]string, 0, len(values))
|
|
for key := range values {
|
|
keys = append(keys, key)
|
|
}
|
|
return keys
|
|
}
|
|
|
|
func headerText(header http.Header) string {
|
|
var builder strings.Builder
|
|
for name, values := range header {
|
|
builder.WriteString(name + "=" + strings.Join(values, ",") + ";")
|
|
}
|
|
return builder.String()
|
|
}
|
|
|
|
func TestClientRetryReusesTheRunAndRunsItOnce(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
client := fixture.client(t)
|
|
request := testRequest()
|
|
|
|
first, err := client.Submit(context.Background(), request)
|
|
if err != nil {
|
|
t.Fatalf("first Submit() error = %v", err)
|
|
}
|
|
// A retry after a lost answer sends the same payload under the same key.
|
|
second, err := client.Submit(context.Background(), request)
|
|
if err != nil {
|
|
t.Fatalf("second Submit() error = %v", err)
|
|
}
|
|
if first.RunID != second.RunID || fixture.startedRuns() != 1 {
|
|
t.Fatalf("run IDs %q and %q, started runs %d, want one run under one ID", first.RunID, second.RunID, fixture.startedRuns())
|
|
}
|
|
|
|
// The same key with another payload must not change the stored run.
|
|
changed := testRequest()
|
|
changed.Source = "print(42)"
|
|
_, err = client.Submit(context.Background(), changed)
|
|
if !errors.Is(err, outbound.ErrCodeRunKeyReused) {
|
|
t.Fatalf("Submit(changed payload) error = %v, want ErrCodeRunKeyReused", err)
|
|
}
|
|
if errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("a reused key is a caller bug, not an unavailable runner: %v", err)
|
|
}
|
|
|
|
// A new generation starts a new run under a new ID.
|
|
changed.Key.Generation = 1
|
|
if _, err := client.Submit(context.Background(), changed); err != nil {
|
|
t.Fatalf("Submit(next generation) error = %v", err)
|
|
}
|
|
if fixture.startedRuns() != 2 {
|
|
t.Fatalf("started runs = %d, want 2", fixture.startedRuns())
|
|
}
|
|
}
|
|
|
|
func TestClientReturnsCandidateVerdictsAsResultsNotErrors(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
evaluate func(api.RunRequest) api.RunResult
|
|
want outbound.CodeRunOutcome
|
|
}{
|
|
{"wrong answer", func(r api.RunRequest) api.RunResult {
|
|
return resultFor(r, map[string]api.RunOutcome{"hidden-1": api.RunOutcomeWrongAnswer})
|
|
}, outbound.CodeOutcomeWrongAnswer},
|
|
{"time limit exceeded", func(r api.RunRequest) api.RunResult {
|
|
return resultFor(r, map[string]api.RunOutcome{"public": api.RunOutcomeTimeLimitExceeded})
|
|
}, outbound.CodeOutcomeTimeLimitExceeded},
|
|
{"memory limit exceeded", func(r api.RunRequest) api.RunResult {
|
|
return resultFor(r, map[string]api.RunOutcome{"hidden-1": api.RunOutcomeMemoryLimitExceeded})
|
|
}, outbound.CodeOutcomeMemoryLimitExceeded},
|
|
{"output limit exceeded", func(r api.RunRequest) api.RunResult {
|
|
return resultFor(r, map[string]api.RunOutcome{"public": api.RunOutcomeOutputLimitExceeded})
|
|
}, outbound.CodeOutcomeOutputLimitExceeded},
|
|
{"runtime error", func(r api.RunRequest) api.RunResult {
|
|
return resultFor(r, map[string]api.RunOutcome{"public": api.RunOutcomeRuntimeError})
|
|
}, outbound.CodeOutcomeRuntimeError},
|
|
{"compile error", compileErrorResult, outbound.CodeOutcomeCompileError},
|
|
}
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.evaluate = test.evaluate
|
|
|
|
status := submitAndPoll(t, fixture.client(t), testRequest())
|
|
|
|
if status.State != outbound.CodeRunFinished || status.Result == nil || status.Result.Outcome != test.want {
|
|
t.Fatalf("status = %+v, want a finished %s result", status, test.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestClientCompileErrorKeepsDiagnosticAndStopsTests(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.evaluate = compileErrorResult
|
|
|
|
result := submitAndPoll(t, fixture.client(t), testRequest()).Result
|
|
|
|
if result.Compile == nil || result.Compile.Outcome != outbound.CodeOutcomeCompileError || result.Compile.Diagnostic == "" {
|
|
t.Fatalf("compile = %+v, want a compile error with a diagnostic", result.Compile)
|
|
}
|
|
for _, group := range result.Groups {
|
|
if group.Outcome != outbound.CodeOutcomeCompileError || len(group.Tests) != 0 || group.PassedTests != 0 || group.TotalTests != 2 {
|
|
t.Fatalf("group = %+v, want no tests after a compile error", group)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestClientFailedGroupKeepsOtherGroupsAndDropsHiddenDiagnostics(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.evaluate = func(request api.RunRequest) api.RunResult {
|
|
result := resultFor(request, map[string]api.RunOutcome{
|
|
"public": api.RunOutcomeRuntimeError, "hidden-1": api.RunOutcomeWrongAnswer,
|
|
})
|
|
// A faulty runner that leaks a diagnostic of a hidden test.
|
|
result.Groups[1].Tests[0].Diagnostic = api.NewOptString("expected 300 got 299")
|
|
return result
|
|
}
|
|
|
|
result := submitAndPoll(t, fixture.client(t), testRequest()).Result
|
|
|
|
public, hidden := result.Groups[0], result.Groups[1]
|
|
if public.Outcome != outbound.CodeOutcomeRuntimeError || public.PassedTests != 0 || public.Tests[0].Diagnostic == "" {
|
|
t.Fatalf("public group = %+v, want a runtime error with its diagnostic", public)
|
|
}
|
|
if hidden.Outcome != outbound.CodeOutcomeWrongAnswer || hidden.Tests[0].Diagnostic != "" {
|
|
t.Fatalf("hidden group = %+v, want a wrong answer without a diagnostic", hidden)
|
|
}
|
|
if result.Outcome != outbound.CodeOutcomeRuntimeError {
|
|
t.Fatalf("run outcome = %q, want the first failed group's outcome", result.Outcome)
|
|
}
|
|
}
|
|
|
|
func TestClientPollSeesRunningThenFinished(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.pollsBeforeFinish = 2
|
|
client := fixture.client(t)
|
|
request := testRequest()
|
|
if _, err := client.Submit(context.Background(), request); err != nil {
|
|
t.Fatalf("Submit() error = %v", err)
|
|
}
|
|
|
|
states := make([]outbound.CodeRunState, 0, 3)
|
|
for range 3 {
|
|
status, err := client.Poll(context.Background(), request)
|
|
if err != nil {
|
|
t.Fatalf("Poll() error = %v", err)
|
|
}
|
|
if status.State == outbound.CodeRunRunning && status.Result != nil {
|
|
t.Fatalf("a running status carries a result: %+v", status)
|
|
}
|
|
states = append(states, status.State)
|
|
}
|
|
want := []outbound.CodeRunState{outbound.CodeRunRunning, outbound.CodeRunFinished, outbound.CodeRunFinished}
|
|
if strings.Join(statesText(states), ",") != strings.Join(statesText(want), ",") {
|
|
t.Fatalf("states = %v, want %v", states, want)
|
|
}
|
|
}
|
|
|
|
func statesText(states []outbound.CodeRunState) []string {
|
|
text := make([]string, 0, len(states))
|
|
for _, state := range states {
|
|
text = append(text, string(state))
|
|
}
|
|
return text
|
|
}
|
|
|
|
func TestClientBusyKeepsTheKeyAndReportsRetryAfter(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.busy = true
|
|
client := fixture.client(t)
|
|
|
|
status, err := client.Submit(context.Background(), testRequest())
|
|
|
|
if err != nil {
|
|
t.Fatalf("Submit() error = %v, want a busy status", err)
|
|
}
|
|
if status.State != outbound.CodeRunBusy || status.RetryAfter != 3*time.Second || status.Result != nil {
|
|
t.Fatalf("status = %+v, want busy with Retry-After 3s", status)
|
|
}
|
|
if fixture.startedRuns() != 0 {
|
|
t.Fatalf("started runs = %d, want none while busy", fixture.startedRuns())
|
|
}
|
|
|
|
fixture.mu.Lock()
|
|
fixture.busy = false
|
|
fixture.mu.Unlock()
|
|
retried, err := client.Submit(context.Background(), testRequest())
|
|
if err != nil || retried.State != outbound.CodeRunRunning || retried.RunID != status.RunID {
|
|
t.Fatalf("retry = %+v, %v, want the run started under the same ID", retried, err)
|
|
}
|
|
}
|
|
|
|
func TestClientRunnerInfrastructureFailureIsNotAVerdict(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.evaluate = func(request api.RunRequest) api.RunResult {
|
|
return uniformResult(request, api.RunOutcomeInfrastructureFailure)
|
|
}
|
|
client := fixture.client(t)
|
|
request := testRequest()
|
|
if _, err := client.Submit(context.Background(), request); err != nil {
|
|
t.Fatalf("Submit() error = %v", err)
|
|
}
|
|
|
|
status, err := client.Poll(context.Background(), request)
|
|
|
|
if !errors.Is(err, outbound.ErrCodeRunnerInfrastructureFailure) || !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("Poll() error = %v, want ErrCodeRunnerInfrastructureFailure under ErrCodeRunnerUnavailable", err)
|
|
}
|
|
if status != (outbound.CodeRunStatus{}) {
|
|
t.Fatalf("Poll() status = %+v, want the zero status next to an error", status)
|
|
}
|
|
}
|
|
|
|
func TestClientMapsRunnerErrorsToInfrastructureErrors(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
answer func(http.ResponseWriter)
|
|
want error
|
|
}{
|
|
{"wrong token", func(w http.ResponseWriter) {
|
|
writeProblem(w, http.StatusUnauthorized, api.ProblemCodeUnauthenticated, nil)
|
|
}, outbound.ErrCodeRunnerUnauthorized},
|
|
{"internal error", func(w http.ResponseWriter) {
|
|
writeProblem(w, http.StatusInternalServerError, api.ProblemCodeInternal, nil)
|
|
}, outbound.ErrCodeRunnerUnavailable},
|
|
{"bad gateway page", func(w http.ResponseWriter) {
|
|
writeJSON(w, http.StatusBadGateway, "text/html", []byte("<html>502</html>"), nil)
|
|
}, outbound.ErrCodeRunnerBadResponse},
|
|
{"busy without Retry-After", func(w http.ResponseWriter) {
|
|
writeProblem(w, http.StatusServiceUnavailable, api.ProblemCodeRunnerBusy, nil)
|
|
}, outbound.ErrCodeRunnerBadResponse},
|
|
{"503 that is not busy", func(w http.ResponseWriter) {
|
|
writeProblem(w, http.StatusServiceUnavailable, api.ProblemCodeInternal, http.Header{"Retry-After": {"1"}})
|
|
}, outbound.ErrCodeRunnerUnavailable},
|
|
{"runner rejects the payload", func(w http.ResponseWriter) {
|
|
writeProblem(w, http.StatusBadRequest, api.ProblemCodeValidationFailed, nil)
|
|
}, outbound.ErrInvalidCodeRunRequest},
|
|
{"payload too large", func(w http.ResponseWriter) {
|
|
writeProblem(w, http.StatusRequestEntityTooLarge, api.ProblemCodePayloadTooLarge, nil)
|
|
}, outbound.ErrInvalidCodeRunRequest},
|
|
{"unsupported media type", func(w http.ResponseWriter) {
|
|
writeProblem(w, http.StatusUnsupportedMediaType, api.ProblemCodeUnsupportedMediaType, nil)
|
|
}, outbound.ErrCodeRunnerBadResponse},
|
|
}
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.override = func(w http.ResponseWriter, _ *http.Request) bool {
|
|
test.answer(w)
|
|
return true
|
|
}
|
|
|
|
status, err := fixture.client(t).Submit(context.Background(), testRequest())
|
|
|
|
if !errors.Is(err, test.want) {
|
|
t.Fatalf("Submit() error = %v, want %v", err, test.want)
|
|
}
|
|
if !errors.Is(err, outbound.ErrInvalidCodeRunRequest) && !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("Submit() error = %v, want it under ErrCodeRunnerUnavailable", err)
|
|
}
|
|
if status != (outbound.CodeRunStatus{}) {
|
|
t.Fatalf("status = %+v, want the zero status next to an error", status)
|
|
}
|
|
if strings.Contains(err.Error(), testToken) || strings.Contains(err.Error(), fixture.server.URL) {
|
|
t.Fatalf("error exposes the token or the runner URL: %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestClientPollReportsALostRun(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
|
|
status, err := fixture.client(t).Poll(context.Background(), testRequest())
|
|
|
|
if !errors.Is(err, outbound.ErrCodeRunNotFound) || errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("Poll() error = %v, want ErrCodeRunNotFound only", err)
|
|
}
|
|
if status != (outbound.CodeRunStatus{}) {
|
|
t.Fatalf("status = %+v, want the zero status", status)
|
|
}
|
|
}
|
|
|
|
func TestClientRejectsMalformedResponses(t *testing.T) {
|
|
good := func(request api.RunRequest) api.RunResult { return resultFor(request, nil) }
|
|
tests := []struct {
|
|
name string
|
|
// raw answers GET with a raw body instead of the protocol.
|
|
raw string
|
|
evaluate func(api.RunRequest) api.RunResult
|
|
mutate func(*api.RunResult)
|
|
}{
|
|
{name: "not JSON", raw: "{not json"},
|
|
{name: "empty body", raw: ""},
|
|
{name: "unknown outcome", raw: `{"run_id":"%s","state":"finished","result":{"outcome":"great","groups":[],"duration_ms":1}}`},
|
|
{name: "finished without a result", raw: `{"run_id":"%s","state":"finished"}`},
|
|
{name: "running with a result", raw: `{"run_id":"%s","state":"running","result":{"outcome":"accepted","groups":[],"duration_ms":1}}`},
|
|
{name: "another run ID", raw: `{"run_id":"11111111-1111-4111-8111-111111111111","state":"running"}`},
|
|
{name: "unknown state", raw: `{"run_id":"%s","state":"queued"}`},
|
|
{name: "trailing data", raw: `{"run_id":"%s","state":"running"} {}`},
|
|
{name: "missing group", evaluate: good, mutate: func(r *api.RunResult) { r.Groups = r.Groups[:1] }},
|
|
{name: "wrong group ID", evaluate: good, mutate: func(r *api.RunResult) { r.Groups[0].ID = "other" }},
|
|
{name: "wrong visibility", evaluate: good, mutate: func(r *api.RunResult) { r.Groups[1].Visibility = api.TestVisibilityPublic }},
|
|
{name: "wrong total", evaluate: good, mutate: func(r *api.RunResult) { r.Groups[0].TotalTests = 3 }},
|
|
{name: "passed above evaluated", evaluate: good, mutate: func(r *api.RunResult) { r.Groups[0].PassedTests = 1 }},
|
|
{name: "wrong test ID", evaluate: good, mutate: func(r *api.RunResult) { r.Groups[0].Tests[1].ID = "9" }},
|
|
{name: "accepted run with a failed group", evaluate: good, mutate: func(r *api.RunResult) {
|
|
r.Groups[1].Outcome = api.RunOutcomeWrongAnswer
|
|
r.Groups[1].Tests[1].Outcome = api.RunOutcomeWrongAnswer
|
|
r.Groups[1].PassedTests = 1
|
|
}},
|
|
{name: "accepted group with a missing test", evaluate: good, mutate: func(r *api.RunResult) {
|
|
r.Groups[0].Tests = r.Groups[0].Tests[:1]
|
|
r.Groups[0].PassedTests = 1
|
|
}},
|
|
{name: "test after a failed one", evaluate: good, mutate: func(r *api.RunResult) {
|
|
r.Outcome = api.RunOutcomeWrongAnswer
|
|
r.Groups[0].Outcome = api.RunOutcomeWrongAnswer
|
|
r.Groups[0].Tests[0].Outcome = api.RunOutcomeWrongAnswer
|
|
r.Groups[0].PassedTests = 0
|
|
}},
|
|
{name: "infrastructure outcome in a test", evaluate: good, mutate: func(r *api.RunResult) {
|
|
r.Groups[0].Tests[1].Outcome = api.RunOutcomeInfrastructureFailure
|
|
}},
|
|
{name: "compile error without compile result", evaluate: compileErrorResult, mutate: func(r *api.RunResult) { r.Compile = api.OptCompileResult{} }},
|
|
{name: "compile error with tests", evaluate: compileErrorResult, mutate: func(r *api.RunResult) {
|
|
r.Groups[0].Tests = []api.TestResult{{ID: "1", Outcome: api.RunOutcomeAccepted}}
|
|
}},
|
|
{name: "accepted run with a failed compile", evaluate: good, mutate: func(r *api.RunResult) {
|
|
r.Compile = api.NewOptCompileResult(api.CompileResult{Outcome: api.RunOutcomeCompileError})
|
|
}},
|
|
}
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
if test.evaluate != nil {
|
|
fixture.evaluate = func(request api.RunRequest) api.RunResult {
|
|
result := test.evaluate(request)
|
|
test.mutate(&result)
|
|
return result
|
|
}
|
|
}
|
|
client := fixture.client(t)
|
|
request := testRequest()
|
|
if _, err := client.Submit(context.Background(), request); err != nil {
|
|
t.Fatalf("Submit() error = %v", err)
|
|
}
|
|
if test.raw != "" || test.name == "empty body" {
|
|
runID := deriveRunID([]byte(testRunKey), request.Key).String()
|
|
body := strings.ReplaceAll(test.raw, "%s", runID)
|
|
fixture.override = func(w http.ResponseWriter, r *http.Request) bool {
|
|
if r.Method != http.MethodGet {
|
|
return false
|
|
}
|
|
writeJSON(w, http.StatusOK, "application/json", []byte(body), nil)
|
|
return true
|
|
}
|
|
}
|
|
|
|
status, err := client.Poll(context.Background(), request)
|
|
|
|
if !errors.Is(err, outbound.ErrCodeRunnerBadResponse) || !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("Poll() = %+v, %v, want ErrCodeRunnerBadResponse", status, err)
|
|
}
|
|
if status != (outbound.CodeRunStatus{}) {
|
|
t.Fatalf("status = %+v, want the zero status next to an error", status)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestClientRejectsAnAcceptedAnswerThatIsFinished(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.override = func(w http.ResponseWriter, r *http.Request) bool {
|
|
if r.Method != http.MethodPut {
|
|
return false
|
|
}
|
|
runID := strings.TrimPrefix(r.URL.Path, "/v1/runs/")
|
|
body := `{"run_id":"` + runID + `","state":"finished","result":{"outcome":"accepted","groups":[],"duration_ms":1}}`
|
|
writeJSON(w, http.StatusAccepted, "application/json", []byte(body), nil)
|
|
return true
|
|
}
|
|
|
|
_, err := fixture.client(t).Submit(context.Background(), testRequest())
|
|
|
|
if !errors.Is(err, outbound.ErrCodeRunnerBadResponse) {
|
|
t.Fatalf("Submit() error = %v, want ErrCodeRunnerBadResponse", err)
|
|
}
|
|
}
|
|
|
|
func TestClientRejectsAnOversizedResponse(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.override = func(w http.ResponseWriter, _ *http.Request) bool {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusOK)
|
|
filler := []byte(strings.Repeat(" ", 1<<20))
|
|
for range 6 {
|
|
if _, err := w.Write(filler); err != nil {
|
|
return true
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
_, err := fixture.client(t).Poll(context.Background(), testRequest())
|
|
|
|
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("Poll() error = %v, want an infrastructure error", err)
|
|
}
|
|
}
|
|
|
|
func TestClientTimesOutWithoutAVerdict(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.override = func(_ http.ResponseWriter, r *http.Request) bool {
|
|
select {
|
|
case <-r.Context().Done():
|
|
case <-time.After(5 * time.Second):
|
|
}
|
|
return true
|
|
}
|
|
settings := fixture.settings()
|
|
settings.RequestTimeout = 150 * time.Millisecond
|
|
client, err := NewClient(settings)
|
|
if err != nil {
|
|
t.Fatalf("NewClient() error = %v", err)
|
|
}
|
|
|
|
status, err := client.Submit(context.Background(), testRequest())
|
|
|
|
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("Submit() error = %v, want ErrCodeRunnerUnavailable", err)
|
|
}
|
|
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, outbound.ErrCodeRunNotFound) {
|
|
t.Fatalf("Submit() error = %v, want a runner timeout, not the caller's deadline", err)
|
|
}
|
|
if status != (outbound.CodeRunStatus{}) {
|
|
t.Fatalf("status = %+v, want the zero status", status)
|
|
}
|
|
}
|
|
|
|
func TestClientReportsTheCallerContext(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
client := fixture.client(t)
|
|
|
|
canceled, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
_, err := client.Submit(canceled, testRequest())
|
|
if !errors.Is(err, context.Canceled) || errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("Submit(canceled) error = %v, want context.Canceled only", err)
|
|
}
|
|
if len(fixture.seen()) != 0 {
|
|
t.Fatal("a canceled context still reached the runner")
|
|
}
|
|
|
|
fixture.override = func(_ http.ResponseWriter, r *http.Request) bool {
|
|
<-r.Context().Done()
|
|
return true
|
|
}
|
|
deadline, cancelDeadline := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
|
defer cancelDeadline()
|
|
_, err = client.Poll(deadline, testRequest())
|
|
if !errors.Is(err, context.DeadlineExceeded) {
|
|
t.Fatalf("Poll(deadline) error = %v, want context.DeadlineExceeded", err)
|
|
}
|
|
}
|
|
|
|
func TestClientStoppedRunnerIsUnavailableWithoutAVerdict(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
client := fixture.client(t)
|
|
fixture.server.Close()
|
|
|
|
for name, call := range map[string]func(context.Context, outbound.CodeRunRequest) (outbound.CodeRunStatus, error){
|
|
"Submit": client.Submit, "Poll": client.Poll,
|
|
} {
|
|
status, err := call(context.Background(), testRequest())
|
|
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("%s() error = %v, want ErrCodeRunnerUnavailable", name, err)
|
|
}
|
|
// Nothing a caller could read as a verdict or as progress.
|
|
if status != (outbound.CodeRunStatus{}) || status.Result != nil || status.State != "" {
|
|
t.Fatalf("%s() status = %+v, want the zero status", name, status)
|
|
}
|
|
if strings.Contains(err.Error(), fixture.server.URL) || strings.Contains(err.Error(), testToken) {
|
|
t.Fatalf("%s() error exposes the runner URL or the token: %v", name, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestClientVerifiesTheRunnerCertificateAgainstTheConfiguredCA(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
|
|
settings := fixture.settings()
|
|
settings.CAPEM = foreignCAPEM(t) // a CA that did not sign this runner
|
|
client, err := NewClient(settings)
|
|
if err != nil {
|
|
t.Fatalf("NewClient() error = %v", err)
|
|
}
|
|
|
|
_, err = client.Submit(context.Background(), testRequest())
|
|
|
|
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("Submit() error = %v, want ErrCodeRunnerUnavailable", err)
|
|
}
|
|
if len(fixture.seen()) != 0 {
|
|
t.Fatal("the request reached a runner whose certificate does not match the CA, so the token was sent to it")
|
|
}
|
|
}
|
|
|
|
func TestClientRefusesRunnerWithoutTLS13(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
fixture.server.Close()
|
|
legacy := httptest.NewUnstartedServer(http.HandlerFunc(fixture.serve))
|
|
legacy.TLS = &tls.Config{MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12}
|
|
legacy.StartTLS()
|
|
t.Cleanup(legacy.Close)
|
|
// The servers share one certificate, which the CA trusts, so the only
|
|
// reason left to fail is the protocol version.
|
|
settings := fixture.settings()
|
|
settings.BaseURL = legacy.URL
|
|
client, err := NewClient(settings)
|
|
if err != nil {
|
|
t.Fatalf("NewClient() error = %v", err)
|
|
}
|
|
|
|
_, err = client.Submit(context.Background(), testRequest())
|
|
|
|
if !errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("Submit() error = %v, want ErrCodeRunnerUnavailable", err)
|
|
}
|
|
if len(fixture.seen()) != 0 {
|
|
t.Fatal("a TLS 1.2 connection carried the request")
|
|
}
|
|
}
|
|
|
|
func TestClientRejectsInvalidRequestsBeforeSending(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
client := fixture.client(t)
|
|
request := testRequest()
|
|
request.Limits.TimeLimitMs = 10
|
|
|
|
for name, call := range map[string]func(context.Context, outbound.CodeRunRequest) (outbound.CodeRunStatus, error){
|
|
"Submit": client.Submit, "Poll": client.Poll,
|
|
} {
|
|
_, err := call(context.Background(), request)
|
|
if !errors.Is(err, outbound.ErrInvalidCodeRunRequest) || errors.Is(err, outbound.ErrCodeRunnerUnavailable) {
|
|
t.Fatalf("%s() error = %v, want ErrInvalidCodeRunRequest only", name, err)
|
|
}
|
|
}
|
|
if len(fixture.seen()) != 0 {
|
|
t.Fatal("an invalid request reached the runner")
|
|
}
|
|
}
|
|
|
|
func TestNewClientValidatesSettings(t *testing.T) {
|
|
fixture := newFixtureRunner(t)
|
|
valid := fixture.settings()
|
|
tests := []struct {
|
|
name string
|
|
change func(*Settings)
|
|
}{
|
|
{"plain http", func(s *Settings) { s.BaseURL = "http://runner.internal:8443" }},
|
|
{"path in URL", func(s *Settings) { s.BaseURL = "https://runner.internal:8443/api" }},
|
|
{"credentials in URL", func(s *Settings) { s.BaseURL = "https://user:pass@runner.internal" }},
|
|
{"no host", func(s *Settings) { s.BaseURL = "https://" }},
|
|
{"empty token", func(s *Settings) { s.Token = "" }},
|
|
{"token with space", func(s *Settings) { s.Token = "bad token" }},
|
|
{"short run key", func(s *Settings) { s.RunKey = "short" }},
|
|
{"no CA", func(s *Settings) { s.CAPEM = nil }},
|
|
{"CA that is not PEM", func(s *Settings) { s.CAPEM = []byte("not a certificate") }},
|
|
{"zero timeout", func(s *Settings) { s.RequestTimeout = 0 }},
|
|
}
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
settings := valid
|
|
test.change(&settings)
|
|
|
|
client, err := NewClient(settings)
|
|
|
|
if err == nil || client != nil {
|
|
t.Fatalf("NewClient() = %v, %v, want an error", client, err)
|
|
}
|
|
if strings.Contains(err.Error(), testToken) || strings.Contains(err.Error(), testRunKey) {
|
|
t.Fatalf("error exposes a secret: %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestSettingsRedactSecrets(t *testing.T) {
|
|
settings := Settings{BaseURL: "https://runner", Token: testToken, RunKey: testRunKey}
|
|
for _, rendered := range []string{
|
|
settings.String(), settings.LogValue().String(),
|
|
formatWith("%v", settings), formatWith("%+v", settings), formatWith("%#v", settings),
|
|
} {
|
|
if strings.Contains(rendered, testToken) || strings.Contains(rendered, testRunKey) {
|
|
t.Fatalf("settings rendering exposes a secret: %q", rendered)
|
|
}
|
|
}
|
|
}
|