Files
ARTEX-chixuweihu/server/gateway_api_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

280 lines
11 KiB
Go

package server
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/Autumn-27/artex/traffic"
)
func TestGatewaySyncAndNonHTTPTrafficAPIs(t *testing.T) {
t.Setenv("ARTEX_GATEWAY_TOKEN", "test-gw-token-218")
tr, err := traffic.Open(t.TempDir(), "127.0.0.1:0")
if err != nil {
t.Fatalf("open traffic: %v", err)
}
defer tr.Close()
s := &Server{
m: &Manager{
traffic: tr,
tasks: map[string]*Task{},
},
}
s.initProxyRoutesAndGateway()
// 1. Unauthorized gateway policy request must be rejected with 401.
reqUnauth := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy", nil)
recUnauth := httptest.NewRecorder()
s.getGatewayPolicy(recUnauth, reqUnauth)
if recUnauth.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 for missing token, got %d", recUnauth.Code)
}
// 2. Configure per-container proxy route + gateway settings.
putRouteBody := `{"mode":"proxy","proxy_url":"socks5://127.0.0.1:1080","note":"task 5 socks5"}`
reqRoute := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/5", bytes.NewBufferString(putRouteBody))
reqRoute.SetPathValue("scope", "task")
reqRoute.SetPathValue("owner_id", "5")
recRoute := httptest.NewRecorder()
s.putProxyRoute(recRoute, reqRoute)
if recRoute.Code != http.StatusOK {
t.Fatalf("putProxyRoute failed: %d %s", recRoute.Code, recRoute.Body.String())
}
reqGW := httptest.NewRequest(http.MethodPut, "/api/proxy/gateway/settings", bytes.NewBufferString(`{"udp_policy":"block","dns_upstream":"1.1.1.1:53"}`))
recGW := httptest.NewRecorder()
s.updateGatewaySettings(recGW, reqGW)
if recGW.Code != http.StatusOK {
t.Fatalf("updateGatewaySettings failed: %d %s", recGW.Code, recGW.Body.String())
}
// 3. Authorized gateway policy fetch returns route & settings.
reqPol := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy?gateway_id=gw-test", nil)
reqPol.Header.Set("X-Artex-Gateway-Token", "test-gw-token-218")
recPol := httptest.NewRecorder()
s.getGatewayPolicy(recPol, reqPol)
if recPol.Code != http.StatusOK {
t.Fatalf("getGatewayPolicy failed: %d %s", recPol.Code, recPol.Body.String())
}
var snap traffic.GatewayPolicySnapshot
if err := json.Unmarshal(recPol.Body.Bytes(), &snap); err != nil {
t.Fatalf("decode policy snapshot: %v", err)
}
if snap.UDPPolicy != traffic.UDPPolicyBlock || snap.DNSUpstream != "1.1.1.1:53" {
t.Fatalf("unexpected gateway policy: %+v", snap)
}
if r, ok := snap.ContainerRoutes["task:5"]; !ok || r.EffectiveURL != "socks5://127.0.0.1:1080" {
t.Fatalf("expected task:5 route in snapshot, got %+v", snap.ContainerRoutes)
}
// 4. Ingest gateway events (net_flows + dns_queries + block_events).
batch := traffic.GatewayEventBatch{
GatewayID: "gw-test",
NetFlows: []traffic.NetFlowRecord{{
ID: "nf-test-1",
TS: time.Now().Unix(),
Protocol: "tcp",
DstIP: "10.0.0.8",
DstPort: 3306,
DstHost: "db.target.local",
Action: "allow",
BytesTX: 64,
BytesRX: 128,
TXPreview: []byte("SELECT 1"),
RXPreview: []byte("5.7.40-mysql"),
SandboxScope: "task",
SandboxOwnerID: "5",
SrcIP: "172.30.0.5",
}},
DNSQueries: []traffic.DNSQueryRecord{{
ID: "dns-test-1",
TS: time.Now().Unix(),
QName: "db.target.local",
QType: "A",
RCode: "NOERROR",
Answers: []string{"10.0.0.8"},
Action: "allow",
Upstream: "direct:1.1.1.1:53",
SandboxScope: "task",
SandboxOwnerID: "5",
SrcIP: "172.30.0.5",
}},
}
rawBatch, _ := json.Marshal(batch)
reqEv := httptest.NewRequest(http.MethodPost, "/api/internal/gateway/events", bytes.NewReader(rawBatch))
reqEv.Header.Set("X-Artex-Gateway-Token", "test-gw-token-218")
recEv := httptest.NewRecorder()
s.postGatewayEvents(recEv, reqEv)
if recEv.Code != http.StatusOK {
t.Fatalf("postGatewayEvents failed: %d %s", recEv.Code, recEv.Body.String())
}
// 5. Query flows + flow detail + DNS via public API handlers.
recFlows := httptest.NewRecorder()
s.getTrafficFlows(recFlows, httptest.NewRequest(http.MethodGet, "/api/traffic/flows?protocol=tcp", nil))
if recFlows.Code != http.StatusOK {
t.Fatalf("getTrafficFlows: %d %s", recFlows.Code, recFlows.Body.String())
}
var flowsResp struct {
Total int `json:"total"`
Flows []traffic.NetFlowRecord `json:"flows"`
}
_ = json.Unmarshal(recFlows.Body.Bytes(), &flowsResp)
if flowsResp.Total != 1 || len(flowsResp.Flows) != 1 || flowsResp.Flows[0].DstPort != 3306 {
t.Fatalf("unexpected flowsResp: %+v", flowsResp)
}
reqDet := httptest.NewRequest(http.MethodGet, "/api/traffic/flows/nf-test-1", nil)
reqDet.SetPathValue("id", "nf-test-1")
recDet := httptest.NewRecorder()
s.getTrafficFlowDetail(recDet, reqDet)
if recDet.Code != http.StatusOK || !bytes.Contains(recDet.Body.Bytes(), []byte("SELECT 1")) {
t.Fatalf("unexpected flow detail: %d %s", recDet.Code, recDet.Body.String())
}
recDNS := httptest.NewRecorder()
s.getTrafficDNS(recDNS, httptest.NewRequest(http.MethodGet, "/api/traffic/dns?q=db.target", nil))
if recDNS.Code != http.StatusOK {
t.Fatalf("getTrafficDNS: %d %s", recDNS.Code, recDNS.Body.String())
}
var dnsResp struct {
Total int `json:"total"`
Queries []traffic.DNSQueryRecord `json:"queries"`
}
_ = json.Unmarshal(recDNS.Body.Bytes(), &dnsResp)
if dnsResp.Total != 1 || len(dnsResp.Queries) != 1 || dnsResp.Queries[0].QName != "db.target.local" {
t.Fatalf("unexpected dnsResp: %+v", dnsResp)
}
// 6. GET /api/proxy/routes reflects gateway connected=true and task:5 override.
recRoutes := httptest.NewRecorder()
s.getProxyRoutes(recRoutes, httptest.NewRequest(http.MethodGet, "/api/proxy/routes", nil))
if recRoutes.Code != http.StatusOK {
t.Fatalf("getProxyRoutes: %d %s", recRoutes.Code, recRoutes.Body.String())
}
body := recRoutes.Body.String()
if !bytes.Contains([]byte(body), []byte(`"connected":true`)) || !bytes.Contains([]byte(body), []byte(`"socks5://127.0.0.1:1080"`)) {
t.Fatalf("unexpected getProxyRoutes body: %s", body)
}
if bytes.Contains([]byte(body), []byte("全局")) {
t.Fatalf("getProxyRoutes must not hardcode Chinese labels in API response: %s", body)
}
}
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)
}
}