Store manual profile names and freeze historical run labels
This commit is contained in:
1 parent
823b048e7c
commit
529dcd4026
9 files changed
+90
-64
No files matched your search
+6
-13
@@ -9,13 +9,6 @@ import (
|
||||
"otche/internal/store"
|
||||
)
|
||||
|
||||
// Build labels come only from successful qualification of this exact revision.
|
||||
// Older revisions retain their recorded control-attempt evidence; no current
|
||||
// profile metadata or arbitrary sample report may rewrite a historical build.
|
||||
const revisionOSBuild = `CASE WHEN v.qualification->>'status'='passed' THEN substring(COALESCE(v.qualification#>>'{environment,os_build}',(SELECT a.report#>>'{environment,os_build}' FROM jsonb_array_elements(CASE WHEN jsonb_typeof(v.qualification->'controls')='array' THEN v.qualification->'controls' ELSE '[]'::jsonb END) WITH ORDINALITY c(control,ordinal) JOIN attempts a ON a.id=CASE WHEN c.control->>'attempt_id' ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$' THEN (c.control->>'attempt_id')::uuid ELSE NULL END JOIN runs qr ON qr.id=a.run_id WHERE qr.revision_id=v.id AND c.ordinal<=4 AND a.report#>>'{environment,os_build}' IS NOT NULL ORDER BY c.ordinal LIMIT 1)) FROM '^([0-9]+\.[0-9]+)(\.|$)') ELSE NULL END`
|
||||
const profileProjection = `to_jsonb(p)||jsonb_build_object('os_build',(SELECT ` + revisionOSBuild + ` FROM revisions v WHERE v.id=p.current_revision_id))`
|
||||
const runProjection = `to_jsonb(r)||jsonb_build_object('profile_name',p.name,'os_build',(SELECT ` + revisionOSBuild + ` FROM revisions v WHERE v.id=r.revision_id))`
|
||||
|
||||
func (s *Server) adminRoutes() {
|
||||
m := s.mux
|
||||
m.HandleFunc("GET /api/v1/admin/users", s.protected(true, func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -24,7 +17,7 @@ func (s *Server) adminRoutes() {
|
||||
m.HandleFunc("POST /api/v1/admin/users", s.protected(true, s.createUser))
|
||||
m.HandleFunc("PATCH /api/v1/admin/users/{id}", s.protected(true, s.updateUser))
|
||||
m.HandleFunc("GET /api/v1/admin/profiles", s.protected(true, func(w http.ResponseWriter, r *http.Request) {
|
||||
s.list(w, r, `SELECT `+profileProjection+` FROM profiles p ORDER BY name`)
|
||||
s.list(w, r, `SELECT to_jsonb(p) FROM profiles p ORDER BY name`)
|
||||
}))
|
||||
m.HandleFunc("POST /api/v1/admin/profiles", s.protected(true, s.createProfile))
|
||||
m.HandleFunc("PATCH /api/v1/admin/profiles/{id}", s.protected(true, s.updateProfile))
|
||||
@@ -32,7 +25,7 @@ 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'||jsonb_build_object('os_build',`+revisionOSBuild+`) 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::text=$1 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"))
|
||||
@@ -160,7 +153,7 @@ func (s *Server) createProfile(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, 400, "invalid_profile", "Name, OS and x64/x86 architecture required")
|
||||
return
|
||||
}
|
||||
v, e := s.queryObject(r.Context(), `WITH p AS (INSERT INTO profiles(id,name,os,architecture) VALUES($1,$2,$3,$4) RETURNING *) SELECT `+profileProjection+` FROM p`, store.NewID(), in.Name, in.OS, in.Architecture)
|
||||
v, e := s.queryObject(r.Context(), `INSERT INTO profiles(id,name,os,architecture) VALUES($1,$2,$3,$4) RETURNING to_jsonb(profiles)`, store.NewID(), in.Name, in.OS, in.Architecture)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -179,7 +172,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(), `WITH p AS (UPDATE profiles SET name=COALESCE($2,name),enabled=COALESCE($3,enabled) WHERE id::text=$1 RETURNING *) SELECT `+profileProjection+` FROM p`, 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::text=$1 RETURNING to_jsonb(profiles)`, r.PathValue("id"), in.Name, in.Enabled)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -187,7 +180,7 @@ 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(), `WITH p AS (UPDATE profiles SET state='maintenance',enabled=false,reason='Maintenance admission closed; drain queued clones before changing source disks' WHERE id::text=$1 RETURNING *) SELECT `+profileProjection+` FROM p`, 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::text=$1 RETURNING to_jsonb(profiles)`, r.PathValue("id"))
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
@@ -249,7 +242,7 @@ func (s *Server) publish(w http.ResponseWriter, r *http.Request) {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
}
|
||||
v, e := s.queryObject(r.Context(), `SELECT `+profileProjection+` FROM profiles p WHERE id=$1`, profile)
|
||||
v, e := s.queryObject(r.Context(), `SELECT to_jsonb(p) FROM profiles p WHERE id=$1`, profile)
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
|
||||
@@ -59,7 +59,7 @@ func TestJobSummariesIncludeAssignedProfile(t *testing.T) {
|
||||
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','{}')`, job, owner, upload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, `INSERT INTO runs(id,job_id,profile_id,revision_id,status) VALUES($1,$2,$3,$4,'completed')`, run, job, profile, revision); err != nil {
|
||||
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 {
|
||||
@@ -151,17 +151,40 @@ func TestJobSummariesIncludeAssignedProfile(t *testing.T) {
|
||||
t.Fatalf("job detail lost evidence: %s", detailResponse.Body.String())
|
||||
}
|
||||
|
||||
// Legacy successful qualification keeps its own recorded control evidence.
|
||||
if _, err = db.Exec(ctx, `UPDATE attempts SET report=report||'{"environment":{"os_build":"26100.1234.26100.1.amd64fre.old"}}'::jsonb WHERE id=$1`, attempt); err != nil {
|
||||
// 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 = db.Exec(ctx, `UPDATE revisions SET qualification=jsonb_build_object('status','passed','controls',jsonb_build_array(jsonb_build_object('attempt_id','not-a-uuid'),jsonb_build_object('attempt_id',$2::text))) WHERE id=$1`, revision, attempt); err != nil {
|
||||
if err = store.Migrate(ctx, db); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newRevision := store.NewID()
|
||||
if _, err = db.Exec(ctx, `INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest,qualification) VALUES($1,$2,'win11','new-fingerprint','new-config','{"status":"passed","environment":{"os_build":"26200.6584.26100.1.amd64fre.new"}}')`, newRevision, profile); err != nil {
|
||||
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)
|
||||
@@ -177,38 +200,43 @@ func TestJobSummariesIncludeAssignedProfile(t *testing.T) {
|
||||
}
|
||||
return body
|
||||
}
|
||||
for _, current := range []string{revision, newRevision} {
|
||||
if _, err = db.Exec(ctx, `UPDATE profiles SET current_revision_id=$2 WHERE id=$1`, profile, current); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectedProfileBuild := "26100.1234"
|
||||
if current == newRevision {
|
||||
expectedProfileBuild = "26200.6584"
|
||||
}
|
||||
for _, endpoint := range []string{"/api/v1/profiles", "/api/v1/admin/profiles"} {
|
||||
item := get(endpoint)["items"].([]any)[0].(map[string]any)
|
||||
if item["os_build"] != expectedProfileBuild || item["name"] != "Windows 11 Pro 25H2 - VM7001" {
|
||||
t.Fatalf("profile build/name changed incorrectly: %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["revision_id"] != revision || run["os_build"] != "26100.1234" {
|
||||
t.Fatalf("historical run borrowed current profile build: %v", run)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err = db.Exec(ctx, `UPDATE revisions SET qualification=jsonb_set(qualification,'{status}','"failed"') WHERE id=$1`, newRevision); err != nil {
|
||||
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)
|
||||
}
|
||||
if get("/api/v1/profiles")["items"].([]any)[0].(map[string]any)["os_build"] != nil {
|
||||
t.Fatal("failed qualification presented as authoritative Windows build")
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,7 @@ func (s *Server) jobRoutes() {
|
||||
m.HandleFunc("GET /api/v1/artifacts/{id}/content", s.protected(false, s.artifactContent))
|
||||
m.HandleFunc("GET /api/v1/attempts/{id}/video", s.protected(false, s.video))
|
||||
m.HandleFunc("GET /api/v1/profiles", s.protected(false, func(w http.ResponseWriter, r *http.Request) {
|
||||
s.list(w, r, `SELECT `+profileProjection+` FROM profiles p ORDER BY name`)
|
||||
s.list(w, r, `SELECT to_jsonb(p) FROM profiles p ORDER BY name`)
|
||||
}))
|
||||
m.HandleFunc("GET /api/v1/dashboard", s.protected(false, s.dashboard))
|
||||
}
|
||||
@@ -347,7 +347,7 @@ func (s *Server) createJob(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
for _, p := range in.ProfileIDs {
|
||||
run := store.NewID()
|
||||
if _, e = tx.Exec(r.Context(), `INSERT INTO runs(id,job_id,profile_id,revision_id)VALUES($1,$2,$3,$4)`, run, id, p, revisions[p]); e == nil {
|
||||
if _, e = tx.Exec(r.Context(), `INSERT INTO runs(id,job_id,profile_id,revision_id,profile_name) SELECT $1,$2,id,$4,name FROM profiles WHERE id=$3`, run, id, p, revisions[p]); e == nil {
|
||||
_, e = tx.Exec(r.Context(), `INSERT INTO attempts(id,run_id,command_id)VALUES($1,$2,$3)`, store.NewID(), run, store.NewID())
|
||||
}
|
||||
if e != nil {
|
||||
@@ -392,9 +392,9 @@ func (s *Server) admit(r *http.Request, tx pgx.Tx, owner string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
const jobRunsSummary = `COALESCE((SELECT jsonb_agg(` + runProjection + ` ORDER BY r.id) FROM runs r JOIN profiles p ON p.id=r.profile_id WHERE r.job_id=j.id),'[]'::jsonb)`
|
||||
const jobRunsSummary = `COALESCE((SELECT jsonb_agg(to_jsonb(r) ORDER BY 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(` + runProjection + `||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 JOIN profiles p ON p.id=r.profile_id 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,'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')`
|
||||
|
||||
func (s *Server) respondJob(w http.ResponseWriter, r *http.Request, id string, status int) {
|
||||
a := user(r)
|
||||
|
||||
Reference in new issue
Block a user