From c93b5d17c3ab69c221d596d47bf2b535c00b74fc Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 18 Nov 2026 02:24:05 +0000 Subject: [PATCH 1/4] Clean up interrupted JavaScript dependency downloads --- .../javascript/JavascriptEngineHandler.java | 73 ++-- .../JavascriptDependencyDownloadTest.java | 321 ++++++++++++++++++ 2 files changed, 365 insertions(+), 29 deletions(-) create mode 100644 AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptDependencyDownloadTest.java diff --git a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java index 5a1e709d01..e3836ff9c5 100644 --- a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java +++ b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java @@ -1,7 +1,9 @@ package com.bencodez.advancedcore.api.javascript; +import java.io.Closeable; import java.io.IOException; import java.io.InputStream; +import java.io.InterruptedIOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -439,44 +441,57 @@ private List getArtifacts(String nashornVersion, String asmVersio * @throws IOException if the artifact cannot be downloaded */ private void downloadArtifact(MavenArtifact artifact, Path target) throws IOException { - Path tempFile = target.resolveSibling(target.getFileName() + ".tmp"); - logDebug("JavascriptEngine: downloading optional dependency: " + artifact.getCoordinate()); logDebug("JavascriptEngine: download URL: " + artifact.getMavenCentralJarUrl()); logDebug("JavascriptEngine: download target: " + target); - HttpURLConnection connection = (HttpURLConnection) URI.create(artifact.getMavenCentralJarUrl()).toURL() - .openConnection(); - connection.setConnectTimeout(CONNECT_TIMEOUT); - connection.setReadTimeout(READ_TIMEOUT); - connection.setInstanceFollowRedirects(true); - connection.setRequestProperty("User-Agent", "AdvancedCore-JavascriptEngine"); - - int responseCode = connection.getResponseCode(); - logDebug("JavascriptEngine: Maven Central response for " + artifact.getCoordinate() + ": HTTP " - + responseCode); - - if (responseCode < 200 || responseCode >= 300) { - connection.disconnect(); - throw new IOException("Failed to download " + artifact.getCoordinate() + ", HTTP " + responseCode); - } + Path candidate = null; + try { + HttpURLConnection connection = (HttpURLConnection) URI.create(artifact.getMavenCentralJarUrl()).toURL() + .openConnection(); + try (Closeable disconnect = connection::disconnect) { + connection.setConnectTimeout(CONNECT_TIMEOUT); + connection.setReadTimeout(READ_TIMEOUT); + connection.setInstanceFollowRedirects(true); + connection.setRequestProperty("User-Agent", "AdvancedCore-JavascriptEngine"); + + int responseCode = connection.getResponseCode(); + logDebug("JavascriptEngine: Maven Central response for " + artifact.getCoordinate() + ": HTTP " + + responseCode); + + if (responseCode < 200 || responseCode >= 300) { + throw new IOException("Failed to download " + artifact.getCoordinate() + ", HTTP " + responseCode); + } + + candidate = Files.createTempFile(target.toAbsolutePath().getParent(), "download-", ".tmp"); + try (InputStream input = connection.getInputStream(); + OutputStream output = Files.newOutputStream(candidate)) { + input.transferTo(output); + } + } - try (InputStream input = connection.getInputStream(); OutputStream output = Files.newOutputStream(tempFile)) { - input.transferTo(output); - } finally { - connection.disconnect(); - } + long size = Files.size(candidate); + logDebug("JavascriptEngine: downloaded " + artifact.getCoordinate() + " size=" + size + " bytes."); - long size = Files.size(tempFile); - logDebug("JavascriptEngine: downloaded " + artifact.getCoordinate() + " size=" + size + " bytes."); + if (size <= 0) { + throw new IOException("Downloaded empty jar for " + artifact.getCoordinate()); + } + if (Thread.currentThread().isInterrupted()) { + throw new InterruptedIOException("Interrupted before saving " + artifact.getCoordinate()); + } - if (size <= 0) { - Files.deleteIfExists(tempFile); - throw new IOException("Downloaded empty jar for " + artifact.getCoordinate()); + Files.move(candidate, target, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException | RuntimeException | Error failure) { + if (candidate != null) { + try { + Files.deleteIfExists(candidate); + } catch (IOException | RuntimeException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + } + throw failure; } - Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING); - logDebug("JavascriptEngine: saved optional dependency: " + target); } diff --git a/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptDependencyDownloadTest.java b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptDependencyDownloadTest.java new file mode 100644 index 0000000000..15d5d72410 --- /dev/null +++ b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptDependencyDownloadTest.java @@ -0,0 +1,321 @@ +package com.bencodez.advancedcore.tests.javascript; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.FilterInputStream; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InterruptedIOException; +import java.io.OutputStream; +import java.lang.reflect.InvocationTargetException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import com.bencodez.advancedcore.api.javascript.JavascriptEngineHandler; + +class JavascriptDependencyDownloadTest { + + private static final byte[] VALID = {1, 2, 3}; + private static final byte[] REPLACEMENT = {4, 5, 6}; + + @TempDir + Path directory; + + @Test + void interruptedTransferRemovesPartialCandidateAndPreservesExistingFiles() throws Exception { + Path target = Files.write(directory.resolve("dependency.jar"), VALID); + Path sibling = Files.write(directory.resolve("other.jar.tmp"), VALID); + InterruptedIOException interrupted = new InterruptedIOException("transfer interrupted"); + TestConnection connection = new TestConnection(new ByteArrayInputStream(REPLACEMENT) { + @Override + public long transferTo(OutputStream output) throws IOException { + output.write(REPLACEMENT[0]); + Thread.currentThread().interrupt(); + throw interrupted; + } + }); + + DownloadInvocation download = prepareDownload(connection); + try { + assertSame(interrupted, assertThrows(InterruptedIOException.class, () -> download.run(target))); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + assertTrue(connection.closed); + assertTrue(connection.disconnected); + assertArrayEquals(VALID, Files.readAllBytes(target)); + assertArrayEquals(VALID, Files.readAllBytes(sibling)); + assertEquals(Set.of(target, sibling), files()); + + prepareDownload(new TestConnection(new ByteArrayInputStream(REPLACEMENT))).run(target); + assertArrayEquals(REPLACEMENT, Files.readAllBytes(target)); + assertEquals(Set.of(target, sibling), files()); + } + + @Test + void cancelledTransferWithNormalEofDoesNotPublish() throws Exception { + Path target = Files.write(directory.resolve("dependency.jar"), VALID); + TestConnection connection = new TestConnection(new ByteArrayInputStream(REPLACEMENT) { + @Override + public long transferTo(OutputStream output) throws IOException { + long bytes = super.transferTo(output); + Thread.currentThread().interrupt(); + return bytes; + } + }); + DownloadInvocation download = prepareDownload(connection); + try { + assertThrows(InterruptedIOException.class, () -> download.run(target)); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + } + assertTrue(connection.closed); + assertTrue(connection.disconnected); + assertArrayEquals(VALID, Files.readAllBytes(target)); + assertEquals(Set.of(target), files()); + } + + @Test + void interruptedAttemptDoesNotRemoveAnotherAttemptsPublication() throws Exception { + Path target = directory.resolve("dependency.jar"); + Path sibling = Files.write(directory.resolve("dependency.jar.tmp"), VALID); + DownloadInvocation competing = prepareDownload(new TestConnection(new ByteArrayInputStream(REPLACEMENT))); + IOException transferFailure = new IOException("transfer failed"); + TestConnection connection = new TestConnection(new ByteArrayInputStream(VALID) { + @Override + public long transferTo(OutputStream output) throws IOException { + output.write(VALID[0]); + Set inFlight = files(); + assertEquals(2, inFlight.size()); + var thread = Executors.newSingleThreadExecutor(); + try { + thread.submit(() -> { + competing.run(target); + return null; + }).get(10, TimeUnit.SECONDS); + } catch (Exception e) { + throw new AssertionError("Competing download did not complete", e); + } finally { + thread.shutdownNow(); + } + assertTrue(files().containsAll(inFlight)); + throw transferFailure; + } + }); + + DownloadInvocation download = prepareDownload(connection); + assertSame(transferFailure, assertThrows(IOException.class, () -> download.run(target))); + assertTrue(connection.closed); + assertTrue(connection.disconnected); + assertArrayEquals(REPLACEMENT, Files.readAllBytes(target)); + assertArrayEquals(VALID, Files.readAllBytes(sibling)); + assertEquals(Set.of(target, sibling), files()); + } + + @Test + void outputOpenFailureRemovesCandidateAndClosesInput() throws Exception { + assertOutputFailureCleanup(true); + } + + @Test + void outputWriteFailureRemovesCandidateAndClosesInput() throws Exception { + assertOutputFailureCleanup(false); + } + + private void assertOutputFailureCleanup(boolean failOnOpen) throws Exception { + Path target = Files.write(directory.resolve("dependency.jar"), VALID); + IOException outputFailure = new IOException("output failed"); + AtomicBoolean outputClosed = new AtomicBoolean(); + TestConnection connection = new TestConnection(new ByteArrayInputStream(REPLACEMENT)); + DownloadInvocation download = prepareDownload(connection); + try (var ignored = mockStatic(Files.class, invocation -> { + if (!invocation.getMethod().getName().equals("newOutputStream")) { + return invocation.callRealMethod(); + } + if (failOnOpen) { + throw outputFailure; + } + return new FilterOutputStream((OutputStream) invocation.callRealMethod()) { + @Override + public void write(int value) throws IOException { + out.write(value); + throw outputFailure; + } + + @Override + public void close() throws IOException { + super.close(); + outputClosed.set(true); + } + }; + })) { + assertSame(outputFailure, assertThrows(IOException.class, () -> download.run(target))); + } + assertEquals(!failOnOpen, outputClosed.get()); + assertTrue(connection.closed); + assertTrue(connection.disconnected); + assertArrayEquals(VALID, Files.readAllBytes(target)); + assertEquals(Set.of(target), files()); + } + + @Test + void emptyBodyAndFailedMoveRemoveCandidates() throws Exception { + Path target = Files.createDirectory(directory.resolve("dependency.jar")); + Path child = Files.write(target.resolve("keep"), VALID); + TestConnection empty = new TestConnection(new ByteArrayInputStream(new byte[0])); + DownloadInvocation emptyDownload = prepareDownload(empty); + IOException emptyFailure = assertThrows(IOException.class, () -> emptyDownload.run(target)); + assertTrue(emptyFailure.getMessage().startsWith("Downloaded empty jar")); + assertEquals(Set.of(target), files()); + + TestConnection nonempty = new TestConnection(new ByteArrayInputStream(REPLACEMENT)); + DownloadInvocation nonemptyDownload = prepareDownload(nonempty); + assertThrows(IOException.class, () -> nonemptyDownload.run(target)); + assertTrue(empty.closed && empty.disconnected); + assertTrue(nonempty.closed && nonempty.disconnected); + assertArrayEquals(VALID, Files.readAllBytes(child)); + assertEquals(Set.of(target), files()); + } + + @Test + void deletionFailureIsSuppressedOnTransferFailure() throws Exception { + Path target = Files.write(directory.resolve("dependency.jar"), VALID); + IOException transferFailure = new IOException("transfer failed"); + IOException cleanupFailure = new IOException("deletion failed"); + TestConnection connection = new TestConnection(new ByteArrayInputStream(REPLACEMENT) { + @Override + public long transferTo(OutputStream output) throws IOException { + output.write(REPLACEMENT[0]); + throw transferFailure; + } + }); + DownloadInvocation download = prepareDownload(connection); + try (var ignored = mockStatic(Files.class, invocation -> { + if (invocation.getMethod().getName().equals("deleteIfExists")) { + throw cleanupFailure; + } + return invocation.callRealMethod(); + })) { + assertSame(transferFailure, assertThrows(IOException.class, () -> download.run(target))); + assertArrayEquals(new Throwable[]{cleanupFailure}, transferFailure.getSuppressed()); + } + assertTrue(connection.closed); + assertTrue(connection.disconnected); + assertArrayEquals(VALID, Files.readAllBytes(target)); + } + + private Set files() throws IOException { + try (var paths = Files.list(directory)) { + return paths.collect(Collectors.toSet()); + } + } + + private static DownloadInvocation prepareDownload(TestConnection connection) throws Exception { + Class artifactType = Class.forName(JavascriptEngineHandler.class.getName() + "$MavenArtifact"); + var constructor = artifactType.getDeclaredConstructor(String.class, String.class, String.class); + constructor.setAccessible(true); + Object artifact = constructor.newInstance("example", "dependency", "1"); + var getUrl = artifactType.getDeclaredMethod("getMavenCentralJarUrl"); + getUrl.setAccessible(true); + String repositoryUrl = (String) getUrl.invoke(artifact); + var download = JavascriptEngineHandler.class.getDeclaredMethod("downloadArtifact", artifactType, Path.class); + download.setAccessible(true); + URL url = URL.of(URI.create(repositoryUrl), new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL ignored) { + return connection; + } + }); + URI uri = mock(URI.class); + when(uri.toURL()).thenReturn(url); + return target -> { + try (var uris = mockStatic(URI.class, CALLS_REAL_METHODS)) { + uris.when(() -> URI.create(repositoryUrl)).thenReturn(uri); + try { + download.invoke(new JavascriptEngineHandler(), artifact, target); + } catch (InvocationTargetException failure) { + if (failure.getCause() instanceof Exception cause) { + throw cause; + } + throw (Error) failure.getCause(); + } + } + }; + } + + @FunctionalInterface + private interface DownloadInvocation { + void run(Path target) throws Exception; + } + + private static final class TestConnection extends HttpURLConnection { + private final InputStream body; + private boolean closed; + private boolean disconnected; + + TestConnection(InputStream body) { + super(null); + this.body = body; + } + + @Override + public int getResponseCode() { + return HTTP_OK; + } + + @Override + public InputStream getInputStream() { + return new FilterInputStream(body) { + @Override + public long transferTo(OutputStream output) throws IOException { + return body.transferTo(output); + } + + @Override + public void close() throws IOException { + closed = true; + super.close(); + } + }; + } + + @Override + public void disconnect() { + disconnected = true; + } + + @Override + public boolean usingProxy() { + return false; + } + + @Override + public void connect() { + } + } +} From 4ee8f0d0a4054350ab2a24afd6e9ae49778deaf0 Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 21 Nov 2026 01:40:37 +0000 Subject: [PATCH 2/4] Close unpublished JavaScript loaders after factory failures --- .../javascript/JavascriptEngineHandler.java | 7 +- .../JavascriptLoaderOwnershipTest.java | 83 +++++++++++++++++++ 2 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptLoaderOwnershipTest.java diff --git a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java index e3836ff9c5..6dc8ada655 100644 --- a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java +++ b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java @@ -292,6 +292,7 @@ private ScriptEngine getDownloadedEngine(String nashornVersion, String asmVersio logDebug("JavascriptEngine: preparing downloaded Nashorn " + nashornVersion + "."); logDebug("JavascriptEngine: dependency folder: " + getLibraryFolder().resolve(nashornVersion)); + URLClassLoader candidateLoader = null; try { List jars = getOrDownloadJars(nashornVersion, asmVersion); @@ -308,13 +309,13 @@ private ScriptEngine getDownloadedEngine(String nashornVersion, String asmVersio } URLClassLoader loader = createClassLoader(jars); + candidateLoader = loader; logDebug("JavascriptEngine: loading Nashorn factory class from downloaded classloader."); Class foundFactory = Class.forName(NASHORN_FACTORY_CLASS, true, loader); Method foundMethod = getScriptEngineMethod(foundFactory); if (foundMethod == null) { - closeQuietly(loader); logWarning("JavascriptEngine: Nashorn " + nashornVersion + " was loaded, but no getScriptEngine method was found."); return null; @@ -324,7 +325,6 @@ private ScriptEngine getDownloadedEngine(String nashornVersion, String asmVersio ScriptEngine engine = (ScriptEngine) foundMethod.invoke(foundFactory.getDeclaredConstructor().newInstance()); if (engine == null) { - closeQuietly(loader); logWarning("JavascriptEngine: Nashorn " + nashornVersion + " returned a null script engine."); return null; } @@ -335,6 +335,7 @@ private ScriptEngine getDownloadedEngine(String nashornVersion, String asmVersio factory = foundFactory; methodToUse = foundMethod; loadedVersion = nashornVersion; + candidateLoader = null; // Published loader ownership belongs to this handler. logDebug("JavascriptEngine: loaded optional Nashorn JavaScript engine " + nashornVersion + "."); logEngine("JavascriptEngine: downloaded engine details", engine); @@ -344,6 +345,8 @@ private ScriptEngine getDownloadedEngine(String nashornVersion, String asmVersio + e.getClass().getSimpleName() + ": " + e.getMessage()); logDebug(e); return null; + } finally { + if (candidateLoader != null) closeQuietly(candidateLoader); } } diff --git a/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptLoaderOwnershipTest.java b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptLoaderOwnershipTest.java new file mode 100644 index 0000000000..72096258a9 --- /dev/null +++ b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptLoaderOwnershipTest.java @@ -0,0 +1,83 @@ +package com.bencodez.advancedcore.tests.javascript; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; +import javax.script.ScriptEngine; +import javax.tools.ToolProvider; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import com.bencodez.advancedcore.AdvancedCorePlugin; +import com.bencodez.advancedcore.api.javascript.JavascriptEngineHandler; + +class JavascriptLoaderOwnershipTest { + @TempDir Path directory; + @Test void throwingConstructorClosesOnlyUnpublishedLoader() throws Exception { exercise("constructor"); } + @Test void throwingFactoryMethodClosesOnlyUnpublishedLoader() throws Exception { exercise("method"); } + @Test void missingFactoryMethodStillClosesLoader() throws Exception { exercise("missing"); } + @Test void successfulLoaderRemainsOwnedUntilExplicitClose() throws Exception { exercise("success"); } + + private void exercise(String mode) throws Exception { + String propertyKey = "test.javascript.loader." + UUID.randomUUID(); + String marker = "marker-" + UUID.randomUUID() + ".txt"; + String constructor = mode.equals("constructor") ? "throw new IllegalStateException(\"constructor refused\");" : ""; + String method = mode.equals("missing") ? "" : "public javax.script.ScriptEngine getScriptEngine(){" + + (mode.equals("method") ? "throw new IllegalStateException(\"factory refused\");" : "return new Engine();") + "}"; + String source = "package org.openjdk.nashorn.api.scripting; public class NashornScriptEngineFactory {" + + "static { System.getProperties().put(\"" + propertyKey + "\",NashornScriptEngineFactory.class.getClassLoader()); }" + + "public NashornScriptEngineFactory(){" + constructor + "}" + method + + "static class Engine extends javax.script.AbstractScriptEngine {" + + "public Object eval(String s,javax.script.ScriptContext c){return null;}" + + "public Object eval(java.io.Reader r,javax.script.ScriptContext c){return null;}" + + "public javax.script.Bindings createBindings(){return new javax.script.SimpleBindings();}" + + "public javax.script.ScriptEngineFactory getFactory(){return null;}}}"; + Path sourceFile = directory.resolve("source/org/openjdk/nashorn/api/scripting/NashornScriptEngineFactory.java"); + Files.createDirectories(sourceFile.getParent()); Files.writeString(sourceFile, source); + Path classes = directory.resolve("classes"); Files.createDirectories(classes); + assertEquals(0, ToolProvider.getSystemJavaCompiler().run(null, null, null, "-d", classes.toString(), sourceFile.toString())); + Path folder = directory.resolve("libs/nashorn/15.7"); Files.createDirectories(folder); + try (var jar = new JarOutputStream(Files.newOutputStream(folder.resolve("nashorn-core-15.7.jar")))) { + try (var files = Files.walk(classes)) { + for (Path file : files.filter(Files::isRegularFile).toList()) { + jar.putNextEntry(new JarEntry(classes.relativize(file).toString().replace('\\', '/'))); + Files.copy(file, jar); jar.closeEntry(); + } + } + jar.putNextEntry(new JarEntry(marker)); jar.write(1); jar.closeEntry(); + } + for (String name : new String[]{"asm", "asm-commons", "asm-analysis", "asm-tree", "asm-util"}) { + try (var jar = new JarOutputStream(Files.newOutputStream(folder.resolve(name + "-9.8.jar")))) { } + } + var plugin = mock(AdvancedCorePlugin.class); when(plugin.getDataFolder()).thenReturn(directory.toFile()); when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger()); + var handler = new JavascriptEngineHandler(); handler.setPlugin(plugin); handler.setAutoDownload(false); + Path oldFolder = directory.resolve("old"); Files.createDirectories(oldFolder); Files.writeString(oldFolder.resolve(marker), "previous"); + try (var previous = new URLClassLoader(new URL[]{oldFolder.toUri().toURL()}, null)) { + handler.setNashornClassLoader(previous); + URLClassLoader candidate = null; + try { + Method load = JavascriptEngineHandler.class.getDeclaredMethod("getDownloadedEngine", String.class, String.class); + load.setAccessible(true); Object engine = load.invoke(handler, "15.7", "9.8"); + candidate = (URLClassLoader) System.getProperties().get(propertyKey); assertNotNull(candidate); + if (mode.equals("success")) { + assertInstanceOf(ScriptEngine.class, engine); assertSame(candidate, handler.getNashornClassLoader()); + assertNotNull(candidate.getResource(marker)); assertNull(previous.getResource(marker)); + handler.closeExistingClassLoader(); assertNull(candidate.getResource(marker)); + } else { + assertNull(engine); assertSame(previous, handler.getNashornClassLoader()); assertNotNull(previous.getResource(marker)); + assertNull(candidate.getResource(marker), "failed attempt must close its own unpublished loader"); + } + } finally { + System.getProperties().remove(propertyKey); + if (candidate != null) candidate.close(); + } + } + } +} From f2e23174df1313aa07a85493a096fac0c1f89685 Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 21 Nov 2026 03:02:54 +0000 Subject: [PATCH 3/4] Recover structurally unreadable cached JavaScript archives --- .../javascript/JavascriptEngineHandler.java | 32 +++++++++-- .../JavascriptCacheArchiveRecoveryTest.java | 53 +++++++++++++++++++ .../JavascriptDependencyDownloadTest.java | 15 +++++- 3 files changed, 95 insertions(+), 5 deletions(-) create mode 100644 AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptCacheArchiveRecoveryTest.java diff --git a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java index 6dc8ada655..4638fcddb4 100644 --- a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java +++ b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java @@ -16,6 +16,8 @@ import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; +import java.util.jar.JarFile; +import java.util.zip.ZipException; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; @@ -372,9 +374,18 @@ private List getOrDownloadJars(String nashornVersion, String asmVersion) t Path jar = libraryFolder.resolve(nashornVersion).resolve(artifact.getFileName()); if (Files.exists(jar)) { - logDebug("JavascriptEngine: found dependency: " + artifact.getCoordinate() + " at " + jar); - jars.add(jar); - continue; + if (!Files.isRegularFile(jar)) { + throw new IOException("Dependency cache path is not a regular file: " + artifact.getCoordinate()); + } + if (isReadableJar(jar)) { + logDebug("JavascriptEngine: found dependency: " + artifact.getCoordinate() + " at " + jar); + jars.add(jar); + continue; + } + if (Files.isSymbolicLink(jar)) { + throw new IOException("Cannot replace unreadable dependency symlink: " + artifact.getCoordinate()); + } + logWarning("JavascriptEngine: unreadable cached dependency: " + artifact.getCoordinate()); } logWarning("JavascriptEngine: missing dependency: " + artifact.getCoordinate() + " expected at " + jar); @@ -479,9 +490,15 @@ private void downloadArtifact(MavenArtifact artifact, Path target) throws IOExce if (size <= 0) { throw new IOException("Downloaded empty jar for " + artifact.getCoordinate()); } + if (!isReadableJar(candidate)) { + throw new IOException("Downloaded unreadable jar for " + artifact.getCoordinate()); + } if (Thread.currentThread().isInterrupted()) { throw new InterruptedIOException("Interrupted before saving " + artifact.getCoordinate()); } + if (Files.isDirectory(target) || Files.isSymbolicLink(target)) { + throw new IOException("Cannot replace dependency directory or symlink: " + artifact.getCoordinate()); + } Files.move(candidate, target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException | RuntimeException | Error failure) { @@ -498,6 +515,15 @@ private void downloadArtifact(MavenArtifact artifact, Path target) throws IOExce logDebug("JavascriptEngine: saved optional dependency: " + target); } + /** Structural archive check only; this does not impose a version or checksum policy. */ + private boolean isReadableJar(Path path) throws IOException { + try (JarFile ignored = new JarFile(path.toFile())) { + return true; + } catch (ZipException invalidArchive) { + return false; + } + } + /** * Creates a URL class loader for dependency jars. * diff --git a/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptCacheArchiveRecoveryTest.java b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptCacheArchiveRecoveryTest.java new file mode 100644 index 0000000000..f12618846c --- /dev/null +++ b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptCacheArchiveRecoveryTest.java @@ -0,0 +1,53 @@ +package com.bencodez.advancedcore.tests.javascript; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import java.io.*;import java.net.*;import java.nio.file.*;import java.lang.reflect.*;import java.util.*;import java.util.concurrent.atomic.AtomicInteger;import java.util.jar.*; +import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir; +import com.bencodez.advancedcore.AdvancedCorePlugin; +import com.bencodez.advancedcore.api.javascript.JavascriptEngineHandler; +class JavascriptCacheArchiveRecoveryTest { + @TempDir Path directory; + private static byte[] jar(String text)throws IOException{var b=new ByteArrayOutputStream();try(var z=new JarOutputStream(b)){z.putNextEntry(new JarEntry("entry.txt"));z.write(text.getBytes(java.nio.charset.StandardCharsets.UTF_8));z.closeEntry();}return b.toByteArray();} + @Test void repairsCorruptNashorn()throws Exception{repair("nashorn-core",new byte[]{1,2,3},false);} + @Test void repairsEmptyNashorn()throws Exception{repair("nashorn-core",new byte[0],false);} + @Test void repairsTruncatedNashorn()throws Exception{repair("nashorn-core",Arrays.copyOf(jar("valid"),20),false);} + @Test void repairsCorruptAsm()throws Exception{repair("asm",new byte[]{1,2,3},false);} + @Test void repairsEmptyAsm()throws Exception{repair("asm",new byte[0],false);} + @Test void repairsTruncatedAsm()throws Exception{repair("asm",Arrays.copyOf(jar("valid"),20),false);} + @Test void repairsAllStructurallyBrokenArchives()throws Exception{repair("nashorn-core",new byte[]{1},true);} + private void repair(String artifact,byte[] broken,boolean all)throws Exception{ + byte[] good=jar("replacement");var f=new Fixture(good);Path target=f.folder.resolve(file(artifact));Files.write(target,broken);if(all)for(String a:ARTIFACTS)Files.write(f.folder.resolve(file(a)),broken); + try(var ignored=f.peer()){assertEquals(6,load(f.handler).size());} + assertArrayEquals(good,Files.readAllBytes(target));assertEquals(all?6:1,f.requests.get());f.preserved(); + } + @Test void disabledDownloadLeavesBrokenBytesAndReturnsUnavailable()throws Exception{ + var f=new Fixture(jar("unused"));f.handler.setAutoDownload(false);Path target=f.folder.resolve(file("asm"));byte[] broken={7};Files.write(target,broken); + try(var ignored=f.peer()){assertTrue(load(f.handler).isEmpty());}assertArrayEquals(broken,Files.readAllBytes(target));assertEquals(0,f.requests.get());f.preserved(); + } + @Test void validCustomArchivesArePreservedWithoutCanonicalBytePolicy()throws Exception{ + var f=new Fixture(jar("different"));f.handler.setAutoDownload(false);byte[] before=Files.readAllBytes(f.folder.resolve(file("nashorn-core"))); + try(var ignored=f.peer()){assertEquals(6,load(f.handler).size());}assertArrayEquals(before,Files.readAllBytes(f.folder.resolve(file("nashorn-core"))));assertEquals(0,f.requests.get());f.preserved(); + } + @Test void invalidReplacementCannotOverwriteAConcurrentGoodPublication()throws Exception{ + var f=new Fixture(new byte[]{1,2,3});Path target=f.folder.resolve(file("asm"));Files.write(target,new byte[]{9});byte[] good=jar("other attempt");f.beforeBody=()->{try{Files.write(target,good);}catch(IOException e){throw new UncheckedIOException(e);}}; + try(var ignored=f.peer()){assertThrows(IOException.class,()->load(f.handler));}assertArrayEquals(good,Files.readAllBytes(target));f.preserved(); + } + @Test void directoryAtManagedPathIsNeverRemoved()throws Exception{ + var f=new Fixture(jar("unused"));Path target=f.folder.resolve(file("asm"));Files.delete(target);Files.createDirectory(target);Files.writeString(target.resolve("operator.txt"),"preserve"); + try(var ignored=f.peer()){assertThrows(IOException.class,()->load(f.handler));}assertEquals("preserve",Files.readString(target.resolve("operator.txt")));assertEquals(0,f.requests.get());f.preserved(); + } + private static final List ARTIFACTS=List.of("nashorn-core","asm","asm-commons","asm-analysis","asm-tree","asm-util"); + private static String file(String a){return a+"-"+(a.equals("nashorn-core")?"15.7":"9.8")+".jar";} + @SuppressWarnings("unchecked") private static List load(JavascriptEngineHandler h)throws Exception{ + var m=JavascriptEngineHandler.class.getDeclaredMethod("getOrDownloadJars",String.class,String.class);m.setAccessible(true);try{return (List)m.invoke(h,"15.7","9.8");}catch(InvocationTargetException e){if(e.getCause() instanceof Exception x)throw x;throw e;} + } + private class Fixture{ + final Path folder=directory.resolve("libs/nashorn/15.7");final JavascriptEngineHandler handler=new JavascriptEngineHandler();final AtomicInteger requests=new AtomicInteger();final byte[] payload;Runnable beforeBody=()->{}; + Fixture(byte[] payload)throws Exception{this.payload=payload;Files.createDirectories(folder);for(String a:ARTIFACTS)Files.write(folder.resolve(file(a)),jar("custom "+a));Files.writeString(folder.resolve("existing.jar.tmp"),"preserve");Files.writeString(folder.resolve("operator.jar"),"unrelated");var plugin=mock(AdvancedCorePlugin.class);when(plugin.getDataFolder()).thenReturn(directory.toFile());when(plugin.getLogger()).thenReturn(java.util.logging.Logger.getAnonymousLogger());handler.setPlugin(plugin);handler.setAutoDownload(true);} + org.mockito.MockedStatic peer()throws Exception{ + Map peers=new HashMap<>();for(String a:ARTIFACTS){String u="https://repo1.maven.org/maven2/"+(a.equals("nashorn-core")?"org/openjdk/nashorn/":"org/ow2/asm/")+a+"/"+(a.equals("nashorn-core")?"15.7":"9.8")+"/"+file(a);URL url=URL.of(URI.create(u),new URLStreamHandler(){protected URLConnection openConnection(URL value){requests.incrementAndGet();return new HttpURLConnection(value){public void connect(){}public void disconnect(){}public boolean usingProxy(){return false;}public int getResponseCode(){return 200;}public InputStream getInputStream(){beforeBody.run();return new ByteArrayInputStream(payload);}};}});URI uri=mock(URI.class);when(uri.toURL()).thenReturn(url);peers.put(u,uri);} + var statics=mockStatic(URI.class,CALLS_REAL_METHODS);statics.when(()->URI.create(anyString())).thenAnswer(call->{String u=call.getArgument(0);return peers.containsKey(u)?peers.get(u):call.callRealMethod();});return statics; + } + void preserved()throws Exception{assertEquals("preserve",Files.readString(folder.resolve("existing.jar.tmp")));assertEquals("unrelated",Files.readString(folder.resolve("operator.jar")));try(var files=Files.list(folder)){assertFalse(files.anyMatch(p->p.getFileName().toString().startsWith("download-")));}} + } +} diff --git a/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptDependencyDownloadTest.java b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptDependencyDownloadTest.java index 15d5d72410..a5e42179bc 100644 --- a/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptDependencyDownloadTest.java +++ b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptDependencyDownloadTest.java @@ -38,8 +38,19 @@ class JavascriptDependencyDownloadTest { - private static final byte[] VALID = {1, 2, 3}; - private static final byte[] REPLACEMENT = {4, 5, 6}; + private static final byte[] VALID = archive("initial"); + private static final byte[] REPLACEMENT = archive("replacement"); + + private static byte[] archive(String value) { + try { + var bytes = new java.io.ByteArrayOutputStream(); + try (var jar = new java.util.jar.JarOutputStream(bytes)) { + var entry = new java.util.jar.JarEntry("entry.txt"); entry.setTime(0); + jar.putNextEntry(entry); jar.write(value.getBytes(java.nio.charset.StandardCharsets.UTF_8)); jar.closeEntry(); + } + return bytes.toByteArray(); + } catch (IOException failure) { throw new AssertionError(failure); } + } @TempDir Path directory; From a1e45afff016d86782ada14e6d97a6f1dda37a5c Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 21 Nov 2026 03:09:39 +0000 Subject: [PATCH 4/4] Preserve healthy cache publications during archive repair --- .../api/javascript/JavascriptEngineHandler.java | 13 +++++++++++-- .../JavascriptCacheArchiveRecoveryTest.java | 11 +++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java index 4638fcddb4..7231b1f18e 100644 --- a/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java +++ b/AdvancedCore/src/main/java/com/bencodez/advancedcore/api/javascript/JavascriptEngineHandler.java @@ -397,7 +397,7 @@ private List getOrDownloadJars(String nashornVersion, String asmVersion) t } Files.createDirectories(jar.getParent()); - downloadArtifact(artifact, jar); + downloadArtifact(artifact, jar, true); jars.add(jar); } @@ -455,6 +455,10 @@ private List getArtifacts(String nashornVersion, String asmVersio * @throws IOException if the artifact cannot be downloaded */ private void downloadArtifact(MavenArtifact artifact, Path target) throws IOException { + downloadArtifact(artifact, target, false); + } + + private void downloadArtifact(MavenArtifact artifact, Path target, boolean preserveReadableCache) throws IOException { logDebug("JavascriptEngine: downloading optional dependency: " + artifact.getCoordinate()); logDebug("JavascriptEngine: download URL: " + artifact.getMavenCentralJarUrl()); logDebug("JavascriptEngine: download target: " + target); @@ -500,7 +504,12 @@ private void downloadArtifact(MavenArtifact artifact, Path target) throws IOExce throw new IOException("Cannot replace dependency directory or symlink: " + artifact.getCoordinate()); } - Files.move(candidate, target, StandardCopyOption.REPLACE_EXISTING); + if (preserveReadableCache && Files.exists(target) && isReadableJar(target)) { + Files.delete(candidate); + return; + } + // No non-atomic fallback: an unsupported publication must preserve the prior cache. + Files.move(candidate, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (IOException | RuntimeException | Error failure) { if (candidate != null) { try { diff --git a/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptCacheArchiveRecoveryTest.java b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptCacheArchiveRecoveryTest.java index f12618846c..b8fa222200 100644 --- a/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptCacheArchiveRecoveryTest.java +++ b/AdvancedCore/src/test/java/com/bencodez/advancedcore/tests/javascript/JavascriptCacheArchiveRecoveryTest.java @@ -32,6 +32,17 @@ private void repair(String artifact,byte[] broken,boolean all)throws Exception{ var f=new Fixture(new byte[]{1,2,3});Path target=f.folder.resolve(file("asm"));Files.write(target,new byte[]{9});byte[] good=jar("other attempt");f.beforeBody=()->{try{Files.write(target,good);}catch(IOException e){throw new UncheckedIOException(e);}}; try(var ignored=f.peer()){assertThrows(IOException.class,()->load(f.handler));}assertArrayEquals(good,Files.readAllBytes(target));f.preserved(); } + @Test void healthyArchivePublishedDuringRepairIsPreserved()throws Exception{ + var f=new Fixture(jar("downloaded"));Path target=f.folder.resolve(file("asm"));Files.write(target,new byte[]{9});byte[] good=jar("operator publication");f.beforeBody=()->{try{Files.write(target,good);}catch(IOException e){throw new UncheckedIOException(e);}}; + try(var ignored=f.peer()){assertEquals(6,load(f.handler).size());}assertArrayEquals(good,Files.readAllBytes(target));assertEquals(1,f.requests.get());f.preserved(); + } + @Test void unsupportedAtomicPublicationPreservesBrokenCache()throws Exception{ + var f=new Fixture(jar("downloaded"));Path target=f.folder.resolve(file("asm"));byte[] broken={9};Files.write(target,broken); + try(var ignored=f.peer();var files=mockStatic(Files.class,CALLS_REAL_METHODS)){ + files.when(()->Files.move(any(Path.class),eq(target),eq(StandardCopyOption.ATOMIC_MOVE),eq(StandardCopyOption.REPLACE_EXISTING))).thenThrow(new AtomicMoveNotSupportedException("candidate","cache","unsupported")); + assertThrows(AtomicMoveNotSupportedException.class,()->load(f.handler)); + }assertArrayEquals(broken,Files.readAllBytes(target));f.preserved(); + } @Test void directoryAtManagedPathIsNeverRemoved()throws Exception{ var f=new Fixture(jar("unused"));Path target=f.folder.resolve(file("asm"));Files.delete(target);Files.createDirectory(target);Files.writeString(target.resolve("operator.txt"),"preserve"); try(var ignored=f.peer()){assertThrows(IOException.class,()->load(f.handler));}assertEquals("preserve",Files.readString(target.resolve("operator.txt")));assertEquals(0,f.requests.get());f.preserved();