package runnerapi import ( "bytes" "encoding/json" "fmt" "hash/crc32" "net/http" "net/http/httptest" "os" "strings" "testing" "tangled.org/dracoblue.de/shuttle/internal/queue" ) func testAPI(t *testing.T, withJob bool) (*API, *queue.Memory) { t.Helper() q := queue.NewMemory() if withJob { _, _ = q.Enqueue(t.Context(), queue.Job{RepoURL: "https://user:secret@example.com/repo.git", SHA: strings.Repeat("a", 40), Ref: "refs/heads/main", Image: queue.Image{Name: "alpine:3"}, Script: []string{"echo ok"}, JobName: "test"}) } a := New(Config{Queue: q, Verify: func(_ *http.Request, token string) (bool, error) { return token == "runner", nil }, Token: func() (string, error) { return "job-token", nil }}) return a, q } func requestJob(t *testing.T, a *API) *httptest.ResponseRecorder { r := httptest.NewRequest("POST", "/api/v4/jobs/request", strings.NewReader(`{"token":"runner","last_update":"ignored"}`)) w := httptest.NewRecorder() a.Handler().ServeHTTP(w, r) return w } func TestEmptyQueue(t *testing.T) { a, _ := testAPI(t, false) if got := requestJob(t, a).Code; got != 204 { t.Fatalf("status %d", got) } } func TestJobFixture(t *testing.T) { a, _ := testAPI(t, true) got := requestJob(t, a) want, err := os.ReadFile("testdata/job_response.json") if err != nil { t.Fatal(err) } var gv, wv any if json.Unmarshal(got.Body.Bytes(), &gv) != nil || json.Unmarshal(want, &wv) != nil { t.Fatal("invalid JSON") } gb, _ := json.MarshalIndent(gv, "", " ") wb, _ := json.MarshalIndent(wv, "", " ") if !bytes.Equal(gb, wb) { t.Fatalf("response mismatch\ngot %s\nwant %s", gb, wb) } } func TestJobWithOptionsFixture(t *testing.T) { q := queue.NewMemory() _, _ = q.Enqueue(t.Context(), queue.Job{ RepoURL: "https://user:secret@example.com/repo.git", SHA: strings.Repeat("a", 40), Ref: "refs/heads/main", Image: queue.Image{ Name: "alpine:3", ExecutorOptions: &queue.ExecutorOptions{ Docker: &queue.DockerOptions{ Platform: "linux/amd64", User: "1000", }, }, }, Services: []queue.Image{ { Name: "postgres:15", ExecutorOptions: &queue.ExecutorOptions{ Docker: &queue.DockerOptions{ Platform: "linux/amd64", User: "postgres", }, }, }, }, Hooks: []queue.Hook{ { Name: "pre_get_sources_script", Script: []string{"echo pre-1", "echo pre-2"}, }, }, Variables: []queue.Variable{ {Key: "EXPAND_VAR", Value: "val1", Public: true, Raw: false}, {Key: "RAW_VAR", Value: "val2", Public: true, Raw: true}, }, Script: []string{"echo ok"}, JobName: "test", }) a := New(Config{ Queue: q, Verify: func(_ *http.Request, token string) (bool, error) { return token == "runner", nil }, Token: func() (string, error) { return "job-token", nil }, }) got := requestJob(t, a) want, err := os.ReadFile("testdata/job_response_options.json") if err != nil { t.Fatal(err) } var gv, wv any if json.Unmarshal(got.Body.Bytes(), &gv) != nil || json.Unmarshal(want, &wv) != nil { t.Fatal("invalid JSON") } gb, _ := json.MarshalIndent(gv, "", " ") wb, _ := json.MarshalIndent(wv, "", " ") if !bytes.Equal(gb, wb) { t.Fatalf("response mismatch\ngot %s\nwant %s", gb, wb) } } func TestTraceRanges(t *testing.T) { a, _ := testAPI(t, true) requestJob(t, a) patch := func(rng, body string) *httptest.ResponseRecorder { r := httptest.NewRequest("PATCH", "/api/v4/jobs/1/trace", strings.NewReader(body)) r.Header.Set("JOB-TOKEN", "job-token") r.Header.Set("Content-Range", rng) w := httptest.NewRecorder() a.Handler().ServeHTTP(w, r) return w } if got := patch("0-2", "abc").Code; got != 202 { t.Fatalf("accept status %d", got) } w := patch("1-2", "xx") if w.Code != 416 || w.Header().Get("Range") != "0-2" { t.Fatalf("mismatch status=%d Range=%q", w.Code, w.Header().Get("Range")) } } func TestStepsAndCache(t *testing.T) { j := queue.Job{BeforeScript: []string{"echo before"}, Script: []string{"echo script"}, AfterScript: []string{"echo after"}, Cache: []queue.Cache{{Key: "key", Paths: []string{"cached/"}, Policy: "pull-push", When: "always", FallbackKeys: []string{"old"}}}} body := JobResponseWithTimeout(j, "token", 123) steps := body["steps"].([]any) first := steps[0].(map[string]any) after := steps[1].(map[string]any) if got := first["script"].([]string); len(got) != 2 || got[0] != "echo before" || got[1] != "echo script" { t.Fatalf("script=%v", got) } if first["timeout"] != 123 || after["timeout"] != 123 || after["when"] != "always" || after["allow_failure"] != true { t.Fatalf("steps=%#v", steps) } if got := body["cache"].([]queue.Cache); len(got) != 1 || got[0].Key != "key" { t.Fatalf("cache=%#v", got) } } func TestJobTimeoutOverridesServerDefault(t *testing.T) { j := queue.Job{TimeoutSeconds: 10, Script: []string{"sleep 60"}} body := JobResponseWithTimeout(j, "token", j.TimeoutSeconds) if body["runner_info"].(map[string]any)["timeout"] != 10 || body["steps"].([]any)[0].(map[string]any)["timeout"] != 10 { t.Fatalf("body=%+v", body) } } func TestChecksumAndTokenExpiry(t *testing.T) { a, _ := testAPI(t, true) requestJob(t, a) r := httptest.NewRequest("PATCH", "/api/v4/jobs/1/trace", strings.NewReader("abc")) r.Header.Set("JOB-TOKEN", "job-token") r.Header.Set("Content-Range", "0-2") a.Handler().ServeHTTP(httptest.NewRecorder(), r) put := func(checksum string) *httptest.ResponseRecorder { body := fmt.Sprintf(`{"state":"success","output":{"bytesize":3,"checksum":%q}}`, checksum) r := httptest.NewRequest("PUT", "/api/v4/jobs/1", strings.NewReader(body)) r.Header.Set("JOB-TOKEN", "job-token") w := httptest.NewRecorder() a.Handler().ServeHTTP(w, r) return w } if got := put("crc32:bad").Code; got != 412 { t.Fatalf("checksum status %d", got) } if got := put(fmt.Sprintf("crc32:%08x", crc32.ChecksumIEEE([]byte("abc")))).Code; got != 200 { t.Fatalf("finish status %d", got) } if got := put(fmt.Sprintf("crc32:%08x", crc32.ChecksumIEEE([]byte("abc")))).Code; got != 403 { t.Fatalf("expired token status %d", got) } } func TestRunningUpdateReturnsOK(t *testing.T) { a, _ := testAPI(t, true) requestJob(t, a) body := `{"state":"running","output":{"bytesize":0,"checksum":"crc32:00000000"}}` r := httptest.NewRequest("PUT", "/api/v4/jobs/1", strings.NewReader(body)) r.Header.Set("JOB-TOKEN", "job-token") w := httptest.NewRecorder() a.Handler().ServeHTTP(w, r) if w.Code != http.StatusOK { t.Fatalf("running update status = %d, want %d", w.Code, http.StatusOK) } if got := requestJob(t, a).Code; got != http.StatusNoContent { t.Fatalf("claimed job became available after running update: status %d", got) } } func TestJobInfoProjectIDPerRepo(t *testing.T) { a := JobResponse(queue.Job{ID: 1, RepoDID: "did:plc:aaaa", JobName: "build", Stage: "test", Ref: "refs/heads/main"}, "t") b := JobResponse(queue.Job{ID: 2, RepoDID: "did:plc:bbbb", JobName: "build", Stage: "test", Ref: "refs/heads/main"}, "t") ia, ib := a["job_info"].(map[string]any), b["job_info"].(map[string]any) if ia["project_id"].(int64) <= 0 || ia["project_id"] == ib["project_id"] { t.Fatalf("project ids must be positive and differ per repo: %v %v", ia["project_id"], ib["project_id"]) } if ProjectID("did:plc:aaaa") != ia["project_id"] { t.Fatal("project id must be stable") } if ia["name"] != "build" || ia["stage"] != "test" { t.Fatalf("job_info = %v", ia) } }