mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-02 20:01:51 +08:00
fix(traffic,server,sandbox): fix TCP/53 false positives, add error-traffic storage toggle, and fix spawn_task/sandbox polling
- Route external TCP/53 through netstack deferred handshake and real-target DNS inspection (RFC 7766 single-write framing) instead of hijacking to host DNS. - Preserve explicit targetServer in ProcessDNSQueryToTarget under upstream proxy so external UDP/53 probes never fall back to host DNSUpstream. - Default error traffic storage (net_flows/dns_queries action=error) to off with hot-toggle controls synced across gateway, Proxy & Egress, and Traffic pages. - Restore json.Unmarshal in spawn_task orchestration tool and poll live sandbox container state in chat/task controls.
This commit is contained in:
1 parent
07309e4530
commit
d5926d6420
22 files changed
+1189
-101
No files matched your search
@@ -56,6 +56,7 @@ func (s *Server) getGatewayPolicy(w http.ResponseWriter, r *http.Request) {
|
||||
ContainerRoutes: make(map[string]traffic.GatewayContainerRoute, len(routesCopy)),
|
||||
UDPPolicy: traffic.NormalizeUDPPolicy(gs.UDPPolicy),
|
||||
DNSUpstream: gs.DNSUpstream,
|
||||
StoreErrorTraffic: gs.StoreErrorTraffic,
|
||||
}
|
||||
|
||||
if s.m.traffic != nil {
|
||||
|
||||
@@ -166,3 +166,114 @@ func TestGatewaySyncAndNonHTTPTrafficAPIs(t *testing.T) {
|
||||
t.Fatalf("getProxyRoutes must not hardcode Chinese labels in API response: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreErrorTrafficPolicyPartialUpdateAndIngestion(t *testing.T) {
|
||||
t.Setenv("ARTEX_GATEWAY_TOKEN", "test-gw-token-err")
|
||||
|
||||
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()
|
||||
|
||||
// Set UDP & DNS first; store_error_traffic remains default false.
|
||||
recSet := httptest.NewRecorder()
|
||||
s.updateGatewaySettings(recSet, httptest.NewRequest(http.MethodPut, "/api/proxy/gateway/settings", bytes.NewBufferString(`{"udp_policy":"direct","dns_upstream":"9.9.9.9:53"}`)))
|
||||
if recSet.Code != http.StatusOK {
|
||||
t.Fatalf("updateGatewaySettings initial failed: %d %s", recSet.Code, recSet.Body.String())
|
||||
}
|
||||
|
||||
// Ingest an error flow & an allow flow while store_error_traffic=false.
|
||||
rawBatch, _ := json.Marshal(traffic.GatewayEventBatch{
|
||||
GatewayID: "gw-err",
|
||||
NetFlows: []traffic.NetFlowRecord{
|
||||
{ID: "nf-ok", TS: time.Now().Unix(), Protocol: "tcp", DstIP: "1.1.1.1", DstPort: 80, Action: "allow"},
|
||||
{ID: "nf-err-1", TS: time.Now().Unix(), Protocol: "tcp", DstIP: "1.1.1.2", DstPort: 81, Action: "error", Error: "refused"},
|
||||
},
|
||||
DNSQueries: []traffic.DNSQueryRecord{
|
||||
{ID: "dns-ok", TS: time.Now().Unix(), QName: "ok.test", QType: "A", Action: "allow"},
|
||||
{ID: "dns-err-1", TS: time.Now().Unix(), QName: "err.test", QType: "A", Action: "error", RCode: "SERVFAIL"},
|
||||
},
|
||||
})
|
||||
reqEv := httptest.NewRequest(http.MethodPost, "/api/internal/gateway/events", bytes.NewReader(rawBatch))
|
||||
reqEv.Header.Set("X-Artex-Gateway-Token", "test-gw-token-err")
|
||||
recEv := httptest.NewRecorder()
|
||||
s.postGatewayEvents(recEv, reqEv)
|
||||
if recEv.Code != http.StatusOK {
|
||||
t.Fatalf("postGatewayEvents failed: %d %s", recEv.Code, recEv.Body.String())
|
||||
}
|
||||
|
||||
// Verify only non-error rows were persisted and GET /api/traffic/flows reports store_error_traffic=false.
|
||||
recFlows := httptest.NewRecorder()
|
||||
s.getTrafficFlows(recFlows, httptest.NewRequest(http.MethodGet, "/api/traffic/flows", nil))
|
||||
var flowsResp struct {
|
||||
StoreErrorTraffic bool `json:"store_error_traffic"`
|
||||
Total int `json:"total"`
|
||||
Flows []traffic.NetFlowRecord `json:"flows"`
|
||||
}
|
||||
_ = json.Unmarshal(recFlows.Body.Bytes(), &flowsResp)
|
||||
if flowsResp.StoreErrorTraffic || flowsResp.Total != 1 || flowsResp.Flows[0].ID != "nf-ok" {
|
||||
t.Fatalf("expected store_error_traffic=false and 1 allow flow, got %+v", flowsResp)
|
||||
}
|
||||
|
||||
// Partial update from Traffic UI toggling only store_error_traffic=true must preserve udp_policy & dns_upstream.
|
||||
recToggle := httptest.NewRecorder()
|
||||
s.updateGatewaySettings(recToggle, httptest.NewRequest(http.MethodPut, "/api/proxy/gateway/settings", bytes.NewBufferString(`{"store_error_traffic":true}`)))
|
||||
if recToggle.Code != http.StatusOK {
|
||||
t.Fatalf("partial toggle failed: %d %s", recToggle.Code, recToggle.Body.String())
|
||||
}
|
||||
var updated GatewaySettings
|
||||
_ = json.Unmarshal(recToggle.Body.Bytes(), &updated)
|
||||
if !updated.StoreErrorTraffic || updated.UDPPolicy != traffic.UDPPolicyDirect || updated.DNSUpstream != "9.9.9.9:53" {
|
||||
t.Fatalf("partial update clobbered fields: %+v", updated)
|
||||
}
|
||||
|
||||
// Gateway policy snapshot reflects store_error_traffic=true.
|
||||
reqPol := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy", nil)
|
||||
reqPol.Header.Set("X-Artex-Gateway-Token", "test-gw-token-err")
|
||||
recPol := httptest.NewRecorder()
|
||||
s.getGatewayPolicy(recPol, reqPol)
|
||||
var snap traffic.GatewayPolicySnapshot
|
||||
_ = json.Unmarshal(recPol.Body.Bytes(), &snap)
|
||||
if !snap.StoreErrorTraffic {
|
||||
t.Fatalf("expected gateway policy snapshot store_error_traffic=true, got %+v", snap)
|
||||
}
|
||||
|
||||
// Subsequent error flow & DNS query are persisted.
|
||||
rawBatch2, _ := json.Marshal(traffic.GatewayEventBatch{
|
||||
GatewayID: "gw-err",
|
||||
NetFlows: []traffic.NetFlowRecord{
|
||||
{ID: "nf-err-2", TS: time.Now().Unix(), Protocol: "tcp", DstIP: "1.1.1.2", DstPort: 81, Action: "error", Error: "refused"},
|
||||
},
|
||||
DNSQueries: []traffic.DNSQueryRecord{
|
||||
{ID: "dns-err-2", TS: time.Now().Unix(), QName: "err.test", QType: "A", Action: "error", RCode: "SERVFAIL"},
|
||||
},
|
||||
})
|
||||
reqEv2 := httptest.NewRequest(http.MethodPost, "/api/internal/gateway/events", bytes.NewReader(rawBatch2))
|
||||
reqEv2.Header.Set("X-Artex-Gateway-Token", "test-gw-token-err")
|
||||
recEv2 := httptest.NewRecorder()
|
||||
s.postGatewayEvents(recEv2, reqEv2)
|
||||
if recEv2.Code != http.StatusOK {
|
||||
t.Fatalf("postGatewayEvents 2 failed: %d %s", recEv2.Code, recEv2.Body.String())
|
||||
}
|
||||
|
||||
recFlows2 := httptest.NewRecorder()
|
||||
s.getTrafficFlows(recFlows2, httptest.NewRequest(http.MethodGet, "/api/traffic/flows?action=error", nil))
|
||||
var flowsResp2 struct {
|
||||
StoreErrorTraffic bool `json:"store_error_traffic"`
|
||||
Total int `json:"total"`
|
||||
Flows []traffic.NetFlowRecord `json:"flows"`
|
||||
}
|
||||
_ = json.Unmarshal(recFlows2.Body.Bytes(), &flowsResp2)
|
||||
if !flowsResp2.StoreErrorTraffic || flowsResp2.Total != 1 || flowsResp2.Flows[0].ID != "nf-err-2" {
|
||||
t.Fatalf("expected error flow stored after toggle, got %+v", flowsResp2)
|
||||
}
|
||||
}
|
||||
@@ -291,6 +291,9 @@ func (s *Server) toolSpawnTask() actool.CoreTool {
|
||||
SeedFirstIntent bool `json:"seed_first_intent"`
|
||||
Attachments []string `json:"attachments"`
|
||||
}
|
||||
if err := json.Unmarshal(in, &a); err != nil {
|
||||
return actool.Errorf("参数无效: " + err.Error()), nil
|
||||
}
|
||||
if strings.TrimSpace(a.Description) == "" {
|
||||
a.Description = "未命名任务"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestToolSpawnTaskUnmarshalsInput(t *testing.T) {
|
||||
s := &Server{m: &Manager{tasks: map[string]*Task{}}}
|
||||
tool := s.toolSpawnTask()
|
||||
|
||||
t.Run("missing goal rejected", func(t *testing.T) {
|
||||
res, err := tool.Call(context.Background(), json.RawMessage(`{"description":"端口探测"}`), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError || !strings.Contains(res.Flatten(), "goal 为必填") {
|
||||
t.Fatalf("expected goal required error, got isError=%v text=%q", res.IsError, res.Flatten())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid json rejected", func(t *testing.T) {
|
||||
res, err := tool.Call(context.Background(), json.RawMessage(`{invalid`), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError || !strings.Contains(res.Flatten(), "参数无效") {
|
||||
t.Fatalf("expected invalid json error, got isError=%v text=%q", res.IsError, res.Flatten())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("valid goal parsed past required check", func(t *testing.T) {
|
||||
res, err := tool.Call(context.Background(), json.RawMessage(`{
|
||||
"description": "47.116.200.74 端口探测",
|
||||
"goal": "仅对 47.116.200.74 做端口探测",
|
||||
"source_task_ids": ["99999"]
|
||||
}`), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !res.IsError || !strings.Contains(res.Flatten(), "关联任务 #99999 不存在") {
|
||||
t.Fatalf("expected source_task_ids check after parsing goal, got isError=%v text=%q", res.IsError, res.Flatten())
|
||||
}
|
||||
})
|
||||
}
|
||||
+28
-8
@@ -33,8 +33,9 @@ type ContainerProxyRoute struct {
|
||||
|
||||
// GatewaySettings persists transparent gateway runtime policy knobs.
|
||||
type GatewaySettings struct {
|
||||
UDPPolicy string `json:"udp_policy"`
|
||||
DNSUpstream string `json:"dns_upstream"`
|
||||
UDPPolicy string `json:"udp_policy"`
|
||||
DNSUpstream string `json:"dns_upstream"`
|
||||
StoreErrorTraffic bool `json:"store_error_traffic"`
|
||||
}
|
||||
|
||||
type proxyRouteRuntime struct {
|
||||
@@ -93,10 +94,18 @@ func (s *Server) initProxyRoutesAndGateway() {
|
||||
gs := rt.gwSettings
|
||||
rt.mu.RUnlock()
|
||||
s.m.traffic.SetGatewaySettings(gs.UDPPolicy, gs.DNSUpstream)
|
||||
s.m.traffic.SetStoreErrorTraffic(gs.StoreErrorTraffic)
|
||||
s.m.traffic.SetUpstreamResolver(s.resolveContainerUpstream)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) storeErrorTrafficEnabled() bool {
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.RLock()
|
||||
defer rt.mu.RUnlock()
|
||||
return rt.gwSettings.StoreErrorTraffic
|
||||
}
|
||||
|
||||
func (s *Server) resolvePoolEntryRawURL(poolID string) string {
|
||||
poolID = strings.TrimSpace(poolID)
|
||||
if poolID == "" {
|
||||
@@ -325,6 +334,7 @@ func (s *Server) getProxyRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
"last_seen": lastSeenStr,
|
||||
"udp_policy": traffic.NormalizeUDPPolicy(gs.UDPPolicy),
|
||||
"dns_upstream": gs.DNSUpstream,
|
||||
"store_error_traffic": gs.StoreErrorTraffic,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -442,19 +452,28 @@ func (s *Server) deleteProxyRoute(w http.ResponseWriter, r *http.Request) {
|
||||
// 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"`
|
||||
UDPPolicy *string `json:"udp_policy"`
|
||||
DNSUpstream *string `json:"dns_upstream"`
|
||||
StoreErrorTraffic *bool `json:"store_error_traffic"`
|
||||
}
|
||||
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()
|
||||
gs := rt.gwSettings
|
||||
if req.UDPPolicy != nil {
|
||||
gs.UDPPolicy = traffic.NormalizeUDPPolicy(*req.UDPPolicy)
|
||||
} else {
|
||||
gs.UDPPolicy = traffic.NormalizeUDPPolicy(gs.UDPPolicy)
|
||||
}
|
||||
if req.DNSUpstream != nil {
|
||||
gs.DNSUpstream = strings.TrimSpace(*req.DNSUpstream)
|
||||
}
|
||||
if req.StoreErrorTraffic != nil {
|
||||
gs.StoreErrorTraffic = *req.StoreErrorTraffic
|
||||
}
|
||||
rt.gwSettings = gs
|
||||
rt.mu.Unlock()
|
||||
if s.m.pg != nil {
|
||||
@@ -464,6 +483,7 @@ func (s *Server) updateGatewaySettings(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if s.m.traffic != nil {
|
||||
s.m.traffic.SetGatewaySettings(gs.UDPPolicy, gs.DNSUpstream)
|
||||
s.m.traffic.SetStoreErrorTraffic(gs.StoreErrorTraffic)
|
||||
}
|
||||
writeJSON(w, 200, gs)
|
||||
}
|
||||
+2
-1
@@ -3736,7 +3736,7 @@ func taskActivityDetail(t *Task, seq int64) (string, error) {
|
||||
func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) {
|
||||
tr := s.m.Traffic()
|
||||
if tr == nil {
|
||||
writeJSON(w, 200, map[string]any{"enabled": false, "exchanges": []any{}})
|
||||
writeJSON(w, 200, map[string]any{"enabled": false, "store_error_traffic": s.storeErrorTrafficEnabled(), "exchanges": []any{}})
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
@@ -3787,6 +3787,7 @@ func (s *Server) getTraffic(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"enabled": s.m.TrafficEnabled(), // reflect the capture toggle
|
||||
"store_error_traffic": s.storeErrorTrafficEnabled(),
|
||||
"proxy": s.m.ProxyAddr(),
|
||||
"count": count, // total recorded (unfiltered)
|
||||
"total": matched, // rows matching the current filter (for pagination)
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
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})
|
||||
writeJSON(w, 200, map[string]any{"enabled": false, "store_error_traffic": s.storeErrorTrafficEnabled(), "flows": []any{}, "total": 0, "count": 0})
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
@@ -41,6 +41,7 @@ func (s *Server) getTrafficFlows(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"enabled": s.m.TrafficEnabled(),
|
||||
"store_error_traffic": s.storeErrorTrafficEnabled(),
|
||||
"count": count,
|
||||
"total": total,
|
||||
"page": page,
|
||||
@@ -95,7 +96,7 @@ func (s *Server) deleteTrafficFlows(w http.ResponseWriter, r *http.Request) {
|
||||
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})
|
||||
writeJSON(w, 200, map[string]any{"enabled": false, "store_error_traffic": s.storeErrorTrafficEnabled(), "queries": []any{}, "total": 0, "count": 0})
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
@@ -126,6 +127,7 @@ func (s *Server) getTrafficDNS(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"enabled": s.m.TrafficEnabled(),
|
||||
"store_error_traffic": s.storeErrorTrafficEnabled(),
|
||||
"count": count,
|
||||
"total": total,
|
||||
"page": page,
|
||||
|
||||
Reference in new issue
Block a user