# Network policies for agent isolation
# Agents can only communicate with specific services, not with each other
# or with the Kubernetes API
---
# Default deny all ingress and egress in agents namespace
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
  namespace: dexorder-agents
spec:
  podSelector: {}
  policyTypes:
    - Ingress
    - Egress
---
# Allow agents to receive connections from gateway (MCP)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-gateway-ingress
  namespace: dexorder-agents
spec:
  podSelector:
    matchLabels:
      dexorder.io/component: agent
  policyTypes:
    - Ingress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              dexorder.io/type: system
          podSelector:
            matchLabels:
              app: gateway
      ports:
        - protocol: TCP
          port: 3000  # MCP server port
        - protocol: TCP
          port: 5555  # ZeroMQ control channel
---
# Allow agents to connect to required services
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-agent-egress
  namespace: dexorder-agents
spec:
  podSelector:
    matchLabels:
      dexorder.io/component: agent
  policyTypes:
    - Egress
  egress:
    # DNS resolution (required)
    - to:
        - namespaceSelector: {}
          podSelector:
            matchLabels:
              k8s-app: kube-dns
      ports:
        - protocol: UDP
          port: 53
        - protocol: TCP
          port: 53
    # Gateway in system namespace (for callbacks)
    - to:
        - namespaceSelector:
            matchLabels:
              dexorder.io/type: system
          podSelector:
            matchLabels:
              app: gateway
      ports:
        - protocol: TCP
          port: 8080
    # Kafka/Redpanda for data subscriptions
    - to:
        - namespaceSelector:
            matchLabels:
              dexorder.io/type: system
          podSelector:
            matchLabels:
              app: redpanda
      ports:
        - protocol: TCP
          port: 9092
    # External HTTPS (for exchange APIs, LLM APIs)
    - to:
        - ipBlock:
            cidr: 0.0.0.0/0
            except:
              # Block access to k8s API server (common ranges)
              - 10.0.0.0/8
              - 172.16.0.0/12
              - 192.168.0.0/16
      ports:
        - protocol: TCP
          port: 443
---
# System namespace: allow ingress from agents
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-agent-callbacks
  namespace: dexorder-system
spec:
  podSelector:
    matchLabels:
      app: gateway
  policyTypes:
    - Ingress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              dexorder.io/type: agents
      ports:
        - protocol: TCP
          port: 8080
