Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: tests

on:
push:
branches: [main, master]
pull_request:
branches: [main, master]

jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 15

steps:
- uses: actions/checkout@v4

- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'

- name: Install dependencies
run: npm install

- name: Install workspace dependencies
run: npm run install:all

- name: Run tests
env:
MONGO_URI: ${{ secrets.MONGO_URI }}
JWT_SECRET: test-secret
CSRF_SECRET: test-csrf-secret
run: npm test -- --runInBand
3 changes: 3 additions & 0 deletions babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
};
41 changes: 38 additions & 3 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,45 @@
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.
// every request to the API. On its own that's the precondition for CSRF — so
// every state-changing request must also carry an anti-CSRF token in a header
// the attacker's page cannot set.
export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

// Cached CSRF token. We fetch it once from /csrf-token (which also sets the
// httpOnly double-submit cookie), then echo it back on every mutating request.
let csrfToken = null

async function fetchCsrfToken() {
if (csrfToken) return csrfToken
const res = await api.get('/csrf-token')
csrfToken = res.data.csrfToken
return csrfToken
}

// Attach the token to every state-changing request (POST / PUT / PATCH / DELETE).
api.interceptors.request.use(async (config) => {
const method = (config.method || 'get').toLowerCase()
if (['post', 'put', 'patch', 'delete'].includes(method)) {
const token = await fetchCsrfToken()
config.headers = config.headers || {}
config.headers['x-csrf-token'] = token
}
return config
})

// Drop the cached token when the session ends or a token is rejected, so the
// next user/session gets a fresh one.
api.interceptors.response.use(
(res) => {
if ((res.config?.url || '').includes('/auth/logout')) csrfToken = null
return res
},
(err) => {
if (err.response?.status === 403) csrfToken = null
return Promise.reject(err)
}
)
159 changes: 159 additions & 0 deletions create-tests.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import fs from 'fs';
import path from 'path';

const files = {
'tests/server/csrf.test.js': [
"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();",
"});",
"",
"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);",
" return cookiePairs(res.headers['set-cookie']);",
"}",
"",
"describe('Maintenance requests - CSRF protection', () => {",
" test('happy path: logged-in user files a request with a valid token', async () => {",
" const authCookies = await registerUser();",
" 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');",
" });",
"",
" test('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('; '))",
" .set('Origin', 'http://attacker.evil')",
" .send({ roomNumber: 'Z9-666', category: 'other', description: 'Forged by attacker via CSRF' });",
" expect(forged.status).toBe(403);",
" 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();",
" });",
"});",
""
].join('\n'),

'tests/server/dos.test.js': [
"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('normal request to the public list succeeds', async () => {",
" const res = await request(app).get('/api/maintenance');",
" expect(res.status).toBe(200);",
" expect(Array.isArray(res.body.requests)).toBe(true);",
" });",
"",
" test('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);",
" }",
" expect(statuses).toContain(200);",
" expect(statuses).toContain(429);",
" });",
"});",
""
].join('\n'),

'tests/client/csrf.test.js': [
"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('requests are sent with credentials', () => {",
" expect(api.defaults.withCredentials).toBe(true);",
" });",
"",
" test('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');",
" });",
"});",
""
].join('\n'),
};

for (const [file, content] of Object.entries(files)) {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content, 'utf8');
console.log('wrote', file);
}
6 changes: 6 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
testEnvironment: 'node',
transform: {
'\\.[jt]sx?$': 'babel-jest',
},
};
44 changes: 42 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,8 @@
"allowScripts": {
"@parcel/watcher@2.6.0": true,
"mongodb-memory-server@11.3.0": true
},
"dependencies": {
"rxjs": "^7.8.2"
}
}
2 changes: 2 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading