diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..75c1bbc --- /dev/null +++ b/.github/workflows/ci.yml @@ -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: '22' + + - name: Install dependencies + run: npm ci + + - 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..9a14288 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -7,3 +7,23 @@ export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +const safeMethods = new Set(['get', 'head', 'options']) +const preAuthRoutes = new Set(['/auth/login', '/auth/register']) +let pendingToken + +api.interceptors.request.use(async config => { + const method = config.method + const path = config.url.split('?')[0].replace(/\/$/, '').toLowerCase() + if (safeMethods.has(method) || (method === 'post' && preAuthRoutes.has(path))) { + return config + } + + // Share an in-flight fetch so concurrent writes use the same cookie and token. + pendingToken ??= api.get('/csrf-token') + .then(({ data }) => data.csrfToken) + .finally(() => { pendingToken = undefined }) + + config.headers.set('x-csrf-token', await pendingToken) + return config +}) 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..4928254 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5444,6 +5444,14 @@ "node": ">= 8" } }, + "node_modules/csrf-csrf": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/csrf-csrf/-/csrf-csrf-4.0.3.tgz", + "integrity": "sha512-DaygOzelL4Qo1pHwI9LPyZL+X2456/OzpT596kNeZGiTSqKVDOk/9PPJ+FjzZacjMUEusOHw3WJKe1RW4iUhrw==", + "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 +10819,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..621a4ca 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..f00373b 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -7,6 +7,9 @@ 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, invalidCsrfTokenError } from './middleware/csrf.js'; + const app = express(); app.use(morgan('dev')); @@ -21,6 +24,11 @@ app.use(cookieParser()); app.get('/api/health', (req, res) => res.json({ ok: true })); +app.get('/api/csrf-token', requireAuth, (req, res) => { + res.set('Cache-Control', 'no-store'); + res.json({ csrfToken: generateCsrfToken(req, res) }); +}); + app.use('/api/auth', authRoutes); app.use('/api/items', itemRoutes); app.use('/api/users', userRoutes); @@ -33,6 +41,9 @@ app.use((req, res) => { // Error handler app.use((err, req, res, next) => { + if (err === invalidCsrfTokenError) { + return res.status(403).json({ message: 'Invalid CSRF token' }); + } console.error(err); res.status(err.status || 500).json({ message: err.message || 'Server Error' }); }); diff --git a/server/src/controllers/authController.js b/server/src/controllers/authController.js index 4644f3e..a9daa48 100644 --- a/server/src/controllers/authController.js +++ b/server/src/controllers/authController.js @@ -1,4 +1,6 @@ import jwt from 'jsonwebtoken'; +import { randomUUID } from 'node:crypto'; +import { csrfCookieName } from '../middleware/csrf.js'; import bcrypt from 'bcryptjs'; import Joi from 'joi'; import { User } from '../models/User.js'; @@ -67,6 +69,7 @@ export async function login(req, res, next) { // POST /api/auth/logout export async function logout(req, res) { res.clearCookie('token'); + res.clearCookie(csrfCookieName); res.json({ ok: true }); } @@ -79,7 +82,7 @@ export async function me(req, res, next) { } function signToken(user) { - const payload = { id: user._id.toString(), name: user.name }; + const payload = { id: user._id.toString(), name: user.name, jti: randomUUID() }; return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }); } diff --git a/server/src/middleware/csrf.js b/server/src/middleware/csrf.js new file mode 100644 index 0000000..4715c28 --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,15 @@ +import { doubleCsrf } from 'csrf-csrf'; + +export const csrfCookieName = 'csrf-token'; +export const { generateCsrfToken, doubleCsrfProtection, invalidCsrfTokenError } = doubleCsrf({ + getSecret: () => process.env.CSRF_SECRET, + getSessionIdentifier: req => req.cookies.token, + cookieName: csrfCookieName, + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/' + }, + getCsrfTokenFromRequest: req => req.get('x-csrf-token') +}); diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index c80d6a0..1317f9d 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -2,11 +2,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/server/src/routes/items.js b/server/src/routes/items.js index 9dff0e8..b89d21b 100644 --- a/server/src/routes/items.js +++ b/server/src/routes/items.js @@ -2,13 +2,15 @@ import { Router } from 'express'; import { requireAuth } from '../middleware/auth.js'; import { getAllItems, getItem, createItem, updateItem, deleteItem } from '../controllers/itemController.js'; +import { doubleCsrfProtection } from '../middleware/csrf.js'; + const router = Router(); // Reading is public; writing requires a logged-in user. router.get('/', getAllItems); router.get('/:id', getItem); -router.post('/', requireAuth, createItem); -router.patch('/:id', requireAuth, updateItem); -router.delete('/:id', requireAuth, deleteItem); +router.post('/', requireAuth, doubleCsrfProtection, createItem); +router.patch('/:id', requireAuth, doubleCsrfProtection, updateItem); +router.delete('/:id', requireAuth, doubleCsrfProtection, deleteItem); export default router; diff --git a/server/src/routes/settings.js b/server/src/routes/settings.js index 2e8f894..ebc9980 100644 --- a/server/src/routes/settings.js +++ b/server/src/routes/settings.js @@ -2,12 +2,11 @@ import { Router } from 'express'; import { requireAuth } from '../middleware/auth.js'; import { getSettings, updateRecoveryEmail } from '../controllers/settingController.js'; +import { doubleCsrfProtection } from '../middleware/csrf.js'; + 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`. router.get('/', requireAuth, getSettings); -router.post('/recovery-email', requireAuth, updateRecoveryEmail); +router.post('/recovery-email', requireAuth, doubleCsrfProtection, updateRecoveryEmail); export default router; diff --git a/server/src/routes/users.js b/server/src/routes/users.js index 2026add..f03e99f 100644 --- a/server/src/routes/users.js +++ b/server/src/routes/users.js @@ -7,12 +7,14 @@ import { deleteUser } from '../controllers/userController.js'; +import { doubleCsrfProtection } from '../middleware/csrf.js'; + const router = Router(); // Creating a user is now done through POST /api/auth/register. router.get('/', getAllUsers); router.get('/:id', getUser); -router.patch('/:id', requireAuth, updateUser); -router.delete('/:id', requireAuth, deleteUser); +router.patch('/:id', requireAuth, doubleCsrfProtection, updateUser); +router.delete('/:id', requireAuth, doubleCsrfProtection, deleteUser); export default router; 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'); + }); +});