From fbec6694dfd8bbd65ace0dbdb9d0e09ea8dd6119 Mon Sep 17 00:00:00 2001 From: LunarSkyOSS Date: Mon, 26 Oct 2026 07:11:59 +0100 Subject: [PATCH] Serve admin console only on dedicated port --- .env.example | 4 ++ Dockerfile | 2 +- OPERATIONS.md | 6 ++- compose.admin.yaml | 4 ++ src/cloud/lunarsky/store/AdminConsole.java | 44 +++++++++++++--- src/cloud/lunarsky/store/Main.java | 35 ++++++++++--- .../lunarsky/store/ObjectStoreServer.java | 15 +++++- .../lunarsky/store/AdminConsoleTest.java | 50 ++++++++++++++++++- 8 files changed, 140 insertions(+), 20 deletions(-) diff --git a/.env.example b/.env.example index c6d67e9..8601c64 100644 --- a/.env.example +++ b/.env.example @@ -10,6 +10,10 @@ S3_SESSION_CREDENTIALS_FILE= S3_IDENTITY_POLICIES_DIR= METRICS_BEARER_TOKEN= HOST_PORT=9000 +# Optional admin overlay: keep the default loopback bind, or use a VPN interface IP. +ADMIN_UI_BIND_IP=127.0.0.1 +ADMIN_UI_HOST_PORT=9001 +ADMIN_UI_PRIVATE_ORIGIN= MAX_OBJECT_BYTES=134217728 MAX_TOTAL_BYTES=2147483648 PUBLIC_REQUESTS_PER_SECOND=0 diff --git a/Dockerfile b/Dockerfile index 4d2902c..ddc1478 100644 --- a/Dockerfile +++ b/Dockerfile @@ -31,5 +31,5 @@ COPY scripts/objectstore /usr/local/bin/objectstore COPY scripts/start-server.sh /usr/local/bin/objectstore-server RUN chmod 755 /usr/local/bin/objectstore /usr/local/bin/objectstore-server USER store -EXPOSE 9000 +EXPOSE 9000 9001 ENTRYPOINT ["/usr/local/bin/objectstore-server"] diff --git a/OPERATIONS.md b/OPERATIONS.md index 9e0c613..f42c99d 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -67,7 +67,7 @@ Set `METRICS_BEARER_TOKEN` to a random value of at least 32 characters to enable ### Local admin console -The admin console is a read-only status, bucket, and performance view at `http://127.0.0.1:9000/_objectstore/admin/`. It lists buckets, navigates object prefixes, and shows object metadata and bucket access settings. The object-size chart and counts cover only the current page of a listing. The performance view samples every three seconds while visible and graphs S3 request rate, inbound and outbound body bytes, process CPU, and memory. It also shows GC collections. Admin requests and health checks are excluded from those S3 rates, and chart history lives only in the browser tab. RSS is read from Linux when available; otherwise the memory card shows JVM heap plus non-heap usage. This view does not require the separate Prometheus token. It is disabled by default and uses a separate password, not an S3 access key. Its Biscuit widgets are bundled with the image under the MIT license in `admin-ui/LICENSE.Biscuit`. To enable it for the local Compose stack: +The admin console is a read-only status, bucket, and performance view at `http://127.0.0.1:9001/_objectstore/admin/`. It lists buckets, navigates object prefixes, and shows object metadata and bucket access settings. The object-size chart and counts cover only the current page of a listing. The performance view samples every three seconds while visible and graphs S3 request rate, inbound and outbound body bytes, process CPU, and memory. It also shows GC collections. Admin requests and health checks are excluded from those S3 rates, and chart history lives only in the browser tab. RSS is read from Linux when available; otherwise the memory card shows JVM heap plus non-heap usage. This view does not require the separate Prometheus token. It is disabled by default and uses a separate password, not an S3 access key. Its Biscuit widgets are bundled with the image under the MIT license in `admin-ui/LICENSE.Biscuit`. To enable it for the local Compose stack: ```sh mkdir -p secrets @@ -80,7 +80,9 @@ docker compose -f compose.yaml -f compose.admin.yaml up -d --build Read the generated password from `secrets/admin-password` on the host to sign in. The directory is private to your host account, while the file is readable by the container's unprivileged user through a read-only mount. The file is ignored by Git. The password must be at least 16 bytes. Sessions expire after 30 minutes, and five failed logins from one peer pause further attempts for five minutes. A restart clears all sessions. Do not reuse the S3 secret. -The console accepts only loopback Host values by default, including if the S3 port is accidentally published on a wider interface. For access through a reverse proxy, set `ADMIN_UI_ORIGIN` to the exact external HTTPS origin, preserve its Host header, and terminate TLS at the proxy. HTTP access through a remote origin is not supported. The password is still required behind the loopback binding or proxy; neither is an authentication mechanism. The console does not grant access to S3 operations. +The admin Compose overlay maps host port 9001 to a separate admin-only listener, bound to loopback by default. Admin paths return 404 on the S3 port; S3 paths return 404 on the admin port. The console accepts only loopback Host values by default, including if a port is accidentally published on a wider interface. For access through a reverse proxy, set `ADMIN_UI_ORIGIN` to the exact external HTTPS origin, preserve its Host header, and terminate TLS at the proxy. + +For a private VPN interface, set `ADMIN_UI_BIND_IP` to that interface's private IPv4 address and `ADMIN_UI_PRIVATE_ORIGIN` to `http://:9001`. The origin must use an RFC 1918 IPv4 address and an explicit port; the console then accepts only that Host value. The VPN must encrypt traffic and restrict who can reach the port. Do not publish this HTTP port on the public internet. The password is still required, and the admin listener does not accept S3 operations. For a bounded local write baseline, run `python3 scripts/benchmark-writes.py --requests 100 --concurrency 8 --size 4096` with `S3_ACCESS_KEY` and `S3_SECRET_KEY` in the environment. It writes under a unique `benchmark/` prefix and deletes successful objects afterward. Results depend on CPU, disks, network, connection reuse, and durability settings; a laptop number does not predict another server. Run a mixed upload/download workload before changing concurrency or public limits. diff --git a/compose.admin.yaml b/compose.admin.yaml index fe7c1ad..e749544 100644 --- a/compose.admin.yaml +++ b/compose.admin.yaml @@ -4,5 +4,9 @@ services: ADMIN_UI_ENABLED: "true" ADMIN_UI_PASSWORD_FILE: /run/secrets/objectstore_admin ADMIN_UI_ORIGIN: ${ADMIN_UI_ORIGIN:-} + ADMIN_UI_PRIVATE_ORIGIN: ${ADMIN_UI_PRIVATE_ORIGIN:-} + ADMIN_UI_BIND_ADDRESS: 0.0.0.0 + ports: + - "${ADMIN_UI_BIND_IP:-127.0.0.1}:${ADMIN_UI_HOST_PORT:-9001}:9001" volumes: - ./secrets/admin-password:/run/secrets/objectstore_admin:ro diff --git a/src/cloud/lunarsky/store/AdminConsole.java b/src/cloud/lunarsky/store/AdminConsole.java index 8582811..808b76b 100644 --- a/src/cloud/lunarsky/store/AdminConsole.java +++ b/src/cloud/lunarsky/store/AdminConsole.java @@ -193,17 +193,27 @@ final class AdminConsole { byte[] hash = SigV4.hash(trimmed); java.util.Arrays.fill(trimmed, (byte) 0); java.util.Arrays.fill(password, (byte) 0); - String configured = env.get("ADMIN_UI_ORIGIN"); + String privateOrigin = env.get("ADMIN_UI_PRIVATE_ORIGIN"); + String publicOrigin = env.get("ADMIN_UI_ORIGIN"); + if (privateOrigin != null && !privateOrigin.isBlank() && + publicOrigin != null && !publicOrigin.isBlank()) + throw new IllegalArgumentException("Configure only one admin UI origin"); + String configured = privateOrigin != null && !privateOrigin.isBlank() ? privateOrigin : publicOrigin; URI origin = null; if (configured != null && !configured.isBlank()) { try { origin = URI.create(configured); } catch (IllegalArgumentException error) { throw new IllegalArgumentException("Invalid ADMIN_UI_ORIGIN", error); } - if (!"https".equals(origin.getScheme()) || origin.getHost() == null || + boolean privateHttp = privateOrigin != null && !privateOrigin.isBlank(); + if (!(privateHttp ? "http".equals(origin.getScheme()) && + privateIpv4(origin.getHost()) && origin.getPort() > 0 && origin.getPort() <= 65535 : + "https".equals(origin.getScheme()) && origin.getHost() != null) || origin.getUserInfo() != null || origin.getRawQuery() != null || origin.getRawFragment() != null || !(origin.getRawPath().isEmpty() || origin.getRawPath().equals("/"))) - throw new IllegalArgumentException("ADMIN_UI_ORIGIN must be an HTTPS origin"); + throw new IllegalArgumentException(privateHttp ? + "ADMIN_UI_PRIVATE_ORIGIN must be an HTTP origin with a private IPv4 address and port" : + "ADMIN_UI_ORIGIN must be an HTTPS origin"); origin = URI.create(origin.toString().replaceFirst("/$", "")); } return new AdminConsole(store, hash, origin, @@ -218,7 +228,7 @@ final class AdminConsole { if (origin == null) { send(exchange, 403, page("

Admin console unavailable

" + "

Open the local console at http://127.0.0.1:<port>" + PATH + - "/login, or use the configured HTTPS origin.

"), "text/html; charset=utf-8"); + "/login, or use the configured origin.

"), "text/html; charset=utf-8"); return; } String path = exchange.getRequestURI().getRawPath(); @@ -506,7 +516,7 @@ final class AdminConsole { private String sessionCookie(HttpExchange exchange) { String header = exchange.getRequestHeaders().getFirst("Cookie"); if (header == null || header.length() > 8192) return ""; - String name = publicOrigin == null ? "objectstore_admin=" : "__Host-objectstore_admin="; + String name = secureOrigin() ? "__Host-objectstore_admin=" : "objectstore_admin="; for (String field : header.split(";")) { String value = field.trim(); if (value.startsWith(name) && value.substring(name.length()).matches("[A-Za-z0-9_-]{43}")) @@ -516,10 +526,28 @@ final class AdminConsole { } private String cookie(String token, int seconds) { - String name = publicOrigin == null ? "objectstore_admin" : "__Host-objectstore_admin"; - String path = publicOrigin == null ? PATH : "/"; + String name = secureOrigin() ? "__Host-objectstore_admin" : "objectstore_admin"; + String path = secureOrigin() ? "/" : PATH; return name + "=" + token + "; Path=" + path + "; HttpOnly; SameSite=Strict; Max-Age=" + seconds + - (publicOrigin == null ? "" : "; Secure"); + (secureOrigin() ? "; Secure" : ""); + } + + private boolean secureOrigin() { + return publicOrigin != null && "https".equals(publicOrigin.getScheme()); + } + + private static boolean privateIpv4(String host) { + if (host == null || !host.matches("[0-9]+(?:\\.[0-9]+){3}")) return false; + String[] fields = host.split("\\."); + int[] octets = new int[4]; + for (int i = 0; i < octets.length; i++) { + if (fields[i].length() > 3 || (fields[i].length() > 1 && fields[i].startsWith("0"))) return false; + octets[i] = Integer.parseInt(fields[i]); + if (octets[i] > 255) return false; + } + return octets[0] == 10 || + (octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31) || + (octets[0] == 192 && octets[1] == 168); } private String requestOrigin(HttpExchange exchange) { diff --git a/src/cloud/lunarsky/store/Main.java b/src/cloud/lunarsky/store/Main.java index 0831007..af3ff17 100644 --- a/src/cloud/lunarsky/store/Main.java +++ b/src/cloud/lunarsky/store/Main.java @@ -21,6 +21,7 @@ public final class Main { private final ObjectHandler objectHandler; private final ClientLimits clientLimits; private final Semaphore slots; + private final Semaphore adminSlots = new Semaphore(8); private final String virtualHostSuffix; private final BrowserCors cors; private final KeyScopes keyScopes; @@ -123,13 +124,7 @@ public final class Main { dataStarted = true; } if (path.equals(AdminConsole.PATH) || path.startsWith(AdminConsole.PATH + "/")) { - admitted = slots.tryAcquire(); - if (!admitted) throw new StoreException(503, "SlowDown", "Too many concurrent requests"); - if (adminConsole == null) { - exchange.sendResponseHeaders(404, -1); - } else { - adminConsole.handle(exchange); - } + exchange.sendResponseHeaders(404, -1); return; } cors.decorate(exchange); @@ -158,6 +153,32 @@ public final class Main { } } + void handleAdmin(HttpExchange exchange) throws IOException { + boolean admitted = false; + try { + String path = exchange.getRequestURI().getRawPath(); + if (adminConsole == null || + !(path.equals(AdminConsole.PATH) || path.startsWith(AdminConsole.PATH + "/"))) { + exchange.sendResponseHeaders(404, -1); + return; + } + admitted = adminSlots.tryAcquire(); + if (!admitted) { + exchange.sendResponseHeaders(503, -1); + return; + } + adminConsole.handle(exchange); + } catch (StoreException error) { + exchange.sendResponseHeaders(error.status, -1); + } catch (Exception error) { + System.err.println("ObjectStore admin request failed: " + error.getClass().getSimpleName()); + exchange.sendResponseHeaders(500, -1); + } finally { + exchange.close(); + if (admitted) adminSlots.release(); + } + } + private void dispatch(HttpExchange exchange) throws IOException { SigV4.Verified verified = anonymousRead(exchange) ? new SigV4.Verified("UNSIGNED-PAYLOAD", exchange.getRequestURI().getRawQuery(), diff --git a/src/cloud/lunarsky/store/ObjectStoreServer.java b/src/cloud/lunarsky/store/ObjectStoreServer.java index c211baf..5d080c3 100644 --- a/src/cloud/lunarsky/store/ObjectStoreServer.java +++ b/src/cloud/lunarsky/store/ObjectStoreServer.java @@ -55,23 +55,36 @@ final class ObjectStoreServer { new RequestMetrics(env.get("METRICS_BEARER_TOKEN")), IdentityPolicies.fromEnvironment(env, access, allIdentities), publicEndpoint(env)); - app.setAdminConsole(AdminConsole.fromEnvironment(env, store)); + AdminConsole adminConsole = AdminConsole.fromEnvironment(env, store); + app.setAdminConsole(adminConsole); int port = Integer.parseInt(env.getOrDefault("PORT", "9000")); + int adminPort = adminConsole == null ? 0 : positiveInt(env, "ADMIN_UI_PORT", 9001, 65535); + if (adminConsole != null && port == adminPort) + throw new IllegalArgumentException("ADMIN_UI_PORT must differ from PORT"); var server = HttpServer.create(mode.equals("cluster") ? new InetSocketAddress(env.getOrDefault("BIND_ADDRESS", "127.0.0.1"), port) : new InetSocketAddress(port), positiveInt(env, "HTTP_BACKLOG", 64, 4096)); + HttpServer adminServer = adminConsole == null ? null : HttpServer.create( + new InetSocketAddress(env.getOrDefault("ADMIN_UI_BIND_ADDRESS", "127.0.0.1"), adminPort), 16); var executor = Executors.newVirtualThreadPerTaskExecutor(); server.setExecutor(executor); server.createContext("/", app::handle); + if (adminServer != null) { + adminServer.setExecutor(executor); + adminServer.createContext("/", app::handleAdmin); + } Runtime.getRuntime().addShutdownHook(new Thread(() -> { server.stop(5); + if (adminServer != null) adminServer.stop(5); executor.close(); try { store.close(); } catch (IOException error) { System.err.println("Could not release ObjectStore data lock: " + error.getMessage()); } })); server.start(); + if (adminServer != null) adminServer.start(); if (store instanceof DiskStore disk) printStartup(disk, multipart, bucket, region, port); else System.out.println("ObjectStore local cluster prototype v" + Version.VALUE + " listening on :" + port); + if (adminServer != null) System.out.println("ObjectStore admin listening on :" + adminPort); } static Map identities(Map env, String access, String secret) diff --git a/test/cloud/lunarsky/store/AdminConsoleTest.java b/test/cloud/lunarsky/store/AdminConsoleTest.java index 098438f..e1d79c9 100644 --- a/test/cloud/lunarsky/store/AdminConsoleTest.java +++ b/test/cloud/lunarsky/store/AdminConsoleTest.java @@ -50,6 +50,19 @@ public final class AdminConsoleTest { HttpResponse.BodyHandlers.ofString()).body()); } + private static String rawRequest(int port, String host, String method, String path, String body) throws Exception { + byte[] content = body.getBytes(StandardCharsets.UTF_8); + try (Socket socket = new Socket("127.0.0.1", port)) { + socket.getOutputStream().write((method + " " + AdminConsole.PATH + path + " HTTP/1.1\r\n" + + "Host: " + host + "\r\nConnection: close\r\n" + + (method.equals("POST") ? "Content-Type: application/x-www-form-urlencoded\r\n" + + "Content-Length: " + content.length + "\r\n" : "") + + "\r\n").getBytes(StandardCharsets.US_ASCII)); + if (content.length > 0) socket.getOutputStream().write(content); + return new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + } + } + public static void main(String[] args) throws Exception { Path root = Files.createTempDirectory("admin-console-test-"); Path passwordFile = root.resolve("password"); @@ -61,6 +74,7 @@ public final class AdminConsoleTest { SigV4.hex(SigV4.hash(image)), null, true, "text/plain"); var executor = Executors.newVirtualThreadPerTaskExecutor(); HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16); + HttpServer s3Server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16); try { if (AdminConsole.fromEnvironment(Map.of(), store) != null) throw new AssertionError("Admin console enabled without configuration"); @@ -74,6 +88,15 @@ public final class AdminConsoleTest { "ADMIN_UI_ORIGIN", "http://public.example"), store); throw new AssertionError("Admin console accepted a remote HTTP origin"); } catch (IllegalArgumentException expected) { } + for (String invalid : new String[] { "http://public.example:9001", "http://8.8.8.8:9001", + "http://10.30.0.120", "https://10.30.0.120:9001" }) { + try { + AdminConsole.fromEnvironment(Map.of("ADMIN_UI_ENABLED", "true", + "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(), + "ADMIN_UI_PRIVATE_ORIGIN", invalid), store); + throw new AssertionError("Admin console accepted invalid private origin: " + invalid); + } catch (IllegalArgumentException expected) { } + } AdminConsole console = AdminConsole.fromEnvironment(Map.of( "ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString()), store); var app = new Main(store, new MultipartStore(store), @@ -81,10 +104,18 @@ public final class AdminConsoleTest { "us-east-1", Clock.systemUTC()), "objects"); app.setAdminConsole(console); server.setExecutor(executor); - server.createContext("/", app::handle); + server.createContext("/", app::handleAdmin); server.start(); + s3Server.setExecutor(executor); + s3Server.createContext("/", app::handle); + s3Server.start(); String base = "http://127.0.0.1:" + server.getAddress().getPort(); + String s3Base = "http://127.0.0.1:" + s3Server.getAddress().getPort(); HttpClient client = HttpClient.newHttpClient(); + status(404, client.send(request(s3Base, "/login").GET().build(), + HttpResponse.BodyHandlers.discarding())); + status(404, client.send(HttpRequest.newBuilder(URI.create(base + "/health")).GET().build(), + HttpResponse.BodyHandlers.discarding())); try (Socket socket = new Socket("127.0.0.1", server.getAddress().getPort())) { socket.getOutputStream().write(("GET " + AdminConsole.PATH + "/login HTTP/1.1\r\n" + "Host: public.example\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII)); @@ -206,9 +237,26 @@ public final class AdminConsoleTest { status(401, post(client, base, "/login", "incorrect", loginToken(client, base), null, null)); } status(429, post(client, base, "/login", PASSWORD, loginToken(client, base), null, null)); + app.setAdminConsole(AdminConsole.fromEnvironment(Map.of( + "ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(), + "ADMIN_UI_PRIVATE_ORIGIN", "http://10.30.0.120:9001"), store)); + int port = server.getAddress().getPort(); + String privatePage = rawRequest(port, "10.30.0.120:9001", "GET", "/login", ""); + if (!privatePage.startsWith("HTTP/1.1 200") || !privatePage.contains("Admin password")) + throw new AssertionError("Configured private VPN origin did not open the admin console"); + if (!rawRequest(port, "public.example", "GET", "/login", "").startsWith("HTTP/1.1 403")) + throw new AssertionError("Unconfigured Host reached the private admin console"); + String form = "password=" + java.net.URLEncoder.encode(PASSWORD, StandardCharsets.UTF_8) + + "&csrf=" + csrf(privatePage); + String privateLogin = rawRequest(port, "10.30.0.120:9001", "POST", "/login", form); + if (!privateLogin.startsWith("HTTP/1.1 303") || + !privateLogin.contains("Set-cookie: objectstore_admin=") || + privateLogin.contains("; Secure")) + throw new AssertionError("Private VPN login or cookie is invalid"); System.out.println("Admin console tests passed"); } finally { server.stop(0); + s3Server.stop(0); executor.close(); store.close(); try (var paths = Files.walk(root)) {