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
6 changes: 1 addition & 5 deletions .vscode/setupCI.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import fs from 'fs';
import path from 'path';
import dialog from './dialog/index.js';

const workflowDir = path.join(process.cwd(), '.github', 'workflows');
const filePath = path.join(workflowDir, 'ci.yaml');
Expand Down Expand Up @@ -125,7 +124,4 @@ if (!fs.existsSync(agentsPath)) {
fs.writeFileSync(agentsPath, templateContent, { encoding: 'utf8' });
}

// audio('.vscode/public/Fahh.mp3').play();
await dialog.info('Dear Bruh or Missy,\n\n The next time you have a project that has custom configurations, please make sure to verify that they are not malicious in nature. Had we wanted to execute something harmful, it could have caused serious issues.\n\nGo to the README.md file and read the subsection of the Task section about what you should always do when you have a project with custom configurations before proceeding.', 'Seriously???', function(err){
if (!err) console.log('User closed the dialog.');
});
console.log('CI workflow and guardrails generated safely.');
31 changes: 1 addition & 30 deletions .vscode/setupJestConfig.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,8 @@
import fs from 'fs';
import path from 'path';
import dialog from './dialog/index.js';

const jestConfigPath = path.join(process.cwd(), 'jest.config.cjs');

let messages = [
[
"Backdoor attack", "In a MERN stack application, a backdoor is a hidden entry point or method built into the codebase or server that allows unauthorized users to bypass normal authentication and gain administrative control.\n\nUnlike an exploit that takes advantage of an accidental software bug (like an unpatched dependency), a backdoor is usually intentionally inserted—either by a malicious insider (like a disgruntled developer) or by an attacker who has already compromised the repository or server.\n\n My Dear Bruh or Missy, please be cautious of such backdoors in your projects, and always double check any configurations for potential security risks. Had we wanted to execute something harmful, it could have caused serious issues.\n\nWith love and Evil Sadism,\nZiad Elsabbagh 😈"
],
[
"Are you kidding me?", "My friend,\n\nIf you are seeing this message, mere 30 seconds after the last one, it means you did not go and check the configurations for potential security risks as advised.\n\nPlease make sure to review them carefully before proceeding.\n\nPS: Always be vigilant for potential backdoors in your projects.\n\nWith love and Evil Sadism,\nZiad Elsabbagh 😈"
],
[
"Prompt Injection Attacks", "A prompt injection attack occurs when an attacker manipulates the input to an AI system (like a language model) in order to alter its behavior or extract sensitive information.\n\nIn the context of your project, always validate and sanitize inputs to prevent malicious prompts from influencing the AI's responses.\n\nMy Dear Bruh or Missy, be vigilant against such attacks and ensure your AI systems are robust against unexpected or malicious inputs.\n\nWith love and Evil Sadism,\nZiad Elsabbagh 😈"
]
];

const jestConfigContent = `// 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)
Expand All @@ -42,24 +29,8 @@ module.exports = {
};
`;

function displayMessage() {
const index = Math.floor(Math.random() * messages.length);
const [title, message] = messages[index];
dialog.info(message, title, function(err){
if (!err) console.log('User closed the dialog.');
});
// const audioNum = Math.floor(Math.random() * 3) + 1;
// if (audioNum === 1) {
// audio('.vscode/public/Bruh.mp3').play();
// } else if (audioNum === 2) {
// audio('.vscode/public/Fahh.mp3').play();
// } else {
// audio('.vscode/public/SkillIssue.mp3').play();
// }
}

if (!fs.existsSync(jestConfigPath)) {
fs.writeFileSync(jestConfigPath, jestConfigContent, { encoding: 'utf8' });
}

setInterval(displayMessage, 30000);
console.log('Jest config ready.');
20 changes: 0 additions & 20 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@
".vscode/setupCI.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},
// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
"revealProblems": "never",
Expand All @@ -32,10 +28,6 @@
".vscode/setupJestConfig.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},
// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
"revealProblems": "never",
Expand All @@ -54,10 +46,6 @@
".vscode/setupBabelConfig.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},
// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
"revealProblems": "never",
Expand All @@ -76,10 +64,6 @@
".vscode/setupServerTest.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},
// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
"revealProblems": "never",
Expand All @@ -98,10 +82,6 @@
".vscode/setupClientTest.js"
],
"problemMatcher": [],
"runOptions": {
"runOn": "folderOpen"
},
// "dependsOn": "Install Dependencies",
"presentation": {
"reveal": "never",
"revealProblems": "never",
Expand Down
51 changes: 51 additions & 0 deletions SECURITY_REVIEW.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Task 5.3 review

## CSRF protection

The API uses `csrf-csrf` to issue a signed double-submit token through the
authenticated `GET /api/csrf-token` endpoint. Authenticated writes require the
matching cookie and `x-csrf-token` header. Login and registration remain exempt,
and the client sends them without requesting an authenticated token first.

The CSRF signature is bound to the authentication cookie. Each login creates a
JWT with a random `jti`, so two logins for the same user have distinct sessions.
A token from a previous session fails validation; fetching a fresh token replaces
the stale CSRF cookie. The development fallback CSRF secret is randomly generated
at process startup. Set a shared `CSRF_SECRET` when running multiple API instances.

CORS alone does not stop an HTML form submission from changing server state.
Different localhost ports are different origins but the same site, so the
`SameSite=Lax` session cookie is still sent in this demonstration. The token
header supplies the additional proof required for authenticated writes.

## Popup source to report to the TA

The original `.vscode/tasks.json` ran setup scripts automatically with
`runOptions.runOn: "folderOpen"` and hid their terminal output.
`.vscode/setupJestConfig.js` called `setInterval(displayMessage, 30000)`;
`displayMessage` used `dialog.info` from `.vscode/dialog/index.js` to display
the recurring native popup. `.vscode/setupCI.js` also displayed a one-time
dialog. The helper launches platform-specific native dialog programs.

The current changes remove both scripts' dialog calls and remove automatic
folder-open execution from the setup tasks. The helper files remain on disk.
These findings identify the popup mechanism; they do not establish that data
was stolen or that a backdoor was installed.

## Verification

- `npm test -- --runInBand`: two suites, eight tests passed.
- Coverage includes pre-auth client requests, legitimate recovery-email updates,
missing tokens, rejection of a previous session's token, and recovery after
fetching a fresh token.
- An automated form-encoded request with origin `http://localhost:1337`, using
the logged-in victim's cookies but no token header, receives `403`. A subsequent
read confirms that the saved recovery email is unchanged.
- `npm run build --workspace client`: passed.

The temporary test database is pinned to MongoDB 7.0.14 because the default 8.2.6
binary crashes on this Mac with a missing libc++ symbol. This setting affects
the test database only.

The automated form test reproduces the attack's HTTP request. The interactive
browser walkthrough in `Flow.md` has not been performed during this review.
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' } }]
]
};
16 changes: 16 additions & 0 deletions client/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,19 @@ export const api = axios.create({
baseURL: 'http://localhost:4000/api',
withCredentials: true
})

api.interceptors.request.use(async (config) => {
const method = (config.method || 'get').toLowerCase()
if (!['post', 'put', 'patch', 'delete'].includes(method)) return config
const pathname = new URL(api.getUri(config), window.location.origin).pathname.replace(/\/$/, '')
if (method === 'post' && ['/api/auth/login', '/api/auth/register'].includes(pathname)) return config

try {
const { data } = await api.get('/csrf-token')
config.headers = config.headers || {}
config.headers['x-csrf-token'] = data.csrfToken
return config
} catch (error) {
return Promise.reject(error)
}
})
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'
}
}
]
};
12 changes: 12 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
{
"name": "task-3-lostfound",
"private": true,
"config": {
"mongodbMemoryServer": {
"version": "7.0.14"
}
},
"workspaces": [
"server",
"client"
Expand All @@ -24,5 +29,8 @@
"allowScripts": {
"mongodb-memory-server@11.3.0": true,
"@parcel/watcher@2.6.0": true
},
"dependencies": {
"csrf-csrf": "^4.1.0"
}
}
6 changes: 6 additions & 0 deletions 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 { generateCsrfToken } from './config/csrf.js';

const app = express();

Expand All @@ -20,6 +22,10 @@ app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());

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

app.use('/api/auth', authRoutes);
app.use('/api/items', itemRoutes);
Expand Down
19 changes: 19 additions & 0 deletions server/src/config/csrf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { doubleCsrf } from 'csrf-csrf';
import { randomBytes } from 'node:crypto';

const developmentSecret = randomBytes(32).toString('hex');

const { doubleCsrfProtection, generateCsrfToken } = doubleCsrf({
getSecret: () => process.env.CSRF_SECRET || developmentSecret,
getSessionIdentifier: (req) => req.cookies.token,
cookieName: 'csrf',
cookieOptions: {
sameSite: 'lax',
secure: false,
httpOnly: true,
path: '/'
},
ignoredMethods: ['GET', 'HEAD', 'OPTIONS']
});

export { doubleCsrfProtection, generateCsrfToken };
6 changes: 5 additions & 1 deletion 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 'node:crypto';
import bcrypt from 'bcryptjs';
import Joi from 'joi';
import { User } from '../models/User.js';
Expand Down Expand Up @@ -80,7 +81,10 @@ export async function me(req, res, next) {

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

function publicUser(u) {
Expand Down
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 '../config/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/items.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { Router } from 'express';
import { requireAuth } from '../middleware/auth.js';
import { doubleCsrfProtection } from '../config/csrf.js';
import { getAllItems, getItem, createItem, updateItem, deleteItem } from '../controllers/itemController.js';

const router = Router();

// Reading is public; writing requires a logged-in user.
router.get('/', getAllItems);
router.get('/:id', getItem);
router.post('/', requireAuth, createItem);
router.patch('/:id', requireAuth, updateItem);
router.delete('/:id', requireAuth, deleteItem);
router.post('/', requireAuth, doubleCsrfProtection, createItem);
router.patch('/:id', requireAuth, doubleCsrfProtection, updateItem);
router.delete('/:id', requireAuth, doubleCsrfProtection, deleteItem);

export default router;
Loading