diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
new file mode 100644
index 0000000..ea5ab25
--- /dev/null
+++ b/.github/workflows/ci.yaml
@@ -0,0 +1,21 @@
+name: Instructor Portal security tests
+on: [push, pull_request]
+
+jobs:
+ test:
+ runs-on: ubuntu-22.04
+ env:
+ MONGOMS_VERSION: 7.0.14
+ 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-7.0.14-${{ runner.os }}
+ - run: npm ci # installs the server+client workspaces
+ - run: npm test --workspace server
diff --git a/.gitignore b/.gitignore
index 177447d..43be891 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,7 @@
# Node.js dependencies
node_modules/
+.npm-cache/
+.cache/
# Build artifacts
build/
@@ -26,4 +28,4 @@ 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/
diff --git a/.vscode/setupCI.js b/.vscode/setupCI.js
index e1ba46d..fc11cbf 100644
--- a/.vscode/setupCI.js
+++ b/.vscode/setupCI.js
@@ -9,7 +9,9 @@ on: [push, pull_request]
jobs:
test:
- runs-on: ubuntu-22.04 # 22.04 has libssl1.1 for mongod 6.0.x
+ runs-on: ubuntu-22.04
+ env:
+ MONGOMS_VERSION: 7.0.14
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@@ -20,11 +22,11 @@ jobs:
uses: actions/cache@v4
with:
path: ~/.cache/mongodb-binaries
- key: mongodb-memory-server-6.0.14-\${{ runner.os }}
+ key: mongodb-memory-server-7.0.14-\${{ runner.os }}
- run: npm ci # installs the server+client workspaces
- run: npm test --workspace server`;
if (!fs.existsSync(workflowDir)) {
fs.mkdirSync(workflowDir, { recursive: true });
}
-fs.writeFileSync(filePath, ciContent, { encoding: 'utf8' });
\ No newline at end of file
+fs.writeFileSync(filePath, ciContent, { encoding: 'utf8' });
diff --git a/.vscode/setupHelper.js b/.vscode/setupHelper.js
index 97842a7..1afb5e4 100644
--- a/.vscode/setupHelper.js
+++ b/.vscode/setupHelper.js
@@ -78,7 +78,7 @@ export const SEED = [
export const SECRET_FIELDS = ['password', 'apiKey', 'privateEmail', 'privatePhone'];
export async function startDb() {
- mongod = await MongoMemoryServer.create();
+ mongod = await MongoMemoryServer.create({ instance: { storageEngine: 'wiredTiger' } });
await mongoose.connect(mongod.getUri(), { autoIndex: true });
}
@@ -94,4 +94,4 @@ export async function seed() {
}
`;
-fs.writeFileSync(envHelperFilePath, envHelperContent, { encoding: 'utf8' });
\ No newline at end of file
+fs.writeFileSync(envHelperFilePath, envHelperContent, { encoding: 'utf8' });
diff --git a/client/src/pages/InstructorDashboard.jsx b/client/src/pages/InstructorDashboard.jsx
index 1dd0ded..139205d 100644
--- a/client/src/pages/InstructorDashboard.jsx
+++ b/client/src/pages/InstructorDashboard.jsx
@@ -2,10 +2,9 @@ import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../api'
-// Instructor Portal dashboard. Reads the naive session from localStorage.
+// Instructor Portal dashboard. Reads the public profile 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.
+// The search box sends a plain name string to the public search endpoint.
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}
- )}
diff --git a/client/src/pages/InstructorLogin.jsx b/client/src/pages/InstructorLogin.jsx
index dbd2c55..2389c9b 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 strings and verifies a bcrypt password hash.
export default function InstructorLogin() {
const nav = useNavigate()
const [username, setUsername] = useState('')
diff --git a/client/src/pages/ReviewForm.jsx b/client/src/pages/ReviewForm.jsx
index bf85442..9d65e82 100644
--- a/client/src/pages/ReviewForm.jsx
+++ b/client/src/pages/ReviewForm.jsx
@@ -2,10 +2,6 @@ import { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { api } from '../api'
-// TODO: build the Write Review page — see README.md "Your task".
-// This page is already routed at /reviews/new (write) and /reviews/:id (edit),
-// and both routes are wrapped in .
-
const defaults = { courseCode: '', rating: 5, comment: '' }
export default function ReviewForm() {
@@ -13,33 +9,82 @@ export default function ReviewForm() {
const { id } = useParams()
const [form, setForm] = useState(defaults)
const [error, setError] = useState('')
+ const [loading, setLoading] = useState(Boolean(id))
+ const [saving, setSaving] = useState(false)
+ const [loadedId, setLoadedId] = useState(null)
- // TODO (edit mode): when there is an `id`, load the review and fill the form.
useEffect(() => {
+ let active = true
+ setError('')
+ setLoadedId(null)
+ setForm(defaults)
+ setLoading(Boolean(id))
if (!id) return
- // TODO
+
+ api.get('/reviews/' + id)
+ .then(({ data }) => {
+ if (!active) return
+ const { courseCode, rating, comment } = data.review
+ setForm({ courseCode, rating, comment: comment || '' })
+ setLoadedId(id)
+ })
+ .catch(err => {
+ if (active) setError(err?.response?.data?.message || 'Could not load review')
+ })
+ .finally(() => { if (active) setLoading(false) })
+
+ return () => { active = false }
}, [id])
- // TODO: update `form` when an input changes (rating should be a number).
function onChange(e) {
- // TODO
+ const { name, value } = e.target
+ setForm(prev => ({ ...prev, [name]: name === 'rating' ? Number(value) : value }))
}
- // TODO: POST a new review, or PATCH the existing one when editing,
- // then go back to /reviews. Show the server's error message on failure.
+ const unavailable = loading || saving || Boolean(id && loadedId !== id)
+
async function onSubmit(e) {
e.preventDefault()
+ if (unavailable) return
setError('')
- // TODO
+ setSaving(true)
+ try {
+ const payload = { ...form, courseCode: form.courseCode.trim().toUpperCase() }
+ if (id) await api.patch('/reviews/' + id, payload)
+ else await api.post('/reviews', payload)
+ nav('/reviews')
+ } catch (err) {
+ setError(err?.response?.data?.message || 'Could not save review')
+ } finally {
+ setSaving(false)
+ }
}
return (
{id ? 'Edit' : 'Write'} Review
+ {loading &&
Loading review...
}
)
diff --git a/package-lock.json b/package-lock.json
index 997c257..5d5205f 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -73,6 +73,7 @@
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@babel/code-frame": "^7.29.7",
"@babel/generator": "^7.29.7",
@@ -2345,6 +2346,7 @@
"integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==",
"dev": true,
"license": "Apache-2.0",
+ "peer": true,
"peerDependencies": {
"bare-abort-controller": "*"
},
@@ -2559,6 +2561,7 @@
}
],
"license": "MIT",
+ "peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.11.26",
"caniuse-lite": "^1.0.30001812",
@@ -3488,6 +3491,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",
@@ -4914,6 +4926,7 @@
"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==",
"dev": true,
"license": "MIT",
+ "peer": true,
"bin": {
"jiti": "bin/jiti.js"
}
@@ -6112,6 +6125,7 @@
}
],
"license": "MIT",
+ "peer": true,
"dependencies": {
"nanoid": "^3.3.18",
"picocolors": "^1.1.1",
@@ -6422,6 +6436,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"loose-envify": "^1.1.0"
},
@@ -6434,6 +6449,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
@@ -6957,6 +6973,7 @@
"integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==",
"devOptional": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"ip-address": "^10.1.1",
"smart-buffer": "^4.2.0"
@@ -7433,6 +7450,7 @@
"integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=12"
},
@@ -7651,6 +7669,7 @@
"integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"esbuild": "^0.21.3",
"postcss": "^8.4.43",
@@ -7871,6 +7890,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/package.json b/server/package.json
index 5bb00a3..d314f0b 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": "NODE_OPTIONS=--experimental-vm-modules jest --runInBand"
+ "test": "node --experimental-vm-modules ../node_modules/jest/bin/jest.js --runInBand",
+ "migrate:instructor-passwords": "node src/scripts/migrateInstructorPasswords.js"
},
"jest": {
"testEnvironment": "node",
@@ -19,6 +20,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/app.js b/server/src/app.js
index c975cd0..bb4f32e 100644
--- a/server/src/app.js
+++ b/server/src/app.js
@@ -1,6 +1,7 @@
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';
@@ -11,6 +12,9 @@ const app = express();
app.use(morgan('dev'));
app.use(cors({ origin: 'http://localhost:5175', credentials: false }));
app.use(express.json());
+app.use(mongoSanitize({
+ onSanitize: ({ req }) => { req.mongoSanitized = true; }
+}));
app.get('/api/health', (req, res) => res.json({ ok: true }));
diff --git a/server/src/controllers/instructorController.js b/server/src/controllers/instructorController.js
index 2a3582d..645c511 100644
--- a/server/src/controllers/instructorController.js
+++ b/server/src/controllers/instructorController.js
@@ -1,51 +1,40 @@
+import Joi from 'joi';
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(),
+ password: Joi.string().max(72).custom((value, helpers) => (
+ Buffer.byteLength(value, 'utf8') <= 72 ? value : helpers.error('any.invalid')
+ )).required()
+}).required();
+
+const searchSchema = Joi.object({
+ name: Joi.string().max(100).allow(''),
+ username: Joi.string().max(100),
+ department: Joi.string().max(100),
+ role: Joi.string().valid('instructor', 'superadmin')
+});
+
+const publicFields = 'name 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
};
}
-// 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 { value, error } = loginSchema.validate(req.body, { convert: false });
+ if (req.mongoSanitized || error) {
+ return res.status(400).json({ message: 'Provide a valid username and password as strings' });
}
-
- // ⚠️ 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 instructor = await Instructor.findOne({ username: value.username }).select('+password');
+ if (!instructor || !(await instructor.comparePassword(value.password))) {
return res.status(401).json({ message: 'Invalid credentials' });
}
return res.json({ instructor: publicProfile(instructor) });
@@ -54,33 +43,34 @@ export async function loginInstructor(req, res, next) {
}
}
-// 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();
+ .select(publicFields).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 { value, error } = searchSchema.validate(req.query, { convert: false });
+ // Sanitization must never broaden a malicious query into a full directory.
+ // Reject unsafe filters without querying the database.
+ if (req.mongoSanitized || error) {
+ return res.json({ count: 0, instructors: [] });
+ }
+ const filter = {};
+ if (value.name) {
+ const literalName = value.name.replace(/[.*+?^$(){}|[\]\\]/g, '\\$&');
+ filter.name = { $regex: literalName, $options: 'i' };
+ }
+ for (const field of ['username', 'department', 'role']) {
+ if (value[field] !== undefined) filter[field] = value[field];
+ }
+ const instructors = await Instructor.find(filter)
+ .select(publicFields).sort({ name: 1 }).lean();
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..4264cf3 100644
--- a/server/src/models/Instructor.js
+++ b/server/src/models/Instructor.js
@@ -1,26 +1,31 @@
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')) return;
+ // bcrypt only considers the first 72 bytes.
+ if (Buffer.byteLength(this.password, 'utf8') > 72) {
+ throw new Error('Instructor passwords must be at most 72 bytes');
+ }
+ this.password = await bcrypt.hash(this.password, 10);
+});
+
+instructorSchema.methods.comparePassword = function (password) {
+ return bcrypt.compare(password, this.password);
+};
+
export const Instructor = mongoose.model('Instructor', instructorSchema);
diff --git a/server/src/routes/instructors.js b/server/src/routes/instructors.js
index 54a0845..0859171 100644
--- a/server/src/routes/instructors.js
+++ b/server/src/routes/instructors.js
@@ -7,8 +7,8 @@ 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.
+// Instructor sign-in is separate from student JWT authentication.
+// Directory and search expose public profile fields only.
router.post('/login', loginInstructor);
router.get('/', getDirectory);
router.get('/search', searchInstructors);
diff --git a/server/src/scripts/migrateInstructorPasswords.js b/server/src/scripts/migrateInstructorPasswords.js
new file mode 100644
index 0000000..2be137f
--- /dev/null
+++ b/server/src/scripts/migrateInstructorPasswords.js
@@ -0,0 +1,34 @@
+import 'dotenv/config';
+import mongoose from 'mongoose';
+import { pathToFileURL } from 'node:url';
+import { connectDB } from '../config/db.js';
+import { Instructor } from '../models/Instructor.js';
+
+// Preserve accounts and secrets; only convert existing plaintext passwords.
+export async function migrateInstructorPasswords() {
+ let updated = 0;
+ const cursor = Instructor.find().select('+password').cursor();
+ try {
+ for await (const instructor of cursor) {
+ if (/^\$2[aby]\$\d{2}\$[./A-Za-z0-9]{53}$/.test(instructor.password)) continue;
+ instructor.markModified('password');
+ await instructor.save();
+ updated += 1;
+ }
+ } finally {
+ await cursor.close();
+ }
+ return updated;
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ try {
+ await connectDB();
+ console.log('Hashed passwords for ' + await migrateInstructorPasswords() + ' instructor(s).');
+ } catch (err) {
+ console.error('Password migration failed:', err.message);
+ process.exitCode = 1;
+ } finally {
+ await mongoose.disconnect();
+ }
+}
diff --git a/server/src/seed/instructors.js b/server/src/seed/instructors.js
index 396a941..d01b103 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 password-hashing save hook for every account.
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/tests/helpers/testEnv.js b/server/tests/helpers/testEnv.js
new file mode 100644
index 0000000..7772cb6
--- /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({ instance: { storageEngine: 'wiredTiger' } });
+ 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');
+ });
+});