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

Kubernetes Gateway API Cross-Namespace ReferenceGrant Security Invariant

Enforces strict multi-tenant boundary isolation across Kubernetes Gateway API resources by requiring explicit, minimal ReferenceGrant declarations for any cross-namespace route-to-service attachments. Prevents unauthorized tenant route hijacking, cross-namespace backend binding leaks, and service mesh boundary bypasses in multi-tenant clusters. Ensures declarative infrastructure pipelines automatically validate bidirectional trust contracts prior to deployment.

Prohibited Anti-Pattern: Implicit Cross-Namespace Route Attachment Lacking Target-Namespace ReferenceGrant Validation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kubernetes Gateway API Cross-Namespace ReferenceGrant Security Invariant - Enforces strict multi-tenant boundary isolation across Kubernetes Gateway API resources by requiring explicit, minimal ReferenceGrant declarations for any cross-namespace route-to-service attachments. Prevents unauthorized tenant route hijacking, cross-namespace backend binding leaks, and service mesh boundary bypasses in multi-tenant clusters. Ensures declarative infrastructure pipelines automatically validate bidirectional trust contracts prior to deployment.
globs: k8s/**/*.yaml, k8s/**/*.yml, deploy/**/*.yaml, deploy/**/*.yml, infra/**/*.ts, infra/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/k8s-gateway-cross-namespace-referencegrant-invariant"
---

# Kubernetes Gateway API Cross-Namespace ReferenceGrant Security Invariant

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

## System Constraints
You are a Principal Platform Security Engineer enforcing Kubernetes Gateway API Cross-Namespace ReferenceGrant Security Invariants. Mandate strict multi-tenant perimeter controls where any HTTPRoute, GRPCRoute, or Gateway cross-namespace reference MUST be met with an exact, minimally scoped ReferenceGrant in the destination namespace. Reject any manifests or IaC templates attempting cross-namespace routing without bidirectional cryptographic or RBAC-equivalent ReferenceGrant assertions. Ensure namespace autonomy is strictly respected: tenant namespaces cannot bind shared mesh services or common ingress gateways without an affirmative ReferenceGrant explicitly published by the resource owner.

## Strict Guidelines
- Engineers MUST ALWAYS create a ReferenceGrant in the target/backend namespace whenever an HTTPRoute or GRPCRoute references a Service across namespace boundaries.
- Engineers MUST NOT configure wildcards ('*') in ReferenceGrant 'from.namespace' or 'to.name' fields when exposing sensitive or internal services to other tenants.
- Engineers MUST ALWAYS scope ReferenceGrant 'from' specs to the exact Group ('gateway.networking.k8s.io'), Kind ('HTTPRoute' or 'GRPCRoute'), and source Namespace of the authorized client.
- Services MUST remain non-routable across namespaces by default; static analysis and admission controllers MUST fail deployments if cross-namespace routes lack corresponding ReferenceGrant manifests.
- Gateways MUST NEVER permit unrestricted route attachments; Gateway listeners MUST specify 'allowedRoutes.namespaces.from: Selector' with precise namespace labeling rather than 'from: All' unless explicitly intended for a public ingress DMZ.

## Bad vs Good Implementations
### Cross-Namespace Backend Binding via ReferenceGrant Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The HTTPRoute in namespace 'tenant-a' attempts to route traffic directly to 'telemetry-backend-service' in namespace 'core-services'. Without a ReferenceGrant created by the owner of 'core-services', this violates Gateway API multi-tenant security guarantees. In compliant implementations this route is rejected or dropped, causing silent production outages; in misconfigured environments, it permits unauthorized route hijacking.
```yaml
# INSECURE: Tenant attempts cross-namespace route to core-services backend without target authorization
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: tenant-analytics-route
  namespace: tenant-a
spec:
  parentRefs:
    - name: shared-gateway
      namespace: ingress-infra
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /api/v1/analytics
      backendRefs:
        - name: telemetry-backend-service
          namespace: core-services # Flaw: core-services has not published a ReferenceGrant; silently drops or bypasses tenancy
          port: 8080
```

#### Production Standard (Correct)
> **Standard**: The resource owner in 'core-services' declares an explicit ReferenceGrant targeting only the HTTPRoute from 'tenant-a' and strictly scoping access to 'telemetry-backend-service'. This creates a verified bidirectional handshake enforcing multi-tenant isolation.
```yaml
# SECURE: Target namespace explicitly issues a minimally scoped ReferenceGrant allowing tenant-a route binding
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata:
  name: allow-tenant-a-telemetry-binding
  namespace: core-services
spec:
  from:
    - group: gateway.networking.k8s.io
      kind: HTTPRoute
      namespace: tenant-a
  to:
    - group: ""
      kind: Service
      name: telemetry-backend-service
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: tenant-analytics-route
  namespace: tenant-a
spec:
  parentRefs:
    - name: shared-gateway
      namespace: ingress-infra
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /api/v1/analytics
      backendRefs:
        - name: telemetry-backend-service
          namespace: core-services
          port: 8080
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kubernetes Gateway API Cross-Namespace ReferenceGrant Security Invariant

Kubernetes Gateway API Cross-Namespace ReferenceGrant Security Invariant defines an industrial-grade behavioral standard for devops engineering. Enforces strict multi-tenant boundary isolation across Kubernetes Gateway API resources by requiring explicit, minimal ReferenceGrant declarations for any cross-namespace route-to-service attachments. Prevents unauthorized tenant route hijacking, cross-namespace backend binding leaks, and service mesh boundary bypasses in multi-tenant clusters. Ensures declarative infrastructure pipelines automatically validate bidirectional trust contracts prior to deployment. 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 Attachment Lacking 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 Attachment Lacking 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 create a ReferenceGrant in the target/backend namespace whenever an HTTPRoute or GRPCRoute references a Service across namespace boundaries.

Engineers MUST ALWAYS create a ReferenceGrant in the target/backend namespace whenever an HTTPRoute or GRPCRoute references a Service 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 configure wildcards ('*') in ReferenceGrant 'from.namespace' or 'to.name' fields when exposing sensitive or internal services to other tenants.

Engineers MUST NOT configure wildcards ('*') in ReferenceGrant 'from.namespace' or 'to.name' fields when exposing sensitive or internal services to other tenants.

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 ALWAYS scope ReferenceGrant 'from' specs to the exact Group ('gateway.networking.k8s.io'), Kind ('HTTPRoute' or 'GRPCRoute'), and source Namespace of the authorized client.

Engineers MUST ALWAYS scope ReferenceGrant 'from' specs to the exact Group ('gateway.networking.k8s.io'), Kind ('HTTPRoute' or 'GRPCRoute'), and source Namespace of the authorized client.

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 remain non-routable across namespaces by default

Services MUST remain non-routable across namespaces by default; static analysis and admission controllers MUST fail deployments if cross-namespace routes lack corresponding ReferenceGrant manifests.

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

Gateways MUST NEVER permit unrestricted route attachments

Gateways MUST NEVER permit unrestricted route attachments; Gateway listeners MUST specify 'allowedRoutes.namespaces.from: Selector' with precise namespace labeling rather than 'from: All' unless explicitly intended for a public ingress DMZ.

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

Enforces strict multi-tenant boundary isolation across Kubernetes Gateway API resources by requiring explicit, minimal ReferenceGrant declarations for any cross-namespace route-to-service attachments. Prevents unauthorized tenant route hijacking, cross-namespace backend binding leaks, and service mesh boundary bypasses in multi-tenant clusters. Ensures declarative infrastructure pipelines automatically validate bidirectional trust contracts prior to deployment. 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 Attachment Lacking 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