Enforce namespace ownership: reserved namespaces and module-prefixed stage ids

- LoadedModules.load takes the host's reserved namespaces (such as iris);
  a pack module whose id uses one fails, naming its jar and the namespace.
- A module defines only stages whose ids start with its own id and '/'.
  Module ids may no longer contain '/', so ids cannot nest and every
  stage id has exactly one possible owner.
- Object feature ids and mantle keys must use the registering module's
  namespace; ModuleRegistry.register(DiscoveredModule) scopes registration.
- A settings type named in when(...) needs a feature id in the namespace
  of some module naming it, so modules can still condition on another
  module's settings.
This commit is contained in:
piexel committed 2026-10-05 21:31:55 +02:00
1 parent 6263075ecd
commit 4cb718f706
13 files changed
+413 -129

No files matched your search

@@ -7,7 +7,8 @@ import com.volmit.object.ObjectGeneratorFactory;
/** Host implementation collects non-stage registrations before loading pack configuration.
* Feature IDs must be unique. JSON fields must be unique per attachment target, including the
* settings types stages name in {@code when(...)}.
* settings types stages name in {@code when(...)}. Feature IDs and mantle keys a module registers
* use the namespace of its module id.
*/
public interface FeatureRegistry {
/** Registers a layer before pack loading. Null arguments throw NullPointerException;
+28 -1
View File
@@ -5,7 +5,10 @@ import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/** Module identity. Stages a module defines must use the namespace of its id. The name is for
/** Module identity. Every stage a module defines has an id that starts with the module id and
* {@code /}, such as {@code iris:stilt/fill} for module {@code iris:stilt}, so a module id has no
* {@code /} of its own: {@code iris:stilt/extra} would own stages under {@code iris:stilt}'s path.
* Settings ids and mantle keys the module registers use its namespace. The name is for
* people, for example in load logs; the id is what the host and other modules match on. Name and
* version must fit on one log line, so they reject control characters such as line breaks.
*
@@ -15,10 +18,13 @@ import java.util.Objects;
* hides from modules or one missing from a package Iris exposes; those still fail the load.
*/
public record ModuleInfo(ResourceId id, String name, String version, List<PackageName> optionalPackages) {
private static final String STAGE_SEPARATOR = "/";
public ModuleInfo {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(name, "name");
Objects.requireNonNull(version, "version");
requireSingleSegment(id);
requireOneLineText(id, "name", name);
requireOneLineText(id, "version", version);
optionalPackages = List.copyOf(optionalPackages);
@@ -43,6 +49,27 @@ public record ModuleInfo(ResourceId id, String name, String version, List<Packag
+ " which covers that package and its subpackages"));
}
/** Whether {@code stageId} may name a stage of this module: it starts with this module's id and '/'. */
public boolean ownsStage(ResourceId stageId) {
return stageId.namespace().equals(id.namespace()) && stageId.path().startsWith(stagePrefix());
}
/** What every stage id of this module starts with, such as {@code iris:stilt/}. */
public String stageIdPrefix() {
return id.namespace() + ":" + stagePrefix();
}
private String stagePrefix() {
return id.path() + STAGE_SEPARATOR;
}
private static void requireSingleSegment(ResourceId id) {
if (!id.path().contains(STAGE_SEPARATOR)) return;
throw new IllegalArgumentException("Module id " + id + " must not contain '" + STAGE_SEPARATOR
+ "': stage ids are a module id, '" + STAGE_SEPARATOR + "' and a name, so " + id
+ " would name stages under another module's id");
}
private static void requireOneLineText(ResourceId id, String field, String value) {
if (value.isBlank()) {
throw new IllegalArgumentException("Blank module " + field + ": " + id);
@@ -2,6 +2,7 @@ package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.stage.Pipeline;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -17,10 +18,18 @@ public record LoadedModules(FeatureCatalog catalog, ResolvedGraph placement, Res
Objects.requireNonNull(chunk, "chunk");
}
/** Pass the built-in modules together with {@link PackModules#modules()} of the pack. */
/** Pass the built-in modules together with {@link PackModules#modules()} of the pack.
*
* @param reservedHostFields JSON fields the host itself uses, per attachment target
* @param reservedNamespaces namespaces only built-in modules may use, such as {@code iris}; a
* pack module whose id uses one fails the load
*/
public static LoadedModules load(
List<DiscoveredModule> modules,
Map<FeatureAttachment.Target, Set<String>> reservedHostFields) {
Map<FeatureAttachment.Target, Set<String>> reservedHostFields,
Collection<String> reservedNamespaces) {
var reserved = ReservedNamespaces.of(reservedNamespaces);
modules.forEach(reserved::requireAllowed);
var registry = new ModuleRegistry(reservedHostFields);
var stages = new StageGraphBuilder();
for (var discovered : modules) {
@@ -36,7 +45,7 @@ public record LoadedModules(FeatureCatalog catalog, ResolvedGraph placement, Res
private static void installModule(DiscoveredModule discovered, StageGraphBuilder stages, ModuleRegistry registry) {
try {
stages.install(discovered);
discovered.module().register(registry);
registry.register(discovered);
} catch (LinkageError error) {
throw new IllegalArgumentException("Module " + discovered.info().id() + " from "
+ discovered.origin() + " failed to link or initialize a class while installing: " + error
@@ -3,6 +3,7 @@ package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
@@ -16,9 +17,11 @@ import java.util.Set;
/** Reference host registry. Single-threaded registration ends with freeze(); the catalog is
* immutable. IDs are unique across feature kinds; JSON fields are unique per attachment target.
* Pass existing host JSON fields to reserve them before modules register. A failed registration
* leaves the registry unchanged. A failed module callback invalidates the host's whole build.
* This does not decode JSON, discover modules or instantiate settings.
* Pass existing host JSON fields to reserve them before modules register. Modules register through
* {@link #register(DiscoveredModule)}; object feature ids and mantle keys must use the registering
* module's namespace. A failed registration leaves the registry unchanged. A failed module callback
* invalidates the host's whole build. This does not decode JSON, discover modules or instantiate
* settings.
*/
public final class ModuleRegistry implements FeatureRegistry {
private final Map<Class<?>, FeatureDescriptor<?>> settings = new HashMap<>();
@@ -28,6 +31,7 @@ public final class ModuleRegistry implements FeatureRegistry {
private final Set<Class<?>> featureTypes = new HashSet<>();
private final Map<Field, String> fields = new HashMap<>();
private FeatureCatalog catalog;
private DiscoveredModule registering;
public ModuleRegistry() {
this(Map.of());
@@ -37,12 +41,28 @@ public final class ModuleRegistry implements FeatureRegistry {
reserveHostFields(reservedFields);
}
/** Lets the module register its contributions through {@link IrisModule#register}. */
public void register(DiscoveredModule discovered) {
Objects.requireNonNull(discovered, "discovered");
checkOpen();
if (registering != null) {
throw new IllegalStateException("Module " + discovered.info().id() + " registered during " + registering.info().id());
}
registering = discovered;
try {
discovered.module().register(this);
} finally {
registering = null;
}
}
@Override
public <F extends IrisFeature> void registerObject(
Class<F> featureType,
ObjectGeneratorFactory<F> factory) {
checkOpen();
var descriptor = FeatureDescriptor.of(featureType);
requireModuleNamespace("Object generator settings " + featureType.getName() + " with feature id", descriptor.id());
var registration = new ObjectRegistration<>(descriptor, factory);
claim(descriptor);
objects.put(featureType, registration);
@@ -53,6 +73,7 @@ public final class ModuleRegistry implements FeatureRegistry {
checkOpen();
Objects.requireNonNull(key, "key");
Objects.requireNonNull(codec, "codec");
requireModuleNamespace("Mantle layer", ResourceId.parse(key.id()));
var registration = new MantleRegistration<>(key, lifetime, codec, codec.version());
if (mantle.putIfAbsent(key.id(), registration) != null) {
@@ -78,6 +99,16 @@ public final class ModuleRegistry implements FeatureRegistry {
return catalog;
}
private void requireModuleNamespace(String registration, ResourceId id) {
if (registering == null) {
throw new IllegalStateException(registration + " " + id + " registered outside IrisModule.register");
}
var namespace = registering.info().id().namespace();
if (id.namespace().equals(namespace)) return;
throw new IllegalArgumentException(registration + " " + id + " must use namespace '" + namespace
+ "' of its registering module " + registering);
}
private void reserveHostFields(Map<FeatureAttachment.Target, Set<String>> reservedFields) {
for (var entry : reservedFields.entrySet()) {
for (var name : entry.getValue()) {
@@ -0,0 +1,47 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
/** Namespaces that only modules from the host's classpath may use, such as {@code iris}. A pack
* module's id must use another namespace. Its stages, settings ids and mantle keys follow its
* namespace, so none of them can be in a reserved namespace either.
*/
final class ReservedNamespaces {
private final Set<String> namespaces;
private ReservedNamespaces(Set<String> namespaces) {
this.namespaces = namespaces;
}
/** Fails on anything that is not a namespace, such as a blank string or a full id. */
static ReservedNamespaces of(Collection<String> namespaces) {
Objects.requireNonNull(namespaces, "reservedNamespaces");
var valid = new TreeSet<String>();
for (var namespace : namespaces) {
valid.add(requireNamespace(namespace));
}
return new ReservedNamespaces(Set.copyOf(valid));
}
void requireAllowed(DiscoveredModule discovered) {
if (discovered.source() == DiscoveredModule.Source.HOST) return;
var namespace = discovered.info().id().namespace();
if (!namespaces.contains(namespace)) return;
throw new IllegalArgumentException("Module " + discovered.info().id() + " from " + discovered.origin()
+ " uses reserved namespace '" + namespace + "', which only modules that ship with the host may use;"
+ " give the module a namespace of its own, which its stages, settings ids and mantle keys then use too");
}
private static String requireNamespace(String namespace) {
Objects.requireNonNull(namespace, "reserved namespace");
if (!ResourceId.isNamespace(namespace)) {
throw new IllegalArgumentException("Reserved namespace '" + namespace
+ "' is not a namespace; name one such as iris, without ':' or a path");
}
return namespace;
}
}
@@ -17,27 +17,32 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
/** Reference host collection of module stages. Install every module, then resolve each pipeline
* once per pack load. Install order never affects the result. If a module's install throws,
* discard the whole builder: it may hold a partial module. Errors about one module name its origin.
*
* <p>A module defines only stages whose ids start with its own id and '/', and a settings type
* named in {@code when(...)} must have a feature id in the namespace of a module that names it.
*/
public final class StageGraphBuilder implements StageGraph {
private final Map<ResourceId, StageDeclaration> declarations = new HashMap<>();
private final Map<ResourceId, String> moduleOrigins = new HashMap<>();
private ResourceId installingModule;
private final Map<ResourceId, DiscoveredModule> modules = new HashMap<>();
private DiscoveredModule installing;
public void install(DiscoveredModule discovered) {
Objects.requireNonNull(discovered, "discovered");
var moduleId = discovered.info().id();
claimModule(moduleId, discovered.origin());
installingModule = moduleId;
claimModule(discovered);
installing = discovered;
try {
discovered.module().install(this);
} finally {
installingModule = null;
installing = null;
}
requireCompleteDefinitions(moduleId);
requireCompleteDefinitions(discovered.info().id());
}
@Override
@@ -60,32 +65,66 @@ public final class StageGraphBuilder implements StageGraph {
return GraphResolver.resolve(pipeline, declarations.values());
}
/** Settings types named by when(...), ordered by feature id. */
/** Settings types named by when(...), ordered by feature id. Fails if a type's feature id is not
* in the namespace of any module that names it: some module of that namespace must own it.
*/
public List<Class<? extends IrisFeature>> settingsTypes() {
return declarations.values().stream()
.flatMap(declaration -> declaration.settings().stream())
.distinct()
.sorted(Comparator.comparing(FeatureDescriptor::id))
.<Class<? extends IrisFeature>>map(FeatureDescriptor::type)
var uses = settingsUses();
uses.forEach(this::requireSettingsOwner);
return uses.stream()
.<Class<? extends IrisFeature>>map(use -> use.settings().type())
.toList();
}
private void claimModule(ResourceId moduleId, String origin) {
if (installingModule != null) {
throw new IllegalStateException("Module " + moduleId + " installed during " + installingModule);
private void claimModule(DiscoveredModule discovered) {
var moduleId = discovered.info().id();
if (installing != null) {
throw new IllegalStateException("Module " + moduleId + " installed during " + installing.info().id());
}
var previous = moduleOrigins.putIfAbsent(moduleId, origin);
var previous = modules.putIfAbsent(moduleId, discovered);
if (previous != null) {
throw new IllegalArgumentException("Duplicate module " + moduleId + " from " + origin
+ "; already loaded from " + previous);
throw new IllegalArgumentException("Duplicate module " + moduleId + " from " + discovered.origin()
+ "; already loaded from " + previous.origin());
}
}
/** Each settings type named by when(...), ordered by feature id, with the modules naming it. */
private List<SettingsUse> settingsUses() {
var uses = new HashMap<Class<?>, SettingsUse>();
for (var declaration : declarations.values()) {
declaration.settings().ifPresent(settings -> uses
.computeIfAbsent(settings.type(), ignored -> new SettingsUse(settings, new TreeSet<>()))
.namers().add(declaration.module()));
}
return uses.values().stream()
.sorted(Comparator.comparing((SettingsUse use) -> use.settings().id())
.thenComparing(use -> use.settings().type().getName()))
.toList();
}
private void requireSettingsOwner(SettingsUse use) {
var settings = use.settings();
var namers = use.namers();
var namespace = settings.id().namespace();
if (namers.stream().anyMatch(module -> module.namespace().equals(namespace))) return;
throw new IllegalArgumentException("Settings type " + settings.type().getName() + " has feature id "
+ settings.id() + ", but no module of namespace '" + namespace + "' names it in when(...); it is named by "
+ describeModules(namers) + ". A feature id uses the namespace of the module that owns the settings");
}
private String describeModules(SortedSet<ResourceId> moduleIds) {
return moduleIds.stream()
.map(modules::get)
.map(DiscoveredModule::toString)
.collect(Collectors.joining(", "));
}
private StageDeclaration declare(Stage<?> stage) {
Objects.requireNonNull(stage, "stage");
var module = requireInstallingModule(stage);
requireModuleNamespace(stage, module);
var discovered = requireInstallingModule(stage);
requireOwnedStageId(stage, discovered);
var module = discovered.info().id();
var declaration = new StageDeclaration(stage, module);
var previous = declarations.putIfAbsent(stage.id(), declaration);
if (previous != null) {
@@ -95,18 +134,18 @@ public final class StageGraphBuilder implements StageGraph {
return declaration;
}
private ResourceId requireInstallingModule(Stage<?> stage) {
if (installingModule == null) {
private DiscoveredModule requireInstallingModule(Stage<?> stage) {
if (installing == null) {
throw new IllegalStateException("Stage " + stage + " defined outside IrisModule.install");
}
return installingModule;
return installing;
}
private void requireModuleNamespace(Stage<?> stage, ResourceId module) {
if (!stage.id().namespace().equals(module.namespace())) {
throw new IllegalArgumentException("Stage " + stage + " must use namespace '"
+ module.namespace() + "' of its defining module " + module + " from " + moduleOrigins.get(module));
}
private static void requireOwnedStageId(Stage<?> stage, DiscoveredModule discovered) {
var info = discovered.info();
if (info.ownsStage(stage.id())) return;
throw new IllegalArgumentException("Stage " + stage + " must start with " + info.stageIdPrefix()
+ ", the id of its defining module " + discovered);
}
private void requireCompleteDefinitions(ResourceId moduleId) {
@@ -121,4 +160,6 @@ public final class StageGraphBuilder implements StageGraph {
+ " has no body; end its definition with run, produce or accumulate");
});
}
private record SettingsUse(FeatureDescriptor<?> settings, SortedSet<ResourceId> namers) {}
}
@@ -1,17 +1,26 @@
package com.volmit.resource;
import java.util.Objects;
import java.util.regex.Pattern;
/** Case-sensitive namespaced identity. Parsing never supplies an implicit namespace. */
public record ResourceId(String namespace, String path) implements Comparable<ResourceId> {
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PATH = Pattern.compile("[a-z0-9_./-]+");
public ResourceId {
Objects.requireNonNull(namespace, "namespace");
Objects.requireNonNull(path, "path");
if (!namespace.matches("[a-z0-9_.-]+") || !path.matches("[a-z0-9_./-]+")) {
if (!isNamespace(namespace) || !PATH.matcher(path).matches()) {
throw new IllegalArgumentException("Invalid resource ID: " + namespace + ":" + path);
}
}
/** Whether {@code value} is a valid namespace on its own, such as {@code iris}. */
public static boolean isNamespace(String value) {
return NAMESPACE.matcher(value).matches();
}
public static ResourceId parse(String value) {
Objects.requireNonNull(value, "value");
int separator = value.indexOf(':');