Can a cookie-bearing request authorize an operation?
CSRF separates a request carrying a browser's ambient authentication information from an operation the user intended to authorize. This experiment targets only a disposable service running locally. Node.js and Playwright submit real browser forms, and the server's mutation counters determine the result. No external service or real account is involved. Read the session/Cookie guide and Cookie-attribute experiment first.
Focus on a different origin within the same site. With the same scheme, app.alpha.test and peer.alpha.test are same-site but have different origins because their hosts differ. Treating SameSite as an exact-origin restriction misses this case. The fixed Lax=1 cookie models authenticated state; it is not an implementation of production session generation or storage. The fixture deliberately isolates request provenance and operation checks from those additional requirements.
Prepare a disposable browser and trusted test certificates
The recorded environment used Node.js 24.22.1, Playwright 1.64.1, and Chromium 156.0.8078.4 on isolated Ubuntu 26.04.1. Save the shared program as web-boundary-lab.cjs. Provide OpenSSL and certutil from libnss3-tools, run npm install playwright@1.64.1 and npx playwright install --with-deps chromium, then execute node web-boundary-lab.cjs csrf. Use an environment where installing browser dependencies is appropriate.
The program creates a temporary CA and certificate and trusts that CA only in the experiment's isolated HOME. It does not reuse an existing browser profile. HTTPS validation remains enabled. Test hostnames resolve to loopback and the server binds only there. Browser, server, and temporary files are cleaned up afterward. If preparation fails, record the failure rather than disabling TLS verification to obtain a passing result.
Place protected and unprotected operations side by side
The fixture exposes unsafe and safe mutation routes. The unsafe route checks the Lax=1 authentication marker but increments its counter without checking provenance or a token. The safe route requires the same marker, the exact app Origin, and a token matching the server-held value. The dynamically chosen port is part of that exact origin.
A cryptographically random token is available through a same-origin route. Tests satisfy only one defense at a time and verify that the other still rejects the request. Limited CORS configuration on observation routes is not treated as a mechanism that prevents form submission. Separate counters for the two routes reveal whether state actually changed. This is stronger evidence than interpreting a page transition or HTTP status alone, and keeps each acceptance condition explicit.
Run the shared program in CSRF mode
The following program is shared with the Cookie experiment; the csrf argument selects this test sequence. It submits actual browser forms rather than substituting fetch results. After cookies are set, a form from peer to unsafe returns 200 and makes unsafeChanges equal one. This observes a cookie-bearing mutation from a same-site but different origin.
Three safe-route cases then return 403: no token, an incorrect token, and a correct token sent from the wrong Origin. Finally, an app-origin form with the correct token returns 200 and makes safeChanges equal one. A valid success case ensures that rejecting every request is not mistaken for a working defense. Output includes browser and library versions, case outcomes, and the two state-change counters. Compare all of those fields with the expected sequence.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const https = require('node:https');
const {execFileSync} = require('node:child_process');
const {randomBytes} = require('node:crypto');
const assert = require('node:assert/strict');
const {chromium} = require('playwright');
const mode = process.argv[2] || 'cookies';
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'web-boundary-'));
const home = path.join(work, 'home');
const db = path.join(home, '.pki', 'nssdb');
fs.mkdirSync(db, {recursive:true});
function run(command, args) { execFileSync(command, args, {cwd:work, stdio:'pipe'}); }
run('openssl', ['req','-x509','-newkey','rsa:2048','-nodes','-days','1','-subj','/CN=Teaching Root','-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign','-keyout','ca.key','-out','ca.pem']);
run('openssl', ['req','-newkey','rsa:2048','-nodes','-subj','/CN=app.alpha.test','-keyout','server.key','-out','server.csr']);
fs.writeFileSync(path.join(work,'server.ext'), 'subjectAltName=DNS:app.alpha.test,DNS:peer.alpha.test,DNS:other.beta.test\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n');
run('openssl', ['x509','-req','-in','server.csr','-CA','ca.pem','-CAkey','ca.key','-CAcreateserial','-days','1','-extfile','server.ext','-out','server.pem']);
run('certutil',['-N','-d','sql:'+db,'--empty-password']);
run('certutil',['-A','-d','sql:'+db,'-n','Teaching Root','-t','C,,','-i',path.join(work,'ca.pem')]);
let app, peer, other, unsafeChanges = 0, safeChanges = 0;
const token = randomBytes(24).toString('hex');
const server = https.createServer({key:fs.readFileSync(path.join(work,'server.key')),cert:fs.readFileSync(path.join(work,'server.pem'))}, (req,res)=>{
const route = req.url.split('?')[0];
const cookie = req.headers.cookie || '';
const origin = req.headers.origin || '';
const send = (status,data)=>{res.writeHead(status,{'Content-Type':'application/json'});res.end(JSON.stringify(data));};
if(route==='/set') {
res.setHeader('Set-Cookie',[
'Strict=1; Path=/; Secure; HttpOnly; SameSite=Strict',
'Lax=1; Path=/; Secure; HttpOnly; SameSite=Lax',
'None=1; Path=/; Secure; HttpOnly; SameSite=None',
'visible=demo; Path=/; Secure; SameSite=Lax',
'scoped=1; Path=/private; Secure; SameSite=None'
]);
return send(200,{set:true});
}
if(route==='/echo'||route==='/private/echo') {
if([app,peer,other].includes(origin)) {
res.setHeader('Access-Control-Allow-Origin',origin);
res.setHeader('Access-Control-Allow-Credentials','true');
}
return send(200,{cookie,origin,method:req.method});
}
if(route==='/token') return send(200,{token});
if(route==='/unsafe'||route==='/safe') {
let data='';req.on('data',part=>data+=part);req.on('end',()=>{
if(!cookie.split('; ').includes('Lax=1')) return send(401,{error:'no test session'});
const supplied = new URLSearchParams(data).get('csrf');
if(route==='/safe'&&(origin!==app||supplied!==token)) return send(403,{error:'request rejected'});
if(route==='/safe') safeChanges++; else unsafeChanges++;
return send(200,{changed:true});
});return;
}
res.writeHead(200,{'Content-Type':'text/html'});
res.end(`<a id="nav" href="${app}/echo">Navigate to app</a><form method="post" action="${app}/unsafe"><label>Token<input name="csrf"></label><button>Send</button></form>`);
});
(async()=>{
let browser;
try {
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const port=server.address().port;
app=`https://app.alpha.test:${port}`;peer=`https://peer.alpha.test:${port}`;other=`https://other.beta.test:${port}`;
browser=await chromium.launch({headless:true,env:{...process.env,HOME:home},args:['--no-proxy-server','--host-resolver-rules=MAP *.alpha.test 127.0.0.1,MAP *.beta.test 127.0.0.1']});
const context=await browser.newContext({ignoreHTTPSErrors:false});
const page=await context.newPage();
await page.goto(app+'/set');
const report={mode,browser:browser.version(),playwright:require('playwright/package.json').version,node:process.version,os:os.release(),tlsValidation:true,results:[]};
if(mode==='cookies') {
const visible=await page.evaluate(()=>document.cookie);
assert(visible.includes('visible=demo')&&!visible.includes('Strict=')&&!visible.includes('Lax=')&&!visible.includes('None='));
report.results.push({case:'document.cookie',observed:visible});
await page.goto(peer+'/page');
const same=await page.evaluate(async url=>(await fetch(url,{credentials:'include'})).json(),app+'/echo');
assert(same.cookie.includes('Strict=1')&&same.cookie.includes('Lax=1'));
report.results.push({case:'same-site cross-origin fetch',...same});
await page.goto(other+'/page');
const cross=await page.evaluate(async url=>(await fetch(url,{credentials:'include'})).json(),app+'/echo');
assert(!cross.cookie.includes('Strict=1')&&!cross.cookie.includes('Lax=1'));
report.results.push({case:'cross-site fetch; None subject to browser policy',...cross});
const navigation=page.waitForResponse(r=>r.url()===app+'/echo'&&r.request().isNavigationRequest());
await page.locator('#nav').click();
const top=await (await navigation).json();
assert(top.cookie.includes('Lax=1')&&!top.cookie.includes('Strict=1'));
report.results.push({case:'cross-site top-level GET',...top});
const privateResponse=await page.goto(app+'/private/echo');
assert((await privateResponse.json()).cookie.includes('scoped=1'));
const ordinary=await page.goto(app+'/echo');
assert(!(await ordinary.json()).cookie.includes('scoped=1'));
const hostOnly=await page.goto(peer+'/echo');
assert(!(await hostOnly.json()).cookie.includes('Lax=1'));
report.results.push({case:'Path and host-only controls',pass:true});
} else if(mode==='csrf') {
async function submit(source,target,supplied='') {
await page.goto(source+'/page');
await page.locator('form').evaluate((form,url)=>form.action=url,app+target);
await page.getByRole('textbox',{name:'Token'}).fill(supplied);
const response=page.waitForResponse(r=>r.url()===app+target&&r.request().isNavigationRequest());
await page.getByRole('button',{name:'Send',exact:true}).click();
return (await response).status();
}
assert.equal(await submit(peer,'/unsafe'),200);
assert.equal(unsafeChanges,1);
assert.equal(await submit(peer,'/safe'),403);
assert.equal(await submit(app,'/safe','wrong'),403);
assert.equal(await submit(peer,'/safe',token),403);
assert.equal(await submit(app,'/safe',token),200);
assert.equal(safeChanges,1);
report.results.push({case:'same-site cross-origin unsafe POST',status:200,changes:unsafeChanges},{case:'safe: missing token, wrong token, wrong origin',status:403},{case:'safe: correct origin and token',status:200,changes:safeChanges});
} else throw Error('Expected cookies or csrf');
console.log(JSON.stringify(report));
} finally {
if(browser) await browser.close();
await new Promise(resolve=>server.close(resolve));
fs.rmSync(work,{recursive:true,force:true});
}
})().catch(error=>{console.error(error);process.exitCode=1;});Interpret SameSite and CORS at their actual boundaries
Do not explain the successful unsafe case by saying SameSite malfunctioned. Peer and app are same-site. SameSite=Lax does not reject a request simply because these two origins differ. Cross-site requests have different cookie conditions; the companion experiment separates fetch behavior from top-level GET navigation. This successful case does not generalize to every cross-site POST.
CORS governs whether scripts may read certain responses. Inability to read a response does not undo a state change caused by a form request. A CSRF token also does not solve arbitrary script execution through XSS. Return to the threat assumptions: can an adversary obtain the token, and in which origin can code execute? This experiment tests selected provenance and token conditions, not every possible way those assumptions could fail.
Check rejected responses against persisted effects
A 403 response should be paired with evidence that safeChanges did not increase. An implementation that mutates first and returns an error afterward has not protected the operation, despite displaying rejection. This program places checks before mutation and asserts that only the final valid request makes the protected count reach one. Apply that pattern to other state-changing APIs: compare the response with the stored result. A response code and the absence of a side effect are different observations, and both matter when the security requirement is that an unauthorized operation never takes effect.
Exercise: name each rejection reason
Explain why peer is rejected even when it sends the correct token. The exact Origin is not the app origin. Then explain why an app request with an incorrect token fails despite satisfying the Origin check. Record which condition passed and which failed instead of compressing both into the phrase “safe request.”
Finally ask whether the fixture accepts a request with no Origin. It does not: exact equality with the allowed origin is required. A real service must define its missing-Origin policy for supported clients and proxies. Submit the command, environment, source origin, token and cookie conditions, status, and mutation counters. Keep the fixed authentication marker as an experimental fixture; production session management requires its separate design and checks.