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-reference-grant-standard

Kubernetes Gateway API v1.2 Bidirectional Cross-Namespace ReferenceGrant Enforcement

Mandates strict bidirectional authorization boundaries for cross-namespace Gateway API v1.2 topologies using explicit ReferenceGrant resources and scoped Gateway listener allowedRoutes. Prevents cross-tenant traffic hijacking, unverified backend routing, and route collision across isolated microservice namespaces.

Prohibited Anti-Pattern: Permissive Wildcard Cross-Namespace Route Attachment Without Explicit ReferenceGrant Scoping

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kubernetes Gateway API v1.2 Bidirectional Cross-Namespace ReferenceGrant Enforcement - Mandates strict bidirectional authorization boundaries for cross-namespace Gateway API v1.2 topologies using explicit ReferenceGrant resources and scoped Gateway listener allowedRoutes. Prevents cross-tenant traffic hijacking, unverified backend routing, and route collision across isolated microservice namespaces.
globs: deploy/**/*.yaml, deploy/**/*.yml, k8s/**/*.yaml, k8s/**/*.yml, charts/**/*.yaml, helm/**/*.yaml, infrastructure/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/k8s-gateway-v1-2-cross-namespace-reference-grant-standard"
---

# Kubernetes Gateway API v1.2 Bidirectional Cross-Namespace ReferenceGrant Enforcement

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Permissive Wildcard Cross-Namespace Route Attachment Without Explicit ReferenceGrant Scoping

## System Constraints
You are a Principal Platform Architect enforcing Kubernetes Gateway API v1.2 networking guardrails. Mandate that any cross-namespace reference—including Gateway listener route attachment across namespaces and HTTPRoute cross-namespace backendRefs—is mutually authenticated via scoped listener allowedRoutes and explicit ReferenceGrant resources. Reject unvalidated wildcard namespace attachments and unbounded service references.

## Strict Guidelines
- Engineers MUST ALWAYS enforce bidirectional attachment when referencing resources across namespaces: the Gateway listener MUST specify `allowedRoutes.namespaces.from: Selector` (never unbounded `All`), and cross-namespace backend references MUST have a matching `ReferenceGrant` in the target namespace.
- Engineers MUST NOT configure `allowedRoutes.namespaces.from: All` on shared production Gateway listeners unless paired with explicit, non-wildcard `allowedRoutes.namespaces.selector` label criteria matching verified tenant namespaces.
- Engineers MUST NOT define `ReferenceGrant` resources with wildcard `from[].namespace: '*'` or unconstrained resource groups; every grant MUST declare discrete source namespaces and exact target Core/Gateway API kinds.
- HTTPRoutes MUST explicitly declare `parentRefs[].namespace` and `parentRefs[].sectionName` when attaching to a Gateway outside their local namespace to prevent cross-listener collisions.
- Platform manifests MUST ensure `ReferenceGrant` uses `gateway.networking.k8s.io/v1beta1` or `gateway.networking.k8s.io/v1alpha2` explicitly matching the cluster Gateway API v1.2 controller capabilities.
- Admission validation (e.g., Kyverno or Gatekeeper) MUST fail deployments containing cross-namespace `backendRefs` that lack a co-located or pre-existing `ReferenceGrant` in the target service's namespace.

## Bad vs Good Implementations
### Cross-Namespace Route Hijacking via Permissive Listener and Unguarded BackendRef

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Gateway listener sets `namespaces.from: All`, enabling malicious or compromised tenants to hijack arbitrary hostnames. Furthermore, the HTTPRoute points across namespace boundaries to `payments/payment-svc` without authorization; in strict Gateway API v1.2 implementations, this causes invalid route states or security breaches if ingress controllers fail to enforce backend boundaries.
```yaml
# INSECURE: Gateway allows any namespace to bind routes without tenant restriction,
# and HTTPRoute routes cross-namespace to payment-svc without a ReferenceGrant.
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: shared-gateway
  namespace: infra-ingress
spec:
  gatewayClassName: internal-egress
  listeners:
    - name: https-wildcard
      protocol: HTTPS
      port: 443
      allowedRoutes:
        namespaces:
          from: All # CRITICAL: Any tenant can intercept hostnames
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: rogue-route
  namespace: untrusted-tenant
spec:
  parentRefs:
    - name: shared-gateway
      namespace: infra-ingress
  hostnames:
    - "api.company.internal"
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /checkout
      backendRefs:
        # CRITICAL: Cross-namespace backend reference without a ReferenceGrant in 'payments'
        - name: payment-svc
          namespace: payments
          port: 8080
```

#### Production Standard (Correct)
> **Standard**: The Gateway restricts route attachment using a namespace selector label. The HTTPRoute specifies the exact `sectionName` of the listener. Finally, the target `payments` namespace controls cross-boundary access by issuing a scoped `ReferenceGrant` explicitly naming the source namespace, resource kind, and destination service name.
```yaml
# SECURE: Mutual opt-in with selector-scoped Gateway attachment and explicit ReferenceGrant.
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: shared-gateway
  namespace: infra-ingress
spec:
  gatewayClassName: internal-egress
  listeners:
    - name: tenant-https
      protocol: HTTPS
      port: 443
      allowedRoutes:
        namespaces:
          from: Selector
          selector:
            matchLabels:
              tenant-access.gateway.infra/allowed: "true"
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: checkout-route
  namespace: tenant-checkout
spec:
  parentRefs:
    - name: shared-gateway
      namespace: infra-ingress
      sectionName: tenant-https
  hostnames:
    - "checkout.company.internal"
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /process
      backendRefs:
        - name: payment-svc
          namespace: payments
          port: 8080
---
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-checkout-to-payment
  namespace: payments # Located in the destination namespace to authorize access
spec:
  from:
    - group: gateway.networking.k8s.io
      kind: HTTPRoute
      namespace: tenant-checkout
  to:
    - group: ""
      kind: Service
      name: payment-svc
```

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 Bidirectional Cross-Namespace ReferenceGrant Enforcement

Kubernetes Gateway API v1.2 Bidirectional Cross-Namespace ReferenceGrant Enforcement defines an industrial-grade behavioral standard for devops engineering. Mandates strict bidirectional authorization boundaries for cross-namespace Gateway API v1.2 topologies using explicit ReferenceGrant resources and scoped Gateway listener allowedRoutes. Prevents cross-tenant traffic hijacking, unverified backend routing, and route collision across isolated microservice 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: Permissive Wildcard Cross-Namespace Route Attachment Without Explicit ReferenceGrant Scoping 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 DriftPermissive Wildcard Cross-Namespace Route Attachment Without Explicit ReferenceGrant ScopingCritical
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 enforce bidirectional attachment when referencing resources across namespaces

Engineers MUST ALWAYS enforce bidirectional attachment when referencing resources across namespaces: the Gateway listener MUST specify `allowedRoutes.namespaces.from: Selector` (never unbounded `All`), and cross-namespace backend references MUST have a matching `ReferenceGrant` in the target 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 `allowedRoutes.namespaces.from

Engineers MUST NOT configure `allowedRoutes.namespaces.from: All` on shared production Gateway listeners unless paired with explicit, non-wildcard `allowedRoutes.namespaces.selector` label criteria matching verified 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

Engineers MUST NOT define `ReferenceGrant` resources with wildcard `from[].namespace

Engineers MUST NOT define `ReferenceGrant` resources with wildcard `from[].namespace: '*'` or unconstrained resource groups; every grant MUST declare discrete source namespaces and exact target Core/Gateway API kinds.

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

HTTPRoutes MUST explicitly declare `parentRefs[].namespace` and `parentRefs[].sectionName` when attaching to a Gateway outside their local namespace to prevent cross-listener collisions.

HTTPRoutes MUST explicitly declare `parentRefs[].namespace` and `parentRefs[].sectionName` when attaching to a Gateway outside their local namespace to prevent cross-listener collisions.

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

Platform manifests MUST ensure `ReferenceGrant` uses `gateway.networking.k8s.io/v1beta1` or `gateway.networking.k8s.io/v1alpha2` explicitly matching the cluster Gateway API v1.2 controller capabilities.

Platform manifests MUST ensure `ReferenceGrant` uses `gateway.networking.k8s.io/v1beta1` or `gateway.networking.k8s.io/v1alpha2` explicitly matching the cluster Gateway API v1.2 controller capabilities.

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

Admission validation (e.g., Kyverno or Gatekeeper) MUST fail deployments containing cross-namespace `backendRefs` that lack a co-located or pre-existing `ReferenceGrant` in the target service's namespace.

Admission validation (e.g., Kyverno or Gatekeeper) MUST fail deployments containing cross-namespace `backendRefs` that lack a co-located or pre-existing `ReferenceGrant` in the target service'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 Bidirectional Cross-Namespace ReferenceGrant Enforcement critical for AI coding assistants?

Mandates strict bidirectional authorization boundaries for cross-namespace Gateway API v1.2 topologies using explicit ReferenceGrant resources and scoped Gateway listener allowedRoutes. Prevents cross-tenant traffic hijacking, unverified backend routing, and route collision across isolated microservice 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 (Permissive Wildcard Cross-Namespace Route Attachment Without Explicit ReferenceGrant Scoping) 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