diff --git a/server/gateway_api.go b/server/gateway_api.go index b60f386..782adce 100644 --- a/server/gateway_api.go +++ b/server/gateway_api.go @@ -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 { diff --git a/server/gateway_api_test.go b/server/gateway_api_test.go index c1ec99b..5d3d8a2 100644 --- a/server/gateway_api_test.go +++ b/server/gateway_api_test.go @@ -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) + } +} diff --git a/server/orchestration.go b/server/orchestration.go index 057599a..e270b86 100644 --- a/server/orchestration.go +++ b/server/orchestration.go @@ -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 = "未命名任务" } diff --git a/server/orchestration_test.go b/server/orchestration_test.go new file mode 100644 index 0000000..30c55d9 --- /dev/null +++ b/server/orchestration_test.go @@ -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()) + } + }) +} diff --git a/server/proxy_routes.go b/server/proxy_routes.go index f41e46d..9aa76f2 100644 --- a/server/proxy_routes.go +++ b/server/proxy_routes.go @@ -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) } diff --git a/server/server.go b/server/server.go index 484de8f..07d0c41 100644 --- a/server/server.go +++ b/server/server.go @@ -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) diff --git a/server/traffic_flows.go b/server/traffic_flows.go index 84c39ad..d865203 100644 --- a/server/traffic_flows.go +++ b/server/traffic_flows.go @@ -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, diff --git a/traffic/gateway_protocol.go b/traffic/gateway_protocol.go index 8f2f976..6627ef8 100644 --- a/traffic/gateway_protocol.go +++ b/traffic/gateway_protocol.go @@ -42,6 +42,7 @@ type GatewayPolicySnapshot struct { PassthroughHosts []string `json:"passthrough_hosts,omitempty"` UDPPolicy string `json:"udp_policy"` DNSUpstream string `json:"dns_upstream,omitempty"` + StoreErrorTraffic bool `json:"store_error_traffic"` } // GatewayEventBatch is posted by artex-gateway to POST /api/internal/gateway/events. @@ -65,6 +66,7 @@ type RemotePolicyState struct { passthroughHosts map[string]struct{} udpPolicy string dnsUpstream string + storeErrorTraffic bool dnsCache *dnsReverseCache gatewayToken string onNetFlow func(NetFlowRecord) @@ -171,6 +173,7 @@ func (s *RemotePolicyState) Apply(snap GatewayPolicySnapshot) { s.passthroughHosts = pass s.udpPolicy = NormalizeUDPPolicy(snap.UDPPolicy) s.dnsUpstream = strings.TrimSpace(snap.DNSUpstream) + s.storeErrorTraffic = snap.StoreErrorTraffic s.mu.Unlock() } @@ -253,12 +256,18 @@ func (s *RemotePolicyState) RememberDNS(ip, domain string) { } func (s *RemotePolicyState) RecordNetFlow(rec NetFlowRecord) { + if strings.EqualFold(strings.TrimSpace(rec.Action), "error") && !s.StoreErrorTraffic() { + return + } if s.onNetFlow != nil { s.onNetFlow(rec) } } func (s *RemotePolicyState) RecordDNSQuery(rec DNSQueryRecord) { + if strings.EqualFold(strings.TrimSpace(rec.Action), "error") && !s.StoreErrorTraffic() { + return + } if s.onDNSQuery != nil { s.onDNSQuery(rec) } @@ -282,6 +291,12 @@ func (s *RemotePolicyState) DNSUpstream() string { return s.dnsUpstream } +func (s *RemotePolicyState) StoreErrorTraffic() bool { + s.mu.RLock() + defer s.mu.RUnlock() + return s.storeErrorTraffic +} + func (s *RemotePolicyState) GatewayToken() string { return s.gatewayToken } diff --git a/traffic/netflow_store.go b/traffic/netflow_store.go index afe1b5a..5ea763d 100644 --- a/traffic/netflow_store.go +++ b/traffic/netflow_store.go @@ -325,6 +325,9 @@ func (t *Traffic) RecordNetFlow(rec NetFlowRecord) error { if rec.Action == "" { rec.Action = "allow" } + if rec.Action == "error" && !t.StoreErrorTraffic() { + return nil + } if len(rec.TXPreview) > maxFlowPreviewBytes { rec.TXPreview = rec.TXPreview[:maxFlowPreviewBytes] } @@ -370,9 +373,13 @@ func (t *Traffic) RecordDNSQuery(rec DNSQueryRecord) error { if rec.QType == "" { rec.QType = "A" } + rec.Action = strings.ToLower(strings.TrimSpace(rec.Action)) if rec.Action == "" { rec.Action = "allow" } + if rec.Action == "error" && !t.StoreErrorTraffic() { + return nil + } answers := rec.Answers if answers == nil { answers = []string{} diff --git a/traffic/netstack.go b/traffic/netstack.go index 34d4cb0..9959769 100644 --- a/traffic/netstack.go +++ b/traffic/netstack.go @@ -66,7 +66,9 @@ type NetstackConfig struct { // - Remote dial success => completes 3-way handshake (nmap reports "open"), // sniffs HTTP/TLS for go-mitmproxy MITM decryption, or reuses the already // established remote socket directly for raw TCP L4 relay + net_flows capture. -// - UDP/53 and TCP/53 => intercepted and processed through ProcessDNSQuery. +// - External TCP/53 => uses the same deferred handshake to the real dstIP:53, +// then inspects/logs DNS-over-TCP frames (never hijacked to host DNS). +// - External UDP/53 => forwarded to dstIP:53 (or via upstream proxy to dstIP:53). // - Non-DNS UDP => subject to SSRF/blacklist and OPSEC UDPPolicy + net_flows. type NetstackGateway struct { cfg NetstackConfig @@ -349,20 +351,6 @@ func (n *NetstackGateway) processTCPForward(r *tcp.ForwarderRequest, srcIP strin src.SrcIP = srcIP } - // DNS-over-TCP (port 53): accept locally and route through ProcessDNSQuery. - if dstPort == 53 { - var wq waiter.Queue - ep, tcpErr := r.CreateEndpoint(&wq) - r.Complete(false) - if tcpErr != nil { - return - } - conn := gonet.NewTCPConn(&wq, ep) - defer conn.Close() - n.serveSingleTCPDNS(conn, srcIP) - return - } - dstHost := n.backend.LookupDNSReverse(dstIP) if dstHost == "" { dstHost = dstIP @@ -478,6 +466,14 @@ func (n *NetstackGateway) processTCPForward(r *tcp.ForwarderRequest, srcIP strin } } + // Direct DNS-over-TCP to an external target:53 (already connected via deferred + // handshake) -> enforce domain/IP blacklist and log to dns_queries while talking + // to the real target socket rather than hijacking to the host's DNS resolver. + if dstPort == 53 && sniff.Proto == ProtoTCP && looksLikeTCPDNS(clientConn) { + n.serveConnectedTCPDNS(clientConn, dstConn, src, dstIP, upstreamLabel) + return + } + // Raw TCP (SSH, MySQL, Redis, SMB, nc, nmap -sT) or TLS passthrough: // reuse the ALREADY-CONNECTED dstConn (zero double-connect!). action := "allow" @@ -524,36 +520,287 @@ func (n *NetstackGateway) recordTCPBlock(start time.Time, proto string, src Sour }) } -func (n *NetstackGateway) serveSingleTCPDNS(conn net.Conn, srcIP string) { - _ = conn.SetDeadline(time.Now().Add(8 * time.Second)) - var lenBuf [2]byte - if _, err := io.ReadFull(conn, lenBuf[:]); err != nil { - return +func looksLikeTCPDNS(conn net.Conn) bool { + pc, ok := conn.(*PeekConn) + if !ok || pc.br == nil { + return false } - msgLen := int(binary.BigEndian.Uint16(lenBuf[:])) - if msgLen <= 0 || msgLen > 65535 { - return + avail := pc.br.Buffered() + if avail < 14 { // 2-byte TCP length prefix + 12-byte DNS header minimum + return false } - raw := make([]byte, msgLen) - if _, err := io.ReadFull(conn, raw); err != nil { - return + hdr, err := pc.br.Peek(2) + if err != nil { + return false + } + msgLen := int(binary.BigEndian.Uint16(hdr)) + if msgLen < 12 || msgLen > 4096 || avail < 2+msgLen { + return false + } + frame, err := pc.br.Peek(2 + msgLen) + if err != nil { + return false } req := new(dns.Msg) - if err := req.Unpack(raw); err != nil { - return + if err := req.Unpack(frame[2:]); err != nil || req.Response || len(req.Question) == 0 { + return false } - resp := n.gw.ProcessDNSQuery(srcIP, req, true) - if resp == nil { - return - } - packed, err := resp.Pack() + return true +} + +func (n *NetstackGateway) recordTCPDNSError(start time.Time, qname, qtype, upstreamTag string, src SourceIdentity, err error) { + errMsg := "tcp dns exchange failed" if err != nil { - return + errMsg = err.Error() + } + n.backend.RecordDNSQuery(DNSQueryRecord{ + TS: start.Unix(), + DurationMS: time.Since(start).Milliseconds(), + QName: qname, + QType: qtype, + RCode: dns.RcodeToString[dns.RcodeServerFailure], + Answers: []string{}, + Action: "error", + Upstream: upstreamTag, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + Error: errMsg, + }) +} + +// writeTCPDNSFrame writes the 2-octet length prefix and DNS message in a single +// Write call (RFC 7766 Section 8) so strict TCP DNS servers (e.g. AliDNS 223.5.5.5) +// do not reset connections receiving split length/payload segments. +func writeTCPDNSFrame(w io.Writer, payload []byte) error { + frame := make([]byte, 2+len(payload)) + binary.BigEndian.PutUint16(frame[:2], uint16(len(payload))) + copy(frame[2:], payload) + _, err := w.Write(frame) + return err +} + +func (n *NetstackGateway) serveConnectedTCPDNS( + clientConn, dstConn net.Conn, + src SourceIdentity, + dstIP string, + upstreamLabel string, +) { + defer dstConn.Close() + targetAddr := net.JoinHostPort(dstIP, "53") + upstreamTag := "direct-tcp:" + targetAddr + if upstreamLabel != "" && upstreamLabel != "direct" { + upstreamTag = "tcp-via:" + upstreamLabel + "->" + targetAddr + } + + for { + _ = clientConn.SetReadDeadline(time.Now().Add(8 * time.Second)) + var lenBuf [2]byte + if _, err := io.ReadFull(clientConn, lenBuf[:]); err != nil { + return + } + msgLen := int(binary.BigEndian.Uint16(lenBuf[:])) + if msgLen <= 0 || msgLen > 65535 { + return + } + raw := make([]byte, msgLen) + if _, err := io.ReadFull(clientConn, raw); err != nil { + return + } + req := new(dns.Msg) + if err := req.Unpack(raw); err != nil { + return + } + qStart := time.Now() + qname := "" + qtype := "A" + isZoneTransfer := false + if len(req.Question) > 0 { + qname = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(req.Question[0].Name)), ".") + qtype = dns.TypeToString[req.Question[0].Qtype] + if qtype == "" { + qtype = strconv.Itoa(int(req.Question[0].Qtype)) + } + isZoneTransfer = req.Question[0].Qtype == dns.TypeAXFR || req.Question[0].Qtype == dns.TypeIXFR + } + + // Pre-resolution domain check against SSRF guard + global/task egress blacklist. + if qname != "" { + if blocked := n.backend.CheckOutbound(qname, "dns", src); blocked != nil { + refused := new(dns.Msg) + refused.SetRcode(req, dns.RcodeRefused) + n.backend.RecordBlockEvent(EgressBlockEvent{ + At: qStart.UTC(), + Host: qname, + Port: "53", + Method: "DNS/" + qtype, + URL: "dns://" + qname, + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: blocked.Reason, + RuleKind: blocked.RuleKind, + RuleID: blocked.RuleID, + Pattern: blocked.Pattern, + Source: blocked.Source, + }) + n.backend.RecordDNSQuery(DNSQueryRecord{ + TS: qStart.Unix(), + DurationMS: time.Since(qStart).Milliseconds(), + QName: qname, + QType: qtype, + RCode: dns.RcodeToString[dns.RcodeRefused], + Answers: []string{}, + Action: "block", + BlockReason: blocked.Reason, + Upstream: upstreamTag, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + if packed, err := refused.Pack(); err == nil { + _ = writeTCPDNSFrame(clientConn, packed) + } + continue + } + } + + // Forward the framed DNS query directly to the already-connected real target dstIP:53. + _ = dstConn.SetDeadline(time.Now().Add(8 * time.Second)) + if err := writeTCPDNSFrame(dstConn, raw); err != nil { + n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err) + return + } + if isZoneTransfer { + // AXFR/IXFR returns a multi-message TCP stream; record the query and pipe verbatim. + n.backend.RecordDNSQuery(DNSQueryRecord{ + TS: qStart.Unix(), + DurationMS: time.Since(qStart).Milliseconds(), + QName: qname, + QType: qtype, + RCode: "STREAM", + Answers: []string{}, + Action: "allow", + Upstream: upstreamTag, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + _ = dstConn.SetDeadline(time.Time{}) + _ = clientConn.SetDeadline(time.Time{}) + _, _ = io.Copy(clientConn, dstConn) + return + } + + var respLenBuf [2]byte + if _, err := io.ReadFull(dstConn, respLenBuf[:]); err != nil { + n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err) + return + } + respLen := int(binary.BigEndian.Uint16(respLenBuf[:])) + if respLen <= 0 || respLen > 65535 { + n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, fmt.Errorf("invalid dns tcp response length %d", respLen)) + return + } + respRaw := make([]byte, respLen) + if _, err := io.ReadFull(dstConn, respRaw); err != nil { + n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err) + return + } + reply := new(dns.Msg) + if err := reply.Unpack(respRaw); err != nil { + n.recordTCPDNSError(qStart, qname, qtype, upstreamTag, src, err) + return + } + + answers, resolvedIPs := extractDNSAnswers(reply) + blockedPost := false + for _, ipStr := range resolvedIPs { + if blocked := n.backend.CheckOutbound(ipStr, "dns", src); blocked != nil { + refused := new(dns.Msg) + refused.SetRcode(req, dns.RcodeRefused) + n.backend.RecordBlockEvent(EgressBlockEvent{ + At: qStart.UTC(), + Host: qname, + Port: "53", + Method: "DNS/" + qtype, + URL: "dns://" + qname + " -> " + ipStr, + SrcIP: src.SrcIP, + Scope: src.Scope, + OwnerID: src.OwnerID, + Reason: blocked.Reason, + RuleKind: blocked.RuleKind, + RuleID: blocked.RuleID, + Pattern: blocked.Pattern, + Source: blocked.Source, + }) + n.backend.RecordDNSQuery(DNSQueryRecord{ + TS: qStart.Unix(), + DurationMS: time.Since(qStart).Milliseconds(), + QName: qname, + QType: qtype, + RCode: dns.RcodeToString[dns.RcodeRefused], + Answers: answers, + Action: "block", + BlockReason: blocked.Reason, + Upstream: upstreamTag, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + if packed, err := refused.Pack(); err == nil { + _ = writeTCPDNSFrame(clientConn, packed) + } + blockedPost = true + break + } + } + if blockedPost { + continue + } + + if qname != "" { + for _, ipStr := range resolvedIPs { + n.backend.RememberDNS(ipStr, qname) + } + } + rcode := dns.RcodeToString[reply.Rcode] + if rcode == "" { + rcode = strconv.Itoa(reply.Rcode) + } + n.backend.RecordDNSQuery(DNSQueryRecord{ + TS: qStart.Unix(), + DurationMS: time.Since(qStart).Milliseconds(), + QName: qname, + QType: qtype, + RCode: rcode, + Answers: answers, + Action: "allow", + Upstream: upstreamTag, + SandboxScope: src.Scope, + SandboxOwnerID: src.OwnerID, + ContainerID: src.ContainerID, + SessionID: src.SessionID, + IntentID: src.IntentID, + SrcIP: src.SrcIP, + }) + + if err := writeTCPDNSFrame(clientConn, respRaw); err != nil { + return + } } - var outLen [2]byte - binary.BigEndian.PutUint16(outLen[:], uint16(len(packed))) - _, _ = conn.Write(outLen[:]) - _, _ = conn.Write(packed) } // handleUDPForward intercepts UDP packets routed into netstack: diff --git a/traffic/netstack_test.go b/traffic/netstack_test.go index 4ffcced..834081b 100644 --- a/traffic/netstack_test.go +++ b/traffic/netstack_test.go @@ -1,6 +1,7 @@ package traffic import ( + "bufio" "context" "encoding/binary" "fmt" @@ -8,9 +9,13 @@ import ( "net" "net/http" "net/url" + "strings" + "sync" + "syscall" "testing" "time" + "github.com/miekg/dns" "gvisor.dev/gvisor/pkg/tcpip" "gvisor.dev/gvisor/pkg/tcpip/checksum" "gvisor.dev/gvisor/pkg/tcpip/header" @@ -312,6 +317,7 @@ func TestNetstackAntiSpoofingAndICMPProxy(t *testing.T) { t.Fatalf("open traffic: %v", err) } defer tr.Close() + tr.SetStoreErrorTraffic(true) tr.SetEgressBlacklist([]EgressBlacklistRule{{ ID: "blk-icmp", Kind: "ip", @@ -392,3 +398,251 @@ func TestNetstackAntiSpoofingAndICMPProxy(t *testing.T) { t.Fatalf("expected >=3 recorded icmp flows (allow/error/block), got total=%d err=%v flows=%+v", total, err, flows) } } + +func TestNetstackTCP53DeferredHandshakeNoFalsePositiveAndRealDNS(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) { + if srcIP == "172.30.0.3" { + return SourceIdentity{Scope: "task", OwnerID: "53", ContainerID: "sbx53", SrcIP: srcIP}, true + } + return SourceIdentity{}, false + }) + tr.SetEgressBlacklist([]EgressBlacklistRule{ + {ID: "blk-dom", Enabled: true, Kind: "domain", Pattern: "blocked.example"}, + }) + + // Start a mock authoritative TCP DNS server returning 198.51.100.77. + dnsLn, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen mock tcp dns: %v", err) + } + defer dnsLn.Close() + go func() { + for { + c, err := dnsLn.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer conn.Close() + for { + var lb [2]byte + if _, err := io.ReadFull(conn, lb[:]); err != nil { + return + } + n := int(binary.BigEndian.Uint16(lb[:])) + buf := make([]byte, n) + if _, err := io.ReadFull(conn, buf); err != nil { + return + } + req := new(dns.Msg) + if err := req.Unpack(buf); err != nil { + return + } + resp := new(dns.Msg) + resp.SetReply(req) + if len(req.Question) > 0 { + resp.Answer = append(resp.Answer, &dns.A{ + Hdr: dns.RR_Header{Name: req.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60}, + A: net.ParseIP("198.51.100.77"), + }) + } + packed, err := resp.Pack() + if err != nil { + return + } + var outLb [2]byte + binary.BigEndian.PutUint16(outLb[:], uint16(len(packed))) + _, _ = conn.Write(outLb[:]) + _, _ = conn.Write(packed) + } + }(c) + } + }() + + pipe := newMemTunPipe() + ns, err := NewNetstackGateway(pipe, NetstackConfig{ + DialTimeout: 150 * time.Millisecond, + PeekTimeout: 80 * time.Millisecond, + DialFunc: func(ctx context.Context, upstream *url.URL, target string, timeout time.Duration) (net.Conn, error) { + switch target { + case "203.0.113.74:53": + return nil, context.DeadlineExceeded + case "203.0.113.75:53": + return nil, syscall.ECONNREFUSED + case "203.0.113.53:53": + return dialTCPThroughUpstream(ctx, upstream, dnsLn.Addr().String(), timeout) + default: + return nil, syscall.ECONNREFUSED + } + }, + }, LocalTransparentBackend{T: tr}) + if err != nil { + t.Fatalf("NewNetstackGateway: %v", err) + } + ns.Start() + defer ns.Close() + + // 1. Filtered external target:53/TCP (repro of 47.116.200.74:53) -> MUST NOT receive SYN-ACK. + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.74"), 45001, 53, 1001) + select { + case pkt := <-pipe.out: + flags, ok := parseTCPFlags(pkt) + t.Fatalf("filtered TCP/53 must drop silently, got tcp=%v flags=%v", ok, flags) + case <-time.After(300 * time.Millisecond): + } + + // 2. Closed external target:53/TCP -> MUST receive RST (not SYN-ACK). + pipe.in <- buildIPv4TCPSYN(net.ParseIP("172.30.0.3"), net.ParseIP("203.0.113.75"), 45002, 53, 1002) + select { + case pkt := <-pipe.out: + flags, ok := parseTCPFlags(pkt) + if !ok || !flags.Contains(header.TCPFlagRst) || flags.Contains(header.TCPFlagSyn) { + t.Fatalf("closed TCP/53 expected RST without SYN, got ok=%v flags=%v", ok, flags) + } + case <-time.After(1 * time.Second): + t.Fatal("timed out waiting for RST on closed TCP/53") + } + + // 3. Direct unit check of serveConnectedTCPDNS against real target socket: + // allowed query gets target's real answer (198.51.100.77) and logs direct-tcp:203.0.113.53:53; + // blacklisted domain gets REFUSED and logs block without hitting upstream. + clientSide, gwClient := net.Pipe() + dstConn, err := net.DialTimeout("tcp4", dnsLn.Addr().String(), time.Second) + if err != nil { + t.Fatalf("dial mock dns: %v", err) + } + done := make(chan struct{}) + go func() { + defer close(done) + defer gwClient.Close() + sniff, peeked := SniffProtocol(gwClient, 200*time.Millisecond) + if sniff.Proto != ProtoTCP || !looksLikeTCPDNS(peeked) { + t.Errorf("expected looksLikeTCPDNS=true, proto=%s", sniff.Proto) + return + } + ns.serveConnectedTCPDNS(peeked, dstConn, SourceIdentity{Scope: "task", OwnerID: "53", SrcIP: "172.30.0.3"}, "203.0.113.53", "direct") + }() + + sendTCPQuery := func(qname string) *dns.Msg { + q := new(dns.Msg) + q.SetQuestion(dns.Fqdn(qname), dns.TypeA) + packed, err := q.Pack() + if err != nil { + t.Fatalf("pack query: %v", err) + } + var lb [2]byte + binary.BigEndian.PutUint16(lb[:], uint16(len(packed))) + if _, err := clientSide.Write(append(lb[:], packed...)); err != nil { + t.Fatalf("write query: %v", err) + } + var rlb [2]byte + if _, err := io.ReadFull(clientSide, rlb[:]); err != nil { + t.Fatalf("read resp len: %v", err) + } + rbuf := make([]byte, binary.BigEndian.Uint16(rlb[:])) + if _, err := io.ReadFull(clientSide, rbuf); err != nil { + t.Fatalf("read resp: %v", err) + } + resp := new(dns.Msg) + if err := resp.Unpack(rbuf); err != nil { + t.Fatalf("unpack resp: %v", err) + } + return resp + } + + okResp := sendTCPQuery("ok.example") + if okResp.Rcode != dns.RcodeSuccess || len(okResp.Answer) != 1 || okResp.Answer[0].(*dns.A).A.String() != "198.51.100.77" { + t.Fatalf("unexpected real TCP DNS answer: %+v", okResp) + } + blkResp := sendTCPQuery("blocked.example") + if blkResp.Rcode != dns.RcodeRefused { + t.Fatalf("expected REFUSED for blacklisted domain, got rcode=%d", blkResp.Rcode) + } + _ = clientSide.Close() + <-done + + rows, total, err := tr.PageDNSQueries(DNSQueryFilter{}, 0, 10) + if err != nil || total != 2 { + t.Fatalf("expected 2 recorded TCP DNS queries, got total=%d err=%v rows=%+v", total, err, rows) + } + var sawOK, sawBlk bool + for _, r := range rows { + if r.QName == "ok.example" && r.Action == "allow" && r.Upstream == "direct-tcp:203.0.113.53:53" { + sawOK = true + } + if r.QName == "blocked.example" && r.Action == "block" && r.Upstream == "direct-tcp:203.0.113.53:53" { + sawBlk = true + } + } + if !sawOK || !sawBlk { + t.Fatalf("expected both ok (direct-tcp:203.0.113.53:53) and blocked rows, got %+v", rows) + } +} + +func TestProcessDNSQueryToTargetUnderUpstreamProxyNeverSubstitutesHostDNS(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + // Set a host DNS upstream that MUST NOT be contacted when targetServer is explicit. + tr.SetGatewaySettings(UDPPolicyBlockOnProxy, "198.51.100.254:53") + + // Mock HTTP CONNECT proxy that records the requested CONNECT target and rejects 47.116.200.74:53. + proxyLn, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen proxy: %v", err) + } + defer proxyLn.Close() + var mu sync.Mutex + var connectTargets []string + go func() { + for { + c, err := proxyLn.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer conn.Close() + br := bufio.NewReader(conn) + line, err := br.ReadString('\n') + if err != nil { + return + } + parts := strings.Fields(line) + if len(parts) >= 2 && parts[0] == "CONNECT" { + mu.Lock() + connectTargets = append(connectTargets, parts[1]) + mu.Unlock() + } + _, _ = conn.Write([]byte("HTTP/1.1 502 Bad Gateway\r\n\r\n")) + }(c) + } + }() + + proxyURL, _ := url.Parse("http://" + proxyLn.Addr().String()) + tr.SetUpstreamResolver(func(SourceIdentity) (*url.URL, bool) { + return proxyURL, true + }) + + gw := NewTransparentGateway(TransparentConfig{}, LocalTransparentBackend{T: tr}) + q := new(dns.Msg) + q.SetQuestion("example.com.", dns.TypeA) + resp, qerr := gw.ProcessDNSQueryToTarget("172.30.0.3", q, false, "47.116.200.74:53") + if resp != nil || qerr == nil { + t.Fatalf("expected (nil, err) when targetServer fails through proxy, got resp=%v err=%v", resp, qerr) + } + + mu.Lock() + got := append([]string(nil), connectTargets...) + mu.Unlock() + if len(got) != 1 || got[0] != "47.116.200.74:53" { + t.Fatalf("expected proxy CONNECT to targetServer 47.116.200.74:53 (not host DNSUpstream), got %v", got) + } +} diff --git a/traffic/traffic.go b/traffic/traffic.go index ca22b2d..8da700f 100644 --- a/traffic/traffic.go +++ b/traffic/traffic.go @@ -188,6 +188,7 @@ type Traffic struct { gatewayToken string udpPolicy string dnsUpstream string + storeErrorTraffic atomic.Bool ssrfCfg *SSRFGuardConfig dnsCache *dnsReverseCache nfWrites atomic.Int64 diff --git a/traffic/transparent.go b/traffic/transparent.go index 4ae966c..36fdae1 100644 --- a/traffic/transparent.go +++ b/traffic/transparent.go @@ -646,9 +646,10 @@ func (g *TransparentGateway) ProcessDNSQuery(srcIP string, r *dns.Msg, viaTCP bo // ProcessDNSQueryToTarget evaluates a direct DNS request sent to a specific // destination IP:port (e.g. `dig @223.5.5.5` or `nmap -sU -p 53 `). -// When no upstream proxy is active, it queries targetServer directly and returns -// (nil, err) on upstream failure instead of synthesizing SERVFAIL, preventing -// false-positive `53/udp open` reports on non-DNS hosts. +// It always queries targetServer (directly or via upstream proxy when active) +// and never substitutes the host's DNSUpstream(), returning (nil, err) on +// failure instead of synthesizing SERVFAIL to prevent false-positive open +// resolver / `53/udp open` reports on non-DNS hosts. func (g *TransparentGateway) ProcessDNSQueryToTarget(srcIP string, r *dns.Msg, viaTCP bool, targetServer string) (*dns.Msg, error) { return g.processDNSQuery(srcIP, r, viaTCP, strings.TrimSpace(targetServer), false) } @@ -712,13 +713,20 @@ func (g *TransparentGateway) processDNSQuery(srcIP string, r *dns.Msg, viaTCP bo upstreamProxy := g.backend.ResolveUpstream(src) dnsServer := "" - if upstreamProxy == nil && targetServer != "" { + if targetServer != "" { dnsServer = targetServer } else { dnsServer = strings.TrimSpace(g.backend.DNSUpstream()) if dnsServer == "" { dnsServer = defaultSystemDNSUpstream() } + if upstreamProxy != nil { + // A remote upstream proxy cannot reach the host's loopback stub (e.g. 127.0.0.53). + h, _ := splitHostAndPort(dnsServer) + if ip := net.ParseIP(strings.TrimSpace(h)); ip != nil && ip.IsLoopback() { + dnsServer = "8.8.8.8:53" + } + } } if _, _, err := net.SplitHostPort(dnsServer); err != nil { dnsServer = net.JoinHostPort(dnsServer, "53") @@ -1417,6 +1425,20 @@ func (t *Traffic) DNSUpstream() string { return t.dnsUpstream } +func (t *Traffic) SetStoreErrorTraffic(enabled bool) { + if t == nil { + return + } + t.storeErrorTraffic.Store(enabled) +} + +func (t *Traffic) StoreErrorTraffic() bool { + if t == nil { + return false + } + return t.storeErrorTraffic.Load() +} + // PassthroughHosts returns the list of hostnames currently downgraded to L4 passthrough. func (t *Traffic) PassthroughHosts() []string { if t == nil { diff --git a/traffic/transparent_test.go b/traffic/transparent_test.go index 413302b..b2c29da 100644 --- a/traffic/transparent_test.go +++ b/traffic/transparent_test.go @@ -521,3 +521,73 @@ func TestPerSourceUpstreamOverrideAndTransparentHTTPBridge(t *testing.T) { // Silence unused tls import check if not needed. _ = tls.VersionTLS12 } + +func TestStoreErrorTrafficDefaultOffAndToggle(t *testing.T) { + tr, err := Open(t.TempDir(), "127.0.0.1:0") + if err != nil { + t.Fatalf("open traffic: %v", err) + } + defer tr.Close() + + if tr.StoreErrorTraffic() { + t.Fatalf("expected StoreErrorTraffic to default to false") + } + + // Default OFF: error flows and DNS error queries are dropped; allow/block/passthrough are stored. + _ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-allow", Protocol: "tcp", DstIP: "1.1.1.1", DstPort: 80, Action: "allow"}) + _ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-block", Protocol: "tcp", DstIP: "1.1.1.2", DstPort: 80, Action: "block"}) + _ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-pass", Protocol: "tls", DstIP: "1.1.1.3", DstPort: 443, Action: "passthrough"}) + _ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-err-dropped", Protocol: "tcp", DstIP: "1.1.1.4", DstPort: 81, Action: "error", Error: "dial timeout"}) + + _ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-allow", QName: "ok.example", QType: "A", Action: "allow"}) + _ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-block", QName: "bad.example", QType: "A", Action: "block"}) + _ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-err-dropped", QName: "fail.example", QType: "A", Action: "error", RCode: "SERVFAIL"}) + + flows, totalFlows, err := tr.PageNetFlows(NetFlowQuery{}, 0, 20) + if err != nil || totalFlows != 3 || len(flows) != 3 { + t.Fatalf("expected 3 non-error flows when StoreErrorTraffic=false, got total=%d rows=%+v err=%v", totalFlows, flows, err) + } + dnsRows, totalDNS, err := tr.PageDNSQueries(DNSQueryFilter{}, 0, 20) + if err != nil || totalDNS != 2 || len(dnsRows) != 2 { + t.Fatalf("expected 2 non-error DNS rows when StoreErrorTraffic=false, got total=%d rows=%+v err=%v", totalDNS, dnsRows, err) + } + + // Enable error storage -> error flows & DNS errors are persisted. + tr.SetStoreErrorTraffic(true) + if !tr.StoreErrorTraffic() { + t.Fatalf("expected StoreErrorTraffic=true after toggle") + } + _ = tr.RecordNetFlow(NetFlowRecord{ID: "nf-err-kept", Protocol: "tcp", DstIP: "1.1.1.4", DstPort: 81, Action: "error", Error: "dial timeout"}) + _ = tr.RecordDNSQuery(DNSQueryRecord{ID: "dns-err-kept", QName: "fail.example", QType: "A", Action: "error", RCode: "SERVFAIL"}) + + errFlows, errFlowTotal, _ := tr.PageNetFlows(NetFlowQuery{Action: "error"}, 0, 10) + if errFlowTotal != 1 || len(errFlows) != 1 || errFlows[0].ID != "nf-err-kept" { + t.Fatalf("expected 1 stored error flow after enabling, got total=%d rows=%+v", errFlowTotal, errFlows) + } + errDNS, errDNSTotal, _ := tr.PageDNSQueries(DNSQueryFilter{Action: "error"}, 0, 10) + if errDNSTotal != 1 || len(errDNS) != 1 || errDNS[0].ID != "dns-err-kept" { + t.Fatalf("expected 1 stored error DNS query after enabling, got total=%d rows=%+v", errDNSTotal, errDNS) + } + + // RemotePolicyState mirrors default-off and snapshot toggle before queueing events. + var gotFlows []NetFlowRecord + var gotDNS []DNSQueryRecord + rs := NewRemotePolicyState("tok", + func(r NetFlowRecord) { gotFlows = append(gotFlows, r) }, + func(r DNSQueryRecord) { gotDNS = append(gotDNS, r) }, + nil, + ) + rs.RecordNetFlow(NetFlowRecord{ID: "r-err-1", Action: "error"}) + rs.RecordNetFlow(NetFlowRecord{ID: "r-ok-1", Action: "allow"}) + rs.RecordDNSQuery(DNSQueryRecord{ID: "d-err-1", Action: "error"}) + rs.RecordDNSQuery(DNSQueryRecord{ID: "d-ok-1", Action: "allow"}) + if len(gotFlows) != 1 || gotFlows[0].ID != "r-ok-1" || len(gotDNS) != 1 || gotDNS[0].ID != "d-ok-1" { + t.Fatalf("RemotePolicyState should drop error events by default: flows=%+v dns=%+v", gotFlows, gotDNS) + } + rs.Apply(GatewayPolicySnapshot{UDPPolicy: UDPPolicyBlockOnProxy, StoreErrorTraffic: true}) + rs.RecordNetFlow(NetFlowRecord{ID: "r-err-2", Action: "error"}) + rs.RecordDNSQuery(DNSQueryRecord{ID: "d-err-2", Action: "error"}) + if len(gotFlows) != 2 || gotFlows[1].ID != "r-err-2" || len(gotDNS) != 2 || gotDNS[1].ID != "d-err-2" { + t.Fatalf("RemotePolicyState should forward error events when enabled: flows=%+v dns=%+v", gotFlows, gotDNS) + } +} diff --git a/web/src/app/(main)/chat/_components/session-sandbox-control.tsx b/web/src/app/(main)/chat/_components/session-sandbox-control.tsx index a1d20a2..b900e96 100644 --- a/web/src/app/(main)/chat/_components/session-sandbox-control.tsx +++ b/web/src/app/(main)/chat/_components/session-sandbox-control.tsx @@ -81,22 +81,30 @@ export function SessionSandboxControl({ const [clearWorkspace, setClearWorkspace] = React.useState(false); const [removeOpen, setRemoveOpen] = React.useState(false); + const reqSeqRef = React.useRef(0); + const fetchInfo = React.useCallback( - async (withStats: boolean) => { - setLoading(true); + async (withStats: boolean, silent = false) => { + const seq = ++reqSeqRef.current; + if (!silent) setLoading(true); try { const res = await api.sandboxContainer("session", ownerID, withStats); - setInfo(res); + if (seq === reqSeqRef.current) { + setInfo(res); + } } catch { // Ignore transient poll errors; popover refresh button lets user retry. } finally { - setLoading(false); + if (seq === reqSeqRef.current && !silent) { + setLoading(false); + } } }, [ownerID], ); React.useEffect(() => { + reqSeqRef.current += 1; setInfo(null); void fetchInfo(false); }, [fetchInfo]); @@ -106,15 +114,42 @@ export function SessionSandboxControl({ void fetchInfo(true); }, [open, fetchInfo]); - // Refresh container status when a chat turn completes (a tool call may have started it). + // Refresh container status whenever a chat turn starts or completes (tool calls + // lazily create/start the container mid-turn). const prevRunningRef = React.useRef(chatRunning); React.useEffect(() => { - if (prevRunningRef.current && !chatRunning) { - void fetchInfo(open); + if (prevRunningRef.current !== chatRunning) { + void fetchInfo(open, true); } prevRunningRef.current = chatRunning; }, [chatRunning, open, fetchInfo]); + // Poll while a chat turn is running (every 2s until the container reports running, + // then every 5s) or while the popover is open so live status never stays stale. + const infoState = info?.state; + React.useEffect(() => { + if (infoState === "local") return; + if (!chatRunning && !open) return; + const intervalMs = chatRunning && infoState !== "running" ? 2000 : 5000; + const timer = window.setInterval(() => { + if (document.visibilityState === "visible") { + void fetchInfo(open, true); + } + }, intervalMs); + return () => window.clearInterval(timer); + }, [chatRunning, open, infoState, fetchInfo]); + + React.useEffect(() => { + if (infoState === "local") return; + const onVisibility = () => { + if (document.visibilityState === "visible") { + void fetchInfo(open, true); + } + }; + document.addEventListener("visibilitychange", onVisibility); + return () => document.removeEventListener("visibilitychange", onVisibility); + }, [open, infoState, fetchInfo]); + // Hide completely when running in local (non-Docker) mode. if (!info || info.state === "local") { return null; @@ -125,18 +160,21 @@ export function SessionSandboxControl({ let stateLabel = info.state; if (info.state === "running") stateLabel = L("沙箱运行中", "Sandbox Running"); + else if (info.state === "created") stateLabel = L("沙箱启动中", "Sandbox Starting"); else if (info.state === "exited") stateLabel = L("沙箱已停止", "Sandbox Stopped"); else if (info.state === "missing") stateLabel = L("沙箱未创建", "Sandbox Standby"); else if (info.state === "error") stateLabel = L("沙箱异常", "Sandbox Error"); let dotClass = "bg-muted-foreground/50"; if (running) dotClass = "bg-emerald-500"; + else if (info.state === "created") dotClass = "bg-amber-500"; else if (info.state === "error") dotClass = "bg-red-500"; const handleStart = async () => { setBusy("start"); try { const res = await api.startSandboxContainer("session", ownerID); + reqSeqRef.current += 1; setInfo(res); toast.success(L("会话沙箱容器已启动", "Session sandbox container started")); } catch (e) { @@ -150,6 +188,7 @@ export function SessionSandboxControl({ setBusy("stop"); try { const res = await api.stopSandboxContainer("session", ownerID); + reqSeqRef.current += 1; setInfo(res); toast.success(L("会话沙箱容器已停止(内存已释放)", "Session sandbox container stopped")); } catch (e) { @@ -166,6 +205,7 @@ export function SessionSandboxControl({ setBusy("recreate"); try { const res = await api.recreateSandboxContainer("session", ownerID, { clear_workspace: wipe }); + reqSeqRef.current += 1; setInfo(res); toast.success( wipe @@ -192,7 +232,6 @@ export function SessionSandboxControl({ setBusy(""); } }; - return ( <> diff --git a/web/src/app/(main)/function/tasks/detail/_components/task-sandbox-control.tsx b/web/src/app/(main)/function/tasks/detail/_components/task-sandbox-control.tsx index 30887a4..5413254 100644 --- a/web/src/app/(main)/function/tasks/detail/_components/task-sandbox-control.tsx +++ b/web/src/app/(main)/function/tasks/detail/_components/task-sandbox-control.tsx @@ -74,22 +74,32 @@ export function TaskSandboxControl({ task, onTaskUpdated }: { task: Task; onTask const [clearWorkspace, setClearWorkspace] = React.useState(false); const [removeOpen, setRemoveOpen] = React.useState(false); + const reqSeqRef = React.useRef(0); + const taskRunning = task.status === "running" && !task.paused; + const fetchInfo = React.useCallback( - async (withStats: boolean) => { - setLoading(true); + async (withStats: boolean, silent = false) => { + const seq = ++reqSeqRef.current; + if (!silent) setLoading(true); try { const res = await api.taskSandbox(task.id, withStats); - setInfo(res); + if (seq === reqSeqRef.current) { + setInfo(res); + } } catch { // Ignore transient poll errors; detail popover lets user retry. } finally { - setLoading(false); + if (seq === reqSeqRef.current && !silent) { + setLoading(false); + } } }, [task.id], ); React.useEffect(() => { + reqSeqRef.current += 1; + setInfo(null); void fetchInfo(false); }, [fetchInfo]); @@ -98,6 +108,45 @@ export function TaskSandboxControl({ task, onTaskUpdated }: { task: Task; onTask void fetchInfo(true); }, [open, fetchInfo]); + // Refresh when task execution state changes (starts container or triggers auto-stop). + const prevTaskRunningRef = React.useRef(taskRunning); + React.useEffect(() => { + const prev = prevTaskRunningRef.current; + prevTaskRunningRef.current = taskRunning; + if (prev === taskRunning) return; + void fetchInfo(open, true); + if (prev && !taskRunning) { + const followUp = window.setTimeout(() => void fetchInfo(open, true), 2000); + return () => window.clearTimeout(followUp); + } + }, [taskRunning, open, fetchInfo]); + + // Poll while the task is running (every 2s until the container reports running, + // then every 5s) or while the popover is open so live status stays in sync. + const infoState = info?.state; + React.useEffect(() => { + if (infoState === "local") return; + if (!taskRunning && !open) return; + const intervalMs = taskRunning && infoState !== "running" ? 2000 : 5000; + const timer = window.setInterval(() => { + if (document.visibilityState === "visible") { + void fetchInfo(open, true); + } + }, intervalMs); + return () => window.clearInterval(timer); + }, [taskRunning, open, infoState, fetchInfo]); + + React.useEffect(() => { + if (infoState === "local") return; + const onVisibility = () => { + if (document.visibilityState === "visible") { + void fetchInfo(open, true); + } + }; + document.addEventListener("visibilitychange", onVisibility); + return () => document.removeEventListener("visibilitychange", onVisibility); + }, [open, infoState, fetchInfo]); + // Hide completely when running in local (non-Docker) mode. if (!info || info.state === "local") { return null; @@ -105,27 +154,24 @@ export function TaskSandboxControl({ task, onTaskUpdated }: { task: Task; onTask const running = info.state === "running"; const exists = info.state !== "missing"; - const taskRunning = task.status === "running" && !task.paused; - const stateLabel = (() => { - switch (info.state) { - case "running": - return L("沙箱运行中", "Sandbox Running"); - case "exited": - return L("沙箱已停止", "Sandbox Stopped"); - case "missing": - return L("沙箱未创建", "Sandbox Not Created"); - case "error": - return L("沙箱异常", "Sandbox Error"); - default: - return info.state; - } - })(); + let stateLabel = info.state; + if (info.state === "running") stateLabel = L("沙箱运行中", "Sandbox Running"); + else if (info.state === "created") stateLabel = L("沙箱启动中", "Sandbox Starting"); + else if (info.state === "exited") stateLabel = L("沙箱已停止", "Sandbox Stopped"); + else if (info.state === "missing") stateLabel = L("沙箱未创建", "Sandbox Not Created"); + else if (info.state === "error") stateLabel = L("沙箱异常", "Sandbox Error"); + + let dotClass = "bg-muted-foreground/50"; + if (running) dotClass = "bg-emerald-500"; + else if (info.state === "created") dotClass = "bg-amber-500"; + else if (info.state === "error") dotClass = "bg-red-500"; const handleStart = async () => { setBusy("start"); try { const res = await api.startTaskSandbox(task.id); + reqSeqRef.current += 1; setInfo(res); toast.success(L("沙箱容器已启动", "Sandbox container started")); } catch (e) { @@ -148,6 +194,7 @@ export function TaskSandboxControl({ task, onTaskUpdated }: { task: Task; onTask setBusy("stop"); try { const res = await api.stopTaskSandbox(task.id, taskRunning); + reqSeqRef.current += 1; setInfo(res); toast.success(L("沙箱容器已停止(内存已释放)", "Sandbox container stopped")); if (taskRunning) onTaskUpdated(); @@ -168,6 +215,7 @@ export function TaskSandboxControl({ task, onTaskUpdated }: { task: Task; onTask pause_task: taskRunning, clear_workspace: wipe, }); + reqSeqRef.current += 1; setInfo(res); toast.success( wipe @@ -203,11 +251,7 @@ export function TaskSandboxControl({ task, onTaskUpdated }: { task: Task; onTask diff --git a/web/src/app/(main)/system/proxy/_components/container-routes-tab.tsx b/web/src/app/(main)/system/proxy/_components/container-routes-tab.tsx index 4916c31..007364e 100644 --- a/web/src/app/(main)/system/proxy/_components/container-routes-tab.tsx +++ b/web/src/app/(main)/system/proxy/_components/container-routes-tab.tsx @@ -11,6 +11,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Switch } from "@/components/ui/switch"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { useLiveTranslation } from "@/i18n/use-live-translation"; import { api } from "@/lib/api"; @@ -60,6 +61,8 @@ export function ContainerRoutesTab({ const [udpPolicy, setUdpPolicy] = React.useState(routesState?.gateway.udp_policy ?? "block_on_proxy"); const [dnsUpstream, setDnsUpstream] = React.useState(routesState?.gateway.dns_upstream ?? ""); const [savingGW, setSavingGW] = React.useState(false); + const [storeErrorTraffic, setStoreErrorTraffic] = React.useState(Boolean(routesState?.gateway.store_error_traffic)); + const [savingErrorToggle, setSavingErrorToggle] = React.useState(false); const [newScope, setNewScope] = React.useState<"task" | "session">("task"); const [newOwnerID, setNewOwnerID] = React.useState(""); @@ -74,13 +77,18 @@ export function ContainerRoutesTab({ if (routesState) { setUdpPolicy(routesState.gateway.udp_policy || "block_on_proxy"); setDnsUpstream(routesState.gateway.dns_upstream || ""); + setStoreErrorTraffic(Boolean(routesState.gateway.store_error_traffic)); } }, [routesState]); const saveGatewaySettings = async () => { setSavingGW(true); try { - await api.updateGatewaySettings({ udp_policy: udpPolicy, dns_upstream: dnsUpstream.trim() }); + await api.updateGatewaySettings({ + udp_policy: udpPolicy, + dns_upstream: dnsUpstream.trim(), + store_error_traffic: storeErrorTraffic, + }); await onRefresh(); toast.success(L("透明网关策略已更新并热下发", "Transparent gateway policy updated")); } catch (e) { @@ -90,6 +98,26 @@ export function ContainerRoutesTab({ } }; + const toggleStoreErrorTraffic = async (checked: boolean) => { + const prev = storeErrorTraffic; + setStoreErrorTraffic(checked); + setSavingErrorToggle(true); + try { + await api.updateGatewaySettings({ store_error_traffic: checked }); + await onRefresh(); + toast.success( + checked + ? L("已开启错误流量存储(连接失败/DNS 错误将落库)", "Error traffic storage enabled") + : L("已关闭错误流量存储(仅存储正常、透传与拦截流量)", "Error traffic storage disabled (default)"), + ); + } catch (e) { + setStoreErrorTraffic(prev); + toast.error(e instanceof Error ? e.message : String(e)); + } finally { + setSavingErrorToggle(false); + } + }; + const handleAddRoute = async (e: React.FormEvent) => { e.preventDefault(); const owner = newOwnerID.trim(); @@ -234,6 +262,28 @@ export function ContainerRoutesTab({ +
+
+ +

+ {L( + "默认关闭:放行、透传与黑名单拦截流量默认存储,端口扫描/超时等错误记录不落库。开启后可在「流量」页排查失败连接。", + "Off by default: allowed, passthrough, and blocked flows are stored, while connection/DNS errors are dropped. Enable to inspect failed connections on the Traffic page.", + )} +

+
+ void toggleStoreErrorTraffic(checked)} + /> +
{gw?.last_seen ? (

{L("网关标识:", "Gateway ID: ")} diff --git a/web/src/app/(main)/system/proxy/page.tsx b/web/src/app/(main)/system/proxy/page.tsx index b271a10..96a3ac7 100644 --- a/web/src/app/(main)/system/proxy/page.tsx +++ b/web/src/app/(main)/system/proxy/page.tsx @@ -99,6 +99,7 @@ export default function ProxyEgressPage() { const [newNote, setNewNote] = React.useState(""); const [addingRule, setAddingRule] = React.useState(false); const [routesState, setRoutesState] = React.useState(null); + const [savingStoreErrorTraffic, setSavingStoreErrorTraffic] = React.useState(false); const applySettings = React.useCallback((s: Settings) => { setGlobalProxyInput(s.global_proxy ?? ""); @@ -141,6 +142,30 @@ export default function ProxyEgressPage() { setRoutesState(rt); }, []); + const toggleStoreErrorTraffic = async (checked: boolean) => { + const prev = Boolean(routesState?.gateway.store_error_traffic); + setSavingStoreErrorTraffic(true); + setRoutesState((current) => + current ? { ...current, gateway: { ...current.gateway, store_error_traffic: checked } } : current, + ); + try { + await api.updateGatewaySettings({ store_error_traffic: checked }); + await refreshRoutes().catch(() => undefined); + toast.success( + checked + ? L("已开启错误流量存储(连接失败/DNS 错误将落库)", "Error traffic storage enabled") + : L("已关闭错误流量存储(仅存储正常、透传与拦截流量)", "Error traffic storage disabled (default)"), + ); + } catch (e) { + setRoutesState((current) => + current ? { ...current, gateway: { ...current.gateway, store_error_traffic: prev } } : current, + ); + toast.error(e instanceof Error ? e.message : String(e)); + } finally { + setSavingStoreErrorTraffic(false); + } + }; + React.useEffect(() => { void loadAll(); }, [loadAll]); @@ -465,7 +490,15 @@ export default function ProxyEgressPage() { - + { + if (value === "routes") { + void refreshRoutes().catch(() => undefined); + } + }} + className="w-full min-w-0 space-y-4" + > @@ -585,6 +618,26 @@ export default function ProxyEgressPage() { /> +

+
+ +

+ {L( + "默认关闭:仅存储放行、透传与拦截流量,不存储连接失败/超时及 DNS 解析错误;也可在「流量」页随时切换。", + "Off by default: stores allowed, passthrough, and blocked traffic while dropping connection/DNS errors. Also configurable on the Traffic page.", + )} +

+
+ void toggleStoreErrorTraffic(checked)} + /> +
+
{t("settings.customProbe")} @@ -919,8 +972,8 @@ export default function ProxyEgressPage() { .reverse() .map((log) => (

- {new Date(log.at).toLocaleTimeString(locale)} ·{" "} - {log.from || t("settings.direct")} → {log.to || t("settings.direct")} · {log.reason} + {new Date(log.at).toLocaleTimeString(locale)} · {log.from || t("settings.direct")} →{" "} + {log.to || t("settings.direct")} · {log.reason}

))} diff --git a/web/src/components/non-http-traffic-panel.tsx b/web/src/components/non-http-traffic-panel.tsx index dd61511..505458c 100644 --- a/web/src/components/non-http-traffic-panel.tsx +++ b/web/src/components/non-http-traffic-panel.tsx @@ -93,7 +93,19 @@ function FlowSourceBadge({ ); } -export function NonHTTPTrafficPanel({ mode, taskId }: { mode: "flows" | "dns"; taskId?: string }) { +export function NonHTTPTrafficPanel({ + mode, + taskId, + storeErrorTraffic, + onStoreErrorTrafficSync, + onEnableStoreErrorTraffic, +}: { + mode: "flows" | "dns"; + taskId?: string; + storeErrorTraffic?: boolean; + onStoreErrorTrafficSync?: (enabled: boolean) => void; + onEnableStoreErrorTraffic?: () => void; +}) { const { isEn, locale } = useLiveTranslation(); const L = (zh: string, en: string) => (isEn ? en : zh); const formatUpstream = (raw?: string) => (!raw || raw === "direct" ? L("直连", "Direct") : raw); @@ -145,6 +157,9 @@ export function NonHTTPTrafficPanel({ mode, taskId }: { mode: "flows" | "dns"; t }); setFlows(res.flows ?? []); setTotal(res.total ?? 0); + if (typeof res.store_error_traffic === "boolean") { + onStoreErrorTrafficSync?.(res.store_error_traffic); + } } else { const res = await api.trafficDNS({ qtype: qtypeFilter, @@ -156,13 +171,16 @@ export function NonHTTPTrafficPanel({ mode, taskId }: { mode: "flows" | "dns"; t }); setDnsRows(res.queries ?? []); setTotal(res.total ?? 0); + if (typeof res.store_error_traffic === "boolean") { + onStoreErrorTrafficSync?.(res.store_error_traffic); + } } } catch (e) { toast.error(e instanceof Error ? e.message : String(e)); } finally { setLoading(false); } - }, [mode, protoFilter, actionFilter, qtypeFilter, taskId, queryDebounced, page, size]); + }, [mode, protoFilter, actionFilter, qtypeFilter, taskId, queryDebounced, page, size, onStoreErrorTrafficSync]); React.useEffect(() => { void load(); @@ -318,6 +336,22 @@ export function NonHTTPTrafficPanel({ mode, taskId }: { mode: "flows" | "dns"; t + {actionFilter === "error" && storeErrorTraffic === false ? ( +
+ + {L( + "当前未开启错误流量存储,新的连接失败 / DNS 错误不会被落库。", + "Error traffic storage is currently off; new failed connections and DNS errors are not recorded.", + )} + + {onEnableStoreErrorTraffic ? ( + + ) : null} +
+ ) : null} + {/* Table */} {mode === "flows" ? ( diff --git a/web/src/components/traffic-history.tsx b/web/src/components/traffic-history.tsx index bd3a88f..ad79d22 100644 --- a/web/src/components/traffic-history.tsx +++ b/web/src/components/traffic-history.tsx @@ -39,13 +39,16 @@ import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"; import { SortableHead } from "@/components/ui/sortable-head"; +import { Switch } from "@/components/ui/switch"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { useLiveTranslation } from "@/i18n/use-live-translation"; import { type UITranslate, useUITranslation } from "@/i18n/use-ui-translation"; import { api } from "@/lib/api"; import { useStoredSortPreference } from "@/lib/sort-preference"; @@ -188,6 +191,8 @@ const STATUS_BUCKETS = ["2xx", "3xx", "4xx", "5xx"]; export function TrafficHistory({ taskId }: { taskId?: string }) { const { ui, liveUI } = useUITranslation(); + const { isEn } = useLiveTranslation(); + const L = (zh: string, en: string) => (isEn ? en : zh); const [protocolTab, setProtocolTab] = React.useState<"http" | "flows" | "dns">("http"); const taskScoped = Boolean(taskId); @@ -235,6 +240,38 @@ export function TrafficHistory({ taskId }: { taskId?: string }) { const [deleteMode, setDeleteMode] = React.useState<"filter" | "selected" | "all" | null>(null); // null = dialog closed const [deleting, setDeleting] = React.useState(false); const [reloadTick, setReloadTick] = React.useState(0); // manual refetch trigger + const [storeErrorTraffic, setStoreErrorTraffic] = React.useState(false); + const [savingStoreError, setSavingStoreError] = React.useState(false); + + React.useEffect(() => { + if (typeof traffic?.store_error_traffic === "boolean") { + setStoreErrorTraffic(traffic.store_error_traffic); + } + }, [traffic?.store_error_traffic]); + + const handleToggleStoreErrorTraffic = React.useCallback( + async (checked: boolean) => { + const prev = storeErrorTraffic; + setStoreErrorTraffic(checked); + setSavingStoreError(true); + try { + const updated = await api.updateGatewaySettings({ store_error_traffic: checked }); + setStoreErrorTraffic(Boolean(updated.store_error_traffic)); + setTraffic((cur) => (cur ? { ...cur, store_error_traffic: Boolean(updated.store_error_traffic) } : cur)); + const enabledMsg = isEn ? "Error traffic storage enabled" : "已开启错误流量存储(连接失败/DNS 错误将落库)"; + const disabledMsg = isEn + ? "Error traffic storage disabled" + : "已关闭错误流量存储(默认仅存储正常、透传与拦截流量)"; + toast.success(updated.store_error_traffic ? enabledMsg : disabledMsg); + } catch (e) { + setStoreErrorTraffic(prev); + toast.error(e instanceof Error ? e.message : String(e)); + } finally { + setSavingStoreError(false); + } + }, + [isEn, storeErrorTraffic], + ); // Debounce both filters so we don't refetch on every keystroke. React.useEffect(() => { @@ -542,16 +579,42 @@ export function TrafficHistory({ taskId }: { taskId?: string }) { - setProtocolTab(v as "http" | "flows" | "dns")}> - - HTTP / HTTPS - TCP / UDP - DNS - - +
+ setProtocolTab(v as "http" | "flows" | "dns")}> + + HTTP / HTTPS + TCP / UDP + DNS + + +
+ + void handleToggleStoreErrorTraffic(checked)} + /> +
+
{protocolTab !== "http" ? ( - + void handleToggleStoreErrorTraffic(true)} + /> ) : ( <> {/* Toolbar */} diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index cdae4f7..53bec14 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -1947,6 +1947,6 @@ export const api = { ) => put(`/proxy/routes/${encodeURIComponent(scope)}/${encodeURIComponent(ownerId)}`, body), deleteProxyRoute: (scope: string, ownerId: string) => del<{ deleted: string }>(`/proxy/routes/${encodeURIComponent(scope)}/${encodeURIComponent(ownerId)}`), - updateGatewaySettings: (body: { udp_policy: string; dns_upstream: string }) => - put<{ udp_policy: string; dns_upstream: string }>("/proxy/gateway/settings", body), + updateGatewaySettings: (body: { udp_policy?: string; dns_upstream?: string; store_error_traffic?: boolean }) => + put<{ udp_policy: string; dns_upstream: string; store_error_traffic: boolean }>("/proxy/gateway/settings", body), }; diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index bda4c6f..41cf6ab 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -971,6 +971,7 @@ export interface TrafficExchange { export interface TrafficResp { enabled: boolean; + store_error_traffic?: boolean; proxy?: string; count?: number; // global total (unfiltered) total?: number; // rows matching the current filter (for pagination) @@ -2136,6 +2137,7 @@ export interface TrafficNetFlow { export interface TrafficNetFlowsResp { enabled: boolean; + store_error_traffic?: boolean; count: number; total: number; page: number; @@ -2165,6 +2167,7 @@ export interface TrafficDNSQuery { export interface TrafficDNSResp { enabled: boolean; + store_error_traffic?: boolean; count: number; total: number; page: number; @@ -2198,6 +2201,7 @@ export interface TransparentGatewayStatus { last_seen?: string; udp_policy: "block_on_proxy" | "block" | "direct" | string; dns_upstream?: string; + store_error_traffic?: boolean; } export interface ProxyRoutesState {