From 6b8844b600a13201152f9de02b216c12bad24e9b Mon Sep 17 00:00:00 2001 From: "nenka.lab" Date: Sun, 15 Nov 2026 17:49:24 +0900 Subject: [PATCH] feat: add shared Java guard module and class access policy --- .../api/discovery/PluginManifestSchema.kt | 7 + .../msgbot/plugin/api/engine/ClassAccess.kt | 70 ++ .../msgbot/plugin/api/engine/ScriptEngine.kt | 3 + .../com/xfl/msgbot/plugin/api/remote/Wire.kt | 3 + .../plugin/api/remote/EngineSessionTest.kt | 19 + guard/build.gradle.kts | 60 ++ .../com/xfl/msgbot/plugin/guard/FolderHost.kt | 218 +++++ .../msgbot/plugin/guard/GuardBoundaryTest.kt | 235 +++++ .../plugin/guard/GuardDifferentialTest.kt | 502 +++++++++++ .../msgbot/plugin/guard/GuardParityTest.kt | 71 ++ .../msgbot/plugin/guard/BridgeGuardHost.kt | 164 ++++ .../com/xfl/msgbot/plugin/guard/ClassRules.kt | 122 +++ .../msgbot/plugin/guard/GuardEnvironment.kt | 103 +++ .../xfl/msgbot/plugin/guard/GuardErrors.kt | 71 ++ .../com/xfl/msgbot/plugin/guard/GuardFd.kt | 128 +++ .../com/xfl/msgbot/plugin/guard/GuardFile.kt | 204 +++++ .../msgbot/plugin/guard/GuardFileBase.java | 47 + .../com/xfl/msgbot/plugin/guard/GuardFiles.kt | 186 ++++ .../com/xfl/msgbot/plugin/guard/GuardHost.kt | 145 ++++ .../com/xfl/msgbot/plugin/guard/GuardNio.kt | 800 ++++++++++++++++++ .../xfl/msgbot/plugin/guard/GuardPolicy.kt | 132 +++ .../xfl/msgbot/plugin/guard/GuardProcess.kt | 201 +++++ .../xfl/msgbot/plugin/guard/GuardReflect.kt | 329 +++++++ .../xfl/msgbot/plugin/guard/GuardScanner.kt | 176 ++++ .../xfl/msgbot/plugin/guard/GuardSession.kt | 83 ++ .../xfl/msgbot/plugin/guard/GuardStreams.kt | 248 ++++++ .../com/xfl/msgbot/plugin/guard/GuardZip.kt | 395 +++++++++ .../xfl/msgbot/plugin/guard/ClassRulesTest.kt | 81 ++ readme.md | 3 +- settings.gradle.kts | 6 +- .../xfl/msgbot/plugin/tck/EngineHarness.kt | 11 + .../com/xfl/msgbot/plugin/tck/FolderFiles.kt | 168 ++++ .../msgbot/plugin/tck/JavaGuardConformance.kt | 236 ++++++ 33 files changed, 5223 insertions(+), 4 deletions(-) create mode 100644 contract/src/main/kotlin/com/xfl/msgbot/plugin/api/engine/ClassAccess.kt create mode 100644 guard/build.gradle.kts create mode 100644 guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/FolderHost.kt create mode 100644 guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardBoundaryTest.kt create mode 100644 guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardDifferentialTest.kt create mode 100644 guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardParityTest.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/BridgeGuardHost.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/ClassRules.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardEnvironment.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardErrors.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFd.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFile.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFileBase.java create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFiles.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardHost.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardNio.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardPolicy.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardProcess.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardReflect.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardScanner.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardSession.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardStreams.kt create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardZip.kt create mode 100644 guard/src/test/java/com/xfl/msgbot/plugin/guard/ClassRulesTest.kt create mode 100644 tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/FolderFiles.kt create mode 100644 tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/JavaGuardConformance.kt diff --git a/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/discovery/PluginManifestSchema.kt b/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/discovery/PluginManifestSchema.kt index 63c5576..976b20e 100644 --- a/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/discovery/PluginManifestSchema.kt +++ b/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/discovery/PluginManifestSchema.kt @@ -42,6 +42,13 @@ object PluginManifestSchema { /** A `@string/...` resource. */ const val ATTR_LABEL = "label" + // + /** + * `true` when the engine lets scripts use Java classes. The host then keeps a [com.xfl.msgbot.plugin.api.engine.ClassAccess] + * for each project and sends it in `LoadRequest.classAccess`. + */ + const val ATTR_JAVA = "java" + // const val ATTR_NAME = "name" const val ATTR_EXTENSION = "extension" diff --git a/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/engine/ClassAccess.kt b/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/engine/ClassAccess.kt new file mode 100644 index 0000000..94d4230 --- /dev/null +++ b/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/engine/ClassAccess.kt @@ -0,0 +1,70 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.api.engine + +import com.xfl.msgbot.plugin.api.value.Value +import com.xfl.msgbot.plugin.api.value.asArrayOrNull +import com.xfl.msgbot.plugin.api.value.asBooleanOrNull +import com.xfl.msgbot.plugin.api.value.asObjectOrNull +import com.xfl.msgbot.plugin.api.value.asStringOrNull + +/** + * Which Java classes a script of one project may use, for an engine that runs Java (``). + * The host keeps it with the project and sends it in [LoadRequest.classAccess]. + * + * Files are never part of this: a script reaches files only through the host, under the project's file rules, + * whatever this says. + * + * @property preset the starting set, see [Preset]. + * @property allow class names added to the preset: an exact name, or a package followed by `.*` (`com.example.*`). + * @property deny class names taken away, in the same form. They win over [allow] and the preset. + * @property restrictions false turns the class rules off entirely, so a script may use any class. Files still go + * through the host. + */ +data class ClassAccess( + val preset: Preset = Preset.SAFE, + val allow: List = emptyList(), + val deny: List = emptyList(), + val restrictions: Boolean = true, +) { + enum class Preset { + /** No Java at all. */ + OFF, + + /** Ordinary classes; reflection, class loaders, processes and runtime internals only through checked stand-ins. */ + SAFE, + + /** [SAFE] plus real reflective members (`Method`, `Field`, `Constructor`) and `java.lang.Process`. */ + WIDE, + + /** [SAFE] with the project's own [allow] and [deny] lists. */ + CUSTOM, + } + + val javaEnabled: Boolean get() = preset != Preset.OFF + + fun toValue(): Value = + Value.VObject( + mapOf( + "preset" to Value.VString(preset.name.lowercase()), + "allow" to Value.VArray(allow.map(Value::VString)), + "deny" to Value.VArray(deny.map(Value::VString)), + "restrictions" to Value.VBool(restrictions), + ), + ) + + companion object { + val DEFAULT = ClassAccess() + + /** Reads what [toValue] wrote. Unknown presets become [Preset.SAFE], so an older engine keeps the safe default. */ + fun fromValue(value: Value): ClassAccess { + val map = value.asObjectOrNull() ?: throw IllegalArgumentException("Class access is a map") + val preset = map["preset"]?.asStringOrNull()?.uppercase()?.let { name -> Preset.entries.firstOrNull { it.name == name } } ?: Preset.SAFE + fun names(key: String) = map[key]?.asArrayOrNull()?.mapNotNull { it.asStringOrNull() }.orEmpty() + return ClassAccess(preset, names("allow"), names("deny"), map["restrictions"]?.asBooleanOrNull() ?: true) + } + } +} diff --git a/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/engine/ScriptEngine.kt b/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/engine/ScriptEngine.kt index b2b434c..221b9ac 100644 --- a/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/engine/ScriptEngine.kt +++ b/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/engine/ScriptEngine.kt @@ -135,6 +135,8 @@ fun interface Cancellable { * @property profile the language facade, run after `__api` is bound and before [entry]. * @property sources project files keyed by path relative to the project folder. * @property options per-project settings the engine declared. + * @property classAccess the Java classes the project's scripts may use; null when the host sends none, which an + * engine that runs Java treats as [ClassAccess.DEFAULT]. */ data class LoadRequest( val language: String, @@ -143,6 +145,7 @@ data class LoadRequest( val entry: String, val sources: Map, val options: Map = emptyMap(), + val classAccess: ClassAccess? = null, ) { init { require(entry in sources) { "The entry '$entry' is not among the sources" } diff --git a/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/remote/Wire.kt b/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/remote/Wire.kt index 65260bf..695447b 100644 --- a/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/remote/Wire.kt +++ b/contract/src/main/kotlin/com/xfl/msgbot/plugin/api/remote/Wire.kt @@ -7,6 +7,7 @@ package com.xfl.msgbot.plugin.api.remote import com.xfl.msgbot.plugin.api.call.CallException import com.xfl.msgbot.plugin.api.call.CallResult +import com.xfl.msgbot.plugin.api.engine.ClassAccess import com.xfl.msgbot.plugin.api.engine.EngineException import com.xfl.msgbot.plugin.api.engine.LoadRequest import com.xfl.msgbot.plugin.api.engine.ProfileScript @@ -118,6 +119,7 @@ internal object Wire { "entry" to request.entry, "sources" to request.sources, "options" to request.options, + "classAccess" to request.classAccess?.toValue(), ) fun loadRequestOf(value: Value): LoadRequest { @@ -133,6 +135,7 @@ internal object Wire { v.asStringOrNull() ?: throw IllegalArgumentException("A source is text") }, options = map["options"]?.map()?.mapValues { (_, v) -> v.asStringOrNull().orEmpty() }.orEmpty(), + classAccess = map["classAccess"]?.takeIf { it != Value.VNull }?.let(ClassAccess::fromValue), ) } diff --git a/contract/src/test/kotlin/com/xfl/msgbot/plugin/api/remote/EngineSessionTest.kt b/contract/src/test/kotlin/com/xfl/msgbot/plugin/api/remote/EngineSessionTest.kt index 26c7765..098e302 100644 --- a/contract/src/test/kotlin/com/xfl/msgbot/plugin/api/remote/EngineSessionTest.kt +++ b/contract/src/test/kotlin/com/xfl/msgbot/plugin/api/remote/EngineSessionTest.kt @@ -1,6 +1,7 @@ package com.xfl.msgbot.plugin.api.remote import com.xfl.msgbot.plugin.api.call.CallResult +import com.xfl.msgbot.plugin.api.engine.ClassAccess import com.xfl.msgbot.plugin.api.engine.EngineContext import com.xfl.msgbot.plugin.api.engine.EngineException import com.xfl.msgbot.plugin.api.engine.EngineScheduler @@ -129,6 +130,7 @@ class EngineSessionTest { when (source) { "loaded" -> Value.of(loaded?.let { listOf(it.language, it.entry, it.options["strict"], it.api.map { spec -> spec.namespace }) }) "seen" -> Value.of(seen.toList()) + "classAccess" -> loaded?.classAccess?.toValue() ?: Value.VNull else -> Value.VNull } @@ -169,6 +171,23 @@ class EngineSessionTest { assertEquals(Value.of(listOf("fake", "main.fake", "true", StandardApi.HOST.map { it.namespace })), engine.eval("loaded")) } + @Test + fun `the class access arrives with the load, and its absence stays absent`() { + val plain = connect() + plain.load(request) + assertEquals(Value.VNull, plain.eval("classAccess")) + val access = ClassAccess(ClassAccess.Preset.CUSTOM, allow = listOf("com.example.*"), deny = listOf("java.net.Socket"), restrictions = false) + val guarded = connect() + guarded.load(request.copy(classAccess = access)) + assertEquals(access, ClassAccess.fromValue(guarded.eval("classAccess"))) + } + + @Test + fun `an unknown preset reads as the safe one`() { + val value = Value.VObject(mapOf("preset" to Value.VString("future"))) + assertEquals(ClassAccess.DEFAULT, ClassAccess.fromValue(value)) + } + @Test fun `a script that cannot load fails the load with its own message`() { val engine = connect() diff --git a/guard/build.gradle.kts b/guard/build.gradle.kts new file mode 100644 index 0000000..919dab9 --- /dev/null +++ b/guard/build.gradle.kts @@ -0,0 +1,60 @@ +plugins { + id("com.android.library") + `maven-publish` +} + +android { + namespace = "com.xfl.msgbot.plugin.guard" + compileSdk = 36 + + defaultConfig { + minSdk = 28 + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + testOptions { + unitTests.isIncludeAndroidResources = false + } + + publishing { + singleVariant("release") { withSourcesJar() } + } +} + +kotlin { + compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) } +} + +dependencies { + api(project(":android")) + testImplementation("junit:junit:4.13.2") + testImplementation(kotlin("test-junit")) + androidTestImplementation("androidx.test:runner:1.7.0") + androidTestImplementation("androidx.test.ext:junit:1.3.0") + androidTestImplementation(kotlin("test-junit")) +} + +publishing { + repositories { + mavenLocal() + maven { + name = "GitHubPackages" + url = uri("https://maven.pkg.github.com/MessengerBotTeam/PluginAPI") + credentials { + username = project.findProperty("gpr.user") as String? ?: System.getenv("USERNAME") + password = project.findProperty("gpr.key") as String? ?: System.getenv("TOKEN") + } + } + } + publications { + register("gpr") { + artifactId = "PluginApi-guard" + afterEvaluate { from(components["release"]) } + } + } +} diff --git a/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/FolderHost.kt b/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/FolderHost.kt new file mode 100644 index 0000000..8e582b6 --- /dev/null +++ b/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/FolderHost.kt @@ -0,0 +1,218 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import android.os.ParcelFileDescriptor +import android.system.ErrnoException +import android.system.Os +import android.system.OsConstants +import android.system.StructStat +import com.xfl.msgbot.plugin.api.engine.HostFileMode +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList + +/** A host that serves [root] and [tmp] the way the app's `ProjectFiles` does, and refuses every other place with EACCES. */ +class FolderHost( + rootFolder: File, + private val tmpFolder: File, +) : GuardHost { + override val root: String = rootFolder.canonicalPath + private val tmp = tmpFolder.canonicalPath + val logs = CopyOnWriteArrayList() + + private fun resolve(path: String): String { + val absolute = if (path.startsWith("/")) path else "$root/$path" + val clean = GuardFile.normalize(absolute) + val parent = File(clean).parentFile + val real = if (parent != null && parent.exists()) File(parent.canonicalFile, File(clean).name).path else clean + if (real != root && !real.startsWith("$root/") && real != tmp && !real.startsWith("$tmp/")) throw HostIOException("EACCES", path, "permission denied, '$path'") + return clean + } + + private fun os( + path: String, + block: () -> T, + ): T = + try { + block() + } catch (e: ErrnoException) { + throw HostIOException(OsConstants.errnoName(e.errno) ?: "EIO", path, e.message ?: "") + } + + private fun entry(stat: StructStat) = + GuardHost.Entry( + isDirectory = OsConstants.S_ISDIR(stat.st_mode), + isSymbolicLink = OsConstants.S_ISLNK(stat.st_mode), + size = stat.st_size, + modifiedMs = stat.st_mtim.tv_sec * 1000 + stat.st_mtim.tv_nsec / 1_000_000, + accessedMs = stat.st_atim.tv_sec * 1000 + stat.st_atim.tv_nsec / 1_000_000, + createdMs = 0, + mode = stat.st_mode and 0xfff, + uid = stat.st_uid, + gid = stat.st_gid, + ) + + override fun stat( + path: String, + followLinks: Boolean, + ): GuardHost.Entry? { + val real = resolve(path) + return try { + entry(if (followLinks) Os.stat(real) else Os.lstat(real)) + } catch (e: ErrnoException) { + if (e.errno == OsConstants.ENOENT || e.errno == OsConstants.ENOTDIR) null else throw HostIOException(OsConstants.errnoName(e.errno) ?: "EIO", path, e.message ?: "") + } + } + + override fun list(path: String): List { + val real = resolve(path) + val file = File(real) + if (!file.exists()) throw HostIOException("ENOENT", path, "no such file or directory, scandir '$path'") + return file.list()?.toList() ?: throw HostIOException("ENOTDIR", path, "not a directory, scandir '$path'") + } + + override fun access( + path: String, + mode: Int, + ): Boolean = + try { + Os.access(resolve(path), mode) + } catch (e: Exception) { + false + } + + override fun statfs(path: String): GuardHost.Space { + val real = resolve(path) + val s = os(path) { Os.statvfs(real) } + return GuardHost.Space(s.f_bsize, s.f_blocks, s.f_bfree, s.f_bavail) + } + + override fun mkdir( + path: String, + recursive: Boolean, + ): Boolean { + val file = File(resolve(path)) + if (file.isDirectory) return false + if (file.exists()) throw HostIOException("EEXIST", path, "file already exists, mkdir '$path'") + if (recursive) return file.mkdirs() + os(path) { Os.mkdir(file.path, 0x1ff) } + return true + } + + override fun remove( + path: String, + recursive: Boolean, + ): Boolean { + val file = File(resolve(path)) + if (!file.exists() && !isLink(file)) return false + if (recursive) return file.deleteRecursively() + os(path) { Os.remove(file.path) } + return true + } + + private fun isLink(file: File) = runCatching { OsConstants.S_ISLNK(Os.lstat(file.path).st_mode) }.getOrDefault(false) + + override fun rename( + from: String, + to: String, + ) { + val a = resolve(from) + val b = resolve(to) + os(from) { Os.rename(a, b) } + } + + override fun symlink( + target: String, + path: String, + ) { + val real = resolve(path) + os(path) { Os.symlink(target, real) } + } + + override fun link( + existing: String, + path: String, + ) { + val a = resolve(existing) + val b = resolve(path) + os(path) { Os.link(a, b) } + } + + override fun readlink(path: String): String { + val real = resolve(path) + return os(path) { Os.readlink(real) } + } + + override fun truncate( + path: String, + size: Long, + ) { + val real = resolve(path) + os(path) { + val fd = Os.open(real, OsConstants.O_WRONLY, 0) + try { + Os.ftruncate(fd, size) + } finally { + Os.close(fd) + } + } + } + + override fun chmod( + path: String, + mode: Int, + ) { + val real = resolve(path) + os(path) { Os.chmod(real, mode) } + } + + override fun utimes( + path: String, + accessedMs: Long, + modifiedMs: Long, + ) { + val real = resolve(path) + if (!File(real).exists()) throw HostIOException("ENOENT", path, "no such file or directory") + File(real).setLastModified(modifiedMs) + } + + override fun realpath(path: String): String { + val real = resolve(path) + if (!File(real).exists()) throw HostIOException("ENOENT", path, "no such file or directory, realpath '$path'") + return File(real).canonicalPath.also { resolve(it) } + } + + override fun tmpdir(): String = tmp + + override fun open( + path: String, + mode: Int, + ): ParcelFileDescriptor { + val real = resolve(path) + val readWrite = (mode and HostFileMode.READ_WRITE) != 0 + var flags = + when { + (mode and HostFileMode.APPEND) != 0 -> OsConstants.O_CREAT or OsConstants.O_APPEND or (if (readWrite) OsConstants.O_RDWR else OsConstants.O_WRONLY) + (mode and HostFileMode.WRITE) != 0 -> OsConstants.O_CREAT or OsConstants.O_TRUNC or (if (readWrite) OsConstants.O_RDWR else OsConstants.O_WRONLY) + readWrite -> OsConstants.O_RDWR + else -> OsConstants.O_RDONLY + } + if ((mode and HostFileMode.EXCLUSIVE) != 0) flags = flags or OsConstants.O_EXCL + val fd = os(path) { Os.open(real, flags or OsConstants.O_CLOEXEC, 0x1b6) } + if (OsConstants.S_ISDIR(Os.fstat(fd).st_mode) && (flags and OsConstants.O_ACCMODE) != OsConstants.O_RDONLY) { + Os.close(fd) + throw HostIOException("EISDIR", path, "illegal operation on a directory") + } + return ParcelFileDescriptor.dup(fd).also { Os.close(fd) } + } + + override fun log( + level: String, + message: String, + ) { + logs += "$level $message" + } +} diff --git a/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardBoundaryTest.kt b/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardBoundaryTest.kt new file mode 100644 index 0000000..0d12828 --- /dev/null +++ b/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardBoundaryTest.kt @@ -0,0 +1,235 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.xfl.msgbot.plugin.api.engine.ClassAccess +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import java.io.FileNotFoundException +import java.lang.reflect.Modifier +import java.nio.file.AccessDeniedException +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths +import java.util.zip.ZipFile +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +@RunWith(AndroidJUnit4::class) +class GuardBoundaryTest { + private lateinit var top: File + private lateinit var project: File + private lateinit var outside: File + private lateinit var tmp: File + private lateinit var host: FolderHost + private lateinit var session: GuardSession + private var previous: GuardSession? = null + + @Before + fun setUp() { + top = File(InstrumentationRegistry.getInstrumentation().targetContext.cacheDir, "guard-boundary").apply { deleteRecursively() } + project = File(top, "project").apply { mkdirs() }.canonicalFile + tmp = File(top, "tmp").apply { mkdirs() }.canonicalFile + outside = File(top, "secret.txt").apply { writeText("secret") }.canonicalFile + host = FolderHost(project, tmp) + use(ClassAccess.DEFAULT) + } + + private fun use(access: ClassAccess) { + session = GuardSession(host, ClassRules(access, listOf("com.example.engine."))) + val old = GuardContext.swap(session) + if (!::top.isInitialized || previous == null) previous = old + } + + @After + fun tearDown() { + Descriptors.useHiddenApi = true + GuardContext.swap(previous) + top.deleteRecursively() + } + + @Test + fun relativePathsAreInTheProjectFolder() { + GuardFile("note.txt").also { it.createNewFile() } + assertTrue(File(project, "note.txt").exists()) + assertEquals("${project.path}/note.txt", GuardFile("note.txt").absolutePath) + assertEquals("${project.path}/note.txt", GuardPaths.get("note.txt").toAbsolutePath().toString()) + GuardFileOutputStream("rel.txt").use { it.write(1) } + assertEquals(1, File(project, "rel.txt").length()) + } + + @Test + fun outsideTheRulesIsRefusedAndReportedOnce() { + val secret = GuardFile(outside.path) + assertFailsWith { secret.exists() } + assertFailsWith { secret.length() } + assertFalse(secret.canRead()) + val io = assertFailsWith { GuardFileInputStream(outside.path) } + assertTrue(io.message!!.contains("EACCES"), io.message) + assertFailsWith { Files.readAllBytes(GuardPaths.get(outside.path)) } + assertFailsWith { GuardRandomAccessFile(outside.path, "r") } + assertFailsWith { GuardZipFile(outside.path) } + assertFailsWith { GuardFile(project, "../secret.txt").exists() } + assertEquals(1, host.logs.count { it.contains(outside.path) }, host.logs.toString()) + } + + @Test + fun realFilesAndPathsBecomeGuarded() { + val file = GuardPolicy.replace(File(outside.path)) + assertIs(file) + assertFailsWith { file.exists() } + val path = GuardPolicy.replace(Paths.get(outside.path)) + assertIs(path) + assertFailsWith { Files.size(path as Path) } + } + + @Test + fun temporaryFilesGoToTheHostsFolder() { + val a = GuardFileBase.createTempFile("abc", ".t") + assertEquals(GuardFileBase::class.java, GuardFile::class.java.getMethod("createTempFile", String::class.java, String::class.java).declaringClass) + assertEquals(tmp.path, a.parent) + val b = GuardFiles.createTempFile("abc", ".t") + assertEquals(tmp.path, b.parent.toString()) + val c = GuardFiles.createTempDirectory("dir") + assertTrue(File(c.toString()).isDirectory) + assertTrue(File(tmp, a.name).exists()) + } + + @Test + fun deleteOnExitRunsWhenTheSessionCloses() { + val file = GuardFile("bye.txt").apply { createNewFile() } + file.deleteOnExit() + assertTrue(File(project, "bye.txt").exists()) + session.close() + assertFalse(File(project, "bye.txt").exists()) + } + + @Test + fun withoutASessionNothingOpens() { + val saved = GuardContext.swap(null) + try { + assertFailsWith { GuardFile("x") } + assertFailsWith { GuardPaths.get("x") } + } finally { + GuardContext.swap(saved) + } + } + + @Test + fun theFallbackWithoutTheHiddenApiFindsTheSameDescriptor() { + Descriptors.useHiddenApi = false + GuardFileOutputStream("p.bin").use { it.write(byteArrayOf(1, 2, 3)) } + GuardRandomAccessFile("p.bin", "rw").use { + it.seek(3) + it.write(4) + assertEquals(4, it.length()) + } + GuardRandomAccessFile("p.bin", "r").use { assertEquals(4, it.channel.size()) } + assertEquals(listOf(1, 2, 3, 4), File(project, "p.bin").readBytes().toList()) + } + + @Test + fun theEnvironmentNamesTheSameFoldersAsGuardFiles() { + @Suppress("DEPRECATION") + val real = android.os.Environment.getExternalStorageDirectory() + val guarded = GuardEnvironment.getExternalStorageDirectory() + assertIs(guarded) + assertEquals(real.path, guarded.path) + assertEquals(android.os.Environment.DIRECTORY_DOWNLOADS, GuardEnvironment.DIRECTORY_DOWNLOADS) + } + + @Test + fun guardClassesDescribeTheClassAskedFor() { + val file = GuardClass.forName("java.io.File") + assertEquals("java.io.File", file.getName()) + assertTrue(file.isInstance(File("x"))) + assertEquals("java.io.File", GuardClass.of(GuardFile::class.java).getName()) + val made = file.getConstructor(GuardClass.of(String::class.java)).newInstance("made.txt") + assertIs(made) + val temp = file.getMethod("createTempFile", GuardClass.of(String::class.java), GuardClass.of(String::class.java)).invoke(null, "abc", null) + assertEquals(tmp.path, (temp as File).parent) + assertEquals("java.nio.file.Paths", GuardClass.forName("java.nio.file.Paths").getName()) + assertFailsWith { GuardClass.forName("java.lang.reflect.Proxy") } + assertFailsWith { GuardClass.forName("com.example.engine.Runtime") } + assertFailsWith { GuardClass.forName("com.xfl.msgbot.plugin.guard.GuardContext") } + assertTrue(host.logs.any { it.contains("java.lang.reflect.Proxy") }) + } + + @Test + fun reflectionOnOrdinaryClassesWorks() { + val list = GuardClass.forName("java.util.ArrayList").getConstructor().newInstance() as MutableList + GuardClass.forName("java.util.ArrayList").getMethod("add", GuardClass.of(Any::class.java)).invoke(list, "x") + assertEquals(listOf("x"), list) + val max = GuardClass.forName("java.lang.Integer").getField("MAX_VALUE").get(null) + assertEquals(Int.MAX_VALUE, max) + assertTrue(Modifier.isPublic(GuardClass.forName("java.lang.String").getModifiers())) + assertIs(GuardPolicy.replace(String::class.java)) + } + + @Test + fun reflectiveMembersOfRefusedClassesAreRefusedWhenUsed() { + val forName = GuardClass.forName("java.lang.Thread").getMethod("currentThread") + assertIs(forName.invoke(null)) + val proxy = java.lang.reflect.Proxy::class.java.getMethod("isProxyClass", Class::class.java) + val standIn = GuardPolicy.replace(proxy) as GuardMethod + assertFailsWith { standIn.invoke(null, String::class.java) } + } + + @Test + fun widePresetLetsRealReflectionThrough() { + use(ClassAccess(ClassAccess.Preset.WIDE)) + val method = String::class.java.getMethod("length") + assertEquals(method, GuardPolicy.replace(method)) + use(ClassAccess.DEFAULT) + assertIs(GuardPolicy.replace(method)) + } + + @Test + fun withoutRestrictionsClassesAreRealButFilesStayGuarded() { + use(ClassAccess(restrictions = false)) + assertEquals(String::class.java, GuardPolicy.replace(String::class.java)) + assertNull(GuardPolicy.substituteOf("java.lang.Class")) + assertEquals(GuardFile::class.java, GuardPolicy.substituteOf("java.io.File")) + assertIs(GuardPolicy.replace(File("x"))) + assertEquals(GuardPolicy.Lookup.Ordinary, GuardPolicy.lookup("java.lang.reflect.Proxy")) + assertEquals(GuardPolicy.Lookup.Denied, GuardPolicy.lookup("com.example.engine.Thing")) + } + + @Test + fun customListsAddAndTakeAway() { + use(ClassAccess(ClassAccess.Preset.CUSTOM, allow = listOf("java.lang.reflect.Proxy"), deny = listOf("java.net.*"))) + assertEquals(GuardPolicy.Lookup.Ordinary, GuardPolicy.lookup("java.lang.reflect.Proxy")) + assertEquals(GuardPolicy.Lookup.Denied, GuardPolicy.lookup("java.net.Socket")) + assertEquals(GuardPolicy.Lookup.Denied, GuardPolicy.lookup("java.lang.invoke.MethodHandles")) + } + + @Test + fun processesNamingPathsOutsideAreRefused() { + assertFailsWith { GuardRuntime.getRuntime().exec(arrayOf("ls", outside.path)) } + assertFailsWith { GuardRuntime.getRuntime().exec("sh -c id") } + GuardRuntime.getRuntime().exec(arrayOf("ls", project.path)).waitFor() + } + + @Test + fun stockZipFileAndGuardAgreeOnAnArchiveInTheProject() { + val zip = File(project, "a.zip") + java.util.zip.ZipOutputStream(zip.outputStream()).use { + it.putNextEntry(java.util.zip.ZipEntry("x")) + it.write("y".toByteArray()) + } + val names = ZipFile(zip).use { z -> z.entries().toList().map { it.name } } + assertEquals(names, GuardZipFile("a.zip").use { z -> z.entries().toList().map { it.name } }) + } +} diff --git a/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardDifferentialTest.kt b/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardDifferentialTest.kt new file mode 100644 index 0000000..5fb0eff --- /dev/null +++ b/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardDifferentialTest.kt @@ -0,0 +1,502 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.FileReader +import java.io.FileWriter +import java.io.PrintStream +import java.io.PrintWriter +import java.io.RandomAccessFile +import java.nio.ByteBuffer +import java.nio.channels.FileChannel +import java.nio.charset.Charset +import java.nio.file.FileVisitOption +import java.nio.file.Files +import java.nio.file.LinkOption +import java.nio.file.Path +import java.nio.file.Paths +import java.nio.file.StandardCopyOption +import java.nio.file.StandardOpenOption +import java.nio.file.attribute.BasicFileAttributes +import java.nio.file.attribute.FileTime +import java.nio.file.attribute.PosixFilePermissions +import java.util.Scanner +import java.util.jar.Attributes +import java.util.jar.JarFile +import java.util.jar.JarOutputStream +import java.util.jar.Manifest +import java.util.zip.CRC32 +import java.util.zip.ZipEntry +import java.util.zip.ZipFile +import java.util.zip.ZipOutputStream +import kotlin.test.assertEquals + +/** + * Runs each scenario twice, once on the real classes in a folder of their own and once on the guard's classes in the + * project folder the host serves, and expects the same transcript: results, exception types and messages. + */ +@RunWith(AndroidJUnit4::class) +class GuardDifferentialTest { + private interface ZipView { + val comment: String? + val names: List + + fun describe(name: String): String? + + fun read(name: String): String? + + fun manifest(): String? + + fun close() + } + + private interface Io { + val base: String + + fun file(path: String): File + + fun fis(path: String): FileInputStream + + fun fos( + path: String, + append: Boolean = false, + ): FileOutputStream + + fun reader( + path: String, + charset: Charset, + ): FileReader + + fun writer( + path: String, + charset: Charset, + append: Boolean, + ): FileWriter + + fun printWriter(file: File): PrintWriter + + fun printStream(path: String): PrintStream + + fun raf( + path: String, + mode: String, + ): RandomAccessFile + + fun path(path: String): Path + + fun scan(file: File): List + + fun zip(path: String): ZipView + + fun jar(path: String): ZipView + } + + private lateinit var top: File + private lateinit var real: Io + private lateinit var guarded: Io + private lateinit var host: FolderHost + private var previous: GuardSession? = null + + private fun view(zip: ZipFile) = + object : ZipView { + override val comment = zip.comment + override val names = zip.entries().toList().map { it.name } + + override fun describe(name: String) = zip.getEntry(name)?.let { "${it.name} ${it.size} ${it.compressedSize} ${it.crc} ${it.method} ${it.comment} ${it.isDirectory}" } + + override fun read(name: String) = zip.getEntry(name)?.let { zip.getInputStream(it).readBytes().decodeToString() } + + override fun manifest() = (zip as? JarFile)?.manifest?.mainAttributes?.getValue("Created-By") + + override fun close() = zip.close() + } + + private fun view(zip: GuardZipFile) = + object : ZipView { + override val comment = zip.getComment() + override val names = zip.entries().toList().map { it.name } + + override fun describe(name: String) = zip.getEntry(name)?.let { "${it.name} ${it.size} ${it.compressedSize} ${it.crc} ${it.method} ${it.comment} ${it.isDirectory}" } + + override fun read(name: String) = zip.getEntry(name)?.let { zip.getInputStream(it)!!.readBytes().decodeToString() } + + override fun manifest() = (zip as? GuardJarFile)?.getManifest()?.mainAttributes?.getValue("Created-By") + + override fun close() = zip.close() + } + + @Before + fun setUp() { + val cache = InstrumentationRegistry.getInstrumentation().targetContext.cacheDir + top = File(cache, "guard-diff").apply { deleteRecursively() } + val mirror = File(top, "real").apply { mkdirs() }.canonicalPath + val project = File(top, "project").apply { mkdirs() } + val tmp = File(top, "tmp").apply { mkdirs() } + host = FolderHost(project, tmp) + previous = GuardContext.swap(GuardSession(host)) + real = + object : Io { + override val base = mirror + + override fun file(path: String) = File("$base/$path") + + override fun fis(path: String) = FileInputStream("$base/$path") + + override fun fos( + path: String, + append: Boolean, + ) = FileOutputStream("$base/$path", append) + + override fun reader( + path: String, + charset: Charset, + ) = FileReader("$base/$path", charset) + + override fun writer( + path: String, + charset: Charset, + append: Boolean, + ) = FileWriter("$base/$path", charset, append) + + override fun printWriter(file: File) = PrintWriter(file) + + override fun printStream(path: String) = PrintStream("$base/$path") + + override fun raf( + path: String, + mode: String, + ) = RandomAccessFile("$base/$path", mode) + + override fun path(path: String): Path = Paths.get(if (path.startsWith("/") || path.isEmpty()) path else "$base/$path") + + override fun scan(file: File) = Scanner(file).use { s -> buildList { while (s.hasNext()) add(if (s.hasNextInt()) "int ${s.nextInt()}" else s.next()) } } + + override fun zip(path: String) = view(ZipFile("$base/$path")) + + override fun jar(path: String) = view(JarFile("$base/$path")) + } + guarded = + object : Io { + override val base = host.root + + override fun file(path: String): File = GuardFile("$base/$path") + + override fun fis(path: String): FileInputStream = GuardFileInputStream("$base/$path") + + override fun fos( + path: String, + append: Boolean, + ): FileOutputStream = GuardFileOutputStream("$base/$path", append) + + override fun reader( + path: String, + charset: Charset, + ): FileReader = GuardFileReader("$base/$path", charset) + + override fun writer( + path: String, + charset: Charset, + append: Boolean, + ): FileWriter = GuardFileWriter("$base/$path", charset, append) + + override fun printWriter(file: File): PrintWriter = GuardPrintWriter(file) + + override fun printStream(path: String): PrintStream = GuardPrintStream("$base/$path") + + override fun raf( + path: String, + mode: String, + ): RandomAccessFile = GuardRandomAccessFile("$base/$path", mode) + + override fun path(path: String): Path = GuardPaths.get(if (path.startsWith("/") || path.isEmpty()) path else "$base/$path") + + override fun scan(file: File) = GuardScanner(file).use { s -> buildList { while (s.hasNext()) add(if (s.hasNextInt()) "int ${s.nextInt()}" else s.next()) } } + + override fun zip(path: String) = view(GuardZipFile("$base/$path")) + + override fun jar(path: String) = view(GuardJarFile("$base/$path")) + } + } + + @After + fun tearDown() { + GuardContext.swap(previous) + top.deleteRecursively() + } + + private fun same(scenario: Io.(MutableList) -> Unit) { + fun run(io: Io): List { + val out = ArrayList() + try { + io.scenario(out) + } catch (e: Throwable) { + out += "escaped ${e.javaClass.name}: ${e.message}" + } + return out.map { it.replace(io.base, "") } + } + assertEquals(run(real), run(guarded)) + } + + private inline fun MutableList.step( + name: String, + block: () -> Any?, + ) { + this += + try { + "$name = ${show(block())}" + } catch (e: Throwable) { + "$name ! ${e.javaClass.name}: ${e.message}" + } + } + + private fun show(value: Any?): String = + when (value) { + is Array<*> -> value.map { show(it) }.sorted().toString() + is Collection<*> -> value.map { show(it) }.toString() + is ByteArray -> value.decodeToString() + is File -> "File(${value.path})" + is Path -> "Path($value)" + else -> value.toString() + } + + @Test + fun filesAndFolders() = + same { out -> + out.step("mkdirs") { file("a/b/c").mkdirs() } + out.step("mkdirs again") { file("a/b/c").mkdirs() } + out.step("isDirectory") { file("a/b").isDirectory } + out.step("isFile dir") { file("a/b").isFile } + out.step("create") { file("a/x.txt").createNewFile() } + out.step("create again") { file("a/x.txt").createNewFile() } + out.step("create in missing") { file("nope/x.txt").createNewFile() } + out.step("write") { fos("a/x.txt").use { it.write("hello".toByteArray()) } } + out.step("length") { file("a/x.txt").length() } + out.step("length missing") { file("a/none").length() } + out.step("exists missing") { file("a/none").exists() } + out.step("list") { file("a").list() } + out.step("list missing") { file("a/none").list() } + out.step("list file") { file("a/x.txt").list() } + out.step("listFiles") { file("a").listFiles() } + out.step("listFiles filter") { file("a").listFiles { f -> f.isFile } } + out.step("rename") { file("a/x.txt").renameTo(file("a/y.txt")) } + out.step("old exists") { file("a/x.txt").exists() } + out.step("new exists") { file("a/y.txt").exists() } + out.step("delete full folder") { file("a").delete() } + out.step("delete file") { file("a/y.txt").delete() } + out.step("delete missing") { file("a/y.txt").delete() } + out.step("mkdir no parent") { file("z/q").mkdir() } + out.step("mkdir") { file("z").mkdir() } + out.step("canonical") { file("a/b/../b/c/./").canonicalPath } + out.step("canonical missing") { file("a/b/none/../more").canonicalPath } + out.step("parent") { file("a/b/c").parentFile } + out.step("uri dir") { file("a/b").toURI() } + out.step("uri file") { file("a/q.txt").toURI() } + out.step("hidden") { file(".hidden").isHidden } + out.step("equals") { file("a/b") == File(file("a/b").path) } + out.step("compare") { file("a/b").compareTo(File(file("a/c").path)) } + out.step("hash") { file("a/b").hashCode() == File(file("a/b").path).hashCode() } + out.step("touch") { file("t").createNewFile() } + out.step("setLastModified") { file("t").setLastModified(1_600_000_000_000) } + out.step("lastModified") { file("t").lastModified() } + out.step("setReadOnly") { file("t").setReadOnly() } + out.step("canWrite read-only") { file("t").canWrite() } + out.step("setWritable") { file("t").setWritable(true) } + out.step("canWrite") { file("t").canWrite() } + out.step("canRead") { file("t").canRead() } + out.step("canExecute") { file("t").canExecute() } + out.step("setExecutable") { file("t").setExecutable(true, true) } + out.step("canExecute after") { file("t").canExecute() } + out.step("space") { file("t").totalSpace > 0 && file("t").usableSpace > 0 } + out.step("toPath") { file("a/b").toPath().fileName } + } + + @Test + fun streams() = + same { out -> + out.step("open missing") { fis("none.txt") } + file("d").mkdir() + out.step("open folder") { fis("d") } + out.step("write folder") { fos("d") } + out.step("write in missing") { fos("none/x.txt") } + out.step("write") { fos("s.txt").use { it.write("one".toByteArray()) } } + out.step("append") { fos("s.txt", true).use { it.write("two".toByteArray()) } } + out.step("read") { fis("s.txt").use { it.readBytes() } } + out.step("channel") { fis("s.txt").use { it.channel.size().toString() + " " + it.channel.position() } } + out.step("skip+available") { fis("s.txt").use { "${it.skip(2)} ${it.available()} ${it.read().toChar()}" } } + out.step("writer utf16") { writer("w.txt", Charsets.UTF_16LE, false).use { it.write("한글 ok") } } + out.step("writer append") { writer("w.txt", Charsets.UTF_16LE, true).use { it.append('!').let { } } } + out.step("reader utf16") { reader("w.txt", Charsets.UTF_16LE).use { it.readText() } } + out.step("raw bytes") { fis("w.txt").use { it.readBytes().size } } + out.step("print writer") { printWriter(file("p.txt")).use { it.println("line"); it.printf("%d", 42).let { } } } + out.step("print writer read") { fis("p.txt").use { it.readBytes() } } + out.step("print stream") { printStream("q.txt").use { it.print(true); it.print(1.5) } } + out.step("print stream read") { fis("q.txt").use { it.readBytes() } } + out.step("print writer missing folder") { printWriter(file("none/p.txt")) } + out.step("scanner") { fos("n.txt").use { it.write("a 1 b 22".toByteArray()) }; scan(file("n.txt")) } + out.step("scanner missing") { scan(file("none.txt")) } + } + + @Test + fun randomAccess() = + same { out -> + out.step("bad mode") { raf("r.bin", "x") } + out.step("read missing") { raf("r.bin", "r") } + out.step("rw creates") { + raf("r.bin", "rw").use { + it.writeInt(7) + it.writeUTF("é") + it.writeLong(-1) + "${it.filePointer} ${it.length()}" + } + } + out.step("read back") { + raf("r.bin", "r").use { + val a = it.readInt() + val b = it.readUTF() + it.seek(0) + "$a $b ${it.readByte()} ${it.length()}" + } + } + out.step("write read-only") { raf("r.bin", "r").use { it.write(1) } } + out.step("setLength") { raf("r.bin", "rw").use { it.setLength(3); it.length() } } + out.step("map") { + raf("m.bin", "rw").use { + it.setLength(8) + val map = it.channel.map(FileChannel.MapMode.READ_WRITE, 0, 8) + map.putInt(0, 0x01020304) + map.force() + it.seek(0) + it.readInt().toString(16) + } + } + out.step("lock") { raf("m.bin", "rw").use { it.channel.lock().use { lock -> "${lock.isValid} ${lock.isShared}" } } } + out.step("readLine") { + fos("l.txt").use { it.write("x\r\ny\nz".toByteArray()) } + raf("l.txt", "r").use { listOf(it.readLine(), it.readLine(), it.readLine(), it.readLine()) } + } + out.step("fd stream") { raf("l.txt", "r").use { r -> FileInputStream(r.fd).readBytes().size } } + } + + @Test + fun nio() = + same { out -> + out.step("write lines") { Files.write(path("n/lines.txt"), listOf("a", "b")) } + Files.createDirectories(path("n/sub/deep")) + out.step("write lines") { Files.write(path("n/lines.txt"), listOf("a", "b")) } + out.step("read lines") { Files.readAllLines(path("n/lines.txt")) } + out.step("size") { Files.size(path("n/lines.txt")) } + out.step("exists") { "${Files.exists(path("n"))} ${Files.notExists(path("n/none"))} ${Files.isDirectory(path("n/sub"))} ${Files.isRegularFile(path("n/lines.txt"))}" } + out.step("read missing") { Files.readAllBytes(path("n/none")) } + out.step("create file twice") { Files.createFile(path("n/one")); Files.createFile(path("n/one")) } + out.step("create dir twice") { Files.createDirectory(path("n/sub")) } + out.step("list") { Files.list(path("n")).use { s -> s.map { it.fileName.toString() }.sorted().toList() } } + out.step("walk") { Files.walk(path("n")).use { s -> s.map { path("n").relativize(it).toString() }.sorted().toList() } } + out.step("find") { Files.find(path("n"), 5, { _, a -> a.isRegularFile }).use { s -> s.map { it.fileName.toString() }.sorted().toList() } } + out.step("copy") { Files.copy(path("n/lines.txt"), path("n/sub/copy.txt")) } + out.step("copy exists") { Files.copy(path("n/lines.txt"), path("n/sub/copy.txt")) } + out.step("copy replace") { Files.copy(path("n/one"), path("n/sub/copy.txt"), StandardCopyOption.REPLACE_EXISTING); Files.size(path("n/sub/copy.txt")) } + out.step("move") { Files.move(path("n/one"), path("n/two")) } + out.step("move missing") { Files.move(path("n/one"), path("n/three")) } + out.step("delete full") { Files.delete(path("n/sub")) } + out.step("delete missing") { Files.delete(path("n/none")) } + out.step("deleteIfExists") { "${Files.deleteIfExists(path("n/two"))} ${Files.deleteIfExists(path("n/two"))}" } + out.step("attributes") { Files.readAttributes(path("n/lines.txt"), BasicFileAttributes::class.java).let { "${it.size()} ${it.isDirectory} ${it.isRegularFile} ${it.isSymbolicLink}" } } + out.step("attribute map") { Files.readAttributes(path("n/lines.txt"), "size,isDirectory").toSortedMap() } + out.step("posix") { Files.setPosixFilePermissions(path("n/lines.txt"), PosixFilePermissions.fromString("rw-r-----")); PosixFilePermissions.toString(Files.getPosixFilePermissions(path("n/lines.txt"))) } + out.step("times") { Files.setLastModifiedTime(path("n/lines.txt"), FileTime.fromMillis(1_500_000_000_000)); Files.getLastModifiedTime(path("n/lines.txt")).toMillis() } + out.step("symlink") { Files.createSymbolicLink(path("n/link"), path("lines.txt")); "${Files.isSymbolicLink(path("n/link"))} ${Files.readSymbolicLink(path("n/link"))} ${Files.readAllLines(path("n/link"))}" } + out.step("link attrs") { Files.readAttributes(path("n/link"), BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS).isSymbolicLink } + out.step("same file") { Files.isSameFile(path("n/link"), path("n/lines.txt")) } + out.step("buffered") { Files.newBufferedWriter(path("n/b.txt")).use { it.write("x\ny") }; Files.newBufferedReader(path("n/b.txt")).use { it.readLines() } } + out.step("lines") { Files.lines(path("n/b.txt")).use { it.toList() } } + out.step("create new twice") { Files.newByteChannel(path("n/b.txt"), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE) } + out.step("append") { Files.write(path("n/b.txt"), "z".toByteArray(), StandardOpenOption.APPEND); Files.readAllBytes(path("n/b.txt")) } + out.step("truncate") { Files.write(path("n/b.txt"), "q".toByteArray(), StandardOpenOption.TRUNCATE_EXISTING); Files.readAllBytes(path("n/b.txt")) } + out.step("channel") { + FileChannel.open(path("n/c.bin"), StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE).use { + it.write(ByteBuffer.wrap(byteArrayOf(1, 2, 3))) + val back = ByteBuffer.allocate(3) + it.read(back, 0) + "${it.size()} ${it.position()} ${back.array().toList()}" + } + } + out.step("temp in dir") { Files.createTempFile(path("n"), "pre", ".suf").fileName.toString().let { it.startsWith("pre") && it.endsWith(".suf") } } + out.step("walk depth") { Files.walk(path("n"), 1, FileVisitOption.FOLLOW_LINKS).use { it.count() } } + out.step("to file") { path("n/lines.txt").toFile().length() } + } + + @Test + fun pathsWithoutFiles() = + same { out -> + out.step("normalize") { path("/a/./b/../c").normalize() } + out.step("relativize") { path("/a/b").relativize(path("/a/c/d")) } + out.step("resolve") { path("/a").resolve("b/c") } + out.step("resolve absolute") { path("/a").resolve("/x") } + out.step("sibling") { path("/a/b").resolveSibling("c") } + out.step("subpath") { path("/a/b/c").subpath(1, 3) } + out.step("names") { path("/a/b/c").map { it.toString() } } + out.step("parts") { path("/a/b/c").let { "${it.fileName} ${it.parent} ${it.root} ${it.nameCount} ${it.isAbsolute}" } } + out.step("starts") { "${path("/a/b").startsWith("/a")} ${path("/a/b").startsWith("/ab")} ${path("/a/b").endsWith("b")}" } + out.step("relative") { Paths.get("x/y").let { "${it.isAbsolute} ${it.parent} ${it.root}" } } + out.step("empty") { path("").let { "${it.nameCount} ${it.fileName}" } } + out.step("uri") { path("/a/b").toUri() } + out.step("matcher") { path("/a/b.txt").fileSystem.getPathMatcher("glob:**/*.{txt,md}").matches(path("/a/b.txt")) } + out.step("nul") { path("/a\u0000b") } + } + + @Test + fun zips() = + same { out -> + ZipOutputStream(fos("z.zip")).use { zip -> + zip.setComment("archive comment") + zip.putNextEntry(ZipEntry("dir/")) + zip.closeEntry() + zip.putNextEntry(ZipEntry("dir/deflated.txt").apply { comment = "entry comment" }) + zip.write("deflated ".repeat(50).toByteArray()) + zip.closeEntry() + val bytes = "stored".toByteArray() + zip.putNextEntry( + ZipEntry("stored.txt").apply { + method = ZipEntry.STORED + size = bytes.size.toLong() + crc = CRC32().apply { update(bytes) }.value + }, + ) + zip.write(bytes) + zip.closeEntry() + } + val zip = zip("z.zip") + out.step("comment") { zip.comment } + out.step("names") { zip.names } + out.step("dir") { zip.describe("dir") } + out.step("deflated") { zip.describe("dir/deflated.txt") } + out.step("stored") { zip.describe("stored.txt") } + out.step("missing") { zip.describe("none") } + out.step("read deflated") { zip.read("dir/deflated.txt")?.length } + out.step("read stored") { zip.read("stored.txt") } + zip.close() + JarOutputStream(fos("j.jar"), Manifest().apply { mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0"; mainAttributes.putValue("Created-By", "test") }).use { jar -> + jar.putNextEntry(ZipEntry("a.txt")) + jar.write("a".toByteArray()) + jar.closeEntry() + } + val jar = jar("j.jar") + out.step("manifest") { jar.manifest() } + out.step("jar names") { jar.names } + jar.close() + out.step("not a zip") { fos("bad.zip").use { it.write("nope".toByteArray()) }; zip("bad.zip") } + out.step("missing zip") { zip("none.zip") } + } +} diff --git a/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardParityTest.kt b/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardParityTest.kt new file mode 100644 index 0000000..be093ea --- /dev/null +++ b/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardParityTest.kt @@ -0,0 +1,71 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Test +import org.junit.runner.RunWith +import java.lang.reflect.Modifier +import kotlin.test.assertEquals + +/** + * Every public constructor, method and field of a replaced class on this Android version must exist on its + * replacement with the same parameters, so a script written for the real class finds what it calls. + */ +@RunWith(AndroidJUnit4::class) +class GuardParityTest { + // Not offered on purpose; each needs a reason. + private val skipped = + setOf( + // Hands out the class loader or internals that get around the guard. + "java.lang.Class", + "java.lang.ClassLoader", + "java.lang.Runtime", + "java.lang.System", + "java.lang.ProcessBuilder", + // Path is an interface the replacement implements in full; its static of() is checked below. + "java.nio.file.Path", + ) + + // Public in the class at run time but @hide in the SDK: apps cannot call them anyway. + private val hidden = + setOf( + "buildExternalStorageAndroidDataDirs", "buildExternalStorageAppCacheDirs", "buildExternalStorageAppDataDirs", + "buildExternalStorageAppFilesDirs", "buildExternalStorageAppMediaDirs", "buildPath", "buildPaths", + "getDataCePackageDirectoryForUser", "getDataDePackageDirectoryForUser", "getDataSystemDeviceProtectedDirectory", + "getDataSystemDirectory", "getInternalMediaDirectories", "getLegacyExternalStorageDirectory", "getOdmDirectory", + "getOemDirectory", "getProductDirectory", "getProductServicesDirectory", "getSystemExtDirectory", "getVendorDirectory", + "initForCurrentUser", "maybeTranslateEmulatedPathToInternal", + ) + + private fun signature( + name: String, + types: Array>, + ) = name + types.joinToString(",", "(", ")") { it.name } + + @Test + fun replacementsOfferEverythingTheRealClassDoes() { + val missing = ArrayList() + for ((name, replacement) in GuardPolicy.substitutes) { + if (name in skipped) continue + val real = Class.forName(name) + for (constructor in real.constructors) { + runCatching { replacement.getConstructor(*constructor.parameterTypes) }.onFailure { missing += "$name ${signature("", constructor.parameterTypes)}" } + } + for (method in real.methods) { + if (method.declaringClass == Any::class.java || name == "android.os.Environment" && method.name in hidden) continue + val found = runCatching { replacement.getMethod(method.name, *method.parameterTypes) }.getOrNull() + if (found == null || Modifier.isStatic(found.modifiers) != Modifier.isStatic(method.modifiers)) missing += "$name ${signature(method.name, method.parameterTypes)}" + } + for (field in real.fields) { + runCatching { replacement.getField(field.name) }.onFailure { missing += "$name field ${field.name}" } + } + } + runCatching { GuardPath::class.java.getMethod("of", String::class.java, Array::class.java) }.onFailure { missing += "Path.of(String,String[])" } + runCatching { GuardPath::class.java.getMethod("of", java.net.URI::class.java) }.onFailure { missing += "Path.of(URI)" } + assertEquals(emptyList(), missing, missing.joinToString("\n")) + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/BridgeGuardHost.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/BridgeGuardHost.kt new file mode 100644 index 0000000..cfca997 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/BridgeGuardHost.kt @@ -0,0 +1,164 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import android.os.ParcelFileDescriptor +import com.xfl.msgbot.plugin.api.call.CallException +import com.xfl.msgbot.plugin.api.call.CallResult +import com.xfl.msgbot.plugin.api.engine.HostBridge +import com.xfl.msgbot.plugin.api.value.Value +import com.xfl.msgbot.plugin.api.value.asArrayOrNull +import com.xfl.msgbot.plugin.api.value.asBooleanOrNull +import com.xfl.msgbot.plugin.api.value.asLongOrNull +import com.xfl.msgbot.plugin.api.value.asObjectOrNull +import com.xfl.msgbot.plugin.api.value.asStringOrNull + +/** [GuardHost] over the host's `fs` and `log` modules and [HostBridge.openFile], for an engine's own [HostBridge]. */ +class BridgeGuardHost(private val host: HostBridge) : GuardHost { + // Asked on first use: an engine may not call the host while it loads. + override val root: String by lazy { realpath(".") } + + override fun stat( + path: String, + followLinks: Boolean, + ): GuardHost.Entry? { + val answer = + try { + fs("stat", path, "path" to Value.VString(path), "followLinks" to Value.VBool(followLinks)) + } catch (e: HostIOException) { + if (e.isMissing || e.errno == "ENOTDIR") return null + throw e + } + return answer.asObjectOrNull()?.let(::entry) + } + + override fun list(path: String): List = + fs("list", path, "path" to Value.VString(path)).asArrayOrNull().orEmpty().mapNotNull { it.asObjectOrNull()?.get("name")?.asStringOrNull() } + + override fun access( + path: String, + mode: Int, + ): Boolean = + try { + fs("access", path, "path" to Value.VString(path), "mode" to Value.of(mode)).asBooleanOrNull() == true + } catch (e: HostIOException) { + false + } + + override fun statfs(path: String): GuardHost.Space { + val map = fs("statfs", path, "path" to Value.VString(path)).asObjectOrNull().orEmpty() + fun long(key: String) = map[key]?.asLongOrNull() ?: 0L + return GuardHost.Space(long("bsize"), long("blocks"), long("bfree"), long("bavail")) + } + + override fun mkdir( + path: String, + recursive: Boolean, + ) = fs("mkdir", path, "path" to Value.VString(path), "recursive" to Value.VBool(recursive)).asBooleanOrNull() == true + + override fun remove( + path: String, + recursive: Boolean, + ) = fs("remove", path, "path" to Value.VString(path), "recursive" to Value.VBool(recursive)).asBooleanOrNull() == true + + override fun rename( + from: String, + to: String, + ) { + fs("rename", from, "from" to Value.VString(from), "to" to Value.VString(to)) + } + + override fun symlink( + target: String, + path: String, + ) { + fs("symlink", path, "target" to Value.VString(target), "path" to Value.VString(path)) + } + + override fun link( + existing: String, + path: String, + ) { + fs("link", path, "existing" to Value.VString(existing), "path" to Value.VString(path)) + } + + override fun readlink(path: String): String = fs("readlink", path, "path" to Value.VString(path)).asStringOrNull().orEmpty() + + override fun truncate( + path: String, + size: Long, + ) { + fs("truncate", path, "path" to Value.VString(path), "size" to Value.of(size)) + } + + override fun chmod( + path: String, + mode: Int, + ) { + fs("chmod", path, "path" to Value.VString(path), "mode" to Value.of(mode)) + } + + override fun utimes( + path: String, + accessedMs: Long, + modifiedMs: Long, + ) { + fs("utimes", path, "path" to Value.VString(path), "accessedMs" to Value.of(accessedMs), "modifiedMs" to Value.of(modifiedMs)) + } + + override fun realpath(path: String): String = fs("realpath", path, "path" to Value.VString(path)).asStringOrNull() ?: throw HostIOException("ENOENT", path, path) + + override fun tmpdir(): String = fs("tmpdir", "").asStringOrNull() ?: throw HostIOException("ENOENT", "", "no temporary folder") + + override fun open( + path: String, + mode: Int, + ): ParcelFileDescriptor = + try { + ParcelFileDescriptor.adoptFd(host.openFile(path, mode)) + } catch (e: CallException) { + throw HostIOException.of(path, e.message) + } + + override fun log( + level: String, + message: String, + ) { + try { + host.call("log.write", mapOf("level" to Value.VString(level), "message" to Value.VString(message), "tag" to Value.VString(TAG))) + } catch (_: Exception) { + } + } + + private fun fs( + name: String, + path: String, + vararg args: Pair, + ): Value = + when (val answer = host.call("fs.$name", mapOf(*args))) { + is CallResult.Ok -> answer.value + is CallResult.Err -> throw HostIOException.of(path, answer.message) + } + + private fun entry(map: Map): GuardHost.Entry { + fun long(key: String) = map[key]?.asLongOrNull() ?: 0L + return GuardHost.Entry( + isDirectory = map["isDirectory"]?.asBooleanOrNull() == true, + isSymbolicLink = map["isSymbolicLink"]?.asBooleanOrNull() == true, + size = long("size"), + modifiedMs = long("modifiedMs"), + accessedMs = long("accessedMs"), + createdMs = long("createdMs"), + mode = long("mode").toInt(), + uid = long("uid").toInt(), + gid = long("gid").toInt(), + ) + } + + companion object { + const val TAG = "java" + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/ClassRules.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/ClassRules.kt new file mode 100644 index 0000000..9346f5e --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/ClassRules.kt @@ -0,0 +1,122 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import com.xfl.msgbot.plugin.api.engine.ClassAccess + +/** + * A project's [ClassAccess] as answers about class names. + * + * @param engineInternals name prefixes of the engine itself (its runtime, its own classes). No setting reaches them: + * a script that holds the engine can switch the guard off. + */ +class ClassRules( + val access: ClassAccess, + engineInternals: List = emptyList(), +) { + private val internals = engineInternals + OWN + private val allow = Names(access.allow) + private val deny = Names(access.deny) + + val restricted: Boolean get() = access.restrictions + + /** Whether [className] belongs to the engine itself (its runtime, its own classes). */ + fun isEngineInternal(className: String): Boolean = !className.startsWith(GUARD) && internals.any { className.startsWith(it) } + + /** Whether a script may not look this class up or use an object of it. */ + fun isDenied(className: String): Boolean { + // Objects of the guard's own classes are what scripts are meant to hold; looking them up by name is refused + // separately, in GuardPolicy.lookup. + if (className.startsWith(GUARD)) return false + if (internals.any { className.startsWith(it) }) return true + if (deny.matches(className)) return true + if (!restricted || className in ALWAYS_ALLOWED) return false + if (allows(className)) return false + return DENIED_UNLESS_LISTED.any { className.startsWith(it) } + } + + /** + * Whether a script may not hold an object whose class is [className]. Narrower than [isDenied]: a value of a JDK + * implementation class (a `sun.nio.ch.FileChannelImpl` behind a `FileChannel`, a `sun.nio.cs` charset) is used through + * its public API and is fine, while objects that give a way around the guard are not. + */ + fun isDeniedValue(className: String): Boolean { + if (className.startsWith(GUARD)) return false + if (internals.any { className.startsWith(it) }) return true + if (deny.matches(className)) return true + if (!restricted || allows(className)) return false + return DENIED_VALUES.any { className.startsWith(it) } + } + + /** Whether the project lets the real object of this class reach a script, instead of the guard's stand-in. */ + fun allows(className: String): Boolean { + if (deny.matches(className)) return false + if (!restricted || allow.matches(className)) return true + return access.preset == ClassAccess.Preset.WIDE && className in WIDE + } + + /** Names written as `a.b.C`, `a.b.*` or `a.b*`. */ + private class Names(list: List) { + private val exact = HashSet() + private val prefixes = ArrayList() + + init { + list.flatMap { it.split(',', '\n', ' ', ';') }.map { it.trim() }.filter { it.isNotEmpty() }.forEach { + if (it.endsWith("*")) prefixes += it.dropLast(1) else exact += it + } + } + + fun matches(name: String) = name in exact || prefixes.any { name.startsWith(it) } + } + + companion object { + private val OWN = listOf("com.xfl.msgbot.plugin.") + private const val GUARD = "com.xfl.msgbot.plugin.guard." + + private val ALWAYS_ALLOWED = setOf("java.lang.reflect.Modifier", "java.lang.reflect.Array") + + private val WIDE = + setOf( + "java.lang.reflect.Method", + "java.lang.reflect.Field", + "java.lang.reflect.Constructor", + "java.lang.reflect.Executable", + "java.lang.reflect.AccessibleObject", + "java.lang.Process", + ) + + // Ways around the guard. A project may still list them, at its own risk. + private val DENIED_UNLESS_LISTED = + listOf( + "java.lang.Process", + "java.lang.Compiler", + "java.lang.reflect.", + "java.lang.invoke.", + "java.net.URLClassLoader", + "java.nio.channels.AsynchronousFileChannel", + "java.nio.file.spi.", + "dalvik.", + "libcore.", + "sun.", + "jdk.internal.", + "android.system.", + "android.app.ActivityThread", + ) + + private val DENIED_VALUES = + listOf( + "java.lang.invoke.", + "sun.misc.Unsafe", + "jdk.internal.misc.", + "dalvik.system.", + "libcore.io.", + "android.app.ActivityThread", + ) + + // Last: it needs the lists above. + val DEFAULT = ClassRules(ClassAccess.DEFAULT) + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardEnvironment.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardEnvironment.kt new file mode 100644 index 0000000..ae3d10e --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardEnvironment.kt @@ -0,0 +1,103 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import android.os.Environment +import java.io.File + +/** + * `android.os.Environment` for scripts. Old bot scripts find their folders through it; the folders it names are the + * same, but as [GuardFile]s, so what the scripts do there goes through the host under the project's file rules. + */ +class GuardEnvironment { + companion object { + @JvmField val DIRECTORY_MUSIC: String = Environment.DIRECTORY_MUSIC + + @JvmField val DIRECTORY_PODCASTS: String = Environment.DIRECTORY_PODCASTS + + @JvmField val DIRECTORY_RINGTONES: String = Environment.DIRECTORY_RINGTONES + + @JvmField val DIRECTORY_ALARMS: String = Environment.DIRECTORY_ALARMS + + @JvmField val DIRECTORY_NOTIFICATIONS: String = Environment.DIRECTORY_NOTIFICATIONS + + @JvmField val DIRECTORY_PICTURES: String = Environment.DIRECTORY_PICTURES + + @JvmField val DIRECTORY_MOVIES: String = Environment.DIRECTORY_MOVIES + + @JvmField val DIRECTORY_DOWNLOADS: String = Environment.DIRECTORY_DOWNLOADS + + @JvmField val DIRECTORY_DCIM: String = Environment.DIRECTORY_DCIM + + @JvmField val DIRECTORY_DOCUMENTS: String = Environment.DIRECTORY_DOCUMENTS + + // Literal: the real fields are newer than the oldest Android this runs on, and not constants. + @JvmField val DIRECTORY_AUDIOBOOKS: String = "Audiobooks" + + @JvmField val DIRECTORY_RECORDINGS: String = "Recordings" + + @JvmField val DIRECTORY_SCREENSHOTS: String = "Screenshots" + + @JvmField val MEDIA_UNKNOWN: String = Environment.MEDIA_UNKNOWN + + @JvmField val MEDIA_CHECKING: String = Environment.MEDIA_CHECKING + + @JvmField val MEDIA_NOFS: String = Environment.MEDIA_NOFS + + @JvmField val MEDIA_SHARED: String = Environment.MEDIA_SHARED + + @JvmField val MEDIA_BAD_REMOVAL: String = Environment.MEDIA_BAD_REMOVAL + + @JvmField val MEDIA_UNMOUNTABLE: String = Environment.MEDIA_UNMOUNTABLE + + @JvmField val MEDIA_EJECTING: String = Environment.MEDIA_EJECTING + + @JvmField val MEDIA_MOUNTED: String = Environment.MEDIA_MOUNTED + + @JvmField val MEDIA_MOUNTED_READ_ONLY: String = Environment.MEDIA_MOUNTED_READ_ONLY + + @JvmField val MEDIA_REMOVED: String = Environment.MEDIA_REMOVED + + @JvmField val MEDIA_UNMOUNTED: String = Environment.MEDIA_UNMOUNTED + + private fun guard(file: File): File = GuardFile(file.path) + + @JvmStatic fun getExternalStorageDirectory(): File = guard(@Suppress("DEPRECATION") Environment.getExternalStorageDirectory()) + + @JvmStatic fun getExternalStoragePublicDirectory(type: String): File = guard(@Suppress("DEPRECATION") Environment.getExternalStoragePublicDirectory(type)) + + @JvmStatic fun getRootDirectory(): File = guard(Environment.getRootDirectory()) + + @JvmStatic fun getDataDirectory(): File = guard(Environment.getDataDirectory()) + + @JvmStatic fun getDownloadCacheDirectory(): File = guard(Environment.getDownloadCacheDirectory()) + + @JvmStatic fun getStorageDirectory(): File = guard(Environment.getStorageDirectory()) + + @JvmStatic fun getExternalStorageState(): String = Environment.MEDIA_MOUNTED + + @JvmStatic fun getExternalStorageState(path: File): String = Environment.MEDIA_MOUNTED + + @JvmStatic fun getStorageState(path: File): String = Environment.MEDIA_MOUNTED + + @JvmStatic fun isExternalStorageEmulated(): Boolean = Environment.isExternalStorageEmulated() + + @JvmStatic fun isExternalStorageEmulated(path: File): Boolean = Environment.isExternalStorageEmulated(path) + + @JvmStatic fun isExternalStorageRemovable(path: File): Boolean = Environment.isExternalStorageRemovable(path) + + @JvmStatic fun isExternalStorageManager(path: File): Boolean = true + + @JvmStatic fun isExternalStorageLegacy(path: File): Boolean = false + + @JvmStatic fun isExternalStorageRemovable(): Boolean = Environment.isExternalStorageRemovable() + + /** True: what a script may do with files is decided by the host, which holds that permission. */ + @JvmStatic fun isExternalStorageManager(): Boolean = true + + @JvmStatic fun isExternalStorageLegacy(): Boolean = false + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardErrors.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardErrors.kt new file mode 100644 index 0000000..b7e96cb --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardErrors.kt @@ -0,0 +1,71 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import android.system.Os +import android.system.OsConstants +import java.io.FileNotFoundException +import java.io.IOException +import java.nio.file.AccessDeniedException +import java.nio.file.DirectoryNotEmptyException +import java.nio.file.FileAlreadyExistsException +import java.nio.file.FileSystemException +import java.nio.file.NoSuchFileException +import java.nio.file.NotDirectoryException +import java.nio.file.NotLinkException + +/** Turns host refusals into the exceptions the real classes throw on Android, with the same messages. */ +internal object GuardErrors { + private fun reason(errno: String): String = + try { + Os.strerror(OsConstants::class.java.getField(errno).getInt(null)) + } catch (_: ReflectiveOperationException) { + errno + } + + /** What `java.io` streams throw: `path: open failed: ENOENT (No such file or directory)`. */ + fun open(e: HostIOException): FileNotFoundException { + report(e) + return FileNotFoundException("${e.path}: open failed: ${e.errno} (${reason(e.errno)})").apply { initCause(e) } + } + + /** What `java.io` throws elsewhere (`createNewFile`, `RandomAccessFile`): an [IOException] with the system's message. */ + fun io(e: HostIOException): IOException { + report(e) + return IOException(reason(e.errno), e) + } + + /** What `java.nio.file` throws for the same failure. */ + fun nio( + e: HostIOException, + other: String? = null, + ): FileSystemException { + report(e) + val path = e.path + return when (e.errno) { + "ENOENT" -> NoSuchFileException(path, other, null) + "EACCES", "EPERM" -> AccessDeniedException(path, other, null) + "EEXIST" -> FileAlreadyExistsException(path, other, null) + "ENOTEMPTY" -> DirectoryNotEmptyException(path) + "ENOTDIR" -> NotDirectoryException(path) + "EINVAL" -> NotLinkException(path, other, null) + else -> FileSystemException(path, other, reason(e.errno)) + }.apply { initCause(e) } + } + + /** + * What a `java.io.File` method that answers yes or no does when the rules forbid the path: the same + * [SecurityException] a Java security manager throws there, instead of an answer that looks like "no". + */ + fun denied(e: HostIOException): SecurityException { + report(e) + return SecurityException("${e.path}: not available to this project (${e.errno})", e) + } + + private fun report(e: HostIOException) { + if (e.isDenied) GuardContext.reportPath(e.path) + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFd.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFd.kt new file mode 100644 index 0000000..d3a2dc3 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFd.kt @@ -0,0 +1,128 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import android.os.ParcelFileDescriptor +import android.system.Os +import com.xfl.msgbot.plugin.api.engine.HostFileMode +import java.io.File +import java.io.FileDescriptor +import java.io.FileNotFoundException +import java.io.RandomAccessFile +import java.lang.reflect.Method + +/** + * Puts a host descriptor under a descriptor number that a real JDK object already owns, so the object (a + * `RandomAccessFile` and the `FileChannel` it hands out) works on the host's file with all of its own code. + * + * The real class can only be made by opening a path, so it first opens a placeholder this process may open, and the + * host's descriptor is then copied over the placeholder's number with `dup2`. + */ +internal object Descriptors { + // Unsupported but allowed hidden API; when a later Android refuses it, a pipe marks the placeholder instead. + private val getInt: Method? = runCatching { FileDescriptor::class.java.getMethod("getInt" + '$') }.getOrNull() + + /** False makes the pipe marker run even where the hidden API works; only tests set it. */ + @Volatile internal var useHiddenApi = true + + private val marker = ThreadLocal?>() + + fun placeholder(): String { + if (getInt != null && useHiddenApi) return "/dev/null" + val pipe = ParcelFileDescriptor.createPipe() + marker.set(pipe) + return "/proc/self/fd/${pipe[0].fd}" + } + + /** Makes [target] refer to [source]'s file and closes [source]. */ + fun retarget( + target: FileDescriptor, + source: ParcelFileDescriptor, + ) { + source.use { Os.dup2(it.fileDescriptor, number(target)) } + } + + fun abandon() { + marker.get()?.forEach { it.close() } + marker.remove() + } + + private fun number(target: FileDescriptor): Int { + if (useHiddenApi) getInt?.let { method -> runCatching { return method.invoke(target) as Int } } + val pipe = marker.get() ?: throw IllegalStateException("No placeholder is waiting on this thread") + try { + val link = Os.readlink("/proc/self/fd/${pipe[0].fd}") + val own = setOf(pipe[0].fd, pipe[1].fd) + return File("/proc/self/fd").list().orEmpty().mapNotNull { it.toIntOrNull() }.filter { it !in own }.single { number -> + runCatching { Os.readlink("/proc/self/fd/$number") }.getOrNull() == link + } + } finally { + abandon() + } + } +} + +/** + * `java.io.RandomAccessFile` for scripts: the real class, working on a descriptor the host opened under the + * project's file rules. [getChannel] is a real `FileChannel`, so mapping and locking work too. + * + * Modes `rws` and `rwd` do not make each write synchronous; call `getFD().sync()` where that matters. + */ +class GuardRandomAccessFile private constructor( + source: ParcelFileDescriptor, + mode: String, +) : RandomAccessFile(Descriptors.placeholder(), mode) { + init { + try { + Descriptors.retarget(fd, source) + } catch (e: Throwable) { + Descriptors.abandon() + source.close() + close() + throw e + } + } + + @Throws(FileNotFoundException::class) + constructor(path: String, mode: String) : this(openFor(path, checkMode(mode)), mode) + + @Throws(FileNotFoundException::class) + constructor(file: File, mode: String) : this(file.path, mode) + + internal constructor(descriptor: ParcelFileDescriptor) : this(descriptor, "rw") + + companion object { + private fun checkMode(mode: String): String { + require(mode == "r" || mode == "rw" || mode == "rws" || mode == "rwd") { + "Illegal mode \"$mode\" must be one of \"r\", \"rw\", \"rws\", or \"rwd\"" + } + return mode + } + + private fun openFor( + path: String, + mode: String, + ): ParcelFileDescriptor { + val host = GuardContext.host() + try { + if (mode == "r") return host.open(path, HostFileMode.READ) + return try { + host.open(path, HostFileMode.READ_WRITE) + } catch (e: HostIOException) { + if (!e.isMissing) throw e + try { + host.open(path, HostFileMode.WRITE or HostFileMode.READ_WRITE or HostFileMode.EXCLUSIVE) + } catch (raced: HostIOException) { + if (raced.errno != "EEXIST") throw raced + host.open(path, HostFileMode.READ_WRITE) + } + } + } catch (e: HostIOException) { + throw GuardErrors.open(e) + } + } + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFile.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFile.kt new file mode 100644 index 0000000..8d89d57 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFile.kt @@ -0,0 +1,204 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import com.xfl.msgbot.plugin.api.engine.HostFileMode +import java.io.File +import java.io.FileFilter +import java.io.FilenameFilter +import java.io.IOException +import java.net.URI +import java.nio.file.Path +import java.security.SecureRandom + +/** + * `java.io.File` for scripts. It is a real `File`, so it can be passed wherever a `File` is taken and compares equal to + * one with the same path, but every question about the disk goes to the host and is answered under the project's file + * rules. Relative paths are relative to the project folder. + * + * A path the rules forbid makes the methods that answer yes or no throw [SecurityException], as under a Java security + * manager; `canRead`, `canWrite` and `canExecute` answer false instead. + */ +class GuardFile : GuardFileBase { + @Transient private val session: GuardSession = GuardContext.current() + + private val host: GuardHost get() = session.host + + constructor(path: String) : super(path) + + constructor(parent: String?, child: String) : super(parent, child) + + constructor(parent: File?, child: String) : super(parent, child) + + constructor(uri: URI) : super(uri) + + private inline fun ask( + orElse: T, + block: () -> T, + ): T = + try { + block() + } catch (e: HostIOException) { + if (e.isDenied) throw GuardErrors.denied(e) + orElse + } + + private fun stat(): GuardHost.Entry? = ask(null) { host.stat(path) } + + private fun permissions(): Int = stat()?.mode?.and(0x1ff) ?: throw GuardErrors.denied(HostIOException("ENOENT", path, path)) + + private fun chmod(bits: Int): Boolean = ask(false) { + host.chmod(path, bits) + true + } + + override fun exists() = stat() != null + + override fun isFile() = stat()?.isRegularFile == true + + override fun isDirectory() = stat()?.isDirectory == true + + override fun isHidden() = name.startsWith(".") + + override fun canRead() = host.access(path, 4) + + override fun canWrite() = host.access(path, 2) + + override fun canExecute() = host.access(path, 1) + + override fun length() = stat()?.size ?: 0L + + override fun lastModified() = stat()?.modifiedMs ?: 0L + + override fun list(): Array? = ask(null) { host.list(path).toTypedArray() } + + override fun list(filter: FilenameFilter?): Array? = list()?.filter { filter == null || filter.accept(this, it) }?.toTypedArray() + + override fun listFiles(): Array? = list()?.map { GuardFile(this, it) }?.toTypedArray() + + override fun listFiles(filter: FilenameFilter?): Array? = list(filter)?.map { GuardFile(this, it) }?.toTypedArray() + + override fun listFiles(filter: FileFilter?): Array? = listFiles()?.filter { filter == null || filter.accept(it) }?.toTypedArray() + + override fun mkdir() = ask(false) { host.mkdir(path, false) } + + override fun mkdirs() = ask(false) { host.mkdir(path, true) } + + override fun createNewFile(): Boolean { + try { + host.open(path, HostFileMode.WRITE or HostFileMode.EXCLUSIVE).close() + return true + } catch (e: HostIOException) { + if (e.errno == "EEXIST") return false + throw GuardErrors.io(e) + } + } + + override fun delete() = ask(false) { host.remove(path, false) } + + override fun deleteOnExit() = session.deleteOnExit(absolutePath) + + override fun renameTo(dest: File) = ask(false) { + host.rename(path, dest.path) + true + } + + override fun getParentFile(): File? = parent?.let { GuardFile(it) } + + override fun getAbsolutePath(): String = if (isAbsolute) path else host.root.trimEnd('/') + "/" + path + + override fun getAbsoluteFile(): File = GuardFile(absolutePath) + + override fun getCanonicalPath(): String = canonical(absolutePath) + + override fun getCanonicalFile(): File = GuardFile(canonicalPath) + + // Like java.io: links are followed as far as something exists, the rest of the path is only cleaned up. + private fun canonical(absolute: String): String { + val clean = normalize(absolute) + if (clean == "/") return clean + return try { + host.realpath(clean) + } catch (e: HostIOException) { + if (e.isDenied) throw GuardErrors.denied(e) + val cut = clean.lastIndexOf('/') + canonical(clean.substring(0, cut).ifEmpty { "/" }).trimEnd('/') + clean.substring(cut) + } + } + + override fun toPath(): Path = GuardPath(host, path) + + override fun setLastModified(time: Long): Boolean { + require(time >= 0) { "Negative time" } + val entry = stat() ?: return false + return ask(false) { + host.utimes(path, entry.accessedMs, time) + true + } + } + + override fun setReadOnly() = exists() && chmod(permissions() and 0x92.inv()) + + override fun setWritable( + writable: Boolean, + ownerOnly: Boolean, + ) = exists() && chmod(bits(permissions(), if (ownerOnly) 0x80 else 0x92, writable)) + + override fun setReadable( + readable: Boolean, + ownerOnly: Boolean, + ) = exists() && chmod(bits(permissions(), if (ownerOnly) 0x100 else 0x124, readable)) + + override fun setExecutable( + executable: Boolean, + ownerOnly: Boolean, + ) = exists() && chmod(bits(permissions(), if (ownerOnly) 0x40 else 0x49, executable)) + + private fun bits( + mode: Int, + mask: Int, + on: Boolean, + ) = if (on) mode or mask else mode and mask.inv() + + private fun space(pick: (GuardHost.Space) -> Long): Long = ask(0L) { host.statfs(path).let { pick(it) * it.blockSize } } + + override fun getTotalSpace() = space { it.blocks } + + override fun getFreeSpace() = space { it.free } + + override fun getUsableSpace() = space { it.available } + + companion object { + internal fun normalize(path: String): String { + val kept = ArrayList() + for (name in path.split('/')) { + when (name) { + "", "." -> Unit + ".." -> if (kept.isNotEmpty()) kept.removeAt(kept.size - 1) + else -> kept += name + } + } + return "/" + kept.joinToString("/") + } + } +} + +internal object TempFiles { + private val random = SecureRandom() + + fun create( + prefix: String, + suffix: String?, + directory: File?, + ): File { + require(prefix.length >= 3) { "Prefix string \"$prefix\" too short: length must be at least 3" } + val folder = directory?.path ?: GuardContext.host().tmpdir() + while (true) { + val file = GuardFile(folder, prefix + java.lang.Long.toUnsignedString(random.nextLong()) + (suffix ?: ".tmp")) + if (file.createNewFile()) return file + } + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFileBase.java b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFileBase.java new file mode 100644 index 0000000..38a3bc0 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFileBase.java @@ -0,0 +1,47 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard; + +import java.io.File; +import java.io.IOException; +import java.net.URI; + +/** + * The static methods of {@link GuardFile}. They hide those of {@code java.io.File}, which Kotlin cannot do, so a + * script that calls {@code File.createTempFile} on the guard's {@code File} makes the file through the host. + */ +public abstract class GuardFileBase extends File { + GuardFileBase(String path) { + super(path); + } + + GuardFileBase(String parent, String child) { + super(parent, child); + } + + GuardFileBase(File parent, String child) { + super(parent, child); + } + + GuardFileBase(URI uri) { + super(uri); + } + + /** One root, {@code /}. */ + public static File[] listRoots() { + return new File[] {new GuardFile("/")}; + } + + /** Like {@code File.createTempFile}, in the host's temporary folder. */ + public static File createTempFile(String prefix, String suffix) throws IOException { + return TempFiles.INSTANCE.create(prefix, suffix, null); + } + + /** Like {@code File.createTempFile}; in the host's temporary folder when {@code directory} is null. */ + public static File createTempFile(String prefix, String suffix, File directory) throws IOException { + return TempFiles.INSTANCE.create(prefix, suffix, directory); + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFiles.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFiles.kt new file mode 100644 index 0000000..9a77632 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardFiles.kt @@ -0,0 +1,186 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import java.io.BufferedReader +import java.io.BufferedWriter +import java.io.InputStream +import java.io.OutputStream +import java.nio.channels.SeekableByteChannel +import java.nio.charset.Charset +import java.nio.file.CopyOption +import java.nio.file.DirectoryStream +import java.nio.file.FileStore +import java.nio.file.FileVisitOption +import java.nio.file.FileVisitor +import java.nio.file.Files +import java.nio.file.LinkOption +import java.nio.file.OpenOption +import java.nio.file.Path +import java.nio.file.attribute.BasicFileAttributes +import java.nio.file.attribute.FileAttribute +import java.nio.file.attribute.FileAttributeView +import java.nio.file.attribute.FileTime +import java.nio.file.attribute.PosixFilePermission +import java.nio.file.attribute.UserPrincipal +import java.util.function.BiPredicate +import java.util.stream.Stream + +/** + * `java.nio.file.Files` for scripts. Every call is the real one, which works on a [GuardPath] through the host; only + * the temporary files and folders made without a folder go to the host's temporary folder instead of this app's. + * A path that is not a [GuardPath] (a real path from another API) is taken as the same path of the project. + */ +class GuardFiles private constructor() { + @Suppress("TooManyFunctions") + companion object { + private fun p(path: Path): Path = path as? GuardPath ?: GuardPath(GuardContext.host(), path.toString()) + + private fun tmp(): Path = GuardPath(GuardContext.host(), GuardContext.host().tmpdir()) + + @JvmStatic fun newInputStream(path: Path, vararg options: OpenOption): InputStream = Files.newInputStream(p(path), *options) + + @JvmStatic fun newOutputStream(path: Path, vararg options: OpenOption): OutputStream = Files.newOutputStream(p(path), *options) + + @JvmStatic fun newByteChannel(path: Path, options: Set, vararg attrs: FileAttribute<*>): SeekableByteChannel = Files.newByteChannel(p(path), options, *attrs) + + @JvmStatic fun newByteChannel(path: Path, vararg options: OpenOption): SeekableByteChannel = Files.newByteChannel(p(path), *options) + + @JvmStatic fun newDirectoryStream(dir: Path): DirectoryStream = Files.newDirectoryStream(p(dir)) + + @JvmStatic fun newDirectoryStream(dir: Path, glob: String): DirectoryStream = Files.newDirectoryStream(p(dir), glob) + + @JvmStatic fun newDirectoryStream(dir: Path, filter: DirectoryStream.Filter): DirectoryStream = Files.newDirectoryStream(p(dir), filter) + + @JvmStatic fun createFile(path: Path, vararg attrs: FileAttribute<*>): Path = Files.createFile(p(path), *attrs) + + @JvmStatic fun createDirectory(dir: Path, vararg attrs: FileAttribute<*>): Path = Files.createDirectory(p(dir), *attrs) + + @JvmStatic fun createDirectories(dir: Path, vararg attrs: FileAttribute<*>): Path = Files.createDirectories(p(dir).toAbsolutePath(), *attrs) + + @JvmStatic fun createTempFile(dir: Path, prefix: String?, suffix: String?, vararg attrs: FileAttribute<*>): Path = Files.createTempFile(p(dir), prefix, suffix, *attrs) + + @JvmStatic fun createTempFile(prefix: String?, suffix: String?, vararg attrs: FileAttribute<*>): Path = Files.createTempFile(tmp(), prefix, suffix, *attrs) + + @JvmStatic fun createTempDirectory(dir: Path, prefix: String?, vararg attrs: FileAttribute<*>): Path = Files.createTempDirectory(p(dir), prefix, *attrs) + + @JvmStatic fun createTempDirectory(prefix: String?, vararg attrs: FileAttribute<*>): Path = Files.createTempDirectory(tmp(), prefix, *attrs) + + @JvmStatic fun createSymbolicLink(link: Path, target: Path, vararg attrs: FileAttribute<*>): Path = Files.createSymbolicLink(p(link), p(target), *attrs) + + @JvmStatic fun createLink(link: Path, existing: Path): Path = Files.createLink(p(link), p(existing)) + + @JvmStatic fun delete(path: Path) = Files.delete(p(path)) + + @JvmStatic fun deleteIfExists(path: Path): Boolean = Files.deleteIfExists(p(path)) + + @JvmStatic fun copy(source: Path, target: Path, vararg options: CopyOption): Path = Files.copy(p(source), p(target), *options) + + @JvmStatic fun copy(input: InputStream, target: Path, vararg options: CopyOption): Long = Files.copy(input, p(target), *options) + + @JvmStatic fun copy(source: Path, out: OutputStream): Long = Files.copy(p(source), out) + + @JvmStatic fun move(source: Path, target: Path, vararg options: CopyOption): Path = Files.move(p(source), p(target), *options) + + @JvmStatic fun readSymbolicLink(link: Path): Path = Files.readSymbolicLink(p(link)) + + @JvmStatic fun getFileStore(path: Path): FileStore = Files.getFileStore(p(path)) + + @JvmStatic fun isSameFile(path: Path, path2: Path): Boolean = Files.isSameFile(p(path), p(path2)) + + @JvmStatic fun isHidden(path: Path): Boolean = Files.isHidden(p(path)) + + @JvmStatic fun probeContentType(path: Path): String? = Files.probeContentType(p(path)) + + @JvmStatic fun getFileAttributeView(path: Path, type: Class, vararg options: LinkOption): V? = Files.getFileAttributeView(p(path), type, *options) + + @JvmStatic fun readAttributes(path: Path, type: Class, vararg options: LinkOption): A = Files.readAttributes(p(path), type, *options) + + @JvmStatic fun setAttribute(path: Path, attribute: String, value: Any?, vararg options: LinkOption): Path = Files.setAttribute(p(path), attribute, value, *options) + + @JvmStatic fun getAttribute(path: Path, attribute: String, vararg options: LinkOption): Any? = Files.getAttribute(p(path), attribute, *options) + + @JvmStatic fun readAttributes(path: Path, attributes: String, vararg options: LinkOption): Map = Files.readAttributes(p(path), attributes, *options) + + @JvmStatic fun getPosixFilePermissions(path: Path, vararg options: LinkOption): Set = Files.getPosixFilePermissions(p(path), *options) + + @JvmStatic fun setPosixFilePermissions(path: Path, perms: Set): Path = Files.setPosixFilePermissions(p(path), perms) + + @JvmStatic fun getOwner(path: Path, vararg options: LinkOption): UserPrincipal = Files.getOwner(p(path), *options) + + @JvmStatic fun setOwner(path: Path, owner: UserPrincipal): Path = Files.setOwner(p(path), owner) + + @JvmStatic fun isSymbolicLink(path: Path): Boolean = Files.isSymbolicLink(p(path)) + + @JvmStatic fun isDirectory(path: Path, vararg options: LinkOption): Boolean = Files.isDirectory(p(path), *options) + + @JvmStatic fun isRegularFile(path: Path, vararg options: LinkOption): Boolean = Files.isRegularFile(p(path), *options) + + @JvmStatic fun getLastModifiedTime(path: Path, vararg options: LinkOption): FileTime = Files.getLastModifiedTime(p(path), *options) + + @JvmStatic fun setLastModifiedTime(path: Path, time: FileTime): Path = Files.setLastModifiedTime(p(path), time) + + @JvmStatic fun size(path: Path): Long = Files.size(p(path)) + + @JvmStatic fun exists(path: Path, vararg options: LinkOption): Boolean = Files.exists(p(path), *options) + + @JvmStatic fun notExists(path: Path, vararg options: LinkOption): Boolean = Files.notExists(p(path), *options) + + @JvmStatic fun isReadable(path: Path): Boolean = Files.isReadable(p(path)) + + @JvmStatic fun isWritable(path: Path): Boolean = Files.isWritable(p(path)) + + @JvmStatic fun isExecutable(path: Path): Boolean = Files.isExecutable(p(path)) + + @JvmStatic fun walkFileTree(start: Path, options: Set, maxDepth: Int, visitor: FileVisitor): Path = Files.walkFileTree(p(start), options, maxDepth, visitor) + + @JvmStatic fun walkFileTree(start: Path, visitor: FileVisitor): Path = Files.walkFileTree(p(start), visitor) + + @JvmStatic fun newBufferedReader(path: Path, cs: Charset): BufferedReader = Files.newBufferedReader(p(path), cs) + + @JvmStatic fun newBufferedReader(path: Path): BufferedReader = Files.newBufferedReader(p(path)) + + @JvmStatic fun newBufferedWriter(path: Path, cs: Charset, vararg options: OpenOption): BufferedWriter = Files.newBufferedWriter(p(path), cs, *options) + + @JvmStatic fun newBufferedWriter(path: Path, vararg options: OpenOption): BufferedWriter = Files.newBufferedWriter(p(path), *options) + + @JvmStatic fun readAllBytes(path: Path): ByteArray = Files.readAllBytes(p(path)) + + // Present at run time but missing from the SDK stubs, so written out instead of delegated. + @JvmStatic fun readString(path: Path): String = readString(path, Charsets.UTF_8) + + @JvmStatic fun readString(path: Path, cs: Charset): String = cs.newDecoder().decode(java.nio.ByteBuffer.wrap(Files.readAllBytes(p(path)))).toString() + + @JvmStatic fun writeString(path: Path, csq: CharSequence, vararg options: OpenOption): Path = writeString(path, csq, Charsets.UTF_8, *options) + + @JvmStatic fun writeString(path: Path, csq: CharSequence, cs: Charset, vararg options: OpenOption): Path { + val bytes = cs.newEncoder().encode(java.nio.CharBuffer.wrap(csq)) + return Files.write(p(path), ByteArray(bytes.remaining()).also { bytes.get(it) }, *options) + } + + @JvmStatic fun readAllLines(path: Path, cs: Charset): List = Files.readAllLines(p(path), cs) + + @JvmStatic fun readAllLines(path: Path): List = Files.readAllLines(p(path)) + + @JvmStatic fun write(path: Path, bytes: ByteArray, vararg options: OpenOption): Path = Files.write(p(path), bytes, *options) + + @JvmStatic fun write(path: Path, lines: Iterable, cs: Charset, vararg options: OpenOption): Path = Files.write(p(path), lines, cs, *options) + + @JvmStatic fun write(path: Path, lines: Iterable, vararg options: OpenOption): Path = Files.write(p(path), lines, *options) + + @JvmStatic fun list(dir: Path): Stream = Files.list(p(dir)) + + @JvmStatic fun walk(start: Path, maxDepth: Int, vararg options: FileVisitOption): Stream = Files.walk(p(start), maxDepth, *options) + + @JvmStatic fun walk(start: Path, vararg options: FileVisitOption): Stream = Files.walk(p(start), *options) + + @JvmStatic fun find(start: Path, maxDepth: Int, matcher: BiPredicate, vararg options: FileVisitOption): Stream = Files.find(p(start), maxDepth, matcher, *options) + + @JvmStatic fun lines(path: Path, cs: Charset): Stream = Files.lines(p(path), cs) + + @JvmStatic fun lines(path: Path): Stream = Files.lines(p(path)) + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardHost.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardHost.kt new file mode 100644 index 0000000..3e9d0e5 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardHost.kt @@ -0,0 +1,145 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import android.os.ParcelFileDescriptor +import java.io.IOException + +/** + * The files a script may reach, as the host decides. Every answer comes from the project's file rules, never from the + * disk of this process, which the plugin cannot read anyway. + * + * Paths are absolute or relative to the project folder. A call the host refuses throws [HostIOException] with the POSIX + * error name the host gave (`EACCES` for a place outside the rules). + */ +interface GuardHost { + class Entry( + val isDirectory: Boolean, + val isSymbolicLink: Boolean, + val size: Long, + val modifiedMs: Long, + val accessedMs: Long, + val createdMs: Long, + val mode: Int, + val uid: Int, + val gid: Int, + ) { + // The host reports permission bits only, so devices and pipes count as regular files. + val isRegularFile: Boolean get() = !isDirectory && !isSymbolicLink + } + + class Space( + val blockSize: Long, + val blocks: Long, + val free: Long, + val available: Long, + ) + + /** Absolute path of the project folder. */ + val root: String + + /** Null when nothing is there. */ + fun stat( + path: String, + followLinks: Boolean = true, + ): Entry? + + fun list(path: String): List + + /** Whether the path may be used as [mode] asks (`R_OK` 4, `W_OK` 2, `X_OK` 1); false instead of `EACCES`/`ENOENT`. */ + fun access( + path: String, + mode: Int, + ): Boolean + + fun statfs(path: String): Space + + /** False when a folder is already there. */ + fun mkdir( + path: String, + recursive: Boolean, + ): Boolean + + /** False when nothing was there. */ + fun remove( + path: String, + recursive: Boolean, + ): Boolean + + fun rename( + from: String, + to: String, + ) + + fun symlink( + target: String, + path: String, + ) + + fun link( + existing: String, + path: String, + ) + + fun readlink(path: String): String + + fun truncate( + path: String, + size: Long, + ) + + fun chmod( + path: String, + mode: Int, + ) + + fun utimes( + path: String, + accessedMs: Long, + modifiedMs: Long, + ) + + fun realpath(path: String): String + + /** The shared temporary folder; whether the script may use it is up to its file rules. */ + fun tmpdir(): String + + /** Opens [path] as a [com.xfl.msgbot.plugin.api.engine.HostFileMode]; the caller owns the descriptor. */ + fun open( + path: String, + mode: Int, + ): ParcelFileDescriptor + + /** Writes a line to the project log. Never throws. */ + fun log( + level: String, + message: String, + ) +} + +/** A refusal or failure from the host. [errno] is the POSIX name (`ENOENT`, `EACCES`, ...), or `EIO` when the host gave none. */ +class HostIOException( + val errno: String, + val path: String, + val detail: String, +) : IOException("$errno: $detail") { + val isDenied: Boolean get() = errno == "EACCES" || errno == "EPERM" + + val isMissing: Boolean get() = errno == "ENOENT" + + companion object { + private val NAME = Regex("^(E[A-Z0-9]+)\\b") + + fun of( + path: String, + message: String?, + ): HostIOException { + val text = message.orEmpty() + val errno = NAME.find(text)?.groupValues?.get(1) ?: "EIO" + return HostIOException(errno, path, text.removePrefix(errno).trimStart(':', ' ').ifEmpty { errno }) + } + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardNio.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardNio.kt new file mode 100644 index 0000000..ebbab19 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardNio.kt @@ -0,0 +1,800 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import com.xfl.msgbot.plugin.api.engine.HostFileMode +import java.io.File +import java.io.IOException +import java.net.URI +import java.nio.channels.FileChannel +import java.nio.channels.SeekableByteChannel +import java.nio.file.AccessDeniedException +import java.nio.file.AccessMode +import java.nio.file.CopyOption +import java.nio.file.DirectoryNotEmptyException +import java.nio.file.DirectoryStream +import java.nio.file.FileAlreadyExistsException +import java.nio.file.FileStore +import java.nio.file.FileSystem +import java.nio.file.FileSystemNotFoundException +import java.nio.file.LinkOption +import java.nio.file.NoSuchFileException +import java.nio.file.OpenOption +import java.nio.file.Path +import java.nio.file.PathMatcher +import java.nio.file.ProviderMismatchException +import java.nio.file.StandardCopyOption +import java.nio.file.StandardOpenOption +import java.nio.file.WatchEvent +import java.nio.file.WatchKey +import java.nio.file.WatchService +import java.nio.file.attribute.BasicFileAttributeView +import java.nio.file.attribute.BasicFileAttributes +import java.nio.file.attribute.FileAttribute +import java.nio.file.attribute.FileAttributeView +import java.nio.file.attribute.FileOwnerAttributeView +import java.nio.file.attribute.FileStoreAttributeView +import java.nio.file.attribute.FileTime +import java.nio.file.attribute.GroupPrincipal +import java.nio.file.attribute.PosixFileAttributeView +import java.nio.file.attribute.PosixFileAttributes +import java.nio.file.attribute.PosixFilePermission +import java.nio.file.attribute.UserPrincipal +import java.nio.file.attribute.UserPrincipalLookupService +import java.nio.file.spi.FileSystemProvider +import java.util.regex.Pattern + +/** + * `java.nio.file.Path` for scripts. The real `java.nio.file.Files` works with it unchanged: it asks the path's + * provider, which is [GuardProvider], so every operation goes to the host under the project's file rules. + * Relative paths are relative to the project folder. + */ +class GuardPath internal constructor( + internal val host: GuardHost, + text: String, +) : Path { + private val text: String = clean(text) + private val names: List = if (this.text.isEmpty()) listOf("") else this.text.split('/').filter { it.isNotEmpty() } + + override fun getFileSystem(): FileSystem = GuardFileSystem + + override fun isAbsolute() = text.startsWith("/") + + override fun getRoot(): Path? = if (isAbsolute) GuardPath(host, "/") else null + + override fun getFileName(): Path? = if (text == "/") null else GuardPath(host, names.last()) + + override fun getParent(): Path? { + val cut = text.lastIndexOf('/') + return when { + text == "/" || cut < 0 -> null + cut == 0 -> GuardPath(host, "/") + else -> GuardPath(host, text.substring(0, cut)) + } + } + + override fun getNameCount() = if (text == "/") 0 else names.size + + override fun getName(index: Int): Path = GuardPath(host, names.getOrNull(index) ?: throw IllegalArgumentException()) + + override fun subpath( + beginIndex: Int, + endIndex: Int, + ): Path { + if (beginIndex < 0 || beginIndex >= nameCount || endIndex > nameCount || beginIndex >= endIndex) throw IllegalArgumentException() + return GuardPath(host, names.subList(beginIndex, endIndex).joinToString("/")) + } + + private fun other(path: Path): GuardPath = path as? GuardPath ?: throw ProviderMismatchException() + + override fun startsWith(other: Path): Boolean { + val o = other as? GuardPath ?: return false + if (o.isAbsolute != isAbsolute) return false + if (o.text == "/") return isAbsolute + if (o.text.isEmpty()) return text.isEmpty() + return o.names.size <= names.size && names.subList(0, o.names.size) == o.names + } + + override fun endsWith(other: Path): Boolean { + val o = other as? GuardPath ?: return false + if (o.isAbsolute) return o.text == text + if (o.text.isEmpty()) return text.isEmpty() + return o.names.size <= names.size && names.subList(names.size - o.names.size, names.size) == o.names + } + + override fun normalize(): Path { + val kept = ArrayList() + for (name in names) { + when { + name == "." || name.isEmpty() -> Unit + name == ".." && kept.isNotEmpty() && kept.last() != ".." -> kept.removeAt(kept.size - 1) + name == ".." && isAbsolute -> Unit + else -> kept.add(name) + } + } + return GuardPath(host, (if (isAbsolute) "/" else "") + kept.joinToString("/")) + } + + override fun resolve(other: Path): Path { + val o = other(other) + return when { + o.isAbsolute -> o + o.text.isEmpty() -> this + text.isEmpty() -> o + else -> GuardPath(host, "$text/${o.text}") + } + } + + override fun relativize(other: Path): Path { + val o = other(other) + if (o.isAbsolute != isAbsolute) throw IllegalArgumentException("'other' is different type of Path") + if (o.text == text) return GuardPath(host, "") + var common = 0 + val mine = if (text.isEmpty()) emptyList() else names + val theirs = if (o.text.isEmpty()) emptyList() else o.names + while (common < mine.size && common < theirs.size && mine[common] == theirs[common]) common++ + val up = List(mine.size - common) { ".." } + return GuardPath(host, (up + theirs.drop(common)).joinToString("/")) + } + + override fun toUri(): URI { + val absolute = toAbsolutePath().toString() + val directory = !absolute.endsWith("/") && runCatching { host.stat(absolute)?.isDirectory == true }.getOrDefault(false) + return URI("file", "", if (directory) "$absolute/" else absolute, null) + } + + override fun toAbsolutePath(): Path = if (isAbsolute) this else GuardPath(host, host.root.trimEnd('/') + "/" + text) + + override fun toRealPath(vararg options: LinkOption): Path { + val absolute = toAbsolutePath().toString() + try { + if (LinkOption.NOFOLLOW_LINKS in options) { + host.stat(absolute, false) ?: throw NoSuchFileException(text) + return toAbsolutePath().normalize() + } + return GuardPath(host, host.realpath(absolute)) + } catch (e: HostIOException) { + throw GuardErrors.nio(HostIOException(e.errno, text, e.detail)) + } + } + + override fun toFile(): File = GuardFile(text) + + override fun register( + watcher: WatchService, + events: Array>, + vararg modifiers: WatchEvent.Modifier, + ): WatchKey = throw UnsupportedOperationException("Watching folders is not available to scripts") + + override fun register( + watcher: WatchService, + vararg events: WatchEvent.Kind<*>, + ): WatchKey = throw UnsupportedOperationException("Watching folders is not available to scripts") + + override fun startsWith(other: String) = startsWith(GuardPath(host, other)) + + override fun endsWith(other: String) = endsWith(GuardPath(host, other)) + + override fun resolve(other: String): Path = resolve(GuardPath(host, other)) + + override fun resolveSibling(other: Path): Path = parent?.resolve(other) ?: other + + override fun resolveSibling(other: String): Path = resolveSibling(GuardPath(host, other)) + + override fun iterator(): MutableIterator = List(nameCount) { getName(it) }.toMutableList().iterator() + + override fun compareTo(other: Path): Int = text.compareTo((other as GuardPath).text) + + override fun equals(other: Any?) = other is GuardPath && other.text == text + + override fun hashCode() = text.hashCode() + + override fun toString() = text + + companion object { + private fun clean(raw: String): String { + if (raw.indexOf('\u0000') >= 0) throw java.nio.file.InvalidPathException(raw, "Nul character not allowed") + val joined = raw.replace(Regex("/+"), "/") + return if (joined.length > 1) joined.trimEnd('/') else joined + } + + /** `Path.of(first, more...)`. */ + @JvmStatic + fun of( + first: String, + vararg more: String, + ): Path = GuardPath(GuardContext.host(), (listOf(first) + more).filter { it.isNotEmpty() }.joinToString("/")) + + /** `Path.of(uri)`; only `file:` URIs exist here. */ + @JvmStatic + fun of(uri: URI): Path { + if (!uri.scheme.equals("file", ignoreCase = true)) throw FileSystemNotFoundException("Provider \"${uri.scheme}\" not installed") + return GuardPath(GuardContext.host(), uri.path) + } + } +} + +/** `java.nio.file.Paths`, which is final. */ +class GuardPaths private constructor() { + companion object { + @JvmStatic + fun get( + first: String, + vararg more: String, + ): Path = GuardPath.of(first, *more) + + @JvmStatic + fun get(uri: URI): Path = GuardPath.of(uri) + } +} + +/** `java.nio.file.FileSystems`, which is final. Only the default file system exists. */ +class GuardFileSystems private constructor() { + companion object { + @JvmStatic + fun getDefault(): FileSystem = GuardFileSystem + + @JvmStatic + fun getFileSystem(uri: URI): FileSystem = GuardProvider.getFileSystem(uri) + + // Android ships no other file system provider (no zipfs), so these fail as the real ones do. + private fun none(): Nothing = throw java.nio.file.ProviderNotFoundException("Provider not found") + + @JvmStatic + fun newFileSystem( + uri: URI, + env: Map, + ): FileSystem = none() + + @JvmStatic + fun newFileSystem( + uri: URI, + env: Map, + loader: ClassLoader?, + ): FileSystem = none() + + @JvmStatic + fun newFileSystem( + path: Path, + ): FileSystem = none() + + @JvmStatic + fun newFileSystem( + path: Path, + loader: ClassLoader?, + ): FileSystem = none() + + @JvmStatic + fun newFileSystem( + path: Path, + env: Map, + ): FileSystem = none() + + @JvmStatic + fun newFileSystem( + path: Path, + env: Map, + loader: ClassLoader?, + ): FileSystem = none() + } +} + +internal object GuardFileSystem : FileSystem() { + override fun provider(): FileSystemProvider = GuardProvider + + override fun close() = throw UnsupportedOperationException() + + override fun isOpen() = true + + override fun isReadOnly() = false + + override fun getSeparator() = "/" + + override fun getRootDirectories(): Iterable = listOf(GuardPath(GuardContext.host(), "/")) + + override fun getFileStores(): Iterable = listOf(GuardFileStore(GuardPath(GuardContext.host(), GuardContext.host().root))) + + override fun supportedFileAttributeViews(): Set = setOf("basic", "posix", "unix", "owner") + + override fun getPath( + first: String, + vararg more: String, + ): Path = GuardPath.of(first, *more) + + override fun getPathMatcher(syntaxAndPattern: String): PathMatcher { + val separator = syntaxAndPattern.indexOf(':') + require(separator > 0) { "Syntax and pattern are required" } + val pattern = syntaxAndPattern.substring(separator + 1) + val regex = + when (syntaxAndPattern.substring(0, separator).lowercase()) { + "regex" -> pattern + "glob" -> Globs.toRegex(pattern) + else -> throw UnsupportedOperationException("Syntax '${syntaxAndPattern.substring(0, separator)}' not recognized") + } + val compiled = Pattern.compile(regex) + return PathMatcher { compiled.matcher(it.toString()).matches() } + } + + override fun getUserPrincipalLookupService(): UserPrincipalLookupService = + object : UserPrincipalLookupService() { + override fun lookupPrincipalByName(name: String): UserPrincipal = Principal(name) + + override fun lookupPrincipalByGroupName(group: String): GroupPrincipal = Principal(group) + } + + override fun newWatchService(): WatchService = throw UnsupportedOperationException("Watching folders is not available to scripts") +} + +/** Glob syntax of `FileSystem.getPathMatcher`: `*`, `**`, `?`, `[...]`, `{a,b}`. */ +internal object Globs { + fun toRegex(glob: String): String { + val out = StringBuilder("^") + var i = 0 + var inGroup = false + while (i < glob.length) { + when (val c = glob[i]) { + '*' -> + if (i + 1 < glob.length && glob[i + 1] == '*') { + out.append(".*") + i++ + } else { + out.append("[^/]*") + } + '?' -> out.append("[^/]") + '[' -> { + val end = glob.indexOf(']', i + 1) + if (end < 0) throw java.util.regex.PatternSyntaxException("Missing ']'", glob, i) + var body = glob.substring(i + 1, end) + if (body.startsWith("!")) body = "^" + body.substring(1) + out.append('[').append(body.replace("\\", "\\\\")).append(']') + i = end + } + '{' -> { + inGroup = true + out.append("(?:") + } + '}' -> { + inGroup = false + out.append(')') + } + ',' -> out.append(if (inGroup) "|" else ",") + '\\' -> { + if (i + 1 < glob.length) out.append(Pattern.quote(glob[++i].toString())) + } + else -> out.append(if (c.isLetterOrDigit() || c == '/') c.toString() else Pattern.quote(c.toString())) + } + i++ + } + return out.append('$').toString() + } +} + +private class Principal(private val name: String) : UserPrincipal, GroupPrincipal { + override fun getName() = name + + override fun equals(other: Any?) = other is Principal && other.name == name + + override fun hashCode() = name.hashCode() + + override fun toString() = name +} + +private class GuardAttributes(private val entry: GuardHost.Entry) : PosixFileAttributes { + override fun lastModifiedTime(): FileTime = FileTime.fromMillis(entry.modifiedMs) + + override fun lastAccessTime(): FileTime = FileTime.fromMillis(entry.accessedMs) + + override fun creationTime(): FileTime = FileTime.fromMillis(entry.createdMs.takeIf { it > 0 } ?: entry.modifiedMs) + + override fun isRegularFile() = entry.isRegularFile + + override fun isDirectory() = entry.isDirectory + + override fun isSymbolicLink() = entry.isSymbolicLink + + override fun isOther() = false + + override fun size() = entry.size + + override fun fileKey(): Any? = null + + override fun owner(): UserPrincipal = Principal(entry.uid.toString()) + + override fun group(): GroupPrincipal = Principal(entry.gid.toString()) + + override fun permissions(): MutableSet = Permissions.of(entry.mode) +} + +private object Permissions { + private val order = + listOf( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_WRITE, + PosixFilePermission.OTHERS_EXECUTE, + ) + + fun of(mode: Int): MutableSet = order.filterIndexed { index, _ -> (mode and (0x100 shr index)) != 0 }.toMutableSet() + + fun mode(set: Set): Int = order.foldIndexed(0) { index, mode, permission -> if (permission in set) mode or (0x100 shr index) else mode } +} + +internal class GuardFileStore(private val path: GuardPath) : FileStore() { + private fun space(): GuardHost.Space = + try { + path.host.statfs(path.toString()) + } catch (e: HostIOException) { + throw GuardErrors.nio(e) + } + + override fun name() = path.host.root + + override fun type() = "host" + + override fun isReadOnly() = false + + override fun getTotalSpace() = space().let { it.blocks * it.blockSize } + + override fun getUsableSpace() = space().let { it.available * it.blockSize } + + override fun getUnallocatedSpace() = space().let { it.free * it.blockSize } + + override fun supportsFileAttributeView(type: Class) = + type == BasicFileAttributeView::class.java || type == PosixFileAttributeView::class.java || type == FileOwnerAttributeView::class.java + + override fun supportsFileAttributeView(name: String) = name in GuardFileSystem.supportedFileAttributeViews() + + override fun getFileStoreAttributeView(type: Class): V? = null + + override fun getAttribute(attribute: String): Any = + when (attribute) { + "totalSpace" -> totalSpace + "usableSpace" -> usableSpace + "unallocatedSpace" -> unallocatedSpace + else -> throw UnsupportedOperationException("'$attribute' not recognized") + } +} + +private fun guard(path: Path): GuardPath = path as? GuardPath ?: throw ProviderMismatchException() + +private inline fun nio( + path: GuardPath, + other: Path? = null, + block: () -> T, +): T = + try { + block() + } catch (e: HostIOException) { + throw GuardErrors.nio(HostIOException(e.errno, path.toString(), e.detail), other?.toString()) + } + +private fun entry( + path: GuardPath, + options: Array, +): GuardHost.Entry = nio(path) { path.host.stat(path.toString(), LinkOption.NOFOLLOW_LINKS !in options) } ?: throw NoSuchFileException(path.toString()) + +internal object GuardProvider : FileSystemProvider() { + override fun getScheme() = "file" + + override fun newFileSystem( + uri: URI, + env: MutableMap, + ): FileSystem = throw UnsupportedOperationException("Other file systems are not available to scripts") + + override fun getFileSystem(uri: URI): FileSystem { + if (!uri.scheme.equals("file", ignoreCase = true)) throw FileSystemNotFoundException("Provider \"${uri.scheme}\" not installed") + return GuardFileSystem + } + + override fun getPath(uri: URI): Path = GuardPath.of(uri) + + override fun newByteChannel( + path: Path, + options: MutableSet, + vararg attrs: FileAttribute<*>, + ): SeekableByteChannel = newFileChannel(path, options, *attrs) + + override fun newFileChannel( + path: Path, + options: MutableSet, + vararg attrs: FileAttribute<*>, + ): FileChannel { + val target = guard(path) + val name = target.toString() + val append = StandardOpenOption.APPEND in options + val write = StandardOpenOption.WRITE in options || append + val read = StandardOpenOption.READ in options || !write + if (append && (read && StandardOpenOption.READ in options || StandardOpenOption.TRUNCATE_EXISTING in options)) { + throw IllegalArgumentException("READ + APPEND or APPEND + TRUNCATE_EXISTING not allowed") + } + val host = target.host + if (!write) return GuardRandomAccessFile(nio(target) { host.open(name, HostFileMode.READ) }).channel + val createNew = StandardOpenOption.CREATE_NEW in options + val create = createNew || StandardOpenOption.CREATE in options + val exists = nio(target) { host.stat(name) } + if (exists?.isDirectory == true) throw java.nio.file.FileSystemException(name, null, "Is a directory") + if (createNew && exists != null) throw FileAlreadyExistsException(name) + if (exists == null && !create) throw NoSuchFileException(name) + val truncate = StandardOpenOption.TRUNCATE_EXISTING in options + val mode = + when { + append -> HostFileMode.APPEND or HostFileMode.READ_WRITE + exists == null || truncate -> HostFileMode.WRITE or HostFileMode.READ_WRITE + else -> HostFileMode.READ_WRITE + } or (if (createNew) HostFileMode.EXCLUSIVE else 0) + val descriptor = nio(target) { host.open(name, mode) } + val channel = GuardRandomAccessFile(descriptor).channel + if (append) channel.position(channel.size()) + if (StandardOpenOption.DELETE_ON_CLOSE in options) GuardContext.current().deleteOnExit(target.toAbsolutePath().toString()) + return channel + } + + override fun newDirectoryStream( + dir: Path, + filter: DirectoryStream.Filter?, + ): DirectoryStream { + val target = guard(dir) + val entry = entry(target, emptyArray()) + if (!entry.isDirectory) throw java.nio.file.NotDirectoryException(target.toString()) + val names = nio(target) { target.host.list(target.toString()) } + val entries = names.map { target.resolve(it) }.filter { filter == null || filter.accept(it) } + return object : DirectoryStream { + private var used = false + + override fun iterator(): MutableIterator { + check(!used) { "Iterator already obtained" } + used = true + return entries.toMutableList().iterator() + } + + override fun close() = Unit + } + } + + override fun createDirectory( + dir: Path, + vararg attrs: FileAttribute<*>, + ) { + val target = guard(dir) + if (nio(target) { target.host.stat(target.toString(), false) } != null) throw FileAlreadyExistsException(target.toString()) + nio(target) { target.host.mkdir(target.toString(), false) } + applyAttributes(target, attrs) + } + + private fun applyAttributes( + target: GuardPath, + attrs: Array>, + ) { + for (attr in attrs) { + if (attr.name() == "posix:permissions") { + @Suppress("UNCHECKED_CAST") + nio(target) { target.host.chmod(target.toString(), Permissions.mode(attr.value() as Set)) } + } else { + throw UnsupportedOperationException("'${attr.name()}' not supported as initial attribute") + } + } + } + + override fun createSymbolicLink( + link: Path, + target: Path, + vararg attrs: FileAttribute<*>, + ) { + val path = guard(link) + nio(path) { path.host.symlink(target.toString(), path.toString()) } + } + + override fun createLink( + link: Path, + existing: Path, + ) { + val path = guard(link) + nio(path, existing) { path.host.link(guard(existing).toString(), path.toString()) } + } + + override fun readSymbolicLink(link: Path): Path { + val path = guard(link) + return GuardPath(path.host, nio(path) { path.host.readlink(path.toString()) }) + } + + override fun delete(path: Path) { + val target = guard(path) + val entry = entry(target, arrayOf(LinkOption.NOFOLLOW_LINKS)) + if (entry.isDirectory && nio(target) { target.host.list(target.toString()) }.isNotEmpty()) throw DirectoryNotEmptyException(target.toString()) + nio(target) { target.host.remove(target.toString(), false) } + } + + override fun copy( + source: Path, + target: Path, + vararg options: CopyOption, + ) { + val from = guard(source) + val to = guard(target) + val follow = LinkOption.NOFOLLOW_LINKS !in options + val entry = entry(from, if (follow) emptyArray() else arrayOf(LinkOption.NOFOLLOW_LINKS)) + if (nio(to) { to.host.stat(to.toString(), false) } != null) { + if (StandardCopyOption.REPLACE_EXISTING !in options) throw FileAlreadyExistsException(to.toString()) + delete(to) + } + when { + entry.isSymbolicLink -> nio(to) { to.host.symlink(from.host.readlink(from.toString()), to.toString()) } + entry.isDirectory -> createDirectory(to) + else -> + newFileChannel(from, mutableSetOf(StandardOpenOption.READ)).use { input -> + newFileChannel(to, mutableSetOf(StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)).use { output -> + var at = 0L + val size = input.size() + while (at < size) at += input.transferTo(at, size - at, output) + } + } + } + if (StandardCopyOption.COPY_ATTRIBUTES in options) { + nio(to) { to.host.utimes(to.toString(), entry.accessedMs, entry.modifiedMs) } + if (!entry.isSymbolicLink) nio(to) { to.host.chmod(to.toString(), entry.mode and 0xfff) } + } + } + + override fun move( + source: Path, + target: Path, + vararg options: CopyOption, + ) { + val from = guard(source) + val to = guard(target) + entry(from, arrayOf(LinkOption.NOFOLLOW_LINKS)) + val existing = nio(to) { to.host.stat(to.toString(), false) } + if (existing != null) { + if (StandardCopyOption.REPLACE_EXISTING !in options) throw FileAlreadyExistsException(to.toString()) + if (from == to) return + delete(to) + } + nio(from, to) { from.host.rename(from.toString(), to.toString()) } + } + + override fun isSameFile( + path: Path, + path2: Path, + ): Boolean { + val a = guard(path) + val b = path2 as? GuardPath ?: return false + if (a == b) return true + return nio(a) { a.host.realpath(a.toAbsolutePath().toString()) } == nio(b) { b.host.realpath(b.toAbsolutePath().toString()) } + } + + override fun isHidden(path: Path) = path.fileName?.toString()?.startsWith(".") == true + + override fun getFileStore(path: Path): FileStore { + val target = guard(path) + entry(target, emptyArray()) + return GuardFileStore(target) + } + + override fun checkAccess( + path: Path, + vararg modes: AccessMode, + ) { + val target = guard(path) + entry(target, emptyArray()) + val mask = modes.fold(0) { mask, mode -> mask or when (mode) { AccessMode.READ -> 4; AccessMode.WRITE -> 2; AccessMode.EXECUTE -> 1 } } + if (mask != 0 && !target.host.access(target.toString(), mask)) throw AccessDeniedException(target.toString()) + } + + private open class Basic( + protected val path: GuardPath, + protected val options: Array, + ) : BasicFileAttributeView { + override fun name() = "basic" + + override fun readAttributes(): BasicFileAttributes = GuardAttributes(entry(path, options)) + + override fun setTimes( + lastModifiedTime: FileTime?, + lastAccessTime: FileTime?, + createTime: FileTime?, + ) { + if (lastModifiedTime == null && lastAccessTime == null) return + val entry = entry(path, options) + nio(path) { path.host.utimes(path.toString(), lastAccessTime?.toMillis() ?: entry.accessedMs, lastModifiedTime?.toMillis() ?: entry.modifiedMs) } + } + } + + private class Posix( + path: GuardPath, + options: Array, + ) : Basic(path, options), PosixFileAttributeView { + override fun name() = "posix" + + override fun readAttributes(): PosixFileAttributes = GuardAttributes(entry(path, options)) + + override fun setPermissions(perms: MutableSet) { + nio(path) { path.host.chmod(path.toString(), Permissions.mode(perms)) } + } + + override fun getOwner(): UserPrincipal = readAttributes().owner() + + override fun setOwner(owner: UserPrincipal) = throw java.nio.file.FileSystemException(path.toString(), null, "Operation not permitted") + + override fun setGroup(group: GroupPrincipal) = throw java.nio.file.FileSystemException(path.toString(), null, "Operation not permitted") + } + + @Suppress("UNCHECKED_CAST") + override fun getFileAttributeView( + path: Path, + type: Class, + vararg options: LinkOption, + ): V? { + val target = guard(path) + return when (type) { + BasicFileAttributeView::class.java -> Basic(target, options) as V + PosixFileAttributeView::class.java, FileOwnerAttributeView::class.java -> Posix(target, options) as V + else -> null + } + } + + @Suppress("UNCHECKED_CAST") + override fun readAttributes( + path: Path, + type: Class, + vararg options: LinkOption, + ): A { + if (type != BasicFileAttributes::class.java && type != PosixFileAttributes::class.java) throw UnsupportedOperationException() + return GuardAttributes(entry(guard(path), options)) as A + } + + override fun readAttributes( + path: Path, + attributes: String, + vararg options: LinkOption, + ): MutableMap { + val view = if (':' in attributes) attributes.substringBefore(':') else "basic" + if (view !in GuardFileSystem.supportedFileAttributeViews()) throw UnsupportedOperationException("View '$view' not available") + val a = GuardAttributes(entry(guard(path), options)) + val all = + linkedMapOf( + "lastModifiedTime" to a.lastModifiedTime(), + "lastAccessTime" to a.lastAccessTime(), + "creationTime" to a.creationTime(), + "size" to a.size(), + "isRegularFile" to a.isRegularFile, + "isDirectory" to a.isDirectory, + "isSymbolicLink" to a.isSymbolicLink, + "isOther" to a.isOther, + "fileKey" to a.fileKey(), + ) + if (view != "basic") { + all["permissions"] = a.permissions() + all["owner"] = a.owner() + all["group"] = a.group() + } + val wanted = attributes.substringAfter(':').split(',') + if ("*" in wanted) return all + return wanted.associateWith { name -> if (name in all) all[name] else throw IllegalArgumentException("'$name' not recognized") }.toMutableMap() + } + + override fun setAttribute( + path: Path, + attribute: String, + value: Any?, + vararg options: LinkOption, + ) { + val target = guard(path) + val name = attribute.substringAfter(':') + val posix = Posix(target, options) + when (name) { + "lastModifiedTime" -> posix.setTimes(value as FileTime, null, null) + "lastAccessTime" -> posix.setTimes(null, value as FileTime, null) + "creationTime" -> Unit + "permissions" -> @Suppress("UNCHECKED_CAST") posix.setPermissions(value as MutableSet) + else -> throw IllegalArgumentException("'$attribute' not recognized") + } + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardPolicy.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardPolicy.kt new file mode 100644 index 0000000..ecf4033 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardPolicy.kt @@ -0,0 +1,132 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import java.io.File +import java.lang.reflect.AccessibleObject +import java.lang.reflect.Constructor +import java.lang.reflect.Field +import java.lang.reflect.Method +import java.nio.file.FileSystems +import java.nio.file.Path + +/** + * What an engine needs to guard Java for scripts: which class a name stands for ([lookup]) and what a Java value + * becomes before a script sees it ([replace]). An engine calls these from its class lookup and from where Java values + * enter the script; everything else is in the guard classes themselves. + * + * The answers follow the [GuardSession] of the current thread ([GuardContext]). + */ +object GuardPolicy { + /** + * Classes that open files, start programs or describe classes, by the name a script asks for. The replacements + * have the same constructors, methods and fields, and extend the real class wherever it is not final. + */ + val substitutes: Map> = + mapOf( + "java.io.File" to GuardFile::class.java, + "java.io.FileInputStream" to GuardFileInputStream::class.java, + "java.io.FileOutputStream" to GuardFileOutputStream::class.java, + "java.io.FileReader" to GuardFileReader::class.java, + "java.io.FileWriter" to GuardFileWriter::class.java, + "java.io.PrintWriter" to GuardPrintWriter::class.java, + "java.io.PrintStream" to GuardPrintStream::class.java, + "java.io.RandomAccessFile" to GuardRandomAccessFile::class.java, + "java.util.Scanner" to GuardScanner::class.java, + "java.util.zip.ZipFile" to GuardZipFile::class.java, + "java.util.jar.JarFile" to GuardJarFile::class.java, + "java.nio.file.Path" to GuardPath::class.java, + "java.nio.file.Paths" to GuardPaths::class.java, + "java.nio.file.Files" to GuardFiles::class.java, + "java.nio.file.FileSystems" to GuardFileSystems::class.java, + "android.os.Environment" to GuardEnvironment::class.java, + "java.lang.Class" to GuardClass::class.java, + "java.lang.ClassLoader" to GuardClassLoader::class.java, + "java.lang.Runtime" to GuardRuntime::class.java, + "java.lang.ProcessBuilder" to GuardProcessBuilder::class.java, + "java.lang.System" to GuardSystem::class.java, + ) + + // Replacements that only matter while the class rules are on; files are guarded either way. + private val classStandIns = setOf("java.lang.Class", "java.lang.ClassLoader", "java.lang.Runtime", "java.lang.ProcessBuilder", "java.lang.System") + + private val originals: Map, String> = substitutes.entries.associate { (name, type) -> type to name } + + /** The replacement for [className] under the current rules, or null when the real class is used. */ + fun substituteOf(className: String): Class<*>? { + if (className in classStandIns && !GuardContext.rules().restricted) return null + return substitutes[className] + } + + /** The class a replacement stands for, or [type] itself. */ + fun originalOf(type: Class<*>): Class<*> = originals[type]?.let { runCatching { Class.forName(it) }.getOrNull() } ?: type + + sealed interface Lookup { + /** Give the script this class. */ + data class Found(val type: Class<*>) : Lookup + + /** No such class for this project: show nothing there (a package in Javet, undefined, or not found). */ + data object Denied : Lookup + + /** Not a guarded name: look it up as the engine always does. */ + data object Ordinary : Lookup + } + + fun lookup(className: String): Lookup { + substituteOf(className)?.let { return Lookup.Found(it) } + val rules = GuardContext.rules() + if (isGuardClass(className) || rules.isDenied(className)) { + // Engines look up their own classes through the same path while they start; that is not the script. + if (!rules.isEngineInternal(className) && !isGuardClass(className)) GuardContext.reportClass(className) + return Lookup.Denied + } + return Lookup.Ordinary + } + + /** True when [className] is one of the guard's own classes, which a script may hold. */ + fun isGuardClass(className: String) = className.startsWith(OWN_PACKAGE) + + /** + * What a Java value becomes before a script sees it: a real file or path becomes the guard's, and under the class + * rules a class, class loader or reflective member becomes a checked stand-in. A value of a class the project may + * not use is refused with [SecurityException]. Arrays and collections are left to the engine, which converts + * their elements one by one. + */ + fun replace(value: Any?): Any? { + if (value == null) return null + val type = value.javaClass + if (isGuardClass(type.name)) return value + when (value) { + is File -> return GuardFile(value.path) + is Path -> if (value.fileSystem === realDefault) return GuardPath(GuardContext.host(), value.toString()) + } + val rules = GuardContext.rules() + if (!rules.restricted) { + if (rules.isDeniedValue(type.name)) refuse(type.name) + return value + } + return when (value) { + is Class<*> -> GuardClass.of(value) + is ClassLoader -> GuardClassLoader.INSTANCE + is Method -> if (rules.allows("java.lang.reflect.Method")) value else GuardMethod(value) + is Constructor<*> -> if (rules.allows("java.lang.reflect.Constructor")) value else GuardConstructor(value) + is Field -> if (rules.allows("java.lang.reflect.Field")) value else GuardField(value) + is Runtime -> GuardRuntime.getRuntime() + is AccessibleObject -> refuse(type.name) + is Process -> value + else -> if (rules.isDeniedValue(type.name)) refuse(type.name) else value + } + } + + private fun refuse(name: String): Nothing { + GuardContext.reportClass(name) + throw SecurityException("$name is not available to this project") + } + + private const val OWN_PACKAGE = "com.xfl.msgbot.plugin.guard." + + private val realDefault = FileSystems.getDefault() +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardProcess.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardProcess.kt new file mode 100644 index 0000000..e23f328 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardProcess.kt @@ -0,0 +1,201 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import java.io.File +import java.util.StringTokenizer + +/** + * What a script may start. A process runs with the rights of this app and the engine cannot look inside it, so this is a + * check of what is written, not a fence: a command that names a path must name one the project may see, and a program + * that reads its arguments as commands (a shell) is refused. Anything that builds a path inside the program gets past it. + */ +internal object ProcessRules { + private val interpreters = setOf("sh", "bash", "ash", "dash", "zsh", "su", "busybox", "toybox", "env", "run-as", "app_process", "app_process32", "app_process64", "cmd", "am", "pm", "xargs", "nohup", "setsid") + + fun check( + host: GuardHost, + command: List, + ) { + if (command.isEmpty()) throw IndexOutOfBoundsException("Empty command") + val program = command[0].substringAfterLast('/') + if (program in interpreters) GuardContext.currentOrNull()?.report("program", program) + if (program in interpreters) throw SecurityException("'$program' reads its arguments as commands, so a script may not start it") + for (token in command) { + if (!token.contains('/') && token != ".." && !token.startsWith("~")) continue + checkPath(host, token, "in the command") + } + } + + fun checkDirectory( + host: GuardHost, + directory: File?, + ) { + if (directory == null) return + checkPath(host, directory.path, "as the working folder") + } + + private fun checkPath( + host: GuardHost, + token: String, + where: String, + ) { + val seen = !token.startsWith("~") && !token.split('/').contains("..") && runCatching { host.stat(token) }.getOrNull() != null + if (!seen) GuardContext.reportPath(token) + if (!seen) throw SecurityException("The path '$token' $where is outside what this project may use") + } + + fun split(command: String): List { + val tokens = StringTokenizer(command) + return List(tokens.countTokens()) { tokens.nextToken() } + } +} + +/** `java.lang.Runtime`: memory and processor facts as usual, programs only through [ProcessRules]. */ +class GuardRuntime private constructor() { + private fun host() = GuardContext.host() + + fun availableProcessors() = Runtime.getRuntime().availableProcessors() + + fun freeMemory() = Runtime.getRuntime().freeMemory() + + fun totalMemory() = Runtime.getRuntime().totalMemory() + + fun maxMemory() = Runtime.getRuntime().maxMemory() + + fun gc() = Runtime.getRuntime().gc() + + fun exec(command: String): Process = exec(ProcessRules.split(command).toTypedArray(), null, null) + + fun exec(command: Array): Process = exec(command, null, null) + + fun exec( + command: String, + env: Array?, + dir: File?, + ): Process = exec(ProcessRules.split(command).toTypedArray(), env, dir) + + fun exec( + command: Array, + env: Array?, + dir: File?, + ): Process { + ProcessRules.check(host(), command.toList()) + ProcessRules.checkDirectory(host(), dir) + val builder = ProcessBuilder(*command) + if (dir != null) builder.directory(File(dir.path)) + if (env != null) { + builder.environment().clear() + env.forEach { entry -> entry.indexOf('=').takeIf { it > 0 }?.let { builder.environment()[entry.substring(0, it)] = entry.substring(it + 1) } } + } + return builder.start() + } + + fun exit(status: Int): Unit = throw SecurityException("A script may not end the process") + + fun halt(status: Int): Unit = throw SecurityException("A script may not end the process") + + fun load(path: String): Unit = throw SecurityException("A script may not load native code") + + fun loadLibrary(name: String): Unit = throw SecurityException("A script may not load native code") + + override fun toString() = "GuardRuntime" + + companion object { + private val INSTANCE = GuardRuntime() + + @JvmStatic + fun getRuntime() = INSTANCE + } +} + +/** `java.lang.ProcessBuilder`, which is final, rebuilt with the same checks at [start]. */ +class GuardProcessBuilder(command: List) { + private val host = GuardContext.host() + private var command: List = command.toList() + private var directory: File? = null + private var mergeErrors = false + private val environment = HashMap(System.getenv()) + + constructor(vararg command: String) : this(command.toList()) + + fun command(): List = command + + fun command(command: List): GuardProcessBuilder = apply { this.command = command.toList() } + + fun command(vararg command: String): GuardProcessBuilder = apply { this.command = command.toList() } + + fun directory(): File? = directory + + fun directory(directory: File?): GuardProcessBuilder = + apply { + ProcessRules.checkDirectory(host, directory) + this.directory = directory?.let { File(it.path) } + } + + fun redirectErrorStream(): Boolean = mergeErrors + + fun redirectErrorStream(merge: Boolean): GuardProcessBuilder = apply { mergeErrors = merge } + + fun environment(): MutableMap = environment + + fun start(): Process { + ProcessRules.check(host, command) + ProcessRules.checkDirectory(host, directory) + val builder = ProcessBuilder(command) + builder.directory(directory) + builder.redirectErrorStream(mergeErrors) + builder.environment().apply { + clear() + putAll(environment) + } + return builder.start() + } +} + +/** `java.lang.System` without what ends the process or loads native code. */ +class GuardSystem private constructor() { + companion object { + @JvmField val `in` = System.`in` + + @JvmField val out = System.out + + @JvmField val err = System.err + + @JvmStatic fun currentTimeMillis() = System.currentTimeMillis() + + @JvmStatic fun nanoTime() = System.nanoTime() + + @JvmStatic fun getProperty(key: String): String? = System.getProperty(key) + + @JvmStatic fun getProperty( + key: String, + default: String?, + ): String? = System.getProperty(key, default) + + @JvmStatic fun lineSeparator(): String = System.lineSeparator() + + @JvmStatic fun identityHashCode(value: Any?) = System.identityHashCode(value) + + @JvmStatic fun arraycopy( + source: Any, + sourcePosition: Int, + target: Any, + targetPosition: Int, + length: Int, + ) = System.arraycopy(source, sourcePosition, target, targetPosition, length) + + @JvmStatic fun gc() = System.gc() + + @JvmStatic fun getenv(name: String): String? = System.getenv(name) + + @JvmStatic fun exit(status: Int): Unit = throw SecurityException("A script may not end the process") + + @JvmStatic fun load(path: String): Unit = throw SecurityException("A script may not load native code") + + @JvmStatic fun loadLibrary(name: String): Unit = throw SecurityException("A script may not load native code") + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardReflect.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardReflect.kt new file mode 100644 index 0000000..11d2bb8 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardReflect.kt @@ -0,0 +1,329 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import java.io.InputStream +import java.lang.reflect.Constructor +import java.lang.reflect.Field +import java.lang.reflect.InvocationTargetException +import java.lang.reflect.Method +import java.lang.reflect.Modifier +import java.net.URL + +private fun unwrap(error: InvocationTargetException): Throwable = error.targetException ?: error + +// A static member is like naming its class, so it follows the lookup rules. An instance member acts on an object the +// script already holds, so it follows the value rules: a public method of sun.nio.ch.FileChannelImpl is a FileChannel method. +private fun check( + type: Class<*>, + what: String, + static: Boolean = false, +) { + val name = GuardPolicy.originalOf(type).name + val rules = GuardContext.rules() + if (if (static) rules.isDenied(name) else rules.isDeniedValue(name)) { + GuardContext.reportClass(name) + throw SecurityException("$what on $name is not available to this project") + } +} + +private fun realTypes(list: Array): Array> = Array(list.size) { list[it].real } + +/** + * `java.lang.Class` for scripts. It describes the class that was asked for ([getName] is `java.io.File`, not the + * guard's), while constructors and static methods come from the guard's replacement, so what a script makes through + * reflection is guarded as well. Members of classes the project may not use are refused when used. + */ +class GuardClass internal constructor( + internal val real: Class<*>, + internal val impl: Class<*>, +) { + fun getName(): String = real.name + + fun getSimpleName(): String = real.simpleName + + fun getCanonicalName(): String? = real.canonicalName + + fun getTypeName(): String = real.typeName + + fun getPackageName(): String = real.`package`?.name ?: real.name.substringBeforeLast('.', "") + + fun isInstance(value: Any?): Boolean = real.isInstance(value) + + fun isAssignableFrom(other: GuardClass): Boolean = real.isAssignableFrom(other.real) + + fun isInterface() = real.isInterface + + fun isArray() = real.isArray + + fun isPrimitive() = real.isPrimitive + + fun isEnum() = real.isEnum + + fun isAnnotation() = real.isAnnotation + + fun isAnonymousClass() = real.isAnonymousClass + + fun isLocalClass() = real.isLocalClass + + fun isMemberClass() = real.isMemberClass + + fun isSynthetic() = real.isSynthetic + + fun getModifiers() = real.modifiers + + fun getSuperclass(): GuardClass? = real.superclass?.let { of(it) } + + fun getInterfaces(): Array = real.interfaces.map { of(it) }.toTypedArray() + + fun getComponentType(): GuardClass? = real.componentType?.let { of(it) } + + fun arrayType(): GuardClass = of(java.lang.reflect.Array.newInstance(real, 0).javaClass) + + fun getEnclosingClass(): GuardClass? = real.enclosingClass?.let { of(it) } + + fun getDeclaringClass(): GuardClass? = real.declaringClass?.let { of(it) } + + fun getClassLoader(): GuardClassLoader = GuardClassLoader.INSTANCE + + fun getEnumConstants(): Array? = real.enumConstants?.map { it }?.toTypedArray() + + fun desiredAssertionStatus() = false + + fun cast(value: Any?): Any? = real.cast(value) + + fun getResourceAsStream(name: String): InputStream? = real.getResourceAsStream(name) + + fun getResource(name: String): URL? = real.getResource(name) + + private fun usable(member: Class<*>) = !GuardContext.rules().isDeniedValue(GuardPolicy.originalOf(member).name) + + fun getMethods(): Array = impl.methods.filter { usable(it.declaringClass) }.map { GuardMethod(it) }.toTypedArray() + + fun getDeclaredMethods(): Array = impl.declaredMethods.filter { Modifier.isPublic(it.modifiers) || impl == real }.map { GuardMethod(it) }.toTypedArray() + + @Throws(NoSuchMethodException::class) + fun getMethod( + name: String, + vararg parameters: GuardClass, + ) = GuardMethod(impl.getMethod(name, *realTypes(parameters))) + + @Throws(NoSuchMethodException::class) + fun getDeclaredMethod( + name: String, + vararg parameters: GuardClass, + ) = GuardMethod(impl.getDeclaredMethod(name, *realTypes(parameters))) + + fun getConstructors(): Array = impl.constructors.map { GuardConstructor(it) }.toTypedArray() + + fun getDeclaredConstructors(): Array = impl.declaredConstructors.filter { Modifier.isPublic(it.modifiers) || impl == real }.map { GuardConstructor(it) }.toTypedArray() + + @Throws(NoSuchMethodException::class) + fun getConstructor(vararg parameters: GuardClass) = GuardConstructor(impl.getConstructor(*realTypes(parameters))) + + @Throws(NoSuchMethodException::class) + fun getDeclaredConstructor(vararg parameters: GuardClass) = GuardConstructor(impl.getDeclaredConstructor(*realTypes(parameters))) + + fun getFields(): Array = impl.fields.map { GuardField(it) }.toTypedArray() + + fun getDeclaredFields(): Array = impl.declaredFields.filter { Modifier.isPublic(it.modifiers) || impl == real }.map { GuardField(it) }.toTypedArray() + + @Throws(NoSuchFieldException::class) + fun getField(name: String) = GuardField(impl.getField(name)) + + @Throws(NoSuchFieldException::class) + fun getDeclaredField(name: String) = GuardField(impl.getDeclaredField(name)) + + /** `Class.newInstance()`, through the guard's no-argument constructor. */ + fun newInstance(): Any? = getConstructor().newInstance() + + override fun toString() = (if (real.isInterface) "interface " else if (real.isPrimitive) "" else "class ") + real.name + + override fun equals(other: Any?) = other is GuardClass && other.real == real + + override fun hashCode() = real.hashCode() + + companion object { + /** The stand-in for [type], which may be a real class or one of the guard's replacements. */ + @JvmStatic + fun of(type: Class<*>): GuardClass { + val original = GuardPolicy.originalOf(type) + return GuardClass(original, GuardPolicy.substituteOf(original.name) ?: original) + } + + @JvmStatic + @Throws(ClassNotFoundException::class) + fun forName(name: String): GuardClass { + GuardPolicy.substituteOf(name)?.let { return GuardClass(Class.forName(name), it) } + if (GuardPolicy.lookup(name) == GuardPolicy.Lookup.Denied) { + throw ClassNotFoundException(name) + } + return of(Class.forName(name)) + } + + @JvmStatic + @Throws(ClassNotFoundException::class) + fun forName( + name: String, + initialize: Boolean, + loader: GuardClassLoader?, + ): GuardClass = forName(name) + } +} + +/** `java.lang.ClassLoader` for scripts: it finds classes by name under the same rules as [GuardClass.forName]. */ +class GuardClassLoader private constructor() { + @Throws(ClassNotFoundException::class) + fun loadClass(name: String): GuardClass = GuardClass.forName(name) + + fun getParent(): GuardClassLoader? = null + + fun getResourceAsStream(name: String): InputStream? = GuardClassLoader::class.java.classLoader?.getResourceAsStream(name) + + fun getResource(name: String): URL? = GuardClassLoader::class.java.classLoader?.getResource(name) + + override fun toString() = "GuardClassLoader" + + companion object { + internal val INSTANCE = GuardClassLoader() + + @JvmStatic + fun getSystemClassLoader() = INSTANCE + } +} + +class GuardMethod internal constructor(private val method: Method) { + fun getName(): String = method.name + + fun getModifiers() = method.modifiers + + fun getParameterCount() = method.parameterCount + + fun getParameterTypes(): Array = method.parameterTypes.map { GuardClass.of(it) }.toTypedArray() + + fun getReturnType(): GuardClass = GuardClass.of(method.returnType) + + fun getExceptionTypes(): Array = method.exceptionTypes.map { GuardClass.of(it) }.toTypedArray() + + fun getDeclaringClass(): GuardClass = GuardClass.of(method.declaringClass) + + fun isVarArgs() = method.isVarArgs + + fun isDefault() = method.isDefault + + fun isAccessible() = true + + fun setAccessible(flag: Boolean) = Unit + + fun trySetAccessible() = true + + fun invoke( + target: Any?, + vararg args: Any?, + ): Any? { + check(method.declaringClass, "Calling ${method.name}", Modifier.isStatic(method.modifiers)) + if (target != null) check(target.javaClass, "Calling ${method.name}") + try { + return GuardPolicy.replace(method.invoke(target, *args)) + } catch (e: IllegalAccessException) { + throw SecurityException("${method.declaringClass.name}.${method.name} cannot be called from a script") + } catch (e: InvocationTargetException) { + throw unwrap(e) + } + } + + override fun toString() = method.toGenericString() + + override fun equals(other: Any?) = other is GuardMethod && other.method == method + + override fun hashCode() = method.hashCode() +} + +class GuardConstructor internal constructor(private val constructor: Constructor<*>) { + fun getName(): String = GuardPolicy.originalOf(constructor.declaringClass).name + + fun getModifiers() = constructor.modifiers + + fun getParameterCount() = constructor.parameterCount + + fun getParameterTypes(): Array = constructor.parameterTypes.map { GuardClass.of(it) }.toTypedArray() + + fun getExceptionTypes(): Array = constructor.exceptionTypes.map { GuardClass.of(it) }.toTypedArray() + + fun getDeclaringClass(): GuardClass = GuardClass.of(constructor.declaringClass) + + fun isVarArgs() = constructor.isVarArgs + + fun isAccessible() = true + + fun setAccessible(flag: Boolean) = Unit + + fun trySetAccessible() = true + + fun newInstance(vararg args: Any?): Any? { + check(constructor.declaringClass, "Creating", static = true) + try { + return constructor.newInstance(*args) + } catch (e: IllegalAccessException) { + throw SecurityException("${constructor.declaringClass.name} cannot be created from a script") + } catch (e: InvocationTargetException) { + throw unwrap(e) + } + } + + override fun toString() = constructor.toGenericString() + + override fun equals(other: Any?) = other is GuardConstructor && other.constructor == constructor + + override fun hashCode() = constructor.hashCode() +} + +class GuardField internal constructor(private val field: Field) { + fun getName(): String = field.name + + fun getModifiers() = field.modifiers + + fun getType(): GuardClass = GuardClass.of(field.type) + + fun getDeclaringClass(): GuardClass = GuardClass.of(field.declaringClass) + + fun isEnumConstant() = field.isEnumConstant + + fun isAccessible() = true + + fun setAccessible(flag: Boolean) = Unit + + fun trySetAccessible() = true + + fun get(target: Any?): Any? { + check(field.declaringClass, "Reading ${field.name}", Modifier.isStatic(field.modifiers)) + if (target != null) check(target.javaClass, "Reading ${field.name}") + return try { + GuardPolicy.replace(field.get(target)) + } catch (e: IllegalAccessException) { + throw SecurityException("${field.declaringClass.name}.${field.name} cannot be read from a script") + } + } + + fun set( + target: Any?, + value: Any?, + ) { + check(field.declaringClass, "Writing ${field.name}", Modifier.isStatic(field.modifiers)) + if (target != null) check(target.javaClass, "Writing ${field.name}") + try { + field.set(target, value) + } catch (e: IllegalAccessException) { + throw SecurityException("${field.declaringClass.name}.${field.name} cannot be written from a script") + } + } + + override fun toString() = field.toGenericString() + + override fun equals(other: Any?) = other is GuardField && other.field == field + + override fun hashCode() = field.hashCode() +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardScanner.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardScanner.kt new file mode 100644 index 0000000..defe51f --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardScanner.kt @@ -0,0 +1,176 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import java.io.Closeable +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.math.BigDecimal +import java.math.BigInteger +import java.nio.channels.ReadableByteChannel +import java.nio.file.Files +import java.nio.file.Path +import java.io.InputStreamReader +import java.nio.channels.Channels +import java.nio.charset.Charset +import java.util.Locale +import java.util.Scanner +import java.util.regex.MatchResult +import java.util.regex.Pattern +import java.util.stream.Stream + +/** `java.util.Scanner` is final, so scripts get this one: the same calls on a real scanner that reads through the guard's streams. */ +class GuardScanner private constructor(private val scanner: Scanner) : Closeable, Iterator { + constructor(source: String) : this(Scanner(source)) + + constructor(source: InputStream) : this(Scanner(source)) + + constructor(source: InputStream, charset: String) : this(Scanner(source, charset)) + + constructor(source: File) : this(Scanner(GuardFileInputStream(source))) + + constructor(source: File, charset: String) : this(Scanner(GuardFileInputStream(source), charset)) + + constructor(source: Path) : this(Scanner(Files.newInputStream(source))) + + constructor(source: Path, charset: String) : this(Scanner(Files.newInputStream(source), charset)) + + constructor(source: Readable) : this(Scanner(source)) + + constructor(source: ReadableByteChannel) : this(Scanner(source)) + + constructor(source: ReadableByteChannel, charset: String) : this(Scanner(source, charset)) + + // Scanner's own Charset constructors are newer than the oldest Android this runs on. + constructor(source: InputStream, charset: Charset) : this(Scanner(InputStreamReader(source, charset))) + + constructor(source: File, charset: Charset) : this(GuardFileInputStream(source), charset) + + constructor(source: Path, charset: Charset) : this(Files.newInputStream(source), charset) + + constructor(source: ReadableByteChannel, charset: Charset) : this(Channels.newInputStream(source), charset) + + override fun hasNext() = scanner.hasNext() + + fun hasNext(pattern: String) = scanner.hasNext(pattern) + + override fun next(): String = scanner.next() + + fun next(pattern: String): String = scanner.next(pattern) + + fun hasNextLine() = scanner.hasNextLine() + + fun nextLine(): String = scanner.nextLine() + + fun hasNextInt() = scanner.hasNextInt() + + fun hasNextInt(radix: Int) = scanner.hasNextInt(radix) + + fun nextInt() = scanner.nextInt() + + fun nextInt(radix: Int) = scanner.nextInt(radix) + + fun hasNextLong() = scanner.hasNextLong() + + fun nextLong() = scanner.nextLong() + + fun hasNextShort() = scanner.hasNextShort() + + fun nextShort() = scanner.nextShort() + + fun hasNextByte() = scanner.hasNextByte() + + fun nextByte() = scanner.nextByte() + + fun hasNextFloat() = scanner.hasNextFloat() + + fun nextFloat() = scanner.nextFloat() + + fun hasNextDouble() = scanner.hasNextDouble() + + fun nextDouble() = scanner.nextDouble() + + fun hasNextBoolean() = scanner.hasNextBoolean() + + fun nextBoolean() = scanner.nextBoolean() + + fun hasNextBigInteger() = scanner.hasNextBigInteger() + + fun nextBigInteger(): BigInteger = scanner.nextBigInteger() + + fun hasNextBigDecimal() = scanner.hasNextBigDecimal() + + fun nextBigDecimal(): BigDecimal = scanner.nextBigDecimal() + + fun useDelimiter(pattern: String): GuardScanner = apply { scanner.useDelimiter(pattern) } + + fun delimiter(): Pattern = scanner.delimiter() + + fun skip(pattern: String): GuardScanner = apply { scanner.skip(pattern) } + + fun findInLine(pattern: String): String? = scanner.findInLine(pattern) + + fun findWithinHorizon( + pattern: String, + horizon: Int, + ): String? = scanner.findWithinHorizon(pattern, horizon) + + fun useRadix(radix: Int): GuardScanner = apply { scanner.useRadix(radix) } + + fun radix() = scanner.radix() + + fun reset(): GuardScanner = apply { scanner.reset() } + + fun tokens(): Stream = scanner.tokens() + + fun ioException(): IOException? = scanner.ioException() + + fun hasNext(pattern: Pattern) = scanner.hasNext(pattern) + + fun next(pattern: Pattern): String = scanner.next(pattern) + + fun hasNextLong(radix: Int) = scanner.hasNextLong(radix) + + fun nextLong(radix: Int) = scanner.nextLong(radix) + + fun hasNextShort(radix: Int) = scanner.hasNextShort(radix) + + fun nextShort(radix: Int) = scanner.nextShort(radix) + + fun hasNextByte(radix: Int) = scanner.hasNextByte(radix) + + fun nextByte(radix: Int) = scanner.nextByte(radix) + + fun hasNextBigInteger(radix: Int) = scanner.hasNextBigInteger(radix) + + fun nextBigInteger(radix: Int): BigInteger = scanner.nextBigInteger(radix) + + fun useDelimiter(pattern: Pattern): GuardScanner = apply { scanner.useDelimiter(pattern) } + + fun skip(pattern: Pattern): GuardScanner = apply { scanner.skip(pattern) } + + fun findInLine(pattern: Pattern): String? = scanner.findInLine(pattern) + + fun findWithinHorizon( + pattern: Pattern, + horizon: Int, + ): String? = scanner.findWithinHorizon(pattern, horizon) + + fun findAll(pattern: String): Stream = scanner.findAll(pattern) + + fun findAll(pattern: Pattern): Stream = scanner.findAll(pattern) + + fun match(): MatchResult = scanner.match() + + fun locale(): Locale = scanner.locale() + + fun useLocale(locale: Locale): GuardScanner = apply { scanner.useLocale(locale) } + + override fun close() = scanner.close() + + override fun toString(): String = scanner.toString() +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardSession.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardSession.kt new file mode 100644 index 0000000..369bf63 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardSession.kt @@ -0,0 +1,83 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import java.io.Closeable +import java.util.concurrent.ConcurrentHashMap + +/** + * What the scripts of one project may use: the files the host shows them and the classes the project allows. + * One per engine session; [close] it when the session ends. + */ +class GuardSession( + val host: GuardHost, + val rules: ClassRules = ClassRules.DEFAULT, +) : Closeable { + private val reported = ConcurrentHashMap.newKeySet() + private val deleteOnExit = ConcurrentHashMap.newKeySet() + + /** Tells the project log, once per name, that the guard stopped something. */ + fun report( + kind: String, + name: String, + ) { + if (reported.add("$kind:$name")) host.log("warn", "Java: $kind '$name' is not available to this project") + } + + internal fun deleteOnExit(path: String) { + deleteOnExit += path + } + + /** Deletes what `File.deleteOnExit` asked for, deepest first. */ + override fun close() { + deleteOnExit.sortedByDescending { it.length }.forEach { + try { + host.remove(it, false) + } catch (_: Exception) { + } + } + deleteOnExit.clear() + } +} + +/** + * The session of the project whose script runs on this thread. Script code makes guard objects through reflection, + * so they cannot be handed their project; they read it from here when they are made. The engine sets it around every + * entry into script code (load, events, timers, eval). + */ +object GuardContext { + private val current = ThreadLocal() + + inline fun with( + session: GuardSession?, + block: () -> T, + ): T { + val previous = swap(session) + try { + return block() + } finally { + swap(previous) + } + } + + fun swap(session: GuardSession?): GuardSession? = current.get().also { current.set(session) } + + fun currentOrNull(): GuardSession? = current.get() + + fun current(): GuardSession = current.get() ?: throw SecurityException("Java files can only be used from a script of this project, on its own thread") + + fun host(): GuardHost = current().host + + fun rules(): ClassRules = current.get()?.rules ?: ClassRules.DEFAULT + + internal fun reportPath(path: String) { + current.get()?.report("path", path) + } + + internal fun reportClass(name: String) { + current.get()?.report("class", name) + } +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardStreams.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardStreams.kt new file mode 100644 index 0000000..07a00db --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardStreams.kt @@ -0,0 +1,248 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import android.os.ParcelFileDescriptor +import android.system.Os +import android.system.OsConstants +import com.xfl.msgbot.plugin.api.engine.HostFileMode +import java.io.BufferedWriter +import java.io.File +import java.io.FileDescriptor +import java.io.FileNotFoundException +import java.io.FileReader +import java.io.FileWriter +import java.io.InputStreamReader +import java.io.OutputStream +import java.io.OutputStreamWriter +import java.io.PrintStream +import java.io.PrintWriter +import java.io.UnsupportedEncodingException +import java.io.Writer +import java.nio.charset.Charset +import java.nio.charset.IllegalCharsetNameException +import java.nio.charset.UnsupportedCharsetException + +internal fun openHost( + path: String, + mode: Int, +): ParcelFileDescriptor { + val descriptor = + try { + GuardContext.host().open(path, mode) + } catch (e: HostIOException) { + throw GuardErrors.open(e) + } + // java.io refuses a folder even for reading (IoBridge.open); a host may hand one out. + if (OsConstants.S_ISDIR(Os.fstat(descriptor.fileDescriptor).st_mode)) { + descriptor.close() + throw GuardErrors.open(HostIOException("EISDIR", path, "is a directory")) + } + return descriptor +} + +internal fun charsetNamed(name: String): Charset = + try { + Charset.forName(name) + } catch (e: IllegalCharsetNameException) { + throw UnsupportedEncodingException(name) + } catch (e: UnsupportedCharsetException) { + throw UnsupportedEncodingException(name) + } + +/** `java.io.FileInputStream` over a descriptor the host opened; [getChannel] is a real read-only `FileChannel`. */ +class GuardFileInputStream private constructor(pfd: ParcelFileDescriptor) : ParcelFileDescriptor.AutoCloseInputStream(pfd) { + @Throws(FileNotFoundException::class) + constructor(path: String) : this(openHost(path, HostFileMode.READ)) + + @Throws(FileNotFoundException::class) + constructor(file: File) : this(file.path) + + constructor(descriptor: FileDescriptor) : this(ParcelFileDescriptor.dup(descriptor)) +} + +/** `java.io.FileOutputStream` over a descriptor the host opened; [getChannel] is a real write-only `FileChannel`. */ +class GuardFileOutputStream private constructor(pfd: ParcelFileDescriptor) : ParcelFileDescriptor.AutoCloseOutputStream(pfd) { + @Throws(FileNotFoundException::class) + constructor(path: String, append: Boolean) : this(openHost(path, if (append) HostFileMode.APPEND else HostFileMode.WRITE)) + + @Throws(FileNotFoundException::class) + constructor(path: String) : this(path, false) + + @Throws(FileNotFoundException::class) + constructor(file: File, append: Boolean) : this(file.path, append) + + @Throws(FileNotFoundException::class) + constructor(file: File) : this(file.path, false) + + constructor(descriptor: FileDescriptor) : this(ParcelFileDescriptor.dup(descriptor)) +} + +/** + * `java.io.FileReader` for scripts. It is a real `FileReader`; reading goes to a reader over the host's descriptor, + * which also lets it take any charset. + */ +class GuardFileReader private constructor( + pfd: ParcelFileDescriptor, + charset: Charset, +) : FileReader(pfd.fileDescriptor) { + private val reader = InputStreamReader(ParcelFileDescriptor.AutoCloseInputStream(pfd), charset) + + @Throws(FileNotFoundException::class) + constructor(path: String) : this(openHost(path, HostFileMode.READ), Charset.defaultCharset()) + + @Throws(FileNotFoundException::class) + constructor(file: File) : this(file.path) + + @Throws(FileNotFoundException::class) + constructor(path: String, charset: Charset) : this(openHost(path, HostFileMode.READ), charset) + + @Throws(FileNotFoundException::class) + constructor(file: File, charset: Charset) : this(file.path, charset) + + constructor(descriptor: FileDescriptor) : this(ParcelFileDescriptor.dup(descriptor), Charset.defaultCharset()) + + override fun read() = reader.read() + + override fun read( + buffer: CharArray, + offset: Int, + length: Int, + ) = reader.read(buffer, offset, length) + + override fun ready() = reader.ready() + + override fun getEncoding(): String? = reader.encoding + + override fun close() = reader.close() +} + +/** `java.io.FileWriter` for scripts, on the same terms as [GuardFileReader]. */ +class GuardFileWriter private constructor( + pfd: ParcelFileDescriptor, + charset: Charset, +) : FileWriter(pfd.fileDescriptor) { + private val writer = OutputStreamWriter(ParcelFileDescriptor.AutoCloseOutputStream(pfd), charset) + + @Throws(java.io.IOException::class) + constructor(path: String, append: Boolean) : this(open(path, append), Charset.defaultCharset()) + + @Throws(java.io.IOException::class) + constructor(path: String) : this(path, false) + + @Throws(java.io.IOException::class) + constructor(file: File, append: Boolean) : this(file.path, append) + + @Throws(java.io.IOException::class) + constructor(file: File) : this(file.path, false) + + @Throws(java.io.IOException::class) + constructor(path: String, charset: Charset) : this(open(path, false), charset) + + @Throws(java.io.IOException::class) + constructor(path: String, charset: Charset, append: Boolean) : this(open(path, append), charset) + + @Throws(java.io.IOException::class) + constructor(file: File, charset: Charset) : this(file.path, charset) + + @Throws(java.io.IOException::class) + constructor(file: File, charset: Charset, append: Boolean) : this(file.path, charset, append) + + constructor(descriptor: FileDescriptor) : this(ParcelFileDescriptor.dup(descriptor), Charset.defaultCharset()) + + override fun write(c: Int) = writer.write(c) + + override fun write( + buffer: CharArray, + offset: Int, + length: Int, + ) = writer.write(buffer, offset, length) + + override fun write( + text: String, + offset: Int, + length: Int, + ) = writer.write(text, offset, length) + + override fun flush() = writer.flush() + + override fun getEncoding(): String? = writer.encoding + + override fun close() = writer.close() + + private companion object { + fun open( + path: String, + append: Boolean, + ) = openHost(path, if (append) HostFileMode.APPEND else HostFileMode.WRITE) + } +} + +private fun fileWriter( + path: String, + charset: Charset, +): Writer = BufferedWriter(OutputStreamWriter(GuardFileOutputStream(path), charset)) + +/** `java.io.PrintWriter`; the constructors that take a file name or a `File` write through the host. */ +class GuardPrintWriter : PrintWriter { + constructor(out: Writer) : super(out) + + constructor(out: Writer, autoFlush: Boolean) : super(out, autoFlush) + + constructor(out: OutputStream) : super(out) + + constructor(out: OutputStream, autoFlush: Boolean) : super(out, autoFlush) + + constructor(out: OutputStream, autoFlush: Boolean, charset: Charset) : super(BufferedWriter(OutputStreamWriter(out, charset)), autoFlush) + + @Throws(FileNotFoundException::class) + constructor(fileName: String) : super(fileWriter(fileName, Charset.defaultCharset()), false) + + @Throws(FileNotFoundException::class, UnsupportedEncodingException::class) + constructor(fileName: String, csn: String) : super(fileWriter(fileName, charsetNamed(csn)), false) + + @Throws(java.io.IOException::class) + constructor(fileName: String, charset: Charset) : super(fileWriter(fileName, charset), false) + + @Throws(FileNotFoundException::class) + constructor(file: File) : this(file.path) + + @Throws(FileNotFoundException::class, UnsupportedEncodingException::class) + constructor(file: File, csn: String) : this(file.path, csn) + + @Throws(java.io.IOException::class) + constructor(file: File, charset: Charset) : this(file.path, charset) +} + +/** `java.io.PrintStream`; the constructors that take a file name or a `File` write through the host. */ +class GuardPrintStream : PrintStream { + constructor(out: OutputStream) : super(out) + + constructor(out: OutputStream, autoFlush: Boolean) : super(out, autoFlush) + + @Throws(UnsupportedEncodingException::class) + constructor(out: OutputStream, autoFlush: Boolean, encoding: String) : super(out, autoFlush, encoding) + + constructor(out: OutputStream, autoFlush: Boolean, charset: Charset) : super(out, autoFlush, charset.name()) + + @Throws(FileNotFoundException::class) + constructor(fileName: String) : super(GuardFileOutputStream(fileName), false) + + @Throws(FileNotFoundException::class, UnsupportedEncodingException::class) + constructor(fileName: String, csn: String) : super(GuardFileOutputStream(fileName), false, charsetNamed(csn).name()) + + @Throws(java.io.IOException::class) + constructor(fileName: String, charset: Charset) : super(GuardFileOutputStream(fileName), false, charset.name()) + + @Throws(FileNotFoundException::class) + constructor(file: File) : this(file.path) + + @Throws(FileNotFoundException::class, UnsupportedEncodingException::class) + constructor(file: File, csn: String) : this(file.path, csn) + + @Throws(java.io.IOException::class) + constructor(file: File, charset: Charset) : this(file.path, charset) +} diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardZip.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardZip.kt new file mode 100644 index 0000000..5b3fbc0 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardZip.kt @@ -0,0 +1,395 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import com.xfl.msgbot.plugin.api.engine.HostFileMode +import java.io.Closeable +import java.io.EOFException +import java.io.File +import java.io.IOException +import java.io.InputStream +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.channels.FileChannel +import java.nio.charset.Charset +import java.util.Calendar +import java.util.Collections +import java.util.Enumeration +import java.util.jar.JarEntry +import java.util.jar.JarFile +import java.util.jar.Manifest +import java.util.stream.Stream +import java.util.zip.Inflater +import java.util.zip.InflaterInputStream +import java.util.zip.ZipEntry +import java.util.zip.ZipException + +/** + * `java.util.zip.ZipFile` for scripts. The real class opens the path itself, so this one reads the archive through a + * descriptor of the host: it reads the central directory like the real class does, so sizes, comments and random + * access to entries are the same. Encrypted entries and compression methods other than stored and deflated are refused, + * as by the real class. + */ +open class GuardZipFile( + private val name: String, + mode: Int, + private val charset: Charset, +) : Closeable { + // Like the real class on Android, a missing archive is a java.nio.file exception. + private val channel: FileChannel = + GuardRandomAccessFile( + try { + GuardContext.host().open(name, HostFileMode.READ) + } catch (e: HostIOException) { + throw GuardErrors.nio(e) + }, + ).channel + private val entries = LinkedHashMap() + private val offsets = HashMap() + private val encrypted = HashSet() + private var comment: String? = null + + @Volatile private var closed = false + + @Throws(IOException::class) + constructor(name: String) : this(name, OPEN_READ, Charsets.UTF_8) + + @Throws(IOException::class) + constructor(file: File) : this(file.path) + + @Throws(IOException::class) + constructor(file: File, mode: Int) : this(file.path, mode, Charsets.UTF_8) + + @Throws(IOException::class) + constructor(name: String, charset: Charset) : this(name, OPEN_READ, charset) + + @Throws(IOException::class) + constructor(file: File, charset: Charset) : this(file.path, OPEN_READ, charset) + + @Throws(IOException::class) + constructor(file: File, mode: Int, charset: Charset) : this(file.path, mode, charset) + + init { + require((mode and OPEN_READ) != 0 && (mode and (OPEN_READ or OPEN_DELETE).inv()) == 0) { "Illegal mode: 0x${Integer.toHexString(mode)}" } + try { + readDirectory() + } catch (e: Exception) { + channel.close() + throw if (e is ZipException) e else ZipException(e.message ?: "zip file is empty").apply { initCause(e) } + } + if ((mode and OPEN_DELETE) != 0) GuardContext.current().deleteOnExit(name) + } + + private fun read( + at: Long, + length: Int, + ): ByteBuffer { + val buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN) + while (buffer.hasRemaining()) { + if (channel.read(buffer, at + buffer.position()) < 0) throw EOFException() + } + return buffer.flip() as ByteBuffer + } + + private fun ByteBuffer.u16(at: Int) = getShort(at).toInt() and 0xffff + + private fun ByteBuffer.u32(at: Int) = getInt(at).toLong() and 0xffffffffL + + private fun readDirectory() { + val size = channel.size() + if (size == 0L) throw ZipException("zip file is empty") + if (size < END_SIZE) throw ZipException("zip END header not found") + val tailLength = minOf(size, (END_SIZE + 0xffff).toLong()).toInt() + val tail = read(size - tailLength, tailLength) + var end = -1 + for (i in tailLength - END_SIZE downTo 0) { + if (tail.getInt(i) == END_SIGNATURE) { + end = i + break + } + } + if (end < 0) throw ZipException("zip END header not found") + var count = tail.u16(end + 10).toLong() + var directoryOffset = tail.u32(end + 16) + val commentLength = tail.u16(end + 20) + if (commentLength > 0 && end + END_SIZE + commentLength <= tailLength) { + comment = String(ByteArray(commentLength).also { tail.position(end + END_SIZE); tail.get(it) }, charset) + } + val endAt = size - tailLength + end + if ((count == 0xffffL || directoryOffset == 0xffffffffL) && endAt >= 20) { + val locator = read(endAt - 20, 20) + if (locator.getInt(0) == ZIP64_LOCATOR_SIGNATURE) { + val record = read(locator.getLong(8), 56) + if (record.getInt(0) != ZIP64_END_SIGNATURE) throw ZipException("invalid zip64 END header") + count = record.getLong(32) + directoryOffset = record.getLong(48) + } + } + var at = directoryOffset + repeat(count.toInt()) { + val header = read(at, CENTRAL_SIZE) + if (header.getInt(0) != CENTRAL_SIGNATURE) throw ZipException("invalid CEN header (bad signature)") + val flags = header.u16(8) + val nameLength = header.u16(28) + val extraLength = header.u16(30) + val commentLength = header.u16(32) + val variable = read(at + CENTRAL_SIZE, nameLength + extraLength + commentLength) + val bytes = ByteArray(variable.limit()).also { variable.get(it) } + val nameCharset = if ((flags and 0x800) != 0) Charsets.UTF_8 else charset + val entry = ZipEntry(String(bytes, 0, nameLength, nameCharset)) + entry.method = header.u16(10) + dosToMillis(header.u32(12)).takeIf { it != -1L }?.let { entry.time = it } + entry.crc = header.u32(16) + var compressed = header.u32(20) + var plain = header.u32(24) + var local = header.u32(42) + val extra = bytes.copyOfRange(nameLength, nameLength + extraLength) + if (extra.isNotEmpty()) { + zip64(extra, plain == 0xffffffffL, compressed == 0xffffffffL, local == 0xffffffffL)?.let { (p, c, l) -> + plain = p ?: plain + compressed = c ?: compressed + local = l ?: local + } + entry.extra = extra + } + entry.size = plain + entry.compressedSize = compressed + if (commentLength > 0) entry.comment = String(bytes, nameLength + extraLength, commentLength, nameCharset) + if ((flags and 1) != 0) encrypted += entry.name + entries.putIfAbsent(entry.name, entry) + offsets[entry.name] = local + at += CENTRAL_SIZE + nameLength + extraLength + commentLength + } + } + + private fun zip64( + extra: ByteArray, + needPlain: Boolean, + needCompressed: Boolean, + needLocal: Boolean, + ): Triple? { + val buffer = ByteBuffer.wrap(extra).order(ByteOrder.LITTLE_ENDIAN) + while (buffer.remaining() >= 4) { + val id = buffer.short.toInt() and 0xffff + val length = buffer.short.toInt() and 0xffff + if (length > buffer.remaining()) return null + if (id != 1) { + buffer.position(buffer.position() + length) + continue + } + val end = buffer.position() + length + fun next(need: Boolean): Long? = if (need && buffer.position() + 8 <= end) buffer.long else null + return Triple(next(needPlain), next(needCompressed), next(needLocal)) + } + return null + } + + private fun dosToMillis(dos: Long): Long { + if (dos == 0L) return -1 + return Calendar.getInstance().run { + clear() + set(((dos shr 25) and 0x7f).toInt() + 1980, ((dos shr 21) and 0x0f).toInt() - 1, ((dos shr 16) and 0x1f).toInt(), ((dos shr 11) and 0x1f).toInt(), ((dos shr 5) and 0x3f).toInt(), ((dos shl 1) and 0x3e).toInt()) + timeInMillis + } + } + + private fun ensureOpen() { + if (closed) throw IllegalStateException("zip file closed") + } + + fun entries(): Enumeration { + ensureOpen() + return Collections.enumeration(entries.values.toList()) + } + + fun stream(): Stream { + ensureOpen() + return entries.values.toList().stream() + } + + fun getEntry(name: String): ZipEntry? { + ensureOpen() + return entries[name] ?: entries["$name/"] + } + + @Throws(IOException::class) + fun getInputStream(entry: ZipEntry): InputStream? { + ensureOpen() + val found = entries[entry.name] ?: return null + if (found.name in encrypted) throw ZipException("invalid CEN header (encrypted entry)") + val local = read(offsets.getValue(found.name), LOCAL_SIZE) + if (local.getInt(0) != LOCAL_SIGNATURE) throw ZipException("invalid LOC header (bad signature)") + val data = offsets.getValue(found.name) + LOCAL_SIZE + local.u16(26) + local.u16(28) + val raw = Range(data, found.compressedSize) + return when (found.method) { + ZipEntry.STORED -> raw + ZipEntry.DEFLATED -> + object : InflaterInputStream(raw, Inflater(true), 8192) { + private var eof = false + + // A raw inflater may want one byte past the data; the real ZipFile gives it a zero too. + override fun fill() { + if (eof) throw EOFException("Unexpected end of ZLIB input stream") + len = `in`.read(buf, 0, buf.size) + if (len == -1) { + buf[0] = 0 + len = 1 + eof = true + } + inf.setInput(buf, 0, len) + } + + override fun available(): Int = if (inf.finished()) 0 else maxOf(0L, found.size - inf.bytesWritten).coerceAtMost(Int.MAX_VALUE.toLong()).toInt() + + override fun close() { + super.close() + inf.end() + } + } + else -> throw ZipException("invalid compression method") + } + } + + private inner class Range( + private var at: Long, + private var left: Long, + ) : InputStream() { + override fun read(): Int { + val one = ByteArray(1) + return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xff + } + + override fun read( + buffer: ByteArray, + offset: Int, + length: Int, + ): Int { + ensureOpen() + if (left <= 0) return -1 + if (length == 0) return 0 + val count = channel.read(ByteBuffer.wrap(buffer, offset, minOf(length.toLong(), left).toInt()), at) + if (count <= 0) return -1 + at += count + left -= count + return count + } + + override fun available() = left.coerceAtMost(Int.MAX_VALUE.toLong()).toInt() + + override fun skip(n: Long): Long = minOf(n, left).coerceAtLeast(0).also { + at += it + left -= it + } + } + + fun getName(): String = name + + fun size(): Int { + ensureOpen() + return entries.size + } + + fun getComment(): String? { + ensureOpen() + return comment + } + + override fun close() { + if (!closed) { + closed = true + channel.close() + } + } + + override fun toString() = name + + companion object { + const val OPEN_READ = 0x1 + const val OPEN_DELETE = 0x4 + + // java.util.zip.ZipConstants, which ZipFile and JarFile expose. + const val LOCSIG = 0x04034b50L + const val EXTSIG = 0x08074b50L + const val CENSIG = 0x02014b50L + const val ENDSIG = 0x06054b50L + const val LOCHDR = 30 + const val EXTHDR = 16 + const val CENHDR = 46 + const val ENDHDR = 22 + const val LOCVER = 4 + const val LOCFLG = 6 + const val LOCHOW = 8 + const val LOCTIM = 10 + const val LOCCRC = 14 + const val LOCSIZ = 18 + const val LOCLEN = 22 + const val LOCNAM = 26 + const val LOCEXT = 28 + const val EXTCRC = 4 + const val EXTSIZ = 8 + const val EXTLEN = 12 + const val CENVEM = 4 + const val CENVER = 6 + const val CENFLG = 8 + const val CENHOW = 10 + const val CENTIM = 12 + const val CENCRC = 16 + const val CENSIZ = 20 + const val CENLEN = 24 + const val CENNAM = 28 + const val CENEXT = 30 + const val CENCOM = 32 + const val CENDSK = 34 + const val CENATT = 36 + const val CENATX = 38 + const val CENOFF = 42 + const val ENDSUB = 8 + const val ENDTOT = 10 + const val ENDSIZ = 12 + const val ENDOFF = 16 + const val ENDCOM = 20 + + private const val END_SIGNATURE = 0x06054b50 + private const val ZIP64_END_SIGNATURE = 0x06064b50 + private const val ZIP64_LOCATOR_SIGNATURE = 0x07064b50 + private const val CENTRAL_SIGNATURE = 0x02014b50 + private const val LOCAL_SIGNATURE = 0x04034b50 + private const val END_SIZE = 22 + private const val CENTRAL_SIZE = 46 + private const val LOCAL_SIZE = 30 + } +} + +/** `java.util.jar.JarFile` on the same terms as [GuardZipFile]; signatures are not checked. */ +class GuardJarFile( + name: String, + verify: Boolean, + mode: Int, +) : GuardZipFile(name, mode, Charsets.UTF_8) { + @Throws(IOException::class) + constructor(name: String) : this(name, true, OPEN_READ) + + @Throws(IOException::class) + constructor(name: String, verify: Boolean) : this(name, verify, OPEN_READ) + + @Throws(IOException::class) + constructor(file: File) : this(file.path) + + @Throws(IOException::class) + constructor(file: File, verify: Boolean) : this(file.path, verify) + + @Throws(IOException::class) + constructor(file: File, verify: Boolean, mode: Int) : this(file.path, verify, mode) + + @Throws(IOException::class) + fun getManifest(): Manifest? = getEntry(JarFile.MANIFEST_NAME)?.let { entry -> getInputStream(entry)?.use { Manifest(it) } } + + fun getJarEntry(name: String): JarEntry? = getEntry(name)?.let { JarEntry(it) } + + companion object { + const val MANIFEST_NAME = JarFile.MANIFEST_NAME + } +} diff --git a/guard/src/test/java/com/xfl/msgbot/plugin/guard/ClassRulesTest.kt b/guard/src/test/java/com/xfl/msgbot/plugin/guard/ClassRulesTest.kt new file mode 100644 index 0000000..d001252 --- /dev/null +++ b/guard/src/test/java/com/xfl/msgbot/plugin/guard/ClassRulesTest.kt @@ -0,0 +1,81 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import com.xfl.msgbot.plugin.api.engine.ClassAccess +import com.xfl.msgbot.plugin.api.engine.ClassAccess.Preset +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ClassRulesTest { + private val engine = listOf("com.caoccao.javet.") + + @Test + fun `the safe preset keeps ordinary classes and refuses the ways around the guard`() { + val rules = ClassRules(ClassAccess(), engine) + assertFalse(rules.isDenied("java.util.ArrayList")) + assertFalse(rules.isDenied("java.lang.reflect.Modifier")) + assertTrue(rules.isDenied("java.lang.reflect.Proxy")) + assertTrue(rules.isDenied("java.lang.invoke.MethodHandles")) + assertTrue(rules.isDenied("dalvik.system.DexClassLoader")) + assertTrue(rules.isDenied("com.caoccao.javet.interop.V8Runtime")) + assertTrue(rules.isEngineInternal("com.caoccao.javet.interop.V8Runtime")) + assertFalse(rules.isEngineInternal("com.xfl.msgbot.plugin.guard.GuardFile")) + assertTrue(rules.isDenied("com.xfl.msgbot.plugin.ipc.PluginService")) + assertFalse(rules.allows("java.lang.reflect.Method")) + } + + @Test + fun `the guard's own objects may be held`() { + assertFalse(ClassRules(ClassAccess(), engine).isDenied("com.xfl.msgbot.plugin.guard.GuardFile")) + } + + @Test + fun `the wide preset lets real reflection and processes through`() { + val rules = ClassRules(ClassAccess(Preset.WIDE), engine) + assertTrue(rules.allows("java.lang.reflect.Method")) + assertFalse(rules.isDenied("java.lang.Process")) + assertTrue(rules.isDenied("java.lang.reflect.Proxy")) + } + + @Test + fun `custom lists add and take away, and deny wins`() { + val rules = ClassRules(ClassAccess(Preset.CUSTOM, allow = listOf("java.lang.reflect.*", "dalvik.system.PathClassLoader"), deny = listOf("java.lang.reflect.Proxy", "java.net.*")), engine) + assertFalse(rules.isDenied("java.lang.reflect.Method")) + assertTrue(rules.isDenied("java.lang.reflect.Proxy")) + assertFalse(rules.isDenied("dalvik.system.PathClassLoader")) + assertTrue(rules.isDenied("java.net.Socket")) + } + + @Test + fun `lists accept commas, spaces and trailing stars`() { + val rules = ClassRules(ClassAccess(Preset.CUSTOM, allow = listOf("java.lang.invoke*, dalvik.system.DexFile;sun.misc.Unsafe")), engine) + assertFalse(rules.isDenied("java.lang.invoke.MethodHandles")) + assertFalse(rules.isDenied("dalvik.system.DexFile")) + assertFalse(rules.isDenied("sun.misc.Unsafe")) + } + + @Test + fun `without restrictions only the engine and the deny list are refused`() { + val rules = ClassRules(ClassAccess(restrictions = false, deny = listOf("java.net.Socket")), engine) + assertFalse(rules.isDenied("java.lang.reflect.Proxy")) + assertTrue(rules.allows("java.lang.reflect.Method")) + assertTrue(rules.isDenied("java.net.Socket")) + assertTrue(rules.isDenied("com.caoccao.javet.interop.V8Runtime")) + } + + @Test + fun `values of JDK implementation classes may be held, ways around the guard may not`() { + val rules = ClassRules(ClassAccess(), engine) + assertFalse(rules.isDeniedValue("sun.nio.ch.FileChannelImpl")) + assertFalse(rules.isDeniedValue("sun.nio.cs.UTF_8")) + assertTrue(rules.isDenied("sun.nio.ch.FileChannelImpl")) + assertTrue(rules.isDeniedValue("java.lang.invoke.MethodHandles${'$'}Lookup")) + assertTrue(rules.isDeniedValue("dalvik.system.PathClassLoader")) + assertTrue(rules.isDeniedValue("com.caoccao.javet.interop.V8Runtime")) + } +} diff --git a/readme.md b/readme.md index 0819aca..03179bb 100644 --- a/readme.md +++ b/readme.md @@ -8,7 +8,8 @@ MessengerBotR의 플러그인 계약이다. 현재 개발 버전은 `0.1.0-SNAPS |---|---| | `contract` | 값, API 스키마, 표준 모듈, 엔진·제공자·도구 SPI, 대칭 RPC. Android에 의존하지 않는다. | | `android` | `PluginService`, Binder 세션, 공유 메모리 전송 | -| `tck` | 엔진과 제공자를 호스트 없이 돌려 보는 `EngineHarness`, `ProviderHarness`. JavaScript 엔진의 적합성 테스트(`JavaScriptEngineConformance`)와 제공자의 적합성 테스트(`ProviderConformance`) | +| `guard` | Java를 쓰는 엔진의 파일·클래스 가드. `File`, 스트림, `RandomAccessFile`, nio, `ZipFile` 등을 호스트 디스크립터 위의 같은 모양 클래스로 바꾸고, `ClassAccess`로 클래스 접근을 정한다. 엔진에는 이름 조회(`GuardPolicy.lookup`)와 값 변환(`GuardPolicy.replace`)만 연결하면 된다 | +| `tck` | 엔진과 제공자를 호스트 없이 돌려 보는 `EngineHarness`, `ProviderHarness`. JavaScript 엔진의 적합성 테스트(`JavaScriptEngineConformance`), Java 가드의 적합성 테스트(`JavaGuardConformance`, 기기에서 실행), 제공자의 적합성 테스트(`ProviderConformance`) | ## 구조 diff --git a/settings.gradle.kts b/settings.gradle.kts index 22a2605..5567fc5 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -21,6 +21,6 @@ rootProject.name = "PluginApi" // The contract is pure JVM so a plugin can be written against it anywhere, including on a // non-Android engine's own terms. Everything that needs Android -- the binder plumbing every -// plugin would otherwise copy -- lives in :android. :tck is the conformance suite an engine's own -// tests extend. -include(":contract", ":android", ":tck") +// plugin would otherwise copy -- lives in :android. :guard is the Java file and class guard that +// engines running Java share. :tck is the conformance suite an engine's own tests extend. +include(":contract", ":android", ":guard", ":tck") diff --git a/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/EngineHarness.kt b/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/EngineHarness.kt index fb54d34..2ac2997 100644 --- a/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/EngineHarness.kt +++ b/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/EngineHarness.kt @@ -34,6 +34,9 @@ class EngineHarness(factory: ScriptEngineFactory) : AutoCloseable { /** Host implementations by qualified name. Unlisted functions answer unknown_function. */ val functions = ConcurrentHashMap) -> CallResult>() + /** Answers [HostBridge.openFile]; null means the host serves no files. */ + @Volatile var openFile: ((path: String, mode: Int) -> Int)? = null + private val thread = EngineThread(threadName) { message, _ -> errors += message } private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "tck-host").apply { isDaemon = true } } @@ -60,6 +63,14 @@ class EngineHarness(factory: ScriptEngineFactory) : AutoCloseable { thread.post { onResult(result) } } } + + override fun openFile( + path: String, + mode: Int, + ): Int { + calls += Call("openFile", mapOf("path" to Value.VString(path), "mode" to Value.of(mode)), Thread.currentThread().name) + return (openFile ?: return super.openFile(path, mode))(path, mode) + } } override val scheduler: EngineScheduler = thread diff --git a/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/FolderFiles.kt b/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/FolderFiles.kt new file mode 100644 index 0000000..aed1033 --- /dev/null +++ b/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/FolderFiles.kt @@ -0,0 +1,168 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.tck + +import com.xfl.msgbot.plugin.api.call.CallException +import com.xfl.msgbot.plugin.api.call.CallResult +import com.xfl.msgbot.plugin.api.value.Value +import com.xfl.msgbot.plugin.api.value.asBooleanOrNull +import com.xfl.msgbot.plugin.api.value.asLongOrNull +import com.xfl.msgbot.plugin.api.value.asStringOrNull +import com.xfl.msgbot.plugin.api.value.vObject +import java.io.File +import java.nio.file.Files +import java.nio.file.LinkOption +import java.nio.file.attribute.FileTime +import java.nio.file.attribute.PosixFilePermission + +/** + * The host `fs` module and `openFile` for one project folder, as the host serves them: the project folder and the + * temporary folder may be used, every other place answers `EACCES`. Installs itself on an [EngineHarness]. + * + * @param open turns a file that passed the rules into a descriptor of this process, opened as the + * [com.xfl.msgbot.plugin.api.engine.HostFileMode] asks; on Android `ParcelFileDescriptor.open(...).detachFd()`. + */ +class FolderFiles( + root: File, + tmp: File, + private val open: (file: File, mode: Int) -> Int, +) { + val root: File = root.canonicalFile + val tmp: File = tmp.canonicalFile + + private fun fail( + errno: String, + path: String, + ): Nothing = throw CallException.failed("$errno: $path") + + /** The file a path names, after the rules; relative paths are relative to [root]. */ + fun resolve(path: String): File { + val file = (if (path.startsWith("/")) File(path) else File(root, path)).let { File(it.toURI().normalize().path.trimEnd('/').ifEmpty { "/" }) } + val parent = file.parentFile + val real = if (parent != null && parent.exists()) File(parent.canonicalFile, file.name) else file + if (!inside(real, root) && !inside(real, tmp)) fail("EACCES", path) + return file + } + + private fun inside( + file: File, + folder: File, + ) = file.path == folder.path || file.path.startsWith(folder.path + "/") + + private fun stat( + file: File, + follow: Boolean, + ): Value { + val options = if (follow) emptyArray() else arrayOf(LinkOption.NOFOLLOW_LINKS) + val path = file.toPath() + val attributes = Files.readAttributes(path, java.nio.file.attribute.BasicFileAttributes::class.java, *options) + val mode = runCatching { Files.getPosixFilePermissions(path, *options).fold(0) { mode, p -> mode or (0x100 shr PosixFilePermission.entries.indexOf(p)) } }.getOrDefault(0x1b6) + return vObject( + "name" to file.name, + "isDirectory" to attributes.isDirectory, + "isSymbolicLink" to attributes.isSymbolicLink, + "size" to attributes.size(), + "modifiedMs" to attributes.lastModifiedTime().toMillis(), + "accessedMs" to attributes.lastAccessTime().toMillis(), + "createdMs" to attributes.creationTime().toMillis(), + "mode" to mode.toLong(), + "uid" to 0L, + "gid" to 0L, + ) + } + + private fun exists(file: File) = Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS) + + private fun answer(block: () -> Any?): CallResult = CallResult.catching { Value.of(block()) } + + private fun Map.text(key: String) = this[key]?.asStringOrNull() ?: throw CallException.badArgs("'$key' is missing") + + private fun Map.flag(key: String) = this[key]?.asBooleanOrNull() == true + + fun install(harness: EngineHarness) { + val f = harness.functions + f["fs.stat"] = { a -> answer { resolve(a.text("path")).let { if (exists(it)) stat(it, a["followLinks"]?.asBooleanOrNull() != false) else null } } } + f["fs.realpath"] = { a -> answer { resolve(a.text("path")).let { if (it.exists()) resolve(it.canonicalPath).path else fail("ENOENT", a.text("path")) } } } + f["fs.tmpdir"] = { answer { tmp.path } } + f["fs.list"] = { a -> + answer { + val dir = resolve(a.text("path")) + if (!dir.exists()) fail("ENOENT", a.text("path")) + (dir.listFiles() ?: fail("ENOTDIR", a.text("path"))).map { stat(it, false) } + } + } + f["fs.access"] = { a -> + answer { + val file = resolve(a.text("path")) + if (!file.exists()) fail("ENOENT", a.text("path")) + val mode = a["mode"]?.asLongOrNull()?.toInt() ?: 0 + val ok = ((mode and 4) == 0 || file.canRead()) && ((mode and 2) == 0 || file.canWrite()) && ((mode and 1) == 0 || file.canExecute()) + if (!ok) fail("EACCES", a.text("path")) + true + } + } + f["fs.statfs"] = { a -> answer { resolve(a.text("path")).let { vObject("type" to 0L, "bsize" to 1L, "blocks" to it.totalSpace, "bfree" to it.freeSpace, "bavail" to it.usableSpace, "files" to 0L, "ffree" to 0L) } } } + f["fs.mkdir"] = { a -> + answer { + val dir = resolve(a.text("path")) + when { + dir.isDirectory -> false + dir.exists() -> fail("EEXIST", a.text("path")) + a.flag("recursive") -> dir.mkdirs() + dir.parentFile?.isDirectory != true -> fail("ENOENT", a.text("path")) + else -> dir.mkdir() + } + } + } + f["fs.remove"] = { a -> + answer { + val file = resolve(a.text("path")) + when { + !exists(file) -> false + a.flag("recursive") -> file.deleteRecursively() + file.isDirectory && !Files.isSymbolicLink(file.toPath()) && !file.list().isNullOrEmpty() -> fail("ENOTEMPTY", a.text("path")) + else -> file.delete() + } + } + } + f["fs.rename"] = { a -> + answer { + val from = resolve(a.text("from")) + val to = resolve(a.text("to")) + if (!exists(from)) fail("ENOENT", a.text("from")) + from.renameTo(to) || fail("EIO", a.text("from")) + } + } + f["fs.symlink"] = { a -> answer { Files.createSymbolicLink(resolve(a.text("path")).toPath(), File(a.text("target")).toPath()); true } } + f["fs.link"] = { a -> answer { Files.createLink(resolve(a.text("path")).toPath(), resolve(a.text("existing")).toPath()); true } } + f["fs.readlink"] = { a -> answer { Files.readSymbolicLink(resolve(a.text("path")).toPath()).toString() } } + f["fs.truncate"] = { a -> answer { java.io.RandomAccessFile(resolve(a.text("path")), "rw").use { it.setLength(a["size"]?.asLongOrNull() ?: 0) }; true } } + f["fs.chmod"] = { a -> + answer { + val mode = a["mode"]?.asLongOrNull()?.toInt() ?: 0 + Files.setPosixFilePermissions(resolve(a.text("path")).toPath(), PosixFilePermission.entries.filterIndexed { i, _ -> (mode and (0x100 shr i)) != 0 }.toSet()) + true + } + } + f["fs.utimes"] = { a -> + answer { + val file = resolve(a.text("path")) + if (!file.exists()) fail("ENOENT", a.text("path")) + Files.setLastModifiedTime(file.toPath(), FileTime.fromMillis(a["modifiedMs"]?.asLongOrNull() ?: 0)) + true + } + } + f["log.write"] = { CallResult.ok() } + harness.openFile = { path, mode -> + val file = resolve(path) + if (file.isDirectory && mode != 0) fail("EISDIR", path) + if ((mode and 4) != 0 && file.exists()) fail("EEXIST", path) + if ((mode == 0 || mode == 8) && !file.exists()) fail("ENOENT", path) + if (mode != 0 && file.parentFile?.isDirectory != true) fail("ENOENT", path) + open(file, mode) + } + } +} diff --git a/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/JavaGuardConformance.kt b/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/JavaGuardConformance.kt new file mode 100644 index 0000000..6cbc29c --- /dev/null +++ b/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/JavaGuardConformance.kt @@ -0,0 +1,236 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.tck + +import com.xfl.msgbot.plugin.api.engine.ClassAccess +import com.xfl.msgbot.plugin.api.engine.ClassAccess.Preset +import com.xfl.msgbot.plugin.api.engine.EngineContext +import com.xfl.msgbot.plugin.api.engine.LoadRequest +import com.xfl.msgbot.plugin.api.engine.ProfileScript +import com.xfl.msgbot.plugin.api.engine.ScriptEngine +import com.xfl.msgbot.plugin.api.standard.StandardApi +import com.xfl.msgbot.plugin.api.value.Value +import org.junit.After +import org.junit.Before +import org.junit.Test +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Conformance tests for a JavaScript engine that lets scripts use Java (``): files only through the + * host under the project's rules, the project's [ClassAccess], and ordinary Java working as before. It runs on a device, + * because the guard opens the host's descriptors. Subclass it in an engine's `androidTest` sources. + */ +abstract class JavaGuardConformance { + /** Called on the engine thread. */ + protected abstract fun createEngine(context: EngineContext): ScriptEngine + + /** A JavaScript expression for the Java class [name] in this engine, such as `Java.type('java.io.File')`. */ + protected abstract fun javaClass(name: String): String + + /** A folder of this test process the suite may fill and delete. */ + protected abstract fun scratchFolder(): File + + /** A descriptor of this process for [file], opened as the [com.xfl.msgbot.plugin.api.engine.HostFileMode] [mode] asks. */ + protected abstract fun openDescriptor( + file: File, + mode: Int, + ): Int + + /** + * Whether Java objects the script receives are replaced on the way, so `file.getClass()` describes the class and + * cannot reach the real one. An engine that cannot rewrite results (GraalJS) makes those objects unusable instead. + */ + protected open val replacesResults: Boolean = true + + protected lateinit var harness: EngineHarness + protected lateinit var files: FolderFiles + protected lateinit var outside: File + private lateinit var top: File + + private val helpers = + """ + function t(f) { try { var v = f(); return 'ok:' + v; } catch (e) { return 'threw:' + e; } } + function has(f) { try { var c = f(); return c === undefined || c === null ? 'none' : 'some'; } catch (e) { return 'none'; } } + """.trimIndent() + + @Before + fun openHarness() { + top = File(scratchFolder(), "java-guard-tck").apply { deleteRecursively() } + val project = File(top, "project").apply { mkdirs() } + val tmp = File(top, "tmp").apply { mkdirs() } + outside = File(top, "outside.txt").apply { writeText("secret") }.canonicalFile + harness = EngineHarness(::createEngine) + files = FolderFiles(project, tmp, ::openDescriptor).also { it.install(harness) } + } + + @After + fun closeHarness() { + harness.close() + top.deleteRecursively() + } + + protected fun load( + access: ClassAccess = ClassAccess.DEFAULT, + entry: String = "", + ) = harness.load( + LoadRequest("javascript", listOf(StandardApi.Log, StandardApi.Fs), ProfileScript("profile.js", helpers), "main.js", mapOf("main.js" to entry), classAccess = access), + ) + + private fun j(name: String) = javaClass(name) + + private val raw = ArrayList() + + // A JavaScript error is compared as "threw"; its text goes into the failure message. + private fun text(source: String): String { + val answer = (harness.eval(source) as? Value.VString)?.value ?: error("Expected a string from: $source") + raw += answer + return if (answer.startsWith("threw:")) "threw" else answer + } + + private fun assertEquals( + expected: Any?, + actual: Any?, + ) = kotlin.test.assertEquals(expected, actual, raw.lastOrNull()) + + private fun warnings(): List = harness.calls.filter { it.function == "log.write" }.map { (it.args["message"] as Value.VString).value } + + @Test + fun filesInTheProjectWork() { + load() + val file = j("java.io.File") + assertEquals( + "ok:true", + text("t(function () { var d = new ($file)('data/sub'); return d.mkdirs(); })"), + ) + text("t(function () { var w = new (${j("java.io.FileWriter")})('data/sub/a.txt'); w.write('hello'); w.close(); return 1; })") + assertEquals("hello", File(files.root, "data/sub/a.txt").readText()) + assertEquals("ok:5", text("t(function () { return new ($file)('data/sub/a.txt').length(); })")) + assertEquals("ok:a.txt", text("t(function () { return new ($file)('data/sub').list()[0]; })")) + assertEquals( + "ok:hello", + text("t(function () { var r = new (${j("java.io.BufferedReader")})(new (${j("java.io.FileReader")})('data/sub/a.txt')); var s = r.readLine(); r.close(); return s; })"), + ) + assertEquals("ok:${files.root.path}/x", text("t(function () { return new ($file)('x').getAbsolutePath(); })")) + } + + @Test + fun randomAccessAndChannelsWork() { + load() + assertEquals( + "ok:8 4", + text( + """ + t(function () { + var f = new (${j("java.io.RandomAccessFile")})('r.bin', 'rw'); + f.writeLong(42); f.setLength(8); f.seek(4); + var answer = f.getChannel().size() + ' ' + f.getFilePointer(); + f.close(); + return answer; + }) + """.trimIndent(), + ), + ) + assertEquals(8L, File(files.root, "r.bin").length()) + } + + @Test + fun nioWorks() { + load() + val paths = j("java.nio.file.Paths") + val nioFiles = j("java.nio.file.Files") + assertEquals( + "ok:3 true", + text( + """ + t(function () { + var p = $paths.get('n/lines.txt'); + $nioFiles.createDirectories(p.getParent()); + $nioFiles.writeString(p, 'a\nb'); + return $nioFiles.size(p) + ' ' + $nioFiles.exists(p); + }) + """.trimIndent(), + ), + ) + assertEquals("a\nb", File(files.root, "n/lines.txt").readText()) + } + + @Test + fun placesOutsideTheRulesAreRefused() { + load() + val path = outside.path + assertEquals("threw", text("t(function () { return new (${j("java.io.File")})('$path').exists(); })")) + assertEquals("threw", text("t(function () { return new (${j("java.io.FileInputStream")})('$path').read(); })")) + assertEquals("threw", text("t(function () { return ${j("java.nio.file.Files")}.readAllBytes(${j("java.nio.file.Paths")}.get('$path')).length; })")) + assertEquals("threw", text("t(function () { return new (${j("java.io.RandomAccessFile")})('$path', 'r').length(); })")) + assertEquals("threw", text("t(function () { return new (${j("java.io.File")})('../outside.txt').length(); })")) + assertEquals("secret", outside.readText()) + assertEquals(1, warnings().count { it.contains(path) }, warnings().toString()) + } + + @Test + fun temporaryFilesGoToTheHostsTemporaryFolder() { + load() + val made = text("t(function () { return ${j("java.io.File")}.createTempFile('abc', '.tmp').getParent(); })") + assertEquals("ok:${files.tmp.path}", made) + } + + @Test + fun ordinaryJavaWorksAsBefore() { + load() + assertEquals("ok:2", text("t(function () { var n = new (${j("java.util.concurrent.atomic.AtomicInteger")})(1); n.incrementAndGet(); return n.get(); })")) + assertEquals("ok:36", text("t(function () { return ${j("java.util.UUID")}.randomUUID().toString().length; })")) + assertEquals("ok:ab", text("t(function () { var b = new (${j("java.lang.StringBuilder")})(); b.append('a'); b.append('b'); return b.toString(); })")) + assertEquals("ok:3", text("t(function () { return ${j("java.lang.Math")}.max(2, 3); })")) + assertEquals("ok:true", text("t(function () { return ${j("java.lang.System")}.currentTimeMillis() > 0; })")) + } + + @Test + fun theWaysAroundTheGuardAreClosed() { + load() + assertEquals("none", text("has(function () { return ${j("java.lang.reflect.Proxy")}; })")) + assertEquals("none", text("has(function () { return ${j("dalvik.system.DexClassLoader")}; })")) + assertEquals("none", text("has(function () { return ${j("com.xfl.msgbot.plugin.guard.GuardContext")}; })")) + // The command as one string: engines differ in how they pass a JavaScript array as String[]. + assertEquals("threw", text("t(function () { return ${j("java.lang.Runtime")}.getRuntime().exec('sh -c id'); })")) + assertEquals( + "threw", + text("t(function () { var r = ${j("java.lang.Class")}.forName('java.lang.Runtime').getMethod('getRuntime').invoke(null); return r.exec('sh -c id').waitFor(); })"), + ) + assertTrue(warnings().any { it.contains("java.lang.reflect.Proxy") }, warnings().toString()) + } + + @Test + fun aFileDescribesItselfAsAFile() { + if (!replacesResults) return + load() + assertEquals("ok:java.io.File", text("t(function () { return new (${j("java.io.File")})('x').getClass().getName(); })")) + assertEquals("threw", text("t(function () { return new (${j("java.io.File")})('x').getClass().getClassLoader().loadClass('java.lang.reflect.Proxy').getName(); })")) + } + + @Test + fun theOffPresetHasNoJava() { + load(ClassAccess(Preset.OFF)) + assertEquals("none", text("has(function () { return ${j("java.util.UUID")}; })")) + assertEquals("none", text("has(function () { return ${j("java.io.File")}; })")) + } + + @Test + fun theProjectsListsAddAndTakeAway() { + load(ClassAccess(Preset.CUSTOM, allow = listOf("java.lang.reflect.Proxy"), deny = listOf("java.util.UUID"))) + assertEquals("some", text("has(function () { return ${j("java.lang.reflect.Proxy")}; })")) + assertEquals("none", text("has(function () { return ${j("java.util.UUID")}; })")) + } + + @Test + fun withoutRestrictionsClassesAreOpenButFilesStayGuarded() { + load(ClassAccess(restrictions = false)) + assertEquals("some", text("has(function () { return ${j("java.lang.reflect.Proxy")}; })")) + assertEquals("threw", text("t(function () { return new (${j("java.io.File")})('${outside.path}').exists(); })")) + assertEquals("ok:true", text("t(function () { return new (${j("java.io.File")})('in.txt').createNewFile(); })")) + } +}