API Auth and Access Contract Design

    1

    Designs API authentication and authorization contracts: token profiles, scopes, gateway validation, and revocation.

    $5

    Secure checkout via Stripe

    Money-back guarantee

    Converts to your local currency at checkout

    Security scanned

    Works with the AI Agents you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIDeepSeekDeepSeekMuseMuse+22 more

    API Auth and Access Contract Design

    Example session with this skill installed

    Design the API authentication and authorization contract for our B2B Merchant Settlement API.

    • Subject: settlement-api v2.0 (run-id: partner-api-auth-001) hosted on AWS API Gateway fronting internal Kubernetes microservices.
    • Deciders: Lead API Security Architect (Sarah Chen) and Head of Payment Operations (Marcus Vance).
    • Client Profile: 320 external institutional partners invoking POST /v1/settlements and GET /v1/settlements/{id}; peak 450 requests/sec.
    • Tension: External partners requested long-lived static API keys in query parameters for simple cURL integration; Sarah Chen strictly forbids API keys in URLs, mandating mTLS authentication with certificate pinning for transport, Ed25519-signed asymmetric JWTs (Bearer header, 15-minute TTL) for identity, and fine-grained ABAC scopes (settlements:write, settlements:read:own).
    • Downstream: Gateway validates outer tokens, strips client certs, and injects a signed internal context header X-Internal-Caller-Context for zero-trust microservice consumption; key rotation automated every 60 days via JWKS endpoints.

    Write the API auth contract under docs/.

    • Read your context and instructions
    • Compiled the api auth

    Wrote docs/architecture/tasks/partner-api-auth-001/api-auth-design/api-security-middleware-spec.md. Complete API security middleware contract specifying mTLS edge termination, Ed25519 Bearer token validation, fine-grained object-level resource binding, and RFC 9457 error semantics.

    ---
    skill: api-auth-design
    ---
    
    # API Security Middleware Specification: B2B Merchant Settlement API [AUTH-SPEC-SETTLE-001]
    
    ## Summary
    
    This specification establishes the API authentication and authorization enforcement contract for `settlement-api v2.0` under run ID `partner-api-auth-001`. It governs ingress traffic from 320 institutional partners invoking `POST /v1/settlements` and `GET /v1/settlements/{id}` through AWS API Gateway to Kubernetes backend services, sustaining 450 peak requests/second. The design rejects partner requests for static query-parameter API keys in favor of dual-layer defense: transport-level mTLS with CA pinning, 15-minute Ed25519-signed asymmetric JWTs presented in the `Authorization: Bearer` header, and strict object-level tenant resource binding (`principal.tenant_id == resource.merchant_id`). Unauthenticated requests yield RFC 9457 `401 Unauthorized` with `WWW-Authenticate`; unauthorized routes yield `403 Forbidden`; unauthorized resource instances yield `404 Not Found` to prevent BOLA identifier enumeration.
    
    ## Detailed Description
    
    External institutional partners process multi-million dollar daily settlements. Exposing API keys in URL query strings exposes credentials in browser history, proxy access logs, and referrer headers. Transport-level authentication (mTLS) alone does not establish application identity or prevent Broken Object Level Authorization (BOLA). This specification establishes deterministic gateway and application middleware contracts separating transport, identity validation, route scope checks, and object resource binding.
    
    

    Incoming Request (mTLS + Bearer JWT)
    │
    ▼
    [ Step 1: Transport Gate (API Gateway) ]
    ├── Client Certificate Pinning & CN Validation ──► Invalid Cert: Terminate TLS (495)
    └── Strip X.509; Forward verified SAN
    │
    ▼
    [ Step 2: Authentication Middleware (Edge) ]
    ├── Validate Signature (Ed25519 via JWKS), iss, aud, exp, nbf
    ├── Missing / Invalid / Expired Token ───────────► HTTP 401 (WWW-Authenticate: Bearer error="invalid_token")
    └── Mint Signed X-Internal-Caller-Context
    │
    ▼
    [ Step 3: Route Scope Authorization ]
    ├── Required Scope Check (e.g. settlements:write)
    └── Scope Missing ───────────────────────────────► HTTP 403 (insufficient_scope)
    │
    ▼
    [ Step 4: Resource-Instance Binding (Application / Envoy) ]
    ├── Enforce: principal.tenant_id == target_resource.merchant_id
    └── Cross-Tenant / Non-Existent Target ──────────► HTTP 404 (RFC 9457, Not Found)

    
    ### Criteria and weights
    
    | Criterion | Why it matters here | Weight | Source of the weight |
    |---|---|---|---|
    | Credential Leakage & Replay Defense | Static URL keys leak via server logs; asymmetric short-lived tokens limit replay blast radius. | 0.35 | Sarah Chen (Lead API Security Architect) |
    | Multi-Tenant Object Isolation | Institutional partners must never enumerate or access other merchants' settlement ledgers (BOLA defense). | 0.30 | Marcus Vance (Head of Payment Operations) |
    | Cryptographic Verification Overhead | Token signature validation across 450 req/sec peak must consume <= 5 ms p99 gateway overhead. | 0.20 | Workload requirement |
    | Deterministic Error Disclosure | Error responses must not leak valid settlement IDs, internal topology, or key-signing secrets. | 0.15 | API Guild Security Standard |
    
    
    ### Comparison
    
    | Mechanism Candidate | Authentication Presentation | Route Authorization | Object-Level Binding | BOLA Enumeration Risk | Evaluation |
    |---|---|---|---|---|---|
    | Candidate A: Query String API Key | Query param `?api_key=secret` | Static Key Map | Backend DB query | Critical: URL logged across proxies; no resource scope binding | Rejected: Violates OWASP API Security Top 10 and corporate policy |
    | Candidate B: mTLS Only (Transport Peer) | Client X.509 Certificate | SAN-to-Role Mapping | Gateway header injection | High: Transport peer lacks fine-grained action scopes; difficult delegation | Rejected: Fails to separate caller transport from application identity |
    | Candidate C: mTLS + Ed25519 JWT + Scoped Middleware (Chosen) | Transport mTLS + Header `Authorization: Bearer <JWT>` | Claim `scope` evaluation | Deterministic `principal.tenant_id == resource.merchant_id` | Minimal: 404 concealment prevents ID enumeration; strict lease binding | Selected: Zero-trust defense-in-depth, 15m TTL, cryptographically isolated |
    
    
    ### Result
    
    Candidate C is selected. Transport is pinned via mTLS at AWS API Gateway; identity is authenticated via asymmetric Ed25519 JWTs (RFC 8037); authorization strictly binds route scopes and tenant resource ownership.
    
    ---
    
    ### Required Mechanisms
    
    #### 1. Operation Contract [MC-OC-01]
    - **Inputs**:
      - `POST /v1/settlements`: Client certificate (mTLS), header `Authorization: Bearer <token>`, JSON body `{"merchant_id": str, "currency": str, "amount_cents": int, "payout_account": str}`.
      - `GET /v1/settlements/{id}`: Client certificate (mTLS), header `Authorization: Bearer <token>`, path parameter `id` (`settle_[a-zA-Z0-9]{16}`).
    - **Algorithm**:
      1. Gateway checks client certificate against approved CA bundle; extracts Subject Alternative Name (`SAN`).
      2. Edge middleware extracts JWT from `Authorization: Bearer`. Validates:
         - Header `alg == "EdDSA"`, `typ == "JWT"`, `kid` resolves in cached JWKS.
         - Signature matches public key from `https://auth.internal.bank/.well-known/jwks.json`.
         - `iss == "https://auth.internal.bank"`, `aud == "https://settlement-api.internal"`.
         - `nbf <= current_time <= exp` (clock skew tolerance: 0s).
      3. Gateway synthesizes internal caller token and passes downstream:
         `X-Internal-Caller-Context: {"sub": "partner-app-42", "tenant_id": "m_8829", "scopes": ["settlements:write"]}` signed with gateway private key.
      4. Application middleware verifies route scope:
         - `POST /v1/settlements` requires `settlements:write` and asserts `body.merchant_id == principal.tenant_id`.
         - `GET /v1/settlements/{id}` requires `settlements:read:own` and asserts loaded settlement `merchant_id == principal.tenant_id`.
    - **Outputs**: Downstream service execution context struct, or immediate client termination (401, 403, 404).
    - **Owner**: Sarah Chen (Lead API Security Architect) and Marcus Vance (Payment Operations).
    - **Failure Handling**: Fail-closed. Any verification failure aborts processing immediately without invoking downstream domain services.
    - **Verification**: Contract integration suite `test_settlement_auth_middleware_contract()` asserting valid tokens pass and spoofed tenant headers fail.
    
    #### 2. Error Taxonomy [MC-ET-01]
    - **Inputs**: Authentication failures, expired credentials, missing scopes, and cross-tenant access attempts.
    - **Algorithm**: Deterministic classification conforming to RFC 9457 Problem Details:
      1. `401 Unauthorized`:
         - Header omitted: `WWW-Authenticate: Bearer`
         - Invalid/expired token: `WWW-Authenticate: Bearer error="invalid_token", error_description="The access token signature is invalid or expired"`
         - Body: RFC 9457 problem document (`type="https://api.bank.internal/errors/unauthorized"`).
      2. `403 Forbidden`:
         - Token valid, but caller lacks route scope: `WWW-Authenticate: Bearer error="insufficient_scope", scope="settlements:write"`
         - Body: RFC 9457 problem document (`type="https://api.bank.internal/errors/forbidden"`).
      3. `404 Not Found` (BOLA Concealment Gate):
         - Token valid, route scope present, but resource `{id}` does not exist OR belongs to another tenant (`principal.tenant_id != resource.merchant_id`).
         - Body: RFC 9457 standard 404 document (`detail="Settlement resource not found"`).
    - **Outputs**: Standardized JSON error response with appropriate security response headers.
    - **Owner**: API Security Architecture Guild.
    - **Failure Handling**: Internal unexpected handler faults return generic `500 Internal Server Error` with zero stack traces or key IDs exposed.
    - **Verification**: Automated security regression suite `test_auth_error_taxonomy_rfc9457()` validating exact headers and bodies.
    
    #### 3. Idempotency [MC-ID-01]
    - **Inputs**: Header `Idempotency-Key` on `POST /v1/settlements`, caller JWT `sub` and `tenant_id`, payload JSON hash.
    - **Algorithm**:
      1. Authentication and authorization middleware run strictly *before* idempotency storage check. Unauthenticated requests are rejected before reserving idempotency keys.
      2. Idempotency partition key scoped to tenant: `IDEMP#<tenant_id>#<Idempotency-Key>`.
      3. Response replayed byte-for-byte on matching payload; HTTP 422 returned on payload mismatch; HTTP 409 returned on in-flight execution.
    - **Outputs**: Deterministic single-execution guarantee per authenticated tenant identity.
    - **Owner**: Marcus Vance (Core Payment Operations).
    - **Failure Handling**: Idempotency lease acquisition failure fails closed with HTTP 503; does not bypass authentication.
    - **Verification**: Concurrency contract test `test_idempotency_auth_precedence()` asserting unauthenticated requests cannot mutate or probe idempotency state.
    
    #### 4. Compatibility [MC-CM-01]
    - **Inputs**: External client contracts, OpenAPI 3.1.0 security scheme declarations, JWKS key rotation schedules.
    - **Algorithm**:
      - Backward compatibility: Gateway maintains dual-signing verification keys during 60-day rotation windows. Both `kid_v1` and `kid_v2` remain active until old key phase-out.
      - Forward evolution: Scope naming follows hierarchical syntax `settlements:<action>[:qualifier]`. Introducing new sub-scopes requires additive backwards-compatible permissions.
    - **Outputs**: OpenAPI 3.1.0 document with `securitySchemes: [mTLS, BearerJWT]`.
    - **Owner**: Sarah Chen (Lead API Security Architect).
    - **Failure Handling**: Rejection of unknown `kid` values; immediate telemetry alert on JWKS fetch failure.
    - **Verification**: Schema linter `test_openapi_security_contract_compatibility()` confirming valid security schemes across revisions.
    
    ---
    
    ### Adversarial Cases and Routing
    
    #### 1. Reject HTTP-Only Specification [ADV-HO-01]
    - **Vulnerability**: Assuming HTTP protocol headers (`Authorization`) or gateway routing rules alone provide authorization without application-level resource ownership binding.
    - **Adversarial Mechanism**: Caller possesses a valid token for Merchant A with `settlements:read:own` scope. Caller issues `GET /v1/settlements/settle_9999` belonging to Merchant B. An HTTP-only route gate checks only that `settlements:read:own` is in the token and returns Merchant B's confidential wire record.
    - **Enforcement & Diagnostic**: Resource-binding middleware must assert `principal.tenant_id == record.merchant_id`. If an endpoint omits resource-binding logic, startup linter emits diagnostic `ERR_UNBOUND_RESOURCE_AUTHORIZATION` and blocks route deployment.
    - **Forbidden Output Behavior**: The system is strictly forbidden from returning settlement domain models without executing an explicit tenant-to-resource ownership assertion.
    
    #### 2. Reject Ambiguous Errors [ADV-AE-01]
    - **Vulnerability**: Emitting `403 Forbidden` when an unauthorized user attempts to access a settlement ID belonging to another tenant.
    - **Adversarial Mechanism**: Attacker scripts sequential IDs `settle_0001`, `settle_0002`... Receiving `404` for missing records but `403` for existing competitor records confirms valid IDs and enables target enumeration.
    - **Enforcement & Diagnostic**: Tenant-mismatch conditions MUST emit `404 Not Found` with identical body timing and format as non-existent records. If code returns `403` for non-owned entities, contract test emits diagnostic `ERR_BOLA_ENUMERATION_LEAK`.
    - **Forbidden Output Behavior**: The system is strictly forbidden from returning `403 Forbidden` for resource instance lookup failures across differing tenant boundaries.
    
    #### 3. Reject Breaking Drift [ADV-BD-01]
    - **Vulnerability**: Permitting API keys in query parameters, switching signature algorithms from EdDSA to `none` or RSA without key rotation synchronization, or changing claim path resolution between gateway and microservices.
    - **Adversarial Mechanism**: Attacker supplies JWT with `{"alg": "none"}` or appends `?token=stolen` to circumvent mTLS header validation.
    - **Enforcement & Diagnostic**: Gateway parser strictly rejects tokens with `alg == "none"` or unpinned asymmetric schemes. Query parameter authentication is discarded at ingress. Drift in claim schema fails CI via diagnostic `ERR_AUTH_CONTRACT_DRIFT`.
    - **Forbidden Output Behavior**: The system is strictly forbidden from accepting credentials in URI query strings or executing verification against un-whitelisted algorithm headers.
    
    ---
    
    ### Invariants and Contracts
    
        Middleware Order Precedence [INV-AUTH-01]
          Request processing order is immutable: (1) Transport mTLS termination -> (2) Bearer JWT validation ->
          (3) Route scope authorization -> (4) Object resource-binding validation. Downstream business logic
          never executes if any prior stage fails.
    
        BOLA Concealment Invariant [INV-AUTH-02]
          Cross-tenant resource lookups must return HTTP 404 Not Found. HTTP 403 Forbidden is reserved
          exclusively for route-level permission failures where resource existence is not in question.
    
        Algorithm Integrity Invariant [INV-AUTH-03]
          The token verification layer must evaluate public keys using Ed25519 (EdDSA) exclusively.
          Algorithms "none", HMAC-SHA256, or mismatched RSA keys must fail validation deterministically.
    
    ## Explicit Unknowns
    
    - Exact mTLS revocation list check latency (OCSP stapling vs CRL cache invalidation) under AWS API Gateway (G-1).
    - Keycloak / IdP failover convergence time across secondary AWS regions for JWKS endpoint resolution (G-2).
    
    ## Traceability
    
    | Claim | Classification | Source | Freshness |
    |---|---|---|---|
    | Peak 450 req/sec across 320 partners | provided | Workload intake | Current |
    | Ed25519 Bearer token with 15-minute TTL | provided | Security requirement | Current |
    | Prohibition of query parameter API keys | provided | Policy requirement | Current |
    | mTLS certificate pinning requirement | provided | Security requirement | Current |
    | 60-day automated JWKS rotation cycle | provided | Architecture intake | Current |
    | HTTP 404 concealment for cross-tenant lookups | decided | Sarah Chen & Marcus Vance | 2026-09-16 |
    | Internal caller context header schema | decided | MC-OC-01 | 2026-09-16 |
    | OpenAPI 3.1.0 security specification | observed | `schemas/settlement_api_v2.json:d4e1a8f9` | 2026-09-16 |
    | Auth middleware contract test suite | observed | `tests/security/test_auth_middleware.py:e81b20ac` | 2026-09-16 |
    
    
    ## Verification
    
    No validator was supplied, so no command was run.
    
    Reviewer self-check against API security middleware domain contracts:
    - **Authentication Precedence**: PASS. Transport mTLS -> Token verify -> Scope check -> Resource bind order enforced.
    - **BOLA Protection**: PASS. Tenant match required (`principal.tenant_id == resource.merchant_id`); 404 concealment mapped.
    - **Cryptographic Enforcement**: PASS. Ed25519 asymmetric signature, `iss`, `aud`, and `exp` checked; query keys rejected.
    - **Error Transparency**: PASS. Compliant with RFC 9457 Problem Details and RFC 6750 `WWW-Authenticate` challenge headers.
    
    ## Open Decisions
    
    - `DEC-AUTH-01`: Sarah Chen to confirm whether mTLS client certificate serial numbers should be appended to internal audit logs in compliance with PCI-DSS 4.0 requirement 10.2 (Owner: Sarah Chen).
    
    ## Next steps
    
    1. Sarah Chen (Lead API Security Architect) signs off on `X-Internal-Caller-Context` schema.
    2. Platform team implements AWS API Gateway custom authorizer using Ed25519 JWKS verification in `infra/gateway/authorizer.ts`.
    3. Payment service team registers resource-binding interceptor in `services/settlement/middleware/auth.py`.
    

    Connects securely to your tools. The creator never sees your data.

    About this skill

    What it does

    This skill maps authoritative identity/authentication/session/token and resource/action authorization requirements onto exact API operations and responses. It specifies credential presentation/validation inputs, principal/security-context propagation, authorization decision/enforcement contracts, challenges, errors and lifecycle behavior.

    Use it when

    Use when accepted API operations/resources and upstream IAM/security contracts need a precise API-facing enforcement and failure contract.

    For example: “Pen test walked from one dealer's account into another's by changing the id in the URL. The endpoint checks the token is valid, and it was.”

    What you get

    • API Security Middleware Spec

    Written as Markdown to <your output folder>/architecture/tasks/<run-id>/api-auth-design/.

    What it will not do

    Do not use for auth/IdP selection, IAM architecture, OIDC/mTLS/key design, threat modeling, API/resource design, provider configuration, credential/token issuance, secret/key management, testing or implementation.

    How it works

    1. Check the concern is enforcement at the API edge.
    2. Separate authentication from authorisation in the middleware order.
    3. Validate every token property, and name them.
    4. Bind scope to the resource, not only to the route.
    5. Define the failure responses precisely.
    6. Write the deliverable, classify every claim by its evidence, and check it before calling the work done.

    What's in the package

    Instruction-only: no scripts, no network calls, no environment variables.

    • LICENSE.txt
    • SKILL.md
    • agents/openai.yaml
    • assets/output-template-task.md
    • references/domain-rules.md
    • references/operating-rules.md
    • references/output-contract.md

    Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for APIs & Backend.

    Do not use for auth/IdP selection, IAM architecture, OIDC/mTLS/key design, threat modeling, API/resource design, provider configuration, credential/token issuance, secret/key management, testing or implementation.

    How to use

    1. 1

      Connect your agent to the Agensi MCP

      Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup

    2. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 3

      Ask for what you need

      Your agent loads this skill and uses it on your task. It always asks before buying a skill.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill goes through the trust checks below.

    Security scanned

    Checked by our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    Money-back guarantee

    Doesn't do what its page promises? You get your money back.

    Trust & safety

    Security scan

    Security scan passed 1 month ago

    Permissions

    Read Files
    Write Files

    Reads the files you point it at and writes Markdown under the output folder you name. No network access, no environment variables, and no bundled scripts.

    Listed1 month ago

    What's inside

    Frequently Asked Questions

    No. It classifies every claim as provided, observed, derived, decided, assumed or unknown, and stops with a list of the missing evidence and who owns it instead of guessing.

    No. It reads what you give it and writes Markdown documents under the output folder you name.

    Any agent that supports SKILL.md skills, including Claude Code, Codex CLI, Cursor and Gemini CLI. It has no scripts and makes no network calls.

    Unzip it into your agent's skills folder, for example: unzip api-auth-design.zip -d ~/.claude/skills/

    New in APIs & Backend