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
17 changes: 17 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Tests

on:
push:
pull_request:

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- 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' } }]
]
};
52 changes: 49 additions & 3 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,56 @@
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. Because the browser also does that for requests
// triggered by other sites, the cookie alone proves nothing — so every
// state-changing request additionally carries a CSRF token in a header, which
// only our own origin can obtain (CORS stops other sites reading it).
export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

const SAFE_METHODS = ['get', 'head', 'options']
// These run before a session exists; the server exempts them too.
const PRE_AUTH = ['/auth/login', '/auth/register']
// The token is bound to the session, so it is stale once the session changes.
const SESSION_CHANGING = [...PRE_AUTH, '/auth/logout']

const matches = (url, paths) => paths.some(p => (url || '').includes(p))

let csrfTokenPromise = null

function getCsrfToken() {
if (!csrfTokenPromise) {
csrfTokenPromise = api.get('/csrf-token')
.then(res => res.data.csrfToken)
.catch(err => { csrfTokenPromise = null; throw err })
}
return csrfTokenPromise
}

api.interceptors.request.use(async config => {
const method = (config.method || 'get').toLowerCase()
if (!SAFE_METHODS.includes(method) && !matches(config.url, PRE_AUTH)) {
config.headers.set('x-csrf-token', await getCsrfToken())
}
return config
})

api.interceptors.response.use(
res => {
if (matches(res.config.url, SESSION_CHANGING)) csrfTokenPromise = null
return res
},
async err => {
const config = err.config
// A rejected token (e.g. the server restarted or the session changed in
// another tab): fetch a fresh one and retry the request once.
if (err.response?.status === 403 && config?.headers?.get?.('x-csrf-token') && !config._csrfRetried) {
config._csrfRetried = true
csrfTokenPromise = null
return api(config)
}
throw err
}
)
24 changes: 24 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// 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',
testMatch: ['<rootDir>/tests/server/**/*.test.js'],
transform: {
'^.+\\.js$': 'babel-jest'
}
},
{
displayName: 'client',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/tests/client/**/*.test.js'],
transform: {
'^.+\\.js$': 'babel-jest'
}
}
]
};
39 changes: 39 additions & 0 deletions package-lock.json

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

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
14 changes: 14 additions & 0 deletions server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ 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 { doubleCsrfProtection, invalidCsrfTokenError, sendCsrfToken } from './middleware/csrf.js';
import { maintenanceLimiter } from './middleware/rateLimit.js';

const app = express();

Expand All @@ -19,6 +21,15 @@ app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

// Throttle the maintenance feature first, so a flood is refused with 429
// before it costs a CSRF check, a JWT verification or a database query.
app.use('/api/maintenance', maintenanceLimiter);

// Every state-changing request (POST/PUT/PATCH/DELETE) on every route must
// carry a valid CSRF token. GET/HEAD/OPTIONS and login/register are exempt.
app.use(doubleCsrfProtection);
app.get('/api/csrf-token', sendCsrfToken);

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

app.use('/api/auth', authRoutes);
Expand All @@ -33,6 +44,9 @@ app.use((req, res) => {

// Error handler
app.use((err, req, res, next) => {
if (err === invalidCsrfTokenError) {
return res.status(403).json({ message: 'Invalid or missing CSRF token' });
}
console.error(err);
res.status(err.status || 500).json({ message: err.message || 'Server Error' });
});
Expand Down
51 changes: 51 additions & 0 deletions server/src/middleware/csrf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import crypto from 'crypto';
import { doubleCsrf } from 'csrf-csrf';

// Used only when CSRF_SECRET is not configured: a random secret that lives for
// this process. Still unguessable, but tokens stop validating after a restart.
let fallbackSecret;
function getSecret() {
if (process.env.CSRF_SECRET) return process.env.CSRF_SECRET;
if (!fallbackSecret) {
console.warn('CSRF_SECRET is not set; using a random per-process secret. Set it in server/.env.');
fallbackSecret = crypto.randomBytes(32).toString('hex');
}
return fallbackSecret;
}

// These run before a session exists, so there is no authenticated state for a
// forged request to abuse and no session to bind a token to.
const PRE_AUTH_ROUTES = new Set(['/api/auth/login', '/api/auth/register']);

// Double-submit cookie pattern. The server signs a random token (HMAC keyed by
// the secret and bound to the session) and stores it in a cookie; the client
// must echo the same token in the x-csrf-token header. A cross-site page can
// make the browser send the cookie, but it can neither read the token (CORS
// blocks reading /api/csrf-token) nor set a custom header on a plain form POST.
const { doubleCsrfProtection, generateCsrfToken, invalidCsrfTokenError } = doubleCsrf({
getSecret,
// Bind the token to the logged-in session (the auth cookie), so a token
// obtained by one user/session cannot be replayed against another.
getSessionIdentifier: (req) => req.cookies?.token || '',
// The "__Host-" prefix requires HTTPS; use it (with secure: true) in production.
cookieName: 'csrf-token',
cookieOptions: {
httpOnly: true, // the client gets the token from the JSON body, not the cookie
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
path: '/'
},
// Safe methods must not change state, so they need no token.
ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],
// Header only: a cross-site HTML form cannot set custom headers, and never
// accept the token from the body or query string.
getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'],
skipCsrfProtection: (req) => PRE_AUTH_ROUTES.has(req.path)
});

// GET /api/csrf-token — hands the client a token for the current session.
export function sendCsrfToken(req, res) {
res.json({ csrfToken: generateCsrfToken(req, res) });
}

export { doubleCsrfProtection, invalidCsrfTokenError };
20 changes: 20 additions & 0 deletions server/src/middleware/rateLimit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import rateLimit from 'express-rate-limit';

const WINDOW_MS = 60 * 1000;

function limiter(limit, message) {
return rateLimit({
windowMs: WINDOW_MS,
limit,
standardHeaders: 'draft-7', // RateLimit-* headers tell clients when to retry
legacyHeaders: false,
message: { message }
});
}

// Every maintenance request, per client IP: 30 per minute. Enough for normal
// browsing of the page, far too few for a flood.
export const maintenanceLimiter = limiter(30, 'Too many requests, please try again later.');

// Writes are rarer and more expensive, so they get a tighter budget on top.
export const maintenanceWriteLimiter = limiter(10, 'Too many changes, please slow down.');
19 changes: 8 additions & 11 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 { maintenanceWriteLimiter } from '../middleware/rateLimit.js';
import {
getAllRequests,
getRequest,
Expand All @@ -12,18 +13,14 @@ 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.
// Two protections are applied in app.js before this router is reached:
// - maintenanceLimiter caps every client at 30 requests/minute (DoS).
// - doubleCsrfProtection rejects any write without a valid CSRF token (CSRF).
// Writes additionally get the tighter maintenanceWriteLimiter below.
router.get('/', getAllRequests);
router.get('/:id', getRequest);
router.post('/', requireAuth, createRequest);
router.patch('/:id', requireAuth, updateRequest);
router.delete('/:id', requireAuth, deleteRequest);
router.post('/', maintenanceWriteLimiter, requireAuth, createRequest);
router.patch('/:id', maintenanceWriteLimiter, requireAuth, updateRequest);
router.delete('/:id', maintenanceWriteLimiter, requireAuth, deleteRequest);

export default router;
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');
});
});
Loading
Loading