Cross-origin isolation, CORS and Fetch Metadata

The same-origin policy refreshed, CORS configured without reflecting Origin into a breach, COOP, COEP and CORP, what cross-origin isolated means and why Spectre forced it, XS-Leaks, and a Fetch Metadata resource isolation policy.

FREEBy ·Lesson·10 min read·Intermediate → Advanced
CORS misconfigurationCOOP COEPcross-origin isolationXS-LeaksSec-Fetch-SiteFetch Metadata

01Origin, site and the same-origin policy

✓What you will learn
  • Tell origin from site and explain what the same-origin policy actually blocks
  • Configure CORS with credentials and preflight correctly, and spot Origin-reflection bugs
  • Explain COOP, COEP and CORP and what cross-origin isolation unlocks
  • Describe XS-Leaks and defend with a Fetch Metadata resource isolation policy

An origin is the triple scheme, host and port: https://app.cyart.io:443. A site is the scheme plus the registrable domain (eTLD+1, using the Public Suffix List): https://cyart.io. So app.cyart.io and docs.cyart.io are different origins but the same site. Cookies and SameSite work on sites; the same-origin policy works on origins.

The same-origin policy (SOP) does not stop cross-origin requests. A page on evil.example can submit forms to, embed images from and send fetch requests to your API. What SOP blocks is reading the response and reaching into another origin's DOM. That gap explains CSRF (requests go out with cookies), and it explains why CORS is a relaxation of SOP, not a protection: it lets a server tell the browser which other origins may read its responses.

02CORS done right

For a cross-origin fetch, the browser adds an Origin header. Simple requests (GET, HEAD or POST with only safelisted headers and a content type of application/x-www-form-urlencoded, multipart/form-data or text/plain) are sent immediately; CORS only decides whether the script may read the response. Anything else (PUT, DELETE, Content-Type: application/json, custom headers) triggers a preflight: an OPTIONS request with Access-Control-Request-Method and Access-Control-Request-Headers, which the server must approve before the real request is sent.

Response headerMeaningPitfall
Access-Control-Allow-OriginWhich origin may read the response: one exact origin or *Only one value allowed; lists are invalid
Access-Control-Allow-Credentials: trueResponse may be read when cookies or HTTP auth were sentBrowsers refuse it together with Allow-Origin: *, which tempts people to reflect Origin instead
Access-Control-Allow-Methods / -HeadersPreflight approvalReflecting the requested headers approves anything
Access-Control-Max-AgeHow long a preflight may be cachedBrowsers cap it (Chromium at 2 hours)
Vary: OriginCaches must key on OriginMissing it lets a CDN serve one origin's ACAO to another
CORS with credentials, exact allow-listts
import type { Request, Response, NextFunction } from "express";

const ALLOWED_ORIGINS = new Set(["https://app.cyart.io", "https://admin.cyart.io"]);

export function cors(req: Request, res: Response, next: NextFunction) {
  const origin = req.headers.origin;
  res.vary("Origin");
  if (typeof origin === "string" && ALLOWED_ORIGINS.has(origin)) { // exact match only
    res.setHeader("Access-Control-Allow-Origin", origin);
    res.setHeader("Access-Control-Allow-Credentials", "true");
  }
  if (req.method === "OPTIONS") {
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Request-Id");
    res.setHeader("Access-Control-Max-Age", "600");
    return res.status(204).end();
  }
  next();
}

// Bugs seen in real audits:
//   origin.endsWith("cyart.io")          -> https://evilcyart.io passes
//   origin.startsWith("https://cyart.io") -> https://cyart.io.evil.example passes
//   /cyart.io/.test(origin)              -> unescaped dot and no anchors: https://cyartXio.attacker.net passes
//   allowing "null"                      -> sandboxed iframes and data: URLs send Origin: null
!Reflecting Origin with credentials is a data breach

If the server copies any Origin into Access-Control-Allow-Origin and sets Allow-Credentials: true, every website the victim visits can read their authenticated API responses. It is the most common serious CORS finding and the usual result of "just make the error go away".

03COOP, COEP, CORP and cross-origin isolation

Spectre (2018) showed that speculative execution lets code read memory it should not, using precise timers to measure cache effects. In a browser, that means a malicious page could read data from any cross-origin resource loaded into the same process. Browsers responded with site isolation (separate processes per site), coarser timers, disabling SharedArrayBuffer, and CORB/ORB (blocking cross-origin no-cors responses such as JSON and HTML from entering the renderer). Then they defined headers that let a page opt in to strong isolation and get the powerful features back.

HeaderValuesEffect
Cross-Origin-Opener-Policy (COOP)same-origin, same-origin-allow-popups, noopener-allow-popups, unsafe-nonePuts the page in its own browsing context group; cross-origin openers and popups lose their window handle to it
Cross-Origin-Embedder-Policy (COEP)require-corp, credentialless, unsafe-nonePage may only load cross-origin subresources that opt in via CORP or CORS (or, with credentialless, are fetched without cookies)
Cross-Origin-Resource-Policy (CORP)same-origin, same-site, cross-originSet on a resource: who may embed it in no-cors mode

A document served with COOP `same-origin` and COEP `require-corp` (or credentialless) is cross-origin isolated: self.crossOriginIsolated is true, and it regains SharedArrayBuffer, more precise performance.now() and performance.measureUserAgentSpecificMemory(). The guarantee is that nothing cross-origin shares its process unless that resource agreed to it.

  • COOP alone is worth deploying on any sensitive page, especially login and payment flows: it kills attacks that use a window reference (frame counting, navigation tricks, opener tampering). Use same-origin-allow-popups if you open OAuth or payment popups that must talk back.
  • CORP `same-origin` on private API responses and user images stops other sites embedding them as no-cors resources, a common XS-Leak and Spectre target.
  • COEP is the hard one: every third-party script, image and iframe must send CORP or CORS headers. credentialless eases it by loading cross-origin no-cors resources without cookies.

04XS-Leaks and Fetch Metadata

XS-Leaks (cross-site leaks) infer information about a user's state on another site through side channels, without reading responses. Examples: an <img> or <script> tag's onload versus onerror reveals whether a URL returns 200 or 404 ("is this user logged in", "does a search for X return results"), window.length on a popup counts its frames, response timing reveals result size, and cache probing reveals visited resources. Each leak is small; chained, they deanonymise users or extract search results.

Fetch Metadata request headers tell the server where a request came from, so it can refuse cross-site requests it never expects. Browsers send them automatically and pages cannot forge them.

HeaderValuesUse
Sec-Fetch-Sitesame-origin, same-site, cross-site, noneWho initiated it. none means the user typed the URL or used a bookmark
Sec-Fetch-Modenavigate, cors, no-cors, same-origin, websocketTop-level navigation versus a subresource or fetch
Sec-Fetch-Destdocument, iframe, image, script, empty, and othersWhat the response will be used as
Sec-Fetch-User?1Navigation triggered by a user gesture
Fetch Metadata middlewarets
import type { Request, Response, NextFunction } from "express";

// Resource isolation policy: reject cross-site requests except plain top-level navigations.
const CROSS_SITE_ALLOWED_PATHS = new Set(["/oauth/callback", "/api/public/status"]);

export function resourceIsolation(req: Request, res: Response, next: NextFunction) {
  const site = req.get("Sec-Fetch-Site");
  if (!site) return next();                                   // older browser or non-browser client
  if (site === "same-origin" || site === "same-site" || site === "none") return next();

  const mode = req.get("Sec-Fetch-Mode");
  const dest = req.get("Sec-Fetch-Dest");
  const isSafeNavigation = mode === "navigate" && req.method === "GET" && dest !== "object" && dest !== "embed";
  if (isSafeNavigation || CROSS_SITE_ALLOWED_PATHS.has(req.path)) return next();

  res.status(403).send("cross-site request blocked");          // log in report-only mode first
}
isame-site is broader than you think

Sec-Fetch-Site: same-site includes every subdomain of your registrable domain, including a user-content or marketing host. If such hosts exist, allow only same-origin on sensitive endpoints.

◎Interview radar

Expect a CORS config to review. Look for Origin reflection with credentials, suffix or regex matching, allowing null, and missing Vary: Origin. Then show depth: CORS does not stop requests being sent, so state-changing endpoints still need CSRF defences, and Fetch Metadata plus COOP/CORP close the XS-Leak side channels CORS never addressed.

“How to say it in the room

"CORS only controls who can read responses, so I'd use an exact origin allow-list with credentials, Vary: Origin, and never reflect or allow null. For the rest of the cross-origin surface I'd add a Fetch Metadata policy that rejects cross-site subresource requests, COOP same-origin on sensitive pages so other windows lose their handle, and CORP same-origin on private responses. Full COEP and cross-origin isolation I'd reserve for pages that need SharedArrayBuffer."

Test yourself

An API responds to any request with `Access-Control-Allow-Origin: <value of the Origin header>` and `Access-Control-Allow-Credentials: true`. What can a malicious site do?

Q1Does CORS protect against CSRF?+

No. A simple cross-site POST is sent with cookies before CORS is consulted, and CORS only governs reading the response. Use SameSite cookies, CSRF tokens or Fetch Metadata checks on state-changing endpoints.

Q2Why does COEP break third-party embeds?+

Under require-corp, every cross-origin no-cors subresource must send Cross-Origin-Resource-Policy allowing the embed, or be loaded with CORS. Many ad, analytics and widget providers do not, so they fail to load. credentialless is the usual escape hatch.

Q3What does `Sec-Fetch-Site: none` mean?+

The request was user-initiated outside any page context: typing a URL, a bookmark, or opening a link from another application. It should be treated like same-origin for navigations.

Finished this one?
Tick it and it shows as done on the roadmap and the course.