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-referencegrant-invariant

Kubernetes Gateway API v1.2 ReferenceGrant Cross-Namespace Security Invariant

Mandates explicit, fine-grained ReferenceGrant resources for all cross-namespace Gateway API v1.2 references between Routes, Gateways, and Services. Prevents cross-tenant traffic hijacking and routing misconfigurations by enforcing unidirectional administrative consent from destination namespaces.

Prohibited Anti-Pattern: Cross-Namespace BackendRef or Route Attachment Without Explicit Destination ReferenceGrant

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kubernetes Gateway API v1.2 ReferenceGrant Cross-Namespace Security Invariant - Mandates explicit, fine-grained ReferenceGrant resources for all cross-namespace Gateway API v1.2 references between Routes, Gateways, and Services. Prevents cross-tenant traffic hijacking and routing misconfigurations by enforcing unidirectional administrative consent from destination namespaces.
globs: infra/**/*.ts, deploy/**/*.ts, src/k8s/**/*.ts, **/*.k8s.ts, **/*.cdk8s.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/k8s-gateway-v1-2-cross-namespace-referencegrant-invariant"
---

# Kubernetes Gateway API v1.2 ReferenceGrant Cross-Namespace Security Invariant

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Cross-Namespace BackendRef or Route Attachment Without Explicit Destination ReferenceGrant

## System Constraints
You are a Principal Software Architect enforcing Kubernetes Gateway API v1.2 security invariants. Multi-tenant cluster isolation requires strict administrative boundaries. When an HTTPRoute or GRPCRoute references a Service in another namespace, or a Route attaches to a Gateway in another namespace, an explicit ReferenceGrant MUST exist in the target namespace. You must reject any cross-namespace references lacking corresponding ReferenceGrants and prohibit wildcard namespace selectors.

## Strict Guidelines
- Engineers MUST ALWAYS deploy a ReferenceGrant in the destination namespace whenever a backendRef references a Service outside the Route's namespace.
- Engineers MUST NOT use wildcard namespace selectors (e.g., namespace: '*') within ReferenceGrant 'from' clauses in multi-tenant environments.
- Services MUST explicitly declare the exact Group, Kind, and source Namespace permitted to route to them via ReferenceGrant spec.from and spec.to.
- Gateways MUST restrict cross-namespace route attachment using explicit allowedRoutes.namespaces.from (Selector or Same) rather than All without ingress controller guardrails.
- Components NEVER assume implicit cross-namespace visibility; cross-namespace routing without an active ReferenceGrant causes backendRefs to enter an unresolved/invalid status (ResolvedRefs: False).

## Bad vs Good Implementations
### Configuring Cross-Namespace BackendRef with ReferenceGrant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: tenant-a attempts to forward traffic to checkout-service in tenant-b. Without a ReferenceGrant deployed within tenant-b granting access to tenant-a HTTPRoutes, Gateway API implementations reject the backendRef with ResolvedRefs: False, risking silent routing failures or unvetted cross-tenant traffic access.
```typescript
import { Construct } from 'constructs';

// ANTI-PATTERN: tenant-a HTTPRoute targets tenant-b Service without tenant-b ReferenceGrant consent
export function buildCrossTenantRoute(scope: Construct) {
  return {
    apiVersion: 'gateway.networking.k8s.io/v1',
    kind: 'HTTPRoute',
    metadata: {
      name: 'checkout-route',
      namespace: 'tenant-a'
    },
    spec: {
      parentRefs: [{ name: 'shared-gateway', namespace: 'infra-gateways' }],
      rules: [{
        matches: [{ path: { type: 'PathPrefix', value: '/checkout' } }],
        backendRefs: [{
          // VIOLATION: Cross-namespace backend without a ReferenceGrant in 'tenant-b'
          name: 'checkout-service',
          namespace: 'tenant-b',
          port: 8080
        }]
      }]
    }
  };
}
```

#### Production Standard (Correct)
> **Standard**: The ReferenceGrant is deployed inside the owner's namespace (tenant-b). It explicitly authorizes only HTTPRoute resources originating from tenant-a to reference the checkout-service Service, fulfilling the Gateway API v1.2 administrative security contract.
```typescript
import { Construct } from 'constructs';

// SECURE: Destination tenant-b provides explicit ReferenceGrant consent for tenant-a HTTPRoute
export function buildCrossTenantRouteAndGrant(scope: Construct) {
  const route = {
    apiVersion: 'gateway.networking.k8s.io/v1',
    kind: 'HTTPRoute',
    metadata: {
      name: 'checkout-route',
      namespace: 'tenant-a'
    },
    spec: {
      parentRefs: [{ name: 'shared-gateway', namespace: 'infra-gateways' }],
      rules: [{
        matches: [{ path: { type: 'PathPrefix', value: '/checkout' } }],
        backendRefs: [{
          name: 'checkout-service',
          namespace: 'tenant-b',
          port: 8080
        }]
      }]
    }
  };

  const referenceGrant = {
    apiVersion: 'gateway.networking.k8s.io/v1beta1',
    kind: 'ReferenceGrant',
    metadata: {
      name: 'allow-tenant-a-checkout',
      namespace: 'tenant-b' // Deployed in the destination resource's namespace
    },
    spec: {
      from: [{
        group: 'gateway.networking.k8s.io',
        kind: 'HTTPRoute',
        namespace: 'tenant-a' // Deterministic least-privilege source namespace
      }],
      to: [{
        group: '', // Core API group for Service
        kind: 'Service',
        name: 'checkout-service' // Explicit target binding
      }]
    }
  };

  return { route, referenceGrant };
}
```

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 ReferenceGrant Cross-Namespace Security Invariant

Kubernetes Gateway API v1.2 ReferenceGrant Cross-Namespace Security Invariant defines an industrial-grade behavioral standard for devops engineering. Mandates explicit, fine-grained ReferenceGrant resources for all cross-namespace Gateway API v1.2 references between Routes, Gateways, and Services. Prevents cross-tenant traffic hijacking and routing misconfigurations by enforcing unidirectional administrative consent from destination 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: Cross-Namespace BackendRef or Route Attachment Without Explicit Destination ReferenceGrant 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 DriftCross-Namespace BackendRef or Route Attachment Without Explicit Destination ReferenceGrantCritical
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 destination namespace whenever a backendRef references a Service outside the Route's namespace.

Engineers MUST ALWAYS deploy a ReferenceGrant in the destination namespace whenever a backendRef references a Service outside the 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.
2

Engineers MUST NOT use wildcard namespace selectors (e.g., namespace

Engineers MUST NOT use wildcard namespace selectors (e.g., namespace: '*') within ReferenceGrant 'from' clauses in multi-tenant environments.

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

Services MUST explicitly declare the exact Group, Kind, and source Namespace permitted to route to them via ReferenceGrant spec.from and spec.to.

Services MUST explicitly declare the exact Group, Kind, and source Namespace permitted to route to them via ReferenceGrant spec.from and spec.to.

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

Gateways MUST restrict cross-namespace route attachment using explicit allowedRoutes.namespaces.from (Selector or Same) rather than All without ingress controller guardrails.

Gateways MUST restrict cross-namespace route attachment using explicit allowedRoutes.namespaces.from (Selector or Same) rather than All without ingress controller guardrails.

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 implicit cross-namespace visibility

Components NEVER assume implicit cross-namespace visibility; cross-namespace routing without an active ReferenceGrant causes backendRefs to enter an unresolved/invalid status (ResolvedRefs: False).

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 ReferenceGrant Cross-Namespace Security Invariant critical for AI coding assistants?

Mandates explicit, fine-grained ReferenceGrant resources for all cross-namespace Gateway API v1.2 references between Routes, Gateways, and Services. Prevents cross-tenant traffic hijacking and routing misconfigurations by enforcing unidirectional administrative consent from destination 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 (Cross-Namespace BackendRef or Route Attachment Without Explicit Destination ReferenceGrant) 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