Compare commits

1 Commits
Author SHA1 Message Date
bskjon 77b56c0126 RealPath
CI / test (push) Canceled after 0s
2026-10-20 00:06:45 +02:00
6 changed files with 111 additions and 0 deletions

No files matched your search

+10
View File
@@ -31,6 +31,16 @@ fun setUp() {
`FakeFile` is intentionally a test implementation, not a full emulation of every platform filesystem behavior. `toJavaFile()` is unsupported by the fake.
`IFile.normalized()` collapses `.` and `..` path segments without following symbolic links. `IFile.realPath()` follows symbolic links and requires the target to exist. To check that a referenced file stays under a root directory, compare canonical `Path` values:
```kotlin
val root = contentFolder.realPath()
val candidate = contentFolder.resolve("media/video.mkv").realPath()
require(candidate.startsWith(root))
```
`FakeFile.symbolicLinkTo()` can model links in tests; `realPath()` resolves those links against the fake file registry.
## Publish
Publish locally with:
+1
View File
@@ -22,6 +22,7 @@ repositories {
dependencies {
implementation("org.lz4:lz4-java:1.8.0")
testImplementation(kotlin("test"))
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
kotlin {
@@ -9,6 +9,7 @@ import java.nio.file.FileSystemException
import java.nio.file.Paths
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.file.Path
class FakeFile(
override var path: String,
@@ -21,6 +22,8 @@ class FakeFile(
private var writable: Boolean = true
) : IFile {
private var symbolicLinkTarget: String? = null
init {
if (!directory) {
directory = !path.substringAfterLast('/').contains('.')
@@ -52,6 +55,35 @@ class FakeFile(
override val absolutePath: String
get() = path
override fun realPath(): Path {
var current = Paths.get(absolutePath).toAbsolutePath().normalize()
repeat(40) {
var replacedLink = false
var prefix = current.root ?: Paths.get("")
val segments = current.iterator().asSequence().toList()
for ((index, segment) in segments.withIndex()) {
prefix = prefix.resolve(segment)
val entry = fileRegistry[prefix.normalize().toString()]
val target = entry?.symbolicLinkTarget ?: continue
val targetPath = Paths.get(target).let { if (it.isAbsolute) it else prefix.parent.resolve(it) }
current = targetPath.resolve(segments.drop(index + 1).joinToString("/")).normalize()
replacedLink = true
break
}
if (replacedLink) return@repeat
val entry = fileRegistry[current.toString()]
?: throw java.nio.file.NoSuchFileException(current.toString())
if (!entry.exists) throw java.nio.file.NoSuchFileException(current.toString())
return current
}
throw FileSystemException(absolutePath, null, "Too many symbolic links")
}
/** Marks this fake path as a symbolic link for canonical-path tests. */
fun symbolicLinkTo(target: String) {
ref().symbolicLinkTarget = target
}
override val nameWithoutExtension: String
get() = name.substringBeforeLast('.', name)
+6
View File
@@ -37,6 +37,12 @@ interface IFile {
fun toPath(): Path = Paths.get(this.absolutePath)
/** Returns this path with `.` and `..` segments collapsed, without following symbolic links. */
fun normalized(): IFile = IFile(toPath().normalize().toString())
/** Resolves symbolic links and returns the existing filesystem object's canonical path. */
fun realPath(): Path
fun toJavaFile(): File
fun readText(): String
@@ -6,6 +6,7 @@ import java.io.InputStream
import java.io.OutputStream
import java.io.PrintWriter
import java.security.MessageDigest
import java.nio.file.Path
class UseFile(path: String) : IFile {
@@ -26,6 +27,8 @@ class UseFile(path: String) : IFile {
override val absolutePath: String
get() = file.absolutePath
override fun realPath(): Path = file.toPath().toRealPath()
override val parentFile: IFile
get() = IFile(parent!!)
@@ -0,0 +1,59 @@
package no.iktdev.files
import java.nio.file.Files
import java.nio.file.Path
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
class IFileRealPathTest {
@AfterTest
fun resetFactory() {
IFile.factory = { UseFile(it) }
FakeFile.wipe()
}
@Test
fun realPathFollowsSymbolicLink() {
val temp = Files.createTempDirectory("ifile-real-path")
try {
val root = Files.createDirectory(temp.resolve("root"))
val file = Files.writeString(root.resolve("media.mkv"), "media")
val link = Files.createSymbolicLink(temp.resolve("link.mkv"), file)
val outside = Files.writeString(temp.resolve("outside.mkv"), "outside")
val escapingLink = Files.createSymbolicLink(root.resolve("outside.mkv"), outside)
assertEquals(file.toRealPath(), UseFile(link.toString()).realPath())
assertTrue(UseFile(link.toString()).realPath().startsWith(UseFile(root.toString()).realPath()))
assertTrue(!UseFile(escapingLink.toString()).realPath().startsWith(UseFile(root.toString()).realPath()))
} finally {
temp.toFile().deleteRecursively()
}
}
@Test
fun realPathRejectsMissingPathsAndFakeLinksResolveOutsideRoot() {
val root = FakeFile("/fake/root", directory = true)
val outside = FakeFile("/fake/outside", directory = true)
FakeFile("/fake/outside/secret.mkv")
val link = FakeFile("/fake/root/secret.mkv")
link.symbolicLinkTo(outside.absolutePath + "/secret.mkv")
assertEquals(Path.of("/fake/outside/secret.mkv"), link.realPath())
assertTrue(!link.realPath().startsWith(root.realPath()))
assertFailsWith<java.nio.file.NoSuchFileException> {
FakeFile("/fake/root/missing.mkv", exists = false).realPath()
}
}
@Test
fun normalizedCollapsesDotSegmentsWithoutChangingFakeFileRegistry() {
FakeFile.wipe()
IFile.factory = { FakeFile(it) }
val normalized = IFile("/fake/root/../media/./video.mkv").normalized()
assertEquals("/fake/media/video.mkv", normalized.path)
}
}