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' } }]
]
};
74 changes: 74 additions & 0 deletions client/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,77 @@ export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

// ---------------------------------------------------------------------------
// Anti-CSRF token handling (pairs with server/src/middleware/csrf.js).
//
// The server requires every state-changing request to echo a per-session CSRF
// token in the `x-csrf-token` header. We fetch it from GET /csrf-token (our own
// origin is allowed by CORS to read the response; an attacker's page is not)
// and attach it to every mutating request. Safe methods and the pre-auth routes
// (login/register) do not need it.
// ---------------------------------------------------------------------------

const SAFE_METHODS = new Set(['get', 'head', 'options'])
const PRE_AUTH_PATHS = ['/auth/login', '/auth/register']
// Requests after which the session (auth cookie) changes, so the old CSRF token
// — which is bound to the session — is no longer valid.
const SESSION_CHANGING_PATHS = ['/auth/login', '/auth/register', '/auth/logout']

let csrfToken = null
let pendingToken = null

function matches(url, paths) {
return paths.some(p => (url || '').endsWith(p))
}

function needsCsrf(config) {
const method = (config.method || 'get').toLowerCase()
return !SAFE_METHODS.has(method) && !matches(config.url, PRE_AUTH_PATHS)
}

async function getCsrfToken({ refresh = false } = {}) {
if (refresh) csrfToken = null
if (csrfToken) return csrfToken
if (!pendingToken) {
pendingToken = api.get('/csrf-token')
.then(res => (csrfToken = res.data.csrfToken))
.finally(() => { pendingToken = null })
}
return pendingToken
}

function setHeader(config, name, value) {
if (config.headers && typeof config.headers.set === 'function') config.headers.set(name, value)
else config.headers = { ...(config.headers || {}), [name]: value }
}

export function clearCsrfToken() {
csrfToken = null
}

api.interceptors.request.use(async config => {
if (needsCsrf(config)) {
setHeader(config, 'x-csrf-token', await getCsrfToken())
}
return config
})

api.interceptors.response.use(
res => {
if (matches(res.config?.url, SESSION_CHANGING_PATHS)) clearCsrfToken()
return res
},
async err => {
const config = err.config
// A stale token (e.g. the session changed) is rejected with 403: fetch a
// fresh one and retry the request exactly once.
if (err.response?.status === 403 && config && needsCsrf(config) && !config._csrfRetried) {
config._csrfRetried = true
setHeader(config, 'x-csrf-token', await getCsrfToken({ refresh: true }))
return api.request(config)
}
if (config && matches(config.url, SESSION_CHANGING_PATHS)) clearCsrfToken()
return Promise.reject(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'
}
}
]
};
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
9 changes: 9 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 itemRoutes from './routes/items.js';
import userRoutes from './routes/users.js';
import settingRoutes from './routes/settings.js';
import { csrfTokenHandler, doubleCsrfProtection } from './middleware/csrf.js';

const app = express();

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

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

// Anti-CSRF: issue a per-session token, then require it (x-csrf-token header) on
// every state-changing request. GET/HEAD/OPTIONS and the pre-auth routes
// (login/register) are exempt. Must run after cookieParser and before the routes.
// CORS and SameSite alone do not stop CSRF: CORS only blocks *reading* the
// response, and SameSite ignores ports (localhost:1337 and :4000 are same-site).
app.get('/api/csrf-token', csrfTokenHandler);
app.use(doubleCsrfProtection);

app.use('/api/auth', authRoutes);
app.use('/api/items', itemRoutes);
app.use('/api/users', userRoutes);
Expand Down
6 changes: 3 additions & 3 deletions server/src/controllers/settingController.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ 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.
// This is a state-changing request. The auth cookie alone is not enough: the
// app-wide CSRF middleware has already verified the x-csrf-token header before
// we get here, so a forged cross-site request never reaches this handler.
export async function updateRecoveryEmail(req, res, next) {
try {
const { value, error } = recoveryEmailSchema.validate({ recoveryEmail: req.body.recoveryEmail });
Expand Down
47 changes: 47 additions & 0 deletions server/src/middleware/csrf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { doubleCsrf } from 'csrf-csrf';

// Anti-CSRF protection using the double-submit-cookie pattern (csrf-csrf).
//
// How it defeats the attack:
// 1. GET /api/csrf-token returns a token in the JSON body AND sets the same
// value in an httpOnly cookie. The token is an HMAC (keyed by CSRF_SECRET)
// over the caller's session identifier + a random value, so it cannot be
// guessed or forged, and it is bound to the current session.
// 2. Every state-changing request must echo the token back in the
// `x-csrf-token` header. The server checks header === cookie AND that the
// HMAC is valid for this session.
// 3. An attacker's page can make the browser SEND cookies, but it cannot READ
// the token (CORS blocks reading our responses, the cookie is httpOnly) and
// a plain HTML <form> cannot set custom headers — so a forged request
// arrives without a valid header and is rejected with 403.

// Routes that run before a session exists (no auth cookie to ride on) are exempt.
const PRE_AUTH_ROUTES = new Set(['/api/auth/login', '/api/auth/register']);

const { generateCsrfToken, doubleCsrfProtection } = 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 each CSRF token to the current session (the auth JWT cookie). A token
// issued for one session is useless for another, and a new login invalidates it.
getSessionIdentifier: (req) => req.cookies?.token ?? '',
// No `__Host-` prefix: browsers only accept those on HTTPS, and dev runs on http.
cookieName: 'psifi.x-csrf-token',
cookieOptions: {
httpOnly: true,
sameSite: 'strict',
path: '/',
secure: process.env.NODE_ENV === 'production'
},
// "Safe" methods never change state, so they are not checked.
ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],
getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'],
skipCsrfProtection: (req) => PRE_AUTH_ROUTES.has(req.path)
});

// GET /api/csrf-token — hand the client a token for its current session.
export function csrfTokenHandler(req, res) {
const csrfToken = generateCsrfToken(req, res);
res.json({ csrfToken });
}

export { doubleCsrfProtection };
7 changes: 4 additions & 3 deletions server/src/routes/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import { getSettings, updateRecoveryEmail } from '../controllers/settingControll

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`.
// Reading and writing both require a logged-in user. The write is additionally
// protected against CSRF by the app-wide `doubleCsrfProtection` middleware
// (see middleware/csrf.js): it is rejected with 403 unless it carries a valid
// x-csrf-token header matching the per-session CSRF cookie.
router.get('/', requireAuth, getSettings);
router.post('/recovery-email', requireAuth, updateRecoveryEmail);

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('/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');
});
});
85 changes: 85 additions & 0 deletions tests/server/csrf.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
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('Account settings — recovery email', () => {
test('a logged-in user can update their own recovery email (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/settings/recovery-email')
.set('Cookie', cookies.join('; '))
.set(headers)
.send({ recoveryEmail: 'legit@user.com' });
expect(res.status).toBe(200);

const check = await request(app).get('/api/settings').set('Cookie', authCookies.join('; '));
expect(check.status).toBe(200);
expect(check.body.settings.recoveryEmail).toBe('legit@user.com');
});

// 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/settings/recovery-email')
.set('Cookie', authCookies.join('; ')) // only the auth cookie — as in a real CSRF
.set('Origin', 'http://attacker.evil') // request originates off-site
.send({ recoveryEmail: 'attacker@evil.com' });

// Secure behavior: refuse the request for lack of a valid CSRF token.
expect(forged.status).toBe(403);

// And the victim's recovery email must be untouched.
const check = await request(app).get('/api/settings').set('Cookie', authCookies.join('; '));
expect(check.status).toBe(200);
expect(check.body.settings.recoveryEmail).not.toBe('attacker@evil.com');
});
});