package cloud.lunarsky.store; import com.sun.net.httpserver.HttpServer; import java.io.ByteArrayInputStream; import java.net.InetSocketAddress; import java.net.Socket; 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.time.Clock; import java.util.Comparator; import java.util.Map; import java.util.concurrent.Executors; public final class AdminConsoleTest implements AutoCloseable { private static final String PASSWORD = "a-very-long-test-admin-password"; private final Path root; private final Path passwordFile; private final Path masterFile; private final DiskStore store; private final DiskBucketNames names; private final BucketActivity activity; private final java.util.concurrent.ExecutorService executor; private final HttpServer server; private final HttpServer s3Server; private final HttpClient client; private final String base; private final String s3Base; private Main app; private ManagedCredentials managed; private String cookie; private String adminCsrf; private static void status(int wanted, HttpResponse response) { if (response.statusCode() != wanted) throw new AssertionError("Expected " + wanted + ", got " + response.statusCode() + ": " + response.body()); } private static HttpRequest.Builder request(String base, String path) { return HttpRequest.newBuilder(URI.create(base + AdminConsole.PATH + path)); } private static HttpResponse post(HttpClient client, String base, String path, String password, String csrf, String origin, String cookie) throws Exception { var builder = request(base, path).header("Content-Type", "application/x-www-form-urlencoded"); if (origin != null) builder.header("Origin", origin); if (cookie != null) builder.header("Cookie", cookie); return client.send(builder.POST(HttpRequest.BodyPublishers.ofString( "password=" + java.net.URLEncoder.encode(password, StandardCharsets.UTF_8) + "&csrf=" + java.net.URLEncoder.encode(csrf, StandardCharsets.UTF_8))).build(), HttpResponse.BodyHandlers.ofString()); } private static String csrf(String page) { var match = java.util.regex.Pattern.compile("name=csrf value='([A-Za-z0-9_-]{43})'").matcher(page); if (!match.find()) throw new AssertionError("CSRF token missing from page"); return match.group(1); } private static HttpResponse action(HttpClient client, String base, String name, String cookie, String origin, String form) throws Exception { var builder = request(base, "/action/" + name) .header("Content-Type", "application/x-www-form-urlencoded") .header("Cookie", cookie); if (origin != null) builder.header("Origin", origin); return client.send(builder.POST(HttpRequest.BodyPublishers.ofString(form)).build(), HttpResponse.BodyHandlers.ofString()); } private static HttpResponse upload(HttpClient client, String base, String path, String cookie, String origin, String csrf, byte[] content) throws Exception { var builder = request(base, "/upload?" + path) .header("Content-Type", "text/plain") .header("Cookie", cookie); if (origin != null) builder.header("Origin", origin); if (csrf != null) builder.header("X-ObjectStore-CSRF", csrf); return client.send(builder.POST(HttpRequest.BodyPublishers.ofByteArray(content)).build(), HttpResponse.BodyHandlers.ofString()); } private static String loginToken(HttpClient client, String base) throws Exception { return csrf(client.send(request(base, "/login").GET().build(), 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); } } private AdminConsoleTest() throws Exception { root = Files.createTempDirectory("admin-console-test-"); passwordFile = root.resolve("password"); Files.writeString(passwordFile, PASSWORD + "\n"); masterFile = root.resolve("credential-master"); Files.writeString(masterFile, "0123456789abcdef".repeat(4)); store = new DiskStore(root.resolve("data"), 1024, 4096); store.ensureBucket("photos"); byte[] image = "small preview".getBytes(StandardCharsets.UTF_8); store.put("photos", "images/cat.txt", new ByteArrayInputStream(image), image.length, SigV4.hex(SigV4.hash(image)), null, true, "text/plain"); names = new DiskBucketNames(store, new MultipartStore(store)); activity = new BucketActivity(root.resolve("data/bucket-activity.tsv")); activity.record("photos", "GET"); executor = Executors.newVirtualThreadPerTaskExecutor(); server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16); s3Server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 16); base = "http://127.0.0.1:" + server.getAddress().getPort(); s3Base = "http://127.0.0.1:" + s3Server.getAddress().getPort(); client = HttpClient.newHttpClient(); } public static void main(String[] args) throws Exception { try (AdminConsoleTest test = new AdminConsoleTest()) { test.verifyLegacyBranding(); test.verifyConfiguration(); test.startServers(); test.verifyUnauthenticatedAccess(); test.verifyLoginPage(); test.verifyPublicAssets(); test.login(); test.verifyOverview(); test.verifyWorkspaceAssets(); test.verifyHealthAndDiagnostics(); test.verifyAuditAccessCheck(); test.verifyJobsAndClusterViews(); test.verifyPerformanceView(); test.verifyPerformanceEvents(); test.verifyPerformanceCounters(); test.verifyBucketBrowser(); test.verifyObjectBrowser(); test.verifyUploadAndDownload(); test.verifyBucketCreation(); test.verifyManagedCredentials(); test.verifyBucketPolicies(); test.verifyBucketGrantsAndVersioning(); test.verifyVersionedUpload(); test.verifyTextEditing(); test.verifyTagsAndDeletion(); test.verifyBucketRename(); test.verifyThemeAndBrandingName(); test.verifyBrandingIcon(); test.verifyInputEscaping(); test.verifyLogoutAndCooldown(); test.verifyPrivateOrigin(); System.out.println("Admin console tests passed"); } } private void verifyLegacyBranding() throws Exception { Path legacyBranding = root.resolve("legacy-branding.txt"); Files.writeString(legacyBranding, "ObjectStoreBranding 1\n" + java.util.Base64.getEncoder().encodeToString("Old name".getBytes(StandardCharsets.UTF_8)) + "\n\n\n"); AdminBranding migrated = new AdminBranding(legacyBranding); if (!migrated.state().name().equals("Old name") || !migrated.state().defaultTheme().equals("deep-dark")) throw new AssertionError("Legacy branding or deep-dark default was lost"); migrated.setDefaultTheme("light"); if (!new AdminBranding(legacyBranding).state().defaultTheme().equals("light") || !new AdminBranding(legacyBranding).state().name().equals("Old name")) throw new AssertionError("Global theme did not persist across branding migration"); } private void verifyConfiguration() throws Exception { if (AdminConsole.fromEnvironment(Map.of(), store) != null) throw new AssertionError("Admin console enabled without configuration"); try { AdminConsole.fromEnvironment(Map.of("ADMIN_UI_ENABLED", "true"), store); throw new AssertionError("Admin console enabled without password file"); } catch (IllegalArgumentException expected) { } try { AdminConsole.fromEnvironment(Map.of("ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(), "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) { } } } private void startServers() throws Exception { AdminConsole console = AdminConsole.fromEnvironment(Map.of( "ADMIN_UI_ENABLED", "true", "ADMIN_UI_PASSWORD_FILE", passwordFile.toString(), "DATA_DIR", root.resolve("data").toString()), names); console.setDiskStore(store); app = new Main(names, names, new SigV4("TESTACCESSKEY123", "test-secret-key-that-is-at-least-32-characters", "us-east-1", Clock.systemUTC()), "objects"); app.setBucketActivity(activity); app.setAdminConsole(console); managed = ManagedCredentials.fromEnvironment(Map.of( "S3_MANAGED_KEYS_MASTER_FILE", masterFile.toString(), "DATA_DIR", root.resolve("data").toString()), store, java.util.Set.of("TESTACCESSKEY123")); app.setManagedCredentials(managed); server.setExecutor(executor); server.createContext("/", app::handleAdmin); server.start(); s3Server.setExecutor(executor); s3Server.createContext("/", app::handle); s3Server.start(); } private void verifyUnauthenticatedAccess() throws Exception { 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)); String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8); if (!response.startsWith("HTTP/1.1 403")) throw new AssertionError("Public Host header reached the admin console"); } status(303, client.send(request(base, "/overview").GET().build(), HttpResponse.BodyHandlers.ofString())); for (String path : new String[] { "/performance", "/performance.json", "/performance.js", "/settings", "/health", "/diagnostics", "/diagnostics/probe.bin", "/audit", "/jobs", "/cluster", "/buckets", "/bucket?name=photos", "/object?bucket=photos&key=images%2Fcat.txt" }) { status(303, client.send(request(base, path).GET().build(), HttpResponse.BodyHandlers.ofString())); } status(401, client.send(request(base, "/jobs.json?id=abcdefghijklmnop").GET().build(), HttpResponse.BodyHandlers.ofString())); } private void verifyLoginPage() throws Exception { var loginPage = client.send(request(base, "/login").GET().build(), HttpResponse.BodyHandlers.ofString()); status(200, loginPage); if (!loginPage.body().contains("Admin password") || !loginPage.body().contains("/_objectstore/admin/logo.png") || !loginPage.headers().firstValue("Cache-Control").orElse("").equals("no-store")) throw new AssertionError("Login page or cache control missing"); var loginAppearance = client.send(request(base, "/workspace.js").GET().build(), HttpResponse.BodyHandlers.ofString()); status(200, loginAppearance); if (!loginAppearance.body().contains("applyPreferences")) throw new AssertionError("Login appearance script missing"); String policy = loginPage.headers().firstValue("Content-Security-Policy").orElse(""); if (!policy.contains("style-src 'self'") || !policy.contains("img-src 'self'")) throw new AssertionError("Admin console content policy missing"); } private void verifyPublicAssets() throws Exception { var logo = client.send(request(base, "/logo.png").GET().build(), HttpResponse.BodyHandlers.ofByteArray()); status(200, logo); if (!logo.headers().firstValue("Content-Type").orElse("").equals("image/png") || logo.body().length < 8 || logo.body()[0] != (byte) 0x89 || logo.body()[1] != 'P' || logo.body()[2] != 'N' || logo.body()[3] != 'G') throw new AssertionError("ObjectStore icon is unavailable"); var style = client.send(request(base, "/style.css").GET().build(), HttpResponse.BodyHandlers.ofString()); status(200, style); if (!style.body().contains("color-scheme: dark") || !style.body().contains("--biscuit-chart-surface: #211c2b")) throw new AssertionError("Dark chart styles missing"); status(303, client.send(request(base, "/biscuit.js").GET().build(), HttpResponse.BodyHandlers.discarding())); } private void login() throws Exception { status(403, post(client, base, "/login", PASSWORD, "invalid", null, null)); status(401, post(client, base, "/login", "incorrect", loginToken(client, base), null, null)); var login = post(client, base, "/login", PASSWORD, loginToken(client, base), null, null); status(303, login); cookie = login.headers().firstValue("Set-Cookie").orElseThrow().split(";", 2)[0]; if (!login.headers().firstValue("Set-Cookie").orElseThrow().contains("HttpOnly; SameSite=Strict")) throw new AssertionError("Session cookie protections missing"); } private void verifyOverview() throws Exception { var overview = client.send(request(base, "/overview").header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()); status(200, overview); if (!overview.body().contains("Storage mode") || !overview.body().contains("biscuit-cardview") || !overview.body().contains("photos") || !overview.body().contains("/performance") || !overview.body().contains("/_objectstore/admin/logo.png") || !overview.body().contains("biscuit-sidebarview") || !overview.body().contains("biscuit-navbarview") || !overview.body().contains("/icons/bucket.svg") || !overview.body().contains("/icons/activity.svg") || !overview.body().contains("class=mobile-nav-link") || !overview.body().contains("biscuit-footerview")) throw new AssertionError("Authenticated overview missing"); adminCsrf = csrf(overview.body()); } private void verifyWorkspaceAssets() throws Exception { var workspace = client.send(request(base, "/workspace.js").header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()); status(200, workspace); var bucketIcon = client.send(request(base, "/icons/bucket.svg") .header("Cookie", cookie).GET().build(), HttpResponse.BodyHandlers.ofString()); status(200, bucketIcon); if (!bucketIcon.body().contains("