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
24 changes: 24 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions babel.config.cjs
Original file line number Diff line number Diff line change
@@ -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' } }]
]
};
24 changes: 20 additions & 4 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,26 @@
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.
// withCredentials sends the httpOnly auth cookie (and the CSRF cookie).
export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

// CSRF: every state-changing request echoes a fresh, session-bound token in the
// x-csrf-token header. A cross-site attacker can neither read nor set it.
const SAFE = ['get', 'head', 'options']
const AUTH_EXEMPT = ['/auth/login', '/auth/register']

api.interceptors.request.use(async (config) => {
const method = (config.method || 'get').toLowerCase()
if (SAFE.includes(method) || AUTH_EXEMPT.includes(config.url)) return config

const { data } = await api.get('/csrf-token')
config.headers = config.headers || {}
if (typeof config.headers.set === 'function') {
config.headers.set('x-csrf-token', data.csrfToken)
} else {
config.headers['x-csrf-token'] = data.csrfToken
}
return config
})
16 changes: 16 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module.exports = {
projects: [
{
displayName: 'server',
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/server/**/*.test.js'],
transform: { '^.+\\.js$': 'babel-jest' }
},
{
displayName: 'client',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/tests/client/**/*.test.js'],
transform: { '^.+\\.js$': 'babel-jest' }
}
]
};
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": "^7.5.0",
"joi": "^17.12.3",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.6.0",
Expand Down
6 changes: 6 additions & 0 deletions server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ 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 { csrfProtection, csrfTokenHandler } from './middleware/csrf.js';

const app = express();

Expand All @@ -21,6 +22,11 @@ app.use(cookieParser());

app.get('/api/health', (req, res) => res.json({ ok: true }));

// CSRF: token endpoint, then protect every state-changing request
// (GET and login/register are exempt inside csrfProtection).
app.get('/api/csrf-token', csrfTokenHandler);
app.use(csrfProtection);

app.use('/api/auth', authRoutes);
app.use('/api/bookings', bookingRoutes);
app.use('/api/users', userRoutes);
Expand Down
29 changes: 29 additions & 0 deletions server/src/middleware/csrf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { doubleCsrf } from 'csrf-csrf';

// Double-submit-cookie CSRF protection. The token is an HMAC bound to the
// session (the auth cookie), so a token minted for one session is useless for another.
const {
generateCsrfToken,
doubleCsrfProtection
} = doubleCsrf({
getSecret: () => process.env.CSRF_SECRET || process.env.JWT_SECRET || 'dev-csrf-secret',
getSessionIdentifier: (req) => req.cookies?.token || '',
cookieName: 'csrf-token',
cookieOptions: { httpOnly: true, sameSite: 'lax', secure: false, path: '/' },
getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'],
// GET/HEAD/OPTIONS are exempt (default)
ignoredMethods: ['GET', 'HEAD', 'OPTIONS']
});

// Pre-auth routes run before a session exists, so there is nothing to forge.
const EXEMPT = new Set(['/api/auth/login', '/api/auth/register']);

export function csrfProtection(req, res, next) {
if (EXEMPT.has(req.path)) return next();
return doubleCsrfProtection(req, res, next);
}

// GET /api/csrf-token
export function csrfTokenHandler(req, res) {
res.json({ csrfToken: generateCsrfToken(req, res, { overwrite: true }) });
}
10 changes: 10 additions & 0 deletions server/src/middleware/rateLimit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import rateLimit from 'express-rate-limit';

// At most 30 requests per client per minute across the maintenance feature.
export const maintenanceLimiter = rateLimit({
windowMs: 60 * 1000,
limit: 30,
standardHeaders: true,
legacyHeaders: false,
message: { message: 'Too many requests, please try again later.' }
});
5 changes: 5 additions & 0 deletions server/src/routes/maintenance.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Router } from 'express';
import { requireAuth } from '../middleware/auth.js';
import { maintenanceLimiter } from '../middleware/rateLimit.js';
import {
getAllRequests,
getRequest,
Expand All @@ -10,6 +11,10 @@ import {

const router = Router();

// DoS protection: throttle every maintenance endpoint per client (429 when exceeded).
router.use(maintenanceLimiter);
// CSRF protection is enforced globally in app.js for all non-GET requests.

// Reading is public; writing requires a logged-in user.
//
// VULNERABLE on two fronts:
Expand Down
40 changes: 40 additions & 0 deletions tests/client/csrf.test.js
Original file line number Diff line number Diff line change
@@ -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');
});
});
82 changes: 82 additions & 0 deletions tests/server/csrf.test.js
Original file line number Diff line number Diff line change
@@ -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();
});
});
43 changes: 43 additions & 0 deletions tests/server/dos.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
});