From 03bbcb276274f93d94f4b1275f32c85eabe53304 Mon Sep 17 00:00:00 2001 From: "nenka.lab" Date: Sun, 15 Nov 2026 18:36:09 +0900 Subject: [PATCH] feat: open SQLite databases within the file rules when the engine app has all files access --- .../msgbot/plugin/guard/GuardBoundaryTest.kt | 38 ++++- .../msgbot/plugin/guard/GuardParityTest.kt | 9 ++ .../xfl/msgbot/plugin/guard/GuardPolicy.kt | 1 + .../xfl/msgbot/plugin/guard/GuardSQLite.kt | 147 ++++++++++++++++++ .../xfl/msgbot/plugin/guard/GuardSession.kt | 30 +++- readme.md | 2 +- .../msgbot/plugin/tck/JavaGuardConformance.kt | 12 ++ 7 files changed, 235 insertions(+), 4 deletions(-) create mode 100644 guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardSQLite.kt 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 index 07f359c..2ea0106 100644 --- a/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardBoundaryTest.kt +++ b/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardBoundaryTest.kt @@ -47,8 +47,11 @@ class GuardBoundaryTest { use(ClassAccess.DEFAULT) } - private fun use(access: ClassAccess) { - session = GuardSession(host, ClassRules(access, listOf("com.example.engine."))) + private fun use( + access: ClassAccess, + storageAccess: Boolean = false, + ) { + session = GuardSession(host, ClassRules(access, listOf("com.example.engine.")), storageAccess = { storageAccess }) val old = GuardContext.swap(session) if (!::top.isInitialized || previous == null) previous = old } @@ -283,4 +286,35 @@ class GuardBoundaryTest { buffer.put("data".toByteArray()).putInt(data) return buffer.array() } + + @Test + fun sqliteWithoutStorageAccessPointsToTheDbModule() { + val error = assertFailsWith { GuardSQLiteDatabase.openOrCreateDatabase("a.db", null) } + assertTrue(error.message!!.contains("db module"), error.message) + assertFalse(File(project, "a.db").exists()) + GuardSQLiteDatabase.openOrCreateDatabase(":memory:", null).use { assertTrue(it.isOpen) } + GuardSQLiteDatabase.create(null).use { assertTrue(it.isOpen) } + assertFailsWith { GuardSQLiteDatabase.openOrCreateDatabase("b.db", null) } + assertEquals(1, host.logs.count { it.contains("SQLite") }, host.logs.toString()) + } + + @Test + fun sqliteWithStorageAccessFollowsTheFileRules() { + use(ClassAccess.DEFAULT, storageAccess = true) + GuardSQLiteDatabase.openOrCreateDatabase("a.db", null).use { db -> + db.execSQL("create table t(v text)") + db.execSQL("insert into t values ('x')") + } + assertTrue(File(project, "a.db").exists()) + GuardSQLiteDatabase.openDatabase(File(project, "a.db").path, null, GuardSQLiteDatabase.OPEN_READONLY).use { db -> + db.rawQuery("select v from t", null).use { assertTrue(it.moveToFirst()); assertEquals("x", it.getString(0)) } + } + val secret = File(top, "secret.db").path + assertFailsWith { GuardSQLiteDatabase.openOrCreateDatabase(secret, null) } + assertFalse(File(secret).exists()) + assertFailsWith { GuardSQLiteDatabase.openOrCreateDatabase(GuardFile("../x.db"), null) } + assertTrue(GuardSQLiteDatabase.deleteDatabase(GuardFile("a.db"))) + assertFalse(File(project, "a.db").exists()) + assertEquals(1, host.logs.count { it.contains(secret) }, host.logs.toString()) + } } 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 index be093ea..d1307ca 100644 --- a/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardParityTest.kt +++ b/guard/src/androidTest/java/com/xfl/msgbot/plugin/guard/GuardParityTest.kt @@ -30,6 +30,11 @@ class GuardParityTest { "java.nio.file.Path", ) + // Final classes whose objects stay real: only their static members are replaced. + private val staticsOnly = setOf("android.database.sqlite.SQLiteDatabase") + + private val hiddenFields = setOf("CONFLICT_VALUES") + // Public in the class at run time but @hide in the SDK: apps cannot call them anyway. private val hidden = setOf( @@ -52,15 +57,19 @@ class GuardParityTest { for ((name, replacement) in GuardPolicy.substitutes) { if (name in skipped) continue val real = Class.forName(name) + val onlyStatic = name in staticsOnly for (constructor in real.constructors) { + if (onlyStatic) break 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 + if (onlyStatic && !Modifier.isStatic(method.modifiers)) 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) { + if (onlyStatic && !Modifier.isStatic(field.modifiers) || field.name in hiddenFields) continue runCatching { replacement.getField(field.name) }.onFailure { missing += "$name field ${field.name}" } } } 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 index 5ef44dd..61cda08 100644 --- a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardPolicy.kt +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardPolicy.kt @@ -39,6 +39,7 @@ object GuardPolicy { "java.util.Formatter" to GuardFormatter::class.java, "android.graphics.BitmapFactory" to GuardBitmapFactory::class.java, "android.media.MediaMetadataRetriever" to GuardMediaMetadataRetriever::class.java, + "android.database.sqlite.SQLiteDatabase" to GuardSQLiteDatabase::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, diff --git a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardSQLite.kt b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardSQLite.kt new file mode 100644 index 0000000..60ae709 --- /dev/null +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardSQLite.kt @@ -0,0 +1,147 @@ +/* + * SPDX-License-Identifier: AGPL-3.0-or-later + * Copyright (C) 2026 MessengerBotTeam + */ + +package com.xfl.msgbot.plugin.guard + +import android.database.DatabaseErrorHandler +import android.database.sqlite.SQLiteCantOpenDatabaseException +import android.database.sqlite.SQLiteDatabase +import java.io.File + +/** + * `android.database.sqlite.SQLiteDatabase`, which is final: its static ways to open, create and delete a database. + * The databases they return are the real class. + * + * SQLite opens its file and the journal next to it by path, which no descriptor from the host can stand in for. So a + * database on storage opens only when the engine app has All files access ([GuardSession.hasStorageAccess]), and then + * only where the project's file rules allow it; without that access it fails with a message that points to the host + * `db` module. Databases in memory always work. + */ +class GuardSQLiteDatabase private constructor() { + companion object { + const val CONFLICT_ROLLBACK = SQLiteDatabase.CONFLICT_ROLLBACK + const val CONFLICT_ABORT = SQLiteDatabase.CONFLICT_ABORT + const val CONFLICT_FAIL = SQLiteDatabase.CONFLICT_FAIL + const val CONFLICT_IGNORE = SQLiteDatabase.CONFLICT_IGNORE + const val CONFLICT_REPLACE = SQLiteDatabase.CONFLICT_REPLACE + const val CONFLICT_NONE = SQLiteDatabase.CONFLICT_NONE + const val SQLITE_MAX_LIKE_PATTERN_LENGTH = SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH + const val OPEN_READWRITE = SQLiteDatabase.OPEN_READWRITE + const val OPEN_READONLY = SQLiteDatabase.OPEN_READONLY + const val NO_LOCALIZED_COLLATORS = SQLiteDatabase.NO_LOCALIZED_COLLATORS + const val CREATE_IF_NECESSARY = SQLiteDatabase.CREATE_IF_NECESSARY + const val ENABLE_WRITE_AHEAD_LOGGING = SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING + const val MAX_SQL_CACHE_SIZE = SQLiteDatabase.MAX_SQL_CACHE_SIZE + const val JOURNAL_MODE_WAL = SQLiteDatabase.JOURNAL_MODE_WAL + const val JOURNAL_MODE_PERSIST = SQLiteDatabase.JOURNAL_MODE_PERSIST + const val JOURNAL_MODE_TRUNCATE = SQLiteDatabase.JOURNAL_MODE_TRUNCATE + const val JOURNAL_MODE_MEMORY = SQLiteDatabase.JOURNAL_MODE_MEMORY + const val JOURNAL_MODE_DELETE = SQLiteDatabase.JOURNAL_MODE_DELETE + const val JOURNAL_MODE_OFF = SQLiteDatabase.JOURNAL_MODE_OFF + const val SYNC_MODE_EXTRA = SQLiteDatabase.SYNC_MODE_EXTRA + const val SYNC_MODE_FULL = SQLiteDatabase.SYNC_MODE_FULL + const val SYNC_MODE_NORMAL = SQLiteDatabase.SYNC_MODE_NORMAL + const val SYNC_MODE_OFF = SQLiteDatabase.SYNC_MODE_OFF + + private const val MEMORY = ":memory:" + + @JvmStatic + fun openDatabase( + path: String, + factory: SQLiteDatabase.CursorFactory?, + flags: Int, + ): SQLiteDatabase = SQLiteDatabase.openDatabase(checked(path, flags), factory, flags) + + @JvmStatic + fun openDatabase( + path: String, + factory: SQLiteDatabase.CursorFactory?, + flags: Int, + errorHandler: DatabaseErrorHandler?, + ): SQLiteDatabase = SQLiteDatabase.openDatabase(checked(path, flags), factory, flags, errorHandler) + + @JvmStatic + fun openDatabase( + path: File, + openParams: SQLiteDatabase.OpenParams, + ): SQLiteDatabase = SQLiteDatabase.openDatabase(File(checked(path.path, openParams.openFlags)), openParams) + + @JvmStatic + fun openOrCreateDatabase( + file: File, + factory: SQLiteDatabase.CursorFactory?, + ): SQLiteDatabase = openOrCreateDatabase(file.path, factory) + + @JvmStatic + fun openOrCreateDatabase( + path: String, + factory: SQLiteDatabase.CursorFactory?, + ): SQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(checked(path, OPEN_READWRITE or CREATE_IF_NECESSARY), factory) + + @JvmStatic + fun openOrCreateDatabase( + path: String, + factory: SQLiteDatabase.CursorFactory?, + errorHandler: DatabaseErrorHandler?, + ): SQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(checked(path, OPEN_READWRITE or CREATE_IF_NECESSARY), factory, errorHandler) + + @JvmStatic + fun deleteDatabase(file: File): Boolean = SQLiteDatabase.deleteDatabase(File(checked(file.path, OPEN_READWRITE))) + + @JvmStatic + fun create(factory: SQLiteDatabase.CursorFactory?): SQLiteDatabase = SQLiteDatabase.create(factory) + + @JvmStatic + fun createInMemory(openParams: SQLiteDatabase.OpenParams): SQLiteDatabase = SQLiteDatabase.createInMemory(openParams) + + @JvmStatic + fun releaseMemory(): Int = SQLiteDatabase.releaseMemory() + + @JvmStatic + fun findEditTable(tables: String): String = SQLiteDatabase.findEditTable(tables) + + // The absolute path of a database the project may use as [flags] ask, or a refusal like SQLite's own. + private fun checked( + path: String, + flags: Int, + ): String { + if (path == MEMORY) return path + val session = GuardContext.current() + val host = session.host + val absolute = GuardFile.normalize(if (path.startsWith("/")) path else host.root.trimEnd('/') + "/" + path) + if (!session.hasStorageAccess) { + session.warnOnce( + "sqlite", + "Java: SQLite needs All files access for this plugin app. Use the db module, or allow the access in the plugin's settings.", + ) + throw SQLiteCantOpenDatabaseException( + "Cannot open $path: SQLite needs All files access for this plugin app. Use the db module instead.", + ) + } + val write = flags and OPEN_READONLY == 0 + val existing = + try { + host.stat(absolute) + } catch (e: HostIOException) { + refuse(path, absolute, e) + } + // A new database needs a folder the project may write to; a missing one is left for SQLite to report. + val target = if (existing != null || flags and CREATE_IF_NECESSARY == 0) absolute else absolute.substringBeforeLast('/').ifEmpty { "/" } + if ((existing != null || target != absolute) && !host.access(target, if (write) 6 else 4)) { + refuse(path, absolute, HostIOException("EACCES", absolute, "permission denied")) + } + return absolute + } + + private fun refuse( + path: String, + absolute: String, + e: HostIOException, + ): Nothing { + if (e.isDenied) GuardContext.reportPath(absolute) + throw SQLiteCantOpenDatabaseException("Cannot open $path: ${e.errno} (${e.detail})") + } + } +} 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 index 369bf63..6dbff28 100644 --- a/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardSession.kt +++ b/guard/src/main/java/com/xfl/msgbot/plugin/guard/GuardSession.kt @@ -5,6 +5,10 @@ package com.xfl.msgbot.plugin.guard +import android.os.Build +import android.os.Environment +import android.system.Os +import android.system.OsConstants import java.io.Closeable import java.util.concurrent.ConcurrentHashMap @@ -15,16 +19,29 @@ import java.util.concurrent.ConcurrentHashMap class GuardSession( val host: GuardHost, val rules: ClassRules = ClassRules.DEFAULT, + private val storageAccess: () -> Boolean = StorageAccess::granted, ) : Closeable { private val reported = ConcurrentHashMap.newKeySet() private val deleteOnExit = ConcurrentHashMap.newKeySet() + /** + * Whether the engine app may reach shared storage itself (All files access). Only classes that cannot work over + * a descriptor, such as SQLite, use it; asked each time, since the user can switch it while the engine runs. + */ + val hasStorageAccess: Boolean get() = storageAccess() + /** Tells the project log, once per name, that the guard stopped something. */ fun report( kind: String, name: String, + ) = warnOnce("$kind:$name", "Java: $kind '$name' is not available to this project") + + /** Writes [message] to the project log as a warning, once per [key]. */ + fun warnOnce( + key: String, + message: String, ) { - if (reported.add("$kind:$name")) host.log("warn", "Java: $kind '$name' is not available to this project") + if (reported.add(key)) host.log("warn", message) } internal fun deleteOnExit(path: String) { @@ -81,3 +98,14 @@ object GuardContext { current.get()?.report("class", name) } } + +/** Whether this app may reach shared storage without the host. */ +object StorageAccess { + fun granted(): Boolean = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + Environment.isExternalStorageManager() + } else { + @Suppress("DEPRECATION") + runCatching { Os.access(Environment.getExternalStorageDirectory().path, OsConstants.W_OK) }.getOrDefault(false) + } +} diff --git a/readme.md b/readme.md index b2e1889..caa7f07 100644 --- a/readme.md +++ b/readme.md @@ -8,7 +8,7 @@ MessengerBotR의 플러그인 계약이다. 현재 개발 버전은 `0.1.0-SNAPS |---|---| | `contract` | 값, API 스키마, 표준 모듈, 엔진·제공자·도구 SPI, 대칭 RPC. Android에 의존하지 않는다. | | `android` | `PluginService`, Binder 세션, 공유 메모리 전송 | -| `guard` | Java를 쓰는 엔진의 파일·클래스 가드. `File`, 스트림, `RandomAccessFile`, nio, `ZipFile`, `Formatter`, `BitmapFactory`, `MediaMetadataRetriever` 등을 호스트 디스크립터 위의 같은 모양 클래스로 바꾸고, `ClassAccess`로 클래스 접근을 정한다. 엔진에는 이름 조회(`GuardPolicy.lookup`)와 값 변환(`GuardPolicy.replace`)만 연결하면 된다 | +| `guard` | Java를 쓰는 엔진의 파일·클래스 가드. `File`, 스트림, `RandomAccessFile`, nio, `ZipFile`, `Formatter`, `BitmapFactory`, `MediaMetadataRetriever` 등을 호스트 디스크립터 위의 같은 모양 클래스로 바꾸고, `SQLiteDatabase`는 엔진 앱에 모든 파일 접근이 있을 때만 파일 규칙 안에서 열며, `ClassAccess`로 클래스 접근을 정한다. 엔진에는 이름 조회(`GuardPolicy.lookup`)와 값 변환(`GuardPolicy.replace`)만 연결하면 된다 | | `tck` | 엔진과 제공자를 호스트 없이 돌려 보는 `EngineHarness`, `ProviderHarness`. JavaScript 엔진의 적합성 테스트(`JavaScriptEngineConformance`), Java 가드의 적합성 테스트(`JavaGuardConformance`, 기기에서 실행), 제공자의 적합성 테스트(`ProviderConformance`) | ## 구조 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 index e3a7d73..462b471 100644 --- a/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/JavaGuardConformance.kt +++ b/tck/src/main/kotlin/com/xfl/msgbot/plugin/tck/JavaGuardConformance.kt @@ -18,6 +18,7 @@ import org.junit.Before import org.junit.Test import java.io.File import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertTrue /** @@ -168,6 +169,17 @@ abstract class JavaGuardConformance { assertEquals(1, warnings().count { it.contains(outside.path) }, warnings().toString()) } + /** Runs where the engine app has no All files access, as on a fresh install. */ + @Test + fun sqliteOnStorageNeedsAllFilesAccess() { + load() + val sqlite = j("android.database.sqlite.SQLiteDatabase") + assertEquals("threw", text("t(function () { return $sqlite.openOrCreateDatabase('a.db', null).isOpen(); })")) + assertFalse(File(files.root, "a.db").exists()) + assertEquals("ok:true", text("t(function () { var d = $sqlite.openOrCreateDatabase(':memory:', null); var open = d.isOpen(); d.close(); return open; })")) + assertEquals(1, warnings().count { it.contains("SQLite") }, warnings().toString()) + } + @Test fun placesOutsideTheRulesAreRefused() { load()