mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 05:03:56 +08:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9af8b37d29 | ||
|
|
85dfd11c19 | ||
|
|
e9bd4cae0d | ||
|
|
936f8c6a74 |
@@ -20,6 +20,7 @@ All notable changes to this project are documented in this file. The format is b
|
||||
- **A command that exits 124 no longer removes the Docker worker.** The runner treated every exit code 124 as its own timeout and removed the task's worker container, which also stopped the task's background jobs. Commands such as `timeout 5 curl ...` exit 124 by themselves. An exit 124 now counts as a runner timeout only when the command ran for at least `timeout_ms`.
|
||||
- **An `exact_ip` task allow rule grants sandbox egress**: the egress allowlist read task allow rules of kind `ip`, which the rule tables never store, so an `exact_ip` allow rule granted nothing. A task scoped to one private address (`10.0.0.5`) could not reach it from the sandbox, directly or through a name resolving only to it. `exact_ip` allow rules now join the allowed CIDRs as a host prefix, like `cidr` allow rules.
|
||||
- **Malformed domain patterns are refused on asset interception rules.** `exact_domain` and `domain_suffix` patterns (global rules, task rules, task creation and task templates) are now answered 400 when they contain whitespace or a control character, an empty label (`a..example.com`, a leading dot, or more than one trailing dot: `example.com..` used to be stored as `example.com.`, a form raw consumers do not match), a single label (`com`, refused for `domain_suffix` too, so a TLD-wide rule is out of scope), a URL or wildcard character (`*`, `/`, `:`; `exact_domain` took `https://example.com` or `*.example.com` and never matched), an IP literal or an all-digit last label (`192.0.2.1`, `127.1`; use `exact_ip` or `cidr`), or a non-ASCII or `xn--` label the IDNA profile refuses (`_bücher.example`), which has no single canonical spelling. `fuzzy_domain` patterns refuse whitespace, control characters and a doubled dot (including the ideographic and fullwidth dots after canonicalisation), and keep leading and trailing dots and single labels (`.gov.cn`). Valid domains are stored exactly as before, and the matcher still canonicalizes targets leniently. Existing rows are not migrated. The intercept layer now uses `idna.Lookup` for target names, the profile the rules use; the previous profile had the same options, so target normalisation does not change, and its comment wrongly said it accepted underscore labels: both profiles refuse them, and such a name is compared lower-cased as written.
|
||||
- **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. An approval clicked after the switch (before the close, or on another instance) is refused under the task row lock and recorded as a system denial without approver; the decide API answers 409 (#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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
+121
-8
@@ -185,6 +185,84 @@ 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.
|
||||
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
|
||||
}
|
||||
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
|
||||
ORDER BY id FOR UPDATE`, taskKey, scope.ConversationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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)
|
||||
}
|
||||
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
|
||||
// gated call asks for when one of its targets has no pin that covers it.
|
||||
type TargetRequest struct {
|
||||
@@ -256,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
|
||||
@@ -281,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 {
|
||||
|
||||
+154
-10
@@ -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)
|
||||
@@ -268,6 +278,47 @@ 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 = 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" ||
|
||||
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} {
|
||||
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.
|
||||
@@ -315,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) {
|
||||
@@ -749,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")
|
||||
}
|
||||
@@ -757,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)
|
||||
@@ -837,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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -988,6 +988,12 @@ 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) {
|
||||
// The click was turned into a system denial (no pin, no approver):
|
||||
// report it as already decided, with the reason, and never as a success.
|
||||
i.pending.resolve(pendingID, false)
|
||||
return fmt.Errorf("%w: %w", ErrAlreadyDecided, err)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
// ref names exactly one scope: one positive task id or one positive
|
||||
// conversation id, the shape the store accepts.
|
||||
func TestTargetScopeRef(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
scope TargetScope
|
||||
want db.TargetScopeRef
|
||||
}{
|
||||
"task": {TargetScope{TaskID: "7"}, db.TargetScopeRef{TaskID: 7}},
|
||||
"conversation": {TargetScope{ConversationID: 9}, db.TargetScopeRef{ConversationID: 9}},
|
||||
} {
|
||||
got, err := tc.scope.ref()
|
||||
if err != nil || got != tc.want {
|
||||
t.Errorf("%s: ref() = %+v, %v; want %+v", name, got, err, tc.want)
|
||||
}
|
||||
}
|
||||
for name, scope := range map[string]TargetScope{
|
||||
"empty": {},
|
||||
"task and conversation": {TaskID: "7", ConversationID: 9},
|
||||
"task zero": {TaskID: "0"},
|
||||
"task negative": {TaskID: "-3"},
|
||||
"task not a number": {TaskID: "seven"},
|
||||
"conversation negative": {ConversationID: -1},
|
||||
} {
|
||||
if got, err := scope.ref(); err == nil {
|
||||
t.Errorf("%s: ref() = %+v, want an error", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// openNoWaitRequest opens one target request for host in scope and returns its
|
||||
// id. The call does not wait, so nobody is attached to the row.
|
||||
func openNoWaitRequest(t *testing.T, ic *Interceptor, scope TargetScope, host string) int64 {
|
||||
t.Helper()
|
||||
scope.WaitBound = 0
|
||||
res := ic.RequestTargets(context.Background(), scope, "WebFetch", webFetchInput, []TargetRequest{target(host, 443, "203.0.113.7")}, nil)
|
||||
if res.Code != TargetApprovalPending || res.PendingID == 0 {
|
||||
t.Fatalf("opening a request for %s: %+v", host, res)
|
||||
}
|
||||
return res.PendingID
|
||||
}
|
||||
|
||||
// noWake fails if anything is delivered to a waiter of the row.
|
||||
func noWake(t *testing.T, probe <-chan bool) {
|
||||
t.Helper()
|
||||
select {
|
||||
case allowed := <-probe:
|
||||
t.Fatalf("a refused click woke the waiters (allowed=%v)", allowed)
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
// unauthoredRow checks that the row still holds the system decision: no
|
||||
// approver, no approver address.
|
||||
func unauthoredRow(t *testing.T, d *db.DB, id int64, status, reason string) {
|
||||
t.Helper()
|
||||
row, err := d.GetInterceptDetail(id)
|
||||
if err != nil || row == nil || row.Status != status || row.DecidedBy != "system" || row.Audit == nil ||
|
||||
row.Audit.EffectiveAction != "deny" || row.Audit.Approver != "" || row.Audit.ApproverAddr != "" {
|
||||
t.Fatalf("row %d = %+v, %v; want a %s system decision without approver", id, row, err, status)
|
||||
}
|
||||
if reason != "" && row.Audit.DecisionReason != reason {
|
||||
t.Fatalf("row %d reason = %q, want %q", id, row.Audit.DecisionReason, reason)
|
||||
}
|
||||
}
|
||||
|
||||
// A click that lands after the request timed out is refused: Decide reports it
|
||||
// as already decided, wakes nobody, and the row keeps the system timeout.
|
||||
func TestDecideLateClickAfterTimeoutIsRefused(t *testing.T) {
|
||||
d := targetTestDB(t)
|
||||
ic := New(d)
|
||||
|
||||
t.Run("merged target request", func(t *testing.T) {
|
||||
scope := taskScope(t, d, ic, time.Minute)
|
||||
ask := askRule(t, d, true, 1, "allow")
|
||||
res := result(t, request(context.Background(), ic, scope, &ask, target("late-timeout.example.com", 443, "203.0.113.7")))
|
||||
if res.Code != TargetDenied || res.PendingID == 0 {
|
||||
t.Fatalf("call after the rule timeout: %+v, want %s", res, TargetDenied)
|
||||
}
|
||||
before, err := d.GetInterceptDetail(res.PendingID)
|
||||
if err != nil || before == nil || before.Status != "timeout" {
|
||||
t.Fatalf("timed-out row = %+v, %v", before, err)
|
||||
}
|
||||
probe := ic.pending.add(res.PendingID)
|
||||
defer ic.pending.remove(res.PendingID, probe)
|
||||
if err := ic.Decide(res.PendingID, true, "ARTEX", "198.51.100.9"); !errors.Is(err, ErrAlreadyDecided) {
|
||||
t.Fatalf("late click = %v, want ErrAlreadyDecided", err)
|
||||
}
|
||||
noWake(t, probe)
|
||||
unauthoredRow(t, d, res.PendingID, "timeout", before.Audit.DecisionReason)
|
||||
if got := pins(t, d, scope); len(got) != 0 {
|
||||
t.Fatalf("a late click after a timeout pinned: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("classic ask", func(t *testing.T) {
|
||||
scope := taskScope(t, d, ic, time.Minute)
|
||||
ctx := WithTaskContext(context.Background(), scope.TaskID, "work#1", nil)
|
||||
dec := Decision{Action: "ask", Message: "classic ask", TimeoutEnabled: true, TimeoutSeconds: 1, TimeoutAction: "deny"}
|
||||
if ic.HandleAsk(ctx, 0, dec, "Bash", []byte(`{"command":"id"}`)) {
|
||||
t.Fatal("a timed-out ask with timeout_action deny was allowed")
|
||||
}
|
||||
var id int64
|
||||
if err := d.QueryRow(`SELECT id FROM intercept_pending WHERE task_id=$1 AND target_key IS NULL`, scope.TaskID).Scan(&id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
probe := ic.pending.add(id)
|
||||
defer ic.pending.remove(id, probe)
|
||||
if err := ic.Decide(id, true, "ARTEX", "198.51.100.9"); !errors.Is(err, ErrAlreadyDecided) {
|
||||
t.Fatalf("late click = %v, want ErrAlreadyDecided", err)
|
||||
}
|
||||
noWake(t, probe)
|
||||
unauthoredRow(t, d, id, "timeout", "")
|
||||
})
|
||||
}
|
||||
|
||||
// The task-row target_gate check refuses an approval for a task whose gate was
|
||||
// switched off (the close of its open requests has not run): the click is
|
||||
// turned into a system denial, Decide reports it as already decided and says
|
||||
// why, waiters are woken with a denial, and nothing is pinned or attributed to
|
||||
// the clicker. A deleted task settles its open requests itself, so a click
|
||||
// after the deletion is refused as already decided and writes nothing.
|
||||
func TestDecideRefusesApprovalOutsideTargetGate(t *testing.T) {
|
||||
d := targetTestDB(t)
|
||||
ic := New(d)
|
||||
open := func(t *testing.T, host string) (TargetScope, int64, int64) {
|
||||
t.Helper()
|
||||
scope := taskScope(t, d, ic, 0)
|
||||
id := openNoWaitRequest(t, ic, scope, host)
|
||||
taskID, err := strconv.ParseInt(scope.TaskID, 10, 64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return scope, taskID, id
|
||||
}
|
||||
|
||||
t.Run("gate switched off", func(t *testing.T) {
|
||||
scope, taskID, id := open(t, "gate-off.example.com")
|
||||
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)
|
||||
}
|
||||
probe := ic.pending.add(id)
|
||||
defer ic.pending.remove(id, probe)
|
||||
err := ic.Decide(id, true, "ARTEX", "198.51.100.9")
|
||||
if !errors.Is(err, ErrAlreadyDecided) || !errors.Is(err, db.ErrTargetGateDisabled) {
|
||||
t.Fatalf("approval outside the gate = %v, want ErrAlreadyDecided carrying ErrTargetGateDisabled", err)
|
||||
}
|
||||
select {
|
||||
case allowed := <-probe:
|
||||
if allowed {
|
||||
t.Fatal("a refused approval woke the waiters with allowed=true")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("a refused approval did not wake the waiters with a denial")
|
||||
}
|
||||
unauthoredRow(t, d, id, "denied", db.TargetGateDisabledReason)
|
||||
if got := pins(t, d, scope); len(got) != 0 {
|
||||
t.Fatalf("an approval outside the gate pinned: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("task deleted", func(t *testing.T) {
|
||||
scope, taskID, id := open(t, "deleted-task.example.com")
|
||||
if err := d.DeleteTask(taskID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
probe := ic.pending.add(id)
|
||||
defer ic.pending.remove(id, probe)
|
||||
if err := ic.Decide(id, true, "ARTEX", "198.51.100.9"); !errors.Is(err, ErrAlreadyDecided) {
|
||||
t.Fatalf("approval after the task was deleted = %v, want ErrAlreadyDecided", err)
|
||||
}
|
||||
noWake(t, probe)
|
||||
unauthoredRow(t, d, id, "denied", "task deleted")
|
||||
if got := pins(t, d, scope); len(got) != 0 {
|
||||
t.Fatalf("an approval after the task was deleted pinned: %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("gate on", func(t *testing.T) {
|
||||
scope := taskScope(t, d, ic, 0)
|
||||
id := openNoWaitRequest(t, ic, scope, "in-gate.example.com")
|
||||
if err := ic.Decide(id, true, "ARTEX", "198.51.100.9"); err != nil {
|
||||
t.Fatalf("approval on a gated task = %v", err)
|
||||
}
|
||||
if got := pins(t, d, scope); len(got) != 1 {
|
||||
t.Fatalf("pins after approval on a gated task = %+v, want one", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A click and the system timeout that settle the same row serialize on its
|
||||
// row lock: a click blocked behind a timeout that commits is refused and
|
||||
// leaves the timeout as written.
|
||||
func TestDecideBlockedBehindTimeoutIsRefused(t *testing.T) {
|
||||
d := targetTestDB(t)
|
||||
ic := New(d)
|
||||
scope := taskScope(t, d, ic, 0)
|
||||
id := openNoWaitRequest(t, ic, scope, "locked-timeout.example.com")
|
||||
|
||||
blocker, err := d.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer blocker.Rollback()
|
||||
var locked int64
|
||||
if err := blocker.QueryRow(`SELECT id FROM intercept_pending WHERE id=$1 FOR UPDATE`, id).Scan(&locked); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const reason = "no approval within the wait bound"
|
||||
if _, err := blocker.Exec(`UPDATE intercept_pending SET status='timeout', decided_at=NOW(), decided_by='system',
|
||||
audit=audit || jsonb_build_object('effective_action','deny','decision_reason',$2::text,'execution_status','not_executed')
|
||||
WHERE id=$1`, id, reason); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
probe := ic.pending.add(id)
|
||||
defer ic.pending.remove(id, probe)
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- ic.Decide(id, true, "ARTEX", "198.51.100.9") }()
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatalf("Decide returned %v while the timeout held the row lock", err)
|
||||
case <-time.After(300 * time.Millisecond):
|
||||
}
|
||||
if err := blocker.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, ErrAlreadyDecided) {
|
||||
t.Fatalf("click behind a committed timeout = %v, want ErrAlreadyDecided", err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("Decide stayed blocked after the timeout committed")
|
||||
}
|
||||
noWake(t, probe)
|
||||
unauthoredRow(t, d, id, "timeout", reason)
|
||||
if got := pins(t, d, scope); len(got) != 0 {
|
||||
t.Fatalf("a click behind a timeout pinned: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Racing a click against the system timeout of the same row: exactly one wins.
|
||||
// When the timeout wins the click is refused and writes nothing; when the click
|
||||
// wins the timeout writes nothing.
|
||||
func TestDecideRacesTimeoutExactlyOneWins(t *testing.T) {
|
||||
d := targetTestDB(t)
|
||||
ic := New(d)
|
||||
scope := taskScope(t, d, ic, 0)
|
||||
wins := map[string]int{}
|
||||
for n := 0; n < 20; n++ {
|
||||
host := fmt.Sprintf("race%d.example.com", n)
|
||||
id := openNoWaitRequest(t, ic, scope, host)
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
start = make(chan struct{})
|
||||
decideErr error
|
||||
settled bool
|
||||
settleErr error
|
||||
)
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
decideErr = ic.Decide(id, true, "ARTEX", "198.51.100.9")
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
// A varying head start for the click, so both orders occur.
|
||||
time.Sleep(time.Duration(n%10) * 2 * time.Millisecond)
|
||||
settled, settleErr = ic.settleTargetRequest(id, "timeout", "no approval within the wait bound")
|
||||
}()
|
||||
close(start)
|
||||
wg.Wait()
|
||||
if settleErr != nil {
|
||||
t.Fatal(settleErr)
|
||||
}
|
||||
row, err := d.GetInterceptDetail(id)
|
||||
if err != nil || row == nil || row.Audit == nil {
|
||||
t.Fatalf("row %d: %+v, %v", id, row, err)
|
||||
}
|
||||
var hostPins int
|
||||
for _, p := range pins(t, d, scope) {
|
||||
if p.Host == host {
|
||||
hostPins++
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case settled && decideErr == nil:
|
||||
t.Fatalf("round %d: both the click and the timeout won", n)
|
||||
case settled:
|
||||
wins["timeout"]++
|
||||
if !errors.Is(decideErr, ErrAlreadyDecided) {
|
||||
t.Fatalf("round %d: click after the timeout = %v, want ErrAlreadyDecided", n, decideErr)
|
||||
}
|
||||
if row.Status != "timeout" || row.DecidedBy != "system" || row.Audit.Approver != "" || row.Audit.ApproverAddr != "" || hostPins != 0 {
|
||||
t.Fatalf("round %d: timeout won but row = %+v, %d pins", n, row, hostPins)
|
||||
}
|
||||
case decideErr == nil:
|
||||
wins["click"]++
|
||||
if row.Status != "allowed" || row.DecidedBy != "human" || row.Audit.Approver != "ARTEX" || hostPins != 1 {
|
||||
t.Fatalf("round %d: click won but row = %+v, %d pins", n, row, hostPins)
|
||||
}
|
||||
default:
|
||||
t.Fatalf("round %d: neither won: click %v, row %+v", n, decideErr, row)
|
||||
}
|
||||
}
|
||||
t.Logf("wins: %v", wins)
|
||||
}
|
||||
+105
-9
@@ -64,14 +64,25 @@ type TargetResult struct {
|
||||
}
|
||||
|
||||
func (s TargetScope) ref() (db.TargetScopeRef, error) {
|
||||
ref := db.TargetScopeRef{ConversationID: s.ConversationID}
|
||||
ref := db.TargetScopeRef{}
|
||||
if s.TaskID != "" {
|
||||
if s.ConversationID != 0 {
|
||||
return ref, fmt.Errorf("target scope: task and conversation scopes cannot be combined")
|
||||
}
|
||||
id, err := strconv.ParseInt(s.TaskID, 10, 64)
|
||||
if err != nil {
|
||||
return ref, fmt.Errorf("target scope: task id %q: %w", s.TaskID, err)
|
||||
}
|
||||
if id <= 0 {
|
||||
return ref, fmt.Errorf("target scope: task id must be positive")
|
||||
}
|
||||
ref.TaskID = id
|
||||
return ref, nil
|
||||
}
|
||||
if s.ConversationID <= 0 {
|
||||
return ref, fmt.Errorf("target scope: a positive task id or conversation id is required")
|
||||
}
|
||||
ref.ConversationID = s.ConversationID
|
||||
return ref, nil
|
||||
}
|
||||
|
||||
@@ -121,6 +132,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 +172,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 +214,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 +244,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 +260,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 +356,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,8 +375,24 @@ 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.
|
||||
if row.DecidedBy != "system" {
|
||||
return row.Status
|
||||
}
|
||||
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
|
||||
}
|
||||
select {
|
||||
case <-ch:
|
||||
case <-poll.C:
|
||||
@@ -334,12 +410,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 {
|
||||
|
||||
@@ -2,6 +2,7 @@ package intercept
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
@@ -69,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)
|
||||
}
|
||||
@@ -116,6 +118,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 +180,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 +399,310 @@ 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 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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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}, pgdb.TargetGateDisabledReason); err != nil {
|
||||
log.Printf("[target-gate] close requests for task %s: %v", taskID, err)
|
||||
}
|
||||
}
|
||||
return task, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -176,6 +176,51 @@ func TestTargetGateChangeActivity(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
|
||||
@@ -533,7 +578,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 {
|
||||
@@ -615,7 +661,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)
|
||||
@@ -697,7 +744,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")
|
||||
|
||||
@@ -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"}`)
|
||||
|
||||
Reference in New Issue
Block a user