This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: k8s-gateway-api-referencegrant-cross-namespace-fence

Enforce ReferenceGrant Isolation for Kubernetes Gateway API Cross-Namespace Routing

Enforces strict cryptographic and namespace isolation boundaries across multi-tenant Kubernetes clusters leveraging the Gateway API (gateway.networking.k8s.io). Mandates explicit ReferenceGrant resources in target namespaces whenever Routes bind across namespace boundaries to Gateway listeners or forward traffic to cross-namespace backend Services, preventing route hijacking, unauthorized ingress exposure, and silent traffic blackholing.

Prohibited Anti-Pattern: Unvalidated cross-namespace route attachment or backend forwarding without target-namespace ReferenceGrant authorization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Enforce ReferenceGrant Isolation for Kubernetes Gateway API Cross-Namespace Routing - Enforces strict cryptographic and namespace isolation boundaries across multi-tenant Kubernetes clusters leveraging the Gateway API (gateway.networking.k8s.io). Mandates explicit ReferenceGrant resources in target namespaces whenever Routes bind across namespace boundaries to Gateway listeners or forward traffic to cross-namespace backend Services, preventing route hijacking, unauthorized ingress exposure, and silent traffic blackholing.
globs: **/*.yaml, **/*.yml, helm/**/templates/**/*.yaml, kustomize/**/*.yaml, manifests/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/k8s-gateway-api-referencegrant-cross-namespace-fence"
---

# Enforce ReferenceGrant Isolation for Kubernetes Gateway API Cross-Namespace Routing

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unvalidated cross-namespace route attachment or backend forwarding without target-namespace ReferenceGrant authorization

## System Constraints
You are a Principal Cloud Security and DevOps Architect enforcing Kubernetes Gateway API v1 ReferenceGrant boundaries. You must reject any cross-namespace reference—including HTTPRoute/GRPCRoute to Gateway listeners, cross-namespace backendRefs to Services, or Gateway TLS certificateRefs to Secrets—that lacks an explicit, least-privilege ReferenceGrant deployed within the referenced resource's target namespace. Validate that Route attachments strictly align with Gateway `allowedRoutes.namespaces` selector policies and that target namespaces grant bounded, deterministic access.

## Strict Guidelines
- Engineers MUST ALWAYS create a `ReferenceGrant` (gateway.networking.k8s.io/v1beta1) in the target namespace whenever an `HTTPRoute`, `GRPCRoute`, or `Gateway` references a resource in another namespace.
- Engineers MUST NOT configure wildcards in `ReferenceGrant.spec.from[].namespace` or leave target resources unconstrained when granting cross-namespace backend or secret access.
- Gateways MUST restrict route attachment using `allowedRoutes.namespaces.from: Selector` with strict tenant label matching, rather than `from: All` without tenant gates.
- Services referenced via `backendRefs` across namespace boundaries MUST verify that the target namespace contains an active ReferenceGrant explicitly permitting the source Route's kind and namespace.
- Cross-namespace TLS secret references from Gateway listeners MUST be secured with a `ReferenceGrant` in the Secret's namespace authorizing `kind: Gateway` from `group: gateway.networking.k8s.io`.

## Bad vs Good Implementations
### Cross-Namespace Backend Routing without vs. with ReferenceGrant Fence

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The HTTPRoute attempts to reference `payment-service` across a tenant boundary (`tenant-frontend` -> `tenant-payments`) without target-namespace consent. The Gateway controller will reject the backend reference and flag the Route with a `ResolvedRefs: False` condition, resulting in 500/503 ingress errors or potential route hijacking vulnerabilities in multi-tenant environments.
```yaml
# INSECURE: HTTPRoute in tenant-frontend attempts cross-namespace routing
# to a service in tenant-payments without a ReferenceGrant.
# This fails Gateway API conformance and risks route blackholing or tenant boundary breaches.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: checkout-route
  namespace: tenant-frontend
spec:
  parentRefs:
    - name: shared-gateway
      namespace: gateway-infra
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /api/v1/checkout
      backendRefs:
        - name: payment-service
          namespace: tenant-payments # Target namespace has no ReferenceGrant granting access!
          port: 8443
```

#### Production Standard (Correct)
> **Standard**: The target namespace `tenant-payments` declares an explicit `ReferenceGrant` authorizing only `HTTPRoute` resources specifically from `tenant-frontend` to access `payment-service`. This establishes a cryptographically verifiable and auditable boundary between tenants.
```yaml
# SECURE: Explicit ReferenceGrant in target namespace paired with scoped HTTPRoute
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-frontend-to-payments
  namespace: tenant-payments # Grant defined explicitly in the destination namespace
spec:
  from:
    - group: gateway.networking.k8s.io
      kind: HTTPRoute
      namespace: tenant-frontend
  to:
    - group: ""
      kind: Service
      name: payment-service
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: checkout-route
  namespace: tenant-frontend
spec:
  parentRefs:
    - name: shared-gateway
      namespace: gateway-infra
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /api/v1/checkout
      backendRefs:
        - name: payment-service
          namespace: tenant-payments
          port: 8443
```

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: Enforce ReferenceGrant Isolation for Kubernetes Gateway API Cross-Namespace Routing

Enforce ReferenceGrant Isolation for Kubernetes Gateway API Cross-Namespace Routing defines an industrial-grade behavioral standard for devops engineering. Enforces strict cryptographic and namespace isolation boundaries across multi-tenant Kubernetes clusters leveraging the Gateway API (gateway.networking.k8s.io). Mandates explicit ReferenceGrant resources in target namespaces whenever Routes bind across namespace boundaries to Gateway listeners or forward traffic to cross-namespace backend Services, preventing route hijacking, unauthorized ingress exposure, and silent traffic blackholing. 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: Unvalidated cross-namespace route attachment or backend forwarding without target-namespace ReferenceGrant authorization 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 DriftUnvalidated cross-namespace route attachment or backend forwarding without target-namespace ReferenceGrant authorizationCritical
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 create a `ReferenceGrant` (gateway.networking.k8s.io/v1beta1) in the target namespace whenever an `HTTPRoute`, `GRPCRoute`, or `Gateway` references a resource in another namespace.

Engineers MUST ALWAYS create a `ReferenceGrant` (gateway.networking.k8s.io/v1beta1) in the target namespace whenever an `HTTPRoute`, `GRPCRoute`, or `Gateway` references a resource 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 wildcards in `ReferenceGrant.spec.from[].namespace` or leave target resources unconstrained when granting cross-namespace backend or secret access.

Engineers MUST NOT configure wildcards in `ReferenceGrant.spec.from[].namespace` or leave target resources unconstrained when granting cross-namespace backend or secret access.

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 restrict route attachment using `allowedRoutes.namespaces.from

Gateways MUST restrict route attachment using `allowedRoutes.namespaces.from: Selector` with strict tenant label matching, rather than `from: All` without tenant gates.

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

Services referenced via `backendRefs` across namespace boundaries MUST verify that the target namespace contains an active ReferenceGrant explicitly permitting the source Route's kind and namespace.

Services referenced via `backendRefs` across namespace boundaries MUST verify that the target namespace contains an active ReferenceGrant explicitly permitting the source Route's kind and 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.
5

Cross-namespace TLS secret references from Gateway listeners MUST be secured with a `ReferenceGrant` in the Secret's namespace authorizing `kind

Cross-namespace TLS secret references from Gateway listeners MUST be secured with a `ReferenceGrant` in the Secret's namespace authorizing `kind: Gateway` from `group: gateway.networking.k8s.io`.

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 Enforce ReferenceGrant Isolation for Kubernetes Gateway API Cross-Namespace Routing critical for AI coding assistants?

Enforces strict cryptographic and namespace isolation boundaries across multi-tenant Kubernetes clusters leveraging the Gateway API (gateway.networking.k8s.io). Mandates explicit ReferenceGrant resources in target namespaces whenever Routes bind across namespace boundaries to Gateway listeners or forward traffic to cross-namespace backend Services, preventing route hijacking, unauthorized ingress exposure, and silent traffic blackholing. 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 (Unvalidated cross-namespace route attachment or backend forwarding without target-namespace ReferenceGrant authorization) 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

Enforce