From ac844769fbdcd9c4723a750cc1364947078fc3f0 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:25:11 -0400 Subject: [PATCH] feat(emr-containers): let a browser's CORS preflight reach a managed endpoint's gateway (#9283) A browser sends its CORS preflight (OPTIONS) without the session token, and Jupyter Enterprise Gateway 2.6.0's TokenAuthorizationMixin checks none for it ("if server_token and not self.request.method == 'OPTIONS'"). Floci's proxy asked one of every request, so a preflight to a managed endpoint's serverUrl got 401. - SessionServers.routeWithoutToken routes a call that carries no token to a running server, in that server's own account and Region, as a call of its session: empty where no server runs, refused while the owner refuses calls. - EmrContainersService.gatewayPreflightRoute is that route for an endpoint's gateway, and the proxy takes it for an OPTIONS request, passing the gateway no session header. An endpoint with no gateway running still answers 401, one that is not ACTIVE 503. - The nightly check sends a preflight without a token and gets the gateway's 200 with its Access-Control-Allow-Methods. --- docs/services/emr-containers.md | 8 +++---- .../EmrContainersGatewayProxy.java | 19 +++++++++++------ .../emrcontainers/EmrContainersService.java | 9 ++++++++ .../emrserverless/SessionServers.java | 17 +++++++++++++++ ...ntainersGatewayNightlyIntegrationTest.java | 21 +++++++++++++------ .../EmrContainersGatewayProxyTest.java | 19 +++++++++++++++++ .../EmrContainersServiceTest.java | 16 ++++++++++++++ .../emrserverless/SessionServersTest.java | 15 +++++++++++++ 8 files changed, 108 insertions(+), 16 deletions(-) diff --git a/docs/services/emr-containers.md b/docs/services/emr-containers.md index b718d1cd75..b7f726fdf2 100644 --- a/docs/services/emr-containers.md +++ b/docs/services/emr-containers.md @@ -231,7 +231,8 @@ remote kernel lifecycle management capability that interactive clients need" (EM not yet expired, as Jupyter Enterprise Gateway takes one: its last `token` parameter, else an `Authorization: token ` header, which is what a Jupyter client sends. Any other request gets that gateway's 401 `{"reason": "Unauthorized", "message": ""}`, an expired token's with a message saying so, and one to an endpoint - that is not `ACTIVE` gets 503. + that is not `ACTIVE` gets 503. A browser's CORS preflight (`OPTIONS`) goes to an endpoint's gateway without a + token, as Jupyter Enterprise Gateway's token check passes it over, and the gateway sends the CORS headers back. * **Kernels**: the image's `python3` ("Python 3"); `spark-python-kubernetes` ("PySpark on Kubernetes", the name the guide's `jupyter-kernel-overrides` example gives it); and `spark-scala-kubernetes` ("Apache Spark with Scala", a name of Floci's beside it, as the guide gives the Scala kernel none), which runs the image's Apache Toree under @@ -262,6 +263,5 @@ remote kernel lifecycle management capability that interactive clients need" (EM `RemoteMappingKernelManager.cull_interval`, "The interval in seconds (integer) on which to check for idle kernels that exceed the cull timeout value." As jupyter_server's culler does by default, a kernel with a client connected is not culled. Other `jeg-config` properties go nowhere. -* **Not emulated yet**: `jupyter-kernel-overrides` images. A browser's CORS preflight (`OPTIONS`), which Jupyter - Enterprise Gateway takes without a token, needs one here. `certificateArn` is kept, and the `serverUrl` is plain - HTTP on Floci's port. +* **Not emulated yet**: `jupyter-kernel-overrides` images. `certificateArn` is kept, and the `serverUrl` is plain HTTP + on Floci's port. diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxy.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxy.java index a24290e3ae..2940b9b361 100644 --- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxy.java +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxy.java @@ -44,7 +44,9 @@ import java.util.concurrent.atomic.AtomicBoolean; * {@code token} parameter, or an {@code Authorization: token } header. One without such a token gets that * gateway's answer, 401 with {@code {"reason": "Unauthorized", "message": ""}}; one whose endpoint is not ACTIVE, * 503, its message saying why. The gateway gets the token's SHA-256 in place of the token, in - * {@link EmrContainersGateways#SESSION_HEADER}, to list a session token's kernels by. + * {@link EmrContainersGateways#SESSION_HEADER}, to list a session token's kernels by. A CORS preflight + * ({@code OPTIONS}), which a browser sends without the token, goes on without one, as that gateway's + * TokenAuthorizationMixin checks none for it. */ @ApplicationScoped public class EmrContainersGatewayProxy { @@ -94,11 +96,13 @@ public class EmrContainersGatewayProxy { int slash = rest.indexOf('/'); String endpointId = slash < 0 ? rest : rest.substring(0, slash); String path = slash < 0 ? "/" : rest.substring(slash); - String token = token(request); + boolean preflight = request.method() == HttpMethod.OPTIONS; + String token = preflight ? null : token(request); request.pause(); // A service reads its storage to route a request, so off the event loop. - vertx.>executeBlocking(() -> service.gatewayRoute(endpointId, token), - false).onComplete(routed -> { + vertx.>executeBlocking(() -> preflight + ? service.gatewayPreflightRoute(endpointId) : service.gatewayRoute(endpointId, token), false) + .onComplete(routed -> { if (routed.failed()) { LOG.warnv(routed.cause(), "A request to endpoint {0}'s gateway could not be routed", endpointId); @@ -113,7 +117,8 @@ public class EmrContainersGatewayProxy { refuse(request, 503, "Service Unavailable", refused.refusal()); } } else { - forward(request, path + query(request), Digests.sha256Hex(token), routed.result().get()); + forward(request, path + query(request), preflight ? null : Digests.sha256Hex(token), + routed.result().get()); } }); } @@ -179,7 +184,9 @@ public class EmrContainersGatewayProxy { options.addHeader(header.getKey(), header.getValue()); } } - options.addHeader(EmrContainersGateways.SESSION_HEADER, session); + if (session != null) { + options.addHeader(EmrContainersGateways.SESSION_HEADER, session); + } client.request(options).onComplete(opened -> { if (opened.failed()) { refuse(request, 502, "Bad Gateway", diff --git a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java index 51ce26913f..6a091df445 100644 --- a/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java +++ b/src/main/java/io/floci/aws/services/emrcontainers/EmrContainersService.java @@ -769,6 +769,15 @@ public class EmrContainersService implements Resettable, StoredResourceArns { : gateways.servers().route(token, endpointId, gatewayOwner); } + /** + * Where a CORS preflight to endpoint {@code endpointId}'s gateway goes, which Jupyter Enterprise Gateway 2.6.0's + * TokenAuthorizationMixin takes without a token: empty where no gateway of this process runs, refused while the + * endpoint is not ACTIVE, else its gateway. Called off the event loop, as the account and Region of none. + */ + public Optional gatewayPreflightRoute(String endpointId) { + return gateways == null ? Optional.empty() : gateways.servers().routeWithoutToken(endpointId, gatewayOwner); + } + /** * The endpoint as it stands, stored: in the docker runner mode, one whose gateway no thread of this process runs, * as after a restart, has ended, TERMINATED_WITH_ERRORS, or TERMINATED where it was being deleted. diff --git a/src/main/java/io/floci/aws/services/emrserverless/SessionServers.java b/src/main/java/io/floci/aws/services/emrserverless/SessionServers.java index 70d09c083b..c940ca0677 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SessionServers.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SessionServers.java @@ -246,6 +246,23 @@ public final class SessionServers { return Optional.of(RequestScopes.callAs(grant.accountId(), grant.region(), () -> callStarted(grant, owner))); } + /** + * Where a call to session {@code sessionId}'s server that carries no token goes, as a server takes a CORS + * preflight without one: empty where no thread of this process runs that server; refused while {@code owner} says + * the session takes no calls; else its server, the call counting as one the session takes until it ends. + */ + public Optional routeWithoutToken(String sessionId, Owner owner) { + Server server; + synchronized (this) { + server = servers.get(sessionId); + } + if (server == null) { + return Optional.empty(); + } + Grant grant = new Grant(server.accountId, server.region, sessionId, Instant.MAX); + return Optional.of(RequestScopes.callAs(server.accountId, server.region, () -> callStarted(grant, owner))); + } + /** Checks the session at {@code at} by {@code check}, run as its account and Region, in place of any it had. */ public void checkAt(String sessionId, Instant at, Runnable check) { if (checks == null) { diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java index a24bb49bde..755fe3ee0c 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayNightlyIntegrationTest.java @@ -53,12 +53,13 @@ import static org.junit.jupiter.api.Assertions.fail; /** * An EMR on EKS managed endpoint, run for real in the {@code docker} runner mode: it runs a Jupyter Enterprise Gateway * in its release's {@code notebook-spark} image from Amazon ECR Public, and a Jupyter client reaches it at its - * {@code serverUrl} with a session token, starts a PySpark kernel there, and a session with a kernel of its own, which - * the kernels and sessions listings show that token alone, and runs code on Floci's S3 over the PySpark kernel's - * WebSocket, as the guide's "Example: Deploy a JupyterLab notebook" does through {@code JUPYTER_GATEWAY_URL}, then - * changes its Spark session's settings with {@code %%configure}, as "Modifying PySpark session parameters" does, - * and runs code on Floci's S3 in the "Apache Spark with Scala" kernel too. An - * endpoint whose {@code jeg-config} sets a short idle timeout culls a kernel left idle. + * {@code serverUrl} with a session token, as a browser's CORS preflight does without one. The client starts a + * PySpark kernel there, and a session with a kernel of its own, which the kernels and sessions listings show that + * token alone, and runs code on Floci's S3 over the PySpark kernel's WebSocket, as the guide's "Example: Deploy a + * JupyterLab notebook" does through {@code JUPYTER_GATEWAY_URL}, then changes its Spark session's settings with + * {@code %%configure}, as "Modifying PySpark session parameters" does, and runs code on Floci's S3 in the "Apache + * Spark with Scala" kernel too. An endpoint whose {@code jeg-config} sets a short idle timeout culls a kernel left + * idle. * *

A nightly check: the release's notebook image is about 6 GB. */ @@ -122,6 +123,14 @@ class EmrContainersGatewayNightlyIntegrationTest { HttpClient http = HttpClient.newHttpClient(); assertEquals(401, http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernelspecs")).build(), HttpResponse.BodyHandlers.discarding()).statusCode(), "a request without the session token"); + // A browser's CORS preflight carries no token, and the gateway answers it. + HttpResponse preflight = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernels")) + .method("OPTIONS", HttpRequest.BodyPublishers.noBody()) + .header("Origin", "http://notebook.test").header("Access-Control-Request-Method", "POST").build(), + HttpResponse.BodyHandlers.discarding()); + assertEquals(200, preflight.statusCode()); + assertTrue(preflight.headers().firstValue("Access-Control-Allow-Methods").orElse("").contains("POST"), + preflight.headers().toString()); HttpResponse specs = http.send(HttpRequest.newBuilder(URI.create(gateway + "/api/kernelspecs")) .header("Authorization", "token " + token).build(), HttpResponse.BodyHandlers.ofString()); assertEquals(200, specs.statusCode(), specs.body()); diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxyTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxyTest.java index b2e0effb34..68916dd54b 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxyTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersGatewayProxyTest.java @@ -81,6 +81,9 @@ class EmrContainersGatewayProxyTest { when(service.gatewayRoute(anyString(), any())).thenReturn(Optional.empty()); when(service.gatewayRoute(ENDPOINT, TOKEN)).thenAnswer(invocation -> Optional.of( SparkConnectTargets.Route.to("127.0.0.1", gateway.actualPort(), requestsEnded::incrementAndGet))); + when(service.gatewayPreflightRoute(anyString())).thenReturn(Optional.empty()); + when(service.gatewayPreflightRoute(ENDPOINT)).thenAnswer(invocation -> Optional.of( + SparkConnectTargets.Route.to("127.0.0.1", gateway.actualPort(), requestsEnded::incrementAndGet))); ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class); when(serviceConfigAccess.isEnabled(eq(EmrContainersService.SERVICE))).thenReturn(true); EmrContainersGatewayProxy proxy = new EmrContainersGatewayProxy(service, serviceConfigAccess, vertx); @@ -125,6 +128,22 @@ class EmrContainersGatewayProxyTest { awaitCount(requestsEnded, 1); } + @Test + void corsPreflightGoesToItsGatewayWithoutAToken() throws Exception { + // A browser's preflight carries no token, and Jupyter Enterprise Gateway checks none for one. + Answer preflight = request(HttpMethod.OPTIONS, BASE + "/api/kernels", null, null); + Answer elsewhere = request(HttpMethod.OPTIONS, EmrContainersService.GATEWAY_PATH + "ep0000000000000/api", + null, null); + + assertEquals(201, preflight.status); + JsonObject got = new JsonObject(preflight.body); + assertEquals("OPTIONS", got.getString("method")); + assertEquals("/api/kernels", got.getString("uri")); + assertNull(got.getString("session"), "a preflight is no session token's"); + assertEquals(401, elsewhere.status, "an endpoint with no gateway running"); + awaitCount(requestsEnded, 1); + } + @Test void queryIsReadAsTheGatewayReadsIt() throws Exception { // Its last token parameter is the one checked, and a malformed escape stays as it came. diff --git a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java index 479d2fbbce..1ac8413872 100644 --- a/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrcontainers/EmrContainersServiceTest.java @@ -1403,6 +1403,22 @@ class EmrContainersServiceTest { runner.stop(otherId); } + @Test + void corsPreflightReachesAnActiveEndpointsGatewayWithoutAToken() { + GatewayRunner runner = new GatewayRunner(); + EmrContainersService service = gatewayService(runner, stores()); + String clusterId = virtualCluster(service, EKS_CLUSTER); + String endpointId = gatewayEndpoint(service, clusterId); + awaitEndpoint(service, clusterId, endpointId, "ACTIVE"); + + SparkConnectTargets.Route route = service.gatewayPreflightRoute(endpointId).orElseThrow(); + assertEquals("127.0.0.1", route.host()); + assertEquals(GatewayRunner.PORT, route.port()); + route.ended().run(); + assertTrue(service.gatewayPreflightRoute("ep0000000000000").isEmpty(), "no gateway runs for it"); + runner.stop(endpointId); + } + @Test void deletedDockerEndpointStopsItsGatewayAndItsTokensGo() { GatewayRunner runner = new GatewayRunner(); diff --git a/src/test/java/io/floci/aws/services/emrserverless/SessionServersTest.java b/src/test/java/io/floci/aws/services/emrserverless/SessionServersTest.java index b37180b565..e797cc8b46 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/SessionServersTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/SessionServersTest.java @@ -83,6 +83,21 @@ class SessionServersTest { assertEquals(List.of("answering", "busy", "idle", "busy"), owner.events); } + @Test + void aCallWithoutATokenReachesARunningServerAsACallOfItsSession() { + answeringServer(); + + Route route = servers.routeWithoutToken(SESSION, owner).orElseThrow(); + route.ended().run(); + + assertEquals(List.of("answering", "busy", "idle"), owner.events); + assertTrue(servers.routeWithoutToken("session-2", owner).isEmpty(), "no server runs for it"); + owner.refusal = () -> "Session " + SESSION + " is TERMINATING."; + Route refused = servers.routeWithoutToken(SESSION, owner).orElseThrow(); + assertEquals(Route.UNAVAILABLE, refused.status()); + assertEquals("Session " + SESSION + " is TERMINATING.", refused.refusal()); + } + @Test void aServersEntryGoesWhenItStopsEvenWhereItsOwnerFailsToHearIt() { answeringServer();