Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 56 additions & 9 deletions keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand All @@ -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;
}
Expand Down
5 changes: 3 additions & 2 deletions keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
72 changes: 72 additions & 0 deletions keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java
Original file line number Diff line number Diff line change
Expand Up @@ -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}).
*
* <p>Every part of the dispatch is verified by construction so no app or library
* {@code XnioWorker.execute} call can pass:
* <ol>
* <li>{@code receiver != null} and {@code task != null};</li>
* <li>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};</li>
* <li>{@code task}'s exact runtime class is
* {@code io.undertow.server.session.InMemorySessionManager$SessionImpl$2$1};</li>
* <li>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}.</li>
* </ol>
*/
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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
}
}

Expand Down Expand Up @@ -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")) {
Expand Down Expand Up @@ -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"
Expand Down
Loading
Loading