Compare commits

2 Commits
Author SHA1 Message Date
bskjon 77b56c0126 RealPath
CI / test (push) Canceled after 0s
2026-10-20 00:06:45 +02:00
bskjon ada8417a6b FF
CI / test (push) Canceled after 0s
2026-10-19 23:30:23 +02:00
6 changed files with 142 additions and 37 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. `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
Publish locally with: Publish locally with:
+1
View File
@@ -22,6 +22,7 @@ repositories {
dependencies { dependencies {
implementation("org.lz4:lz4-java:1.8.0") implementation("org.lz4:lz4-java:1.8.0")
testImplementation(kotlin("test")) testImplementation(kotlin("test"))
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
} }
kotlin { kotlin {
+63 -37
View File
@@ -7,6 +7,9 @@ import java.io.PrintWriter
import java.nio.file.FileAlreadyExistsException import java.nio.file.FileAlreadyExistsException
import java.nio.file.FileSystemException import java.nio.file.FileSystemException
import java.nio.file.Paths import java.nio.file.Paths
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.file.Path
class FakeFile( class FakeFile(
override var path: String, override var path: String,
@@ -14,10 +17,13 @@ class FakeFile(
private var size: Long = 0, private var size: Long = 0,
private var directory: Boolean = false, private var directory: Boolean = false,
private var content: String = "", private var content: String = "",
private var bytes: ByteArray = content.toByteArray(Charsets.UTF_8),
private var modified: Long = System.currentTimeMillis(), private var modified: Long = System.currentTimeMillis(),
private var writable: Boolean = true private var writable: Boolean = true
) : IFile { ) : IFile {
private var symbolicLinkTarget: String? = null
init { init {
if (!directory) { if (!directory) {
directory = !path.substringAfterLast('/').contains('.') directory = !path.substringAfterLast('/').contains('.')
@@ -49,6 +55,35 @@ class FakeFile(
override val absolutePath: String override val absolutePath: String
get() = path 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 override val nameWithoutExtension: String
get() = name.substringBeforeLast('.', name) get() = name.substringBeforeLast('.', name)
@@ -67,18 +102,20 @@ class FakeFile(
override fun readText(): String = ref().content override fun readText(): String = ref().content
override fun lastModified(): Long = ref().modified override fun lastModified(): Long = ref().modified
override fun canRead(): Boolean { override fun canRead(): Boolean {
return true return ref().exists
} }
override fun canWrite(): Boolean { override fun canWrite(): Boolean {
return true val r = ref()
return r.exists && r.writable
} }
override fun writeText(text: String) { override fun writeText(text: String) {
val r = ref() val r = ref()
r.exists = true r.exists = true
r.content = text r.content = text
r.size = text.toByteArray().size.toLong() r.bytes = text.toByteArray(Charsets.UTF_8)
r.size = r.bytes.size.toLong()
r.modified = System.currentTimeMillis() r.modified = System.currentTimeMillis()
} }
@@ -86,7 +123,8 @@ class FakeFile(
val r = ref() val r = ref()
r.exists = true r.exists = true
r.content += "$text\n" r.content += "$text\n"
r.size = r.content.toByteArray().size.toLong() r.bytes = r.content.toByteArray(Charsets.UTF_8)
r.size = r.bytes.size.toLong()
r.modified = System.currentTimeMillis() r.modified = System.currentTimeMillis()
} }
@@ -107,7 +145,8 @@ class FakeFile(
override fun setWritable(state: Boolean): Boolean { override fun setWritable(state: Boolean): Boolean {
val r = ref() val r = ref()
return r.setWritable(state) r.writable = state
return true
} }
override fun mkdirs(): Boolean { override fun mkdirs(): Boolean {
@@ -118,17 +157,19 @@ class FakeFile(
val r = ref() val r = ref()
r.exists = false r.exists = false
r.content = "" r.content = ""
r.bytes = byteArrayOf()
r.size = 0 r.size = 0
return true return true
} }
override fun deleteRecursively(): Boolean { override fun deleteRecursively(): Boolean {
val prefix = absolutePath val prefix = absolutePath.trimEnd('/') + "/"
fileRegistry.values fileRegistry.values
.filter { it.absolutePath.startsWith(prefix) } .filter { it.absolutePath == absolutePath || it.absolutePath.startsWith(prefix) }
.forEach { .forEach {
it.exists = false it.exists = false
it.content = "" it.content = ""
it.bytes = byteArrayOf()
it.size = 0 it.size = 0
} }
delete() delete()
@@ -156,6 +197,7 @@ class FakeFile(
val prefix = if (absolutePath.endsWith("/")) absolutePath else "$absolutePath/" val prefix = if (absolutePath.endsWith("/")) absolutePath else "$absolutePath/"
return fileRegistry.values return fileRegistry.values
.filter { it.absolutePath.startsWith(prefix) } .filter { it.absolutePath.startsWith(prefix) }
.filter { it.exists }
.filter { child -> .filter { child ->
// relative path after root // relative path after root
val rel = child.absolutePath.removePrefix(prefix) val rel = child.absolutePath.removePrefix(prefix)
@@ -167,7 +209,8 @@ class FakeFile(
override fun walk(): Sequence<IFile> = override fun walk(): Sequence<IFile> =
fileRegistry.values fileRegistry.values
.filter { it.absolutePath.startsWith(absolutePath) } .filter { it.exists }
.filter { it.absolutePath == absolutePath || it.absolutePath.startsWith(absolutePath.trimEnd('/') + "/") }
.asSequence() .asSequence()
override fun printWriter(): PrintWriter = override fun printWriter(): PrintWriter =
@@ -177,7 +220,8 @@ class FakeFile(
val r = ref() val r = ref()
r.exists = true r.exists = true
r.content += str r.content += str
r.size = r.content.toByteArray().size.toLong() r.bytes = r.content.toByteArray(Charsets.UTF_8)
r.size = r.bytes.size.toLong()
r.modified = System.currentTimeMillis() r.modified = System.currentTimeMillis()
} }
@@ -195,7 +239,8 @@ class FakeFile(
r.exists = true r.exists = true
r.directory = false r.directory = false
r.size = bytes.size.toLong() r.size = bytes.size.toLong()
r.content = String(bytes) // lagres som binær data i string-form r.bytes = bytes.copyOf()
r.content = String(bytes, Charsets.UTF_8)
r.modified = System.currentTimeMillis() r.modified = System.currentTimeMillis()
} }
@@ -209,7 +254,7 @@ class FakeFile(
} }
override fun setLastModified(time: Long) { override fun setLastModified(time: Long) {
this.modified = time ref().modified = time
} }
override fun renameTo(dest: IFile): Boolean { override fun renameTo(dest: IFile): Boolean {
@@ -234,26 +279,7 @@ class FakeFile(
override fun openInputStream(): InputStream { override fun openInputStream(): InputStream {
val r = ref() val r = ref()
val bytes = r.content.toByteArray() return ByteArrayInputStream(r.bytes.copyOf())
return object : InputStream() {
var pos = 0
override fun read(): Int {
return if (pos < bytes.size) {
bytes[pos++].toInt() and 0xFF
} else {
-1
}
}
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (pos >= bytes.size) return -1
val toCopy = minOf(len, bytes.size - pos)
System.arraycopy(bytes, pos, b, off, toCopy)
pos += toCopy
return toCopy
}
}
} }
override fun openOutputStream(): OutputStream { override fun openOutputStream(): OutputStream {
@@ -261,20 +287,20 @@ class FakeFile(
r.exists = true r.exists = true
return object : OutputStream() { return object : OutputStream() {
private val buffer = StringBuilder() private val buffer = ByteArrayOutputStream()
override fun write(b: Int) { override fun write(b: Int) {
buffer.append(b.toChar()) buffer.write(b)
} }
override fun write(b: ByteArray, off: Int, len: Int) { override fun write(b: ByteArray, off: Int, len: Int) {
buffer.append(String(b, off, len)) buffer.write(b, off, len)
} }
override fun flush() { override fun flush() {
val newContent = buffer.toString() r.bytes = buffer.toByteArray()
r.content += newContent r.content = String(r.bytes, Charsets.UTF_8)
r.size = r.content.toByteArray().size.toLong() r.size = r.bytes.size.toLong()
r.modified = System.currentTimeMillis() r.modified = System.currentTimeMillis()
} }
+6
View File
@@ -37,6 +37,12 @@ interface IFile {
fun toPath(): Path = Paths.get(this.absolutePath) 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 toJavaFile(): File
fun readText(): String fun readText(): String
@@ -6,6 +6,7 @@ import java.io.InputStream
import java.io.OutputStream import java.io.OutputStream
import java.io.PrintWriter import java.io.PrintWriter
import java.security.MessageDigest import java.security.MessageDigest
import java.nio.file.Path
class UseFile(path: String) : IFile { class UseFile(path: String) : IFile {
@@ -26,6 +27,8 @@ class UseFile(path: String) : IFile {
override val absolutePath: String override val absolutePath: String
get() = file.absolutePath get() = file.absolutePath
override fun realPath(): Path = file.toPath().toRealPath()
override val parentFile: IFile override val parentFile: IFile
get() = IFile(parent!!) 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)
}
}