feat(server): add admin API for tampering hooks (CRUD, toggle, versions, rollback, dry-run)

This commit is contained in:
BaaRai
2026-11-21 00:48:27 +01:00
parent d522a9cc47
commit 76e936d8f3
4 changed files with 629 additions and 0 deletions
+5
View File
@@ -266,6 +266,10 @@ type Manager struct {
rewriteMu sync.Mutex
rewriteSet atomic.Pointer[rewrite.Set]
rewriteErrors rewrite.ErrorLog
// Capture-proxy constrained Go tampering hooks (P4.2), behind ARTEX_TAMPER_HOOKS_ENABLED.
hookMu sync.Mutex
hookSet atomic.Pointer[traffic.HookSet]
hookLoadErrs map[int64]string
companyMu sync.Mutex // serializes task/company-scope commits with live handle registration
// taskStateMu preserves commit order between PostgreSQL lifecycle writes and
@@ -463,6 +467,7 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
if tr != nil {
m.traffic = tr
m.reloadRewriteRules() // in place before the proxy accepts a connection
m.reloadTamperHooks() // opt-in behind ARTEX_TAMPER_HOOKS_ENABLED=1
if scfg, ok := traffic.SOCKS5ConfigFromEnv(); ok {
scfg.DialContext = m.interceptor.DialSOCKS5
scfg.ResolveUDP4 = m.interceptor.ResolveUDP4
+10
View File
@@ -1033,6 +1033,16 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("DELETE /api/traffic/rewrite-rules/{id}", s.rewriteDeleteRule)
mux.HandleFunc("POST /api/traffic/rewrite-rules/{id}/toggle", s.rewriteToggleRule)
// capture-proxy constrained Go tampering hooks (P4.2, operator-only, opt-in via ARTEX_TAMPER_HOOKS_ENABLED)
mux.HandleFunc("GET /api/traffic/hooks", s.tamperListHooks)
mux.HandleFunc("POST /api/traffic/hooks", s.tamperCreateHook)
mux.HandleFunc("PUT /api/traffic/hooks/{id}", s.tamperUpdateHook)
mux.HandleFunc("DELETE /api/traffic/hooks/{id}", s.tamperDeleteHook)
mux.HandleFunc("POST /api/traffic/hooks/{id}/toggle", s.tamperToggleHook)
mux.HandleFunc("GET /api/traffic/hooks/{id}/versions", s.tamperListHookVersions)
mux.HandleFunc("POST /api/traffic/hooks/{id}/rollback", s.tamperRollbackHook)
mux.HandleFunc("POST /api/traffic/hooks/dry-run", s.tamperDryRunHook)
// asset interception rule management (global blocklist: domains/IPs/URLs/CIDRs)
mux.HandleFunc("GET /api/asset-intercept/rules", s.assetInterceptListRules)
mux.HandleFunc("POST /api/asset-intercept/rules", s.assetInterceptCreateRule)
+457
View File
@@ -0,0 +1,457 @@
package server
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"time"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/traffic"
"github.com/Autumn-27/artex/traffic/rewrite"
)
// --- capture-proxy constrained Go tampering hooks (P4.2) ---
// Global configuration, operator/admin only, never exposed as an agent tool.
// Execution is opt-in behind ARTEX_TAMPER_HOOKS_ENABLED=1 (off by default).
type tamperHookReq struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Phase rewrite.Phase `json:"phase"`
Priority int `json:"priority"`
Matchers rewrite.Matchers `json:"matchers"`
Source string `json:"source"`
Note string `json:"note"`
}
type tamperHookDTO struct {
ID int64 `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Phase string `json:"phase"`
Priority int `json:"priority"`
Matchers rewrite.Matchers `json:"matchers"`
Source string `json:"source"`
SourceSHA256 string `json:"source_sha256"`
Version int `json:"version"`
Note string `json:"note"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LoadError string `json:"load_error,omitempty"`
LastError *rewrite.LastError `json:"last_error,omitempty"`
}
type tamperHookVersionDTO struct {
ID int64 `json:"id"`
HookID int64 `json:"hook_id"`
Version int `json:"version"`
Name string `json:"name"`
Phase string `json:"phase"`
Priority int `json:"priority"`
Matchers rewrite.Matchers `json:"matchers"`
Source string `json:"source"`
SourceSHA256 string `json:"source_sha256"`
Note string `json:"note"`
CreatedAt time.Time `json:"created_at"`
}
type tamperDryRunReq struct {
HookID int64 `json:"hook_id,omitempty"`
Name string `json:"name,omitempty"`
Phase rewrite.Phase `json:"phase,omitempty"`
Matchers rewrite.Matchers `json:"matchers"`
Source string `json:"source,omitempty"`
Request struct {
Method string `json:"method"`
URL string `json:"url"`
Headers map[string][]string `json:"headers"`
Body string `json:"body"`
} `json:"request"`
Response struct {
Status int `json:"status"`
Headers map[string][]string `json:"headers"`
Body string `json:"body"`
} `json:"response"`
}
var errTamperHookInvalid = errors.New("invalid tampering hook")
func tamperHookInvalid(err error) error { return fmt.Errorf("%w: %v", errTamperHookInvalid, err) }
func tamperHookWriteErr(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, sql.ErrNoRows):
writeErr(w, 404, "tampering hook not found")
case errors.Is(err, errTamperHookInvalid), errors.Is(err, db.ErrTrafficTamperHookLimit), errors.Is(err, db.ErrTrafficTamperHookEnabledLimit):
writeErr(w, 400, err.Error())
default:
writeErr(w, 500, err.Error())
}
}
func decodeTamperHookRow(row db.TrafficTamperHook) (traffic.HookDef, error) {
var m rewrite.Matchers
if len(row.Matchers) > 0 {
if err := json.Unmarshal(row.Matchers, &m); err != nil {
return traffic.HookDef{}, err
}
}
return traffic.HookDef{
ID: row.ID, Name: row.Name, Enabled: row.Enabled, Phase: rewrite.Phase(row.Phase),
Priority: row.Priority, Matchers: m, Source: row.Source, SourceSHA256: row.SourceSHA256,
Version: row.Version, Note: row.Note,
}, nil
}
func (m *Manager) tamperHookDTO(row db.TrafficTamperHook) tamperHookDTO {
var matchers rewrite.Matchers
_ = json.Unmarshal(row.Matchers, &matchers)
out := tamperHookDTO{
ID: row.ID, Name: row.Name, Enabled: row.Enabled, Phase: row.Phase,
Priority: row.Priority, Matchers: matchers, Source: row.Source,
SourceSHA256: row.SourceSHA256, Version: row.Version, Note: row.Note,
CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
}
m.hookMu.Lock()
if m.hookLoadErrs != nil {
out.LoadError = m.hookLoadErrs[row.ID]
}
m.hookMu.Unlock()
if hs := m.hookSet.Load(); hs != nil {
out.LastError = hs.LastError(row.ID)
}
return out
}
// reloadTamperHooks compiles enabled hooks into an immutable snapshot and swaps
// it onto the capture proxy. When ARTEX_TAMPER_HOOKS_ENABLED is off (default),
// zero hooks are loaded and the proxy receives nil (baseline fast path).
func (m *Manager) reloadTamperHooks() {
m.hookMu.Lock()
defer m.hookMu.Unlock()
if !traffic.TamperHooksEnabledFromEnv() {
m.hookLoadErrs = nil
m.hookSet.Store(nil)
if m.traffic != nil {
m.traffic.SetTamperHooks(nil)
}
return
}
rows, err := m.pg.ListTrafficTamperHooks()
if err != nil {
log.Printf("[traffic] tampering hooks not reloaded: %v", err)
return
}
defs := make([]traffic.HookDef, 0, len(rows))
decodeErrs := map[int64]string{}
for _, row := range rows {
d, err := decodeTamperHookRow(row)
if err != nil {
if row.Enabled {
decodeErrs[row.ID] = "the stored hook cannot be decoded"
}
continue
}
defs = append(defs, d)
}
hs, loadErrs := traffic.CompileHooks(defs, db.TrafficTraceKey())
for id, msg := range decodeErrs {
loadErrs[id] = msg
}
for id, msg := range loadErrs {
log.Printf("[traffic] tampering hook %d not loaded: %s", id, msg)
}
m.hookLoadErrs = loadErrs
m.hookSet.Store(hs)
if m.traffic != nil {
m.traffic.SetTamperHooks(hs)
}
}
func (s *Server) tamperListHooks(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
rows, err := pg.ListTrafficTamperHooks()
if err != nil {
writeErr(w, 500, err.Error())
return
}
hooks := make([]tamperHookDTO, 0, len(rows))
for _, row := range rows {
hooks = append(hooks, s.m.tamperHookDTO(row))
}
writeJSON(w, 200, map[string]any{
"hooks": hooks,
"enabled_by_env": traffic.TamperHooksEnabledFromEnv(),
})
}
func (s *Server) tamperCreateHook(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
var req tamperHookReq
if err := decode(w, r, &req); err != nil {
writeErr(w, 400, err.Error())
return
}
def := traffic.HookDef{
Name: req.Name, Enabled: false, Phase: req.Phase, Priority: req.Priority,
Matchers: req.Matchers, Source: req.Source, Note: req.Note,
}
if err := traffic.ValidateHookDef(def); err != nil {
tamperHookWriteErr(w, tamperHookInvalid(err))
return
}
matchersJSON, _ := json.Marshal(req.Matchers)
row, err := pg.CreateTrafficTamperHook(db.TrafficTamperHook{
Name: req.Name, Enabled: false, Phase: string(req.Phase), Priority: req.Priority,
Matchers: matchersJSON, Source: req.Source, Note: req.Note,
})
if err != nil {
tamperHookWriteErr(w, err)
return
}
s.m.reloadTamperHooks()
writeJSON(w, 200, s.m.tamperHookDTO(row))
}
func (s *Server) tamperUpdateHook(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id <= 0 {
writeErr(w, 400, "invalid hook id")
return
}
var req tamperHookReq
if err := decode(w, r, &req); err != nil {
writeErr(w, 400, err.Error())
return
}
def := traffic.HookDef{
ID: id, Name: req.Name, Enabled: req.Enabled, Phase: req.Phase, Priority: req.Priority,
Matchers: req.Matchers, Source: req.Source, Note: req.Note,
}
if err := traffic.ValidateHookDef(def); err != nil {
tamperHookWriteErr(w, tamperHookInvalid(err))
return
}
matchersJSON, _ := json.Marshal(req.Matchers)
row, err := pg.UpdateTrafficTamperHook(id, func(stored db.TrafficTamperHook) (db.TrafficTamperHook, error) {
return db.TrafficTamperHook{
Name: req.Name, Enabled: req.Enabled, Phase: string(req.Phase), Priority: req.Priority,
Matchers: matchersJSON, Source: req.Source, Note: req.Note,
}, nil
})
if err != nil {
tamperHookWriteErr(w, err)
return
}
s.m.reloadTamperHooks()
writeJSON(w, 200, s.m.tamperHookDTO(row))
}
func (s *Server) tamperDeleteHook(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id <= 0 {
writeErr(w, 400, "invalid hook id")
return
}
if err := pg.DeleteTrafficTamperHook(id); err != nil {
tamperHookWriteErr(w, err)
return
}
s.m.reloadTamperHooks()
writeJSON(w, 200, map[string]any{"deleted": true})
}
func (s *Server) tamperToggleHook(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id <= 0 {
writeErr(w, 400, "invalid hook id")
return
}
var body struct {
Enabled bool `json:"enabled"`
}
if err := decode(w, r, &body); err != nil {
writeErr(w, 400, err.Error())
return
}
if err := pg.ToggleTrafficTamperHook(id, body.Enabled); err != nil {
tamperHookWriteErr(w, err)
return
}
row, err := pg.GetTrafficTamperHook(id)
if err != nil {
tamperHookWriteErr(w, err)
return
}
s.m.reloadTamperHooks()
writeJSON(w, 200, s.m.tamperHookDTO(row))
}
func (s *Server) tamperListHookVersions(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id <= 0 {
writeErr(w, 400, "invalid hook id")
return
}
if _, err := pg.GetTrafficTamperHook(id); err != nil {
tamperHookWriteErr(w, err)
return
}
vers, err := pg.ListTrafficTamperHookVersions(id)
if err != nil {
writeErr(w, 500, err.Error())
return
}
out := make([]tamperHookVersionDTO, 0, len(vers))
for _, v := range vers {
var m rewrite.Matchers
_ = json.Unmarshal(v.Matchers, &m)
out = append(out, tamperHookVersionDTO{
ID: v.ID, HookID: v.HookID, Version: v.Version, Name: v.Name,
Phase: v.Phase, Priority: v.Priority, Matchers: m, Source: v.Source,
SourceSHA256: v.SourceSHA256, Note: v.Note, CreatedAt: v.CreatedAt,
})
}
writeJSON(w, 200, map[string]any{"versions": out})
}
func (s *Server) tamperRollbackHook(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil || id <= 0 {
writeErr(w, 400, "invalid hook id")
return
}
var body struct {
Version int `json:"version"`
}
if err := decode(w, r, &body); err != nil {
writeErr(w, 400, err.Error())
return
}
if body.Version <= 0 {
writeErr(w, 400, "version must be > 0")
return
}
row, err := pg.RollbackTrafficTamperHook(id, body.Version)
if err != nil {
tamperHookWriteErr(w, err)
return
}
s.m.reloadTamperHooks()
writeJSON(w, 200, s.m.tamperHookDTO(row))
}
func (s *Server) tamperDryRunHook(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
var req tamperDryRunReq
if err := decode(w, r, &req); err != nil {
writeErr(w, 400, err.Error())
return
}
var def traffic.HookDef
if req.HookID > 0 {
row, err := pg.GetTrafficTamperHook(req.HookID)
if err != nil {
tamperHookWriteErr(w, err)
return
}
def, err = decodeTamperHookRow(row)
if err != nil {
writeErr(w, 400, "stored hook cannot be decoded")
return
}
} else {
name := req.Name
if name == "" {
name = "dry-run"
}
def = traffic.HookDef{
Name: name, Phase: req.Phase, Matchers: req.Matchers, Source: req.Source, Version: 1,
}
}
rawURL := req.Request.URL
if rawURL == "" {
rawURL = "https://example.test/"
}
u, err := url.Parse(rawURL)
if err != nil {
writeErr(w, 400, "invalid request.url: "+err.Error())
return
}
method := req.Request.Method
if method == "" {
method = http.MethodGet
}
status := req.Response.Status
if status == 0 {
status = http.StatusOK
}
reqHdr := http.Header{}
for k, vs := range req.Request.Headers {
reqHdr[http.CanonicalHeaderKey(k)] = append([]string(nil), vs...)
}
respHdr := http.Header{}
for k, vs := range req.Response.Headers {
respHdr[http.CanonicalHeaderKey(k)] = append([]string(nil), vs...)
}
res, err := traffic.DryRunHook(def, rewrite.Input{
Request: rewrite.Request{Method: method, URL: u, Header: reqHdr, Body: []byte(req.Request.Body)},
Response: rewrite.Response{Status: status, Header: respHdr, Body: []byte(req.Response.Body)},
}, db.TrafficTraceKey())
if err != nil {
tamperHookWriteErr(w, tamperHookInvalid(err))
return
}
writeJSON(w, 200, map[string]any{
"changed": res.Changed,
"request": map[string]any{
"method": res.Request.Method,
"url": res.Request.URL.String(),
"headers": res.Request.Header,
"body": string(res.Request.Body),
},
"response": map[string]any{
"status": res.Response.Status,
"headers": res.Response.Header,
"body": string(res.Response.Body),
},
"lines": res.Lines,
})
}
+157
View File
@@ -0,0 +1,157 @@
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http/httptest"
"testing"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/traffic"
)
func TestTamperHooksAPIValidationKillSwitchCRUDVersionsRollbackDryRun(t *testing.T) {
t.Setenv(traffic.TamperHooksEnabledEnv, "")
m, err := NewManager(t.TempDir(), "127.0.0.1:0")
if err != nil {
db.SkipPGUnavailable(t, err)
}
t.Cleanup(func() { _ = m.Close() })
ctx, cancel := context.WithCancel(context.Background())
cancel()
s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
token, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
}
do := func(method, path string, body any) (int, map[string]any) {
t.Helper()
var rdr *bytes.Reader
if body != nil {
b, _ := json.Marshal(body)
rdr = bytes.NewReader(b)
} else {
rdr = bytes.NewReader(nil)
}
req := httptest.NewRequest(method, path, rdr)
req.Header.Set("Authorization", "Bearer "+token)
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, req)
var out map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &out)
return rec.Code, out
}
// 1. Forbidden constructs/imports rejected at AST validation with HTTP 400.
forbidden := []string{
`package hook; import "os"; func OnRequest(req *Request) error { _ = os.Getenv("X"); return nil }`,
`package hook; import "io/fs"; func OnRequest(req *Request) error { return nil }`,
`package hook; import "net"; func OnRequest(req *Request) error { return nil }`,
`package hook; import "os/exec"; func OnRequest(req *Request) error { return nil }`,
`package hook; import "syscall"; func OnRequest(req *Request) error { return nil }`,
`package hook; import "unsafe"; func OnRequest(req *Request) error { return nil }`,
`package hook; import "reflect"; func OnRequest(req *Request) error { return nil }`,
`package hook; import "time"; func OnRequest(req *Request) error { _ = time.Now(); return nil }`,
`package hook; import "math/rand"; func OnRequest(req *Request) error { _ = rand.Int(); return nil }`,
`package hook; func f(){}; func OnRequest(req *Request) error { go f(); return nil }`,
`package hook; func OnRequest(req *Request) error { var c chan int; _ = c; return nil }`,
`package hook; func OnRequest(req *Request) error { select {}; return nil }`,
`package hook; func f(){}; func OnRequest(req *Request) error { defer f(); return nil }`,
`package hook; func OnRequest(req *Request) error { goto end; end: return nil }`,
`package hook; func init() {}; func OnRequest(req *Request) error { return nil }`,
`package hook; var g = 1; func OnRequest(req *Request) error { g++; return nil }`,
}
for i, src := range forbidden {
code, _ := do("POST", "/api/traffic/hooks", map[string]any{
"name": fmt.Sprintf("bad-%d", i), "phase": "request", "source": src,
})
if code != 400 {
t.Fatalf("forbidden hook %d returned HTTP %d, want 400", i, code)
}
}
// 2. Create valid hook (always created disabled, version 1).
const srcV1 = `package hook
func OnRequest(req *Request) error {
req.SetHeader("X-Ver", "1")
return nil
}`
const srcV2 = `package hook
func OnRequest(req *Request) error {
req.SetHeader("X-Ver", "2")
return nil
}`
code, created := do("POST", "/api/traffic/hooks", map[string]any{
"name": "p42-api-hook", "enabled": true, "phase": "request", "priority": 5,
"matchers": map[string]any{"host": "api.example.test"},
"source": srcV1, "note": "v1",
})
if code != 200 {
t.Fatalf("create hook HTTP %d: %v", code, created)
}
id := int64(created["id"].(float64))
t.Cleanup(func() { _ = m.pg.DeleteTrafficTamperHook(id) })
if created["enabled"] != false || created["version"].(float64) != 1 {
t.Fatalf("expected created disabled v1, got %v", created)
}
// 3. Toggle enabled while kill switch is OFF: zero hooks loaded onto proxy.
code, toggled := do("POST", fmt.Sprintf("/api/traffic/hooks/%d/toggle", id), map[string]any{"enabled": true})
if code != 200 || toggled["enabled"] != true {
t.Fatalf("toggle HTTP %d: %v", code, toggled)
}
if m.traffic.TamperHooks() != nil {
t.Fatal("expected nil TamperHooks on proxy when ARTEX_TAMPER_HOOKS_ENABLED is off")
}
// 4. Enable kill switch and reload: snapshot now holds 1 request hook.
t.Setenv(traffic.TamperHooksEnabledEnv, "1")
m.reloadTamperHooks()
if m.traffic.TamperHooks().Len("request") != 1 {
t.Fatalf("expected 1 loaded request hook when kill switch on, got %d", m.traffic.TamperHooks().Len("request"))
}
// 5. Update -> v2, list versions, rollback to v1 -> v3.
code, upd := do("PUT", fmt.Sprintf("/api/traffic/hooks/%d", id), map[string]any{
"name": "p42-api-hook", "enabled": true, "phase": "request", "priority": 5,
"matchers": map[string]any{"host": "api.example.test"},
"source": srcV2, "note": "v2",
})
if code != 200 || upd["version"].(float64) != 2 {
t.Fatalf("update HTTP %d: %v", code, upd)
}
code, vers := do("GET", fmt.Sprintf("/api/traffic/hooks/%d/versions", id), nil)
if code != 200 || len(vers["versions"].([]any)) != 2 {
t.Fatalf("versions HTTP %d: %v", code, vers)
}
code, rb := do("POST", fmt.Sprintf("/api/traffic/hooks/%d/rollback", id), map[string]any{"version": 1})
if code != 200 || rb["version"].(float64) != 3 || rb["source"] != srcV1 {
t.Fatalf("rollback HTTP %d: %v", code, rb)
}
// 6. Dry-run endpoint against stored hook_id.
code, dry := do("POST", "/api/traffic/hooks/dry-run", map[string]any{
"hook_id": id,
"request": map[string]any{"method": "GET", "url": "https://api.example.test/v1/ping"},
})
if code != 200 || dry["changed"] != true {
t.Fatalf("dry-run HTTP %d: %v", code, dry)
}
reqMap := dry["request"].(map[string]any)
hdrs := reqMap["headers"].(map[string]any)
if xver := hdrs["X-Ver"].([]any); len(xver) != 1 || xver[0] != "1" {
t.Fatalf("dry-run X-Ver = %v, want [1]", xver)
}
// 7. Delete cleans up and updates proxy snapshot.
code, _ = do("DELETE", fmt.Sprintf("/api/traffic/hooks/%d", id), nil)
if code != 200 {
t.Fatalf("delete HTTP %d", code)
}
if m.traffic.TamperHooks().Len("request") != 0 {
t.Fatalf("expected 0 loaded hooks after delete, got %d", m.traffic.TamperHooks().Len("request"))
}
}