mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 04:14:15 +00:00
Decide already answers ErrAlreadyDecided when ResolveTargetRequest turns an approval on a gate-off or deleted task into a system denial. It now wraps db.ErrTargetGateDisabled as well, so the 409 says why the click was refused; errors.Is(err, ErrAlreadyDecided) still holds for every caller. Tests: - TargetScope.ref() accepts exactly one positive task or conversation id; - a click after a merged target request or a classic ask timed out is refused, wakes nobody and leaves the system timeout unauthored; - the task-row target_gate check refuses approvals on a gate-off or deleted task (system denial, no approver, no pin) and still pins on a gated task; - a click blocked behind a committing timeout on the row lock is refused, and a click racing the timeout never lets both win. CHANGELOG: mention the refused late approval in the #804 entry.
324 lines
11 KiB
Go
324 lines
11 KiB
Go
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)
|
|
}
|