1 const middleware
= require("../../src/middleware/urlSanitizer.js");
2 const sanitizeURL
= require("../../src/utils/urlSanitizer.js");
3 const parseURL
= require("../../src/utils/urlParser.js");
5 jest
.mock("../../src/utils/urlSanitizer.js");
6 jest
.mock("../../src/utils/urlParser.js");
8 describe("Path sanitizer middleware", () => {
9 let req
, res
, logFacilities
, config
, next
;
15 search
: "?query=test",
18 url
: "/test?query=test#hash",
35 allowDoubleSlashes
: false,
36 rewriteDirtyURLs
: false,
41 sanitizeURL
.mockImplementation((url
) => url
);
42 parseURL
.mockImplementation((url
) => ({ pathname
: url
}));
45 test("should call next if URL is not dirty", () => {
46 middleware(req
, res
, logFacilities
, config
, next
);
47 expect(next
).toHaveBeenCalled();
50 test("should redirect if URL is dirty and rewriteDirtyURLs is false", () => {
51 req
.parsedURL
.pathname
= "/dirty%20url";
52 middleware(req
, res
, logFacilities
, config
, next
);
53 expect(res
.redirect
).toHaveBeenCalledWith(
54 "/dirty%20url?query=test#hash",
57 expect(next
).not
.toHaveBeenCalled();
60 test("should rewrite URL if URL is dirty and rewriteDirtyURLs is true", () => {
61 req
.parsedURL
.pathname
= "/dirty%20url";
62 config
.rewriteDirtyURLs
= true;
63 middleware(req
, res
, logFacilities
, config
, next
);
64 expect(req
.url
).toBe("/dirty%20url?query=test#hash");
65 expect(next
).toHaveBeenCalled();
68 test("should redirect if URL is dirty (sanitized via sanitizeURL) and rewriteDirtyURLs is false", () => {
69 req
.parsedURL
.pathname
= "/dirty%20url";
70 sanitizeURL
.mockImplementation((url
) => url
.replace(/dirty/g, "clean"));
71 middleware(req
, res
, logFacilities
, config
, next
);
72 expect(res
.redirect
).toHaveBeenCalledWith(
73 "/clean%20url?query=test#hash",
76 expect(next
).not
.toHaveBeenCalled();
79 test("should rewrite URL if URL is dirty (sanitized via sanitizeURL) and rewriteDirtyURLs is true", () => {
80 req
.parsedURL
.pathname
= "/dirty%20url";
81 config
.rewriteDirtyURLs
= true;
82 sanitizeURL
.mockImplementation((url
) => url
.replace(/dirty/g, "clean"));
83 middleware(req
, res
, logFacilities
, config
, next
);
84 expect(req
.url
).toBe("/clean%20url?query=test#hash");
85 expect(next
).toHaveBeenCalled();
88 test("should handle parseURL errors", () => {
89 req
.parsedURL
.pathname
= "/dirty%20url";
90 config
.rewriteDirtyURLs
= true;
91 sanitizeURL
.mockImplementation((url
) => url
.replace(/dirty/g, "clean"));
92 parseURL
.mockImplementation(() => {
93 throw new Error("Parse error");
95 middleware(req
, res
, logFacilities
, config
, next
);
96 expect(res
.error
).toHaveBeenCalledWith(400, new Error("Parse error"));
97 expect(next
).not
.toHaveBeenCalled();