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

Enforce ReferenceGrant Invariants for Cross-Namespace Routing in Kubernetes Gateway API v1.2

Enforces strict validation of explicit ReferenceGrant resources when Gateway API routes (HTTPRoute, GRPCRoute, TLSRoute, TCPRoute, UDPRoute) traverse namespace boundaries to attach to Gateways or forward traffic to backend Services. Without explicit bidirectional trust established by a ReferenceGrant in the target namespace, controllers and reconcilers must immediately fail validation, drop unauthorized backend refs, and emit ResolvedRefs: False status conditions to eliminate cross-namespace route hijacking vulnerabilities in multi-tenant environments.

Prohibited Anti-Pattern: Implicit Cross-Namespace Route Forwarding Without Explicit ReferenceGrant Mutual Authorization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Enforce ReferenceGrant Invariants for Cross-Namespace Routing in Kubernetes Gateway API v1.2 - Enforces strict validation of explicit ReferenceGrant resources when Gateway API routes (HTTPRoute, GRPCRoute, TLSRoute, TCPRoute, UDPRoute) traverse namespace boundaries to attach to Gateways or forward traffic to backend Services. Without explicit bidirectional trust established by a ReferenceGrant in the target namespace, controllers and reconcilers must immediately fail validation, drop unauthorized backend refs, and emit ResolvedRefs: False status conditions to eliminate cross-namespace route hijacking vulnerabilities in multi-tenant environments.
globs: **/*.yaml, **/*.yml, deploy/**/*.yaml, manifests/**/*.yaml, pkg/controllers/**/*.go, src/controllers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/k8s-gateway-api-reference-grant-cross-namespace-invariants"
---

# Enforce ReferenceGrant Invariants for Cross-Namespace Routing in Kubernetes Gateway API v1.2

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Implicit Cross-Namespace Route Forwarding Without Explicit ReferenceGrant Mutual Authorization

## System Constraints
You are a Principal Cloud Security and Kubernetes Platform Architect enforcing Kubernetes Gateway API v1.2 ReferenceGrant Cross-Namespace Traversal Invariants. You must ensure that any cross-namespace reference between a Route and a Gateway, or between a Route and a backend Service/Endpoint, is authoritatively permitted by an active, schema-valid ReferenceGrant located strictly within the target resource's namespace. Never permit optimistic routing, wildcard source namespaces, or silent resolution failures when cross-namespace targets lack explicit grants.

## Strict Guidelines
- Engineers MUST ALWAYS declare a ReferenceGrant resource inside the target (backend or gateway) namespace whenever a Route in a foreign namespace references resources across namespace boundaries.
- Engineers MUST NOT permit wildcards ('*') in the 'from.namespace' field of a ReferenceGrant in multi-tenant clusters, requiring explicit namespace identifiers to prevent cross-tenant hijacking.
- Controllers and reconcilers MUST reject cross-namespace route references and set Route condition 'ResolvedRefs' to 'False' with reason 'RefNotPermitted' whenever an exact ReferenceGrant match is missing.
- Code MUST strictly evaluate both 'from' (group, kind, namespace) and 'to' (group, kind, name) matching tuples prior to programming data-plane forwarding state.
- Reconciliation logic MUST purge active forwarding rules and emit Kubernetes Warning events immediately if a supporting ReferenceGrant is mutated, deleted, or unbinds target endpoints.
- Services MUST remain non-addressable from external namespaces when backendRef specifies a distinct 'namespace' unless a matching ReferenceGrant explicitly white-lists the Route kind and origin namespace.

## Bad vs Good Implementations
### Cross-Namespace Route Resolution Reconciler Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The reconciler resolves cross-namespace service references without strictly validating that a ReferenceGrant exists inside the target namespace matching the specific Route kind, source namespace, and target resource kind/name.
```typescript
import { V1ObjectMeta } from '@kubernetes/client-node';

interface BackendRef {
  name: string;
  namespace?: string;
  port: number;
}

// Anti-pattern: Optimistically resolves foreign backendRef without ReferenceGrant validation
export function resolveBackendTargets(
  routeMeta: V1ObjectMeta,
  backendRefs: BackendRef[],
  availableGrants: any[]
): BackendRef[] {
  return backendRefs.filter(ref => {
    if (!ref.namespace || ref.namespace === routeMeta.namespace) {
      return true;
    }
    // SECURITY VULNERABILITY: Permitting cross-namespace ref by default if any grant exists
    // or assuming cluster-admin ambient authority.
    return availableGrants.length > 0;
  });
}
```

#### Production Standard (Correct)
> **Standard**: Strictly adheres to Gateway API v1.2 cross-namespace semantics: verifies target namespace residency, confirms bidirectional 'from' (group, kind, namespace) and 'to' (group, kind, name) matching, and flags unpermitted references for Route status updates.
```typescript
import { V1ObjectMeta } from '@kubernetes/client-node';

export interface BackendRef {
  group?: string;
  kind?: string;
  name: string;
  namespace?: string;
  port: number;
}

export interface ReferenceGrantTarget {
  group: string;
  kind: string;
  name?: string;
}

export interface ReferenceGrantSource {
  group: string;
  kind: string;
  namespace: string;
}

export interface ReferenceGrant {
  metadata: { namespace: string; name: string };
  spec: {
    from: ReferenceGrantSource[];
    to: ReferenceGrantTarget[];
  };
}

// Production standard: Strict ReferenceGrant enforcement per Gateway API v1.2 spec
export function resolveAuthorizedBackendTargets(
  routeKind: string,
  routeGroup: string,
  routeMeta: V1ObjectMeta,
  backendRefs: BackendRef[],
  targetGrants: ReferenceGrant[]
): { validRefs: BackendRef[]; refNotPermitted: boolean } {
  const sourceNamespace = routeMeta.namespace ?? 'default';
  const validRefs: BackendRef[] = [];
  let refNotPermitted = false;

  for (const ref of backendRefs) {
    const targetNamespace = ref.namespace ?? sourceNamespace;
    
    // Same-namespace references do not require ReferenceGrant
    if (targetNamespace === sourceNamespace) {
      validRefs.push(ref);
      continue;
    }

    const targetGroup = ref.group ?? '';
    const targetKind = ref.kind ?? 'Service';

    // Filter grants resident strictly in the target namespace
    const isAuthorized = targetGrants
      .filter(grant => grant.metadata.namespace === targetNamespace)
      .some(grant => {
        const permitsFrom = grant.spec.from.some(
          from => from.group === routeGroup &&
                  from.kind === routeKind &&
                  from.namespace === sourceNamespace
        );
        const permitsTo = grant.spec.to.some(
          to => to.group === targetGroup &&
                to.kind === targetKind &&
                (!to.name || to.name === ref.name)
        );
        return permitsFrom && permitsTo;
      });

    if (isAuthorized) {
      validRefs.push(ref);
    } else {
      refNotPermitted = true;
    }
  }

  return { validRefs, refNotPermitted };
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Enforce ReferenceGrant Invariants for Cross-Namespace Routing in Kubernetes Gateway API v1.2

Enforce ReferenceGrant Invariants for Cross-Namespace Routing in Kubernetes Gateway API v1.2 defines an industrial-grade behavioral standard for devops engineering. Enforces strict validation of explicit ReferenceGrant resources when Gateway API routes (HTTPRoute, GRPCRoute, TLSRoute, TCPRoute, UDPRoute) traverse namespace boundaries to attach to Gateways or forward traffic to backend Services. Without explicit bidirectional trust established by a ReferenceGrant in the target namespace, controllers and reconcilers must immediately fail validation, drop unauthorized backend refs, and emit ResolvedRefs: False status conditions to eliminate cross-namespace route hijacking vulnerabilities in multi-tenant environments. 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 Explicit ReferenceGrant Mutual 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 DriftImplicit Cross-Namespace Route Forwarding Without Explicit ReferenceGrant Mutual 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 declare a ReferenceGrant resource inside the target (backend or gateway) namespace whenever a Route in a foreign namespace references resources across namespace boundaries.

Engineers MUST ALWAYS declare a ReferenceGrant resource inside the target (backend or gateway) namespace whenever a Route in a foreign namespace references resources across namespace 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.
2

Engineers MUST NOT permit wildcards ('*') in the 'from.namespace' field of a ReferenceGrant in multi-tenant clusters, requiring explicit namespace identifiers to prevent cross-tenant hijacking.

Engineers MUST NOT permit wildcards ('*') in the 'from.namespace' field of a ReferenceGrant in multi-tenant clusters, requiring explicit namespace identifiers to prevent cross-tenant hijacking.

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

Controllers and reconcilers MUST reject cross-namespace route references and set Route condition 'ResolvedRefs' to 'False' with reason 'RefNotPermitted' whenever an exact ReferenceGrant match is missing.

Controllers and reconcilers MUST reject cross-namespace route references and set Route condition 'ResolvedRefs' to 'False' with reason 'RefNotPermitted' whenever an exact ReferenceGrant match is missing.

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

Code MUST strictly evaluate both 'from' (group, kind, namespace) and 'to' (group, kind, name) matching tuples prior to programming data-plane forwarding state.

Code MUST strictly evaluate both 'from' (group, kind, namespace) and 'to' (group, kind, name) matching tuples prior to programming data-plane forwarding state.

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

Reconciliation logic MUST purge active forwarding rules and emit Kubernetes Warning events immediately if a supporting ReferenceGrant is mutated, deleted, or unbinds target endpoints.

Reconciliation logic MUST purge active forwarding rules and emit Kubernetes Warning events immediately if a supporting ReferenceGrant is mutated, deleted, or unbinds target endpoints.

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

Services MUST remain non-addressable from external namespaces when backendRef specifies a distinct 'namespace' unless a matching ReferenceGrant explicitly white-lists the Route kind and origin namespace.

Services MUST remain non-addressable from external namespaces when backendRef specifies a distinct 'namespace' unless a matching ReferenceGrant explicitly white-lists the Route kind and origin 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Enforce ReferenceGrant Invariants for Cross-Namespace Routing in Kubernetes Gateway API v1.2 critical for AI coding assistants?

Enforces strict validation of explicit ReferenceGrant resources when Gateway API routes (HTTPRoute, GRPCRoute, TLSRoute, TCPRoute, UDPRoute) traverse namespace boundaries to attach to Gateways or forward traffic to backend Services. Without explicit bidirectional trust established by a ReferenceGrant in the target namespace, controllers and reconcilers must immediately fail validation, drop unauthorized backend refs, and emit ResolvedRefs: False status conditions to eliminate cross-namespace route hijacking vulnerabilities in multi-tenant environments. 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 Explicit ReferenceGrant Mutual 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