Publish reviewed standalone otche-backend sources

This commit is contained in:
omar committed 2026-09-23 17:15:07 +03:00
commit ccb09de352
67 files changed
+11396

No files matched your search

+344
View File
@@ -0,0 +1,344 @@
package api
import (
"encoding/json"
"net/http"
"strings"
"golang.org/x/crypto/bcrypt"
"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) {
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 `+profileProjection+` 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'||jsonb_build_object('os_build',`+revisionOSBuild+`) 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"))
}))
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"))
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) FROM bindings b ORDER BY owner_id`)
}))
m.HandleFunc("GET /api/v1/admin/health", s.protected(true, s.health))
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::text=$1 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 {
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(), `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)
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(), `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)
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(), `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"))
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)
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::text=$1 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 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 `+profileProjection+` 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::text=$1 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::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"))
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})
}
+122
View File
@@ -0,0 +1,122 @@
package api
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"otche/internal/store"
)
// This integration test uses its own PostgreSQL schema and never a runtime adapter.
func TestAccountLoginLimitAndSessionRevocation(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)
}
password := "Regression-only-long-password"
for _, name := range []string{"first-user", "second-user"} {
if _, err = CreateUser(ctx, db, name, password, "operator"); err != nil {
t.Fatal(err)
}
}
s, err := New(db, Config{Origin: "http://localhost", ArtifactRoot: t.TempDir()})
if err != nil {
t.Fatal(err)
}
login := func(name, pass string) *httptest.ResponseRecorder {
body, _ := json.Marshal(map[string]string{"username": name, "password": pass})
r := httptest.NewRequest("POST", "/api/v1/auth/login", strings.NewReader(string(body)))
r.RemoteAddr = "172.20.0.2:80"
r.Header.Set("Origin", "http://localhost")
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
return w
}
var cookie *http.Cookie
for i := range 17 {
w := login("first-user", password)
if w.Code != 200 {
t.Fatalf("valid login %d locked out: %d %s", i, w.Code, w.Body)
}
cookie = w.Result().Cookies()[0]
}
for i := range 15 {
w := login("first-user", "wrong password")
if w.Code != 401 {
t.Fatalf("failed attempt %d: %d", i, w.Code)
}
}
if w := login("first-user", password); w.Code != 429 {
t.Fatalf("exhausted account should throttle, got %d", w.Code)
}
if w := login("second-user", password); w.Code != 200 {
t.Fatalf("shared proxy must not lock unrelated account: %d", w.Code)
}
if _, err = db.Exec(ctx, `UPDATE users SET disabled=true WHERE username='first-user'`); err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("GET", "/api/v1/auth/session", nil)
r.AddCookie(cookie)
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
if w.Code != 401 {
t.Fatalf("disabled user session retained access: %d", w.Code)
}
if _, err = db.Exec(ctx, `UPDATE users SET role='admin' WHERE username='second-user'`); err != nil {
t.Fatal(err)
}
elevated := login("second-user", password)
adminRequest := httptest.NewRequest("GET", "/api/v1/admin/users", nil)
adminRequest.AddCookie(elevated.Result().Cookies()[0])
before := httptest.NewRecorder()
s.ServeHTTP(before, adminRequest)
if before.Code != 200 {
t.Fatalf("admin access unavailable: %d", before.Code)
}
if _, err = db.Exec(ctx, `UPDATE users SET role='operator' WHERE username='second-user'`); err != nil {
t.Fatal(err)
}
after := httptest.NewRecorder()
s.ServeHTTP(after, adminRequest)
if after.Code != 403 {
t.Fatalf("demoted existing session retained admin: %d", after.Code)
}
db.Close()
w = httptest.NewRecorder()
s.ServeHTTP(w, r)
if w.Code != 500 {
t.Fatalf("database failure disguised as auth failure: %d", w.Code)
}
fmt.Fprintln(os.Stdout, "17 valid proxied logins; account failure throttling; unrelated user unaffected; revoked session denied; DB failure remains 500")
}
+139
View File
@@ -0,0 +1,139 @@
package api
import (
"context"
"encoding/json"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"otche/internal/store"
)
func TestBindingExpiryBlocksReadinessAndAdmission(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, "expiry-admin", "Regression-only-long-password", "admin")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO bindings(owner_id,pool,iso_storage,disk_storage,node,configured,reason,isolation_expires_at)VALUES($1,'pool','iso','disks','node',true,'',now()+interval '1 hour');`, owner); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO heartbeats(name,seen_at,ready,blockers)VALUES('worker',now(),true,'[]')`); err != nil {
t.Fatal(err)
}
upload, profile, revision := 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,'benign.exe',1,$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,'isolated expiry fixture','Windows','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,'isolated-test','test','test')`, revision, profile); 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":"expiry-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]
var session struct {
CSRF string `json:"csrf_token"`
}
if err = json.Unmarshal(logged.Body.Bytes(), &session); err != nil {
t.Fatal(err)
}
for _, state := range []struct {
expiry string
want bool
}{{"now()+interval '1 hour'", true}, {"now()-interval '1 second'", false}, {"NULL", false}} {
if _, err = db.Exec(ctx, "UPDATE bindings SET configured=true,isolation_expires_at="+state.expiry); err != nil {
t.Fatal(err)
}
for _, endpoint := range []string{"/api/v1/dashboard", "/api/v1/admin/bindings"} {
r := httptest.NewRequest("GET", endpoint, nil)
r.AddCookie(cookie)
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("%s: %d %s", endpoint, w.Code, w.Body)
}
var body map[string]any
if err = json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
var got bool
if endpoint == "/api/v1/dashboard" {
got = body["integration"].(map[string]any)["ready"].(bool)
} else {
got = body["items"].([]any)[0].(map[string]any)["configured"].(bool)
}
if got != state.want {
t.Fatalf("%s readiness=%v for expiry %s", endpoint, got, state.expiry)
}
}
requestBody, err := json.Marshal(map[string]any{"upload_id": upload, "profile_ids": []string{profile}, "settings": map[string]any{"internet": "offline", "duration_seconds": 30, "filename": "original", "privilege": "user", "args_mode": "none", "args": []string{}}})
if err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("POST", "/api/v1/jobs", strings.NewReader(string(requestBody)))
r.AddCookie(cookie)
r.Header.Set("Origin", "http://localhost")
r.Header.Set("X-CSRF-Token", session.CSRF)
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
if state.want {
if w.Code != 201 {
t.Fatalf("valid isolation proof did not admit owned job: %d %s", w.Code, w.Body)
}
} else {
var rejected struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
if err = json.Unmarshal(w.Body.Bytes(), &rejected); err != nil {
t.Fatal(err)
}
if w.Code != 409 || rejected.Error.Code != "admission_closed" {
t.Fatalf("expired/null proof did not close public admission: %d %s", w.Code, w.Body)
}
}
}
}
+119
View File
@@ -0,0 +1,119 @@
package api
import (
"archive/zip"
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"github.com/jackc/pgx/v5/pgxpool"
"net/http/httptest"
"os"
"otche/internal/store"
"path/filepath"
"strings"
"testing"
)
func TestGrubArchiveOwnerAuthorization(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, "grub-owner", "Grub-regression-password-only", "operator")
if err != nil {
t.Fatal(err)
}
if _, err = CreateUser(ctx, db, "grub-other", "Grub-regression-password-only", "operator"); err != nil {
t.Fatal(err)
}
upload, job, artifact := 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,'test.bat',1,$3,'upload-' || $4)`, upload, owner, strings.Repeat("a", 64), upload); 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,'test.bat','completed','{}')`, job, owner, upload); err != nil {
t.Fatal(err)
}
var archive bytes.Buffer
z := zip.NewWriter(&archive)
f, err := z.Create("manifest.json")
if err != nil {
t.Fatal(err)
}
f.Write([]byte(`{"status":"empty","requested":1,"collected":0}`))
if err = z.Close(); err != nil {
t.Fatal(err)
}
root := t.TempDir()
if err = os.WriteFile(filepath.Join(root, "private.zip"), archive.Bytes(), 0600); err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(archive.Bytes())
if _, err = db.Exec(ctx, `INSERT INTO artifacts(id,job_id,kind,filename,content_type,size,sha256,storage_key) VALUES($1,$2,'grub_archive','grub.zip','application/zip',$3,$4,'private.zip')`, artifact, job, archive.Len(), hex.EncodeToString(sum[:])); err != nil {
t.Fatal(err)
}
s, err := New(db, Config{Origin: "http://localhost", ArtifactRoot: root})
if err != nil {
t.Fatal(err)
}
for _, user := range []string{"grub-owner", "grub-other"} {
login := httptest.NewRequest("POST", "/api/v1/auth/login", strings.NewReader(`{"username":"`+user+`","password":"Grub-regression-password-only"}`))
login.Header.Set("Origin", "http://localhost")
logged := httptest.NewRecorder()
s.ServeHTTP(logged, login)
if logged.Code != 200 {
t.Fatalf("login %s: %d", user, logged.Code)
}
req := httptest.NewRequest("GET", "/api/v1/artifacts/"+artifact+"/content", nil)
req.AddCookie(logged.Result().Cookies()[0])
res := httptest.NewRecorder()
s.ServeHTTP(res, req)
if user == "grub-other" {
if res.Code != 404 || bytes.Equal(res.Body.Bytes(), archive.Bytes()) {
t.Fatal("foreign owner received private archive")
}
continue
}
if res.Code != 200 || !bytes.Equal(res.Body.Bytes(), archive.Bytes()) || !strings.HasPrefix(res.Header().Get("Content-Disposition"), "attachment;") || res.Header().Get("Content-Type") != "application/octet-stream" {
t.Fatalf("owner archive not a safe exact-byte attachment: %d %v", res.Code, res.Header())
}
}
}
func TestGrubSettingsManifestBound(t *testing.T) {
base := Settings{Internet: "offline", Duration: 30, Filename: "original", Privilege: "user", ArgsMode: "custom", Args: []string{}, GrubPaths: []string{`C:\Logs\100%done{copy}.log`}}
if err := base.validate("file.bat"); err != nil {
t.Fatal(err)
}
base.Args = make([]string, 64)
for i := range base.Args {
base.Args[i] = strings.Repeat("&", 256)
}
if err := base.validate("file.bat"); err == nil {
t.Fatal("escaped serialized manifest overflow was admitted")
}
}
+214
View File
@@ -0,0 +1,214 @@
package api
import (
"context"
"encoding/json"
"net/http/httptest"
"os"
"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','{}')`, 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 {
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 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 {
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 {
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 {
t.Fatal(err)
}
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
}
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 {
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")
}
}
+605
View File
@@ -0,0 +1,605 @@
package api
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
"otche/internal/grub"
"otche/internal/pve"
"otche/internal/store"
)
type Settings struct {
Internet string `json:"internet"`
Duration int `json:"duration_seconds"`
Filename string `json:"filename"`
Privilege string `json:"privilege"`
ArgsMode string `json:"args_mode"`
Args []string `json:"args"`
SetZoneID bool `json:"set_zoneid"`
DLLMode string `json:"dll_mode"`
DLLExport string `json:"dll_export"`
Architecture string `json:"architecture"`
WSHHost string `json:"wsh_host"`
MSIUI string `json:"msi_ui"`
GrubPaths []string `json:"grub_paths,omitempty"`
}
var extensions = map[string]bool{".exe": true, ".dll": true, ".scr": true, ".com": true, ".ps1": true, ".vbs": true, ".js": true, ".bat": true, ".cmd": true, ".msi": true}
var exportRE = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_@?$]{0,127}$`)
func validFilename(v string) bool {
if v == "" || len(v) > 180 || strings.ContainsAny(v, "\\/:*?\"<>|\x00\r\n") || strings.TrimSpace(v) != v || strings.HasSuffix(v, ".") {
return false
}
for _, c := range v {
if c < 32 {
return false
}
}
base := strings.ToUpper(strings.SplitN(v, ".", 2)[0])
if base == "CON" || base == "PRN" || base == "AUX" || base == "NUL" || regexp.MustCompile(`^(COM|LPT)[1-9]$`).MatchString(base) {
return false
}
return extensions[strings.ToLower(filepath.Ext(v))]
}
func (v *Settings) validate(filename string) error {
if err := grub.Validate(v.GrubPaths); err != nil {
return err
}
if v.Internet != "online" && v.Internet != "offline" {
return errors.New("internet must be online/offline")
}
ok := false
for _, d := range []int{30, 60, 90, 120, 180, 300, 600, 900, 1200} {
if v.Duration == d {
ok = true
}
}
if !ok {
return errors.New("unsupported duration_seconds")
}
if v.Filename != "original" && v.Filename != "random" {
return errors.New("filename must be original/random")
}
if v.Privilege != "user" && v.Privilege != "admin" {
return errors.New("privilege must be user/admin")
}
if v.ArgsMode != "none" && v.ArgsMode != "custom" {
return errors.New("args_mode must be none/custom")
}
if v.ArgsMode == "none" && len(v.Args) != 0 {
return errors.New("args must be empty with args_mode none")
}
if len(v.Args) > 64 {
return errors.New("too many arguments")
}
for _, a := range v.Args {
if len(a) > 2048 || strings.ContainsAny(a, "\x00\r\n") {
return errors.New("invalid argument")
}
}
if v.DLLMode == "" && !strings.EqualFold(filepath.Ext(filename), ".dll") {
v.DLLMode = "regsvr32"
}
if v.Architecture == "" {
v.Architecture = "auto"
}
if v.WSHHost == "" {
v.WSHHost = "cscript"
}
if v.MSIUI == "" {
v.MSIUI = "full"
}
if v.Architecture != "auto" && v.Architecture != "x86" && v.Architecture != "x64" {
return errors.New("invalid architecture")
}
if v.WSHHost != "cscript" && v.WSHHost != "wscript" {
return errors.New("invalid WSH host")
}
if v.MSIUI != "full" && v.MSIUI != "quiet" && v.MSIUI != "passive" {
return errors.New("invalid MSI UI")
}
if strings.EqualFold(filepath.Ext(filename), ".dll") {
if v.DLLMode != "regsvr32" && v.DLLMode != "rundll32" {
return errors.New("DLL requires explicit compatible handler")
}
if v.DLLMode == "rundll32" && !exportRE.MatchString(v.DLLExport) {
return errors.New("DLL requires explicit compatible export")
}
}
encoded, err := json.Marshal(v)
if err != nil || len(encoded) > pve.ControlLimit-2048 {
return errors.New("serialized settings and arguments exceed guest manifest transport bound")
}
return nil
}
func (s *Server) jobRoutes() {
m := s.mux
m.HandleFunc("POST /api/v1/uploads", s.protected(false, s.upload))
m.HandleFunc("GET /api/v1/uploads/{id}/content", s.protected(false, s.uploadContent))
m.HandleFunc("POST /api/v1/jobs", s.protected(false, s.createJob))
m.HandleFunc("GET /api/v1/jobs", s.protected(false, s.jobs))
m.HandleFunc("GET /api/v1/jobs/{id}", s.protected(false, s.getJob))
m.HandleFunc("POST /api/v1/jobs/{id}/cancel", s.protected(false, s.cancelJob))
m.HandleFunc("POST /api/v1/jobs/{id}/retry", s.protected(false, s.retryJob))
m.HandleFunc("GET /api/v1/jobs/{id}/events", s.protected(false, s.events))
m.HandleFunc("GET /api/v1/jobs/{id}/artifacts", s.protected(false, s.artifacts))
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`)
}))
m.HandleFunc("GET /api/v1/dashboard", s.protected(false, s.dashboard))
}
func (s *Server) upload(w http.ResponseWriter, r *http.Request) {
a := user(r)
name, e := url.PathUnescape(r.Header.Get("X-Filename"))
if e != nil || !validFilename(name) {
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)
if e != nil {
s.dbError(w, e)
return
}
remaining := s.cfg.MaxOwnerBytes - used
if remaining <= 0 {
fail(w, 429, "quota_exceeded", "Owner storage quota reached")
return
}
limit := s.cfg.MaxUploadBytes
if remaining < limit {
limit = remaining
}
if r.ContentLength > limit {
fail(w, 413, "upload_too_large", "Upload exceeds quota")
return
}
uploadID := store.NewID()
key := "uploads/" + a.ID + "/" + uploadID
path := filepath.Join(s.cfg.ArtifactRoot, filepath.FromSlash(key))
if e = os.MkdirAll(filepath.Dir(path), 0700); e != nil {
fail(w, 500, "storage_error", "Private storage unavailable")
return
}
f, e := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if e != nil {
fail(w, 500, "storage_error", "Private storage unavailable")
return
}
keep := false
defer func() {
f.Close()
if !keep {
os.Remove(path)
}
}()
h := sha256.New()
n, e := io.Copy(io.MultiWriter(f, h), http.MaxBytesReader(w, r.Body, limit))
if e != nil {
fail(w, 413, "upload_failed", "Upload incomplete or exceeds limit")
return
}
if n == 0 {
fail(w, 400, "empty_upload", "Empty uploads are not accepted")
return
}
if e = f.Sync(); e != nil {
fail(w, 500, "storage_error", "Could not commit upload")
return
}
if e = f.Close(); e != nil {
fail(w, 500, "storage_error", "Could not finalize upload")
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)
if e != nil {
s.dbError(w, e)
return
}
if e = tx.Commit(r.Context()); e != nil {
s.dbError(w, e)
return
}
keep = true
jsonResponse(w, 201, map[string]any{"id": uploadID, "filename": name, "size": n, "sha256": sum, "created_at": created})
}
func (s *Server) servePrivate(w http.ResponseWriter, r *http.Request, key, name, ct string) {
root, e := os.OpenRoot(s.cfg.ArtifactRoot)
if e != nil {
fail(w, 500, "storage_error", "Storage unavailable")
return
}
defer root.Close()
f, e := root.Open(filepath.FromSlash(key))
if e != nil {
fail(w, 404, "artifact_unavailable", "Artifact unavailable")
return
}
defer f.Close()
st, e := f.Stat()
if e != nil || !st.Mode().IsRegular() {
fail(w, 404, "artifact_unavailable", "Artifact unavailable")
return
}
disposition := "attachment"
if ct == "video/mp4" {
disposition = "inline"
}
w.Header().Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": name}))
if ct != "video/mp4" {
ct = "application/octet-stream"
}
w.Header().Set("Content-Type", ct)
http.ServeContent(w, r, name, st.ModTime(), f)
}
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)
if e != nil {
s.dbError(w, e)
return
}
s.servePrivate(w, r, key, name, "application/octet-stream")
}
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)
if e != nil {
s.dbError(w, e)
return
}
s.servePrivate(w, r, key, name, ct)
}
func (s *Server) createJob(w http.ResponseWriter, r *http.Request) {
var in struct {
UploadID string `json:"upload_id"`
ProfileIDs []string `json:"profile_ids"`
Settings Settings `json:"settings"`
}
if !decode(w, r, &in) {
return
}
if !uuidRE.MatchString(in.UploadID) || len(in.ProfileIDs) == 0 || len(in.ProfileIDs) > 12 {
fail(w, 400, "invalid_request", "Select one to twelve profiles and an upload")
return
}
seen := map[string]bool{}
for _, p := range in.ProfileIDs {
if !uuidRE.MatchString(p) || seen[p] {
fail(w, 400, "invalid_request", "Profile identifiers must be unique UUIDs")
return
}
seen[p] = true
}
a := user(r)
tx, e := s.db.Begin(r.Context())
if e != nil {
s.dbError(w, e)
return
}
defer tx.Rollback(r.Context())
var name string
e = tx.QueryRow(r.Context(), `SELECT filename FROM uploads WHERE id=$1 AND owner_id=$2`, in.UploadID, a.ID).Scan(&name)
if e != nil {
s.dbError(w, e)
return
}
if e = in.Settings.validate(name); e != nil {
fail(w, 400, "invalid_settings", e.Error())
return
}
if e = s.admit(r, tx, a.ID); e != nil {
fail(w, 409, "admission_closed", e.Error())
return
}
revisions := map[string]string{}
for _, id := range in.ProfileIDs {
var revision string
var valid bool
e = tx.QueryRow(r.Context(), `SELECT COALESCE(current_revision_id::text,''),enabled AND qualification='qualified' AND state='published' AND ($2='offline' OR online_available) FROM profiles WHERE id=$1 FOR SHARE`, id, in.Settings.Internet).Scan(&revision, &valid)
if e != nil || !valid || revision == "" {
fail(w, 409, "profile_unavailable", "Selected profile is unqualified, in maintenance, or does not support the requested network")
return
}
revisions[id] = revision
}
execName := name
if in.Settings.Filename == "random" {
execName = store.NewID() + filepath.Ext(name)
}
id := store.NewID()
settings, _ := json.Marshal(in.Settings)
_, e = tx.Exec(r.Context(), `INSERT INTO jobs(id,owner_id,upload_id,execution_filename,settings)VALUES($1,$2,$3,$4,$5)`, id, a.ID, in.UploadID, execName, settings)
if e != nil {
s.dbError(w, e)
return
}
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 {
_, 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 {
s.dbError(w, e)
return
}
}
_, e = tx.Exec(r.Context(), `INSERT INTO events(job_id,kind,message)VALUES($1,'queued','Job admitted with immutable settings and source revisions')`, id)
if e != nil {
s.dbError(w, e)
return
}
if e = tx.Commit(r.Context()); e != nil {
s.dbError(w, e)
return
}
s.respondJob(w, r, id, 201)
}
func (s *Server) admit(r *http.Request, tx pgx.Tx, owner string) error {
var id string
if e := tx.QueryRow(r.Context(), `SELECT id::text FROM users WHERE id=$1 FOR UPDATE`, owner).Scan(&id); e != nil {
return e
}
var configured bool
e := tx.QueryRow(r.Context(), `SELECT configured AND COALESCE(isolation_expires_at>now(),false) FROM bindings WHERE owner_id=$1`, owner).Scan(&configured)
if e != nil || !configured {
return errors.New("Owner PVE isolation and credentials are not configured")
}
var workerReady bool
e = tx.QueryRow(r.Context(), `SELECT COALESCE(bool_or(ready AND seen_at>now()-interval '45 seconds'),false) FROM heartbeats WHERE name='worker'`).Scan(&workerReady)
if e != nil || !workerReady {
return errors.New("Execution worker is not ready")
}
var count int
e = tx.QueryRow(r.Context(), `SELECT count(*) FROM jobs WHERE owner_id=$1 AND status IN('queued','running')`, owner).Scan(&count)
if e != nil {
return e
}
if count >= s.cfg.MaxQueuedJobs {
return errors.New("Owner queue quota reached")
}
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 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')`
func (s *Server) respondJob(w http.ResponseWriter, r *http.Request, id string, status int) {
a := user(r)
v, e := s.queryObject(r.Context(), jobQuery, id, a.ID, a.Role)
if e != nil {
s.dbError(w, e)
return
}
jsonResponse(w, status, v)
}
func (s *Server) getJob(w http.ResponseWriter, r *http.Request) {
s.respondJob(w, r, r.PathValue("id"), 200)
}
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)
return id, e
}
func (s *Server) jobs(w http.ResponseWriter, r *http.Request) {
a := user(r)
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
if page < 1 {
page = 1
}
size, _ := strconv.Atoi(r.URL.Query().Get("page_size"))
if size < 1 {
size = 25
}
if size > 100 {
size = 100
}
if page > 100000 {
fail(w, 400, "invalid_page", "Page too large")
return
}
q := r.URL.Query().Get("q")
if len(q) > 128 {
fail(w, 400, "invalid_query", "Search too long")
return
}
status := r.URL.Query().Get("status")
var total int
where := ` FROM jobs j JOIN uploads u ON u.id=j.upload_id WHERE(j.owner_id=$1 OR $2='admin') AND($3='' OR u.filename ILIKE '%'||$3||'%' OR u.sha256=$3) AND($4='' OR j.status=$4)`
e := s.db.QueryRow(r.Context(), `SELECT count(*)`+where, a.ID, a.Role, q, status).Scan(&total)
if e != nil {
s.dbError(w, e)
return
}
v, e := s.queryList(r.Context(), `SELECT to_jsonb(j)||jsonb_build_object('filename',u.filename,'sha256',u.sha256,'size',u.size,'runs',`+jobRunsSummary+`)`+where+` ORDER BY j.created_at DESC LIMIT $5 OFFSET $6`, a.ID, a.Role, q, status, size, (page-1)*size)
if e != nil {
s.dbError(w, e)
return
}
var next any
if page*size < total {
next = page + 1
}
jsonResponse(w, 200, map[string]any{"items": v, "total": total, "page": page, "page_size": size, "next_page": next})
}
func (s *Server) cancelJob(w http.ResponseWriter, r *http.Request) {
id, e := s.ownJob(r)
if e != nil {
s.dbError(w, e)
return
}
_, e = s.db.Exec(r.Context(), `UPDATE jobs SET cancel_requested=true,updated_at=now() WHERE id=$1 AND status IN('queued','running')`, id)
if e != nil {
s.dbError(w, e)
return
}
s.respondJob(w, r, id, 200)
}
func (s *Server) retryJob(w http.ResponseWriter, r *http.Request) {
id, e := s.ownJob(r)
if e != nil {
s.dbError(w, e)
return
}
tx, e := s.db.Begin(r.Context())
if e != nil {
s.dbError(w, e)
return
}
defer tx.Rollback(r.Context())
var status, owner string
e = tx.QueryRow(r.Context(), `SELECT status,owner_id::text FROM jobs WHERE id=$1 FOR UPDATE`, id).Scan(&status, &owner)
if e != nil {
s.dbError(w, e)
return
}
if status == "queued" || status == "running" {
fail(w, 409, "job_active", "An active job cannot be retried")
return
}
if e = s.admit(r, tx, owner); e != nil {
fail(w, 409, "admission_closed", e.Error())
return
}
rows, e := tx.Query(r.Context(), `SELECT r.id::text,p.enabled AND p.state='published' AND p.qualification='qualified' AND p.current_revision_id=r.revision_id FROM runs r JOIN profiles p ON p.id=r.profile_id WHERE r.job_id=$1 FOR SHARE OF p`, id)
if e != nil {
s.dbError(w, e)
return
}
ids := []string{}
valid := true
for rows.Next() {
var run string
var ok bool
if e = rows.Scan(&run, &ok); e != nil {
break
}
valid = valid && ok
ids = append(ids, run)
}
rows.Close()
if e != nil {
s.dbError(w, e)
return
}
if !valid {
fail(w, 409, "revision_unavailable", "Original source revision is no longer admitted; retry cannot silently change revision")
return
}
for _, run := range ids {
if _, e = tx.Exec(r.Context(), `INSERT INTO attempts(id,run_id,command_id)VALUES($1,$2,$3)`, store.NewID(), run, store.NewID()); e != nil {
s.dbError(w, e)
return
}
}
_, e = tx.Exec(r.Context(), `UPDATE runs SET status='queued' WHERE job_id=$1`, id)
if e == nil {
_, e = tx.Exec(r.Context(), `UPDATE jobs SET status='queued',cancel_requested=false,updated_at=now() WHERE id=$1`, id)
}
if e == nil {
_, e = tx.Exec(r.Context(), `INSERT INTO events(job_id,kind,message)VALUES($1,'retry','New attempts queued; prior attempts preserved')`, id)
}
if e != nil {
s.dbError(w, e)
return
}
if e = tx.Commit(r.Context()); e != nil {
s.dbError(w, e)
return
}
s.respondJob(w, r, id, 200)
}
func (s *Server) events(w http.ResponseWriter, r *http.Request) {
id, e := s.ownJob(r)
if e != nil {
s.dbError(w, e)
return
}
after, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
s.list(w, r, `SELECT to_jsonb(e) FROM events e WHERE job_id=$1 AND id>$2 ORDER BY id LIMIT 500`, id, after)
}
func (s *Server) artifacts(w http.ResponseWriter, r *http.Request) {
id, e := s.ownJob(r)
if e != nil {
s.dbError(w, e)
return
}
s.list(w, r, `SELECT to_jsonb(a)-'storage_key'||jsonb_build_object('url','/api/v1/artifacts/'||a.id||'/content') FROM artifacts a WHERE job_id=$1 ORDER BY created_at`, id)
}
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)
if e != nil {
s.dbError(w, e)
return
}
jsonResponse(w, 200, v)
}
func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
a := user(r)
metrics, e := s.queryObject(r.Context(), `SELECT jsonb_build_object('jobs',count(*),'queued',count(*)FILTER(WHERE status='queued'),'running',count(*)FILTER(WHERE status='running'),'completed',count(*)FILTER(WHERE status='completed'),'failed',count(*)FILTER(WHERE status='failed'),'cancelled',count(*)FILTER(WHERE status='cancelled'),'detected',count(*)FILTER(WHERE EXISTS(SELECT 1 FROM runs r JOIN attempts a ON a.run_id=r.id WHERE r.job_id=j.id AND a.findings='detected'))) FROM jobs j WHERE owner_id=$1 OR $2='admin'`, a.ID, a.Role)
if e != nil {
s.dbError(w, e)
return
}
recent, e := s.queryList(r.Context(), `SELECT to_jsonb(j)||jsonb_build_object('filename',u.filename,'sha256',u.sha256,'size',u.size,'runs',`+jobRunsSummary+`) FROM jobs j JOIN uploads u ON u.id=j.upload_id WHERE j.owner_id=$1 OR $2='admin' ORDER BY j.created_at DESC LIMIT 5`, a.ID, a.Role)
if e != nil {
s.dbError(w, e)
return
}
health := s.integration(r)
jsonResponse(w, 200, map[string]any{"metrics": metrics, "recent_jobs": recent, "queue": map[string]any{"queued": metrics["queued"], "running": metrics["running"]}, "integration": health})
}
func (s *Server) integration(r *http.Request) map[string]any {
var ready bool
var b []byte
e := s.db.QueryRow(r.Context(), `SELECT ready AND seen_at>now()-interval '45 seconds',blockers FROM heartbeats WHERE name='worker'`).Scan(&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 is unavailable")
}
}
var configured bool
if e = s.db.QueryRow(r.Context(), `SELECT configured AND COALESCE(isolation_expires_at>now(),false) FROM bindings WHERE owner_id=$1`, user(r).ID).Scan(&configured); e != nil || !configured {
ready = false
blockers = append(blockers, "Owner isolation binding is missing, invalid or expired")
}
return map[string]any{"ready": ready, "blockers": blockers}
}
+319
View File
@@ -0,0 +1,319 @@
package api
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
"otche/internal/store"
)
type Config struct {
Origin, ArtifactRoot string
SecureCookies bool
MaxUploadBytes, MaxOwnerBytes int64
MaxQueuedJobs int
}
type Server struct {
db *pgxpool.Pool
cfg Config
mux *http.ServeMux
dummyHash []byte
}
type identity struct{ ID, Username, Role, CSRF, TokenHash string }
type authKey struct{}
var uuidRE = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
var usernameRE = regexp.MustCompile(`^[A-Za-z0-9_.-]{3,64}$`)
func New(db *pgxpool.Pool, c Config) (*Server, error) {
if c.Origin == "" || c.ArtifactRoot == "" {
return nil, errors.New("origin and artifact root required")
}
if c.MaxUploadBytes <= 0 {
c.MaxUploadBytes = 512 << 20
}
if c.MaxOwnerBytes <= 0 {
c.MaxOwnerBytes = 8 << 30
}
if c.MaxQueuedJobs <= 0 {
c.MaxQueuedJobs = 20
}
if e := os.MkdirAll(c.ArtifactRoot, 0700); e != nil {
return nil, e
}
h, e := bcrypt.GenerateFromPassword([]byte(randomToken()), 12)
if e != nil {
return nil, e
}
s := &Server{db: db, cfg: c, mux: http.NewServeMux(), dummyHash: h}
s.routes()
return s, nil
}
func randomToken() string {
b := make([]byte, 32)
if _, e := rand.Read(b); e != nil {
panic(e)
}
return hex.EncodeToString(b)
}
func hashToken(v string) string { h := sha256.Sum256([]byte(v)); return hex.EncodeToString(h[:]) }
func jsonResponse(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func fail(w http.ResponseWriter, status int, code, message string) {
jsonResponse(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}})
}
func decode(w http.ResponseWriter, r *http.Request, v any) bool {
r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
if e := d.Decode(v); e != nil {
fail(w, 400, "invalid_request", "Invalid JSON request")
return false
}
if e := d.Decode(new(any)); e != io.EOF {
fail(w, 400, "invalid_request", "Expected one JSON value")
return false
}
return true
}
func user(r *http.Request) identity { return r.Context().Value(authKey{}).(identity) }
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("Content-Security-Policy", "default-src 'none'; sandbox")
defer func() {
if recover() != nil {
slog.Error("API request panicked")
fail(w, 500, "internal_error", "Request failed")
}
}()
s.mux.ServeHTTP(w, r)
}
func (s *Server) origin(w http.ResponseWriter, r *http.Request) bool {
if r.Header.Get("Origin") != s.cfg.Origin {
fail(w, 403, "origin_rejected", "Origin is not allowed")
return false
}
return true
}
func (s *Server) protected(admin bool, h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("otche_session")
if err != nil || len(c.Value) != 64 {
fail(w, 401, "unauthenticated", "Sign in required")
return
}
a := identity{TokenHash: hashToken(c.Value)}
err = s.db.QueryRow(r.Context(), `SELECT u.id::text,u.username,u.role,s.csrf_token FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=$1 AND s.expires_at>now() AND NOT u.disabled`, a.TokenHash).Scan(&a.ID, &a.Username, &a.Role, &a.CSRF)
if errors.Is(err, pgx.ErrNoRows) {
fail(w, 401, "unauthenticated", "Session expired")
return
}
if err != nil {
s.dbError(w, err)
return
}
if admin && a.Role != "admin" {
fail(w, 403, "forbidden", "Administrator required")
return
}
if r.Method != "GET" && r.Method != "HEAD" {
if !s.origin(w, r) {
return
}
if subtle.ConstantTimeCompare([]byte(r.Header.Get("X-CSRF-Token")), []byte(a.CSRF)) != 1 {
fail(w, 403, "csrf_rejected", "CSRF token required")
return
}
}
h(w, r.WithContext(context.WithValue(r.Context(), authKey{}, a)))
}
}
func (s *Server) dbError(w http.ResponseWriter, e error) {
if errors.Is(e, pgx.ErrNoRows) {
fail(w, 404, "not_found", "Resource not found")
return
}
slog.Error("database operation failed", "type", "query")
fail(w, 500, "internal_error", "Database operation failed")
}
func (s *Server) queryObject(ctx context.Context, q string, args ...any) (map[string]any, error) {
var b []byte
e := s.db.QueryRow(ctx, q, args...).Scan(&b)
if e != nil {
return nil, e
}
var v map[string]any
e = json.Unmarshal(b, &v)
return v, e
}
func (s *Server) queryList(ctx context.Context, q string, args ...any) ([]map[string]any, error) {
rows, e := s.db.Query(ctx, q, args...)
if e != nil {
return nil, e
}
defer rows.Close()
out := []map[string]any{}
for rows.Next() {
var b []byte
if e = rows.Scan(&b); e != nil {
return nil, e
}
var v map[string]any
if e = json.Unmarshal(b, &v); e != nil {
return nil, e
}
out = append(out, v)
}
return out, rows.Err()
}
func (s *Server) list(w http.ResponseWriter, r *http.Request, q string, args ...any) {
v, e := s.queryList(r.Context(), q, args...)
if e != nil {
s.dbError(w, e)
return
}
jsonResponse(w, 200, map[string]any{"items": v})
}
func (s *Server) routes() {
m := s.mux
m.HandleFunc("GET /api/v1/health", func(w http.ResponseWriter, r *http.Request) {
ctx, c := context.WithTimeout(r.Context(), 2*time.Second)
defer c()
if s.db.Ping(ctx) != nil {
fail(w, 503, "unavailable", "Database unavailable")
return
}
jsonResponse(w, 200, map[string]string{"status": "ok"})
})
m.HandleFunc("POST /api/v1/auth/login", s.login)
m.HandleFunc("GET /api/v1/auth/session", s.protected(false, s.session))
m.HandleFunc("POST /api/v1/auth/logout", s.protected(false, s.logout))
s.jobRoutes()
s.adminRoutes()
}
func (s *Server) session(w http.ResponseWriter, r *http.Request) {
a := user(r)
jsonResponse(w, 200, map[string]any{"user": map[string]string{"id": a.ID, "username": a.Username, "role": a.Role}, "csrf_token": a.CSRF})
}
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
if !s.origin(w, r) {
return
}
var in struct {
Username string `json:"username"`
Password string `json:"password"`
}
if !decode(w, r, &in) {
return
}
if !usernameRE.MatchString(in.Username) || len(in.Password) > 72 {
fail(w, 401, "invalid_credentials", "Invalid username or password")
return
}
// Account-scoped failures cannot collapse every proxied user into nginx's IP.
// No client-supplied forwarding header is trusted for authentication policy.
tx, err := s.db.Begin(r.Context())
if err != nil {
s.dbError(w, err)
return
}
defer tx.Rollback(r.Context())
key := hashToken("account:" + strings.ToLower(in.Username))
_, err = tx.Exec(r.Context(), `INSERT INTO login_limits(key,failures,reset_at) VALUES($1,0,now()+interval '15 minutes') ON CONFLICT DO NOTHING`, key)
if err != nil {
s.dbError(w, err)
return
}
var failures int
err = tx.QueryRow(r.Context(), `SELECT CASE WHEN reset_at>now() THEN failures ELSE 0 END FROM login_limits WHERE key=$1 FOR UPDATE`, key).Scan(&failures)
if err != nil {
s.dbError(w, err)
return
}
if failures >= 15 {
w.Header().Set("Retry-After", "900")
fail(w, 429, "rate_limited", "Too many failed login attempts for this account")
return
}
a := identity{}
var hash string
var disabled bool
err = tx.QueryRow(r.Context(), `SELECT id::text,username,role,password_hash,disabled FROM users WHERE username=$1`, in.Username).Scan(&a.ID, &a.Username, &a.Role, &hash, &disabled)
missing := errors.Is(err, pgx.ErrNoRows)
if err != nil && !missing {
s.dbError(w, err)
return
}
if missing {
hash = string(s.dummyHash)
}
match := bcrypt.CompareHashAndPassword([]byte(hash), []byte(in.Password)) == nil
if missing || !match || disabled {
_, err = tx.Exec(r.Context(), `UPDATE login_limits SET failures=$2,reset_at=CASE WHEN reset_at<=now() THEN now()+interval '15 minutes' ELSE reset_at END WHERE key=$1`, key, failures+1)
if err == nil {
err = tx.Commit(r.Context())
}
if err != nil {
s.dbError(w, err)
return
}
fail(w, 401, "invalid_credentials", "Invalid username or password")
return
}
token := randomToken()
a.CSRF = randomToken()
_, err = tx.Exec(r.Context(), `DELETE FROM login_limits WHERE key=$1`, key)
if err == nil {
_, err = tx.Exec(r.Context(), `INSERT INTO sessions(token_hash,user_id,csrf_token,expires_at) VALUES($1,$2,$3,now()+interval '12 hours')`, hashToken(token), a.ID, a.CSRF)
}
if err == nil {
err = tx.Commit(r.Context())
}
if err != nil {
s.dbError(w, err)
return
}
http.SetCookie(w, &http.Cookie{Name: "otche_session", Value: token, Path: "/api", HttpOnly: true, Secure: s.cfg.SecureCookies, SameSite: http.SameSiteStrictMode, MaxAge: 43200})
s.session(w, r.WithContext(context.WithValue(r.Context(), authKey{}, a)))
}
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
_, e := s.db.Exec(r.Context(), `DELETE FROM sessions WHERE token_hash=$1`, user(r).TokenHash)
if e != nil {
s.dbError(w, e)
return
}
http.SetCookie(w, &http.Cookie{Name: "otche_session", Value: "", Path: "/api", HttpOnly: true, Secure: s.cfg.SecureCookies, SameSite: http.SameSiteStrictMode, MaxAge: -1})
w.WriteHeader(204)
}
func CreateUser(ctx context.Context, db *pgxpool.Pool, username, password, role string) (string, error) {
if !usernameRE.MatchString(username) || len(password) < 14 || len(password) > 72 || strings.TrimSpace(password) != password || role != "admin" && role != "operator" {
return "", errors.New("username must be 3-64 safe characters, password 14-72 bytes, role admin/operator")
}
h, e := bcrypt.GenerateFromPassword([]byte(password), 12)
if e != nil {
return "", e
}
id := store.NewID()
_, e = db.Exec(ctx, `INSERT INTO users(id,username,password_hash,role)VALUES($1,$2,$3,$4)`, id, username, string(h), role)
return id, e
}