package server import ( "bytes" "context" "encoding/json" "fmt" "net" "io" "net/http" "net/http/httptest" "net/url" "strings" "time" "os" "strconv" "github.com/Autumn-27/artex/db" "sync/atomic" "testing" "github.com/Autumn-27/artex/traffic" ) func TestContainerProxyPoolModeAndRotation(t *testing.T) { t.Setenv("ARTEX_GATEWAY_TOKEN", "gw-tok-pool-test") m := &Manager{ tasks: map[string]*Task{}, proxyPool: &proxyPoolState{ active: "node-a", entries: []proxyPoolEntry{ { ProxyPoolEntry: ProxyPoolEntry{ID: "node-a", Name: "HK-1", URL: "http://127.0.0.1:18081", Enabled: true, Health: "healthy"}, RawURL: "http://127.0.0.1:18081", }, { ProxyPoolEntry: ProxyPoolEntry{ID: "node-b", Name: "SG-2", URL: "http://127.0.0.1:18082", Enabled: true, Health: "healthy"}, RawURL: "http://127.0.0.1:18082", }, }, }, globalProxy: "http://127.0.0.1:18081", } s := &Server{m: m} s.initProxyRoutesAndGateway() // 1. Set task:5 to mode=pool. req := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/5", bytes.NewBufferString(`{"mode":"pool"}`)) req.SetPathValue("scope", "task") req.SetPathValue("owner_id", "5") rec := httptest.NewRecorder() s.putProxyRoute(rec, req) if rec.Code != http.StatusOK { t.Fatalf("putProxyRoute pool failed: %d %s", rec.Code, rec.Body.String()) } // 2. Pin session:conv-9 to node-a by name. reqPin := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/session/conv-9", bytes.NewBufferString(`{"mode":"proxy","proxy_pool_id":"HK-1"}`)) reqPin.SetPathValue("scope", "session") reqPin.SetPathValue("owner_id", "conv-9") recPin := httptest.NewRecorder() s.putProxyRoute(recPin, reqPin) if recPin.Code != http.StatusOK { t.Fatalf("putProxyRoute pin failed: %d %s", recPin.Code, recPin.Body.String()) } // 3. Force task:8 direct. reqDir := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/8", bytes.NewBufferString(`{"mode":"direct"}`)) reqDir.SetPathValue("scope", "task") reqDir.SetPathValue("owner_id", "8") recDir := httptest.NewRecorder() s.putProxyRoute(recDir, reqDir) if recDir.Code != http.StatusOK { t.Fatalf("putProxyRoute direct failed: %d %s", recDir.Code, recDir.Body.String()) } fetchSnap := func() traffic.GatewayPolicySnapshot { polReq := httptest.NewRequest(http.MethodGet, "/api/internal/gateway/policy?gateway_id=gw-1", nil) polReq.Header.Set("X-Artex-Gateway-Token", "gw-tok-pool-test") polRec := httptest.NewRecorder() s.getGatewayPolicy(polRec, polReq) if polRec.Code != http.StatusOK { t.Fatalf("getGatewayPolicy: %d %s", polRec.Code, polRec.Body.String()) } var snap traffic.GatewayPolicySnapshot if err := json.Unmarshal(polRec.Body.Bytes(), &snap); err != nil { t.Fatalf("unmarshal snapshot: %v", err) } return snap } state := traffic.NewRemotePolicyState("gw-tok-pool-test", nil, nil, nil) state.Apply(fetchSnap()) if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "task", OwnerID: "5"}); u == nil || u.String() != "http://127.0.0.1:18081" { t.Fatalf("expected task:5 pool -> node-a, got %v", u) } if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "session", OwnerID: "conv-9"}); u == nil || u.String() != "http://127.0.0.1:18081" { t.Fatalf("expected session:conv-9 pin -> node-a, got %v", u) } if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "task", OwnerID: "8"}); u != nil { t.Fatalf("expected task:8 direct -> nil, got %v", u) } // 4. Rotate proxy pool active entry to node-b. m.proxyPool.mu.Lock() m.proxyPool.active = "node-b" m.proxyPool.mu.Unlock() m.mu.Lock() m.globalProxy = "http://127.0.0.1:18082" m.mu.Unlock() state.Apply(fetchSnap()) if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "task", OwnerID: "5"}); u == nil || u.String() != "http://127.0.0.1:18082" { t.Fatalf("expected task:5 pool to follow rotation to node-b, got %v", u) } if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "session", OwnerID: "conv-9"}); u == nil || u.String() != "http://127.0.0.1:18081" { t.Fatalf("expected session:conv-9 pin to stay on node-a after rotation, got %v", u) } if u := state.ResolveUpstream(traffic.SourceIdentity{Scope: "task", OwnerID: "8"}); u != nil { t.Fatalf("expected task:8 direct to stay direct after rotation, got %v", u) } // 5. Verify GET /api/proxy/routes/{scope}/{owner_id} reflects rotated effective proxy. getReq := httptest.NewRequest(http.MethodGet, "/api/proxy/routes/task/5", nil) getReq.SetPathValue("scope", "task") getReq.SetPathValue("owner_id", "5") getRec := httptest.NewRecorder() s.getProxyRoute(getRec, getReq) if getRec.Code != http.StatusOK { t.Fatalf("getProxyRoute failed: %d %s", getRec.Code, getRec.Body.String()) } var view map[string]any if err := json.Unmarshal(getRec.Body.Bytes(), &view); err != nil { t.Fatalf("decode getProxyRoute: %v", err) } if view["mode"] != "pool" || view["effective_proxy"] != "http://127.0.0.1:18082" { t.Fatalf("unexpected getProxyRoute view: %+v", view) } } func TestChatProxyToolsListAndSetTaskProxy(t *testing.T) { m := &Manager{ tasks: map[string]*Task{ "12": {ID: "12", Name: "Demo Task"}, }, proxyPool: &proxyPoolState{ active: "p1", entries: []proxyPoolEntry{ { ProxyPoolEntry: ProxyPoolEntry{ID: "p1", Name: "JP-Node", URL: "socks5://127.0.0.1:1081", Enabled: true, Health: "healthy"}, RawURL: "socks5://127.0.0.1:1081", }, }, }, } s := &Server{m: m} s.initProxyRoutesAndGateway() setTool := s.toolSetTaskProxy() res, err := setTool.Call(context.Background(), json.RawMessage(`{"task_id":12,"mode":"pool","note":"chat requested"}`), nil) if err != nil || res.IsError { t.Fatalf("set_task_proxy pool failed: err=%v res=%+v", err, res) } text1 := "" for _, b := range res.Content { text1 += b.Text } if !strings.Contains(text1, `"mode":"pool"`) || !strings.Contains(text1, `socks5://127.0.0.1:1081`) { t.Fatalf("unexpected set_task_proxy output: %s", text1) } // Pin by node Name instead of ID. res, err = setTool.Call(context.Background(), json.RawMessage(`{"task_id":"12","mode":"proxy","proxy_pool_id":"JP-Node"}`), nil) if err != nil || res.IsError { t.Fatalf("set_task_proxy by name failed: err=%v res=%+v", err, res) } text2 := "" for _, b := range res.Content { text2 += b.Text } if !strings.Contains(text2, `"proxy_pool_id":"p1"`) { t.Fatalf("expected canonical pool id p1, got: %s", text2) } listTool := s.toolListProxyPool() listRes, err := listTool.Call(context.Background(), json.RawMessage(`{}`), nil) if err != nil || listRes.IsError { t.Fatalf("list_proxy_pool failed: err=%v res=%+v", err, listRes) } text3 := "" for _, b := range listRes.Content { text3 += b.Text } if !strings.Contains(text3, `"JP-Node"`) || !strings.Contains(text3, `"owner_id":"12"`) { t.Fatalf("unexpected list_proxy_pool output: %s", text3) } // Non-existent task must error. badRes, err := setTool.Call(context.Background(), json.RawMessage(`{"task_id":"999","mode":"direct"}`), nil) if err != nil || !badRes.IsError { t.Fatalf("expected error for missing task, got err=%v res=%+v", err, badRes) } } func TestChatMentionTaskParsing(t *testing.T) { refs, err := parseChatMentions("请给 @[任务#5 官网渗透] 和 @[task#5 重复] 以及 @[task#19 API审计] 设置代理池") if err != nil { t.Fatalf("parseChatMentions error: %v", err) } if len(refs) != 2 || refs[0].Kind != "task" || refs[0].ID != 5 || refs[1].Kind != "task" || refs[1].ID != 19 { t.Fatalf("unexpected task mention refs: %+v", refs) } } func TestRealHTTPProxyRoutingPerContainer(t *testing.T) { var targetHits, proxyAHits, proxyBHits atomic.Int32 targetSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { targetHits.Add(1) w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("DIRECT_ORIGIN")) })) defer targetSrv.Close() makeProxy := func(tag string, counter *atomic.Int32) *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { counter.Add(1) if r.Method == http.MethodConnect { hj, ok := w.(http.Hijacker) if !ok { http.Error(w, "hijack unsupported", 500) return } conn, _, err := hj.Hijack() if err != nil { return } defer conn.Close() _, _ = conn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) buf := make([]byte, 4096) _, _ = conn.Read(buf) body := "VIA_" + tag _, _ = fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(body), body) return } w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("VIA_" + tag)) })) } proxyA := makeProxy("PROXY_A", &proxyAHits) defer proxyA.Close() proxyB := makeProxy("PROXY_B", &proxyBHits) defer proxyB.Close() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("alloc free port: %v", err) } proxyAddr := ln.Addr().String() _ = ln.Close() tr, err := traffic.Open(t.TempDir(), proxyAddr) if err != nil { t.Fatalf("open traffic: %v", err) } defer tr.Close() go func() { _ = tr.Start() }() deadline := time.Now().Add(3 * time.Second) for time.Now().Before(deadline) { if c, derr := net.DialTimeout("tcp", proxyAddr, 100*time.Millisecond); derr == nil { _ = c.Close() break } time.Sleep(25 * time.Millisecond) } m := &Manager{ traffic: tr, tasks: map[string]*Task{}, proxyPool: &proxyPoolState{ active: "pa", entries: []proxyPoolEntry{ {ProxyPoolEntry: ProxyPoolEntry{ID: "pa", Name: "A", URL: proxyA.URL, Enabled: true, Health: "healthy"}, RawURL: proxyA.URL}, {ProxyPoolEntry: ProxyPoolEntry{ID: "pb", Name: "B", URL: proxyB.URL, Enabled: true, Health: "healthy"}, RawURL: proxyB.URL}, }, }, globalProxy: proxyA.URL, } _ = tr.SetUpstreamProxy(proxyA.URL) s := &Server{m: m} s.initProxyRoutesAndGateway() if _, err := s.setContainerProxyRoute("task", "1", ProxyRouteInput{Mode: "pool"}); err != nil { t.Fatalf("set task 1 pool: %v", err) } if _, err := s.setContainerProxyRoute("task", "2", ProxyRouteInput{Mode: "proxy", ProxyPoolID: "pb"}); err != nil { t.Fatalf("set task 2 pb: %v", err) } if _, err := s.setContainerProxyRoute("task", "3", ProxyRouteInput{Mode: "direct"}); err != nil { t.Fatalf("set task 3 direct: %v", err) } callAsTask := func(taskID string) string { t.Helper() tagged := traffic.FormatProxyContextURL("http://"+proxyAddr, traffic.SourceIdentity{Scope: "task", OwnerID: taskID}) pu, err := url.Parse(tagged) if err != nil { t.Fatalf("parse tagged proxy url: %v", err) } client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}} defer client.CloseIdleConnections() resp, err := client.Get(targetSrv.URL + "/check") if err != nil { t.Fatalf("request as task %s failed: %v", taskID, err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) return string(body) } if got := callAsTask("1"); got != "VIA_PROXY_A" { t.Fatalf("task 1 (pool active=pa) expected VIA_PROXY_A, got %q", got) } if got := callAsTask("2"); got != "VIA_PROXY_B" { t.Fatalf("task 2 (pinned pb) expected VIA_PROXY_B, got %q", got) } if got := callAsTask("3"); got != "DIRECT_ORIGIN" { t.Fatalf("task 3 (direct) expected DIRECT_ORIGIN, got %q", got) } // Rotate pool active to pb and re-verify task 1 follows the rotation! m.proxyPool.mu.Lock() m.proxyPool.active = "pb" m.proxyPool.mu.Unlock() if got := callAsTask("1"); got != "VIA_PROXY_B" { t.Fatalf("task 1 (pool rotated to pb) expected VIA_PROXY_B, got %q", got) } if proxyAHits.Load() == 0 || proxyBHits.Load() < 2 || targetHits.Load() == 0 { t.Fatalf("unexpected hit counts: proxyA=%d proxyB=%d direct=%d", proxyAHits.Load(), proxyBHits.Load(), targetHits.Load()) } } func TestProxyScheduleAndTaskMentionWithPostgres(t *testing.T) { dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN")) if dsn == "" { t.Skip("requires ARTEX_PG_DSN") } pg, err := db.Open(dsn) if err != nil { t.Fatalf("open pg: %v", err) } defer pg.Close() m := &Manager{ pg: pg, dir: t.TempDir(), tasks: map[string]*Task{}, proxyPool: &proxyPoolState{ active: "pg-node-1", entries: []proxyPoolEntry{ { ProxyPoolEntry: ProxyPoolEntry{ID: "pg-node-1", Name: "PG-Node-1", URL: "http://127.0.0.1:19801", Enabled: true, Health: "healthy"}, RawURL: "http://127.0.0.1:19801", }, }, }, globalProxy: "http://127.0.0.1:19801", } s := &Server{m: m} s.initProxyRoutesAndGateway() task, err := m.CreateTask("proxy-e2e-task", "verify proxy schedule and mention", nil, 0, 0) if err != nil { t.Fatalf("CreateTask: %v", err) } taskID, _ := strconv.ParseInt(task.ID, 10, 64) // 1. Create schedule with custom authenticated proxy URL -> applied to bound task & masked in response. body := fmt.Sprintf(`{"name":"proxy-sched","schedule_type":"weekly","weekdays":[1,2,3,4,5],"start_time":"09:00","proxy_mode":"proxy","proxy_url":"http://alice:topsecret@127.0.0.1:19802","task_ids":[%d]}`, taskID) req := httptest.NewRequest(http.MethodPost, "/api/schedules", bytes.NewBufferString(body)) rec := httptest.NewRecorder() s.createSchedule(rec, req) if rec.Code != http.StatusCreated { t.Fatalf("createSchedule failed: %d %s", rec.Code, rec.Body.String()) } if strings.Contains(rec.Body.String(), "topsecret") { t.Fatalf("createSchedule leaked raw proxy password: %s", rec.Body.String()) } var schedResp map[string]any if err := json.Unmarshal(rec.Body.Bytes(), &schedResp); err != nil { t.Fatalf("decode schedule: %v", err) } schedID := int64(schedResp["id"].(float64)) view, _ := s.containerProxyRouteView("task", task.ID) if view.Mode != "proxy" || !strings.Contains(view.EffectiveProxy, "127.0.0.1:19802") { t.Fatalf("expected schedule proxy applied to bound task, got %+v", view) } // 2. Update schedule to mode=pool -> bound task immediately switches to pool mode. updBody := fmt.Sprintf(`{"name":"proxy-sched","schedule_type":"weekly","weekdays":[1,2,3,4,5],"start_time":"09:00","proxy_mode":"pool","task_ids":[%d]}`, taskID) updReq := httptest.NewRequest(http.MethodPatch, fmt.Sprintf("/api/schedules/%d", schedID), bytes.NewBufferString(updBody)) updReq.SetPathValue("id", strconv.FormatInt(schedID, 10)) updRec := httptest.NewRecorder() s.updateSchedule(updRec, updReq) if updRec.Code != http.StatusOK { t.Fatalf("updateSchedule failed: %d %s", updRec.Code, updRec.Body.String()) } view, _ = s.containerProxyRouteView("task", task.ID) if view.Mode != "pool" || view.EffectiveProxy != "http://127.0.0.1:19801" { t.Fatalf("expected updated schedule pool mode applied to task, got %+v", view) } // 3. @task mention search & context snapshot injection. page, err := pg.SearchChatMentionsPage(context.Background(), "task", "proxy-e2e-task", "") if err != nil { t.Fatalf("SearchChatMentionsPage: %v", err) } found := false for _, item := range page.Items { if item.Kind == "task" && item.ID == taskID { found = true break } } if !found { t.Fatalf("expected task #%d in @task mention search, got %+v", taskID, page.Items) } injected, err := composeChatMentionMessage(pg, fmt.Sprintf("给 @[task#%d proxy-e2e-task] 设置代理池", taskID)) if err != nil { t.Fatalf("composeChatMentionMessage: %v", err) } if !strings.Contains(injected, "proxy-e2e-task") || !strings.Contains(injected, `"mode":"pool"`) { t.Fatalf("expected task snapshot with proxy_route in mention message, got: %s", injected) } }