This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: oauth2-rar-fine-grained-policy-standard

OAuth 2.0 RFC 9396 Rich Authorization Requests (RAR) Policy Enforcement

RFC 9396 Rich Authorization Requests (RAR) mandate that capability tokens convey transaction-specific, fine-grained authorization details rather than broad, ambient OAuth scopes. Resource servers and token-issuing gateways must strictly validate, structurally type, and cryptographically bind authorization details to prevent token re-use, lateral movement, and privilege escalation in zero-trust architectures.

Prohibited Anti-Pattern: Falling Back to Ambient Coarse Scopes or Unvalidated authorization_details Payloads

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OAuth 2.0 RFC 9396 Rich Authorization Requests (RAR) Policy Enforcement - RFC 9396 Rich Authorization Requests (RAR) mandate that capability tokens convey transaction-specific, fine-grained authorization details rather than broad, ambient OAuth scopes. Resource servers and token-issuing gateways must strictly validate, structurally type, and cryptographically bind authorization details to prevent token re-use, lateral movement, and privilege escalation in zero-trust architectures.
globs: src/auth/**/*.ts, src/middleware/**/*.ts, src/gateway/**/*.ts, src/controllers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth2-rar-fine-grained-policy-standard"
---

# OAuth 2.0 RFC 9396 Rich Authorization Requests (RAR) Policy Enforcement

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Falling Back to Ambient Coarse Scopes or Unvalidated authorization_details Payloads

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.0 Rich Authorization Requests (RFC 9396) invariants. You must prevent ambient privilege escalation by rejecting coarse-grained OAuth scope assumptions and requiring complete schema validation for the `authorization_details` array on incoming tokens. Every authorized transaction must be explicitly bounded by type, action, target resource identifier, and quantitative transaction constraints.

## Strict Guidelines
- Engineers MUST ALWAYS enforce strict schema validation (e.g., via Zod or type-narrowing predicates) on the `authorization_details` claim within capability tokens before allowing resource execution.
- Engineers MUST NOT fall back to coarse-grained ambient scopes (e.g., `scope: 'payments:write'`) when an endpoint performs high-privilege, transaction-specific operations.
- Resource servers MUST verify that the incoming HTTP request parameters match the exact parameters specified in the token's matching `authorization_details` element (e.g., exact recipient account, maximum transaction amount, currency).
- Services MUST reject requests if no element in `authorization_details` matches the required `type` field or if the requested action is not an explicit subset of permitted `actions`.
- Components NEVER execute financial, administrative, or state-mutating actions without asserting that the token authorization detail has not expired or been decoupled from the current transaction context.

## Bad vs Good Implementations
### Enforcing RFC 9396 Authorization Details on Sensitive Mutation Endpoints

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The middleware falls back to ambient scopes ('payment:write'), bypassing transaction-specific constraints entirely. Even when checking authorization_details, it performs no structural schema validation or boundary checks (e.g., recipient account, maximum amount) against the actual request payload.
```typescript
import { Request, Response, NextFunction } from 'express';

interface AuthenticatedToken {
  sub: string;
  scope?: string;
  authorization_details?: Array<Record<string, unknown>>;
}

export function authorizePayment(req: Request & { user?: AuthenticatedToken }, res: Response, next: NextFunction) {
  const token = req.user;
  if (!token) {
    return res.status(401).json({ error: 'unauthorized' });
  }

  // BAD: Falling back to ambient coarse-grained scope without validating the RAR payload
  const hasScope = token.scope?.split(' ').includes('payment:write');
  if (hasScope) {
    return next(); // Lateral escalation risk: token can pay ANY party for ANY amount
  }

  // BAD: Weak, untyped check without verifying requested payload limits
  const rar = token.authorization_details?.find((d) => d.type === 'payment_initiation');
  if (!rar) {
    return res.status(403).json({ error: 'insufficient_authorization' });
  }

  return next();
}
```

#### Production Standard (Correct)
> **Standard**: Validates the RFC 9396 authorization_details payload using a strict Zod schema, ensuring precise transaction authorization. It verifies that requested parameters (amount and destination account) match the bounded token payload, completely preventing ambient privilege reuse and lateral movement.
```typescript
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';

const PaymentInitiationDetailSchema = z.object({
  type: z.literal('payment_initiation'),
  actions: z.array(z.string()).refine((actions) => actions.includes('execute')),
  locations: z.array(z.string().url()).optional(),
  instructedAmount: z.object({
    currency: z.literal('USD'),
    amount: z.string().regex(/^\d+(\.\d{2})?$/)
  }),
  creditorAccount: z.object({
    iban: z.string().min(15).max(34)
  })
});

type PaymentInitiationDetail = z.infer<typeof PaymentInitiationDetailSchema>;

interface AuthenticatedToken {
  sub: string;
  authorization_details?: unknown[];
}

export function enforceRarPaymentAuthorization(req: Request & { user?: AuthenticatedToken }, res: Response, next: NextFunction) {
  const token = req.user;
  if (!token?.authorization_details || !Array.isArray(token.authorization_details)) {
    return res.status(403).json({ error: 'missing_authorization_details' });
  }

  const candidate = token.authorization_details.find(
    (detail): detail is Record<string, unknown> => typeof detail === 'object' && detail !== null && (detail as { type?: unknown }).type === 'payment_initiation'
  );

  const parsed = PaymentInitiationDetailSchema.safeParse(candidate);
  if (!parsed.success) {
    return res.status(403).json({ error: 'invalid_authorization_details', details: parsed.error.issues });
  }

  const authorization: PaymentInitiationDetail = parsed.data;
  const { requestedAmount, targetIban } = req.body;

  // Enforce zero-trust transaction bounds against token authorization
  const authorizedMax = parseFloat(authorization.instructedAmount.amount);
  const requested = parseFloat(requestedAmount);

  if (requested > authorizedMax || targetIban !== authorization.creditorAccount.iban) {
    return res.status(403).json({ error: 'authorization_payload_mismatch' });
  }

  return next();
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OAuth 2.0 RFC 9396 Rich Authorization Requests (RAR) Policy Enforcement

OAuth 2.0 RFC 9396 Rich Authorization Requests (RAR) Policy Enforcement defines an industrial-grade behavioral standard for security engineering. RFC 9396 Rich Authorization Requests (RAR) mandate that capability tokens convey transaction-specific, fine-grained authorization details rather than broad, ambient OAuth scopes. Resource servers and token-issuing gateways must strictly validate, structurally type, and cryptographically bind authorization details to prevent token re-use, lateral movement, and privilege escalation in zero-trust architectures. 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: Falling Back to Ambient Coarse Scopes or Unvalidated authorization_details Payloads 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 DriftFalling Back to Ambient Coarse Scopes or Unvalidated authorization_details PayloadsCritical
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 schema validation (e.g., via Zod or type-narrowing predicates) on the `authorization_details` claim within capability tokens before allowing resource execution.

Engineers MUST ALWAYS enforce strict schema validation (e.g., via Zod or type-narrowing predicates) on the `authorization_details` claim within capability tokens before allowing resource execution.

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 fall back to coarse-grained ambient scopes (e.g., `scope

Engineers MUST NOT fall back to coarse-grained ambient scopes (e.g., `scope: 'payments:write'`) when an endpoint performs high-privilege, transaction-specific operations.

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

Resource servers MUST verify that the incoming HTTP request parameters match the exact parameters specified in the token's matching `authorization_details` element (e.g., exact recipient account, maximum transaction amount, currency).

Resource servers MUST verify that the incoming HTTP request parameters match the exact parameters specified in the token's matching `authorization_details` element (e.g., exact recipient account, maximum transaction amount, currency).

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 reject requests if no element in `authorization_details` matches the required `type` field or if the requested action is not an explicit subset of permitted `actions`.

Services MUST reject requests if no element in `authorization_details` matches the required `type` field or if the requested action is not an explicit subset of permitted `actions`.

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 NEVER execute financial, administrative, or state-mutating actions without asserting that the token authorization detail has not expired or been decoupled from the current transaction context.

Components NEVER execute financial, administrative, or state-mutating actions without asserting that the token authorization detail has not expired or been decoupled from the current transaction context.

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 OAuth 2.0 RFC 9396 Rich Authorization Requests (RAR) Policy Enforcement critical for AI coding assistants?

RFC 9396 Rich Authorization Requests (RAR) mandate that capability tokens convey transaction-specific, fine-grained authorization details rather than broad, ambient OAuth scopes. Resource servers and token-issuing gateways must strictly validate, structurally type, and cryptographically bind authorization details to prevent token re-use, lateral movement, and privilege escalation in zero-trust architectures. 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 (Falling Back to Ambient Coarse Scopes or Unvalidated authorization_details Payloads) 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

OAuth