From c00be49ede09668515e0d822faa6f4cdf0ba9c78 Mon Sep 17 00:00:00 2001 From: Eneko Fernandez Date: Mon, 30 Oct 2023 15:27:13 +0000 Subject: [PATCH] add denylist for paths --- helpers/index.js | 19 +++++++++++++++++-- test/helpers_test.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/helpers/index.js b/helpers/index.js index 348e785db..bd53fac13 100644 --- a/helpers/index.js +++ b/helpers/index.js @@ -51,10 +51,25 @@ res.end(); } + // list of invalid redirect paths + const denylist = ['//']; + + const isInvalidRedirectPath = (redirectPath) => { + return denylist.some((denylistItem) => redirectPath.includes(denylistItem)); + } + /* Rewrites and redirects any url that doesn't end with a slash. */ helpers.rewriteSlash = function(req, res, next) { - if(req.url.substr(-1) == '/' && req.url.length > 1) - res.redirect(301, req.url.slice(0, -1)); + if(req.url.substr(-1) == '/' && req.url.length > 1){ + var redirectPath = req.url.slice(0, -1); + + if (isInvalidRedirectPath(redirectPath)) { + res.status(400).send('invalid URL to redirect to'); + }else { + console.log("redirecting") + res.redirect(301, redirectPath ); + } + } else next(); } diff --git a/test/helpers_test.js b/test/helpers_test.js index 46e338627..371d8d154 100644 --- a/test/helpers_test.js +++ b/test/helpers_test.js @@ -22,6 +22,36 @@ app.use(bodyParser.json()); }); + describe("#redirectHandler", function() { + it("should return bad request if invalid redirection", function(done) { + app.use(function(req, res) { + helpers.rewriteSlash(req, res, done); + }); + + chai.request(app). + get("//category.html/"). + end(function(err, res) { + expect(res).to.have.status(400); + done(); + }); + }); + + it("should redirect if valid redirection", function(done) { + app.use(function(req, res) { + helpers.rewriteSlash(req, res, done); + }); + + chai.request(app). + get("/category.html/"). + end(function(err, res) { + expect(res).to.have.status(301); + done(); + }); + }); + + }); + + describe("#errorHandler", function() { var message, code, error, res, resErr;