You do not need to use a third-party library to do this. The file APIs that Java provides give you the ability to verify that a file is a descendent of another.
Path.resolve(String) will resolve parent directory references, absolute, and relative paths. If an absolute path is passed as an argument to the resolve method it returns the absolute path. It does not guarantee that the returned value is a descendent of the path the method was invoked on.
You can check that a path is a descendent of another path by using the Path.startsWith(Path) method.
Path root = java.nio.file.Files.createTempDirectory(null);
Path relative = root.resolve(pathAsString).normalize();
if (!relative.startsWith(root)) {
throw new IllegalArgumentException("Path contains invalid characters");
}
When pathAsString
contains references to parent directories or was an absolute path, relative
can reference a file that is not contained in root
. When this is the case you can throw an exception before any modifications to the file are permitted.