From 9a70ed51d69f283888e382cc2280c9d3252ff588 Mon Sep 17 00:00:00 2001 From: hamzaelsheikh Date: Thu, 12 Nov 2026 14:51:01 +0200 Subject: [PATCH 1/2] Fix CSRF and rate limit maintenance routes --- README.md | 1 + client/src/api.js | 36 +++++++++++++++++ client/src/context/AuthContext.jsx | 5 ++- package-lock.json | 39 +++++++++++++++++++ server/package.json | 2 + server/src/app.js | 12 +++++- server/src/controllers/authController.js | 3 +- server/src/middleware/csrf.js | 17 ++++++++ server/src/middleware/maintenanceRateLimit.js | 9 +++++ server/src/routes/auth.js | 3 +- server/src/routes/bookings.js | 7 ++-- server/src/routes/maintenance.js | 9 +++-- 12 files changed, 133 insertions(+), 10 deletions(-) create mode 100644 server/src/middleware/csrf.js create mode 100644 server/src/middleware/maintenanceRateLimit.js diff --git a/README.md b/README.md index 3c31cd4..d735f5d 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=use-a-separate-long-random-secret-in-production ``` ## What was added on top of Task 3 diff --git a/client/src/api.js b/client/src/api.js index 0aacdce..ca8302c 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -8,3 +8,39 @@ export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +let csrfToken = null +let csrfTokenRequest = null + +const protectedWrite = (config) => { + const method = (config.method || 'get').toLowerCase() + const url = config.url || '' + const isMutation = ['post', 'patch', 'put', 'delete'].includes(method) + const isPreAuth = url.includes('/auth/login') || url.includes('/auth/register') + return isMutation && !isPreAuth && !url.includes('/csrf-token') +} + +async function getCsrfToken() { + if (csrfToken) return csrfToken + if (!csrfTokenRequest) { + csrfTokenRequest = api.get('/csrf-token') + .then(({ data }) => { + csrfToken = data.csrfToken + return csrfToken + }) + .finally(() => { csrfTokenRequest = null }) + } + return csrfTokenRequest +} + +api.interceptors.request.use(async (config) => { + if (!protectedWrite(config)) return config + const token = await getCsrfToken() + config.headers = config.headers || {} + config.headers['x-csrf-token'] = token + return config +}) + +export function clearCsrfToken() { + csrfToken = null +} diff --git a/client/src/context/AuthContext.jsx b/client/src/context/AuthContext.jsx index 3875abd..5e38f32 100644 --- a/client/src/context/AuthContext.jsx +++ b/client/src/context/AuthContext.jsx @@ -1,5 +1,5 @@ import { createContext, useCallback, useContext, useEffect, useState } from 'react' -import { api } from '../api' +import { api, clearCsrfToken } from '../api' const AuthContext = createContext(null) @@ -19,17 +19,20 @@ export function AuthProvider({ children }) { const login = useCallback(async (email, password) => { // The server sets the auth cookie in its response; nothing to store here. const res = await api.post('/auth/login', { email, password }) + clearCsrfToken() setUser(res.data.user) }, []) const register = useCallback(async (name, email, password) => { const res = await api.post('/auth/register', { name, email, password }) + clearCsrfToken() setUser(res.data.user) }, []) const logout = useCallback(async () => { // Ask the server to clear the auth cookie, then reset local state. try { await api.post('/auth/logout') } catch { /* ignore */ } + clearCsrfToken() setUser(null) window.location.href = '/login' }, []) 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..071cec1 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -6,13 +6,19 @@ 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'; +import { requireAuth } from './middleware/auth.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(cors({ + origin: process.env.CLIENT_ORIGIN || 'http://localhost:5175', + credentials: true, + allowedHeaders: ['Content-Type', 'X-CSRF-Token'] +})); 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. @@ -21,6 +27,10 @@ app.use(cookieParser()); 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); app.use('/api/users', userRoutes); diff --git a/server/src/controllers/authController.js b/server/src/controllers/authController.js index 4644f3e..5cf8043 100644 --- a/server/src/controllers/authController.js +++ b/server/src/controllers/authController.js @@ -1,4 +1,5 @@ import jwt from 'jsonwebtoken'; +import { randomUUID } from 'crypto'; import bcrypt from 'bcryptjs'; import Joi from 'joi'; import { User } from '../models/User.js'; @@ -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/middleware/csrf.js b/server/src/middleware/csrf.js new file mode 100644 index 0000000..24715c9 --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,17 @@ +import { doubleCsrf } from 'csrf-csrf'; + +export const { generateCsrfToken, doubleCsrfProtection } = doubleCsrf({ + // Resolve this at request time so test/bootstrap code can set environment + // variables before the first request, and use a dedicated secret in prod. + getSecret: () => process.env.CSRF_SECRET || process.env.JWT_SECRET, + getSessionIdentifier: (req) => req.cookies?.token || '', + cookieName: 'csrf-token', + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/' + }, + getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'], + ignoredMethods: ['GET', 'HEAD', 'OPTIONS'] +}); diff --git a/server/src/middleware/maintenanceRateLimit.js b/server/src/middleware/maintenanceRateLimit.js new file mode 100644 index 0000000..c0cb2df --- /dev/null +++ b/server/src/middleware/maintenanceRateLimit.js @@ -0,0 +1,9 @@ +import { rateLimit } from 'express-rate-limit'; + +export const maintenanceRateLimit = rateLimit({ + windowMs: 60 * 1000, + limit: 30, + standardHeaders: 'draft-8', + legacyHeaders: false, + message: { message: 'Too many maintenance requests. Please try again in a minute.' } +}); diff --git a/server/src/routes/auth.js b/server/src/routes/auth.js index c80d6a0..eb8d714 100644 --- a/server/src/routes/auth.js +++ b/server/src/routes/auth.js @@ -1,12 +1,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/bookings.js b/server/src/routes/bookings.js index 63b0a93..25468d0 100644 --- a/server/src/routes/bookings.js +++ b/server/src/routes/bookings.js @@ -1,5 +1,6 @@ import { Router } from 'express'; import { requireAuth } from '../middleware/auth.js'; +import { doubleCsrfProtection } from '../middleware/csrf.js'; import { getAllBookings, getBooking, @@ -13,8 +14,8 @@ const router = Router(); // Reading is public; writing requires a logged-in user. router.get('/', getAllBookings); router.get('/:id', getBooking); -router.post('/', requireAuth, createBooking); -router.patch('/:id', requireAuth, updateBooking); -router.delete('/:id', requireAuth, deleteBooking); +router.post('/', requireAuth, doubleCsrfProtection, createBooking); +router.patch('/:id', requireAuth, doubleCsrfProtection, updateBooking); +router.delete('/:id', requireAuth, doubleCsrfProtection, deleteBooking); export default router; diff --git a/server/src/routes/maintenance.js b/server/src/routes/maintenance.js index dea0023..e448bed 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 { maintenanceRateLimit } from '../middleware/maintenanceRateLimit.js'; import { getAllRequests, getRequest, @@ -20,10 +22,11 @@ const router = Router(); // 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(maintenanceRateLimit); router.get('/', getAllRequests); router.get('/:id', getRequest); -router.post('/', requireAuth, createRequest); -router.patch('/:id', requireAuth, updateRequest); -router.delete('/:id', requireAuth, deleteRequest); +router.post('/', requireAuth, doubleCsrfProtection, createRequest); +router.patch('/:id', requireAuth, doubleCsrfProtection, updateRequest); +router.delete('/:id', requireAuth, doubleCsrfProtection, deleteRequest); export default router; From 7679991e8be6dd34437a25d5f4635356cb3b42c9 Mon Sep 17 00:00:00 2001 From: hamzaelsheikh Date: Thu, 12 Nov 2026 15:44:27 +0200 Subject: [PATCH 2/2] Harden CSRF coverage and add CI verification --- .github/workflows/ci.yml | 32 +++++++++++ babel.config.cjs | 4 ++ client/src/api.js | 6 +-- jest.config.cjs | 16 ++++++ server/src/controllers/authController.js | 2 +- server/src/routes/maintenance.js | 12 +---- server/src/routes/users.js | 8 ++- tests/client/csrf.test.js | 32 +++++++++++ tests/server/csrf.test.js | 68 ++++++++++++++++++++++++ tests/server/dos.test.js | 35 ++++++++++++ 10 files changed, 198 insertions(+), 17 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..f187c44 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,32 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + verify: + runs-on: ubuntu-latest + timeout-minutes: 15 + + steps: + - name: Check out source + 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: Build client + run: npm run build --workspace client + + - name: Run test suite + run: npm test -- --runInBand diff --git a/babel.config.cjs b/babel.config.cjs new file mode 100644 index 0000000..5358a07 --- /dev/null +++ b/babel.config.cjs @@ -0,0 +1,4 @@ +// Lets Jest load the project's ESM source 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 ca8302c..2d4ba92 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -1,9 +1,7 @@ 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. +// The auth cookie is sent automatically. The interceptor below adds the +// separate anti-CSRF proof required for authenticated state-changing requests. export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true diff --git a/jest.config.cjs b/jest.config.cjs new file mode 100644 index 0000000..26eb695 --- /dev/null +++ b/jest.config.cjs @@ -0,0 +1,16 @@ +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/server/src/controllers/authController.js b/server/src/controllers/authController.js index 5cf8043..e301f1b 100644 --- a/server/src/controllers/authController.js +++ b/server/src/controllers/authController.js @@ -14,7 +14,7 @@ function setAuthCookie(res, token) { res.cookie('token', token, { httpOnly: true, sameSite: 'lax', - secure: false, // true in production (HTTPS only) + secure: process.env.NODE_ENV === 'production', maxAge: COOKIE_MAX_AGE }); } diff --git a/server/src/routes/maintenance.js b/server/src/routes/maintenance.js index e448bed..0eb6827 100644 --- a/server/src/routes/maintenance.js +++ b/server/src/routes/maintenance.js @@ -12,16 +12,8 @@ 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. +// Reading is public. The whole feature is rate-limited, and authenticated +// writes additionally require a CSRF token before they reach the controller. router.use(maintenanceRateLimit); router.get('/', getAllRequests); router.get('/:id', getRequest); diff --git a/server/src/routes/users.js b/server/src/routes/users.js index 2026add..12aa325 100644 --- a/server/src/routes/users.js +++ b/server/src/routes/users.js @@ -1,5 +1,6 @@ import { Router } from 'express'; import { requireAuth } from '../middleware/auth.js'; +import { doubleCsrfProtection } from '../middleware/csrf.js'; import { getAllUsers, getUser, @@ -12,7 +13,10 @@ 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); +// Every authenticated state change requires the same CSRF proof as bookings +// and maintenance requests. Login and registration are intentionally exempt +// because a session does not exist yet. +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..40151f4 --- /dev/null +++ b/tests/client/csrf.test.js @@ -0,0 +1,32 @@ +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('sends credentials with requests', () => { + expect(api.defaults.withCredentials).toBe(true); + }); + + test('attaches a CSRF token to mutations', async () => { + await api.post('/maintenance', { roomNumber: 'B2-104', category: 'plumbing', description: 'Leaking tap' }); + const sent = captured.find((config) => (config.url || '').includes('/maintenance')); + 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..61f2053 --- /dev/null +++ b/tests/server/csrf.test.js @@ -0,0 +1,68 @@ +import request from 'supertest'; +import mongoose from 'mongoose'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import app from '../../server/src/app.js'; + +let mongo; +let counter = 0; + +// The first run may download MongoDB's platform binary, which is much slower +// than Jest's default timeout on constrained connections. +jest.setTimeout(10 * 60 * 1000); + +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()); +}); + +afterAll(async () => { + await mongoose.disconnect(); + await mongo?.stop(); +}); + +function cookiePairs(setCookie) { + return (setCookie || []).map((cookie) => cookie.split(';')[0]); +} + +async function registerUser() { + counter += 1; + const response = await request(app) + .post('/api/auth/register') + .send({ name: 'Victim', email: `victim${Date.now()}_${counter}@test.dev`, password: 'secret123' }); + expect(response.status).toBe(201); + return cookiePairs(response.headers['set-cookie']); +} + +describe('Maintenance requests — CSRF protection', () => { + test('accepts an authenticated request carrying a valid CSRF token', async () => { + let cookies = await registerUser(); + const tokenResponse = await request(app).get('/api/csrf-token').set('Cookie', cookies.join('; ')); + expect(tokenResponse.status).toBe(200); + cookies = [...cookies, ...cookiePairs(tokenResponse.headers['set-cookie'])]; + + const response = await request(app) + .post('/api/maintenance') + .set('Cookie', cookies.join('; ')) + .set('x-csrf-token', tokenResponse.body.csrfToken) + .send({ roomNumber: 'B2-104', category: 'plumbing', description: 'Leaking tap' }); + + expect(response.status).toBe(201); + expect(response.body.request.description).toBe('Leaking tap'); + }); + + test('rejects a forged request that has only the victim auth cookie', async () => { + const authCookies = await registerUser(); + const response = 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(response.status).toBe(403); + const list = await request(app).get('/api/maintenance'); + expect(list.body.requests.find((requestItem) => requestItem.description === 'Forged by attacker via CSRF')).toBeUndefined(); + }); +}); diff --git a/tests/server/dos.test.js b/tests/server/dos.test.js new file mode 100644 index 0000000..cabe624 --- /dev/null +++ b/tests/server/dos.test.js @@ -0,0 +1,35 @@ +import request from 'supertest'; +import mongoose from 'mongoose'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import app from '../../server/src/app.js'; + +let mongo; + +// The first run may download MongoDB's platform binary, which is much slower +// than Jest's default timeout on constrained connections. +jest.setTimeout(10 * 60 * 1000); + +beforeAll(async () => { + process.env.JWT_SECRET = 'test-secret'; + process.env.CSRF_SECRET = 'test-csrf-secret'; + mongo = await MongoMemoryServer.create(); + await mongoose.connect(mongo.getUri()); +}); + +afterAll(async () => { + await mongoose.disconnect(); + await mongo?.stop(); +}); + +describe('Maintenance requests — DoS protection', () => { + test('serves normal traffic but throttles a single-client flood', async () => { + const statuses = []; + for (let index = 0; index < 40; index += 1) { + const response = await request(app).get('/api/maintenance'); + statuses.push(response.status); + } + + expect(statuses).toContain(200); + expect(statuses).toContain(429); + }); +});