Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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());
Expand Down
25 changes: 25 additions & 0 deletions tests/mongoSanitize.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
});