From bf5ed16d04207eedcacd3403f651666fb3334560 Mon Sep 17 00:00:00 2001 From: adamaelropy Date: Wed, 11 Nov 2026 16:42:16 +0200 Subject: [PATCH] feat: implement CSRF protection and related middleware, update API for secure state-changing requests --- .github/workflows/ci.yaml | 24 ++++ .gitignore | 2 - .vscode/tasks.json | 10 +- babel.config.cjs | 6 + client/src/api.js | 113 ++++++++++++++++- jest.config.cjs | 24 ++++ package-lock.json | 10 ++ server/package.json | 1 + server/src/app.js | 41 ++++-- server/src/controllers/authController.js | 132 +++++++++++++++----- server/src/controllers/settingController.js | 6 +- server/src/middleware/auth.js | 25 ++-- server/src/middleware/csrf.js | 46 +++++++ server/src/routes/settings.js | 6 +- tests/client/csrf.test.js | 40 ++++++ tests/server/csrf.test.js | 85 +++++++++++++ 16 files changed, 509 insertions(+), 62 deletions(-) create mode 100644 .github/workflows/ci.yaml create mode 100644 babel.config.cjs create mode 100644 jest.config.cjs create mode 100644 server/src/middleware/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/.gitignore b/.gitignore index 1c45a7e..227c9f2 100644 --- a/.gitignore +++ b/.gitignore @@ -16,8 +16,6 @@ npm-debug.log* yarn-debug.log* yarn-error.log* -CLAUDE.md -AGENTS.md # OS and Editor specific files .DS_Store 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/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..1d54b41 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -1,9 +1,110 @@ -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 -}) + withCredentials: true, +}); + +const SAFE_METHODS = ['get', 'head', 'options']; + +const CSRF_EXEMPT_ROUTES = [ + '/auth/login', + '/auth/register', +]; + +const AUTH_ROUTES = [ + ...CSRF_EXEMPT_ROUTES, + '/auth/logout', +]; + +let csrfToken = null; +let pending = null; + +const getUrl = (config) => config.url || ''; + +const isMutating = (config) => + !SAFE_METHODS.includes( + (config.method || 'get').toLowerCase() + ); + +const matchesRoute = (config, routes) => + routes.some(route => { + const url = getUrl(config).split('?')[0]; + return url === route || url.endsWith(route); + }); + +const isCsrfExempt = (config) => + matchesRoute(config, CSRF_EXEMPT_ROUTES); + +const isAuthRoute = (config) => + matchesRoute(config, AUTH_ROUTES); + +export function clearCsrfToken() { + csrfToken = null; +} + +async function getCsrfToken() { + if (csrfToken) return csrfToken; + + if (!pending) { + pending = api.get('/csrf-token') + .then(response => { + csrfToken = response.data.csrfToken; + return csrfToken; + }) + .finally(() => { + pending = null; + }); + } + + return pending; +} + +// Attach CSRF token to state-changing requests. +api.interceptors.request.use(async config => { + if (isMutating(config) && !isCsrfExempt(config)) { + const token = await getCsrfToken(); + + if (typeof config.headers.set === 'function') { + config.headers.set('x-csrf-token', token); + } else { + config.headers['x-csrf-token'] = token; + } + } + + return config; +}); + +// Clear cached token after authentication changes. +api.interceptors.response.use( + response => { + if (isAuthRoute(response.config)) { + clearCsrfToken(); + } + + return response; + }, + + async error => { + const config = error.config; + + const csrfRejected = + error.response?.status === 403 && + /csrf/i.test(error.response?.data?.message || ''); + + if ( + csrfRejected && + config && + isMutating(config) && + !config._csrfRetried + ) { + config._csrfRetried = true; + clearCsrfToken(); + + return api.request(config); + } + + 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..dabde0c 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.1.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..a1b4048 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.1.0", "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..e4087b0 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -1,26 +1,44 @@ + 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 { + 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, +})); + 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 })); +// Health check +app.get('/api/health', (req, res) => { + res.json({ ok: true }); +}); + +// CSRF token endpoint +app.get('/api/csrf-token', csrfTokenHandler); + +// Protect state-changing requests. +app.use(csrfProtection); +// API routes app.use('/api/auth', authRoutes); app.use('/api/items', itemRoutes); app.use('/api/users', userRoutes); @@ -33,8 +51,17 @@ app.use((req, res) => { // Error handler app.use((err, req, res, next) => { + 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' }); + + res.status(err.status || 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..1d1daeb 100644 --- a/server/src/controllers/authController.js +++ b/server/src/controllers/authController.js @@ -1,88 +1,162 @@ + import jwt from 'jsonwebtoken'; import bcrypt from 'bcryptjs'; import Joi from 'joi'; import { User } from '../models/User.js'; -// How long the auth cookie lives, in ms (mirrors JWT_EXPIRES_IN's default of 7d). const COOKIE_MAX_AGE = 7 * 24 * 60 * 60 * 1000; -// The session token is stored in an httpOnly cookie so client JS can never read -// it (good against XSS token theft) — but the browser sends it automatically, -// which is the precondition for CSRF. function setAuthCookie(res, token) { res.cookie('token', token, { httpOnly: true, sameSite: 'lax', - secure: false, // true in production (HTTPS only) - maxAge: COOKIE_MAX_AGE + secure: process.env.NODE_ENV === 'production', + maxAge: COOKIE_MAX_AGE, + path: '/', }); } const registerSchema = Joi.object({ name: Joi.string().min(2).max(60).required(), email: Joi.string().email().required(), - password: Joi.string().min(6).required() + password: Joi.string().min(6).required(), }); // POST /api/auth/register export async function register(req, res, next) { try { const { value, error } = registerSchema.validate(req.body); - if (error) return res.status(400).json({ message: error.message }); - const existing = await User.findOne({ email: value.email }); - if (existing) return res.status(409).json({ message: 'Email already used' }); + if (error) { + return res.status(400).json({ + message: error.message, + }); + } + + const existing = await User.findOne({ + email: value.email, + }); + + if (existing) { + return res.status(409).json({ + message: 'Email already used', + }); + } const password = await bcrypt.hash(value.password, 10); - const user = await User.create({ name: value.name, email: value.email, password }); + + const user = await User.create({ + name: value.name, + email: value.email, + password, + }); + const token = signToken(user); + setAuthCookie(res, token); - res.status(201).json({ user: publicUser(user) }); - } catch (err) { next(err); } + + return res.status(201).json({ + user: publicUser(user), + }); + } catch (error) { + next(error); + } } const loginSchema = Joi.object({ email: Joi.string().email().required(), - password: Joi.string().required() + password: Joi.string().required(), }); // POST /api/auth/login export async function login(req, res, next) { try { const { value, error } = loginSchema.validate(req.body); - if (error) return res.status(400).json({ message: error.message }); - const user = await User.findOne({ email: value.email }); - if (!user) return res.status(401).json({ message: 'Invalid credentials' }); + if (error) { + return res.status(400).json({ + message: error.message, + }); + } + + const user = await User.findOne({ + email: value.email, + }); + + if (!user) { + return res.status(401).json({ + message: 'Invalid credentials', + }); + } + + const passwordMatches = await user.comparePassword( + value.password + ); - const ok = await user.comparePassword(value.password); - if (!ok) return res.status(401).json({ message: 'Invalid credentials' }); + if (!passwordMatches) { + return res.status(401).json({ + message: 'Invalid credentials', + }); + } const token = signToken(user); + setAuthCookie(res, token); - res.json({ user: publicUser(user) }); - } catch (err) { next(err); } + + return res.json({ + user: publicUser(user), + }); + } catch (error) { + next(error); + } } // POST /api/auth/logout export async function logout(req, res) { - res.clearCookie('token'); - res.json({ ok: true }); + res.clearCookie('token', { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/', + }); + + return res.json({ + ok: true, + }); } // GET /api/auth/me export async function me(req, res, next) { try { const user = await User.findById(req.user.id).lean(); - res.json({ user: user && publicUser(user) }); - } catch (err) { next(err); } + + return res.json({ + user: user ? publicUser(user) : null, + }); + } catch (error) { + next(error); + } } 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' }); + const payload = { + id: user._id.toString(), + name: user.name, + }; + + return jwt.sign( + payload, + process.env.JWT_SECRET, + { + expiresIn: process.env.JWT_EXPIRES_IN || '7d', + } + ); } -function publicUser(u) { - return { id: u._id?.toString() || u.id, name: u.name, email: u.email }; +function publicUser(user) { + return { + id: user._id?.toString() || user.id, + name: user.name, + email: user.email, + }; } diff --git a/server/src/controllers/settingController.js b/server/src/controllers/settingController.js index e30276f..2efc82b 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. +// A state-changing request: by the time it reaches here, the app-wide CSRF +// middleware has already verified the `x-csrf-token` header, so a forged +// cross-site request (auth cookie only, no token) never gets this far. export async function updateRecoveryEmail(req, res, next) { try { const { value, error } = recoveryEmailSchema.validate({ recoveryEmail: req.body.recoveryEmail }); diff --git a/server/src/middleware/auth.js b/server/src/middleware/auth.js index 1bad39f..67eb03c 100644 --- a/server/src/middleware/auth.js +++ b/server/src/middleware/auth.js @@ -1,17 +1,28 @@ + import jwt from 'jsonwebtoken'; export function requireAuth(req, res, next) { - // The JWT now rides in an httpOnly cookie instead of the Authorization header. - // The browser attaches it automatically on every request to this origin — - // which is exactly what makes cross-site request forgery (CSRF) possible. + // Read the JWT from the httpOnly authentication cookie. const token = req.cookies?.token; - if (!token) return res.status(401).json({ message: 'Missing token' }); + + if (!token) { + return res.status(401).json({ + message: 'Missing token', + }); + } try { - const payload = jwt.verify(token, process.env.JWT_SECRET); + const payload = jwt.verify( + token, + process.env.JWT_SECRET + ); + req.user = payload; + return next(); - } catch (err) { - return res.status(401).json({ message: 'Invalid or expired token' }); + } catch (error) { + return res.status(401).json({ + message: 'Invalid or expired token', + }); } } diff --git a/server/src/middleware/csrf.js b/server/src/middleware/csrf.js new file mode 100644 index 0000000..3e508ae --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,46 @@ + +import { doubleCsrf } from 'csrf-csrf'; + +const { + doubleCsrfProtection, + generateCsrfToken, +} = doubleCsrf({ + getSecret: () => { + if (!process.env.CSRF_SECRET) { + throw new Error('CSRF_SECRET is missing from environment variables'); + } + + return process.env.CSRF_SECRET; + }, + + getSessionIdentifier: (req) => + req.cookies?.token || 'anonymous', + + cookieName: 'csrf-token', + + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/', + }, + + getCsrfTokenFromRequest: (req) => + req.headers['x-csrf-token'], + + skipCsrfProtection: (req) => + req.path === '/api/auth/login' || + req.path === '/api/auth/register', +}); + +export function csrfTokenHandler(req, res, next) { + try { + const csrfToken = generateCsrfToken(req, res); + + return res.json({ csrfToken }); + } catch (error) { + next(error); + } +} + +export const csrfProtection = doubleCsrfProtection; diff --git a/server/src/routes/settings.js b/server/src/routes/settings.js index 2e8f894..864fa2d 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 additionally +// protected against CSRF by the app-wide `csrfProtection` middleware (app.js), +// which rejects any POST lacking a valid `x-csrf-token` header with 403. router.get('/', requireAuth, getSettings); router.post('/recovery-email', requireAuth, updateRecoveryEmail); 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'); + }); +});