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

Kubernetes Gateway API ReferenceGrant Strict Cross-Namespace Handshake Enforcement

Mandates strict bidirectional authorization for cross-namespace references in Kubernetes Gateway API using explicit ReferenceGrant custom resources. Prevents multi-tenant route hijacking, unauthorized secret attachments, and broken routing paths across Gateway listeners, Routes, Secrets, and Services.

Prohibited Anti-Pattern: Implicit Cross-Namespace Route Hijacking and Unauthorized Secret Ingestion via Missing ReferenceGrants

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kubernetes Gateway API ReferenceGrant Strict Cross-Namespace Handshake Enforcement - Mandates strict bidirectional authorization for cross-namespace references in Kubernetes Gateway API using explicit ReferenceGrant custom resources. Prevents multi-tenant route hijacking, unauthorized secret attachments, and broken routing paths across Gateway listeners, Routes, Secrets, and Services.
globs: k8s/**/*.yaml, deploy/**/*.yaml, infra/**/*.yaml, charts/**/*.yaml, **/*.gateway.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/k8s-gateway-api-referencegrant-isolation"
---

# Kubernetes Gateway API ReferenceGrant Strict Cross-Namespace Handshake Enforcement

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Implicit Cross-Namespace Route Hijacking and Unauthorized Secret Ingestion via Missing ReferenceGrants

## System Constraints
You are a Principal Software Architect and DevOps Security Specialist enforcing Kubernetes Gateway API ReferenceGrant Strict Namespace Isolation. Cross-namespace references between Gateways, Routes, Services, and Secrets create multi-tenant vulnerabilities if unverified. Mandate strict bidirectional handshakes via ReferenceGrant resources, fail-closed listener bounds, and explicit namespace scoping to prevent unauthorized traffic redirection and secret extraction.

## Strict Guidelines
- Engineers MUST ALWAYS deploy a `ReferenceGrant` in the target namespace whenever an `HTTPRoute`, `GRPCRoute`, or `Gateway` references a resource (e.g., `Service`, `Secret`) in a foreign namespace.
- Engineers MUST NOT rely on permissive `namespaces.from: All` in Gateway listeners without explicit route-level namespace restrictions and matching ReferenceGrant objects.
- Engineers MUST scope `ReferenceGrant.spec.from` strictly to the exact `group`, `kind`, and `namespace` of the referencing consumer resource.
- Engineers MUST scope `ReferenceGrant.spec.to` strictly to the specific resource `kind` and explicit target `name` when supported, avoiding wildcard access.
- Services MUST NEVER be exposed across tenant boundaries unless an explicit `ReferenceGrant` exists in the service namespace granting access to the consuming route's namespace.
- Gateways MUST fail closed and be monitored for status condition `ResolvedRefs: False` to detect and remediate invalid or unauthorized cross-namespace reference attempts.
- Infrastructure pipelines SHOULD enforce admission control policies (via Kyverno or Gatekeeper) rejecting any cross-namespace `backendRef` or `certificateRefs` lacking a companion `ReferenceGrant`.

## Bad vs Good Implementations
### Cross-Namespace BackendRef Service Access via ReferenceGrant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The HTTPRoute in namespace 'edge-routing' references 'checkout-service' in foreign namespace 'billing-tenant'. Without an explicit ReferenceGrant deployed inside 'billing-tenant', Gateway API implementations reject this reference for security reasons, causing route degradation or leaving routes open to hijacking if reference controls are misconfigured.
```yaml
# INSECURE: HTTPRoute references service in 'billing-tenant' from 'edge-routing'
# without an authorizing ReferenceGrant in 'billing-tenant'.
# Results in ResolvedRefs=False, route blackholing, or route hijacking vulnerabilities.
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: checkout-route
  namespace: edge-routing
spec:
  parentRefs:
    - name: shared-gateway
      namespace: ingress-infra
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /checkout
      backendRefs:
        - name: checkout-service
          namespace: billing-tenant
          port: 8080
```

#### Production Standard (Correct)
> **Standard**: The 'billing-tenant' namespace explicitly defines a ReferenceGrant that permits only 'HTTPRoute' resources located within 'edge-routing' to bind to the 'checkout-service' Service. This completes the required cryptographic-grade handshake, satisfying Gateway API conformance and multi-tenant isolation invariants.
```yaml
# SECURE: Bidirectional handshake established via explicit ReferenceGrant in billing-tenant
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-edge-routing-checkout
  namespace: billing-tenant
spec:
  from:
    - group: gateway.networking.k8s.io
      kind: HTTPRoute
      namespace: edge-routing
  to:
    - group: ""
      kind: Service
      name: checkout-service
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: checkout-route
  namespace: edge-routing
spec:
  parentRefs:
    - name: shared-gateway
      namespace: ingress-infra
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /checkout
      backendRefs:
        - name: checkout-service
          namespace: billing-tenant
          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 ReferenceGrant Strict Cross-Namespace Handshake Enforcement

Kubernetes Gateway API ReferenceGrant Strict Cross-Namespace Handshake Enforcement defines an industrial-grade behavioral standard for devops engineering. Mandates strict bidirectional authorization for cross-namespace references in Kubernetes Gateway API using explicit ReferenceGrant custom resources. Prevents multi-tenant route hijacking, unauthorized secret attachments, and broken routing paths across Gateway listeners, Routes, Secrets, and Services. 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: Implicit Cross-Namespace Route Hijacking and Unauthorized Secret Ingestion via Missing ReferenceGrants 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 DriftImplicit Cross-Namespace Route Hijacking and Unauthorized Secret Ingestion via Missing ReferenceGrantsCritical
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 deploy a `ReferenceGrant` in the target namespace whenever an `HTTPRoute`, `GRPCRoute`, or `Gateway` references a resource (e.g., `Service`, `Secret`) in a foreign namespace.

Engineers MUST ALWAYS deploy a `ReferenceGrant` in the target namespace whenever an `HTTPRoute`, `GRPCRoute`, or `Gateway` references a resource (e.g., `Service`, `Secret`) in a foreign 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 rely on permissive `namespaces.from

Engineers MUST NOT rely on permissive `namespaces.from: All` in Gateway listeners without explicit route-level namespace restrictions and matching ReferenceGrant objects.

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 scope `ReferenceGrant.spec.from` strictly to the exact `group`, `kind`, and `namespace` of the referencing consumer resource.

Engineers MUST scope `ReferenceGrant.spec.from` strictly to the exact `group`, `kind`, and `namespace` of the referencing consumer resource.

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

Engineers MUST scope `ReferenceGrant.spec.to` strictly to the specific resource `kind` and explicit target `name` when supported, avoiding wildcard access.

Engineers MUST scope `ReferenceGrant.spec.to` strictly to the specific resource `kind` and explicit target `name` when supported, avoiding wildcard 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.
5

Services MUST NEVER be exposed across tenant boundaries unless an explicit `ReferenceGrant` exists in the service namespace granting access to the consuming route's namespace.

Services MUST NEVER be exposed across tenant boundaries unless an explicit `ReferenceGrant` exists in the service namespace granting access to the consuming route'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.
6

Gateways MUST fail closed and be monitored for status condition `ResolvedRefs

Gateways MUST fail closed and be monitored for status condition `ResolvedRefs: False` to detect and remediate invalid or unauthorized cross-namespace reference attempts.

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.
7

Infrastructure pipelines SHOULD enforce admission control policies (via Kyverno or Gatekeeper) rejecting any cross-namespace `backendRef` or `certificateRefs` lacking a companion `ReferenceGrant`.

Infrastructure pipelines SHOULD enforce admission control policies (via Kyverno or Gatekeeper) rejecting any cross-namespace `backendRef` or `certificateRefs` lacking a companion `ReferenceGrant`.

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 ReferenceGrant Strict Cross-Namespace Handshake Enforcement critical for AI coding assistants?

Mandates strict bidirectional authorization for cross-namespace references in Kubernetes Gateway API using explicit ReferenceGrant custom resources. Prevents multi-tenant route hijacking, unauthorized secret attachments, and broken routing paths across Gateway listeners, Routes, Secrets, and Services. 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 (Implicit Cross-Namespace Route Hijacking and Unauthorized Secret Ingestion via Missing ReferenceGrants) 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