// Reference Guide · API Security · AI Era

API Security
in the AI Era

Authentication, resource authorization, token lifecycle, API boundaries, gateway enforcement, webhooks, CORS, and AI-agent threats.
A versioned HTTP API baseline with tests and primary sources.

API1–API10
OWASP API 2023 Mapped
LLM 2025
AI Baseline
Agentic 2026
Agent Baseline
2026-08-16
Last Reviewed
Critical

Broken Auth

Credential transport, rotation, token validation, and obsolete OAuth flows. Covered by OWASP API2:2023.

High

JWT Attacks

Algorithm confusion, weak keys, cross-JWT confusion, and profile-specific claim failures.

High

AI-Specific Threats

Prompt injection via API, model endpoint abuse, token exfiltration through LLM responses.

Control

Gateway Enforcement

Centralize shared controls at the gateway while keeping object and business authorization in the application.

API Authentication Mechanisms

The method you use to prove who's calling the API. Each has a different threat profile, operational cost, and appropriate use case. Most APIs use more than one mechanism depending on the caller type.

01

API Keys

Static Bearer Credentials · Simple but High Impact When Exposed
High Risk
How They Work + Where They Fail
What they are
A static string the client sends with every request. No expiry by default. No user context. Server looks it up in a table, grants or denies.
Key in URL (Critical)
GET /data?api_key=abc123 — logged in server logs, proxy logs, browser history, referrer headers. Treat as compromised immediately.
Key in source code
Committed credentials can propagate into repository history, forks, build artifacts, caches, and logs even after the visible source line is removed.
!
No rotation policy
An indefinitely valid key can outlive its owner, workload, or intended purpose. Without ownership and usage telemetry, exposure may go unnoticed.
# BAD — key in URL GET /api/data?api_key=sk_live_abc123 # GOOD — key in header GET /api/data X-API-Key: sk_live_abc123
Required Controls

Mandatory

Use a documented header scheme such as a dedicated API-key header. Do not place credentials in URL query parameters.
Define issuance, rotation, overlap, revocation, ownership, and emergency-replacement procedures from the threat model. Do not rely on an arbitrary universal rotation interval.
Use an approved runtime secret mechanism. Do not commit keys, bake them into images, or store them in plaintext configuration.
Scope keys to minimum required permissions. A read-only key should not have write access.
Log and alert on key usage anomalies. Unusual volume, unusual source IPs, off-hours usage.

AI Context

!LLM integrations commonly use API keys to call model endpoints. Scope and monitor them carefully because they may authorize costly inference, access to stored data, or management operations.
Do not place API keys in prompts or model context. Context can propagate into application, proxy, tracing, evaluation, or provider systems.
Risk Verdict

Static bearer API keys provide limited identity and lifecycle semantics compared with modern token or signed-request designs. Use them only with explicit transport, storage, scope, rotation, monitoring, and revocation controls.

02

HMAC Request Signing

Hash-Based Message Authentication · Scheme-Specific M2M Control
Design Option
How HMAC Signing Works
01
Build canonical request
Method + path + timestamp + body hash + selected headers. Both sides must agree on exactly what gets signed.
02
Sign with shared secret
HMAC-SHA256(canonical_string, secret_key). The result authenticates the exact canonical bytes to a party that also knows the shared secret.
03
Server verifies
Recomputes the HMAC and compares it in constant time. A timestamp bounds freshness; separate duplicate detection is needed when replays inside that window matter.
Authorization: HMAC-SHA256 keyId=svc-a, timestamp=1716307200, signature=7f3a... # What gets signed: POST\n/api/v2/events\n1716307200\n x-content-sha256:abc...\n # → HMAC-SHA256 of this string with the shared secret
Key Facts

Why It's Stronger Than API Keys

The shared secret is not sent with the request. The signature proves integrity and possession of that secret, subject to the canonicalization and key-management design.
!A timestamp limits the replay window but does not prevent replay inside it. Use a unique request identifier, nonce, sequence, or idempotency key with server-side duplicate detection when replay matters.
Body is included in the signature. Any tampering with the payload invalidates the signature.

Where It's Used

HMAC appears in request-signing and webhook schemes, but their canonicalization, headers, encodings, and replay rules are not interchangeable.
Useful for service-to-service calls when both parties can provision, protect, rotate, and revoke a shared secret.

Limitations

!Both sides must store the shared secret securely. If the receiver is compromised, the secret is compromised.
!Either holder of the shared secret can produce a valid signature. If the receiver must be unable to forge caller signatures, use a reviewed asymmetric request-signature design instead.
Use Case Verdict

HMAC request signing is a useful M2M option when both parties can protect a shared secret and agree on canonicalization. Add timestamp validation and duplicate detection for replay resistance; a timestamp alone is not sufficient.

03

Service Accounts + mTLS

Certificate-Based Identity · High-Assurance M2M Option
Threat-Model Option AI/Agent
Service Identity Model
Each service has a certificate
Issued by a trusted CA and mapped to a workload identity, commonly through a URI or DNS subject alternative name. Lifetime and automated rotation are set by operational risk and recovery requirements.
mTLS at the connection layer
Both client and server present certs. TLS handshake validates both. Connection fails if either cert is invalid, expired, or not trusted by the CA.
Certificate-bound token (when selected)
An RFC 8705 access token bound to the client certificate cannot be used without proving possession of the matching private key, if the resource server enforces the binding.
Key Facts

AI Agent Context

Assign workload identities at the smallest operational boundary that needs independent policy, rotation, revocation, and audit. Avoid sharing one certificate across unrelated services.
SPIFFE-compatible systems are one option for issuing and rotating workload identities. Their trust domain, attestation, and authorization mapping still require design review.
!Operationally expensive. Requires CA, cert issuance pipeline, rotation automation, and revocation (CRL or OCSP).

When to Use

Consider it where mutual workload authentication or bearer-token replay is a material threat and the environment can operate certificate issuance, rotation, revocation, and key protection reliably.
Use Case Verdict

mTLS plus workload identity is a strong option when the threat model requires mutual authentication or certificate-bound tokens and the deployment can operate PKI safely. Automated issuance, rotation, revocation, and workload identity are part of the control.

Resource and Business Authorization

Authentication establishes who or what is calling. Every handler must still decide whether that principal may perform this action on this resource, property, tenant, and business workflow.

01

Object-Level Authorization

OWASP API1:2023 · BOLA / IDOR · Tenant Isolation
Critical
Failure and Negative Test
# Caller has scope orders:read, but owns order A only GET /orders/B Authorization: Bearer <valid-token> FAIL: handler loads B by identifier and returns it PASS: query or policy constrains B to caller + tenant
Required Controls
Authorize every object lookup using the authenticated subject, tenant, requested action, and resource attributes. A valid token and broad scope are not sufficient.
Apply the ownership or tenant constraint in the data query or centralized policy decision, not only in a user-interface filter.
Test horizontal access, cross-tenant access, guessed identifiers, nested resources, bulk operations, exports, and indirect references.
!Opaque or random identifiers reduce guessing but do not replace authorization.
Authorization Boundary

Gateway scopes can reject obviously disallowed operations, but object ownership and tenant isolation normally require application or policy-layer context. Source: OWASP API1:2023.

02

Property and Function Authorization

OWASP API3 + API5 · Mass Assignment · Privileged Functions
Critical
Attack Examples
PATCH /users/me { "display_name": "A", "role": "admin" } GET /admin/export Authorization: Bearer <ordinary-user-token>
Required Controls
Use explicit input and output schemas. Allowlist writable and readable properties for the caller and operation; do not bind request bodies directly to privileged domain objects.
Authorize the HTTP method and business function independently from route visibility. Default deny newly added administrative endpoints.
Test ordinary users against administrative routes, alternate methods, hidden fields, bulk updates, and response fields containing confidential properties.
Authorization Boundary

Schema validation determines shape; authorization determines which principal may read or write each property and invoke each function. Sources: API3 and API5.

03

Sensitive Business Flows

OWASP API6:2023 · Automation and Economic Abuse
High
Flows to Identify
Account creation, password recovery, reservations, purchases, referral credits, voting, inventory holds, exports, and expensive AI actions can be abused with valid credentials.
!A technically authorized request can still violate business limits or automate a flow intended for bounded human use.
Controls and Verification
Define invariants, per-principal and per-tenant quotas, state-transition rules, idempotency behavior, and step-up approval for consequential actions.
Detect distributed low-rate abuse using account, device, payment, destination, and workflow signals rather than IP address alone.
Test concurrency, retries, replay, race conditions, and automation that stays below simple request-rate thresholds.
Business Control

Rate limiting is only one defense. The application must enforce business invariants and state transitions. Source: OWASP API6:2023.

JWT Security

JWTs are common in API authentication and authorization, but safe validation depends on the exact token profile. These are concrete attacks and the validation rules that address them.

01

Algorithm Confusion Attack

alg:none / RS256→HS256 Downgrade · Critical
Critical
How The Attack Works
1
alg:none attack
Attacker sets the header alg to "none". Vulnerable libraries accept unsigned tokens because they follow the header's algorithm instruction, not a server-enforced allowlist.
2
RS256 → HS256 downgrade
Server uses RS256 (asymmetric). Attacker changes header to HS256, signs the token with the server's public key (which is often publicly available). Vulnerable servers verify with the public key as the HMAC secret.
# Vulnerable header { "alg": "none", "typ": "JWT" } # Fix: server-side allowlist, never trust header # Python example jwt.decode(token, key, algorithms=["RS256"], # explicit allowlist options={"verify_signature": True} )
Required Controls
Server must enforce an explicit algorithm allowlist. Never derive the algorithm from the token header.
Reject tokens with alg:none unconditionally. No exceptions.
If using asymmetric signing, keep signing private keys separate from verification public keys and configure the expected algorithm explicitly.
Choose an approved algorithm that your ecosystem implements safely. ES256 has smaller keys and signatures than RSA, but it is not inherently misuse-proof. FAPI 2.0 permits PS256, ES256, and EdDSA with Ed25519.
Critical Verdict

Algorithm-confusion defenses require more than signature success. Configure the expected token profile and algorithm set server-side, reject unsupported algorithms including none, use the correct key type, and test negative cases.

02

Missing Claim Validation

Profile-specific claims · Audience and Token-Type Confusion
High
Define the Token Profile First
# Generic JWT (RFC 7519): required claims are context-dependent. # The application MUST define and enforce its accepted profile. # OAuth JWT access token profile (RFC 9068): require: typ=at+jwt, iss, exp, aud, sub, client_id, iat, jti validate: signature, algorithm, issuer, audience, time, token type # Client credentials under RFC 9068 still has sub: sub → identifies the client application, not a human user # Never accept an ID token where an access token is expected.
Key Facts
Signature validation alone is not enough. A token signed by a trusted IdP for a different service is still not valid for your service.
Accepting a token without enforcing the claims required by its profile can create indefinite lifetime, token-substitution, or cross-service access.
Validate aud against a hardcoded list of acceptable audience values for your service. Reject anything not on the list.
Use an explicit token type and mutually exclusive validation rules for access tokens, ID tokens, authorization assertions, and other JWT kinds.
Project recommendation: choose token lifetimes from the threat model and recovery design. Shorter access-token lifetimes reduce theft exposure but increase authorization-server dependency.
!AI context: LLM services calling downstream APIs must validate the aud claim. A token issued for the LLM frontend is not valid for the backend data API.
High Risk Verdict

Library defaults vary. Configure the accepted token type, algorithms, issuer, audience, required claims, and clock-skew policy explicitly, then test rejection of a token from the wrong profile or audience.

03

JWT Storage and Transport

Where You Store It Determines How It Gets Stolen
Medium
Storage Options + Attack Vectors
# BAD: localStorage — XSS can read it localStorage.setItem('token', jwt) # BAD: sessionStorage — still XSS-accessible sessionStorage.setItem('token', jwt) # BETTER: HttpOnly cookie — XSS cannot read Set-Cookie: token=...; HttpOnly; Secure; SameSite=Strict # COMMON M2M PATTERN: protected in-memory cache # Persist only when the threat model and platform require it # Refresh via client_credentials when expired
Key Facts
localStorage is accessible by any JavaScript on the page. One XSS vulnerability = token theft.
HttpOnly cookies prevent direct JavaScript reads, but injected scripts can still act through the browser. Choose SameSite behavior and CSRF defenses for the application's cross-site flows.
M2M services commonly use a protected in-memory cache. Persist a token only when the workload and availability design require it, using platform-protected storage with narrow access and a defined cleanup policy.
!Environment variables can propagate to child processes and may be exposed through process inspection, diagnostics, or orchestration APIs. Prefer narrowly mounted or brokered runtime credentials when the platform supports them.
Storage Verdict

Choose storage from the client type and threat model. Browser applications commonly use a backend-for-frontend or Secure, HttpOnly cookies with CSRF defenses. M2M services commonly use a protected in-memory cache. Avoid exposing bearer tokens to script-readable browser storage.

04

JWKS Resolution and Rotation

Issuer Binding · kid Ambiguity · Cache State
Critical
Resolution Rules
Configure trusted issuers and their HTTPS metadata or JWKS locations. Do not accept a token-supplied jku or x5u as an unrestricted fetch target.
Filter keys by intended use, algorithm, and key type. Reject duplicate eligible keys with the same kid as ambiguous instead of selecting by array order.
On an unknown kid, perform a bounded refresh with request coalescing and cooldown. A miss must not create an attacker-controlled fetch loop.
Cache-State Tests
Project baseline: a successful, well-formed set containing zero usable signing keys is authoritative and evicts the old set.
Project baseline: malformed, truncated, non-success, and transport-failed refreshes do not replace a last-known-good set, but the request that required the failed refresh still fails.
Test initial load, planned overlap rotation, rotated-out keys, duplicate kid, zero usable keys, malformed JSON, timeout, concurrency, cooldown, and recovery.
Key-State Boundary

JWKS handling is a state machine, not a one-time signature lookup. Document which responses are authoritative and which are retrieval failures. Sources: RFC 8414, RFC 8725, and the FAPI 2.0 JWKS requirements.

05

Revocation and Introspection

Early Termination · Opaque vs Self-Contained Tokens
High
Choose the Enforcement Model
Self-contained JWTs support local validation, but a resource server will normally accept them until expiry unless it also consults current state.
Opaque tokens normally require introspection or gateway lookup, adding a live dependency but enabling centralized active-state decisions.
!A jti claim does not revoke anything by itself. A resource server must consult an authoritative denylist or another active-state mechanism.
Required Decisions and Tests
Define maximum exposure after account disablement, logout, client compromise, signing-key compromise, and grant withdrawal.
Protect revocation and introspection endpoints with authenticated clients, least privilege, TLS, rate limits, and non-sensitive error responses.
Test that a revoked grant or inactive token becomes unusable within the documented bound, including through gateway and application caches.
Lifecycle Boundary

Short lifetimes limit exposure; they do not answer every immediate-revocation requirement. Sources: RFC 7009 and RFC 7662.

06

Delegation and Identity Chains

Token Exchange · Actor Identity · Audience Narrowing
High Agent
Unsafe Pattern
User token → Agent A → Agent B → Data API FAIL: the same bearer token is forwarded through every hop PASS: each hop obtains an audience-bound token with narrowed rights and preserved subject/actor context
Controls
Separate the resource owner, requesting client, acting workload or agent, and target resource in policy and audit records.
Use token exchange only when supported by the trust architecture. Narrow audience, scope, lifetime, and delegation depth at every hop.
Reject token passthrough and confused-deputy designs where a middle tier forwards a token not issued for the downstream resource.
Delegation Boundary

Do not infer delegation merely because a service possesses a user's token. Preserve actor context and exchange for a token intended for the next resource. Source: RFC 8693.

API Gateway Enforcement

Use the gateway for shared edge controls such as TLS policy, coarse token validation, request limits, and rate limiting. Restrict direct service access. Keep object, property, tenant, and business authorization in the application or its policy layer.

🏗 What the Gateway Should Own

TLS termination and minimum version enforcement (TLS 1.2+ minimum, TLS 1.3 preferred)
Auth token validation (JWT signature, claims, expiry)
Rate limiting and throttling per client, per endpoint
IP allowlisting for internal services
Request size limits — prevent payload floods
mTLS enforcement for M2M routes
API versioning routing and deprecation cutoffs
Centralized audit logging with request ID correlation

⚠ Common Gateway Misconfigurations

Auth validation in app code only — bypassed when gateway routes to service directly
TLS 1.0/1.1 still enabled — scan your gateway cipher suites
No request size cap — downstream services get flooded with multi-MB payloads
Internal services directly accessible without going through the gateway
Different rate limits for prod vs staging — attackers fingerprint and exploit staging
!AI endpoints (LLM inference) not behind the same gateway controls as other APIs
01

Gateway Security Evaluation

Verify Behavior, Not Product Labels
Reference
Requirement Evidence to Require
JWT verificationNegative tests for wrong issuer, audience, type, algorithm, signature, time, and required claims.
JWKS lifecycleRotation, duplicate and unknown kid, malformed refresh, cache, cooldown, and revocation-state tests.
mTLS / DPoPHandshake or proof validation, token confirmation binding, replay behavior, failure telemetry, and key rotation.
Authorization boundaryDocument which coarse checks run at the gateway and which object, property, tenant, and business checks remain in the service.
Resource controlsPer-principal and per-tenant rate, concurrency, request-size, decoded-size, timeout, and cost limits.
Logging and privacyCorrelated security events with credential, token, prompt, personal-data, and body redaction verified.
Bypass resistanceNetwork tests prove protected services are not directly reachable around the gateway.
! Product capability claims age quickly. Build a deployment-specific acceptance test and record the product version, configuration, and evidence.

API Input, Output, and Egress Boundaries

APIs cross trust boundaries in both directions. Validate what clients send, constrain where the service can connect, and treat upstream responses as untrusted input.

01

Server-Side Request Forgery

OWASP API7:2023 · User-Controlled Destinations
Critical
Test Inputs
http://127.0.0.1/admin http://169.254.169.254/ http://[::1]/ https://allowed.example/redirect-to-private https://name-that-rebinds.example/
Required Controls
Avoid arbitrary server-side fetches. Prefer identifiers mapped to configured destinations over caller-supplied URLs.
When URLs are required, allowlist scheme, host, and port; resolve and reject loopback, link-local, private, multicast, and otherwise prohibited address ranges.
Revalidate every redirect target, restrict protocols, apply response-size and timeout limits, and enforce network egress policy independently of application validation.
Test alternate IP encodings, IPv6, redirects, DNS rebinding, credentials in URLs, and cloud metadata destinations.
Egress Boundary

URL parsing alone is insufficient. Application validation and network egress restrictions must agree. Source: OWASP API7:2023.

02

Unsafe Consumption of APIs

OWASP API10:2023 · Upstream Responses Are Untrusted
High
Common Failure
The service trusts a partner API more than a public client, then writes unexpected fields, follows redirects, renders markup, or passes upstream text into an interpreter or LLM tool loop.
Long timeouts, unlimited retries, and unbounded response bodies let an upstream dependency exhaust local resources.
Controls and Verification
Validate upstream status, media type, schema, size, and semantic bounds before using the response. Ignore or reject unknown security-sensitive fields.
Use TLS verification, explicit destinations, bounded timeouts, bounded retries with backoff, circuit breakers, and separate credentials per dependency.
Fuzz malformed, oversized, slow, redirected, duplicated-field, and semantically hostile upstream responses.
!Retrieved text used by an LLM remains untrusted even when it came from an authenticated partner API.
Dependency Boundary

Authentication of an upstream system does not make all of its data safe for every downstream use. Source: OWASP API10:2023.

03

Request and Response Contracts

Schema · Content Type · Size · Error Surface
High
Contract Controls
Allowlist media types, methods, fields, enum values, numeric ranges, collection lengths, nesting depth, and total decoded bytes before expensive processing.
Define duplicate-key handling, reject non-finite numbers where the contract requires interoperable JSON, and avoid unsafe native-object deserialization.
Return stable error codes and correlation identifiers without stack traces, credentials, internal paths, SQL fragments, prompts, or upstream response bodies.
Verification
Generate negative tests from the API schema and add adversarial cases for duplicate fields, deep nesting, oversized compressed bodies, unsupported encodings, and ambiguous Unicode.
Test the decoded-body limit, not only the compressed wire size, and apply limits before logging or buffering entire bodies.
Validate response schemas too, particularly where authorization determines which properties may leave the service.
Contract Boundary

A schema is both an interoperability contract and a security allowlist. Keep authorization checks separate because valid shape does not imply permitted access.

Rate Limiting and Throttling

Rate limiting is both an availability control and a security control. Without it, a single caller can exhaust your service, enumerate your data, or run brute-force attacks. AI endpoints have additional exposure because inference is expensive and slow.

01

Rate Limit Strategies

Fixed Window, Sliding Window, Token Bucket, Leaky Bucket
Reference
Strategy Comparison
StrategyBurst HandlingUse Case
Fixed WindowEdge burstSimple quotas. Easy to implement. Vulnerable to burst at window boundary.
Sliding WindowGoodMore accurate than fixed. Good for general API rate limiting.
Token BucketAllows burstAllow controlled burst with long-term average limit. Good for variable-load APIs.
Leaky BucketNo burstSmooth output rate. Good for protecting slow downstream services.
What to Rate Limit
Per API key or client ID — prevent a single caller from monopolizing capacity
Per IP address — secondary control for unauthenticated endpoints
Per endpoint — your inference endpoint needs tighter limits than your health check
Per user (for multi-tenant AI) — prevent one tenant from degrading others
!AI-specific: limit input tokens, output tokens, concurrent work, and cost in addition to request count. Requests can differ by orders of magnitude in compute and spend.
When rejecting a request for rate limits, return 429 and communicate retry timing where it is safe and meaningful for the policy.
AI Endpoint Verdict

Request-count limits alone can miss large differences in inference cost. Combine them with bounds on input and output tokens, concurrency, execution time, tool calls, and spend where those dimensions apply.

Webhook Security

Webhooks reverse the API call direction — a third-party calls your endpoint. That means you have no control over the caller at the network level. Verification happens at the payload level.

01

HMAC Payload Verification

The Standard Webhook Security Pattern
Required
Verification Pattern
# Illustrative GitHub-compatible example: signature = HMAC-SHA256(raw_body, webhook_secret) Header: X-Hub-Signature-256: sha256={signature} # A compatible receiver must: # 1. Read raw body bytes BEFORE parsing JSON # 2. Compute expected signature # 3. Compare the decoded signature in constant time # WRONG — timing attack vulnerable if received_sig == expected_sig: # RIGHT — constant-time if hmac.compare_digest(received_sig, expected_sig):
Required Controls
Complete the provider-defined authenticity check before executing business logic. For an HMAC scheme, verify the signature over the exact documented bytes before parsing or acting.
Decode the provider's signature representation and use a constant-time comparison function to avoid content-dependent comparison behavior.
If the provider signs a timestamp, validate it within a documented window. Also reject duplicate event or delivery identifiers because a timestamp alone does not prevent replay inside the window.
Acknowledge promptly only after the event is durably accepted or recorded. Process asynchronously with idempotency so retries cannot repeat consequential work.
Do not use source-IP allowlisting as the sole authenticity control. Verify the provider-defined signature or other authenticated transport independently.
!AI context: model-job callbacks need the same control objectives, but use the provider's documented authentication scheme and signed-byte definition. Treat any resulting privileged action as a separate authorization decision.
Webhook Verdict

A webhook receiver needs a provider-defined authenticity and integrity check, replay handling, durable acceptance, idempotent processing, and secret or key rotation. HMAC is common, but the exact signed bytes and header format are scheme-specific.

CORS — Cross-Origin Resource Sharing

CORS is a browser-enforced policy. It does not protect your API from non-browser callers. Its purpose is to control which web origins can make cross-origin requests from a browser. Misconfiguration is extremely common and often has high impact.

01

CORS Misconfigurations

Origin Reflection, Wildcard + Credentials, Null Origin
Critical
The Three Critical Misconfigs
# 1. ORIGIN REFLECTION (Critical) Access-Control-Allow-Origin: [whatever the request sent] # If credentials are allowed, an attacker origin may read the response. # 2. WILDCARD + CREDENTIALS (Invalid but dangerous when misconfigured) Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true # Browsers reject this combination. # Reflecting the request Origin instead creates a credentialed cross-origin risk. # 3. NULL ORIGIN (High) Access-Control-Allow-Origin: null # Sandboxed iframes and local files send Origin: null # Attacker can craft a page that sends null origin # CORRECT PATTERN Access-Control-Allow-Origin: https://app.yourdomain.com # Explicit allowlist. No reflection. No null. No wildcard + creds.
Required Controls
Maintain an explicit allowlist of permitted origins. Validate incoming Origin header against the list. Return the matching origin or nothing.
Never reflect the Origin header value directly into Access-Control-Allow-Origin without allowlist validation.
Reject Origin: null unless a documented sandboxed or local-origin use case requires it and has an independent authorization boundary.
A public, unauthenticated read-only resource may use wildcard (*). A browser request using credentials mode requires an explicit allowed origin rather than wildcard.
When the allowed origin varies by request, send Vary: Origin so shared caches keep responses separate.
!CORS does not apply to server-to-server calls or curl. It is browser-only. CORS alone is not an API security control — it is a browser behavior control.
!AI apps served from a CDN calling an LLM backend: make sure the CORS policy allows the exact frontend origin. Wildcard here means any page on the internet can call your LLM endpoint from a user's browser.
CORS Verdict

Unvalidated origin reflection can expose credentialed responses to an attacker-controlled origin. Review framework behavior and cache handling. Use an explicit allowlist and emit Vary: Origin when the response header varies by request.

AI-Specific API Threats

Standard API security controls are necessary but not sufficient for AI systems. These threats are specific to APIs that sit in front of or behind LLMs, agents, and ML inference endpoints.

01

Prompt Injection via API

Indirect Prompt Injection · Agent Hijacking
Critical AI-Specific
Attack Pattern
1
Direct injection
Attacker sends a crafted API payload containing instructions that override the system prompt. The LLM follows the injected instruction instead of the application's intended behavior.
2
Indirect injection
Agent reads external data (email, document, web page) that contains injected instructions. The agent acts on the instructions as if they came from the user. The API call looked clean — the data it fetched was malicious.
3
Exfiltration via output
Injection instructs the LLM to include sensitive data (session tokens, API keys, user PII) in its response, which the application then returns to the attacker via the API response.
Controls
Treat all external data, including retrieved documents and tool output, as untrusted. Sanitization can block known patterns but is not a complete prompt-injection boundary.
Separate system prompt from user-controlled input at the API call level. Use structured message formats, not string concatenation.
Output validation: scan LLM responses for sensitive patterns (API key formats, JWT patterns, PII) before returning to caller.
Principle of least privilege for agents: the agent's API credentials should only have access to what it needs for its specific task.
!No complete technical solution exists yet. Layered controls reduce risk. Defense in depth: input sanitization + output filtering + capability scoping + audit logging.
AI Threat Verdict

Prompt injection has no parameterization boundary equivalent to prepared SQL statements. Manage it with capability scoping, no ambient authority, approval for consequential actions, provenance-aware handling of retrieved content, and output validation. Input filtering alone is not sufficient.

02

Model Endpoint Abuse

Inference Cost Attacks, Model Extraction, Data Extraction
High AI-Specific
Attack Types
$
Cost exhaustion
Send maximum-token requests at high volume. Inference is expensive. Attacker runs up compute bill or degrades service for other users.
Model extraction
Systematic querying to reconstruct model behavior, fine-tuning data, or proprietary system prompts. Often done at low rate to avoid rate limiting.
Training data extraction
Specific prompts designed to cause the model to regurgitate training data, potentially including PII or proprietary content.
Controls
Token-based rate limits per caller. Set max input tokens and max output tokens per request and per time window.
Cost-based quotas per API key. Alert when a key's spend exceeds expected baseline.
Detect systematic enumeration patterns in access logs. Low-volume, high-diversity queries probing the same endpoint are a signal.
!Do not put secrets in a system prompt or treat the prompt as a confidentiality boundary. Output filtering is only a secondary control because equivalent content can be transformed or paraphrased.
Abuse Verdict

AI inference endpoints have a cost dimension that standard APIs don't. Standard request-count rate limiting is insufficient. You need token quotas, cost tracking, and anomaly detection on usage patterns. Treat inference budget management as a security control, not just a cost control.

03

Sensitive Data in LLM Context

Data Leakage Through Model Inputs and Outputs
High AI-Specific
Leakage Vectors
API keys and tokens in prompts can propagate into provider, proxy, tracing, evaluation, or application logs. Treat a secret placed in model context as exposed beyond its intended boundary.
Personal or regulated data sent to an external model without an approved purpose, data-flow review, retention policy, and contractual controls can violate organizational or legal obligations.
Cross-tenant data leakage in multi-user systems — one user's context bleeds into another's response when conversation history is mismanaged.
Verbose error responses from the LLM API revealing internal system details, file paths, or data schemas.
Controls
PII detection and redaction before sending to external LLM. Use Presidio, AWS Comprehend, or equivalent.
Use approved private connectivity where it reduces network exposure, and separately verify provider processing, retention, training-use, regional, and support-access terms.
Isolate conversation state by principal and tenant by default. Any collaborative or shared context needs explicit authorization, provenance, and revocation behavior.
Output scanning for PII and secrets before returning LLM response to caller.
Data Leakage Verdict

Every call to an externally operated model is a potential third-party data transfer. Classify prompt and retrieval content, minimize it, confirm the approved purpose and contract, isolate tenants, and validate outputs. Private network connectivity does not settle data-use or retention questions.

04

Agent Authority and Tool Use

Excessive Agency · Tool Misuse · Consequential Actions
Critical Agent
Authority Model
Give each agent an explicit allowlist of tools and operations. Do not expose destructive or administrative functions merely because the integration supports them.
Issue credentials per agent, tenant, task, and target resource where practical. Avoid shared ambient credentials inherited from the host process.
Re-authorize every tool call against the verified principal and current context. Model output is a request for an action, not proof that the action is permitted.
Approval and Verification
Require a clear human confirmation for destructive, external-communication, financial, privilege-changing, or broad data-export actions.
Bind approval to the exact action parameters and expiry. Do not reuse a generic approval after the destination, scope, or payload changes.
Independently verify high-impact claims and action parameters before execution. Model confidence and fluent output are not evidence.
Define timeouts, circuit breakers, bounded retries, rollback or compensation, and an emergency stop so one agent failure does not cascade unchecked.
Test direct and indirect prompt injection, tool-argument substitution, approval bypass, confused deputy, cross-tenant calls, and retry after partial failure.
Agent Boundary

The deterministic authorization layer, not the model, owns capability and approval decisions. Sources: OWASP LLM06:2025 and the OWASP Agentic Top 10 2026.

05

AI Supply Chain, Retrieval, and Memory

Models · Datasets · Embeddings · Tools · Persistent Context
High AI-Specific
Assets and Trust Boundaries
Models, adapters, datasets, prompt templates, agent skills, MCP servers, embedding models, vector indexes, and evaluation data can introduce malicious or corrupted behavior.
Persistent memory can turn one malicious interaction into durable instructions or cross-session data leakage.
!Similarity search is not authorization. Retrieval must enforce tenant and document permissions before content enters model context.
Controls and Verification
Pin and inventory model, tool, skill, and server identities; verify provenance and signatures where available; review permissions before installation or update.
Partition retrieval and memory by tenant and principal. Apply authorization before retrieval and again before returning cited source content.
Make memory writes explicit, attributable, reviewable, and reversible. Treat retrieved and remembered content as untrusted on every later use.
Test poisoned documents, adversarial metadata, stale permissions, deleted sources, malicious tool descriptions, compromised dependencies, and cross-tenant vector matches.
Supply-Chain Boundary

AI artifacts and retrieved content are executable influence even when they are not executable code. Sources: OWASP LLM03:2025, LLM04:2025, and LLM08:2025.

API Versioning and Deprecation Security

Every live API version remains part of the attack surface. Older versions become higher risk when fixes, authorization policies, inventory, monitoring, or gateway controls diverge from the current version.

🔴 Why Old Versions Are Dangerous

A patch applied only to the current version leaves any equivalent deprecated endpoint vulnerable.
Older versions may retain weaker authentication or token-validation requirements after the current version changes.
Object-authorization fixes must be verified across every version that exposes the same resource.
Route-specific gateway, WAF, schema, and rate-limit rules can drift or omit legacy endpoints.
!Generated clients, agent tools, and long-lived integrations can keep an old version active after normal user interfaces have migrated.

✅ Deprecation Controls

Maintain an API version inventory. Know which versions are live, who is using them, and what their security posture is.
Set and enforce sunset dates. Use the Deprecation header and deprecation documentation link from RFC 9745, plus the Sunset header from RFC 8594 when a shutdown date is planned.
Apply the same gateway security controls (auth, rate limiting, WAF) to all versions, not just current.
Enforce a reviewed migration deadline. After shutdown, return a status and documentation appropriate to the resource state; 410 Gone is suitable when it is intentionally and permanently unavailable.
Monitor old version usage. Alert on any traffic to sunset endpoints — it's either a migration failure or an attacker who found a soft target.

API Security Review Checklist

Use this for design reviews, vendor assessments, and internal API audits. Click each item to mark it complete. Progress is not saved — copy this to your review document.

0 / 30 complete

API keys never appear in URL query parameters

Use the documented header scheme. Scan logs for api_key= or token= in URL patterns.

Critical

Secrets use an approved runtime mechanism and rotation policy

Not committed, baked into images, or stored in plaintext configuration. Exposure through environment, process, diagnostic, and orchestration surfaces has been assessed.

Critical

JWT algorithm explicitly allowlisted server-side

alg:none rejected. An approved algorithm set is enforced for the token profile. Never select the verifier from an untrusted alg header alone.

Critical

JWT profile and required claims explicitly enforced

Token type, algorithm, issuer, audience, time claims, and every profile-required claim are configured explicitly. Wrong token types and audiences are rejected.

Critical

CORS origin allowlist in place — no dynamic reflection

Use an explicit list. Reject the null origin unless a documented use case and compensating controls require it.

Critical

Webhook authenticity and replay controls match the provider's scheme

Verify the exact signed bytes before acting. Where supplied, validate signed time and event identifiers; process idempotently.

High

Rate-limit coverage is documented for every reachable endpoint

Document exceptions. Apply per-client and per-operation controls; AI endpoints also bound tokens, concurrency, time, tool calls, and cost where applicable.

High

TLS 1.2 minimum enforced at gateway. TLS 1.0/1.1 disabled.

Scan cipher suite config. TLS 1.3 preferred where clients support it.

High

M2M services use non-user workload identities and appropriate grants

No shared user accounts for service-to-service calls. Use client credentials, workload identity, token exchange, or another reviewed non-user design as applicable.

High

Deprecated API versions retain an equivalent security baseline

Authentication, authorization, gateway, schema, monitoring, and abuse controls remain effective until the sunset date is enforced.

High

Token lifetime, renewal, and early-revocation bounds are documented

Access-token exposure, refresh-token rotation, introspection, revocation, cache behavior, and authorization-server availability are tested against the threat model.

High

API keys scoped to minimum required permissions

Read-only keys cannot write. Per-endpoint scoping where the platform supports it.

Medium

Request size limits enforced at gateway

Max request body size. Max URL length. Prevents payload flood and some injection attacks.

Medium

Security-relevant API events carry a request ID for correlation

Record auth failures, policy denials, 4xx/5xx rates, and usage anomalies with sensitive fields redacted. Document intentionally unlogged traffic.

Medium

Error responses do not expose internal details

No stack traces, file paths, DB errors, or schema info in API error responses.

Medium

[AI] Secrets are excluded from prompts, retrieval, memory, and context windows

Model context can propagate into application, proxy, tracing, evaluation, or provider systems. Inject credentials only at the deterministic tool boundary.

AI

[AI] External-model data flows are classified, minimized, and approved

Purpose, retention, training use, region, contract, tenant isolation, and necessary redaction or transformation are documented.

AI

[AI] Model output is validated for its downstream use

Apply schema, authorization, encoding, destination, and sensitive-data checks before displaying output, executing code, calling tools, or sending external messages.

AI

[AI] Agent capabilities scoped to minimum required for its task

Least privilege for agent API credentials. An agent that reads email should not write to the DB.

AI

[AI] Model-provider network and data-handling controls are reviewed separately

Private connectivity reduces network exposure but does not by itself settle provider processing, retention, training, region, or support access.

AI

Object and tenant authorization enforced on every resource operation

Cross-user, cross-tenant, nested-resource, bulk, export, and guessed-identifier tests fail closed even with a valid token and scope.

API1

Readable fields, writable fields, and privileged functions are allowlisted

Mass assignment, confidential response properties, alternate methods, and administrative routes are tested with an ordinary principal.

API3/5

Sensitive business flows enforce invariants beyond request-rate limits

Quotas, state transitions, idempotency, concurrency, replay, and distributed low-rate automation are tested.

API6

JWKS rotation and failure-state matrix is tested

Unknown and duplicate kid, zero usable keys, malformed/truncated response, timeout, concurrency, cooldown, rotation overlap, and recovery have explicit expected outcomes.

Critical

Revoked or inactive tokens fail within the documented bound

Revocation, introspection, denylist, gateway cache, application cache, and account-disable paths agree.

High

Server-side fetches resist SSRF bypasses

Explicit destinations, address-range rejection, redirect revalidation, DNS rebinding, metadata endpoints, size/time limits, and network egress policy are tested.

API7

Upstream API responses are treated as untrusted

Status, media type, schema, size, redirects, timeouts, retries, and hostile content are validated before downstream use.

API10

[MCP] Resource metadata, PKCE, audience binding, and no token passthrough verified

Remote HTTP MCP uses the pinned specification revision. Upstream API calls receive separate tokens intended for those resources.

MCP

[AI] Consequential agent actions require parameter-bound approval

Destructive, financial, privilege-changing, data-export, and external-communication actions cannot proceed on model output alone.

Agent

[AI] Retrieval and persistent memory enforce principal and tenant boundaries

Poisoned content, malicious metadata, stale permissions, deleted sources, cross-tenant vector matches, and memory-write provenance are tested.

AI