mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-02 12:01:50 +08:00
feat(traffic,sandbox): add TUN/netstack transparent gateway, egress controls, CAP_NET_RAW hardening, and i18n fixes
- Implement full-traffic transparent gateway (cmd/artex-gateway, traffic/netstack.go, traffic/transparent.go) using Linux TUN + gVisor netstack deferred TCP handshakes (eliminating nmap/nc false-positive open ports), real ICMPv4 Echo proxying, UDP/DNS interception, and per-container upstream proxy overrides. - Add egress blacklist + asset-intercept sync, non-HTTP flow/DNS SQLite persistence and APIs, and /system/proxy & /function/traffic TCP/UDP/DNS UI panels. - Fix sandbox Playwright MCP browser loopback --proxy-server rewrite and NODE_EXTRA_CA_CERTS override in server/mcpstdio.go. - Strip all SUID/SGID binaries in Dockerfile.sandbox, grant minimal cap_net_raw+ep to nmap/nping/ping with ARTEX_SANDBOX_ALLOW_NET_RAW toggle, and enforce IPv4/IPv6 anti-spoofing in iptables and netstack. - Remove hardcoded Chinese "(全局)" from GET /api/proxy/routes, localize ContainerRoutesTab / NonHTTPTrafficPanel labels, and expose reactive locale/isEn from useLiveTranslation for React Compiler compatibility.
This commit is contained in:
1 parent
9c43e694a3
commit
d786de90af
69 files changed
+13082
-1433
No files matched your search
@@ -49,6 +49,7 @@ func (s *Server) assetInterceptCreateRule(w http.ResponseWriter, r *http.Request
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, rule)
|
||||
}
|
||||
|
||||
@@ -76,6 +77,7 @@ func (s *Server) assetInterceptUpdateRule(w http.ResponseWriter, r *http.Request
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, rule)
|
||||
}
|
||||
|
||||
@@ -93,6 +95,7 @@ func (s *Server) assetInterceptDeleteRule(w http.ResponseWriter, r *http.Request
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, map[string]any{"deleted": id})
|
||||
}
|
||||
|
||||
@@ -117,6 +120,7 @@ func (s *Server) assetInterceptToggleRule(w http.ResponseWriter, r *http.Request
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "enabled": req.Enabled})
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -120,7 +120,7 @@ func extractToken(r *http.Request) string {
|
||||
func (s *Server) requireAuth(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/api/auth/") || p == "/api/health" || p == "/api/basic-auth/check" {
|
||||
if strings.HasPrefix(p, "/api/auth/") || strings.HasPrefix(p, "/api/internal/gateway/") || p == "/api/health" || p == "/api/basic-auth/check" {
|
||||
h.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
)
|
||||
|
||||
func TestEnsureBrowserMCPArgs(t *testing.T) {
|
||||
@@ -178,3 +178,72 @@ func TestDefaultEnabledSettingsAndScreenshotTimestampHeader(t *testing.T) {
|
||||
t.Fatal("expected X-Report-Screenshot-Timestamp header when setting is unset (default true)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdaptSandboxMCPArgsAndEnv(t *testing.T) {
|
||||
// 1. Loopback --proxy-server (split and =) rewritten to sandbox-reachable proxy URL.
|
||||
in := []string{"--browser", "chromium", "--headless", "--no-sandbox", "--proxy-server", "http://127.0.0.1:8788"}
|
||||
got := adaptSandboxMCPArgs(in, "http://172.30.0.2:8788")
|
||||
want := []string{"--browser", "chromium", "--headless", "--no-sandbox", "--proxy-server", "http://172.30.0.2:8788"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("adaptSandboxMCPArgs(split) = %v, want %v", got, want)
|
||||
}
|
||||
|
||||
inEq := []string{"--headless", "--proxy-server=http://localhost:8788"}
|
||||
gotEq := adaptSandboxMCPArgs(inEq, "http://172.30.0.2:8788")
|
||||
wantEq := []string{"--headless", "--proxy-server=http://172.30.0.2:8788"}
|
||||
if !reflect.DeepEqual(gotEq, wantEq) {
|
||||
t.Fatalf("adaptSandboxMCPArgs(=) = %v, want %v", gotEq, wantEq)
|
||||
}
|
||||
|
||||
// 2. Empty sandboxProxyURL strips unusable loopback proxy flag cleanly.
|
||||
gotStrip := adaptSandboxMCPArgs(in, "")
|
||||
wantStrip := []string{"--browser", "chromium", "--headless", "--no-sandbox"}
|
||||
if !reflect.DeepEqual(gotStrip, wantStrip) {
|
||||
t.Fatalf("adaptSandboxMCPArgs(strip) = %v, want %v", gotStrip, wantStrip)
|
||||
}
|
||||
|
||||
// 3. Explicit non-loopback user proxy passes through untouched.
|
||||
inCustom := []string{"--headless", "--proxy-server", "http://10.0.0.5:8080"}
|
||||
gotCustom := adaptSandboxMCPArgs(inCustom, "http://172.30.0.2:8788")
|
||||
if !reflect.DeepEqual(gotCustom, inCustom) {
|
||||
t.Fatalf("adaptSandboxMCPArgs(custom) = %v, want %v", gotCustom, inCustom)
|
||||
}
|
||||
|
||||
// 4. stripURLCredentials drops userinfo so Chromium accepts --proxy-server.
|
||||
if got := stripURLCredentials("http://artexctx_sc=task:[email protected]:8788"); got != "http://172.30.0.2:8788" {
|
||||
t.Fatalf("stripURLCredentials = %q", got)
|
||||
}
|
||||
|
||||
// 5. buildSandboxMCPEnv never lets host CA path clobber /etc/artex/ca.crt.
|
||||
caFile := filepath.Join(t.TempDir(), "mitmproxy-ca-cert.pem")
|
||||
if err := os.WriteFile(caFile, []byte("FAKE-CA"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr, err := sandbox.New(sandbox.Config{
|
||||
Mode: sandbox.ModeLocal,
|
||||
ProxyURL: "http://172.30.0.2:8788",
|
||||
CACertPath: caFile,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env := buildSandboxMCPEnv(mgr, map[string]string{
|
||||
"NODE_EXTRA_CA_CERTS": "/app/data/traffic/_ca/mitmproxy-ca-cert.pem",
|
||||
"CUSTOM_KEY": "custom-val",
|
||||
})
|
||||
envMap := map[string]string{}
|
||||
for _, kv := range env {
|
||||
if k, v, ok := strings.Cut(kv, "="); ok {
|
||||
envMap[k] = v
|
||||
}
|
||||
}
|
||||
if envMap["NODE_EXTRA_CA_CERTS"] != sandbox.ContainerCACertPath {
|
||||
t.Fatalf("NODE_EXTRA_CA_CERTS = %q, want %q", envMap["NODE_EXTRA_CA_CERTS"], sandbox.ContainerCACertPath)
|
||||
}
|
||||
if envMap["CUSTOM_KEY"] != "custom-val" {
|
||||
t.Fatalf("CUSTOM_KEY = %q, want custom-val", envMap["CUSTOM_KEY"])
|
||||
}
|
||||
if envMap["HTTP_PROXY"] != "http://172.30.0.2:8788" {
|
||||
t.Fatalf("HTTP_PROXY = %q, want http://172.30.0.2:8788", envMap["HTTP_PROXY"])
|
||||
}
|
||||
}
|
||||
+28
-16
@@ -191,28 +191,40 @@ func completedRFC(unix int64) string {
|
||||
|
||||
// ---- TrafficExchange (frontend "TrafficExchange") ---- ts as RFC3339.
|
||||
type TrafficExchangeDTO struct {
|
||||
ID string `json:"id"`
|
||||
TS string `json:"ts"`
|
||||
Host string `json:"host"`
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Status int `json:"status"`
|
||||
ContentType string `json:"content_type"`
|
||||
RespLen int `json:"resp_len"`
|
||||
ID string `json:"id"`
|
||||
TS string `json:"ts"`
|
||||
Host string `json:"host"`
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Status int `json:"status"`
|
||||
ContentType string `json:"content_type"`
|
||||
RespLen int `json:"resp_len"`
|
||||
SandboxScope string `json:"sandbox_scope,omitempty"`
|
||||
SandboxOwnerID string `json:"sandbox_owner_id,omitempty"`
|
||||
ContainerID string `json:"container_id,omitempty"`
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
IntentID int64 `json:"intent_id,omitempty"`
|
||||
SrcIP string `json:"src_ip,omitempty"`
|
||||
}
|
||||
|
||||
func trafficDTOs(ex []traffic.ExchangeMeta) []TrafficExchangeDTO {
|
||||
out := make([]TrafficExchangeDTO, 0, len(ex))
|
||||
for _, e := range ex {
|
||||
out = append(out, TrafficExchangeDTO{
|
||||
ID: e.ID,
|
||||
TS: rfc3339(time.Unix(e.TS, 0)),
|
||||
Host: e.Host,
|
||||
Method: e.Method,
|
||||
URL: e.URL,
|
||||
Status: e.Status,
|
||||
ContentType: e.ContentType,
|
||||
RespLen: e.RespLen,
|
||||
ID: e.ID,
|
||||
TS: rfc3339(time.Unix(e.TS, 0)),
|
||||
Host: e.Host,
|
||||
Method: e.Method,
|
||||
URL: e.URL,
|
||||
Status: e.Status,
|
||||
ContentType: e.ContentType,
|
||||
RespLen: e.RespLen,
|
||||
SandboxScope: e.SandboxScope,
|
||||
SandboxOwnerID: e.SandboxOwnerID,
|
||||
ContainerID: e.ContainerID,
|
||||
SessionID: e.SessionID,
|
||||
IntentID: e.IntentID,
|
||||
SrcIP: e.SrcIP,
|
||||
})
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
const (
|
||||
settingEgressBlacklistRules = "egress_blacklist_rules_json"
|
||||
settingEgressBlacklistSync = "egress_blacklist_sync_asset_intercept"
|
||||
)
|
||||
|
||||
func (s *Server) loadCustomEgressBlacklist() []traffic.EgressBlacklistRule {
|
||||
if s.m.pg == nil {
|
||||
return []traffic.EgressBlacklistRule{}
|
||||
}
|
||||
raw, ok, err := s.m.pg.GetSetting(settingEgressBlacklistRules)
|
||||
if err != nil || !ok || strings.TrimSpace(raw) == "" {
|
||||
return []traffic.EgressBlacklistRule{}
|
||||
}
|
||||
var rules []traffic.EgressBlacklistRule
|
||||
if err := json.Unmarshal([]byte(raw), &rules); err != nil {
|
||||
return []traffic.EgressBlacklistRule{}
|
||||
}
|
||||
if rules == nil {
|
||||
return []traffic.EgressBlacklistRule{}
|
||||
}
|
||||
for i := range rules {
|
||||
rules[i].Source = "custom"
|
||||
}
|
||||
return rules
|
||||
}
|
||||
|
||||
func (s *Server) saveCustomEgressBlacklist(rules []traffic.EgressBlacklistRule) error {
|
||||
if s.m.pg == nil {
|
||||
return fmt.Errorf("database unavailable")
|
||||
}
|
||||
if rules == nil {
|
||||
rules = []traffic.EgressBlacklistRule{}
|
||||
}
|
||||
b, err := json.Marshal(rules)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.m.pg.SetSetting(settingEgressBlacklistRules, string(b))
|
||||
}
|
||||
|
||||
func (s *Server) egressBlacklistSyncAssetEnabled() bool {
|
||||
if s.m.pg == nil {
|
||||
return false
|
||||
}
|
||||
return s.m.pg.GetBool(settingEgressBlacklistSync, false)
|
||||
}
|
||||
|
||||
// translateAssetInterceptRules converts enabled global asset_intercept_rules
|
||||
// into network-layer egress blacklist rules. Rules that only match URL paths
|
||||
// without a concrete host are skipped because network-layer checks operate on
|
||||
// destination host/IP/CIDR.
|
||||
func translateAssetInterceptRules(in []db.AssetInterceptRule) []traffic.EgressBlacklistRule {
|
||||
out := make([]traffic.EgressBlacklistRule, 0, len(in))
|
||||
for _, r := range in {
|
||||
if !r.Enabled {
|
||||
continue
|
||||
}
|
||||
pat := strings.TrimSpace(r.Pattern)
|
||||
if pat == "" {
|
||||
continue
|
||||
}
|
||||
var kind, normalized string
|
||||
switch r.Kind {
|
||||
case "exact_domain":
|
||||
kind = "domain"
|
||||
normalized = pat
|
||||
case "fuzzy_domain":
|
||||
kind = "suffix"
|
||||
normalized = pat
|
||||
case "exact_ip":
|
||||
kind = "ip"
|
||||
normalized = pat
|
||||
case "cidr":
|
||||
kind = "cidr"
|
||||
normalized = pat
|
||||
case "exact_url", "fuzzy_url":
|
||||
raw := pat
|
||||
if !strings.Contains(raw, "://") {
|
||||
raw = "http://" + raw
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || strings.TrimSpace(u.Hostname()) == "" {
|
||||
continue
|
||||
}
|
||||
h := u.Hostname()
|
||||
if net.ParseIP(h) != nil {
|
||||
kind = "ip"
|
||||
normalized = h
|
||||
} else if r.Kind == "fuzzy_url" {
|
||||
kind = "suffix"
|
||||
normalized = h
|
||||
} else {
|
||||
kind = "domain"
|
||||
normalized = h
|
||||
}
|
||||
default:
|
||||
continue
|
||||
}
|
||||
er := traffic.EgressBlacklistRule{
|
||||
ID: fmt.Sprintf("asset-%d", r.ID),
|
||||
Enabled: true,
|
||||
Kind: kind,
|
||||
Pattern: normalized,
|
||||
Note: r.Note,
|
||||
Source: "asset_intercept",
|
||||
}
|
||||
if err := traffic.NormalizeEgressRule(&er); err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, er)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// syncEgressBlacklist compiles and hot-loads custom egress blacklist rules plus
|
||||
// optionally synced global asset_intercept_rules into the recording proxy.
|
||||
func (s *Server) syncEgressBlacklist() {
|
||||
if s.m.traffic == nil {
|
||||
return
|
||||
}
|
||||
custom := s.loadCustomEgressBlacklist()
|
||||
effective := make([]traffic.EgressBlacklistRule, 0, len(custom))
|
||||
effective = append(effective, custom...)
|
||||
if s.egressBlacklistSyncAssetEnabled() && s.m.pg != nil {
|
||||
if assetRules, err := s.m.pg.ListAssetInterceptRules(); err == nil {
|
||||
effective = append(effective, translateAssetInterceptRules(assetRules)...)
|
||||
}
|
||||
}
|
||||
s.m.traffic.SetEgressBlacklist(effective)
|
||||
}
|
||||
|
||||
// GET /api/proxy/blacklist
|
||||
func (s *Server) getEgressBlacklist(w http.ResponseWriter, r *http.Request) {
|
||||
custom := s.loadCustomEgressBlacklist()
|
||||
syncOn := s.egressBlacklistSyncAssetEnabled()
|
||||
synced := []traffic.EgressBlacklistRule{}
|
||||
if s.m.pg != nil {
|
||||
if assetRules, err := s.m.pg.ListAssetInterceptRules(); err == nil {
|
||||
synced = translateAssetInterceptRules(assetRules)
|
||||
}
|
||||
}
|
||||
events := []traffic.EgressBlockEvent{}
|
||||
if s.m.traffic != nil {
|
||||
events = s.m.traffic.BlockEvents(100)
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"rules": custom,
|
||||
"synced_rules": synced,
|
||||
"sync_asset_intercept": syncOn,
|
||||
"events": events,
|
||||
})
|
||||
}
|
||||
|
||||
// PUT /api/proxy/blacklist/settings
|
||||
func (s *Server) updateEgressBlacklistSettings(w http.ResponseWriter, r *http.Request) {
|
||||
pg := s.pg(w)
|
||||
if pg == nil {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
SyncAssetIntercept bool `json:"sync_asset_intercept"`
|
||||
}
|
||||
if err := decode(r, &req); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
val := "false"
|
||||
if req.SyncAssetIntercept {
|
||||
val = "true"
|
||||
}
|
||||
if err := pg.SetSetting(settingEgressBlacklistSync, val); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
s.getEgressBlacklist(w, r)
|
||||
}
|
||||
|
||||
// POST /api/proxy/blacklist/rules
|
||||
func (s *Server) createEgressBlacklistRule(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
Kind string `json:"kind"`
|
||||
Pattern string `json:"pattern"`
|
||||
Port int `json:"port"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
if err := decode(r, &req); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
enabled := true
|
||||
if req.Enabled != nil {
|
||||
enabled = *req.Enabled
|
||||
}
|
||||
now := time.Now().UTC().Format(time.RFC3339)
|
||||
rule := traffic.EgressBlacklistRule{
|
||||
ID: fmt.Sprintf("eb-%d", time.Now().UnixNano()),
|
||||
Enabled: enabled,
|
||||
Kind: req.Kind,
|
||||
Pattern: req.Pattern,
|
||||
Port: req.Port,
|
||||
Note: req.Note,
|
||||
Source: "custom",
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if err := traffic.NormalizeEgressRule(&rule); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
rules := s.loadCustomEgressBlacklist()
|
||||
for _, existing := range rules {
|
||||
if existing.Kind == rule.Kind && existing.Pattern == rule.Pattern && existing.Port == rule.Port {
|
||||
writeErr(w, 409, "相同规则已存在")
|
||||
return
|
||||
}
|
||||
}
|
||||
rules = append([]traffic.EgressBlacklistRule{rule}, rules...)
|
||||
if err := s.saveCustomEgressBlacklist(rules); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, rule)
|
||||
}
|
||||
|
||||
// PUT /api/proxy/blacklist/rules/{id}
|
||||
func (s *Server) updateEgressBlacklistRule(w http.ResponseWriter, r *http.Request) {
|
||||
id := strings.TrimSpace(r.PathValue("id"))
|
||||
if id == "" {
|
||||
writeErr(w, 400, "invalid rule id")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
Kind *string `json:"kind"`
|
||||
Pattern *string `json:"pattern"`
|
||||
Port *int `json:"port"`
|
||||
Note *string `json:"note"`
|
||||
}
|
||||
if err := decode(r, &req); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
rules := s.loadCustomEgressBlacklist()
|
||||
idx := -1
|
||||
for i := range rules {
|
||||
if rules[i].ID == id {
|
||||
idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if idx < 0 {
|
||||
writeErr(w, 404, "规则不存在")
|
||||
return
|
||||
}
|
||||
updated := rules[idx]
|
||||
if req.Enabled != nil {
|
||||
updated.Enabled = *req.Enabled
|
||||
}
|
||||
if req.Kind != nil {
|
||||
updated.Kind = *req.Kind
|
||||
}
|
||||
if req.Pattern != nil {
|
||||
updated.Pattern = *req.Pattern
|
||||
}
|
||||
if req.Port != nil {
|
||||
updated.Port = *req.Port
|
||||
}
|
||||
if req.Note != nil {
|
||||
updated.Note = *req.Note
|
||||
}
|
||||
updated.Source = "custom"
|
||||
updated.UpdatedAt = time.Now().UTC().Format(time.RFC3339)
|
||||
if err := traffic.NormalizeEgressRule(&updated); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
rules[idx] = updated
|
||||
if err := s.saveCustomEgressBlacklist(rules); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, updated)
|
||||
}
|
||||
|
||||
// DELETE /api/proxy/blacklist/rules/{id}
|
||||
func (s *Server) deleteEgressBlacklistRule(w http.ResponseWriter, r *http.Request) {
|
||||
id := strings.TrimSpace(r.PathValue("id"))
|
||||
if id == "" {
|
||||
writeErr(w, 400, "invalid rule id")
|
||||
return
|
||||
}
|
||||
rules := s.loadCustomEgressBlacklist()
|
||||
next := make([]traffic.EgressBlacklistRule, 0, len(rules))
|
||||
found := false
|
||||
for _, rule := range rules {
|
||||
if rule.ID == id {
|
||||
found = true
|
||||
continue
|
||||
}
|
||||
next = append(next, rule)
|
||||
}
|
||||
if !found {
|
||||
writeErr(w, 404, "规则不存在")
|
||||
return
|
||||
}
|
||||
if err := s.saveCustomEgressBlacklist(next); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.syncEgressBlacklist()
|
||||
writeJSON(w, 200, map[string]any{"deleted": id})
|
||||
}
|
||||
|
||||
// DELETE /api/proxy/blacklist/events
|
||||
func (s *Server) clearEgressBlockEvents(w http.ResponseWriter, _ *http.Request) {
|
||||
if s.m.traffic != nil {
|
||||
s.m.traffic.ClearBlockEvents()
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"cleared": true})
|
||||
}
|
||||
|
||||
type cachedTaskEgressRules struct {
|
||||
block []traffic.EgressBlacklistRule
|
||||
allow []traffic.EgressBlacklistRule
|
||||
fetchedAt time.Time
|
||||
}
|
||||
|
||||
var taskEgressRulesCache sync.Map // int64(taskID) -> cachedTaskEgressRules
|
||||
|
||||
const taskEgressCacheTTL = 3 * time.Second
|
||||
|
||||
// checkTaskEgressBlacklist evaluates task-scoped task_intercept_rules at the
|
||||
// recording proxy egress boundary (#218 Phase 2). Built-in SSRF guard is always
|
||||
// evaluated before this callback and cannot be bypassed by task allow rules.
|
||||
func (s *Server) checkTaskEgressBlacklist(taskIDStr, rawHost, scheme string) (string, string) {
|
||||
if s == nil || s.m == nil || s.m.Assets() == nil {
|
||||
return "", ""
|
||||
}
|
||||
taskID, err := strconv.ParseInt(strings.TrimSpace(taskIDStr), 10, 64)
|
||||
if err != nil || taskID <= 0 {
|
||||
return "", ""
|
||||
}
|
||||
var entry cachedTaskEgressRules
|
||||
if v, ok := taskEgressRulesCache.Load(taskID); ok {
|
||||
if c, ok2 := v.(cachedTaskEgressRules); ok2 && time.Since(c.fetchedAt) < taskEgressCacheTTL {
|
||||
entry = c
|
||||
}
|
||||
}
|
||||
if entry.fetchedAt.IsZero() {
|
||||
blockRaw, allowRaw, err := s.m.Assets().TaskInterceptRulesSplit(taskID)
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
entry = cachedTaskEgressRules{
|
||||
block: translateAssetInterceptRules(blockRaw),
|
||||
allow: translateAssetInterceptRules(allowRaw),
|
||||
fetchedAt: time.Now(),
|
||||
}
|
||||
taskEgressRulesCache.Store(taskID, entry)
|
||||
}
|
||||
if len(entry.block) == 0 {
|
||||
return "", ""
|
||||
}
|
||||
if len(entry.allow) > 0 {
|
||||
if reason, _ := traffic.MatchEgressRules(entry.allow, rawHost, scheme); reason != "" {
|
||||
return "", ""
|
||||
}
|
||||
}
|
||||
if reason, pat := traffic.MatchEgressRules(entry.block, rawHost, scheme); reason != "" {
|
||||
return fmt.Sprintf("task #%d intercept rule: %s", taskID, reason), pat
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// loadTaskEgressRules returns translated block rules for one task (used for gateway sync).
|
||||
func (s *Server) loadTaskEgressRules(taskIDStr string) []traffic.EgressBlacklistRule {
|
||||
if s == nil || s.m == nil || s.m.Assets() == nil {
|
||||
return nil
|
||||
}
|
||||
taskID, err := strconv.ParseInt(strings.TrimSpace(taskIDStr), 10, 64)
|
||||
if err != nil || taskID <= 0 {
|
||||
return nil
|
||||
}
|
||||
blockRaw, _, err := s.m.Assets().TaskInterceptRulesSplit(taskID)
|
||||
if err != nil || len(blockRaw) == 0 {
|
||||
return nil
|
||||
}
|
||||
return translateAssetInterceptRules(blockRaw)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func TestTranslateAssetInterceptRules(t *testing.T) {
|
||||
in := []db.AssetInterceptRule{
|
||||
{ID: 1, Enabled: true, Kind: "exact_domain", Pattern: "Admin.Example.com", Note: "prod"},
|
||||
{ID: 2, Enabled: true, Kind: "fuzzy_domain", Pattern: "gov.cn", Note: "gov"},
|
||||
{ID: 3, Enabled: true, Kind: "exact_ip", Pattern: "198.51.100.9"},
|
||||
{ID: 4, Enabled: true, Kind: "cidr", Pattern: "203.0.113.0/24"},
|
||||
{ID: 5, Enabled: true, Kind: "exact_url", Pattern: "https://pay.example.org:8443/checkout"},
|
||||
{ID: 6, Enabled: false, Kind: "exact_domain", Pattern: "disabled.example.com"},
|
||||
{ID: 7, Enabled: true, Kind: "fuzzy_url", Pattern: "/admin/delete"},
|
||||
}
|
||||
got := translateAssetInterceptRules(in)
|
||||
if len(got) != 5 {
|
||||
t.Fatalf("translated %d rules, want 5: %+v", len(got), got)
|
||||
}
|
||||
want := []struct {
|
||||
kind string
|
||||
pattern string
|
||||
}{
|
||||
{"domain", "admin.example.com"},
|
||||
{"suffix", "*.gov.cn"},
|
||||
{"ip", "198.51.100.9"},
|
||||
{"cidr", "203.0.113.0/24"},
|
||||
{"domain", "pay.example.org"},
|
||||
}
|
||||
for i, w := range want {
|
||||
if got[i].Kind != w.kind || got[i].Pattern != w.pattern || got[i].Source != "asset_intercept" {
|
||||
t.Fatalf("rule[%d] = %+v, want kind=%s pattern=%s source=asset_intercept", i, got[i], w.kind, w.pattern)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
// authorizeGatewayRequest authenticates internal requests from artex-gateway.
|
||||
// When ARTEX_GATEWAY_TOKEN is configured, X-Artex-Gateway-Token must match
|
||||
// exactly (constant-time). When unset, only loopback callers are permitted.
|
||||
func (s *Server) authorizeGatewayRequest(r *http.Request) bool {
|
||||
expected := strings.TrimSpace(os.Getenv("ARTEX_GATEWAY_TOKEN"))
|
||||
if expected != "" {
|
||||
got := strings.TrimSpace(r.Header.Get("X-Artex-Gateway-Token"))
|
||||
return len(got) == len(expected) && subtle.ConstantTimeCompare([]byte(got), []byte(expected)) == 1
|
||||
}
|
||||
host := r.RemoteAddr
|
||||
if h, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
|
||||
host = h
|
||||
}
|
||||
ip := net.ParseIP(strings.Trim(strings.TrimSpace(host), "[]"))
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
// GET /api/internal/gateway/policy
|
||||
func (s *Server) getGatewayPolicy(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeGatewayRequest(r) {
|
||||
writeErr(w, http.StatusUnauthorized, "unauthorized gateway request")
|
||||
return
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
gwID := strings.TrimSpace(r.URL.Query().Get("gateway_id"))
|
||||
rt.mu.Lock()
|
||||
rt.gwLastSeen = time.Now()
|
||||
if gwID != "" {
|
||||
rt.gwID = gwID
|
||||
}
|
||||
gs := rt.gwSettings
|
||||
routesCopy := make(map[string]ContainerProxyRoute, len(rt.routes))
|
||||
for k, v := range rt.routes {
|
||||
routesCopy[k] = v
|
||||
}
|
||||
rt.mu.Unlock()
|
||||
|
||||
snap := traffic.GatewayPolicySnapshot{
|
||||
GlobalUpstreamURL: strings.TrimSpace(s.m.GlobalProxy()),
|
||||
ContainerRoutes: make(map[string]traffic.GatewayContainerRoute, len(routesCopy)),
|
||||
UDPPolicy: traffic.NormalizeUDPPolicy(gs.UDPPolicy),
|
||||
DNSUpstream: gs.DNSUpstream,
|
||||
}
|
||||
|
||||
if s.m.traffic != nil {
|
||||
if ssrf := s.m.traffic.SSRFGuardConfigSnapshot(); ssrf != nil && ssrf.Enabled {
|
||||
gp := &traffic.GatewaySSRFPolicy{
|
||||
Enabled: true,
|
||||
BlockPrivate: ssrf.BlockPrivate,
|
||||
BlockedHosts: ssrf.BlockedHosts,
|
||||
}
|
||||
for _, c := range ssrf.BlockedCIDRs {
|
||||
if c != nil {
|
||||
gp.BlockedCIDRs = append(gp.BlockedCIDRs, c.String())
|
||||
}
|
||||
}
|
||||
for _, ip := range ssrf.InfraIPs {
|
||||
if ip != nil {
|
||||
gp.InfraIPs = append(gp.InfraIPs, ip.String())
|
||||
}
|
||||
}
|
||||
snap.SSRF = gp
|
||||
}
|
||||
snap.PassthroughHosts = s.m.traffic.PassthroughHosts()
|
||||
}
|
||||
|
||||
// Global + synced egress blacklist rules.
|
||||
rules := s.loadCustomEgressBlacklist()
|
||||
if s.egressBlacklistSyncAssetEnabled() && s.m.pg != nil {
|
||||
if globalAssets, err := s.m.pg.ListAssetInterceptRules(); err == nil {
|
||||
rules = append(rules, translateAssetInterceptRules(globalAssets)...)
|
||||
}
|
||||
}
|
||||
snap.BlacklistRules = rules
|
||||
|
||||
// Active sandbox container IP map + task-level asset intercept rules.
|
||||
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
|
||||
ipSnap := mgr.ContainerIPSnapshot()
|
||||
snap.ContainerIPs = make(map[string]traffic.SourceIdentity, len(ipSnap))
|
||||
taskIDs := map[string]struct{}{}
|
||||
for ip, ci := range ipSnap {
|
||||
snap.ContainerIPs[ip] = traffic.SourceIdentity{
|
||||
Scope: string(ci.Scope),
|
||||
OwnerID: ci.OwnerID,
|
||||
ContainerID: ci.ContainerID,
|
||||
SrcIP: ip,
|
||||
}
|
||||
if ci.Scope == sandbox.ScopeTask && ci.OwnerID != "" {
|
||||
taskIDs[ci.OwnerID] = struct{}{}
|
||||
}
|
||||
}
|
||||
if s.egressBlacklistSyncAssetEnabled() && s.m.pg != nil && len(taskIDs) > 0 {
|
||||
snap.TaskRules = make(map[string][]traffic.EgressBlacklistRule, len(taskIDs))
|
||||
for tid := range taskIDs {
|
||||
if tr := s.loadTaskEgressRules(tid); len(tr) > 0 {
|
||||
snap.TaskRules[tid] = tr
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for key, route := range routesCopy {
|
||||
snap.ContainerRoutes[key] = traffic.GatewayContainerRoute{
|
||||
Scope: route.Scope,
|
||||
OwnerID: route.OwnerID,
|
||||
Mode: route.Mode,
|
||||
ProxyPoolID: route.ProxyPoolID,
|
||||
ProxyURL: maskSecrets(route.ProxyURL),
|
||||
EffectiveURL: s.resolveRouteEffectiveRawURL(route),
|
||||
Note: route.Note,
|
||||
UpdatedAt: route.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, 200, snap)
|
||||
}
|
||||
|
||||
// POST /api/internal/gateway/events
|
||||
func (s *Server) postGatewayEvents(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeGatewayRequest(r) {
|
||||
writeErr(w, http.StatusUnauthorized, "unauthorized gateway request")
|
||||
return
|
||||
}
|
||||
var batch traffic.GatewayEventBatch
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<20)).Decode(&batch); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid batch payload")
|
||||
return
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.Lock()
|
||||
rt.gwLastSeen = time.Now()
|
||||
if strings.TrimSpace(batch.GatewayID) != "" {
|
||||
rt.gwID = strings.TrimSpace(batch.GatewayID)
|
||||
}
|
||||
rt.mu.Unlock()
|
||||
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeJSON(w, 200, map[string]any{"ingested": 0})
|
||||
return
|
||||
}
|
||||
ingested := 0
|
||||
for _, nf := range batch.NetFlows {
|
||||
if err := tr.RecordNetFlow(nf); err == nil {
|
||||
ingested++
|
||||
}
|
||||
}
|
||||
for _, dq := range batch.DNSQueries {
|
||||
if err := tr.RecordDNSQuery(dq); err == nil {
|
||||
ingested++
|
||||
}
|
||||
}
|
||||
for _, ev := range batch.BlockEvents {
|
||||
tr.RecordBlockEvent(ev)
|
||||
ingested++
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ingested": ingested})
|
||||
}
|
||||
|
||||
// startEmbeddedTransparentGatewayIfConfigured optionally launches an in-process
|
||||
// TransparentGateway when bare-metal Linux operators set ARTEX_EMBEDDED_TRANSPARENT_TCP
|
||||
// / ARTEX_EMBEDDED_TRANSPARENT_DNS / ARTEX_EMBEDDED_TRANSPARENT_UDP directly on artex.
|
||||
func (s *Server) startEmbeddedTransparentGatewayIfConfigured() {
|
||||
if s.m.traffic == nil {
|
||||
return
|
||||
}
|
||||
tcpAddr := strings.TrimSpace(os.Getenv("ARTEX_EMBEDDED_TRANSPARENT_TCP"))
|
||||
dnsAddr := strings.TrimSpace(os.Getenv("ARTEX_EMBEDDED_TRANSPARENT_DNS"))
|
||||
udpAddr := strings.TrimSpace(os.Getenv("ARTEX_EMBEDDED_TRANSPARENT_UDP"))
|
||||
if tcpAddr == "" && dnsAddr == "" && udpAddr == "" {
|
||||
return
|
||||
}
|
||||
mitmAddr := strings.TrimSpace(s.m.ProxyAddr())
|
||||
if strings.HasPrefix(mitmAddr, ":") {
|
||||
mitmAddr = "127.0.0.1" + mitmAddr
|
||||
}
|
||||
gw := traffic.NewTransparentGateway(traffic.TransparentConfig{
|
||||
TCPAddr: tcpAddr,
|
||||
DNSAddr: dnsAddr,
|
||||
UDPAddr: udpAddr,
|
||||
MITMProxyAddr: mitmAddr,
|
||||
}, traffic.LocalTransparentBackend{T: s.m.traffic})
|
||||
if err := gw.Start(); err != nil {
|
||||
log.Printf("[gateway] embedded transparent gateway start failed: %v", err)
|
||||
return
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.Lock()
|
||||
rt.embeddedGW = gw
|
||||
rt.gwID = "embedded"
|
||||
rt.gwLastSeen = time.Now()
|
||||
rt.mu.Unlock()
|
||||
log.Printf("[gateway] embedded transparent gateway started tcp=%q dns=%q udp=%q", tcpAddr, dnsAddr, udpAddr)
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
func TestGatewaySyncAndNonHTTPTrafficAPIs(t *testing.T) {
|
||||
t.Setenv("ARTEX_GATEWAY_TOKEN", "test-gw-token-218")
|
||||
|
||||
tr, err := traffic.Open(t.TempDir(), "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("open traffic: %v", err)
|
||||
}
|
||||
defer tr.Close()
|
||||
|
||||
s := &Server{
|
||||
m: &Manager{
|
||||
traffic: tr,
|
||||
tasks: map[string]*Task{},
|
||||
},
|
||||
}
|
||||
s.initProxyRoutesAndGateway()
|
||||
|
||||
// 1. Unauthorized gateway policy request must be rejected with 401.
|
||||
reqUnauth := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy", nil)
|
||||
recUnauth := httptest.NewRecorder()
|
||||
s.getGatewayPolicy(recUnauth, reqUnauth)
|
||||
if recUnauth.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 for missing token, got %d", recUnauth.Code)
|
||||
}
|
||||
|
||||
// 2. Configure per-container proxy route + gateway settings.
|
||||
putRouteBody := `{"mode":"proxy","proxy_url":"socks5://127.0.0.1:1080","note":"task 5 socks5"}`
|
||||
reqRoute := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/5", bytes.NewBufferString(putRouteBody))
|
||||
reqRoute.SetPathValue("scope", "task")
|
||||
reqRoute.SetPathValue("owner_id", "5")
|
||||
recRoute := httptest.NewRecorder()
|
||||
s.putProxyRoute(recRoute, reqRoute)
|
||||
if recRoute.Code != http.StatusOK {
|
||||
t.Fatalf("putProxyRoute failed: %d %s", recRoute.Code, recRoute.Body.String())
|
||||
}
|
||||
|
||||
reqGW := httptest.NewRequest(http.MethodPut, "/api/proxy/gateway/settings", bytes.NewBufferString(`{"udp_policy":"block","dns_upstream":"1.1.1.1:53"}`))
|
||||
recGW := httptest.NewRecorder()
|
||||
s.updateGatewaySettings(recGW, reqGW)
|
||||
if recGW.Code != http.StatusOK {
|
||||
t.Fatalf("updateGatewaySettings failed: %d %s", recGW.Code, recGW.Body.String())
|
||||
}
|
||||
|
||||
// 3. Authorized gateway policy fetch returns route & settings.
|
||||
reqPol := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy?gateway_id=gw-test", nil)
|
||||
reqPol.Header.Set("X-Artex-Gateway-Token", "test-gw-token-218")
|
||||
recPol := httptest.NewRecorder()
|
||||
s.getGatewayPolicy(recPol, reqPol)
|
||||
if recPol.Code != http.StatusOK {
|
||||
t.Fatalf("getGatewayPolicy failed: %d %s", recPol.Code, recPol.Body.String())
|
||||
}
|
||||
var snap traffic.GatewayPolicySnapshot
|
||||
if err := json.Unmarshal(recPol.Body.Bytes(), &snap); err != nil {
|
||||
t.Fatalf("decode policy snapshot: %v", err)
|
||||
}
|
||||
if snap.UDPPolicy != traffic.UDPPolicyBlock || snap.DNSUpstream != "1.1.1.1:53" {
|
||||
t.Fatalf("unexpected gateway policy: %+v", snap)
|
||||
}
|
||||
if r, ok := snap.ContainerRoutes["task:5"]; !ok || r.EffectiveURL != "socks5://127.0.0.1:1080" {
|
||||
t.Fatalf("expected task:5 route in snapshot, got %+v", snap.ContainerRoutes)
|
||||
}
|
||||
|
||||
// 4. Ingest gateway events (net_flows + dns_queries + block_events).
|
||||
batch := traffic.GatewayEventBatch{
|
||||
GatewayID: "gw-test",
|
||||
NetFlows: []traffic.NetFlowRecord{{
|
||||
ID: "nf-test-1",
|
||||
TS: time.Now().Unix(),
|
||||
Protocol: "tcp",
|
||||
DstIP: "10.0.0.8",
|
||||
DstPort: 3306,
|
||||
DstHost: "db.target.local",
|
||||
Action: "allow",
|
||||
BytesTX: 64,
|
||||
BytesRX: 128,
|
||||
TXPreview: []byte("SELECT 1"),
|
||||
RXPreview: []byte("5.7.40-mysql"),
|
||||
SandboxScope: "task",
|
||||
SandboxOwnerID: "5",
|
||||
SrcIP: "172.30.0.5",
|
||||
}},
|
||||
DNSQueries: []traffic.DNSQueryRecord{{
|
||||
ID: "dns-test-1",
|
||||
TS: time.Now().Unix(),
|
||||
QName: "db.target.local",
|
||||
QType: "A",
|
||||
RCode: "NOERROR",
|
||||
Answers: []string{"10.0.0.8"},
|
||||
Action: "allow",
|
||||
Upstream: "direct:1.1.1.1:53",
|
||||
SandboxScope: "task",
|
||||
SandboxOwnerID: "5",
|
||||
SrcIP: "172.30.0.5",
|
||||
}},
|
||||
}
|
||||
rawBatch, _ := json.Marshal(batch)
|
||||
reqEv := httptest.NewRequest(http.MethodPost, "/api/internal/gateway/events", bytes.NewReader(rawBatch))
|
||||
reqEv.Header.Set("X-Artex-Gateway-Token", "test-gw-token-218")
|
||||
recEv := httptest.NewRecorder()
|
||||
s.postGatewayEvents(recEv, reqEv)
|
||||
if recEv.Code != http.StatusOK {
|
||||
t.Fatalf("postGatewayEvents failed: %d %s", recEv.Code, recEv.Body.String())
|
||||
}
|
||||
|
||||
// 5. Query flows + flow detail + DNS via public API handlers.
|
||||
recFlows := httptest.NewRecorder()
|
||||
s.getTrafficFlows(recFlows, httptest.NewRequest(http.MethodGet, "/api/traffic/flows?protocol=tcp", nil))
|
||||
if recFlows.Code != http.StatusOK {
|
||||
t.Fatalf("getTrafficFlows: %d %s", recFlows.Code, recFlows.Body.String())
|
||||
}
|
||||
var flowsResp struct {
|
||||
Total int `json:"total"`
|
||||
Flows []traffic.NetFlowRecord `json:"flows"`
|
||||
}
|
||||
_ = json.Unmarshal(recFlows.Body.Bytes(), &flowsResp)
|
||||
if flowsResp.Total != 1 || len(flowsResp.Flows) != 1 || flowsResp.Flows[0].DstPort != 3306 {
|
||||
t.Fatalf("unexpected flowsResp: %+v", flowsResp)
|
||||
}
|
||||
|
||||
reqDet := httptest.NewRequest(http.MethodGet, "/api/traffic/flows/nf-test-1", nil)
|
||||
reqDet.SetPathValue("id", "nf-test-1")
|
||||
recDet := httptest.NewRecorder()
|
||||
s.getTrafficFlowDetail(recDet, reqDet)
|
||||
if recDet.Code != http.StatusOK || !bytes.Contains(recDet.Body.Bytes(), []byte("SELECT 1")) {
|
||||
t.Fatalf("unexpected flow detail: %d %s", recDet.Code, recDet.Body.String())
|
||||
}
|
||||
|
||||
recDNS := httptest.NewRecorder()
|
||||
s.getTrafficDNS(recDNS, httptest.NewRequest(http.MethodGet, "/api/traffic/dns?q=db.target", nil))
|
||||
if recDNS.Code != http.StatusOK {
|
||||
t.Fatalf("getTrafficDNS: %d %s", recDNS.Code, recDNS.Body.String())
|
||||
}
|
||||
var dnsResp struct {
|
||||
Total int `json:"total"`
|
||||
Queries []traffic.DNSQueryRecord `json:"queries"`
|
||||
}
|
||||
_ = json.Unmarshal(recDNS.Body.Bytes(), &dnsResp)
|
||||
if dnsResp.Total != 1 || len(dnsResp.Queries) != 1 || dnsResp.Queries[0].QName != "db.target.local" {
|
||||
t.Fatalf("unexpected dnsResp: %+v", dnsResp)
|
||||
}
|
||||
|
||||
// 6. GET /api/proxy/routes reflects gateway connected=true and task:5 override.
|
||||
recRoutes := httptest.NewRecorder()
|
||||
s.getProxyRoutes(recRoutes, httptest.NewRequest(http.MethodGet, "/api/proxy/routes", nil))
|
||||
if recRoutes.Code != http.StatusOK {
|
||||
t.Fatalf("getProxyRoutes: %d %s", recRoutes.Code, recRoutes.Body.String())
|
||||
}
|
||||
body := recRoutes.Body.String()
|
||||
if !bytes.Contains([]byte(body), []byte(`"connected":true`)) || !bytes.Contains([]byte(body), []byte(`"socks5://127.0.0.1:1080"`)) {
|
||||
t.Fatalf("unexpected getProxyRoutes body: %s", body)
|
||||
}
|
||||
if bytes.Contains([]byte(body), []byte("全局")) {
|
||||
t.Fatalf("getProxyRoutes must not hardcode Chinese labels in API response: %s", body)
|
||||
}
|
||||
}
|
||||
@@ -2181,6 +2181,13 @@ func (m *Manager) DeleteTask(id string, opts DeleteTaskOptions) (DeleteTaskResul
|
||||
finalizeErrs = append(finalizeErrs, fmt.Errorf("finalize traffic deletion: %w", err))
|
||||
}
|
||||
}
|
||||
if opts.DeleteTraffic && m.traffic != nil {
|
||||
if deletedNonHTTP, err := m.traffic.DeleteNonHTTPByOwner("task", id); err != nil {
|
||||
finalizeErrs = append(finalizeErrs, fmt.Errorf("finalize non-http traffic deletion: %w", err))
|
||||
} else {
|
||||
result.TrafficDeleted += deletedNonHTTP
|
||||
}
|
||||
}
|
||||
if fileStage != nil {
|
||||
if err := fileStage.commit(); err != nil {
|
||||
finalizeErrs = append(finalizeErrs, fmt.Errorf("finalize task file deletion: %w", err))
|
||||
|
||||
+133
-5
@@ -8,11 +8,13 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
"github.com/Autumn-27/norma/mcp"
|
||||
@@ -186,12 +188,14 @@ func newSandboxStdioMCPClient(ctx context.Context, mgr *sandbox.Manager, target
|
||||
if strings.TrimSpace(workDir) != "" {
|
||||
containerWorkDir = sandbox.HostToContainerPath(mgr.Config().LocalRootFor(target), workDir)
|
||||
}
|
||||
envSlice := append([]string{}, mgr.ProxyEnv(true)...)
|
||||
for k, v := range env {
|
||||
envSlice = append(envSlice, k+"="+v)
|
||||
sandboxProxyURL := ""
|
||||
if mgr != nil {
|
||||
sandboxProxyURL = stripURLCredentials(mgr.Config().ProxyURL)
|
||||
}
|
||||
adaptedArgs := adaptSandboxMCPArgs(args, sandboxProxyURL)
|
||||
envSlice := buildSandboxMCPEnv(mgr, env)
|
||||
stream, err := mgr.ExecStream(ctx, target, sandbox.ExecSpec{
|
||||
Cmd: append([]string{command}, args...),
|
||||
Cmd: append([]string{command}, adaptedArgs...),
|
||||
WorkDir: containerWorkDir,
|
||||
Env: envSlice,
|
||||
})
|
||||
@@ -221,6 +225,130 @@ func newSandboxStdioMCPClient(ctx context.Context, mgr *sandbox.Manager, target
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// adaptSandboxMCPArgs rewrites loopback --proxy-server flags (such as
|
||||
// http://127.0.0.1:8788 persisted for local mode by syncBrowserMCPProxy) to the
|
||||
// sandbox-reachable recording proxy URL (e.g. http://172.30.0.2:8788).
|
||||
// Chromium rejects inline credentials in --proxy-server, so sandboxProxyURL must
|
||||
// be credential-free; Layer-1 container source IP provides attribution.
|
||||
func adaptSandboxMCPArgs(args []string, sandboxProxyURL string) []string {
|
||||
out := make([]string, 0, len(args))
|
||||
for i := 0; i < len(args); i++ {
|
||||
arg := args[i]
|
||||
if arg == "--proxy-server" && i+1 < len(args) {
|
||||
val := args[i+1]
|
||||
i++
|
||||
if isLoopbackProxyTarget(val) {
|
||||
if sandboxProxyURL != "" {
|
||||
out = append(out, "--proxy-server", sandboxProxyURL)
|
||||
}
|
||||
continue
|
||||
}
|
||||
out = append(out, "--proxy-server", val)
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(arg, "--proxy-server=") {
|
||||
val := strings.TrimPrefix(arg, "--proxy-server=")
|
||||
if isLoopbackProxyTarget(val) {
|
||||
if sandboxProxyURL != "" {
|
||||
out = append(out, "--proxy-server="+sandboxProxyURL)
|
||||
}
|
||||
continue
|
||||
}
|
||||
out = append(out, arg)
|
||||
continue
|
||||
}
|
||||
out = append(out, arg)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isLoopbackProxyTarget(raw string) bool {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return false
|
||||
}
|
||||
if !strings.Contains(raw, "://") {
|
||||
raw = "http://" + raw
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
h := strings.ToLower(strings.Trim(strings.TrimSpace(u.Hostname()), "[]"))
|
||||
if h == "localhost" || h == "0.0.0.0" || h == "::" {
|
||||
return true
|
||||
}
|
||||
if ip := net.ParseIP(h); ip != nil && (ip.IsLoopback() || ip.IsUnspecified()) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func stripURLCredentials(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return ""
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
u.User = nil
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// buildSandboxMCPEnv merges MCP-configured env vars with sandbox proxy/CA env
|
||||
// vars so host-side CA paths (like /app/data/traffic/_ca/mitmproxy-ca-cert.pem)
|
||||
// never clobber the in-container mounted CA path (/etc/artex/ca.crt).
|
||||
func buildSandboxMCPEnv(mgr *sandbox.Manager, userEnv map[string]string) []string {
|
||||
merged := make(map[string]string, len(userEnv)+12)
|
||||
hostCA := ""
|
||||
if mgr != nil {
|
||||
hostCA = strings.TrimSpace(mgr.Config().CACertPath)
|
||||
}
|
||||
for k, v := range userEnv {
|
||||
if isHostCAPathOverride(k, v, hostCA) {
|
||||
continue
|
||||
}
|
||||
merged[k] = v
|
||||
}
|
||||
if mgr != nil {
|
||||
for _, kv := range mgr.ProxyEnv(true) {
|
||||
if k, v, ok := strings.Cut(kv, "="); ok {
|
||||
merged[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
keys := make([]string, 0, len(merged))
|
||||
for k := range merged {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
out := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
out = append(out, k+"="+merged[k])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isHostCAPathOverride(key, val, hostCA string) bool {
|
||||
switch key {
|
||||
case "NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "GIT_SSL_CAINFO":
|
||||
v := strings.TrimSpace(val)
|
||||
if v == "" {
|
||||
return true
|
||||
}
|
||||
if hostCA != "" && v == hostCA {
|
||||
return true
|
||||
}
|
||||
// Persisted control-plane paths do not exist inside sandbox containers.
|
||||
if strings.HasPrefix(v, "/app/data/") || strings.Contains(v, "mitmproxy-ca-cert.pem") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *stdioMCPClient) readLoop(r io.Reader) {
|
||||
br := bufio.NewReaderSize(r, 64*1024)
|
||||
for {
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/internal/sandbox"
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
const (
|
||||
settingContainerProxyRoutes = "proxy_container_routes_json"
|
||||
settingGatewayPolicy = "proxy_gateway_settings_json"
|
||||
)
|
||||
|
||||
// ContainerProxyRoute persists a per-sandbox-owner upstream proxy override (#218 Phase 4).
|
||||
type ContainerProxyRoute struct {
|
||||
Scope string `json:"scope"` // task, session
|
||||
OwnerID string `json:"owner_id"` // task ID or session ID
|
||||
Mode string `json:"mode"` // inherit, direct, proxy
|
||||
ProxyPoolID string `json:"proxy_pool_id,omitempty"` // optional proxy pool entry ID
|
||||
ProxyURL string `json:"proxy_url,omitempty"` // raw custom URL in storage; masked in API output
|
||||
Note string `json:"note,omitempty"`
|
||||
UpdatedAt string `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
// GatewaySettings persists transparent gateway runtime policy knobs.
|
||||
type GatewaySettings struct {
|
||||
UDPPolicy string `json:"udp_policy"`
|
||||
DNSUpstream string `json:"dns_upstream"`
|
||||
}
|
||||
|
||||
type proxyRouteRuntime struct {
|
||||
mu sync.RWMutex
|
||||
routes map[string]ContainerProxyRoute // key: "scope:owner_id"
|
||||
gwSettings GatewaySettings
|
||||
gwID string
|
||||
gwLastSeen time.Time
|
||||
embeddedGW *traffic.TransparentGateway
|
||||
}
|
||||
|
||||
func (s *Server) ensureRouteRuntime() *proxyRouteRuntime {
|
||||
s.cfgMu.Lock()
|
||||
defer s.cfgMu.Unlock()
|
||||
if s.proxyRoutes == nil {
|
||||
s.proxyRoutes = &proxyRouteRuntime{
|
||||
routes: map[string]ContainerProxyRoute{},
|
||||
gwSettings: GatewaySettings{
|
||||
UDPPolicy: traffic.UDPPolicyBlockOnProxy,
|
||||
},
|
||||
}
|
||||
}
|
||||
return s.proxyRoutes
|
||||
}
|
||||
|
||||
func (s *Server) initProxyRoutesAndGateway() {
|
||||
rt := s.ensureRouteRuntime()
|
||||
// Load persisted per-container proxy routes.
|
||||
if s.m.pg != nil {
|
||||
if raw, ok, err := s.m.pg.GetSetting(settingContainerProxyRoutes); err == nil && ok && strings.TrimSpace(raw) != "" {
|
||||
var list []ContainerProxyRoute
|
||||
if json.Unmarshal([]byte(raw), &list) == nil {
|
||||
rt.mu.Lock()
|
||||
for _, r := range list {
|
||||
if r.Scope != "" && r.OwnerID != "" {
|
||||
rt.routes[r.Scope+":"+r.OwnerID] = r
|
||||
}
|
||||
}
|
||||
rt.mu.Unlock()
|
||||
}
|
||||
}
|
||||
if raw, ok, err := s.m.pg.GetSetting(settingGatewayPolicy); err == nil && ok && strings.TrimSpace(raw) != "" {
|
||||
var gs GatewaySettings
|
||||
if json.Unmarshal([]byte(raw), &gs) == nil {
|
||||
gs.UDPPolicy = traffic.NormalizeUDPPolicy(gs.UDPPolicy)
|
||||
gs.DNSUpstream = strings.TrimSpace(gs.DNSUpstream)
|
||||
rt.mu.Lock()
|
||||
rt.gwSettings = gs
|
||||
rt.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if s.m.traffic != nil {
|
||||
rt.mu.RLock()
|
||||
gs := rt.gwSettings
|
||||
rt.mu.RUnlock()
|
||||
s.m.traffic.SetGatewaySettings(gs.UDPPolicy, gs.DNSUpstream)
|
||||
s.m.traffic.SetUpstreamResolver(s.resolveContainerUpstream)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) resolvePoolEntryRawURL(poolID string) string {
|
||||
poolID = strings.TrimSpace(poolID)
|
||||
if poolID == "" {
|
||||
return ""
|
||||
}
|
||||
for _, e := range s.m.proxyPoolEntries() {
|
||||
if e.ID == poolID {
|
||||
return strings.TrimSpace(e.RawURL)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) resolveRouteEffectiveRawURL(r ContainerProxyRoute) string {
|
||||
if strings.ToLower(strings.TrimSpace(r.Mode)) != "proxy" {
|
||||
return ""
|
||||
}
|
||||
if r.ProxyPoolID != "" {
|
||||
if raw := s.resolvePoolEntryRawURL(r.ProxyPoolID); raw != "" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(r.ProxyURL)
|
||||
}
|
||||
|
||||
func (s *Server) resolveContainerUpstream(src traffic.SourceIdentity) (*url.URL, bool) {
|
||||
if src.Scope == "" || src.OwnerID == "" {
|
||||
return nil, false
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.RLock()
|
||||
r, ok := rt.routes[src.Scope+":"+src.OwnerID]
|
||||
rt.mu.RUnlock()
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(r.Mode)) {
|
||||
case "direct":
|
||||
return nil, true
|
||||
case "proxy":
|
||||
raw := s.resolveRouteEffectiveRawURL(r)
|
||||
if raw == "" {
|
||||
return nil, false
|
||||
}
|
||||
u, err := traffic.ValidateProxyURL(raw)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return u, true
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) saveContainerProxyRoutesLocked(rt *proxyRouteRuntime) error {
|
||||
if s.m.pg == nil {
|
||||
return nil
|
||||
}
|
||||
list := make([]ContainerProxyRoute, 0, len(rt.routes))
|
||||
for _, r := range rt.routes {
|
||||
list = append(list, r)
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool {
|
||||
if list[i].Scope != list[j].Scope {
|
||||
return list[i].Scope < list[j].Scope
|
||||
}
|
||||
return list[i].OwnerID < list[j].OwnerID
|
||||
})
|
||||
b, err := json.Marshal(list)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.m.pg.SetSetting(settingContainerProxyRoutes, string(b))
|
||||
}
|
||||
|
||||
func (s *Server) maskedRouteView(r ContainerProxyRoute) ContainerProxyRoute {
|
||||
out := r
|
||||
if out.ProxyURL != "" {
|
||||
out.ProxyURL = maskSecrets(out.ProxyURL)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type containerRouteStatusItem struct {
|
||||
Scope string `json:"scope"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
ContainerName string `json:"container_name,omitempty"`
|
||||
ContainerID string `json:"container_id,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
Mode string `json:"mode"` // inherit, direct, proxy
|
||||
ProxyPoolID string `json:"proxy_pool_id,omitempty"`
|
||||
ProxyURL string `json:"proxy_url,omitempty"`
|
||||
EffectiveProxy string `json:"effective_proxy"`
|
||||
Note string `json:"note,omitempty"`
|
||||
UpdatedAt string `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
// GET /api/proxy/routes
|
||||
func (s *Server) getProxyRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.RLock()
|
||||
routesMap := make(map[string]ContainerProxyRoute, len(rt.routes))
|
||||
for k, v := range rt.routes {
|
||||
routesMap[k] = v
|
||||
}
|
||||
gs := rt.gwSettings
|
||||
gwID := rt.gwID
|
||||
gwLast := rt.gwLastSeen
|
||||
embedded := rt.embeddedGW != nil
|
||||
rt.mu.RUnlock()
|
||||
|
||||
globalRaw := strings.TrimSpace(s.m.GlobalProxy())
|
||||
globalDisplay := "direct"
|
||||
if globalRaw != "" {
|
||||
globalDisplay = maskSecrets(globalRaw)
|
||||
}
|
||||
|
||||
effectiveFor := func(route *ContainerProxyRoute) string {
|
||||
if route == nil || route.Mode == "" || route.Mode == "inherit" {
|
||||
return globalDisplay
|
||||
}
|
||||
if route.Mode == "direct" {
|
||||
return "direct"
|
||||
}
|
||||
if raw := s.resolveRouteEffectiveRawURL(*route); raw != "" {
|
||||
return maskSecrets(raw)
|
||||
}
|
||||
return globalDisplay
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
items := make([]containerRouteStatusItem, 0, len(routesMap)+4)
|
||||
|
||||
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||
st := mgr.StatusWithStats(ctx, false)
|
||||
cancel()
|
||||
ipSnap := mgr.ContainerIPSnapshot()
|
||||
ipByName := map[string]string{}
|
||||
for ip, id := range ipSnap {
|
||||
ipByName[id.ContainerName] = ip
|
||||
}
|
||||
for _, c := range st.Containers {
|
||||
key := string(c.Scope) + ":" + c.OwnerID
|
||||
seen[key] = true
|
||||
var rPtr *ContainerProxyRoute
|
||||
mode := "inherit"
|
||||
var poolID, proxyURL, note, updatedAt string
|
||||
if existing, ok := routesMap[key]; ok {
|
||||
cp := existing
|
||||
rPtr = &cp
|
||||
mode = existing.Mode
|
||||
poolID = existing.ProxyPoolID
|
||||
proxyURL = maskSecrets(existing.ProxyURL)
|
||||
note = existing.Note
|
||||
updatedAt = existing.UpdatedAt
|
||||
}
|
||||
items = append(items, containerRouteStatusItem{
|
||||
Scope: string(c.Scope),
|
||||
OwnerID: c.OwnerID,
|
||||
ContainerName: c.Name,
|
||||
ContainerID: c.ShortID,
|
||||
State: c.State,
|
||||
IP: ipByName[c.Name],
|
||||
Mode: mode,
|
||||
ProxyPoolID: poolID,
|
||||
ProxyURL: proxyURL,
|
||||
EffectiveProxy: effectiveFor(rPtr),
|
||||
Note: note,
|
||||
UpdatedAt: updatedAt,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Include persisted route rules for tasks/sessions without a currently present container.
|
||||
for key, route := range routesMap {
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
cp := route
|
||||
items = append(items, containerRouteStatusItem{
|
||||
Scope: route.Scope,
|
||||
OwnerID: route.OwnerID,
|
||||
State: "inactive",
|
||||
Mode: route.Mode,
|
||||
ProxyPoolID: route.ProxyPoolID,
|
||||
ProxyURL: maskSecrets(route.ProxyURL),
|
||||
EffectiveProxy: effectiveFor(&cp),
|
||||
Note: route.Note,
|
||||
UpdatedAt: route.UpdatedAt,
|
||||
})
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
if items[i].Scope != items[j].Scope {
|
||||
return items[i].Scope < items[j].Scope
|
||||
}
|
||||
return items[i].OwnerID < items[j].OwnerID
|
||||
})
|
||||
|
||||
routesList := make([]ContainerProxyRoute, 0, len(routesMap))
|
||||
for _, route := range routesMap {
|
||||
routesList = append(routesList, s.maskedRouteView(route))
|
||||
}
|
||||
sort.Slice(routesList, func(i, j int) bool {
|
||||
if routesList[i].Scope != routesList[j].Scope {
|
||||
return routesList[i].Scope < routesList[j].Scope
|
||||
}
|
||||
return routesList[i].OwnerID < routesList[j].OwnerID
|
||||
})
|
||||
|
||||
connected := embedded || (!gwLast.IsZero() && time.Since(gwLast) < 15*time.Second)
|
||||
var lastSeenStr string
|
||||
if !gwLast.IsZero() {
|
||||
lastSeenStr = gwLast.UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"global_proxy": globalDisplay,
|
||||
"routes": routesList,
|
||||
"containers": items,
|
||||
"gateway": map[string]any{
|
||||
"connected": connected,
|
||||
"embedded": embedded,
|
||||
"gateway_id": gwID,
|
||||
"last_seen": lastSeenStr,
|
||||
"udp_policy": traffic.NormalizeUDPPolicy(gs.UDPPolicy),
|
||||
"dns_upstream": gs.DNSUpstream,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// PUT /api/proxy/routes/{scope}/{owner_id}
|
||||
func (s *Server) putProxyRoute(w http.ResponseWriter, r *http.Request) {
|
||||
scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope")))
|
||||
ownerID := strings.TrimSpace(r.PathValue("owner_id"))
|
||||
if (scope != "task" && scope != "session") || ownerID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "invalid scope or owner_id (scope must be task or session)")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Mode string `json:"mode"`
|
||||
ProxyPoolID string `json:"proxy_pool_id"`
|
||||
ProxyURL string `json:"proxy_url"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
mode := strings.ToLower(strings.TrimSpace(req.Mode))
|
||||
if mode == "" {
|
||||
mode = "inherit"
|
||||
}
|
||||
if mode != "inherit" && mode != "direct" && mode != "proxy" {
|
||||
writeErr(w, http.StatusBadRequest, "mode must be inherit, direct, or proxy")
|
||||
return
|
||||
}
|
||||
|
||||
rt := s.ensureRouteRuntime()
|
||||
key := scope + ":" + ownerID
|
||||
|
||||
if mode == "inherit" {
|
||||
rt.mu.Lock()
|
||||
delete(rt.routes, key)
|
||||
err := s.saveContainerProxyRoutesLocked(rt)
|
||||
rt.mu.Unlock()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, ContainerProxyRoute{Scope: scope, OwnerID: ownerID, Mode: "inherit"})
|
||||
return
|
||||
}
|
||||
|
||||
route := ContainerProxyRoute{
|
||||
Scope: scope,
|
||||
OwnerID: ownerID,
|
||||
Mode: mode,
|
||||
ProxyPoolID: strings.TrimSpace(req.ProxyPoolID),
|
||||
ProxyURL: strings.TrimSpace(req.ProxyURL),
|
||||
Note: strings.TrimSpace(req.Note),
|
||||
UpdatedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
if mode == "proxy" {
|
||||
if route.ProxyPoolID != "" {
|
||||
if s.resolvePoolEntryRawURL(route.ProxyPoolID) == "" {
|
||||
writeErr(w, http.StatusBadRequest, fmt.Sprintf("proxy_pool_id %q not found", route.ProxyPoolID))
|
||||
return
|
||||
}
|
||||
route.ProxyURL = ""
|
||||
} else {
|
||||
// If user left masked placeholder unchanged, preserve existing raw URL.
|
||||
if strings.Contains(route.ProxyURL, "***") {
|
||||
rt.mu.RLock()
|
||||
if prev, ok := rt.routes[key]; ok && prev.ProxyURL != "" {
|
||||
route.ProxyURL = prev.ProxyURL
|
||||
}
|
||||
rt.mu.RUnlock()
|
||||
}
|
||||
if _, err := traffic.ValidateProxyURL(route.ProxyURL); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
route.ProxyPoolID = ""
|
||||
route.ProxyURL = ""
|
||||
}
|
||||
|
||||
rt.mu.Lock()
|
||||
rt.routes[key] = route
|
||||
err := s.saveContainerProxyRoutesLocked(rt)
|
||||
rt.mu.Unlock()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, s.maskedRouteView(route))
|
||||
}
|
||||
|
||||
// DELETE /api/proxy/routes/{scope}/{owner_id}
|
||||
func (s *Server) deleteProxyRoute(w http.ResponseWriter, r *http.Request) {
|
||||
scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope")))
|
||||
ownerID := strings.TrimSpace(r.PathValue("owner_id"))
|
||||
if scope == "" || ownerID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "missing scope or owner_id")
|
||||
return
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.Lock()
|
||||
delete(rt.routes, scope+":"+ownerID)
|
||||
err := s.saveContainerProxyRoutesLocked(rt)
|
||||
rt.mu.Unlock()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"deleted": scope + ":" + ownerID})
|
||||
}
|
||||
|
||||
// PUT /api/proxy/gateway/settings
|
||||
func (s *Server) updateGatewaySettings(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
UDPPolicy string `json:"udp_policy"`
|
||||
DNSUpstream string `json:"dns_upstream"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
gs := GatewaySettings{
|
||||
UDPPolicy: traffic.NormalizeUDPPolicy(req.UDPPolicy),
|
||||
DNSUpstream: strings.TrimSpace(req.DNSUpstream),
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.Lock()
|
||||
rt.gwSettings = gs
|
||||
rt.mu.Unlock()
|
||||
if s.m.pg != nil {
|
||||
if b, err := json.Marshal(gs); err == nil {
|
||||
_ = s.m.pg.SetSetting(settingGatewayPolicy, string(b))
|
||||
}
|
||||
}
|
||||
if s.m.traffic != nil {
|
||||
s.m.traffic.SetGatewaySettings(gs.UDPPolicy, gs.DNSUpstream)
|
||||
}
|
||||
writeJSON(w, 200, gs)
|
||||
}
|
||||
+28
-1
@@ -42,11 +42,26 @@ func (s *Server) initSandbox() {
|
||||
}
|
||||
}
|
||||
sandbox.SetDefault(mgr)
|
||||
// Build merged system + MITM CA bundle so sandbox containers trust the recording
|
||||
// proxy at the system CA store level (/etc/ssl/certs/ca-certificates.crt) without root.
|
||||
if s.m.traffic != nil {
|
||||
if bundle := s.m.traffic.EnsureSystemCABundle(); bundle != "" {
|
||||
mgr.SetSystemCABundlePath(bundle)
|
||||
}
|
||||
s.m.traffic.SetGatewayToken(os.Getenv("ARTEX_GATEWAY_TOKEN"))
|
||||
}
|
||||
// Always load persisted egress blacklist rules, per-container proxy routes,
|
||||
// gateway settings, and task-level egress checker (works in both local & Docker modes).
|
||||
s.syncEgressBlacklist()
|
||||
s.initProxyRoutesAndGateway()
|
||||
if s.m.traffic != nil {
|
||||
s.m.traffic.SetTaskBlacklistChecker(s.checkTaskEgressBlacklist)
|
||||
}
|
||||
s.startEmbeddedTransparentGatewayIfConfigured()
|
||||
if !mgr.Enabled() {
|
||||
log.Printf("[sandbox] mode=local (set ARTEX_SANDBOX_MODE=docker to enable container isolation)")
|
||||
return
|
||||
}
|
||||
|
||||
validTasks := map[string]bool{}
|
||||
for _, t := range s.m.List() {
|
||||
validTasks[t.ID] = true
|
||||
@@ -86,6 +101,18 @@ func (s *Server) initSandbox() {
|
||||
BlockedCIDRs: mgr.SandboxSubnets(),
|
||||
InfraIPs: parseProtectIPs(os.Getenv("ARTEX_PROXY_PROTECT_IPS")),
|
||||
})
|
||||
s.m.traffic.SetSourceResolver(func(srcIP string) (traffic.SourceIdentity, bool) {
|
||||
id, ok := mgr.ResolveContainerByIP(srcIP)
|
||||
if !ok {
|
||||
return traffic.SourceIdentity{}, false
|
||||
}
|
||||
return traffic.SourceIdentity{
|
||||
Scope: string(id.Scope),
|
||||
OwnerID: id.OwnerID,
|
||||
ContainerID: id.ContainerID,
|
||||
SrcIP: srcIP,
|
||||
}, true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+53
-27
@@ -144,8 +144,9 @@ type Server struct {
|
||||
proxyPoolTickMu sync.Mutex
|
||||
// proxyProbe is injectable for deterministic reconnect race tests. Production
|
||||
// servers leave it nil and use probeEgress directly.
|
||||
proxyProbe func(context.Context, string, string, []string, time.Duration) egressProbeResult
|
||||
side *sideQuestionState
|
||||
proxyProbe func(context.Context, string, string, []string, time.Duration) egressProbeResult
|
||||
proxyRoutes *proxyRouteRuntime
|
||||
side *sideQuestionState
|
||||
}
|
||||
|
||||
// provEntry is a cached provider + its config for one LLM profile id.
|
||||
@@ -332,6 +333,15 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
|
||||
func (s *Server) Close() {
|
||||
if s != nil {
|
||||
s.proxyPoolWG.Wait()
|
||||
if s.proxyRoutes != nil {
|
||||
s.proxyRoutes.mu.Lock()
|
||||
gw := s.proxyRoutes.embeddedGW
|
||||
s.proxyRoutes.embeddedGW = nil
|
||||
s.proxyRoutes.mu.Unlock()
|
||||
if gw != nil {
|
||||
_ = gw.Close()
|
||||
}
|
||||
}
|
||||
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
|
||||
sctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
mgr.Shutdown(sctx)
|
||||
@@ -998,6 +1008,11 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("DELETE /api/traffic/all", s.deleteAllTraffic)
|
||||
mux.HandleFunc("GET /api/traffic/exchange", s.getTrafficExchange)
|
||||
mux.HandleFunc("GET /api/traffic/blob", s.getTrafficBlob)
|
||||
mux.HandleFunc("GET /api/traffic/flows", s.getTrafficFlows)
|
||||
mux.HandleFunc("GET /api/traffic/flows/{id}", s.getTrafficFlowDetail)
|
||||
mux.HandleFunc("DELETE /api/traffic/flows", s.deleteTrafficFlows)
|
||||
mux.HandleFunc("GET /api/traffic/dns", s.getTrafficDNS)
|
||||
mux.HandleFunc("DELETE /api/traffic/dns", s.deleteTrafficDNS)
|
||||
mux.HandleFunc("GET /api/commands", s.pgListCommands)
|
||||
mux.HandleFunc("GET /api/commands/stats", s.pgToolStats) // 按工具聚合调用次数
|
||||
mux.HandleFunc("GET /api/llm/records", s.pgListLLMRecords)
|
||||
@@ -1043,8 +1058,19 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("DELETE /api/settings/proxy-pool/{id}", s.deleteProxyPool)
|
||||
mux.HandleFunc("POST /api/settings/proxy-pool/{id}/test", s.testProxyPoolEntry)
|
||||
mux.HandleFunc("POST /api/settings/proxy-pool/test-all", s.testAllProxyPool)
|
||||
mux.HandleFunc("GET /api/proxy/blacklist", s.getEgressBlacklist)
|
||||
mux.HandleFunc("PUT /api/proxy/blacklist/settings", s.updateEgressBlacklistSettings)
|
||||
mux.HandleFunc("POST /api/proxy/blacklist/rules", s.createEgressBlacklistRule)
|
||||
mux.HandleFunc("PUT /api/proxy/blacklist/rules/{id}", s.updateEgressBlacklistRule)
|
||||
mux.HandleFunc("DELETE /api/proxy/blacklist/rules/{id}", s.deleteEgressBlacklistRule)
|
||||
mux.HandleFunc("DELETE /api/proxy/blacklist/events", s.clearEgressBlockEvents)
|
||||
mux.HandleFunc("GET /api/proxy/routes", s.getProxyRoutes)
|
||||
mux.HandleFunc("PUT /api/proxy/routes/{scope}/{owner_id}", s.putProxyRoute)
|
||||
mux.HandleFunc("DELETE /api/proxy/routes/{scope}/{owner_id}", s.deleteProxyRoute)
|
||||
mux.HandleFunc("PUT /api/proxy/gateway/settings", s.updateGatewaySettings)
|
||||
mux.HandleFunc("GET /api/internal/gateway/policy", s.getGatewayPolicy)
|
||||
mux.HandleFunc("POST /api/internal/gateway/events", s.postGatewayEvents)
|
||||
mux.HandleFunc("POST /api/settings/proxy-pool/{id}/activate", s.activateProxyPool)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/proxy/test", s.testTaskProxy)
|
||||
mux.HandleFunc("GET /api/report", s.getReport)
|
||||
mux.HandleFunc("GET /api/chat/mentions", s.searchChatMentions)
|
||||
mux.HandleFunc("POST /api/chat", s.chat)
|
||||
@@ -3717,8 +3743,9 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) {
|
||||
page := atoiDefault(q.Get("page"), 0)
|
||||
size := atoiDefault(q.Get("size"), 100)
|
||||
var taskHosts []string
|
||||
var rawTaskID string
|
||||
taskScoped := false
|
||||
if rawTaskID := strings.TrimSpace(q.Get("task_id")); rawTaskID != "" {
|
||||
if rawTaskID = strings.TrimSpace(q.Get("task_id")); rawTaskID != "" {
|
||||
taskScoped = true
|
||||
taskID, err := strconv.ParseInt(rawTaskID, 10, 64)
|
||||
if err != nil || taskID <= 0 || s.m.ResolveTask(rawTaskID) == nil {
|
||||
@@ -3731,25 +3758,25 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if taskScoped && len(taskHosts) == 0 {
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"enabled": s.m.TrafficEnabled(), "proxy": s.m.ProxyAddr(), "count": 0,
|
||||
"total": 0, "page": page, "size": size, "exchanges": []any{},
|
||||
})
|
||||
return
|
||||
}
|
||||
intentID, _ := strconv.ParseInt(strings.TrimSpace(q.Get("intent_id")), 10, 64)
|
||||
pageQuery := traffic.PageQuery{
|
||||
Hosts: taskHosts,
|
||||
Host: q.Get("host"),
|
||||
Method: q.Get("method"),
|
||||
Query: q.Get("q"),
|
||||
Body: q.Get("body"),
|
||||
Path: q.Get("path"),
|
||||
Status: q.Get("status"),
|
||||
RespMin: int64(atoiDefault(q.Get("resp_min"), -1)),
|
||||
RespMax: int64(atoiDefault(q.Get("resp_max"), -1)),
|
||||
Sort: q.Get("sort"),
|
||||
Order: q.Get("order"),
|
||||
Hosts: taskHosts,
|
||||
OwnerTaskID: rawTaskID,
|
||||
SandboxScope: q.Get("scope"),
|
||||
SandboxOwnerID: q.Get("owner_id"),
|
||||
ContainerID: q.Get("container_id"),
|
||||
SessionID: q.Get("session_id"),
|
||||
IntentID: intentID,
|
||||
Host: q.Get("host"),
|
||||
Method: q.Get("method"),
|
||||
Query: q.Get("q"),
|
||||
Body: q.Get("body"),
|
||||
Path: q.Get("path"),
|
||||
Status: q.Get("status"),
|
||||
RespMin: int64(atoiDefault(q.Get("resp_min"), -1)),
|
||||
RespMax: int64(atoiDefault(q.Get("resp_max"), -1)),
|
||||
Sort: q.Get("sort"),
|
||||
Order: q.Get("order"),
|
||||
}
|
||||
ex, matched, _ := tr.Page(pageQuery, page, size)
|
||||
count, _ := tr.Count() // global total, for the stat card
|
||||
@@ -3778,7 +3805,8 @@ func (s *Server) getTrafficHosts(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
var hosts []string
|
||||
if rawTaskID := strings.TrimSpace(r.URL.Query().Get("task_id")); rawTaskID != "" {
|
||||
rawTaskID := strings.TrimSpace(r.URL.Query().Get("task_id"))
|
||||
if rawTaskID != "" {
|
||||
taskID, err := strconv.ParseInt(rawTaskID, 10, 64)
|
||||
if err != nil || taskID <= 0 || s.m.ResolveTask(rawTaskID) == nil {
|
||||
writeErr(w, http.StatusNotFound, "task not found")
|
||||
@@ -3792,10 +3820,8 @@ func (s *Server) getTrafficHosts(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
var result []traffic.HostCount
|
||||
var err error
|
||||
if len(hosts) > 0 {
|
||||
result, err = tr.HostsForScope(hosts)
|
||||
} else if r.URL.Query().Get("task_id") != "" {
|
||||
result = []traffic.HostCount{}
|
||||
if rawTaskID != "" {
|
||||
result, err = tr.HostsForTask(rawTaskID, hosts)
|
||||
} else {
|
||||
result, err = tr.Hosts()
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ func (s *Server) taskInterceptCreateRule(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
taskEgressRulesCache.Delete(taskID)
|
||||
writeJSON(w, 200, rule)
|
||||
}
|
||||
|
||||
@@ -133,6 +134,7 @@ func (s *Server) taskInterceptUpdateRule(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
taskEgressRulesCache.Delete(taskID)
|
||||
writeJSON(w, 200, rule)
|
||||
}
|
||||
|
||||
@@ -156,6 +158,7 @@ func (s *Server) taskInterceptDeleteRule(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
taskEgressRulesCache.Delete(taskID)
|
||||
writeJSON(w, 200, map[string]any{"deleted": deleted})
|
||||
}
|
||||
|
||||
@@ -185,5 +188,6 @@ func (s *Server) taskInterceptToggleRule(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
taskEgressRulesCache.Delete(taskID)
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "enabled": req.Enabled})
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/traffic"
|
||||
)
|
||||
|
||||
// GET /api/traffic/flows
|
||||
func (s *Server) getTrafficFlows(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeJSON(w, 200, map[string]any{"enabled": false, "flows": []any{}, "total": 0, "count": 0})
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
page := atoiDefault(q.Get("page"), 0)
|
||||
size := atoiDefault(q.Get("size"), 100)
|
||||
rawTaskID := strings.TrimSpace(q.Get("task_id"))
|
||||
if rawTaskID != "" && s.m.ResolveTask(rawTaskID) == nil {
|
||||
writeErr(w, http.StatusNotFound, "task not found")
|
||||
return
|
||||
}
|
||||
rows, total, err := tr.PageNetFlows(traffic.NetFlowQuery{
|
||||
Protocol: q.Get("protocol"),
|
||||
Action: q.Get("action"),
|
||||
OwnerTaskID: rawTaskID,
|
||||
SandboxScope: q.Get("scope"),
|
||||
SandboxOwnerID: q.Get("owner_id"),
|
||||
ContainerID: q.Get("container_id"),
|
||||
Query: q.Get("q"),
|
||||
}, page, size)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
count, _ := tr.CountNetFlows()
|
||||
if rawTaskID != "" {
|
||||
count = total
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"enabled": s.m.TrafficEnabled(),
|
||||
"count": count,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"flows": rows,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /api/traffic/flows/{id}
|
||||
func (s *Server) getTrafficFlowDetail(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeErr(w, http.StatusNotFound, "traffic disabled")
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(r.PathValue("id"))
|
||||
if id == "" {
|
||||
writeErr(w, http.StatusBadRequest, "missing id")
|
||||
return
|
||||
}
|
||||
flow, err := tr.GetNetFlow(id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, flow)
|
||||
}
|
||||
|
||||
// DELETE /api/traffic/flows
|
||||
func (s *Server) deleteTrafficFlows(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeErr(w, http.StatusNotFound, "traffic disabled")
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
scope := strings.TrimSpace(q.Get("scope"))
|
||||
ownerID := strings.TrimSpace(q.Get("owner_id"))
|
||||
if tid := strings.TrimSpace(q.Get("task_id")); tid != "" && scope == "" {
|
||||
scope = "task"
|
||||
ownerID = tid
|
||||
}
|
||||
n, err := tr.DeleteNetFlows(scope, ownerID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"deleted": n})
|
||||
}
|
||||
|
||||
// GET /api/traffic/dns
|
||||
func (s *Server) getTrafficDNS(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeJSON(w, 200, map[string]any{"enabled": false, "queries": []any{}, "total": 0, "count": 0})
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
page := atoiDefault(q.Get("page"), 0)
|
||||
size := atoiDefault(q.Get("size"), 100)
|
||||
rawTaskID := strings.TrimSpace(q.Get("task_id"))
|
||||
if rawTaskID != "" && s.m.ResolveTask(rawTaskID) == nil {
|
||||
writeErr(w, http.StatusNotFound, "task not found")
|
||||
return
|
||||
}
|
||||
rows, total, err := tr.PageDNSQueries(traffic.DNSQueryFilter{
|
||||
QType: q.Get("qtype"),
|
||||
RCode: q.Get("rcode"),
|
||||
Action: q.Get("action"),
|
||||
OwnerTaskID: rawTaskID,
|
||||
SandboxScope: q.Get("scope"),
|
||||
SandboxOwnerID: q.Get("owner_id"),
|
||||
ContainerID: q.Get("container_id"),
|
||||
Query: q.Get("q"),
|
||||
}, page, size)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
count, _ := tr.CountDNSQueries()
|
||||
if rawTaskID != "" {
|
||||
count = total
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"enabled": s.m.TrafficEnabled(),
|
||||
"count": count,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
"queries": rows,
|
||||
})
|
||||
}
|
||||
|
||||
// DELETE /api/traffic/dns
|
||||
func (s *Server) deleteTrafficDNS(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeErr(w, http.StatusNotFound, "traffic disabled")
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
scope := strings.TrimSpace(q.Get("scope"))
|
||||
ownerID := strings.TrimSpace(q.Get("owner_id"))
|
||||
if tid := strings.TrimSpace(q.Get("task_id")); tid != "" && scope == "" {
|
||||
scope = "task"
|
||||
ownerID = tid
|
||||
}
|
||||
n, err := tr.DeleteDNSQueries(scope, ownerID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"deleted": n})
|
||||
}
|
||||
Reference in new issue
Block a user