Support custom observation windows up to thirty minutes and prompt cancellation

This commit is contained in:
omar committed 2026-10-23 05:13:57 +03:00
1 parent 57958b3fe6
commit 47003a2bd3
16 files changed
+564 -78

No files matched your search

+13 -1
View File
@@ -7,6 +7,8 @@ import (
"reflect"
"strings"
"testing"
"otche/internal/duration"
)
// Exercise the public HTTP surface, without database/session availability.
@@ -138,7 +140,6 @@ func TestOpenAPIConsumerShapes(t *testing.T) {
field string
values []any
}{
{"SettingsInput", "duration_seconds", []any{float64(30), float64(60), float64(90), float64(120), float64(180), float64(300), float64(600), float64(900), float64(1200)}},
{"SettingsInput", "internet", []any{"offline", "online"}},
{"Attempt", "findings", []any{"unknown", "detected", "not_observed"}},
{"Attempt", "telemetry", []any{"pending", "complete", "partial", "unavailable"}},
@@ -149,6 +150,17 @@ func TestOpenAPIConsumerShapes(t *testing.T) {
t.Errorf("%s.%s enum = %v, want %v", tc.schema, tc.field, field["enum"], tc.values)
}
}
// Arbitrary whole seconds replace the former preset enum on input and stored settings.
for _, schema := range []string{"SettingsInput", "Settings"} {
field := documentObject(t, schemas, schema, "properties", "duration_seconds")
if field["type"] != "integer" || field["minimum"] != float64(duration.MinSeconds) || field["maximum"] != float64(duration.MaxSeconds) || field["enum"] != nil {
t.Errorf("%s.duration_seconds = %v, want integer %d..%d without presets", schema, field, duration.MinSeconds, duration.MaxSeconds)
}
}
cancel := documentObject(t, document, "paths", "/jobs/{id}/cancel", "post")
if description, _ := cancel["description"].(string); !strings.Contains(description, "outcome=cancelled") || !strings.Contains(description, "evidence_held") {
t.Errorf("cancel operation does not document queued finalization and evidence retention: %q", description)
}
for schema, fields := range map[string][]string{
"JobInput": {"upload_id", "profile_ids", "settings"},
"APIKeyInput": {"name", "scopes", "expires_in_days"},
+223
View File
@@ -0,0 +1,223 @@
package api
import (
"context"
"encoding/json"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"otche/internal/store"
)
func TestSettingsDurationBounds(t *testing.T) {
base := Settings{Internet: "offline", Filename: "original", Privilege: "user", ArgsMode: "none", Args: []string{}}
for _, seconds := range []int{1, 45, 1800} {
v := base
v.Duration = seconds
if err := v.validate("sample.exe"); err != nil {
t.Fatalf("%d rejected: %v", seconds, err)
}
}
for _, seconds := range []int{-1, 0, 1801} {
v := base
v.Duration = seconds
if err := v.validate("sample.exe"); err == nil || !strings.Contains(err.Error(), "duration_seconds") {
t.Fatalf("%d accepted or unclear: %v", seconds, err)
}
}
// Whole seconds only: the JSON boundary must not round or coerce.
for _, literal := range []string{`45.5`, `30.0`, `1e2`, `"60"`, `true`, `9223372036854775808`} {
var in struct {
Settings Settings `json:"settings"`
}
w := httptest.NewRecorder()
if decode(w, httptest.NewRequest("POST", "/api/v1/jobs", strings.NewReader(`{"settings":{"duration_seconds":`+literal+`}}`)), &in) || w.Code != 400 {
t.Fatalf("non-integer duration %s decoded as %d", literal, in.Settings.Duration)
}
}
var in struct {
Settings Settings `json:"settings"`
}
if !decode(httptest.NewRecorder(), httptest.NewRequest("POST", "/api/v1/jobs", strings.NewReader(`{"settings":{"duration_seconds":1800}}`)), &in) || in.Settings.Duration != 1800 {
t.Fatal("integer duration was not decoded exactly")
}
}
// Cancellation must not wait for worker capacity: unclaimed queued Attempts end
// immediately, while Attempts held by a live worker keep their lease so the
// fenced finalizer can salvage evidence and stop the owned clone.
func TestCancelFinishesUnclaimedAttemptsAndPreservesClaimedLease(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, "duration-operator", "Regression-only-long-password", "operator")
if err != nil {
t.Fatal(err)
}
upload, first, second := store.NewID(), store.NewID(), store.NewID()
exec := func(sql string, args ...any) {
t.Helper()
if _, err := db.Exec(ctx, sql, args...); err != nil {
t.Fatal(err)
}
}
exec(`INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key) VALUES($1::uuid,$2,'sample.exe',1,$3,$1::uuid::text)`, upload, owner, strings.Repeat("a", 64))
for i, profile := range []string{first, second} {
revision := store.NewID()
exec(`INSERT INTO profiles(id,name,os,architecture,enabled,qualification,state,current_revision_id) VALUES($1,$2,'Windows 11','x64',true,'qualified','published',$3)`, profile, []string{"A profile", "B profile"}[i], revision)
exec(`INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest) VALUES($1,$2,$3,'fingerprint','config')`, revision, profile, "source-"+profile)
}
exec(`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)
exec(`INSERT INTO heartbeats(name,seen_at,ready) VALUES('worker',now(),true)`)
s, err := New(db, Config{Origin: "http://localhost", ArtifactRoot: t.TempDir(), MaxQueuedJobs: 2})
if err != nil {
t.Fatal(err)
}
login := httptest.NewRequest("POST", "/api/v1/auth/login", strings.NewReader(`{"username":"duration-operator","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)
}
var session struct {
CSRF string `json:"csrf_token"`
}
if err = json.Unmarshal(logged.Body.Bytes(), &session); err != nil {
t.Fatal(err)
}
cookie := logged.Result().Cookies()[0]
type attempt struct {
ID, Phase, Outcome, Cleanup string
}
type job struct {
ID, Status string
CancelRequested bool `json:"cancel_requested"`
Settings Settings
Runs []struct {
ProfileID string `json:"profile_id"`
Status string
Attempts []attempt
}
Error struct{ Code string }
}
request := func(method, path, body string, status int) job {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.AddCookie(cookie)
req.Header.Set("Origin", "http://localhost")
req.Header.Set("X-CSRF-Token", session.CSRF)
res := httptest.NewRecorder()
s.ServeHTTP(res, req)
var value job
if err := json.Unmarshal(res.Body.Bytes(), &value); err != nil || res.Code != status {
t.Fatalf("%s %s: %d %s", method, path, res.Code, res.Body)
}
return value
}
submit := func(duration string, status int, profiles ...string) job {
t.Helper()
ids, _ := json.Marshal(profiles)
return request("POST", "/api/v1/jobs", `{"upload_id":"`+upload+`","profile_ids":`+string(ids)+`,"settings":{"internet":"offline","duration_seconds":`+duration+`,"filename":"original","privilege":"user","args_mode":"none","args":[]}}`, status)
}
for duration, code := range map[string]string{"0": "invalid_settings", "1801": "invalid_settings", "-5": "invalid_settings", "45.5": "invalid_request", `"60"`: "invalid_request"} {
if got := submit(duration, 400, first); got.Error.Code != code {
t.Fatalf("duration %s: error %q, want %q", duration, got.Error.Code, code)
}
}
shortest := submit("1", 201, first)
if shortest.Settings.Duration != 1 || shortest.Status != "queued" {
t.Fatalf("minimum duration not stored exactly: %+v", shortest)
}
longest := submit("1800", 201, first, second)
if longest.Settings.Duration != 1800 {
t.Fatalf("maximum duration not stored exactly: %+v", longest)
}
// Queue quota (2) is full until cancellation settles a job.
submit("60", 409, first)
cancelled := request("POST", "/api/v1/jobs/"+shortest.ID+"/cancel", `{}`, 200)
if cancelled.Status != "cancelled" || !cancelled.CancelRequested || cancelled.Runs[0].Status != "cancelled" {
t.Fatalf("unclaimed queued job did not settle on cancel: %+v", cancelled)
}
if a := cancelled.Runs[0].Attempts[0]; a.Phase != "finished" || a.Outcome != "cancelled" || a.Cleanup != "complete" {
t.Fatalf("unclaimed attempt was not finished as cancelled: %+v", a)
}
var events int
if err = db.QueryRow(ctx, `SELECT count(*) FROM events WHERE job_id=$1 AND kind='cancelled'`, shortest.ID).Scan(&events); err != nil || events != 1 {
t.Fatalf("cancel event missing: %d %v", events, err)
}
if again := request("POST", "/api/v1/jobs/"+shortest.ID+"/cancel", `{}`, 200); again.Status != "cancelled" {
t.Fatalf("repeated cancel changed a terminal job: %+v", again)
}
replacement := submit("60", 201, first)
// One Attempt is held by a live worker; the other was claimed by a worker
// whose lease expired before provisioning, so it owns no resources.
held := map[string]string{}
for _, run := range longest.Runs {
held[run.ProfileID] = run.Attempts[0].ID
}
exec(`UPDATE attempts SET phase='provisioning',claimed_at=now(),lease_owner='live-worker',lease_until=now()+interval '1 minute' WHERE id=$1`, held[first])
exec(`UPDATE runs SET status='running' WHERE id=(SELECT run_id FROM attempts WHERE id=$1)`, held[first])
exec(`UPDATE jobs SET status='running' WHERE id=$1`, longest.ID)
exec(`UPDATE attempts SET claimed_at=now(),lease_owner='dead-worker',lease_until=now()-interval '1 second' WHERE id=$1`, held[second])
mixed := request("POST", "/api/v1/jobs/"+longest.ID+"/cancel", `{}`, 200)
if mixed.Status != "running" || !mixed.CancelRequested {
t.Fatalf("job with a live attempt settled before its worker finalizer: %+v", mixed)
}
for _, run := range mixed.Runs {
a := run.Attempts[0]
switch run.ProfileID {
case first:
if a.Phase != "provisioning" || a.Outcome != "pending" || run.Status != "running" {
t.Fatalf("API overrode a live worker attempt: %+v %s", a, run.Status)
}
case second:
if a.Phase != "finished" || a.Outcome != "cancelled" || run.Status != "cancelled" {
t.Fatalf("expired unprovisioned attempt kept waiting: %+v %s", a, run.Status)
}
}
}
var lease string
if err = db.QueryRow(ctx, `SELECT lease_owner FROM attempts WHERE id=$1 AND lease_until>now()`, held[first]).Scan(&lease); err != nil || lease != "live-worker" {
t.Fatalf("cancel revoked the live worker's cleanup lease: %q %v", lease, err)
}
// A queued attempt that somehow owns an allocation is never finished by the API.
exec(`INSERT INTO allocations(id,attempt_id,owner_id,node,vmid,pool,state) SELECT $1,a.id,$2,'test',123456,'test','reserved' FROM attempts a JOIN runs r ON r.id=a.run_id WHERE r.job_id=$3`, store.NewID(), owner, replacement.ID)
guarded := request("POST", "/api/v1/jobs/"+replacement.ID+"/cancel", `{}`, 200)
if guarded.Status != "queued" || guarded.Runs[0].Attempts[0].Phase != "queued" {
t.Fatalf("API finished an attempt that owns an allocation: %+v", guarded)
}
}
+1 -1
View File
@@ -58,7 +58,7 @@ func TestJobSummariesIncludeAssignedProfile(t *testing.T) {
if _, err = db.Exec(ctx, `INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest) VALUES($1,$2,'win11','fingerprint','config')`, revision, profile); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO jobs(id,owner_id,upload_id,execution_filename,status,settings) VALUES($1,$2,$3,'panel-bat-smoke.bat','completed','{"internet":"offline"}')`, job, owner, upload); err != nil {
if _, err = db.Exec(ctx, `INSERT INTO jobs(id,owner_id,upload_id,execution_filename,status,settings) VALUES($1,$2,$3,'panel-bat-smoke.bat','completed','{"internet":"offline","duration_seconds":30}')`, job, owner, upload); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO runs(id,job_id,profile_id,revision_id,profile_name,status) SELECT $1,$2,id,$4,name,'completed' FROM profiles WHERE id=$3`, run, job, profile, revision); err != nil {
+68 -9
View File
@@ -1,6 +1,7 @@
package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
@@ -16,6 +17,7 @@ import (
"strings"
"github.com/jackc/pgx/v5"
"otche/internal/duration"
"otche/internal/grub"
"otche/internal/netpolicy"
"otche/internal/pve"
@@ -66,14 +68,8 @@ func (v *Settings) validate(filename string) error {
return err
}
v.AllowedCIDRs = allowed
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 err = duration.Validate(v.Duration); err != nil {
return err
}
if v.Filename != "original" && v.Filename != "random" {
return errors.New("filename must be original/random")
@@ -483,19 +479,78 @@ func (s *Server) jobs(w http.ResponseWriter, r *http.Request) {
}
jsonResponse(w, 200, map[string]any{"items": v, "total": total, "page": page, "page_size": size, "next_page": next})
}
// cancelQueuedAttemptsSQL finishes Attempts no live worker generation holds.
// A queued phase precedes provisioning, so they own no VM, disk, extractor or
// guest command; remaining job media is reconciled by the worker after finish.
// Claimed Attempts keep their lease and stop through the worker's fenced
// finalizer, which salvages partial evidence before stopping the owned clone.
const cancelQueuedAttemptsSQL = `UPDATE attempts a SET phase='finished',outcome='cancelled',telemetry='unavailable',cleanup='complete',error='Cancelled before execution; no VM was provisioned',finished_at=now(),lease_owner=NULL,lease_until=NULL
FROM runs r WHERE r.id=a.run_id AND r.job_id=$1 AND a.phase='queued' AND (a.lease_until IS NULL OR a.lease_until<now())
AND NOT EXISTS(SELECT 1 FROM allocations l WHERE l.attempt_id=a.id) AND NOT EXISTS(SELECT 1 FROM extractor_allocations x WHERE x.attempt_id=a.id)
RETURNING a.id::text,a.run_id::text`
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)
ctx := r.Context()
tx, e := s.db.Begin(ctx)
if e != nil {
s.dbError(w, e)
return
}
defer tx.Rollback(ctx)
var active bool
e = tx.QueryRow(ctx, `UPDATE jobs SET cancel_requested=true,updated_at=now() WHERE id=$1 AND status IN('queued','running') RETURNING true`, id).Scan(&active)
if e != nil && !errors.Is(e, pgx.ErrNoRows) {
s.dbError(w, e)
return
}
if active {
if e = cancelQueued(ctx, tx, id); e != nil {
s.dbError(w, e)
return
}
}
if e = tx.Commit(ctx); e != nil {
s.dbError(w, e)
return
}
s.respondJob(w, r, id, 200)
}
// cancelQueued runs inside the cancel transaction so a cancelled queued Job never
// waits for worker capacity or readiness and stops counting against queue quota.
func cancelQueued(ctx context.Context, tx pgx.Tx, job string) error {
rows, e := tx.Query(ctx, cancelQueuedAttemptsSQL, job)
if e != nil {
return e
}
var attempts, runs []string
for rows.Next() {
var attempt, run string
if e = rows.Scan(&attempt, &run); e != nil {
rows.Close()
return e
}
attempts, runs = append(attempts, attempt), append(runs, run)
}
rows.Close()
if e = rows.Err(); e != nil || len(attempts) == 0 {
return e
}
if _, e = tx.Exec(ctx, `INSERT INTO events(job_id,attempt_id,kind,message) SELECT $1,unnest($2::uuid[]),'cancelled','Cancelled before a worker claimed it; no VM was provisioned'`, job, attempts); e != nil {
return e
}
if _, e = tx.Exec(ctx, `UPDATE runs SET status='cancelled' WHERE id=ANY($1::uuid[]) AND NOT EXISTS(SELECT 1 FROM attempts a WHERE a.run_id=runs.id AND a.phase<>'finished')`, runs); e != nil {
return e
}
_, e = tx.Exec(ctx, `UPDATE jobs SET status='cancelled',updated_at=now() WHERE id=$1 AND NOT EXISTS(SELECT 1 FROM runs WHERE job_id=$1 AND status IN('queued','running'))`, job)
return e
}
func (s *Server) retryJob(w http.ResponseWriter, r *http.Request) {
id, e := s.ownJob(r)
if e != nil {
@@ -534,6 +589,10 @@ func (s *Server) retryJob(w http.ResponseWriter, r *http.Request) {
fail(w, 409, "invalid_settings", "Stored network settings cannot be retried; submit a new job: "+e.Error())
return
}
if e = duration.Validate(settings.Duration); e != nil {
fail(w, 409, "invalid_settings", "Stored duration cannot be retried; submit a new job: "+e.Error())
return
}
if e = s.admit(r, tx, owner, settings.Internet); e != nil {
fail(w, 409, "admission_closed", e.Error())
return
+9 -27
View File
@@ -790,7 +790,7 @@
}
},
"400": {
"description": "invalid_request или invalid_settings. JSON ≤64 KiB, сериализованные настройки ≤38 KiB.",
"description": "invalid_request (включая нецелый duration_seconds) или invalid_settings (включая duration_seconds вне 1..1800). JSON ≤64 KiB, сериализованные настройки ≤38 KiB.",
"content": {
"application/json": {
"schema": {
@@ -1074,7 +1074,7 @@
"Задания"
],
"summary": "Запросить отмену задания",
"description": "Для queued/running выставляет cancel_requested=true, остановка асинхронна. Для terminal job не меняет состояние. Возвращает Job либо ограниченное подтверждение в зависимости от jobs:read, не гарантию завершённого cleanup.",
"description": "Для queued/running выставляет cancel_requested=true. В той же транзакции Attempts в фазе queued без живого lease worker и без allocation сразу завершаются outcome=cancelled, telemetry=unavailable, cleanup=complete; их Runs становятся cancelled, а Job — cancelled, если не осталось queued/running Runs (квота очереди освобождается без ожидания worker). Захваченные worker Attempts прерываются асинхронно (~5 с): до allocation очищается только media (cleanup=complete); с allocation сохраняется частичное наблюдение, видео и журнал, затем собственный клон жёстко останавливается через PVE, cleanup=evidence_held (явный admin release) или failed. Для terminal job не меняет состояние. Возвращает Job либо ограниченное подтверждение в зависимости от jobs:read, не гарантию завершённого cleanup.",
"security": [
{
"BearerAuth": []
@@ -1227,7 +1227,7 @@
}
},
"409": {
"description": "job_active: Job queued/running либо есть любой unfinished Attempt; invalid_settings: legacy/недействительная сеть; admission_closed; revision_unavailable: исходная ревизия больше не опубликована/не допущена.",
"description": "job_active: Job queued/running либо есть любой unfinished Attempt; invalid_settings: legacy/недействительная сеть или сохранённый duration_seconds вне 1..1800; admission_closed; revision_unavailable: исходная ревизия больше не опубликована/не допущена.",
"content": {
"application/json": {
"schema": {
@@ -2328,18 +2328,9 @@
},
"duration_seconds": {
"type": "integer",
"enum": [
30,
60,
90,
120,
180,
300,
600,
900,
1200
],
"description": "Окно наблюдения; не общее время provisioning/очереди/сбора."
"minimum": 1,
"maximum": 1800,
"description": "Окно наблюдения в целых секундах 1..1800; не общее время provisioning/очереди/сбора. Дробные/строковые/логические значения не приводятся: 400 invalid_request; целые вне диапазона: 400 invalid_settings."
},
"filename": {
"type": "string",
@@ -2469,18 +2460,9 @@
},
"duration_seconds": {
"type": "integer",
"enum": [
30,
60,
90,
120,
180,
300,
600,
900,
1200
],
"description": "Окно наблюдения; не общее время provisioning/очереди/сбора."
"minimum": 1,
"maximum": 1800,
"description": "Неизменяемое окно наблюдения в целых секундах 1..1800; не общее время provisioning/очереди/сбора."
},
"filename": {
"type": "string",