From 67c4d2cefe2db35c448c455b79fc7f4700f24837 Mon Sep 17 00:00:00 2001 From: janaelgazzar Date: Thu, 12 Nov 2026 10:37:28 +0200 Subject: [PATCH] for testing --- .github/workflows/ci.yml | 42 +++++++++++ babel.config.cjs | 6 ++ client/src/api.js | 25 +++++-- jest.config.cjs | 24 +++++++ package-lock.json | 90 +++++++++++------------- server/package.json | 2 + server/src/app.js | 38 ++++++++++ server/src/controllers/authController.js | 5 +- server/src/routes/maintenance.js | 23 +++--- tests/client/csrf.test.js | 40 +++++++++++ tests/server/csrf.test.js | 82 +++++++++++++++++++++ tests/server/dos.test.js | 43 +++++++++++ 12 files changed, 358 insertions(+), 62 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 babel.config.cjs create mode 100644 jest.config.cjs create mode 100644 tests/client/csrf.test.js create mode 100644 tests/server/csrf.test.js create mode 100644 tests/server/dos.test.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..429f1ce --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,42 @@ +name: Tests + +# Run the test suite on every pull request, and on pushes to main. +on: + pull_request: + push: + branches: [main] + +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' + cache: 'npm' + + # Keep the MongoDB binary used by mongodb-memory-server between runs, + # so it is only downloaded once instead of on every pull request. + - name: Cache MongoDB binary + uses: actions/cache@v4 + with: + path: ~/.cache/mongodb-binaries + key: mongodb-binaries-${{ runner.os }}-${{ hashFiles('package-lock.json') }} + + - name: Install dependencies + run: npm ci + + # Download MongoDB before the tests start, so the tests' 60s + # beforeAll timeout is not spent on the download. + - name: Pre-download MongoDB + run: node -e "import('mongodb-memory-server').then(async m => { const s = await m.MongoMemoryServer.create(); await s.stop(); console.log('MongoDB ready') })" + + # The tests set their own JWT_SECRET / CSRF_SECRET and use an in-memory + # database, so no secrets or .env file are needed here. + - name: Run tests + 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 0aacdce..05e62e5 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -1,10 +1,27 @@ 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. +// `withCredentials: true` makes the browser send the httpOnly auth cookie (and +// the CSRF cookie) on every request to the API. export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +const SAFE_METHODS = ['get', 'head', 'options'] +const CSRF_EXEMPT = ['/auth/login', '/auth/register'] + +// Before every state-changing request, fetch a fresh CSRF token and echo it in +// the `x-csrf-token` header. The token is bound to the session cookie, which +// changes on login/register, so fetching per request never sends a stale one. +api.interceptors.request.use(async (config) => { + const method = (config.method || 'get').toLowerCase() + const url = config.url || '' + if (SAFE_METHODS.includes(method) || CSRF_EXEMPT.some((p) => url.includes(p))) { + return config + } + + // This is a GET, so it skips the branch above — no recursion. + const { data } = await api.get('/csrf-token') + config.headers['x-csrf-token'] = data.csrfToken + 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 7d89ea0..49c6879 100644 --- a/package-lock.json +++ b/package-lock.json @@ -101,6 +101,7 @@ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", @@ -1962,6 +1963,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" }, @@ -1985,6 +1987,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" } @@ -3175,9 +3178,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3199,9 +3199,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3223,9 +3220,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3247,9 +3241,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3271,9 +3262,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3295,9 +3283,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3899,6 +3884,7 @@ "integrity": "sha512-yOriVnggzrnQ3a9OKOCxaVuSug3w3/SbOj5i7VwXWZEyUNl3bLF9V3MfxGbZKuwqJOQyRfqXyROBB1CoZLFWzA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@types/node": "*", "@types/tough-cookie": "*", @@ -4074,9 +4060,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4091,9 +4074,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4108,9 +4088,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4125,9 +4102,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4142,9 +4116,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4159,9 +4130,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4176,9 +4144,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4193,9 +4158,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4210,9 +4172,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4227,9 +4186,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4668,6 +4624,7 @@ "integrity": "sha512-cIjZnSO+y89ykVX9x96OVnA6tGORBn7vGJ/e3PCbBHMEyfMNG/ixzOS0lLa6saMlWcs69bSKjxFyDwjK152OMg==", "dev": true, "license": "Apache-2.0", + "peer": true, "engines": { "bare": ">=1.20.0" } @@ -4678,6 +4635,7 @@ "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==", "dev": true, "license": "Apache-2.0", + "peer": true, "peerDependencies": { "bare-abort-controller": "*" }, @@ -4893,6 +4851,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.11.26", "caniuse-lite": "^1.0.30001813", @@ -6322,6 +6281,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 +6841,21 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-rate-limit": { + "version": "7.5.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.1.tgz", + "integrity": "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==", + "license": "MIT", + "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", @@ -8063,6 +8046,7 @@ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -8185,6 +8169,7 @@ "integrity": "sha512-wprhLejRtwN6h8ZgaqC0eYjGJ1uMdGPT/+b3eFncbG4NWuuP9QL+vWwRinu9waw7hkOLcpMJGVJAMgBwsPssMQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "chalk": "^4.1.2", "graceful-fs": "^4.2.11", @@ -8432,6 +8417,7 @@ "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", "dev": true, "license": "MIT", + "peer": true, "bin": { "jiti": "bin/jiti.js" } @@ -8475,6 +8461,7 @@ "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", @@ -9800,6 +9787,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", @@ -10110,6 +10098,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -10122,6 +10111,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -11291,6 +11281,7 @@ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -11622,6 +11613,7 @@ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", @@ -11962,8 +11954,10 @@ "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", + "express-rate-limit": "^7.5.0", "joi": "^17.12.3", "jsonwebtoken": "^9.0.2", "mongoose": "^8.6.0", diff --git a/server/package.json b/server/package.json index db19c7f..065d650 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.0.3", "dotenv": "^16.4.5", "express": "^4.19.2", + "express-rate-limit": "^7.5.0", "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..03574b0 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -2,6 +2,7 @@ import express from 'express'; import morgan from 'morgan'; import cors from 'cors'; import cookieParser from 'cookie-parser'; +import { doubleCsrf } from 'csrf-csrf'; import authRoutes from './routes/auth.js'; import bookingRoutes from './routes/bookings.js'; import userRoutes from './routes/users.js'; @@ -9,6 +10,9 @@ import maintenanceRoutes from './routes/maintenance.js'; const app = express(); +// Don't advertise "X-Powered-By: Express" — it tells attackers what we run. +app.disable('x-powered-by'); + 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.) @@ -19,6 +23,40 @@ app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(cookieParser()); +// --------------------------------------------------------------------------- +// CSRF protection (double-submit cookie pattern via csrf-csrf). +// +// The server issues a signed token two ways: in a JSON body (which the client +// reads and echoes back in the `x-csrf-token` header) and in an httpOnly +// cookie. A state-changing request is accepted only if the header matches the +// cookie. An attacker's page can make the browser SEND cookies, but cannot READ +// our cookies or responses, and a plain HTML form cannot set custom headers — +// so a forged request arrives without a valid token and is rejected with 403. +// --------------------------------------------------------------------------- +const { doubleCsrfProtection, generateCsrfToken } = doubleCsrf({ + // Read lazily so the secret can come from .env (index.js) or be set by tests. + getSecret: () => process.env.CSRF_SECRET, + // Bind each token to the current login session (the JWT auth cookie). + getSessionIdentifier: (req) => req.cookies.token ?? '', + // The default "__Host-" prefixed name requires HTTPS; we run on http://localhost. + cookieName: 'x-csrf-token', + cookieOptions: { sameSite: 'strict', secure: false, httpOnly: true, path: '/' }, + getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'] +}); + +// Hands the client a token (and sets the matching cookie). +app.get('/api/csrf-token', (req, res) => { + res.json({ csrfToken: generateCsrfToken(req, res) }); +}); + +// Protect every state-changing request. GET/HEAD/OPTIONS are ignored by +// csrf-csrf automatically ("safe" methods). Login/register are exempt because +// they run before a session exists, so there is nothing to bind a token to. +const CSRF_EXEMPT = ['/api/auth/login', '/api/auth/register']; +app.use((req, res, next) => + CSRF_EXEMPT.includes(req.path) ? next() : doubleCsrfProtection(req, res, next) +); + app.get('/api/health', (req, res) => res.json({ ok: true })); app.use('/api/auth', authRoutes); diff --git a/server/src/controllers/authController.js b/server/src/controllers/authController.js index 4644f3e..02227a1 100644 --- a/server/src/controllers/authController.js +++ b/server/src/controllers/authController.js @@ -12,7 +12,10 @@ const COOKIE_MAX_AGE = 7 * 24 * 60 * 60 * 1000; function setAuthCookie(res, token) { res.cookie('token', token, { httpOnly: true, - sameSite: 'lax', + // Strict: never sent on cross-site requests. An extra layer only — the + // attacker on localhost:1337 counts as the SAME site, so the CSRF token + // is still the real defense. + sameSite: 'strict', secure: false, // true in production (HTTPS only) maxAge: COOKIE_MAX_AGE }); diff --git a/server/src/routes/maintenance.js b/server/src/routes/maintenance.js index dea0023..1d2023d 100644 --- a/server/src/routes/maintenance.js +++ b/server/src/routes/maintenance.js @@ -1,4 +1,5 @@ import { Router } from 'express'; +import { rateLimit } from 'express-rate-limit'; import { requireAuth } from '../middleware/auth.js'; import { getAllRequests, @@ -10,16 +11,20 @@ import { const router = Router(); +// DoS protection: each client (by IP) may make at most 30 requests per minute +// to the maintenance feature. Excess requests get 429 Too Many Requests and are +// refused before reaching the controller, so a flood never hits the database. +const maintenanceLimiter = rateLimit({ + windowMs: 60 * 1000, + limit: 30, + standardHeaders: 'draft-7', + legacyHeaders: false, + message: { message: 'Too many requests, please try again later.' } +}); +router.use(maintenanceLimiter); + // 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. +// CSRF protection for the write routes is applied globally in app.js. router.get('/', getAllRequests); router.get('/:id', getRequest); router.post('/', requireAuth, createRequest); diff --git a/tests/client/csrf.test.js b/tests/client/csrf.test.js new file mode 100644 index 0000000..4873239 --- /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('/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..5851fc9 --- /dev/null +++ b/tests/server/csrf.test.js @@ -0,0 +1,82 @@ +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('Maintenance requests — CSRF protection', () => { + test('a logged-in user can file a maintenance request (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/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'); + }); + + // 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/maintenance') + .set('Cookie', authCookies.join('; ')) // only the auth cookie — as in a real CSRF + .set('Origin', 'http://attacker.evil') // request originates off-site + .send({ roomNumber: 'Z9-666', category: 'other', description: 'Forged by attacker via CSRF' }); + + // Secure behavior: refuse the request for lack of a valid CSRF token. + expect(forged.status).toBe(403); + + // And no forged request must have been written to the database. + 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(); + }); +}); diff --git a/tests/server/dos.test.js b/tests/server/dos.test.js new file mode 100644 index 0000000..9382c98 --- /dev/null +++ b/tests/server/dos.test.js @@ -0,0 +1,43 @@ +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('a normal request to the public list succeeds (the happy path)', async () => { + const res = await request(app).get('/api/maintenance'); + expect(res.status).toBe(200); + expect(Array.isArray(res.body.requests)).toBe(true); + }); + + // The core DoS test. One client floods the public endpoint. A secure server + // rate-limits it (429 after a small number of requests) so a flood cannot + // exhaust it; a vulnerable server serves every request (200), unbounded. + test('a 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); + } + + // Legitimate traffic is still served early in the window... + expect(statuses).toContain(200); + // ...but the flood is throttled with 429 Too Many Requests. + expect(statuses).toContain(429); + }); +});