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, 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"` } // GatewaySettings persists transparent gateway runtime policy knobs. type GatewaySettings struct { UDPPolicy string `json:"udp_policy"` DNSUpstream string `json:"dns_upstream"` } 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.SetUpstreamResolver(s.resolveContainerUpstream) } } func (s *Server) resolvePoolEntryRawURL(poolID string) string { poolID = strings.TrimSpace(poolID) if poolID == "" { return "" } for _, e := range s.m.proxyPoolEntries() { if e.ID == poolID { return strings.TrimSpace(e.RawURL) } } return "" } func (s *Server) resolveRouteEffectiveRawURL(r ContainerProxyRoute) string { if strings.ToLower(strings.TrimSpace(r.Mode)) != "proxy" { 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) { 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 "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 } } 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, 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, }, }) } // 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")) 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"` } 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()) 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)) } // 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"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { writeErr(w, http.StatusBadRequest, "invalid JSON body") return } gs := GatewaySettings{ UDPPolicy: traffic.NormalizeUDPPolicy(req.UDPPolicy), DNSUpstream: strings.TrimSpace(req.DNSUpstream), } rt := s.ensureRouteRuntime() rt.mu.Lock() 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) } writeJSON(w, 200, gs) }