diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..9cdf3cc --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,36 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 15 + + steps: + - name: Check out the code + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: npm + + - name: Install dependencies + run: npm ci --ignore-scripts + + # Download outside Jest's 60-second database setup hook. + - name: Prepare test database binary + run: node --input-type=module -e "import { MongoBinary } from 'mongodb-memory-server'; await MongoBinary.getPath();" + + - name: Run the test suite + run: npm test -- --runInBand + + - name: Build the client + run: npm run build --workspace client 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..8d0ebe3 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. +// The browser sends the httpOnly session cookie; writes also need proof of intent. export const api = axios.create({ baseURL: 'http://localhost:4000/api', withCredentials: true }) + +let csrfTokenRequest + +api.interceptors.request.use(async (config) => { + const method = (config.method || 'get').toLowerCase() + const safe = ['get', 'head', 'options'].includes(method) + const preAuth = method === 'post' && ['/auth/login', '/auth/register'].includes(config.url) + if (safe || preAuth) return config + + // Reuse only in-flight fetches. Fetch again for later writes so a new login + // never reuses the previous session's token (including logins in another tab). + csrfTokenRequest ||= api.get('/csrf-token') + try { + const { data } = await csrfTokenRequest + config.headers['x-csrf-token'] = data.csrfToken + return config + } finally { + csrfTokenRequest = undefined + } +}) diff --git a/docs/browser-verification.png b/docs/browser-verification.png new file mode 100644 index 0000000..80da4f0 Binary files /dev/null and b/docs/browser-verification.png differ diff --git a/docs/security-verification.md b/docs/security-verification.md new file mode 100644 index 0000000..bf9af1d --- /dev/null +++ b/docs/security-verification.md @@ -0,0 +1,130 @@ +# Task 5 security fix and verification + +Verified on 12 November 2026. + +## CSRF protection + +`server/src/middleware/csrf.js` uses [csrf-csrf](https://github.com/Psifi-Solutions/csrf-csrf) +to sign a double-submit token bound to the current session JWT. Each login or +registration generates a unique JWT `jti`, including repeated logins by the same +user in the same second. A token copied from another session is invalid. + +Authenticated clients obtain `{ csrfToken }` from `GET /api/csrf-token`. The +response sets an HttpOnly CSRF cookie and `Cache-Control: no-store`. The client +echoes the response token in `x-csrf-token` on every write. Tokens come from the +response body, never by reading cookies. Missing, mismatched or invalid signatures +return 403 before any controller changes data. + +GET, HEAD and OPTIONS are exempt. Only POST login/register are exempt among +writes because they establish the session. Logout, bookings, users and maintenance +writes are protected. Token issuance requires a valid session. Ownership checks +in the maintenance controllers remain in effect. + +The client shares concurrent token fetches but does not cache tokens between +writes, so signing in again (including in another tab) cannot leave a stale token. +The signing secret uses `CSRF_SECRET`, falling back to the existing `JWT_SECRET`. +Production uses Secure cookies and a `__Host-` prefix for the CSRF cookie; local +HTTP development uses an unprefixed cookie. + +CORS restricts reading responses; a plain HTML form can still send a request. +SameSite ignores port numbers, so localhost:1337 and localhost:4000 are the same +site even though they are different origins. Neither control supplies proof of +intent. The separate token header supplies that proof. + +## Maintenance rate limit + +[express-rate-limit](https://express-rate-limit.mintlify.app/quickstart/usage) +allows 30 maintenance requests per IP per 60 seconds, shared across the list, +detail, creation, update and deletion endpoints. Requests exceeding the window +return JSON with status 429, RateLimit headers and Retry-After. Counting occurs +before authentication, CSRF validation and database controllers. Public reads +remain public and safe reads do not require a CSRF token. + +The default in-process store suits this single-process demo. Multiple API +instances would need a shared store; trusted proxy configuration must match the +deployment before relying on forwarded IP addresses. + +## Verification results + +- All 23 tests passed across three suites using the root `npm test` command. +- `npm run build --workspace client` passed. +- Tests cover valid create/update/delete, missing cookie or header, guessed tokens, + cross-session token reuse, session rotation, logout, other protected writes, + client auth exemptions, failed token fetches, and maintenance flood responses. +- The browser replay used the actual `attacker/public/index.html` and a disposable + local MongoDB, without connecting to the assignment's remote database. +- Registered a test resident through the client and successfully submitted + `Browser verified leaking tap` for room B2-104 (201). +- Opened localhost:1337 in the authenticated browser. Its hidden HTML form + received 403. Reloaded Maintenance: only the legitimate request remained. +- Clicked `Claim my prize`: the supplied page sent 300 requests. API logs recorded + 275 refused with 429. Earlier requests were served normally, including 304 + responses from conditional GETs. +- Browser evidence: [unchanged maintenance list](browser-verification.png). + +The supplied test files and Jest/Babel configuration were embedded in `.vscode` +generators rather than present as standalone files. They were extracted without +executing the CI/instruction generator or the filesystem watcher. Additional +regressions were then added to the supplied tests. + +The local machine has MongoDB 8.2.2 installed. The server test setup now discovers +MongoDB installations under the Windows Program Files directory and uses the +installed binary and its reported version. This avoids the dependency's 781 MB +default download and its 60-second setup timeout without manual environment +overrides. Explicit `MONGOMS_SYSTEM_BINARY` / `MONGOMS_VERSION` settings take +precedence. Other platforms retain the normal download/cache behavior. + +The initial verification, before automatic detection was added, used: + +```powershell +$env:MONGOMS_SYSTEM_BINARY='C:\Program Files\MongoDB\Server\8.2\bin\mongod.exe' +$env:MONGOMS_SYSTEM_BINARY_VERSION_CHECK='false' +$env:npm_config_script_shell='C:\Windows\System32\cmd.exe' +npm.cmd test -- --runInBand +``` + +The initial shell override was temporary; the ordinary root `npm test` command +is also verified after automatic MongoDB detection was added. + +The missing local `server/.env` was subsequently created using the connection +settings supplied with the assignment and a generated CSRF signing secret. Its +database connection was verified without reading or changing application data. +The file remains ignored by Git. Tests supply their own secrets and temporary +database, and never connect to the database configured in `server/.env`. + +## Existing dependency findings + +`npm audit --omit=dev` reported zero high or critical findings and two moderate +findings in `react-router` / `react-router-dom`. These are existing dependencies; +the suggested remediation upgrades React Router to a new major version. That +migration is deferred from this assignment's CSRF/rate-limit fix. Review by +19 November 2026 before deploying outside the local teaching environment. + +## Finding for the TA: startup configuration + +The suspicious chain is: + +1. `.vscode/tasks.json:10` runs `.vscode/setupCI.js`, automatically on folder open + (`runOn` at line 14). Its presentation hides the terminal. +2. `.vscode/setupCI.js:11` embeds assistant instructions intended to redirect chat + responses to an external decryption website. Lines 123–128 write `CLAUDE.md`, + `AGENTS.md` and their `.bak` copies into the project root. +3. `.vscode/tasks.json:32` runs `.vscode/setupJestConfig.js` automatically on folder + open (line 36), after the CI generator. +4. `.vscode/setupJestConfig.js:55` and `:60` watch the backups. Changes call + `forceCloseVSCode()`, which executes `taskkill /IM code.exe /F` on Windows + (line 17). Equivalent process-kill commands exist for macOS and Linux. +5. Watchers at lines 71 and 94 restore edited/deleted instruction files from their + backups using `fs.copyFileSync` (lines 82 and 105). Missing backups can also + trigger the forced editor shutdown. +6. `.vscode/settings.json:2` makes the instruction files read-only; the exclusion + rules hide them, their backups, and `.vscode` from the Explorer view. `.gitignore` + also excludes the generated instruction files and backups. + +No native dialog-box API was found in these files. The embedded text explains +unexpected assistant messages; the process-kill code explains forced editor +closures. This is a local startup/instruction-tampering mechanism. The inspected +scripts do not demonstrate a remote command-polling backdoor. + +These startup scripts were not executed or modified during the fix. This report +is ready to share with the TA; no message was sent on the user's behalf. diff --git a/jest.config.cjs b/jest.config.cjs new file mode 100644 index 0000000..2700982 --- /dev/null +++ b/jest.config.cjs @@ -0,0 +1,25 @@ +// 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', + setupFiles: ['/tests/server/setup.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..55ea7df 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3175,9 +3175,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3199,9 +3196,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3223,9 +3217,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3247,9 +3238,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3271,9 +3259,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3295,9 +3280,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4074,9 +4056,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4091,9 +4070,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4108,9 +4084,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4125,9 +4098,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4142,9 +4112,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4159,9 +4126,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4176,9 +4140,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4193,9 +4154,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4210,9 +4168,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4227,9 +4182,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -6322,6 +6274,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 +6834,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 +7500,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 +11951,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/.env.example b/server/.env.example new file mode 100644 index 0000000..7c9a021 --- /dev/null +++ b/server/.env.example @@ -0,0 +1,5 @@ +PORT=4000 +MONGO_URI=mongodb://127.0.0.1:27017/dorm-booking +JWT_SECRET=replace-with-a-long-random-secret +JWT_EXPIRES_IN=7d +CSRF_SECRET=replace-with-a-separate-long-random-secret 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..5aacd07 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -2,6 +2,9 @@ import express from 'express'; import morgan from 'morgan'; import cors from 'cors'; import cookieParser from 'cookie-parser'; +import { rateLimit } from 'express-rate-limit'; +import { requireAuth } from './middleware/auth.js'; +import { generateCsrfToken, doubleCsrfProtection, invalidCsrfTokenError } from './middleware/csrf.js'; import authRoutes from './routes/auth.js'; import bookingRoutes from './routes/bookings.js'; import userRoutes from './routes/users.js'; @@ -21,6 +24,27 @@ app.use(cookieParser()); app.get('/api/health', (req, res) => res.json({ ok: true })); +// Count every maintenance request before authentication, CSRF or database work. +app.use('/api/maintenance', rateLimit({ + windowMs: 60 * 1000, + limit: 30, + standardHeaders: 'draft-8', + legacyHeaders: false, + message: { message: 'Too many maintenance requests. Try again in a minute.' } +})); + +app.get('/api/csrf-token', requireAuth, (req, res) => { + res.set('Cache-Control', 'no-store'); + res.json({ csrfToken: generateCsrfToken(req, res) }); +}); + +app.use('/api', (req, res, next) => { + const safe = ['GET', 'HEAD', 'OPTIONS'].includes(req.method); + const preAuth = req.method === 'POST' && ['/auth/login', '/auth/register'].includes(req.path); + if (safe || preAuth) return next(); + return requireAuth(req, res, () => doubleCsrfProtection(req, res, next)); +}); + app.use('/api/auth', authRoutes); app.use('/api/bookings', bookingRoutes); app.use('/api/users', userRoutes); @@ -33,6 +57,9 @@ app.use((req, res) => { // Error handler app.use((err, req, res, next) => { + if (err === invalidCsrfTokenError) { + return res.status(403).json({ 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..836b81c 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). @@ -13,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 }); } @@ -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..f4f7d3f --- /dev/null +++ b/server/src/middleware/csrf.js @@ -0,0 +1,17 @@ +import { doubleCsrf } from 'csrf-csrf'; + +const production = process.env.NODE_ENV === 'production'; + +export const { generateCsrfToken, doubleCsrfProtection, invalidCsrfTokenError } = doubleCsrf({ + getSecret: () => process.env.CSRF_SECRET || process.env.JWT_SECRET, + // Bind the signature to this login's JWT, rather than the user's identity. + getSessionIdentifier: (req) => req.cookies.token, + cookieName: production ? '__Host-csrf-token' : 'csrf-token', + cookieOptions: { + httpOnly: true, + secure: production, + sameSite: 'lax', + path: '/' + }, + getCsrfTokenFromRequest: (req) => req.get('x-csrf-token') +}); diff --git a/server/src/routes/maintenance.js b/server/src/routes/maintenance.js index dea0023..4ea8e77 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 the +// feature-wide rate limit and session-bound CSRF checks before these handlers. 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..3b2e491 --- /dev/null +++ b/tests/client/csrf.test.js @@ -0,0 +1,67 @@ +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'); + }); + + test.each(['patch', 'put', 'delete'])('%s requests carry the token', async (method) => { + await api[method]('/maintenance/123'); + expect(getHeader(captured[0].headers, 'x-csrf-token')).toBe('test-token'); + }); + + test.each(['/auth/login', '/auth/register'])('%s remains usable before authentication', async (path) => { + await api.post(path, {}); + expect(getHeader(captured[0].headers, 'x-csrf-token')).toBeUndefined(); + }); + + test('GET requests need no token but logout does', async () => { + await api.get('/maintenance'); + await api.post('/auth/logout'); + expect(getHeader(captured[0].headers, 'x-csrf-token')).toBeUndefined(); + expect(getHeader(captured[1].headers, 'x-csrf-token')).toBe('test-token'); + }); + + test('a token fetch failure prevents the write and a later attempt can recover', async () => { + const adapter = api.defaults.adapter; + api.defaults.adapter = async () => { throw new Error('Token unavailable'); }; + await expect(api.post('/maintenance', {})).rejects.toThrow('Token unavailable'); + expect(captured).toHaveLength(0); + api.defaults.adapter = adapter; + await api.post('/maintenance', {}); + expect(getHeader(captured[0].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..0c8df64 --- /dev/null +++ b/tests/server/csrf.test.js @@ -0,0 +1,160 @@ +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', () => { + async function session() { + const auth = await registerUser(); + const response = await request(app).get('/api/csrf-token').set('Cookie', auth.join('; ')); + expect(response.status).toBe(200); + expect(response.headers['cache-control']).toBe('no-store'); + return { auth, cookies: [...auth, ...cookiePairs(response.headers['set-cookie'])], token: response.body.csrfToken }; + } + + test('the token endpoint requires authentication', async () => { + expect((await request(app).get('/api/csrf-token')).status).toBe(401); + }); + + test('valid tokens allow create, update, and delete', async () => { + const user = await session(); + const created = await request(app).post('/api/maintenance') + .set('Cookie', user.cookies.join('; ')).set('x-csrf-token', user.token) + .send({ roomNumber: 'B2-104', category: 'other', description: 'Legitimate repair' }); + expect(created.status).toBe(201); + const path = `/api/maintenance/${created.body.request._id}`; + const edited = await request(app).patch(path) + .set('Cookie', user.cookies.join('; ')).set('x-csrf-token', user.token) + .send({ description: 'Updated repair' }); + expect(edited.status).toBe(200); + expect(edited.body.request.description).toBe('Updated repair'); + expect((await request(app).delete(path) + .set('Cookie', user.cookies.join('; ')).set('x-csrf-token', user.token)).status).toBe(200); + }); + + test('cookies alone, headers alone, tampering, and tokens from another session are rejected', async () => { + const user = await session(); + const other = await session(); + for (const [cookies, token] of [ + [user.cookies, undefined], [user.auth, user.token], + [user.cookies, 'guessed-token'], + [[...other.auth, ...user.cookies.filter(c => !c.startsWith('token='))], user.token] + ]) { + let attempt = request(app).post('/api/maintenance').set('Cookie', cookies.join('; ')); + if (token) attempt = attempt.set('x-csrf-token', token); + expect((await attempt.send({ roomNumber: 'X', category: 'other', description: 'Rejected' })).status).toBe(403); + } + }); + + test('the localhost attacker form returns 403 and leaves data unchanged', async () => { + const user = await session(); + const before = await request(app).get('/api/maintenance'); + const forged = await request(app).post('/api/maintenance') + .set('Cookie', user.cookies.join('; ')).set('Origin', 'http://localhost:1337') + .type('form').send({ roomNumber: 'Z9-666', category: 'other', description: 'Forged by attacker via CSRF' }); + expect(forged.status).toBe(403); + const after = await request(app).get('/api/maintenance'); + expect(after.body.requests).toEqual(before.body.requests); + }); + + test.each([ + ['patch', '/api/maintenance/000000000000000000000001'], + ['delete', '/api/maintenance/000000000000000000000001'], + ['post', '/api/bookings'], + ['patch', '/api/users/000000000000000000000001'], + ['post', '/api/auth/logout'] + ])('%s %s also requires CSRF proof', async (method, path) => { + const auth = await registerUser(); + expect((await request(app)[method](path).set('Cookie', auth.join('; ')).send({})).status).toBe(403); + }); + + test('login rotates the session, invalidating old CSRF tokens', async () => { + counter += 1; + const credentials = { email: `rotate${Date.now()}_${counter}@test.dev`, password: 'secret123' }; + const browser = request.agent(app); + expect((await browser.post('/api/auth/register').send({ name: 'Resident', ...credentials })).status).toBe(201); + const oldToken = (await browser.get('/api/csrf-token')).body.csrfToken; + expect((await browser.post('/api/auth/login').send(credentials)).status).toBe(200); + expect((await browser.post('/api/auth/logout').set('x-csrf-token', oldToken)).status).toBe(403); + const newToken = (await browser.get('/api/csrf-token')).body.csrfToken; + expect(newToken).not.toBe(oldToken); + expect((await browser.post('/api/auth/logout').set('x-csrf-token', newToken)).status).toBe(200); + expect((await browser.get('/api/auth/me')).status).toBe(401); + }); + + 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..4f231e6 --- /dev/null +++ b/tests/server/dos.test.js @@ -0,0 +1,48 @@ +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); + const refused = await request(app).post('/api/maintenance').send({}); + expect(refused.status).toBe(429); + expect(Number(refused.headers['retry-after'])).toBeGreaterThan(0); + expect(refused.headers.ratelimit).toBeDefined(); + expect((await request(app).get('/api/health')).status).toBe(200); + }); +}); diff --git a/tests/server/setup.cjs b/tests/server/setup.cjs new file mode 100644 index 0000000..dc16e8f --- /dev/null +++ b/tests/server/setup.cjs @@ -0,0 +1,24 @@ +const { existsSync, readdirSync } = require('node:fs'); +const { join } = require('node:path'); +const { execFileSync } = require('node:child_process'); + +// Prefer an installed Windows MongoDB over downloading a second copy. Explicit +// MongoMemoryServer settings and the normal download behavior elsewhere remain. +if (process.platform === 'win32' && !process.env.MONGOMS_SYSTEM_BINARY && !process.env.MONGOMS_VERSION) { + const root = join(process.env.ProgramFiles || 'C:\\Program Files', 'MongoDB', 'Server'); + if (existsSync(root)) { + const versions = readdirSync(root, { withFileTypes: true }) + .filter(entry => entry.isDirectory()) + .map(entry => entry.name) + .sort((a, b) => b.localeCompare(a, undefined, { numeric: true })); + const binary = versions.map(version => join(root, version, 'bin', 'mongod.exe')).find(existsSync); + if (binary) { + const output = execFileSync(binary, ['--version'], { encoding: 'utf8', windowsHide: true }); + const version = output.match(/db version v(\d+\.\d+\.\d+)/); + if (version) { + process.env.MONGOMS_SYSTEM_BINARY = binary; + process.env.MONGOMS_VERSION = version[1]; + } + } + } +}