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/.gitignore b/.gitignore
index 177447d..8648236 100644
--- a/.gitignore
+++ b/.gitignore
@@ -26,4 +26,5 @@ Thumbs.db
# Server-side specific ignores (if server is in a subfolder)
server/node_modules/
-server/build/
\ No newline at end of file
+server/build/
+server/.local-demo/
diff --git a/Flow.md b/Flow.md
index 02c5641..411331a 100644
--- a/Flow.md
+++ b/Flow.md
@@ -1,5 +1,10 @@
# NoSQL Injection Lab — Instructor Portal
+> This walkthrough describes the original vulnerable implementation. After the
+> security fix, operator requests should return **400**, not the success
+> responses shown below. See `SECURITY.md` for implementation and verification
+> details, including which checks have actually been run locally.
+
This walkthrough shows you how to attack the **Instructor Portal** of the Course
Review Board and, step by step, *why* each attack works. You will:
diff --git a/client/src/pages/InstructorDashboard.jsx b/client/src/pages/InstructorDashboard.jsx
index 1dd0ded..62c12eb 100644
--- a/client/src/pages/InstructorDashboard.jsx
+++ b/client/src/pages/InstructorDashboard.jsx
@@ -4,8 +4,7 @@ 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.
+// Search returns public directory fields and treats the name as literal text.
export default function InstructorDashboard() {
const nav = useNavigate()
const [instructor, setInstructor] = useState(null)
@@ -58,9 +57,6 @@ export default function InstructorDashboard() {
@{instructor.username} • {instructor.department} • role: {instructor.role}
- {instructor.apiKey && (
- API key: {instructor.apiKey}
- )}
Log out
diff --git a/client/src/pages/InstructorLogin.jsx b/client/src/pages/InstructorLogin.jsx
index dbd2c55..6c4aecd 100644
--- a/client/src/pages/InstructorLogin.jsx
+++ b/client/src/pages/InstructorLogin.jsx
@@ -5,8 +5,7 @@ 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.
+// The backing endpoint validates string credentials and verifies a bcrypt hash.
export default function InstructorLogin() {
const nav = useNavigate()
const [username, setUsername] = useState('')
diff --git a/package-lock.json b/package-lock.json
index 997c257..c570e0e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -3488,6 +3488,10 @@
"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"
+ },
"node_modules/express/node_modules/debug": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
@@ -7871,6 +7875,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
+ "express-mongo-sanitize": "^2.2.0",
"joi": "^17.12.3",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.6.0",
diff --git a/package.json b/package.json
index 140dedd..84f6624 100644
--- a/package.json
+++ b/package.json
@@ -7,9 +7,9 @@
],
"scripts": {
"install:all": "npm --workspaces install",
- "dev": "concurrently -n server,client -c blue,magenta \"npm:dev --workspace server\" \"npm:dev --workspace client\""
+ "dev": "concurrently -n server,client -c blue,magenta \"npm --prefix server run dev\" \"npm --prefix client run dev\""
},
"devDependencies": {
"concurrently": "^8.2.2"
}
-}
\ No newline at end of file
+}
diff --git a/server/package.json b/server/package.json
index 5bb00a3..7d637c5 100644
--- a/server/package.json
+++ b/server/package.json
@@ -5,8 +5,11 @@
"scripts": {
"dev": "nodemon src/index.js",
"start": "node src/index.js",
+ "dev:db": "node src/seed/localDemoDb.js",
"seed:instructors": "node src/seed/instructors.js",
- "test": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand"
+ "migrate:instructor-passwords": "node src/seed/migrateInstructorPasswords.js",
+ "test:unit": "node --test tests/instructor-controller.check.js",
+ "test": "node --experimental-vm-modules ../node_modules/jest/bin/jest.js --runInBand"
},
"jest": {
"testEnvironment": "node",
@@ -19,6 +22,7 @@
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
+ "express-mongo-sanitize": "^2.2.0",
"joi": "^17.12.3",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.6.0",
diff --git a/server/src/controllers/instructorController.js b/server/src/controllers/instructorController.js
index 2a3582d..0875fcd 100644
--- a/server/src/controllers/instructorController.js
+++ b/server/src/controllers/instructorController.js
@@ -1,86 +1,62 @@
+import Joi from 'joi';
+import bcrypt from 'bcryptjs';
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".
-// =============================================================================
+const loginSchema = Joi.object({
+ username: Joi.string().max(100).required(),
+ // bcrypt uses at most 72 bytes. Never trim or otherwise alter passwords.
+ password: Joi.string().required().custom((value, helpers) =>
+ Buffer.byteLength(value, 'utf8') <= 72 ? value : helpers.error('any.invalid'))
+}).required();
+const searchSchema = Joi.object({
+ name: Joi.string().max(100).allow(''),
+ department: Joi.string().max(100),
+ role: Joi.string().valid('instructor', 'superadmin')
+}).required();
+const validationOptions = { convert: false, abortEarly: false, allowUnknown: false };
+const directoryFields = '_id name department role';
+const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-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
- };
-}
-
-// 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' });
- }
-
- // ⚠️ 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 });
-
- if (!instructor) {
+ const { error, value } = loginSchema.validate(req.body, validationOptions);
+ if (error) return res.status(400).json({ message: 'Invalid login input' });
+ // Only a validated username enters the query; bcrypt verifies the password.
+ const instructor = await Instructor.findOne({ username: value.username }).select('+password');
+ if (!instructor || !(await bcrypt.compare(value.password, instructor.password))) {
return res.status(401).json({ message: 'Invalid credentials' });
}
- return res.json({ instructor: publicProfile(instructor) });
+ return res.json({ instructor: {
+ id: instructor._id.toString(),
+ name: instructor.name,
+ username: instructor.username,
+ department: instructor.department,
+ role: instructor.role
+ } });
} 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')
- .sort({ name: 1 })
- .lean();
+ const instructors = await Instructor.find().select(directoryFields).sort({ name: 1 }).lean();
res.json({ instructors });
} catch (err) {
next(err);
}
}
-// 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();
+ const { error, value } = searchSchema.validate(req.query, validationOptions);
+ if (error) return res.status(400).json({ message: 'Invalid search input' });
+ // Build a filter from allowed strings. Search text is literal, not regex code.
+ const filter = {};
+ if (value.name) filter.name = { $regex: escapeRegex(value.name), $options: 'i' };
+ if (value.department) filter.department = value.department;
+ if (value.role) filter.role = value.role;
+ const instructors = await Instructor.find(filter).select(directoryFields).sort({ name: 1 }).lean();
res.json({ count: instructors.length, instructors });
} catch (err) {
next(err);
diff --git a/server/src/middleware/instructorInput.js b/server/src/middleware/instructorInput.js
new file mode 100644
index 0000000..6190ec2
--- /dev/null
+++ b/server/src/middleware/instructorInput.js
@@ -0,0 +1,16 @@
+import mongoSanitize from 'express-mongo-sanitize';
+
+const sanitize = mongoSanitize({
+ onSanitize: ({ req }) => { req.unsafeInstructorInput = true; }
+});
+
+export function sanitizeInstructorInput(req, res, next) {
+ sanitize(req, res, (err) => {
+ if (err) return next(err);
+ // Silently dropping operators could broaden a search to every account.
+ if (req.unsafeInstructorInput) {
+ return res.status(400).json({ message: 'Query operators and dotted keys are not allowed' });
+ }
+ next();
+ });
+}
diff --git a/server/src/models/Instructor.js b/server/src/models/Instructor.js
index c5ea0e0..87a3bfe 100644
--- a/server/src/models/Instructor.js
+++ b/server/src/models/Instructor.js
@@ -1,26 +1,27 @@
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 },
+ password: { type: String, required: true, select: false },
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 }
+ 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 }
);
+instructorSchema.pre('save', async function () {
+ if (this.isModified('password')) {
+ if (Buffer.byteLength(this.password, 'utf8') > 72) {
+ throw new Error('Password must not exceed 72 bytes');
+ }
+ this.password = await bcrypt.hash(this.password, 12);
+ }
+});
+
export const Instructor = mongoose.model('Instructor', instructorSchema);
diff --git a/server/src/routes/instructors.js b/server/src/routes/instructors.js
index 54a0845..8a08490 100644
--- a/server/src/routes/instructors.js
+++ b/server/src/routes/instructors.js
@@ -1,4 +1,5 @@
import { Router } from 'express';
+import { sanitizeInstructorInput } from '../middleware/instructorInput.js';
import {
loginInstructor,
getDirectory,
@@ -7,8 +8,9 @@ import {
const router = Router();
-// The Instructor Portal has its own (naive, vulnerable) login — it does NOT use
-// the JWT requireAuth middleware. That is intentional for the lab.
+router.use(sanitizeInstructorInput);
+
+// The instructor portal is separate from student JWT authentication.
router.post('/login', loginInstructor);
router.get('/', getDirectory);
router.get('/search', searchInstructors);
diff --git a/server/src/seed/instructors.js b/server/src/seed/instructors.js
index 396a941..4434fd7 100644
--- a/server/src/seed/instructors.js
+++ b/server/src/seed/instructors.js
@@ -5,7 +5,7 @@ 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).
+// create() runs the model's bcrypt save hook before storing these fixtures.
const instructors = [
{
name: 'Prof. Alice Smith',
@@ -50,7 +50,7 @@ const instructors = [
async function run() {
await connectDB();
await Instructor.deleteMany({});
- const created = await Instructor.insertMany(instructors);
+ const created = await Instructor.create(instructors);
console.log(`Seeded ${created.length} instructor(s):`);
for (const i of created) {
console.log(` - ${i.username} (${i.role})`);
diff --git a/server/src/seed/localDemoDb.js b/server/src/seed/localDemoDb.js
new file mode 100644
index 0000000..4aa349a
--- /dev/null
+++ b/server/src/seed/localDemoDb.js
@@ -0,0 +1,30 @@
+// Local-only MongoDB for the TA demonstration; no system installation required.
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import { mkdir } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const dbPath = fileURLToPath(new URL('../../.local-demo/mongo-data/', import.meta.url));
+const systemBinary = fileURLToPath(new URL('../../.local-demo/bin/mongod.exe', import.meta.url));
+await mkdir(dbPath, { recursive: true });
+
+const database = await MongoMemoryServer.create({
+ binary: { version: '7.0.14', ...(existsSync(systemBinary) ? { systemBinary } : {}) },
+ instance: {
+ ip: '127.0.0.1',
+ port: 27017,
+ dbPath,
+ storageEngine: 'wiredTiger'
+ }
+});
+console.log('Local demo MongoDB ready at mongodb://127.0.0.1:27017/task51_ta_demo');
+
+let stopping = false;
+async function stop() {
+ if (stopping) return;
+ stopping = true;
+ await database.stop({ doCleanup: false });
+ process.exit(0);
+}
+process.on('SIGINT', stop);
+process.on('SIGTERM', stop);
diff --git a/server/src/seed/migrateInstructorPasswords.js b/server/src/seed/migrateInstructorPasswords.js
new file mode 100644
index 0000000..d38e733
--- /dev/null
+++ b/server/src/seed/migrateInstructorPasswords.js
@@ -0,0 +1,23 @@
+import 'dotenv/config';
+import mongoose from 'mongoose';
+import { connectDB } from '../config/db.js';
+import { Instructor } from '../models/Instructor.js';
+
+// One-time upgrade for accounts created by the original plaintext seed.
+// Use save() so hashing follows the same rules as new accounts.
+try {
+ await connectDB();
+ let migrated = 0;
+ for await (const instructor of Instructor.find().select('+password').cursor()) {
+ if (/^\$2[aby]\$\d{2}\$[./A-Za-z0-9]{53}$/.test(instructor.password)) continue;
+ instructor.markModified('password');
+ await instructor.save();
+ migrated++;
+ }
+ console.log(`Hashed passwords for ${migrated} existing instructor(s).`);
+} catch (err) {
+ console.error('Password migration failed:', err.message);
+ process.exitCode = 1;
+} finally {
+ await mongoose.disconnect();
+}
diff --git a/server/tests/helpers/testEnv.js b/server/tests/helpers/testEnv.js
new file mode 100644
index 0000000..65dbf1a
--- /dev/null
+++ b/server/tests/helpers/testEnv.js
@@ -0,0 +1,90 @@
+// 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 { existsSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+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() {
+ // Reuse the locally prepared demo runtime; tests still get their own
+ // temporary database and random port, separate from the TA demo data.
+ const localBinary = fileURLToPath(new URL('../../.local-demo/bin/mongod.exe', import.meta.url));
+ mongod = await MongoMemoryServer.create(existsSync(localBinary)
+ ? { binary: { systemBinary: localBinary, version: '7.0.14' } }
+ : {});
+ 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-controller.check.js b/server/tests/instructor-controller.check.js
new file mode 100644
index 0000000..2894573
--- /dev/null
+++ b/server/tests/instructor-controller.check.js
@@ -0,0 +1,117 @@
+// Offline checks: real controllers, Joi, bcrypt and Mongoose schema; database
+// calls are mocked. HTTP/sanitizer/storage integration is covered by Jest.
+import { test, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
+import bcrypt from 'bcryptjs';
+import { Instructor } from '../src/models/Instructor.js';
+import { loginInstructor, searchInstructors, getDirectory } from '../src/controllers/instructorController.js';
+
+afterEach(() => mock.restoreAll());
+const secrets = ['password', 'apiKey', 'privateEmail', 'privatePhone'];
+function response() {
+ return { statusCode: 200, status(code) { this.statusCode = code; return this; },
+ json(body) { this.body = body; return this; } };
+}
+function unexpected(err) { throw err; }
+
+for (const [label, body] of [
+ ['Attack 1 $ne', { username: { $ne: null }, password: { $ne: null } }],
+ ['Attack 1 $gt', { username: { $gt: '' }, password: { $gt: '' } }],
+ ...['^S', '^Se', '^S3', '^S3cr3t-Admin-Pw!$', '^X'].map(prefix =>
+ [`Attack 3 ${prefix}`, { username: 'admin', password: { $regex: prefix } }]),
+ ['array', { username: ['admin'], password: 'secret' }],
+ ['number', { username: 'admin', password: 123 }],
+ ['null', { username: null, password: 'secret' }],
+ ['missing password', { username: 'admin' }],
+ ['unknown field', { username: 'admin', password: 'secret', role: 'superadmin' }],
+ ['bcrypt byte limit', { username: 'admin', password: 'é'.repeat(37) }]
+]) {
+ test(`login rejects ${label} before querying`, async () => {
+ const find = mock.method(Instructor, 'findOne', () => { throw new Error('Database reached'); });
+ const res = response();
+ await loginInstructor({ body }, res, unexpected);
+ assert.equal(res.statusCode, 400);
+ assert.equal(find.mock.callCount(), 0);
+ assert.equal(res.body.instructor, undefined);
+ });
+}
+
+for (const [label, query] of [
+ ['Attack 2 $ne', { role: { $ne: 'instructor' } }],
+ ['Attack 2 $regex', { username: { $regex: '^admin' } }],
+ ['Attack 2 bracket key', { 'role[$ne]': 'instructor' }],
+ ['Attack 4 password', { $where: 'this.password.length>10' }],
+ ['Attack 4 apiKey', { $where: "this.apiKey && this.apiKey.indexOf('sk_live')===0" }],
+ ['dotted key', { 'name.$ne': 'Smith' }],
+ ['array', { name: ['Smith', 'Jones'] }],
+ ['private filter', { privateEmail: 'root@university.edu' }]
+]) {
+ test(`search rejects ${label} before querying`, async () => {
+ const find = mock.method(Instructor, 'find', () => { throw new Error('Database reached'); });
+ const res = response();
+ await searchInstructors({ query }, res, unexpected);
+ assert.equal(res.statusCode, 400);
+ assert.equal(find.mock.callCount(), 0);
+ });
+}
+
+const hash = await bcrypt.hash('correct password', 4);
+for (const [password, status] of [['correct password', 200], ['wrong', 401]]) {
+ test(`honest login returns ${status}`, async () => {
+ mock.method(Instructor, 'findOne', filter => {
+ assert.deepEqual(filter, { username: 'admin' });
+ return { select: async fields => {
+ assert.equal(fields, '+password');
+ return { _id: '123', name: 'Admin', username: 'admin', role: 'superadmin',
+ department: 'IT', password: hash, apiKey: 'secret', privateEmail: 'secret' };
+ } };
+ });
+ const res = response();
+ await loginInstructor({ body: { username: 'admin', password } }, res, unexpected);
+ assert.equal(res.statusCode, status);
+ for (const key of secrets) assert.equal(res.body.instructor?.[key], undefined);
+ });
+}
+
+for (const [name, expected] of [['sMiTh', 'sMiTh'], ['.*', '\\.\\*'], ['[a]+(b)$', '\\[a\\]\\+\\(b\\)\\$']]) {
+ test(`search builds a literal filter for ${name}`, async () => {
+ mock.method(Instructor, 'find', filter => {
+ assert.deepEqual(filter, { name: { $regex: expected, $options: 'i' }, department: 'CS' });
+ return { select(fields) {
+ assert.equal(fields, '_id name department role');
+ return { sort: () => ({ lean: async () => [] }) };
+ } };
+ });
+ const res = response();
+ await searchInstructors({ query: { name, department: 'CS' } }, res, unexpected);
+ assert.deepEqual(res.body, { count: 0, instructors: [] });
+ });
+}
+
+test('directory uses an inclusive public projection', async () => {
+ mock.method(Instructor, 'find', () => ({ select(fields) {
+ assert.equal(fields, '_id name department role');
+ return { sort: () => ({ lean: async () => [] }) };
+ } }));
+ const res = response();
+ await getDirectory({}, res, unexpected);
+ assert.deepEqual(res.body, { instructors: [] });
+});
+
+test('private fields are excluded by default', () => {
+ for (const key of secrets) assert.equal(Instructor.schema.path(key).options.select, false);
+});
+
+test('save hook hashes passwords and does not rehash unchanged passwords', async () => {
+ const doc = new Instructor({ name: 'Test', username: 'test', password: 'correct password' });
+ const runHook = () => new Promise((resolve, reject) => {
+ Instructor.schema.s.hooks.execPre('save', doc, [], err => err ? reject(err) : resolve());
+ });
+ await runHook();
+ assert.notEqual(doc.password, 'correct password');
+ assert.equal(await bcrypt.compare('correct password', doc.password), true);
+ const savedHash = doc.password;
+ doc.$__reset();
+ await runHook();
+ assert.equal(doc.password, savedHash);
+});
diff --git a/server/tests/instructor-injection.test.js b/server/tests/instructor-injection.test.js
new file mode 100644
index 0000000..9539e90
--- /dev/null
+++ b/server/tests/instructor-injection.test.js
@@ -0,0 +1,266 @@
+// =============================================================================
+// 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 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);
+afterEach(() => jest.restoreAllMocks());
+
+// ---------------------------------------------------------------------------
+// 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(400);
+ 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(400);
+ 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(400);
+ 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(400);
+ 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');
+ });
+});
+
+// Reject malformed requests before they reach the database, including on a
+// database tier that would otherwise permit $where.
+describe('Invalid input never reaches MongoDB', () => {
+ test.each([
+ { username: { $ne: null }, password: { $ne: null } },
+ { username: { $gt: '' }, password: { $gt: '' } },
+ { username: 'admin', password: { $regex: '^S' } },
+ { username: 'admin', password: { $regex: '^X' } },
+ { username: ['admin'], password: 'secret' },
+ { username: 'admin', password: 123 },
+ { username: 'admin', password: 'secret', role: 'superadmin' },
+ { username: 'admin', password: 'é'.repeat(37) }
+ ])('rejects invalid login %#', async (body) => {
+ const find = jest.spyOn(Instructor, 'findOne');
+ const res = await api.post('/api/instructors/login').send(body);
+ expect(res.status).toBe(400);
+ expect(find).not.toHaveBeenCalled();
+ });
+
+ test.each([
+ { 'role[$ne]': 'instructor' },
+ { 'username[$regex]': '^admin' },
+ { $where: 'this.password.length>10' },
+ { $where: "this.apiKey && this.apiKey.indexOf('sk_live')===0" },
+ { 'name.$ne': 'Smith' },
+ { name: ['Smith', 'Jones'] },
+ { password: 'secret' },
+ { apiKey: 'secret' }
+ ])('rejects invalid search %#', async (query) => {
+ const find = jest.spyOn(Instructor, 'find');
+ const res = await api.get('/api/instructors/search').query(query);
+ expect(res.status).toBe(400);
+ expect(find).not.toHaveBeenCalled();
+ });
+
+ test('partial case-insensitive search works and returns only public fields', async () => {
+ const res = await api.get('/api/instructors/search').query({ name: 'sMiTh' });
+ expect(res.status).toBe(200);
+ expect(res.body.count).toBe(1);
+ expect(Object.keys(res.body.instructors[0]).sort()).toEqual(['_id', 'department', 'name', 'role']);
+ });
+
+ test('regex metacharacters are searched literally', async () => {
+ const res = await api.get('/api/instructors/search').query({ name: '.*' });
+ expect(res.status).toBe(200);
+ expect(res.body.count).toBe(0);
+ });
+
+ test('successful login does not leak private fields', async () => {
+ const res = await api.post('/api/instructors/login').send({ username: 'admin', password: ADMIN_PASSWORD });
+ expect(res.status).toBe(200);
+ expect(leaksSecret(res.body.instructor)).toBe(false);
+ });
+});