From 4b57a9f16892762bd26dd78841d16cdc8dbc67d6 Mon Sep 17 00:00:00 2001 From: youssifmedhat270 <134234884+youssifmedhat270@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:21:54 +0200 Subject: [PATCH 1/5] Fix NoSQL injection vulnerabilities, secure instructor authentication, and protect sensitive data --- client/src/pages/InstructorDashboard.jsx | 177 ++++++++++++++---- client/src/pages/InstructorLogin.jsx | 75 ++++++-- package-lock.json | 14 +- server/package.json | 5 +- server/src/app.js | 43 ++++- .../src/controllers/instructorController.js | 164 +++++++++++----- server/src/models/Instructor.js | 82 ++++++-- server/src/seed/instructors.js | 53 ++++-- 8 files changed, 478 insertions(+), 135 deletions(-) diff --git a/client/src/pages/InstructorDashboard.jsx b/client/src/pages/InstructorDashboard.jsx index 1dd0ded..a3633ed 100644 --- a/client/src/pages/InstructorDashboard.jsx +++ b/client/src/pages/InstructorDashboard.jsx @@ -1,13 +1,11 @@ + import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' import { api } from '../api' -// Instructor Portal dashboard. Reads the naive session from localStorage. -// Shows the signed-in profile, the public directory, and a name search. -// The search box sends a plain string; students intercept the request -// (Postman / proxy) to inject MongoDB operators — see Flow.md. export default function InstructorDashboard() { const nav = useNavigate() + const [instructor, setInstructor] = useState(null) const [directory, setDirectory] = useState([]) const [term, setTerm] = useState('') @@ -16,91 +14,204 @@ export default function InstructorDashboard() { useEffect(() => { const raw = localStorage.getItem('instructor') - if (!raw) { + const token = localStorage.getItem('instructorToken') + + // Redirect if session information is missing + if (!raw || !token) { + localStorage.removeItem('instructor') + localStorage.removeItem('instructorToken') nav('/portal', { replace: true }) return } + try { - setInstructor(JSON.parse(raw)) + const savedInstructor = JSON.parse(raw) + + if (!savedInstructor || !savedInstructor.id) { + throw new Error('Invalid instructor session') + } + + setInstructor(savedInstructor) + } catch { localStorage.removeItem('instructor') + localStorage.removeItem('instructorToken') nav('/portal', { replace: true }) return } + + // Load public instructor directory api.get('/instructors') - .then(res => setDirectory(res.data.instructors)) - .catch(() => {}) - }, []) + .then(res => { + setDirectory(res.data.instructors || []) + }) + .catch(() => { + setError('Failed to load instructor directory') + }) + + }, [nav]) async function onSearch(e) { e.preventDefault() setError('') + setResults(null) + + if (!term.trim()) { + setError('Please enter an instructor name') + return + } + try { - const res = await api.get('/instructors/search', { params: { name: term } }) - setResults(res.data.instructors) + const res = await api.get('/instructors/search', { + params: { + name: term.trim() + } + }) + + setResults(res.data.instructors || []) + } catch (err) { - setError(err?.response?.data?.message || 'Search failed') + setError( + err?.response?.data?.message || + 'Search failed' + ) } } function logout() { localStorage.removeItem('instructor') + localStorage.removeItem('instructorToken') + nav('/portal', { replace: true }) } - if (!instructor) return null + if (!instructor) { + return null + } return (
+ + {/* Instructor profile */}
+
-

Welcome, {instructor.name}

+

+ Welcome, {instructor.name} +

+
- @{instructor.username} • {instructor.department} • role: {instructor.role} + @{instructor.username} + {' • '} + {instructor.department} + {' • '} + role: {instructor.role}
- {instructor.apiKey && ( -
API key: {instructor.apiKey}
- )}
- + + +
+ {/* Search instructors */}
-

Find an instructor

-
+ +

+ Find an instructor +

+ + + setTerm(e.target.value)} /> - + + +
- {error &&
{error}
} - {results && ( + + {error && ( +
+ {error} +
+ )} + + {results !== null && (
-
{results.length} result(s)
+ +
+ {results.length} result(s) +
+ {results.map(r => ( -
-                {JSON.stringify(r, null, 2)}
-              
+
+
+ {r.name} +
+ +
+ {r.department} • {r.role} +
+
))} +
)} +
+ {/* Public instructor directory */}
-

Directory

+ +

+ Directory +

+
+ {directory.map(d => ( -
-
{d.name}
-
{d.department} • {d.role}
+
+ +
+ {d.name} +
+ +
+ {d.department} • {d.role} +
+
))} - {directory.length === 0 &&
No instructors.
} + + {directory.length === 0 && ( +
+ No instructors. +
+ )} +
+
+
) } diff --git a/client/src/pages/InstructorLogin.jsx b/client/src/pages/InstructorLogin.jsx index dbd2c55..1768e2d 100644 --- a/client/src/pages/InstructorLogin.jsx +++ b/client/src/pages/InstructorLogin.jsx @@ -1,50 +1,99 @@ + import { useState } from 'react' import { useNavigate } from 'react-router-dom' import { api } from '../api' -// Instructor Portal login. This portal is separate from the student JWT auth -// (AuthContext) — it has its own simple session stored in localStorage. -// -// The form sends plain strings (honest use). The backing endpoint is -// intentionally vulnerable to NoSQL injection; see Flow.md for the lab. export default function InstructorLogin() { const nav = useNavigate() + const [username, setUsername] = useState('') const [password, setPassword] = useState('') const [error, setError] = useState('') + const [loading, setLoading] = useState(false) async function handleSubmit(e) { e.preventDefault() setError('') + setLoading(true) + try { - const res = await api.post('/instructors/login', { username, password }) - localStorage.setItem('instructor', JSON.stringify(res.data.instructor)) - nav('/portal/dashboard') + const res = await api.post('/instructors/login', { + username, + password + }) + + const { token, instructor } = res.data + + if (!token || !instructor) { + throw new Error('Invalid login response') + } + + // Store instructor session + localStorage.setItem( + 'instructor', + JSON.stringify(instructor) + ) + + localStorage.setItem('instructorToken', token) + + // Redirect to dashboard + nav('/portal/dashboard', { replace: true }) + } catch (err) { - setError(err?.response?.data?.message || 'Login failed') + setError( + err?.response?.data?.message || + err?.message || + 'Login failed' + ) + } finally { + setLoading(false) } } return (
-

Instructor Portal

-

Staff sign-in

+ +

+ Instructor Portal +

+ +

+ Staff sign-in +

+
+ setUsername(e.target.value)} + required /> + setPassword(e.target.value)} + required /> - {error &&
{error}
} - + + {error && ( +
+ {error} +
+ )} + + +
) diff --git a/package-lock.json b/package-lock.json index 997c257..9f85562 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3488,6 +3488,15 @@ "url": "https://opencollective.com/express" } }, + "node_modules/express-mongo-sanitize": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/express-mongo-sanitize/-/express-mongo-sanitize-2.2.0.tgz", + "integrity": "sha512-PZBs5nwhD6ek9ZuP+W2xmpvcrHwXZxD5GdieX2dsjPbAbH4azOkrHbycBud2QRU+YQF1CT+pki/lZGedHgo/dQ==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/express/node_modules/debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", @@ -7871,8 +7880,9 @@ "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.19.2", - "joi": "^17.12.3", - "jsonwebtoken": "^9.0.2", + "express-mongo-sanitize": "^2.2.0", + "joi": "^17.13.9", + "jsonwebtoken": "^9.0.3", "mongoose": "^8.6.0", "morgan": "^1.10.0" }, diff --git a/server/package.json b/server/package.json index 5bb00a3..a90196c 100644 --- a/server/package.json +++ b/server/package.json @@ -19,8 +19,9 @@ "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.19.2", - "joi": "^17.12.3", - "jsonwebtoken": "^9.0.2", + "express-mongo-sanitize": "^2.2.0", + "joi": "^17.13.9", + "jsonwebtoken": "^9.0.3", "mongoose": "^8.6.0", "morgan": "^1.10.0" }, diff --git a/server/src/app.js b/server/src/app.js index c975cd0..a08d86f 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -1,6 +1,9 @@ + import express from 'express'; import morgan from 'morgan'; import cors from 'cors'; +import mongoSanitize from 'express-mongo-sanitize'; + import authRoutes from './routes/auth.js'; import reviewRoutes from './routes/reviews.js'; import userRoutes from './routes/users.js'; @@ -9,10 +12,37 @@ import instructorRoutes from './routes/instructors.js'; const app = express(); app.use(morgan('dev')); -app.use(cors({ origin: 'http://localhost:5175', credentials: false })); +app.use(cors({ + origin: 'http://localhost:5175', + credentials: false +})); + app.use(express.json()); -app.get('/api/health', (req, res) => res.json({ ok: true })); +// Reject MongoDB injection operators +app.use((req, res, next) => { + try { + if ( + mongoSanitize.has(req.body || {}) || + mongoSanitize.has(req.query || {}) || + mongoSanitize.has(req.params || {}) + ) { + return res.status(400).json({ + message: 'Invalid request parameters' + }); + } + + next(); + } catch (error) { + return res.status(400).json({ + message: 'Invalid request' + }); + } +}); + +app.get('/api/health', (req, res) => { + res.json({ ok: true }); +}); app.use('/api/auth', authRoutes); app.use('/api/reviews', reviewRoutes); @@ -21,13 +51,18 @@ app.use('/api/instructors', instructorRoutes); // Not found app.use((req, res) => { - res.status(404).json({ message: 'Not Found' }); + res.status(404).json({ + message: 'Not Found' + }); }); // Error handler app.use((err, req, res, next) => { console.error(err); - res.status(err.status || 500).json({ message: err.message || 'Server Error' }); + + res.status(err.status || 500).json({ + message: err.message || 'Server Error' + }); }); export default app; diff --git a/server/src/controllers/instructorController.js b/server/src/controllers/instructorController.js index 2a3582d..ad3fa2a 100644 --- a/server/src/controllers/instructorController.js +++ b/server/src/controllers/instructorController.js @@ -1,69 +1,116 @@ + +import Joi from 'joi'; +import bcrypt from 'bcryptjs'; +import jwt from 'jsonwebtoken'; + import { Instructor } from '../models/Instructor.js'; -// ============================================================================= -// INSTRUCTOR PORTAL CONTROLLER — ⚠️ INTENTIONALLY VULNERABLE (security lab) -// ============================================================================= -// -// Unlike the review/auth controllers in this project, these handlers do NOT -// validate input with Joi and the app has NO express-mongo-sanitize. They pass -// `req.body` / `req.query` straight into Mongoose. Because Express parses JSON -// bodies and bracket-notation query strings into nested objects, an attacker -// can smuggle MongoDB query operators ($ne, $gt, $regex, $where, ...) into -// what the code treats as plain strings. -// -// This is the bug students must find and fix. Do not "clean this up". -// ============================================================================= +// Public fields only +const PUBLIC_FIELDS = 'name username department role'; function publicProfile(doc) { - // A successful login is a "trophy": we deliberately return the sensitive - // fields so a bypass clearly reveals what it compromised. return { id: doc._id.toString(), name: doc.name, username: doc.username, department: doc.department, - role: doc.role, - apiKey: doc.apiKey, - privateEmail: doc.privateEmail, - privatePhone: doc.privatePhone + role: doc.role }; } +// Validate login input +const loginSchema = Joi.object({ + username: Joi.string() + .trim() + .min(1) + .max(100) + .required(), + + password: Joi.string() + .min(1) + .required() +}).required(); + +// Validate search input +const searchSchema = Joi.object({ + name: Joi.string().trim().min(1).max(100), + username: Joi.string().trim().min(1).max(100), + department: Joi.string().trim().min(1).max(100), + role: Joi.string().valid('instructor', 'superadmin') +}).min(1).required(); + // POST /api/instructors/login export async function loginInstructor(req, res, next) { try { - const { username, password } = req.body; - if (username === undefined || password === undefined) { - return res.status(400).json({ message: 'username and password are required' }); + const { error, value } = loginSchema.validate( + req.body, + { + convert: false, + allowUnknown: false + } + ); + + if (error) { + return res.status(400).json({ + message: 'Invalid login input' + }); } - // ⚠️ VULNERABLE (NoSQL injection): `username` and `password` are placed - // directly into the query. Honest clients send strings, but a crafted body - // like {"username":{"$ne":null},"password":{"$ne":null}} turns this into a - // filter that matches any account (authentication bypass). With - // {"password":{"$regex":"^S"}} the success/failure response becomes an - // oracle for extracting the stored password one character at a time. - const instructor = await Instructor.findOne({ username, password }); + const instructor = await Instructor.findOne({ + username: value.username + }).select('+password'); if (!instructor) { - return res.status(401).json({ message: 'Invalid credentials' }); + return res.status(401).json({ + message: 'Invalid credentials' + }); } - return res.json({ instructor: publicProfile(instructor) }); + + const matches = await bcrypt.compare( + value.password, + instructor.password + ); + + if (!matches) { + return res.status(401).json({ + message: 'Invalid credentials' + }); + } + + const token = jwt.sign( + { + id: instructor._id.toString(), + role: instructor.role, + accountType: 'instructor' + }, + process.env.JWT_SECRET, + { + expiresIn: process.env.JWT_EXPIRES_IN || '7d' + } + ); + + return res.json({ + token, + instructor: publicProfile(instructor) + }); + } catch (err) { next(err); } } // GET /api/instructors -// Public directory. Deliberately limited fields so the contrast with the -// leaky /search endpoint below is obvious. export async function getDirectory(req, res, next) { try { const instructors = await Instructor.find() - .select('name department role') + .select(PUBLIC_FIELDS) .sort({ name: 1 }) .lean(); - res.json({ instructors }); + + return res.json({ + instructors + }); + } catch (err) { next(err); } @@ -72,16 +119,43 @@ export async function getDirectory(req, res, next) { // GET /api/instructors/search export async function searchInstructors(req, res, next) { try { - // ⚠️ VULNERABLE (NoSQL injection): the entire query string is used as the - // MongoDB filter and full documents (incl. password / apiKey / private - // contact info) are returned. Examples of what this allows: - // ?name=Smith -> intended, honest use - // ?role[$ne]=instructor -> operator injection, leaks superadmin - // ?username[$regex]=^admin -> regex enumeration - // ?$where=this.password.length>10 -> server-side JavaScript execution - const filter = req.query; - const instructors = await Instructor.find(filter).lean(); - res.json({ count: instructors.length, instructors }); + const { error, value } = searchSchema.validate( + req.query, + { + convert: false, + allowUnknown: false + } + ); + + if (error) { + return res.status(400).json({ + message: 'Invalid search parameters' + }); + } + + // Build a safe filter + const filter = {}; + + for (const key of [ + 'name', + 'username', + 'department', + 'role' + ]) { + if (value[key] !== undefined) { + filter[key] = value[key]; + } + } + + const instructors = await Instructor.find(filter) + .select(PUBLIC_FIELDS) + .lean(); + + return res.json({ + count: instructors.length, + instructors + }); + } catch (err) { next(err); } diff --git a/server/src/models/Instructor.js b/server/src/models/Instructor.js index c5ea0e0..60209e8 100644 --- a/server/src/models/Instructor.js +++ b/server/src/models/Instructor.js @@ -1,26 +1,70 @@ + import mongoose from 'mongoose'; +import bcrypt from 'bcryptjs'; -// Instructor Portal account. -// -// NOTE (security lab): this model is intentionally insecure. Passwords are -// stored in PLAINTEXT (never do this in real code) so that the NoSQL injection -// lab can demonstrate blind $regex password extraction. The apiKey / private -// contact fields are "trophy" data that filter-injection attacks can leak. const instructorSchema = new mongoose.Schema( { - name: { type: String, required: true }, - username: { type: String, required: true, unique: true, trim: true }, - // ⚠️ VULNERABLE (lab): plaintext password, no bcrypt hashing. - password: { type: String, required: true }, - department: { type: String }, - role: { type: String, default: 'instructor' }, // 'instructor' | 'superadmin' - - // Sensitive "trophy" fields the directory hides but injection can leak. - apiKey: { type: String }, - privateEmail: { type: String }, - privatePhone: { type: String } + name: { + type: String, + required: true + }, + + username: { + type: String, + required: true, + unique: true, + trim: true + }, + + password: { + type: String, + required: true, + select: false + }, + + department: { + type: String + }, + + role: { + type: String, + enum: ['instructor', 'superadmin'], + default: 'instructor' + }, + + apiKey: { + type: String, + select: false + }, + + privateEmail: { + type: String, + select: false + }, + + privatePhone: { + type: String, + select: false + } }, - { timestamps: true } + { + timestamps: true + } ); -export const Instructor = mongoose.model('Instructor', instructorSchema); +// Hash password before saving +instructorSchema.pre('save', async function () { + if (!this.isModified('password')) { + return; + } + + this.password = await bcrypt.hash( + this.password, + 12 + ); +}); + +export const Instructor = mongoose.model( + 'Instructor', + instructorSchema +); diff --git a/server/src/seed/instructors.js b/server/src/seed/instructors.js index 396a941..ea8d5d9 100644 --- a/server/src/seed/instructors.js +++ b/server/src/seed/instructors.js @@ -1,11 +1,14 @@ + import dotenv from 'dotenv'; dotenv.config(); + import mongoose from 'mongoose'; +import { randomBytes } from 'node:crypto'; + import { connectDB } from '../config/db.js'; import { Instructor } from '../models/Instructor.js'; -// Seed data for the Instructor Portal NoSQL injection lab. -// Passwords are plaintext ON PURPOSE (see Instructor model / Flow.md). +// Demo instructor accounts const instructors = [ { name: 'Prof. Alice Smith', @@ -35,32 +38,48 @@ const instructors = [ privatePhone: '+1-555-0103' }, { - // The high-value target: the only superadmin, holding the API key. name: 'Portal Administrator', username: 'admin', password: 'S3cr3t-Admin-Pw!', department: 'IT', role: 'superadmin', - apiKey: 'sk_live_9f3b2c7d8e4a1b6f0d5c2a9e', + apiKey: randomBytes(24).toString('hex'), privateEmail: 'root@university.edu', privatePhone: '+1-555-0000' } ]; async function run() { - await connectDB(); - await Instructor.deleteMany({}); - const created = await Instructor.insertMany(instructors); - console.log(`Seeded ${created.length} instructor(s):`); - for (const i of created) { - console.log(` - ${i.username} (${i.role})`); + try { + await connectDB(); + + // WARNING: + // This deletes all existing instructors. + // Only run against the lab database. + await Instructor.deleteMany({}); + + // create() triggers password hashing + const created = await Instructor.create(instructors); + + console.log( + `Seeded ${created.length} instructor(s):` + ); + + for (const instructor of created) { + console.log( + `- ${instructor.username} (${instructor.role})` + ); + } + + console.log('Done.'); + + } catch (err) { + console.error('Seed failed:', err); + process.exitCode = 1; + + } finally { + await mongoose.disconnect(); } - await mongoose.disconnect(); - console.log('Done.'); - process.exit(0); } -run().catch((err) => { - console.error('Seed failed:', err); - process.exit(1); -}); +run(); From 7cb7ece0819f1ae0ede8d3c22cb3889277f00ffb Mon Sep 17 00:00:00 2001 From: youssifmedhat270 <134234884+youssifmedhat270@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:26:09 +0200 Subject: [PATCH 2/5] Testing changes --- .github/workflows/ci.yaml | 19 ++ server/tests/helpers/testEnv.js | 83 +++++++++ server/tests/instructor-injection.test.js | 210 ++++++++++++++++++++++ 3 files changed, 312 insertions(+) create mode 100644 .github/workflows/ci.yaml create mode 100644 server/tests/helpers/testEnv.js create mode 100644 server/tests/instructor-injection.test.js diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 0000000..cebc8f5 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,19 @@ +name: Instructor Portal security tests +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-22.04 # 22.04 has libssl1.1 for mongod 6.0.x + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm # uses the root package-lock.json + - name: Cache mongod binary + uses: actions/cache@v4 + with: + path: ~/.cache/mongodb-binaries + key: mongodb-memory-server-6.0.14-${{ runner.os }} + - run: npm ci # installs the server+client workspaces + - run: npm test --workspace server \ No newline at end of file diff --git a/server/tests/helpers/testEnv.js b/server/tests/helpers/testEnv.js new file mode 100644 index 0000000..c7a688a --- /dev/null +++ b/server/tests/helpers/testEnv.js @@ -0,0 +1,83 @@ +// Shared test environment for the Instructor Portal security suite. +// +// Spins up a throwaway in-memory MongoDB (a REAL mongod, so server-side +// operators like $regex and $where genuinely execute) and seeds it with the +// same accounts as src/seed/instructors.js. +// +// Seeding goes through Instructor.create(), so whatever hooks the project's own +// model defines run naturally: +// - vulnerable project -> no hook, password stored in plaintext +// - solution project -> pre('save') bcrypt hash +// The suite therefore exercises each project's real behavior with identical code. + +import mongoose from 'mongoose'; +import { MongoMemoryServer } from 'mongodb-memory-server'; +import { Instructor } from '../../src/models/Instructor.js'; + +let mongod; + +// The portal accounts under test. The `admin` superadmin is the high-value +// target holding the trophy fields (apiKey / private contact info). +export const ADMIN_PASSWORD = 'S3cr3t-Admin-Pw!'; +export const ADMIN_API_KEY = 'sk_live_9f3b2c7d8e4a1b6f0d5c2a9e'; + +export const SEED = [ + { + name: 'Prof. Alice Smith', + username: 'prof.smith', + password: 'password123', + department: 'CS', + role: 'instructor', + privateEmail: 'alice.smith@university.edu', + privatePhone: '+1-555-0101' + }, + { + name: 'Prof. Brian Jones', + username: 'prof.jones', + password: 'mathRules!', + department: 'Math', + role: 'instructor', + privateEmail: 'brian.jones@university.edu', + privatePhone: '+1-555-0102' + }, + { + name: 'Prof. Chen Lee', + username: 'prof.lee', + password: 'linalg2024', + department: 'Math', + role: 'instructor', + privateEmail: 'chen.lee@university.edu', + privatePhone: '+1-555-0103' + }, + { + name: 'Portal Administrator', + username: 'admin', + password: ADMIN_PASSWORD, + department: 'IT', + role: 'superadmin', + apiKey: ADMIN_API_KEY, + privateEmail: 'root@university.edu', + privatePhone: '+1-555-0000' + } +]; + +// Fields that must NEVER appear in any directory/search response or in an +// authentication-bypass trophy. If a test ever sees one of these on a returned +// object, a secret has leaked. +export const SECRET_FIELDS = ['password', 'apiKey', 'privateEmail', 'privatePhone']; + +export async function startDb() { + mongod = await MongoMemoryServer.create(); + await mongoose.connect(mongod.getUri(), { autoIndex: true }); +} + +export async function stopDb() { + await mongoose.disconnect(); + if (mongod) await mongod.stop(); +} + +export async function seed() { + await Instructor.deleteMany({}); + // create() (not insertMany) so a project's pre('save') hook runs if present. + await Instructor.create(SEED); +} diff --git a/server/tests/instructor-injection.test.js b/server/tests/instructor-injection.test.js new file mode 100644 index 0000000..652c80a --- /dev/null +++ b/server/tests/instructor-injection.test.js @@ -0,0 +1,210 @@ +// ============================================================================= +// Instructor Portal — NoSQL injection test suite +// ============================================================================= +// +// One suite, two outcomes: +// - Against Task-5.1-solution -> everything is GREEN (all four attacks are +// blocked and legitimate behavior still works). +// - Against the vulnerable Task-5.1 -> the four "Attack" blocks FAIL (the +// injections succeed / secrets leak), while the "Legitimate behavior" block +// stays green. +// +// The assertions check the SECURITY PROPERTY ("not logged in", "no secret field +// leaked", "no true/false oracle"), not the exact wording/status of the model +// solution, so any correct fix passes — not only this particular one. +// +// Each attack maps to a step in Flow.md. + +import { jest } from '@jest/globals'; +import request from 'supertest'; +import mongoose from 'mongoose'; + +import app from '../src/app.js'; +import { Instructor } from '../src/models/Instructor.js'; +import { + startDb, + stopDb, + seed, + SECRET_FIELDS, + ADMIN_PASSWORD +} from './helpers/testEnv.js'; + +jest.setTimeout(120000); // first run may download the mongod binary + +const api = request(app); + +// True if `obj` exposes any of the secret fields with a non-empty value. +function leaksSecret(obj) { + return SECRET_FIELDS.some( + (f) => obj != null && obj[f] !== undefined && obj[f] !== null + ); +} + +beforeAll(startDb); +afterAll(stopDb); +beforeEach(seed); + +// --------------------------------------------------------------------------- +// Attack 1 — Authentication bypass (Flow.md §2) +// Sending operators instead of string credentials must NOT log anyone in. +// --------------------------------------------------------------------------- +describe('Attack 1: authentication bypass via operator injection', () => { + test('{$ne:null}/{$ne:null} does not authenticate', async () => { + const res = await api + .post('/api/instructors/login') + .send({ username: { $ne: null }, password: { $ne: null } }); + + expect(res.status).not.toBe(200); + expect([400, 401]).toContain(res.status); + expect(res.body.instructor).toBeUndefined(); + }); + + test('{$gt:""}/{$gt:""} does not authenticate', async () => { + const res = await api + .post('/api/instructors/login') + .send({ username: { $gt: '' }, password: { $gt: '' } }); + + expect(res.status).not.toBe(200); + expect([400, 401]).toContain(res.status); + expect(res.body.instructor).toBeUndefined(); + }); +}); + +// --------------------------------------------------------------------------- +// Attack 2 — Leak hidden data via operator injection on /search (Flow.md §3) +// ?role[$ne]=instructor must not return secret fields for any account. +// --------------------------------------------------------------------------- +describe('Attack 2: operator injection on /search leaks secrets', () => { + test('?role[$ne]=instructor returns no secret fields', async () => { + const res = await api + .get('/api/instructors/search') + .query({ 'role[$ne]': 'instructor' }); + + expect(res.status).toBe(200); + const instructors = res.body.instructors || []; + const leaked = instructors.filter(leaksSecret); + expect(leaked).toEqual([]); + }); + + test('?username[$regex]=^admin returns no secret fields', async () => { + const res = await api + .get('/api/instructors/search') + .query({ 'username[$regex]': '^admin' }); + + expect(res.status).toBe(200); + const instructors = res.body.instructors || []; + expect(instructors.filter(leaksSecret)).toEqual([]); + }); +}); + +// --------------------------------------------------------------------------- +// Attack 3 — Blind password extraction via $regex oracle (Flow.md §4) +// A $regex password must (a) never log in and (b) not reveal whether the guess +// was right (same response for a right vs wrong prefix => no oracle). The stored +// password must also not be plaintext. +// --------------------------------------------------------------------------- +describe('Attack 3: $regex blind-extraction oracle', () => { + test('a $regex password object never authenticates', async () => { + const res = await api + .post('/api/instructors/login') + .send({ username: 'admin', password: { $regex: '^S' } }); + + expect(res.status).not.toBe(200); + expect(res.body.instructor).toBeUndefined(); + }); + + test('right vs wrong regex prefix are indistinguishable (no oracle)', async () => { + const right = await api + .post('/api/instructors/login') + .send({ username: 'admin', password: { $regex: '^S' } }); // matches S3cr3t... + const wrong = await api + .post('/api/instructors/login') + .send({ username: 'admin', password: { $regex: '^X' } }); // matches nothing + + expect(right.status).not.toBe(200); + expect(wrong.status).not.toBe(200); + // The attacker learns one bit per guess only if these differ. + expect(right.status).toBe(wrong.status); + }); + + test('admin password is not stored in plaintext', async () => { + const admin = await Instructor.findOne({ username: 'admin' }).select('+password'); + expect(admin).toBeTruthy(); + expect(admin.password).toBeDefined(); + expect(admin.password).not.toBe(ADMIN_PASSWORD); + }); +}); + +// --------------------------------------------------------------------------- +// Attack 4 — Server-side JavaScript execution via $where (Flow.md §5) +// $where injected through /search must not run as code nor leak secret fields. +// (mongodb-memory-server runs a local mongod that DOES allow $where, so on the +// vulnerable app this genuinely executes and leaks — which is what fails here.) +// --------------------------------------------------------------------------- +describe('Attack 4: $where server-side JavaScript injection', () => { + test('?$where=this.password.length>10 leaks no secrets', async () => { + const res = await api + .get('/api/instructors/search') + .query({ $where: 'this.password.length > 10' }); + + expect(res.status).toBe(200); + const instructors = res.body.instructors || []; + expect(instructors.filter(leaksSecret)).toEqual([]); + }); + + test("?$where=apiKey.indexOf('sk_live') leaks no secrets", async () => { + const res = await api + .get('/api/instructors/search') + .query({ $where: "this.apiKey && this.apiKey.indexOf('sk_live') === 0" }); + + expect(res.status).toBe(200); + const instructors = res.body.instructors || []; + expect(instructors.filter(leaksSecret)).toEqual([]); + }); +}); + +// --------------------------------------------------------------------------- +// Legitimate behavior — must keep working after the fix. These pass on BOTH the +// vulnerable and the solution projects (the fix must not break normal use). +// --------------------------------------------------------------------------- +describe('Legitimate behavior is preserved', () => { + test('honest login with the correct password succeeds', async () => { + const res = await api + .post('/api/instructors/login') + .send({ username: 'admin', password: ADMIN_PASSWORD }); + + expect(res.status).toBe(200); + expect(res.body.instructor).toBeDefined(); + expect(res.body.instructor.role).toBe('superadmin'); + }); + + test('honest login with a wrong password is rejected', async () => { + const res = await api + .post('/api/instructors/login') + .send({ username: 'admin', password: 'definitely-wrong' }); + + expect(res.status).toBe(401); + expect(res.body.instructor).toBeUndefined(); + }); + + test('public directory returns only safe fields', async () => { + const res = await api.get('/api/instructors'); + + expect(res.status).toBe(200); + const instructors = res.body.instructors || []; + expect(instructors.length).toBeGreaterThan(0); + expect(instructors.filter(leaksSecret)).toEqual([]); + }); + + test('honest search by name finds the matching instructor', async () => { + // Full name is used so this is green on both versions (the vulnerable + // search does an exact match; the solution does a case-insensitive contains). + const res = await api + .get('/api/instructors/search') + .query({ name: 'Prof. Alice Smith' }); + + expect(res.status).toBe(200); + const names = (res.body.instructors || []).map((i) => i.name); + expect(names).toContain('Prof. Alice Smith'); + }); +}); From 035ffa6ebd4413576a8146f1c20a1ffa482ceb2c Mon Sep 17 00:00:00 2001 From: youssifmedhat270 <134234884+youssifmedhat270@users.noreply.github.com> Date: Sat, 7 Nov 2026 13:40:20 +0200 Subject: [PATCH 3/5] Fix changes --- server/package.json | 3 +- server/src/app.js | 28 +++--- .../src/controllers/instructorController.js | 86 +++++++++++-------- 3 files changed, 69 insertions(+), 48 deletions(-) diff --git a/server/package.json b/server/package.json index a90196c..bd1e247 100644 --- a/server/package.json +++ b/server/package.json @@ -6,8 +6,7 @@ "dev": "nodemon src/index.js", "start": "node src/index.js", "seed:instructors": "node src/seed/instructors.js", - "test": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand" - }, +"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand" }, "jest": { "testEnvironment": "node", "testMatch": [ diff --git a/server/src/app.js b/server/src/app.js index a08d86f..d469a3e 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -12,6 +12,7 @@ import instructorRoutes from './routes/instructors.js'; const app = express(); app.use(morgan('dev')); + app.use(cors({ origin: 'http://localhost:5175', credentials: false @@ -19,24 +20,29 @@ app.use(cors({ app.use(express.json()); -// Reject MongoDB injection operators +// Sanitize requests instead of returning HTTP 400. +// MongoDB operators are removed before controllers run. app.use((req, res, next) => { try { - if ( - mongoSanitize.has(req.body || {}) || - mongoSanitize.has(req.query || {}) || - mongoSanitize.has(req.params || {}) - ) { - return res.status(400).json({ - message: 'Invalid request parameters' + if (req.body && typeof req.body === 'object') { + req.body = mongoSanitize.sanitize(req.body); + } + + if (req.query && typeof req.query === 'object') { + const safeQuery = mongoSanitize.sanitize( + structuredClone(req.query) + ); + + Object.defineProperty(req, 'query', { + configurable: true, + enumerable: true, + value: safeQuery }); } next(); } catch (error) { - return res.status(400).json({ - message: 'Invalid request' - }); + next(error); } }); diff --git a/server/src/controllers/instructorController.js b/server/src/controllers/instructorController.js index ad3fa2a..35bdc4c 100644 --- a/server/src/controllers/instructorController.js +++ b/server/src/controllers/instructorController.js @@ -5,7 +5,6 @@ import jwt from 'jsonwebtoken'; import { Instructor } from '../models/Instructor.js'; -// Public fields only const PUBLIC_FIELDS = 'name username department role'; function publicProfile(doc) { @@ -18,7 +17,6 @@ function publicProfile(doc) { }; } -// Validate login input const loginSchema = Joi.object({ username: Joi.string() .trim() @@ -31,14 +29,6 @@ const loginSchema = Joi.object({ .required() }).required(); -// Validate search input -const searchSchema = Joi.object({ - name: Joi.string().trim().min(1).max(100), - username: Joi.string().trim().min(1).max(100), - department: Joi.string().trim().min(1).max(100), - role: Joi.string().valid('instructor', 'superadmin') -}).min(1).required(); - // POST /api/instructors/login export async function loginInstructor(req, res, next) { try { @@ -77,19 +67,35 @@ export async function loginInstructor(req, res, next) { }); } + // Jest runs with NODE_ENV=test. + // Production must provide its own JWT_SECRET. + const jwtSecret = + process.env.JWT_SECRET || + ( + process.env.NODE_ENV === 'test' + ? 'task5-test-only-secret-do-not-use-in-production' + : null + ); + + if (!jwtSecret) { + return res.status(500).json({ + message: 'Authentication configuration error' + }); + } + const token = jwt.sign( { id: instructor._id.toString(), role: instructor.role, accountType: 'instructor' }, - process.env.JWT_SECRET, + jwtSecret, { expiresIn: process.env.JWT_EXPIRES_IN || '7d' } ); - return res.json({ + return res.status(200).json({ token, instructor: publicProfile(instructor) }); @@ -107,7 +113,7 @@ export async function getDirectory(req, res, next) { .sort({ name: 1 }) .lean(); - return res.json({ + return res.status(200).json({ instructors }); @@ -119,39 +125,49 @@ export async function getDirectory(req, res, next) { // GET /api/instructors/search export async function searchInstructors(req, res, next) { try { - const { error, value } = searchSchema.validate( - req.query, - { - convert: false, - allowUnknown: false - } - ); - - if (error) { - return res.status(400).json({ - message: 'Invalid search parameters' - }); - } - - // Build a safe filter - const filter = {}; - - for (const key of [ + // Explicitly allow only supported string filters. + // Never pass req.query directly to MongoDB. + const allowedFields = [ 'name', 'username', 'department', 'role' - ]) { - if (value[key] !== undefined) { - filter[key] = value[key]; + ]; + + const filter = {}; + + for (const field of allowedFields) { + const value = req.query[field]; + + // Ignore objects, arrays, and injected operators. + if (typeof value !== 'string') { + continue; } + + if (!value.trim()) { + continue; + } + + // Restrict the values to valid text. + const { error } = Joi.string() + .trim() + .min(1) + .max(100) + .validate(value, { convert: false }); + + if (error) { + continue; + } + + filter[field] = value.trim(); } const instructors = await Instructor.find(filter) .select(PUBLIC_FIELDS) + .sort({ name: 1 }) .lean(); - return res.json({ + return res.status(200).json({ count: instructors.length, instructors }); From b0b48c81db9c0810831eb3b69984e08f720126dc Mon Sep 17 00:00:00 2001 From: youssifmedhat270 <134234884+youssifmedhat270@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:01:23 +0200 Subject: [PATCH 4/5] test --- server/src/app.js | 1 + 1 file changed, 1 insertion(+) diff --git a/server/src/app.js b/server/src/app.js index d469a3e..9e4bf63 100644 --- a/server/src/app.js +++ b/server/src/app.js @@ -72,3 +72,4 @@ app.use((err, req, res, next) => { }); export default app; +// test comment \ No newline at end of file From 14ac9804ad1a5d54d62f9164fb5478cfc34a4fcf Mon Sep 17 00:00:00 2001 From: youssifmedhat270 <134234884+youssifmedhat270@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:06:15 +0200 Subject: [PATCH 5/5] test --- package-lock.json | 26 ++++++++++++++++++++++++++ server/package.json | 4 +++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index 9f85562..7dc74b1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -580,6 +580,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@epic-web/invariant": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@epic-web/invariant/-/invariant-1.0.0.tgz", + "integrity": "sha512-lrTPqgvfFQtR/eY/qkIzp98OGdNJu0m5ji3q/nJI8v3SXkRKEnWiOxMmbvcSoAIzv/cGiuvRy57k4suKQSAdwA==", + "dev": true, + "license": "MIT" + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", @@ -3002,6 +3009,24 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/cross-env": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz", + "integrity": "sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@epic-web/invariant": "^1.0.0", + "cross-spawn": "^7.0.6" + }, + "bin": { + "cross-env": "dist/bin/cross-env.js", + "cross-env-shell": "dist/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -7887,6 +7912,7 @@ "morgan": "^1.10.0" }, "devDependencies": { + "cross-env": "^10.1.0", "jest": "^29.7.0", "mongodb-memory-server": "^9.5.0", "nodemon": "^3.1.0", diff --git a/server/package.json b/server/package.json index bd1e247..f48eb75 100644 --- a/server/package.json +++ b/server/package.json @@ -6,7 +6,8 @@ "dev": "nodemon src/index.js", "start": "node src/index.js", "seed:instructors": "node src/seed/instructors.js", -"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand" }, + "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand" + }, "jest": { "testEnvironment": "node", "testMatch": [ @@ -25,6 +26,7 @@ "morgan": "^1.10.0" }, "devDependencies": { + "cross-env": "^10.1.0", "jest": "^29.7.0", "mongodb-memory-server": "^9.5.0", "nodemon": "^3.1.0",