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

Kubernetes Gateway API v1.2 Cross-Namespace ReferenceGrant Invariants

Enforces zero-trust cross-namespace routing contracts between Gateway API v1.2 HTTPRoutes and target backend Services or parent Gateways. Mandates explicit, least-privilege ReferenceGrant resources in target namespaces to prevent unauthorized cross-tenant route-hijacking and traffic intercept attacks. Prohibits wildcard namespace trust, dangling references, and implicit cross-namespace backend bindings.

Prohibited Anti-Pattern: Unvalidated Cross-Namespace HTTPRoute Backends Lacking Explicit, Least-Privilege ReferenceGrants

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kubernetes Gateway API v1.2 Cross-Namespace ReferenceGrant Invariants - Enforces zero-trust cross-namespace routing contracts between Gateway API v1.2 HTTPRoutes and target backend Services or parent Gateways. Mandates explicit, least-privilege ReferenceGrant resources in target namespaces to prevent unauthorized cross-tenant route-hijacking and traffic intercept attacks. Prohibits wildcard namespace trust, dangling references, and implicit cross-namespace backend bindings.
globs: deploy/**/*.yaml, k8s/**/*.yaml, charts/**/templates/*.yaml, infra/**/*.ts, cdk8s/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/k8s-gateway-v1-2-referencegrant-cross-namespace-invariants"
---

# Kubernetes Gateway API v1.2 Cross-Namespace ReferenceGrant Invariants

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unvalidated Cross-Namespace HTTPRoute Backends Lacking Explicit, Least-Privilege ReferenceGrants

## System Constraints
You are a Principal Infrastructure & Security Architect enforcing strict Kubernetes Gateway API v1.2 ReferenceGrant invariants. In a multi-tenant cluster, cross-namespace references between Gateways, HTTPRoutes, and Services represent high-risk security boundaries vulnerable to tenant hijacking and traffic interception. You must mandate that every cross-namespace backendRef is authorized by an explicit, scoped ReferenceGrant (gateway.networking.k8s.io/v1beta1) residing in the target resource's namespace. Reject any configuration that relies on global wildcards, unvetted parentRef namespaces, or missing ReferenceGrant resources.

## Strict Guidelines
- Engineers MUST ALWAYS deploy a ReferenceGrant in the destination namespace whenever an HTTPRoute references a Service or backend in a different namespace.
- Engineers MUST NOT configure ReferenceGrant resources with wildcard '*' namespaces in the 'from' array or wildcard names in the 'to' array.
- HTTPRoute backendRefs targeting a remote namespace MUST explicitly match the authorized 'group', 'kind', and 'name' specified in the destination ReferenceGrant.
- Parent Gateways MUST configure 'allowedRoutes.namespaces' with 'FromNamespaces.Selector' or explicit namespace lists, never permitting unbounded cross-namespace route attachments without authorization.
- CI/CD validation pipelines MUST statically verify that any HTTPRoute declaring a foreign 'parentRef.namespace' or 'backendRef.namespace' has a corresponding ReferenceGrant committed in the identical release bundle.
- Engineers MUST verify that Gateway controllers emit 'ResolvedRefs: True' conditions on HTTPRoutes and alert immediately when 'ResolvedRefs: False' occurs due to missing ReferenceGrants.

## Bad vs Good Implementations
### CDK8s Cross-Namespace Route Authorization Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The HTTPRoute in namespace 'tenant-a' attempts to route traffic to 'auth-service' in namespace 'shared-services' across namespace boundaries without defining a ReferenceGrant in 'shared-services'. In strict Gateway API v1.2 implementations, this causes traffic blackholing and exposes the application to route-squatting attacks.
```typescript
import { Construct } from 'constructs';
import { ApiObject } from 'cdk8s';

export class TenantRouteStack extends Construct {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    // CRITICAL SECURITY FLAW: Cross-namespace backend reference without
    // a corresponding ReferenceGrant in the 'shared-services' namespace.
    // In Gateway API v1.2, this will silently fail with ResolvedRefs: False,
    // or allow route-squatting if an insecure gateway controller is misconfigured.
    new ApiObject(this, 'TenantHttpRoute', {
      apiVersion: 'gateway.networking.k8s.io/v1',
      kind: 'HTTPRoute',
      metadata: {
        name: 'tenant-app-route',
        namespace: 'tenant-a',
      },
      spec: {
        parentRefs: [{
          name: 'shared-gateway',
          namespace: 'gateway-infra',
        }],
        rules: [{
          matches: [{ path: { type: 'PathPrefix', value: '/api/v1/auth' } }],
          backendRefs: [{
            name: 'auth-service',
            namespace: 'shared-services',
            port: 8080,
          }],
        }],
      },
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: A scoped ReferenceGrant is explicitly provisioned in 'shared-services' authorizing only HTTPRoutes in namespace 'tenant-a' to bind specifically to 'auth-service'. This satisfies zero-trust invariants and ensures predictable status conditions ('ResolvedRefs: True') across multi-tenant clusters.
```typescript
import { Construct } from 'constructs';
import { ApiObject } from 'cdk8s';

export class SecureCrossNamespaceRoutingStack extends Construct {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    // 1. Explicit ReferenceGrant in target namespace granting least-privilege access
    new ApiObject(this, 'AuthServiceReferenceGrant', {
      apiVersion: 'gateway.networking.k8s.io/v1beta1',
      kind: 'ReferenceGrant',
      metadata: {
        name: 'allow-tenant-a-auth-access',
        namespace: 'shared-services',
      },
      spec: {
        from: [{
          group: 'gateway.networking.k8s.io',
          kind: 'HTTPRoute',
          namespace: 'tenant-a',
        }],
        to: [{
          group: '',
          kind: 'Service',
          name: 'auth-service',
        }],
      },
    });

    // 2. HTTPRoute in source namespace consuming authorized backend
    new ApiObject(this, 'TenantHttpRoute', {
      apiVersion: 'gateway.networking.k8s.io/v1',
      kind: 'HTTPRoute',
      metadata: {
        name: 'tenant-app-route',
        namespace: 'tenant-a',
      },
      spec: {
        parentRefs: [{
          name: 'shared-gateway',
          namespace: 'gateway-infra',
        }],
        rules: [{
          matches: [{ path: { type: 'PathPrefix', value: '/api/v1/auth' } }],
          backendRefs: [{
            group: '',
            kind: 'Service',
            name: 'auth-service',
            namespace: 'shared-services',
            port: 8080,
          }],
        }],
      },
    });
  }
}
```

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 Cross-Namespace ReferenceGrant Invariants

Kubernetes Gateway API v1.2 Cross-Namespace ReferenceGrant Invariants defines an industrial-grade behavioral standard for devops engineering. Enforces zero-trust cross-namespace routing contracts between Gateway API v1.2 HTTPRoutes and target backend Services or parent Gateways. Mandates explicit, least-privilege ReferenceGrant resources in target namespaces to prevent unauthorized cross-tenant route-hijacking and traffic intercept attacks. Prohibits wildcard namespace trust, dangling references, and implicit cross-namespace backend bindings. 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 HTTPRoute Backends Lacking Explicit, Least-Privilege 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 DriftUnvalidated Cross-Namespace HTTPRoute Backends Lacking Explicit, Least-Privilege 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 destination namespace whenever an HTTPRoute references a Service or backend in a different namespace.

Engineers MUST ALWAYS deploy a ReferenceGrant in the destination namespace whenever an HTTPRoute references a Service or backend in a different 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 ReferenceGrant resources with wildcard '*' namespaces in the 'from' array or wildcard names in the 'to' array.

Engineers MUST NOT configure ReferenceGrant resources with wildcard '*' namespaces in the 'from' array or wildcard names in the 'to' array.

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

HTTPRoute backendRefs targeting a remote namespace MUST explicitly match the authorized 'group', 'kind', and 'name' specified in the destination ReferenceGrant.

HTTPRoute backendRefs targeting a remote namespace MUST explicitly match the authorized 'group', 'kind', and 'name' specified in the destination 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.
4

Parent Gateways MUST configure 'allowedRoutes.namespaces' with 'FromNamespaces.Selector' or explicit namespace lists, never permitting unbounded cross-namespace route attachments without authorization.

Parent Gateways MUST configure 'allowedRoutes.namespaces' with 'FromNamespaces.Selector' or explicit namespace lists, never permitting unbounded cross-namespace route attachments without authorization.

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

CI/CD validation pipelines MUST statically verify that any HTTPRoute declaring a foreign 'parentRef.namespace' or 'backendRef.namespace' has a corresponding ReferenceGrant committed in the identical release bundle.

CI/CD validation pipelines MUST statically verify that any HTTPRoute declaring a foreign 'parentRef.namespace' or 'backendRef.namespace' has a corresponding ReferenceGrant committed in the identical release bundle.

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

Engineers MUST verify that Gateway controllers emit 'ResolvedRefs

Engineers MUST verify that Gateway controllers emit 'ResolvedRefs: True' conditions on HTTPRoutes and alert immediately when 'ResolvedRefs: False' occurs due to missing ReferenceGrants.

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

Enforces zero-trust cross-namespace routing contracts between Gateway API v1.2 HTTPRoutes and target backend Services or parent Gateways. Mandates explicit, least-privilege ReferenceGrant resources in target namespaces to prevent unauthorized cross-tenant route-hijacking and traffic intercept attacks. Prohibits wildcard namespace trust, dangling references, and implicit cross-namespace backend bindings. 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 HTTPRoute Backends Lacking Explicit, Least-Privilege 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