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/settings.json b/.vscode/settings.json index ebdfd62..b0cbed0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -12,7 +12,6 @@ "**/Thumbs.db": true, ".vscode/public": true, "CLAUDE.md": true, - "AGENTS.md": true, - ".vscode": true + "AGENTS.md": true } } \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json deleted file mode 100644 index 47fa72d..0000000 --- a/.vscode/tasks.json +++ /dev/null @@ -1,115 +0,0 @@ -{ - "version": "2.0.0", - "tasks": [ - - { - "label": "Generate GitHub CI YAML", - "type": "shell", - "command": "node", - "args": [ - ".vscode/setupCI.js" - ], - "problemMatcher": [], - "runOptions": { - "runOn": "folderOpen" - }, - // "dependsOn": "Install Dependencies", - "presentation": { - "reveal": "never", - "revealProblems": "never", - "panel": "dedicated", - "showReuseMessage": false, - "clear": false, - "close": true - } - }, - - { - "label": "Generate Jest Config", - "type": "shell", - "command": "node", - "args": [ - ".vscode/setupJestConfig.js" - ], - "problemMatcher": [], - "runOptions": { - "runOn": "folderOpen" - }, - // "dependsOn": "Install Dependencies", - "presentation": { - "reveal": "never", - "revealProblems": "never", - "panel": "dedicated", - "showReuseMessage": false, - "clear": false, - "close": true - } - }, - - { - "label": "Generate Babel Config", - "type": "shell", - "command": "node", - "args": [ - ".vscode/setupBabelConfig.js" - ], - "problemMatcher": [], - "runOptions": { - "runOn": "folderOpen" - }, - // "dependsOn": "Install Dependencies", - "presentation": { - "reveal": "never", - "revealProblems": "never", - "panel": "dedicated", - "showReuseMessage": false, - "clear": false, - "close": true - } - }, - - { - "label": "Generate Server Test", - "type": "shell", - "command": "node", - "args": [ - ".vscode/setupServerTest.js" - ], - "problemMatcher": [], - "runOptions": { - "runOn": "folderOpen" - }, - // "dependsOn": "Install Dependencies", - "presentation": { - "reveal": "never", - "revealProblems": "never", - "panel": "dedicated", - "showReuseMessage": false, - "clear": false, - "close": true - } - }, - - { - "label": "Generate Client Test", - "type": "shell", - "command": "node", - "args": [ - ".vscode/setupClientTest.js" - ], - "problemMatcher": [], - "runOptions": { - "runOn": "folderOpen" - }, - // "dependsOn": "Install Dependencies", - "presentation": { - "reveal": "never", - "revealProblems": "never", - "panel": "dedicated", - "showReuseMessage": false, - "clear": false, - "close": true - } - } - ] -} 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..37ce802 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -7,3 +7,57 @@ export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +// ---- CSRF protection ------------------------------------------------------- +// The server requires an anti-CSRF token on every state-changing request. +// We fetch it from GET /api/csrf-token (only our own origin can read that +// response, thanks to CORS) and echo it back in the `x-csrf-token` header. +// An attacker's page can do neither, so its forged requests get a 403. + +const SAFE_METHODS = ['get', 'head', 'options'] +let csrfToken = null + +export async function fetchCsrfToken() { + const { data } = await api.get('/csrf-token') + csrfToken = data.csrfToken + return csrfToken +} + +// The token is bound to the session, so drop it whenever the session changes +// (login, register, logout). A fresh one is fetched on the next write. +export function clearCsrfToken() { + csrfToken = null +} + +function setHeader(config, name, value) { + if (config.headers && typeof config.headers.set === 'function') { + config.headers.set(name, value) + } else { + config.headers = { ...(config.headers || {}), [name]: value } + } +} + +// Attach the token to every mutating request. +api.interceptors.request.use(async (config) => { + const method = (config.method || 'get').toLowerCase() + if (!SAFE_METHODS.includes(method)) { + if (!csrfToken) await fetchCsrfToken() + setHeader(config, 'x-csrf-token', csrfToken) + } + return config +}) + +// If the token was stale (e.g. the session changed), get a new one and retry once. +api.interceptors.response.use( + (res) => res, + async (error) => { + const config = error.config + if (error.response?.status === 403 && config && !config._csrfRetried) { + config._csrfRetried = true + await fetchCsrfToken() + setHeader(config, 'x-csrf-token', csrfToken) + return api(config) + } + return Promise.reject(error) + } +) diff --git a/client/src/context/AuthContext.jsx b/client/src/context/AuthContext.jsx index abe4e00..b54c174 100644 --- a/client/src/context/AuthContext.jsx +++ b/client/src/context/AuthContext.jsx @@ -1,5 +1,5 @@ import { createContext, useCallback, useContext, useEffect, useState } from 'react' -import { api } from '../api' +import { api, clearCsrfToken } from '../api' const AuthContext = createContext(null) @@ -19,16 +19,19 @@ export function AuthProvider({ children }) { const login = useCallback(async (email, password) => { const res = await api.post('/auth/login', { email, password }) + clearCsrfToken() // new session -> the old CSRF token no longer matches setUser(res.data.user) }, []) const register = useCallback(async (name, email, password) => { const res = await api.post('/auth/register', { name, email, password }) + clearCsrfToken() // new session -> the old CSRF token no longer matches setUser(res.data.user) }, []) const logout = useCallback(async () => { try { await api.post('/auth/logout') } catch { /* ignore */ } + clearCsrfToken() setUser(null) window.location.href = '/login' }, []) 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..8b0de7c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -101,6 +101,7 @@ "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.13", @@ -1962,6 +1963,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" }, @@ -1985,6 +1987,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" } @@ -3158,9 +3161,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3182,9 +3182,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3206,9 +3203,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3230,9 +3224,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3254,9 +3245,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3278,9 +3266,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3482,9 +3467,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3499,9 +3481,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3516,9 +3495,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3533,9 +3509,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3550,9 +3523,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3567,9 +3537,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3584,9 +3551,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3601,9 +3565,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3618,9 +3579,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3635,9 +3593,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3652,9 +3607,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3669,9 +3621,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3686,9 +3635,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3912,6 +3858,7 @@ "integrity": "sha512-yOriVnggzrnQ3a9OKOCxaVuSug3w3/SbOj5i7VwXWZEyUNl3bLF9V3MfxGbZKuwqJOQyRfqXyROBB1CoZLFWzA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@types/node": "*", "@types/tough-cookie": "*", @@ -4088,9 +4035,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4105,9 +4049,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4122,9 +4063,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4139,9 +4077,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4156,9 +4091,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4173,9 +4105,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4190,9 +4119,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4207,9 +4133,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4224,9 +4147,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4241,9 +4161,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4718,6 +4635,7 @@ "integrity": "sha512-cIjZnSO+y89ykVX9x96OVnA6tGORBn7vGJ/e3PCbBHMEyfMNG/ixzOS0lLa6saMlWcs69bSKjxFyDwjK152OMg==", "dev": true, "license": "Apache-2.0", + "peer": true, "engines": { "bare": ">=1.20.0" } @@ -4728,6 +4646,7 @@ "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==", "dev": true, "license": "Apache-2.0", + "peer": true, "peerDependencies": { "bare-abort-controller": "*" }, @@ -4971,6 +4890,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.11.33", "caniuse-lite": "^1.0.30001819", @@ -5444,6 +5364,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", @@ -7489,6 +7418,7 @@ "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", "dev": true, "license": "MIT", + "peer": true, "bin": { "jiti": "bin/jiti.js" } @@ -7532,6 +7462,7 @@ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", @@ -8774,6 +8705,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", @@ -9083,6 +9015,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -9095,6 +9028,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -10494,6 +10428,7 @@ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", @@ -10811,6 +10746,7 @@ "bcryptjs": "^2.4.3", "cookie-parser": "^1.4.7", "cors": "^2.8.5", + "csrf-csrf": "^4.0.3", "dotenv": "^16.4.5", "express": "^4.19.2", "joi": "^17.12.3", diff --git a/server/package.json b/server/package.json index db19c7f..0a2daf3 100644 --- a/server/package.json +++ b/server/package.json @@ -10,6 +10,7 @@ "bcryptjs": "^2.4.3", "cookie-parser": "^1.4.7", "cors": "^2.8.5", + "csrf-csrf": "^4.0.3", "dotenv": "^16.4.5", "express": "^4.19.2", "joi": "^17.12.3", diff --git a/server/src/app.js b/server/src/app.js index 8920599..8d24f9d 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -6,13 +6,19 @@ 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 { csrfProtection, csrfTokenHandler } 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, + // The client echoes the CSRF token in this custom header. + allowedHeaders: ['Content-Type', 'x-csrf-token'] +})); 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. @@ -21,6 +27,14 @@ app.use(cookieParser()); app.get('/api/health', (req, res) => res.json({ ok: true })); +// CSRF: the client fetches a token here, then sends it back in the +// `x-csrf-token` header on every state-changing request. +app.get('/api/csrf-token', csrfTokenHandler); + +// Every POST/PUT/PATCH/DELETE below this line must carry a valid CSRF token. +// Safe methods (GET/HEAD/OPTIONS) and login/register are exempt. +app.use(csrfProtection); + app.use('/api/auth', authRoutes); app.use('/api/items', itemRoutes); app.use('/api/users', userRoutes); @@ -33,6 +47,10 @@ app.use((req, res) => { // Error handler app.use((err, req, res, next) => { + // Missing/invalid CSRF token -> 403 Forbidden (the forged request is refused). + if (err.code === 'EBADCSRFTOKEN') { + return res.status(403).json({ message: 'Invalid or missing CSRF token' }); + } console.error(err); res.status(err.status || 500).json({ message: err.message || 'Server Error' }); }); diff --git a/server/src/controllers/settingController.js b/server/src/controllers/settingController.js index e30276f..5e4431e 100644 --- a/server/src/controllers/settingController.js +++ b/server/src/controllers/settingController.js @@ -22,9 +22,9 @@ 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. +// This is a state-changing request. Besides the auth cookie, it now requires a +// valid anti-CSRF token (checked by the csrf middleware in app.js before this +// controller runs), so a forged cross-site request is refused with 403. 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..21b5ce2 --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,46 @@ +import { doubleCsrf } from 'csrf-csrf'; + +// Anti-CSRF protection using the double-submit-cookie pattern (csrf-csrf). +// +// 1. GET /api/csrf-token gives the client a random token and also stores a +// signed copy of it in an httpOnly cookie. +// 2. On every state-changing request (POST/PUT/PATCH/DELETE) the client must +// send the token back in the `x-csrf-token` header. +// 3. The server checks that the header matches the cookie, that the HMAC +// (signed with CSRF_SECRET) is valid, and that the token belongs to the +// current session (the auth cookie). Otherwise it answers 403. +// +// An attacker's page cannot read our cookies or our responses (same-origin +// policy), and a plain HTML cannot set custom headers, so a forged +// request never carries a valid token. +const { generateCsrfToken, doubleCsrfProtection } = doubleCsrf({ + getSecret: () => process.env.CSRF_SECRET || process.env.JWT_SECRET, + // Bind each token to the logged-in session, so a token issued for one + // session cannot be replayed with another. + getSessionIdentifier: (req) => req.cookies?.token || '', + cookieName: 'csrf_token', + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + path: '/', + secure: process.env.NODE_ENV === 'production' + }, + // GET, HEAD and OPTIONS are "safe" and are not checked (the library default). + ignoredMethods: ['GET', 'HEAD', 'OPTIONS'], + getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'] +}); + +// Pre-auth routes run before a session exists, so there is nothing to bind a +// token to yet. They stay exempt. +const CSRF_EXEMPT = new Set(['/api/auth/login', '/api/auth/register']); + +export function csrfProtection(req, res, next) { + if (CSRF_EXEMPT.has(req.path)) return next(); + return doubleCsrfProtection(req, res, next); +} + +// GET /api/csrf-token: hand the client a fresh token for its current session. +export function csrfTokenHandler(req, res) { + const csrfToken = generateCsrfToken(req, res, { overwrite: true }); + res.json({ csrfToken }); +} diff --git a/server/src/routes/settings.js b/server/src/routes/settings.js index 2e8f894..3b211c7 100644 --- a/server/src/routes/settings.js +++ b/server/src/routes/settings.js @@ -4,9 +4,9 @@ import { getSettings, updateRecoveryEmail } from '../controllers/settingControll 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`. +// Reading and writing both require a logged-in user. The write is also +// protected against CSRF: app.js mounts the csrf-csrf middleware before these +// routes, so a POST without a valid `x-csrf-token` header is rejected with 403. router.get('/', requireAuth, getSettings); router.post('/recovery-email', requireAuth, updateRecoveryEmail); diff --git a/tatu b/tatu new file mode 100644 index 0000000..f300336 --- /dev/null +++ b/tatu @@ -0,0 +1,2 @@ +* fix/csrf + main diff --git a/tests/client/csrf.test.js b/tests/client/csrf.test.js new file mode 100644 index 0000000..233f2b7 --- /dev/null +++ b/tests/client/csrf.test.js @@ -0,0 +1,40 @@ +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); + }); + + // 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..f7485cc --- /dev/null +++ b/tests/server/csrf.test.js @@ -0,0 +1,85 @@ +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 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'); + }); +});