SonarCloud How to fix change this code to not construct the path from user-controlled data

Get sonar warning

Change this code to not construct the path from user-controlled data.
I/O function calls should not be vulnerable to path injection attacks [javasecurity:S2083]
Code

public static void storeImageToHttpResponse(String imageBasePath, String fullpath, String filename, long fileLength, HttpServletResponse response) throws IOException{
    BufferedInputStream input = null;
    BufferedOutputStream output = null;
    try {
        InputStream is = new FileInputStream(validateImagePath(imageBasePath, fullpath));

        
    }  finally {
        if (output != null) try { output.close(); output.flush(); } catch (IOException logOrIgnore) {}
        if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
    } 
}

public static File validateImagePath(String imageBasePath, String fullPath) throws IOException {
    File file = new File(fullPath);
    return validateImagePath(imageBasePath, file);
}

public static File validateImagePath(String imageBasePath, File file) throws IOException {
    Path targetPath = new File(imageBasePath).toPath().normalize();
    if(!file.toPath().normalize().startsWith(targetPath)) {
        throw new IOException(String.format("Image %s is outside of the target directory %s", file.getAbsolutePath(), imageBasePath));
    }
    return file;
}

But still get warning
enter image description here

Pls help/advise

Leave a Comment