Limit pack modules to the API, the JDK and their own pack

The pack class loader's parent is now ApiAndJdkClassLoader: com.volmit.
classes and resources come from the API's loader, everything else from
the platform loader, so modules no longer see Iris internals or the
libraries Iris bundles.

Before any class is defined, a pack load now fails when a jar holds a
com.volmit. class, and when a class references a class that is not in
the API, the JDK or a jar of the pack (read with java.lang.classfile).
Linkage errors while installing name the module's jar. ModuleInfo names
and versions reject line breaks and other control characters.
This commit is contained in:
piexel committed 2026-10-05 18:24:53 +02:00
1 parent 862f4d19be
commit 1553959cf4
11 files changed
+563 -60

No files matched your search

@@ -41,6 +41,16 @@ class ApiValuesTest {
assertThrows(NullPointerException.class, () -> ModuleInfo.of("example:moss", null, "1.0.0"));
}
@Test
void moduleInfoTextFitsOnOneLogLine() {
for (var broken : List.of("Moss\nINFO forged line", "Moss\r", "Moss\tTabbed", "Moss\u2028Next")) {
var failure = assertThrows(IllegalArgumentException.class, () -> ModuleInfo.of("example:moss", broken, "1.0.0"));
assertEquals("Module name of example:moss contains a line break or other control character", failure.getMessage());
}
assertThrows(IllegalArgumentException.class, () -> ModuleInfo.of("example:moss", "Moss", "1.0\n"));
assertEquals("Mosß é", ModuleInfo.of("example:moss", "Mosß é", "1.0.0").name());
}
@Test
void sparseObjectsCopySortAndRejectDuplicateOrOutOfBoundsBlocks() {
var a = new ObjectBlock(new BlockPosition(-1, 0, 0), new BlockState("minecraft:stone"));
@@ -0,0 +1,48 @@
package com.volmit.host;
import com.volmit.IrisModule;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class ApiAndJdkClassLoaderTest {
private static final ClassLoader HOST = IrisModule.class.getClassLoader();
private static final String HOST_LIBRARY_SERVICE_FILE = "META-INF/services/org.junit.platform.engine.TestEngine";
private final ApiAndJdkClassLoader loader = new ApiAndJdkClassLoader(HOST);
private static String classFile(Class<?> type) {
return type.getName().replace('.', '/') + ".class";
}
@Test
void loadsApiClassesFromTheHostAndJdkClassesFromThePlatform() throws Exception {
assertSame(IrisModule.class, loader.loadClass(IrisModule.class.getName()));
assertSame(List.class, loader.loadClass(List.class.getName()));
assertSame(java.sql.Connection.class, loader.loadClass(java.sql.Connection.class.getName()));
}
@Test
void hidesHostClassesOutsideTheApi() {
assertDoesNotThrow(() -> HOST.loadClass(Test.class.getName()));
assertThrows(ClassNotFoundException.class, () -> loader.loadClass(Test.class.getName()));
}
@Test
void resourcesFollowTheSameRuleAsClasses() throws Exception {
assertNotNull(loader.getResource(classFile(IrisModule.class)));
assertNotNull(loader.getResource(classFile(List.class)));
assertNull(loader.getResource(classFile(Test.class)));
assertFalse(Collections.list(HOST.getResources(HOST_LIBRARY_SERVICE_FILE)).isEmpty());
assertTrue(Collections.list(loader.getResources(HOST_LIBRARY_SERVICE_FILE)).isEmpty());
}
@Test
void knowsWhichClassesItHasWithoutLoadingThem() {
assertTrue(loader.hasClass(IrisModule.class.getName()));
assertTrue(loader.hasClass("java.lang.String"));
assertFalse(loader.hasClass(Test.class.getName()));
assertFalse(loader.hasClass("com.volmit.DoesNotExist"));
}
}
@@ -1,5 +1,7 @@
package com.volmit.host;
import com.volmit.IrisModule;
import com.volmit.example.placement.AnchorModule;
import com.volmit.example.placement.PlacementModules;
import com.volmit.support.TestModuleJar;
import org.junit.jupiter.api.Test;
@@ -21,6 +23,7 @@ class PackModulesTest {
private static final String SHARED_CLASS = "pack.shared.Util";
private static final String SHARED_SOURCE = "package pack.shared; public final class Util {}";
private static final byte[] UNUSED_CLASS_BYTES = {(byte) 0xCA, (byte) 0xFE};
private static final String VERSIONED_SHARED_CLASS = "META-INF/versions/9/pack/shared/Util.class";
private static final String DEFINED_PROPERTY = "irisapi.test.packModuleConstructed";
@TempDir
@@ -36,6 +39,11 @@ class PackModulesTest {
return LoadedModules.load(modules, Map.of());
}
/** Versioned entries of a multi-release jar are read like any class, so they must be real class files. */
private byte[] sharedClassFile() {
return TestModuleJar.compileClass(pack, SHARED_CLASS, SHARED_SOURCE);
}
private static String failure(Executable load) {
return assertThrows(IllegalArgumentException.class, load).getMessage();
}
@@ -54,7 +62,8 @@ class PackModulesTest {
@Test
void loadsOneModulePerJarInFileNameOrderAndResolvesThemWithBuiltIns(@TempDir Path build) throws Exception {
var alpha = module("pack.alpha.AlphaModule", "alpha:core", ALPHA_MEMBERS,
"graph.define(MARK).requires(com.volmit.example.placement.AnchorModule.HEIGHT).run(context -> {});");
"graph.define(MARK).requires(com.volmit.example.placement.AnchorModule.HEIGHT).run(context -> {});")
.compileAgainstHostOf(AnchorModule.class);
var alphaJar = alpha.writeInto(build, "alpha.jar");
module("pack.beta.BetaModule", "beta:core", NO_MEMBERS,
"graph.define(Stage.placement(\"beta:core/use\")).requires(pack.alpha.AlphaModule.MARK).run(context -> {});")
@@ -77,6 +86,18 @@ class PackModulesTest {
}
}
@Test
void packClassLoaderSeesOnlyTheApiTheJdkAndThePack() throws Exception {
module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "gamma.jar");
try (var packModules = PackModules.load(pack)) {
var loader = packModules.modules().getFirst().module().getClass().getClassLoader();
assertSame(IrisModule.class, loader.loadClass(IrisModule.class.getName()));
assertSame(List.class, loader.loadClass(List.class.getName()));
assertThrows(ClassNotFoundException.class, () -> loader.loadClass(Test.class.getName()));
}
}
@Test
void closingThePackStopsItsClassLoaderFromLoadingMoreClasses() throws Exception {
module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_STAGES)
@@ -172,7 +193,7 @@ class PackModulesTest {
.source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "alpha.jar");
module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_STAGES)
.multiRelease()
.resource("META-INF/versions/9/pack/shared/Util.class", UNUSED_CLASS_BYTES)
.resource(VERSIONED_SHARED_CLASS, sharedClassFile())
.writeInto(pack, "beta.jar");
assertMentions(failure(() -> PackModules.load(pack)),
@@ -183,10 +204,10 @@ class PackModulesTest {
void versionedEntriesOutsideAMultiReleaseJarAreNotClasses() {
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES)
.source(SHARED_CLASS, SHARED_SOURCE)
.resource("META-INF/versions/9/pack/shared/Util.class", UNUSED_CLASS_BYTES)
.resource(VERSIONED_SHARED_CLASS, UNUSED_CLASS_BYTES)
.writeInto(pack, "alpha.jar");
module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_STAGES)
.resource("META-INF/versions/9/pack/shared/Util.class", UNUSED_CLASS_BYTES)
.resource(VERSIONED_SHARED_CLASS, UNUSED_CLASS_BYTES)
.writeInto(pack, "beta.jar");
try (var packModules = PackModules.load(pack)) {
@@ -199,7 +220,7 @@ class PackModulesTest {
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES)
.source(SHARED_CLASS, SHARED_SOURCE)
.multiRelease()
.resource("META-INF/versions/9/pack/shared/Util.class", UNUSED_CLASS_BYTES)
.resource(VERSIONED_SHARED_CLASS, sharedClassFile())
.writeInto(pack, "alpha.jar");
try (var packModules = PackModules.load(pack)) {
@@ -207,6 +228,106 @@ class PackModulesTest {
}
}
@Test
void apiClassInAJarFailsNamingTheJarAndTheClass() {
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES)
.source("com.volmit.extra.Helper", "package com.volmit.extra; public final class Helper {}")
.source("com.volmit.extra.Other", "package com.volmit.extra; public final class Other {}")
.writeInto(pack, "alpha.jar");
assertEquals("Module jar " + origin("alpha.jar") + " contains Iris API class com.volmit.extra.Helper and 1 more;"
+ " Iris provides the API at runtime, so mark the Iris API dependency compileOnly (Maven: provided)"
+ " and keep module classes out of com.volmit.*",
failure(() -> PackModules.load(pack)));
}
@Test
void referenceToAHostLibraryFailsNamingTheJarAndBothClasses() {
module("pack.user.User", "user:core", "static Object probe() { return org.junit.jupiter.api.Test.class; }", NO_STAGES)
.compileAgainstHostOf(Test.class)
.writeInto(pack, "user.jar");
assertEquals("Module jar " + origin("user.jar") + " uses classes that are not in the Iris API, the JDK or the"
+ " pack's module jars:\n pack.user.User -> org.junit.jupiter.api.Test\n"
+ "A module can use only the Iris API, the JDK and the classes in its pack's module jars;"
+ " ship any library it needs inside a module jar of the pack.",
failure(() -> PackModules.load(pack)));
}
@Test
void referenceToAMissingApiClassPointsAtADifferentApiBuild(@TempDir Path build) {
var newerApi = new TestModuleJar()
.source("com.volmit.Newer", "package com.volmit; public final class Newer {}")
.writeInto(build, "newer-api.jar");
module("pack.user.User", "user:core", "static Object probe() { return com.volmit.Newer.class; }", NO_STAGES)
.compileAgainst(newerApi)
.writeInto(pack, "user.jar");
assertMentions(failure(() -> PackModules.load(pack)),
"pack.user.User -> com.volmit.Newer", "the jar was built against a different Iris API");
}
@Test
void referencesToTheJdkTheApiAndOtherPackJarsLoad(@TempDir Path build) throws Exception {
var marker = new TestModuleJar()
.source("pack.marker.Marker", """
package pack.marker;
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface Marker {}
""")
.writeInto(build, "marker.jar");
var alpha = module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES)
.source("pack.alpha.Shared", """
package pack.alpha;
public record Shared(int[] values, String[][] names) {
public enum Kind { SMALL, LARGE }
}
""");
var alphaJar = alpha.writeInto(build, "alpha.jar");
alpha.writeInto(pack, "alpha.jar");
module("pack.beta.Beta", "beta:core", """
@pack.marker.Marker
static final pack.alpha.Shared[] SHARED = { new pack.alpha.Shared(new int[] {1}, new String[][] {{"a"}}) };
static int size(pack.alpha.Shared.Kind kind) {
return switch (kind) { case SMALL -> 1; case LARGE -> 2; };
}
""", """
java.util.function.IntSupplier size = () -> size(pack.alpha.Shared.Kind.LARGE) + SHARED[0].values().length;
graph.define(Stage.placement("beta:core/size")).run(context -> java.util.List.of(size).forEach(java.util.function.IntSupplier::getAsInt));
""")
.compileAgainst(alphaJar)
.compileAgainst(marker)
.writeInto(pack, "beta.jar");
try (var packModules = PackModules.load(pack)) {
var loaded = LoadedModules.load(packModules.modules(), Map.of());
assertTrue(loaded.placement().stages().stream().anyMatch(stage -> stage.stage().id().toString().equals("beta:core/size")));
var beta = packModules.modules().getLast().module().getClass();
assertEquals(0, beta.getDeclaredField("SHARED").getAnnotations().length,
"the annotation type is not in the pack, so the JVM skips it");
}
}
@Test
void methodMissingAtInstallFailsNamingTheJar(@TempDir Path build) {
var libraryWithMethod = new TestModuleJar()
.source("pack.lib.Lib", "package pack.lib; public final class Lib { public static void added() {} }")
.writeInto(build, "lib.jar");
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES)
.source("pack.lib.Lib", "package pack.lib; public final class Lib {}")
.writeInto(pack, "alpha.jar");
module("pack.beta.Beta", "beta:core", NO_MEMBERS, "pack.lib.Lib.added();")
.compileAgainst(libraryWithMethod)
.writeInto(pack, "beta.jar");
try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of())),
"Module beta:core from " + origin("beta.jar") + " failed to link or initialize a class while installing",
"java.lang.NoSuchMethodError", "pack.lib.Lib.added()");
}
}
@Test
void duplicateModuleIdsAcrossJarsFailNamingBothJars() {
module("pack.one.Duplicate", "dup:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "one.jar");
@@ -1,7 +1,6 @@
package com.volmit.support;
import com.volmit.IrisModule;
import com.volmit.example.placement.AnchorModule;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -25,7 +24,9 @@ import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
/** Builds a real module jar from Java source at test time. Its classes are not on the test
* classpath, so only a pack class loader can define them.
* classpath, so only a pack class loader can define them. Sources compile against the API's main
* classes only, like a real module; built-in example modules and host libraries must be added with
* {@link #compileAgainstHostOf}, so a jar cannot depend on test support classes by accident.
*/
public final class TestModuleJar {
private static final String SERVICES_FILE = "META-INF/services/" + IrisModule.class.getName();
@@ -34,13 +35,23 @@ public final class TestModuleJar {
private final Map<String, byte[]> resources = new LinkedHashMap<>();
private boolean multiRelease;
private final List<String> entryPoints = new ArrayList<>();
private final List<Path> classpath = new ArrayList<>(List.of(classesOf(IrisModule.class), classesOf(AnchorModule.class)));
private final List<Path> classpath = new ArrayList<>(List.of(classesOf(IrisModule.class)));
/** An entry class with the given module id whose install body may use {@code graph}. */
public static TestModuleJar module(String className, String moduleId, String members, String install) {
return new TestModuleJar().source(className, moduleSource(className, moduleId, members, install)).entryPoint(className);
}
/** Compiles one class on its own and returns its class file, for raw entries such as versioned classes. */
public static byte[] compileClass(Path workDirectory, String className, String code) {
try {
var classes = new TestModuleJar().source(className, code).compile(Files.createTempDirectory(workDirectory, "classes"));
return Files.readAllBytes(classes.resolve(className.replace('.', '/') + ".class"));
} catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}
public TestModuleJar source(String className, String code) {
sources.put(className, code);
return this;
@@ -64,11 +75,17 @@ public final class TestModuleJar {
return this;
}
public TestModuleJar compileAgainst(Path jar) {
classpath.add(jar);
/** Puts a jar or class directory on the compile classpath only; it is not packaged. */
public TestModuleJar compileAgainst(Path classes) {
classpath.add(classes);
return this;
}
/** Compiles against wherever {@code type} was loaded from, such as a host library jar. */
public TestModuleJar compileAgainstHostOf(Class<?> type) {
return compileAgainst(classesOf(type));
}
/** Writes {@code <packRoot>/modules/<jarName>} and returns its path. */
public Path writeInto(Path packRoot, String jarName) {
try {