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-gatew-776

Hierarchical Policy Attachment and Cross-Namespace Route Isolation in Gateway API v1.2

Enforces strict tenant boundary isolation and non-overridable hierarchical routing policies within Kubernetes Gateway API v1.2. Prohibits wildcard listener bindings, mandates explicit ReferenceGrant contracts for cross-namespace backend references, and guarantees centralized security policies cannot be bypassed or overridden by child routes.

Prohibited Anti-Pattern: Unrestricted Listener Bindings and Unguarded Cross-Namespace Route Hijacking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hierarchical Policy Attachment and Cross-Namespace Route Isolation in Gateway API v1.2 - Enforces strict tenant boundary isolation and non-overridable hierarchical routing policies within Kubernetes Gateway API v1.2. Prohibits wildcard listener bindings, mandates explicit ReferenceGrant contracts for cross-namespace backend references, and guarantees centralized security policies cannot be bypassed or overridden by child routes.
globs: deploy/**/*.yaml, deploy/**/*.yml, k8s/**/*.yaml, k8s/**/*.yml, helm/**/*.yaml, helm/**/*.yml, infra/**/*.yaml, infra/**/*.yml
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-gatew-776"
---

# Hierarchical Policy Attachment and Cross-Namespace Route Isolation in Gateway API v1.2

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unrestricted Listener Bindings and Unguarded Cross-Namespace Route Hijacking

## System Constraints
You are a Principal Cloud Security and Infrastructure Architect enforcing Kubernetes Gateway API v1.2 specifications (GEP-713, GEP-1709). Your mandate is to eliminate cross-namespace route hijacking, enforce granular ReferenceGrant requirements, and preserve hierarchical policy inheritance across multi-tenant clusters.

## Strict Guidelines
- Engineers MUST ALWAYS restrict Gateway listeners using `allowedRoutes.namespaces.from: Selector` with explicit label matching, never `namespaces.from: All` without strict hostname constraints.
- Engineers MUST NEVER permit an HTTPRoute or GRPCRoute in a tenant namespace to claim wildcards or apex domains belonging to root infrastructure or sibling tenants.
- Engineers MUST configure a `ReferenceGrant` in the target namespace whenever a Route attaches to a backend Service located across a namespace boundary.
- Hierarchical policy attachments (such as auth or rate-limiting policies) attached to parent Gateways MUST define non-overridable default/override behaviors per GEP-713 to block downstream bypass by tenant routes.
- Services MUST validate that incoming traffic through Gateway listeners strictly enforces TLS termination policies and rejects plain text fallback across tenant boundaries.

## Bad vs Good Implementations
### Multi-Tenant Listener Binding and Cross-Namespace Reference Grant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The Gateway sets `namespaces.from: All`, enabling untrusted namespaces to register routes for `api.company.com`. Additionally, the HTTPRoute refers to a backend Service in `core-auth` without an accompanying ReferenceGrant, exposing cluster services to unauthorized cross-namespace traffic forwarding.
```yaml
# VULNERABLE: Permissive namespace attachment allows any tenant to hijack routes
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: shared-gateway
  namespace: gateway-infra
spec:
  gatewayClassName: egress-gw
  listeners:
    - name: https-wildcard
      protocol: HTTPS
      port: 443
      allowedRoutes:
        namespaces:
          from: All # CRITICAL: Allows any namespace to attach and hijack apex domains
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: tenant-route
  namespace: tenant-b
spec:
  parentRefs:
    - name: shared-gateway
      namespace: gateway-infra
  hostnames:
    - "api.company.com" # Route hijacking: tenant-b claims root API domain
  rules:
    - backendRefs:
        - name: auth-service
          namespace: core-auth # Cross-namespace reference without ReferenceGrant
          port: 8080
```

#### Production Standard (Correct)
> **Standard**: The Gateway explicitly restricts listener attachment using `namespaces.from: Selector` bound to verified tenant labels, restricting tenant hostnames to dedicated subdomains. Cross-namespace communication from `tenant-b` to `tenant-b-backends` is formally permitted by an isolated `ReferenceGrant` scoped specifically to `payment-service`.
```yaml
# SECURE: Explicit label selectors, hostname constraints, and ReferenceGrant enforcement
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: shared-gateway
  namespace: gateway-infra
spec:
  gatewayClassName: egress-gw
  listeners:
    - name: tenant-b-https
      protocol: HTTPS
      port: 443
      hostname: "tenant-b.company.com"
      allowedRoutes:
        namespaces:
          from: Selector
          selector:
            matchLabels:
              tenant: "tenant-b"
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: tenant-b-route
  namespace: tenant-b
spec:
  parentRefs:
    - name: shared-gateway
      namespace: gateway-infra
      sectionName: tenant-b-https
  hostnames:
    - "tenant-b.company.com"
  rules:
    - backendRefs:
        - name: payment-service
          namespace: tenant-b-backends
          port: 8080
---
# Explicit grant allowing HTTPRoute in tenant-b to target services in tenant-b-backends
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-tenant-b-route
  namespace: tenant-b-backends
spec:
  from:
    - group: gateway.networking.k8s.io
      kind: HTTPRoute
      namespace: tenant-b
  to:
    - group: ""
      kind: Service
      name: payment-service
```

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: Hierarchical Policy Attachment and Cross-Namespace Route Isolation in Gateway API v1.2

Hierarchical Policy Attachment and Cross-Namespace Route Isolation in Gateway API v1.2 defines an industrial-grade behavioral standard for devops engineering. Enforces strict tenant boundary isolation and non-overridable hierarchical routing policies within Kubernetes Gateway API v1.2. Prohibits wildcard listener bindings, mandates explicit ReferenceGrant contracts for cross-namespace backend references, and guarantees centralized security policies cannot be bypassed or overridden by child routes. 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: Unrestricted Listener Bindings and Unguarded Cross-Namespace Route Hijacking 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 DriftUnrestricted Listener Bindings and Unguarded Cross-Namespace Route HijackingCritical
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 restrict Gateway listeners using `allowedRoutes.namespaces.from

Engineers MUST ALWAYS restrict Gateway listeners using `allowedRoutes.namespaces.from: Selector` with explicit label matching, never `namespaces.from: All` without strict hostname constraints.

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 NEVER permit an HTTPRoute or GRPCRoute in a tenant namespace to claim wildcards or apex domains belonging to root infrastructure or sibling tenants.

Engineers MUST NEVER permit an HTTPRoute or GRPCRoute in a tenant namespace to claim wildcards or apex domains belonging to root infrastructure or sibling tenants.

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 configure a `ReferenceGrant` in the target namespace whenever a Route attaches to a backend Service located across a namespace boundary.

Engineers MUST configure a `ReferenceGrant` in the target namespace whenever a Route attaches to a backend Service located across a namespace boundary.

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

Hierarchical policy attachments (such as auth or rate-limiting policies) attached to parent Gateways MUST define non-overridable default/override behaviors per GEP-713 to block downstream bypass by tenant routes.

Hierarchical policy attachments (such as auth or rate-limiting policies) attached to parent Gateways MUST define non-overridable default/override behaviors per GEP-713 to block downstream bypass by tenant routes.

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

Services MUST validate that incoming traffic through Gateway listeners strictly enforces TLS termination policies and rejects plain text fallback across tenant boundaries.

Services MUST validate that incoming traffic through Gateway listeners strictly enforces TLS termination policies and rejects plain text fallback across tenant boundaries.

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 Hierarchical Policy Attachment and Cross-Namespace Route Isolation in Gateway API v1.2 critical for AI coding assistants?

Enforces strict tenant boundary isolation and non-overridable hierarchical routing policies within Kubernetes Gateway API v1.2. Prohibits wildcard listener bindings, mandates explicit ReferenceGrant contracts for cross-namespace backend references, and guarantees centralized security policies cannot be bypassed or overridden by child routes. 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 (Unrestricted Listener Bindings and Unguarded Cross-Namespace Route Hijacking) 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

Hierarchical