diff --git a/src/main/java/run/halo/app/utils/FileUtils.java b/src/main/java/run/halo/app/utils/FileUtils.java index e23279b6b..46a1dd277 100644 --- a/src/main/java/run/halo/app/utils/FileUtils.java +++ b/src/main/java/run/halo/app/utils/FileUtils.java @@ -107,6 +107,12 @@ public class FileUtils { Assert.notNull(newName, "New name must not be null"); Path newPath = pathToRename.resolveSibling(newName); + var parent = pathToRename.getParent(); + if (parent == null) { + parent = pathToRename; + } + checkDirectoryTraversal(parent, newPath); + log.info("Rename [{}] to [{}]", pathToRename, newPath); Files.move(pathToRename, newPath); diff --git a/src/test/java/run/halo/app/utils/FileUtilsTest.java b/src/test/java/run/halo/app/utils/FileUtilsTest.java index 23738188a..07f4bbc85 100644 --- a/src/test/java/run/halo/app/utils/FileUtilsTest.java +++ b/src/test/java/run/halo/app/utils/FileUtilsTest.java @@ -3,6 +3,7 @@ package run.halo.app.utils; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; @@ -22,6 +23,7 @@ import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import run.halo.app.exception.ForbiddenException; import run.halo.app.model.support.HaloConst; /** @@ -134,6 +136,14 @@ class FileUtilsTest { assertEquals(content, new String(Files.readAllBytes(newPath))); } + @Test + void shouldThrowErrorIfNewNameIsInvalidWhenRenaming() { + final var target = tempDirectory.resolve("fake.file"); + assertThrows(ForbiddenException.class, () -> FileUtils.rename(target, "../fake.file")); + assertThrows(ForbiddenException.class, () -> FileUtils.rename(target, "../../fake.file")); + assertThrows(ForbiddenException.class, () -> FileUtils.rename(target, "/fake.file")); + } + @Test void testRenameFolder() throws IOException { Path testPath = tempDirectory.resolve("test/test");