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

+1 -1
View File
@@ -28,7 +28,7 @@ The command modes are `api`, `worker`, `watchdog`, `healthcheck`, `migrate`, `us
go test ./...
```
Database-backed tests require a **dedicated disposable PostgreSQL database** via `OTCHE_TEST_DATABASE_URL`, never a production DSN. Recorder tests use FFmpeg. Inspect test prerequisites before interpreting skips as success. Windows helper tests are `windows/Test-OtcheArguments.ps1` and `windows/Test-OtcheGrub.ps1`; run only under the existing approved execution policy. They do not qualify a source image. No automatic source VM operations are part of a normal build or test.
Database-backed tests require a **dedicated disposable PostgreSQL database** via `OTCHE_TEST_DATABASE_URL`, never a production DSN. Recorder tests use FFmpeg. Inspect test prerequisites before interpreting skips as success. Windows helper tests are `windows/Test-OtcheArguments.ps1`, `windows/Test-OtcheGrub.ps1` and `windows/Test-OtcheDuration.ps1`; run only under the existing approved execution policy. They do not qualify a source image. No automatic source VM operations are part of a normal build or test.
## Execution prerequisites and safety
+4 -2
View File
@@ -106,7 +106,7 @@ curl --fail-with-body --silent --show-error \
## Длительность, online и Grub
`duration_seconds` — ровно одно из 30, 60, 90, 120, 180, 300, 600, 900, 1200. Это окно наблюдения, **не** SLA всего задания: очередь, provisioning, подготовка рабочего стола, сбор и cleanup добавляют время. Для преждевременно заблокированного образца фактические start/PID/duration могут быть null.
`duration_seconds` — целое число секунд от 1 до 1800 включительно (JSON integer). Дробные (`45.5`, `30.0`), экспоненциальные (`1e2`), строковые и логические значения не округляются и не приводятся: HTTP 400 `invalid_request`; целые вне 1..1800 (и отсутствующее поле) — HTTP 400 `invalid_settings`. Значение неизменяемо после создания и повторно проверяется при retry (HTTP 409 `invalid_settings`) и worker перед выделением VM. Это окно наблюдения, **не** SLA всего задания: очередь, provisioning, подготовка рабочего стола, сбор и cleanup добавляют время. Для преждевременно заблокированного образца фактические start/PID/duration могут быть null. Требует подписанный Windows runner 1.1.0 на опубликованной ревизии источника.
Начинайте с offline (без NIC). Для online нужен отдельный актуальный proof владельца, online_available профиля и явный `allowed_cidrs`. Политика неизменяема; IPv6/имена/порты/диапазоны не принимаются. `0.0.0.0/0` означает публичный IPv4, не всю сеть: защищённая инфраструктура всегда закрыта. Grub собирает только явно указанные обычные локальные Windows-файлы выбранным user/admin token после наблюдения; не произвольное чтение SYSTEM/host. Снимки best effort, не атомарные: `changed`, `missing`, `access_denied` и частичный архив — честные результаты, не Defender findings. Подробные ограничения ниже остаются частью контракта.
@@ -114,7 +114,7 @@ curl --fail-with-body --silent --show-error \
`POST /uploads` body raw bytes (`application/octet-stream`), filename in `X-Filename` (encodeURIComponent). Response 201 `{id,filename,size,sha256,created_at}`. Original bytes immutable. No multipart. `GET /uploads/{id}/content` authorized attachment.
`POST /jobs` `{upload_id,profile_ids:[UUID],settings:{internet:"offline"|"online",allowed_cidrs?:string[],duration_seconds:30|60|90|120|180|300|600|900|1200,filename:"original"|"random",privilege:"user"|"admin",args_mode:"none"|"custom",args:string[],set_zoneid:boolean,dll_mode:"regsvr32"|"rundll32",dll_export:string,architecture:"auto"|"x86"|"x64",wsh_host:"cscript"|"wscript",msi_ui:"full"|"quiet"|"passive"}}` -> 201 Job. Arguments are an explicit JSON string array; only `{sample.path}` and `{sample.name}` expand in guest after path selection. DLL export mandatory with rundll32, never guessed. MSI logs always collected. Defender only; each selected profile creates exactly one Run. Immutable settings, random basename selected once per Job preserving extension.
`POST /jobs` `{upload_id,profile_ids:[UUID],settings:{internet:"offline"|"online",allowed_cidrs?:string[],duration_seconds:integer 1..1800,filename:"original"|"random",privilege:"user"|"admin",args_mode:"none"|"custom",args:string[],set_zoneid:boolean,dll_mode:"regsvr32"|"rundll32",dll_export:string,architecture:"auto"|"x86"|"x64",wsh_host:"cscript"|"wscript",msi_ui:"full"|"quiet"|"passive"}}` -> 201 Job. Arguments are an explicit JSON string array; only `{sample.path}` and `{sample.name}` expand in guest after path selection. DLL export mandatory with rundll32, never guessed. MSI logs always collected. Defender only; each selected profile creates exactly one Run. Immutable settings, random basename selected once per Job preserving extension.
**Strict per-job IPv4 destinations:** `online` requires `allowed_cidrs` with 1–128 nonblank IPv4 addresses/CIDRs and at most 8192 aggregate UTF-8 bytes, measured before trimming/deduplication. `offline` requires an absent or empty array; even a blank array entry is invalid. Surrounding whitespace is trimmed; bare IPv4 becomes `/32`; host bits are masked; exact canonical duplicates are removed in first-occurrence order. Overlapping entries are not collapsed. Names, address ranges, ports, IPv6 (including IPv4-mapped IPv6), leading-zero octets/prefix lengths and malformed entries are rejected with HTTP 400 `invalid_settings`. The returned immutable settings contain the normalized list.
@@ -130,6 +130,8 @@ Readable live logs are captured as bounded **best-effort open-length snapshots**
`GET /jobs?page=1&page_size=25&q=&status=` -> `{items:Job[],total,page,page_size,next_page:null|number}`; `GET /jobs/{id}` Job with runs; `POST /jobs/{id}/cancel` -> Job; `POST /jobs/{id}/retry` -> same Job with a new Attempt for every Run (including previously successful Runs), preserving every prior Attempt and original immutable settings/revisions, admission rechecked. Retry returns HTTP 409 `job_active` if the Job is queued/running **or any of its Attempts is unfinished**, even if the stored Job status is terminal. Job `{id,owner_id,upload_id,filename,execution_filename,sha256,size,settings,status,created_at,updated_at,cancel_requested,runs:Run[]}`. Status `queued|running|completed|cancelled|failed`.
**Cancel** (`POST /jobs/{id}/cancel`, no body fields) sets `cancel_requested=true` for a `queued`/`running` Job; on a terminal Job it is a no-op returning 200. In the same transaction every Attempt that no live worker holds and that is still in phase `queued` without any allocation is finished immediately as `outcome:"cancelled"`, `telemetry:"unavailable"`, `cleanup:"complete"` (no VM was provisioned); its Run becomes `cancelled`, and the Job becomes `cancelled` as soon as no Run is queued/running, releasing queue quota without waiting for worker capacity. Attempts already claimed by a worker keep their lease: within about 5 seconds the worker interrupts the current stage (media, clone, readiness, delivery, observation, collection) and ends the Attempt `outcome:"cancelled"`. Before a clone allocation exists only job media is cleaned (`cleanup:"complete"`). With an allocation, the finalizer salvages partial guest status/telemetry/Defender evidence, finalizes the video and observation journal, then hard-stops the owned clone through PVE (the runner is not asked to exit gracefully); cleanup is `evidence_held` (stopped clone retained for explicit administrative release) or `failed` if the stop could not be confirmed. The independent watchdog stops owned clones whose worker lease expires. An Attempt that finished before the worker observed the request keeps its real outcome. Job status becomes `cancelled` only after the last Run settles. Retry clears `cancel_requested`.
Для трёх mutation-ответов create/cancel/retry полный `Job` выше относится только к cookie-сессии или API-ключу с `jobs:read`; ключ только с `jobs:write` получает ограниченный `JobAcknowledgement` из раздела прав. GET-список возвращает `JobSummary[]` с `RunSummary[]`, без вложенных Attempts и queue_ahead.
Retry also revalidates the stored immutable network policy and current profile online availability without changing either the destination list or source revision. Historical online jobs without `allowed_cidrs` (and any other now-invalid policy) return HTTP 409 `invalid_settings`; submit a new job with explicit destinations. Missing historical destinations mean unavailable/legacy information, not unrestricted access.
+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",
+19
View File
@@ -0,0 +1,19 @@
// Package duration is the observation-window contract shared by job admission,
// the worker and the signed Windows runner (Confirm-OtcheManifest).
package duration
import "fmt"
const (
MinSeconds = 1
MaxSeconds = 1800
)
// Validate accepts the immutable duration_seconds setting. JSON decoding into
// an int already rejects fractions, strings and exponent notation.
func Validate(seconds int) error {
if seconds < MinSeconds || seconds > MaxSeconds {
return fmt.Errorf("duration_seconds must be an integer from %d to %d", MinSeconds, MaxSeconds)
}
return nil
}
+16
View File
@@ -0,0 +1,16 @@
package duration
import "testing"
func TestValidateBoundaries(t *testing.T) {
for _, seconds := range []int{1, 2, 30, 45, 1200, 1799, 1800} {
if err := Validate(seconds); err != nil {
t.Fatalf("%d rejected: %v", seconds, err)
}
}
for _, seconds := range []int{-1800, -1, 0, 1801, 3600} {
if Validate(seconds) == nil {
t.Fatalf("%d accepted", seconds)
}
}
}
+15 -2
View File
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"os"
"otche/internal/duration"
"otche/internal/grub"
"otche/internal/netpolicy"
"otche/internal/pve"
@@ -203,8 +204,8 @@ func (e *engine) execute(ctx context.Context, a attempt) (outcome, findings, tel
return outcome, findings, telemetry, cleanup, nil, err
}
}
if opts.Duration < 30 || opts.Duration > 1200 || (opts.Privilege != "user" && opts.Privilege != "admin") {
return outcome, findings, telemetry, cleanup, nil, errors.New("invalid immutable run limits")
if err = runLimits(opts); err != nil {
return outcome, findings, telemetry, cleanup, nil, err
}
if err = grub.Validate(opts.GrubPaths); err != nil {
return outcome, findings, telemetry, cleanup, nil, err
@@ -637,6 +638,18 @@ func (e *engine) execute(ctx context.Context, a attempt) (outcome, findings, tel
collected = r.Telemetry == "complete"
return outcome, findings, telemetry, cleanup, report, nil
}
// runLimits re-checks immutable settings at execution time; a stored row that
// bypassed admission never reaches a clone or the guest runner.
func runLimits(opts settings) error {
if err := duration.Validate(opts.Duration); err != nil {
return fmt.Errorf("invalid immutable run limits: %w", err)
}
if opts.Privilege != "user" && opts.Privilege != "admin" {
return errors.New("invalid immutable run limits: privilege must be user/admin")
}
return nil
}
func validResult(a attempt, r guestResult) bool {
return r.CommandID == a.CommandID && r.AttemptID == a.ID && r.JobID == a.JobID && strings.Contains("|executed|blocked_before_execution|incompatible|policy_blocked|delivery_error|interrupted|cancelled|error|", "|"+r.Outcome+"|") && strings.Contains("|unknown|detected|not_observed|", "|"+r.Findings+"|") && strings.Contains("|complete|partial|unavailable|", "|"+r.Telemetry+"|") && json.Valid(r.Report)
}
+92
View File
@@ -121,3 +121,95 @@ func TestLeaseGenerationFencesExpiredClaimAndAllowsCancelledCleanup(t *testing.T
t.Fatalf("stale worker overwrote phase: %s", phase)
}
}
// Cancelling a running Job must interrupt execution promptly through the lease
// supervisor, yet keep renewing the lease the finalizer needs for salvage/stop.
func TestCancelInterruptsExecutionAndKeepsCleanupLease(t *testing.T) {
ctx, db := workerTestDB(t)
owner, profile, revision, upload, job, run, aid := newID(), newID(), newID(), newID(), newID(), newID(), newID()
for _, s := range []struct {
sql string
args []any
}{
{"INSERT INTO users(id,username,password_hash,role)VALUES($1,'cancel-owner','unused','operator')", []any{owner}},
{"INSERT INTO profiles(id,name,os,architecture)VALUES($1,'cancel-profile','Windows','x64')", []any{profile}},
{"INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest)VALUES($1,$2,'source','fp','cfg')", []any{revision, profile}},
{"INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key)VALUES($1,$2,'safe.exe',1,'hash','test-upload')", []any{upload, owner}},
{`INSERT INTO jobs(id,owner_id,upload_id,execution_filename,settings,status)VALUES($1,$2,$3,'safe.exe','{"duration_seconds":1800}','running')`, []any{job, owner, upload}},
{"INSERT INTO runs(id,job_id,profile_id,revision_id,profile_name,status)VALUES($1,$2,$3,$4,'Cancel fixture','running')", []any{run, job, profile, revision}},
{"INSERT INTO attempts(id,run_id,command_id)VALUES($1,$2,$3)", []any{aid, run, newID()}},
} {
if _, err := db.Exec(ctx, s.sql, s.args...); err != nil {
t.Fatal(err)
}
}
e := engine{db: db, cfg: Config{Concurrent: 1, Owners: map[string]Binding{owner: {MaxActiveAttempts: 1}}}, id: "cancel-worker"}
claimed, err := e.claim(ctx)
if err != nil {
t.Fatal(err)
}
e.id = claimed.Lease
if err = e.phase(ctx, claimed, "running"); err != nil {
t.Fatal(err)
}
execution, cancel := context.WithCancel(ctx)
defer cancel()
done := make(chan struct{})
stopped := make(chan struct{})
go func() {
defer close(stopped)
e.superviseLease(claimed, 20*time.Millisecond, cancel, done)
}()
select {
case <-execution.Done():
t.Fatal("supervisor cancelled an uncancelled running attempt")
case <-time.After(200 * time.Millisecond):
}
if _, err = db.Exec(ctx, "UPDATE jobs SET cancel_requested=true WHERE id=$1", job); err != nil {
t.Fatal(err)
}
select {
case <-execution.Done():
case <-time.After(5 * time.Second):
t.Fatal("cancel_requested did not interrupt running execution")
}
if err = e.fence(ctx, claimed); err == nil || err.Error() != "cancelled" {
t.Fatalf("finalizer would not classify the interruption as cancelled: %v", err)
}
var before time.Time
if err = db.QueryRow(ctx, "SELECT lease_until FROM attempts WHERE id=$1", aid).Scan(&before); err != nil {
t.Fatal(err)
}
deadline := time.Now().Add(5 * time.Second)
for {
var after time.Time
if err = db.QueryRow(ctx, "SELECT lease_until FROM attempts WHERE id=$1", aid).Scan(&after); err != nil {
t.Fatal(err)
}
if after.After(before) {
break
}
if time.Now().After(deadline) {
t.Fatal("cancelled attempt stopped renewing the cleanup lease")
}
time.Sleep(20 * time.Millisecond)
}
if err = e.leaseAlive(ctx, claimed); err != nil {
t.Fatalf("finalizer lost authority to salvage and stop the owned clone: %v", err)
}
close(done)
<-stopped
}
func TestRunLimitsDurationBoundaries(t *testing.T) {
for _, seconds := range []int{1, 45, 1800} {
if err := runLimits(settings{Duration: seconds, Privilege: "admin"}); err != nil {
t.Fatalf("%d rejected: %v", seconds, err)
}
}
for _, opts := range []settings{{Duration: 0, Privilege: "user"}, {Duration: 1801, Privilege: "user"}, {Duration: -1, Privilege: "user"}, {Duration: 60, Privilege: "system"}} {
if runLimits(opts) == nil {
t.Fatalf("invalid immutable limits accepted: %+v", opts)
}
}
}
+30 -22
View File
@@ -213,33 +213,41 @@ func (e *engine) phase(ctx context.Context, a attempt, phase string) error {
_, err = e.db.Exec(ctx, "INSERT INTO events(job_id,attempt_id,kind,message) VALUES($1,$2,'phase',$3)", a.JobID, a.ID, phase)
return err
}
// leaseRenewInterval bounds cancellation latency for a running Attempt.
const leaseRenewInterval = 5 * time.Second
// superviseLease renews the claim and cancels execution as soon as the Job is
// cancelled or the lease is lost. Cancellation keeps renewing: the fenced
// finalizer needs the live lease to salvage evidence and stop the owned clone.
func (e *engine) superviseLease(a attempt, interval time.Duration, cancel context.CancelFunc, done <-chan struct{}) {
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-done:
return
case <-t.C:
renew, finish := context.WithTimeout(context.Background(), 5*time.Second)
tag, err := e.db.Exec(renew, "UPDATE attempts SET lease_until=now()+interval '30 seconds' WHERE id=$1 AND lease_owner=$2 AND lease_until>now()", a.ID, e.id)
if err != nil || tag.RowsAffected() != 1 {
finish()
cancel()
return
}
if err = e.fence(renew, a); err != nil {
cancel()
}
finish()
}
}
}
func (e *engine) runClaim(parent context.Context, a attempt) {
ctx, cancel := context.WithCancel(parent)
defer cancel()
done := make(chan struct{})
defer close(done)
go func() {
t := time.NewTicker(5 * time.Second)
defer t.Stop()
for {
select {
case <-done:
return
case <-t.C:
renew, finish := context.WithTimeout(context.Background(), 5*time.Second)
tag, err := e.db.Exec(renew, "UPDATE attempts SET lease_until=now()+interval '30 seconds' WHERE id=$1 AND lease_owner=$2 AND lease_until>now()", a.ID, e.id)
if err != nil || tag.RowsAffected() != 1 {
finish()
cancel()
return
}
if err = e.fence(renew, a); err != nil {
cancel()
}
finish()
}
}
}()
go e.superviseLease(a, leaseRenewInterval, cancel, done)
_, _ = e.db.Exec(ctx, "UPDATE jobs SET status='running',updated_at=now() WHERE id=$1", a.JobID)
_, _ = e.db.Exec(ctx, "UPDATE runs SET status='running' WHERE id=$1", a.RunID)
outcome, findings, telemetry, cleanup, report, err := e.execute(ctx, a)
+16 -8
View File
@@ -43,12 +43,14 @@ if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') {throw 'Appr
if ((Get-ExecutionPolicy) -eq 'Restricted') {throw 'Restricted blocks installer and runner files; obtain approved organizational script policy first'}
$root='C:\ProgramData\Otche'
$files=@('Otche.Common.psm1','Invoke-Otche.ps1','Invoke-OtcheDispatch.ps1','Start-OtcheCommand.ps1','Collect-Otche.ps1','Test-OtcheReady.ps1')
# Runner/collector limits cover the 1800-second maximum observation window plus
# readiness (90s), Grub export (150s), collector tail (240s) and final handoff.
function Get-SourceTaskDefinitions([string]$AccountName) {
foreach ($level in @('user','admin')) {
@{name=('Otche-'+$level);user=$AccountName;logon='Interactive';run_level=$(if ($level -eq 'admin') {'Highest'} else {'Limited'});arguments="-NoProfile -NonInteractive -File `"$root\runner\Invoke-OtcheDispatch.ps1`" -Privilege $level";seconds=1800}
@{name=('Otche-'+$level);user=$AccountName;logon='Interactive';run_level=$(if ($level -eq 'admin') {'Highest'} else {'Limited'});arguments="-NoProfile -NonInteractive -File `"$root\runner\Invoke-OtcheDispatch.ps1`" -Privilege $level";seconds=3600}
}
@{name='Otche-DesktopReady';user=$AccountName;logon='Interactive';run_level='Limited';arguments="-NoProfile -NonInteractive -WindowStyle Hidden -File `"$root\runner\Test-OtcheReady.ps1`" -Privilege user -DesktopProbe";seconds=90}
@{name='Otche-Collector';user='SYSTEM';logon='ServiceAccount';run_level='Highest';arguments="-NoProfile -NonInteractive -File `"$root\runner\Collect-Otche.ps1`"";seconds=1800}
@{name='Otche-Collector';user='SYSTEM';logon='ServiceAccount';run_level='Highest';arguments="-NoProfile -NonInteractive -File `"$root\runner\Collect-Otche.ps1`"";seconds=3600}
}
function Get-SourceSid([string]$Name) {
if ($Name -match '^S-1-') {return ([Security.Principal.SecurityIdentifier]::new($Name)).Value}
@@ -102,7 +104,9 @@ function Test-SourceInstall([switch]$ForUpdate) {
if (@($task.Actions).Count -ne 1 -or $task.Actions[0].Execute -ine "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -or $task.Actions[0].Arguments -cne $definition.arguments -or $task.Actions[0].WorkingDirectory -ine "$root\runner") {throw 'Task action differs'}
if (@($task.Triggers|Where-Object {$null -ne $_}).Count -ne 0) {throw 'On-demand task has unexpected triggers'}
$taskSeconds=[Xml.XmlConvert]::ToTimeSpan([string]$task.Settings.ExecutionTimeLimit).TotalSeconds
if ($taskSeconds -ne $definition.seconds -and !($ForUpdate -and $definition.name -eq 'Otche-DesktopReady' -and $taskSeconds -eq 15)) {throw 'Task execution deadline differs'}
# -UpdateRunner migrates only the previously shipped limits; anything else needs review.
$previous=($definition.name -eq 'Otche-DesktopReady' -and $taskSeconds -eq 15) -or ($definition.name -in @('Otche-user','Otche-admin','Otche-Collector') -and $taskSeconds -eq 1800)
if ($taskSeconds -ne $definition.seconds -and !($ForUpdate -and $previous)) {throw 'Task execution deadline differs'}
} catch {$problems.Add('Task '+$definition.name+': '+$_.Exception.Message)}
}
try {
@@ -182,10 +186,14 @@ if ($Verify -or $UpdateRunner) {
$check=Test-SourceInstall -ForUpdate:$UpdateRunner
if ($Verify -or !$check.ok) {$check|ConvertTo-Json -Depth 5 -Compress;if (!$check.ok) {exit 1};exit 0}
Update-SourceRunnerFiles $PSScriptRoot "$root\runner" $files
$desktopTask=Get-ScheduledTask -TaskName 'Otche-DesktopReady' -TaskPath '\'
$desktopSettings=$desktopTask.Settings
$desktopSettings.ExecutionTimeLimit='PT90S'
Set-ScheduledTask -TaskName 'Otche-DesktopReady' -TaskPath '\' -Settings $desktopSettings | Out-Null
# Change only each task's execution limit through its existing settings object;
# principals, stored logon and actions are left untouched.
foreach ($definition in @(Get-SourceTaskDefinitions '')) {
$task=Get-ScheduledTask -TaskName $definition.name -TaskPath '\'
$taskSettings=$task.Settings
$taskSettings.ExecutionTimeLimit=[Xml.XmlConvert]::ToString([TimeSpan]::FromSeconds($definition.seconds))
Set-ScheduledTask -TaskName $definition.name -TaskPath '\' -Settings $taskSettings | Out-Null
}
Import-Module "$root\runner\Otche.Common.psm1" -Force
Get-OtcheBaseline|ConvertTo-Json -Depth 18 -Compress
exit 0
@@ -270,7 +278,7 @@ try {
[IO.File]::SetAttributes($destination,([IO.File]::GetAttributes($destination) -band (-bnot [IO.FileAttributes]::ReadOnly)))
}
Import-Module "$root\runner\Otche.Common.psm1" -Force
Write-OtcheJson "$root\source.json" @{account_sid=$account.SID.Value;account="$env:COMPUTERNAME\$user";installed_at=(Get-OtcheUtc);runner_version='1.0.0';autologon=[bool]$EnableAutoLogon} -CreateNew
Write-OtcheJson "$root\source.json" @{account_sid=$account.SID.Value;account="$env:COMPUTERNAME\$user";installed_at=(Get-OtcheUtc);runner_version='1.1.0';autologon=[bool]$EnableAutoLogon} -CreateNew
$exe="$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe"
foreach ($definition in @(Get-SourceTaskDefinitions "$env:COMPUTERNAME\$user")) {
$settings=New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::FromSeconds($definition.seconds)) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
+4 -2
View File
@@ -1,5 +1,5 @@
Set-StrictMode -Version 2.0
$script:OtcheVersion = '1.0.0'
$script:OtcheVersion = '1.1.0'
$script:OtcheRoot = 'C:\ProgramData\Otche'
function Read-OtcheJson([string]$Path, [int]$MaxBytes = 1048576) {
@@ -70,7 +70,9 @@ function Confirm-OtcheManifest($Manifest) {
foreach ($rule in @(@('privilege','user','admin'),@('architecture','auto','x86','x64'),@('wsh_host','cscript','wscript'),@('msi_ui','full','quiet','passive'),@('internet','offline','online'),@('args_mode','none','custom'),@('filename','original','random'),@('dll_mode','regsvr32','rundll32'))) {
if ([string](Get-OtcheProperty $s $rule[0]) -notin $rule[1..($rule.Length-1)]) { throw ('Invalid setting ' + $rule[0]) }
}
if ($s.duration_seconds -notin @(30,60,90,120,180,300,600,900,1200)) { throw 'Invalid duration' }
# Whole seconds 1..1800, matching backend internal/duration. Fractions, strings and booleans are rejected, never coerced.
$duration = Get-OtcheProperty $s 'duration_seconds'
if (($duration -isnot [int] -and $duration -isnot [long]) -or $duration -lt 1 -or $duration -gt 1800) { throw 'Invalid duration' }
if ($s.set_zoneid -isnot [bool]) { throw 'set_zoneid must be boolean' }
if ($null -eq $s.args -or $s.args -isnot [array] -or $s.args.Count -gt 64) { throw 'args must be an explicit bounded array' }
foreach ($arg in $s.args) { if ($arg -isnot [string] -or $arg.Length -gt 4096 -or $arg.Contains([string][char]0)) { throw 'Invalid argument' } }
+11 -3
View File
@@ -55,7 +55,10 @@ Prerequisites and trust
only if it is a regular, non-reparse file whose hash matches the signed bundle;
unrecognized staging files are left untouched for inspection. Cleanup failures
are warnings when another failure is already pending, preserving its real cause.
No task, account, registry, autologon secret or directory ACL is changed. The JSON
Only task execution limits are set to the shipped values through each task's
existing settings object (Otche-user/admin/Collector 3600s for the 1800-second
maximum window, DesktopReady 90s); principals, stored logon and actions stay.
No account, registry, autologon secret or directory ACL is changed. The JSON
output is the NEW Get-OtcheBaseline, not qualification. Do not dispatch during
maintenance. Replacement is atomic per file, not a six-file transaction: if an
I/O failure interrupts replacement, correct the failure and rerun -UpdateRunner,
@@ -94,7 +97,8 @@ and arbitrary WWAHost applications are not treated as unfinished setup.
This bounded startup budget includes normal Authenticode/native-helper initialization
when an allowlist blocks certificate-network lookups; signature checks are not disabled.
The worker waits for the accepted QGA PID to exit and never overlaps readiness scripts.
Approved -UpdateRunner maintenance migrates the previous 15-second task budget.
Approved -UpdateRunner maintenance migrates the previous 15-second task budget
and the previous 1800-second runner/collector limits; any other limit is drift.
Deadline timestamps are parsed with invariant RoundtripKind and normalized to UTC;
the guest may use any Windows time zone (UTC is no longer a prerequisite). The clock
still must be correct. Probe responses use results\desktop-probe-<nonce>.json; the
@@ -112,7 +116,8 @@ Manifest (JSON data, max 1 MiB): command_id, attempt_id, job_id (canonical UUIDs
iso_label OT<first 14 uppercase hexadecimal job UUID characters> (16 ASCII characters, identical ISO9660/Joliet labels), sha256 (lowercase),
filename (execution_filename selected ONCE by worker per Job), settings from API.
Settings require architecture auto|x86|x64, wsh_host cscript|wscript, msi_ui
full|quiet|passive, plus existing fields. args is a JSON string array; only
full|quiet|passive, duration_seconds a JSON integer 1..1800 (runner 1.1.0; never
coerced from fractions/strings), plus existing fields. args is a JSON string array; only
{sample.path}/{sample.name} are expanded. ISO root job.json contains job_id,
sha256,filename,iso_label; payload is sample/<filename>, unchanged original bytes.
Optional root qualification='benign'|'eicar'. EICAR is delivery-only, never started.
@@ -257,3 +262,6 @@ Grub optional file snapshots
- Test-OtcheGrub.ps1 is a harmless local helper regression (not source qualification):
actual live writer/read sharing, identical basenames, empty/missing/denied files,
literal percent/braces, byte limits and device/network/traversal/reparse rejection.
- Test-OtcheDuration.ps1 is a harmless local helper regression (not source
qualification): Confirm-OtcheManifest accepts integer duration_seconds 1..1800 only
and the installer's runner/collector task limits cover the 1800-second window.
+42
View File
@@ -0,0 +1,42 @@
<#
.SYNOPSIS
Harmless Windows PowerShell 5.1 observation-window boundary regression.
.DESCRIPTION
Parses manifests exactly like Read-OtcheJson and verifies Confirm-OtcheManifest
accepts whole-second durations 1..1800 only. Reads Install-OtcheSource.ps1 without
running it and verifies runner/collector task limits cover the maximum window.
No task, account, policy, registry, Defender or source configuration changes.
Run under the existing approved script policy; never add an execution-policy switch.
#>
#requires -Version 5.1
[CmdletBinding()]
param()
Set-StrictMode -Version 2
$ErrorActionPreference='Stop'
Import-Module "$PSScriptRoot\Otche.Common.psm1" -Force
function Test-Duration([string]$Literal) {
$settings='"privilege":"user","architecture":"auto","wsh_host":"cscript","msi_ui":"full","internet":"offline","args_mode":"none","filename":"original","dll_mode":"regsvr32","set_zoneid":false,"args":[]'
if ($Literal) {$settings+=',"duration_seconds":'+$Literal}
$json='{"command_id":"00000000-0000-4000-8000-000000000001","attempt_id":"00000000-0000-4000-8000-000000000002","job_id":"00000000-0000-4000-8000-000000000003","iso_label":"OT0000000000000A","sha256":"'+('a'*64)+'","filename":"sample.exe","settings":{'+$settings+'}}'
try {Confirm-OtcheManifest ($json|ConvertFrom-Json -ErrorAction Stop);return $true} catch {if ($_.Exception.Message -ne 'Invalid duration') {throw};return $false}
}
foreach ($accepted in @('1','2','45','1200','1799','1800')) {
if (!(Test-Duration $accepted)) {throw "Valid duration rejected: $accepted"}
}
foreach ($rejected in @('0','-1','1801','3600','45.5','30.0','1e2','"60"','true','null','')) {
if (Test-Duration $rejected) {throw "Invalid duration accepted: $rejected"}
}
$errors=$null
$installer=[Management.Automation.Language.Parser]::ParseFile((Join-Path $PSScriptRoot 'Install-OtcheSource.ps1'),[ref]$null,[ref]$errors)
if ($errors.Count) {throw 'Install-OtcheSource.ps1 does not parse'}
$definition=@($installer.FindAll({param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Get-SourceTaskDefinitions'},$true))
if ($definition.Count -ne 1) {throw 'Get-SourceTaskDefinitions not found'}
$root='C:\ProgramData\Otche'
. ([scriptblock]::Create($definition[0].Extent.Text))
$limits=@{}
foreach ($task in @(Get-SourceTaskDefinitions 'fixture')) {$limits[$task.name]=$task.seconds}
# Invoke-Otche: readiness 90 + window 1800 + Grub export 150 + collector handoff 12.
foreach ($name in @('Otche-user','Otche-admin')) {if ($limits[$name] -lt 2052) {throw "$name task limit cannot cover a 1800-second window"}}
# Collect-Otche observes for duration_seconds + 240 after its own start.
if ($limits['Otche-Collector'] -lt 2040) {throw 'Otche-Collector task limit cannot cover a 1800-second window'}
'PASS duration_seconds accepts whole seconds 1..1800 only; runner and collector task limits cover the maximum window.'