package traffic import ( "net" "net/url" "strings" "sync" ) // GatewaySSRFPolicy is the JSON-serializable form of SSRFGuardConfig synced to artex-gateway. type GatewaySSRFPolicy struct { Enabled bool `json:"enabled"` BlockPrivate bool `json:"block_private"` BlockedHosts []string `json:"blocked_hosts,omitempty"` BlockedCIDRs []string `json:"blocked_cidrs,omitempty"` InfraIPs []string `json:"infra_ips,omitempty"` } // GatewayContainerRoute describes one per-owner upstream proxy override. type GatewayContainerRoute struct { Scope string `json:"scope"` OwnerID string `json:"owner_id"` Mode string `json:"mode"` // inherit, direct, proxy ProxyPoolID string `json:"proxy_pool_id,omitempty"` ProxyURL string `json:"proxy_url,omitempty"` EffectiveURL string `json:"effective_url,omitempty"` // resolved raw URL (only in internal gateway sync) Note string `json:"note,omitempty"` UpdatedAt string `json:"updated_at,omitempty"` } // GatewayPolicySnapshot is returned by GET /api/internal/gateway/policy so the // standalone artex-gateway enforces the exact same real-time SSRF guard, egress // blacklist, task rules, container IP attribution, and per-container proxy routing // as the main ARTEX control plane. type GatewayPolicySnapshot struct { SSRF *GatewaySSRFPolicy `json:"ssrf,omitempty"` BlacklistRules []EgressBlacklistRule `json:"blacklist_rules,omitempty"` TaskRules map[string][]EgressBlacklistRule `json:"task_rules,omitempty"` ContainerIPs map[string]SourceIdentity `json:"container_ips,omitempty"` GlobalUpstreamURL string `json:"global_upstream_url,omitempty"` ContainerRoutes map[string]GatewayContainerRoute `json:"container_routes,omitempty"` // key: "scope:owner_id" PassthroughHosts []string `json:"passthrough_hosts,omitempty"` UDPPolicy string `json:"udp_policy"` DNSUpstream string `json:"dns_upstream,omitempty"` StoreErrorTraffic bool `json:"store_error_traffic"` } // GatewayEventBatch is posted by artex-gateway to POST /api/internal/gateway/events. type GatewayEventBatch struct { GatewayID string `json:"gateway_id,omitempty"` NetFlows []NetFlowRecord `json:"net_flows,omitempty"` DNSQueries []DNSQueryRecord `json:"dns_queries,omitempty"` BlockEvents []EgressBlockEvent `json:"block_events,omitempty"` } // RemotePolicyState holds an in-memory compiled snapshot of GatewayPolicySnapshot // and implements the read side of TransparentBackend for cmd/artex-gateway. type RemotePolicyState struct { mu sync.RWMutex ssrf *ssrfGuard blacklist *egressBlacklist taskRules map[string]*egressBlacklist containerIPs map[string]SourceIdentity globalUpstream *url.URL containerRoutes map[string]*url.URL // key -> nil (direct) or *url.URL (proxy) passthroughHosts map[string]struct{} udpPolicy string dnsUpstream string storeErrorTraffic bool dnsCache *dnsReverseCache gatewayToken string onNetFlow func(NetFlowRecord) onDNSQuery func(DNSQueryRecord) onBlockEvent func(EgressBlockEvent) } // NewRemotePolicyState creates a RemotePolicyState wired to event callbacks. func NewRemotePolicyState(token string, onFlow func(NetFlowRecord), onDNS func(DNSQueryRecord), onBlock func(EgressBlockEvent)) *RemotePolicyState { return &RemotePolicyState{ taskRules: map[string]*egressBlacklist{}, containerIPs: map[string]SourceIdentity{}, containerRoutes: map[string]*url.URL{}, passthroughHosts: map[string]struct{}{}, udpPolicy: UDPPolicyBlockOnProxy, dnsCache: newDNSReverseCache(), gatewayToken: strings.TrimSpace(token), onNetFlow: onFlow, onDNSQuery: onDNS, onBlockEvent: onBlock, } } // Apply atomically replaces the compiled policy from snap. func (s *RemotePolicyState) Apply(snap GatewayPolicySnapshot) { var ssrf *ssrfGuard if snap.SSRF != nil && snap.SSRF.Enabled { var cidrs []*net.IPNet for _, c := range snap.SSRF.BlockedCIDRs { if _, n, err := net.ParseCIDR(strings.TrimSpace(c)); err == nil { cidrs = append(cidrs, n) } } var infraIPs []net.IP for _, raw := range snap.SSRF.InfraIPs { if ip := net.ParseIP(strings.TrimSpace(raw)); ip != nil { infraIPs = append(infraIPs, ip) } } ssrf = newSSRFGuard(SSRFGuardConfig{ Enabled: true, BlockPrivate: snap.SSRF.BlockPrivate, BlockedHosts: snap.SSRF.BlockedHosts, BlockedCIDRs: cidrs, InfraIPs: infraIPs, HostNetworkMode: true, }) } bl := newEgressBlacklist(snap.BlacklistRules) taskBL := make(map[string]*egressBlacklist, len(snap.TaskRules)) for tid, rules := range snap.TaskRules { if len(rules) > 0 { taskBL[tid] = newEgressBlacklist(rules) } } ipMap := make(map[string]SourceIdentity, len(snap.ContainerIPs)) for ip, id := range snap.ContainerIPs { norm := normalizeIPString(ip) if norm != "" { id.SrcIP = norm ipMap[norm] = id } } var globalUp *url.URL if strings.TrimSpace(snap.GlobalUpstreamURL) != "" { if u, err := ValidateProxyURL(snap.GlobalUpstreamURL); err == nil { globalUp = u } } routes := make(map[string]*url.URL, len(snap.ContainerRoutes)) for key, r := range snap.ContainerRoutes { switch strings.ToLower(strings.TrimSpace(r.Mode)) { case "direct": routes[key] = nil case "proxy": raw := strings.TrimSpace(r.EffectiveURL) if raw == "" { raw = strings.TrimSpace(r.ProxyURL) } if u, err := ValidateProxyURL(raw); err == nil { routes[key] = u } } } pass := make(map[string]struct{}, len(snap.PassthroughHosts)) for _, h := range snap.PassthroughHosts { if h = hostOnly(h); h != "" { pass[h] = struct{}{} } } s.mu.Lock() s.ssrf = ssrf s.blacklist = bl s.taskRules = taskBL s.containerIPs = ipMap s.globalUpstream = globalUp s.containerRoutes = routes s.passthroughHosts = pass s.udpPolicy = NormalizeUDPPolicy(snap.UDPPolicy) s.dnsUpstream = strings.TrimSpace(snap.DNSUpstream) s.storeErrorTraffic = snap.StoreErrorTraffic s.mu.Unlock() } func (s *RemotePolicyState) ResolveSource(srcIP string) SourceIdentity { norm := normalizeIPString(srcIP) s.mu.RLock() id, ok := s.containerIPs[norm] s.mu.RUnlock() if ok { id.SrcIP = norm return id } return SourceIdentity{SrcIP: norm} } func (s *RemotePolicyState) CheckOutbound(rawHost, scheme string, src SourceIdentity) *BlockDecision { s.mu.RLock() ssrf := s.ssrf bl := s.blacklist var taskBL *egressBlacklist if src.Scope == "task" && src.OwnerID != "" { taskBL = s.taskRules[src.OwnerID] } s.mu.RUnlock() if ssrf != nil { if reason := ssrf.Check(rawHost); reason != "" { return &BlockDecision{Reason: reason, RuleKind: "ssrf_guard", Source: "ssrf_guard"} } } if bl != nil { if m := bl.Check(rawHost, scheme); m != nil { return &BlockDecision{ Reason: m.Reason, RuleKind: m.RuleKind, RuleID: m.RuleID, Pattern: m.Pattern, Source: m.Source, } } } if taskBL != nil { if m := taskBL.Check(rawHost, scheme); m != nil { return &BlockDecision{ Reason: m.Reason, RuleKind: "task_intercept", RuleID: m.RuleID, Pattern: m.Pattern, Source: "asset_intercept", } } } return nil } func (s *RemotePolicyState) ResolveUpstream(src SourceIdentity) *url.URL { s.mu.RLock() defer s.mu.RUnlock() if src.Scope != "" && src.OwnerID != "" { if u, ok := s.containerRoutes[src.Scope+":"+src.OwnerID]; ok { return u // nil means explicit direct } } return s.globalUpstream } func (s *RemotePolicyState) IsPassthrough(host string) bool { s.mu.RLock() _, ok := s.passthroughHosts[hostOnly(host)] s.mu.RUnlock() return ok } func (s *RemotePolicyState) LookupDNSReverse(ip string) string { return s.dnsCache.Lookup(ip) } func (s *RemotePolicyState) RememberDNS(ip, domain string) { s.dnsCache.Set(ip, domain) } func (s *RemotePolicyState) RecordNetFlow(rec NetFlowRecord) { if strings.EqualFold(strings.TrimSpace(rec.Action), "error") && !s.StoreErrorTraffic() { return } if s.onNetFlow != nil { s.onNetFlow(rec) } } func (s *RemotePolicyState) RecordDNSQuery(rec DNSQueryRecord) { if strings.EqualFold(strings.TrimSpace(rec.Action), "error") && !s.StoreErrorTraffic() { return } if s.onDNSQuery != nil { s.onDNSQuery(rec) } } func (s *RemotePolicyState) RecordBlockEvent(ev EgressBlockEvent) { if s.onBlockEvent != nil { s.onBlockEvent(ev) } } func (s *RemotePolicyState) UDPPolicy() string { s.mu.RLock() defer s.mu.RUnlock() return s.udpPolicy } func (s *RemotePolicyState) DNSUpstream() string { s.mu.RLock() defer s.mu.RUnlock() return s.dnsUpstream } func (s *RemotePolicyState) StoreErrorTraffic() bool { s.mu.RLock() defer s.mu.RUnlock() return s.storeErrorTraffic } func (s *RemotePolicyState) GatewayToken() string { return s.gatewayToken }