Expose bounded web contexts for embedded tools

This commit is contained in:
2026-09-19 16:34:09 +03:00
parent bcd1a75a19
commit 625efc9fb3
3 changed files with 339 additions and 9 deletions
@@ -1,6 +1,8 @@
package online.astradev.packs;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
@@ -11,7 +13,9 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
@@ -20,11 +24,26 @@ import java.util.concurrent.TimeUnit;
/** Serves only published archives, with expiring links and bounded downloads. */
public final class PackHost implements AutoCloseable {
private static final String PACK_PREFIX = "/astrapacks";
private static final int MAX_CUSTOM_CONTEXTS = 8;
private record Grant(String hash, long expires) {}
private static final class WebMount {
private final String prefix;
private final HttpHandler handler;
private HttpContext context;
private WebMount(String prefix, HttpHandler handler) {
this.prefix = prefix;
this.handler = handler;
}
}
private final PackConfig.Hosting config;
private final Map<String, Path> published = new ConcurrentHashMap<>();
private final Map<String, Grant> grants = new ConcurrentHashMap<>();
private final Map<String, WebMount> webMounts = new LinkedHashMap<>();
private final Map<String, Integer> downloadsByIp = new HashMap<>();
private final ExecutorService workers = Executors.newVirtualThreadPerTaskExecutor();
private HttpServer server;
@@ -35,10 +54,141 @@ public final class PackHost implements AutoCloseable {
}
public void start() throws IOException {
server = HttpServer.create(new InetSocketAddress(config.bindAddress, config.port), 0);
server.createContext("/", this::handle);
server.setExecutor(workers);
server.start();
synchronized (webMounts) {
if (server != null) {
throw new IllegalStateException("AstraPacks HTTP host is already started");
}
HttpServer next =
HttpServer.create(new InetSocketAddress(config.bindAddress, config.port), 0);
next.createContext("/", this::handle);
for (WebMount mount : webMounts.values()) {
mount.context = next.createContext(mount.prefix, mount.handler);
}
next.setExecutor(workers);
next.start();
server = next;
}
}
/** Mounts a custom HTTP context, either before or after this host is started. */
public AutoCloseable mountWebContext(String prefix, HttpHandler handler) {
String normalizedPrefix = normalizePrefix(prefix);
Objects.requireNonNull(handler, "handler");
WebMount mount = new WebMount(normalizedPrefix, handler);
synchronized (webMounts) {
ensureAvailablePrefix(normalizedPrefix);
if (webMounts.size() >= MAX_CUSTOM_CONTEXTS) {
throw new IllegalStateException("AstraPacks supports at most 8 custom HTTP contexts");
}
webMounts.put(normalizedPrefix, mount);
if (server != null) {
try {
mount.context = server.createContext(normalizedPrefix, handler);
} catch (RuntimeException error) {
webMounts.remove(normalizedPrefix);
throw error;
}
}
}
return () -> unmount(mount);
}
private void unmount(WebMount mount) {
synchronized (webMounts) {
if (!webMounts.remove(mount.prefix, mount)) return;
removeContext(mount);
}
}
private void removeContext(WebMount mount) {
if (mount.context == null || server == null) return;
server.removeContext(mount.context);
mount.context = null;
}
public String publicUrl(String path) {
return publicUrl(config.publicAddress, path);
}
public String publicUrl(String publicAddress, String path) {
String address = requirePublicAddress(publicAddress);
return address + validateAbsolutePath(path);
}
private void ensureAvailablePrefix(String prefix) {
if (isPackPrefix(prefix)) {
throw new IllegalArgumentException("The /astrapacks HTTP namespace is reserved");
}
for (String existing : webMounts.keySet()) {
if (prefixesOverlap(existing, prefix)) {
throw new IllegalArgumentException(
"HTTP context overlaps an existing custom context: " + existing);
}
}
}
private static boolean isPackPrefix(String prefix) {
return prefix.equals(PACK_PREFIX) || prefix.startsWith(PACK_PREFIX + "/");
}
private static boolean prefixesOverlap(String first, String second) {
return first.startsWith(second) || second.startsWith(first);
}
private static String normalizePrefix(String prefix) {
Objects.requireNonNull(prefix, "prefix");
validatePrefixShape(prefix);
return withoutTrailingSlashes(prefix);
}
private static void validatePrefixShape(String prefix) {
if (prefix.length() > 128
|| !prefix.startsWith("/")
|| prefix.equals("/")
|| hasForbiddenPathSyntax(prefix)
|| prefix.indexOf("//") >= 0) {
throw new IllegalArgumentException("Invalid HTTP context prefix: " + prefix);
}
}
private static String withoutTrailingSlashes(String prefix) {
String normalized = prefix;
while (normalized.length() > 1 && normalized.endsWith("/")) {
normalized = normalized.substring(0, normalized.length() - 1);
}
return normalized;
}
private static String validateAbsolutePath(String path) {
Objects.requireNonNull(path, "path");
if (!path.startsWith("/")
|| path.startsWith("//")
|| hasForbiddenPathSyntax(path)
|| containsControlCharacter(path)) {
throw new IllegalArgumentException("Expected a safe absolute HTTP path: " + path);
}
return path;
}
private static boolean hasForbiddenPathSyntax(String path) {
return path.indexOf("..") >= 0
|| path.indexOf('\\') >= 0
|| path.indexOf('?') >= 0
|| path.indexOf('#') >= 0;
}
private static boolean containsControlCharacter(String value) {
return value.chars().anyMatch(character -> character < 0x20 || character == 0x7f);
}
private static String requirePublicAddress(String publicAddress) {
if (publicAddress == null || publicAddress.isBlank()) {
throw new IllegalStateException(
"Set hosting.publicAddress before creating public AstraPacks URLs");
}
String address = publicAddress.replaceFirst("/+$", "");
PackConfig.validateUrl(address);
return address;
}
public void publish(PackBuilder.Pack pack) {
@@ -48,7 +198,7 @@ public final class PackHost implements AutoCloseable {
}
public String issuePath(PackBuilder.Pack pack) {
String path = "/astrapacks/" + pack.sha1() + ".zip";
String path = PACK_PREFIX + "/" + pack.sha1() + ".zip";
if (!config.blockNonGameRequests) {
return path;
}
@@ -71,11 +221,11 @@ public final class PackHost implements AutoCloseable {
return;
}
String path = exchange.getRequestURI().getPath();
if (!path.matches("/astrapacks/[a-f0-9]{40}\\.zip")) {
if (!path.matches(PACK_PREFIX + "/[a-f0-9]{40}\\.zip")) {
exchange.sendResponseHeaders(404, -1);
return;
}
String hash = path.substring("/astrapacks/".length(), path.length() - ".zip".length());
String hash = path.substring(PACK_PREFIX.length() + 1, path.length() - ".zip".length());
Path file = published.get(hash);
if (file == null || !Files.isRegularFile(file)) {
exchange.sendResponseHeaders(404, -1);
@@ -181,8 +331,15 @@ public final class PackHost implements AutoCloseable {
@Override
public void close() {
if (server != null) {
server.stop(0);
synchronized (webMounts) {
if (server != null) {
for (WebMount mount : webMounts.values()) {
removeContext(mount);
}
server.stop(0);
server = null;
}
webMounts.clear();
}
workers.shutdownNow();
grants.clear();
@@ -1,5 +1,7 @@
package online.astradev.packs;
import com.sun.net.httpserver.HttpHandler;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component;
@@ -169,6 +171,18 @@ public final class PackRuntime implements AutoCloseable {
return address.replaceAll("/+$", "") + host.issuePath(pack);
}
/** Mounts an editor or other web endpoint on AstraPacks' HTTP origin. */
public AutoCloseable mountWebContext(String prefix, HttpHandler handler) {
if (closed) {
throw new IllegalStateException("AstraPacks is closed");
}
return host.mountWebContext(prefix, handler);
}
public String publicUrl(String path) {
return host.publicUrl(config.hosting.publicAddress, path);
}
public void build(CommandSourceStack source) {
requestBuild(source, false);
}
@@ -0,0 +1,159 @@
package online.astradev.packs;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class PackWebMountTest {
@TempDir Path root;
@Test
void mountsBeforeStartAndUnmountsExactlyThatContext() throws Exception {
int port = freePort();
PackConfig config = config(port);
AtomicBoolean virtualThread = new AtomicBoolean();
try (PackHost host = new PackHost(config.hosting)) {
AutoCloseable mount =
host.mountWebContext(
"/editor/",
exchange -> respond(exchange, "editor", virtualThread));
host.start();
try (HttpClient client = HttpClient.newHttpClient()) {
URI uri = URI.create("http://127.0.0.1:" + port + "/editor/index.html");
assertEquals("editor", get(client, uri).body());
assertTrue(virtualThread.get(), "mounted handlers must run on virtual threads");
mount.close();
mount.close();
assertEquals(404, get(client, uri).statusCode());
}
}
}
@Test
void mountsAfterStartAndKeepsThePackNamespaceAvailable() throws Exception {
int port = freePort();
PackConfig config = config(port);
try (PackHost host = new PackHost(config.hosting)) {
host.start();
AutoCloseable mount =
host.mountWebContext("/editor", exchange -> respond(exchange, "mounted", null));
try (HttpClient client = HttpClient.newHttpClient()) {
URI base = URI.create("http://127.0.0.1:" + port);
assertEquals("mounted", get(client, base.resolve("/editor")).body());
assertEquals(404, get(client, base.resolve("/astrapacks/not-a-pack.zip")).statusCode());
}
mount.close();
}
}
@Test
void rejectsUnsafeReservedOverlappingAndExcessContexts() throws Exception {
PackHost host = new PackHost(config(freePort()).hosting);
try {
assertThrows(IllegalArgumentException.class, () -> host.mountWebContext("/", ignored -> {}));
assertThrows(IllegalArgumentException.class, () -> host.mountWebContext("editor", ignored -> {}));
assertThrows(IllegalArgumentException.class, () -> host.mountWebContext("/ed..itor", ignored -> {}));
assertThrows(IllegalArgumentException.class, () -> host.mountWebContext("/editor\\x", ignored -> {}));
assertThrows(IllegalArgumentException.class, () -> host.mountWebContext("/editor?x", ignored -> {}));
assertThrows(IllegalArgumentException.class, () -> host.mountWebContext("/editor#x", ignored -> {}));
assertThrows(IllegalArgumentException.class, () -> host.mountWebContext("/astrapacks", ignored -> {}));
assertThrows(IllegalArgumentException.class, () -> host.mountWebContext("/astrapacks/editor", ignored -> {}));
for (int index = 0; index < 8; index++) {
host.mountWebContext("/mount" + index, ignored -> {});
}
assertThrows(
IllegalStateException.class,
() -> host.mountWebContext("/mount-extra", ignored -> {}));
} finally {
host.close();
}
PackHost overlap = new PackHost(config(freePort()).hosting);
try (AutoCloseable ignored = overlap.mountWebContext("/editor", exchange -> {})) {
assertThrows(
IllegalArgumentException.class,
() -> overlap.mountWebContext("/editor/preview", exchange -> {}));
assertThrows(
IllegalArgumentException.class,
() -> overlap.mountWebContext("/editor/", exchange -> {}));
}
overlap.close();
}
@Test
void buildsPublicUrlsOnlyFromSafePaths() throws Exception {
PackConfig config = config(freePort());
config.hosting.publicAddress = "https://packs.example.test/base/";
try (PackHost host = new PackHost(config.hosting)) {
assertEquals(
"https://packs.example.test/base/editor",
host.publicUrl("/editor"));
assertEquals(
"https://packs.example.test/base/editor/index.html",
host.publicUrl(config.hosting.publicAddress, "/editor/index.html"));
assertThrows(IllegalArgumentException.class, () -> host.publicUrl(""));
assertThrows(IllegalArgumentException.class, () -> host.publicUrl("editor"));
assertThrows(IllegalArgumentException.class, () -> host.publicUrl("/editor?token=x"));
assertThrows(IllegalArgumentException.class, () -> host.publicUrl("/editor/../secret"));
assertThrows(IllegalArgumentException.class, () -> host.publicUrl("/editor\\secret"));
assertThrows(
IllegalArgumentException.class,
() -> host.publicUrl("javascript:alert(1)", "/editor"));
}
config.hosting.publicAddress = "";
try (PackHost host = new PackHost(config.hosting)) {
assertThrows(IllegalStateException.class, () -> host.publicUrl("/editor"));
}
}
private PackConfig config(int port) throws IOException {
PackConfig config = new PackConfig();
config.hosting.bindAddress = "127.0.0.1";
config.hosting.port = port;
Files.createDirectories(config.contents(root));
return config;
}
private static int freePort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
}
private static void respond(HttpExchange exchange, String text, AtomicBoolean virtualThread)
throws IOException {
try (exchange) {
if (virtualThread != null) {
virtualThread.set(Thread.currentThread().isVirtual());
}
byte[] body = text.getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
}
}
private static HttpResponse<String> get(HttpClient client, URI uri) throws Exception {
return client.send(
HttpRequest.newBuilder(uri).build(),
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
}
}