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

on:
push:
pull_request:

permissions:
contents: read

jobs:
verify:
runs-on: ubuntu-latest
timeout-minutes: 15

steps:
- name: Check out source
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 ci

- name: Build client
run: npm run build --workspace client

- name: Run test suite
run: npm test -- --runInBand
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ PORT=4000
MONGO_URI=mongodb://tasks:pass1234@ac-j3acrgb-shard-00-00.lueesfz.mongodb.net:27017,ac-j3acrgb-shard-00-01.lueesfz.mongodb.net:27017,ac-j3acrgb-shard-00-02.lueesfz.mongodb.net:27017/?ssl=true&replicaSet=atlas-6to6iy-shard-0&authSource=admin&appName=Cluster0
JWT_SECRET=4a498d90a0f923ae4b3f1f65571ff25985d17e2f3286e8e90383e449f68a40a8
JWT_EXPIRES_IN=7d
CSRF_SECRET=use-a-separate-long-random-secret-in-production
```

## What was added on top of Task 3
Expand Down
4 changes: 4 additions & 0 deletions babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Lets Jest load the project's ESM source through babel-jest.
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }]]
};
42 changes: 38 additions & 4 deletions client/src/api.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,44 @@
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.
// The auth cookie is sent automatically. The interceptor below adds the
// separate anti-CSRF proof required for authenticated state-changing requests.
export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

let csrfToken = null
let csrfTokenRequest = null

const protectedWrite = (config) => {
const method = (config.method || 'get').toLowerCase()
const url = config.url || ''
const isMutation = ['post', 'patch', 'put', 'delete'].includes(method)
const isPreAuth = url.includes('/auth/login') || url.includes('/auth/register')
return isMutation && !isPreAuth && !url.includes('/csrf-token')
}

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

api.interceptors.request.use(async (config) => {
if (!protectedWrite(config)) return config
const token = await getCsrfToken()
config.headers = config.headers || {}
config.headers['x-csrf-token'] = token
return config
})

export function clearCsrfToken() {
csrfToken = null
}
5 changes: 4 additions & 1 deletion client/src/context/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createContext, useCallback, useContext, useEffect, useState } from 'react'
import { api } from '../api'
import { api, clearCsrfToken } from '../api'

const AuthContext = createContext(null)

Expand All @@ -19,17 +19,20 @@ export function AuthProvider({ children }) {
const login = useCallback(async (email, password) => {
// The server sets the auth cookie in its response; nothing to store here.
const res = await api.post('/auth/login', { email, password })
clearCsrfToken()
setUser(res.data.user)
}, [])

const register = useCallback(async (name, email, password) => {
const res = await api.post('/auth/register', { name, email, password })
clearCsrfToken()
setUser(res.data.user)
}, [])

const logout = useCallback(async () => {
// Ask the server to clear the auth cookie, then reset local state.
try { await api.post('/auth/logout') } catch { /* ignore */ }
clearCsrfToken()
setUser(null)
window.location.href = '/login'
}, [])
Expand Down
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' }
}
]
};
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
12 changes: 11 additions & 1 deletion server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,19 @@ 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 { generateCsrfToken } from './middleware/csrf.js';
import { requireAuth } from './middleware/auth.js';

const app = express();

app.use(morgan('dev'));
// CORS is locked to the client origin with credentials enabled so the browser
// may send the auth cookie on cross-origin XHR. (CORS alone does NOT stop CSRF.)
app.use(cors({ origin: 'http://localhost:5175', credentials: true }));
app.use(cors({
origin: process.env.CLIENT_ORIGIN || 'http://localhost:5175',
credentials: true,
allowedHeaders: ['Content-Type', 'X-CSRF-Token']
}));
app.use(express.json());
// Parse urlencoded bodies so a bare HTML <form> POST (the classic CSRF vector,
// which needs no JavaScript and triggers no CORS preflight) is understood.
Expand All @@ -21,6 +27,10 @@ app.use(cookieParser());

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

app.get('/api/csrf-token', requireAuth, (req, res) => {
res.json({ csrfToken: generateCsrfToken(req, res) });
});

app.use('/api/auth', authRoutes);
app.use('/api/bookings', bookingRoutes);
app.use('/api/users', userRoutes);
Expand Down
5 changes: 3 additions & 2 deletions server/src/controllers/authController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import jwt from 'jsonwebtoken';
import { randomUUID } from 'crypto';
import bcrypt from 'bcryptjs';
import Joi from 'joi';
import { User } from '../models/User.js';
Expand All @@ -13,7 +14,7 @@ function setAuthCookie(res, token) {
res.cookie('token', token, {
httpOnly: true,
sameSite: 'lax',
secure: false, // true in production (HTTPS only)
secure: process.env.NODE_ENV === 'production',
maxAge: COOKIE_MAX_AGE
});
}
Expand Down Expand Up @@ -79,7 +80,7 @@ export async function me(req, res, next) {
}

function signToken(user) {
const payload = { id: user._id.toString(), name: user.name };
const payload = { id: user._id.toString(), name: user.name, jti: randomUUID() };
return jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN || '7d' });
}

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

export const { generateCsrfToken, doubleCsrfProtection } = doubleCsrf({
// Resolve this at request time so test/bootstrap code can set environment
// variables before the first request, and use a dedicated secret in prod.
getSecret: () => process.env.CSRF_SECRET || process.env.JWT_SECRET,
getSessionIdentifier: (req) => req.cookies?.token || '',
cookieName: 'csrf-token',
cookieOptions: {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
path: '/'
},
getCsrfTokenFromRequest: (req) => req.headers['x-csrf-token'],
ignoredMethods: ['GET', 'HEAD', 'OPTIONS']
});
9 changes: 9 additions & 0 deletions server/src/middleware/maintenanceRateLimit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { rateLimit } from 'express-rate-limit';

export const maintenanceRateLimit = rateLimit({
windowMs: 60 * 1000,
limit: 30,
standardHeaders: 'draft-8',
legacyHeaders: false,
message: { message: 'Too many maintenance requests. Please try again in a minute.' }
});
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/bookings.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 {
getAllBookings,
getBooking,
Expand All @@ -13,8 +14,8 @@ const router = Router();
// Reading is public; writing requires a logged-in user.
router.get('/', getAllBookings);
router.get('/:id', getBooking);
router.post('/', requireAuth, createBooking);
router.patch('/:id', requireAuth, updateBooking);
router.delete('/:id', requireAuth, deleteBooking);
router.post('/', requireAuth, doubleCsrfProtection, createBooking);
router.patch('/:id', requireAuth, doubleCsrfProtection, updateBooking);
router.delete('/:id', requireAuth, doubleCsrfProtection, deleteBooking);

export default router;
21 changes: 8 additions & 13 deletions server/src/routes/maintenance.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Router } from 'express';
import { requireAuth } from '../middleware/auth.js';
import { doubleCsrfProtection } from '../middleware/csrf.js';
import { maintenanceRateLimit } from '../middleware/maintenanceRateLimit.js';
import {
getAllRequests,
getRequest,
Expand All @@ -10,20 +12,13 @@ import {

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.
// Reading is public. The whole feature is rate-limited, and authenticated
// writes additionally require a CSRF token before they reach the controller.
router.use(maintenanceRateLimit);
router.get('/', getAllRequests);
router.get('/:id', getRequest);
router.post('/', requireAuth, createRequest);
router.patch('/:id', requireAuth, updateRequest);
router.delete('/:id', requireAuth, deleteRequest);
router.post('/', requireAuth, doubleCsrfProtection, createRequest);
router.patch('/:id', requireAuth, doubleCsrfProtection, updateRequest);
router.delete('/:id', requireAuth, doubleCsrfProtection, deleteRequest);

export default router;
8 changes: 6 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,10 @@ 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);
// Every authenticated state change requires the same CSRF proof as bookings
// and maintenance requests. Login and registration are intentionally exempt
// because a session does not exist yet.
router.patch('/:id', requireAuth, doubleCsrfProtection, updateUser);
router.delete('/:id', requireAuth, doubleCsrfProtection, deleteUser);

export default router;
Loading