From e8c0ddf01c52ac30dc6e17654be75b3c0013f166 Mon Sep 17 00:00:00 2001 From: Reem Elmoghazy Date: Wed, 11 Nov 2026 15:29:32 +0200 Subject: [PATCH] Add CSRF protection with csrf-csrf and CI workflow --- .github/workflows/ci.yaml | 24 ++++++ babel.config.cjs | 6 ++ client/src/api.js | 67 ++++++++++++++++ jest.config.cjs | 24 ++++++ server/package.json | 1 + server/src/app.js | 12 +++ server/src/controllers/settingController.js | 6 +- server/src/middleware/csrf.js | 60 +++++++++++++++ server/src/routes/settings.js | 6 +- tests/client/csrf.test.js | 40 ++++++++++ tests/server/csrf.test.js | 85 +++++++++++++++++++++ 11 files changed, 325 insertions(+), 6 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..c5767e3 --- /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 --no-audit --no-fund + + - name: Run the test suite + run: npm test 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..5e7f4c6 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -7,3 +7,70 @@ export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +// ---- CSRF protection -------------------------------------------------------- +// The server requires an `x-csrf-token` header on every state-changing request. +// We fetch the token from GET /api/csrf-token (only our own origin can read that +// response, because of CORS) and echo it back on each write. The attacker's +// forged form can't do either, so its request is rejected with 403. + +const MUTATING_METHODS = ['post', 'put', 'patch', 'delete'] +// These run before a session exists, so the server doesn't check them. +const CSRF_EXEMPT = ['/auth/login', '/auth/register'] + +let csrfToken = null +let pending = null + +async function getCsrfToken() { + if (csrfToken) return csrfToken + if (!pending) { + pending = api.get('/csrf-token') + .then(res => { csrfToken = res.data.csrfToken; return csrfToken }) + .finally(() => { pending = null }) + } + return pending +} + +// The token is tied to the session, so throw it away whenever the session changes. +export function clearCsrfToken() { + csrfToken = null +} + +function isMutating(config) { + return MUTATING_METHODS.includes((config.method || 'get').toLowerCase()) +} + +function isExempt(config) { + return CSRF_EXEMPT.some(path => (config.url || '').includes(path)) +} + +api.interceptors.request.use(async (config) => { + if (isMutating(config) && !isExempt(config)) { + config.headers = config.headers || {} + 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 +}) + +api.interceptors.response.use( + (res) => { + // Logging in, registering or logging out starts a new session, so the + // old token is no longer valid. + if (isMutating(res.config) && /\/auth\/(login|register|logout)/.test(res.config.url || '')) { + clearCsrfToken() + } + return res + }, + async (error) => { + const config = error.config + // If the token was stale (e.g. the session changed), get a fresh one and retry once. + if (error.response?.status === 403 && config && isMutating(config) && !isExempt(config) && !config._csrfRetried) { + config._csrfRetried = true + clearCsrfToken() + return api(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/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..62b6589 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -6,6 +6,7 @@ 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, invalidCsrfTokenError } from './middleware/csrf.js'; const app = express(); @@ -21,6 +22,14 @@ app.use(cookieParser()); app.get('/api/health', (req, res) => res.json({ ok: true })); +// Hands the client a CSRF token for its current session. This is a GET, so the +// protection below lets it through. CORS stops other sites from reading the token. +app.get('/api/csrf-token', csrfTokenHandler); + +// Every state-changing request (POST/PUT/PATCH/DELETE) must carry a valid +// x-csrf-token header. Safe methods 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 +42,9 @@ app.use((req, res) => { // Error handler app.use((err, req, res, next) => { + if (err === invalidCsrfTokenError || 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..351d663 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: it requires the auth cookie AND a valid anti-CSRF +// token (checked by the csrf-csrf middleware in app.js), so a forged cross-site +// request is rejected with 403 before reaching this handler. 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..407580d --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,60 @@ +import { doubleCsrf } from 'csrf-csrf'; + +// Anti-CSRF protection using the double-submit-cookie pattern (csrf-csrf). +// +// How it works: +// 1. The client calls GET /api/csrf-token. The server generates a token that is +// HMAC-signed with CSRF_SECRET and bound to the current session (the auth +// cookie). The token is returned in the JSON body, and a hash of it is set in +// an httpOnly cookie. +// 2. On every state-changing request the client echoes the token back in the +// `x-csrf-token` header. The server checks that the header token matches the +// cookie AND was issued for this session. +// +// Why the attacker can't pass this check: an auto-submitting
on another +// site can make the browser send our cookies, but it can't set a custom header, +// and CORS stops the attacker's page from reading the token out of the +// /api/csrf-token response. So the forged request arrives without a valid +// token and gets a 403. +const { + doubleCsrfProtection, + generateCsrfToken, + invalidCsrfTokenError +} = doubleCsrf({ + // Read the secret lazily so it can come from .env (or be set by the tests). + getSecret: () => process.env.CSRF_SECRET || process.env.JWT_SECRET, + // Bind each token to the logged-in session. A token issued for one session + // (or for no session) won't work for another. + getSessionIdentifier: (req) => req.cookies?.token ?? '', + // No `__Host-` prefix: browsers only accept those cookies over HTTPS, and this + // demo runs on plain http://localhost. + cookieName: 'x-csrf-token', + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + secure: false, // true in production (HTTPS only) + path: '/' + }, + // GET / HEAD / OPTIONS are "safe" methods and stay exempt. + ignoredMethods: ['GET', 'HEAD', 'OPTIONS'], + // The client sends the token in a custom header. A plain HTML form can't set + // a custom header, which is part of what blocks the attack. + getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'] +}); + +// Routes that run before a session exists. There is no session to forge +// requests for yet, so they stay exempt. +const PRE_AUTH_ROUTES = new Set(['/api/auth/login', '/api/auth/register']); + +export function csrfProtection(req, res, next) { + if (PRE_AUTH_ROUTES.has(req.path)) return next(); + return doubleCsrfProtection(req, res, next); +} + +// GET /api/csrf-token: issues a token for the current session. +export function csrfTokenHandler(req, res) { + const csrfToken = generateCsrfToken(req, res, { overwrite: true }); + res.json({ csrfToken }); +} + +export { invalidCsrfTokenError }; diff --git a/server/src/routes/settings.js b/server/src/routes/settings.js index 2e8f894..6e5ec40 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 applies the csrf-csrf middleware, so a POST +// without a valid x-csrf-token header is rejected with 403 before it gets here. 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'); + }); +});