Run owner jobs in parallel with atomic reservations and harden recovery
Worker - Per-owner max_active_attempts (default 1, <= concurrent) replaces the one-active-attempt-per-owner claim rule; claims fill free slots each tick in deterministic created_at/profile_name/id order and record claimed_at. - Disk, memory and artifact reservations are admitted and inserted in one owner-locked transaction; clones reserve measured source disk bytes and source RAM plus overhead; pending clone storage and aggregate artifact headroom are accounted. - nextid lock is released right after the allocation reservation; source lock waits follow the caller context (20 min ceiling) with specific text. - Shared settleJobSQL for worker and watchdog; cancellation is reported as cancelled instead of failed/error. - Safety deadline is refreshed when collection starts so the watchdog cannot take over a live collection. - Evidence release continues past failures, keeps the original error and stops retrying until an admin re-requests. - Job ISO media is reconciled after all attempts finish (fixes leaks and the parallel-finish race); readiness errors carry the last guest/transport cause and distinguish cancellation/lease loss. - Watchdog prunes expired sessions, login limits and old orphan events; worker health events are throttled. PVE client - Bounded retries for idempotent GETs on transport errors/5xx only; task polling starts at 250 ms; task exitstatus is logged for operators; QGA file reads use 1 MiB chunks. API/store - Indexes for hot job/claim/quota queries; claimed_at column. - Native UUID path comparisons with early 404; deterministic run ordering; queue_ahead; admin held-attempts listing; stale revision publish guard; retry refused while any attempt is unfinished. - Uploads stream outside the DB transaction with a short locked quota recheck; explicit pool sizes; `otche healthcheck` CLI mode. Recorder - Network reads and FFmpeg writes happen outside the framebuffer lock; wall-clock frame pacing with bounded catch-up and explicit gaps; fsync at most once per second after the first durable fragment. Windows runner - UTC-safe timestamp parsing everywhere; readiness checks desktop first and computes the baseline once; per-nonce probe results; collector publishes initial telemetry immediately and reads event logs incrementally. - Baseline records UAC, Smart App Control, Secure Boot and Device Guard registry state; installer stores the LSA secret last and gains read-only -Verify and signed -UpdateRunner maintenance modes.
This commit is contained in:
1 parent
529dcd4026
commit
dfb285fc2e
37 files changed
+1829
-261
No files matched your search
+25
-10
@@ -25,13 +25,13 @@ func (s *Server) adminRoutes() {
|
||||
m.HandleFunc("POST /api/v1/admin/profiles/{id}/publish", s.protected(true, s.publish))
|
||||
m.HandleFunc("POST /api/v1/admin/profiles/{id}/qualify", s.protected(true, s.qualify))
|
||||
m.HandleFunc("GET /api/v1/admin/profiles/{id}/revisions", s.protected(true, func(w http.ResponseWriter, r *http.Request) {
|
||||
s.list(w, r, `SELECT to_jsonb(v)-'source_ref' FROM revisions v WHERE profile_id::text=$1 ORDER BY created_at DESC`, r.PathValue("id"))
|
||||
s.list(w, r, `SELECT to_jsonb(v)-'source_ref' FROM revisions v WHERE profile_id=$1::uuid ORDER BY created_at DESC`, r.PathValue("id"))
|
||||
}))
|
||||
m.HandleFunc("GET /api/v1/admin/profiles/{id}/qualifications", s.protected(true, func(w http.ResponseWriter, r *http.Request) {
|
||||
s.list(w, r, `SELECT to_jsonb(q) FROM qualifications q WHERE profile_id::text=$1 ORDER BY created_at DESC`, r.PathValue("id"))
|
||||
s.list(w, r, `SELECT to_jsonb(q) FROM qualifications q WHERE profile_id=$1::uuid ORDER BY created_at DESC`, r.PathValue("id"))
|
||||
}))
|
||||
m.HandleFunc("GET /api/v1/admin/qualifications/{id}", s.protected(true, func(w http.ResponseWriter, r *http.Request) {
|
||||
v, e := s.queryObject(r.Context(), `SELECT to_jsonb(q) FROM qualifications q WHERE id::text=$1`, r.PathValue("id"))
|
||||
v, e := s.queryObject(r.Context(), `SELECT to_jsonb(q) FROM qualifications q WHERE id=$1::uuid`, r.PathValue("id"))
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -42,6 +42,7 @@ func (s *Server) adminRoutes() {
|
||||
s.list(w, r, `SELECT to_jsonb(b)||jsonb_build_object('configured',configured AND COALESCE(isolation_expires_at>now(),false),'reason',CASE WHEN configured AND NOT COALESCE(isolation_expires_at>now(),false) THEN 'Isolation proof expired or requires revalidation' ELSE reason END) FROM bindings b ORDER BY owner_id`)
|
||||
}))
|
||||
m.HandleFunc("GET /api/v1/admin/health", s.protected(true, s.health))
|
||||
m.HandleFunc("GET /api/v1/admin/attempts/held", s.protected(true, s.heldAttempts))
|
||||
m.HandleFunc("POST /api/v1/admin/attempts/{id}/release-evidence", s.protected(true, s.releaseEvidence))
|
||||
}
|
||||
func (s *Server) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -104,7 +105,7 @@ func (s *Server) updateUser(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
var id, role string
|
||||
var disabled bool
|
||||
e = tx.QueryRow(r.Context(), `SELECT id::text,role,disabled FROM users WHERE id::text=$1 FOR UPDATE`, r.PathValue("id")).Scan(&id, &role, &disabled)
|
||||
e = tx.QueryRow(r.Context(), `SELECT id::text,role,disabled FROM users WHERE id=$1::uuid FOR UPDATE`, r.PathValue("id")).Scan(&id, &role, &disabled)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -172,7 +173,7 @@ func (s *Server) updateProfile(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, 400, "invalid_profile", "Invalid name")
|
||||
return
|
||||
}
|
||||
v, e := s.queryObject(r.Context(), `UPDATE profiles SET name=COALESCE($2,name),enabled=COALESCE($3,enabled) WHERE id::text=$1 RETURNING to_jsonb(profiles)`, r.PathValue("id"), in.Name, in.Enabled)
|
||||
v, e := s.queryObject(r.Context(), `UPDATE profiles SET name=COALESCE($2,name),enabled=COALESCE($3,enabled) WHERE id=$1::uuid RETURNING to_jsonb(profiles)`, r.PathValue("id"), in.Name, in.Enabled)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -180,13 +181,13 @@ func (s *Server) updateProfile(w http.ResponseWriter, r *http.Request) {
|
||||
jsonResponse(w, 200, v)
|
||||
}
|
||||
func (s *Server) maintenance(w http.ResponseWriter, r *http.Request) {
|
||||
v, e := s.queryObject(r.Context(), `UPDATE profiles SET state='maintenance',enabled=false,reason='Maintenance admission closed; drain queued clones before changing source disks' WHERE id::text=$1 RETURNING to_jsonb(profiles)`, r.PathValue("id"))
|
||||
v, e := s.queryObject(r.Context(), `UPDATE profiles SET state='maintenance',enabled=false,reason='Maintenance admission closed; drain queued clones before changing source disks' WHERE id=$1::uuid RETURNING to_jsonb(profiles)`, r.PathValue("id"))
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
}
|
||||
var pending int
|
||||
e = s.db.QueryRow(r.Context(), `SELECT count(*) FROM runs r JOIN attempts a ON a.run_id=r.id WHERE r.profile_id::text=$1 AND a.phase IN('queued','provisioning')`, r.PathValue("id")).Scan(&pending)
|
||||
e = s.db.QueryRow(r.Context(), `SELECT count(*) FROM runs r JOIN attempts a ON a.run_id=r.id WHERE r.profile_id=$1::uuid AND a.phase IN('queued','provisioning')`, r.PathValue("id")).Scan(&pending)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -212,7 +213,7 @@ func (s *Server) publish(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
defer tx.Rollback(r.Context())
|
||||
var profile string
|
||||
e = tx.QueryRow(r.Context(), `SELECT id::text FROM profiles WHERE id::text=$1 FOR UPDATE`, r.PathValue("id")).Scan(&profile)
|
||||
e = tx.QueryRow(r.Context(), `SELECT id::text FROM profiles WHERE id=$1::uuid FOR UPDATE`, r.PathValue("id")).Scan(&profile)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -223,6 +224,16 @@ func (s *Server) publish(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, 409, "unqualified_revision", "Worker-validated source and passed qualification required")
|
||||
return
|
||||
}
|
||||
var stale bool
|
||||
e = tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM revisions newer WHERE newer.source_ref=v.source_ref AND newer.created_at>v.created_at) FROM revisions v WHERE v.id=$1`, in.RevisionID).Scan(&stale)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
}
|
||||
if stale {
|
||||
fail(w, 409, "stale_revision", "A newer revision exists for this source")
|
||||
return
|
||||
}
|
||||
var pending int
|
||||
e = tx.QueryRow(r.Context(), `SELECT count(*) FROM runs r JOIN attempts a ON a.run_id=r.id WHERE r.profile_id=$1 AND r.revision_id<>$2 AND a.phase IN('queued','provisioning')`, profile, in.RevisionID).Scan(&pending)
|
||||
if e != nil {
|
||||
@@ -257,7 +268,7 @@ func (s *Server) qualify(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
defer tx.Rollback(r.Context())
|
||||
var id string
|
||||
e = tx.QueryRow(r.Context(), `SELECT id::text FROM profiles WHERE id::text=$1 FOR UPDATE`, r.PathValue("id")).Scan(&id)
|
||||
e = tx.QueryRow(r.Context(), `SELECT id::text FROM profiles WHERE id=$1::uuid FOR UPDATE`, r.PathValue("id")).Scan(&id)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -324,7 +335,7 @@ func (s *Server) releaseEvidence(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, 400, "confirmation_required", "Explicit confirm true required")
|
||||
return
|
||||
}
|
||||
tag, e := s.db.Exec(r.Context(), `UPDATE attempts SET release_requested=true WHERE id::text=$1 AND phase='finished' AND cleanup IN ('evidence_held','failed') AND EXISTS(SELECT 1 FROM allocations WHERE attempt_id=attempts.id)`, r.PathValue("id"))
|
||||
tag, e := s.db.Exec(r.Context(), `UPDATE attempts SET release_requested=true WHERE id=$1::uuid AND phase='finished' AND cleanup IN ('evidence_held','failed') AND EXISTS(SELECT 1 FROM allocations WHERE attempt_id=attempts.id)`, r.PathValue("id"))
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -335,3 +346,7 @@ func (s *Server) releaseEvidence(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
jsonResponse(w, 202, map[string]any{"release_requested": true})
|
||||
}
|
||||
|
||||
func (s *Server) heldAttempts(w http.ResponseWriter, r *http.Request) {
|
||||
s.list(w, r, `SELECT jsonb_build_object('attempt_id',a.id,'job_id',j.id,'run_id',r.id,'profile_name',r.profile_name,'filename',u.filename,'outcome',a.outcome,'cleanup',a.cleanup,'error',a.error,'finished_at',a.finished_at,'release_requested',a.release_requested,'allocation',CASE WHEN v.id IS NULL THEN NULL ELSE jsonb_build_object('id',v.id,'node',v.node,'vmid',v.vmid,'state',v.state) END) FROM attempts a JOIN runs r ON r.id=a.run_id JOIN jobs j ON j.id=r.job_id JOIN uploads u ON u.id=j.upload_id LEFT JOIN allocations v ON v.attempt_id=a.id WHERE a.phase='finished' AND a.cleanup IN ('evidence_held','failed') ORDER BY a.finished_at DESC NULLS LAST,a.created_at DESC,a.id LIMIT 200`)
|
||||
}
|
||||
@@ -120,3 +120,40 @@ func TestAccountLoginLimitAndSessionRevocation(t *testing.T) {
|
||||
}
|
||||
fmt.Fprintln(os.Stdout, "17 valid proxied logins; account failure throttling; unrelated user unaffected; revoked session denied; DB failure remains 500")
|
||||
}
|
||||
|
||||
func TestInvalidUUIDPathsReturnNotFound(t *testing.T) {
|
||||
s := &Server{mux: http.NewServeMux()}
|
||||
s.routes()
|
||||
for _, route := range []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{"GET", "/api/v1/jobs/not-a-uuid"},
|
||||
{"POST", "/api/v1/jobs/not-a-uuid/retry"},
|
||||
{"GET", "/api/v1/uploads/not-a-uuid/content"},
|
||||
{"GET", "/api/v1/artifacts/not-a-uuid/content"},
|
||||
{"GET", "/api/v1/attempts/not-a-uuid/video"},
|
||||
{"PATCH", "/api/v1/admin/users/not-a-uuid"},
|
||||
{"POST", "/api/v1/admin/profiles/not-a-uuid/publish"},
|
||||
{"GET", "/api/v1/admin/profiles/not-a-uuid/revisions"},
|
||||
{"GET", "/api/v1/admin/qualifications/not-a-uuid"},
|
||||
{"POST", "/api/v1/admin/attempts/not-a-uuid/release-evidence"},
|
||||
} {
|
||||
t.Run(route.method+" "+route.path, func(t *testing.T) {
|
||||
r := httptest.NewRequest(route.method, route.path, strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, r)
|
||||
var body struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != 404 || body.Error.Code != "not_found" {
|
||||
t.Fatalf("invalid UUID: %d %s", w.Code, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,10 @@ package api
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -239,4 +241,171 @@ func TestJobSummariesIncludeAssignedProfile(t *testing.T) {
|
||||
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) }
|
||||
+40
-19
@@ -144,6 +144,8 @@ func (s *Server) jobRoutes() {
|
||||
}))
|
||||
m.HandleFunc("GET /api/v1/dashboard", s.protected(false, s.dashboard))
|
||||
}
|
||||
const ownerStorageQuery = `SELECT COALESCE((SELECT sum(size) FROM uploads WHERE owner_id=$1),0)+COALESCE((SELECT sum(a.size) FROM artifacts a JOIN jobs j ON j.id=a.job_id WHERE j.owner_id=$1),0)`
|
||||
|
||||
func (s *Server) upload(w http.ResponseWriter, r *http.Request) {
|
||||
a := user(r)
|
||||
name, e := url.PathUnescape(r.Header.Get("X-Filename"))
|
||||
@@ -151,19 +153,8 @@ func (s *Server) upload(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, 400, "invalid_filename", "A safe filename with one of the ten supported extensions is required")
|
||||
return
|
||||
}
|
||||
tx, e := s.db.Begin(r.Context())
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(r.Context())
|
||||
var id string
|
||||
if e = tx.QueryRow(r.Context(), `SELECT id::text FROM users WHERE id=$1 FOR UPDATE`, a.ID).Scan(&id); e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
}
|
||||
var used int64
|
||||
e = tx.QueryRow(r.Context(), `SELECT COALESCE((SELECT sum(size) FROM uploads WHERE owner_id=$1),0)+COALESCE((SELECT sum(a.size) FROM artifacts a JOIN jobs j ON j.id=a.job_id WHERE j.owner_id=$1),0)`, a.ID).Scan(&used)
|
||||
e = s.db.QueryRow(r.Context(), ownerStorageQuery, a.ID).Scan(&used)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -218,6 +209,25 @@ func (s *Server) upload(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, 500, "storage_error", "Could not finalize upload")
|
||||
return
|
||||
}
|
||||
tx, e := s.db.Begin(r.Context())
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback(r.Context())
|
||||
var id string
|
||||
if e = tx.QueryRow(r.Context(), `SELECT id::text FROM users WHERE id=$1 FOR UPDATE`, a.ID).Scan(&id); e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
}
|
||||
if e = tx.QueryRow(r.Context(), ownerStorageQuery, a.ID).Scan(&used); e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
}
|
||||
if n > s.cfg.MaxOwnerBytes-used {
|
||||
fail(w, 429, "quota_exceeded", "Owner storage quota reached")
|
||||
return
|
||||
}
|
||||
sum := hex.EncodeToString(h.Sum(nil))
|
||||
var created any
|
||||
e = tx.QueryRow(r.Context(), `INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key) VALUES($1,$2,$3,$4,$5,$6) RETURNING created_at`, uploadID, a.ID, name, n, sum, key).Scan(&created)
|
||||
@@ -264,7 +274,7 @@ func (s *Server) servePrivate(w http.ResponseWriter, r *http.Request, key, name,
|
||||
func (s *Server) uploadContent(w http.ResponseWriter, r *http.Request) {
|
||||
a := user(r)
|
||||
var key, name string
|
||||
e := s.db.QueryRow(r.Context(), `SELECT storage_key,filename FROM uploads WHERE id::text=$1 AND(owner_id=$2 OR $3='admin')`, r.PathValue("id"), a.ID, a.Role).Scan(&key, &name)
|
||||
e := s.db.QueryRow(r.Context(), `SELECT storage_key,filename FROM uploads WHERE id=$1::uuid AND(owner_id=$2 OR $3='admin')`, r.PathValue("id"), a.ID, a.Role).Scan(&key, &name)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -274,7 +284,7 @@ func (s *Server) uploadContent(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) artifactContent(w http.ResponseWriter, r *http.Request) {
|
||||
a := user(r)
|
||||
var key, name, ct string
|
||||
e := s.db.QueryRow(r.Context(), `SELECT a.storage_key,a.filename,a.content_type FROM artifacts a JOIN jobs j ON j.id=a.job_id WHERE a.id::text=$1 AND(j.owner_id=$2 OR $3='admin')`, r.PathValue("id"), a.ID, a.Role).Scan(&key, &name, &ct)
|
||||
e := s.db.QueryRow(r.Context(), `SELECT a.storage_key,a.filename,a.content_type FROM artifacts a JOIN jobs j ON j.id=a.job_id WHERE a.id=$1::uuid AND(j.owner_id=$2 OR $3='admin')`, r.PathValue("id"), a.ID, a.Role).Scan(&key, &name, &ct)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -392,9 +402,11 @@ func (s *Server) admit(r *http.Request, tx pgx.Tx, owner string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
const jobRunsSummary = `COALESCE((SELECT jsonb_agg(to_jsonb(r) ORDER BY r.id) FROM runs r WHERE r.job_id=j.id),'[]'::jsonb)`
|
||||
const jobRunsSummary = `COALESCE((SELECT jsonb_agg(to_jsonb(r) ORDER BY r.profile_name,r.id) FROM runs r WHERE r.job_id=j.id),'[]'::jsonb)`
|
||||
|
||||
const jobQuery = `SELECT to_jsonb(j)||jsonb_build_object('filename',u.filename,'sha256',u.sha256,'size',u.size,'runs',COALESCE((SELECT jsonb_agg(to_jsonb(r)||jsonb_build_object('attempts',COALESCE((SELECT jsonb_agg((to_jsonb(a)-'lease_owner'-'lease_until'-'release_requested')||jsonb_build_object('allocation',CASE WHEN $3='admin' THEN(SELECT jsonb_build_object('id',v.id,'node',v.node,'vmid',v.vmid,'state',v.state) FROM allocations v WHERE v.attempt_id=a.id) ELSE NULL END,'artifacts',COALESCE((SELECT jsonb_agg(to_jsonb(ar)-'storage_key'||jsonb_build_object('url','/api/v1/artifacts/'||ar.id||'/content')) FROM artifacts ar WHERE ar.attempt_id=a.id),'[]'::jsonb)) ORDER BY a.created_at) FROM attempts a WHERE a.run_id=r.id),'[]'::jsonb))) FROM runs r WHERE r.job_id=j.id),'[]'::jsonb)) FROM jobs j JOIN uploads u ON u.id=j.upload_id WHERE j.id::text=$1 AND(j.owner_id=$2 OR $3='admin')`
|
||||
const jobQuery = `SELECT to_jsonb(j)||jsonb_build_object('filename',u.filename,'sha256',u.sha256,'size',u.size,
|
||||
'queue_ahead',(SELECT (SELECT count(*) FROM attempts ahead JOIN runs ar ON ar.id=ahead.run_id WHERE ar.job_id<>j.id AND ahead.phase='queued' AND ahead.claimed_at IS NULL AND ahead.created_at<first_queued.created_at) FROM (SELECT min(qa.created_at) AS created_at FROM attempts qa JOIN runs qr ON qr.id=qa.run_id WHERE qr.job_id=j.id AND qa.phase='queued' AND qa.claimed_at IS NULL) first_queued WHERE first_queued.created_at IS NOT NULL),
|
||||
'runs',COALESCE((SELECT jsonb_agg(to_jsonb(r)||jsonb_build_object('attempts',COALESCE((SELECT jsonb_agg((to_jsonb(a)-'lease_owner'-'lease_until'-'release_requested')||jsonb_build_object('allocation',CASE WHEN $3='admin' THEN(SELECT jsonb_build_object('id',v.id,'node',v.node,'vmid',v.vmid,'state',v.state) FROM allocations v WHERE v.attempt_id=a.id) ELSE NULL END,'artifacts',COALESCE((SELECT jsonb_agg(to_jsonb(ar)-'storage_key'||jsonb_build_object('url','/api/v1/artifacts/'||ar.id||'/content')) FROM artifacts ar WHERE ar.attempt_id=a.id),'[]'::jsonb)) ORDER BY a.created_at) FROM attempts a WHERE a.run_id=r.id),'[]'::jsonb)) ORDER BY r.profile_name,r.id) FROM runs r WHERE r.job_id=j.id),'[]'::jsonb)) FROM jobs j JOIN uploads u ON u.id=j.upload_id WHERE j.id=$1::uuid AND(j.owner_id=$2 OR $3='admin')`
|
||||
|
||||
func (s *Server) respondJob(w http.ResponseWriter, r *http.Request, id string, status int) {
|
||||
a := user(r)
|
||||
@@ -411,7 +423,7 @@ func (s *Server) getJob(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) ownJob(r *http.Request) (string, error) {
|
||||
a := user(r)
|
||||
var id string
|
||||
e := s.db.QueryRow(r.Context(), `SELECT id::text FROM jobs WHERE id::text=$1 AND(owner_id=$2 OR $3='admin')`, r.PathValue("id"), a.ID, a.Role).Scan(&id)
|
||||
e := s.db.QueryRow(r.Context(), `SELECT id::text FROM jobs WHERE id=$1::uuid AND(owner_id=$2 OR $3='admin')`, r.PathValue("id"), a.ID, a.Role).Scan(&id)
|
||||
return id, e
|
||||
}
|
||||
func (s *Server) jobs(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -486,7 +498,13 @@ func (s *Server) retryJob(w http.ResponseWriter, r *http.Request) {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
}
|
||||
if status == "queued" || status == "running" {
|
||||
var unfinished bool
|
||||
e = tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM attempts a JOIN runs r ON r.id=a.run_id WHERE r.job_id=$1 AND a.phase<>'finished')`, id).Scan(&unfinished)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
}
|
||||
if unfinished || status == "queued" || status == "running" {
|
||||
fail(w, 409, "job_active", "An active job cannot be retried")
|
||||
return
|
||||
}
|
||||
@@ -511,6 +529,9 @@ func (s *Server) retryJob(w http.ResponseWriter, r *http.Request) {
|
||||
ids = append(ids, run)
|
||||
}
|
||||
rows.Close()
|
||||
if e == nil {
|
||||
e = rows.Err()
|
||||
}
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -561,7 +582,7 @@ func (s *Server) artifacts(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
func (s *Server) video(w http.ResponseWriter, r *http.Request) {
|
||||
a := user(r)
|
||||
v, e := s.queryObject(r.Context(), `SELECT a.video FROM attempts a JOIN runs r ON r.id=a.run_id JOIN jobs j ON j.id=r.job_id WHERE a.id::text=$1 AND(j.owner_id=$2 OR $3='admin')`, r.PathValue("id"), a.ID, a.Role)
|
||||
v, e := s.queryObject(r.Context(), `SELECT a.video FROM attempts a JOIN runs r ON r.id=a.run_id JOIN jobs j ON j.id=r.job_id WHERE a.id=$1::uuid AND(j.owner_id=$2 OR $3='admin')`, r.PathValue("id"), a.ID, a.Role)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
@@ -41,6 +42,19 @@ var uuidRE = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4
|
||||
var usernameRE = regexp.MustCompile(`^[A-Za-z0-9_.-]{3,64}$`)
|
||||
|
||||
func New(db *pgxpool.Pool, c Config) (*Server, error) {
|
||||
if os.Getenv("PUBLIC_ORIGIN") == "" {
|
||||
slog.Warn("PUBLIC_ORIGIN is unset; configure the external origin before exposing the API")
|
||||
}
|
||||
if os.Getenv("ALLOW_INSECURE_HTTP") == "true" {
|
||||
addr := os.Getenv("LISTEN_ADDR")
|
||||
if addr == "" {
|
||||
addr = ":8080"
|
||||
}
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err != nil || !strings.EqualFold(host, "localhost") && !net.ParseIP(host).IsLoopback() {
|
||||
slog.Warn("ALLOW_INSECURE_HTTP is enabled on a non-loopback listener; session cookies are not secure and HTTP must not be exposed to untrusted networks", "listen_addr", addr)
|
||||
}
|
||||
}
|
||||
if c.Origin == "" || c.ArtifactRoot == "" {
|
||||
return nil, errors.New("origin and artifact root required")
|
||||
}
|
||||
@@ -117,6 +131,10 @@ func (s *Server) origin(w http.ResponseWriter, r *http.Request) bool {
|
||||
}
|
||||
func (s *Server) protected(admin bool, h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if id := r.PathValue("id"); id != "" && !uuidRE.MatchString(id) {
|
||||
fail(w, 404, "not_found", "Resource not found")
|
||||
return
|
||||
}
|
||||
c, err := r.Cookie("otche_session")
|
||||
if err != nil || len(c.Value) != 64 {
|
||||
fail(w, 401, "unauthenticated", "Sign in required")
|
||||
|
||||
Reference in new issue
Block a user