This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: envoy-extauthz-rebac-circuit-breaker-standard

Envoy ext_authz Distributed ReBAC Dynamic Circuit-Breaking Standard

Enforces strict deadline fencing, local bounded fallback caching, and dynamic circuit breaking for Envoy external authorization (ext_authz) services interfacing with distributed ReBAC (Zanzibar-style) graph backends. Prevents unbounded graph expansion latency from cascading to the ingress edge by mandating fail-closed deterministic timeouts and concurrency isolation. Guarantees ingress edge resilience during high-cardinality relationship traversals without sacrificing security posture.

Prohibited Anti-Pattern: Unbounded ReBAC Graph Traversal Without Edge Deadline Fencing and Fail-Closed Circuit Breaking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Envoy ext_authz Distributed ReBAC Dynamic Circuit-Breaking Standard - Enforces strict deadline fencing, local bounded fallback caching, and dynamic circuit breaking for Envoy external authorization (ext_authz) services interfacing with distributed ReBAC (Zanzibar-style) graph backends. Prevents unbounded graph expansion latency from cascading to the ingress edge by mandating fail-closed deterministic timeouts and concurrency isolation. Guarantees ingress edge resilience during high-cardinality relationship traversals without sacrificing security posture.
globs: src/authz/**/*.{ts,tsx}, src/gateway/**/*.{ts,tsx}, src/infrastructure/envoy/**/*.{ts,tsx}, src/server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/envoy-extauthz-rebac-circuit-breaker-standard"
---

# Envoy ext_authz Distributed ReBAC Dynamic Circuit-Breaking Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded ReBAC Graph Traversal Without Edge Deadline Fencing and Fail-Closed Circuit Breaking

## System Constraints
You are a Principal Software Architect specializing in zero-trust ingress security, Envoy ext_authz integration, and distributed ReBAC graph architectures (Google Zanzibar/SpiceDB/OpenFGA). Enforce deterministic gRPC deadline fencing, fail-closed dynamic circuit breaking, and bounded local caching on all ext_authz evaluation pipelines.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict gRPC deadline propagation (grpc-timeout) on all Envoy ext_authz Check handlers, rejecting execution if remaining budget is below the minimum threshold (e.g., < 15ms).
- Engineers MUST NEVER configure Envoy ext_authz with 'failure_mode_allow: true' on security-critical authorization boundaries; all edge-level failovers MUST default to fail-closed (DENIED).
- Services MUST implement dynamic circuit breakers that trip on authorization tail-latency (P99 > threshold) or elevated upstream error rates, short-circuiting expensive recursive graph evaluations directly at the ext_authz process boundary.
- Code MUST isolate high-cardinality ReBAC check requests using bounded concurrency pools (bulkheads) to prevent deep graph union/intersection computations from exhausting ingress worker threads.
- Components MUST query a local in-memory L1 cache with cryptographic cache keys (incorporating user token subject, relation, object ID, and consistency zookie/token) with low TTLs (< 5 seconds) before dispatching to remote ReBAC engines.
- Services MUST return deterministic Envoy ext_authz CheckResponse status codes (PERMISSION_DENIED with explicit custom response headers) instead of hanging or returning raw 5xx transport errors to prevent edge worker starvation.

## Bad vs Good Implementations
### Envoy ext_authz ReBAC gRPC Service Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The check handler does not respect gRPC deadlines, lacks a circuit breaker, performs no local caching of relationship evaluation results, and permits unconstrained graph traversals. Under tail-latency spikes or graph partition loops, Envoy worker threads back up waiting on ext_authz, saturating connection pools and failing open or taking down the entire ingress gateway.
```typescript
import { ServerUnaryCall, sendUnaryData, status } from '@grpc/grpc-js';
import { CheckRequest, CheckResponse } from './generated/envoy/service/auth/v3/auth_pb';
import { RebacClient } from './rebac-client';

const rebacClient = new RebacClient();

// ANTI-PATTERN: Unbounded traversal, no deadline awareness, no circuit breaker,
// no local caching, and leaks internal 500s directly causing edge cascading failure.
export async function check(
  call: ServerUnaryCall<CheckRequest, CheckResponse>,
  callback: sendUnaryData<CheckResponse>
): Promise<void> {
  try {
    const req = call.request;
    const subject = req.getAttributes()?.getRequest()?.getHttp()?.getHeadersMap().get('x-user-id');
    const resource = req.getAttributes()?.getRequest()?.getHttp()?.getPath();

    // Unbounded remote call into Zanzibar/ReBAC engine during deep graph traversal
    const isAllowed = await rebacClient.checkRelationship({
      subject: `user:${subject}`,
      relation: 'viewer',
      object: `document:${resource}`
    });

    const response = new CheckResponse();
    if (isAllowed) {
      response.setStatus({ code: status.OK });
    } else {
      response.setStatus({ code: status.PERMISSION_DENIED });
    }
    callback(null, response);
  } catch (err) {
    // Cascading failure: Returns gRPC INTERNAL, crashing ingress workers under load
    callback({ code: status.INTERNAL, message: (err as Error).message });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements deterministic deadline budgeting, bounded short-lived L1 caching with consistency tokens, and a fast-tripping dynamic circuit breaker. If the ReBAC engine experiences tail-latency spikes due to high-cardinality graph traversals, the handler short-circuits gracefully, adhering strictly to fail-closed isolation without crashing Envoy ingress workers.
```typescript
import { ServerUnaryCall, sendUnaryData, status } from '@grpc/grpc-js';
import { CheckRequest, CheckResponse, OkHttpResponse, DeniedHttpResponse } from './generated/envoy/service/auth/v3/auth_pb';
import { HttpStatus } from './generated/envoy/type/v3/http_status_pb';
import { RebacClient } from './rebac-client';
import { CircuitBreaker } from './resilience/circuit-breaker';
import { BoundedLruCache } from './cache/lru-cache';

const rebacClient = new RebacClient({ endpoint: process.env.REBAC_GRPC_ENDPOINT! });
const localCache = new BoundedLruCache<boolean>({ maxEntries: 50_000, ttlMs: 3_000 });
const breaker = new CircuitBreaker({
  failureThresholdPercent: 30,
  latencyThresholdMs: 45,
  halfOpenTimeoutMs: 5_000
});

const MIN_REMAINING_DEADLINE_MS = 15;

export async function check(
  call: ServerUnaryCall<CheckRequest, CheckResponse>,
  callback: sendUnaryData<CheckResponse>
): Promise<void> {
  const startTime = Date.now();
  const deadline = call.getDeadline();
  const remainingMs = typeof deadline === 'number' ? deadline - startTime : Infinity;

  // Fail-closed deterministic fencing if deadline budget is depleted
  if (remainingMs < MIN_REMAINING_DEADLINE_MS) {
    return callback(null, buildDeniedResponse(HttpStatus.StatusCode.GatewayTimeout, 'DeadlineExceeded'));
  }

  const headers = call.request.getAttributes()?.getRequest()?.getHttp()?.getHeadersMap();
  const subject = headers?.get('x-user-id');
  const resource = call.request.getAttributes()?.getRequest()?.getHttp()?.getPath();
  const consistencyToken = headers?.get('x-rebac-zookie') ?? 'latest';

  if (!subject || !resource) {
    return callback(null, buildDeniedResponse(HttpStatus.StatusCode.Unauthorized, 'MissingIdentityHeaders'));
  }

  const cacheKey = `rebac:v1:${subject}:viewer:${resource}:${consistencyToken}`;
  const cachedDecision = localCache.get(cacheKey);
  if (cachedDecision !== undefined) {
    return callback(null, cachedDecision ? buildOkResponse() : buildDeniedResponse(HttpStatus.StatusCode.Forbidden, 'CachedDenial'));
  }

  // Dynamic circuit breaker isolating edge ingress from high-cardinality graph expansion
  if (!breaker.canExecute()) {
    return callback(null, buildDeniedResponse(HttpStatus.StatusCode.ServiceUnavailable, 'AuthzCircuitOpen'));
  }

  try {
    const checkBudgetMs = Math.min(remainingMs - 5, 50);
    const isAllowed = await Promise.race([
      rebacClient.checkRelationship({
        subject: `user:${subject}`,
        relation: 'viewer',
        object: `document:${resource}`,
        consistencyToken
      }),
      new Promise<never>((_, reject) =>
        setTimeout(() => reject(new Error('ReBAC_Timeout')), checkBudgetMs)
      )
    ]);

    const elapsed = Date.now() - startTime;
    breaker.recordSuccess(elapsed);
    localCache.set(cacheKey, isAllowed);

    if (isAllowed) {
      callback(null, buildOkResponse());
    } else {
      callback(null, buildDeniedResponse(HttpStatus.StatusCode.Forbidden, 'RebacRejected'));
    }
  } catch (err) {
    breaker.recordFailure();
    // Invariant: Strictly fail-closed with structured ext_authz response; never leak internal gRPC exceptions
    callback(null, buildDeniedResponse(HttpStatus.StatusCode.Forbidden, 'FailClosedAuthzError'));
  }
}

function buildOkResponse(): CheckResponse {
  const response = new CheckResponse();
  response.setStatus({ code: status.OK });
  response.setOkResponse(new OkHttpResponse());
  return response;
}

function buildDeniedResponse(httpCode: HttpStatus.StatusCode, reason: string): CheckResponse {
  const response = new CheckResponse();
  response.setStatus({ code: status.PERMISSION_DENIED });
  const denied = new DeniedHttpResponse();
  denied.setStatus({ code: httpCode });
  denied.setBody(`Access Denied: ${reason}`);
  response.setDeniedResponse(denied);
  return response;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Envoy ext_authz Distributed ReBAC Dynamic Circuit-Breaking Standard

Envoy ext_authz Distributed ReBAC Dynamic Circuit-Breaking Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict deadline fencing, local bounded fallback caching, and dynamic circuit breaking for Envoy external authorization (ext_authz) services interfacing with distributed ReBAC (Zanzibar-style) graph backends. Prevents unbounded graph expansion latency from cascading to the ingress edge by mandating fail-closed deterministic timeouts and concurrency isolation. Guarantees ingress edge resilience during high-cardinality relationship traversals without sacrificing security posture. 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: Unbounded ReBAC Graph Traversal Without Edge Deadline Fencing and Fail-Closed Circuit Breaking 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 DriftUnbounded ReBAC Graph Traversal Without Edge Deadline Fencing and Fail-Closed Circuit BreakingCritical
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 enforce strict gRPC deadline propagation (grpc-timeout) on all Envoy ext_authz Check handlers, rejecting execution if remaining budget is below the minimum threshold (e.g., < 15ms).

Engineers MUST ALWAYS enforce strict gRPC deadline propagation (grpc-timeout) on all Envoy ext_authz Check handlers, rejecting execution if remaining budget is below the minimum threshold (e.g., < 15ms).

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 NEVER configure Envoy ext_authz with 'failure_mode_allow

Engineers MUST NEVER configure Envoy ext_authz with 'failure_mode_allow: true' on security-critical authorization boundaries; all edge-level failovers MUST default to fail-closed (DENIED).

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 implement dynamic circuit breakers that trip on authorization tail-latency (P99 > threshold) or elevated upstream error rates, short-circuiting expensive recursive graph evaluations directly at the ext_authz process boundary.

Services MUST implement dynamic circuit breakers that trip on authorization tail-latency (P99 > threshold) or elevated upstream error rates, short-circuiting expensive recursive graph evaluations directly at the ext_authz process boundary.

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 isolate high-cardinality ReBAC check requests using bounded concurrency pools (bulkheads) to prevent deep graph union/intersection computations from exhausting ingress worker threads.

Code MUST isolate high-cardinality ReBAC check requests using bounded concurrency pools (bulkheads) to prevent deep graph union/intersection computations from exhausting ingress worker threads.

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 MUST query a local in-memory L1 cache with cryptographic cache keys (incorporating user token subject, relation, object ID, and consistency zookie/token) with low TTLs (< 5 seconds) before dispatching to remote ReBAC engines.

Components MUST query a local in-memory L1 cache with cryptographic cache keys (incorporating user token subject, relation, object ID, and consistency zookie/token) with low TTLs (< 5 seconds) before dispatching to remote ReBAC engines.

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 return deterministic Envoy ext_authz CheckResponse status codes (PERMISSION_DENIED with explicit custom response headers) instead of hanging or returning raw 5xx transport errors to prevent edge worker starvation.

Services MUST return deterministic Envoy ext_authz CheckResponse status codes (PERMISSION_DENIED with explicit custom response headers) instead of hanging or returning raw 5xx transport errors to prevent edge worker starvation.

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 Envoy ext_authz Distributed ReBAC Dynamic Circuit-Breaking Standard critical for AI coding assistants?

Enforces strict deadline fencing, local bounded fallback caching, and dynamic circuit breaking for Envoy external authorization (ext_authz) services interfacing with distributed ReBAC (Zanzibar-style) graph backends. Prevents unbounded graph expansion latency from cascading to the ingress edge by mandating fail-closed deterministic timeouts and concurrency isolation. Guarantees ingress edge resilience during high-cardinality relationship traversals without sacrificing security posture. 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 (Unbounded ReBAC Graph Traversal Without Edge Deadline Fencing and Fail-Closed Circuit Breaking) 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

Envoy