package api import ( "encoding/json" "net/http" "strings" "golang.org/x/crypto/bcrypt" "otche/internal/store" ) func (s *Server) adminRoutes() { m := s.mux m.HandleFunc("GET /api/v1/admin/users", s.protected(true, func(w http.ResponseWriter, r *http.Request) { s.list(w, r, `SELECT to_jsonb(u)-'password_hash' FROM users u ORDER BY created_at`) })) 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 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)) m.HandleFunc("POST /api/v1/admin/profiles/{id}/maintenance", s.protected(true, s.maintenance)) 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=$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=$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=$1::uuid`, r.PathValue("id")) if e != nil { s.dbError(w, e) return } jsonResponse(w, 200, v) })) m.HandleFunc("GET /api/v1/admin/bindings", s.protected(true, func(w http.ResponseWriter, r *http.Request) { 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,'online_ready',online_ready AND COALESCE(online_expires_at>now(),false),'online_reason',CASE WHEN online_ready AND NOT COALESCE(online_expires_at>now(),false) THEN 'Online network proof expired or requires revalidation' ELSE online_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) { var in struct { Username string `json:"username"` Password string `json:"password"` Role string `json:"role"` } if !decode(w, r, &in) { return } id, e := CreateUser(r.Context(), s.db, in.Username, in.Password, in.Role) if e != nil { fail(w, 400, "invalid_user", "Username must be unique (3-64 safe characters), password 14-72 bytes, role admin/operator") return } v, e := s.queryObject(r.Context(), `SELECT to_jsonb(u)-'password_hash' FROM users u WHERE id=$1`, id) if e != nil { s.dbError(w, e) return } jsonResponse(w, 201, v) } func (s *Server) updateUser(w http.ResponseWriter, r *http.Request) { var in struct { Role *string `json:"role"` Disabled *bool `json:"disabled"` Password *string `json:"password"` } if !decode(w, r, &in) { return } if in.Role != nil && *in.Role != "admin" && *in.Role != "operator" { fail(w, 400, "invalid_role", "Role must be admin/operator") return } var hash *string if in.Password != nil { if len(*in.Password) < 14 || len(*in.Password) > 72 || strings.TrimSpace(*in.Password) != *in.Password { fail(w, 400, "invalid_password", "Password must be 14-72 bytes without surrounding whitespace") return } b, e := bcrypt.GenerateFromPassword([]byte(*in.Password), 12) if e != nil { fail(w, 500, "internal_error", "Password hashing failed") return } h := string(b) hash = &h } tx, e := s.db.Begin(r.Context()) if e != nil { s.dbError(w, e) return } defer tx.Rollback(r.Context()) if _, e = tx.Exec(r.Context(), `SELECT pg_advisory_xact_lock(74638292)`); e != nil { s.dbError(w, e) return } var id, role string var disabled bool 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 } if role == "admin" && !disabled && (in.Role != nil && *in.Role != "admin" || in.Disabled != nil && *in.Disabled) { var count int e = tx.QueryRow(r.Context(), `SELECT count(*) FROM users WHERE role='admin' AND NOT disabled`).Scan(&count) if e != nil { s.dbError(w, e) return } if count <= 1 { fail(w, 409, "last_administrator", "Cannot disable or demote the last administrator") return } } _, e = tx.Exec(r.Context(), `UPDATE users SET role=COALESCE($2,role),disabled=COALESCE($3,disabled),password_hash=COALESCE($4,password_hash) WHERE id=$1`, id, in.Role, in.Disabled, hash) if e == nil { _, e = tx.Exec(r.Context(), `DELETE FROM sessions WHERE user_id=$1`, id) } if e == nil && (in.Password != nil || in.Disabled != nil && *in.Disabled) { _, e = tx.Exec(r.Context(), `UPDATE api_keys SET revoked_at=now() WHERE owner_id=$1 AND revoked_at IS NULL`, id) } if e != nil { s.dbError(w, e) return } if e = tx.Commit(r.Context()); e != nil { s.dbError(w, e) return } v, e := s.queryObject(r.Context(), `SELECT to_jsonb(u)-'password_hash' FROM users u WHERE id=$1`, id) if e != nil { s.dbError(w, e) return } jsonResponse(w, 200, v) } func (s *Server) createProfile(w http.ResponseWriter, r *http.Request) { var in struct { Name string `json:"name"` OS string `json:"os"` Architecture string `json:"architecture"` } if !decode(w, r, &in) { return } if strings.TrimSpace(in.Name) == "" || len(in.Name) > 120 || len(in.OS) > 120 || in.OS == "" || in.Architecture != "x64" && in.Architecture != "x86" { fail(w, 400, "invalid_profile", "Name, OS and x64/x86 architecture required") return } 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 } jsonResponse(w, 201, v) } func (s *Server) updateProfile(w http.ResponseWriter, r *http.Request) { var in struct { Name *string `json:"name"` Enabled *bool `json:"enabled"` } if !decode(w, r, &in) { return } if in.Name != nil && (strings.TrimSpace(*in.Name) == "" || len(*in.Name) > 120) { 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=$1::uuid RETURNING to_jsonb(profiles)`, r.PathValue("id"), in.Name, in.Enabled) if e != nil { s.dbError(w, e) return } 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=$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=$1::uuid AND a.phase IN('queued','provisioning')`, r.PathValue("id")).Scan(&pending) if e != nil { s.dbError(w, e) return } v["drain"] = map[string]any{"pending_clones": pending, "safe_to_maintain": pending == 0} jsonResponse(w, 200, v) } func (s *Server) publish(w http.ResponseWriter, r *http.Request) { var in struct { RevisionID string `json:"revision_id"` } if !decode(w, r, &in) { return } if !uuidRE.MatchString(in.RevisionID) { fail(w, 400, "invalid_revision", "Revision UUID required") return } tx, e := s.db.Begin(r.Context()) if e != nil { s.dbError(w, e) return } defer tx.Rollback(r.Context()) var profile string 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 } var qualified bool e = tx.QueryRow(r.Context(), `SELECT qualification IS NOT NULL AND qualification->>'status'='passed' FROM revisions WHERE id=$1 AND profile_id=$2`, in.RevisionID, profile).Scan(&qualified) if e != nil || !qualified { 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 { s.dbError(w, e) return } if pending > 0 { fail(w, 409, "source_not_drained", "Old revision still has unmaterialized attempts") return } _, e = tx.Exec(r.Context(), `UPDATE profiles SET current_revision_id=$2,qualification='qualified',state='published',enabled=true,reason='' WHERE id=$1`, profile, in.RevisionID) if e != nil { s.dbError(w, e) return } if e = tx.Commit(r.Context()); e != nil { s.dbError(w, e) return } 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 } jsonResponse(w, 200, v) } func (s *Server) qualify(w http.ResponseWriter, r *http.Request) { tx, e := s.db.Begin(r.Context()) if e != nil { s.dbError(w, e) return } defer tx.Rollback(r.Context()) var id string 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 } var exists bool e = tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM revisions WHERE profile_id=$1)`, id).Scan(&exists) if e != nil { s.dbError(w, e) return } if !exists { fail(w, 409, "source_not_configured", "Configure and validate source through worker CLI before qualification") return } e = tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM qualifications WHERE profile_id=$1 AND status IN('queued','running'))`, id).Scan(&exists) if e != nil { s.dbError(w, e) return } if exists { fail(w, 409, "qualification_active", "A qualification is already active") return } qid := store.NewID() _, e = tx.Exec(r.Context(), `INSERT INTO qualifications(id,profile_id)VALUES($1,$2)`, qid, id) if e != nil { s.dbError(w, e) return } if e = tx.Commit(r.Context()); e != nil { s.dbError(w, e) return } jsonResponse(w, 202, map[string]any{"id": qid, "status": "queued"}) } func (s *Server) health(w http.ResponseWriter, r *http.Request) { var seen any var ready bool var b []byte e := s.db.QueryRow(r.Context(), `SELECT seen_at,ready AND seen_at>now()-interval '45 seconds',blockers FROM heartbeats WHERE name='worker'`).Scan(&seen, &ready, &b) blockers := []string{} if e != nil { blockers = append(blockers, "Execution worker has not connected") } else { _ = json.Unmarshal(b, &blockers) } if !ready && len(blockers) == 0 { blockers = append(blockers, "Execution worker heartbeat is stale") } worker := "unavailable" if ready { worker = "ready" } jsonResponse(w, 200, map[string]any{"database": "ready", "worker": worker, "last_worker_seen": seen, "integration_ready": ready, "blockers": blockers}) } func (s *Server) releaseEvidence(w http.ResponseWriter, r *http.Request) { var in struct { Confirm bool `json:"confirm"` } if !decode(w, r, &in) { return } if !in.Confirm { 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=$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 } if tag.RowsAffected() != 1 { fail(w, 409, "not_retained", "Attempt is not holding releasable evidence") return } 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`) }