This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: envoy-gateway-extauthz-monotonic-budgeting-fail-closed

Envoy Gateway 1.2 ExtAuthz Monotonic Budgeting and Fail-Closed Boundary

Mandates strict fail-closed authorization posture and monotonic deadline budgeting for External Authorization (ExtAuthz) filters in Envoy Gateway 1.2. Prevents worker thread saturation, denial-of-service, and unauthorized bypass by enforcing explicit request timeouts, connection pool circuit breaking, and failOpen=false invariants.

Prohibited Anti-Pattern: Unbounded ExtAuthz Timeouts and Permissive Fail-Open Fallbacks Leading to Proxy Thread Starvation and Auth Bypass

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Envoy Gateway 1.2 ExtAuthz Monotonic Budgeting and Fail-Closed Boundary - Mandates strict fail-closed authorization posture and monotonic deadline budgeting for External Authorization (ExtAuthz) filters in Envoy Gateway 1.2. Prevents worker thread saturation, denial-of-service, and unauthorized bypass by enforcing explicit request timeouts, connection pool circuit breaking, and failOpen=false invariants.
globs: **/k8s/**/*.yaml, **/gateway/**/*.yaml, **/securitypolicy*.yaml, **/envoyproxy*.yaml, src/middleware/auth/**/*.{ts,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/envoy-gateway-extauthz-monotonic-budgeting-fail-closed"
---

# Envoy Gateway 1.2 ExtAuthz Monotonic Budgeting and Fail-Closed Boundary

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded ExtAuthz Timeouts and Permissive Fail-Open Fallbacks Leading to Proxy Thread Starvation and Auth Bypass

## System Constraints
You are a Principal Security and Infrastructure Architect enforcing Envoy Gateway 1.2 external authorization invariants. You must ensure that all ExtAuthz integrations enforce monotonic timeout budgeting, resilient circuit breaking, and absolute fail-closed boundaries (failOpen: false) to prevent proxy worker thread exhaustion and unauthorized route transit.

## Strict Guidelines
- Engineers MUST ALWAYS set 'failOpen: false' within Envoy Gateway 'SecurityPolicy' resources referencing external authorization providers.
- Engineers MUST ALWAYS define an explicit, sub-second timeout on ExtAuthz gRPC/HTTP services that is strictly less than 20% of the overall downstream client request deadline.
- Engineers MUST configure explicit circuit breaking via 'BackendTrafficPolicy' or ExtAuthz cluster settings to limit 'maxConnections', 'maxPendingRequests', and 'consecutive5xxErrors' targeting the ExtAuthz daemon.
- ExtAuthz service handlers MUST extract downstream incoming deadlines (e.g., 'grpc-timeout' or context deadlines) and monotonically propagate reduced deadlines to upstream identity providers.
- Engineers MUST NOT rely on default Envoy timeout values (which default to non-zero high thresholds or indefinite streaming) for external authorization calls.
- Services MUST emit immediate HTTP 403 Forbidden or 504 Gateway Timeout responses upon authorization timeout rather than hanging worker thread contexts.

## Bad vs Good Implementations
### Envoy Gateway 1.2 SecurityPolicy and BackendTrafficPolicy ExtAuthz Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Setting 'failOpen: true' allows unauthenticated traffic to reach backend services if ExtAuthz fails or degrades. Missing explicit timeouts and circuit breaker constraints allows slow auth calls to monopolize Envoy worker threads, leading to cascading cluster-wide DoS.
```yaml
# INSECURE: Default failOpen allows unauthorized bypass during outage,
# and unconstrained timeout/circuit-breakers starve Envoy worker threads.
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: SecurityPolicy
metadata:
  name: default-extauth-policy
  namespace: production
spec:
  targetRef:
    group: gateway.networking.k8s.io
    kind: HTTPRoute
    name: protected-api
  extAuth:
    failOpen: true # CRITICAL: Bypasses security checks on auth service error/timeout
    grpc:
      backendRefs:
        - name: extauth-service
          port: 9001
      # Missing explicit timeout: defaults to cluster default (causing worker pile-up)
```

#### Production Standard (Correct)
> **Standard**: Enforces 'failOpen: false' to ensure no unauthenticated requests bypass the gateway. Binds the ExtAuthz call to an explicit 250ms timeout and bounds connection queues via BackendTrafficPolicy circuit breakers, protecting proxy worker threads from saturation.
```yaml
# PRODUCTION SECURE: Fail-closed boundary, strict monotonic timeout,
# and explicit circuit breaking limiting worker thread queueing.
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: SecurityPolicy
metadata:
  name: strict-extauth-policy
  namespace: production
spec:
  targetRef:
    group: gateway.networking.k8s.io
    kind: HTTPRoute
    name: protected-api
  extAuth:
    failOpen: false # Enforces fail-closed: drops unauthorized traffic on error
    headersToExtAuth:
      - x-request-id
      - authorization
    grpc:
      backendRefs:
        - name: extauth-service
          port: 9001
    # Monotonic bounded budget: auth call terminates in 250ms max
    timeout: 250ms
---
apiVersion: gateway.envoyproxy.io/v1alpha1
kind: BackendTrafficPolicy
metadata:
  name: extauth-circuit-breaker
  namespace: production
spec:
  targetRef:
    group: ""
    kind: Service
    name: extauth-service
  circuitBreaker:
    maxConnections: 1024
    maxPendingRequests: 100
    maxRequests: 2048
  faultInjection: null
```

### ExtAuthz Node.js/TypeScript gRPC Handler Monotonic Deadline Budgeting

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The gRPC server ignores the incoming deadline, executes an unbounded fetch call to an external service, and fails open by returning OK on exceptions.
```typescript
// INSECURE: Ignores upstream context deadline and launches unbudgeted auth query
import * as grpc from '@grpc/grpc-js';

export const check = async (call: grpc.ServerUnaryCall<any, any>, callback: grpc.sendUnaryData<any>) => {
  try {
    // Anti-pattern: No timeout or deadline propagation to the identity provider
    const user = await fetch('http://identity-provider.internal/validate', {
      headers: { Authorization: call.metadata.get('authorization')[0] as string }
    });
    
    callback(null, { status: { code: grpc.status.OK } });
  } catch (err) {
    // Anti-pattern: Hangs or permits error handling without enforcing fail-closed bounds
    callback(null, { status: { code: grpc.status.OK } });
  }
};
```

#### Production Standard (Correct)
> **Standard**: Calculates remaining deadline from incoming gRPC call, subtracts a processing margin (monotonic budgeting), uses AbortController to cleanly cancel hung outbound checks, and strictly fails closed with UNAUTHENTICATED or PERMISSION_DENIED.
```typescript
// PRODUCTION SECURE: Enforces monotonic deadline propagation and fail-closed guarantees
import * as grpc from '@grpc/grpc-js';

const SAFETY_MARGIN_MS = 50;

export const check = async (call: grpc.ServerUnaryCall<any, any>, callback: grpc.sendUnaryData<any>) => {
  const incomingDeadline = call.getDeadline();
  const now = Date.now();
  const rawRemaining = typeof incomingDeadline === 'number' ? incomingDeadline - now : 200;
  
  // Monotonic budget: Deduct safety margin for serialization/network overhead
  const remainingBudgetMs = Math.max(0, rawRemaining - SAFETY_MARGIN_MS);

  if (remainingBudgetMs <= 0) {
    return callback(null, {
      status: { code: grpc.status.DEADLINE_EXCEEDED, message: 'ExtAuthz monotonic budget exhausted' }
    });
  }

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), remainingBudgetMs);

  try {
    const authHeader = call.metadata.get('authorization')[0] as string | undefined;
    if (!authHeader) {
      return callback(null, { status: { code: grpc.status.PERMISSION_DENIED } });
    }

    const response = await fetch('http://identity-provider.internal/validate', {
      headers: { Authorization: authHeader },
      signal: controller.signal
    });

    if (!response.ok) {
      return callback(null, { status: { code: grpc.status.PERMISSION_DENIED } });
    }

    return callback(null, { status: { code: grpc.status.OK } });
  } catch (err) {
    // Fail-closed: Explicit denial on timeout or upstream failure
    return callback(null, {
      status: { 
        code: grpc.status.UNAUTHENTICATED, 
        message: 'Authentication verification failed or timed out' 
      }
    });
  } finally {
    clearTimeout(timeoutId);
  }
};
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Envoy Gateway 1.2 ExtAuthz Monotonic Budgeting and Fail-Closed Boundary

Envoy Gateway 1.2 ExtAuthz Monotonic Budgeting and Fail-Closed Boundary defines an industrial-grade behavioral standard for security engineering. Mandates strict fail-closed authorization posture and monotonic deadline budgeting for External Authorization (ExtAuthz) filters in Envoy Gateway 1.2. Prevents worker thread saturation, denial-of-service, and unauthorized bypass by enforcing explicit request timeouts, connection pool circuit breaking, and failOpen=false invariants. 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 ExtAuthz Timeouts and Permissive Fail-Open Fallbacks Leading to Proxy Thread Starvation and Auth Bypass 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 ExtAuthz Timeouts and Permissive Fail-Open Fallbacks Leading to Proxy Thread Starvation and Auth BypassCritical
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 set 'failOpen

Engineers MUST ALWAYS set 'failOpen: false' within Envoy Gateway 'SecurityPolicy' resources referencing external authorization providers.

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 ALWAYS define an explicit, sub-second timeout on ExtAuthz gRPC/HTTP services that is strictly less than 20% of the overall downstream client request deadline.

Engineers MUST ALWAYS define an explicit, sub-second timeout on ExtAuthz gRPC/HTTP services that is strictly less than 20% of the overall downstream client request deadline.

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 configure explicit circuit breaking via 'BackendTrafficPolicy' or ExtAuthz cluster settings to limit 'maxConnections', 'maxPendingRequests', and 'consecutive5xxErrors' targeting the ExtAuthz daemon.

Engineers MUST configure explicit circuit breaking via 'BackendTrafficPolicy' or ExtAuthz cluster settings to limit 'maxConnections', 'maxPendingRequests', and 'consecutive5xxErrors' targeting the ExtAuthz daemon.

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

ExtAuthz service handlers MUST extract downstream incoming deadlines (e.g., 'grpc-timeout' or context deadlines) and monotonically propagate reduced deadlines to upstream identity providers.

ExtAuthz service handlers MUST extract downstream incoming deadlines (e.g., 'grpc-timeout' or context deadlines) and monotonically propagate reduced deadlines to upstream identity providers.

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

Engineers MUST NOT rely on default Envoy timeout values (which default to non-zero high thresholds or indefinite streaming) for external authorization calls.

Engineers MUST NOT rely on default Envoy timeout values (which default to non-zero high thresholds or indefinite streaming) for external authorization calls.

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 emit immediate HTTP 403 Forbidden or 504 Gateway Timeout responses upon authorization timeout rather than hanging worker thread contexts.

Services MUST emit immediate HTTP 403 Forbidden or 504 Gateway Timeout responses upon authorization timeout rather than hanging worker thread contexts.

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 Gateway 1.2 ExtAuthz Monotonic Budgeting and Fail-Closed Boundary critical for AI coding assistants?

Mandates strict fail-closed authorization posture and monotonic deadline budgeting for External Authorization (ExtAuthz) filters in Envoy Gateway 1.2. Prevents worker thread saturation, denial-of-service, and unauthorized bypass by enforcing explicit request timeouts, connection pool circuit breaking, and failOpen=false invariants. 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 ExtAuthz Timeouts and Permissive Fail-Open Fallbacks Leading to Proxy Thread Starvation and Auth Bypass) 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