修复FileUtil.checkSlip方法缺陷

This commit is contained in:
Looly
2023-06-09 22:00:57 +08:00
parent cdba0162f8
commit a4ade53dfe
3 changed files with 9 additions and 12 deletions

View File

@@ -3459,18 +3459,7 @@ public class FileUtil extends PathUtil {
*/
public static File checkSlip(File parentFile, File file) throws IllegalArgumentException {
if (null != parentFile && null != file) {
String parentCanonicalPath;
String canonicalPath;
try {
parentCanonicalPath = parentFile.getCanonicalPath();
canonicalPath = file.getCanonicalPath();
} catch (IOException e) {
// issue#I4CWMO@Gitee
// getCanonicalPath有时会抛出奇怪的IO异常此时忽略异常使用AbsolutePath判断。
parentCanonicalPath = parentFile.getAbsolutePath();
canonicalPath = file.getAbsolutePath();
}
if (false == canonicalPath.startsWith(parentCanonicalPath)) {
if(!file.toPath().startsWith(parentFile.toPath())){
throw new IllegalArgumentException("New file is outside of the parent dir: " + file.getName());
}
}

View File

@@ -532,4 +532,11 @@ public class FileUtilTest {
// 当复制文件到目标目录的时候,返回复制的目标文件,而非目录
Console.log(copy);
}
@Test
public void checkSlipTest() {
Assert.assertThrows(IllegalArgumentException.class, ()->{
FileUtil.checkSlip(FileUtil.file("test/a"), FileUtil.file("test/../a"));
});
}
}