From 90e734e0eef726937f5d0261d57d2320df3d87cc Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Thu, 20 Aug 2026 01:55:07 +0000 Subject: [PATCH] fix(security): sanitize MongoDB operator injection in requests - Integrate express-mongo-sanitize middleware in-place to strip $ operators - Add integration test for NoSQL injection protection in tests/mongoSanitize.test.js Co-authored-by: SOURAV-ROY <8663561+SOURAV-ROY@users.noreply.github.com> --- index.js | 11 ++++++++--- tests/mongoSanitize.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 tests/mongoSanitize.test.js diff --git a/index.js b/index.js index f073c89..ad8531e 100644 --- a/index.js +++ b/index.js @@ -2,7 +2,7 @@ const path = require("path"); const express = require("express"); const dotenv = require("dotenv"); const morgan = require("morgan"); -// const mongoSanitize = require("express-mongo-sanitize"); +const mongoSanitize = require("express-mongo-sanitize"); const helmet = require("helmet"); // const xssClean = require("xss-clean"); const expressRateLimit = require("express-rate-limit"); @@ -85,8 +85,13 @@ if (process.env.NODE_ENV === "development") { //File Uploading ******************************************************* app.use(fileUpload()); -// Sanitize Data ******************************************************* -// app.use(mongoSanitize()); +// Sanitize Data (In-place sanitization compatible with Express 5 getter properties) +app.use((req, res, next) => { + if (req.body) mongoSanitize.sanitize(req.body); + if (req.params) mongoSanitize.sanitize(req.params); + if (req.query) mongoSanitize.sanitize(req.query); + next(); +}); //Set Security Headers ************************************************ app.use(helmet()); diff --git a/tests/mongoSanitize.test.js b/tests/mongoSanitize.test.js new file mode 100644 index 0000000..03145ab --- /dev/null +++ b/tests/mongoSanitize.test.js @@ -0,0 +1,25 @@ +const request = require("supertest"); +const app = require("../index"); + +describe("NoSQL Injection Prevention (mongoSanitize)", () => { + it("should sanitize $ operators from request body", async () => { + const agent = request.agent(app); + + // Fetch CSRF Token + const csrfRes = await agent.get("/api/v1/auth/csrf-token"); + const csrfToken = csrfRes.body.csrfToken; + + // Attempt login with NoSQL injection operator in email field + const res = await agent + .post("/api/v1/auth/login") + .set("x-csrf-token", csrfToken) + .send({ + email: { $gt: "" }, + password: "password123", + }); + + // Should fail with 400 or 401 instead of internal server error + expect(res.status).not.toBe(500); + expect(res.body.success).toBe(false); + }); +});