diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..1cd0dec --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,33 @@ +name: tests + +on: + push: + branches: [main, master] + pull_request: + branches: [main, master] + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 15 + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + + - name: Install dependencies + run: npm install + + - name: Install workspace dependencies + run: npm run install:all + + - name: Run tests + env: + MONGO_URI: ${{ secrets.MONGO_URI }} + JWT_SECRET: test-secret + CSRF_SECRET: test-csrf-secret + run: npm test -- --runInBand \ No newline at end of file diff --git a/babel.config.cjs b/babel.config.cjs new file mode 100644 index 0000000..6ea33a9 --- /dev/null +++ b/babel.config.cjs @@ -0,0 +1,3 @@ +module.exports = { + presets: [['@babel/preset-env', { targets: { node: 'current' } }]], +}; diff --git a/client/src/api.js b/client/src/api.js index 0aacdce..686963c 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -1,10 +1,45 @@ import axios from 'axios' // `withCredentials: true` makes the browser send the httpOnly auth cookie on -// every request to the API — including requests triggered by a different site. -// That convenience is exactly what leaves this app open to CSRF: there is no -// second proof that a state-changing request actually came from our own UI. +// every request to the API. On its own that's the precondition for CSRF — so +// every state-changing request must also carry an anti-CSRF token in a header +// the attacker's page cannot set. export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +// Cached CSRF token. We fetch it once from /csrf-token (which also sets the +// httpOnly double-submit cookie), then echo it back on every mutating request. +let csrfToken = null + +async function fetchCsrfToken() { + if (csrfToken) return csrfToken + const res = await api.get('/csrf-token') + csrfToken = res.data.csrfToken + return csrfToken +} + +// Attach the token to every state-changing request (POST / PUT / PATCH / DELETE). +api.interceptors.request.use(async (config) => { + const method = (config.method || 'get').toLowerCase() + if (['post', 'put', 'patch', 'delete'].includes(method)) { + const token = await fetchCsrfToken() + config.headers = config.headers || {} + config.headers['x-csrf-token'] = token + } + return config +}) + +// Drop the cached token when the session ends or a token is rejected, so the +// next user/session gets a fresh one. +api.interceptors.response.use( + (res) => { + if ((res.config?.url || '').includes('/auth/logout')) csrfToken = null + return res + }, + (err) => { + if (err.response?.status === 403) csrfToken = null + return Promise.reject(err) + } +) \ No newline at end of file diff --git a/create-tests.mjs b/create-tests.mjs new file mode 100644 index 0000000..82ba52c --- /dev/null +++ b/create-tests.mjs @@ -0,0 +1,159 @@ +import fs from 'fs'; +import path from 'path'; + +const files = { + 'tests/server/csrf.test.js': [ + "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();", + "});", + "", + "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);", + " return cookiePairs(res.headers['set-cookie']);", + "}", + "", + "describe('Maintenance requests - CSRF protection', () => {", + " test('happy path: logged-in user files a request with a valid token', async () => {", + " const authCookies = await registerUser();", + " 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/maintenance')", + " .set('Cookie', cookies.join('; '))", + " .set(headers)", + " .send({ roomNumber: 'B2-104', category: 'plumbing', description: 'Leaking tap' });", + " expect(res.status).toBe(201);", + " expect(res.body.request.description).toBe('Leaking tap');", + " });", + "", + " test('forged cross-site request with no CSRF token is rejected', async () => {", + " const authCookies = await registerUser();", + " const forged = await request(app)", + " .post('/api/maintenance')", + " .set('Cookie', authCookies.join('; '))", + " .set('Origin', 'http://attacker.evil')", + " .send({ roomNumber: 'Z9-666', category: 'other', description: 'Forged by attacker via CSRF' });", + " expect(forged.status).toBe(403);", + " const list = await request(app).get('/api/maintenance');", + " const forgedItem = list.body.requests.find((r) => r.description === 'Forged by attacker via CSRF');", + " expect(forgedItem).toBeUndefined();", + " });", + "});", + "" + ].join('\n'), + + 'tests/server/dos.test.js': [ + "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();", + "});", + "", + "describe('Maintenance requests - DoS / rate limiting', () => {", + " test('normal request to the public list succeeds', async () => {", + " const res = await request(app).get('/api/maintenance');", + " expect(res.status).toBe(200);", + " expect(Array.isArray(res.body.requests)).toBe(true);", + " });", + "", + " test('flood of requests from one client is rate-limited', async () => {", + " const statuses = [];", + " for (let i = 0; i < 40; i++) {", + " const res = await request(app).get('/api/maintenance');", + " statuses.push(res.status);", + " }", + " expect(statuses).toContain(200);", + " expect(statuses).toContain(429);", + " });", + "});", + "" + ].join('\n'), + + 'tests/client/csrf.test.js': [ + "import { api } from '../../client/src/api.js';", + "", + "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 = [];", + " 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', () => {", + " expect(api.defaults.withCredentials).toBe(true);", + " });", + "", + " test('mutating request carries the x-csrf-token header', async () => {", + " await api.post('/maintenance', { roomNumber: 'B2-104', category: 'plumbing', description: 'Leaking tap' });", + " const sent = captured.find((c) => (c.url || '').includes('/maintenance'));", + " expect(sent).toBeDefined();", + " expect(getHeader(sent.headers, 'x-csrf-token')).toBe('test-token');", + " });", + "});", + "" + ].join('\n'), +}; + +for (const [file, content] of Object.entries(files)) { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content, 'utf8'); + console.log('wrote', file); +} diff --git a/jest.config.cjs b/jest.config.cjs new file mode 100644 index 0000000..c387dae --- /dev/null +++ b/jest.config.cjs @@ -0,0 +1,6 @@ +module.exports = { + testEnvironment: 'node', + transform: { + '\\.[jt]sx?$': 'babel-jest', + }, +}; diff --git a/package-lock.json b/package-lock.json index 7d89ea0..2de4fc8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,9 @@ "server", "client" ], + "dependencies": { + "rxjs": "^7.8.2" + }, "devDependencies": { "@babel/core": "^7.26.0", "@babel/preset-env": "^7.26.0", @@ -6322,6 +6325,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", @@ -6873,6 +6885,25 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-rate-limit": { + "version": "8.7.4", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.4.tgz", + "integrity": "sha512-LKBXzX700wz3zAGNNmVnjRI5mEbYkLv7UbMI4+9Xa+JPcg2UZh6AgY/2CZh9RrJjFM5ttC/N1lD+KzyFoZITCw==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, "node_modules/express/node_modules/debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", @@ -7520,6 +7551,15 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/ip-address": { + "version": "10.7.6", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, "node_modules/ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", @@ -10414,7 +10454,6 @@ "version": "7.8.2", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", - "dev": true, "license": "Apache-2.0", "dependencies": { "tslib": "^2.1.0" @@ -11403,7 +11442,6 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, "license": "0BSD" }, "node_modules/type-detect": { @@ -11962,8 +12000,10 @@ "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", + "express-rate-limit": "^8.7.4", "joi": "^17.12.3", "jsonwebtoken": "^9.0.2", "mongoose": "^8.6.0", diff --git a/package.json b/package.json index 79abf85..cb0464b 100644 --- a/package.json +++ b/package.json @@ -23,5 +23,8 @@ "allowScripts": { "@parcel/watcher@2.6.0": true, "mongodb-memory-server@11.3.0": true + }, + "dependencies": { + "rxjs": "^7.8.2" } } diff --git a/server/package.json b/server/package.json index db19c7f..49be74d 100644 --- a/server/package.json +++ b/server/package.json @@ -10,8 +10,10 @@ "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", + "express-rate-limit": "^8.7.4", "joi": "^17.12.3", "jsonwebtoken": "^9.0.2", "mongoose": "^8.6.0", diff --git a/server/src/app.js b/server/src/app.js index d5bfda2..c71d05a 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -6,21 +6,26 @@ import authRoutes from './routes/auth.js'; import bookingRoutes from './routes/bookings.js'; import userRoutes from './routes/users.js'; import maintenanceRoutes from './routes/maintenance.js'; +import { generateCsrfToken } from './middleware/csrf.js'; const app = express(); app.use(morgan('dev')); -// CORS is locked to the client origin with credentials enabled so the browser -// may send the auth cookie on cross-origin XHR. (CORS alone does NOT stop CSRF.) app.use(cors({ origin: 'http://localhost:5175', credentials: true })); app.use(express.json()); -// Parse urlencoded bodies so a bare HTML
POST (the classic CSRF vector, -// which needs no JavaScript and triggers no CORS preflight) is understood. app.use(express.urlencoded({ extended: true })); app.use(cookieParser()); app.get('/api/health', (req, res) => res.json({ ok: true })); +// Issue a CSRF token. Client fetches this, then echoes it back in the +// `x-csrf-token` header on every state-changing request. The token is also +// set as an httpOnly double-submit cookie the attacker cannot read. +app.get('/api/csrf-token', (req, res) => { + const csrfToken = generateCsrfToken(req, res); + res.json({ csrfToken }); +}); + app.use('/api/auth', authRoutes); app.use('/api/bookings', bookingRoutes); app.use('/api/users', userRoutes); @@ -37,4 +42,4 @@ app.use((err, req, res, next) => { res.status(err.status || 500).json({ message: err.message || 'Server Error' }); }); -export default app; +export default app; \ No newline at end of file diff --git a/server/src/middleware/csrf.js b/server/src/middleware/csrf.js new file mode 100644 index 0000000..a39af87 --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,21 @@ +import { doubleCsrf } from 'csrf-csrf'; + +const { + generateCsrfToken, + doubleCsrfProtection, +} = doubleCsrf({ + getSecret: () => process.env.CSRF_SECRET || process.env.JWT_SECRET || 'dev-csrf-secret', + cookieName: 'x-csrf-token', + cookieOptions: { + sameSite: 'lax', + secure: false, + httpOnly: true, + path: '/', + }, + getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'], + getSessionIdentifier: (req) => req.cookies?.token || '', + ignoredMethods: ['GET', 'HEAD', 'OPTIONS'], + size: 32, +}); + +export { generateCsrfToken, doubleCsrfProtection }; diff --git a/server/src/middleware/rateLimiter.js b/server/src/middleware/rateLimiter.js new file mode 100644 index 0000000..d2f39a5 --- /dev/null +++ b/server/src/middleware/rateLimiter.js @@ -0,0 +1,10 @@ +import rateLimit from 'express-rate-limit'; + +export const maintenanceLimiter = rateLimit({ + windowMs: 60 * 1000, + limit: 20, + standardHeaders: 'draft-8', + legacyHeaders: false, + statusCode: 429, + message: { message: 'Too many requests, please try again later.' }, +}); \ No newline at end of file diff --git a/server/src/routes/maintenance.js b/server/src/routes/maintenance.js index dea0023..77a09cb 100644 --- a/server/src/routes/maintenance.js +++ b/server/src/routes/maintenance.js @@ -1,5 +1,7 @@ import { Router } from 'express'; import { requireAuth } from '../middleware/auth.js'; +import { doubleCsrfProtection } from '../middleware/csrf.js'; +import { maintenanceLimiter } from '../middleware/rateLimiter.js'; import { getAllRequests, getRequest, @@ -10,20 +12,13 @@ import { const router = Router(); -// Reading is public; writing requires a logged-in user. -// -// VULNERABLE on two fronts: -// 1. CSRF — the write routes trust the auth cookie alone. There is no -// anti-CSRF token, so any website the victim visits can forge a -// state-changing request in the victim's name (the browser attaches the -// cookie automatically). -// 2. DoS — there is no rate limiting anywhere, so the public list endpoint -// (and the writes) can be flooded with unlimited requests to exhaust the -// server. +router.use(maintenanceLimiter); + router.get('/', getAllRequests); router.get('/:id', getRequest); -router.post('/', requireAuth, createRequest); -router.patch('/:id', requireAuth, updateRequest); -router.delete('/:id', requireAuth, deleteRequest); -export default router; +router.post('/', doubleCsrfProtection, requireAuth, createRequest); +router.patch('/:id', doubleCsrfProtection, requireAuth, updateRequest); +router.delete('/:id', doubleCsrfProtection, requireAuth, deleteRequest); + +export default router; \ No newline at end of file diff --git a/tests/client/csrf.test.js b/tests/client/csrf.test.js new file mode 100644 index 0000000..a9f1e69 --- /dev/null +++ b/tests/client/csrf.test.js @@ -0,0 +1,33 @@ +import { api } from '../../client/src/api.js'; + +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 = []; + 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', () => { + expect(api.defaults.withCredentials).toBe(true); + }); + + test('mutating request carries the x-csrf-token header', async () => { + await api.post('/maintenance', { roomNumber: 'B2-104', category: 'plumbing', description: 'Leaking tap' }); + const sent = captured.find((c) => (c.url || '').includes('/maintenance')); + 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..f401f99 --- /dev/null +++ b/tests/server/csrf.test.js @@ -0,0 +1,72 @@ +import request from 'supertest'; +import mongoose from 'mongoose'; +import 'dotenv/config'; +import app from '../../server/src/app.js'; +import { MaintenanceRequest } from '../../server/src/models/MaintenanceRequest.js'; + +beforeAll(async () => { + process.env.JWT_SECRET = 'test-secret'; + process.env.JWT_EXPIRES_IN = '1h'; + process.env.CSRF_SECRET = 'test-csrf-secret'; + await mongoose.connect(process.env.MONGO_URI); +}, 30000); + +afterAll(async () => { + await mongoose.disconnect(); +}); + +beforeEach(async () => { + await MaintenanceRequest.deleteMany({}); +}); + +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); + return cookiePairs(res.headers['set-cookie']); +} + +describe('Maintenance requests - CSRF protection', () => { + test('happy path: logged-in user files a request with a valid token', async () => { + const authCookies = await registerUser(); + + 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/maintenance') + .set('Cookie', cookies.join('; ')) + .set(headers) + .send({ roomNumber: 'B2-104', category: 'plumbing', description: 'Leaking tap' }); + expect(res.status).toBe(201); + expect(res.body.request.description).toBe('Leaking tap'); + }, 30000); + + test('forged cross-site request with no CSRF token is rejected', async () => { + const authCookies = await registerUser(); + + const forged = await request(app) + .post('/api/maintenance') + .set('Cookie', authCookies.join('; ')) + .set('Origin', 'http://attacker.evil') + .send({ roomNumber: 'Z9-666', category: 'other', description: 'Forged by attacker via CSRF' }); + expect(forged.status).toBe(403); + + const list = await request(app).get('/api/maintenance'); + const forgedItem = list.body.requests.find((r) => r.description === 'Forged by attacker via CSRF'); + expect(forgedItem).toBeUndefined(); + }, 30000); +}); \ No newline at end of file diff --git a/tests/server/dos.test.js b/tests/server/dos.test.js new file mode 100644 index 0000000..39edfe8 --- /dev/null +++ b/tests/server/dos.test.js @@ -0,0 +1,33 @@ +import request from 'supertest'; +import mongoose from 'mongoose'; +import 'dotenv/config'; +import app from '../../server/src/app.js'; + +beforeAll(async () => { + process.env.JWT_SECRET = 'test-secret'; + process.env.JWT_EXPIRES_IN = '1h'; + process.env.CSRF_SECRET = 'test-csrf-secret'; + await mongoose.connect(process.env.MONGO_URI); +}, 30000); + +afterAll(async () => { + await mongoose.disconnect(); +}); + +describe('Maintenance requests - DoS / rate limiting', () => { + test('normal request to the public list succeeds', async () => { + const res = await request(app).get('/api/maintenance'); + expect(res.status).toBe(200); + expect(Array.isArray(res.body.requests)).toBe(true); + }, 30000); + + test('flood of requests from one client is rate-limited', async () => { + const statuses = []; + for (let i = 0; i < 40; i++) { + const res = await request(app).get('/api/maintenance'); + statuses.push(res.status); + } + expect(statuses).toContain(200); + expect(statuses).toContain(429); + }, 60000); +}); \ No newline at end of file