From d22d0cb86ec6ba34cd21a26ea009fe57b85b7a04 Mon Sep 17 00:00:00 2001 From: Lenin Mookiah <2639584+leninworld@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:31:40 -0800 Subject: [PATCH 1/2] fix(intercept): release waiting target approvals when the gate is switched off Switching a task's target gate off left a gated call waiting out its bound and the open request approvable, so a late click still pinned the target. The waiter now reads the live flag and closes the call's requests as a system decision; a plain call then runs as on an ungated task, a merged ask is told to retry. Switching the gate off closes the task's open target requests, so a late Decide gets ErrAlreadyDecided and pins nothing. TCP dials and UDP resolves that open a request during the switch fall back to the gate-off path. Fixes #804 --- CHANGELOG.md | 1 + db/target_pins.go | 33 ++++ db/target_pins_test.go | 40 +++++ intercept/target_dial.go | 8 + intercept/target_dial_pg_test.go | 59 +++++++ intercept/target_request.go | 95 +++++++++-- intercept/target_request_test.go | 260 +++++++++++++++++++++++++++++++ server/manager.go | 6 + server/target_gate_flag_test.go | 49 +++++- 9 files changed, 541 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 682cc50eb..6aa5f9af2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to this project are documented in this file. The format is b ### Fixed +- **Switching a task's target gate off releases its waiting approvals**: the waiter observes the live flag on its 2 s poll, closes open requests so a late click can no longer pin the target, and lets a plain target-gated call continue as it would on an ungated task; a call whose rule or judge approval was merged into the request is told to retry, since that approval was not given (#804). - **`GET /api/tasks/{id}/scope` reports scope approval**: the query behind it did not select `approved_by_operator` or `expanded`, so every row came back with `approved_by_operator: false` and `expanded: false`, including operator-approved rows that grant sandbox egress. The rows now carry both columns as stored, for the task's own scope and for its source tasks' scope. - **The OpenAI Responses format no longer defaults to `gpt-5`**: OpenAI shuts `gpt-5` down on 2026-12-11 and lists `gpt-6.2-sol` as its replacement, so `ARTEX_LLM_PROVIDER=openai-responses` without `ARTEX_LLM_MODEL` (or a profile saved through the API without a model) would start failing then. The default is now `gpt-6.2-sol`; a model set in the profile or in `ARTEX_LLM_MODEL` is kept as is. A gateway set with `ARTEX_LLM_BASE_URL` that does not serve `gpt-6.2-sol` needs `ARTEX_LLM_MODEL` set explicitly. - **`start.sh` stops during a crash backoff**: a SIGTERM or SIGINT that arrived while the supervisor slept before a restart was handled only after the sleep, and the loop then started `artex` again and waited on it, so `docker stop` waited out its grace period and SIGKILLed a freshly started server. The backoff sleep can now be interrupted, and the loop checks for a pending stop before each launch. `scripts/test-start-sh.sh` covers it in CI. diff --git a/db/target_pins.go b/db/target_pins.go index 064b9c385..27ff88d5a 100644 --- a/db/target_pins.go +++ b/db/target_pins.go @@ -185,6 +185,39 @@ WHERE COALESCE(task_id,'')=$1 AND status='pending' AND target_key IS NOT NULL`, return err } +// CloseTargetRequests settles every open target request in scope on behalf of +// the system and returns the ids that were closed. Classic asks and requests in +// other scopes are left untouched. +func (d *DB) CloseTargetRequests(scope TargetScopeRef, reason string) ([]int64, error) { + if err := scope.check(); err != nil { + return nil, err + } + taskID, _ := scope.pendingScope() + taskKey := "" + if taskID != nil { + taskKey = *taskID + } + rows, err := d.Query(`UPDATE intercept_pending SET status='denied', decided_at=NOW(), decided_by='system', + audit=CASE WHEN audit IS NULL THEN NULL ELSE audit || + jsonb_build_object('effective_action', 'deny', 'decision_reason', $3::text, 'execution_status', 'not_executed') END +WHERE COALESCE(task_id,'')=$1 AND COALESCE(conversation_id,0)=$2 + AND status='pending' AND target_key IS NOT NULL +RETURNING id`, taskKey, scope.ConversationID, reason) + if err != nil { + return nil, err + } + defer rows.Close() + var ids []int64 + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + // TargetRequest is a new target approval request: the intercept_pending row a // gated call asks for when one of its targets has no pin that covers it. type TargetRequest struct { diff --git a/db/target_pins_test.go b/db/target_pins_test.go index 9e4fbec60..6199d9a4e 100644 --- a/db/target_pins_test.go +++ b/db/target_pins_test.go @@ -268,6 +268,46 @@ func TestTargetRequestNewRowAfterDecision(t *testing.T) { } } +func TestCloseTargetRequestsOnlyClosesPendingTargetsInScope(t *testing.T) { + d := openTargetDB(t) + scope := TargetScopeRef{TaskID: targetTask(t, d, TaskCreateOptions{}).ID} + other := TargetScopeRef{TaskID: targetTask(t, d, TaskCreateOptions{}).ID} + closed, _ := openTargetRequest(t, d, scope, "close.example.com", 443, "203.0.113.7") + decided, _ := openTargetRequest(t, d, scope, "decided.example.com", 443, "203.0.113.8") + if _, ok, err := d.ResolveTargetRequest(decided, false, "ARTEX", "198.51.100.9"); err != nil || !ok { + t.Fatalf("pre-decide row: ok=%v err=%v", ok, err) + } + otherID, _ := openTargetRequest(t, d, other, "other.example.com", 443, "203.0.113.9") + classic, err := d.CreateInterceptPending(0, 0, strconv.FormatInt(scope.TaskID, 10), "worker", "Bash", nil, "classic ask") + if err != nil { + t.Fatal(err) + } + + const reason = "the target gate was switched off; nothing was pinned" + ids, err := d.CloseTargetRequests(scope, reason) + if err != nil || !slices.Equal(ids, []int64{closed}) { + t.Fatalf("closed ids = %v, err=%v; want [%d]", ids, err, closed) + } + row, err := d.GetInterceptDetail(closed) + if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" || row.Audit == nil || + row.Audit.EffectiveAction != "deny" || row.Audit.DecisionReason != reason || row.Audit.ExecutionStatus != "not_executed" { + t.Fatalf("closed row = %+v, %v", row, err) + } + for name, id := range map[string]int64{"already decided target": decided, "other scope target": otherID, "classic ask": classic} { + row, err := d.GetInterceptPending(id) + if err != nil || row == nil { + t.Fatalf("%s row %d = %+v, %v", name, id, row, err) + } + if name == "already decided target" { + if row.Status != "denied" || row.DecidedBy != "human" { + t.Fatalf("%s changed: %+v", name, row) + } + } else if row.Status != "pending" || row.DecidedBy != "" { + t.Fatalf("%s changed: %+v", name, row) + } + } +} + // Settling the row, superseding the old pin and writing the new one are one // transaction: when the pin cannot be written the row stays pending and the // previous pin stays active. diff --git a/intercept/target_dial.go b/intercept/target_dial.go index 40b1d50b1..51f610a63 100644 --- a/intercept/target_dial.go +++ b/intercept/target_dial.go @@ -98,6 +98,10 @@ func (i *Interceptor) dialTarget(ctx context.Context, scope TargetScope, toolNam // Wait bound 0: the request is found or created, and the dial does not wait. scope.WaitBound = 0 res = i.RequestTargets(ctx, scope, toolName, input, unpinned, nil) + if res.Code == "" { + // The gate was switched off meanwhile (#804): dial as with the gate off. + return i.baseDialer()(ctx, network, addr) + } if res.Code == TargetApprovalPending { res.Reason = notCovered(unpinned[0], scope) } @@ -337,6 +341,10 @@ func (i *Interceptor) resolveTargetUDP4(ctx context.Context, scope TargetScope, if len(unpinned) > 0 { scope.WaitBound = 0 res = i.RequestTargets(ctx, scope, toolName, input, unpinned, nil) + if res.Code == "" { + // The gate was switched off meanwhile (#804): resolve as with the gate off. + return i.ResolveUDP4(ctx, addr) + } if res.Code == TargetApprovalPending { res.Reason = notCovered(unpinned[0], scope) } diff --git a/intercept/target_dial_pg_test.go b/intercept/target_dial_pg_test.go index 930617bd8..8654ecddf 100644 --- a/intercept/target_dial_pg_test.go +++ b/intercept/target_dial_pg_test.go @@ -26,6 +26,65 @@ func pgDialGate(t *testing.T, d *db.DB) (*Interceptor, *fakeResolver, *dialRecor return ic, res, rec } +// The gate remains on through the dial check and request creation, then turns +// off at RequestTargets' post-open re-read. The dial must take the same base +// path as a call that entered with the gate off, and the opened row must not be +// left available for a late approval. +func TestPinnedDialGateSwitchedOffAfterRequestUsesBaseDialer(t *testing.T) { + d := targetTestDB(t) + ic, _, rec := pgDialGate(t, d) + srv, _, port := pinnedServer(t, "gate-off") + addr := "198.51.100.7:" + port + rec.route(addr, srv.Listener.Addr().String()) + scope := taskScope(t, d, ic, time.Minute) + var reads atomic.Int32 + scope.Enabled = func() bool { return reads.Add(1) < 3 } + + conn, err := PinnedDialer("WebFetch", true)(WithTargetScope(t.Context(), scope), "tcp", addr) + if err != nil { + t.Fatalf("dial after the post-open gate switch-off: %v", err) + } + conn.Close() + if reads.Load() < 3 { + t.Fatalf("the gate was read %d times, want the post-open re-read", reads.Load()) + } + if got := rec.calls(); !slices.Equal(got, []string{addr}) { + t.Fatalf("base dialer calls = %v, want %s", got, addr) + } + id := onlyTargetRow(t, d, scope) + row, err := d.GetInterceptDetail(id) + if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" { + t.Fatalf("dial request row = %+v, %v; want denied by the system", row, err) + } +} + +// The UDP resolver has the same post-open release as the TCP dialer. A literal +// address avoids DNS and proves the fallback returned the plain UDP address. +func TestPinnedUDP4GateSwitchedOffAfterRequestResolvesPlain(t *testing.T) { + d := targetTestDB(t) + ic, _, _ := pgDialGate(t, d) + scope := taskScope(t, d, ic, time.Minute) + var reads atomic.Int32 + scope.Enabled = func() bool { return reads.Add(1) < 3 } + const raw = "198.51.100.8:5353" + + addr, err := PinnedUDP4Resolver("socks5-udp", true)(WithTargetScope(t.Context(), scope), raw) + if err != nil { + t.Fatalf("UDP resolve after the post-open gate switch-off: %v", err) + } + if addr == nil || addr.String() != raw { + t.Fatalf("resolved UDP address = %v, want %s", addr, raw) + } + if reads.Load() < 3 { + t.Fatalf("the gate was read %d times, want the post-open re-read", reads.Load()) + } + id := onlyTargetRow(t, d, scope) + row, err := d.GetInterceptDetail(id) + if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" { + t.Fatalf("UDP request row = %+v, %v; want denied by the system", row, err) + } +} + // openTarget returns the audit target of the single open request of scope. func openTarget(t *testing.T, d *db.DB, scope TargetScope) (*db.InterceptDetail, db.InterceptTarget) { t.Helper() diff --git a/intercept/target_request.go b/intercept/target_request.go index 70430b4e2..632faf63f 100644 --- a/intercept/target_request.go +++ b/intercept/target_request.go @@ -121,6 +121,13 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too // A call that never waits cannot own a call-bound row. ask = nil } + // The gate is read live: switched off since the call was checked, it no + // longer applies, and switched off while the call waits, it releases the + // call (#804). + gateOn := scope.Enabled + if gateOn != nil && !gateOn() { + return TargetResult{} + } var res TargetResult var merged *targetWaiter @@ -154,6 +161,29 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too res.Code, res.Host, res.Port, res.PendingID, res.Reason = code, w.target.Host, w.target.Port, w.id, reason return res } + const gateOffSettleReason = "the target gate was switched off while the call waited; nothing was pinned" + const mergedGateOffReason = "the target gate was switched off while the call waited and the merged approval was not given; retry the call" + settleGateOff := func() error { + for _, w := range waiters { + if w.id != 0 { + if _, err := i.settleTargetRequest(w.id, "denied", gateOffSettleReason); err != nil { + return err + } + } + } + return nil + } + // Switched off while the rows were opened: the manager's close may have + // run before them, so close them here, as a waiting call does. + if gateOn != nil && !gateOn() { + if err := settleGateOff(); err != nil { + return blocked(waiters[0], TargetGateUnavailable, err.Error()) + } + if merged != nil { + return blocked(merged, TargetApprovalPending, mergedGateOffReason) + } + return res + } if scope.WaitBound <= 0 { return blocked(waiters[0], TargetApprovalPending, "this call does not wait for approvals; the request stays open") } @@ -173,8 +203,16 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too ruleTimeout = timer.C } status, reason := "", "" - switch st := i.awaitTarget(ctx, merged.id, bound.C, ruleTimeout); st { + switch st := i.awaitTarget(ctx, merged.id, bound.C, ruleTimeout, gateOn); st { case "allowed": + case waitGateOff: + if err := settleGateOff(); err != nil { + return blocked(merged, TargetGateUnavailable, err.Error()) + } + if i.targetAllowed(merged.id) { + break + } + return blocked(merged, TargetApprovalPending, mergedGateOffReason) case waitRuleTimeout: status, reason = "timeout", "approval timed out" if mergedAsk.TimeoutAction == "allow" { @@ -195,11 +233,11 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too } } - for _, w := range waiters { + for n, w := range waiters { if w == merged || w.id == 0 { continue } - st := i.awaitTarget(ctx, w.id, bound.C, nil) + st := i.awaitTarget(ctx, w.id, bound.C, nil, gateOn) if (st == "denied" || st == "timeout") && !w.created && i.wasMerged(w.id) { // The row this call attached to was bound to another call and closed // with it. That says nothing about the host: ask once more, with a @@ -211,11 +249,20 @@ func (i *Interceptor) RequestTargets(ctx context.Context, scope TargetScope, too if retry.id == 0 { continue } - w = retry - st = i.awaitTarget(ctx, w.id, bound.C, nil) + // Kept in waiters, so a gate-off release closes it too. + w, waiters[n] = retry, retry + st = i.awaitTarget(ctx, w.id, bound.C, nil, gateOn) } switch st { case "allowed": + case waitGateOff: + if err := settleGateOff(); err != nil { + return blocked(w, TargetGateUnavailable, err.Error()) + } + if i.targetAllowed(w.id) { + continue + } + return res case waitElapsed: return blocked(w, TargetApprovalPending, "no approval within the wait bound; the request stays open") case waitCancelled: @@ -298,13 +345,15 @@ const ( waitRuleTimeout = "wait_rule_timeout" // the timeout of a merged ask waitCancelled = "wait_cancelled" // the call's context waitGone = "wait_gone" // the row no longer exists (its conversation was deleted) + // waitGateOff means the scope's target gate was switched off while waiting. + waitGateOff = "wait_gate_off" ) // awaitTarget waits for the decision on one request row and returns its status // (allowed | denied | timeout) or the way the wait ended. It never settles the // row. The row is re-read before each wait: that covers a decision taken before // the waiter registered, and one taken on another instance. -func (i *Interceptor) awaitTarget(ctx context.Context, id int64, bound, ruleTimeout <-chan time.Time) string { +func (i *Interceptor) awaitTarget(ctx context.Context, id int64, bound, ruleTimeout <-chan time.Time, enabled func() bool) string { ch := i.pending.add(id) defer i.pending.remove(id, ch) poll := time.NewTicker(targetPollInterval) @@ -315,7 +364,15 @@ func (i *Interceptor) awaitTarget(ctx context.Context, id int64, bound, ruleTime return waitGone } if err == nil && row.Status != "pending" { - return row.Status + // A human decision that won the race still counts. A system close + // caused by this same switch is the gate-off wait outcome. + if row.DecidedBy != "system" || enabled == nil || enabled() { + return row.Status + } + return waitGateOff + } + if enabled != nil && !enabled() { + return waitGateOff } select { case <-ch: @@ -334,12 +391,32 @@ func (i *Interceptor) awaitTarget(ctx context.Context, id int64, bound, ruleTime // leaving, and wakes the calls attached to it. It reports whether the row was // still open; a merged row closed this way never pins. func (i *Interceptor) settleMerged(id int64, status, reason string) bool { + resolved, _ := i.settleTargetRequest(id, status, reason) + return resolved +} + +// settleTargetRequest closes one target request on behalf of the system and +// wakes every local call waiting on it. +func (i *Interceptor) settleTargetRequest(id int64, status, reason string) (bool, error) { resolved, err := i.db.ResolveIntercept(id, status, "deny", reason, "system") if err != nil || !resolved { - return false + return false, err } i.pending.resolve(id, false) - return true + return true, nil +} + +// CloseTargetRequests closes every open target request in scope and wakes the +// local calls waiting on the rows. Calls on other instances wake on their poll. +func (i *Interceptor) CloseTargetRequests(scope db.TargetScopeRef, reason string) error { + ids, err := i.db.CloseTargetRequests(scope, reason) + if err != nil { + return err + } + for _, id := range ids { + i.pending.resolve(id, false) + } + return nil } func (i *Interceptor) targetAllowed(id int64) bool { diff --git a/intercept/target_request_test.go b/intercept/target_request_test.go index 81a5172ef..dd8e2aa0e 100644 --- a/intercept/target_request_test.go +++ b/intercept/target_request_test.go @@ -2,6 +2,7 @@ package intercept import ( "context" + "errors" "fmt" "slices" "strconv" @@ -116,6 +117,17 @@ func result(t *testing.T, ch <-chan TargetResult) TargetResult { } } +func promptResult(t *testing.T, ch <-chan TargetResult) TargetResult { + t.Helper() + select { + case res := <-ch: + return res + case <-time.After(5 * time.Second): + t.Fatal("the call was not released within a few seconds") + return TargetResult{} + } +} + func stillWaiting(t *testing.T, ch <-chan TargetResult) { t.Helper() select { @@ -167,6 +179,22 @@ WHERE COALESCE(task_id,'')=$1 AND COALESCE(conversation_id,0)=$2 AND target_key return n } +// onlyTargetRow returns the id of the scope's only target request, regardless +// of whether it is still pending or has already been decided. +func onlyTargetRow(t *testing.T, d *db.DB, scope TargetScope) int64 { + t.Helper() + if n := allRows(t, d, scope); n != 1 { + t.Fatalf("%d target request rows, want one", n) + } + var id int64 + if err := d.QueryRow(`SELECT id FROM intercept_pending +WHERE COALESCE(task_id,'')=$1 AND COALESCE(conversation_id,0)=$2 AND target_key IS NOT NULL`, + scope.TaskID, scope.ConversationID).Scan(&id); err != nil { + t.Fatal(err) + } + return id +} + // waiters is how many calls wait on request id through ic. func waiters(ic *Interceptor, id int64) int { ic.pending.mu.Lock() @@ -370,6 +398,238 @@ func TestMergedRequestSettledWhenCreatorLeaves(t *testing.T) { } } +func TestTargetGateSwitchOffReleasesPlainRequest(t *testing.T) { + d := targetTestDB(t) + ic := New(d) + var enabled atomic.Bool + enabled.Store(true) + scope := taskScope(t, d, ic, 30*time.Second) + scope.Enabled = enabled.Load + call := request(context.Background(), ic, scope, nil, + target("a.example.com", 443, "203.0.113.1"), + target("b.example.com", 443, "203.0.113.2")) + var ids []int64 + eventually(t, "both target requests", func() bool { + ids = openRows(t, d, scope) + return len(ids) == 2 + }) + eventually(t, "the first target wait", func() bool { return waiters(ic, ids[0]) == 1 }) + + enabled.Store(false) + if res := promptResult(t, call); res.Code != "" { + t.Fatalf("call after the gate was switched off: %+v, want no block", res) + } + for _, id := range ids { + row, err := d.GetInterceptDetail(id) + if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" || + row.Audit == nil || row.Audit.EffectiveAction != "deny" || row.Audit.ExecutionStatus != "not_executed" || + row.Audit.DecisionReason != "the target gate was switched off while the call waited; nothing was pinned" { + t.Fatalf("closed target row %d = %+v, %v", id, row, err) + } + if err := ic.Decide(id, true, "ARTEX", "198.51.100.9"); !errors.Is(err, ErrAlreadyDecided) { + t.Fatalf("late approval of %d = %v, want ErrAlreadyDecided", id, err) + } + } + if got := pins(t, d, scope); len(got) != 0 { + t.Fatalf("late approvals created pins: %+v", got) + } +} + +func TestTargetGateSwitchOffClosesMergedRequest(t *testing.T) { + d := targetTestDB(t) + ic := New(d) + var enabled atomic.Bool + enabled.Store(true) + scope := taskScope(t, d, ic, 30*time.Second) + scope.Enabled = enabled.Load + ask := askRule(t, d, false, 0, "deny") + call := request(context.Background(), ic, scope, &ask, target("app.example.com", 443, "203.0.113.7")) + id := oneOpenRow(t, d, scope) + eventually(t, "the merged target wait", func() bool { return waiters(ic, id) == 1 }) + + enabled.Store(false) + res := promptResult(t, call) + if res.Code != TargetApprovalPending || !res.AskMerged || res.PendingID != id || + !strings.Contains(res.Reason, "target gate was switched off") || !strings.Contains(res.Reason, "merged approval was not given") { + t.Fatalf("merged call after the gate was switched off: %+v", res) + } + row, err := d.GetInterceptDetail(id) + if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" || row.Audit == nil || + row.Audit.DecisionReason != "the target gate was switched off while the call waited; nothing was pinned" { + t.Fatalf("closed merged row = %+v, %v", row, err) + } + if got := pins(t, d, scope); len(got) != 0 { + t.Fatalf("closing the merged row created pins: %+v", got) + } +} + +// A call that reaches RequestTargets after the gate was switched off opens no +// request: the gate no longer applies to it. +func TestTargetGateOffOpensNoRequest(t *testing.T) { + d := targetTestDB(t) + ic := New(d) + scope := taskScope(t, d, ic, 30*time.Second) + scope.Enabled = func() bool { return false } + res := ic.RequestTargets(context.Background(), scope, "WebFetch", webFetchInput, + []TargetRequest{target("app.example.com", 443, "203.0.113.7")}, nil) + if res.Code != "" || res.PendingID != 0 { + t.Fatalf("call with the gate off = %+v, want no block", res) + } + var n int + if err := d.QueryRow(`SELECT COUNT(*) FROM intercept_pending WHERE task_id=$1`, scope.TaskID).Scan(&n); err != nil { + t.Fatal(err) + } + if n != 0 { + t.Fatalf("the call opened %d request rows with the gate off", n) + } +} + +// The gate is switched off after the call entered but before it waits (here a +// call that never waits): the manager's close may already have run, so the +// call closes the rows it opened and no late click can pin them. +func TestTargetGateSwitchedOffWhileOpeningClosesRows(t *testing.T) { + d := targetTestDB(t) + ic := New(d) + scope := taskScope(t, d, ic, 0) + var reads atomic.Int32 + scope.Enabled = func() bool { return reads.Add(1) == 1 } + res := ic.RequestTargets(context.Background(), scope, "WebFetch", webFetchInput, + []TargetRequest{target("app.example.com", 443, "203.0.113.7")}, nil) + if res.Code != "" { + t.Fatalf("call after the gate was switched off = %+v, want no block", res) + } + if reads.Load() < 2 { + t.Fatalf("the gate was read %d times, want a re-read after the rows were opened", reads.Load()) + } + var ids []int64 + rows, err := d.Query(`SELECT id FROM intercept_pending WHERE task_id=$1 AND target_key IS NOT NULL`, scope.TaskID) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + t.Fatal(err) + } + ids = append(ids, id) + } + rows.Close() + if len(ids) != 1 { + t.Fatalf("target rows = %v, want the one the call opened", ids) + } + row, err := d.GetInterceptDetail(ids[0]) + if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" { + t.Fatalf("row opened while the gate was switched off = %+v, %v", row, err) + } + if err := ic.Decide(ids[0], true, "ARTEX", "198.51.100.9"); !errors.Is(err, ErrAlreadyDecided) { + t.Fatalf("late approval = %v, want ErrAlreadyDecided", err) + } + if got := pins(t, d, scope); len(got) != 0 { + t.Fatalf("late approval created pins: %+v", got) + } +} + +// An attached call whose merged row closes retries with a plain row. Switching +// the gate off while it waits on that retry releases the call and closes the +// retry, so a late approval cannot create a pin. +func TestTargetGateSwitchOffReleasesAttachedRetry(t *testing.T) { + d := targetTestDB(t) + ic := New(d) + var enabled atomic.Bool + enabled.Store(true) + scope := taskScope(t, d, ic, 30*time.Second) + scope.Enabled = enabled.Load + ask := askRule(t, d, false, 0, "deny") + tgt := target("app.example.com", 443, "203.0.113.7") + + creatorCtx, cancelCreator := context.WithCancel(context.Background()) + creator := request(creatorCtx, ic, scope, &ask, tgt) + merged := oneOpenRow(t, d, scope) + attached := request(context.Background(), ic, scope, nil, tgt) + eventually(t, "both calls to wait on the merged row", func() bool { return waiters(ic, merged) == 2 }) + + cancelCreator() + if res := promptResult(t, creator); res.Code != TargetDenied || !res.AskMerged || res.PendingID != merged { + t.Fatalf("creator after leaving = %+v, want a denied merged request", res) + } + var retry int64 + eventually(t, "the attached call to wait on its retry row", func() bool { + ids := openRows(t, d, scope) + if len(ids) == 1 && ids[0] != merged && waiters(ic, ids[0]) == 1 { + retry = ids[0] + } + return retry != 0 + }) + + enabled.Store(false) + if res := promptResult(t, attached); res.Code != "" { + t.Fatalf("attached call after the gate was switched off = %+v, want no block", res) + } + row, err := d.GetInterceptDetail(retry) + if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" || row.Audit == nil || + row.Audit.DecisionReason != "the target gate was switched off while the call waited; nothing was pinned" { + t.Fatalf("retry row after gate switch-off = %+v, %v; want denied by the system", row, err) + } + if err := ic.Decide(retry, true, "ARTEX", "198.51.100.9"); !errors.Is(err, ErrAlreadyDecided) { + t.Fatalf("late approval of retry row = %v, want ErrAlreadyDecided", err) + } + if got := pins(t, d, scope); len(got) != 0 { + t.Fatalf("late approval of retry row created pins: %+v", got) + } +} + +// awaitTarget re-reads the row before consulting the live gate. Therefore an +// approval already stored by a human wins even when the gate is now off, and a +// system gate-off settlement cannot overwrite the allowed row. +func TestHumanTargetApprovalWinsGateSwitchOff(t *testing.T) { + d := targetTestDB(t) + ic := New(d) + var enabled atomic.Bool + enabled.Store(true) + scope := taskScope(t, d, ic, 30*time.Second) + scope.Enabled = enabled.Load + call := request(context.Background(), ic, scope, nil, target("app.example.com", 443, "203.0.113.7")) + id := oneOpenRow(t, d, scope) + eventually(t, "the target call to wait", func() bool { return waiters(ic, id) == 1 }) + + if err := ic.Decide(id, true, "ARTEX", "198.51.100.9"); err != nil { + t.Fatal(err) + } + enabled.Store(false) + if status := ic.awaitTarget(context.Background(), id, make(chan time.Time), nil, enabled.Load); status != "allowed" { + t.Fatalf("re-read of the human-approved row with the gate off = %q, want allowed", status) + } + if resolved, err := ic.settleTargetRequest(id, "denied", "gate switched off"); err != nil || resolved { + t.Fatalf("system settlement of human-approved row = resolved %v, err %v; want an unchanged row", resolved, err) + } + if res := promptResult(t, call); res.Code != "" { + t.Fatalf("human-approved call after gate switch-off = %+v, want no block", res) + } + row, err := d.GetInterceptDetail(id) + if err != nil || row == nil || row.Status != "allowed" || row.DecidedBy != "human" { + t.Fatalf("human-approved row after gate switch-off = %+v, %v", row, err) + } + if got := pins(t, d, scope); len(got) != 1 || got[0].Host != "app.example.com" { + t.Fatalf("pins after the human approval = %+v, want the approved target", got) + } +} + +func TestCloseTargetRequestsWakesWaiter(t *testing.T) { + d := targetTestDB(t) + ic := New(d) + scope := taskScope(t, d, ic, 30*time.Second) + call := request(context.Background(), ic, scope, nil, target("app.example.com", 443, "203.0.113.7")) + id := oneOpenRow(t, d, scope) + eventually(t, "the target wait", func() bool { return waiters(ic, id) == 1 }) + + if err := ic.CloseTargetRequests(scope.dbRef(t), "target requests closed by test"); err != nil { + t.Fatal(err) + } + if res := promptResult(t, call); res.Code != TargetDenied || res.PendingID != id { + t.Fatalf("woken call = %+v, want %s", res, TargetDenied) + } +} + // A timeout never pins, whatever the rule says: timeout_action = allow is // overridden on a merged row and the override is recorded. func TestTimeoutNeverPins(t *testing.T) { diff --git a/server/manager.go b/server/manager.go index 0e4545526..cbe7cb74c 100644 --- a/server/manager.go +++ b/server/manager.go @@ -1116,7 +1116,13 @@ func (m *Manager) UpdateTaskMetadata(taskID string, patch pgdb.TaskPatch) (*Task // Live switch (#86): runRound reads the flag per round, so the next // planning round (edge or heartbeat) already respects the new value. task.PlanQuietMode = updated.PlanQuietMode + wasTargetGateEnabled := task.targetGate.Load() task.targetGate.Store(updated.TargetGate) + if wasTargetGateEnabled && !updated.TargetGate { + if err := m.interceptor.CloseTargetRequests(pgdb.TargetScopeRef{TaskID: id}, "the target gate was switched off; nothing was pinned"); err != nil { + log.Printf("[target-gate] close requests for task %s: %v", taskID, err) + } + } return task, nil } diff --git a/server/target_gate_flag_test.go b/server/target_gate_flag_test.go index 1aca315fb..3f0e68e50 100644 --- a/server/target_gate_flag_test.go +++ b/server/target_gate_flag_test.go @@ -154,6 +154,51 @@ func TestTargetGateLiveSwitch(t *testing.T) { } } +func TestTaskTargetGateSwitchOffClosesOpenRequests(t *testing.T) { + g := newGateServer(t) + on := true + task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on}) + scope := taskRef(t, task) + path := "/api/tasks/" + task.ID + id := openTargetRow(t, g.m.pg, scope, "app.example.com", "203.0.113.7") + + if code, body := g.do(t, "PATCH", path, `{"target_gate":true}`); code != 200 || body["target_gate"] != true { + t.Fatalf("true to true: %d %v", code, body) + } + if row, err := g.m.pg.GetInterceptPending(id); err != nil || row == nil || row.Status != "pending" { + t.Fatalf("request after true to true = %+v, %v; want pending", row, err) + } + if code, body := g.do(t, "PATCH", path, `{"target_gate":false}`); code != 200 || body["target_gate"] != false { + t.Fatalf("switch off: %d %v", code, body) + } + row, err := g.m.pg.GetInterceptDetail(id) + if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" || row.Audit == nil || + row.Audit.EffectiveAction != "deny" || row.Audit.DecisionReason != "the target gate was switched off; nothing was pinned" || + row.Audit.ExecutionStatus != "not_executed" { + t.Fatalf("request after switch off = %+v, %v", row, err) + } + if err := g.m.interceptor.Decide(id, true, "ARTEX", "192.0.2.1"); !errors.Is(err, intercept.ErrAlreadyDecided) { + t.Fatalf("late approval = %v, want ErrAlreadyDecided", err) + } + if got, err := g.m.pg.ListTargetPins(scope); err != nil || len(got) != 0 { + t.Fatalf("pins after late approval = %+v, %v", got, err) + } + + // Neither false-to-true nor true-to-true closes an open row. + stillOpen := openTargetRow(t, g.m.pg, scope, "next.example.com", "203.0.113.8") + for n := 0; n < 2; n++ { + if code, body := g.do(t, "PATCH", path, `{"target_gate":true}`); code != 200 || body["target_gate"] != true { + t.Fatalf("switch on %d: %d %v", n, code, body) + } + if row, err := g.m.pg.GetInterceptPending(stillOpen); err != nil || row == nil || row.Status != "pending" { + t.Fatalf("request after switch on %d = %+v, %v; want pending", n, row, err) + } + } + if err := g.m.interceptor.Decide(stillOpen, false, "ARTEX", "192.0.2.1"); err != nil { + t.Fatal(err) + } +} + const gateTestGoal = "Probe the lab target at http://127.0.0.1:9/v1 for unauthenticated data exposure; record one record as evidence and stop." // The flag is set on the existing create path. Omitted means off, and a task @@ -675,7 +720,9 @@ func TestTargetPinRoutes(t *testing.T) { // that took the intent over attaches to the same request. func TestClaimLostEndsGateWait(t *testing.T) { g := newGateServer(t) - task := g.newTask(t, db.TaskCreateOptions{}) + // A gated task: with the gate off, RequestTargets opens no request. + on := true + task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on}) pg, ic := g.m.pg, g.m.interceptor store := task.Store intent, err := store.AddIntent(map[string]any{"summary": "leased"}, 1, nil, "planner") From a31d4cb2378fff036d1f49b6a5b6dd67e7745539 Mon Sep 17 00:00:00 2001 From: Lenin Mookiah <2639584+leninworld@users.noreply.github.com> Date: Wed, 2 Dec 2026 04:17:37 -0800 Subject: [PATCH 2/2] fix(intercept): refuse late target approvals under the task row lock Switching the gate off and closing the task's open requests are two operations, so an approval landing between them (or while the close fails, or on another instance) could still pin the target. ResolveTargetRequest now locks the task row before the pending row (the order task deletion uses), reads target_gate under that lock and turns an approval on a gate-off or deleted task into a system denial: no pin, no approver fields, the same row shape CloseTargetRequests writes. Decide reports it as already decided and wakes local waiters with false, and a waiter seeing that system close releases the call even if its local gate flag lags. Tests that approve target requests now create gate-on tasks. The task-row lock and its test come from #808. Co-authored-by: Jwalith --- agent/hooks_reach_test.go | 7 +- db/target_pins.go | 108 +++++++++++++++++++--- db/target_pins_test.go | 128 +++++++++++++++++++++++--- guard/target_gate_test.go | 3 +- intercept/intercept.go | 4 + intercept/target_request.go | 16 +++- intercept/target_request_test.go | 75 ++++++++++++++- server/intercept_batch_decide_test.go | 11 ++- server/manager.go | 2 +- server/target_gate_flag_test.go | 6 +- server/target_gate_wiring_test.go | 3 +- 11 files changed, 321 insertions(+), 42 deletions(-) diff --git a/agent/hooks_reach_test.go b/agent/hooks_reach_test.go index 37af6478a..63ce641b9 100644 --- a/agent/hooks_reach_test.go +++ b/agent/hooks_reach_test.go @@ -105,12 +105,13 @@ func newHookReachFixture(t *testing.T) hookReachFixture { t.Helper() d := testDB(t) t.Cleanup(func() { _ = d.Close() }) - expID, err := d.CreateExploration("hook reach probe", "prove tool calls reach the hooks") + on := true + task, err := d.CreateTaskWithOptions("hook reach probe", "prove tool calls reach the hooks", db.TaskCreateOptions{TargetGate: &on}) if err != nil { t.Fatal(err) } - t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) }) - f := hookReachFixture{expID: expID, taskID: fmt.Sprint(expID), ts: d.Exploration(expID), workDir: t.TempDir()} + t.Cleanup(func() { _ = d.DeleteTask(task.ID) }) + f := hookReachFixture{expID: task.ExplorationID, taskID: fmt.Sprint(task.ID), ts: d.Exploration(task.ExplorationID), workDir: t.TempDir()} f.marker = filepath.Join(f.workDir, "tool-ran") input, _ := json.Marshal(map[string]string{"command": "touch " + f.marker}) f.bash = string(input) diff --git a/db/target_pins.go b/db/target_pins.go index 27ff88d5a..06fda3d25 100644 --- a/db/target_pins.go +++ b/db/target_pins.go @@ -185,6 +185,33 @@ WHERE COALESCE(task_id,'')=$1 AND status='pending' AND target_key IS NOT NULL`, return err } +// TargetGateDisabledReason is the audit reason used when disabling a task's +// target gate closes or refuses an approval request. +const TargetGateDisabledReason = "the target gate was switched off; nothing was pinned" + +// ErrTargetGateDisabled reports an approval that was system-refused because +// the task's target gate was disabled before the decision committed. +var ErrTargetGateDisabled = errors.New("the target gate was disabled before the target approval was decided") + +// systemDenyTargetRequest settles one locked target request without attributing +// the decision to a human. Its audit shape is shared by gate-off bulk closes and +// approvals refused after the task gate was disabled. +func systemDenyTargetRequest(tx *sql.Tx, id int64, reason string) error { + _, err := tx.Exec(`UPDATE intercept_pending SET status='denied', decided_at=NOW(), decided_by='system', + audit=CASE WHEN audit IS NULL THEN NULL ELSE (audit - 'approver' - 'approver_addr') || + jsonb_build_object( + 'effective_action', 'deny', + 'decision_reason', $2::text, + 'execution_status', 'not_executed', + 'targets', COALESCE(( + SELECT jsonb_agg(value || '{"outcome":"denied"}'::jsonb) + FROM jsonb_array_elements(COALESCE(audit->'targets', '[]'::jsonb)) AS target(value) + ), '[]'::jsonb) + ) END +WHERE id=$1 AND status='pending' AND target_key IS NOT NULL`, id, reason) + return err +} + // CloseTargetRequests settles every open target request in scope on behalf of // the system and returns the ids that were closed. Classic asks and requests in // other scopes are left untouched. @@ -197,25 +224,43 @@ func (d *DB) CloseTargetRequests(scope TargetScopeRef, reason string) ([]int64, if taskID != nil { taskKey = *taskID } - rows, err := d.Query(`UPDATE intercept_pending SET status='denied', decided_at=NOW(), decided_by='system', - audit=CASE WHEN audit IS NULL THEN NULL ELSE audit || - jsonb_build_object('effective_action', 'deny', 'decision_reason', $3::text, 'execution_status', 'not_executed') END + tx, err := d.Begin() + if err != nil { + return nil, err + } + defer tx.Rollback() + rows, err := tx.Query(`SELECT id FROM intercept_pending WHERE COALESCE(task_id,'')=$1 AND COALESCE(conversation_id,0)=$2 AND status='pending' AND target_key IS NOT NULL -RETURNING id`, taskKey, scope.ConversationID, reason) + ORDER BY id FOR UPDATE`, taskKey, scope.ConversationID) if err != nil { return nil, err } - defer rows.Close() var ids []int64 for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { + rows.Close() return nil, err } ids = append(ids, id) } - return ids, rows.Err() + if err := rows.Err(); err != nil { + rows.Close() + return nil, err + } + if err := rows.Close(); err != nil { + return nil, err + } + for _, id := range ids { + if err := systemDenyTargetRequest(tx, id, reason); err != nil { + return nil, err + } + } + if err := tx.Commit(); err != nil { + return nil, err + } + return ids, nil } // TargetRequest is a new target approval request: the intercept_pending row a @@ -289,20 +334,46 @@ func (d *DB) TargetRequestKey(id int64) (string, error) { return key.String, err } -// ResolveTargetRequest settles an open target request with a human decision, in -// one transaction. Allowed pins the addresses the request displayed: the active -// pin of the same key, if any, becomes superseded and a new version holds its -// addresses plus the displayed ones (addresses leave only by revocation). -// Denied pins nothing. approver and remoteAddr go to the pin and to the row's -// audit; decided_by on the row stays the actor class, human. ok is false when -// the row is not an open target request. If the pin cannot be written the row -// stays pending. +// ResolveTargetRequest settles an open target request in one transaction. +// A task-scoped approval first locks the task and is refused with a system +// denial when the task is gone or its target gate is off. Otherwise, allowed +// pins the displayed addresses: the active pin of the same key, if any, becomes +// superseded and a new version holds its addresses plus the displayed ones +// (addresses leave only by revocation). Denied pins nothing. Human decisions +// record approver and remoteAddr in the pin and row audit; decided_by remains +// the actor class. ok is false when the row is not open. A system-refused +// approval returns ErrTargetGateDisabled after committing the denial. If the +// pin cannot be written the row stays pending. func (d *DB) ResolveTargetRequest(id int64, allowed bool, approver, remoteAddr string) (pin *TargetPin, ok bool, err error) { tx, err := d.Begin() if err != nil { return nil, false, err } defer tx.Rollback() + var initialTaskID sql.NullString + err = tx.QueryRow(`SELECT task_id FROM intercept_pending +WHERE id=$1 AND status='pending' AND target_key IS NOT NULL`, id).Scan(&initialTaskID) + if errors.Is(err, sql.ErrNoRows) { + return nil, false, nil + } + if err != nil { + return nil, false, err + } + taskGateEnabled := true + if allowed && initialTaskID.Valid { + taskIDValue, parseErr := strconv.ParseInt(initialTaskID.String, 10, 64) + if parseErr != nil { + return nil, false, fmt.Errorf("target request %d: task id %q: %w", id, initialTaskID.String, parseErr) + } + // Lock task before pending, matching task deletion's lock order. + lockErr := tx.QueryRow(`SELECT target_gate FROM tasks +WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, taskIDValue).Scan(&taskGateEnabled) + if errors.Is(lockErr, sql.ErrNoRows) { + taskGateEnabled = false + } else if lockErr != nil { + return nil, false, lockErr + } + } var taskID sql.NullString var convID sql.NullInt64 var raw []byte @@ -314,6 +385,15 @@ WHERE id=$1 AND status='pending' AND target_key IS NOT NULL FOR UPDATE`, id).Sca if err != nil { return nil, false, err } + if allowed && taskID.Valid && !taskGateEnabled { + if err := systemDenyTargetRequest(tx, id, TargetGateDisabledReason); err != nil { + return nil, false, err + } + if err := tx.Commit(); err != nil { + return nil, false, err + } + return nil, false, ErrTargetGateDisabled + } var audit InterceptAudit if len(raw) > 0 { if err := json.Unmarshal(raw, &audit); err != nil { diff --git a/db/target_pins_test.go b/db/target_pins_test.go index 6199d9a4e..2bde1b46c 100644 --- a/db/target_pins_test.go +++ b/db/target_pins_test.go @@ -25,10 +25,14 @@ func openTargetDB(t *testing.T) *DB { return d } -// targetTask creates a task and removes it, its pins and its approval rows at -// the end of the test (pins and approval rows outlive a task delete by design). +// targetTask silently defaults the gate on because approvals need a gated task. +// It removes the task, its pins and approval rows at the end of the test. func targetTask(t *testing.T, d *DB, opts TaskCreateOptions) *Task { t.Helper() + if opts.TargetGate == nil { + gateOn := true + opts.TargetGate = &gateOn + } task, err := d.CreateTaskWithOptions("target gate store", "pins and requests", opts) if err != nil { t.Fatal(err) @@ -41,6 +45,12 @@ func targetTask(t *testing.T, d *DB, opts TaskCreateOptions) *Task { return task } +func defaultOffTargetTask(t *testing.T, d *DB) *Task { + t.Helper() + gateOff := false + return targetTask(t, d, TaskCreateOptions{TargetGate: &gateOff}) +} + func targetConversation(t *testing.T, d *DB) *Conversation { t.Helper() c, err := d.CreateConversation("assistant", fmt.Sprintf("target gate %d", time.Now().UnixNano()), nil) @@ -283,14 +293,15 @@ func TestCloseTargetRequestsOnlyClosesPendingTargetsInScope(t *testing.T) { t.Fatal(err) } - const reason = "the target gate was switched off; nothing was pinned" + const reason = TargetGateDisabledReason ids, err := d.CloseTargetRequests(scope, reason) if err != nil || !slices.Equal(ids, []int64{closed}) { t.Fatalf("closed ids = %v, err=%v; want [%d]", ids, err, closed) } row, err := d.GetInterceptDetail(closed) if err != nil || row == nil || row.Status != "denied" || row.DecidedBy != "system" || row.Audit == nil || - row.Audit.EffectiveAction != "deny" || row.Audit.DecisionReason != reason || row.Audit.ExecutionStatus != "not_executed" { + row.Audit.EffectiveAction != "deny" || row.Audit.DecisionReason != reason || row.Audit.ExecutionStatus != "not_executed" || + len(row.Audit.Targets) != 1 || row.Audit.Targets[0].Outcome != "denied" || row.Audit.Approver != "" || row.Audit.ApproverAddr != "" { t.Fatalf("closed row = %+v, %v", row, err) } for name, id := range map[string]int64{"already decided target": decided, "other scope target": otherID, "classic ask": classic} { @@ -355,6 +366,88 @@ FOR EACH ROW EXECUTE FUNCTION test_refuse_target_pin()`); err != nil { } } +func TestResolveTargetRequestRefusesApprovalAfterTaskGateDisabled(t *testing.T) { + d := openTargetDB(t) + on, off := true, false + task := targetTask(t, d, TaskCreateOptions{TargetGate: &on}) + scope := TargetScopeRef{TaskID: task.ID} + id, created := openTargetRequest(t, d, scope, "late-approval.example.com", 443, "203.0.113.77") + if !created { + t.Fatal("target request was not created") + } + if updated, err := d.UpdateTask(task.ID, TaskPatch{TargetGate: &off}); err != nil || updated == nil || updated.TargetGate { + t.Fatalf("disable target gate: task=%+v err=%v", updated, err) + } + + if pin, ok, err := d.ResolveTargetRequest(id, true, "ARTEX", "198.51.100.9"); !errors.Is(err, ErrTargetGateDisabled) || ok || pin != nil { + t.Fatalf("late approval: pin=%+v ok=%v err=%v, want ErrTargetGateDisabled", pin, ok, err) + } + detail, err := d.GetInterceptDetail(id) + if err != nil || detail == nil || detail.Status != "denied" || detail.DecidedBy != "system" || detail.Audit == nil || + detail.Audit.DecisionReason != TargetGateDisabledReason || detail.Audit.EffectiveAction != "deny" || + detail.Audit.ExecutionStatus != "not_executed" || len(detail.Audit.Targets) != 1 || detail.Audit.Targets[0].Outcome != "denied" || + detail.Audit.Approver != "" || detail.Audit.ApproverAddr != "" { + t.Fatalf("late-approval row = %+v, %v; want unauthored system denial", detail, err) + } + if pins, err := d.ListTargetPins(scope); err != nil || len(pins) != 0 { + t.Fatalf("late approval pins = %+v, err=%v; want none", pins, err) + } +} + +func TestResolveTargetRequestWaitsForTaskGateLock(t *testing.T) { + d := openTargetDB(t) + on := true + task := targetTask(t, d, TaskCreateOptions{TargetGate: &on}) + scope := TargetScopeRef{TaskID: task.ID} + id, _ := openTargetRequest(t, d, scope, "locked-gate.example.com", 443, "203.0.113.78") + + blocker, err := d.Begin() + if err != nil { + t.Fatal(err) + } + defer blocker.Rollback() + var lockedID int64 + if err := blocker.QueryRow(`SELECT id FROM tasks WHERE id=$1 FOR UPDATE`, task.ID).Scan(&lockedID); err != nil { + t.Fatal(err) + } + if _, err := blocker.Exec(`UPDATE tasks SET target_gate=false WHERE id=$1`, task.ID); err != nil { + t.Fatal(err) + } + + type resolveResult struct { + pin *TargetPin + ok bool + err error + } + started := make(chan struct{}) + done := make(chan resolveResult, 1) + go func() { + close(started) + pin, ok, err := d.ResolveTargetRequest(id, true, "ARTEX", "198.51.100.9") + done <- resolveResult{pin: pin, ok: ok, err: err} + }() + <-started + select { + case got := <-done: + t.Fatalf("ResolveTargetRequest returned while task row was locked: %+v", got) + case <-time.After(100 * time.Millisecond): + } + if err := blocker.Commit(); err != nil { + t.Fatal(err) + } + select { + case got := <-done: + if !errors.Is(got.err, ErrTargetGateDisabled) || got.ok || got.pin != nil { + t.Fatalf("approval after lock release = %+v, want ErrTargetGateDisabled", got) + } + case <-time.After(5 * time.Second): + t.Fatal("ResolveTargetRequest remained blocked after commit") + } + if pins, err := d.ListTargetPins(scope); err != nil || len(pins) != 0 { + t.Fatalf("approval after gate-off commit pins = %+v, err=%v; want none", pins, err) + } +} + // Approving a request for a pinned key extends the pin: the new version holds // the old addresses plus the displayed ones. Addresses leave only by revocation. func TestTargetPinVersioningExtends(t *testing.T) { @@ -789,7 +882,15 @@ func TestConversationBatchDeleteRevokesOnlyDeletedIds(t *testing.T) { func TestTaskTargetGateDefaultsOff(t *testing.T) { d := openTargetDB(t) - task := targetTask(t, d, TaskCreateOptions{}) + task, err := d.CreateTaskWithOptions("target gate store", "pins and requests", TaskCreateOptions{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = d.DeleteTask(task.ID) + _, _ = d.Exec(`DELETE FROM target_pins WHERE task_id=$1`, task.ID) + _, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id=$1`, strconv.FormatInt(task.ID, 10)) + }) if task.TargetGate { t.Fatal("a task created without the option has the gate on") } @@ -797,8 +898,7 @@ func TestTaskTargetGateDefaultsOff(t *testing.T) { if err != nil || got == nil || got.TargetGate { t.Fatalf("stored task = %+v, %v; want the gate off", got, err) } - off := false - if explicit := targetTask(t, d, TaskCreateOptions{TargetGate: &off}); explicit.TargetGate { + if explicit := defaultOffTargetTask(t, d); explicit.TargetGate { t.Fatal("a task created with the option false has the gate on") } c := targetConversation(t, d) @@ -877,18 +977,22 @@ func TestConversationTargetGateRoundTrip(t *testing.T) { // pins. func TestRetestConversationCopiesFlagNotPins(t *testing.T) { d := openTargetDB(t) - on := true for _, tc := range []struct { name string - opts TaskCreateOptions want bool }{ - {"gate on", TaskCreateOptions{TargetGate: &on}, true}, - {"gate off", TaskCreateOptions{}, false}, + {"gate on", true}, + {"gate off", false}, } { t.Run(tc.name, func(t *testing.T) { - task := targetTask(t, d, tc.opts) + task := targetTask(t, d, TaskCreateOptions{}) approveTarget(t, d, TargetScopeRef{TaskID: task.ID}, "app.example.com", 443, "203.0.113.7") + if !tc.want { + off := false + if updated, err := d.UpdateTask(task.ID, TaskPatch{TargetGate: &off}); err != nil || updated == nil || updated.TargetGate { + t.Fatalf("disable target gate: task=%+v err=%v", updated, err) + } + } fid, err := d.AddFinding(task.ID, 0, "retest-gate", "gated finding", "high", "summary", "evidence", "worker", nil) if err != nil { t.Fatal(err) diff --git a/guard/target_gate_test.go b/guard/target_gate_test.go index 5752fdf07..ef458e3fb 100644 --- a/guard/target_gate_test.go +++ b/guard/target_gate_test.go @@ -332,7 +332,8 @@ func newGateDB(t *testing.T) *gateDB { t.Fatal(err) } t.Cleanup(func() { d.Close() }) - task, err := d.CreateTaskWithOptions("guard target gate", "the gate in the hook", db.TaskCreateOptions{}) + on := true + task, err := d.CreateTaskWithOptions("guard target gate", "the gate in the hook", db.TaskCreateOptions{TargetGate: &on}) if err != nil { t.Fatal(err) } diff --git a/intercept/intercept.go b/intercept/intercept.go index 89f711183..b9b3d7937 100644 --- a/intercept/intercept.go +++ b/intercept/intercept.go @@ -988,6 +988,10 @@ func (i *Interceptor) Decide(pendingID int64, allowed bool, approver, remoteAddr } else { resolved, err = i.db.ResolveInterceptBy(pendingID, status, action, reason, "human", approver, remoteAddr) } + if errors.Is(err, db.ErrTargetGateDisabled) { + i.pending.resolve(pendingID, false) + return ErrAlreadyDecided + } if err != nil { return err } diff --git a/intercept/target_request.go b/intercept/target_request.go index 632faf63f..8fefc4c55 100644 --- a/intercept/target_request.go +++ b/intercept/target_request.go @@ -364,12 +364,20 @@ func (i *Interceptor) awaitTarget(ctx context.Context, id int64, bound, ruleTime return waitGone } if err == nil && row.Status != "pending" { - // A human decision that won the race still counts. A system close - // caused by this same switch is the gate-off wait outcome. - if row.DecidedBy != "system" || enabled == nil || enabled() { + // A human decision that won the race still counts. + if row.DecidedBy != "system" { return row.Status } - return waitGateOff + if enabled != nil && !enabled() { + return waitGateOff + } + // The persisted reason wins when another instance closed the row + // before this instance observed the gate flag change. + detail, detailErr := i.db.GetInterceptDetail(id) + if detailErr == nil && detail != nil && detail.Audit != nil && detail.Audit.DecisionReason == db.TargetGateDisabledReason { + return waitGateOff + } + return row.Status } if enabled != nil && !enabled() { return waitGateOff diff --git a/intercept/target_request_test.go b/intercept/target_request_test.go index dd8e2aa0e..00d3e526c 100644 --- a/intercept/target_request_test.go +++ b/intercept/target_request_test.go @@ -70,7 +70,8 @@ func targetTestDB(t *testing.T) *db.DB { // on and the given wait bound. func taskScope(t *testing.T, d *db.DB, ic *Interceptor, wait time.Duration) TargetScope { t.Helper() - task, err := d.CreateTaskWithOptions("target requests", "request, wait, decide", db.TaskCreateOptions{}) + gateOn := true + task, err := d.CreateTaskWithOptions("target requests", "request, wait, decide", db.TaskCreateOptions{TargetGate: &gateOn}) if err != nil { t.Fatal(err) } @@ -435,6 +436,61 @@ func TestTargetGateSwitchOffReleasesPlainRequest(t *testing.T) { } } +func TestDecideLateApprovalUsesGateOffRelease(t *testing.T) { + oldPoll := targetPollInterval + targetPollInterval = 2 * time.Second + t.Cleanup(func() { targetPollInterval = oldPoll }) + + d := targetTestDB(t) + ic := New(d) + var enabled atomic.Bool + enabled.Store(true) + scope := taskScope(t, d, ic, 30*time.Second) + scope.Enabled = enabled.Load + call := request(context.Background(), ic, scope, nil, target("late-click.example.com", 443, "203.0.113.79")) + id := oneOpenRow(t, d, scope) + eventually(t, "the target waiter", func() bool { return waiters(ic, id) == 1 }) + probe := ic.pending.add(id) + defer ic.pending.remove(id, probe) + + taskID, err := strconv.ParseInt(scope.TaskID, 10, 64) + if err != nil { + t.Fatal(err) + } + off := false + if updated, err := d.UpdateTask(taskID, db.TaskPatch{TargetGate: &off}); err != nil || updated == nil || updated.TargetGate { + t.Fatalf("disable target gate: task=%+v err=%v", updated, err) + } + enabled.Store(false) + if err := ic.Decide(id, true, "ARTEX", "198.51.100.9"); !errors.Is(err, ErrAlreadyDecided) { + t.Fatalf("late approval = %v, want ErrAlreadyDecided", err) + } + select { + case allowed := <-probe: + if allowed { + t.Fatal("Decide woke a waiter with an approval") + } + case <-time.After(500 * time.Millisecond): + t.Fatal("Decide did not wake the local waiter with a denial") + } + select { + case res := <-call: + if res.Code != "" { + t.Fatalf("waiter after gate-off refusal = %+v, want release without a block", res) + } + case <-time.After(500 * time.Millisecond): + t.Fatal("waiter was not released promptly after gate-off refusal") + } + detail, err := d.GetInterceptDetail(id) + if err != nil || detail == nil || detail.Status != "denied" || detail.DecidedBy != "system" || detail.Audit == nil || + detail.Audit.DecisionReason != db.TargetGateDisabledReason || detail.Audit.Approver != "" || detail.Audit.ApproverAddr != "" { + t.Fatalf("late-click row = %+v, %v; want unauthored system denial", detail, err) + } + if got := pins(t, d, scope); len(got) != 0 { + t.Fatalf("late click created pins: %+v", got) + } +} + func TestTargetGateSwitchOffClosesMergedRequest(t *testing.T) { d := targetTestDB(t) ic := New(d) @@ -630,6 +686,23 @@ func TestCloseTargetRequestsWakesWaiter(t *testing.T) { } } +func TestCloseTargetRequestsGateOffReasonBeatsLaggingFlag(t *testing.T) { + d := targetTestDB(t) + ic := New(d) + scope := taskScope(t, d, ic, 30*time.Second) + scope.Enabled = func() bool { return true } + call := request(context.Background(), ic, scope, nil, target("lagging-flag.example.com", 443, "203.0.113.8")) + id := oneOpenRow(t, d, scope) + eventually(t, "the target wait", func() bool { return waiters(ic, id) == 1 }) + + if err := ic.CloseTargetRequests(scope.dbRef(t), db.TargetGateDisabledReason); err != nil { + t.Fatal(err) + } + if res := promptResult(t, call); res.Code != "" { + t.Fatalf("woken call with lagging gate flag = %+v, want release without a block", res) + } +} + // A timeout never pins, whatever the rule says: timeout_action = allow is // overridden on a merged row and the override is recorded. func TestTimeoutNeverPins(t *testing.T) { diff --git a/server/intercept_batch_decide_test.go b/server/intercept_batch_decide_test.go index 632c8618c..383684bc4 100644 --- a/server/intercept_batch_decide_test.go +++ b/server/intercept_batch_decide_test.go @@ -8,7 +8,6 @@ import ( "strconv" "strings" "testing" - "time" "github.com/Autumn-27/artex/db" "github.com/Autumn-27/artex/intercept" @@ -32,9 +31,15 @@ func TestInterceptBatchDecideHTTP(t *testing.T) { t.Fatal(err) } scope := "approval-http-batch-decide" - // A target request needs a numeric task scope; no foreign key ties it to tasks. - targetTask := 900000000 + time.Now().UnixNano()%1000000 + // A target request needs a task whose target gate is on. + on := true + target, err := d.CreateTaskWithOptions("approval batch decide", "target request fixture", db.TaskCreateOptions{TargetGate: &on}) + if err != nil { + t.Fatal(err) + } + targetTask := target.ID t.Cleanup(func() { + _ = d.DeleteTask(targetTask) _, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id=$1 OR task_id=$2`, scope, strconv.FormatInt(targetTask, 10)) }) do := func(method, path, body string) *httptest.ResponseRecorder { diff --git a/server/manager.go b/server/manager.go index cbe7cb74c..b85d3504c 100644 --- a/server/manager.go +++ b/server/manager.go @@ -1119,7 +1119,7 @@ func (m *Manager) UpdateTaskMetadata(taskID string, patch pgdb.TaskPatch) (*Task wasTargetGateEnabled := task.targetGate.Load() task.targetGate.Store(updated.TargetGate) if wasTargetGateEnabled && !updated.TargetGate { - if err := m.interceptor.CloseTargetRequests(pgdb.TargetScopeRef{TaskID: id}, "the target gate was switched off; nothing was pinned"); err != nil { + if err := m.interceptor.CloseTargetRequests(pgdb.TargetScopeRef{TaskID: id}, pgdb.TargetGateDisabledReason); err != nil { log.Printf("[target-gate] close requests for task %s: %v", taskID, err) } } diff --git a/server/target_gate_flag_test.go b/server/target_gate_flag_test.go index 3f0e68e50..5d42bf205 100644 --- a/server/target_gate_flag_test.go +++ b/server/target_gate_flag_test.go @@ -556,7 +556,8 @@ func TestConversationTargetGateOverHTTP(t *testing.T) { // address; decided_by stays the actor class. func TestInterceptDecideRecordsApproverOverHTTP(t *testing.T) { g := newGateServer(t) - task := g.newTask(t, db.TaskCreateOptions{}) + on := true + task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on}) scope := taskRef(t, task) pg := g.m.pg decide := func(id int64, decision string) int { @@ -638,7 +639,8 @@ func TestJWTSubject(t *testing.T) { func TestTargetPinRoutes(t *testing.T) { g := newGateServer(t) pg := g.m.pg - task, other := g.newTask(t, db.TaskCreateOptions{}), g.newTask(t, db.TaskCreateOptions{}) + on := true + task, other := g.newTask(t, db.TaskCreateOptions{TargetGate: &on}), g.newTask(t, db.TaskCreateOptions{TargetGate: &on}) conv, err := pg.CreateConversation("auto", "pin routes", nil) if err != nil { t.Fatal(err) diff --git a/server/target_gate_wiring_test.go b/server/target_gate_wiring_test.go index 872520ddb..6e7bfe90f 100644 --- a/server/target_gate_wiring_test.go +++ b/server/target_gate_wiring_test.go @@ -210,7 +210,8 @@ func TestTargetGateEndpointsFollowConfig(t *testing.T) { // request stays open and nothing is pinned. func TestInterceptDecideRefusesEmptyPinOverHTTP(t *testing.T) { g := newGateServer(t) - task := g.newTask(t, db.TaskCreateOptions{}) + on := true + task := g.newTask(t, db.TaskCreateOptions{TargetGate: &on}) scope := taskRef(t, task) id := openTargetRow(t, g.m.pg, scope, "no-address.example.com") code, body := g.do(t, "POST", fmt.Sprintf("/api/intercept/pending/%d/decide", id), `{"decision":"allowed"}`)