This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: oauth-rar-rfc9396-enforcement-standard

RFC 9396 OAuth Rich Authorization Requests (RAR) Cryptographic & Schema Verification Guardrail

Enforces strict schema validation, deterministic transaction matching, and cryptographic sender-constraint binding on RFC 9396 'authorization_details' vectors. Prevents privilege-widening attacks in complex API handshakes where coarse scopes bypass fine-grained authorization constraints.

Prohibited Anti-Pattern: Coarse-Scope Fallback and Unvalidated authorization_details Processing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: RFC 9396 OAuth Rich Authorization Requests (RAR) Cryptographic & Schema Verification Guardrail - Enforces strict schema validation, deterministic transaction matching, and cryptographic sender-constraint binding on RFC 9396 'authorization_details' vectors. Prevents privilege-widening attacks in complex API handshakes where coarse scopes bypass fine-grained authorization constraints.
globs: src/auth/**/*.{ts,js}, src/middleware/**/*.{ts,js}, src/security/**/*.{ts,js}, src/controllers/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth-rar-rfc9396-enforcement-standard"
---

# RFC 9396 OAuth Rich Authorization Requests (RAR) Cryptographic & Schema Verification Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Coarse-Scope Fallback and Unvalidated authorization_details Processing

## System Constraints
You are a Principal Security Architect enforcing strict compliance with RFC 9396 (OAuth 2.0 Rich Authorization Requests). You must reject any authorization logic that relies on coarse OAuth scopes when fine-grained transactional authorization details are present or required. Mandate that every authorization_details element is schema-validated, strictly bounded to the target resource context, and verified against sender-constrained tokens (DPoP RFC 9449 or mTLS RFC 8705).

## Strict Guidelines
- Engineers MUST ALWAYS validate 'authorization_details' claims against an immutable, strongly-typed schema (e.g., Zod, TypeBox) defining explicit 'type', 'actions', 'locations', and resource-specific payload constraints.
- Engineers MUST NOT allow coarse OAuth 2.0 scopes (e.g., 'payment:write') to supersede or bypass 'authorization_details' validation when fine-grained policies are mandated.
- Resource Servers MUST verify that the active HTTP request parameters (such as target account, transaction amount, and target endpoint URI) match or represent a strict subset of the constraints expressed in the token's validated 'authorization_details'.
- Services MUST ensure that tokens containing RFC 9396 'authorization_details' are cryptographically sender-constrained using DPoP (RFC 9449) or mTLS (RFC 8705) to prevent token export and replay across unauthorized execution vectors.
- Components NEVER accept open-ended or arbitrary key-value pairs within 'authorization_details'; all unrecognized fields must trigger immediate authorization rejection.

## Bad vs Good Implementations
### RFC 9396 Transaction Enforcement Middleware

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relies on a coarse scope fallback, performs unsafe type-casting without strict runtime schema parsing, fails to confirm currency/debtor constraints against the incoming request, and does not enforce sender-constrained cryptographic validation.
```typescript
import { Request, Response, NextFunction } from 'express';

// VULNERABLE: Fallback to coarse scope and unvalidated RAR payload
export function authorizePayment(req: Request, res: Response, next: NextFunction) {
  const token = req.user;
  
  // Flaw 1: Coarse scope fallback enables privilege widening
  if (token.scope?.includes('payment:execute')) {
    return next();
  }

  // Flaw 2: Blind casting without schema validation or request matching
  const details = token.authorization_details as Array<{ type: string; max_amount?: number }>;
  const paymentDetail = details?.find((d) => d.type === 'payment_initiation');

  if (paymentDetail) {
    // Flaw 3: Incomplete check (ignores currency, beneficiary, sender binding)
    if (!paymentDetail.max_amount || req.body.amount <= paymentDetail.max_amount) {
      return next();
    }
  }

  return res.status(403).json({ error: 'insufficient_authorization' });
}
```

#### Production Standard (Correct)
> **Standard**: Implements deterministic RFC 9396 authorization detail verification using strict schema validation, enforces sender-constrained key binding (DPoP RFC 9449), and performs deep field-by-field equality checks against request parameters to completely block privilege-widening.
```typescript
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';

// Strict RFC 9396 Payment Initiation RAR Schema
const PaymentDetailsSchema = z.object({
  type: z.literal('payment_initiation'),
  actions: z.array(z.enum(['initiate', 'confirm'])).min(1),
  locations: z.array(z.string().url()).optional(),
  instructedAmount: z.object({
    amount: z.string().regex(/^\d+(\.\d{2})?$/),
    currency: z.enum(['USD', 'EUR', 'GBP']),
  }),
  debtorAccount: z.object({
    iban: z.string().regex(/^[A-Z]{2}\d{2}[A-Z0-9]{1,30}$/),
  }),
  creditorAccount: z.object({
    iban: z.string().regex(/^[A-Z]{2}\d{2}[A-Z0-9]{1,30}$/),
  }),
}).strict();

const AuthorizationDetailsClaimSchema = z.array(PaymentDetailsSchema);

export function enforceRarPayment(req: Request, res: Response, next: NextFunction) {
  // 1. Enforce sender-constrained binding (DPoP check)
  if (!req.dpop?.thumbprint || req.user?.cnf?.jkt !== req.dpop.thumbprint) {
    return res.status(401).json({ error: 'invalid_token', error_description: 'Sender-constraint thumbprint mismatch' });
  }

  // 2. Validate token authorization_details against strict RFC 9396 schema
  const parseResult = AuthorizationDetailsClaimSchema.safeParse(req.user?.authorization_details);
  if (!parseResult.success) {
    return res.status(403).json({ error: 'invalid_authorization_details', details: parseResult.error.flatten() });
  }

  // 3. Match transaction vectors identically against incoming request payload
  const { amount, currency, debtorIban, creditorIban } = req.body;
  const isAuthorized = parseResult.data.some((rar) => {
    const actionMatch = rar.actions.includes('initiate');
    const currencyMatch = rar.instructedAmount.currency === currency;
    const amountBound = parseFloat(amount) <= parseFloat(rar.instructedAmount.amount);
    const debtorMatch = rar.debtorAccount.iban === debtorIban;
    const creditorMatch = rar.creditorAccount.iban === creditorIban;
    return actionMatch && currencyMatch && amountBound && debtorMatch && creditorMatch;
  });

  if (!isAuthorized) {
    return res.status(403).json({ error: 'forbidden', error_description: 'Request exceeds authorized RAR parameters' });
  }

  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: RFC 9396 OAuth Rich Authorization Requests (RAR) Cryptographic & Schema Verification Guardrail

RFC 9396 OAuth Rich Authorization Requests (RAR) Cryptographic & Schema Verification Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict schema validation, deterministic transaction matching, and cryptographic sender-constraint binding on RFC 9396 'authorization_details' vectors. Prevents privilege-widening attacks in complex API handshakes where coarse scopes bypass fine-grained authorization constraints. 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: Coarse-Scope Fallback and Unvalidated authorization_details Processing 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 DriftCoarse-Scope Fallback and Unvalidated authorization_details ProcessingCritical
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 validate 'authorization_details' claims against an immutable, strongly-typed schema (e.g., Zod, TypeBox) defining explicit 'type', 'actions', 'locations', and resource-specific payload constraints.

Engineers MUST ALWAYS validate 'authorization_details' claims against an immutable, strongly-typed schema (e.g., Zod, TypeBox) defining explicit 'type', 'actions', 'locations', and resource-specific payload constraints.

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 allow coarse OAuth 2.0 scopes (e.g., 'payment

Engineers MUST NOT allow coarse OAuth 2.0 scopes (e.g., 'payment:write') to supersede or bypass 'authorization_details' validation when fine-grained policies are mandated.

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 active HTTP request parameters (such as target account, transaction amount, and target endpoint URI) match or represent a strict subset of the constraints expressed in the token's validated 'authorization_details'.

Resource Servers MUST verify that the active HTTP request parameters (such as target account, transaction amount, and target endpoint URI) match or represent a strict subset of the constraints expressed in the token's validated 'authorization_details'.

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 ensure that tokens containing RFC 9396 'authorization_details' are cryptographically sender-constrained using DPoP (RFC 9449) or mTLS (RFC 8705) to prevent token export and replay across unauthorized execution vectors.

Services MUST ensure that tokens containing RFC 9396 'authorization_details' are cryptographically sender-constrained using DPoP (RFC 9449) or mTLS (RFC 8705) to prevent token export and replay across unauthorized execution vectors.

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 accept open-ended or arbitrary key-value pairs within 'authorization_details'

Components NEVER accept open-ended or arbitrary key-value pairs within 'authorization_details'; all unrecognized fields must trigger immediate authorization rejection.

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 RFC 9396 OAuth Rich Authorization Requests (RAR) Cryptographic & Schema Verification Guardrail critical for AI coding assistants?

Enforces strict schema validation, deterministic transaction matching, and cryptographic sender-constraint binding on RFC 9396 'authorization_details' vectors. Prevents privilege-widening attacks in complex API handshakes where coarse scopes bypass fine-grained authorization constraints. 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 (Coarse-Scope Fallback and Unvalidated authorization_details Processing) 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

RFC