From 1111a89116a364949f9b10931a02fa90df6b379c Mon Sep 17 00:00:00 2001 From: Mariam Abaza Date: Wed, 11 Nov 2026 15:52:44 -0800 Subject: [PATCH 1/2] csrf commit --- Flow.md | 38 ++++++++-------- README.md | 13 +++--- babel.config.cjs | 6 +++ client/src/api.js | 60 +++++++++++++++++++++++-- package-lock.json | 10 +++++ server/package.json | 1 + server/src/app.js | 41 ++++++++++++++--- server/src/index.js | 1 + server/src/middleware/csrf.js | 52 +++++++++++++++++++++ tests/client/csrf.test.js | 40 +++++++++++++++++ tests/server/csrf.test.js | 85 +++++++++++++++++++++++++++++++++++ 11 files changed, 313 insertions(+), 34 deletions(-) create mode 100644 babel.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/Flow.md b/Flow.md index ec11055..8641fea 100644 --- a/Flow.md +++ b/Flow.md @@ -29,6 +29,7 @@ PORT=4000 MONGO_URI= JWT_SECRET= JWT_EXPIRES_IN=7d +CSRF_SECRET= ``` Start the app: @@ -82,24 +83,24 @@ form** that POSTs to `http://localhost:4000/api/settings/recovery-email` with `recoveryEmail=attacker@evil.com`, targeting a hidden iframe so you see nothing. Now go back to the app tab and **refresh the Settings page** (or `GET -http://localhost:4000/api/settings` in a logged-in tab). The recovery email is now -**`attacker@evil.com`** — changed without your consent. From here the attacker triggers a -password reset and receives the link. **Account takeover.** +http://localhost:4000/api/settings` in a logged-in tab). With the CSRF fix applied, the forged +request is rejected with **`403 Forbidden`**, and your recovery email remains unchanged. > Want to watch it happen? Open DevTools → **Network** on the attacker page before it loads, -> and you will see the cross-site `POST` to `/api/settings/recovery-email` return `200`, with -> your `token` cookie attached under **Request Headers → Cookie**. +> and you will see the cross-site `POST` to `/api/settings/recovery-email` return `403`, with +> your `token` cookie attached under **Request Headers → Cookie**. The attacker cannot read +> the CSRF token or set the required `x-csrf-token` header. --- ## 4. Why it works (the vulnerable code path) 1. **Auth is a cookie the browser sends for you** — `server/src/middleware/auth.js` reads the - JWT from `req.cookies.token`. The victim's browser attaches it to the attacker's forged - request automatically; the server cannot tell the difference between that and a real click. -2. **The write trusts the cookie alone** — `server/src/controllers/settingController.js` - (`updateRecoveryEmail`) performs the update with **no proof the request came from our own - app**: no anti-CSRF token, no check that a real user action triggered it. + JWT from `req.cookies.token`. The victim's browser still attaches it to the attacker's forged + request automatically. +2. **The write now also requires a CSRF token** — the `csrf-csrf` middleware checks a signed + token bound to the session JWT. The client obtains it from `GET /api/csrf-token` and sends it + in the `x-csrf-token` header on every state-changing request. 3. **The body is a plain form** — `server/src/app.js` parses `urlencoded` bodies, so a bare HTML `
` POST (which needs no JavaScript and triggers no CORS preflight) is enough. 4. **CORS does not save you.** CORS only blocks the attacker from *reading* the response; the @@ -114,9 +115,9 @@ password reset and receives the link. **Account takeover.** > deliberate lesson: **`SameSite` is a useful layer but not a substitute for a real anti-CSRF > token.** The fix the solution uses works regardless of site/port. -The fix: require a secret, per-session **CSRF token** on every state-changing request — a value -the attacker's site cannot read or guess. The solution project does this with the `csrf-csrf` -package. +The middleware leaves safe `GET`, `HEAD`, and `OPTIONS` requests and pre-authentication +`POST /api/auth/login` and `POST /api/auth/register` exempt. Other state-changing requests made +with an authenticated session require a valid token. --- @@ -129,13 +130,12 @@ npm install # first time only npm test ``` -What to expect **in this vulnerable project**: +What to expect after applying the fix: -- The tests describe the **secure** behavior the feature *should* have: a forged request with no - CSRF token is rejected (server), and the client attaches a CSRF token to mutating requests. -- So here they are **expected to FAIL** (the suite is red). That red result is the starting - point — your job is to make them green by adding CSRF protection. The solution project shows - them all passing. +- The tests verify that a legitimate update succeeds when accompanied by a CSRF token, a forged + request without one returns `403` without changing the recovery email, and the client attaches + the token to writes. +- All CSRF tests should pass. Notes: diff --git a/README.md b/README.md index e03fc86..f7124c6 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,9 @@ Create the `server/.env` file. ```ini PORT=4000 MONGO_URI=mongodb://tasks:pass1234@ac-j3acrgb-shard-00-00.lueesfz.mongodb.net:27017,ac-j3acrgb-shard-00-01.lueesfz.mongodb.net:27017,ac-j3acrgb-shard-00-02.lueesfz.mongodb.net:27017/?ssl=true&replicaSet=atlas-6to6iy-shard-0&authSource=admin&appName=Cluster0 -JWT_SECRET=4a498d90a0f923ae4b3f1f65571ff25985d17e2f3286e8e90383e449f68a40a8 +JWT_SECRET= JWT_EXPIRES_IN=7d +CSRF_SECRET= ``` ## What was added on top of Task 3 @@ -62,7 +63,8 @@ JWT_EXPIRES_IN=7d `req.cookies.token`. A `POST /api/auth/logout` route clears the cookie. The browser now sends the session automatically on every request — which is exactly the precondition for `CSRF`. - `app.js` now mounts `cookie-parser`, `express.urlencoded` (so plain HTML-form bodies are - parsed), and CORS with `credentials: true` locked to the client origin. + parsed), and CORS with `credentials: true` locked to the client origin. It also issues + session-bound CSRF tokens and rejects state-changing requests without a matching token. - Added a new model called **`Setting`** with the attributes: `user`, `recoveryEmail`, `notifications`. - Added the **Setting controller** with the following routes: @@ -73,8 +75,8 @@ JWT_EXPIRES_IN=7d ### Client - `api.js` now sends requests with `withCredentials: true` (so the auth cookie rides along) and no - longer stores a token in `localStorage`. `AuthContext` restores the session via - `GET /api/auth/me`. + longer stores a token in `localStorage`. It fetches a CSRF token when needed and sends it in + the `x-csrf-token` header on writes. `AuthContext` restores the session via `GET /api/auth/me`. - Added the **`Settings.jsx`** page (and a **Settings** nav link) for viewing and updating the recovery email. @@ -93,7 +95,8 @@ Please note that the demo works over `http://localhost` because the attacker's p `SameSite` attribute keys off the registrable domain, not the port, so the `SameSite=Lax` auth cookie is still sent. This is a deliberate lesson: `SameSite` is a useful layer but **not** a complete defense, which is why a real anti-`CSRF` token is required (details in the `Flow.md` -file). After reading the file, read the next section. +file). The fixed application rejects the attacker's forged write with `403` and leaves the +recovery email unchanged. After reading the file, read the next section. ## Task 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..b104356 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -1,9 +1,63 @@ + 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. export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +let csrfToken = null +let csrfTokenRequest = null + +const safeMethods = ['get', 'head', 'options'] + +function isLoginOrRegister(url = '') { + return /\/auth\/(login|register)\/?$/.test(url) +} + +api.interceptors.request.use(async (config) => { + const method = (config.method || 'get').toLowerCase() + + // Safe requests don't need a CSRF token. + if (safeMethods.includes(method)) { + return config + } + + // Login and registration happen before an authenticated session exists. + if (isLoginOrRegister(config.url)) { + return config + } + + // Obtain a token if we don't already have one. + if (!csrfToken) { + if (!csrfTokenRequest) { + csrfTokenRequest = api.get('/csrf-token') + .then(({ data }) => { + csrfToken = data.csrfToken + return csrfToken + }) + .finally(() => { + csrfTokenRequest = null + }) + } + + await csrfTokenRequest + } + + config.headers = config.headers || {} + config.headers['X-CSRF-Token'] = csrfToken + + return config +}) + +// A successful login, registration or logout changes the session. +// The next write request will fetch a fresh token. +api.interceptors.response.use((response) => { + const url = response.config?.url || '' + + if (/\/auth\/(login|register|logout)\/?$/.test(url)) { + csrfToken = null + } + + return response +}) 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..f77381e 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -1,25 +1,49 @@ + 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 })); + +// Cookie parsing must happen before CSRF protection. app.use(cookieParser()); -app.get('/api/health', (req, res) => res.json({ ok: true })); +app.get('/api/health', (req, res) => + res.json({ ok: true }) +); + +// Apply CSRF protection to state-changing requests. +app.use(doubleCsrfProtection); + +// Endpoint for authenticated clients to obtain a CSRF token. +app.get('/api/csrf-token', requireAuth, (req, res) => { + const csrfToken = generateCsrfToken(req, res); + + res.json({ csrfToken }); +}); app.use('/api/auth', authRoutes); app.use('/api/items', itemRoutes); @@ -34,7 +58,10 @@ 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/index.js b/server/src/index.js index 320417a..6af0119 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -1,4 +1,5 @@ import dotenv from 'dotenv'; + dotenv.config(); import app from './app.js'; import { connectDB } from './config/db.js'; diff --git a/server/src/middleware/csrf.js b/server/src/middleware/csrf.js new file mode 100644 index 0000000..5709d07 --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,52 @@ + +import { doubleCsrf } from 'csrf-csrf'; + +const { + generateCsrfToken, + doubleCsrfProtection +} = doubleCsrf({ + // Use a strong secret stored in the environment. + // Fall back to JWT_SECRET for environments that haven't + // configured CSRF_SECRET yet. + getSecret: () => + process.env.CSRF_SECRET || process.env.JWT_SECRET, + + // Bind the CSRF token to the authenticated JWT session. + // Each login creates a different JWT. + getSessionIdentifier: (req) => + req.cookies?.token || 'anonymous', + + cookieName: 'csrf-token', + + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/' + }, + + // Safe methods do not need CSRF protection. + ignoredMethods: ['GET', 'HEAD', 'OPTIONS'], + + // The frontend must send the token in this header. + getCsrfTokenFromRequest: (req) => + req.headers['x-csrf-token'], + + // Login and registration happen before authentication. + skipCsrfProtection: (req) => + req.method === 'POST' && + [ + '/api/auth/login', + '/api/auth/register' + ].includes(req.path), + + errorConfig: { + statusCode: 403, + message: 'Invalid CSRF token' + } +}); + +export { + generateCsrfToken, + doubleCsrfProtection +}; 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'); + }); +}); From 0156eee80900e5f64611202416e8cd48b4e2e6ae Mon Sep 17 00:00:00 2001 From: Mariam Abaza Date: Wed, 11 Nov 2026 16:04:12 -0800 Subject: [PATCH 2/2] csrf --- .github/workflows/ci.yaml | 24 ++++++++++++++++++++++++ README.md | 2 +- jest.config.cjs | 24 ++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/ci.yaml create mode 100644 jest.config.cjs 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/README.md b/README.md index f7124c6..7ca13bf 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ Create the `server/.env` file. ```ini PORT=4000 MONGO_URI=mongodb://tasks:pass1234@ac-j3acrgb-shard-00-00.lueesfz.mongodb.net:27017,ac-j3acrgb-shard-00-01.lueesfz.mongodb.net:27017,ac-j3acrgb-shard-00-02.lueesfz.mongodb.net:27017/?ssl=true&replicaSet=atlas-6to6iy-shard-0&authSource=admin&appName=Cluster0 -JWT_SECRET= +JWT_SECRET=e393815729680c491a3ce5bb3c5d3968b6aaa69eb64e2ca6452a1c38062b69b2 JWT_EXPIRES_IN=7d CSRF_SECRET= ``` 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' + } + } + ] +};