This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: k8s-gateway-v1-2-cross-namespace-policy-attachment-standard

Kubernetes Gateway API v1.2 Cross-Namespace Policy Attachment and TLS Isolation

Enforces strict tenant boundary isolation across Kubernetes Gateway API v1.2 resources by requiring explicit ReferenceGrant objects for all cross-namespace route and secret attachments. Mandates hierarchical TLS termination invariants at the Gateway listener level to block unauthorized edge hostname hijacking and route overrides by untrusted tenant namespaces.

Prohibited Anti-Pattern: Attaching cross-namespace HTTPRoutes or referencing tenant Secrets without an explicit ReferenceGrant and bounded listener allowedRoutes.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kubernetes Gateway API v1.2 Cross-Namespace Policy Attachment and TLS Isolation - Enforces strict tenant boundary isolation across Kubernetes Gateway API v1.2 resources by requiring explicit ReferenceGrant objects for all cross-namespace route and secret attachments. Mandates hierarchical TLS termination invariants at the Gateway listener level to block unauthorized edge hostname hijacking and route overrides by untrusted tenant namespaces.
globs: k8s/**/*.yaml, deploy/**/*.yaml, helm/**/*.yaml, infra/**/*.yaml, manifests/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/k8s-gateway-v1-2-cross-namespace-policy-attachment-standard"
---

# Kubernetes Gateway API v1.2 Cross-Namespace Policy Attachment and TLS Isolation

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Attaching cross-namespace HTTPRoutes or referencing tenant Secrets without an explicit ReferenceGrant and bounded listener allowedRoutes.

## System Constraints
You are a Principal Software Architect and Kubernetes Security Auditor enforcing Gateway API v1.2 specifications. Your objective is to ensure that cross-namespace routing, TLS certificate delegation, and hierarchical policy attachments strictly adhere to Gateway API invariants. Reject any cross-namespace resource access that lacks an accompanying ReferenceGrant, and verify that Gateway listeners restrict Route attachment via explicit allowedRoutes definitions.

## Strict Guidelines
- Engineers MUST ALWAYS declare an explicit ReferenceGrant (`gateway.networking.k8s.io/v1beta1` or `v1`) in the target resource's namespace whenever an HTTPRoute or Gateway references a backend Service or TLS Secret residing in another namespace.
- Engineers MUST NOT configure Gateway listeners with `allowedRoutes.namespaces.from: All` without enforcing strict hostname collision guards and domain ownership validation across tenant namespaces.
- Gateways MUST declare explicit `allowedRoutes.namespaces.from: Selector` matching specific labeled tenant namespaces rather than permissive wildcards.
- TLS termination policies at the Gateway listener level MUST dictate whether downstream routes are permitted to perform Terminate or Passthrough modes; tenant HTTPRoutes MUST NEVER override parent Gateway TLS settings.
- Cross-namespace backend references without an authorized ReferenceGrant MUST fail closed with a Route condition of `ResolvedRefs: False` and reason `RefNotPermitted`.
- Components NEVER reference Secrets across namespace boundaries directly; secret access MUST be mediated through a ReferenceGrant with `from.group: gateway.networking.k8s.io`, `from.kind: Gateway` and `to.kind: Secret` in the secret's namespace.

## Bad vs Good Implementations
### Cross-Namespace Route Attachment and Backend Delegation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Gateway allows route binding from 'All' namespaces without boundary checks, references a TLS secret in another namespace without authorization, and tenant-a attempts to send traffic to core-services without a ReferenceGrant, creating an edge route override and lateral movement vector.
```yaml
# INSECURE: Tenant attempts cross-namespace service routing and gateway binding
# without matching ReferenceGrant or bounded listener selectors.
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: shared-edge-gw
  namespace: gateway-infra
spec:
  gatewayClassName: eg-gateway-class
  listeners:
    - name: https-wildcard
      port: 443
      protocol: HTTPS
      tls:
        mode: Terminate
        certificateRefs:
          # Anti-pattern: direct reference to tenant secret without ReferenceGrant
          - name: tenant-cert
            namespace: tenant-a
      allowedRoutes:
        # Anti-pattern: allows any namespace to attach routes to this listener
        namespaces:
          from: All
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: tenant-route
  namespace: tenant-a
spec:
  parentRefs:
    - name: shared-edge-gw
      namespace: gateway-infra
  rules:
    - backendRefs:
        # Anti-pattern: route in tenant-a targets service in core-services without permission
        - name: core-api-svc
          namespace: core-services
          port: 8080
```

#### Production Standard (Correct)
> **Standard**: The Gateway restricts route attachment using namespace label selectors and binds to a specific sectionName. Explicit ReferenceGrants in 'cert-manager-ns' and 'core-services' validate that the cross-namespace secret retrieval and backend service routing are cryptographically and administratively approved.
```yaml
# SECURE: Explicit listener bounds, TLS ReferenceGrant, and Route ReferenceGrant
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: shared-edge-gw
  namespace: gateway-infra
spec:
  gatewayClassName: eg-gateway-class
  listeners:
    - name: https-tenant-a
      hostname: "a.example.com"
      port: 443
      protocol: HTTPS
      tls:
        mode: Terminate
        certificateRefs:
          - name: edge-tls-secret
            namespace: cert-manager-ns
      allowedRoutes:
        namespaces:
          from: Selector
          selector:
            matchLabels:
              gateway.company.internal/allowed-tenant: tenant-a
---
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-gateway-tls-read
  namespace: cert-manager-ns
spec:
  from:
    - group: gateway.networking.k8s.io
      kind: Gateway
      namespace: gateway-infra
  to:
    - group: ""
      kind: Secret
      name: edge-tls-secret
---
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-tenant-a-core-svc-ref
  namespace: core-services
spec:
  from:
    - group: gateway.networking.k8s.io
      kind: HTTPRoute
      namespace: tenant-a
  to:
    - group: ""
      kind: Service
      name: core-api-svc
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: tenant-route
  namespace: tenant-a
spec:
  parentRefs:
    - name: shared-edge-gw
      namespace: gateway-infra
      sectionName: https-tenant-a
  hostnames:
    - "a.example.com"
  rules:
    - backendRefs:
        - name: core-api-svc
          namespace: core-services
          port: 8080
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kubernetes Gateway API v1.2 Cross-Namespace Policy Attachment and TLS Isolation

Kubernetes Gateway API v1.2 Cross-Namespace Policy Attachment and TLS Isolation defines an industrial-grade behavioral standard for devops engineering. Enforces strict tenant boundary isolation across Kubernetes Gateway API v1.2 resources by requiring explicit ReferenceGrant objects for all cross-namespace route and secret attachments. Mandates hierarchical TLS termination invariants at the Gateway listener level to block unauthorized edge hostname hijacking and route overrides by untrusted tenant namespaces. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Attaching cross-namespace HTTPRoutes or referencing tenant Secrets without an explicit ReferenceGrant and bounded listener allowedRoutes. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAttaching cross-namespace HTTPRoutes or referencing tenant Secrets without an explicit ReferenceGrant and bounded listener allowedRoutes.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS declare an explicit ReferenceGrant (`gateway.networking.k8s.io/v1beta1` or `v1`) in the target resource's namespace whenever an HTTPRoute or Gateway references a backend Service or TLS Secret residing in another namespace.

Engineers MUST ALWAYS declare an explicit ReferenceGrant (`gateway.networking.k8s.io/v1beta1` or `v1`) in the target resource's namespace whenever an HTTPRoute or Gateway references a backend Service or TLS Secret residing in another namespace.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT configure Gateway listeners with `allowedRoutes.namespaces.from

Engineers MUST NOT configure Gateway listeners with `allowedRoutes.namespaces.from: All` without enforcing strict hostname collision guards and domain ownership validation across tenant namespaces.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Gateways MUST declare explicit `allowedRoutes.namespaces.from

Gateways MUST declare explicit `allowedRoutes.namespaces.from: Selector` matching specific labeled tenant namespaces rather than permissive wildcards.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

TLS termination policies at the Gateway listener level MUST dictate whether downstream routes are permitted to perform Terminate or Passthrough modes

TLS termination policies at the Gateway listener level MUST dictate whether downstream routes are permitted to perform Terminate or Passthrough modes; tenant HTTPRoutes MUST NEVER override parent Gateway TLS settings.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Cross-namespace backend references without an authorized ReferenceGrant MUST fail closed with a Route condition of `ResolvedRefs

Cross-namespace backend references without an authorized ReferenceGrant MUST fail closed with a Route condition of `ResolvedRefs: False` and reason `RefNotPermitted`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Components NEVER reference Secrets across namespace boundaries directly

Components NEVER reference Secrets across namespace boundaries directly; secret access MUST be mediated through a ReferenceGrant with `from.group: gateway.networking.k8s.io`, `from.kind: Gateway` and `to.kind: Secret` in the secret's namespace.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Kubernetes Gateway API v1.2 Cross-Namespace Policy Attachment and TLS Isolation critical for AI coding assistants?

Enforces strict tenant boundary isolation across Kubernetes Gateway API v1.2 resources by requiring explicit ReferenceGrant objects for all cross-namespace route and secret attachments. Mandates hierarchical TLS termination invariants at the Gateway listener level to block unauthorized edge hostname hijacking and route overrides by untrusted tenant namespaces. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Attaching cross-namespace HTTPRoutes or referencing tenant Secrets without an explicit ReferenceGrant and bounded listener allowedRoutes.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Kubernetes