From 064045d9b160b8d029578826048edf6a4d95e263 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 06:48:23 +0000 Subject: [PATCH 1/2] Bump org.xerial:sqlite-jdbc from 3.53.4.0 to 3.54.1.0 in /VotingPlugin Bumps [org.xerial:sqlite-jdbc](https://github.com/xerial/sqlite-jdbc) from 3.53.4.0 to 3.54.1.0. - [Release notes](https://github.com/xerial/sqlite-jdbc/releases) - [Changelog](https://github.com/xerial/sqlite-jdbc/blob/master/CHANGELOG) - [Commits](https://github.com/xerial/sqlite-jdbc/compare/3.53.4.0...3.54.1.0) --- updated-dependencies: - dependency-name: org.xerial:sqlite-jdbc dependency-version: 3.54.1.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- VotingPlugin/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VotingPlugin/pom.xml b/VotingPlugin/pom.xml index d2da72925..05dbadd2f 100644 --- a/VotingPlugin/pom.xml +++ b/VotingPlugin/pom.xml @@ -396,7 +396,7 @@ org.xerial sqlite-jdbc - 3.53.4.0 + 3.54.1.0 org.checkerframework From 4505721a3c198025da66f45e9c5320ae00bc45b1 Mon Sep 17 00:00:00 2001 From: BenCodez <17074231+BenCodez@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:01:36 +0000 Subject: [PATCH 2/2] Preserve offline SQLite native loading across supported platforms Embed and verify all supported native resources while preserving native overrides and plugin-owned extraction. Cover offline loading, rejected resources and the downloadable artifact. --- VotingPlugin/pom.xml | 20 +-- .../util/SqliteNativeLibrary.java | 95 ++++++++++- .../tests/packaging/PackagedArtifactTest.java | 130 ++++++++++++-- .../tests/util/SqliteNativeLibraryTest.java | 160 +++++++++++++++++- docs/jar-packaging.md | 51 +++--- 5 files changed, 397 insertions(+), 59 deletions(-) diff --git a/VotingPlugin/pom.xml b/VotingPlugin/pom.xml index 05dbadd2f..0d8b94454 100644 --- a/VotingPlugin/pom.xml +++ b/VotingPlugin/pom.xml @@ -225,24 +225,8 @@ META-INF/versions/** - - org.xerial:sqlite-jdbc - - - org/sqlite/native/FreeBSD/** - org/sqlite/native/Linux-Musl/** - org/sqlite/native/Linux/aarch64/** - org/sqlite/native/Linux/arm/** - org/sqlite/native/Linux/armv6/** - org/sqlite/native/Linux/armv7/** - org/sqlite/native/Linux/ppc64/** - org/sqlite/native/Linux/riscv64/** - org/sqlite/native/Linux/x86/** - org/sqlite/native/Mac/** - org/sqlite/native/Windows/** - - + *:* diff --git a/VotingPlugin/src/main/java/com/bencodez/votingplugin/util/SqliteNativeLibrary.java b/VotingPlugin/src/main/java/com/bencodez/votingplugin/util/SqliteNativeLibrary.java index fc3513ff5..c05041dc2 100644 --- a/VotingPlugin/src/main/java/com/bencodez/votingplugin/util/SqliteNativeLibrary.java +++ b/VotingPlugin/src/main/java/com/bencodez/votingplugin/util/SqliteNativeLibrary.java @@ -13,6 +13,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HexFormat; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.jar.JarEntry; @@ -20,13 +21,57 @@ import org.sqlite.util.OSInfo; -/** Prepares the current Xerial SQLite native without embedding every target in the plugin JAR. */ +/** Verifies the embedded Xerial SQLite native, with a pinned-driver fallback for custom packaging. */ public final class SqliteNativeLibrary { - static final String DRIVER_FILE = "sqlite-jdbc-3.53.4.0.jar"; - static final String DRIVER_SHA256 = "bcb1f51e36f940867e83342f9efbf5968ac44a6bef4d397bb4af7b17b45cd2fb"; + static final String DRIVER_FILE = "sqlite-jdbc-3.54.1.0.jar"; + static final String DRIVER_SHA256 = "f8dce420a6016278497f4f0560f65602b9db858de141b541cf91a4644ebe4639"; private static final URI DRIVER_URI = URI.create("https://maven-central.storage-download.googleapis.com/maven2/" - + "org/xerial/sqlite-jdbc/3.53.4.0/" + DRIVER_FILE); + + "org/xerial/sqlite-jdbc/3.54.1.0/" + DRIVER_FILE); private static final long MAX_DRIVER_BYTES = 16L * 1024L * 1024L; + private static final int MAX_NATIVE_BYTES = 2 * 1024 * 1024; + // Digests from the official artifact identified by DRIVER_SHA256. Never trust a resource + // supplied by a different driver or classloader merely because its path matches. + private static final Map NATIVE_SHA256 = Map.ofEntries( + Map.entry("org/sqlite/native/FreeBSD/aarch64/libsqlitejdbc.so", + "d450f90bfaf858c2e52505b4370c99ede31c07430c66c3231132a6920b26ed5c"), + Map.entry("org/sqlite/native/FreeBSD/x86/libsqlitejdbc.so", + "61f86fe5144d8965a3e64bfa48af874f6901167a8b3e4e6a370500640ac8ac1b"), + Map.entry("org/sqlite/native/FreeBSD/x86_64/libsqlitejdbc.so", + "04584ec9a87bc2d59e707949f2c9db3e206108dd8fce1cf1797f13d7e0760f30"), + Map.entry("org/sqlite/native/Linux/aarch64/libsqlitejdbc.so", + "2deb508458a39049204b0e92db5d82e53598eb4e2d34dff3ee29cc47a38f83ee"), + Map.entry("org/sqlite/native/Linux/arm/libsqlitejdbc.so", + "9b50eb59ae3a2d2a956287c53b3c6cf87cd5ffff58c00889fbd5a7a9ef220482"), + Map.entry("org/sqlite/native/Linux/armv6/libsqlitejdbc.so", + "3601ac7a21215b9dc928db447a63a28383dad419e579d77168ab6c91acbbbf3b"), + Map.entry("org/sqlite/native/Linux/armv7/libsqlitejdbc.so", + "43f0c78a6de21ce39539a0df93edf19bcef79c95358467128459d551666f098c"), + Map.entry("org/sqlite/native/Linux/ppc64/libsqlitejdbc.so", + "1a2f43080088c6230aa1554e1fc198e1961f8ef8f5df94656a612fee97ada41a"), + Map.entry("org/sqlite/native/Linux/riscv64/libsqlitejdbc.so", + "cbfb0bed9e5feca3dcec0fcd95d9e9c21f90382adc62be64fcd3300772d7c74d"), + Map.entry("org/sqlite/native/Linux/x86/libsqlitejdbc.so", + "7440830f45d7b2e32f16c27cc6d61e65070f9a7ea6ceff731a141943faf97512"), + Map.entry("org/sqlite/native/Linux/x86_64/libsqlitejdbc.so", + "9149f234a03da04caba72ce534dfa0f0e5b999ae8d03d630034be65f24c7b44c"), + Map.entry("org/sqlite/native/Linux-Musl/aarch64/libsqlitejdbc.so", + "126521645e72d05b57442583ab33b2c8494fd04d60d1be442a15536723e26861"), + Map.entry("org/sqlite/native/Linux-Musl/x86/libsqlitejdbc.so", + "cf9e993ea2a052f8ec3931a202f4fea0049e7f0276b3726c1ac87d52064c45c0"), + Map.entry("org/sqlite/native/Linux-Musl/x86_64/libsqlitejdbc.so", + "b21aac0da3a80a0c4cee035d5919021c991ee17c8284a76b38ab7b62e68bab52"), + Map.entry("org/sqlite/native/Mac/aarch64/libsqlitejdbc.dylib", + "47fa68b43f34552fbfedeed25e82875a42cfd53e81c33c7cee20ac3f729c060e"), + Map.entry("org/sqlite/native/Mac/x86_64/libsqlitejdbc.dylib", + "51d30fe476f0170cd42102baabb82c4b39d43996c9209cdc60876a4b928d85f7"), + Map.entry("org/sqlite/native/Windows/aarch64/sqlitejdbc.dll", + "59ec28822968199a7a94feb62a44357ab201c7bc3c55ebdf0e3e5ece840a45b6"), + Map.entry("org/sqlite/native/Windows/armv7/sqlitejdbc.dll", + "175095c594d0fa73e819d7b1066a4d8a19265d89bbe4bf0c629a29dc233b6e04"), + Map.entry("org/sqlite/native/Windows/x86/sqlitejdbc.dll", + "d03f852a3350e65f6ed8244e6f348d154aca10c89820e1387885dd95b4fa0445"), + Map.entry("org/sqlite/native/Windows/x86_64/sqlitejdbc.dll", + "4896f8ba8824a85f10f31383e38b9542b6043886a0c834e0d6c8606b02f82308")); private static final long STALE_NATIVE_MILLIS = 24L * 60L * 60L * 1000L; private SqliteNativeLibrary() { @@ -34,7 +79,11 @@ private SqliteNativeLibrary() { /** Ensures Xerial can load the native for this operating system and architecture. */ public static synchronized void ensureAvailable(Path directory) throws IOException { - if (System.getProperty("org.sqlite.lib.path") != null) { + String configuredName = System.getProperty("org.sqlite.lib.name"); + // A custom name alone selects a library through Xerial/java.library.path. + // The standard name still uses our verified extraction, including on noexec temp mounts. + if (System.getProperty("org.sqlite.lib.path") != null + || (configuredName != null && !configuredName.equals(System.mapLibraryName("sqlitejdbc")))) { try { if (!org.sqlite.core.NativeDB.load()) throw new IOException("Configured SQLite native library did not load"); return; @@ -53,10 +102,21 @@ static Path prepareNative(Path directory, String folder, ClassLoader resourceLoa throws IOException { String libraryName = nativeLibraryName(folder); String resource = "org/sqlite/native/" + folder + "/" + libraryName; - if (resourceLoader.getResource(resource) != null) return null; + byte[] embeddedBytes = null; + try (InputStream embedded = resourceLoader.getResourceAsStream(resource)) { + if (embedded != null) { + String expected = NATIVE_SHA256.get(resource); + byte[] bytes = embedded.readNBytes(MAX_NATIVE_BYTES + 1); + if (expected == null || bytes.length == 0 || bytes.length > MAX_NATIVE_BYTES + || !expected.equals(sha256(bytes))) { + throw new IOException("Embedded SQLite native failed SHA-256 verification: " + resource); + } + embeddedBytes = bytes; + } + } Files.createDirectories(directory); Path driver = directory.resolve(DRIVER_FILE); - if (!hasExpectedDigest(driver, DRIVER_SHA256)) { + if (embeddedBytes == null && !hasExpectedDigest(driver, DRIVER_SHA256)) { try { downloadVerified(driver, fetcher); } catch (IOException failure) { @@ -70,7 +130,18 @@ static Path prepareNative(Path directory, String folder, ClassLoader resourceLoa Path nativeDirectory = platformDirectory.resolve("load-" + UUID.randomUUID()); Files.createDirectories(nativeDirectory); Path nativeLibrary = nativeDirectory.resolve(libraryName); - extractVerifiedEntry(driver, resource, nativeLibrary); + if (embeddedBytes != null) { + // Keep loading in the plugin directory, including when the JVM temp directory + // is read-only or mounted noexec on a previously fallback-backed platform. + Path temporary = Files.createTempFile(nativeDirectory, libraryName + ".", ".extract"); + setPrivatePermissions(temporary); + try { + Files.write(temporary, embeddedBytes); + moveReplacing(temporary, nativeLibrary); + } finally { Files.deleteIfExists(temporary); } + } else { + extractVerifiedEntry(driver, resource, nativeLibrary); + } nativeLibrary.toFile().deleteOnExit(); nativeDirectory.toFile().deleteOnExit(); return nativeLibrary; @@ -187,6 +258,14 @@ private static void moveReplacing(Path source, Path target) throws IOException { } } + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + private static boolean hasExpectedDigest(Path file, String expected) throws IOException { if (!Files.isRegularFile(file)) return false; try (InputStream input = Files.newInputStream(file)) { diff --git a/VotingPlugin/src/test/java/com/bencodez/votingplugin/tests/packaging/PackagedArtifactTest.java b/VotingPlugin/src/test/java/com/bencodez/votingplugin/tests/packaging/PackagedArtifactTest.java index 9ca757675..fb4dd462f 100644 --- a/VotingPlugin/src/test/java/com/bencodez/votingplugin/tests/packaging/PackagedArtifactTest.java +++ b/VotingPlugin/src/test/java/com/bencodez/votingplugin/tests/packaging/PackagedArtifactTest.java @@ -1,6 +1,8 @@ package com.bencodez.votingplugin.tests.packaging; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -59,19 +61,65 @@ void containsOneRelocatedRuntimeWithoutUnusedHttpCrypto() throws Exception { assertNull(artifact.getEntry("com/zaxxer/hikari/HikariDataSource.class")); assertNull(artifact.getEntry("com/tcoded/folialib/FoliaLib.class")); assertFalse(artifact.stream().anyMatch(entry -> entry.getName().contains("/bouncycastle/"))); - assertNotNull(artifact.getEntry("org/sqlite/native/Linux/x86_64/libsqlitejdbc.so"), - "The common Linux x86_64 SQLite runtime must remain available offline"); - assertFalse(artifact.stream().anyMatch(entry -> !entry.isDirectory() - && entry.getName().startsWith("org/sqlite/native/") - && !entry.getName().startsWith("org/sqlite/native/Linux/x86_64/")), - "Only the common offline SQLite native may be embedded"); + } long artifactBytes = Files.size(artifactPath); warnIfArtifactExceedsSizeTarget(artifactBytes, System.out); - System.out.printf("VotingPlugin downloadable artifact: %,d bytes; duplicate Rhino, external crypto and uncommon SQLite natives absent%n", + System.out.printf("VotingPlugin downloadable artifact: %,d bytes; duplicate Rhino and external crypto absent; all supported SQLite natives retained%n", Files.size(artifactPath)); } + @Test + void everyOfficialSqliteNativeIsPackagedOnceAndVerifiedOffline(@TempDir Path directory) throws Exception { + Path driver = Path.of(org.sqlite.JDBC.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + byte[] officialBytes = Files.readAllBytes(driver); + assertEquals("f8dce420a6016278497f4f0560f65602b9db858de141b541cf91a4644ebe4639", + java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256") + .digest(officialBytes)), "Expected the pinned official SQLite driver"); + Files.writeString(directory.resolve("sqlite-jdbc-3.53.4.0.jar"), "previous installation cache"); + try (JarFile official = new JarFile(driver.toFile()); + JarFile artifact = new JarFile(packagedJar().toFile()); + URLClassLoader loader = new URLClassLoader(new URL[] { packagedJar().toUri().toURL() }, + ClassLoader.getPlatformClassLoader())) { + var expected = official.stream().filter(entry -> !entry.isDirectory() + && entry.getName().startsWith("org/sqlite/native/")).map(java.util.jar.JarEntry::getName) + .collect(java.util.stream.Collectors.toSet()); + var actual = artifact.stream().filter(entry -> !entry.isDirectory() + && entry.getName().startsWith("org/sqlite/native/")).map(java.util.jar.JarEntry::getName) + .collect(java.util.stream.Collectors.toSet()); + assertEquals(20, expected.size(), "Cover every supported target, not just this host"); + assertEquals(expected, actual, "No offline target may be removed or shadowed by another dependency"); + Class nativeType = Class.forName("com.bencodez.votingplugin.util.SqliteNativeLibrary", true, loader); + Class fetcherType = Class.forName(nativeType.getName() + "$ArtifactFetcher", true, loader); + Object noNetwork = java.lang.reflect.Proxy.newProxyInstance(loader, new Class[] { fetcherType }, + (proxy, method, arguments) -> { throw new AssertionError("packaged offline native must not fetch"); }); + var prepare = nativeType.getDeclaredMethod("prepareNative", Path.class, String.class, + ClassLoader.class, fetcherType); + prepare.setAccessible(true); + for (String name : expected) { + assertEquals(1, artifact.stream().filter(entry -> entry.getName().equals(name)).count(), name); + assertArrayEquals(official.getInputStream(official.getEntry(name)).readAllBytes(), + artifact.getInputStream(artifact.getEntry(name)).readAllBytes(), name); + String folder = name.substring("org/sqlite/native/".length(), name.lastIndexOf('/')); + Path prepared = (Path) prepare.invoke(null, directory, folder, loader, noNetwork); + assertTrue(prepared.startsWith(directory.resolve("sqlite-native")), name); + assertArrayEquals(official.getInputStream(official.getEntry(name)).readAllBytes(), + Files.readAllBytes(prepared), name); + } + // Exercise integrity rejection using the packaged loader implementation, with no Maven classes. + ClassLoader corrupt = new ClassLoader(ClassLoader.getPlatformClassLoader()) { + @Override public java.io.InputStream getResourceAsStream(String name) { + return new java.io.ByteArrayInputStream(new byte[] { 1, 2, 3 }); + } + }; + var failure = org.junit.jupiter.api.Assertions.assertThrows(java.lang.reflect.InvocationTargetException.class, + () -> prepare.invoke(null, directory, "Mac/x86_64", corrupt, noNetwork)); + assertTrue(failure.getCause() instanceof java.io.IOException); + assertTrue(failure.getCause().getMessage().contains("SHA-256")); + assertFalse(Files.exists(directory.resolve("sqlite-jdbc-3.54.1.0.jar"))); + } + } + @Test void artifactSizeTargetWarnsWithoutRejectingOversizedArtifacts() { ByteArrayOutputStream output = new ByteArrayOutputStream(); @@ -97,12 +145,70 @@ private static void warnIfArtifactExceedsSizeTarget(long artifactBytes, PrintStr void packagedNeoForgeRuntimeStartsAndClosesWithoutTestDependencies(@TempDir Path directory) throws Exception { URL jar = packagedJar().toUri().toURL(); URL platformSlf4j = org.slf4j.Logger.class.getProtectionDomain().getCodeSource().getLocation(); - try (URLClassLoader loader = new URLClassLoader(new URL[] { jar, platformSlf4j }, - ClassLoader.getPlatformClassLoader())) { - Class runtime = Class.forName("com.bencodez.votingplugin.neoforge.NeoForgeRuntime", true, loader); - try (AutoCloseable instance = (AutoCloseable) runtime.getMethod("start", Path.class).invoke(null, directory)) { - assertTrue(Files.isRegularFile(directory.resolve("VotingPlugin.db"))); + Path unusableTemp = directory.resolve("not-a-directory"); + Files.writeString(unusableTemp, "synthetic unusable temp directory"); + String oldJavaTemp = System.getProperty("java.io.tmpdir"); + String oldSqliteTemp = System.getProperty("org.sqlite.tmpdir"); + try { + System.setProperty("java.io.tmpdir", unusableTemp.toString()); + System.setProperty("org.sqlite.tmpdir", unusableTemp.toString()); + try (URLClassLoader loader = new URLClassLoader(new URL[] { jar, platformSlf4j }, + ClassLoader.getPlatformClassLoader())) { + Class runtime = Class.forName("com.bencodez.votingplugin.neoforge.NeoForgeRuntime", true, loader); + try (AutoCloseable instance = (AutoCloseable) runtime.getMethod("start", Path.class).invoke(null, directory)) { + assertTrue(Files.isRegularFile(directory.resolve("VotingPlugin.db"))); + assertTrue(Files.isDirectory(directory.resolve("libraries/sqlite-native"))); + } + } + } finally { + if (oldJavaTemp == null) System.clearProperty("java.io.tmpdir"); + else System.setProperty("java.io.tmpdir", oldJavaTemp); + if (oldSqliteTemp == null) System.clearProperty("org.sqlite.tmpdir"); + else System.setProperty("org.sqlite.tmpdir", oldSqliteTemp); + } + } + + @Test + void packagedSqliteHonorsACustomNameWithoutANativePath(@TempDir Path directory) throws Exception { + URL jar = packagedJar().toUri().toURL(); + URL logging = org.slf4j.Logger.class.getProtectionDomain().getCodeSource().getLocation(); + String nativeName = System.mapLibraryName("sqlitejdbc-custom"); + String resource = "org/sqlite/native/" + org.sqlite.util.OSInfo.getNativeLibFolderPathForCurrentOS() + + "/" + System.mapLibraryName("sqlitejdbc"); + try (JarFile artifact = new JarFile(packagedJar().toFile()); + var input = artifact.getInputStream(artifact.getEntry(resource))) { + Files.copy(input, directory.resolve(nativeName)); + } + java.util.Map previous = new java.util.HashMap<>(); + for (String key : java.util.List.of("org.sqlite.lib.path", "org.sqlite.lib.name", "java.library.path")) { + previous.put(key, System.getProperty(key)); + } + try { + System.clearProperty("org.sqlite.lib.path"); + System.setProperty("org.sqlite.lib.name", nativeName); + System.setProperty("java.library.path", directory.toString()); + Path libraries = directory.resolve("plugin-libraries"); + try (URLClassLoader loader = new URLClassLoader(new URL[] { jar, logging }, + ClassLoader.getPlatformClassLoader())) { + Class.forName("com.bencodez.votingplugin.util.SqliteNativeLibrary", true, loader) + .getMethod("ensureAvailable", Path.class).invoke(null, libraries); + java.sql.Driver jdbc = (java.sql.Driver) Class.forName("org.sqlite.JDBC", true, loader) + .getConstructor().newInstance(); + try (var connection = jdbc.connect("jdbc:sqlite::memory:", new java.util.Properties()); + var statement = connection.createStatement(); + var rows = statement.executeQuery("SELECT 42")) { + assertTrue(rows.next()); + assertEquals(42, rows.getInt(1)); + } } + assertFalse(Files.exists(libraries), "custom name must select the existing library"); + assertEquals(nativeName, System.getProperty("org.sqlite.lib.name")); + assertNull(System.getProperty("org.sqlite.lib.path")); + } finally { + previous.forEach((key, value) -> { + if (value == null) System.clearProperty(key); + else System.setProperty(key, value); + }); } } diff --git a/VotingPlugin/src/test/java/com/bencodez/votingplugin/tests/util/SqliteNativeLibraryTest.java b/VotingPlugin/src/test/java/com/bencodez/votingplugin/tests/util/SqliteNativeLibraryTest.java index 9b9a9454f..c374cc71e 100644 --- a/VotingPlugin/src/test/java/com/bencodez/votingplugin/tests/util/SqliteNativeLibraryTest.java +++ b/VotingPlugin/src/test/java/com/bencodez/votingplugin/tests/util/SqliteNativeLibraryTest.java @@ -5,14 +5,21 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; + +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.IOException; +import java.io.ByteArrayInputStream; +import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.util.jar.JarFile; +import java.util.stream.Stream; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -25,7 +32,156 @@ void usesEmbeddedCommonNativeWithoutFetching() throws Exception { SqliteNativeLibrary.class.getClassLoader(), (source, target) -> { throw new AssertionError("embedded native must not download the driver"); }); - assertNull(prepared); + assertTrue(Files.isRegularFile(prepared)); + } + + @TestFactory + Stream everySupportedNativeWorksOfflineWithOnlyThePreviousDriverCached() throws Exception { + Path driver = Path.of(org.sqlite.JDBC.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + Files.writeString(directory.resolve("sqlite-jdbc-3.53.4.0.jar"), "previous installation cache"); + try (JarFile jar = new JarFile(driver.toFile())) { + return jar.stream().filter(entry -> !entry.isDirectory() + && entry.getName().startsWith("org/sqlite/native/")).map(entry -> { + String resource = entry.getName(); + String folder = resource.substring("org/sqlite/native/".length(), resource.lastIndexOf('/')); + return DynamicTest.dynamicTest(folder, () -> { + Path prepared = SqliteNativeLibraryAccess.prepareNative(directory, folder, + SqliteNativeLibrary.class.getClassLoader(), (source, target) -> { + throw new AssertionError("offline upgrade must not fetch a new driver"); + }); + assertTrue(prepared.startsWith(directory.resolve("sqlite-native"))); + try (InputStream expected = SqliteNativeLibrary.class.getClassLoader().getResourceAsStream(resource)) { + assertArrayEquals(expected.readAllBytes(), Files.readAllBytes(prepared)); + } + assertTrue(Files.notExists(directory.resolve(SqliteNativeLibraryAccess.DRIVER_FILE))); + assertTrue(Files.exists(directory.resolve("sqlite-jdbc-3.53.4.0.jar"))); + }); + }).toList().stream(); + } + } + + @Test + void embeddedNativePreparationDoesNotDependOnTheJvmTempDirectory() throws Exception { + Path unusableTemp = directory.resolve("not-a-directory"); + Files.writeString(unusableTemp, "synthetic unusable temp directory"); + String oldJavaTemp = System.getProperty("java.io.tmpdir"); + String oldSqliteTemp = System.getProperty("org.sqlite.tmpdir"); + try { + System.setProperty("java.io.tmpdir", unusableTemp.toString()); + System.setProperty("org.sqlite.tmpdir", unusableTemp.toString()); + Path prepared = SqliteNativeLibraryAccess.prepareNative(directory, "Mac/x86_64", + SqliteNativeLibrary.class.getClassLoader(), (source, target) -> { + throw new AssertionError("offline native must not download"); + }); + assertTrue(prepared.startsWith(directory.resolve("sqlite-native"))); + assertTrue(Files.isRegularFile(prepared)); + } finally { + restoreProperty("java.io.tmpdir", oldJavaTemp); + restoreProperty("org.sqlite.tmpdir", oldSqliteTemp); + } + } + + private static void restoreProperty(String name, String value) { + if (value == null) System.clearProperty(name); + else System.setProperty(name, value); + } + + @TestFactory + Stream preservesExplicitNativeSelectionAcrossOverrideModes() { + return Stream.of("path-only", "name-only", "both", "standard-name").map(mode -> + DynamicTest.dynamicTest(mode, () -> { + Path caseDirectory = Files.createDirectory(directory.resolve(mode)); + Path customDirectory = Files.createDirectory(caseDirectory.resolve("custom-native")); + String standardName = System.mapLibraryName("sqlitejdbc"); + String nativeName = mode.equals("path-only") || mode.equals("standard-name") ? standardName + : System.mapLibraryName("sqlitejdbc-test-" + mode); + String resource = "org/sqlite/native/" + + org.sqlite.util.OSInfo.getNativeLibFolderPathForCurrentOS() + "/" + standardName; + try (InputStream bytes = SqliteNativeLibrary.class.getClassLoader().getResourceAsStream(resource)) { + assertNotNull(bytes); + Files.copy(bytes, customDirectory.resolve(nativeName)); + } + Path badTemp = caseDirectory.resolve("not-a-directory"); + Files.writeString(badTemp, "synthetic unusable temp directory"); + java.util.Map previous = new java.util.HashMap<>(); + for (String key : java.util.List.of("org.sqlite.lib.path", "org.sqlite.lib.name", + "java.library.path", "org.sqlite.tmpdir", "java.io.tmpdir")) { + previous.put(key, System.getProperty(key)); + } + URL code = SqliteNativeLibrary.class.getProtectionDomain().getCodeSource().getLocation(); + URL driver = org.sqlite.JDBC.class.getProtectionDomain().getCodeSource().getLocation(); + URL logging = org.slf4j.Logger.class.getProtectionDomain().getCodeSource().getLocation(); + try { + System.clearProperty("org.sqlite.lib.path"); + System.clearProperty("org.sqlite.lib.name"); + System.setProperty("java.io.tmpdir", badTemp.toString()); + System.setProperty("org.sqlite.tmpdir", badTemp.toString()); + System.setProperty("java.library.path", mode.equals("name-only") + ? customDirectory.toString() : badTemp.toString()); + if (mode.equals("path-only") || mode.equals("both")) { + System.setProperty("org.sqlite.lib.path", customDirectory.toString()); + } + if (!mode.equals("path-only")) System.setProperty("org.sqlite.lib.name", nativeName); + Path libraries = caseDirectory.resolve("plugin-libraries"); + try (URLClassLoader isolated = new URLClassLoader(new URL[] { code, driver, logging }, + ClassLoader.getPlatformClassLoader())) { + Class preparation = Class.forName(SqliteNativeLibrary.class.getName(), true, isolated); + preparation.getMethod("ensureAvailable", Path.class).invoke(null, libraries); + java.sql.Driver jdbc = (java.sql.Driver) Class.forName("org.sqlite.JDBC", true, isolated) + .getConstructor().newInstance(); + try (var connection = jdbc.connect("jdbc:sqlite::memory:", new java.util.Properties()); + var statement = connection.createStatement(); + var rows = statement.executeQuery("SELECT 42")) { + assertTrue(rows.next()); + org.junit.jupiter.api.Assertions.assertEquals(42, rows.getInt(1)); + } + } + if (mode.equals("standard-name")) assertTrue(Files.isDirectory(libraries.resolve("sqlite-native"))); + else assertTrue(Files.notExists(libraries), "explicit selection must not be replaced by embedded native"); + if (!mode.equals("path-only")) { + org.junit.jupiter.api.Assertions.assertEquals(nativeName, System.getProperty("org.sqlite.lib.name")); + } + } finally { + previous.forEach(SqliteNativeLibraryTest::restoreProperty); + } + })); + } + + @TestFactory + Stream rejectsCorruptEmptyAndOversizedEmbeddedNativesWithoutFetching() { + return Stream.of(new byte[0], new byte[] { 1, 2, 3 }, new byte[2 * 1024 * 1024 + 1]) + .map(bytes -> DynamicTest.dynamicTest("invalid native length " + bytes.length, () -> { + ClassLoader corrupt = new ClassLoader(ClassLoader.getPlatformClassLoader()) { + @Override public InputStream getResourceAsStream(String name) { + return new ByteArrayInputStream(bytes); + } + }; + IOException error = assertThrows(IOException.class, + () -> SqliteNativeLibraryAccess.prepareNative(directory, "Mac/x86_64", corrupt, + (source, target) -> { throw new AssertionError("must reject corrupt embedded native"); })); + assertTrue(error.getMessage().contains("SHA-256")); + assertTrue(Files.notExists(directory.resolve("sqlite-native"))); + })); + } + + @Test + void missingNativeAndUnverifiedCacheCannotSucceedOffline() throws Exception { + Files.writeString(directory.resolve(SqliteNativeLibraryAccess.DRIVER_FILE), "unverified cache"); + try (URLClassLoader empty = new URLClassLoader(new URL[0], ClassLoader.getPlatformClassLoader())) { + assertThrows(IOException.class, () -> SqliteNativeLibraryAccess.prepareNative(directory, + "Mac/x86_64", empty, (source, target) -> { throw new IOException("offline"); })); + assertTrue(Files.notExists(directory.resolve("sqlite-native"))); + } + } + + @Test + void rejectsUnverifiedDownloadedDriver() throws Exception { + try (URLClassLoader empty = new URLClassLoader(new URL[0], ClassLoader.getPlatformClassLoader())) { + assertThrows(IOException.class, () -> SqliteNativeLibraryAccess.prepareNative(directory, + "Mac/x86_64", empty, (source, target) -> Files.writeString(target, "unverified driver"))); + assertTrue(Files.notExists(directory.resolve(SqliteNativeLibraryAccess.DRIVER_FILE))); + assertTrue(Files.notExists(directory.resolve("sqlite-native"))); + } } @Test diff --git a/docs/jar-packaging.md b/docs/jar-packaging.md index 0dbc4cacb..96ea514b4 100644 --- a/docs/jar-packaging.md +++ b/docs/jar-packaging.md @@ -13,27 +13,40 @@ downloadable plugin does not bundle Bouncy Castle. The package phase runs `PackagedArtifactTest` after shading. It opens the actual downloadable JAR, checks plugin resources and required relocated classes, and -rejects duplicate Rhino, raw Hikari/Folia, external crypto providers, uncommon -SQLite native targets, and Checker Framework annotations. It creates both +rejects duplicate Rhino, raw Hikari/Folia, external crypto providers and Checker +Framework annotations. It verifies every SQLite native target against the pinned +official driver artifact. It creates both server and client TLS identities from the packaged JDK-only implementation. -SQLite keeps the Linux x86_64 native in the plugin for offline startup on the -common server platform. When SQLite is selected on another supported target, -VotingPlugin downloads the pinned `sqlite-jdbc` 3.53.4.0 artifact, verifies its -SHA-256 digest, extracts only that target's native into the plugin data folder, -loads it, and restores the JVM-wide Xerial loader properties. MySQL installations -and Linux x86_64 SQLite installations do not make this request. - -For an offline Windows, macOS, ARM, musl, or FreeBSD installation, pre-provision -the official `sqlite-jdbc-3.53.4.0.jar` as -`/libraries/sqlite-jdbc-3.53.4.0.jar`. Its SHA-256 -must be `bcb1f51e36f940867e83342f9efbf5968ac44a6bef4d397bb4af7b17b45cd2fb`; -VotingPlugin rejects any other content and then extracts only the current -platform's native without network access. Operators that already provision a -native may instead set both `org.sqlite.lib.path` and `org.sqlite.lib.name` as -JVM properties. Extracted natives use a unique load directory so a replacement -plugin classloader never reuses the prior classloader's JNI path; stale copies -are removed on a best-effort basis. +SQLite retains all 20 native targets from the official `sqlite-jdbc` 3.54.1.0 +artifact in the downloadable plugin. Windows, macOS, Linux (including ARM and +musl), and FreeBSD installations can replace the plugin JAR and start offline; +no new driver download, cache deletion, or manual provisioning is required. +Each embedded native is checked against a pinned SHA-256 digest, extracted to a +unique load directory under the plugin libraries directory, and loaded with the +existing temporary Xerial properties. The JVM-wide properties are restored. +Native loading does not depend on a writable or executable JVM temp directory. +A corrupt or unexpected embedded native fails validation rather than silently +switching to a download. + +The verified-driver fallback remains available if a native resource is absent +from a custom/repackaged installation. It accepts only the official +`sqlite-jdbc-3.54.1.0.jar` (SHA-256 +`f8dce420a6016278497f4f0560f65602b9db858de141b541cf91a4644ebe4639`) +in the VotingPlugin libraries directory, or downloads and verifies that exact +artifact. The normal downloadable plugin never needs this fallback for a +supported target. Explicit `org.sqlite.lib.path` / `org.sqlite.lib.name` JVM +properties retain their existing operator-controlled behavior. Extracted natives +keep unique load directories for replacement classloaders and best-effort +stale-file cleanup. + +Retaining all supported natives adds about 11 MiB of compressed resources compared +to keeping only Linux x86_64. This is necessary for offline drop-in upgrades; +the size target remains advisory, while missing, duplicated, or mismatched natives +fail the package check. Resource verification across all targets does not claim +native execution on foreign operating systems; startup is exercised on the build +host by the isolated packaged NeoForge runtime test with an unusable JVM temp +directory. The package-phase test reports a prominent warning when the downloadable artifact exceeds the 10 MiB size target. Size alone does not fail the build; dependency