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
36 changes: 34 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
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' } }]
]
};
30 changes: 26 additions & 4 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -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
})
26 changes: 26 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -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: '<rootDir>/tests/setupMongo.cjs',
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.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
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
15 changes: 15 additions & 0 deletions server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,34 @@ 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();

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 <form> POST (the classic CSRF vector,
// which needs no JavaScript and triggers no CORS preflight) is understood.
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);
Expand All @@ -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' });
});
Expand Down
19 changes: 14 additions & 5 deletions server/src/controllers/authController.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
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;

// 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({
Expand All @@ -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); }
}
Expand All @@ -59,14 +64,15 @@ 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); }
}

// POST /api/auth/logout
export async function logout(req, res) {
res.clearCookie('token');
res.clearCookie(csrfCookieName, csrfCookieOptions);
res.json({ ok: true });
}

Expand All @@ -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) {
Expand Down
22 changes: 22 additions & 0 deletions server/src/middleware/csrf.js
Original file line number Diff line number Diff line change
@@ -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')
});
9 changes: 9 additions & 0 deletions server/src/middleware/maintenanceRateLimit.js
Original file line number Diff line number Diff line change
@@ -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.' }
});
3 changes: 2 additions & 1 deletion server/src/routes/auth.js
Original file line number Diff line number Diff line change
@@ -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;
Loading