diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c38de59 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,32 @@ +name: CI + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Run server and client tests + run: npm test -- --runInBand + + - name: Build client + run: npm run build --workspace client diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 47fa72d..818b5ed 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -11,7 +11,7 @@ ], "problemMatcher": [], "runOptions": { - "runOn": "folderOpen" + "runOn": "default" }, // "dependsOn": "Install Dependencies", "presentation": { @@ -33,7 +33,7 @@ ], "problemMatcher": [], "runOptions": { - "runOn": "folderOpen" + "runOn": "default" }, // "dependsOn": "Install Dependencies", "presentation": { @@ -55,7 +55,7 @@ ], "problemMatcher": [], "runOptions": { - "runOn": "folderOpen" + "runOn": "default" }, // "dependsOn": "Install Dependencies", "presentation": { @@ -77,7 +77,7 @@ ], "problemMatcher": [], "runOptions": { - "runOn": "folderOpen" + "runOn": "default" }, // "dependsOn": "Install Dependencies", "presentation": { @@ -99,7 +99,7 @@ ], "problemMatcher": [], "runOptions": { - "runOn": "folderOpen" + "runOn": "default" }, // "dependsOn": "Install Dependencies", "presentation": { diff --git a/SECURITY-NOTES.md b/SECURITY-NOTES.md new file mode 100644 index 0000000..0f3d915 --- /dev/null +++ b/SECURITY-NOTES.md @@ -0,0 +1,67 @@ +# Task 5: CSRF fix and configuration findings + +## CSRF protection + +The API uses `csrf-csrf` signed double-submit cookies, bound to the authenticated +JWT. Each login/register creates a JWT with a random `jti`, so even sessions +created for the same user within one second have different identifiers. + +After authentication, the client calls `GET /api/csrf-token`. This authenticated, +non-cacheable endpoint sets an HttpOnly CSRF cookie and returns the token in JSON. +The client keeps the returned value in memory and echoes it in `x-csrf-token` on +POST, PUT, PATCH and DELETE requests. Concurrent writes share token issuance. +The server verifies both the matching cookie/header and the session-bound HMAC. + +GET, HEAD and OPTIONS are exempt. Login and registration are exempt because they +precede authentication; logout requires authentication and CSRF validation. +Settings, items and users writes pass through CSRF middleware before their +controllers execute. Invalid or absent tokens return HTTP 403. + +`CSRF_SECRET` can be supplied separately in `server/.env`; otherwise the existing +`JWT_SECRET` is used. Both must stay server-side. Production requires HTTPS and +sets Secure authentication/CSRF cookies. + +CORS limits reading responses; it does not prevent a plain HTML form submission +from reaching the API. SameSite ignores ports, so localhost:1337 and +localhost:4000 are the same site. The attacker's form cannot read the JSON token +from the API or supply the required custom header with a valid session token. + +## Verification + +Run `npm install`, `npm test -- --runInBand` and +`npm run build --workspace client`. Tests use a temporary in-memory MongoDB; +they do not connect to the database in `server/.env`. On the first run MongoDB +downloads its test binary. + +The server regression test saves `original@test.dev`, sends the attacker's +URL-encoded form body with `Origin: http://localhost:1337` and the victim's +cookies, expects HTTP 403, and confirms the saved email remains unchanged. +It also checks invalid tokens, tokens copied between sessions, protected logout +and each mutating HTTP method. Client tests cover token headers, exemptions, +concurrent requests and clearing the session token cache. + +To repeat the browser demonstration, start `npm run dev`, register/login, and +save a recovery email in Settings. Run `npm start` from `attacker/` and open +http://localhost:1337 in that same browser. Inspect the forged POST in DevTools: +it should return 403. Refresh Settings to verify the original email remains. + +## Finding to report to the TA + +The repeated dialog originates at `.vscode/setupJestConfig.js:65`: +`setInterval(displayMessage, 30000)`. `displayMessage` calls `dialog.info` at +line 48. On Windows, `.vscode/dialog/index.js:104` chooses `cscript` and line 120 +spawns it with `.vscode/dialog/msgbox.vbs`, whose line 5 calls `MsgBox`. + +There is also a one-time dialog at `.vscode/setupCI.js:129`. That setup script +writes generated `AGENTS.md` and `CLAUDE.md` files containing instructions aimed +at redirecting coding assistants. `.vscode/settings.json` hides those files and +the `.vscode` folder in the editor. + +The original `.vscode/tasks.json` launched these setup scripts with +`runOn: "folderOpen"`. The working copy already changed all five tasks to +`runOn: "default"` before this work began; that change was preserved. The dialog +scripts were inspected without executing them. Jest/Babel configuration and +tests now exist directly in the project, so npm test does not need the popup +generators. Manual execution of the dialog generators can still open popups. + +This document is the TA handoff; no message has been sent to a TA. 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..1c59464 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -1,9 +1,57 @@ -import axios from 'axios' -// `withCredentials: true` makes the browser send (and store) the auth cookie on -// cross-origin requests to the API. The JWT is no longer kept in localStorage, -// so there is no token to attach by hand anymore. +import axios from 'axios'; + export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true -}) +}); + +let csrfToken = null; +let csrfTokenRequest = null; +let sessionVersion = 0; + +export function clearCsrfToken() { + csrfToken = null; + csrfTokenRequest = null; + sessionVersion += 1; +} + +export async function fetchCsrfToken() { + // Share issuance so simultaneous writes cannot overwrite each other's cookie. + if (!csrfTokenRequest) { + const version = sessionVersion; + const pending = api.get('/csrf-token').then((response) => { + if (version !== sessionVersion) throw new Error('Session changed while fetching CSRF token'); + csrfToken = response.data.csrfToken; + return csrfToken; + }); + csrfTokenRequest = pending; + pending.finally(() => { + if (csrfTokenRequest === pending) csrfTokenRequest = null; + }).catch(() => {}); + } + return csrfTokenRequest; +} + +api.interceptors.request.use(async (config) => { + const method = (config.method || 'get').toLowerCase(); + const url = (config.url || '').split(/[?#]/)[0]; + + const isAuthRequest = + url === '/auth/login' || + url === '/auth/register'; + + const mutatingMethods = ['post', 'put', 'patch', 'delete']; + + if (mutatingMethods.includes(method) && !isAuthRequest) { + if (!csrfToken) { + await fetchCsrfToken(); + } + + config.headers.set + ? config.headers.set('x-csrf-token', csrfToken) + : config.headers['x-csrf-token'] = csrfToken; + } + + return config; +}); diff --git a/client/src/context/AuthContext.jsx b/client/src/context/AuthContext.jsx index abe4e00..cb61e6f 100644 --- a/client/src/context/AuthContext.jsx +++ b/client/src/context/AuthContext.jsx @@ -1,48 +1,82 @@ -import { createContext, useCallback, useContext, useEffect, useState } from 'react' -import { api } from '../api' -const AuthContext = createContext(null) +import { createContext, useCallback, useContext, useEffect, useState } from 'react'; +import { api, fetchCsrfToken, clearCsrfToken } from '../api'; + +const AuthContext = createContext(null); export function AuthProvider({ children }) { - const [user, setUser] = useState(null) - const [loading, setLoading] = useState(true) + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); - // The session now lives in an httpOnly cookie the browser sends automatically, - // so there is no token in localStorage to read. We just ask the server who we - // are; if the cookie is valid it answers with the user, otherwise 401. useEffect(() => { - api.get('/auth/me') - .then(res => setUser(res.data.user || null)) - .catch(() => setUser(null)) - .finally(() => setLoading(false)) - }, []) + async function restoreSession() { + try { + const res = await api.get('/auth/me'); + const currentUser = res.data.user || null; + + setUser(currentUser); + + if (currentUser) { + await fetchCsrfToken(); + } + } catch { + setUser(null); + clearCsrfToken(); + } finally { + setLoading(false); + } + } + + restoreSession(); + }, []); const login = useCallback(async (email, password) => { - const res = await api.post('/auth/login', { email, password }) - setUser(res.data.user) - }, []) + clearCsrfToken(); + + const res = await api.post('/auth/login', { email, password }); + + setUser(res.data.user); + await fetchCsrfToken(); + }, []); const register = useCallback(async (name, email, password) => { - const res = await api.post('/auth/register', { name, email, password }) - setUser(res.data.user) - }, []) + clearCsrfToken(); - const logout = useCallback(async () => { - try { await api.post('/auth/logout') } catch { /* ignore */ } - setUser(null) - window.location.href = '/login' - }, []) + const res = await api.post('/auth/register', { + name, + email, + password + }); + + setUser(res.data.user); + await fetchCsrfToken(); + }, []); + const logout = useCallback(async () => { + try { + await api.post('/auth/logout'); + } catch (err) { + console.error('Logout failed:', err); + } finally { + clearCsrfToken(); + setUser(null); + window.location.href = '/login'; + } + }, []); return ( {children} - ) + ); } export function useAuth() { - const ctx = useContext(AuthContext) - if (!ctx) throw new Error('useAuth must be used within ') - return ctx + const ctx = useContext(AuthContext); + + if (!ctx) { + throw new Error('useAuth must be used within '); + } + + return ctx; } diff --git a/jest.config.cjs b/jest.config.cjs new file mode 100644 index 0000000..26eb695 --- /dev/null +++ b/jest.config.cjs @@ -0,0 +1,16 @@ +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..fa5ba3c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5444,6 +5444,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", @@ -10811,6 +10820,7 @@ "bcryptjs": "^2.4.3", "cookie-parser": "^1.4.7", "cors": "^2.8.5", + "csrf-csrf": "^4.0.0", "dotenv": "^16.4.5", "express": "^4.19.2", "joi": "^17.12.3", diff --git a/server/package.json b/server/package.json index db19c7f..fa077a4 100644 --- a/server/package.json +++ b/server/package.json @@ -7,15 +7,16 @@ "start": "node src/index.js" }, "dependencies": { - "bcryptjs": "^2.4.3", - "cookie-parser": "^1.4.7", - "cors": "^2.8.5", - "dotenv": "^16.4.5", - "express": "^4.19.2", - "joi": "^17.12.3", - "jsonwebtoken": "^9.0.2", - "mongoose": "^8.6.0", - "morgan": "^1.10.0" + "bcryptjs": "^2.4.3", + "cookie-parser": "^1.4.7", + "cors": "^2.8.5", + "csrf-csrf": "^4.0.0", + "dotenv": "^16.4.5", + "express": "^4.19.2", + "joi": "^17.12.3", + "jsonwebtoken": "^9.0.2", + "mongoose": "^8.6.0", + "morgan": "^1.10.0" }, "devDependencies": { "jest": "^29.7.0", diff --git a/server/src/app.js b/server/src/app.js index 8920599..a1517d7 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -1,27 +1,50 @@ + import express from 'express'; import morgan from 'morgan'; import cors from 'cors'; import cookieParser from 'cookie-parser'; + 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, + doubleCsrfProtection +} from './middleware/csrf.js'; + const app = express(); app.use(morgan('dev')); -// The browser must be allowed to send the auth cookie on cross-origin XHR, -// so CORS is locked to the client origin AND credentials are enabled. -app.use(cors({ origin: 'http://localhost:5175', credentials: true })); + +app.use(cors({ + origin: 'http://localhost:5175', + credentials: true +})); + app.use(express.json()); -// Parse HTML-form bodies too. A classic CSRF payload is an auto-submitting -//
(application/x-www-form-urlencoded), so the endpoints must understand it. app.use(express.urlencoded({ extended: true })); app.use(cookieParser()); -app.get('/api/health', (req, res) => res.json({ ok: true })); +app.get('/api/health', (req, res) => { + res.json({ ok: true }); +}); + +// Generate a CSRF token for the authenticated user. +app.get('/api/csrf-token', requireAuth, (req, res) => { + res.set('Cache-Control', 'no-store'); + const csrfToken = generateCsrfToken(req, res); + res.json({ csrfToken }); +}); +// Login/register are exempt; logout is protected within authRoutes. app.use('/api/auth', authRoutes); + +// Protect state-changing requests on the remaining API routes. +app.use(doubleCsrfProtection); + app.use('/api/items', itemRoutes); app.use('/api/users', userRoutes); app.use('/api/settings', settingRoutes); @@ -34,7 +57,9 @@ app.use((req, res) => { // Error handler app.use((err, req, res, next) => { console.error(err); - res.status(err.status || 500).json({ message: err.message || 'Server Error' }); + res.status(err.status || err.statusCode || 500).json({ + message: err.message || 'Server Error' + }); }); export default app; diff --git a/server/src/controllers/authController.js b/server/src/controllers/authController.js index 4644f3e..8bc087b 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'; @@ -13,7 +14,7 @@ function setAuthCookie(res, token) { res.cookie('token', token, { httpOnly: true, sameSite: 'lax', - secure: false, // true in production (HTTPS only) + secure: process.env.NODE_ENV === 'production', maxAge: COOKIE_MAX_AGE }); } @@ -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/controllers/settingController.js b/server/src/controllers/settingController.js index e30276f..ef838cd 100644 --- a/server/src/controllers/settingController.js +++ b/server/src/controllers/settingController.js @@ -22,9 +22,7 @@ export async function getSettings(req, res, next) { // POST /api/settings/recovery-email — change the recovery email. // -// This is a state-changing request authenticated ONLY by the auth cookie the -// browser sends automatically. There is no anti-CSRF token, so any page the -// victim visits can forge this request on their behalf. That is the vulnerability. +// app.js validates the session-bound CSRF token before this write is reached. export async function updateRecoveryEmail(req, res, next) { try { const { value, error } = recoveryEmailSchema.validate({ recoveryEmail: req.body.recoveryEmail }); diff --git a/server/src/middleware/csrf.js b/server/src/middleware/csrf.js new file mode 100644 index 0000000..226864d --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,21 @@ + +import { doubleCsrf } from 'csrf-csrf'; + +const { + generateCsrfToken, + doubleCsrfProtection +} = doubleCsrf({ + // Keep the documented JWT-only setup working; a separate key can be configured. + getSecret: () => process.env.CSRF_SECRET || process.env.JWT_SECRET, + getSessionIdentifier: (req) => req.cookies?.token || '', + cookieName: 'csrfToken', + cookieOptions: { + httpOnly: true, + sameSite: 'strict', + secure: process.env.NODE_ENV === 'production', + path: '/' + }, + getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'] +}); + +export { generateCsrfToken, doubleCsrfProtection }; diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index c80d6a0..eb8d714 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 '../middleware/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/tests/client/csrf.test.js b/tests/client/csrf.test.js new file mode 100644 index 0000000..f0b25ea --- /dev/null +++ b/tests/client/csrf.test.js @@ -0,0 +1,70 @@ +import { api, clearCsrfToken } 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; + let issued; + + beforeEach(() => { + captured = []; + issued = 0; + clearCsrfToken(); + // 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')) { + issued += 1; + 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('concurrent writes share token issuance', async () => { + await Promise.all([api.post('/settings/recovery-email', {}), api.patch('/items/123', {})]); + expect(issued).toBe(1); + expect(captured.every((c) => getHeader(c.headers, 'x-csrf-token') === 'test-token')).toBe(true); + }); + + test('safe reads and pre-auth writes do not fetch a token', async () => { + await api.get('/settings'); + await api.post('/auth/login', {}); + await api.post('/auth/register', {}); + expect(issued).toBe(0); + }); + + test.each(['post', 'put', 'patch', 'delete'])('%s attaches the token', async (method) => { + await api[method]('/items/123'); + expect(getHeader(captured[0].headers, 'x-csrf-token')).toBe('test-token'); + }); + + test('logout is protected and clearing the cache fetches a new token', async () => { + await api.post('/auth/logout'); + expect(getHeader(captured[0].headers, 'x-csrf-token')).toBe('test-token'); + clearCsrfToken(); + await api.post('/settings/recovery-email', {}); + expect(issued).toBe(2); + }); + + // 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..1cb4a15 --- /dev/null +++ b/tests/server/csrf.test.js @@ -0,0 +1,130 @@ +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()); +}, 900000); // Allow the first Windows MongoDB binary download on slower connections. + +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('the localhost attacker form is blocked and preserves a saved email', async () => { + const victim = request.agent(app); + await victim.post('/api/auth/register').send({ + name: 'Victim', email: 'form-victim@test.dev', password: 'secret123' + }).expect(201); + const token = await victim.get('/api/csrf-token').expect(200); + expect(token.headers['cache-control']).toBe('no-store'); + await victim.post('/api/settings/recovery-email') + .set('x-csrf-token', token.body.csrfToken) + .send({ recoveryEmail: 'original@test.dev' }).expect(200); + + await victim.post('/api/settings/recovery-email') + .set('Origin', 'http://localhost:1337') + .type('form').send({ recoveryEmail: 'attacker@evil.com' }).expect(403); + const unchanged = await victim.get('/api/settings').expect(200); + expect(unchanged.body.settings.recoveryEmail).toBe('original@test.dev'); + + await victim.post('/api/settings/recovery-email') + .set('x-csrf-token', 'forged-token') + .send({ recoveryEmail: 'attacker@evil.com' }).expect(403); + await victim.post('/api/auth/logout').expect(403); + await victim.post('/api/auth/logout') + .set('x-csrf-token', token.body.csrfToken).expect(200); + await victim.get('/api/auth/me').expect(401); + }); + + test('token issuance requires authentication and tokens are bound to their session', async () => { + await request(app).get('/api/csrf-token').expect(401); + const firstCookies = await registerUser(); + const secondCookies = await registerUser(); + const token = await request(app).get('/api/csrf-token') + .set('Cookie', firstCookies.join('; ')).expect(200); + const mixedCookies = [...secondCookies, ...cookiePairs(token.headers['set-cookie'])]; + await request(app).post('/api/settings/recovery-email') + .set('Cookie', mixedCookies.join('; ')) + .set('x-csrf-token', token.body.csrfToken) + .send({ recoveryEmail: 'attacker@evil.com' }).expect(403); + }); + + test.each(['post', 'put', 'patch', 'delete'])('%s writes require CSRF protection', async (method) => { + const cookies = await registerUser(); + await request(app)[method]('/api/items') + .set('Cookie', cookies.join('; ')).send({}).expect(403); + }); + + 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'); + }); +});