From c18f3702eba40fdd4dea99f7c4c139913da51b3c Mon Sep 17 00:00:00 2001 From: slayerjain Date: Sun, 29 Nov 2026 16:11:06 +0530 Subject: [PATCH] fix(dedup): exempt verified Undertow session expiry from XNIO latch Undertow's InMemorySessionManager$SessionImpl schedules a timer cancelTask ($2#run) that executes outside any HTTP request window and dispatches a SessionImpl$2$1 task onto SessionImpl.this.worker via XnioWorker.execute(Runnable). Because RequestGate.handXnioWorker had no verification for this internal expiry dispatch, every Undertow session expiry latched asyncExecutors=false (untracked-async:xnio-worker-outside-window), even with no application session listeners. Verify Undertow's session-expiry dispatch by construction without any blanket allowlist: - ServerEntries.wrapXnioWorkerExecute passes both the receiver (this) and task to RequestGate.handXnioWorker(Object, Runnable), keeping the 1-arg overload for compatibility (receiver=null fails closed). - SinkAllowlist.isAllowedUndertowSessionExpiryXnioDispatch checks: 1. exact runtime task class InMemorySessionManager$SessionImpl$2$1; 2. exact immediate external caller frame (skipping only Keploy and org.xnio.XnioWorker, never reflection or app frames) InMemorySessionManager$SessionImpl$2#run; 3. same-ClassLoader owner-identity chain: task.this$1 is exact SessionImpl$2, cancelTask.this$0 is exact SessionImpl, session.cancelTask == cancelTask, and session.worker == receiver. - RequestGate wraps verified expiry tasks in a non-Hand XnioIdleBackgroundTask recognized by enterXnioWorkerDispatch so XnioWorker's internal pool/thread sinks stay clean while the task runs on the worker thread with no window permit and no tracked dispatch scope (application listeners and user async work still fail closed). - Drop the Undertow exclusions from SessionListenerHookTest now that listener-free Undertow expiry keeps asyncExecutors=true while application listeners and HttpSessionBindingListener still contaminate and latch. Signed-off-by: slayerjain --- .../java/io/keploy/dedup/RequestGate.java | 65 +++++- .../java/io/keploy/dedup/ServerEntries.java | 5 +- .../java/io/keploy/dedup/SinkAllowlist.java | 72 ++++++ .../dedup/ForkedAsyncAndHonestyTest.java | 42 ++++ .../io/keploy/dedup/JdkSinkBridgeTest.java | 219 ++++++++++++++++++ .../keploy/dedup/SessionListenerHookTest.java | 65 +++--- .../org/example/servers/AsyncHonestyApp.java | 11 + 7 files changed, 432 insertions(+), 47 deletions(-) diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java index c53d8866..d843416f 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -726,25 +726,66 @@ public static Runnable handAsyncContext(Runnable task) { return handed; } + /** + * Non-{@link Hand} wrapper for Undertow's verified timer-driven session-expiry + * dispatch onto {@code XnioWorker.execute(Runnable)}. {@link #enterXnioWorkerDispatch} + * recognizes it so {@code XnioWorker}'s internal task-pool queue/thread-start sinks + * stay clean while the task itself executes on the worker thread with NO request + * window permit and NO tracked-dispatch scope (so any app listener or user async + * hand-off triggered during invalidation still fails closed). + */ + private static final class XnioIdleBackgroundTask implements Runnable { + final Runnable task; + + XnioIdleBackgroundTask(Runnable task) { + this.task = task; + } + + @Override + public void run() { + task.run(); + } + } + /** * Wraps a {@link Runnable} dispatched onto Undertow's {@code org.xnio.XnioWorker} * so both Undertow's own I/O-to-worker request dispatch (from hooked * {@code Connectors.executeRootHandler}) and in-request {@code XnioWorker.execute} - * calls hold the active request window's permit. Any call outside an active - * request window, tracked job, or unarmed server request fails closed by - * latching {@code asyncExecutors=false}. + * calls hold the active request window's permit. Outside-window calls fail closed + * by latching {@code asyncExecutors=false} except for Undertow's verified + * {@code InMemorySessionManager$SessionImpl} timer-driven expiry dispatch, which + * runs unwrapped of any window permit via {@code XnioIdleBackgroundTask}. * * @param task runnable passed to {@code XnioWorker.execute(Runnable)} * @return wrapped runnable holding the window permit, or {@code task} unchanged */ public static Runnable handXnioWorker(Runnable task) { + return handXnioWorker(null, task); + } + + /** + * Receiver-aware overload invoked by {@code ServerEntries#wrapXnioWorkerExecute} + * so Undertow's timer-driven session-expiry dispatch can be verified against the + * exact {@code XnioWorker} instance owned by {@code InMemorySessionManager$SessionImpl}. + * + * @param receiver {@code org.xnio.XnioWorker} instance on which {@code execute} was called + * @param task runnable passed to {@code XnioWorker.execute(Runnable)} + * @return wrapped runnable holding the window permit, an {@code XnioIdleBackgroundTask} + * for verified Undertow session expiry, or {@code task} unchanged + */ + public static Runnable handXnioWorker(Object receiver, Runnable task) { if (task == null) { return null; } if (!armed) { - noteUnarmedHandOffIfInFlight(); if (!isInsideUnarmedRequest()) { + if (SinkAllowlist.isAllowedUndertowSessionExpiryXnioDispatch(receiver, task)) { + return new XnioIdleBackgroundTask(task); + } + noteUnarmedHandOffIfInFlight(); noteBackgroundWorkerOutsideWindow("untracked-async:xnio-worker-outside-window", false); + } else { + noteUnarmedHandOffIfInFlight(); } return task; } @@ -754,6 +795,9 @@ public static Runnable handXnioWorker(Runnable task) { Window window = INSIDE.get(); JobGate.Attribution job = currentOrExpiredJob(window); if (window == null && job == null) { + if (SinkAllowlist.isAllowedUndertowSessionExpiryXnioDispatch(receiver, task)) { + return new XnioIdleBackgroundTask(task); + } noteBackgroundWorkerOutsideWindow("untracked-async:xnio-worker-outside-window", true); return task; } @@ -768,15 +812,18 @@ public static Runnable handXnioWorker(Runnable task) { /** * Enters a tracked dispatch scope around {@code XnioWorker.execute} only when - * the dispatch carries a proven {@link Hand} permit (or belongs to an unarmed - * server request inside {@code Connectors.executeRootHandler}). Outside-window - * calls return {@code false} so downstream JDK sinks still fail closed. + * the dispatch carries a proven {@code Hand} permit, a verified Undertow + * session-expiry {@code XnioIdleBackgroundTask}, or belongs to an unarmed + * server request inside {@code Connectors.executeRootHandler}. Outside-window + * app calls return {@code false} so downstream JDK sinks still fail closed. * - * @param handed task returned by {@link #handXnioWorker(Runnable)} + * @param handed task returned by {@link #handXnioWorker(Object, Runnable)} * @return {@code true} if a tracked dispatch scope was entered */ public static boolean enterXnioWorkerDispatch(Object handed) { - if (handed instanceof Hand || (!armed && isInsideUnarmedRequest())) { + if (handed instanceof Hand + || handed instanceof XnioIdleBackgroundTask + || (!armed && isInsideUnarmedRequest())) { enterTrackedDispatch(); return true; } diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java index 11b4674f..6c6fc10c 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -1840,10 +1840,11 @@ public void visitEnd() { Label thrown = new Label(); mv.visitTryCatchBlock(start, end, thrown, null); - // Runnable handed = RequestGate.handXnioWorker(r); + // Runnable handed = RequestGate.handXnioWorker(this, r); + mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "handXnioWorker", - "(Ljava/lang/Runnable;)Ljava/lang/Runnable;", false); + "(Ljava/lang/Object;Ljava/lang/Runnable;)Ljava/lang/Runnable;", false); mv.visitVarInsn(Opcodes.ASTORE, 2); // boolean tracked = RequestGate.enterXnioWorkerDispatch(handed); mv.visitVarInsn(Opcodes.ALOAD, 2); diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java b/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java index 896f7bef..da44510c 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java @@ -819,6 +819,78 @@ public String apply(Stream stream) { return null; } + private static final String UNDERTOW_SESSION_IMPL_CLASS = + "io.undertow.server.session.InMemorySessionManager$SessionImpl"; + private static final String UNDERTOW_SESSION_CANCEL_TASK_CLASS = + "io.undertow.server.session.InMemorySessionManager$SessionImpl$2"; + private static final String UNDERTOW_SESSION_CANCEL_TASK_CALLER = + UNDERTOW_SESSION_CANCEL_TASK_CLASS + "#run"; + private static final String UNDERTOW_SESSION_EXPIRY_WORKER_TASK_CLASS = + "io.undertow.server.session.InMemorySessionManager$SessionImpl$2$1"; + + /** + * Returns {@code true} iff an outside-window {@code org.xnio.XnioWorker.execute(Runnable)} + * call is Undertow's own {@code InMemorySessionManager$SessionImpl} timer-driven session + * expiry dispatch (Undertow 2.2.37 / 2.3.18 {@code SessionImpl$2#run} dispatching + * {@code new SessionImpl$2$1(this)} onto {@code SessionImpl.this.worker}). + * + *

Every part of the dispatch is verified by construction so no app or library + * {@code XnioWorker.execute} call can pass: + *

    + *
  1. {@code receiver != null} and {@code task != null};
  2. + *
  3. the immediate external caller frame (skipping only Keploy frames and + * {@code org.xnio.XnioWorker} itself, never reflection or app frames) is + * exact {@code io.undertow.server.session.InMemorySessionManager$SessionImpl$2#run};
  4. + *
  5. {@code task}'s exact runtime class is + * {@code io.undertow.server.session.InMemorySessionManager$SessionImpl$2$1};
  6. + *
  7. owner-identity chain: {@code task.this$1} is an exact + * {@code InMemorySessionManager$SessionImpl$2} in the same {@link ClassLoader}, + * its {@code this$0} is an exact {@code InMemorySessionManager$SessionImpl} in + * the same {@link ClassLoader}, {@code session.cancelTask == cancelTask}, and + * {@code session.worker == receiver}.
  8. + *
+ */ + static boolean isAllowedUndertowSessionExpiryXnioDispatch(Object receiver, Runnable task) { + if (receiver == null || task == null + || !UNDERTOW_SESSION_EXPIRY_WORKER_TASK_CLASS.equals(task.getClass().getName())) { + return false; + } + String callerFrame = firstExternalCallerFrameSkipping("org.xnio.XnioWorker"); + boolean allowed = isAllowedUndertowSessionExpiryXnioDispatch(receiver, task, callerFrame); + audit("xnio-worker:execute", allowed, "caller", receiver, task, callerFrame); + return allowed; + } + + static boolean isAllowedUndertowSessionExpiryXnioDispatch(Object receiver, Runnable task, String callerFrame) { + if (receiver == null || task == null || !UNDERTOW_SESSION_CANCEL_TASK_CALLER.equals(callerFrame)) { + return false; + } + Class taskClass = task.getClass(); + if (!UNDERTOW_SESSION_EXPIRY_WORKER_TASK_CLASS.equals(taskClass.getName())) { + return false; + } + ClassLoader taskLoader = taskClass.getClassLoader(); + try { + Object cancelTask = readField(task, "this$1"); + if (cancelTask == null + || !UNDERTOW_SESSION_CANCEL_TASK_CLASS.equals(cancelTask.getClass().getName()) + || cancelTask.getClass().getClassLoader() != taskLoader) { + return false; + } + Object sessionImpl = readField(cancelTask, "this$0"); + if (sessionImpl == null + || !UNDERTOW_SESSION_IMPL_CLASS.equals(sessionImpl.getClass().getName()) + || sessionImpl.getClass().getClassLoader() != taskLoader) { + return false; + } + Object sessionCancelTask = readField(sessionImpl, "cancelTask"); + Object sessionWorker = readField(sessionImpl, "worker"); + return sessionCancelTask == cancelTask && sessionWorker == receiver; + } catch (Throwable ignored) { + return false; + } + } + static boolean isAllowedServerExecutorCaller(String sinkName, String callerFrame, Object receiver) { return isAllowedServerExecutorCaller(sinkName, callerFrame, receiver, null); } diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index 954f71da..0c0d5029 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -656,6 +656,22 @@ public void forkedServletAsyncContextStartAfterCompleteNeverLeaksAcrossServers() covDef.contains("windowCut")); assertTrue(label + " /async-dispatch-deferred must keep asyncExecutors=true: " + app.lastHello, parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + + if ("undertow".equals(server)) { + // 2c. Undertow 2.2 background session expiry (InMemorySessionManager$SessionImpl$2#run + // dispatching $2$1 onto XnioWorker.execute from the XNIO timer outside any window) + // must keep asyncExecutors=true with zero contamination. + String covSess = app.runHttpTest("ac/ut22-session-create", "/session-expire", "session-armed"); + assertFalse(label + " /session-expire must not contaminate: " + covSess, + covSess.contains("contaminated")); + Thread.sleep(2200L); + String covAfter = app.runHttpTest("ac/ut22-session-after-expiry", "/clean"); + assertFalse(label + " window after Undertow 2.2 session expiry must be clean: " + covAfter, + covAfter.contains("contaminated")); + assertTrue(label + " Undertow 2.2 session expiry must keep asyncExecutors=true: " + + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } } } @@ -1129,6 +1145,27 @@ private void verifyJakartaServerFork(String serverName, File depsDir, String pkg assertTrue("in-window XnioWorker.execute must capture JakartaAsyncTail IN-WINDOW: " + cov, cov.contains("\"" + tailPath + "\"")); } + // (c1b) Undertow 2.3 background session expiry (InMemorySessionManager$SessionImpl$2#run + // dispatching $2$1 onto XnioWorker.execute from the XNIO timer outside any window) + // must keep asyncExecutors=true and clean windows in both modes, while an app's + // own outside-window XnioWorker.execute still latches asyncExecutors=false. + for (boolean pm : new boolean[] {true, false}) { + try (ForkedApp app = startJakartaIsolatedFork(serverName + "-session-expiry", outDir, libDir, depsDir, + fqcn, "2000", pm, null)) { + app.runHttpTest("jk/ut-sess-warm", "/clean"); + assertTrue("Undertow 2.3 baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String covCreate = app.runHttpTest("jk/ut-sess-create", "/session-expire"); + assertFalse("Undertow 2.3 /session-expire must not contaminate (prefix=" + pm + "): " + covCreate, + covCreate.contains("contaminated")); + Thread.sleep(2200L); + String covAfter = app.runHttpTest("jk/ut-sess-after-expiry", "/clean"); + assertFalse("Undertow 2.3 window after session expiry must be clean (prefix=" + pm + "): " + + covAfter, covAfter.contains("contaminated")); + assertTrue("Undertow 2.3 session expiry must keep asyncExecutors=true (prefix=" + pm + "): " + + app.lastHello, parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + } // (c2) Outside-window XnioWorker.execute at startup must latch asyncExecutors=false. try (ForkedApp app = startJakartaIsolatedFork(serverName + "-xnio-boot", outDir, libDir, depsDir, fqcn, "2000", false, "boot-xnio-outside")) { @@ -1623,6 +1660,11 @@ private static String buildJakartaUndertow23Source() { + " JakartaAsyncTail.ran();\n" + " });\n" + " }\n" + + " if (\"/session-expire\".equals(path)) {\n" + + " jakarta.servlet.http.HttpSession s = req.getSession(true);\n" + + " s.setMaxInactiveInterval(1);\n" + + " s.setAttribute(\"k\", \"v\");\n" + + " }\n" + " if (\"/xnio-io-after\".equals(path)) {\n" + " WORKER.getIoThread().executeAfter(() -> JakartaAsyncTail.ran(), ms, TimeUnit.MILLISECONDS);\n" + " }\n" diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java index 7ed3380f..5f03ed25 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java @@ -951,6 +951,225 @@ protected Class findClass(String name) throws ClassNotFoundException { } } + @Test + public void undertowSessionExpiryXnioDispatchAllowsOnlyExactOwnedCancelTaskAndFailsClosedOtherwise() + throws Exception { + final ServerEntries transformer = new ServerEntries(true); + final byte[] rawWorker = generateSyntheticXnioWorker(); + final java.util.Set childDefined = new java.util.HashSet<>(java.util.Arrays.asList( + "org.xnio.XnioWorker", + "org.example.ForgedExpiryTask", + "io.undertow.server.session.InMemorySessionManager$SessionImpl", + "io.undertow.server.session.InMemorySessionManager$SessionImpl$1", + "io.undertow.server.session.InMemorySessionManager$SessionImpl$2", + "io.undertow.server.session.InMemorySessionManager$SessionImpl$2$1" + )); + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + ClassLoader cl = new ClassLoader(JdkSinkBridgeTest.class.getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (childDefined.contains(name)) { + Class found = findLoadedClass(name); + if (found == null) { + found = findClass(name); + } + if (resolve) { + resolveClass(found); + } + return found; + } + return super.loadClass(name, resolve); + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + if ("org.xnio.XnioWorker".equals(name)) { + byte[] out = transformer.transform(this, "org/xnio/XnioWorker", null, + JdkSinkBridgeTest.class.getProtectionDomain(), rawWorker); + byte[] effective = out != null ? out : rawWorker; + return defineClass(name, effective, 0, effective.length); + } + if ("org.example.ForgedExpiryTask".equals(name)) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "org/example/ForgedExpiryTask", null, + "java/lang/Object", new String[]{"java/lang/Runnable"}); + cw.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, "this$1", "Ljava/lang/Object;", null, null) + .visitEnd(); + MethodVisitor ctor = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "(Ljava/lang/Object;)V", + null, null); + ctor.visitCode(); + ctor.visitVarInsn(Opcodes.ALOAD, 0); + ctor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); + ctor.visitVarInsn(Opcodes.ALOAD, 0); + ctor.visitVarInsn(Opcodes.ALOAD, 1); + ctor.visitFieldInsn(Opcodes.PUTFIELD, "org/example/ForgedExpiryTask", "this$1", + "Ljava/lang/Object;"); + ctor.visitInsn(Opcodes.RETURN); + ctor.visitMaxs(0, 0); + ctor.visitEnd(); + MethodVisitor run = cw.visitMethod(Opcodes.ACC_PUBLIC, "run", "()V", null, null); + run.visitCode(); + run.visitInsn(Opcodes.RETURN); + run.visitMaxs(0, 0); + run.visitEnd(); + cw.visitEnd(); + byte[] bytes = cw.toByteArray(); + return defineClass(name, bytes, 0, bytes.length); + } + if (childDefined.contains(name)) { + String res = name.replace('.', '/') + ".class"; + try (java.io.InputStream in = JdkSinkBridgeTest.class.getClassLoader().getResourceAsStream(res)) { + if (in == null) { + throw new ClassNotFoundException(name); + } + java.io.ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream(); + byte[] chunk = new byte[4096]; + int n; + while ((n = in.read(chunk)) >= 0) { + buf.write(chunk, 0, n); + } + byte[] bytes = buf.toByteArray(); + return defineClass(name, bytes, 0, bytes.length); + } catch (java.io.IOException e) { + throw new ClassNotFoundException(name, e); + } + } + throw new ClassNotFoundException(name); + } + }; + + Class workerCls = cl.loadClass("org.xnio.XnioWorker"); + Class sessionImplCls = cl.loadClass("io.undertow.server.session.InMemorySessionManager$SessionImpl"); + Class cancelTaskCls = cl.loadClass("io.undertow.server.session.InMemorySessionManager$SessionImpl$2"); + Class workerTaskCls = cl.loadClass("io.undertow.server.session.InMemorySessionManager$SessionImpl$2$1"); + + final AtomicBoolean trackedDuringExecute = new AtomicBoolean(false); + final AtomicReference capturedTask = new AtomicReference<>(); + final AtomicBoolean throwOnExecute = new AtomicBoolean(false); + Object ownWorker = workerCls.getDeclaredConstructor(AtomicBoolean.class, AtomicReference.class, + AtomicBoolean.class).newInstance(trackedDuringExecute, capturedTask, throwOnExecute); + Object foreignWorker = workerCls.getDeclaredConstructor(AtomicBoolean.class, AtomicReference.class, + AtomicBoolean.class).newInstance(new AtomicBoolean(), new AtomicReference(), + new AtomicBoolean()); + Method execMethod = workerCls.getMethod("execute", Runnable.class); + + java.lang.reflect.Constructor sessionCtor = sessionImplCls.getDeclaredConstructor( + io.undertow.server.session.InMemorySessionManager.class, + io.undertow.server.session.SessionConfig.class, + org.xnio.XnioIoThread.class, + workerCls, + int.class); + sessionCtor.setAccessible(true); + Object session = sessionCtor.newInstance(null, null, null, ownWorker, Integer.valueOf(-1)); + java.lang.reflect.Field cancelTaskField = sessionImplCls.getDeclaredField("cancelTask"); + cancelTaskField.setAccessible(true); + Runnable cancelTask = (Runnable) cancelTaskField.get(session); + assertEquals("io.undertow.server.session.InMemorySessionManager$SessionImpl$2", + cancelTask.getClass().getName()); + + java.lang.reflect.Constructor workerTaskCtor = workerTaskCls.getDeclaredConstructor(cancelTaskCls); + workerTaskCtor.setAccessible(true); + Runnable realWorkerTask = (Runnable) workerTaskCtor.newInstance(cancelTask); + + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + try { + // 1. Armed outside any request window: real SessionImpl$2#run() dispatching + // SessionImpl$2$1 onto its own XnioWorker enters tracked dispatch (so internal + // XNIO queue/thread sinks stay clean) WITHOUT latching asyncExecutors=false and + // WITHOUT wrapping in a Hand permit. + RequestGate.open("xnio-expiry-1", null); + RequestGate.await(1000); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + trackedDuringExecute.set(false); + capturedTask.set(null); + + cancelTask.run(); + + assertTrue("verified Undertow session expiry must enter tracked dispatch inside XnioWorker.execute", + trackedDuringExecute.get()); + assertFalse("tracked dispatch must exit cleanly after XnioWorker.execute returns", + RequestGate.isTrackedDispatchActive()); + assertNotNull("expiry task must reach keploy$async$execute", capturedTask.get()); + assertFalse("expiry background wrapper must NOT carry a RequestGate.Hand permit", + RequestGate.isTrackedTask(capturedTask.get())); + assertFalse("verified Undertow session expiry must NOT latch asyncExecutors=false (armed)", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // 2. Unarmed outside any request: real SessionImpl$2#run() also stays clean. + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + trackedDuringExecute.set(false); + capturedTask.set(null); + + cancelTask.run(); + + assertTrue("verified Undertow session expiry must enter tracked dispatch (unarmed)", + trackedDuringExecute.get()); + assertFalse("verified Undertow session expiry must NOT latch asyncExecutors=false (unarmed)", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // 3. Adversarial: passing the REAL SessionImpl$2$1 instance directly from app/test + // code (wrong caller frame) must FAIL CLOSED and latch asyncExecutors=false. + RequestGate.open("xnio-expiry-2", null); + RequestGate.await(1000); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + trackedDuringExecute.set(false); + capturedTask.set(null); + + execMethod.invoke(ownWorker, realWorkerTask); + + assertFalse("direct/reflective call with SessionImpl$2$1 must NOT enter tracked dispatch", + trackedDuringExecute.get()); + assertTrue("direct/reflective call with SessionImpl$2$1 must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // 4. Adversarial: passing an arbitrary app Runnable from outside a window must FAIL CLOSED. + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + trackedDuringExecute.set(false); + execMethod.invoke(ownWorker, (Runnable) () -> { }); + assertFalse("app Runnable outside window must NOT enter tracked dispatch", + trackedDuringExecute.get()); + assertTrue("app Runnable outside window must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // 5. Predicate owner-identity checks: exact caller + exact owned worker + attached cancelTask. + final String validCaller = "io.undertow.server.session.InMemorySessionManager$SessionImpl$2#run"; + assertTrue("exact caller + exact SessionImpl$2$1 + own worker must pass", + SinkAllowlist.isAllowedUndertowSessionExpiryXnioDispatch(ownWorker, realWorkerTask, validCaller)); + assertFalse("null receiver must fail closed", + SinkAllowlist.isAllowedUndertowSessionExpiryXnioDispatch(null, realWorkerTask, validCaller)); + assertFalse("foreign XnioWorker receiver must fail closed", + SinkAllowlist.isAllowedUndertowSessionExpiryXnioDispatch(foreignWorker, realWorkerTask, validCaller)); + assertFalse("non-SessionImpl$2$1 app Runnable must fail closed even with valid caller", + SinkAllowlist.isAllowedUndertowSessionExpiryXnioDispatch(ownWorker, () -> { }, validCaller)); + assertFalse("wrong caller frame must fail closed", + SinkAllowlist.isAllowedUndertowSessionExpiryXnioDispatch(ownWorker, realWorkerTask, + "com.example.App#run")); + + // Detached/forged cancelTask (session.cancelTask != task.this$1) must fail closed. + java.lang.reflect.Constructor cancelCtor = cancelTaskCls.getDeclaredConstructor(sessionImplCls); + cancelCtor.setAccessible(true); + Object detachedCancelTask = cancelCtor.newInstance(session); + Runnable detachedWorkerTask = (Runnable) workerTaskCtor.newInstance(detachedCancelTask); + assertFalse("detached SessionImpl$2 not registered as session.cancelTask must fail closed", + SinkAllowlist.isAllowedUndertowSessionExpiryXnioDispatch(ownWorker, detachedWorkerTask, + validCaller)); + + // Forged Runnable in the same ClassLoader carrying a real this$1 == session.cancelTask + // reference must STILL fail closed because its runtime class is not SessionImpl$2$1. + Class forgedTaskCls = cl.loadClass("org.example.ForgedExpiryTask"); + Runnable forgedTask = (Runnable) forgedTaskCls.getConstructor(Object.class).newInstance(cancelTask); + assertFalse("forged Runnable with matching this$1 in same ClassLoader must fail closed", + SinkAllowlist.isAllowedUndertowSessionExpiryXnioDispatch(ownWorker, forgedTask, validCaller)); + } finally { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + RequestGate.disarm(); + } + } + @Test public void jettyAndUndertowLatchOnCallHooksFailClosedWhenInvoked() throws Exception { final ServerEntries transformer = new ServerEntries(true); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java index 24a696b0..cc7301ea 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java @@ -755,11 +755,9 @@ public void forkedTomcatAndJettyAndUndertowBackgroundSessionExpiryContaminatesAn String warm = app.runHttpTest("se/" + server + "-warm", "/clean"); assertFalse(label + " warm must not carry session-listener: " + warm, warm.contains("session-listener:")); - if (!"undertow".equals(server)) { - assertFalse(label + " warm must not be contaminated: " + warm, warm.contains("contaminated")); - assertTrue(label + " baseline must keep asyncExecutors=true: " + app.lastHello, - parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); - } + assertFalse(label + " warm must not be contaminated: " + warm, warm.contains("contaminated")); + assertTrue(label + " baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); String cov1 = app.runHttpTest("se/" + server + "-create", "/create-session?ttl=1&bind=true"); assertFalse(label + " /create-session must not contaminate with session-listener: " + cov1, cov1.contains("session-listener:")); @@ -778,18 +776,16 @@ public void forkedTomcatAndJettyAndUndertowBackgroundSessionExpiryContaminatesAn // 1b. Background session expiry with ONLY HttpSessionBindingListener (no HttpSessionListener) -> // W2 contaminated ("session-listener:...#valueUnbound") + latched! - if (!"undertow".equals(server)) { - try (ForkedApp app = startSessionFork(server, "none", prefixMode)) { - app.runHttpTest("se/" + server + "-bind-create", "/create-session?ttl=1&bind=true"); - String cov2 = app.runHttpTest("se/" + server + "-bind-expire", - "/sleep?ms=8000&waitExpiry=true"); - assertTrue(label + " W2 overlapping HttpSessionBindingListener.valueUnbound MUST carry" - + " session-listener: " + cov2 + "\nlog:\n" + readFile(app.log), - cov2.contains("session-listener:") && cov2.contains("#valueUnbound")); - assertFalse(label + " background valueUnbound MUST latch asyncExecutors=false: " - + app.lastHello, - parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); - } + try (ForkedApp app = startSessionFork(server, "none", prefixMode)) { + app.runHttpTest("se/" + server + "-bind-create", "/create-session?ttl=1&bind=true"); + String cov2 = app.runHttpTest("se/" + server + "-bind-expire", + "/sleep?ms=8000&waitExpiry=true"); + assertTrue(label + " W2 overlapping HttpSessionBindingListener.valueUnbound MUST carry" + + " session-listener: " + cov2 + "\nlog:\n" + readFile(app.log), + cov2.contains("session-listener:") && cov2.contains("#valueUnbound")); + assertFalse(label + " background valueUnbound MUST latch asyncExecutors=false: " + + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); } // 2. Synchronous in-request session.invalidate() WITH listeners -> ZERO session-listener contamination! @@ -797,27 +793,24 @@ public void forkedTomcatAndJettyAndUndertowBackgroundSessionExpiryContaminatesAn String cov1 = app.runHttpTest("se/" + server + "-sync-inv", "/invalidate-sync"); assertFalse(label + " synchronous in-request invalidate must not carry session-listener: " + cov1, cov1.contains("session-listener:")); - if (!"undertow".equals(server)) { - assertFalse(label + " synchronous in-request invalidate must not be contaminated: " + cov1, - cov1.contains("contaminated")); - assertTrue(label + " synchronous in-request invalidate must keep asyncExecutors=true: " - + app.lastHello + "\nlog:\n" + readFile(app.log), - parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); - } + assertFalse(label + " synchronous in-request invalidate must not be contaminated: " + cov1, + cov1.contains("contaminated")); + assertTrue(label + " synchronous in-request invalidate must keep asyncExecutors=true: " + + app.lastHello + "\nlog:\n" + readFile(app.log), + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); } - // 3. Background session expiry with NO app listeners on Tomcat & Jetty -> ZERO false latch! - if (!"undertow".equals(server)) { - try (ForkedApp app = startSessionFork(server, "none", prefixMode)) { - app.runHttpTest("se/" + server + "-nolistener-create", "/create-session?ttl=1&bind=false"); - String cov2 = app.runHttpTest("se/" + server + "-nolistener-wait", "/sleep?ms=2400"); - assertFalse(label + " listener-free background expiry must not contaminate W2: " + cov2 - + "\nlog:\n" + readFile(app.log), - cov2.contains("contaminated")); - assertTrue(label + " listener-free background expiry must keep asyncExecutors=true: " - + app.lastHello + "\nlog:\n" + readFile(app.log), - parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); - } + // 3. Background session expiry with NO app listeners across Tomcat, Jetty, and Undertow + // -> ZERO false latch! + try (ForkedApp app = startSessionFork(server, "none", prefixMode)) { + app.runHttpTest("se/" + server + "-nolistener-create", "/create-session?ttl=1&bind=false"); + String cov2 = app.runHttpTest("se/" + server + "-nolistener-wait", "/sleep?ms=2400"); + assertFalse(label + " listener-free background expiry must not contaminate W2: " + cov2 + + "\nlog:\n" + readFile(app.log), + cov2.contains("contaminated")); + assertTrue(label + " listener-free background expiry must keep asyncExecutors=true: " + + app.lastHello + "\nlog:\n" + readFile(app.log), + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); } } } diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index 1ef7f9d0..ca2de1ee 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -219,6 +219,17 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO resp.flushBuffer(); return; } + if ("/session-expire".equals(path)) { + javax.servlet.http.HttpSession session = req.getSession(true); + session.setMaxInactiveInterval(1); + session.setAttribute("k", "v"); + byte[] ok = "session-armed".getBytes(StandardCharsets.UTF_8); + resp.setContentType("text/plain"); + resp.setContentLength(ok.length); + resp.getOutputStream().write(ok); + resp.flushBuffer(); + return; + } if ("/async-after-complete".equals(path)) { final javax.servlet.AsyncContext ctx = req.startAsync(); final long delay = ms;