Files
otche-backend/internal/api/job_summary_test.go
T

412 lines
17 KiB
Go

package api
import (
"context"
"encoding/json"
"io"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"otche/internal/store"
)
func TestJobSummariesIncludeAssignedProfile(t *testing.T) {
url := os.Getenv("OTCHE_TEST_DATABASE_URL")
if url == "" {
t.Skip("OTCHE_TEST_DATABASE_URL required for isolated PostgreSQL regression")
}
ctx := context.Background()
admin, err := pgxpool.New(ctx, url)
if err != nil {
t.Fatal(err)
}
defer admin.Close()
schema := "test_" + strings.ReplaceAll(store.NewID(), "-", "")
if _, err = admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
t.Fatal(err)
}
defer admin.Exec(ctx, "DROP SCHEMA "+schema+" CASCADE")
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
t.Fatal(err)
}
cfg.ConnConfig.RuntimeParams["search_path"] = schema
db, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if err = store.Migrate(ctx, db); err != nil {
t.Fatal(err)
}
owner, err := CreateUser(ctx, db, "summary-admin", "Regression-only-long-password", "admin")
if err != nil {
t.Fatal(err)
}
upload, profile, revision, job, run, attempt, artifact := store.NewID(), store.NewID(), store.NewID(), store.NewID(), store.NewID(), store.NewID(), store.NewID()
if _, err = db.Exec(ctx, `INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key) VALUES($1,$2,'panel-bat-smoke.bat',187,$3,$4)`, upload, owner, strings.Repeat("a", 64), upload); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO profiles(id,name,os,architecture,enabled,qualification,state,current_revision_id) VALUES($1,'Windows 11 Pro 25H2 - VM7001','Windows 11','x64',true,'qualified','published',$2)`, profile, revision); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest) VALUES($1,$2,'win11','fingerprint','config')`, revision, profile); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO jobs(id,owner_id,upload_id,execution_filename,status,settings) VALUES($1,$2,$3,'panel-bat-smoke.bat','completed','{"internet":"offline","duration_seconds":30}')`, job, owner, upload); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO runs(id,job_id,profile_id,revision_id,profile_name,status) SELECT $1,$2,id,$4,name,'completed' FROM profiles WHERE id=$3`, run, job, profile, revision); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO attempts(id,run_id,command_id,phase,outcome,findings,telemetry,cleanup,report) VALUES($1,$2,$3,'finished','executed','not_observed','complete','complete','{"execution":{"exit_code":0}}')`, attempt, run, store.NewID()); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO artifacts(id,job_id,attempt_id,kind,filename,content_type,size,sha256,storage_key) VALUES($1,$2,$3,'report','report.json','application/json',27,$4,$5)`, artifact, job, attempt, strings.Repeat("b", 64), artifact); err != nil {
t.Fatal(err)
}
s, err := New(db, Config{Origin: "http://localhost", ArtifactRoot: t.TempDir(), MaxQueuedJobs: 20})
if err != nil {
t.Fatal(err)
}
login := httptest.NewRequest("POST", "/api/v1/auth/login", strings.NewReader(`{"username":"summary-admin","password":"Regression-only-long-password"}`))
login.Header.Set("Origin", "http://localhost")
logged := httptest.NewRecorder()
s.ServeHTTP(logged, login)
if logged.Code != 200 {
t.Fatalf("login: %d %s", logged.Code, logged.Body)
}
cookie := logged.Result().Cookies()[0]
for _, endpoint := range []string{"/api/v1/dashboard", "/api/v1/jobs"} {
req := httptest.NewRequest("GET", endpoint, nil)
req.AddCookie(cookie)
res := httptest.NewRecorder()
s.ServeHTTP(res, req)
if res.Code != 200 {
t.Fatalf("%s: %d %s", endpoint, res.Code, res.Body)
}
var body struct {
RecentJobs []struct {
Runs []struct {
ProfileName string `json:"profile_name"`
} `json:"runs"`
} `json:"recent_jobs"`
Items []struct {
Runs []struct {
ProfileName string `json:"profile_name"`
} `json:"runs"`
} `json:"items"`
}
if err = json.Unmarshal(res.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
var runs []struct {
ProfileName string `json:"profile_name"`
}
if endpoint == "/api/v1/dashboard" {
if len(body.RecentJobs) != 1 {
t.Fatalf("dashboard recent_jobs: %#v", body.RecentJobs)
}
runs = body.RecentJobs[0].Runs
} else {
if len(body.Items) != 1 {
t.Fatalf("jobs items: %#v", body.Items)
}
runs = body.Items[0].Runs
}
if len(runs) != 1 || runs[0].ProfileName != "Windows 11 Pro 25H2 - VM7001" {
t.Fatalf("%s profile summary: %#v response=%s", endpoint, runs, res.Body.String())
}
}
detailRequest := httptest.NewRequest("GET", "/api/v1/jobs/"+job, nil)
detailRequest.AddCookie(cookie)
detailResponse := httptest.NewRecorder()
s.ServeHTTP(detailResponse, detailRequest)
if detailResponse.Code != 200 {
t.Fatalf("job detail: %d %s", detailResponse.Code, detailResponse.Body)
}
var detail struct {
Runs []struct {
ProfileName string `json:"profile_name"`
Attempts []struct {
Report struct {
Execution struct {
ExitCode *int `json:"exit_code"`
} `json:"execution"`
} `json:"report"`
Artifacts []struct {
ID string `json:"id"`
} `json:"artifacts"`
} `json:"attempts"`
} `json:"runs"`
}
if err = json.Unmarshal(detailResponse.Body.Bytes(), &detail); err != nil {
t.Fatal(err)
}
if len(detail.Runs) != 1 || detail.Runs[0].ProfileName != "Windows 11 Pro 25H2 - VM7001" || len(detail.Runs[0].Attempts) != 1 || detail.Runs[0].Attempts[0].Report.Execution.ExitCode == nil || *detail.Runs[0].Attempts[0].Report.Execution.ExitCode != 0 || len(detail.Runs[0].Attempts[0].Artifacts) != 1 || detail.Runs[0].Attempts[0].Artifacts[0].ID != artifact {
t.Fatalf("job detail lost evidence: %s", detailResponse.Body.String())
}
// Legacy migration freezes the currently known name, never inferred OS data.
if _, err = db.Exec(ctx, `ALTER TABLE runs ALTER COLUMN profile_name DROP NOT NULL; UPDATE runs SET profile_name=NULL`); err != nil {
t.Fatal(err)
}
if err = store.Migrate(ctx, db); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `UPDATE attempts SET report=report||'{"environment":{"os_build":"99999.9999.unrelated-telemetry"}}'::jsonb WHERE id=$1`, attempt); err != nil {
t.Fatal(err)
}
var session struct {
CSRF string `json:"csrf_token"`
}
if err = json.Unmarshal(logged.Body.Bytes(), &session); err != nil {
t.Fatal(err)
}
writeRequest := func(method, path string, body any) map[string]any {
t.Helper()
encoded, _ := json.Marshal(body)
req := httptest.NewRequest(method, path, strings.NewReader(string(encoded)))
req.AddCookie(cookie)
req.Header.Set("Origin", "http://localhost")
req.Header.Set("X-CSRF-Token", session.CSRF)
res := httptest.NewRecorder()
s.ServeHTTP(res, req)
if res.Code != 200 && res.Code != 201 {
t.Fatalf("%s %s: %d %s", method, path, res.Code, res.Body)
}
var value map[string]any
if err := json.Unmarshal(res.Body.Bytes(), &value); err != nil {
t.Fatal(err)
}
return value
}
get := func(endpoint string) map[string]any {
t.Helper()
req := httptest.NewRequest("GET", endpoint, nil)
req.AddCookie(cookie)
res := httptest.NewRecorder()
s.ServeHTTP(res, req)
if res.Code != 200 {
t.Fatalf("%s: %d %s", endpoint, res.Code, res.Body)
}
var body map[string]any
if err := json.Unmarshal(res.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
return body
}
manualName := "Windows lab — build 26200.6584"
writeRequest("PATCH", "/api/v1/admin/profiles/"+profile, map[string]any{"name": manualName})
if err = store.Migrate(ctx, db); err != nil {
t.Fatal(err)
}
for _, endpoint := range []string{"/api/v1/profiles", "/api/v1/admin/profiles"} {
item := get(endpoint)["items"].([]any)[0].(map[string]any)
if item["name"] != manualName {
t.Fatalf("manual name was reinterpreted: %v", item)
}
}
for _, endpoint := range []string{"/api/v1/jobs/" + job, "/api/v1/jobs", "/api/v1/dashboard"} {
body := get(endpoint)
if endpoint == "/api/v1/jobs" {
body = body["items"].([]any)[0].(map[string]any)
}
if endpoint == "/api/v1/dashboard" {
body = body["recent_jobs"].([]any)[0].(map[string]any)
}
run := body["runs"].([]any)[0].(map[string]any)
if run["profile_name"] != "Windows 11 Pro 25H2 - VM7001" || run["revision_id"] != revision {
t.Fatalf("historical name/revision changed after rename: %v", run)
}
}
if _, err = db.Exec(ctx, `INSERT INTO bindings(owner_id,pool,iso_storage,disk_storage,node,configured,isolation_expires_at) VALUES($1,'test','test','test','test',true,now()+interval '1 hour')`, owner); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO heartbeats(name,seen_at,ready) VALUES('worker',now(),true)`); err != nil {
t.Fatal(err)
}
created := writeRequest("POST", "/api/v1/jobs", map[string]any{"upload_id": upload, "profile_ids": []string{profile}, "settings": Settings{Internet: "offline", Duration: 30, Filename: "original", Privilege: "user", ArgsMode: "none", Args: []string{}}})
createdID := created["id"].(string)
if created["runs"].([]any)[0].(map[string]any)["profile_name"] != manualName {
t.Fatal("new run did not snapshot explicitly entered name")
}
writeRequest("PATCH", "/api/v1/admin/profiles/"+profile, map[string]any{"name": "Another explicitly entered label"})
if get("/api/v1/jobs/" + createdID)["runs"].([]any)[0].(map[string]any)["profile_name"] != manualName {
t.Fatal("queued run name followed later profile edit")
}
requestError := func(method, path, body string, status int, code string) {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.AddCookie(cookie)
req.Header.Set("Origin", "http://localhost")
req.Header.Set("X-CSRF-Token", session.CSRF)
res := httptest.NewRecorder()
s.ServeHTTP(res, req)
var value struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
if err := json.Unmarshal(res.Body.Bytes(), &value); err != nil {
t.Fatal(err)
}
if res.Code != status || value.Error.Code != code {
t.Fatalf("%s %s: %d %s", method, path, res.Code, res.Body)
}
}
// A stale terminal job status must not allow duplicate unfinished attempts.
{
if _, err := db.Exec(ctx, `UPDATE jobs SET status='failed' WHERE id=$1`, createdID); err != nil {
t.Fatal(err)
}
requestError("POST", "/api/v1/jobs/"+createdID+"/retry", `{}`, 409, "job_active")
body := get("/api/v1/jobs/" + createdID)
attempts := body["runs"].([]any)[0].(map[string]any)["attempts"].([]any)
if body["status"] != "failed" || len(attempts) != 1 || attempts[0].(map[string]any)["phase"] != "queued" {
t.Fatalf("rejected retry changed the job or duplicated its unfinished attempt: %v", body)
}
if _, err := db.Exec(ctx, `UPDATE attempts SET phase='finished',outcome='error' WHERE run_id IN (SELECT id FROM runs WHERE job_id=$1)`, createdID); err != nil {
t.Fatal(err)
}
body = writeRequest("POST", "/api/v1/jobs/"+createdID+"/retry", map[string]any{})
attempts = body["runs"].([]any)[0].(map[string]any)["attempts"].([]any)
if body["status"] != "queued" || len(attempts) != 2 || attempts[0].(map[string]any)["phase"] != "finished" || attempts[1].(map[string]any)["phase"] != "queued" {
t.Fatalf("terminal retry did not preserve history and queue one new attempt: %v", body)
}
body = writeRequest("POST", "/api/v1/jobs/"+job+"/retry", map[string]any{})
attempts = body["runs"].([]any)[0].(map[string]any)["attempts"].([]any)
if len(attempts) != 2 || attempts[0].(map[string]any)["outcome"] != "executed" || attempts[1].(map[string]any)["phase"] != "queued" {
t.Fatalf("whole-job retry omitted a previously successful run: %v", body)
}
}
// Source seals are shared even when revisions belong to different profiles.
{
if _, err := db.Exec(ctx, `UPDATE revisions SET qualification='{"status":"passed"}' WHERE id=$1`, revision); err != nil {
t.Fatal(err)
}
otherProfile, newer := store.NewID(), store.NewID()
if _, err := db.Exec(ctx, `INSERT INTO profiles(id,name,os,architecture) VALUES($1,'Other manual label','Windows','x64')`, otherProfile); err != nil {
t.Fatal(err)
}
if _, err := db.Exec(ctx, `INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest,created_at) SELECT $1,$2,source_ref,'new-fingerprint','new-config',created_at+interval '1 second' FROM revisions WHERE id=$3`, newer, otherProfile, revision); err != nil {
t.Fatal(err)
}
writeRequest("POST", "/api/v1/admin/profiles/"+profile+"/maintenance", map[string]any{})
requestError("POST", "/api/v1/admin/profiles/"+profile+"/publish", `{"revision_id":"`+revision+`"}`, 409, "stale_revision")
for _, item := range get("/api/v1/admin/profiles")["items"].([]any) {
p := item.(map[string]any)
if p["id"] == profile && (p["state"] != "maintenance" || p["enabled"] != false) {
t.Fatalf("rejected stale publish reopened admission: %v", p)
}
}
}
if _, err := db.Exec(ctx, `UPDATE attempts SET created_at='2026-01-01T00:00:00Z' WHERE run_id=$1 AND phase='queued'`, run); err != nil {
t.Fatal(err)
}
if _, err := db.Exec(ctx, `UPDATE attempts SET created_at='2026-01-02T00:00:00Z' WHERE run_id IN (SELECT id FROM runs WHERE job_id=$1) AND phase='queued'`, createdID); err != nil {
t.Fatal(err)
}
if ahead := get("/api/v1/jobs/" + createdID)["queue_ahead"]; ahead != float64(1) {
t.Fatalf("earlier queued attempt was not counted: %v", ahead)
}
if _, err := db.Exec(ctx, `UPDATE attempts SET claimed_at=now() WHERE run_id=$1 AND phase='queued'`, run); err != nil {
t.Fatal(err)
}
if ahead := get("/api/v1/jobs/" + createdID)["queue_ahead"]; ahead != float64(0) {
t.Fatalf("already claimed attempt was counted ahead: %v", ahead)
}
claimedJob := get("/api/v1/jobs/" + job)
if claimedJob["queue_ahead"] != nil {
t.Fatalf("job without unclaimed queued attempts has a queue position: %v", claimedJob["queue_ahead"])
}
for _, value := range claimedJob["runs"].([]any)[0].(map[string]any)["attempts"].([]any) {
a := value.(map[string]any)
if a["phase"] == "queued" && a["claimed_at"] == nil {
t.Fatal("claimed_at missing from job detail")
}
}
if _, err := db.Exec(ctx, `UPDATE attempts SET cleanup='failed',finished_at=now() WHERE id=$1`, attempt); err != nil {
t.Fatal(err)
}
held := get("/api/v1/admin/attempts/held")["items"].([]any)
if len(held) != 1 || held[0].(map[string]any)["attempt_id"] != attempt || held[0].(map[string]any)["allocation"] != nil {
t.Fatalf("failed cleanup without allocation missing from held evidence: %v", held)
}
allocation := store.NewID()
if _, err := db.Exec(ctx, `INSERT INTO allocations(id,attempt_id,owner_id,node,vmid,pool,state) VALUES($1,$2,$3,'test-node',7100,'test-pool','stopped')`, allocation, attempt, owner); err != nil {
t.Fatal(err)
}
held = get("/api/v1/admin/attempts/held")["items"].([]any)
if held[0].(map[string]any)["allocation"].(map[string]any)["id"] != allocation {
t.Fatalf("held evidence lost its diagnostic allocation: %v", held)
}
// A competing commit while bytes arrive must not block on the owner or exceed quota.
s.cfg.MaxOwnerBytes = 1024
s.cfg.MaxUploadBytes = 512
streamed := false
payload := strings.NewReader("test")
probe := uploadReaderFunc(func(p []byte) (int, error) {
if !streamed {
streamed = true
tx, err := db.Begin(ctx)
if err != nil {
return 0, err
}
defer tx.Rollback(ctx)
if _, err = tx.Exec(ctx, `SELECT id FROM users WHERE id=$1 FOR UPDATE NOWAIT`, owner); err != nil {
return 0, err
}
var used int64
if err = tx.QueryRow(ctx, ownerStorageQuery, owner).Scan(&used); err != nil {
return 0, err
}
competitor := store.NewID()
if _, err = tx.Exec(ctx, `INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key) VALUES($1,$2,'concurrent.exe',$3,$4,$5)`, competitor, owner, s.cfg.MaxOwnerBytes-used-1, strings.Repeat("c", 64), competitor); err != nil {
return 0, err
}
if err = tx.Commit(ctx); err != nil {
return 0, err
}
}
return payload.Read(p)
})
uploadRequest := httptest.NewRequest("POST", "/api/v1/uploads", io.NopCloser(probe))
uploadRequest.AddCookie(cookie)
uploadRequest.Header.Set("Origin", "http://localhost")
uploadRequest.Header.Set("X-CSRF-Token", session.CSRF)
uploadRequest.Header.Set("X-Filename", "race.exe")
uploadResponse := httptest.NewRecorder()
s.ServeHTTP(uploadResponse, uploadRequest)
var uploadError struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
if err := json.Unmarshal(uploadResponse.Body.Bytes(), &uploadError); err != nil {
t.Fatal(err)
}
if uploadResponse.Code != 429 || uploadError.Error.Code != "quota_exceeded" {
t.Fatalf("upload held a streaming lock or skipped final quota check: %d %s", uploadResponse.Code, uploadResponse.Body)
}
files, err := os.ReadDir(filepath.Join(s.cfg.ArtifactRoot, "uploads", owner))
if err != nil || len(files) != 0 {
t.Fatalf("rejected upload retained private file: %v %v", files, err)
}
var uploaded int
if err := db.QueryRow(ctx, `SELECT count(*) FROM uploads WHERE filename='race.exe'`).Scan(&uploaded); err != nil || uploaded != 0 {
t.Fatalf("rejected upload was committed: %d %v", uploaded, err)
}
}
type uploadReaderFunc func([]byte) (int, error)
func (f uploadReaderFunc) Read(p []byte) (int, error) { return f(p) }