package server import ( "context" "encoding/json" "fmt" "net/http" "net/url" "sort" "strings" "sync" "time" "github.com/Autumn-27/artex/internal/sandbox" "github.com/Autumn-27/artex/traffic" ) const ( settingContainerProxyRoutes = "proxy_container_routes_json" settingGatewayPolicy = "proxy_gateway_settings_json" ) // ContainerProxyRoute persists a per-sandbox-owner upstream proxy override (#218 Phase 4). 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, 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"` DNSUpstream string `json:"dns_upstream"` StoreErrorTraffic bool `json:"store_error_traffic"` } type proxyRouteRuntime struct { mu sync.RWMutex routes map[string]ContainerProxyRoute // key: "scope:owner_id" gwSettings GatewaySettings gwID string gwLastSeen time.Time embeddedGW *traffic.TransparentGateway } func (s *Server) ensureRouteRuntime() *proxyRouteRuntime { s.cfgMu.Lock() defer s.cfgMu.Unlock() if s.proxyRoutes == nil { s.proxyRoutes = &proxyRouteRuntime{ routes: map[string]ContainerProxyRoute{}, gwSettings: GatewaySettings{ UDPPolicy: traffic.UDPPolicyBlockOnProxy, }, } } return s.proxyRoutes } func (s *Server) initProxyRoutesAndGateway() { rt := s.ensureRouteRuntime() // Load persisted per-container proxy routes. if s.m.pg != nil { if raw, ok, err := s.m.pg.GetSetting(settingContainerProxyRoutes); err == nil && ok && strings.TrimSpace(raw) != "" { var list []ContainerProxyRoute if json.Unmarshal([]byte(raw), &list) == nil { rt.mu.Lock() for _, r := range list { if r.Scope != "" && r.OwnerID != "" { rt.routes[r.Scope+":"+r.OwnerID] = r } } rt.mu.Unlock() } } if raw, ok, err := s.m.pg.GetSetting(settingGatewayPolicy); err == nil && ok && strings.TrimSpace(raw) != "" { var gs GatewaySettings if json.Unmarshal([]byte(raw), &gs) == nil { gs.UDPPolicy = traffic.NormalizeUDPPolicy(gs.UDPPolicy) gs.DNSUpstream = strings.TrimSpace(gs.DNSUpstream) rt.mu.Lock() rt.gwSettings = gs rt.mu.Unlock() } } } if s.m.traffic != nil { rt.mu.RLock() gs := rt.gwSettings rt.mu.RUnlock() s.m.traffic.SetGatewaySettings(gs.UDPPolicy, gs.DNSUpstream) s.m.traffic.SetStoreErrorTraffic(gs.StoreErrorTraffic) s.m.traffic.SetUpstreamResolver(s.resolveContainerUpstream) } } func (s *Server) storeErrorTrafficEnabled() bool { rt := s.ensureRouteRuntime() rt.mu.RLock() defer rt.mu.RUnlock() return rt.gwSettings.StoreErrorTraffic } func (s *Server) resolvePoolEntryByIDOrName(ref string) (string, string) { ref = strings.TrimSpace(ref) if ref == "" { return "", "" } entries := s.m.proxyPoolEntries() for _, e := range entries { if e.ID == ref { return e.ID, strings.TrimSpace(e.RawURL) } } 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 { 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 "" } } func (s *Server) resolveContainerUpstream(src traffic.SourceIdentity) (*url.URL, bool) { if src.Scope == "" || src.OwnerID == "" { return nil, false } rt := s.ensureRouteRuntime() rt.mu.RLock() r, ok := rt.routes[src.Scope+":"+src.OwnerID] rt.mu.RUnlock() if !ok { return nil, false } switch strings.ToLower(strings.TrimSpace(r.Mode)) { case "direct": return nil, true case "pool", "proxy": raw := s.resolveRouteEffectiveRawURL(r) if raw == "" { return nil, false } u, err := traffic.ValidateProxyURL(raw) if err != nil { return nil, false } return u, true default: return nil, false } } type proxyRouteValidationError struct { code string msg string params map[string]any } func (e *proxyRouteValidationError) Error() string { return e.msg } func writeProxyRouteErr(w http.ResponseWriter, status int, err error) { if verr, ok := err.(*proxyRouteValidationError); ok && verr.code != "" { writeProductError(w, status, verr.code, verr.msg, verr.params) return } writeErr(w, status, err.Error()) } 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{ code: "proxy_route_invalid_mode", msg: "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{ code: "proxy_pool_no_available_nodes", msg: "代理池暂无可用节点,请先在代理设置中添加并启用节点", } } route.ProxyPoolID = "" route.ProxyURL = "" case "proxy": if route.ProxyPoolID != "" { id, raw := s.resolvePoolEntryByIDOrName(route.ProxyPoolID) if raw == "" { return ContainerProxyRoute{}, &proxyRouteValidationError{ code: "proxy_pool_node_not_found", msg: fmt.Sprintf("proxy_pool_id %q not found", route.ProxyPoolID), params: map[string]any{"id": 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{ code: "proxy_route_invalid_url", msg: err.Error(), params: map[string]any{"detail": 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{ code: "proxy_route_invalid_target", msg: "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 } list := make([]ContainerProxyRoute, 0, len(rt.routes)) for _, r := range rt.routes { list = append(list, r) } sort.Slice(list, func(i, j int) bool { if list[i].Scope != list[j].Scope { return list[i].Scope < list[j].Scope } return list[i].OwnerID < list[j].OwnerID }) b, err := json.Marshal(list) if err != nil { return err } return s.m.pg.SetSetting(settingContainerProxyRoutes, string(b)) } func (s *Server) maskedRouteView(r ContainerProxyRoute) ContainerProxyRoute { out := r if out.ProxyURL != "" { out.ProxyURL = maskSecrets(out.ProxyURL) } return out } type containerRouteStatusItem struct { Scope string `json:"scope"` OwnerID string `json:"owner_id"` ContainerName string `json:"container_name,omitempty"` ContainerID string `json:"container_id,omitempty"` State string `json:"state,omitempty"` IP string `json:"ip,omitempty"` 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"` Note string `json:"note,omitempty"` UpdatedAt string `json:"updated_at,omitempty"` } // GET /api/proxy/routes func (s *Server) getProxyRoutes(w http.ResponseWriter, r *http.Request) { rt := s.ensureRouteRuntime() rt.mu.RLock() routesMap := make(map[string]ContainerProxyRoute, len(rt.routes)) for k, v := range rt.routes { routesMap[k] = v } gs := rt.gwSettings gwID := rt.gwID gwLast := rt.gwLastSeen embedded := rt.embeddedGW != nil rt.mu.RUnlock() globalRaw := strings.TrimSpace(s.m.GlobalProxy()) globalDisplay := "direct" if globalRaw != "" { globalDisplay = maskSecrets(globalRaw) } effectiveFor := func(route *ContainerProxyRoute) string { if route == nil || route.Mode == "" || route.Mode == "inherit" { return globalDisplay } if route.Mode == "direct" { return "direct" } if raw := s.resolveRouteEffectiveRawURL(*route); raw != "" { return maskSecrets(raw) } return globalDisplay } seen := map[string]bool{} items := make([]containerRouteStatusItem, 0, len(routesMap)+4) if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() { ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) st := mgr.StatusWithStats(ctx, false) cancel() ipSnap := mgr.ContainerIPSnapshot() ipByName := map[string]string{} for ip, id := range ipSnap { ipByName[id.ContainerName] = ip } for _, c := range st.Containers { key := string(c.Scope) + ":" + c.OwnerID seen[key] = true var rPtr *ContainerProxyRoute mode := "inherit" var poolID, proxyURL, note, updatedAt string if existing, ok := routesMap[key]; ok { cp := existing rPtr = &cp mode = existing.Mode poolID = existing.ProxyPoolID proxyURL = maskSecrets(existing.ProxyURL) note = existing.Note updatedAt = existing.UpdatedAt } items = append(items, containerRouteStatusItem{ Scope: string(c.Scope), OwnerID: c.OwnerID, ContainerName: c.Name, ContainerID: c.ShortID, State: c.State, IP: ipByName[c.Name], Mode: mode, ProxyPoolID: poolID, ProxyURL: proxyURL, EffectiveProxy: effectiveFor(rPtr), Note: note, UpdatedAt: updatedAt, }) } } // Include persisted route rules for tasks/sessions without a currently present container. for key, route := range routesMap { if seen[key] { continue } cp := route items = append(items, containerRouteStatusItem{ Scope: route.Scope, OwnerID: route.OwnerID, State: "inactive", Mode: route.Mode, ProxyPoolID: route.ProxyPoolID, ProxyURL: maskSecrets(route.ProxyURL), EffectiveProxy: effectiveFor(&cp), Note: route.Note, UpdatedAt: route.UpdatedAt, }) } sort.Slice(items, func(i, j int) bool { if items[i].Scope != items[j].Scope { return items[i].Scope < items[j].Scope } return items[i].OwnerID < items[j].OwnerID }) routesList := make([]ContainerProxyRoute, 0, len(routesMap)) for _, route := range routesMap { routesList = append(routesList, s.maskedRouteView(route)) } sort.Slice(routesList, func(i, j int) bool { if routesList[i].Scope != routesList[j].Scope { return routesList[i].Scope < routesList[j].Scope } return routesList[i].OwnerID < routesList[j].OwnerID }) connected := embedded || (!gwLast.IsZero() && time.Since(gwLast) < 15*time.Second) var lastSeenStr string if !gwLast.IsZero() { lastSeenStr = gwLast.UTC().Format(time.RFC3339) } writeJSON(w, 200, map[string]any{ "global_proxy": globalDisplay, "routes": routesList, "containers": items, "gateway": map[string]any{ "connected": connected, "embedded": embedded, "gateway_id": gwID, "last_seen": lastSeenStr, "udp_policy": traffic.NormalizeUDPPolicy(gs.UDPPolicy), "dns_upstream": gs.DNSUpstream, "store_error_traffic": gs.StoreErrorTraffic, }, }) } // 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 == "" { writeProductError(w, http.StatusBadRequest, "proxy_route_invalid_target", "invalid scope or owner_id (scope must be task or session)", nil) return } 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 } route, err := s.setContainerProxyRoute(scope, ownerID, req) if err != nil { if _, ok := err.(*proxyRouteValidationError); ok { writeProxyRouteErr(w, http.StatusBadRequest, err) return } writeErr(w, http.StatusInternalServerError, err.Error()) return } writeJSON(w, 200, route) } // DELETE /api/proxy/routes/{scope}/{owner_id} func (s *Server) deleteProxyRoute(w http.ResponseWriter, r *http.Request) { scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope"))) ownerID := strings.TrimSpace(r.PathValue("owner_id")) if scope == "" || ownerID == "" { writeErr(w, http.StatusBadRequest, "missing scope or owner_id") return } rt := s.ensureRouteRuntime() rt.mu.Lock() delete(rt.routes, scope+":"+ownerID) err := s.saveContainerProxyRoutesLocked(rt) rt.mu.Unlock() if err != nil { writeErr(w, http.StatusInternalServerError, err.Error()) return } writeJSON(w, 200, map[string]any{"deleted": scope + ":" + ownerID}) } // PUT /api/proxy/gateway/settings func (s *Server) updateGatewaySettings(w http.ResponseWriter, r *http.Request) { var req struct { UDPPolicy *string `json:"udp_policy"` DNSUpstream *string `json:"dns_upstream"` StoreErrorTraffic *bool `json:"store_error_traffic"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { writeErr(w, http.StatusBadRequest, "invalid JSON body") return } rt := s.ensureRouteRuntime() rt.mu.Lock() gs := rt.gwSettings if req.UDPPolicy != nil { gs.UDPPolicy = traffic.NormalizeUDPPolicy(*req.UDPPolicy) } else { gs.UDPPolicy = traffic.NormalizeUDPPolicy(gs.UDPPolicy) } if req.DNSUpstream != nil { gs.DNSUpstream = strings.TrimSpace(*req.DNSUpstream) } if req.StoreErrorTraffic != nil { gs.StoreErrorTraffic = *req.StoreErrorTraffic } rt.gwSettings = gs rt.mu.Unlock() if s.m.pg != nil { if b, err := json.Marshal(gs); err == nil { _ = s.m.pg.SetSetting(settingGatewayPolicy, string(b)) } } if s.m.traffic != nil { s.m.traffic.SetGatewaySettings(gs.UDPPolicy, gs.DNSUpstream) s.m.traffic.SetStoreErrorTraffic(gs.StoreErrorTraffic) } writeJSON(w, 200, gs) }