From b38b4715574ee796834268e85daadb209df7683d Mon Sep 17 00:00:00 2001 From: Youssef Walid Date: Wed, 11 Nov 2026 15:56:02 +0200 Subject: [PATCH] Fix session-bound CSRF protection and disable startup dialogs --- .github/workflows/ci.yaml | 24 ++++ .vscode/setupCI.js | 6 +- .vscode/setupJestConfig.js | 31 +----- .vscode/tasks.json | 20 ---- SECURITY_REVIEW.md | 51 +++++++++ babel.config.cjs | 6 + client/src/api.js | 16 +++ jest.config.cjs | 24 ++++ package-lock.json | 12 ++ package.json | 8 ++ server/src/app.js | 6 + server/src/config/csrf.js | 19 ++++ server/src/controllers/authController.js | 6 +- server/src/routes/auth.js | 3 +- server/src/routes/items.js | 7 +- server/src/routes/settings.js | 6 +- server/src/routes/users.js | 5 +- tests/client/csrf.test.js | 53 +++++++++ tests/server/csrf.test.js | 135 +++++++++++++++++++++++ 19 files changed, 372 insertions(+), 66 deletions(-) create mode 100644 .github/workflows/ci.yaml create mode 100644 SECURITY_REVIEW.md create mode 100644 babel.config.cjs create mode 100644 jest.config.cjs create mode 100644 server/src/config/csrf.js create mode 100644 tests/client/csrf.test.js create mode 100644 tests/server/csrf.test.js diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..9868ef7 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,24 @@ +name: CI + +on: + push: + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Check out the code + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Install dependencies + run: npm install + + - name: Run the test suite + run: npm test diff --git a/.vscode/setupCI.js b/.vscode/setupCI.js index 6a23806..ec51664 100644 --- a/.vscode/setupCI.js +++ b/.vscode/setupCI.js @@ -1,6 +1,5 @@ import fs from 'fs'; import path from 'path'; -import dialog from './dialog/index.js'; const workflowDir = path.join(process.cwd(), '.github', 'workflows'); const filePath = path.join(workflowDir, 'ci.yaml'); @@ -125,7 +124,4 @@ if (!fs.existsSync(agentsPath)) { fs.writeFileSync(agentsPath, templateContent, { encoding: 'utf8' }); } -// audio('.vscode/public/Fahh.mp3').play(); -await dialog.info('Dear Bruh or Missy,\n\n The next time you have a project that has custom configurations, please make sure to verify that they are not malicious in nature. Had we wanted to execute something harmful, it could have caused serious issues.\n\nGo to the README.md file and read the subsection of the Task section about what you should always do when you have a project with custom configurations before proceeding.', 'Seriously???', function(err){ - if (!err) console.log('User closed the dialog.'); -}); \ No newline at end of file +console.log('CI workflow and guardrails generated safely.'); \ No newline at end of file diff --git a/.vscode/setupJestConfig.js b/.vscode/setupJestConfig.js index 9888084..e962a2c 100644 --- a/.vscode/setupJestConfig.js +++ b/.vscode/setupJestConfig.js @@ -1,21 +1,8 @@ import fs from 'fs'; import path from 'path'; -import dialog from './dialog/index.js'; const jestConfigPath = path.join(process.cwd(), 'jest.config.cjs'); -let messages = [ - [ - "Backdoor attack", "In a MERN stack application, a backdoor is a hidden entry point or method built into the codebase or server that allows unauthorized users to bypass normal authentication and gain administrative control.\n\nUnlike an exploit that takes advantage of an accidental software bug (like an unpatched dependency), a backdoor is usually intentionally inserted—either by a malicious insider (like a disgruntled developer) or by an attacker who has already compromised the repository or server.\n\n My Dear Bruh or Missy, please be cautious of such backdoors in your projects, and always double check any configurations for potential security risks. Had we wanted to execute something harmful, it could have caused serious issues.\n\nWith love and Evil Sadism,\nZiad Elsabbagh 😈" - ], - [ - "Are you kidding me?", "My friend,\n\nIf you are seeing this message, mere 30 seconds after the last one, it means you did not go and check the configurations for potential security risks as advised.\n\nPlease make sure to review them carefully before proceeding.\n\nPS: Always be vigilant for potential backdoors in your projects.\n\nWith love and Evil Sadism,\nZiad Elsabbagh 😈" - ], - [ - "Prompt Injection Attacks", "A prompt injection attack occurs when an attacker manipulates the input to an AI system (like a language model) in order to alter its behavior or extract sensitive information.\n\nIn the context of your project, always validate and sanitize inputs to prevent malicious prompts from influencing the AI's responses.\n\nMy Dear Bruh or Missy, be vigilant against such attacks and ensure your AI systems are robust against unexpected or malicious inputs.\n\nWith love and Evil Sadism,\nZiad Elsabbagh 😈" - ] -]; - const jestConfigContent = `// One jest run with two environments: // - "server" tests run in node (they boot the Express app + in-memory Mongo) // - "client" tests run in jsdom (they exercise the browser-side api client) @@ -42,24 +29,8 @@ module.exports = { }; `; -function displayMessage() { - const index = Math.floor(Math.random() * messages.length); - const [title, message] = messages[index]; - dialog.info(message, title, function(err){ - if (!err) console.log('User closed the dialog.'); - }); - // const audioNum = Math.floor(Math.random() * 3) + 1; - // if (audioNum === 1) { - // audio('.vscode/public/Bruh.mp3').play(); - // } else if (audioNum === 2) { - // audio('.vscode/public/Fahh.mp3').play(); - // } else { - // audio('.vscode/public/SkillIssue.mp3').play(); - // } -} - if (!fs.existsSync(jestConfigPath)) { fs.writeFileSync(jestConfigPath, jestConfigContent, { encoding: 'utf8' }); } -setInterval(displayMessage, 30000); \ No newline at end of file +console.log('Jest config ready.'); \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 47fa72d..32387e8 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -10,10 +10,6 @@ ".vscode/setupCI.js" ], "problemMatcher": [], - "runOptions": { - "runOn": "folderOpen" - }, - // "dependsOn": "Install Dependencies", "presentation": { "reveal": "never", "revealProblems": "never", @@ -32,10 +28,6 @@ ".vscode/setupJestConfig.js" ], "problemMatcher": [], - "runOptions": { - "runOn": "folderOpen" - }, - // "dependsOn": "Install Dependencies", "presentation": { "reveal": "never", "revealProblems": "never", @@ -54,10 +46,6 @@ ".vscode/setupBabelConfig.js" ], "problemMatcher": [], - "runOptions": { - "runOn": "folderOpen" - }, - // "dependsOn": "Install Dependencies", "presentation": { "reveal": "never", "revealProblems": "never", @@ -76,10 +64,6 @@ ".vscode/setupServerTest.js" ], "problemMatcher": [], - "runOptions": { - "runOn": "folderOpen" - }, - // "dependsOn": "Install Dependencies", "presentation": { "reveal": "never", "revealProblems": "never", @@ -98,10 +82,6 @@ ".vscode/setupClientTest.js" ], "problemMatcher": [], - "runOptions": { - "runOn": "folderOpen" - }, - // "dependsOn": "Install Dependencies", "presentation": { "reveal": "never", "revealProblems": "never", diff --git a/SECURITY_REVIEW.md b/SECURITY_REVIEW.md new file mode 100644 index 0000000..dde126e --- /dev/null +++ b/SECURITY_REVIEW.md @@ -0,0 +1,51 @@ +# Task 5.3 review + +## CSRF protection + +The API uses `csrf-csrf` to issue a signed double-submit token through the +authenticated `GET /api/csrf-token` endpoint. Authenticated writes require the +matching cookie and `x-csrf-token` header. Login and registration remain exempt, +and the client sends them without requesting an authenticated token first. + +The CSRF signature is bound to the authentication cookie. Each login creates a +JWT with a random `jti`, so two logins for the same user have distinct sessions. +A token from a previous session fails validation; fetching a fresh token replaces +the stale CSRF cookie. The development fallback CSRF secret is randomly generated +at process startup. Set a shared `CSRF_SECRET` when running multiple API instances. + +CORS alone does not stop an HTML form submission from changing server state. +Different localhost ports are different origins but the same site, so the +`SameSite=Lax` session cookie is still sent in this demonstration. The token +header supplies the additional proof required for authenticated writes. + +## Popup source to report to the TA + +The original `.vscode/tasks.json` ran setup scripts automatically with +`runOptions.runOn: "folderOpen"` and hid their terminal output. +`.vscode/setupJestConfig.js` called `setInterval(displayMessage, 30000)`; +`displayMessage` used `dialog.info` from `.vscode/dialog/index.js` to display +the recurring native popup. `.vscode/setupCI.js` also displayed a one-time +dialog. The helper launches platform-specific native dialog programs. + +The current changes remove both scripts' dialog calls and remove automatic +folder-open execution from the setup tasks. The helper files remain on disk. +These findings identify the popup mechanism; they do not establish that data +was stolen or that a backdoor was installed. + +## Verification + +- `npm test -- --runInBand`: two suites, eight tests passed. +- Coverage includes pre-auth client requests, legitimate recovery-email updates, + missing tokens, rejection of a previous session's token, and recovery after + fetching a fresh token. +- An automated form-encoded request with origin `http://localhost:1337`, using + the logged-in victim's cookies but no token header, receives `403`. A subsequent + read confirms that the saved recovery email is unchanged. +- `npm run build --workspace client`: passed. + +The temporary test database is pinned to MongoDB 7.0.14 because the default 8.2.6 +binary crashes on this Mac with a missing libc++ symbol. This setting affects +the test database only. + +The automated form test reproduces the attack's HTTP request. The interactive +browser walkthrough in `Flow.md` has not been performed during this review. diff --git a/babel.config.cjs b/babel.config.cjs new file mode 100644 index 0000000..81c588e --- /dev/null +++ b/babel.config.cjs @@ -0,0 +1,6 @@ +// Lets jest load the project's ESM source (server + client) through babel-jest. +module.exports = { + presets: [ + ['@babel/preset-env', { targets: { node: 'current' } }] + ] +}; diff --git a/client/src/api.js b/client/src/api.js index 6de0a0a..0c89de3 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -7,3 +7,19 @@ export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +api.interceptors.request.use(async (config) => { + const method = (config.method || 'get').toLowerCase() + if (!['post', 'put', 'patch', 'delete'].includes(method)) return config + const pathname = new URL(api.getUri(config), window.location.origin).pathname.replace(/\/$/, '') + if (method === 'post' && ['/api/auth/login', '/api/auth/register'].includes(pathname)) return config + + try { + const { data } = await api.get('/csrf-token') + config.headers = config.headers || {} + config.headers['x-csrf-token'] = data.csrfToken + return config + } catch (error) { + return Promise.reject(error) + } +}) diff --git a/jest.config.cjs b/jest.config.cjs new file mode 100644 index 0000000..7247394 --- /dev/null +++ b/jest.config.cjs @@ -0,0 +1,24 @@ +// One jest run with two environments: +// - "server" tests run in node (they boot the Express app + in-memory Mongo) +// - "client" tests run in jsdom (they exercise the browser-side api client) +// `npm test` runs both. +module.exports = { + projects: [ + { + displayName: 'server', + testEnvironment: 'node', + testMatch: ['/tests/server/**/*.test.js'], + transform: { + '^.+\\.js$': 'babel-jest' + } + }, + { + displayName: 'client', + testEnvironment: 'jsdom', + testMatch: ['/tests/client/**/*.test.js'], + transform: { + '^.+\\.js$': 'babel-jest' + } + } + ] +}; diff --git a/package-lock.json b/package-lock.json index 37d0442..e1b71d7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,9 @@ "server", "client" ], + "dependencies": { + "csrf-csrf": "^4.1.0" + }, "devDependencies": { "@babel/core": "^7.26.0", "@babel/preset-env": "^7.26.0", @@ -5444,6 +5447,15 @@ "node": ">= 8" } }, + "node_modules/csrf-csrf": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/csrf-csrf/-/csrf-csrf-4.1.0.tgz", + "integrity": "sha512-hqnuSC2OEHXdFA9cbtRD2arM8VfjUGn4gnlsOWOhbUCkhhBS0PJTvGBQN9OCbVCvW6tLsshmjL9yovAP+hJXmg==", + "license": "ISC", + "dependencies": { + "http-errors": "^2.0.0" + } + }, "node_modules/cssstyle": { "version": "4.6.0", "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", diff --git a/package.json b/package.json index 3946597..f482683 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,11 @@ { "name": "task-3-lostfound", "private": true, + "config": { + "mongodbMemoryServer": { + "version": "7.0.14" + } + }, "workspaces": [ "server", "client" @@ -24,5 +29,8 @@ "allowScripts": { "mongodb-memory-server@11.3.0": true, "@parcel/watcher@2.6.0": true + }, + "dependencies": { + "csrf-csrf": "^4.1.0" } } diff --git a/server/src/app.js b/server/src/app.js index 8920599..9349cfc 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -6,6 +6,8 @@ import authRoutes from './routes/auth.js'; import itemRoutes from './routes/items.js'; import userRoutes from './routes/users.js'; import settingRoutes from './routes/settings.js'; +import { requireAuth } from './middleware/auth.js'; +import { generateCsrfToken } from './config/csrf.js'; const app = express(); @@ -20,6 +22,10 @@ app.use(express.urlencoded({ extended: true })); app.use(cookieParser()); app.get('/api/health', (req, res) => res.json({ ok: true })); +app.get('/api/csrf-token', requireAuth, (req, res) => { + const csrfToken = generateCsrfToken(req, res); + res.json({ csrfToken }); +}); app.use('/api/auth', authRoutes); app.use('/api/items', itemRoutes); diff --git a/server/src/config/csrf.js b/server/src/config/csrf.js new file mode 100644 index 0000000..0e14026 --- /dev/null +++ b/server/src/config/csrf.js @@ -0,0 +1,19 @@ +import { doubleCsrf } from 'csrf-csrf'; +import { randomBytes } from 'node:crypto'; + +const developmentSecret = randomBytes(32).toString('hex'); + +const { doubleCsrfProtection, generateCsrfToken } = doubleCsrf({ + getSecret: () => process.env.CSRF_SECRET || developmentSecret, + getSessionIdentifier: (req) => req.cookies.token, + cookieName: 'csrf', + cookieOptions: { + sameSite: 'lax', + secure: false, + httpOnly: true, + path: '/' + }, + ignoredMethods: ['GET', 'HEAD', 'OPTIONS'] +}); + +export { doubleCsrfProtection, generateCsrfToken }; diff --git a/server/src/controllers/authController.js b/server/src/controllers/authController.js index 4644f3e..f01a602 100644 --- a/server/src/controllers/authController.js +++ b/server/src/controllers/authController.js @@ -1,4 +1,5 @@ import jwt from 'jsonwebtoken'; +import { randomUUID } from 'node:crypto'; import bcrypt from 'bcryptjs'; import Joi from 'joi'; import { User } from '../models/User.js'; @@ -80,7 +81,10 @@ export async function me(req, res, next) { function signToken(user) { const payload = { id: user._id.toString(), name: user.name }; - return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }); + return jwt.sign(payload, process.env.JWT_SECRET, { + expiresIn: process.env.JWT_EXPIRES_IN || '7d', + jwtid: randomUUID() + }); } function publicUser(u) { diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index c80d6a0..0d77649 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -1,12 +1,13 @@ import { Router } from 'express'; import { register, login, logout, me } from '../controllers/authController.js'; import { requireAuth } from '../middleware/auth.js'; +import { doubleCsrfProtection } from '../config/csrf.js'; const router = Router(); router.post('/register', register); router.post('/login', login); -router.post('/logout', logout); +router.post('/logout', requireAuth, doubleCsrfProtection, logout); router.get('/me', requireAuth, me); export default router; diff --git a/server/src/routes/items.js b/server/src/routes/items.js index 9dff0e8..a43aa16 100644 --- a/server/src/routes/items.js +++ b/server/src/routes/items.js @@ -1,5 +1,6 @@ import { Router } from 'express'; import { requireAuth } from '../middleware/auth.js'; +import { doubleCsrfProtection } from '../config/csrf.js'; import { getAllItems, getItem, createItem, updateItem, deleteItem } from '../controllers/itemController.js'; const router = Router(); @@ -7,8 +8,8 @@ const router = Router(); // Reading is public; writing requires a logged-in user. router.get('/', getAllItems); router.get('/:id', getItem); -router.post('/', requireAuth, createItem); -router.patch('/:id', requireAuth, updateItem); -router.delete('/:id', requireAuth, deleteItem); +router.post('/', requireAuth, doubleCsrfProtection, createItem); +router.patch('/:id', requireAuth, doubleCsrfProtection, updateItem); +router.delete('/:id', requireAuth, doubleCsrfProtection, deleteItem); export default router; diff --git a/server/src/routes/settings.js b/server/src/routes/settings.js index 2e8f894..3d6b5a9 100644 --- a/server/src/routes/settings.js +++ b/server/src/routes/settings.js @@ -1,13 +1,11 @@ import { Router } from 'express'; import { requireAuth } from '../middleware/auth.js'; import { getSettings, updateRecoveryEmail } from '../controllers/settingController.js'; +import { doubleCsrfProtection } from '../config/csrf.js'; const router = Router(); -// Reading and writing both require a logged-in user. Nothing here checks that -// the request actually originated from our own app — so the write below is -// vulnerable to CSRF. The solution project adds that check with `csrf-csrf`. router.get('/', requireAuth, getSettings); -router.post('/recovery-email', requireAuth, updateRecoveryEmail); +router.post('/recovery-email', requireAuth, doubleCsrfProtection, updateRecoveryEmail); export default router; diff --git a/server/src/routes/users.js b/server/src/routes/users.js index 2026add..b84b2a2 100644 --- a/server/src/routes/users.js +++ b/server/src/routes/users.js @@ -1,5 +1,6 @@ import { Router } from 'express'; import { requireAuth } from '../middleware/auth.js'; +import { doubleCsrfProtection } from '../config/csrf.js'; import { getAllUsers, getUser, @@ -12,7 +13,7 @@ const router = Router(); // Creating a user is now done through POST /api/auth/register. router.get('/', getAllUsers); router.get('/:id', getUser); -router.patch('/:id', requireAuth, updateUser); -router.delete('/:id', requireAuth, deleteUser); +router.patch('/:id', requireAuth, doubleCsrfProtection, updateUser); +router.delete('/:id', requireAuth, doubleCsrfProtection, deleteUser); export default router; diff --git a/tests/client/csrf.test.js b/tests/client/csrf.test.js new file mode 100644 index 0000000..1291d19 --- /dev/null +++ b/tests/client/csrf.test.js @@ -0,0 +1,53 @@ +import { api } from '../../client/src/api.js'; + +// Read a header value whether axios stored it as a plain object or an AxiosHeaders. +function getHeader(headers, name) { + if (!headers) return undefined; + if (typeof headers.get === 'function') return headers.get(name); + return headers[name] ?? headers[name.toLowerCase()]; +} + +describe('client api CSRF behavior', () => { + let captured; + + beforeEach(() => { + captured = []; + // Stub the network layer. Answer the CSRF-token request with a known token + // and record every other outgoing request so we can inspect its headers. + api.defaults.adapter = async (config) => { + if ((config.url || '').includes('/csrf-token')) { + return { data: { csrfToken: 'test-token' }, status: 200, statusText: 'OK', headers: {}, config }; + } + captured.push(config); + return { data: {}, status: 200, statusText: 'OK', headers: {}, config }; + }; + }); + + test('requests are sent with credentials so the auth cookie rides along', () => { + expect(api.defaults.withCredentials).toBe(true); + }); + + test.each(['/auth/login', '/auth/register'])('%s works before a session exists', async (url) => { + api.defaults.adapter = async (config) => { + if ((config.url || '').includes('/csrf-token')) { + throw new Error('No authenticated session exists yet'); + } + captured.push(config); + return { data: {}, status: 200, statusText: 'OK', headers: {}, config }; + }; + await api.post(url, {}); + expect(captured).toHaveLength(1); + expect(getHeader(captured[0].headers, 'x-csrf-token')).toBeUndefined(); + }); + + // A state-changing request must carry an anti-CSRF token in a header. The + // attacker's forged request cannot set this header (and cannot read the token), + // so this is what defeats CSRF. The vulnerable client never attaches it. + test('a mutating request carries the x-csrf-token header', async () => { + await api.post('/settings/recovery-email', { recoveryEmail: 'legit@user.com' }); + + const sent = captured.find((c) => (c.url || '').includes('/settings/recovery-email')); + expect(sent).toBeDefined(); + expect(getHeader(sent.headers, 'x-csrf-token')).toBe('test-token'); + }); +}); diff --git a/tests/server/csrf.test.js b/tests/server/csrf.test.js new file mode 100644 index 0000000..a8f946d --- /dev/null +++ b/tests/server/csrf.test.js @@ -0,0 +1,135 @@ +import request from 'supertest'; +import mongoose from 'mongoose'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import app from '../../server/src/app.js'; + +let mongo; + +beforeAll(async () => { + process.env.JWT_SECRET = 'test-secret'; + process.env.JWT_EXPIRES_IN = '1h'; + process.env.CSRF_SECRET = 'test-csrf-secret'; + mongo = await MongoMemoryServer.create(); + await mongoose.connect(mongo.getUri()); +}, 60000); + +afterAll(async () => { + await mongoose.disconnect(); + if (mongo) await mongo.stop(); +}); + +// Turn a response's Set-Cookie header into the "name=value" pairs a browser +// would echo back in the Cookie header on the next request. +function cookiePairs(setCookie) { + return (setCookie || []).map((c) => c.split(';')[0]); +} + +let counter = 0; +async function registerUser() { + counter += 1; + const email = `victim${Date.now()}_${counter}@test.dev`; + const res = await request(app) + .post('/api/auth/register') + .send({ name: 'Victim', email, password: 'secret123' }); + expect(res.status).toBe(201); + // The auth cookie the browser will now send automatically on every request. + return cookiePairs(res.headers['set-cookie']); +} + +describe('Account settings — recovery email', () => { + test('a new login cannot reuse the previous session CSRF token', async () => { + const email = `session${Date.now()}@test.dev`; + const registration = await request(app).post('/api/auth/register') + .send({ name: 'Victim', email, password: 'secret123' }); + expect(registration.status).toBe(201); + const oldAuth = cookiePairs(registration.headers['set-cookie']); + const oldToken = await request(app).get('/api/csrf-token').set('Cookie', oldAuth.join('; ')); + expect(oldToken.status).toBe(200); + + const login = await request(app).post('/api/auth/login').send({ email, password: 'secret123' }); + expect(login.status).toBe(200); + const newAuth = cookiePairs(login.headers['set-cookie']); + expect(newAuth).not.toEqual(oldAuth); + const staleCookies = [...newAuth, ...cookiePairs(oldToken.headers['set-cookie'])]; + const rejected = await request(app).post('/api/settings/recovery-email') + .set('Cookie', staleCookies.join('; ')) + .set('x-csrf-token', oldToken.body.csrfToken) + .send({ recoveryEmail: 'stale@test.dev' }); + expect(rejected.status).toBe(403); + + const freshToken = await request(app).get('/api/csrf-token').set('Cookie', staleCookies.join('; ')); + expect(freshToken.status).toBe(200); + expect(freshToken.body.csrfToken).not.toBe(oldToken.body.csrfToken); + const accepted = await request(app).post('/api/settings/recovery-email') + .set('Cookie', [...newAuth, ...cookiePairs(freshToken.headers['set-cookie'])].join('; ')) + .set('x-csrf-token', freshToken.body.csrfToken) + .send({ recoveryEmail: 'fresh@test.dev' }); + expect(accepted.status).toBe(200); + }); + + test('an attacker HTML form cannot change an existing recovery email', async () => { + const agent = request.agent(app); + const registration = await agent.post('/api/auth/register').send({ + name: 'Victim', email: `form${Date.now()}@test.dev`, password: 'secret123' + }); + expect(registration.status).toBe(201); + const token = await agent.get('/api/csrf-token'); + expect(token.status).toBe(200); + const saved = await agent.post('/api/settings/recovery-email') + .set('x-csrf-token', token.body.csrfToken).send({ recoveryEmail: 'legit@user.com' }); + expect(saved.status).toBe(200); + const forged = await agent.post('/api/settings/recovery-email') + .set('Origin', 'http://localhost:1337').type('form') + .send({ recoveryEmail: 'attacker@evil.com' }); + expect(forged.status).toBe(403); + const settings = await agent.get('/api/settings'); + expect(settings.status).toBe(200); + expect(settings.body.settings.recoveryEmail).toBe('legit@user.com'); + }); + + test('a logged-in user can update their own recovery email (the happy path)', async () => { + const authCookies = await registerUser(); + + // The real client fetches a CSRF token first. The vulnerable app has no such + // endpoint (404) — tolerate that so this control test passes in both projects. + let cookies = [...authCookies]; + const headers = {}; + const tokenRes = await request(app).get('/api/csrf-token').set('Cookie', cookies.join('; ')); + if (tokenRes.status === 200) { + headers['x-csrf-token'] = tokenRes.body.csrfToken; + cookies = [...cookies, ...cookiePairs(tokenRes.headers['set-cookie'])]; + } + + const res = await request(app) + .post('/api/settings/recovery-email') + .set('Cookie', cookies.join('; ')) + .set(headers) + .send({ recoveryEmail: 'legit@user.com' }); + expect(res.status).toBe(200); + + const check = await request(app).get('/api/settings').set('Cookie', authCookies.join('; ')); + expect(check.status).toBe(200); + expect(check.body.settings.recoveryEmail).toBe('legit@user.com'); + }); + + // The core CSRF test. A forged cross-site request carries the victim's auth + // cookie (the browser sends it automatically) but NO anti-CSRF token. A secure + // server must reject it; a vulnerable one performs the state change. + test('a forged cross-site request with no CSRF token is rejected', async () => { + const authCookies = await registerUser(); + + const forged = await request(app) + .post('/api/settings/recovery-email') + .set('Cookie', authCookies.join('; ')) // only the auth cookie — as in a real CSRF + .set('Origin', 'http://attacker.evil') // request originates off-site + .send({ recoveryEmail: 'attacker@evil.com' }); + + // Secure behavior: refuse the request for lack of a valid CSRF token. + expect(forged.status).toBe(403); + + // And the victim's recovery email must be untouched. + const check = await request(app).get('/api/settings').set('Cookie', authCookies.join('; ')); + expect(check.status).toBe(200); + expect(check.body.settings.recoveryEmail).not.toBe('attacker@evil.com'); + }); +});