Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -14,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;
Expand Down Expand Up @@ -290,6 +294,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<Path> jars = getOrDownloadJars(nashornVersion, asmVersion);

Expand All @@ -306,13 +311,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;
Expand All @@ -322,7 +327,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;
}
Expand All @@ -333,6 +337,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);
Expand All @@ -342,6 +347,8 @@ private ScriptEngine getDownloadedEngine(String nashornVersion, String asmVersio
+ e.getClass().getSimpleName() + ": " + e.getMessage());
logDebug(e);
return null;
} finally {
if (candidateLoader != null) closeQuietly(candidateLoader);
}
}

Expand All @@ -367,9 +374,18 @@ private List<Path> 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);
Expand All @@ -381,7 +397,7 @@ private List<Path> getOrDownloadJars(String nashornVersion, String asmVersion) t
}

Files.createDirectories(jar.getParent());
downloadArtifact(artifact, jar);
downloadArtifact(artifact, jar, true);
jars.add(jar);
}

Expand Down Expand Up @@ -439,45 +455,82 @@ private List<MavenArtifact> 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");
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);

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");
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);
}
}

int responseCode = connection.getResponseCode();
logDebug("JavascriptEngine: Maven Central response for " + artifact.getCoordinate() + ": HTTP "
+ responseCode);
long size = Files.size(candidate);
logDebug("JavascriptEngine: downloaded " + artifact.getCoordinate() + " size=" + size + " bytes.");

if (responseCode < 200 || responseCode >= 300) {
connection.disconnect();
throw new IOException("Failed to download " + artifact.getCoordinate() + ", HTTP " + responseCode);
}
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());
}

try (InputStream input = connection.getInputStream(); OutputStream output = Files.newOutputStream(tempFile)) {
input.transferTo(output);
} finally {
connection.disconnect();
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 {
Files.deleteIfExists(candidate);
} catch (IOException | RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
}
}
throw failure;
}

long size = Files.size(tempFile);
logDebug("JavascriptEngine: downloaded " + artifact.getCoordinate() + " size=" + size + " bytes.");
logDebug("JavascriptEngine: saved optional dependency: " + target);
}

if (size <= 0) {
Files.deleteIfExists(tempFile);
throw new IOException("Downloaded empty jar for " + artifact.getCoordinate());
/** 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;
}

Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING);

logDebug("JavascriptEngine: saved optional dependency: " + target);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
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 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();
}
private static final List<String> 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<Path> load(JavascriptEngineHandler h)throws Exception{
var m=JavascriptEngineHandler.class.getDeclaredMethod("getOrDownloadJars",String.class,String.class);m.setAccessible(true);try{return (List<Path>)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<URI> peer()throws Exception{
Map<String,URI> 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-")));}}
}
}
Loading
Loading