Skip to content
Open

loay #101

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
32 changes: 32 additions & 0 deletions .github/workflows/security-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Security Tests (CSRF + DoS)

on:
push:
pull_request:
workflow_dispatch: # adds a "Run workflow" button in the Actions tab

jobs:
security-tests:
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'
cache: npm

- name: Install dependencies
run: npm install

- name: CSRF test (server) - forged request must get 403
run: npx jest tests/server/csrf.test.js --verbose

- name: DoS test (server) - flood must get 429
run: npx jest tests/server/dos.test.js --verbose

- name: CSRF test (client) - app must send x-csrf-token
run: npx jest tests/client/csrf.test.js --verbose
25 changes: 25 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Tests

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'
cache: npm

- name: Install dependencies
run: npm install

- name: Run the test suite (CSRF + DoS)
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' } }]
]
};
64 changes: 61 additions & 3 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,68 @@
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 would leave the app open to CSRF,
// so every state-changing request also carries an anti-CSRF token in the
// `x-csrf-token` header — a value only our own origin can read (CORS blocks
// other sites from reading /csrf-token) and that a plain HTML form cannot set.
export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

const SAFE_METHODS = ['get', 'head', 'options']
// Pre-auth routes are exempt on the server (no session exists yet).
const CSRF_EXEMPT = ['/auth/login', '/auth/register']

let csrfToken = null
let pending = null

// Fetch (and cache) a CSRF token for the current session.
async function getCsrfToken() {
if (csrfToken) return csrfToken
if (!pending) {
pending = api.get('/csrf-token')
.then(res => { csrfToken = res.data.csrfToken; return csrfToken })
.finally(() => { pending = null })
}
return pending
}

// The token is bound to the session, so it must be refreshed whenever the
// session changes (login / register / logout).
export function clearCsrfToken() {
csrfToken = null
}

const isSessionChange = (url = '') =>
CSRF_EXEMPT.some(p => url.includes(p)) || url.includes('/auth/logout')

api.interceptors.request.use(async (config) => {
const method = (config.method || 'get').toLowerCase()
const url = config.url || ''
if (!SAFE_METHODS.includes(method) && !CSRF_EXEMPT.some(p => url.includes(p))) {
const token = await getCsrfToken()
config.headers = config.headers || {}
if (typeof config.headers.set === 'function') config.headers.set('x-csrf-token', token)
else config.headers['x-csrf-token'] = token
}
return config
})

api.interceptors.response.use(
(res) => {
if (isSessionChange(res.config?.url)) clearCsrfToken()
return res
},
async (error) => {
const { config, response } = error
// A stale token (e.g. the session changed) -> fetch a fresh one and retry once.
if (response?.status === 403 && config && !config._csrfRetried &&
/csrf/i.test(response.data?.message || '')) {
clearCsrfToken()
config._csrfRetried = true
return api(config)
}
return Promise.reject(error)
}
)
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
7 changes: 7 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/security.js';

const app = express();

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

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

// Anti-CSRF: the client fetches a token here and echoes it in the
// x-csrf-token header on every state-changing request. Safe methods (GET) and
// the pre-auth routes (login/register) are exempt; everything else is checked.
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
72 changes: 72 additions & 0 deletions server/src/middleware/security.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { doubleCsrf } from 'csrf-csrf';
import { rateLimit } from 'express-rate-limit';

// ---------------------------------------------------------------------------
// CSRF protection — double-submit-cookie pattern (csrf-csrf)
// ---------------------------------------------------------------------------
// The server hands the client a secret token (GET /api/csrf-token). The same
// value is also bound to an httpOnly cookie as an HMAC, tied to the user's
// session. Every state-changing request must echo the token in the
// `x-csrf-token` header.
//
// An attacker's page cannot pass this check:
// - It cannot READ the token: the response body of /api/csrf-token is
// blocked by CORS (only http://localhost:5175 may read it), and the cookie
// is httpOnly.
// - It cannot GUESS the token: it is random and HMAC-signed with CSRF_SECRET.
// - A plain HTML <form> cannot set custom headers at all, and a cross-origin
// fetch() with a custom header triggers a CORS preflight that we refuse.
//
// Why CORS / SameSite alone are not enough:
// - CORS only controls who may READ a response. The browser still SENDS a
// "simple" request (e.g. a form POST) and the server still acts on it.
// - SameSite keys off the registrable domain, not the port, so
// localhost:1337 -> localhost:4000 is "same-site" and the Lax cookie is
// sent. Sibling subdomains and older browsers break it too.

const { doubleCsrfProtection, generateCsrfToken } = doubleCsrf({
// Read lazily so the secret can come from .env (or be set by tests at runtime).
getSecret: () => process.env.CSRF_SECRET || process.env.JWT_SECRET,
// Bind the token to the current session (the auth cookie). After login /
// logout the session changes, so the client must fetch a fresh token.
getSessionIdentifier: (req) => req.cookies?.token || '',
cookieName: 'x-csrf-token',
cookieOptions: {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production', // HTTPS only in production
path: '/'
},
// GET / HEAD / OPTIONS are "safe" (must not change state) and stay exempt.
ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],
getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token']
});

// Pre-auth routes run before a session exists, so there is nothing for an
// attacker to ride on yet — they stay exempt. Everything else is protected.
const CSRF_EXEMPT = new Set(['/api/auth/login', '/api/auth/register']);

export function csrfProtection(req, res, next) {
if (req.method === 'POST' && CSRF_EXEMPT.has(req.path)) return next();
return doubleCsrfProtection(req, res, next);
}

// GET /api/csrf-token — issues (and sets the cookie for) a token for this session.
export function csrfTokenHandler(req, res) {
const csrfToken = generateCsrfToken(req, res, { overwrite: true });
res.json({ csrfToken });
}

// ---------------------------------------------------------------------------
// DoS protection — rate limiting (express-rate-limit)
// ---------------------------------------------------------------------------
// One client (keyed by IP) may make at most MAINTENANCE_RATE_LIMIT requests to
// the maintenance feature per minute; beyond that it gets 429 Too Many Requests
// and the controller (and its database query) never runs.
export const maintenanceLimiter = rateLimit({
windowMs: 60 * 1000,
limit: Number(process.env.MAINTENANCE_RATE_LIMIT) || 30,
standardHeaders: 'draft-7', // RateLimit-* headers so clients know when to retry
legacyHeaders: false,
message: { message: 'Too many requests, please try again later.' }
});
16 changes: 8 additions & 8 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/security.js';
import {
getAllRequests,
getRequest,
Expand All @@ -12,14 +13,13 @@ 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.
// Hardened on two fronts:
// 1. CSRF — every write must carry a valid x-csrf-token header (enforced
// app-wide by csrfProtection in app.js), so a forged cross-site request
// is rejected with 403 before it reaches these handlers.
// 2. DoS — the whole feature is rate-limited per client; a flood gets 429.
router.use(maintenanceLimiter);

router.get('/', getAllRequests);
router.get('/:id', getRequest);
router.post('/', requireAuth, createRequest);
Expand Down
Loading