From e24b1f0a424d7b9fb30659f74cbbfcd52ef73f65 Mon Sep 17 00:00:00 2001 From: Miriam Date: Thu, 12 Nov 2026 15:48:03 +0200 Subject: [PATCH 1/2] Fix CSRF and DoS vulnerabilities --- Flow.md | 104 +++++++++++------------ README.md | 49 ++++------- babel.config.cjs | 5 ++ client/src/api.js | 41 ++++++++- jest.config.cjs | 20 +++++ package-lock.json | 39 +++++++++ server/package.json | 2 + server/src/app.js | 32 +++++++ server/src/controllers/authController.js | 3 +- server/src/routes/maintenance.js | 21 ++--- tests/client/csrf.test.js | 40 +++++++++ tests/server/csrf.test.js | 82 ++++++++++++++++++ tests/server/dos.test.js | 43 ++++++++++ 13 files changed, 377 insertions(+), 104 deletions(-) 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/Flow.md b/Flow.md index 5e34662..8731e40 100644 --- a/Flow.md +++ b/Flow.md @@ -1,18 +1,18 @@ # Flow — Simulating the CSRF and DoS Attacks -This project ships a **deliberately vulnerable** feature: **Maintenance Requests** -(`/maintenance`). Any logged-in resident can file a request to fix something in a room. -Two things are wrong with it: +This project includes a **Maintenance Requests** feature (`/maintenance`). Any logged-in +resident can file a request to fix something in a room. This flow verifies defenses against +CSRF and request flooding: 1. **CSRF (Cross-Site Request Forgery).** The app authenticates every request with a **JWT stored in an httpOnly cookie**. The browser attaches that cookie **automatically** to *every* request to the API — including requests triggered by a completely different - website. So an attacker's page can forge a state-changing request **in the victim's name** - without ever seeing their password or token. -2. **DoS (Denial of Service).** There is **no rate limiting** anywhere, so a single client - can flood the endpoints with unlimited requests and exhaust the server. + website, so state-changing requests also require a session-bound CSRF token that an attacker + page cannot read or guess. +2. **DoS (Denial of Service).** Maintenance endpoints are rate-limited so one client cannot + make unlimited requests in a short time. -Follow the steps to reproduce both, then read *Why it works*, then run the tests. +Follow the steps to verify both protections, then read *Why it works*, then run the tests. --- @@ -31,6 +31,7 @@ PORT=4000 MONGO_URI= JWT_SECRET= JWT_EXPIRES_IN=7d +CSRF_SECRET= ``` Start the app: @@ -50,9 +51,8 @@ Open the client at **http://localhost:5175**. and note the `token` cookie. It is **HttpOnly** (JavaScript cannot read it) — but the browser still sends it on every request to the API. 3. Click **Maintenance** and file a request (e.g. room `B2-104`, *plumbing*, "Leaking tap"). - This is a legitimate action; the forged one is about to look just like it. -**Leave this browser logged in.** Both attacks rely on the victim's active session. +**Leave this browser logged in.** The demo attempts both attacks against the active session. --- @@ -71,7 +71,7 @@ npm start # Attacker site on http://localhost:1337 --- -## 3. Spring the CSRF trap +## 3. Verify the CSRF protection In the **same browser** where you are logged in as the victim, open: @@ -79,66 +79,58 @@ In the **same browser** where you are logged in as the victim, open: http://localhost:1337 ``` -It looks like a harmless "You won a prize!" page. But on load it **auto-submits a hidden -form** that POSTs to `http://localhost:4000/api/maintenance` with a forged request -(`description=Forged by attacker via CSRF`), targeting a hidden iframe so you see nothing. +It looks like a harmless "You won a prize!" page. On load it auto-submits a hidden form that +attempts to POST a forged maintenance request, targeting a hidden iframe. -Now go back to the app tab and **refresh the Maintenance page**. A request you never made — -`Forged by attacker via CSRF` for room `Z9-666` — is now filed **in your name**. The server -could not tell it apart from a real click. +The POST should be rejected with `403` because the form cannot provide the session's CSRF token. +Go back to the app and refresh Maintenance: no request for room `Z9-666` should appear. -> 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/maintenance` return `201`, with your -> `token` cookie attached under **Request Headers → Cookie**. +In DevTools → **Network**, verify that the POST is refused and does not create a request. CORS +only controls whether an origin may read a response; it does not prevent the browser from sending +the form. The anti-CSRF token is the proof the server checks. --- ## 4. Spring the DoS flood -Still on `http://localhost:1337`, click **"Claim my prize"**. The page fires **hundreds of -`fetch` requests** at `http://localhost:4000/api/maintenance` straight from the victim's -browser. +Still on `http://localhost:1337`, click **"Claim my prize"**. The page fires many `fetch` requests +at `http://localhost:4000/api/maintenance` from the victim's browser. -Open DevTools → **Network** and watch: every request returns `200` and is served in full. -There is nothing stopping one client (or a crowd of victims lured to this page) from -hammering the API until it falls over. **No request is ever refused.** +Open DevTools → **Network** and verify that early requests return `200`, then excess requests +return `429 Too Many Requests`. --- -## 5. Why it works (the vulnerable code path) +## 5. Why the protections work **CSRF** -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/routes/maintenance.js` guards `POST /` - with only `requireAuth`. There is **no proof the request came from our own app**: no - anti-CSRF token. -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 - browser still *sends* the request and the server still *acts on it*. CSRF is about the - write succeeding, not about reading the reply. +1. **Auth is a cookie the browser sends automatically** — so cookie-authenticated state-changing + requests need additional proof. +2. **The token is session-bound** — `csrf-csrf` signs it using `CSRF_SECRET` and binds it to the + auth cookie. The client reads it from the authenticated `/api/csrf-token` response and sends it + in `x-csrf-token`. An attacker page cannot read that response or set the required header on a + plain HTML form. +3. **Safe methods and pre-auth routes differ** — `GET`, `HEAD`, and `OPTIONS` are ignored by CSRF + protection; login and registration are exempt because there is no session yet. All other + state-changing requests require the token. +4. **CORS does not prevent sending forms.** It only controls whether the attacker can read the + response. The token check prevents the server from acting on the forged write. > ### Why `SameSite` doesn't save you here > The auth cookie is `SameSite=Lax`. You might expect that to block a cross-site POST — and > across true different sites (`evil.com` → `yourbank.com`) it largely would. But the attacker -> page (`localhost:1337`) and the API (`localhost:4000`) are the **same site**: the port is not -> part of a site's identity, only the registrable domain is. So the cookie is sent. This is a -> deliberate lesson: **`SameSite` is a useful layer but not a substitute for a real anti-CSRF -> token.** +> page (`localhost:1337`) and the API (`localhost:4000`) are the **same site**: ports do not +> distinguish sites. The browser may therefore send the `SameSite=Lax` auth cookie with the +> forged request. SameSite is useful defense-in-depth, not a substitute for a CSRF token. **DoS** -5. **No rate limiting** — `server/src/routes/maintenance.js` applies no limiter, so - `maintenanceController.getAllRequests` runs for *every* request, no matter how many arrive - from one client in how short a time. Each one hits the database. +5. **Rate limiting** — `server/src/routes/maintenance.js` applies a per-IP limit to all + maintenance endpoints, returning `429` after 30 requests in a 15-minute window. -The fixes: require a secret, per-session **CSRF token** on every state-changing request (a -value the attacker's site cannot read or guess), and **rate-limit** the feature so a flood is -refused with `429`. The solution project does this with the `csrf-csrf` and -`express-rate-limit` packages. +Login and registration remain available before a session exists. Configure a separate, +cryptographically random `CSRF_SECRET`; do not reuse the JWT secret. --- @@ -151,14 +143,14 @@ npm install # first time only npm test ``` -What to expect **in this vulnerable project**: +The CSRF and DoS tests verify the protected behavior: -- The tests describe the **secure** behavior the feature *should* have: a forged request with - no CSRF token is rejected (server), a flood is throttled to `429` (server), and the client - attaches a CSRF token to mutating requests (client). -- 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 and rate limiting. The - solution project shows them all passing. +- a forged write without a CSRF token is rejected and does not change data; +- repeated requests to maintenance endpoints are throttled with `429`; and +- the client attaches its CSRF token to mutating requests. + +The tests should pass once dependencies are installed and `CSRF_SECRET` is configured in the +server environment (the tests set their own value). Notes: diff --git a/README.md b/README.md index 3c31cd4..f623657 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ 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_EXPIRES_IN=7d +CSRF_SECRET= ``` ## What was added on top of Task 3 @@ -87,8 +88,11 @@ JWT_EXPIRES_IN=7d **httpOnly cookie** (`authController.js`), and `middleware/auth.js` reads the token from `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. +- `app.js` mounts `cookie-parser`, `express.urlencoded`, and CORS locked to the client origin. +- Mutating API requests require a signed, session-bound CSRF token from `GET /api/csrf-token`. + Login and registration remain exempt because no authenticated session exists yet. The client + adds the token header automatically; maintenance endpoints are limited to 30 requests per + client per 15 minutes. - Added a new model called **`MaintenanceRequest`** with the attributes: `roomNumber`, `category`, `description`, `status`, `author`. - Added the **Maintenance controller** with the following routes: @@ -113,10 +117,8 @@ JWT_EXPIRES_IN=7d For this you will **not** need Postman — a `CSRF` attack is carried out by a webpage, not a crafted API client. The `attacker/` folder is a small, separate Express server that plays the role of a -malicious site the victim visits. Look through the `Flow.md` Markdown file for the detailed steps -to simulate both attacks (register a victim, run the attacker server, open its link, and watch a -maintenance request get silently filed in the victim's name — then click through and watch the same -page flood the API with requests). +malicious site the victim visits. Follow [Flow.md](./Flow.md) to verify that its forged write is +rejected and that its flood eventually receives `429 Too Many Requests`. Please note that the demo works over `http://localhost` because the attacker's port (`localhost:1337`) and the API's port (`localhost:4000`) are the **same site** — a cookie's @@ -131,42 +133,23 @@ file). After reading the file, read the next section. View Task -The attack in the `Flow.md` file works for two independent reasons. +The demonstration in `Flow.md` shows two attacks that the application now blocks. -First, the write endpoint `POST /api/maintenance` (`maintenanceController.js` + -`routes/maintenance.js`) trusts the session cookie **alone**: there is no proof the request -actually originated from our own app — no anti-`CSRF` token, no check of intent. Since the browser -attaches that cookie to any cross-site request, any page the victim visits can forge a request in -their name. +First, state-changing requests require a signed, session-bound anti-CSRF token in addition to the +session cookie. `GET /api/csrf-token` issues it to authenticated clients, and `csrf-csrf` rejects +forged writes without the matching `x-csrf-token` header. -Second, none of the maintenance endpoints place **any limit on how often one client may call -them**, so the attacker's page can flood `GET /api/maintenance` with unlimited requests and -exhaust the server — a `DoS`. +Second, `express-rate-limit` caps each client's maintenance traffic at 30 requests per 15 minutes. +Excess calls receive `429 Too Many Requests`. -**Fix both.** Make the maintenance feature safe while keeping its legitimate behavior, then re-run -the attacks in `Flow.md` and confirm they now fail (the forged request should return `403` and -leave the data unchanged, and the flood should be refused with `429`). - -- **CSRF:** issue a secret, per-session **CSRF token** that the attacker's site cannot read or - guess; require that token on every state-changing request; leave "safe" `GET` requests and the - pre-auth routes (login/register, which run before a session exists) exempt; and echo the token - from the client on each write. Use the **`csrf-csrf`** package (the double-submit-cookie pattern; - the old `csurf` is deprecated). You are expected to understand **why** `CORS` and `SameSite` - cookies do not by themselves close this hole, and to think carefully about which requests need - protection and which must stay exempt. -- **DoS:** throttle the feature so one client cannot flood it. Use the **`express-rate-limit`** - package to return `429 Too Many Requests` once a client exceeds a sensible limit in a time - window. - -A test suite ships with the project. Run it from the project root: +A test suite is available through the project setup. Run it from the project root: ```bash npm install # first time only npm test ``` -The `CSRF` and `DoS` tests describe the **secure** behavior and are **expected to FAIL** in this -project (the suite is red). Your job is to make them green by applying the fix. +The CSRF and DoS tests verify the protections above and should pass. ### Custom Configurations diff --git a/babel.config.cjs b/babel.config.cjs new file mode 100644 index 0000000..55bbc87 --- /dev/null +++ b/babel.config.cjs @@ -0,0 +1,5 @@ +module.exports = { + presets: [ + ['@babel/preset-env', { targets: { node: 'current' } }] + ] +} diff --git a/client/src/api.js b/client/src/api.js index 0aacdce..b51816c 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -1,10 +1,43 @@ 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. export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +const safeMethods = new Set(['get', 'head', 'options']) +const preAuthPaths = new Set(['/auth/login', '/auth/register']) +const sessionPaths = new Set([...preAuthPaths, '/auth/logout']) +let csrfTokenPromise + +api.interceptors.request.use(async config => { + const method = (config.method || 'get').toLowerCase() + const path = (config.url || '').split('?')[0] + + if (safeMethods.has(method) || preAuthPaths.has(path)) return config + + if (!csrfTokenPromise) { + csrfTokenPromise = api.get('/csrf-token') + .then(res => { + const token = res.data?.csrfToken + if (typeof token !== 'string' || !token) { + throw new Error('CSRF token endpoint returned no token') + } + return token + }) + .catch(error => { + csrfTokenPromise = undefined + throw error + }) + } + + const csrfToken = await csrfTokenPromise + config.headers.set('x-csrf-token', csrfToken) + return config +}) + +api.interceptors.response.use(response => { + const path = (response.config.url || '').split('?')[0] + if (sessionPaths.has(path)) csrfTokenPromise = undefined + return response +}) diff --git a/jest.config.cjs b/jest.config.cjs new file mode 100644 index 0000000..3e256a4 --- /dev/null +++ b/jest.config.cjs @@ -0,0 +1,20 @@ +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..fe3567a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6322,6 +6322,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 +6882,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 +7548,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", @@ -11962,8 +11999,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/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..93eba92 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -2,10 +2,12 @@ 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'; import maintenanceRoutes from './routes/maintenance.js'; +import { requireAuth } from './middleware/auth.js'; const app = express(); @@ -19,7 +21,37 @@ app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(cookieParser()); +const { doubleCsrfProtection, generateCsrfToken } = doubleCsrf({ + getSecret: () => { + if (!process.env.CSRF_SECRET) { + throw new Error('CSRF_SECRET must be set'); + } + return process.env.CSRF_SECRET; + }, + getSessionIdentifier: req => req.cookies?.token || 'unauthenticated', + cookieName: 'csrf-token', + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/' + }, + ignoredMethods: ['GET', 'HEAD', 'OPTIONS'], + getCsrfTokenFromRequest: req => req.headers['x-csrf-token'] +}); + +app.use((req, res, next) => { + const isPreAuthRequest = req.method === 'POST' && + ['/api/auth/login', '/api/auth/register'].includes(req.path); + + if (isPreAuthRequest) return next(); + return doubleCsrfProtection(req, res, next); +}); + app.get('/api/health', (req, res) => res.json({ ok: true })); +app.get('/api/csrf-token', requireAuth, (req, res) => { + res.json({ csrfToken: generateCsrfToken(req, res) }); +}); app.use('/api/auth', authRoutes); app.use('/api/bookings', bookingRoutes); diff --git a/server/src/controllers/authController.js b/server/src/controllers/authController.js index 4644f3e..099bade 100644 --- a/server/src/controllers/authController.js +++ b/server/src/controllers/authController.js @@ -1,6 +1,7 @@ import jwt from 'jsonwebtoken'; import bcrypt from 'bcryptjs'; import Joi from 'joi'; +import { randomUUID } from 'node:crypto'; import { User } from '../models/User.js'; // How long the auth cookie lives, in ms (mirrors JWT_EXPIRES_IN's default of 7d). @@ -79,7 +80,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/routes/maintenance.js b/server/src/routes/maintenance.js index dea0023..b044ae2 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,16 @@ 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(rateLimit({ + windowMs: 15 * 60 * 1000, + limit: 30, + standardHeaders: 'draft-8', + legacyHeaders: false, + message: { message: 'Too many maintenance requests. Please try again later.' } +})); + +// Reads remain public; all state-changing routes also pass the app-wide CSRF +// middleware, and writes require an authenticated user. 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); + }); +}); From dd4cd16a621333f2984bda22a688ca9f52393f99 Mon Sep 17 00:00:00 2001 From: miriamemad Date: Thu, 12 Nov 2026 16:09:44 +0200 Subject: [PATCH 2/2] Add GitHub Actions workflow for running tests --- .github/workflows/tests.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .github/workflows/tests.yml diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..911bd8e --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,27 @@ +name: Tests + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v4 + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + - name: Install dependencies + run: npm ci + - name: Run tests + run: npm test -- --runInBand