CORS misconfiguration: which sites a browser lets read your responses, and the settings that let the wrong ones in
Cross-origin resource sharing (CORS) is how your server tells a visitor's browser which other websites may read its responses.
It does not stop simple requests reaching your server, and it does not check who is asking. This guide explains the headers, the preflight and the five misconfigurations that hand the read to sites you never meant to trust, with a request trace and a regression test you can run with Node.js alone.
In this guide
CORS request trace and regression test
An illustration on invented origins and a made-up account. A Node.js lab with no installs sends simple and preflighted requests from an allowed origin, a disallowed origin and with credentials under seven CORS policies, and prints each request's headers, each response's headers, the server's log line and two verdicts: what the scripted client received, and whether a browser would let the page read it, decided from the real headers by the Fetch Standard's rules.
How to use itHide the instructions
A regression test asserts headers and visibility, passing only on the exact allow-list, and steps show the same in your own browser. For learning and for testing a policy you own.
cors-misconfiguration.txt
Introduction26 lines
Part 1: The lab files630 lines
Part 2: The request trace315 lines
Part 3: The regression test228 lines
Part 4: See it in your own browser20 lines
Part 5: Point the test at your own API5 lines
Part 6: A CORS policy record to fill in18 lines
Whole template1,278 lines
ILLUSTRATION ONLY. The API, its account and every origin below (app.example.com, api.example.com, staging-app.example.com, attacker.example.net and app.example.com.attacker.example.net) are invented for this page. The lab runs on your own machine, binds to 127.0.0.1, keeps everything in memory and serves made-up data. Use it for learning and for testing a CORS policy you own.
What this asset is, and what it is not. Part 1 is a Node.js lab: an API with seven switchable CORS policies, a scripted client and a regression test. For every exchange, the trace in Part 2 prints the request headers that matter, the response headers, the server's own log line and two verdicts side by side: what the scripted client received, which is always whatever the server sent, and whether a browser would let the calling page read it. The second verdict comes from browser-rules.mjs, which applies the WHATWG Fetch Standard's CORS check and preflight rules to the real response headers. It is not a browser: it leaves out the preflight cache, redirects, the length limits on safelisted header values, the Range header and the cookie rules. Part 4 shows you how to check it against your own browser.
The cookie assumption. With credentials, the scripted client always sends the session cookie. A real browser sends it to another site only when the cookie's SameSite attribute and the browser's third-party cookie settings allow it (MDN Set-Cookie; MDN CORS guide). The trace shows the case where they do.
Written and run on: Node.js 26.0.0, the only version it was run on. It uses node:http, node:crypto, node:test and node:assert, which ship with Node.js, so there is nothing to install. Every output below comes from that run; timings and ports will differ on your machine.
What browser-rules.mjs follows: the WHATWG Fetch Standard (Living Standard, last updated 19 October 2026), the sections "CORS check", "CORS-preflight fetch" and "HTTP fetch", and the definitions of "CORS-safelisted method", "CORS-safelisted request-header", "CORS-unsafe request-header names" and "CORS non-wildcard request-header name".
The seven policies:
none no CORS headers at all
allow-list the whole origin must be on a written list (https://app.example.com); credentials allowed; Vary: Origin
wildcard Access-Control-Allow-Origin: *
wildcard-credentials * with Access-Control-Allow-Credentials: true
reflect-credentials copies any Origin into Access-Control-Allow-Origin with credentials, and echoes the requested headers on a preflight
prefix-match accepts any origin that starts with https://app.example.com
null-allowed the allow-list, plus null
The five requests sent under each policy:
1 GET /api/account from the app's own origin, with credentials
2 GET /api/account from the disallowed origin, with credentials
3 GET /internal/report, a route with no sign-in that trusts its network, from the disallowed origin, without credentials
4 POST /api/notes with a JSON body from the app's own origin, with credentials (a Content-Type of application/json needs a preflight)
5 the same POST from the disallowed origin
The disallowed origin is https://attacker.example.net, except under prefix-match (https://app.example.com.attacker.example.net) and null-allowed (null), where the trace uses the origin that gets through.
================================================================
PART 1: THE LAB FILES
================================================================
Make an empty folder, save the five files below into it with the names shown, and open a terminal in that folder.
================================================================
FILE 1 OF 5: cors-lab-api.mjs
================================================================
// cors-lab-api.mjs: an invented API with seven switchable CORS policies, and
// a plain HTTP client that sends whatever headers it is given.
// Illustration only. It listens on 127.0.0.1, keeps everything in memory and
// serves made-up data for one made-up account.
import { createServer, request as httpRequest } from 'node:http'
import { randomBytes } from 'node:crypto'
// The origins this illustration pretends to use. The API would be
// https://api.example.com and its own front end https://app.example.com.
export const APP_ORIGIN = 'https://app.example.com'
export const ATTACKER_ORIGIN = 'https://attacker.example.net'
export const LOOKALIKE_ORIGIN = 'https://app.example.com.attacker.example.net'
// none: no CORS headers. allow-list: the whole origin must be on a written
// list. The other five are the mistakes this lab shows.
export const POLICY_NAMES = [
'none',
'allow-list',
'wildcard',
'wildcard-credentials',
'reflect-credentials',
'prefix-match',
'null-allowed',
]
// options: policy, allowedOrigins (defaults to the app origin), port
// (defaults to one the system picks) and logRequests (print each request).
export function startCorsLab(options) {
const settings = Object.assign({ policy: 'allow-list', allowedOrigins: [APP_ORIGIN], logRequests: false }, options)
if (!POLICY_NAMES.includes(settings.policy)) throw new Error('Unknown policy: ' + settings.policy)
const state = {
sessionId: randomBytes(18).toString('base64url'),
counts: { preflights: 0, accountReads: 0, reportReads: 0, notesSaved: 0 },
log: [],
}
const server = createServer(function (request, response) {
routeRequest(settings, state, request, response)
})
return new Promise(function (resolve) {
server.listen(settings.port || 0, '127.0.0.1', function () {
const port = server.address().port
resolve({ server: server, state: state, port: port, sessionCookie: 'lab_session=' + state.sessionId })
})
})
}
// Whether a policy names this origin in Access-Control-Allow-Origin.
function approvesOrigin(settings, origin) {
if (!origin) return false
if (settings.policy === 'allow-list') return settings.allowedOrigins.includes(origin)
if (settings.policy === 'reflect-credentials') return true
if (settings.policy === 'prefix-match') return origin.startsWith(settings.allowedOrigins[0])
if (settings.policy === 'null-allowed') return settings.allowedOrigins.includes(origin) || origin === 'null'
return false
}
// The CORS headers each policy sends. requestedHeaders is the
// Access-Control-Request-Headers value of a preflight, or '' otherwise.
function buildCorsHeaders(settings, origin, isPreflight, requestedHeaders) {
const headers = {}
if (settings.policy === 'none') return headers
if (settings.policy === 'wildcard' || settings.policy === 'wildcard-credentials') {
headers['Access-Control-Allow-Origin'] = '*'
if (settings.policy === 'wildcard-credentials') headers['Access-Control-Allow-Credentials'] = 'true'
} else {
// The answer depends on the Origin header, so caches must keep one
// answer per origin.
headers['Vary'] = 'Origin'
if (!approvesOrigin(settings, origin)) return headers
headers['Access-Control-Allow-Origin'] = origin
headers['Access-Control-Allow-Credentials'] = 'true'
}
if (isPreflight) addPreflightHeaders(settings, headers, requestedHeaders)
return headers
}
// reflect-credentials echoes whatever headers the preflight asks for.
// The other policies name the one header the app's own page sends.
function addPreflightHeaders(settings, headers, requestedHeaders) {
headers['Access-Control-Allow-Methods'] = 'GET, POST'
const echoHeaders = settings.policy === 'reflect-credentials' && requestedHeaders
headers['Access-Control-Allow-Headers'] = echoHeaders ? requestedHeaders : 'Content-Type'
headers['Access-Control-Max-Age'] = '600'
}
function routeRequest(settings, state, request, response) {
const url = new URL(request.url, 'http://127.0.0.1')
const origin = readHeader(request, 'Origin')
if (request.method === 'OPTIONS') return answerPreflight(settings, state, request, response, origin)
const corsHeaders = buildCorsHeaders(settings, origin, false, '')
const route = request.method + ' ' + url.pathname
if (route === 'GET /api/account') return sendAccount(settings, state, request, response, corsHeaders)
if (route === 'GET /internal/report') return sendReport(settings, state, request, response, corsHeaders)
if (route === 'POST /api/notes') return saveNote(settings, state, request, response, corsHeaders)
if (route === 'GET /lab/sign-in') return signIn(settings, state, request, response)
finish(settings, state, request, response, { status: 404, headers: corsHeaders, body: { error: 'not found' }, note: 'not found' })
}
// The preflight is answered by the CORS policy alone; no route code runs.
function answerPreflight(settings, state, request, response, origin) {
state.counts.preflights += 1
const requestedHeaders = readHeader(request, 'Access-Control-Request-Headers') || ''
const corsHeaders = buildCorsHeaders(settings, origin, true, requestedHeaders)
const note = 'preflight answered (preflights so far: ' + state.counts.preflights + ')'
finish(settings, state, request, response, { status: 204, headers: corsHeaders, body: null, note: note })
}
// The signed-in account. The session cookie, not the Origin, decides.
function sendAccount(settings, state, request, response, corsHeaders) {
if (!hasValidSession(state, request)) {
const refusal = { status: 401, headers: corsHeaders, body: { error: 'sign-in required' }, note: 'refused: no session' }
return finish(settings, state, request, response, refusal)
}
state.counts.accountReads += 1
const note = 'account data sent (account reads so far: ' + state.counts.accountReads + ')'
const account = { name: 'Sam Example', plan: 'Team' }
finish(settings, state, request, response, { status: 200, headers: corsHeaders, body: account, note: note })
}
// A route with no sign-in, because it trusts the network it sits on.
function sendReport(settings, state, request, response, corsHeaders) {
state.counts.reportReads += 1
const note = 'office-only report sent (report reads so far: ' + state.counts.reportReads + ')'
const report = { report: 'office rota', access: 'anyone who can reach this server' }
finish(settings, state, request, response, { status: 200, headers: corsHeaders, body: report, note: note })
}
// A state-changing route: JSON only, and only for the signed-in session.
// The note itself is not stored; the count is the evidence.
async function saveNote(settings, state, request, response, corsHeaders) {
await readBody(request)
const contentType = (readHeader(request, 'Content-Type') || '').split(';')[0].trim()
if (contentType !== 'application/json') {
const refusal = { status: 415, headers: corsHeaders, body: { error: 'JSON only' }, note: 'refused: not JSON' }
return finish(settings, state, request, response, refusal)
}
if (!hasValidSession(state, request)) {
const refusal = { status: 401, headers: corsHeaders, body: { error: 'sign-in required' }, note: 'refused: no session' }
return finish(settings, state, request, response, refusal)
}
state.counts.notesSaved += 1
const note = 'note saved (notes saved so far: ' + state.counts.notesSaved + ')'
finish(settings, state, request, response, { status: 201, headers: corsHeaders, body: { saved: true }, note: note })
}
// Used by browser-check.mjs: sets the session cookie in your browser.
function signIn(settings, state, request, response) {
response.setHeader('Set-Cookie', 'lab_session=' + state.sessionId + '; Path=/; HttpOnly; SameSite=Lax')
const page = { signedIn: 'Sam Example', next: 'open the two pages the terminal lists' }
finish(settings, state, request, response, { status: 200, headers: {}, body: page, note: 'session cookie set' })
}
function hasValidSession(state, request) {
const pairs = (readHeader(request, 'Cookie') || '').split(';')
for (const pair of pairs) {
if (pair.trim() === 'lab_session=' + state.sessionId) return true
}
return false
}
// Writes the response and records one log line for it.
function finish(settings, state, request, response, result) {
const line = request.method + ' ' + request.url +
' | Origin: ' + (readHeader(request, 'Origin') || '(none)') +
' | session: ' + (hasValidSession(state, request) ? 'valid' : 'none') +
' | ' + result.status + ' ' + result.note
state.log.push(line)
if (settings.logRequests) console.log(line)
const headers = Object.assign({}, result.headers)
if (result.body !== null) headers['Content-Type'] = 'application/json'
response.writeHead(result.status, headers)
response.end(result.body === null ? '' : JSON.stringify(result.body))
}
// Node.js stores incoming header names in lower case.
function readHeader(request, name) {
return request.headers[name.toLowerCase()]
}
function readBody(request) {
return new Promise(function (resolve) {
const chunks = []
request.on('data', function (chunk) { chunks.push(chunk) })
request.on('end', function () { resolve(Buffer.concat(chunks).toString('utf8')) })
})
}
// A plain HTTP client. It sends exactly the headers it is given and hands
// back whatever the server answered: no CORS rule applies to it.
export function sendRequest(port, method, path, headers, body) {
return new Promise(function (resolve, reject) {
const options = { host: '127.0.0.1', port: port, method: method, path: path, headers: headers }
const outgoing = httpRequest(options, function (response) {
const chunks = []
response.on('data', function (chunk) { chunks.push(chunk) })
response.on('end', function () {
const text = Buffer.concat(chunks).toString('utf8')
resolve({ status: response.statusCode, headers: response.headers, body: text })
})
})
outgoing.on('error', reject)
outgoing.end(body || '')
})
}
================================================================
FILE 2 OF 5: browser-rules.mjs
================================================================
// browser-rules.mjs: the WHATWG Fetch Standard's CORS rules as plain
// functions, so the trace can say whether a browser would let the calling
// page read each response. They apply the published rules to the real
// headers the lab server sent. This is not a browser. It leaves out the
// preflight cache, redirects, the length limits on safelisted header values,
// the Range header and the cookie rules that decide whether a cookie is sent.
// Each quoted name is a section or a definition in the Fetch Standard,
// a Living Standard.
const SAFELISTED_METHODS = ['GET', 'HEAD', 'POST']
const SAFELISTED_CONTENT_TYPES = ['application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain']
const NON_WILDCARD_HEADER = 'Authorization'
function pass(reason) {
return { ok: true, reason: reason }
}
function fail(reason) {
return { ok: false, reason: reason }
}
// "CORS-safelisted request-header", without the length and Range rules.
function isSafelistedHeader(name, value) {
const lowerName = name.toLowerCase()
if (lowerName === 'accept' || lowerName === 'accept-language' || lowerName === 'content-language') return true
if (lowerName !== 'content-type') return false
const essence = value.split(';')[0].trim().toLowerCase()
return SAFELISTED_CONTENT_TYPES.includes(essence)
}
// "CORS-unsafe request-header names": the headers the page itself set that
// are not safelisted, in lower case and sorted. The browser's own headers,
// such as Origin and Cookie, are not part of pageHeaders.
export function listUnsafeHeaderNames(pageHeaders) {
const names = []
for (const name of Object.keys(pageHeaders)) {
if (!isSafelistedHeader(name, pageHeaders[name])) names.push(name.toLowerCase())
}
return names.sort()
}
// "HTTP fetch": a CORS request gets a preflight when its method is not a
// CORS-safelisted method or the page set a header that is not safelisted.
export function needsPreflight(method, pageHeaders) {
return !SAFELISTED_METHODS.includes(method) || listUnsafeHeaderNames(pageHeaders).length > 0
}
// "CORS check". credentialsMode is 'include' or 'same-origin'; for a
// cross-origin request, 'same-origin' sends no credentials. Response header
// names arrive in lower case from Node.js.
export function corsCheck(requestOrigin, credentialsMode, responseHeaders) {
const allowOrigin = responseHeaders['access-control-allow-origin']
if (allowOrigin === undefined) return fail('no Access-Control-Allow-Origin')
const withCredentials = credentialsMode === 'include'
if (!withCredentials && allowOrigin === '*') return pass('* is accepted without credentials')
// With credentials, * reaches this step and fails, because * is never an origin.
if (allowOrigin !== requestOrigin) {
if (allowOrigin === '*') return fail('* is not accepted with credentials')
return fail('Access-Control-Allow-Origin names ' + allowOrigin + ', not this origin')
}
if (!withCredentials) return pass('origin matches')
if (responseHeaders['access-control-allow-credentials'] === 'true') return pass('origin matches and credentials are allowed')
return fail('origin matches, but Access-Control-Allow-Credentials is not true')
}
// "CORS-preflight fetch": the answer to the OPTIONS request has to pass the
// CORS check with the actual request's credentials mode, have an ok status,
// and list the method and every unsafe header the actual request will use.
export function checkPreflight(actualRequest, preflightResponse) {
const check = corsCheck(actualRequest.origin, actualRequest.credentialsMode, preflightResponse.headers)
if (!check.ok) return check
const status = preflightResponse.status
if (status < 200 || status > 299) return fail('status ' + status + ' is not an ok status')
const withCredentials = actualRequest.credentialsMode === 'include'
const methods = splitHeaderList(preflightResponse.headers['access-control-allow-methods'])
const headerNames = splitHeaderList(preflightResponse.headers['access-control-allow-headers']).map(toLowerCase)
const method = actualRequest.method
const methodAllowed = methods.includes(method) || SAFELISTED_METHODS.includes(method) || (!withCredentials && methods.includes('*'))
if (!methodAllowed) return fail(method + ' is not in Access-Control-Allow-Methods')
const nonWildcardName = NON_WILDCARD_HEADER.toLowerCase()
const pageHeaderNames = Object.keys(actualRequest.pageHeaders).map(toLowerCase)
if (pageHeaderNames.includes(nonWildcardName) && !headerNames.includes(nonWildcardName)) {
return fail(NON_WILDCARD_HEADER + ' has to be listed by name')
}
for (const name of listUnsafeHeaderNames(actualRequest.pageHeaders)) {
const headerAllowed = headerNames.includes(name) || (!withCredentials && headerNames.includes('*'))
if (!headerAllowed) return fail(name + ' is not in Access-Control-Allow-Headers')
}
return pass('origin, credentials, method and headers are all approved')
}
function splitHeaderList(value) {
if (!value) return []
return value.split(',').map(function (item) { return item.trim() }).filter(Boolean)
}
function toLowerCase(text) {
return text.toLowerCase()
}
================================================================
FILE 3 OF 5: run-trace.mjs
================================================================
// run-trace.mjs: sends five requests to the lab API under each of seven CORS
// policies and prints, for each one, the request headers that matter, the
// response headers, the server's own log line and two verdicts: what this
// scripted client received, and whether a browser would let the calling
// page read it, decided by browser-rules.mjs. This client is not a browser.
import { APP_ORIGIN, ATTACKER_ORIGIN, LOOKALIKE_ORIGIN, sendRequest, startCorsLab } from './cors-lab-api.mjs'
import { checkPreflight, corsCheck, listUnsafeHeaderNames, needsPreflight } from './browser-rules.mjs'
// Each misconfiguration is probed from the origin that exploits it.
const policies = [
{ name: 'none', label: 'no CORS headers at all', hostileOrigin: ATTACKER_ORIGIN },
{ name: 'allow-list', label: 'exact allow-list: ' + APP_ORIGIN, hostileOrigin: ATTACKER_ORIGIN },
{ name: 'wildcard', label: 'Access-Control-Allow-Origin: *', hostileOrigin: ATTACKER_ORIGIN },
{ name: 'wildcard-credentials', label: '* with Access-Control-Allow-Credentials: true', hostileOrigin: ATTACKER_ORIGIN },
{ name: 'reflect-credentials', label: 'echoes any Origin, with credentials', hostileOrigin: ATTACKER_ORIGIN },
{ name: 'prefix-match', label: 'origin only has to start with ' + APP_ORIGIN, hostileOrigin: LOOKALIKE_ORIGIN },
{ name: 'null-allowed', label: 'allow-list that also lists null', hostileOrigin: 'null' },
]
const JSON_HEADERS = { 'Content-Type': 'application/json' }
// credentialsMode is the fetch() credentials option: 'include' sends the
// session cookie cross-origin; the default, 'same-origin', does not.
const exchanges = [
{ id: '1', label: 'simple GET, allowed origin, with credentials',
method: 'GET', path: '/api/account', fromApp: true, credentialsMode: 'include', pageHeaders: {} },
{ id: '2', label: 'simple GET, disallowed origin, with credentials',
method: 'GET', path: '/api/account', fromApp: false, credentialsMode: 'include', pageHeaders: {} },
{ id: '3', label: 'simple GET to an office-only route, disallowed origin, no credentials',
method: 'GET', path: '/internal/report', fromApp: false, credentialsMode: 'same-origin', pageHeaders: {} },
{ id: '4', label: 'JSON POST, allowed origin, with credentials',
method: 'POST', path: '/api/notes', fromApp: true, credentialsMode: 'include', pageHeaders: JSON_HEADERS },
{ id: '5', label: 'JSON POST, disallowed origin, with credentials',
method: 'POST', path: '/api/notes', fromApp: false, credentialsMode: 'include', pageHeaders: JSON_HEADERS },
]
const CORS_HEADER_NAMES = [
'access-control-allow-origin',
'access-control-allow-credentials',
'access-control-allow-methods',
'access-control-allow-headers',
'access-control-max-age',
'vary',
]
const DISPLAY_NAMES = {
'access-control-allow-origin': 'Access-Control-Allow-Origin',
'access-control-allow-credentials': 'Access-Control-Allow-Credentials',
'access-control-allow-methods': 'Access-Control-Allow-Methods',
'access-control-allow-headers': 'Access-Control-Allow-Headers',
'access-control-max-age': 'Access-Control-Max-Age',
'vary': 'Vary',
}
// The request as a browser would send it: the page's headers plus the
// Origin header and, with credentials included, the session cookie.
function buildRequest(exchange, origin, lab) {
const headers = Object.assign({ Origin: origin }, exchange.pageHeaders)
if (exchange.credentialsMode === 'include') headers.Cookie = lab.sessionCookie
const body = exchange.method === 'POST' ? '{"text":"hello"}' : ''
return { method: exchange.method, path: exchange.path, origin: origin, credentialsMode: exchange.credentialsMode, pageHeaders: exchange.pageHeaders, headers: headers, body: body }
}
// The OPTIONS request a browser sends first: the method and the unsafe
// header names of the actual request, and never the cookie.
function buildPreflight(actualRequest) {
const unsafeNames = listUnsafeHeaderNames(actualRequest.pageHeaders)
const headers = { Origin: actualRequest.origin, 'Access-Control-Request-Method': actualRequest.method }
if (unsafeNames.length) headers['Access-Control-Request-Headers'] = unsafeNames.join(',')
return { method: 'OPTIONS', path: actualRequest.path, headers: headers, body: '' }
}
function describeRequestHeaders(request) {
const parts = [request.method + ' ' + request.path]
for (const name of Object.keys(request.headers)) {
const value = name === 'Cookie' ? 'lab_session (the signed-in session)' : request.headers[name]
parts.push(name + ': ' + value)
}
return parts.join(' | ')
}
function describeResponseHeaders(response) {
const parts = [String(response.status)]
for (const name of CORS_HEADER_NAMES) {
if (response.headers[name] !== undefined) parts.push(DISPLAY_NAMES[name] + ': ' + response.headers[name])
}
if (parts.length === 1) parts.push('no CORS headers')
return parts.join(' | ')
}
function lastLogLine(lab) {
return lab.state.log[lab.state.log.length - 1]
}
async function send(lab, request) {
return sendRequest(lab.port, request.method, request.path, request.headers, request.body)
}
// Prints one simple exchange and returns the read verdict.
async function traceSimple(lab, request) {
const response = await send(lab, request)
const verdict = corsCheck(request.origin, request.credentialsMode, response.headers)
console.log(' request ' + describeRequestHeaders(request))
console.log(' response ' + describeResponseHeaders(response))
console.log(' server ' + lastLogLine(lab))
console.log(' client received ' + response.status + ' ' + response.body)
console.log(' browser ' + (verdict.ok ? 'page CAN read it' : 'page CANNOT read it') + ': ' + verdict.reason)
return verdict.ok ? 'read' : 'blocked'
}
// Prints the OPTIONS request, then the actual request. The scripted client
// sends the actual request even when a browser would not.
async function tracePreflighted(lab, request) {
const preflight = buildPreflight(request)
const preflightResponse = await send(lab, preflight)
const approval = checkPreflight(request, preflightResponse)
console.log(' a request ' + describeRequestHeaders(preflight))
console.log(' response ' + describeResponseHeaders(preflightResponse))
console.log(' server ' + lastLogLine(lab))
console.log(' browser preflight ' + (approval.ok ? 'PASSES' : 'FAILS') + ': ' + approval.reason)
const response = await send(lab, request)
console.log(' b request ' + describeRequestHeaders(request))
console.log(' response ' + describeResponseHeaders(response))
console.log(' server ' + lastLogLine(lab))
console.log(' client received ' + response.status + ' ' + response.body)
if (!approval.ok) {
console.log(' browser would NOT have sent this request; the scripted client sent it anyway')
return 'not sent'
}
const verdict = corsCheck(request.origin, request.credentialsMode, response.headers)
console.log(' browser sends it; ' + (verdict.ok ? 'page CAN read the answer' : 'page CANNOT read the answer') + ': ' + verdict.reason)
return verdict.ok ? 'sent, read' : 'sent, blocked'
}
async function tracePolicy(policy) {
const lab = await startCorsLab({ policy: policy.name })
console.log('POLICY ' + policy.name + ': ' + policy.label)
console.log('Allowed origin: ' + APP_ORIGIN + ' Disallowed origin: ' + policy.hostileOrigin)
const results = []
for (const exchange of exchanges) {
const origin = exchange.fromApp ? APP_ORIGIN : policy.hostileOrigin
const request = buildRequest(exchange, origin, lab)
const preflighted = needsPreflight(request.method, request.pageHeaders)
console.log(exchange.id + ' ' + exchange.label + (preflighted ? ' (needs a preflight)' : ''))
const result = preflighted ? await tracePreflighted(lab, request) : await traceSimple(lab, request)
results.push(result)
}
const counts = lab.state.counts
console.log('Server totals: ' + counts.accountReads + ' account reads, ' + counts.reportReads + ' report reads, ' +
counts.notesSaved + ' notes saved, ' + counts.preflights + ' preflights')
console.log('')
lab.server.close()
return results
}
function printSummary(resultsByPolicy) {
console.log('SUMMARY: what a browser would let the calling page do (the scripted client received every response)')
const heading = exchanges.map(function (exchange) { return (' ' + exchange.id).padEnd(13) })
console.log(('policy'.padEnd(22) + heading.join('')).trimEnd())
for (const policy of policies) {
const cells = resultsByPolicy[policy.name].map(function (result) { return (' ' + result).padEnd(13) })
console.log((policy.name.padEnd(22) + cells.join('')).trimEnd())
}
}
async function main() {
const resultsByPolicy = {}
for (const policy of policies) resultsByPolicy[policy.name] = await tracePolicy(policy)
printSummary(resultsByPolicy)
}
main()
================================================================
FILE 4 OF 5: cors-policy.test.mjs
================================================================
// cors-policy.test.mjs: asserts the response headers and, through
// browser-rules.mjs, what a calling page could actually read. It passes on
// the exact allow-list and fails on each of the other policies.
// Run: node cors-policy.test.mjs (allow-list)
// node cors-policy.test.mjs reflect-credentials (or any other policy name)
import assert from 'node:assert/strict'
import { after, before, test } from 'node:test'
import { APP_ORIGIN, ATTACKER_ORIGIN, LOOKALIKE_ORIGIN, POLICY_NAMES, sendRequest, startCorsLab } from './cors-lab-api.mjs'
import { checkPreflight, corsCheck } from './browser-rules.mjs'
const policy = process.argv[2] || 'allow-list'
if (!POLICY_NAMES.includes(policy)) throw new Error('Unknown policy: ' + policy)
let lab
before(async function () {
lab = await startCorsLab({ policy: policy })
})
after(function () {
lab.server.close()
})
// A credentialed GET of the signed-in account, as a page on origin would send it.
function readAccount(origin) {
return sendRequest(lab.port, 'GET', '/api/account', { Origin: origin, Cookie: lab.sessionCookie }, '')
}
function canPageRead(origin, credentialsMode, response) {
return corsCheck(origin, credentialsMode, response.headers).ok
}
test('headers: the app gets its exact origin back, credentials true and Vary: Origin', async function () {
const response = await readAccount(APP_ORIGIN)
assert.equal(response.headers['access-control-allow-origin'], APP_ORIGIN)
assert.equal(response.headers['access-control-allow-credentials'], 'true')
assert.match(response.headers['vary'] || '', /Origin/)
})
test('visibility: the app can read the signed-in account', async function () {
const response = await readAccount(APP_ORIGIN)
assert.equal(response.status, 200)
assert.equal(canPageRead(APP_ORIGIN, 'include', response), true)
})
test('visibility: another site cannot read the account, though the server sent it', async function () {
const readsBefore = lab.state.counts.accountReads
const response = await readAccount(ATTACKER_ORIGIN)
assert.equal(lab.state.counts.accountReads, readsBefore + 1, 'the server processed the request')
assert.equal(response.status, 200)
assert.equal(canPageRead(ATTACKER_ORIGIN, 'include', response), false)
})
test('visibility: a look-alike origin cannot read the account', async function () {
const response = await readAccount(LOOKALIKE_ORIGIN)
assert.equal(canPageRead(LOOKALIKE_ORIGIN, 'include', response), false)
})
test('visibility: a null origin cannot read the account', async function () {
const response = await readAccount('null')
assert.equal(canPageRead('null', 'include', response), false)
})
test('preflight: another site is not approved to send a JSON POST with credentials', async function () {
const headers = { Origin: ATTACKER_ORIGIN, 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'content-type' }
const preflightResponse = await sendRequest(lab.port, 'OPTIONS', '/api/notes', headers, '')
const actualRequest = { origin: ATTACKER_ORIGIN, method: 'POST', credentialsMode: 'include', pageHeaders: { 'Content-Type': 'application/json' } }
assert.equal(checkPreflight(actualRequest, preflightResponse).ok, false)
})
test('visibility: another site cannot read the office-only route', async function () {
const response = await sendRequest(lab.port, 'GET', '/internal/report', { Origin: ATTACKER_ORIGIN }, '')
assert.equal(canPageRead(ATTACKER_ORIGIN, 'same-origin', response), false)
})
test('headers: another site gets no Access-Control-Allow-Origin at all', async function () {
const response = await readAccount(ATTACKER_ORIGIN)
assert.equal(response.headers['access-control-allow-origin'], undefined)
})
test('server: with no Origin and no preflight, only the session check decides', async function () {
const savedBefore = lab.state.counts.notesSaved
const json = { 'Content-Type': 'application/json' }
const signedIn = await sendRequest(lab.port, 'POST', '/api/notes', Object.assign({ Cookie: lab.sessionCookie }, json), '{}')
const signedOut = await sendRequest(lab.port, 'POST', '/api/notes', json, '{}')
assert.equal(signedIn.status, 201)
assert.equal(signedOut.status, 401)
assert.equal(lab.state.counts.notesSaved, savedBefore + 1)
})
================================================================
FILE 5 OF 5: browser-check.mjs
================================================================
// browser-check.mjs: lets your own browser show what the trace predicts.
// It starts the lab API and two plain pages on 127.0.0.1, each on its own
// port, so each page is a different origin from the API and from each other.
// The API lists the first page's origin as allowed; the second is not listed.
// Run: node browser-check.mjs allow-list (or any other policy name)
// Stop it with Ctrl+C.
import { createServer } from 'node:http'
import { POLICY_NAMES, startCorsLab } from './cors-lab-api.mjs'
const policy = process.argv[2] || 'allow-list'
if (!POLICY_NAMES.includes(policy)) throw new Error('Use one of: ' + POLICY_NAMES.join(', '))
// A page with no script of its own: you run the requests from its console.
function startPage(label) {
const server = createServer(function (request, response) {
response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
response.end('<!doctype html><meta charset="utf-8"><title>CORS lab: ' + label + '</title><p>CORS lab page (' + label + ').</p>')
})
return new Promise(function (resolve) {
server.listen(0, '127.0.0.1', function () { resolve(server.address().port) })
})
}
const listedPort = await startPage('origin on the allow-list')
const unlistedPort = await startPage('origin not on the list')
const listedOrigin = 'http://127.0.0.1:' + listedPort
const lab = await startCorsLab({ policy: policy, allowedOrigins: [listedOrigin], logRequests: true })
const api = 'http://127.0.0.1:' + lab.port
console.log('Policy: ' + policy)
console.log('1. Sign in to the API: ' + api + '/lab/sign-in')
console.log('2. Page on the allow-list: ' + listedOrigin + '/')
console.log('3. Page not on the list: http://127.0.0.1:' + unlistedPort + '/')
console.log('In each page, open the developer tools console and run these one at a time:')
console.log("fetch('" + api + "/api/account', { credentials: 'include' }).then(function (response) { return response.text() }).then(console.log, console.error)")
console.log("fetch('" + api + "/api/notes', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: '{}' }).then(function (response) { return response.text() }).then(console.log, console.error)")
console.log('Each request the API receives prints one line below.')
================================================================
PART 2: THE REQUEST TRACE
================================================================
Command: node run-trace.mjs
POLICY none: no CORS headers at all
Allowed origin: https://app.example.com Disallowed origin: https://attacker.example.net
1 simple GET, allowed origin, with credentials
request GET /api/account | Origin: https://app.example.com | Cookie: lab_session (the signed-in session)
response 200 | no CORS headers
server GET /api/account | Origin: https://app.example.com | session: valid | 200 account data sent (account reads so far: 1)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CANNOT read it: no Access-Control-Allow-Origin
2 simple GET, disallowed origin, with credentials
request GET /api/account | Origin: https://attacker.example.net | Cookie: lab_session (the signed-in session)
response 200 | no CORS headers
server GET /api/account | Origin: https://attacker.example.net | session: valid | 200 account data sent (account reads so far: 2)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CANNOT read it: no Access-Control-Allow-Origin
3 simple GET to an office-only route, disallowed origin, no credentials
request GET /internal/report | Origin: https://attacker.example.net
response 200 | no CORS headers
server GET /internal/report | Origin: https://attacker.example.net | session: none | 200 office-only report sent (report reads so far: 1)
client received 200 {"report":"office rota","access":"anyone who can reach this server"}
browser page CANNOT read it: no Access-Control-Allow-Origin
4 JSON POST, allowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://app.example.com | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | no CORS headers
server OPTIONS /api/notes | Origin: https://app.example.com | session: none | 204 preflight answered (preflights so far: 1)
browser preflight FAILS: no Access-Control-Allow-Origin
b request POST /api/notes | Origin: https://app.example.com | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | no CORS headers
server POST /api/notes | Origin: https://app.example.com | session: valid | 201 note saved (notes saved so far: 1)
client received 201 {"saved":true}
browser would NOT have sent this request; the scripted client sent it anyway
5 JSON POST, disallowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://attacker.example.net | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | no CORS headers
server OPTIONS /api/notes | Origin: https://attacker.example.net | session: none | 204 preflight answered (preflights so far: 2)
browser preflight FAILS: no Access-Control-Allow-Origin
b request POST /api/notes | Origin: https://attacker.example.net | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | no CORS headers
server POST /api/notes | Origin: https://attacker.example.net | session: valid | 201 note saved (notes saved so far: 2)
client received 201 {"saved":true}
browser would NOT have sent this request; the scripted client sent it anyway
Server totals: 2 account reads, 1 report reads, 2 notes saved, 2 preflights
POLICY allow-list: exact allow-list: https://app.example.com
Allowed origin: https://app.example.com Disallowed origin: https://attacker.example.net
1 simple GET, allowed origin, with credentials
request GET /api/account | Origin: https://app.example.com | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Vary: Origin
server GET /api/account | Origin: https://app.example.com | session: valid | 200 account data sent (account reads so far: 1)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CAN read it: origin matches and credentials are allowed
2 simple GET, disallowed origin, with credentials
request GET /api/account | Origin: https://attacker.example.net | Cookie: lab_session (the signed-in session)
response 200 | Vary: Origin
server GET /api/account | Origin: https://attacker.example.net | session: valid | 200 account data sent (account reads so far: 2)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CANNOT read it: no Access-Control-Allow-Origin
3 simple GET to an office-only route, disallowed origin, no credentials
request GET /internal/report | Origin: https://attacker.example.net
response 200 | Vary: Origin
server GET /internal/report | Origin: https://attacker.example.net | session: none | 200 office-only report sent (report reads so far: 1)
client received 200 {"report":"office rota","access":"anyone who can reach this server"}
browser page CANNOT read it: no Access-Control-Allow-Origin
4 JSON POST, allowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://app.example.com | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: Content-Type | Access-Control-Max-Age: 600 | Vary: Origin
server OPTIONS /api/notes | Origin: https://app.example.com | session: none | 204 preflight answered (preflights so far: 1)
browser preflight PASSES: origin, credentials, method and headers are all approved
b request POST /api/notes | Origin: https://app.example.com | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Vary: Origin
server POST /api/notes | Origin: https://app.example.com | session: valid | 201 note saved (notes saved so far: 1)
client received 201 {"saved":true}
browser sends it; page CAN read the answer: origin matches and credentials are allowed
5 JSON POST, disallowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://attacker.example.net | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Vary: Origin
server OPTIONS /api/notes | Origin: https://attacker.example.net | session: none | 204 preflight answered (preflights so far: 2)
browser preflight FAILS: no Access-Control-Allow-Origin
b request POST /api/notes | Origin: https://attacker.example.net | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Vary: Origin
server POST /api/notes | Origin: https://attacker.example.net | session: valid | 201 note saved (notes saved so far: 2)
client received 201 {"saved":true}
browser would NOT have sent this request; the scripted client sent it anyway
Server totals: 2 account reads, 1 report reads, 2 notes saved, 2 preflights
POLICY wildcard: Access-Control-Allow-Origin: *
Allowed origin: https://app.example.com Disallowed origin: https://attacker.example.net
1 simple GET, allowed origin, with credentials
request GET /api/account | Origin: https://app.example.com | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: *
server GET /api/account | Origin: https://app.example.com | session: valid | 200 account data sent (account reads so far: 1)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CANNOT read it: * is not accepted with credentials
2 simple GET, disallowed origin, with credentials
request GET /api/account | Origin: https://attacker.example.net | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: *
server GET /api/account | Origin: https://attacker.example.net | session: valid | 200 account data sent (account reads so far: 2)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CANNOT read it: * is not accepted with credentials
3 simple GET to an office-only route, disallowed origin, no credentials
request GET /internal/report | Origin: https://attacker.example.net
response 200 | Access-Control-Allow-Origin: *
server GET /internal/report | Origin: https://attacker.example.net | session: none | 200 office-only report sent (report reads so far: 1)
client received 200 {"report":"office rota","access":"anyone who can reach this server"}
browser page CAN read it: * is accepted without credentials
4 JSON POST, allowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://app.example.com | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: * | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: Content-Type | Access-Control-Max-Age: 600
server OPTIONS /api/notes | Origin: https://app.example.com | session: none | 204 preflight answered (preflights so far: 1)
browser preflight FAILS: * is not accepted with credentials
b request POST /api/notes | Origin: https://app.example.com | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: *
server POST /api/notes | Origin: https://app.example.com | session: valid | 201 note saved (notes saved so far: 1)
client received 201 {"saved":true}
browser would NOT have sent this request; the scripted client sent it anyway
5 JSON POST, disallowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://attacker.example.net | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: * | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: Content-Type | Access-Control-Max-Age: 600
server OPTIONS /api/notes | Origin: https://attacker.example.net | session: none | 204 preflight answered (preflights so far: 2)
browser preflight FAILS: * is not accepted with credentials
b request POST /api/notes | Origin: https://attacker.example.net | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: *
server POST /api/notes | Origin: https://attacker.example.net | session: valid | 201 note saved (notes saved so far: 2)
client received 201 {"saved":true}
browser would NOT have sent this request; the scripted client sent it anyway
Server totals: 2 account reads, 1 report reads, 2 notes saved, 2 preflights
POLICY wildcard-credentials: * with Access-Control-Allow-Credentials: true
Allowed origin: https://app.example.com Disallowed origin: https://attacker.example.net
1 simple GET, allowed origin, with credentials
request GET /api/account | Origin: https://app.example.com | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: * | Access-Control-Allow-Credentials: true
server GET /api/account | Origin: https://app.example.com | session: valid | 200 account data sent (account reads so far: 1)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CANNOT read it: * is not accepted with credentials
2 simple GET, disallowed origin, with credentials
request GET /api/account | Origin: https://attacker.example.net | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: * | Access-Control-Allow-Credentials: true
server GET /api/account | Origin: https://attacker.example.net | session: valid | 200 account data sent (account reads so far: 2)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CANNOT read it: * is not accepted with credentials
3 simple GET to an office-only route, disallowed origin, no credentials
request GET /internal/report | Origin: https://attacker.example.net
response 200 | Access-Control-Allow-Origin: * | Access-Control-Allow-Credentials: true
server GET /internal/report | Origin: https://attacker.example.net | session: none | 200 office-only report sent (report reads so far: 1)
client received 200 {"report":"office rota","access":"anyone who can reach this server"}
browser page CAN read it: * is accepted without credentials
4 JSON POST, allowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://app.example.com | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: * | Access-Control-Allow-Credentials: true | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: Content-Type | Access-Control-Max-Age: 600
server OPTIONS /api/notes | Origin: https://app.example.com | session: none | 204 preflight answered (preflights so far: 1)
browser preflight FAILS: * is not accepted with credentials
b request POST /api/notes | Origin: https://app.example.com | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: * | Access-Control-Allow-Credentials: true
server POST /api/notes | Origin: https://app.example.com | session: valid | 201 note saved (notes saved so far: 1)
client received 201 {"saved":true}
browser would NOT have sent this request; the scripted client sent it anyway
5 JSON POST, disallowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://attacker.example.net | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: * | Access-Control-Allow-Credentials: true | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: Content-Type | Access-Control-Max-Age: 600
server OPTIONS /api/notes | Origin: https://attacker.example.net | session: none | 204 preflight answered (preflights so far: 2)
browser preflight FAILS: * is not accepted with credentials
b request POST /api/notes | Origin: https://attacker.example.net | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: * | Access-Control-Allow-Credentials: true
server POST /api/notes | Origin: https://attacker.example.net | session: valid | 201 note saved (notes saved so far: 2)
client received 201 {"saved":true}
browser would NOT have sent this request; the scripted client sent it anyway
Server totals: 2 account reads, 1 report reads, 2 notes saved, 2 preflights
POLICY reflect-credentials: echoes any Origin, with credentials
Allowed origin: https://app.example.com Disallowed origin: https://attacker.example.net
1 simple GET, allowed origin, with credentials
request GET /api/account | Origin: https://app.example.com | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Vary: Origin
server GET /api/account | Origin: https://app.example.com | session: valid | 200 account data sent (account reads so far: 1)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CAN read it: origin matches and credentials are allowed
2 simple GET, disallowed origin, with credentials
request GET /api/account | Origin: https://attacker.example.net | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: https://attacker.example.net | Access-Control-Allow-Credentials: true | Vary: Origin
server GET /api/account | Origin: https://attacker.example.net | session: valid | 200 account data sent (account reads so far: 2)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CAN read it: origin matches and credentials are allowed
3 simple GET to an office-only route, disallowed origin, no credentials
request GET /internal/report | Origin: https://attacker.example.net
response 200 | Access-Control-Allow-Origin: https://attacker.example.net | Access-Control-Allow-Credentials: true | Vary: Origin
server GET /internal/report | Origin: https://attacker.example.net | session: none | 200 office-only report sent (report reads so far: 1)
client received 200 {"report":"office rota","access":"anyone who can reach this server"}
browser page CAN read it: origin matches
4 JSON POST, allowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://app.example.com | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: content-type | Access-Control-Max-Age: 600 | Vary: Origin
server OPTIONS /api/notes | Origin: https://app.example.com | session: none | 204 preflight answered (preflights so far: 1)
browser preflight PASSES: origin, credentials, method and headers are all approved
b request POST /api/notes | Origin: https://app.example.com | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Vary: Origin
server POST /api/notes | Origin: https://app.example.com | session: valid | 201 note saved (notes saved so far: 1)
client received 201 {"saved":true}
browser sends it; page CAN read the answer: origin matches and credentials are allowed
5 JSON POST, disallowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://attacker.example.net | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: https://attacker.example.net | Access-Control-Allow-Credentials: true | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: content-type | Access-Control-Max-Age: 600 | Vary: Origin
server OPTIONS /api/notes | Origin: https://attacker.example.net | session: none | 204 preflight answered (preflights so far: 2)
browser preflight PASSES: origin, credentials, method and headers are all approved
b request POST /api/notes | Origin: https://attacker.example.net | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: https://attacker.example.net | Access-Control-Allow-Credentials: true | Vary: Origin
server POST /api/notes | Origin: https://attacker.example.net | session: valid | 201 note saved (notes saved so far: 2)
client received 201 {"saved":true}
browser sends it; page CAN read the answer: origin matches and credentials are allowed
Server totals: 2 account reads, 1 report reads, 2 notes saved, 2 preflights
POLICY prefix-match: origin only has to start with https://app.example.com
Allowed origin: https://app.example.com Disallowed origin: https://app.example.com.attacker.example.net
1 simple GET, allowed origin, with credentials
request GET /api/account | Origin: https://app.example.com | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Vary: Origin
server GET /api/account | Origin: https://app.example.com | session: valid | 200 account data sent (account reads so far: 1)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CAN read it: origin matches and credentials are allowed
2 simple GET, disallowed origin, with credentials
request GET /api/account | Origin: https://app.example.com.attacker.example.net | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: https://app.example.com.attacker.example.net | Access-Control-Allow-Credentials: true | Vary: Origin
server GET /api/account | Origin: https://app.example.com.attacker.example.net | session: valid | 200 account data sent (account reads so far: 2)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CAN read it: origin matches and credentials are allowed
3 simple GET to an office-only route, disallowed origin, no credentials
request GET /internal/report | Origin: https://app.example.com.attacker.example.net
response 200 | Access-Control-Allow-Origin: https://app.example.com.attacker.example.net | Access-Control-Allow-Credentials: true | Vary: Origin
server GET /internal/report | Origin: https://app.example.com.attacker.example.net | session: none | 200 office-only report sent (report reads so far: 1)
client received 200 {"report":"office rota","access":"anyone who can reach this server"}
browser page CAN read it: origin matches
4 JSON POST, allowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://app.example.com | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: Content-Type | Access-Control-Max-Age: 600 | Vary: Origin
server OPTIONS /api/notes | Origin: https://app.example.com | session: none | 204 preflight answered (preflights so far: 1)
browser preflight PASSES: origin, credentials, method and headers are all approved
b request POST /api/notes | Origin: https://app.example.com | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Vary: Origin
server POST /api/notes | Origin: https://app.example.com | session: valid | 201 note saved (notes saved so far: 1)
client received 201 {"saved":true}
browser sends it; page CAN read the answer: origin matches and credentials are allowed
5 JSON POST, disallowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://app.example.com.attacker.example.net | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: https://app.example.com.attacker.example.net | Access-Control-Allow-Credentials: true | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: Content-Type | Access-Control-Max-Age: 600 | Vary: Origin
server OPTIONS /api/notes | Origin: https://app.example.com.attacker.example.net | session: none | 204 preflight answered (preflights so far: 2)
browser preflight PASSES: origin, credentials, method and headers are all approved
b request POST /api/notes | Origin: https://app.example.com.attacker.example.net | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: https://app.example.com.attacker.example.net | Access-Control-Allow-Credentials: true | Vary: Origin
server POST /api/notes | Origin: https://app.example.com.attacker.example.net | session: valid | 201 note saved (notes saved so far: 2)
client received 201 {"saved":true}
browser sends it; page CAN read the answer: origin matches and credentials are allowed
Server totals: 2 account reads, 1 report reads, 2 notes saved, 2 preflights
POLICY null-allowed: allow-list that also lists null
Allowed origin: https://app.example.com Disallowed origin: null
1 simple GET, allowed origin, with credentials
request GET /api/account | Origin: https://app.example.com | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Vary: Origin
server GET /api/account | Origin: https://app.example.com | session: valid | 200 account data sent (account reads so far: 1)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CAN read it: origin matches and credentials are allowed
2 simple GET, disallowed origin, with credentials
request GET /api/account | Origin: null | Cookie: lab_session (the signed-in session)
response 200 | Access-Control-Allow-Origin: null | Access-Control-Allow-Credentials: true | Vary: Origin
server GET /api/account | Origin: null | session: valid | 200 account data sent (account reads so far: 2)
client received 200 {"name":"Sam Example","plan":"Team"}
browser page CAN read it: origin matches and credentials are allowed
3 simple GET to an office-only route, disallowed origin, no credentials
request GET /internal/report | Origin: null
response 200 | Access-Control-Allow-Origin: null | Access-Control-Allow-Credentials: true | Vary: Origin
server GET /internal/report | Origin: null | session: none | 200 office-only report sent (report reads so far: 1)
client received 200 {"report":"office rota","access":"anyone who can reach this server"}
browser page CAN read it: origin matches
4 JSON POST, allowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: https://app.example.com | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: Content-Type | Access-Control-Max-Age: 600 | Vary: Origin
server OPTIONS /api/notes | Origin: https://app.example.com | session: none | 204 preflight answered (preflights so far: 1)
browser preflight PASSES: origin, credentials, method and headers are all approved
b request POST /api/notes | Origin: https://app.example.com | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: https://app.example.com | Access-Control-Allow-Credentials: true | Vary: Origin
server POST /api/notes | Origin: https://app.example.com | session: valid | 201 note saved (notes saved so far: 1)
client received 201 {"saved":true}
browser sends it; page CAN read the answer: origin matches and credentials are allowed
5 JSON POST, disallowed origin, with credentials (needs a preflight)
a request OPTIONS /api/notes | Origin: null | Access-Control-Request-Method: POST | Access-Control-Request-Headers: content-type
response 204 | Access-Control-Allow-Origin: null | Access-Control-Allow-Credentials: true | Access-Control-Allow-Methods: GET, POST | Access-Control-Allow-Headers: Content-Type | Access-Control-Max-Age: 600 | Vary: Origin
server OPTIONS /api/notes | Origin: null | session: none | 204 preflight answered (preflights so far: 2)
browser preflight PASSES: origin, credentials, method and headers are all approved
b request POST /api/notes | Origin: null | Content-Type: application/json | Cookie: lab_session (the signed-in session)
response 201 | Access-Control-Allow-Origin: null | Access-Control-Allow-Credentials: true | Vary: Origin
server POST /api/notes | Origin: null | session: valid | 201 note saved (notes saved so far: 2)
client received 201 {"saved":true}
browser sends it; page CAN read the answer: origin matches and credentials are allowed
Server totals: 2 account reads, 1 report reads, 2 notes saved, 2 preflights
SUMMARY: what a browser would let the calling page do (the scripted client received every response)
policy 1 2 3 4 5
none blocked blocked blocked not sent not sent
allow-list read blocked blocked sent, read not sent
wildcard blocked blocked read not sent not sent
wildcard-credentials blocked blocked read not sent not sent
reflect-credentials read read read sent, read sent, read
prefix-match read read read sent, read sent, read
null-allowed read read read sent, read sent, read
Reading the evidence:
none No page on another origin can read anything, and the app's own JSON POST is never sent, so a front end on another origin cannot work.
allow-list The app reads its account and saves its note. The other site can read nothing, yet the server line for exchange 2 shows the account was looked up and sent, and in exchange 5 the scripted client's POST saved a note even though a browser would have held it back. The server, not CORS, has to decide those.
wildcard No credentialed read works, the app's own included, because * is refused with credentials. The office-only route is readable from any origin (exchange 3).
wildcard-credentials Adding Access-Control-Allow-Credentials: true to * changes nothing: every credentialed read and preflight is still refused.
reflect-credentials Every response is readable and every POST is sent, from any origin. On its simple GET, the app's own origin receives the same headers as under allow-list.
prefix-match The look-alike host under attacker.example.net passes the check and reads the account.
null-allowed The null origin, which any site can produce with a sandboxed frame, reads the account.
Every policy The scripted client received every response in full. Only a browser applies the verdict.
================================================================
PART 3: THE REGRESSION TEST
================================================================
Each test asserts either the response headers or what a page could read or send, decided by browser-rules.mjs from those headers. The test passes on allow-list and fails on every other policy, so a pipeline step running it fails when the policy changes.
Command: node cors-policy.test.mjs
✔ headers: the app gets its exact origin back, credentials true and Vary: Origin (9.078125ms)
✔ visibility: the app can read the signed-in account (0.70475ms)
✔ visibility: another site cannot read the account, though the server sent it (0.426209ms)
✔ visibility: a look-alike origin cannot read the account (0.350167ms)
✔ visibility: a null origin cannot read the account (0.395292ms)
✔ preflight: another site is not approved to send a JSON POST with credentials (0.356375ms)
✔ visibility: another site cannot read the office-only route (0.292ms)
✔ headers: another site gets no Access-Control-Allow-Origin at all (0.280541ms)
✔ server: with no Origin and no preflight, only the session check decides (0.801ms)
ℹ tests 9
ℹ suites 0
ℹ pass 9
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 17.743375
The process exits with code 0.
Command: node cors-policy.test.mjs none
✖ headers: the app gets its exact origin back, credentials true and Vary: Origin (10.622708ms)
✖ visibility: the app can read the signed-in account (0.739584ms)
✔ visibility: another site cannot read the account, though the server sent it (0.453042ms)
✔ visibility: a look-alike origin cannot read the account (0.37925ms)
✔ visibility: a null origin cannot read the account (0.432083ms)
✔ preflight: another site is not approved to send a JSON POST with credentials (0.385458ms)
✔ visibility: another site cannot read the office-only route (0.298333ms)
✔ headers: another site gets no Access-Control-Allow-Origin at all (0.309417ms)
✔ server: with no Origin and no preflight, only the session check decides (0.741667ms)
ℹ tests 9
ℹ suites 0
ℹ pass 7
ℹ fail 2
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 19.668125
✖ failing tests:
test at cors-policy.test.mjs:33:1
✖ headers: the app gets its exact origin back, credentials true and Vary: Origin (10.622708ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ undefined
- 'https://app.example.com'
(stack trace lines removed here)
(The other 1 failing test is listed here in the same form; removed for length.)
Command: node cors-policy.test.mjs wildcard
✖ headers: the app gets its exact origin back, credentials true and Vary: Origin (9.585708ms)
✖ visibility: the app can read the signed-in account (0.724625ms)
✔ visibility: another site cannot read the account, though the server sent it (0.443833ms)
✔ visibility: a look-alike origin cannot read the account (0.406ms)
✔ visibility: a null origin cannot read the account (0.431292ms)
✔ preflight: another site is not approved to send a JSON POST with credentials (0.4135ms)
✖ visibility: another site cannot read the office-only route (0.334583ms)
✖ headers: another site gets no Access-Control-Allow-Origin at all (0.353167ms)
✔ server: with no Origin and no preflight, only the session check decides (0.829208ms)
ℹ tests 9
ℹ suites 0
ℹ pass 5
ℹ fail 4
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 18.575375
✖ failing tests:
test at cors-policy.test.mjs:33:1
✖ headers: the app gets its exact origin back, credentials true and Vary: Origin (9.585708ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ '*'
- 'https://app.example.com'
(stack trace lines removed here)
(The other 3 failing tests are listed here in the same form; removed for length.)
Command: node cors-policy.test.mjs wildcard-credentials
✖ headers: the app gets its exact origin back, credentials true and Vary: Origin (10.250958ms)
✖ visibility: the app can read the signed-in account (0.792958ms)
✔ visibility: another site cannot read the account, though the server sent it (0.444209ms)
✔ visibility: a look-alike origin cannot read the account (0.372833ms)
✔ visibility: a null origin cannot read the account (0.41175ms)
✔ preflight: another site is not approved to send a JSON POST with credentials (0.420625ms)
✖ visibility: another site cannot read the office-only route (0.362291ms)
✖ headers: another site gets no Access-Control-Allow-Origin at all (0.339291ms)
✔ server: with no Origin and no preflight, only the session check decides (0.756458ms)
ℹ tests 9
ℹ suites 0
ℹ pass 5
ℹ fail 4
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 19.323917
✖ failing tests:
test at cors-policy.test.mjs:33:1
✖ headers: the app gets its exact origin back, credentials true and Vary: Origin (10.250958ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ '*'
- 'https://app.example.com'
(stack trace lines removed here)
(The other 3 failing tests are listed here in the same form; removed for length.)
Command: node cors-policy.test.mjs reflect-credentials
✔ headers: the app gets its exact origin back, credentials true and Vary: Origin (9.081ms)
✔ visibility: the app can read the signed-in account (0.798208ms)
✖ visibility: another site cannot read the account, though the server sent it (1.134208ms)
✖ visibility: a look-alike origin cannot read the account (1.035834ms)
✖ visibility: a null origin cannot read the account (0.525291ms)
✖ preflight: another site is not approved to send a JSON POST with credentials (0.823709ms)
✖ visibility: another site cannot read the office-only route (0.459958ms)
✖ headers: another site gets no Access-Control-Allow-Origin at all (0.518625ms)
✔ server: with no Origin and no preflight, only the session check decides (1.196083ms)
ℹ tests 9
ℹ suites 0
ℹ pass 3
ℹ fail 6
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 20.757667
✖ failing tests:
test at cors-policy.test.mjs:46:1
✖ visibility: another site cannot read the account, though the server sent it (1.134208ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
true !== false
(stack trace lines removed here)
(The other 5 failing tests are listed here in the same form; removed for length.)
Command: node cors-policy.test.mjs prefix-match
✔ headers: the app gets its exact origin back, credentials true and Vary: Origin (9.108291ms)
✔ visibility: the app can read the signed-in account (0.681833ms)
✔ visibility: another site cannot read the account, though the server sent it (0.42375ms)
✖ visibility: a look-alike origin cannot read the account (0.944916ms)
✔ visibility: a null origin cannot read the account (0.433375ms)
✔ preflight: another site is not approved to send a JSON POST with credentials (0.53275ms)
✔ visibility: another site cannot read the office-only route (0.370666ms)
✔ headers: another site gets no Access-Control-Allow-Origin at all (0.320291ms)
✔ server: with no Origin and no preflight, only the session check decides (0.741666ms)
ℹ tests 9
ℹ suites 0
ℹ pass 8
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 18.549625
✖ failing tests:
test at cors-policy.test.mjs:54:1
✖ visibility: a look-alike origin cannot read the account (0.944916ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
true !== false
(stack trace lines removed here)
Command: node cors-policy.test.mjs null-allowed
✔ headers: the app gets its exact origin back, credentials true and Vary: Origin (9.351833ms)
✔ visibility: the app can read the signed-in account (0.942917ms)
✔ visibility: another site cannot read the account, though the server sent it (0.6675ms)
✔ visibility: a look-alike origin cannot read the account (0.901833ms)
✖ visibility: a null origin cannot read the account (1.289416ms)
✔ preflight: another site is not approved to send a JSON POST with credentials (0.455375ms)
✔ visibility: another site cannot read the office-only route (0.648625ms)
✔ headers: another site gets no Access-Control-Allow-Origin at all (0.552917ms)
✔ server: with no Origin and no preflight, only the session check decides (1.393083ms)
ℹ tests 9
ℹ suites 0
ℹ pass 8
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 21.258875
✖ failing tests:
test at cors-policy.test.mjs:59:1
✖ visibility: a null origin cannot read the account (1.289416ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
true !== false
(stack trace lines removed here)
Each of the six runs with a policy other than allow-list exits with code 1.
What each run shows:
allow-list All nine tests pass, including the one that shows the other site's request reached the server and was processed.
none The app's own origin gets no Access-Control-Allow-Origin and cannot read its account.
wildcard The app cannot read with credentials, the office-only route is readable from anywhere, and * is sent to every origin.
wildcard-credentials The same four failures as wildcard.
reflect-credentials The two tests about the app's own origin pass: its headers look right. The six tests about other origins fail. A test that only checked the app's own headers would have passed this policy.
prefix-match Only the look-alike test fails.
null-allowed Only the null-origin test fails.
================================================================
PART 4: SEE IT IN YOUR OWN BROWSER
================================================================
Command: node browser-check.mjs allow-list
Policy: allow-list
1. Sign in to the API: http://127.0.0.1:61591/lab/sign-in
2. Page on the allow-list: http://127.0.0.1:61589/
3. Page not on the list: http://127.0.0.1:61590/
In each page, open the developer tools console and run these one at a time:
fetch('http://127.0.0.1:61591/api/account', { credentials: 'include' }).then(function (response) { return response.text() }).then(console.log, console.error)
fetch('http://127.0.0.1:61591/api/notes', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: '{}' }).then(function (response) { return response.text() }).then(console.log, console.error)
Each request the API receives prints one line below.
Your browser is the evidence in this part. The two pages and the API all use the host 127.0.0.1 on different ports, so they are three different origins (MDN Origin glossary) but the same site, because the port is ignored when deciding the site and an IP address has no registrable domain (MDN Site glossary; HTML Standard; URL Standard). That keeps SameSite and third-party cookie rules out of the way here; across real sites those rules decide whether the cookie is sent at all.
1. Open the first address. It signs you in to the lab API by setting a session cookie, lab_session, for 127.0.0.1.
2. Open the second address, a page on an origin the API lists. Open the developer tools, choose the Console, and run the first fetch line the terminal printed. If the console asks you to confirm before pasting, follow its instruction. Under the Fetch Standard's rules the page can read the response, so the account JSON should be printed. In the Network panel, select the request to /api/account and read the Origin request header and the Access-Control-Allow-Origin, Access-Control-Allow-Credentials and Vary response headers. Compare them with exchange 1 under allow-list.
3. Open the third address, a page on an origin the API does not list, and run the same line. The rules say the fetch fails; MDN says the reason is not given to the script and the console shows it. The terminal prints a line showing the API received the request with a valid session and sent the account data. Compare with exchange 2.
4. Run the second fetch line, the JSON POST, from both pages. From the listed page the terminal should print an OPTIONS line and then a POST line. From the unlisted page it should print only the OPTIONS line, because the browser holds the POST back when the preflight fails. Compare with exchanges 4 and 5.
5. Stop the lab with Ctrl+C, start it again with node browser-check.mjs reflect-credentials, sign in again and repeat step 3. Under the rules, the unlisted page can now read the account.
If your browser does something the trace does not predict, record the browser and its version, and check MDN's compatibility data for the header involved.
================================================================
PART 5: POINT THE TEST AT YOUR OWN API
================================================================
1. Copy cors-policy.test.mjs and browser-rules.mjs into your project's tests.
2. Replace startCorsLab with your API started on a test port with a seeded test account, and replace the three routes with your own: one that returns signed-in data, any route that answers without sign-in, and one state-changing route with a JSON body.
3. Set APP_ORIGIN to each origin your environment's list contains, one run per origin, and keep the attacker, look-alike and null origins.
4. Keep both kinds of assertion for every route: the response headers, and what corsCheck and checkPreflight say a page could read or send.
5. Run it in the pipeline that deploys your API, against a staging or local copy and test accounts, never against real customers' accounts.
================================================================
PART 6: A CORS POLICY RECORD TO FILL IN
================================================================
One record per route or group of routes that answers browsers on other origins. Keep it with the code and change it in the same commit as the configuration.
Route or route group: for example /api/account and /api/notes
Who calls it from a browser: for example the customer portal front end
Production origins: https://app.example.com
Staging origins: https://staging-app.example.com
Development origins: development configuration only, never production
How origins are compared: the whole serialised origin, exactly, against this list
Credentials: yes or no; if no, leave Access-Control-Allow-Credentials out
Methods allowed on preflight: GET, POST
Headers allowed on preflight: Content-Type
Access-Control-Max-Age (seconds): 600, the longest wait you accept after a change
Vary: Origin: yes, on every response whose Access-Control-Allow-Origin depends on the request
Never on this route: *, null, prefix or suffix matches, reflecting the Origin header
Routes that send *, if any: for example /api/public/opening-hours: no cookies, nothing reachable only from your network
Server checks that decide access: sign-in on every request, an authorisation check on every record, CSRF defences on state-changing routes
Test that proves it: cors-policy.test.mjs, run in the deployment pipeline
Owner and last review date:What CORS is, and what a misconfiguration gives away
Picture a customer portal at app.example.com whose pages fetch account details from an API at api.example.com.
To the browser those are two different origins, so by default a page on one cannot read what the other sends back. Cross-origin resource sharing, shortened to CORS, is how the API says which other origins may read its responses.
A CORS misconfiguration is a policy that says yes to origins it should not, so that a page on someone else's site can read what your API returns to a signed-in visitor.
One point matters more than any header. CORS relaxes a browser restriction on reading responses. It does not stop a simple request from reaching your server, it does not authenticate anyone, and a client that is not a browser ignores it. MDN's CORS guide says the headers let servers describe which origins are permitted to read that information from a web browser.
OWASP's test for CORS, WSTG-CLNT-07, says it is up to the client to determine and enforce whether it has access to the response data, and that relying on the Origin header for access control checks is not a good idea because it may be spoofed outside the browser.
The README of the Express cors middleware puts it plainly under Common Misconceptions: CORS is not access control, and any HTTP client, including another server, can call your API regardless of CORS settings.
So a permissive policy is dangerous because of what a logged-in visitor's browser can then be made to read. When the other site's page asks for credentials, the browser can attach the visitor's cookie, where the cookie's SameSite attribute and the browser's third-party cookie settings allow it, and if your policy approves that site, it hands the page's script the response.
A strict policy, in turn, is not a substitute for checking who is asking. OWASP's HTML5 Security Cheat Sheet says not to rely only on the Origin header for access control checks and to protect sensitive data with application-level protocols.
The OWASP Top 10:2025 says access control is only effective when implemented in trusted server-side code or serverless APIs, and lists CORS misconfiguration that allows API access from unauthorised or untrusted origins among the common access control vulnerabilities in A01 Broken Access Control.
The hono advisory described below maps a CORS flaw to MITRE's CWE-942, Permissive Cross-domain Security Policy with Untrusted Domains, which describes a web-client protection mechanism whose policy includes untrusted domains the web client is allowed to communicate with. CWE-942 does not name CORS; its examples are Flash and Silverlight policy files. The OWASP Top 10:2025 maps CWE-942 to A02 Security Misconfiguration.
Origins and the same-origin policy in plain terms
An origin is the scheme, hostname and port of a URL, and two URLs share an origin only when all three match.
MDN's glossary gives http://example.com and http://example.com:8080 as different origins because the ports differ, and http://example.com and http://myapp.example.com as different because the hostnames differ. So https://app.example.com and https://api.example.com are two origins, even when one business runs both.
The same-origin policy is the browser's default between origins. MDN places the interactions it controls in three categories, and two matter here: cross-origin writes, such as links, redirects and form submissions, are typically allowed, and cross-origin reads are typically disallowed, though MDN notes that read access is often leaked by embedding.
A page on another site can make a visitor's browser send a request to your API. What the policy stops, by default, is that page's script reading the answer.
MDN's CORS guide says fetch() and XMLHttpRequest follow the same-origin policy, so a web application using them can only request resources from its own origin unless the response from the other origin includes the right CORS headers.
CORS is the opt-in. The WHATWG Fetch Standard, which MDN notes now defines CORS, says the protocol exists to allow sharing responses cross-origin and to allow more versatile fetches than an HTML form can make. It says the protocol has to be an opt-in mechanism to prevent leaking data from responses behind a firewall, and, for requests that include credentials, to prevent leaking potentially sensitive data. Every misconfiguration on this page is that opt-in given to more origins than the owner meant.
CORS headers: how the server says yes
A browser adds an Origin header to a cross-origin request made by a page's script, naming the page's origin.
The server answers with headers, and the browser decides. In the Fetch Standard, Access-Control-Allow-Origin indicates whether the response can be shared, by returning the literal value of the Origin request header, which can be null, or *. Its syntax allows one value: one origin, null or the wildcard.
MDN's reference says a server that supports clients from several origins must return the origin of the specific client making the request, which takes code that checks the Origin header against a list of allowed origins and, when it is on the list, sends that same value back.
The browser's side is a short algorithm the Fetch Standard calls the CORS check. With no Access-Control-Allow-Origin, it fails. For a request without credentials, * passes. Otherwise the value has to equal the request's origin exactly, and for a request with credentials, Access-Control-Allow-Credentials also has to be true.
When the check fails, the fetch returns a network error to the page. MDN adds that, for security reasons, the script is not told the specifics of a CORS failure; the browser's console shows them.
MDN's reference for Access-Control-Allow-Credentials says credentials include cookies, TLS client certificates and authentication headers containing a username and password. Browsers do not send them on cross-origin fetch() or XMLHttpRequest calls by default; a page has to ask, with the fetch() credentials option set to include, which otherwise defaults to same-origin.
A simple GET with credentials goes out without a preflight, carrying the cookie, and the browser then refuses to make the response available to the page unless Access-Control-Allow-Credentials is true.
That header has one valid value, true, and it is case-sensitive. MDN's advice when you do not need credentials is to omit it rather than set it to false.
The wildcard and credentials do not mix, and the Fetch Standard is exact about which side refuses. Its table of combinations says that if the credentials mode is include, Access-Control-Allow-Origin cannot be *, and marks the response as not shared even when Access-Control-Allow-Credentials is true.
The refusal is the browser's: in the CORS check, * never equals the request's origin, so a credentialed request fails the check and the page receives a network error in place of the response, which the server has already sent.
MDN describes the same outcome: the browser blocks access to the response and reports a CORS error in the developer tools console. The rule extends to Access-Control-Allow-Headers, Access-Control-Allow-Methods and Access-Control-Expose-Headers, where * counts as a wildcard only for requests without credentials.
When the value of Access-Control-Allow-Origin depends on the request's Origin, tell caches. MDN's reference says a response that names an explicit origin should also include Vary: Origin, and the Fetch Standard says Vary is to be used whenever the CORS requirements are more complicated than * or one fixed origin.
Its example is a response cached from a plain navigation, without Access-Control-Allow-Origin, being reused for a later CORS request. For * or one fixed origin, it says to send Access-Control-Allow-Origin on every response for that resource and not to use Vary.
CORS is not the only gate on cookies. MDN's CORS guide says third-party cookie policies still apply to credentialed requests to a different domain, and may prevent the cookie being sent even when the server allows credentials.
The IETF cookie draft says most user agents limit third-party cookies in a variety of ways, so resources cannot rely on them being treated consistently. The SameSite attribute also decides: MDN's Set-Cookie reference says Lax leaves the cookie off cross-site requests made with fetch(), while None sends it with cross-site requests.
The cookie security guide covers those attributes; this page assumes the cookie is sent, which is the case CORS has to handle.
The CORS preflight: what it asks, and what it is not
Some cross-origin requests go out at once and some wait for permission.
MDN calls the first kind simple requests, a term from the obsolete CORS specification that the Fetch Standard does not use. In the Fetch Standard's terms, the method has to be a CORS-safelisted method, GET, HEAD or POST, and every header the page sets has to be a CORS-safelisted request-header: Accept, Accept-Language, Content-Language, Content-Type or Range, each with conditions on its value.
For a header the page sets, Content-Type qualifies only as application/x-www-form-urlencoded, multipart/form-data or text/plain. MDN adds that no event listener may be registered on an XMLHttpRequest upload and no ReadableStream may be used.
MDN explains why simple requests skip the preflight: an HTML form could already send them to any origin, so the server does not have to opt in to receive a request that looks like a form submission, although it still has to opt in with Access-Control-Allow-Origin before the response is shared with script.
Anything else gets a preflight first, unless the browser holds a cached approval. A Content-Type of application/json, a PUT or DELETE, or a header such as Authorization or X-Requested-With all fall outside the safelist.
The preflight is an OPTIONS request to the same URL. Under the Fetch Standard, the browser sends Access-Control-Request-Method with the method it wants to use and, when there are any, Access-Control-Request-Headers with the names of the headers that are not safelisted, in lower case. It never includes credentials.
The answer has to pass the same CORS check, using the credentials mode of the request that will follow, and have an ok status such as 200 or 204. Access-Control-Allow-Methods has to cover the method unless it is safelisted, and Access-Control-Allow-Headers has to cover each header that is not safelisted; for a credentialed request * does not count, and Authorization always has to be listed by name.
Only then does the browser send the actual request. When the preflight fails, the fetch ends in a network error and the actual request is not sent.
Access-Control-Max-Age says how many seconds the browser may cache that approval. The Fetch Standard's default is 5 seconds and lets a browser impose its own limit; MDN's reference lists 24 hours in Firefox and 2 hours in Chromium from version 76.
A cached approval can be reused until its max-age runs out, so a narrowed list of methods or headers can take that long to reach a browser that cached the old answer.
A preflight is not a security check run on your behalf. The Fetch Standard describes it as a check to see if the CORS protocol is understood. It runs only in browsers and only for requests that are not simple, and it carries no credentials, so it says nothing about who the user is.
ASVS 5.0 notes that the preflight can also be a useful request forgery prevention mechanism for endpoints that are not designed to be called from another origin, and its requirement 3.5.2, at Level 1, asks that an application relying on it makes sure the functionality cannot be called with a request that does not trigger a preflight, which may require checking the Origin and Content-Type request headers or using an extra header field that is not CORS-safelisted.
OWASP's HTML5 cheat sheet makes the related point that current implementations might not perform a preflight, so it is important that ordinary GET and POST requests perform any access control necessary.
CORS misconfigurations, in the order a reviewer meets them
Each of these is a policy that says yes to an origin its owner did not mean to trust.
The request trace on this page runs every one of them against the same invented API, so the effect described here is also shown there, request by request.
The quickest way to make a cross-origin error go away is to copy the request's Origin header into Access-Control-Allow-Origin and add Access-Control-Allow-Credentials: true. The browser's CORS check then passes for every site. WSTG-CLNT-07 names a server that returns the Origin header without any additional checks as an insecure configuration that can lead to access of sensitive data, and OWASP's HTML5 cheat sheet says not to blindly return the Origin header content without any checks.
A CORS library can make it one setting. The Express cors README says that setting its origin option to true reflects the request origin. A published advisory shows the same outcome reached by accident: CVE-2026-54290 in the hono npm package, GHSA-88fw-hqm2-52qc, published on 9 June 2026 and rated high with a CVSS v3.1 score of 7.1.
With credentials set to true and no explicit origin, hono's CORS Middleware reflected the request's Origin and sent Access-Control-Allow-Credentials: true, so any site could make credentialed cross-origin requests and read the responses. The advisory notes that browsers reject * with credentials, so the same configuration used to fail closed; reflecting the origin made it succeed for every origin, null included, and its preflight echoed the requested headers back. It affects hono versions before 4.12.25 and is fixed in 4.12.25.
In the trace this is the reflect-credentials policy, which also echoes the requested headers on a preflight, so the trace's JSON POSTs pass their preflight too. On a simple request, the headers your own front end receives are the same as under a correct allow-list, which is why a test that only checks your own front end's headers would pass it.
Origin: null looks like no origin at all, and it can be tempting to list it so that a page opened from a local file works. MDN's reference for Access-Control-Allow-Origin says the null value should not be used. The origin of resources that use a non-hierarchical scheme, such as data: or file:, and of sandboxed documents is serialised as null; many browsers grant such documents access to a response with Access-Control-Allow-Origin: null, and any origin can create a hostile document with a null origin.
MDN's Origin glossary gives a sandboxed iframe without allow-same-origin as one source of a null origin, and its Origin header reference adds cross-origin redirects. An allow-list that contains null therefore contains any site willing to put its script in a sandboxed frame. OWASP's CSRF cheat sheet gives the same instruction for Origin checks: the literal null value should not be allowlisted.
An allow-list is only as good as its comparison. A check that the origin starts with https://app.example.com also accepts https://app.example.com.attacker.example.net, a host under someone else's domain. A check that it ends with example.com also accepts any domain whose name happens to end in those characters.
The Express cors README shows how quietly this can arrive: its documentation describes a regular expression for example.com, anchored only at the end, as reflecting any origin ending with example.com.
Compare the whole serialised origin, scheme, host and port, against a list. OWASP makes the point for two neighbouring checks: its CSRF cheat sheet says a target origin check must match the entire origin, so that example.org.attacker.com does not pass a check for example.org, and its HTML5 cheat sheet warns, for message origins, that a check for .owasp.org written with indexOf will match owasp.org.attacker.com.
The browser's own CORS check is an exact comparison, and the Fetch Standard's table marks an Access-Control-Allow-Origin with a trailing slash as not shared, because a serialised origin has no trailing slash.
Access-Control-Allow-Origin: * is the honest setting for public data, and the Fetch Standard treats it that way. In its background note on a basic safe CORS protocol setup, it says the wildcard is safe even for a resource that exposes more to a cookie or HTTP authentication, because the header will not reveal that, much as the resource is already shared with curl and wget.
The exception is data protected by IP authentication or a firewall: for those resources, it says, using the CORS protocol is unsafe, and if a resource cannot be accessed from a random device connected to the web using curl and wget, the header is not to be included.
That is the misconfiguration: an internal dashboard, an admin API on a private network or a service on a staff machine, answering without sign-in because only trusted machines can reach it, with * added so that some other tool can call it from a browser. The Fetch Standard gives preventing leaks from responses behind a firewall as one reason CORS had to be an opt-in, and * opts in for every site.
ASVS 5.0 requirement 3.4.2, at Level 1, asks that Access-Control-Allow-Origin is a fixed value, or that an Origin value used in it is validated against an allowlist of trusted origins, and that when * is needed the response does not include any sensitive information.
OWASP's HTML5 cheat sheet adds that the header belongs only on the URLs that need cross-domain access, not across the whole domain.
Access-Control-Allow-Credentials: true is the setting that turns a read into a read of the visitor's account. The Fetch Standard says that, generally speaking, both sharing responses and allowing requests with credentials is rather unsafe, and extreme care has to be taken to avoid the confused deputy problem. MDN's reference adds that sending credentials cross-origin can make a site vulnerable to cross-site request forgery.
Give credentials only to the routes and origins that need them, and name the methods and headers the preflight approves. The Express cors README says its allowedHeaders setting, when not specified, defaults to reflecting the headers in the preflight's Access-Control-Request-Headers, and the hono advisory notes that echoing them approved credentialed requests that were not simple.
MDN's CSRF guide spells out the consequence: a site becomes open to forged requests from a particular origin if its response to a state-changing request includes Access-Control-Allow-Origin listing that origin and Access-Control-Allow-Credentials.
* with Access-Control-Allow-Credentials: true looks like the same mistake and behaves differently. It fails closed: the browser refuses every credentialed read and preflight under it, your own front end's included, as the trace's wildcard-credentials policy shows. It is a broken configuration rather than an open one.
Copying the request's Origin into the header instead is what hono's affected versions did, and the advisory says that turned a configuration that used to fail closed into one that succeeds for every origin.
What a strict CORS policy still leaves to your server
The exact allow-list in the trace does everything CORS can do, and its own output shows where that stops.
In exchange 2, a page on another site asks for the signed-in account with credentials. The server's log line shows the request arrived with a valid session and the account data was sent; the browser rule then withholds it from the page.
Nothing in CORS stopped the server doing the work, and the Fetch Standard warns that any work the server performs might nonetheless leak through side channels, such as timing.
In exchange 5, the other site's preflight fails, so a browser would not send the JSON POST. The scripted client sends it anyway, with the same session cookie, and the note is saved. A browser honours the preflight; nothing else has to. The regression test's last check passes under every policy for the same reason: with no Origin header and no preflight, only the session check decides.
So CORS sits on top of the checks your server makes, never in their place. Authenticate every request, decide on the server what this user may read and change, and keep CSRF defences on state-changing routes. OWASP's HTML5 cheat sheet says CORS does not prevent the requested data from going to an unauthorised location, and that the server still needs its usual CSRF prevention.
How to write a CORS policy down
Write the policy as data that a person can read and a test can check, rather than as logic buried in middleware.
Part 6 of the asset is a record to fill in for each route or group of routes. These are the rules it encodes.
- One list of origins per environment. Production lists the production front ends and staging lists staging; localhost and preview addresses belong in development configuration only. Compare the incoming Origin with the list exactly and send that same value back, as MDN's reference describes.
- Per route where needed. OWASP's HTML5 cheat sheet says to use Access-Control-Allow-Origin only on the URLs that need cross-domain access, not for the whole domain. Public data that needs no sign-in and no network position can take * on its own routes, under the conditions the Fetch Standard sets out.
- Credentials only where the route needs the visitor's cookie, and never with *, which the browser refuses with credentials (Fetch Standard).
- Explicit methods and headers in the preflight answer. MDN says a server responding to a credentialed request must not use * in either, so the lists have to be written out anyway.
- Vary: Origin on every response from a route whose Access-Control-Allow-Origin depends on the request (MDN; Fetch Standard).
- An Access-Control-Max-Age you are prepared to wait out after a change, within the limits browsers impose (Fetch Standard; MDN).
- No null and no pattern matching: the whole origin, or nothing (MDN; OWASP).
- A regression test that asserts what a page on each origin could read, not only which headers came back. ASVS 5.0 requirement 3.4.2 states the outcome the test should hold you to.
What frameworks and CORS libraries do by default
Read your library's defaults before you trust a configuration that works.
The Express cors README's default configuration sets origin to * and the methods to GET, HEAD, PUT, PATCH, POST and DELETE. Setting origin to true reflects the request origin, a string sets one origin, a regular expression reflects any origin that matches it, an array accepts the strings and patterns it lists, and a function can apply logic of your own. credentials: true adds Access-Control-Allow-Credentials. Its examples show the middleware sending Vary: Origin when it names an origin.
Next.js documents three places to set CORS headers. Its Route Handler reference shows them set on one handler's response with the standard Web API methods, in an example that sends Access-Control-Allow-Origin: *, and says that to add CORS headers to multiple Route Handlers you can use Proxy or the next.config.js file.
Its Proxy reference shows an allowedOrigins array: the example checks the request's Origin against it with includes, sends Access-Control-Allow-Origin with that origin only when it is on the list, and answers OPTIONS preflights directly.
For a route that reads cookies, copy the list-and-compare shape rather than the wildcard, add Access-Control-Allow-Credentials: true if the front end sends cookies, and add Vary: Origin, which that example leaves out and the Fetch Standard asks for when the value depends on the request.
The Next.js guide in this library includes the route handler check that handlers returning private data send CORS headers only to origins you expect.
If you use hono, the advisory above applies to versions before 4.12.25. Whatever the framework, the test in Part 3 of the asset checks the behaviour rather than the configuration, which is what matters when a default changes under you.
Running the request trace on your own machine
The trace is an illustration, written for this page.
An invented API at https://api.example.com, served on 127.0.0.1 on a port the system picks, has one made-up account, an office-only route that needs no sign-in, and a JSON route that saves a note. Its CORS policy switches between the seven in the asset.
It was written and run on Node.js 26.0.0 with modules that ship with Node.js, so there is nothing to install, and every output in the asset is copied from that run. Use it for learning and for testing a policy you own.
It cannot run a browser, and it does not pretend to. A scripted client sends each request with the Origin header and, where credentials are included, the session cookie a browser would attach, and prints what the server sent back.
Beside that, a small function in browser-rules.mjs applies the Fetch Standard's CORS check and preflight rules to the real response headers and says whether a browser would let the calling page read the response, or send the actual request at all.
That function is the published rules applied to real headers. It is not a browser, and it leaves out the preflight cache, redirects and the cookie rules that decide whether a cookie is sent.
- Save the five files into an empty folder and open a terminal there.
- Run node run-trace.mjs. For each policy it prints five exchanges, each with the request headers, the response headers, the server's log line, what the client received and what a browser would allow, then a summary table.
- Run node cors-policy.test.mjs. All nine tests pass on the allow-list. Run it again with a policy name, such as reflect-credentials or null-allowed, and the tests that policy breaks fail. The Node.js test runner sets the exit code to 1 when any test fails, so a pipeline step running it fails too.
- Run node browser-check.mjs allow-list and follow Part 4 to watch your own browser do what the trace predicts.
Seeing it in your browser's network panel
The browser check starts the API and two plain pages on 127.0.0.1, each on its own port, so each is a different origin. The API lists the first page's origin and not the second. Sign in at the address it prints, open each page, and run the two fetch lines it prints from the developer tools console: one credentialed GET of the account and one JSON POST that needs a preflight.
In the Network panel, select each request and read the Origin request header and the Access-Control-Allow-Origin, Access-Control-Allow-Credentials and Vary response headers. The terminal prints one line for every request the API receives. From the unlisted page you should see the GET arrive with a valid session and the account sent, while the console reports the fetch failed; and for the POST, only the OPTIONS line, because the browser holds the POST back when the preflight fails. Restart with reflect-credentials and the unlisted page can read the account.
Pointing the regression test at your own API
Keep the nine tests and change three things: start your own API on a test port with a seeded test account in place of the lab, use your own routes in place of the three lab routes, and set the allowed origin to each origin on your environment's list.
Keep the attacker, look-alike and null origins, and keep both kinds of assertion for every route: the headers, and what corsCheck and checkPreflight say a page could read or send. Run it against a staging or local copy with test accounts.
How to test a CORS policy you own
OWASP's WSTG-CLNT-07, Testing Cross Origin Resource Sharing, has two objectives: identify endpoints that implement CORS, and ensure that the CORS configuration is secure or harmless.
These steps cover both on an application you own.
- Find every route that sends Access-Control-Allow-Origin. Search the code and configuration for the header and for your CORS library's settings, and read the response headers of each API route, including routes that serve files and errors.
- Send each route a request with Origin set to your front end, to an origin not on your list, to a look-alike that starts or ends with your domain, and to null, each with and without a test account's session cookie. Record Access-Control-Allow-Origin, Access-Control-Allow-Credentials and Vary.
- Send an OPTIONS preflight for each method and header your front end uses that is not safelisted, from your front end and from an unlisted origin, and record Access-Control-Allow-Methods, Access-Control-Allow-Headers and Access-Control-Max-Age.
- Decide what a page could read with the CORS check, not by eye. browser-rules.mjs in the asset does this from recorded headers.
- For every route that sends *, confirm the response includes no sensitive information (ASVS 5.0 requirement 3.4.2) and nothing protected through IP authentication or a firewall, which the Fetch Standard says makes using the CORS protocol unsafe.
- Test only systems you own or are authorised in writing to test, with test accounts and test records.
Where CORS ends and the neighbouring guides begin
A forged request does not need to read anything, and a simple request needs no preflight, so CORS does little against cross-site request forgery; the CSRF guide covers the checks that refuse a forged request.
Whether a session cookie travels on a cross-site request at all depends on its attributes, which the cookie security guide covers. A token your own script puts in an Authorization header is not something the browser attaches by itself, and how an API should verify such tokens is the subject of the JWT security guide.
Checking that every API call comes from someone allowed to make it, the work CORS never does, belongs to the API security guide. And the Next.js guide covers where CORS headers sit among the other entry points of a Next.js application.
Where an outside test fits
Your own trace checks the routes you know about.
A Clever Ops web application and API penetration test covers authentication and sessions, what each role can see and change, and the API called directly rather than only through the screens. The website security check, which does not sign in, includes cross-origin rules under WSTG-CLNT-07: its good result is that endpoints either send no Access-Control-Allow-Origin header or name the origins allowed, and none echoes back whatever origin asks.
Each finding comes with evidence, a fix written for your stack and the criteria the retest will use. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
A cross-origin resource sharing policy that lets origins read your responses when they should not: echoing back any Origin, listing null, matching origins loosely, sending * on data that relies on network position, or allowing credentials more widely than the routes need. With credentials allowed, a page on another site can read what your API returns to a signed-in visitor's browser. The hono advisory on this page maps such a flaw to MITRE's CWE-942, Permissive Cross-domain Security Policy with Untrusted Domains.
No. CORS tells browsers which other origins may read your responses. It does not stop a simple request reaching your server, it does not authenticate anyone, and clients that are not browsers ignore it. WSTG-CLNT-07 says the Origin header may be spoofed outside the browser and that application-level protocols are still needed to protect sensitive data. Authentication and authorisation on your server decide who may do what.
For public data anyone could fetch, the Fetch Standard calls it safe, and the browser does not share a credentialed response under it. It is unsafe for anything protected by IP address or a firewall, and ASVS 5.0 requirement 3.4.2 asks that a response sent with * includes no sensitive information.
Because the browser refuses. In the Fetch Standard's CORS check, a credentialed request needs Access-Control-Allow-Origin to equal its own origin exactly and Access-Control-Allow-Credentials to be true, so * fails and the page gets a network error, although the server has sent the response. Name the origin from an allow-list instead; reflecting whatever Origin arrives opens the account to every site.
An OPTIONS request a browser sends before a cross-origin request that is not simple, such as a POST with Content-Type: application/json or a request with an Authorization header. It carries Access-Control-Request-Method and, where needed, Access-Control-Request-Headers, never credentials, and the browser sends the actual request only if the answer approves the origin, method and headers. It is not authentication, and clients that are not browsers skip it.
Because anyone can send it. MDN says sandboxed documents and resources with schemes such as data: or file: have the origin null, that many browsers grant such documents access when Access-Control-Allow-Origin is null, and that any origin can create a hostile document with a null origin.
When Access-Control-Allow-Origin depends on the request's Origin, yes: MDN and the Fetch Standard both say to send Vary: Origin. MDN says it indicates that server responses can differ based on the Origin request header, and the Fetch Standard's example is a cached response to a non-CORS request, without Access-Control-Allow-Origin, being reused for a later CORS request. For * or one fixed origin, the Fetch Standard says to send the header on every response and not to use Vary.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.