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
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ npm-debug.log*
yarn-debug.log*
yarn-error.log*

CLAUDE.md
AGENTS.md

# OS and Editor specific files
.DS_Store
Expand All @@ -30,3 +28,5 @@ Thumbs.db
# Server-side specific ignores (if server is in a subfolder)
server/node_modules/
server/build/

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

// ---- Anti-CSRF -------------------------------------------------------------
// Every state-changing request (anything but GET/HEAD/OPTIONS) must carry the
// per-session CSRF token in the `x-csrf-token` header. The token comes from
// GET /csrf-token, which also sets the matching httpOnly cookie. An attacker's
// page can neither call that endpoint and read the answer (CORS) nor set a
// custom header from an auto-submitting form, which is what defeats CSRF.
const SAFE_METHODS = new Set(['get', 'head', 'options'])
// Pre-auth routes run before a session exists and are exempt on the server too.
const CSRF_EXEMPT = ['/auth/login', '/auth/register']
const CSRF_TOKEN_URL = '/csrf-token'

let csrfToken = null
let pendingFetch = null

async function fetchCsrfToken() {
if (!pendingFetch) {
pendingFetch = api.get(CSRF_TOKEN_URL)
.then(res => { csrfToken = res.data.csrfToken; return csrfToken })
.finally(() => { pendingFetch = null })
}
return pendingFetch
}

export function clearCsrfToken() { csrfToken = null }

function needsCsrfToken(config) {
const method = (config.method || 'get').toLowerCase()
const url = config.url || ''
if (SAFE_METHODS.has(method)) return false
if (url.includes(CSRF_TOKEN_URL)) return false
return !CSRF_EXEMPT.some(p => url.startsWith(p))
}

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

// Attach the token to every mutating request, fetching it lazily the first time.
api.interceptors.request.use(async (config) => {
if (!needsCsrfToken(config)) return config
try {
const token = csrfToken || await fetchCsrfToken()
setHeader(config, 'x-csrf-token', token)
} catch {
// Not logged in (401) or API down: send as-is and let the server answer.
}
return config
})

api.interceptors.response.use(
(res) => {
// The token is bound to the session. Whenever the session changes (login,
// register, logout) drop the cached token so the next write fetches a new one.
if (/\/auth\/(login|register|logout)$/.test(res.config?.url || '')) clearCsrfToken()
return res
},
async (err) => {
const cfg = err.config
const rejectedForCsrf = err.response?.status === 403 && err.response?.data?.code === 'EBADCSRFTOKEN'
// A stale token (e.g. another tab re-logged in): refresh once and retry.
if (rejectedForCsrf && cfg && !cfg._csrfRetried) {
cfg._csrfRetried = true
clearCsrfToken()
return api.request(cfg)
}
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'
}
}
]
};
16 changes: 15 additions & 1 deletion server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ 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 { requireAuth } from './middleware/auth.js';
import { doubleCsrfProtection, issueCsrfToken } from './middleware/csrf.js';

const app = express();

Expand All @@ -21,6 +23,13 @@ app.use(cookieParser());

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

// Anti-CSRF (see middleware/csrf.js). The token endpoint is a safe GET and is
// mounted before the guard; the guard then covers every state-changing request
// (POST/PATCH/DELETE) on every route below, except the pre-auth login/register
// routes which it skips by path. GET/HEAD/OPTIONS are never checked.
app.get('/api/csrf-token', requireAuth, issueCsrfToken);
app.use(doubleCsrfProtection);

app.use('/api/auth', authRoutes);
app.use('/api/items', itemRoutes);
app.use('/api/users', userRoutes);
Expand All @@ -33,8 +42,13 @@ app.use((req, res) => {

// Error handler
app.use((err, req, res, next) => {
// Missing / invalid / mismatched CSRF token: the request did not provably come
// from our own app. Refuse it without touching any state.
if (err.code === 'EBADCSRFTOKEN') {
return res.status(403).json({ message: 'Invalid or missing CSRF token', code: 'EBADCSRFTOKEN' });
}
console.error(err);
res.status(err.status || 500).json({ message: err.message || 'Server Error' });
});

export default app;
export default app;
9 changes: 5 additions & 4 deletions server/src/controllers/settingController.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ 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 proves WHO the user
// is, not that THEY intended this request, so it is protected by the anti-CSRF
// guard in app.js: without a valid `x-csrf-token` header the request never
// reaches this handler.
export async function updateRecoveryEmail(req, res, next) {
try {
const { value, error } = recoveryEmailSchema.validate({ recoveryEmail: req.body.recoveryEmail });
Expand All @@ -37,4 +38,4 @@ export async function updateRecoveryEmail(req, res, next) {
);
res.json({ settings: publicSettings(doc) });
} catch (err) { next(err); }
}
}
63 changes: 63 additions & 0 deletions server/src/middleware/csrf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { doubleCsrf } from 'csrf-csrf';

// Anti-CSRF protection using the *signed double-submit cookie* pattern (csrf-csrf v4).
//
// Why the existing defenses were not enough:
// - CORS only stops the attacker's page from READING the response. The browser
// still SENDS a plain <form> POST (no preflight), cookie attached, and the
// server still acts on it. CSRF only needs the write to succeed.
// - SameSite=Lax keys off the registrable domain, not the port. localhost:1337
// and localhost:4000 are the same site, so the auth cookie is still sent.
//
// What this adds: a secret token that only our own front-end can obtain and echo
// back in the `x-csrf-token` header. The token is an HMAC over a random value,
// the user's session (the JWT cookie) and a server secret. A copy lives in an
// httpOnly cookie; the request must ALSO carry the same token in a header. An
// attacker page can neither read the token nor set a custom header from an
// auto-submitting form, and cannot forge the HMAC without the secret, so a
// forged request fails validation and is rejected with 403.

// Pre-auth routes run before a session exists, so there is nothing to bind a
// token to and nothing for an attacker to gain. They stay exempt.
const CSRF_EXEMPT_PATHS = new Set(['/api/auth/login', '/api/auth/register']);

function getSecret() {
// Evaluated per request so tests / dotenv can set it after this module loads.
const secret = process.env.CSRF_SECRET || process.env.JWT_SECRET;
if (!secret) throw new Error('CSRF_SECRET (or JWT_SECRET) must be set');
return secret;
}

export const {
generateCsrfToken,
doubleCsrfProtection,
invalidCsrfTokenError
} = doubleCsrf({
getSecret,
// Bind every token to the session that requested it: the JWT in the auth
// cookie. A token minted for one login cannot be replayed for another.
getSessionIdentifier: (req) => req.cookies?.token || '',
// No `__Host-` prefix: the demo runs over plain http://localhost and that
// prefix requires Secure/HTTPS. Use it (with secure: true) in production.
cookieName: 'csrf-token',
cookieOptions: {
httpOnly: true,
sameSite: 'lax',
secure: false, // true in production (HTTPS only)
path: '/'
},
// Only the header counts. Never fall back to the cookie or body here — that
// would turn the check into "cookie equals cookie" and defeat the point.
getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'],
// "Safe" methods are never protected; the pre-auth routes are skipped by path.
ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],
skipCsrfProtection: (req) => CSRF_EXEMPT_PATHS.has(req.path)
});

// GET /api/csrf-token — hand the logged-in client a fresh token (and set the
// matching cookie). Mounted behind requireAuth so a token is always bound to a
// real session.
export function issueCsrfToken(req, res) {
const csrfToken = generateCsrfToken(req, res, { overwrite: true });
res.json({ csrfToken });
}
9 changes: 5 additions & 4 deletions server/src/routes/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ 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
// covered by the app-wide anti-CSRF guard (app.js -> middleware/csrf.js): it must
// carry a valid `x-csrf-token` header matching the csrf cookie, which a forged
// cross-site form cannot supply, so a CSRF attempt is rejected with 403.
router.get('/', requireAuth, getSettings);
router.post('/recovery-email', requireAuth, updateRecoveryEmail);

export default router;
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