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

on:
push:
pull_request:
workflow_dispatch:

permissions:
contents: read

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: actions/setup-node@v6
with:
node-version: 24
cache: npm
- name: Install locked dependencies
run: npm ci --ignore-scripts --no-audit --no-fund
- name: Run lab tests
run: npm test -- --runInBand
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' } }]
]
};
28 changes: 24 additions & 4 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,29 @@
import axios from 'axios'

// `withCredentials: true` makes the browser send (and store) the auth cookie on
// cross-origin requests to the API. The JWT is no longer kept in localStorage,
// so there is no token to attach by hand anymore.
const apiUrl = new URL('http://localhost:4000/api')

export const api = axios.create({
baseURL: 'http://localhost:4000/api',
baseURL: apiUrl.href,
withCredentials: true
})

const safeMethods = new Set(['get', 'head', 'options'])
let pendingCsrfToken

api.interceptors.request.use(async (config) => {
if (safeMethods.has(config.method)) return config

const url = new URL(api.getUri(config))
if (url.origin !== apiUrl.origin) return config
if (config.method === 'post' && /^\/api\/auth\/(?:login|register)\/?$/i.test(url.pathname)) {
return config
}

// Share an in-flight fetch so parallel writes use the same newly issued cookie.
pendingCsrfToken ??= api.get('/csrf-token')
.then(({ data }) => data.csrfToken)
.finally(() => { pendingCsrfToken = undefined })

config.headers.set('x-csrf-token', await pendingCsrfToken)
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' }
}
]
};
10 changes: 10 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"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",
"joi": "^17.12.3",
Expand Down
8 changes: 6 additions & 2 deletions server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import cookieParser from 'cookie-parser';
import { requireAuth } from './middleware/auth.js';
import { issueCsrfToken, invalidCsrfTokenError } from './middleware/csrf.js';
import authRoutes from './routes/auth.js';
import itemRoutes from './routes/items.js';
import userRoutes from './routes/users.js';
Expand All @@ -14,12 +16,11 @@ app.use(morgan('dev'));
// so CORS is locked to the client origin AND credentials are enabled.
app.use(cors({ origin: 'http://localhost:5175', credentials: true }));
app.use(express.json());
// Parse HTML-form bodies too. A classic CSRF payload is an auto-submitting
// <form> (application/x-www-form-urlencoded), so the endpoints must understand it.
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, issueCsrfToken);

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

// Error handler
app.use((err, req, res, next) => {
if (err === invalidCsrfTokenError) {
return res.status(403).json({ message: 'Invalid CSRF token' });
}
console.error(err);
res.status(err.status || 500).json({ message: err.message || 'Server Error' });
});
Expand Down
8 changes: 7 additions & 1 deletion server/src/controllers/authController.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { randomUUID } from 'node:crypto';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import Joi from 'joi';
import { User } from '../models/User.js';
import { clearCsrfCookie } 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;
Expand Down Expand Up @@ -67,6 +69,7 @@ export async function login(req, res, next) {
// POST /api/auth/logout
export async function logout(req, res) {
res.clearCookie('token');
clearCsrfCookie(res);
res.json({ ok: true });
}

Expand All @@ -80,7 +83,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
4 changes: 0 additions & 4 deletions server/src/controllers/settingController.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@ export async function getSettings(req, res, next) {
}

// POST /api/settings/recovery-email — change the recovery email.
//
// This is a state-changing request authenticated ONLY by the auth cookie the
// browser sends automatically. There is no anti-CSRF token, so any page the
// victim visits can forge this request on their behalf. That is the vulnerability.
export async function updateRecoveryEmail(req, res, next) {
try {
const { value, error } = recoveryEmailSchema.validate({ recoveryEmail: req.body.recoveryEmail });
Expand Down
3 changes: 1 addition & 2 deletions server/src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import dotenv from 'dotenv';
dotenv.config();
import 'dotenv/config';
import app from './app.js';
import { connectDB } from './config/db.js';

Expand Down
27 changes: 27 additions & 0 deletions server/src/middleware/csrf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { createHmac } from 'node:crypto';
import { doubleCsrf } from 'csrf-csrf';

const secure = process.env.NODE_ENV === 'production';
const cookieName = secure ? '__Host-csrf-token' : 'csrf-token';
const cookieOptions = { httpOnly: true, sameSite: 'lax', secure, path: '/' };

const { generateCsrfToken, doubleCsrfProtection, invalidCsrfTokenError } = doubleCsrf({
getSecret: () => process.env.CSRF_SECRET || createHmac('sha256', process.env.JWT_SECRET)
.update('campus-lost-found:csrf')
.digest('hex'),
// The routes verify the JWT before calling this middleware.
getSessionIdentifier: (req) => req.cookies.token,
cookieName,
cookieOptions
});

export function issueCsrfToken(req, res) {
res.set('Cache-Control', 'no-store');
res.json({ csrfToken: generateCsrfToken(req, res) });
}

export function clearCsrfCookie(res) {
res.clearCookie(cookieName, cookieOptions);
}

export { doubleCsrfProtection, invalidCsrfTokenError };
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;
7 changes: 4 additions & 3 deletions server/src/routes/items.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { Router } from 'express';
import { requireAuth } from '../middleware/auth.js';
import { doubleCsrfProtection } from '../middleware/csrf.js';
import { getAllItems, getItem, createItem, updateItem, deleteItem } from '../controllers/itemController.js';

const router = Router();

// Reading is public; writing requires a logged-in user.
router.get('/', getAllItems);
router.get('/:id', getItem);
router.post('/', requireAuth, createItem);
router.patch('/:id', requireAuth, updateItem);
router.delete('/:id', requireAuth, deleteItem);
router.post('/', requireAuth, doubleCsrfProtection, createItem);
router.patch('/:id', requireAuth, doubleCsrfProtection, updateItem);
router.delete('/:id', requireAuth, doubleCsrfProtection, deleteItem);

export default router;
6 changes: 2 additions & 4 deletions server/src/routes/settings.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { Router } from 'express';
import { requireAuth } from '../middleware/auth.js';
import { doubleCsrfProtection } from '../middleware/csrf.js';
import { getSettings, updateRecoveryEmail } from '../controllers/settingController.js';

const router = Router();

// Reading and writing both require a logged-in user. Nothing here checks that
// the request actually originated from our own app — so the write below is
// vulnerable to CSRF. The solution project adds that check with `csrf-csrf`.
router.get('/', requireAuth, getSettings);
router.post('/recovery-email', requireAuth, updateRecoveryEmail);
router.post('/recovery-email', requireAuth, doubleCsrfProtection, updateRecoveryEmail);

export default router;
5 changes: 3 additions & 2 deletions server/src/routes/users.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 { doubleCsrfProtection } from '../middleware/csrf.js';
import {
getAllUsers,
getUser,
Expand All @@ -12,7 +13,7 @@ const router = Router();
// Creating a user is now done through POST /api/auth/register.
router.get('/', getAllUsers);
router.get('/:id', getUser);
router.patch('/:id', requireAuth, updateUser);
router.delete('/:id', requireAuth, deleteUser);
router.patch('/:id', requireAuth, doubleCsrfProtection, updateUser);
router.delete('/:id', requireAuth, doubleCsrfProtection, deleteUser);

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('/settings/recovery-email', { recoveryEmail: 'legit@user.com' });

const sent = captured.find((c) => (c.url || '').includes('/settings/recovery-email'));
expect(sent).toBeDefined();
expect(getHeader(sent.headers, 'x-csrf-token')).toBe('test-token');
});
});
Loading