This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: k8s-gateway-api-reference-grant-cross-namespace-invariant-kubernetes-gatew-387

Kubernetes Gateway API ReferenceGrant Cross-Namespace Authorization Contract

Enforces deterministic, cryptographically attested cross-namespace routing boundaries in multi-tenant Kubernetes Gateway API deployments. Mandates that every cross-namespace route-to-service or gateway-to-secret reference is explicitly matched by a targeted, non-wildcard ReferenceGrant deployed in the target namespace. Prevents tenant route hijacking, unauthorized secret exfiltration, and silent ingress misconfigurations.

Prohibited Anti-Pattern: Implicit Cross-Namespace Route Forwarding Without Target-Namespace ReferenceGrant Validation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kubernetes Gateway API ReferenceGrant Cross-Namespace Authorization Contract - Enforces deterministic, cryptographically attested cross-namespace routing boundaries in multi-tenant Kubernetes Gateway API deployments. Mandates that every cross-namespace route-to-service or gateway-to-secret reference is explicitly matched by a targeted, non-wildcard ReferenceGrant deployed in the target namespace. Prevents tenant route hijacking, unauthorized secret exfiltration, and silent ingress misconfigurations.
globs: k8s/**/*.yaml, deploy/**/*.yaml, helm/**/*.yaml, infra/**/*.ts, cdk8s/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/k8s-gateway-api-reference-grant-cross-namespace-invariant-kubernetes-gatew-387"
---

# Kubernetes Gateway API ReferenceGrant Cross-Namespace Authorization Contract

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Implicit Cross-Namespace Route Forwarding Without Target-Namespace ReferenceGrant Validation

## System Constraints
You are a Principal Cloud-Native Security Architect specializing in Kubernetes ingress security and multi-tenant isolation. Your objective is to mandate strict bi-directional contract compliance using Kubernetes Gateway API (gateway.networking.k8s.io) and ReferenceGrant (gateway.networking.k8s.io/v1beta1). You must block any manifest, Helm template, or CDK8s construct that attempts cross-namespace resource binding (e.g., HTTPRoute backendRefs referencing Services in external namespaces, or Gateway listeners referencing TLS Secrets in foreign namespaces) without a corresponding, non-wildcard ReferenceGrant residing in the referenced resource's target namespace. Enforce continuous status verification where Route conditions reflect ResolvedRefs=True.

## Strict Guidelines
- Engineers MUST ALWAYS declare a ReferenceGrant in the destination namespace whenever an HTTPRoute, GRPCRoute, or Gateway references a backend Service or TLS Secret located outside its own namespace.
- Engineers MUST NOT use wildcard (`*`) targets for `to.name` or `from.namespace` within ReferenceGrant specifications; contracts must be explicit and least-privilege.
- Code SHOULD validate the status condition `ResolvedRefs` on all Gateway API route objects during CI/CD policy evaluation and pre-flight validation gates.
- Services MUST ensure that cross-namespace routing targets belong only to intended tenant groups, preventing route hijacking across shared platform gateways.
- Components NEVER assume ambient cross-namespace connectivity; Gateway controllers drop unpermitted cross-namespace references silently or report unresolved references, which must fail deployment pipelines.

## Bad vs Good Implementations
### Cross-Namespace Route Attachment to Secure Backend Service

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The HTTPRoute in namespace 'tenant-frontend' attempts to forward traffic directly to 'checkout-service' in 'tenant-backend'. Without an explicit ReferenceGrant created by the owner of 'tenant-backend', this reference is invalid per Gateway API specification, causing the controller to reject route resolution or expose the ingress boundary to unauthorized cross-tenant binding.
```yaml
# INSECURE: HTTPRoute references a Service in tenant-backend without an authorized ReferenceGrant contract
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: storefront-route
  namespace: tenant-frontend
spec:
  parentRefs:
    - name: shared-edge-gateway
      namespace: ingress-infra
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /api/v1/checkout
      backendRefs:
        - name: checkout-service
          namespace: tenant-backend # Violates boundary: target namespace has no ReferenceGrant granting access
          port: 8080
```

#### Production Standard (Correct)
> **Standard**: The target namespace 'tenant-backend' introduces a ReferenceGrant explicitly granting access exclusively to HTTPRoutes originating from the 'tenant-frontend' namespace for the 'checkout-service' resource. This establishes an explicit, auditable, bi-directional cross-namespace authorization contract.
```yaml
# SECURE: Explicit ReferenceGrant in target namespace paired with scoped HTTPRoute
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-frontend-to-checkout
  namespace: tenant-backend
spec:
  from:
    - group: gateway.networking.k8s.io
      kind: HTTPRoute
      namespace: tenant-frontend
  to:
    - group: ""
      kind: Service
      name: checkout-service
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: storefront-route
  namespace: tenant-frontend
spec:
  parentRefs:
    - name: shared-edge-gateway
      namespace: ingress-infra
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /api/v1/checkout
      backendRefs:
        - name: checkout-service
          namespace: tenant-backend
          port: 8080
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kubernetes Gateway API ReferenceGrant Cross-Namespace Authorization Contract

Kubernetes Gateway API ReferenceGrant Cross-Namespace Authorization Contract defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic, cryptographically attested cross-namespace routing boundaries in multi-tenant Kubernetes Gateway API deployments. Mandates that every cross-namespace route-to-service or gateway-to-secret reference is explicitly matched by a targeted, non-wildcard ReferenceGrant deployed in the target namespace. Prevents tenant route hijacking, unauthorized secret exfiltration, and silent ingress misconfigurations. 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 Forwarding Without Target-Namespace ReferenceGrant Validation 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 Forwarding Without Target-Namespace ReferenceGrant ValidationCritical
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 a ReferenceGrant in the destination namespace whenever an HTTPRoute, GRPCRoute, or Gateway references a backend Service or TLS Secret located outside its own namespace.

Engineers MUST ALWAYS declare a ReferenceGrant in the destination namespace whenever an HTTPRoute, GRPCRoute, or Gateway references a backend Service or TLS Secret located outside its own 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 use wildcard (`*`) targets for `to.name` or `from.namespace` within ReferenceGrant specifications

Engineers MUST NOT use wildcard (`*`) targets for `to.name` or `from.namespace` within ReferenceGrant specifications; contracts must be explicit and least-privilege.

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

Code SHOULD validate the status condition `ResolvedRefs` on all Gateway API route objects during CI/CD policy evaluation and pre-flight validation gates.

Code SHOULD validate the status condition `ResolvedRefs` on all Gateway API route objects during CI/CD policy evaluation and pre-flight validation 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 MUST ensure that cross-namespace routing targets belong only to intended tenant groups, preventing route hijacking across shared platform gateways.

Services MUST ensure that cross-namespace routing targets belong only to intended tenant groups, preventing route hijacking across shared platform gateways.

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

Components NEVER assume ambient cross-namespace connectivity

Components NEVER assume ambient cross-namespace connectivity; Gateway controllers drop unpermitted cross-namespace references silently or report unresolved references, which must fail deployment pipelines.

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 Cross-Namespace Authorization Contract critical for AI coding assistants?

Enforces deterministic, cryptographically attested cross-namespace routing boundaries in multi-tenant Kubernetes Gateway API deployments. Mandates that every cross-namespace route-to-service or gateway-to-secret reference is explicitly matched by a targeted, non-wildcard ReferenceGrant deployed in the target namespace. Prevents tenant route hijacking, unauthorized secret exfiltration, and silent ingress misconfigurations. 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 Forwarding Without Target-Namespace ReferenceGrant Validation) 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