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

// --- Anti-CSRF token ---
// Fetch the token once, then attach it to every POST/PUT/PATCH/DELETE
// in the x-csrf-token header.
const SAFE_METHODS = ['get', 'head', 'options']
let csrfToken = null
let pending = null

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 belongs to one session, so forget it when the session changes.
export function clearCsrfToken() {
csrfToken = null
}

function isAuthRoute(url = '') {
return /\/auth\/(login|register|logout)/.test(url)
}

api.interceptors.request.use(async (config) => {
const method = (config.method || 'get').toLowerCase()
if (!SAFE_METHODS.includes(method) && !isAuthRoute(config.url)) {
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) => {
// Login/logout changes the session, so the old token is no longer valid.
if (isAuthRoute(res.config?.url)) clearCsrfToken()
return res
},
async (error) => {
const { config, response } = error
// If the token went stale, get a new one and retry once.
const isCsrfError = /csrf/i.test(response?.data?.message || '')
if (response?.status === 403 && isCsrfError && config && !config._csrfRetried && !isAuthRoute(config.url)) {
config._csrfRetried = true
clearCsrfToken()
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'
}
}
]
};
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
16 changes: 11 additions & 5 deletions server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,28 @@ 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();

app.use(morgan('dev'));
// The browser must be allowed to send the auth cookie on cross-origin XHR,
// 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 }));

// Issue an anti-CSRF token (a GET, so it is not CSRF-protected itself).
app.get('/api/csrf-token', csrfTokenHandler);

// Auth routes come BEFORE the CSRF check: login/register run before a session exists.
app.use('/api/auth', authRoutes);

// Everything below needs a valid CSRF token on POST/PUT/PATCH/DELETE.
// GET/HEAD/OPTIONS are exempt. A bad or missing token returns 403.
app.use(doubleCsrfProtection);

app.use('/api/items', itemRoutes);
app.use('/api/users', userRoutes);
app.use('/api/settings', settingRoutes);
Expand All @@ -37,4 +43,4 @@ app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message || 'Server Error' });
});

export default app;
export default app;
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 { doubleCsrf } from 'csrf-csrf';

// Anti-CSRF protection using the double-submit-cookie pattern.
// The token is tied to the user's session and signed with CSRF_SECRET.
// The attacker's page can't read it, and a plain HTML form can't send
// a custom header, so a forged request gets 403.
const { generateCsrfToken, doubleCsrfProtection } = doubleCsrf({
getSecret: () => process.env.CSRF_SECRET || process.env.JWT_SECRET,
getSessionIdentifier: (req) => req.cookies?.token || '',
cookieName: 'x-csrf-token', // "__Host-" default needs HTTPS, so plain name in dev
cookieOptions: {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
path: '/'
},
ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],
getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token']
});

// GET /api/csrf-token — gives the client a token to send back on writes.
export function csrfTokenHandler(req, res) {
const csrfToken = generateCsrfToken(req, res, { overwrite: true });
res.json({ csrfToken });
}

export { doubleCsrfProtection };
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');
});
});