mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-19 22:50:55 +08:00
Intercept: always allow a pending Bash prefix (argv allow rule, code-owned denylist)
POST /api/intercept/pending/{id}/always-allow derives an argv allow rule from the stored pending row (never from the body), at priority -1000, reusing an identical enabled rule, and leaves the request pending. A code-owned denylist of interpreters, launchers, package managers, orchestration and destructive programs refuses such rules at creation, in the manual rule form, and neutralises argv allow rules at matching; argv deny and ask rules still match.
This commit is contained in:
+81
-2
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -413,6 +414,67 @@ func (s *Server) interceptDecide(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
// alwaysAllowPriority places "always allow" rules below every default and
|
||||
// manual rule, so any deny or ask rule that matches the same call wins.
|
||||
const alwaysAllowPriority = -1000
|
||||
|
||||
// interceptAlwaysAllow creates an argv allow rule from a pending Bash request.
|
||||
// The request body is never read: the command comes from the stored row, so a
|
||||
// caller cannot choose what gets allowed. The request itself stays pending.
|
||||
func (s *Server) interceptAlwaysAllow(w http.ResponseWriter, r *http.Request) {
|
||||
pg := s.pg(w)
|
||||
if pg == nil {
|
||||
return
|
||||
}
|
||||
id, ok := pathInt(r, "id")
|
||||
if !ok {
|
||||
writeErr(w, 400, "bad pending id")
|
||||
return
|
||||
}
|
||||
p, err := pg.GetInterceptPending(id)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if p == nil {
|
||||
writeErr(w, 404, "not found")
|
||||
return
|
||||
}
|
||||
if p.Status != "pending" {
|
||||
writeErr(w, 409, "the request is no longer pending")
|
||||
return
|
||||
}
|
||||
prefix, err := intercept.AlwaysAllowPrefix(p.ToolName, p.ToolInput)
|
||||
if err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
pattern, _ := json.Marshal(prefix)
|
||||
rules, err := pg.ListInterceptRules()
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
for _, rule := range rules {
|
||||
if rule.MatchType != "argv" || rule.Action != "allow" || !rule.Enabled || rule.MatchTarget != "tool_input" {
|
||||
continue
|
||||
}
|
||||
if tokens, err := intercept.ParseArgvPattern(rule.Pattern); err == nil && slices.Equal(tokens, prefix) {
|
||||
writeJSON(w, 200, map[string]any{"rule": rule, "created": false})
|
||||
return
|
||||
}
|
||||
}
|
||||
// Timeout fields take the rule form's defaults.
|
||||
rule, err := pg.CreateInterceptRule("always-allow: "+strings.Join(prefix, " "), "tool_input", "argv", string(pattern),
|
||||
"allow", "", alwaysAllowPriority, true, true, 60, "deny")
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.m.interceptor.Invalidate()
|
||||
writeJSON(w, 200, map[string]any{"rule": rule, "created": true})
|
||||
}
|
||||
|
||||
// --- target pins (hosts a human approved for one task or one conversation) ---
|
||||
|
||||
// taskPinScope resolves {id} to the pin scope of an existing task.
|
||||
@@ -667,9 +729,15 @@ func validateInterceptRuleReq(req interceptRuleReq) error {
|
||||
if req.MatchTarget != "tool_input" {
|
||||
return fmt.Errorf("an argv rule matches tool_input (the Bash command)")
|
||||
}
|
||||
if _, err := intercept.ParseArgvPattern(req.Pattern); err != nil {
|
||||
tokens, err := intercept.ParseArgvPattern(req.Pattern)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid argv pattern: %w", err)
|
||||
}
|
||||
if req.Action == "allow" {
|
||||
if err := intercept.CheckArgvAllow(tokens); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("match_type must be string, regex or argv")
|
||||
}
|
||||
@@ -708,7 +776,18 @@ func (s *Server) interceptDetail(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 404, "not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, detail)
|
||||
// The "always allow" button label: the prefix the endpoint would allow,
|
||||
// derived here so the UI never parses the command.
|
||||
out := struct {
|
||||
*db.InterceptDetail
|
||||
AlwaysAllowPrefix string `json:"always_allow_prefix,omitempty"`
|
||||
}{InterceptDetail: detail}
|
||||
if detail.Status == "pending" {
|
||||
if prefix, err := intercept.AlwaysAllowPrefix(detail.ToolName, detail.ToolInput); err == nil {
|
||||
out.AlwaysAllowPrefix = strings.Join(prefix, " ")
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// The navigation endpoint returns only the original call and its paired result.
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
)
|
||||
|
||||
// PG test: needs a PostgreSQL database (ARTEX_PG_DSN); skipped without one.
|
||||
// POST /api/intercept/pending/{id}/always-allow derives the rule from the
|
||||
// stored row, never from the body, and leaves the request pending.
|
||||
func TestInterceptAlwaysAllowPG(t *testing.T) {
|
||||
dsn, _, err := db.DSN()
|
||||
if err != nil {
|
||||
t.Skip("no test database configured")
|
||||
}
|
||||
d, err := db.Open(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
m := &Manager{pg: d, interceptor: intercept.New(d)}
|
||||
s := &Server{m: m, jwtKey: []byte("always-allow-test-key")}
|
||||
h := s.Handler()
|
||||
token, err := signJWT(s.jwtKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const scope = "always-allow-http"
|
||||
t.Cleanup(func() {
|
||||
_, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id=$1`, scope)
|
||||
_, _ = d.Exec(`DELETE FROM intercept_rules WHERE name LIKE 'always-allow: %'`)
|
||||
})
|
||||
pending := func(tool, cmd string) int64 {
|
||||
t.Helper()
|
||||
input, _ := json.Marshal(map[string]string{"command": cmd})
|
||||
id, err := d.CreateInterceptPending(0, 0, scope, "test", tool, input, "ask")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
post := func(id int64, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest("POST", fmt.Sprintf("/api/intercept/pending/%d/always-allow", id), strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
ruleCount := func() int {
|
||||
t.Helper()
|
||||
rules, err := d.ListInterceptRules()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return len(rules)
|
||||
}
|
||||
type result struct {
|
||||
Rule db.InterceptRule `json:"rule"`
|
||||
Created bool `json:"created"`
|
||||
}
|
||||
|
||||
id := pending("Bash", "gh pr list --json title")
|
||||
before := ruleCount()
|
||||
// The body carries dummy tokens and another command: all of it is ignored.
|
||||
dummy := `{"pending_id":1,"command":"rm -rf /","pattern":"[\"rm\"]","token":"dummy-token","access_token":"dummy"}`
|
||||
rec := post(id, dummy)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("always-allow: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
var got result
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := got.Rule
|
||||
if !got.Created || r.Pattern != `["gh","pr","list"]` || r.MatchType != "argv" || r.MatchTarget != "tool_input" ||
|
||||
r.Action != "allow" || !r.Enabled || r.Priority != -1000 || r.Name != "always-allow: gh pr list" ||
|
||||
!r.TimeoutEnabled || r.TimeoutSeconds != 60 || r.TimeoutAction != "deny" {
|
||||
t.Fatalf("rule %+v created=%v", r, got.Created)
|
||||
}
|
||||
if n := ruleCount(); n != before+1 {
|
||||
t.Fatalf("rule count %d, want %d", n, before+1)
|
||||
}
|
||||
if p, err := d.GetInterceptPending(id); err != nil || p == nil || p.Status != "pending" {
|
||||
t.Fatalf("pending row after always-allow: %+v %v", p, err)
|
||||
}
|
||||
// The cache was invalidated: the new rule matches at once.
|
||||
if dec, ok := m.interceptor.Match("Bash", []byte(`{"command":"gh pr list --limit 5"}`)); !ok || dec.RuleID != r.ID {
|
||||
t.Fatalf("match after creation: %+v %v", dec, ok)
|
||||
}
|
||||
|
||||
// An identical rule is reused, not duplicated.
|
||||
rec = post(pending("Bash", "gh pr list"), "")
|
||||
var again result
|
||||
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &again) != nil || again.Created || again.Rule.ID != r.ID {
|
||||
t.Fatalf("second always-allow: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if n := ruleCount(); n != before+1 {
|
||||
t.Fatalf("rule count after reuse %d, want %d", n, before+1)
|
||||
}
|
||||
|
||||
// Refusals: 400 and no rule.
|
||||
for name, c := range map[string][2]string{
|
||||
"not Bash": {"shell_open", "gh pr list"},
|
||||
"compound": {"Bash", "gh pr list; id"},
|
||||
"denylisted": {"Bash", "python3.11 -c 'import os'"},
|
||||
"path to env": {"Bash", "/usr/bin/env gh pr list"},
|
||||
} {
|
||||
rid := pending(c[0], c[1])
|
||||
if rec := post(rid, dummy); rec.Code != 400 {
|
||||
t.Errorf("%s: %d %s, want 400", name, rec.Code, rec.Body)
|
||||
}
|
||||
if p, _ := d.GetInterceptPending(rid); p == nil || p.Status != "pending" {
|
||||
t.Errorf("%s: pending row changed: %+v", name, p)
|
||||
}
|
||||
}
|
||||
if n := ruleCount(); n != before+1 {
|
||||
t.Fatalf("rule count after refusals %d, want %d", n, before+1)
|
||||
}
|
||||
|
||||
// A decided request is refused.
|
||||
decided := pending("Bash", "gh pr view 1")
|
||||
if err := d.DecideInterceptPending(decided, "denied"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec := post(decided, ""); rec.Code != 409 {
|
||||
t.Fatalf("decided request: %d %s, want 409", rec.Code, rec.Body)
|
||||
}
|
||||
|
||||
// The detail carries the prefix for the button label.
|
||||
req := httptest.NewRequest("GET", fmt.Sprintf("/api/intercept/history/%d", id), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
drec := httptest.NewRecorder()
|
||||
h.ServeHTTP(drec, req)
|
||||
var detail struct {
|
||||
Status string `json:"status"`
|
||||
AlwaysAllowPrefix string `json:"always_allow_prefix"`
|
||||
}
|
||||
if drec.Code != 200 || json.Unmarshal(drec.Body.Bytes(), &detail) != nil || detail.AlwaysAllowPrefix != "gh pr list" || detail.Status != "pending" {
|
||||
t.Fatalf("detail: %d %s", drec.Code, drec.Body)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package server
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
)
|
||||
|
||||
func TestValidateArgvRuleReq(t *testing.T) {
|
||||
base := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: `["git","push"]`, Action: "allow"}
|
||||
@@ -23,3 +27,28 @@ func TestValidateArgvRuleReq(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The manual rule form refuses an argv allow rule for a denylisted program,
|
||||
// with the message of the "always allow" endpoint; deny and ask stay creatable.
|
||||
func TestValidateArgvAllowDenylist(t *testing.T) {
|
||||
for _, pattern := range []string{`["python"]`, `["python3.11"]`, `["/usr/bin/env"]`, `["find"]`, `["docker","run"]`} {
|
||||
req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"}
|
||||
tokens, _ := intercept.ParseArgvPattern(pattern)
|
||||
want := intercept.CheckArgvAllow(tokens)
|
||||
if err := validateInterceptRuleReq(req); err == nil || want == nil || err.Error() != want.Error() {
|
||||
t.Errorf("allow %s: %v, want %v", pattern, err, want)
|
||||
}
|
||||
for _, action := range []string{"deny", "ask"} {
|
||||
req.Action = action
|
||||
if err := validateInterceptRuleReq(req); err != nil {
|
||||
t.Errorf("%s %s refused: %v", action, pattern, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, pattern := range []string{`["nmap"]`, `["git","push"]`} {
|
||||
req := interceptRuleReq{Name: "r", MatchTarget: "tool_input", MatchType: "argv", Pattern: pattern, Action: "allow"}
|
||||
if err := validateInterceptRuleReq(req); err != nil {
|
||||
t.Errorf("allow %s refused: %v", pattern, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -958,6 +958,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/intercept/pending", s.interceptListPending)
|
||||
mux.HandleFunc("GET /api/intercept/pending/{id}", s.interceptGetOne)
|
||||
mux.HandleFunc("POST /api/intercept/pending/{id}/decide", s.interceptDecide)
|
||||
mux.HandleFunc("POST /api/intercept/pending/{id}/always-allow", s.interceptAlwaysAllow) // creates an argv allow rule; the request stays pending
|
||||
mux.HandleFunc("GET /api/intercept/history", s.interceptHistory)
|
||||
mux.HandleFunc("GET /api/intercept/history/{id}", s.interceptDetail)
|
||||
mux.HandleFunc("GET /api/intercept/history/{id}/execution", s.interceptExecution)
|
||||
|
||||
Reference in New Issue
Block a user