mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-03 20:21:51 +08:00
feat(proxy,chat): add per-task/schedule/chat proxy pool routing and @task mentions
- Support pool auto-rotation mode alongside inherit/direct/node/custom proxy routes across gateway and MITM proxy
- Add GET /api/proxy/routes/{scope}/{owner_id}, task create/DTO proxy_route, and schedule proxy persistence + propagation
- Add list_proxy_pool and set_task_proxy chat agent tools and @task mention search/context injection
- Wire shared proxy/pool selectors into tasks, schedules, chat sandbox popover, and container routes UI
This commit is contained in:
1 parent
b18cf89b77
commit
778e49317d
28 files changed
+1683
-124
No files matched your search
@@ -272,6 +272,9 @@ func (sc *Scheduler) fireTaskSchedulesAt(now time.Time) {
|
||||
for _, item := range items {
|
||||
w := windows[item.ID]
|
||||
errors := []string{}
|
||||
if w.active {
|
||||
sc.s.applyScheduleProxyToTasks(item)
|
||||
}
|
||||
for _, id := range item.TaskIDs {
|
||||
if seen[id] {
|
||||
continue
|
||||
|
||||
+27
-3
@@ -17,11 +17,11 @@ const maxChatMentions = 10
|
||||
|
||||
// The visible token survives drafts, uploads, retries and conversation history.
|
||||
// Labels are only for display: the server trusts only the type and numeric ID.
|
||||
var chatMentionPattern = regexp.MustCompile(`@\[(finding|asset|company|endpoint|ip|app|root_domain|subdomain|service|漏洞|资产|企业|接口|IP|应用|域名|子域名|服务)#([0-9]+)(?: [^\]\r\n]*)?\]`)
|
||||
var chatMentionPattern = regexp.MustCompile(`@\[(task|finding|asset|company|endpoint|ip|app|root_domain|subdomain|service|任务|漏洞|资产|企业|接口|IP|应用|域名|子域名|服务)#([0-9]+)(?: [^\]\r\n]*)?\]`)
|
||||
var chatMentionKinds = map[string]string{
|
||||
"漏洞": "finding", "资产": "asset", "企业": "company", "接口": "endpoint",
|
||||
"任务": "task", "漏洞": "finding", "资产": "asset", "企业": "company", "接口": "endpoint",
|
||||
"IP": "ip", "应用": "app", "域名": "root_domain", "子域名": "subdomain", "服务": "service",
|
||||
"finding": "finding", "asset": "asset", "company": "company", "endpoint": "endpoint",
|
||||
"task": "task", "finding": "finding", "asset": "asset", "company": "company", "endpoint": "endpoint",
|
||||
"ip": "ip", "app": "app", "root_domain": "root_domain", "subdomain": "subdomain", "service": "service",
|
||||
}
|
||||
|
||||
@@ -140,6 +140,30 @@ func composeChatMentionMessage(pg *db.DB, message string) (string, error) {
|
||||
|
||||
func loadChatMention(pg *db.DB, ref chatMentionRef) (any, error) {
|
||||
switch ref.Kind {
|
||||
case "task":
|
||||
t, err := pg.GetTask(ref.ID)
|
||||
if err != nil || t == nil {
|
||||
return nil, err
|
||||
}
|
||||
route := map[string]any{"mode": "inherit"}
|
||||
if raw, ok, _ := pg.GetSetting(settingContainerProxyRoutes); ok && strings.TrimSpace(raw) != "" {
|
||||
var list []ContainerProxyRoute
|
||||
if json.Unmarshal([]byte(raw), &list) == nil {
|
||||
targetOwner := strconv.FormatInt(t.ID, 10)
|
||||
for _, r := range list {
|
||||
if r.Scope == "task" && r.OwnerID == targetOwner {
|
||||
route = map[string]any{
|
||||
"mode": r.Mode,
|
||||
"proxy_pool_id": r.ProxyPoolID,
|
||||
"proxy_url": maskSecrets(r.ProxyURL),
|
||||
"note": r.Note,
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return map[string]any{"task": t, "proxy_route": route}, nil
|
||||
case "finding":
|
||||
f, err := pg.GetFinding(ref.ID)
|
||||
if err != nil || f == nil {
|
||||
|
||||
@@ -78,6 +78,7 @@ type TaskDTO struct {
|
||||
NoResultMinFindings int `json:"no_result_min_findings"`
|
||||
NoResultMinSeverity string `json:"no_result_min_severity"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
ProxyRoute *TaskProxyRouteDTO `json:"proxy_route,omitempty"`
|
||||
}
|
||||
|
||||
type ProxyReconnectDTO struct {
|
||||
@@ -96,6 +97,14 @@ type FindingSeverityDTO struct {
|
||||
Low int `json:"low"`
|
||||
}
|
||||
|
||||
// TaskProxyRouteDTO summarizes a task container's effective proxy route override.
|
||||
type TaskProxyRouteDTO struct {
|
||||
Mode string `json:"mode"`
|
||||
ProxyPoolID string `json:"proxy_pool_id,omitempty"`
|
||||
ProxyURL string `json:"proxy_url,omitempty"`
|
||||
EffectiveProxy string `json:"effective_proxy"`
|
||||
}
|
||||
|
||||
func applyTaskArchiveBlocker(dto *TaskDTO, blockers map[int64]int64) {
|
||||
if dto == nil || len(blockers) == 0 {
|
||||
return
|
||||
|
||||
+39
-1
@@ -83,6 +83,8 @@ func (s *Server) orchestrationTools() []actool.CoreTool {
|
||||
s.toolUpdateFindingReport(),
|
||||
s.toolGetFindingTraffic(),
|
||||
s.toolBindFindingTraffic(),
|
||||
s.toolListProxyPool(),
|
||||
s.toolSetTaskProxy(),
|
||||
}, s.findingCaseTools()...)
|
||||
}
|
||||
|
||||
@@ -275,6 +277,9 @@ func (s *Server) toolSpawnTask() actool.CoreTool {
|
||||
"plan_heartbeat_seconds": map[string]any{"type": "integer", "description": "可选:planner 心跳触发间隔(秒)。距上轮规划结束/任务开始满该值且期间无触发 → 触发一轮规划(兜底死锁 + 唤醒去监督飞行中的 worker)。留空或 0 = 默认 600(10min);"},
|
||||
"seed_first_intent": map[string]any{"type": "boolean", "description": "可选:对于简单任务可开启,创建时直接下发一条种子意图(内容=描述+目标)让 worker 免等首轮 planner 直接开跑测试;默认 false(走标准先规划再执行)。"},
|
||||
"attachments": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "可选:要从当前对话工作区附带到新任务工作区(/workspace/uploads/)的文件路径列表,如 [\"uploads/targets.txt\"]。"},
|
||||
"proxy_mode": map[string]any{"type": "string", "enum": []string{"inherit", "direct", "pool", "proxy"}, "description": "可选:任务容器出口代理模式(inherit=继承全局,direct=直连,pool=代理池自动轮换,proxy=指定节点或自定义 URL)"},
|
||||
"proxy_pool_id": strParam("可选(proxy_mode=proxy 时):代理池节点 ID 或名称"),
|
||||
"proxy_url": strParam("可选(proxy_mode=proxy 且未指定 proxy_pool_id 时):自定义代理 URL"),
|
||||
}, "description", "goal"),
|
||||
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
var a struct {
|
||||
@@ -290,6 +295,9 @@ func (s *Server) toolSpawnTask() actool.CoreTool {
|
||||
PlanHeartbeatSeconds int `json:"plan_heartbeat_seconds"`
|
||||
SeedFirstIntent bool `json:"seed_first_intent"`
|
||||
Attachments []string `json:"attachments"`
|
||||
ProxyMode string `json:"proxy_mode"`
|
||||
ProxyPoolID string `json:"proxy_pool_id"`
|
||||
ProxyURL string `json:"proxy_url"`
|
||||
}
|
||||
if err := json.Unmarshal(in, &a); err != nil {
|
||||
return actool.Errorf("参数无效: " + err.Error()), nil
|
||||
@@ -336,6 +344,28 @@ func (s *Server) toolSpawnTask() actool.CoreTool {
|
||||
if pin != nil {
|
||||
llmIDs = []int64{*pin}
|
||||
}
|
||||
var validatedProxy *ProxyRouteInput
|
||||
if strings.TrimSpace(a.ProxyMode) != "" || strings.TrimSpace(a.ProxyPoolID) != "" || strings.TrimSpace(a.ProxyURL) != "" {
|
||||
pm := strings.TrimSpace(a.ProxyMode)
|
||||
if pm == "" {
|
||||
pm = "proxy"
|
||||
}
|
||||
norm, perr := s.validateAndNormalizeProxyRoute(ProxyRouteInput{
|
||||
Mode: pm,
|
||||
ProxyPoolID: a.ProxyPoolID,
|
||||
ProxyURL: a.ProxyURL,
|
||||
}, nil)
|
||||
if perr != nil {
|
||||
return actool.Errorf("任务代理配置无效: " + perr.Error()), nil
|
||||
}
|
||||
if norm.Mode != "inherit" {
|
||||
validatedProxy = &ProxyRouteInput{
|
||||
Mode: norm.Mode,
|
||||
ProxyPoolID: norm.ProxyPoolID,
|
||||
ProxyURL: norm.ProxyURL,
|
||||
}
|
||||
}
|
||||
}
|
||||
name := ""
|
||||
autoTitleEnabled := s.m.pg.GetBool(db.SettingTaskAutoTitle, false)
|
||||
if autoTitleEnabled {
|
||||
@@ -395,6 +425,11 @@ func (s *Server) toolSpawnTask() actool.CoreTool {
|
||||
}
|
||||
}
|
||||
}
|
||||
if validatedProxy != nil {
|
||||
if _, perr := s.setContainerProxyRoute("task", t.ID, *validatedProxy); perr != nil {
|
||||
log.Printf("[spawn_task] 任务 #%s 应用代理路由失败: %v", t.ID, perr)
|
||||
}
|
||||
}
|
||||
// 共享的建后流程,与 HTTP 建任务(server.go createTask)复用同一段 launchTask:
|
||||
// seed + 后台可见地做目标分解(第0轮/LLM步骤/逐条goal) + engine.Run。
|
||||
// seed_first_intent 默认 false(标准先规划再执行);简单任务可开启直接下发一 work 测试。
|
||||
@@ -633,6 +668,8 @@ func defaultOrchestrationToolBindings(name string) json.RawMessage {
|
||||
switch {
|
||||
case name == "resume_task":
|
||||
return json.RawMessage(`["auto","mainagent"]`)
|
||||
case name == "list_proxy_pool" || name == "set_task_proxy":
|
||||
return json.RawMessage(`["auto","mainagent","pentest"]`)
|
||||
case name == "bind_finding_traffic" || strings.Contains(name, "finding_case") || name == "search_finding_duplicates" || name == "get_finding_record" || name == "merge_finding_records":
|
||||
return json.RawMessage(`["reporter"]`)
|
||||
default:
|
||||
@@ -655,6 +692,7 @@ func (s *Server) seedOrchestrationTools() {
|
||||
s.refreshBuiltinToolSchemas()
|
||||
s.seedAutoDefaultBindings()
|
||||
s.seedTaskReopenBindings()
|
||||
s.seedProxyToolBindings()
|
||||
s.seedPlannerDefaultBindings()
|
||||
s.seedPlannerListAssetsBinding()
|
||||
s.seedCompanyScopeRebind()
|
||||
@@ -746,7 +784,7 @@ func (s *Server) migrateReporterWorkflow() {
|
||||
// reaches an old DB otherwise. Preserves each tool's agent binding + enabled flag.
|
||||
// Bump the flag whenever these tools' schemas/descriptions change in code.
|
||||
func (s *Server) refreshBuiltinToolSchemas() {
|
||||
const flag = "tool_schema_refresh_v9_task_reopen_tools"
|
||||
const flag = "tool_schema_refresh_v10_proxy_tools"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -259,6 +259,34 @@ func (m *Manager) proxyPoolEntries() []proxyPoolEntry {
|
||||
return append([]proxyPoolEntry(nil), m.proxyPool.entries...)
|
||||
}
|
||||
|
||||
// ActivePoolRawURL returns the active (or first available enabled) proxy pool entry ID and raw URL.
|
||||
func (m *Manager) ActivePoolRawURL() (string, string) {
|
||||
if m == nil || m.proxyPool == nil {
|
||||
return "", ""
|
||||
}
|
||||
m.proxyPool.mu.Lock()
|
||||
defer m.proxyPool.mu.Unlock()
|
||||
if len(m.proxyPool.entries) == 0 {
|
||||
return "", ""
|
||||
}
|
||||
for _, e := range m.proxyPool.entries {
|
||||
if e.ID == m.proxyPool.active && e.Enabled && strings.TrimSpace(e.RawURL) != "" {
|
||||
return e.ID, strings.TrimSpace(e.RawURL)
|
||||
}
|
||||
}
|
||||
for _, e := range m.proxyPool.entries {
|
||||
if e.Enabled && e.Health != "unhealthy-cooling" && strings.TrimSpace(e.RawURL) != "" {
|
||||
return e.ID, strings.TrimSpace(e.RawURL)
|
||||
}
|
||||
}
|
||||
for _, e := range m.proxyPool.entries {
|
||||
if e.Enabled && strings.TrimSpace(e.RawURL) != "" {
|
||||
return e.ID, strings.TrimSpace(e.RawURL)
|
||||
}
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
func (m *Manager) setProxyPoolEntries(entries []proxyPoolEntry, active string) error {
|
||||
if m.proxyPool == nil {
|
||||
m.proxyPool = &proxyPoolState{}
|
||||
|
||||
+210
-91
@@ -24,13 +24,21 @@ const (
|
||||
type ContainerProxyRoute struct {
|
||||
Scope string `json:"scope"` // task, session
|
||||
OwnerID string `json:"owner_id"` // task ID or session ID
|
||||
Mode string `json:"mode"` // inherit, direct, proxy
|
||||
Mode string `json:"mode"` // inherit, direct, pool, proxy
|
||||
ProxyPoolID string `json:"proxy_pool_id,omitempty"` // optional proxy pool entry ID
|
||||
ProxyURL string `json:"proxy_url,omitempty"` // raw custom URL in storage; masked in API output
|
||||
Note string `json:"note,omitempty"`
|
||||
UpdatedAt string `json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
// ProxyRouteInput is the shared request payload for setting a container/task/schedule proxy route.
|
||||
type ProxyRouteInput struct {
|
||||
Mode string `json:"mode"`
|
||||
ProxyPoolID string `json:"proxy_pool_id,omitempty"`
|
||||
ProxyURL string `json:"proxy_url,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
}
|
||||
|
||||
// GatewaySettings persists transparent gateway runtime policy knobs.
|
||||
type GatewaySettings struct {
|
||||
UDPPolicy string `json:"udp_policy"`
|
||||
@@ -106,29 +114,45 @@ func (s *Server) storeErrorTrafficEnabled() bool {
|
||||
return rt.gwSettings.StoreErrorTraffic
|
||||
}
|
||||
|
||||
func (s *Server) resolvePoolEntryRawURL(poolID string) string {
|
||||
poolID = strings.TrimSpace(poolID)
|
||||
if poolID == "" {
|
||||
return ""
|
||||
func (s *Server) resolvePoolEntryByIDOrName(ref string) (string, string) {
|
||||
ref = strings.TrimSpace(ref)
|
||||
if ref == "" {
|
||||
return "", ""
|
||||
}
|
||||
for _, e := range s.m.proxyPoolEntries() {
|
||||
if e.ID == poolID {
|
||||
return strings.TrimSpace(e.RawURL)
|
||||
entries := s.m.proxyPoolEntries()
|
||||
for _, e := range entries {
|
||||
if e.ID == ref {
|
||||
return e.ID, strings.TrimSpace(e.RawURL)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
for _, e := range entries {
|
||||
if name := strings.TrimSpace(e.Name); name != "" && strings.EqualFold(name, ref) {
|
||||
return e.ID, strings.TrimSpace(e.RawURL)
|
||||
}
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
func (s *Server) resolvePoolEntryRawURL(poolID string) string {
|
||||
_, raw := s.resolvePoolEntryByIDOrName(poolID)
|
||||
return raw
|
||||
}
|
||||
|
||||
func (s *Server) resolveRouteEffectiveRawURL(r ContainerProxyRoute) string {
|
||||
if strings.ToLower(strings.TrimSpace(r.Mode)) != "proxy" {
|
||||
switch strings.ToLower(strings.TrimSpace(r.Mode)) {
|
||||
case "pool":
|
||||
_, raw := s.m.ActivePoolRawURL()
|
||||
return raw
|
||||
case "proxy":
|
||||
if r.ProxyPoolID != "" {
|
||||
if raw := s.resolvePoolEntryRawURL(r.ProxyPoolID); raw != "" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(r.ProxyURL)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
if r.ProxyPoolID != "" {
|
||||
if raw := s.resolvePoolEntryRawURL(r.ProxyPoolID); raw != "" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(r.ProxyURL)
|
||||
}
|
||||
|
||||
func (s *Server) resolveContainerUpstream(src traffic.SourceIdentity) (*url.URL, bool) {
|
||||
@@ -145,7 +169,7 @@ func (s *Server) resolveContainerUpstream(src traffic.SourceIdentity) (*url.URL,
|
||||
switch strings.ToLower(strings.TrimSpace(r.Mode)) {
|
||||
case "direct":
|
||||
return nil, true
|
||||
case "proxy":
|
||||
case "pool", "proxy":
|
||||
raw := s.resolveRouteEffectiveRawURL(r)
|
||||
if raw == "" {
|
||||
return nil, false
|
||||
@@ -160,6 +184,148 @@ func (s *Server) resolveContainerUpstream(src traffic.SourceIdentity) (*url.URL,
|
||||
}
|
||||
}
|
||||
|
||||
type proxyRouteValidationError struct{ msg string }
|
||||
|
||||
func (e *proxyRouteValidationError) Error() string { return e.msg }
|
||||
|
||||
func (s *Server) validateAndNormalizeProxyRoute(req ProxyRouteInput, prev *ContainerProxyRoute) (ContainerProxyRoute, error) {
|
||||
mode := strings.ToLower(strings.TrimSpace(req.Mode))
|
||||
if mode == "" {
|
||||
mode = "inherit"
|
||||
}
|
||||
if mode != "inherit" && mode != "direct" && mode != "pool" && mode != "proxy" {
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{"mode must be inherit, direct, pool, or proxy"}
|
||||
}
|
||||
route := ContainerProxyRoute{
|
||||
Mode: mode,
|
||||
ProxyPoolID: strings.TrimSpace(req.ProxyPoolID),
|
||||
ProxyURL: strings.TrimSpace(req.ProxyURL),
|
||||
Note: strings.TrimSpace(req.Note),
|
||||
UpdatedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
switch mode {
|
||||
case "inherit", "direct":
|
||||
route.ProxyPoolID = ""
|
||||
route.ProxyURL = ""
|
||||
case "pool":
|
||||
if _, raw := s.m.ActivePoolRawURL(); raw == "" {
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{"代理池暂无可用节点,请先在代理设置中添加并启用节点"}
|
||||
}
|
||||
route.ProxyPoolID = ""
|
||||
route.ProxyURL = ""
|
||||
case "proxy":
|
||||
if route.ProxyPoolID != "" {
|
||||
id, raw := s.resolvePoolEntryByIDOrName(route.ProxyPoolID)
|
||||
if raw == "" {
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{fmt.Sprintf("proxy_pool_id %q not found", route.ProxyPoolID)}
|
||||
}
|
||||
route.ProxyPoolID = id
|
||||
route.ProxyURL = ""
|
||||
} else {
|
||||
// If user left masked placeholder unchanged, preserve existing raw URL.
|
||||
if strings.Contains(route.ProxyURL, "***") && prev != nil && prev.ProxyURL != "" {
|
||||
route.ProxyURL = prev.ProxyURL
|
||||
}
|
||||
if _, err := traffic.ValidateProxyURL(route.ProxyURL); err != nil {
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{err.Error()}
|
||||
}
|
||||
}
|
||||
}
|
||||
return route, nil
|
||||
}
|
||||
|
||||
func (s *Server) setContainerProxyRoute(scope, ownerID string, req ProxyRouteInput) (ContainerProxyRoute, error) {
|
||||
scope = strings.ToLower(strings.TrimSpace(scope))
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
if (scope != "task" && scope != "session") || ownerID == "" {
|
||||
return ContainerProxyRoute{}, &proxyRouteValidationError{"invalid scope or owner_id (scope must be task or session)"}
|
||||
}
|
||||
rt := s.ensureRouteRuntime()
|
||||
key := scope + ":" + ownerID
|
||||
rt.mu.RLock()
|
||||
var prevPtr *ContainerProxyRoute
|
||||
if prev, ok := rt.routes[key]; ok {
|
||||
cp := prev
|
||||
prevPtr = &cp
|
||||
}
|
||||
rt.mu.RUnlock()
|
||||
|
||||
route, err := s.validateAndNormalizeProxyRoute(req, prevPtr)
|
||||
if err != nil {
|
||||
return ContainerProxyRoute{}, err
|
||||
}
|
||||
route.Scope = scope
|
||||
route.OwnerID = ownerID
|
||||
|
||||
if route.Mode == "inherit" {
|
||||
rt.mu.Lock()
|
||||
delete(rt.routes, key)
|
||||
err := s.saveContainerProxyRoutesLocked(rt)
|
||||
rt.mu.Unlock()
|
||||
if err != nil {
|
||||
return ContainerProxyRoute{}, err
|
||||
}
|
||||
return ContainerProxyRoute{Scope: scope, OwnerID: ownerID, Mode: "inherit"}, nil
|
||||
}
|
||||
|
||||
rt.mu.Lock()
|
||||
rt.routes[key] = route
|
||||
err = s.saveContainerProxyRoutesLocked(rt)
|
||||
rt.mu.Unlock()
|
||||
if err != nil {
|
||||
return ContainerProxyRoute{}, err
|
||||
}
|
||||
return s.maskedRouteView(route), nil
|
||||
}
|
||||
|
||||
func (s *Server) effectiveProxyDisplay(route *ContainerProxyRoute) (effective string, globalDisplay string) {
|
||||
globalRaw := strings.TrimSpace(s.m.GlobalProxy())
|
||||
globalDisplay = "direct"
|
||||
if globalRaw != "" {
|
||||
globalDisplay = maskSecrets(globalRaw)
|
||||
}
|
||||
if route == nil || route.Mode == "" || route.Mode == "inherit" {
|
||||
return globalDisplay, globalDisplay
|
||||
}
|
||||
if route.Mode == "direct" {
|
||||
return "direct", globalDisplay
|
||||
}
|
||||
if raw := s.resolveRouteEffectiveRawURL(*route); raw != "" {
|
||||
return maskSecrets(raw), globalDisplay
|
||||
}
|
||||
if route.Mode == "pool" {
|
||||
return "direct", globalDisplay
|
||||
}
|
||||
return globalDisplay, globalDisplay
|
||||
}
|
||||
|
||||
func (s *Server) containerProxyRouteView(scope, ownerID string) (containerRouteStatusItem, string) {
|
||||
scope = strings.ToLower(strings.TrimSpace(scope))
|
||||
ownerID = strings.TrimSpace(ownerID)
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.RLock()
|
||||
existing, ok := rt.routes[scope+":"+ownerID]
|
||||
rt.mu.RUnlock()
|
||||
item := containerRouteStatusItem{
|
||||
Scope: scope,
|
||||
OwnerID: ownerID,
|
||||
Mode: "inherit",
|
||||
}
|
||||
var rPtr *ContainerProxyRoute
|
||||
if ok {
|
||||
cp := existing
|
||||
rPtr = &cp
|
||||
item.Mode = existing.Mode
|
||||
item.ProxyPoolID = existing.ProxyPoolID
|
||||
item.ProxyURL = maskSecrets(existing.ProxyURL)
|
||||
item.Note = existing.Note
|
||||
item.UpdatedAt = existing.UpdatedAt
|
||||
}
|
||||
eff, globalDisplay := s.effectiveProxyDisplay(rPtr)
|
||||
item.EffectiveProxy = eff
|
||||
return item, globalDisplay
|
||||
}
|
||||
|
||||
func (s *Server) saveContainerProxyRoutesLocked(rt *proxyRouteRuntime) error {
|
||||
if s.m.pg == nil {
|
||||
return nil
|
||||
@@ -196,7 +362,7 @@ type containerRouteStatusItem struct {
|
||||
ContainerID string `json:"container_id,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
Mode string `json:"mode"` // inherit, direct, proxy
|
||||
Mode string `json:"mode"` // inherit, direct, pool, proxy
|
||||
ProxyPoolID string `json:"proxy_pool_id,omitempty"`
|
||||
ProxyURL string `json:"proxy_url,omitempty"`
|
||||
EffectiveProxy string `json:"effective_proxy"`
|
||||
@@ -339,94 +505,47 @@ func (s *Server) getProxyRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// PUT /api/proxy/routes/{scope}/{owner_id}
|
||||
func (s *Server) putProxyRoute(w http.ResponseWriter, r *http.Request) {
|
||||
// GET /api/proxy/routes/{scope}/{owner_id}
|
||||
func (s *Server) getProxyRoute(w http.ResponseWriter, r *http.Request) {
|
||||
scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope")))
|
||||
ownerID := strings.TrimSpace(r.PathValue("owner_id"))
|
||||
if (scope != "task" && scope != "session") || ownerID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "invalid scope or owner_id (scope must be task or session)")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Mode string `json:"mode"`
|
||||
ProxyPoolID string `json:"proxy_pool_id"`
|
||||
ProxyURL string `json:"proxy_url"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
item, globalDisplay := s.containerProxyRouteView(scope, ownerID)
|
||||
writeJSON(w, 200, map[string]any{
|
||||
"scope": item.Scope,
|
||||
"owner_id": item.OwnerID,
|
||||
"mode": item.Mode,
|
||||
"proxy_pool_id": item.ProxyPoolID,
|
||||
"proxy_url": item.ProxyURL,
|
||||
"effective_proxy": item.EffectiveProxy,
|
||||
"global_proxy": globalDisplay,
|
||||
"note": item.Note,
|
||||
"updated_at": item.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
// PUT /api/proxy/routes/{scope}/{owner_id}
|
||||
func (s *Server) putProxyRoute(w http.ResponseWriter, r *http.Request) {
|
||||
scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope")))
|
||||
ownerID := strings.TrimSpace(r.PathValue("owner_id"))
|
||||
var req ProxyRouteInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "invalid JSON body")
|
||||
return
|
||||
}
|
||||
mode := strings.ToLower(strings.TrimSpace(req.Mode))
|
||||
if mode == "" {
|
||||
mode = "inherit"
|
||||
}
|
||||
if mode != "inherit" && mode != "direct" && mode != "proxy" {
|
||||
writeErr(w, http.StatusBadRequest, "mode must be inherit, direct, or proxy")
|
||||
return
|
||||
}
|
||||
|
||||
rt := s.ensureRouteRuntime()
|
||||
key := scope + ":" + ownerID
|
||||
|
||||
if mode == "inherit" {
|
||||
rt.mu.Lock()
|
||||
delete(rt.routes, key)
|
||||
err := s.saveContainerProxyRoutesLocked(rt)
|
||||
rt.mu.Unlock()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
route, err := s.setContainerProxyRoute(scope, ownerID, req)
|
||||
if err != nil {
|
||||
if _, ok := err.(*proxyRouteValidationError); ok {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, ContainerProxyRoute{Scope: scope, OwnerID: ownerID, Mode: "inherit"})
|
||||
return
|
||||
}
|
||||
|
||||
route := ContainerProxyRoute{
|
||||
Scope: scope,
|
||||
OwnerID: ownerID,
|
||||
Mode: mode,
|
||||
ProxyPoolID: strings.TrimSpace(req.ProxyPoolID),
|
||||
ProxyURL: strings.TrimSpace(req.ProxyURL),
|
||||
Note: strings.TrimSpace(req.Note),
|
||||
UpdatedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
if mode == "proxy" {
|
||||
if route.ProxyPoolID != "" {
|
||||
if s.resolvePoolEntryRawURL(route.ProxyPoolID) == "" {
|
||||
writeErr(w, http.StatusBadRequest, fmt.Sprintf("proxy_pool_id %q not found", route.ProxyPoolID))
|
||||
return
|
||||
}
|
||||
route.ProxyURL = ""
|
||||
} else {
|
||||
// If user left masked placeholder unchanged, preserve existing raw URL.
|
||||
if strings.Contains(route.ProxyURL, "***") {
|
||||
rt.mu.RLock()
|
||||
if prev, ok := rt.routes[key]; ok && prev.ProxyURL != "" {
|
||||
route.ProxyURL = prev.ProxyURL
|
||||
}
|
||||
rt.mu.RUnlock()
|
||||
}
|
||||
if _, err := traffic.ValidateProxyURL(route.ProxyURL); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
route.ProxyPoolID = ""
|
||||
route.ProxyURL = ""
|
||||
}
|
||||
|
||||
rt.mu.Lock()
|
||||
rt.routes[key] = route
|
||||
err := s.saveContainerProxyRoutesLocked(rt)
|
||||
rt.mu.Unlock()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, s.maskedRouteView(route))
|
||||
writeJSON(w, 200, route)
|
||||
}
|
||||
|
||||
// DELETE /api/proxy/routes/{scope}/{owner_id}
|
||||
|
||||
@@ -0,0 +1,438 @@
|
||||
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:[email protected]: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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
func parseTaskIDArg(raw json.RawMessage) string {
|
||||
if len(raw) == 0 {
|
||||
return ""
|
||||
}
|
||||
var s string
|
||||
if json.Unmarshal(raw, &s) == nil {
|
||||
return strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(s), "#"))
|
||||
}
|
||||
var n int64
|
||||
if json.Unmarshal(raw, &n) == nil && n > 0 {
|
||||
return strconv.FormatInt(n, 10)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) toolListProxyPool() actool.CoreTool {
|
||||
return roTool("list_proxy_pool",
|
||||
"查看当前全局出口代理、代理池节点列表(含 ID、名称、健康状态、出口 IP)以及所有任务/会话容器的自定义代理路由。",
|
||||
objSchema(map[string]any{}),
|
||||
func(context.Context, json.RawMessage) (actool.Result, error) {
|
||||
entries, activeID, _ := s.m.ProxyPoolSnapshot()
|
||||
rt := s.ensureRouteRuntime()
|
||||
rt.mu.RLock()
|
||||
routesCopy := make([]ContainerProxyRoute, 0, len(rt.routes))
|
||||
for _, r := range rt.routes {
|
||||
routesCopy = append(routesCopy, r)
|
||||
}
|
||||
rt.mu.RUnlock()
|
||||
|
||||
globalRaw := strings.TrimSpace(s.m.GlobalProxy())
|
||||
globalDisplay := "direct"
|
||||
if globalRaw != "" {
|
||||
globalDisplay = maskSecrets(globalRaw)
|
||||
}
|
||||
routes := make([]map[string]any, 0, len(routesCopy))
|
||||
for _, r := range routesCopy {
|
||||
cp := r
|
||||
eff, _ := s.effectiveProxyDisplay(&cp)
|
||||
routes = append(routes, map[string]any{
|
||||
"scope": r.Scope,
|
||||
"owner_id": r.OwnerID,
|
||||
"mode": r.Mode,
|
||||
"proxy_pool_id": r.ProxyPoolID,
|
||||
"proxy_url": maskSecrets(r.ProxyURL),
|
||||
"effective_proxy": eff,
|
||||
"note": r.Note,
|
||||
"updated_at": r.UpdatedAt,
|
||||
})
|
||||
}
|
||||
return jsonResult(map[string]any{
|
||||
"global_proxy": globalDisplay,
|
||||
"active_pool_id": activeID,
|
||||
"entries": entries,
|
||||
"routes": routes,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolSetTaskProxy() actool.CoreTool {
|
||||
return wrTool("set_task_proxy",
|
||||
"为指定任务的沙箱容器设置出口代理或代理池(保存并立即对透明网关与抓包代理热生效)。\n"+
|
||||
"- mode=pool:使用代理池自动轮换(跟随当前健康活跃节点)\n"+
|
||||
"- mode=proxy:绑定代理池指定节点(传 proxy_pool_id,支持节点 ID 或名称)或自定义代理(传 proxy_url)\n"+
|
||||
"- mode=direct:强制直连(绕过全局代理/代理池)\n"+
|
||||
"- mode=inherit:恢复继承全局出口代理设置",
|
||||
objSchema(map[string]any{
|
||||
"task_id": strParam("目标任务 ID(如 \"5\")"),
|
||||
"mode": map[string]any{"type": "string", "enum": []string{"inherit", "direct", "pool", "proxy"}, "description": "代理模式:pool=代理池自动轮换,proxy=指定节点或自定义 URL,direct=直连,inherit=继承全局"},
|
||||
"proxy_pool_id": strParam("可选(mode=proxy 时):代理池节点 ID 或名称,可用 list_proxy_pool 查看"),
|
||||
"proxy_url": strParam("可选(mode=proxy 且未传 proxy_pool_id 时):自定义代理 URL,如 socks5://host:1080 或 http://user:pass@host:8080"),
|
||||
"note": strParam("可选:路由备注"),
|
||||
}, "task_id", "mode"),
|
||||
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
var a struct {
|
||||
TaskID json.RawMessage `json:"task_id"`
|
||||
Mode string `json:"mode"`
|
||||
ProxyPoolID string `json:"proxy_pool_id"`
|
||||
ProxyURL string `json:"proxy_url"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
if err := json.Unmarshal(in, &a); err != nil {
|
||||
return actool.Errorf("参数无效: " + err.Error()), nil
|
||||
}
|
||||
taskID := parseTaskIDArg(a.TaskID)
|
||||
if taskID == "" {
|
||||
return actool.Errorf("task_id 不能为空"), nil
|
||||
}
|
||||
t, ok := s.m.Task(taskID)
|
||||
if !ok {
|
||||
return actool.Errorf(fmt.Sprintf("任务 #%s 不存在", taskID)), nil
|
||||
}
|
||||
mode := strings.ToLower(strings.TrimSpace(a.Mode))
|
||||
if mode == "" {
|
||||
if strings.TrimSpace(a.ProxyPoolID) != "" || strings.TrimSpace(a.ProxyURL) != "" {
|
||||
mode = "proxy"
|
||||
} else {
|
||||
return actool.Errorf("mode 不能为空"), nil
|
||||
}
|
||||
}
|
||||
route, err := s.setContainerProxyRoute("task", t.ID, ProxyRouteInput{
|
||||
Mode: mode,
|
||||
ProxyPoolID: a.ProxyPoolID,
|
||||
ProxyURL: a.ProxyURL,
|
||||
Note: a.Note,
|
||||
})
|
||||
if err != nil {
|
||||
return actool.Errorf("设置任务代理失败: " + err.Error()), nil
|
||||
}
|
||||
view, globalDisplay := s.containerProxyRouteView("task", t.ID)
|
||||
return jsonResult(map[string]any{
|
||||
"task_id": t.ID,
|
||||
"task_name": t.lifecycleSnapshot().Name,
|
||||
"scope": route.Scope,
|
||||
"owner_id": route.OwnerID,
|
||||
"mode": view.Mode,
|
||||
"proxy_pool_id": view.ProxyPoolID,
|
||||
"proxy_url": view.ProxyURL,
|
||||
"effective_proxy": view.EffectiveProxy,
|
||||
"global_proxy": globalDisplay,
|
||||
"note": view.Note,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// seedProxyToolBindings adds list_proxy_pool and set_task_proxy bindings ONCE
|
||||
// on existing DBs so chat agents can manage task proxies immediately.
|
||||
func (s *Server) seedProxyToolBindings() {
|
||||
const flag = "proxy_tool_bindings_v1"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
for _, agentKey := range []string{"auto", "mainagent", "pentest"} {
|
||||
if err := s.m.pg.AddAgentToToolBinding(agentKey, []string{"list_proxy_pool", "set_task_proxy"}); err != nil {
|
||||
log.Printf("[%s] 代理工具默认绑定失败: %v", agentKey, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = s.m.pg.SetSetting(flag, "true")
|
||||
}
|
||||
+95
-6
@@ -23,6 +23,9 @@ type scheduleRequest struct {
|
||||
StartTime string `json:"start_time"`
|
||||
EndTime string `json:"end_time"`
|
||||
StartImmediately bool `json:"start_immediately"`
|
||||
ProxyMode string `json:"proxy_mode,omitempty"`
|
||||
ProxyPoolID string `json:"proxy_pool_id,omitempty"`
|
||||
ProxyURL string `json:"proxy_url,omitempty"`
|
||||
TaskIDs []int64 `json:"task_ids"`
|
||||
}
|
||||
|
||||
@@ -33,9 +36,68 @@ func (s *Server) scheduleInput(req scheduleRequest, existing *db.TaskSchedule) d
|
||||
} else if existing != nil {
|
||||
enabled = existing.Enabled
|
||||
}
|
||||
proxyMode := strings.ToLower(strings.TrimSpace(req.ProxyMode))
|
||||
proxyPoolID := strings.TrimSpace(req.ProxyPoolID)
|
||||
proxyURL := strings.TrimSpace(req.ProxyURL)
|
||||
if proxyMode == "" {
|
||||
if existing != nil && existing.ProxyMode != "" {
|
||||
proxyMode = existing.ProxyMode
|
||||
if proxyPoolID == "" && proxyURL == "" {
|
||||
proxyPoolID = existing.ProxyPoolID
|
||||
proxyURL = existing.ProxyURL
|
||||
}
|
||||
} else {
|
||||
proxyMode = "inherit"
|
||||
}
|
||||
}
|
||||
return db.TaskScheduleInput{Name: req.Name, Enabled: enabled, TimezoneMode: req.TimezoneMode, ScheduleType: req.ScheduleType,
|
||||
RunDate: req.RunDate, EndDate: req.EndDate, Weekdays: req.Weekdays, StartTime: req.StartTime, EndTime: req.EndTime,
|
||||
StartImmediately: req.StartImmediately, TaskIDs: req.TaskIDs}
|
||||
StartImmediately: req.StartImmediately, ProxyMode: proxyMode, ProxyPoolID: proxyPoolID, ProxyURL: proxyURL, TaskIDs: req.TaskIDs}
|
||||
}
|
||||
|
||||
func (s *Server) validateScheduleProxy(in *db.TaskScheduleInput, existing *db.TaskSchedule) error {
|
||||
var prev *ContainerProxyRoute
|
||||
if existing != nil && existing.ProxyURL != "" {
|
||||
prev = &ContainerProxyRoute{
|
||||
Mode: existing.ProxyMode,
|
||||
ProxyPoolID: existing.ProxyPoolID,
|
||||
ProxyURL: existing.ProxyURL,
|
||||
}
|
||||
}
|
||||
norm, err := s.validateAndNormalizeProxyRoute(ProxyRouteInput{
|
||||
Mode: in.ProxyMode,
|
||||
ProxyPoolID: in.ProxyPoolID,
|
||||
ProxyURL: in.ProxyURL,
|
||||
}, prev)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
in.ProxyMode = norm.Mode
|
||||
in.ProxyPoolID = norm.ProxyPoolID
|
||||
in.ProxyURL = norm.ProxyURL
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) applyScheduleProxyToTasks(item *db.TaskSchedule) {
|
||||
if item == nil || len(item.TaskIDs) == 0 {
|
||||
return
|
||||
}
|
||||
mode := strings.ToLower(strings.TrimSpace(item.ProxyMode))
|
||||
if mode == "" || mode == "inherit" {
|
||||
return
|
||||
}
|
||||
req := ProxyRouteInput{
|
||||
Mode: mode,
|
||||
ProxyPoolID: item.ProxyPoolID,
|
||||
ProxyURL: item.ProxyURL,
|
||||
Note: fmt.Sprintf("schedule #%d", item.ID),
|
||||
}
|
||||
for _, taskID := range item.TaskIDs {
|
||||
if taskID <= 0 {
|
||||
continue
|
||||
}
|
||||
_, _ = s.setContainerProxyRoute("task", strconv.FormatInt(taskID, 10), req)
|
||||
}
|
||||
}
|
||||
|
||||
func parseScheduleID(r *http.Request) (int64, error) {
|
||||
@@ -43,9 +105,23 @@ func parseScheduleID(r *http.Request) (int64, error) {
|
||||
}
|
||||
|
||||
func (s *Server) scheduleDTO(item *db.TaskSchedule) map[string]any {
|
||||
raw, _ := json.Marshal(item)
|
||||
safe := *item
|
||||
if safe.ProxyURL != "" {
|
||||
safe.ProxyURL = maskSecrets(safe.ProxyURL)
|
||||
}
|
||||
raw, _ := json.Marshal(&safe)
|
||||
var dto map[string]any
|
||||
_ = json.Unmarshal(raw, &dto)
|
||||
var routePtr *ContainerProxyRoute
|
||||
if item.ProxyMode != "" && item.ProxyMode != "inherit" {
|
||||
routePtr = &ContainerProxyRoute{
|
||||
Mode: item.ProxyMode,
|
||||
ProxyPoolID: item.ProxyPoolID,
|
||||
ProxyURL: item.ProxyURL,
|
||||
}
|
||||
}
|
||||
eff, _ := s.effectiveProxyDisplay(routePtr)
|
||||
dto["effective_proxy"] = eff
|
||||
window := evaluateScheduleWindow(item, time.Now())
|
||||
if stats, err := s.m.pg.ScheduleRunStats(item.ID); err == nil {
|
||||
dto["run_count"] = stats.RunCount
|
||||
@@ -113,15 +189,21 @@ func (s *Server) createSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
item, err := s.m.pg.CreateTaskSchedule(s.scheduleInput(req, nil))
|
||||
input := s.scheduleInput(req, nil)
|
||||
if err := s.validateScheduleProxy(&input, nil); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
item, err := s.m.pg.CreateTaskSchedule(input)
|
||||
if err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
s.applyScheduleProxyToTasks(item)
|
||||
if req.StartImmediately && item.Enabled {
|
||||
s.runScheduleTasks(item)
|
||||
}
|
||||
writeJSON(w, 201, item)
|
||||
writeJSON(w, 201, s.scheduleDTO(item))
|
||||
}
|
||||
|
||||
func (s *Server) updateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -140,12 +222,18 @@ func (s *Server) updateSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
item, err := s.m.pg.UpdateTaskSchedule(id, s.scheduleInput(req, old))
|
||||
input := s.scheduleInput(req, old)
|
||||
if err := s.validateScheduleProxy(&input, old); err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
item, err := s.m.pg.UpdateTaskSchedule(id, input)
|
||||
if err != nil {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, item)
|
||||
s.applyScheduleProxyToTasks(item)
|
||||
writeJSON(w, 200, s.scheduleDTO(item))
|
||||
}
|
||||
|
||||
func (s *Server) deleteSchedule(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -217,6 +305,7 @@ func (s *Server) runScheduleTasksNow(item *db.TaskSchedule) (int, []string) {
|
||||
}
|
||||
|
||||
func (s *Server) startScheduleTasks(item *db.TaskSchedule, forceManualPause bool) (int, []string) {
|
||||
s.applyScheduleProxyToTasks(item)
|
||||
started := 0
|
||||
errors := []string{}
|
||||
for _, taskID := range item.TaskIDs {
|
||||
|
||||
+54
-1
@@ -1065,6 +1065,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("DELETE /api/proxy/blacklist/rules/{id}", s.deleteEgressBlacklistRule)
|
||||
mux.HandleFunc("DELETE /api/proxy/blacklist/events", s.clearEgressBlockEvents)
|
||||
mux.HandleFunc("GET /api/proxy/routes", s.getProxyRoutes)
|
||||
mux.HandleFunc("GET /api/proxy/routes/{scope}/{owner_id}", s.getProxyRoute)
|
||||
mux.HandleFunc("PUT /api/proxy/routes/{scope}/{owner_id}", s.putProxyRoute)
|
||||
mux.HandleFunc("DELETE /api/proxy/routes/{scope}/{owner_id}", s.deleteProxyRoute)
|
||||
mux.HandleFunc("PUT /api/proxy/gateway/settings", s.updateGatewaySettings)
|
||||
@@ -1344,6 +1345,7 @@ func (s *Server) listTasks(w http.ResponseWriter, r *http.Request) {
|
||||
dto := taskDTO(t, s.resolvedTaskStatus(t))
|
||||
dto.WorkerActualCount, dto.WorkerTargetCount = s.engine.WorkerCounts(t)
|
||||
applyTaskArchiveBlocker(&dto, archiveBlockers)
|
||||
s.applyTaskProxyDTO(&dto)
|
||||
metric := metrics[t.ExpID]
|
||||
dto.Tokens = tokenTotalDTO(metric.Tokens)
|
||||
// prefer the live in-memory heartbeat (fresher) and fall back to the
|
||||
@@ -1823,6 +1825,7 @@ type createTaskReq struct {
|
||||
WorkerCount int `json:"worker_count,omitempty"` // 本任务 Worker 数;0/省略=用全局默认;上限50
|
||||
// InterceptRules 任务级资产拦截/允许规则(创建时录入,存 task_intercept_rules,不进全局表)。
|
||||
InterceptRules []taskInterceptRuleReq `json:"intercept_rules,omitempty"`
|
||||
ProxyRoute *ProxyRouteInput `json:"proxy_route,omitempty"` // 任务容器出口代理配置(inherit/direct/pool/proxy)
|
||||
}
|
||||
|
||||
// taskCreateError is a rejected task creation: an HTTP-style status plus a
|
||||
@@ -1843,7 +1846,9 @@ func (s *Server) createTask(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, cerr.Status, cerr.Msg)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 201, taskDTO(t, s.resolvedTaskStatus(t)))
|
||||
dto := taskDTO(t, s.resolvedTaskStatus(t))
|
||||
s.applyTaskProxyDTO(&dto)
|
||||
writeJSON(w, 201, dto)
|
||||
}
|
||||
|
||||
// createTaskFromRequest validates a creation request, stores the task and
|
||||
@@ -1897,8 +1902,37 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr
|
||||
if err := db.ValidateTaskScheduleInput(input); err != nil {
|
||||
return nil, &taskCreateError{400, err.Error()}
|
||||
}
|
||||
if err := s.validateScheduleProxy(&input, nil); err != nil {
|
||||
return nil, &taskCreateError{400, err.Error()}
|
||||
}
|
||||
schedule = &input
|
||||
}
|
||||
var validatedProxy *ProxyRouteInput
|
||||
if req.ProxyRoute != nil {
|
||||
norm, err := s.validateAndNormalizeProxyRoute(*req.ProxyRoute, nil)
|
||||
if err != nil {
|
||||
return nil, &taskCreateError{400, "任务代理配置无效:" + err.Error()}
|
||||
}
|
||||
if norm.Mode != "inherit" {
|
||||
validatedProxy = &ProxyRouteInput{
|
||||
Mode: norm.Mode,
|
||||
ProxyPoolID: norm.ProxyPoolID,
|
||||
ProxyURL: norm.ProxyURL,
|
||||
Note: norm.Note,
|
||||
}
|
||||
}
|
||||
} else if schedule != nil && schedule.ProxyMode != "" && schedule.ProxyMode != "inherit" {
|
||||
validatedProxy = &ProxyRouteInput{
|
||||
Mode: schedule.ProxyMode,
|
||||
ProxyPoolID: schedule.ProxyPoolID,
|
||||
ProxyURL: schedule.ProxyURL,
|
||||
}
|
||||
}
|
||||
if validatedProxy != nil && schedule != nil && (schedule.ProxyMode == "" || schedule.ProxyMode == "inherit") {
|
||||
schedule.ProxyMode = validatedProxy.Mode
|
||||
schedule.ProxyPoolID = validatedProxy.ProxyPoolID
|
||||
schedule.ProxyURL = validatedProxy.ProxyURL
|
||||
}
|
||||
remark, err := normalizeRemark(req.Remark)
|
||||
if err != nil {
|
||||
return nil, &taskCreateError{400, err.Error()}
|
||||
@@ -1937,6 +1971,11 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr
|
||||
_, _ = s.m.pg.Exec(`UPDATE tasks SET description=$2, goal=$3 WHERE id=$1`, id, newDesc, newGoal)
|
||||
}
|
||||
}
|
||||
if validatedProxy != nil {
|
||||
if _, err := s.setContainerProxyRoute("task", t.ID, *validatedProxy); err != nil {
|
||||
log.Printf("[task] 新建任务 #%s 应用代理路由失败: %v", t.ID, err)
|
||||
}
|
||||
}
|
||||
log.Printf("[task] 新建任务 #%s «%s» 目标: %s", t.ID, req.Description, req.Goal)
|
||||
// 共享的建后流程(seed + 种子意图 + 后台目标分解 + engine.Run),与 spawn_task 复用同一段。
|
||||
// launchTask 内部异步,不阻塞 UI —— 目标分解在后台可见地进行。
|
||||
@@ -2152,9 +2191,23 @@ func (s *Server) getTask(w http.ResponseWriter, r *http.Request) {
|
||||
dto.WorkerActualCount, dto.WorkerTargetCount = s.engine.WorkerCounts(t)
|
||||
archiveBlockers, _ := s.m.PG().TaskArchiveBlockers()
|
||||
applyTaskArchiveBlocker(&dto, archiveBlockers)
|
||||
s.applyTaskProxyDTO(&dto)
|
||||
writeJSON(w, 200, dto)
|
||||
}
|
||||
|
||||
func (s *Server) applyTaskProxyDTO(dto *TaskDTO) {
|
||||
if dto == nil || dto.ID == "" {
|
||||
return
|
||||
}
|
||||
item, _ := s.containerProxyRouteView("task", dto.ID)
|
||||
dto.ProxyRoute = &TaskProxyRouteDTO{
|
||||
Mode: item.Mode,
|
||||
ProxyPoolID: item.ProxyPoolID,
|
||||
ProxyURL: item.ProxyURL,
|
||||
EffectiveProxy: item.EffectiveProxy,
|
||||
}
|
||||
}
|
||||
|
||||
// taskCoverage returns a task's rough asset test coverage (denominator/tested/backlog).
|
||||
func (s *Server) taskCoverage(w http.ResponseWriter, r *http.Request) {
|
||||
t, ok := s.m.Task(r.PathValue("id"))
|
||||
|
||||
Reference in new issue
Block a user