I am using the below code which is properly sanitizing the url.
But still I keep getting Sonar Exception “Change this code to not construct the URL from user-controlled data.”
The line await fetch(sanitizedURL, options)
is throwing Sonar exception.
I have tried if(!sanitizedCode) { throw Error .. }
but it is also not working.
What modification is needed in the below code to resolve the issue?
function sanitizeURL(inputURL) {
try {
const parsedURL = new URL(inputURL);
const domainsList = [inputURL];
if (!schemesList.includes(parsedURL.protocol)) {
throw new Error('Invalid URL scheme');
}
if (!domainsList.some(domain => domain.includes(parsedURL))) {
throw new Error("URL not in allowed list");
}
return parsedURL.toString();
} catch (error) {
console.log("Caught error: ", error);
throw error;
}
}
async function fetchWithCheck(url, options = {}, responseType = "json", errorMessage = null) {
let data;
try {
const sanitizedURL = sanitizeURL(url);
const response = await fetch(sanitizedURL, options);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
switch (responseType) {
case "json":
data = await response.json();
break;
default:
throw new Error(`Unsupported response type: ${responseType}`);
}
return data;
} catch (error) {
console.log(logMessage, error);
const newError = new Error("problem fetching data");
newError.cause = error;
throw newError;
}
}