Files
ARTEX-chixuweihu/traffic/transparent_test.go
T
ji ruo d5926d6420 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.
2026-12-02 15:17:42 +08:00

594 lines
20 KiB
Go

package traffic
import (
"bytes"
"crypto/tls"
"encoding/binary"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
"time"
"github.com/miekg/dns"
)
func buildTestClientHello(sni string) []byte {
// Build minimal valid TLS 1.2 ClientHello with server_name extension.
var ext []byte
if sni != "" {
nameBytes := []byte(sni)
entry := make([]byte, 3+len(nameBytes))
entry[0] = 0x00 // host_name
binary.BigEndian.PutUint16(entry[1:3], uint16(len(nameBytes)))
copy(entry[3:], nameBytes)
list := make([]byte, 2+len(entry))
binary.BigEndian.PutUint16(list[0:2], uint16(len(entry)))
copy(list[2:], entry)
ext = make([]byte, 4+len(list))
binary.BigEndian.PutUint16(ext[0:2], 0x0000) // server_name ext type
binary.BigEndian.PutUint16(ext[2:4], uint16(len(list)))
copy(ext[4:], list)
}
var body bytes.Buffer
body.Write([]byte{0x03, 0x03}) // TLS 1.2
body.Write(make([]byte, 32)) // random
body.WriteByte(0x00) // session id len
body.Write([]byte{0x00, 0x02, 0x13, 0x01}) // cipher suites
body.Write([]byte{0x01, 0x00}) // compression methods
var extLen [2]byte
binary.BigEndian.PutUint16(extLen[:], uint16(len(ext)))
body.Write(extLen[:])
body.Write(ext)
hs := make([]byte, 4+body.Len())
hs[0] = 0x01 // ClientHello
hs[1] = byte((body.Len() >> 16) & 0xff)
hs[2] = byte((body.Len() >> 8) & 0xff)
hs[3] = byte(body.Len() & 0xff)
copy(hs[4:], body.Bytes())
rec := make([]byte, 5+len(hs))
rec[0] = 0x16 // Handshake
rec[1] = 0x03
rec[2] = 0x01
binary.BigEndian.PutUint16(rec[3:5], uint16(len(hs)))
copy(rec[5:], hs)
return rec
}
func TestSniffProtocol(t *testing.T) {
t.Run("TLS ClientHello SNI", func(t *testing.T) {
c1, c2 := net.Pipe()
defer c1.Close()
defer c2.Close()
ch := buildTestClientHello("api.target.example")
go func() { _, _ = c1.Write(ch) }()
res, wrapped := SniffProtocol(c2, 200*time.Millisecond)
if res.Proto != ProtoTLS || res.SNI != "api.target.example" {
t.Fatalf("expected TLS with SNI api.target.example, got %+v", res)
}
buf := make([]byte, len(ch))
if _, err := io.ReadFull(wrapped, buf); err != nil {
t.Fatalf("read replayed bytes: %v", err)
}
if !bytes.Equal(buf, ch) {
t.Fatalf("peeked bytes mismatch")
}
})
t.Run("Plaintext HTTP", func(t *testing.T) {
c1, c2 := net.Pipe()
defer c1.Close()
defer c2.Close()
req := []byte("GET /admin HTTP/1.1\r\nHost: web.target.local:8080\r\n\r\n")
go func() { _, _ = c1.Write(req) }()
res, wrapped := SniffProtocol(c2, 200*time.Millisecond)
if res.Proto != ProtoHTTP || res.Host != "web.target.local:8080" {
t.Fatalf("expected HTTP host web.target.local:8080, got %+v", res)
}
buf := make([]byte, len(req))
if _, err := io.ReadFull(wrapped, buf); err != nil {
t.Fatalf("read replayed bytes: %v", err)
}
if !bytes.Equal(buf, req) {
t.Fatalf("replayed HTTP mismatch")
}
})
t.Run("Raw TCP server-speaks-first timeout", func(t *testing.T) {
c1, c2 := net.Pipe()
defer c1.Close()
defer c2.Close()
start := time.Now()
res, _ := SniffProtocol(c2, 40*time.Millisecond)
if res.Proto != ProtoTCP {
t.Fatalf("expected ProtoTCP on timeout, got %+v", res)
}
if time.Since(start) > 500*time.Millisecond {
t.Fatalf("peek timeout took too long: %v", time.Since(start))
}
})
t.Run("Raw TCP binary protocol", func(t *testing.T) {
c1, c2 := net.Pipe()
defer c1.Close()
defer c2.Close()
payload := []byte("SSH-2.0-OpenSSH_9.6\r\n")
go func() { _, _ = c1.Write(payload) }()
res, _ := SniffProtocol(c2, 200*time.Millisecond)
if res.Proto != ProtoTCP {
t.Fatalf("expected ProtoTCP for SSH banner, got %+v", res)
}
})
}
func TestTransparentTCPAndBlacklistAndNetFlows(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()
// Pretend loopback client belongs to task 77 container.
tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) {
if srcIP == "127.0.0.1" {
return SourceIdentity{
Scope: "task",
OwnerID: "77",
ContainerID: "deadbeef12345678",
SrcIP: "172.30.0.9",
}, true
}
return SourceIdentity{}, false
})
// Start a raw TCP echo server (simulating Redis/nc/custom TCP service).
echoLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen echo: %v", err)
}
defer echoLn.Close()
go func() {
for {
c, err := echoLn.Accept()
if err != nil {
return
}
go func(conn net.Conn) {
defer conn.Close()
_, _ = conn.Write([]byte("+PONG-BANNER\r\n"))
buf := make([]byte, 64)
n, _ := conn.Read(buf)
if n > 0 {
_, _ = conn.Write([]byte("ECHO:" + string(buf[:n])))
}
}(c)
}
}()
echoAddr := echoLn.Addr().(*net.TCPAddr)
// Map echo IP to a domain in reverse DNS cache and test allow + block.
tr.RememberDNS(echoAddr.IP.String(), "redis.internal.test")
gw := NewTransparentGateway(TransparentConfig{
TCPAddr: "127.0.0.1:0",
PeekTimeout: 60 * time.Millisecond,
OrigDstResolver: func(_ net.Conn) (net.IP, int, error) {
return echoAddr.IP, echoAddr.Port, nil
},
}, LocalTransparentBackend{T: tr})
if err := gw.Start(); err != nil {
t.Fatalf("start transparent gateway: %v", err)
}
defer gw.Close()
// 1) Allowed raw TCP connection.
conn, err := net.DialTimeout("tcp", gw.TCPAddr(), 2*time.Second)
if err != nil {
t.Fatalf("dial gateway: %v", err)
}
_, _ = conn.Write([]byte("PING\r\n"))
got, _ := io.ReadAll(conn)
_ = conn.Close()
if !strings.Contains(string(got), "+PONG-BANNER") || !strings.Contains(string(got), "ECHO:PING") {
t.Fatalf("unexpected TCP relay response: %q", string(got))
}
// Wait briefly for flow persistence.
var flows []NetFlowRecord
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
rows, _, _ := tr.PageNetFlows(NetFlowQuery{OwnerTaskID: "77"}, 0, 10)
if len(rows) > 0 {
flows = rows
break
}
time.Sleep(20 * time.Millisecond)
}
if len(flows) != 1 {
t.Fatalf("expected 1 net_flow row, got %d", len(flows))
}
if flows[0].Protocol != "tcp" || flows[0].Action != "allow" || flows[0].DstHost != "redis.internal.test" {
t.Fatalf("unexpected flow row: %+v", flows[0])
}
if flows[0].BytesTX == 0 || flows[0].BytesRX == 0 {
t.Fatalf("expected non-zero bytes TX/RX: %+v", flows[0])
}
detail, err := tr.GetNetFlow(flows[0].ID)
if err != nil {
t.Fatalf("GetNetFlow: %v", err)
}
if !strings.Contains(detail.TXPreviewText, "PING") || !strings.Contains(detail.RXPreviewText, "PONG-BANNER") {
t.Fatalf("unexpected previews: tx=%q rx=%q", detail.TXPreviewText, detail.RXPreviewText)
}
// 2) Add egress blacklist for redis.internal.test -> next TCP flow must be blocked and recorded.
tr.SetEgressBlacklist([]EgressBlacklistRule{{
ID: "r1",
Enabled: true,
Kind: "suffix",
Pattern: "internal.test",
}})
conn2, err := net.DialTimeout("tcp", gw.TCPAddr(), 2*time.Second)
if err != nil {
t.Fatalf("dial gateway (blocked): %v", err)
}
_, _ = conn2.Write([]byte("PING\r\n"))
got2, _ := io.ReadAll(conn2)
_ = conn2.Close()
if len(got2) != 0 {
t.Fatalf("expected blocked TCP connection to receive 0 bytes, got %q", string(got2))
}
deadline = time.Now().Add(2 * time.Second)
var blockedFlows []NetFlowRecord
for time.Now().Before(deadline) {
rows, _, _ := tr.PageNetFlows(NetFlowQuery{Action: "block"}, 0, 10)
if len(rows) > 0 {
blockedFlows = rows
break
}
time.Sleep(20 * time.Millisecond)
}
if len(blockedFlows) != 1 || blockedFlows[0].BlockReason == "" {
t.Fatalf("expected 1 blocked net_flow, got %+v", blockedFlows)
}
// 3) Verify traffic_search tool queries tcp flows.
tools := tr.Tools()
rawArgs, _ := json.Marshal(map[string]any{"protocol": "tcp", "host": "redis.internal.test", "task_id": "77"})
res, err := tools[0].Call(t.Context(), rawArgs, nil)
if err != nil {
t.Fatalf("traffic_search tcp: %v", err)
}
if !strings.Contains(res.Flatten(), "redis.internal.test") {
t.Fatalf("expected traffic_search tcp to return flow, got %s", res.Flatten())
}
// 4) DeleteNonHTTPByOwner cleans up task 77's flows.
deleted, err := tr.DeleteNonHTTPByOwner("task", "77")
if err != nil || deleted < 2 {
t.Fatalf("expected >=2 deleted rows, got %d err=%v", deleted, err)
}
}
func TestTransparentDNSInterceptionAndBlocking(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 == "127.0.0.1" {
return SourceIdentity{Scope: "task", OwnerID: "88", ContainerID: "cafebabe9999", SrcIP: "172.30.0.8"}, true
}
return SourceIdentity{}, false
})
tr.SetEgressBlacklist([]EgressBlacklistRule{
{ID: "b-dom", Enabled: true, Kind: "suffix", Pattern: "blocked.gov"},
{ID: "b-ip", Enabled: true, Kind: "ip", Pattern: "198.51.100.77"},
})
// Mock upstream authoritative DNS server on localhost.
upPC, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen mock upstream dns: %v", err)
}
defer upPC.Close()
upMux := dns.NewServeMux()
upMux.HandleFunc(".", func(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
if len(r.Question) > 0 {
q := r.Question[0]
ip := "93.184.216.34"
if strings.Contains(strings.ToLower(q.Name), "rebind.example") {
ip = "198.51.100.77"
}
m.Answer = append(m.Answer, &dns.A{
Hdr: dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 60},
A: net.ParseIP(ip),
})
}
_ = w.WriteMsg(m)
})
upSrv := &dns.Server{PacketConn: upPC, Handler: upMux}
go func() { _ = upSrv.ActivateAndServe() }()
defer upSrv.Shutdown()
tr.SetGatewaySettings(UDPPolicyBlockOnProxy, upPC.LocalAddr().String())
// Pick a free UDP+TCP port for the transparent DNS listener.
probeLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("probe port: %v", err)
}
dnsAddr := probeLn.Addr().String()
_ = probeLn.Close()
gw := NewTransparentGateway(TransparentConfig{DNSAddr: dnsAddr}, LocalTransparentBackend{T: tr})
if err := gw.Start(); err != nil {
t.Fatalf("start dns gateway: %v", err)
}
defer gw.Close()
c := &dns.Client{Net: "udp", Timeout: 2 * time.Second}
// 1) Allowed domain resolves and caches IP -> domain.
q1 := new(dns.Msg)
q1.SetQuestion("app.allowed.example.", dns.TypeA)
r1, _, err := c.Exchange(q1, dnsAddr)
if err != nil || r1.Rcode != dns.RcodeSuccess || len(r1.Answer) == 0 {
t.Fatalf("expected allowed DNS reply, got r1=%v err=%v", r1, err)
}
if rev := tr.LookupDNSReverse("93.184.216.34"); rev != "app.allowed.example" {
t.Fatalf("expected reverse DNS cache 'app.allowed.example', got %q", rev)
}
// 2) Blacklisted domain is REFUSED pre-resolution.
q2 := new(dns.Msg)
q2.SetQuestion("secret.blocked.gov.", dns.TypeA)
r2, _, err := c.Exchange(q2, dnsAddr)
if err != nil || r2.Rcode != dns.RcodeRefused {
t.Fatalf("expected REFUSED for blacklisted domain, got r2=%v err=%v", r2, err)
}
// 3) DNS rebinding / resolved blacklisted IP is REFUSED post-resolution.
q3 := new(dns.Msg)
q3.SetQuestion("rebind.example.", dns.TypeA)
r3, _, err := c.Exchange(q3, dnsAddr)
if err != nil || r3.Rcode != dns.RcodeRefused {
t.Fatalf("expected REFUSED for blacklisted resolved IP, got r3=%v err=%v", r3, err)
}
// Verify all 3 queries recorded in dns_queries with task attribution.
rows, total, err := tr.PageDNSQueries(DNSQueryFilter{OwnerTaskID: "88"}, 0, 10)
if err != nil || total != 3 || len(rows) != 3 {
t.Fatalf("expected 3 dns_queries rows, got total=%d len=%d err=%v", total, len(rows), err)
}
}
func TestTransparentUDPPolicy(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 global upstream proxy + OPSEC default UDPPolicyBlockOnProxy.
if err := tr.SetUpstreamProxy("socks5://127.0.0.1:1080"); err != nil {
t.Fatalf("set upstream: %v", err)
}
tr.SetGatewaySettings(UDPPolicyBlockOnProxy, "")
gw := NewTransparentGateway(TransparentConfig{}, LocalTransparentBackend{T: tr})
src := &net.UDPAddr{IP: net.ParseIP("172.30.0.5"), Port: 54321}
dst := &net.UDPAddr{IP: net.ParseIP("93.184.216.34"), Port: 9999}
gw.HandleUDPPacket(src, dst, []byte("hello-udp"))
rows, total, err := tr.PageNetFlows(NetFlowQuery{Protocol: "udp", Action: "block"}, 0, 10)
if err != nil || total != 1 || len(rows) != 1 {
t.Fatalf("expected 1 blocked UDP flow under block_on_proxy, got total=%d err=%v", total, err)
}
if !strings.Contains(rows[0].BlockReason, "OPSEC") {
t.Fatalf("expected OPSEC block reason, got %q", rows[0].BlockReason)
}
}
func TestPerSourceUpstreamOverrideAndTransparentHTTPBridge(t *testing.T) {
// Start recording proxy on an ephemeral port.
probe, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("probe: %v", err)
}
proxyAddr := probe.Addr().String()
_ = probe.Close()
tr, err := Open(t.TempDir(), proxyAddr)
if err != nil {
t.Fatalf("open traffic: %v", err)
}
defer tr.Close()
tr.SetGatewayToken("gw-secret-token")
// Verify per-source upstream resolver precedence.
if err := tr.SetUpstreamProxy("http://127.0.0.1:19999"); err != nil {
t.Fatalf("set global upstream: %v", err)
}
directURL, _ := url.Parse("http://127.0.0.1:29999")
tr.SetUpstreamResolver(func(src SourceIdentity) (*url.URL, bool) {
if src.Scope == "task" && src.OwnerID == "10" {
return nil, true // force direct
}
if src.Scope == "task" && src.OwnerID == "20" {
return directURL, true // custom proxy
}
return nil, false // inherit global
})
if u := tr.resolveUpstreamForSource(SourceIdentity{Scope: "task", OwnerID: "10"}); u != nil {
t.Fatalf("task 10 should resolve to direct (nil), got %v", u)
}
if u := tr.resolveUpstreamForSource(SourceIdentity{Scope: "task", OwnerID: "20"}); u == nil || u.String() != directURL.String() {
t.Fatalf("task 20 should resolve to %v, got %v", directURL, u)
}
if u := tr.resolveUpstreamForSource(SourceIdentity{Scope: "task", OwnerID: "30"}); u == nil || u.Host != "127.0.0.1:19999" {
t.Fatalf("task 30 should inherit global proxy, got %v", u)
}
// Clear global proxy and start real go-mitmproxy to verify HTTP transparent bridge.
_ = tr.SetUpstreamProxy("")
go func() { _ = tr.Start() }()
// Wait for proxy port to listen.
for range 40 {
if c, derr := net.DialTimeout("tcp", proxyAddr, 50*time.Millisecond); derr == nil {
_ = c.Close()
break
}
time.Sleep(25 * time.Millisecond)
}
targetSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Proxy-Authorization") != "" {
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte("transparent-http-ok"))
}))
defer targetSrv.Close()
tu, _ := url.Parse(targetSrv.URL)
th, tpStr, _ := net.SplitHostPort(tu.Host)
tp, _ := strconv.Atoi(tpStr)
tr.SetSourceResolver(func(srcIP string) (SourceIdentity, bool) {
if srcIP == "127.0.0.1" {
return SourceIdentity{Scope: "task", OwnerID: "10", ContainerID: "abc123456789", SrcIP: "172.30.0.10"}, true
}
return SourceIdentity{}, false
})
gw := NewTransparentGateway(TransparentConfig{
TCPAddr: "127.0.0.1:0",
MITMProxyAddr: proxyAddr,
OrigDstResolver: func(_ net.Conn) (net.IP, int, error) {
return net.ParseIP(th), tp, nil
},
}, LocalTransparentBackend{T: tr})
if err := gw.Start(); err != nil {
t.Fatalf("start gateway: %v", err)
}
defer gw.Close()
// Send origin-form HTTP directly to transparent gateway (simulating curl after `unset HTTP_PROXY`).
c, err := net.DialTimeout("tcp", gw.TCPAddr(), 2*time.Second)
if err != nil {
t.Fatalf("dial gw: %v", err)
}
_, _ = c.Write([]byte("GET /hello HTTP/1.1\r\nHost: " + tu.Host + "\r\nConnection: close\r\n\r\n"))
respBytes, _ := io.ReadAll(c)
_ = c.Close()
if !strings.Contains(string(respBytes), "transparent-http-ok") {
t.Fatalf("expected transparent HTTP response, got %q", string(respBytes))
}
// Verify exchange recorded with task 10 attribution.
deadline := time.Now().Add(2 * time.Second)
var rows []ExchangeMeta
for time.Now().Before(deadline) {
ex, _, _ := tr.Page(PageQuery{OwnerTaskID: "10", RespMin: -1, RespMax: -1}, 0, 10)
if len(ex) > 0 {
rows = ex
break
}
time.Sleep(25 * time.Millisecond)
}
if len(rows) == 0 || rows[0].SandboxOwnerID != "10" {
t.Fatalf("expected HTTP exchange attributed to task 10, got %+v", rows)
}
// 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)
}
}