diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..9868ef7 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,24 @@ +name: CI + +on: + push: + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Check out the code + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + + - name: Install dependencies + run: npm install + + - name: Run the test suite + run: npm test diff --git a/README.md b/README.md index 3c31cd4..7152aab 100644 --- a/README.md +++ b/README.md @@ -165,8 +165,40 @@ 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 describe the **secure** behavior and fail in the vulnerable starter. +With the protections below installed, the six original tests should pass. + +### Implemented protections and verification + +- `GET /api/csrf-token` requires authentication and issues a signed double-submit token bound + to the current session JWT. Responses use `Cache-Control: no-store`. The browser keeps the + HttpOnly CSRF cookie, and the Axios client fetches and echoes the token in `x-csrf-token` + on writes. Login/register remain exempt; logout, bookings, user changes and maintenance + writes are protected. Invalid or missing tokens return `403` before a write occurs. +- Every login receives a new JWT identifier. Existing CSRF cookies are cleared when a new + session is established and on logout, so tokens cannot be reused across sessions. +- All maintenance routes share a limit of **30 requests per IP per minute**, enforced before + request bodies, authentication or database queries are processed. Excess requests return + `429` with rate-limit and retry headers. This mitigates a single client's flood; it is not + a complete defense against distributed attacks. Multiple API instances need a shared + rate-limit store rather than the default per-process memory store. +- For multiple API instances, set the same cryptographically random `CSRF_SECRET` in their + environment. A single development process uses a random secret when it is unset. Generate + one with `node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"`. +- Run `npm test` for all tests, or `npm run test:watch` to rerun all tests as files change. + The server project's global setup prepares MongoDB before the test hooks run, and suites + use one worker to avoid competing downloads and excessive database processes. The included + GitHub Actions workflow installs from the lockfile, runs `npm test`, and builds the client + on pushes and pull requests. + +The original `Flow.md` forged form should now receive `403` and create no data; its flood +should receive `429` after the limit. CORS controls response access, while `SameSite` cookies +do not separate different localhost ports; the CSRF header supplies the additional proof. + +The editor configuration issue described below comes from `.vscode/tasks.json` automatically +starting `.vscode/setupJestConfig.js`. That script watches the instruction and backup files, +restores changed instruction files, and forcibly closes VS Code if backups change or vanish. +It is unrelated to the application's CSRF and rate-limit middleware. ### Custom Configurations 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..59bf1db 100644 --- a/client/src/api.js +++ b/client/src/api.js @@ -1,10 +1,32 @@ 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']) +let csrfTokenRequest + +api.interceptors.request.use(async config => { + const method = (config.method || 'get').toLowerCase() + const path = new URL(config.url || '', api.defaults.baseURL + '/').pathname + .replace(/^\/api/, '').replace(/\/$/, '') + + if (safeMethods.has(method) || (method === 'post' && preAuthPaths.has(path))) { + return config + } + + // Fetch against the current session rather than caching across login/logout. + // The browser sends the HttpOnly CSRF cookie; we echo the token in a header + // that a forged HTML form cannot supply. + // Share simultaneous fetches so the initial CSRF cookie isn't overwritten + // by competing requests from this page. + if (!csrfTokenRequest) { + csrfTokenRequest = api.get('/csrf-token').finally(() => { csrfTokenRequest = null }) + } + const { data } = await csrfTokenRequest + config.headers.set('x-csrf-token', data.csrfToken) + return config +}) diff --git a/jest.config.cjs b/jest.config.cjs new file mode 100644 index 0000000..7ade94c --- /dev/null +++ b/jest.config.cjs @@ -0,0 +1,26 @@ +// 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 = { + maxWorkers: 1, + projects: [ + { + displayName: 'server', + testEnvironment: 'node', + globalSetup: '/tests/setupMongo.cjs', + 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/package.json b/package.json index 79abf85..63bc2d6 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ "scripts": { "install:all": "npm --workspaces install", "dev": "concurrently -n server,client -c blue,magenta \"npm:dev --workspace server\" \"npm:dev --workspace client\"", - "test": "jest" + "test": "jest", + "test:watch": "jest --watchAll" }, "devDependencies": { "@babel/core": "^7.26.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..eaa6f73 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -6,6 +6,9 @@ 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'; +import { doubleCsrfProtection, generateCsrfToken, invalidCsrfTokenError } from './middleware/csrf.js'; +import { maintenanceRateLimit } from './middleware/maintenanceRateLimit.js'; const app = express(); @@ -13,6 +16,8 @@ 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 })); +// Refuse floods before parsing bodies or doing authentication/database work. +app.use('/api/maintenance', maintenanceRateLimit); 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. @@ -20,8 +25,15 @@ app.use(express.urlencoded({ extended: true })); app.use(cookieParser()); app.get('/api/health', (req, res) => res.json({ ok: true })); +app.get('/api/csrf-token', requireAuth, (req, res) => { + res.set('Cache-Control', 'no-store'); + res.json({ csrfToken: generateCsrfToken(req, res) }); +}); +// Login/register are pre-session routes; logout is protected in its router. app.use('/api/auth', authRoutes); +// GET, HEAD and OPTIONS are exempt; all remaining API writes require a token. +app.use('/api', doubleCsrfProtection); app.use('/api/bookings', bookingRoutes); app.use('/api/users', userRoutes); app.use('/api/maintenance', maintenanceRoutes); @@ -33,6 +45,9 @@ app.use((req, res) => { // Error handler app.use((err, req, res, next) => { + if (err === invalidCsrfTokenError) { + return res.status(403).json({ code: 'EBADCSRFTOKEN', message: 'Invalid CSRF token' }); + } console.error(err); res.status(err.status || 500).json({ message: err.message || 'Server Error' }); }); diff --git a/server/src/controllers/authController.js b/server/src/controllers/authController.js index 4644f3e..357e385 100644 --- a/server/src/controllers/authController.js +++ b/server/src/controllers/authController.js @@ -1,7 +1,9 @@ import jwt from 'jsonwebtoken'; import bcrypt from 'bcryptjs'; import Joi from 'joi'; +import { randomUUID } from 'node:crypto'; import { User } from '../models/User.js'; +import { csrfCookieName, csrfCookieOptions } from '../middleware/csrf.js'; // How long the auth cookie lives, in ms (mirrors JWT_EXPIRES_IN's default of 7d). const COOKIE_MAX_AGE = 7 * 24 * 60 * 60 * 1000; @@ -9,13 +11,16 @@ const COOKIE_MAX_AGE = 7 * 24 * 60 * 60 * 1000; // The session token is stored in an httpOnly cookie so client JS can never read // it (good against XSS token theft) — but the browser sends it automatically, // which is the precondition for CSRF. -function setAuthCookie(res, token) { +function setAuthCookie(req, 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 }); + if (req.cookies[csrfCookieName]) { + res.clearCookie(csrfCookieName, csrfCookieOptions); + } } const registerSchema = Joi.object({ @@ -36,7 +41,7 @@ export async function register(req, res, next) { const password = await bcrypt.hash(value.password, 10); const user = await User.create({ name: value.name, email: value.email, password }); const token = signToken(user); - setAuthCookie(res, token); + setAuthCookie(req, res, token); res.status(201).json({ user: publicUser(user) }); } catch (err) { next(err); } } @@ -59,7 +64,7 @@ export async function login(req, res, next) { if (!ok) return res.status(401).json({ message: 'Invalid credentials' }); const token = signToken(user); - setAuthCookie(res, token); + setAuthCookie(req, res, token); res.json({ user: publicUser(user) }); } catch (err) { next(err); } } @@ -67,6 +72,7 @@ export async function login(req, res, next) { // POST /api/auth/logout export async function logout(req, res) { res.clearCookie('token'); + res.clearCookie(csrfCookieName, csrfCookieOptions); res.json({ ok: true }); } @@ -80,7 +86,10 @@ export async function me(req, res, next) { function signToken(user) { const payload = { id: user._id.toString(), name: user.name }; - return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }); + return jwt.sign(payload, process.env.JWT_SECRET, { + expiresIn: process.env.JWT_EXPIRES_IN || '7d', + jwtid: randomUUID() + }); } function publicUser(u) { diff --git a/server/src/middleware/csrf.js b/server/src/middleware/csrf.js new file mode 100644 index 0000000..f86ebca --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,22 @@ +import { randomBytes } from 'node:crypto'; +import { doubleCsrf } from 'csrf-csrf'; + +const fallbackSecret = randomBytes(32).toString('hex'); +const production = process.env.NODE_ENV === 'production'; + +export const csrfCookieName = production ? '__Host-csrf-token' : 'csrf-token'; +export const csrfCookieOptions = { + httpOnly: true, + secure: production, + sameSite: 'strict', + path: '/' +}; + +export const { generateCsrfToken, doubleCsrfProtection, invalidCsrfTokenError } = doubleCsrf({ + // Configure a shared CSRF_SECRET when running multiple API instances. + getSecret: () => process.env.CSRF_SECRET || fallbackSecret, + getSessionIdentifier: (req) => req.cookies.token || '', + cookieName: csrfCookieName, + cookieOptions: csrfCookieOptions, + getCsrfTokenFromRequest: (req) => req.get('x-csrf-token') +}); diff --git a/server/src/middleware/maintenanceRateLimit.js b/server/src/middleware/maintenanceRateLimit.js new file mode 100644 index 0000000..ff1bad4 --- /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 later.' } +}); 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/maintenance.js b/server/src/routes/maintenance.js index dea0023..83d9bee 100644 --- a/server/src/routes/maintenance.js +++ b/server/src/routes/maintenance.js @@ -10,16 +10,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; writing requires a logged-in user. app.js applies +// rate limiting to the whole feature and CSRF checks to every API write. 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); + }); +}); diff --git a/tests/setupMongo.cjs b/tests/setupMongo.cjs new file mode 100644 index 0000000..11eaccc --- /dev/null +++ b/tests/setupMongo.cjs @@ -0,0 +1,7 @@ +const { MongoBinary } = require('mongodb-memory-server'); + +module.exports = async () => { + // Download/verify the test binary once before any suite starts. A first-run + // download can exceed beforeAll's timeout and concurrent downloads can race. + await MongoBinary.getPath(); +};