This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: oauth2-rar-type-attestation-guardrail

Strict Schema Contract Attestation for OAuth 2.1 Rich Authorization Requests (RAR)

Enforces deterministic runtime schema validation and client capability attestation for fine-grained OAuth 2.1 Rich Authorization Requests (RFC 9396). Prevents privilege escalation by disallowing open or weakly typed authorization_details objects, mandating closed schemas with strict property allowlists, and binding authorization types directly to registered client profiles before token minting.

Prohibited Anti-Pattern: Dynamic Pass-Through or Permissive Parsing of authorization_details Payloads Leading to Privilege Escalation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict Schema Contract Attestation for OAuth 2.1 Rich Authorization Requests (RAR) - Enforces deterministic runtime schema validation and client capability attestation for fine-grained OAuth 2.1 Rich Authorization Requests (RFC 9396). Prevents privilege escalation by disallowing open or weakly typed authorization_details objects, mandating closed schemas with strict property allowlists, and binding authorization types directly to registered client profiles before token minting.
globs: src/auth/**/*.{ts,tsx}, src/oauth/**/*.{ts,tsx}, src/server/auth/**/*.{ts,tsx}, src/routes/oauth/**/*.{ts,tsx}, src/tokens/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/oauth2-rar-type-attestation-guardrail"
---

# Strict Schema Contract Attestation for OAuth 2.1 Rich Authorization Requests (RAR)

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Dynamic Pass-Through or Permissive Parsing of authorization_details Payloads Leading to Privilege Escalation

## System Constraints
You are a Principal Security Architect enforcing OAuth 2.1 Rich Authorization Requests (RAR - RFC 9396) Type Attestation. Mandate invariant validation: any incoming authorization_details MUST pass exhaustive discriminated union schema validation with strict property stripping or rejection (additionalProperties: false), and every RAR type requested MUST be strictly attested against the client's registered capabilities before processing authorization or issuing tokens.

## Strict Guidelines
- Engineers MUST ALWAYS validate incoming authorization_details arrays using an exhaustive discriminated union schema with strict mode (rejecting unknown properties) keyed on the 'type' field.
- Engineers MUST verify that the authenticated client_id is explicitly authorized to request each specific RAR 'type' and its associated action sets in the client registry prior to initiating consent or token generation.
- Services MUST reject requests containing duplicate RAR types unless the specific RAR type specification explicitly documents and supports multiple instances.
- Components NEVER blindly serialize or pass unvalidated authorization_details into JSON Web Tokens (JWT) or internal security contexts without canonical type instantiation.
- Code SHOULD enforce deterministic normalization and canonical sorting of authorization detail attributes before hashing or persisting transaction state.

## Bad vs Good Implementations
### Strict Discriminated RAR Schema Attestation vs Permissive Any-Type Pass-Through

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The handler accepts any JSON structure inside authorization_details, checks only for the existence of a 'type' property, does not enforce property constraints (e.g., transaction limits, allowed actions), and fails to check whether the client is authorized for the given RAR type, enabling privilege escalation.
```typescript
import { Request, Response } from 'express';

interface ClientRecord {
  clientId: string;
  allowedScopes: string[];
}

// VULNERABLE: Treats authorization_details as loose records without schema validation
// or client capability attestation, allowing arbitrary privilege injection into tokens.
export async function handleAuthorizeRequest(req: Request, res: Response, client: ClientRecord) {
  const rawDetails = req.body.authorization_details;

  if (rawDetails) {
    const details = typeof rawDetails === 'string' ? JSON.parse(rawDetails) : rawDetails;

    if (Array.isArray(details)) {
      for (const item of details) {
        // Blind acceptance of authorization type without checking client permissions
        if (!item.type) {
          return res.status(400).json({ error: 'invalid_authorization_details' });
        }
      }
      // Privilege escalation: Unchecked attributes copied directly to grant context
      const grantContext = { clientId: client.clientId, details };
      return res.status(200).json({ grantContext });
    }
  }

  return res.status(400).json({ error: 'missing_authorization_details' });
}
```

#### Production Standard (Correct)
> **Standard**: The implementation defines strict, closed Zod schemas using discriminated unions, forbids unrecognized fields with .strict(), verifies client eligibility against an authoritative registry of allowed RAR types, and guards against duplicate type injections.
```typescript
import { Request, Response } from 'express';
import { z } from 'zod';

// RFC 9396 strictly defined transaction types
const PaymentAuthorizationDetailSchema = z.object({
  type: z.literal('payment_initiation'),
  actions: z.array(z.enum(['initiate', 'confirm'])).nonempty(),
  locations: z.array(z.string().url()).optional(),
  instructedAmount: z.object({
    currency: z.string().regex(/^[A-Z]{3}$/),
    amount: z.string().regex(/^\d+(\.\d{1,2})?$/),
  }),
  creditorAccount: z.object({
    iban: z.string().regex(/^[A-Z]{2}\d{2}[A-Z0-9]{1,30}$/),
  }),
}).strict();

const AccountAuthorizationDetailSchema = z.object({
  type: z.literal('account_information'),
  actions: z.array(z.enum(['list_accounts', 'read_balances'])).nonempty(),
  locations: z.array(z.string().url()).optional(),
}).strict();

const RichAuthorizationDetailsSchema = z.array(
  z.discriminatedUnion('type', [
    PaymentAuthorizationDetailSchema,
    AccountAuthorizationDetailSchema,
  ])
).nonempty();

export type ValidatedAuthorizationDetails = z.infer<typeof RichAuthorizationDetailsSchema>;

interface ClientRecord {
  clientId: string;
  allowedRarTypes: readonly string[];
}

export async function handleAuthorizeRequest(req: Request, res: Response, client: ClientRecord) {
  const parseResult = RichAuthorizationDetailsSchema.safeParse(req.body.authorization_details);

  if (!parseResult.success) {
    return res.status(400).json({
      error: 'invalid_authorization_details',
      error_description: 'authorization_details payload failed schema attestation',
    });
  }

  const details = parseResult.data;

  // Verify client is registered and authorized for each requested RAR type
  const isClientAuthorized = details.every((detail) =>
    client.allowedRarTypes.includes(detail.type)
  );

  if (!isClientAuthorized) {
    return res.status(403).json({
      error: 'unauthorized_client',
      error_description: 'Client lacks registration for one or more requested authorization types',
    });
  }

  // Prevent duplicate type declarations if not permitted by security policy
  const uniqueTypes = new Set(details.map((d) => d.type));
  if (uniqueTypes.size !== details.length) {
    return res.status(400).json({
      error: 'invalid_authorization_details',
      error_description: 'Duplicate authorization_details types detected',
    });
  }

  const grantContext = { clientId: client.clientId, authorizationDetails: details };
  return res.status(200).json({ grantContext });
}
```

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: Strict Schema Contract Attestation for OAuth 2.1 Rich Authorization Requests (RAR)

Strict Schema Contract Attestation for OAuth 2.1 Rich Authorization Requests (RAR) defines an industrial-grade behavioral standard for security engineering. Enforces deterministic runtime schema validation and client capability attestation for fine-grained OAuth 2.1 Rich Authorization Requests (RFC 9396). Prevents privilege escalation by disallowing open or weakly typed authorization_details objects, mandating closed schemas with strict property allowlists, and binding authorization types directly to registered client profiles before token minting. 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: Dynamic Pass-Through or Permissive Parsing of authorization_details Payloads Leading to Privilege Escalation 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 DriftDynamic Pass-Through or Permissive Parsing of authorization_details Payloads Leading to Privilege EscalationCritical
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 incoming authorization_details arrays using an exhaustive discriminated union schema with strict mode (rejecting unknown properties) keyed on the 'type' field.

Engineers MUST ALWAYS validate incoming authorization_details arrays using an exhaustive discriminated union schema with strict mode (rejecting unknown properties) keyed on the 'type' field.

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 verify that the authenticated client_id is explicitly authorized to request each specific RAR 'type' and its associated action sets in the client registry prior to initiating consent or token generation.

Engineers MUST verify that the authenticated client_id is explicitly authorized to request each specific RAR 'type' and its associated action sets in the client registry prior to initiating consent or token generation.

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 reject requests containing duplicate RAR types unless the specific RAR type specification explicitly documents and supports multiple instances.

Services MUST reject requests containing duplicate RAR types unless the specific RAR type specification explicitly documents and supports multiple instances.

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

Components NEVER blindly serialize or pass unvalidated authorization_details into JSON Web Tokens (JWT) or internal security contexts without canonical type instantiation.

Components NEVER blindly serialize or pass unvalidated authorization_details into JSON Web Tokens (JWT) or internal security contexts without canonical type instantiation.

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

Code SHOULD enforce deterministic normalization and canonical sorting of authorization detail attributes before hashing or persisting transaction state.

Code SHOULD enforce deterministic normalization and canonical sorting of authorization detail attributes before hashing or persisting transaction state.

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 Strict Schema Contract Attestation for OAuth 2.1 Rich Authorization Requests (RAR) critical for AI coding assistants?

Enforces deterministic runtime schema validation and client capability attestation for fine-grained OAuth 2.1 Rich Authorization Requests (RFC 9396). Prevents privilege escalation by disallowing open or weakly typed authorization_details objects, mandating closed schemas with strict property allowlists, and binding authorization types directly to registered client profiles before token minting. 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 (Dynamic Pass-Through or Permissive Parsing of authorization_details Payloads Leading to Privilege Escalation) 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

Strict