From 548fb9a3bffff48c755120deb254d36445bb7d96 Mon Sep 17 00:00:00 2001 From: slayerjain Date: Sun, 29 Nov 2026 11:39:01 +0530 Subject: [PATCH 1/2] fix(dedup): contaminate and latch asyncExecutors on background HTTP session-expiry listeners Background HTTP session-expiry timers (Tomcat StandardManager/ManagerBase, Jetty HouseKeeper/SessionInactivityTimer, Undertow InMemorySessionManager) can invoke application session listeners outside any HTTP request. Without a hook, cleanup code executed during background session expiry can land silently inside an unrelated later test's coverage window. Hook container session-listener dispatch invokeinterface call sites across Tomcat 8.5/9/10.1/11, Jetty 9.4/11/12.0/12.1 (including ee8/ee9 nested SessionHandler, ee10/ee11 SessionHandler, and Jetty 12 core AbstractSessionManager/ManagedSession), and Undertow 2.2/2.3 for HttpSessionListener, HttpSessionAttributeListener, HttpSessionBindingListener, HttpSessionActivationListener, HttpSessionIdListener, and container-native session listener interfaces: - Keep Jetty 12 ee8/ee9 outer nested SessionHandler optional while requiring its nested CoreSessionManager so Jetty 12.0.0/12.0.16/12.1.15 never log false hook-failure warnings or falsely latch asyncExecutors=false. - Fast-path as a no-op inside an active HTTP request or tracked/expired job so synchronous HttpSession.invalidate() and changeSessionId() stay clean. - Outside any tracked request or job, enter JobGate("session-listener") to contaminate overlapping windows (session-listener:#) and latch asyncExecutors=false. - Skip exact container-internal bridges (SessionListenerBridge, Jetty 12 SessionHandler, Tomcat SingleSignOnListener) only on container-native interfaces, and skip exact org.apache.tomcat.websocket.server.WsSessionListener (auto-registered by Tomcat WsSci in Spring Boot and standalone Tomcat) only on Servlet interfaces (never subclasses) so listener-free expiries stay clean. - Document behavior and limits (e.g. Spring Session adapters) in README.md. Signed-off-by: slayerjain --- README.md | 2 +- .../main/java/io/keploy/dedup/JobGate.java | 12 +- .../java/io/keploy/dedup/RequestGate.java | 88 ++ .../java/io/keploy/dedup/ServerEntries.java | 363 +++++- .../keploy/dedup/SessionListenerHookTest.java | 1080 +++++++++++++++++ .../org/example/servers/SessionExpiryApp.java | 244 ++++ .../example/servers/SessionExpiryTail.java | 18 + 7 files changed, 1801 insertions(+), 6 deletions(-) create mode 100644 keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java create mode 100644 keploy-sdk/src/test/java/org/example/servers/SessionExpiryApp.java create mode 100644 keploy-sdk/src/test/java/org/example/servers/SessionExpiryTail.java diff --git a/README.md b/README.md index 3749d08c..4384623d 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Executor wrapping is **fail-closed**: only positively verified safe executors (e When Keploy is absent (no collector connected and no control command received), runtime request counting, executor wrapping, and job/listener tracking remain unarmed (zero-allocation static sentinel token, zero task wrapping); every armed window opened while any pre-arming request or job remains in flight (or within the tail window of an unarmed hand-off, plus the first armed window after unarmed traffic ran) is marked contaminated (`"armed-mid-flight"`). If a test records coverage probes while no Tomcat, Jetty, or Undertow request entry ran (for example on Netty/WebFlux, gRPC, Vert.x, Micronaut, JDK `HttpServer`, Armeria, Helidon, Play, or a server loaded before the agent), the record emits `"unverified":["no-server-entry"]` (omitted when empty, and kept separate from `"contaminated"` so older Enterprise collectors keep measuring uncounted servers while v3 collectors fail closed on any non-empty `"unverified"`). -A scheduled job or message listener that runs while a testcase runs puts its lines in that testcase's coverage: JaCoCo's probes do not say which thread hit them. The agent sees each run of a Quartz job (1.x and 2.x, and Spring's Quartz support), a Spring `@Scheduled` method, and Spring Kafka (`KafkaMessageListenerContainer$ListenerConsumer`), RabbitMQ (`AbstractMessageListenerContainer.doInvokeListener`), and JMS (`AbstractMessageListenerContainer.doInvokeListener`) message listeners. A testcase whose window a run overlapped, from its `START` to the read of its probes at `END` (a job already running at the `START` counts), names the jobs and listeners in `"contaminated":["quartz:." | "scheduled:." | "kafka:@" | "listener:@", ...]` after `windowCut`: at most 8 names, then `"+N"` for N more; left out when none ran. Listener attribution (topic/queue/destination and listener bean class) is inspected once per container instance and cached lock-free. The probes stay in the record; a Keploy that reads the key does not judge that testcase (an older one ignores the key). A job that ends before a `START` is not named: the `START` clears what it ran. The work a job's or listener's run hands to verified executors counts as a run of the same job, with the same name, from when the task starts until it returns or throws, whether or not `END` waits: so a testcase whose window the task runs in is named, even when the job itself returned before that testcase's `START`. Chained re-submissions inherit a 30 s budget from hop 1 so a self-resubmitting loop stops propagating attribution past its budget, while any expired handed-off task that is still executing continues marking overlapping windows `"job-tail:"` until it actually exits. `END` does not wait for it. Limits: work on custom unhooked messaging clients (plain `KafkaConsumer.poll`, `reactor-kafka`, Kafka Streams), a `java.util.Timer`, a Spring `SchedulingConfigurer` plain `Runnable`, or a reactive/Kotlin `suspend` `@Scheduled` method is not seen. No job or listener run is seen when the agent was never started as a `-javaagent` in the JVM, nor when the target class loaded before the agent started. +A scheduled job or message listener that runs while a testcase runs puts its lines in that testcase's coverage: JaCoCo's probes do not say which thread hit them. The agent sees each run of a Quartz job (1.x and 2.x, and Spring's Quartz support), a Spring `@Scheduled` method, and Spring Kafka (`KafkaMessageListenerContainer$ListenerConsumer`), RabbitMQ (`AbstractMessageListenerContainer.doInvokeListener`), and JMS (`AbstractMessageListenerContainer.doInvokeListener`) message listeners. Background HTTP session listeners invoked outside any tracked request or job (such as container session-expiry timers firing `HttpSessionListener`, `HttpSessionAttributeListener`, `HttpSessionBindingListener`, `HttpSessionActivationListener`, `HttpSessionIdListener`, or container-native session listeners across Tomcat 8.5–11, Jetty 9.4–12.1 including `ee8`/`ee9`/`ee10`/`ee11`, and Undertow 2.2–2.3) are hooked alike: overlapping windows are marked `"session-listener:#"` and `asyncExecutors=false` is latched so dedup fails closed, while synchronous in-request `HttpSession.invalidate()` and listener-free session expiries (including Tomcat's default `WsSessionListener`) remain clean. A testcase whose window a run overlapped, from its `START` to the read of its probes at `END` (a job already running at the `START` counts), names the jobs and listeners in `"contaminated":["quartz:." | "scheduled:." | "kafka:@" | "listener:@" | "session-listener:#", ...]` after `windowCut`: at most 8 names, then `"+N"` for N more; left out when none ran. Listener attribution (topic/queue/destination and listener bean class) is inspected once per container instance and cached lock-free. The probes stay in the record; a Keploy that reads the key does not judge that testcase (an older one ignores the key). A job that ends before a `START` is not named: the `START` clears what it ran. The work a job's or listener's run hands to verified executors counts as a run of the same job, with the same name, from when the task starts until it returns or throws, whether or not `END` waits: so a testcase whose window the task runs in is named, even when the job itself returned before that testcase's `START`. Chained re-submissions inherit a 30 s budget from hop 1 so a self-resubmitting loop stops propagating attribution past its budget, while any expired handed-off task that is still executing continues marking overlapping windows `"job-tail:"` until it actually exits. `END` does not wait for it. Limits: work on custom unhooked messaging clients (plain `KafkaConsumer.poll`, `reactor-kafka`, Kafka Streams), a `java.util.Timer`, a Spring `SchedulingConfigurer` plain `Runnable`, a reactive/Kotlin `suspend` `@Scheduled` method, or external session-store adapters that dispatch Servlet session listeners outside the servlet container (such as Spring Session's `SessionEventHttpSessionListenerAdapter` / `HttpSessionAdapter`) is not seen. No job or listener run is seen when the agent was never started as a `-javaagent` in the JVM, nor when the target class loaded before the agent started. Since 2.2.0 a testcase's record also names, in `"classMismatch":[className, ...]` after its probes, each class whose probes come from bytes other than the ones the agent indexed: a class loader that weaves the bytes it defines (load-time weaving) or an agent listed before JaCoCo's that does not ask to retransform changed the class before JaCoCo saw it, or the JVM loaded a multi-release jar's versioned copy. JaCoCo's id for such a class is not the CRC64 of the indexed bytes, so its probe indices do not belong to the indexed class, and Keploy must not read them against it. The key is left out when there is no such class. Of two copies of one class (loaded twice, from different bytes) that a testcase ran, the record reports the copy the agent indexed, else the one the coverage manifest already names, else the lowest class id compared as an unsigned number; a BACKGROUND record chooses alike, and names such classes in a `classMismatch` of its own. Every class id the agent writes (the coverage manifest's `id`) is 16 lowercase hex digits since 2.2.0; older agents wrote it unpadded, so read it as a hex number. diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java index d90015f4..2887ea75 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/JobGate.java @@ -101,7 +101,7 @@ static boolean hasExpiredRunning() { * No-op when Keploy is unarmed. * * @param job the object whose {@code run()} runs the job - * @param kind "quartz", "scheduled", "kafka", or "listener" + * @param kind "quartz", "scheduled", "kafka", "listener", or "session-listener" * @return the token to pass to {@link #exit(Object)} when it is done */ public static Object enter(Object job, String kind) { @@ -125,6 +125,13 @@ public static Object enter(Object job, String kind) { // whose window already closed; fail closed on asyncExecutors. KeployDedupAgent.noteObservedUntrackedAsyncLibrary( "scheduled job (" + run.name + ")", true); + } else if ("session-listener".equals(kind)) { + // A container session-expiry listener firing outside any tracked + // request or job may be executing application cleanup for a + // session created by an earlier HTTP test; fail closed on + // asyncExecutors in addition to contaminating overlapping windows. + KeployDedupAgent.noteObservedUntrackedAsyncLibrary( + "session listener outside request window (" + run.name + ")", true); } } catch (Throwable t) { // The job runs on. A run counted as going on before this (an @@ -391,6 +398,9 @@ static String name(Object job, String kind) { if ("kafka".equals(kind) || "listener".equals(kind)) { return cachedListenerName(job, kind); } + if ("session-listener".equals(kind) && job instanceof String) { + return kind + ":" + job; + } String name; try { if ("quartz".equals(kind)) { 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 fd8e93f4..94d18c5e 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -94,6 +94,29 @@ public final class RequestGate { // keeps marking every subsequent window "armed-mid-flight" until exit(). private static final Object UNARMED_TOKEN = new Object(); private static final LongAdder UNARMED_IN_FLIGHT = new LongAdder(); + + // Exact container-internal listener bridge classes skipped ONLY on + // container-native listener interfaces (never on Servlet HttpSession*Listener + // interfaces), because these bridges either delegate into hooked Servlet + // session listener dispatchers or perform container-only SSO bookkeeping. + private static final Set INTERNAL_CONTAINER_SESSION_LISTENERS = Collections.unmodifiableSet( + new java.util.HashSet<>(java.util.Arrays.asList( + "io.undertow.servlet.core.SessionListenerBridge", + "org.eclipse.jetty.ee11.servlet.SessionHandler", + "org.eclipse.jetty.ee10.servlet.SessionHandler", + "org.eclipse.jetty.ee9.nested.SessionHandler", + "org.eclipse.jetty.ee8.nested.SessionHandler", + "org.apache.catalina.authenticator.SingleSignOnListener" + ))); + + // Exact container-internal Servlet session listener classes auto-registered + // by default container initializers (e.g. Tomcat's WsSci in Spring Boot and + // standalone Tomcat) skipped ONLY on exact class name (never subclasses) so + // listener-free session expiry does not falsely contaminate or latch. + private static final Set INTERNAL_SERVLET_SESSION_LISTENERS = Collections.unmodifiableSet( + new java.util.HashSet<>(java.util.Arrays.asList( + "org.apache.tomcat.websocket.server.WsSessionListener" + ))); // Timestamp of the last unarmed async hand-off (zero-allocation, zero // wrapping) so windows opened shortly after arming still carry // armed-mid-flight even if the initiating unarmed request already exited. @@ -555,6 +578,7 @@ static void disarm() { unarmedEntered = false; pendingArmedMidFlight = false; lastUnarmedHandOffNanos = 0L; + UNARMED_REQUEST_DEPTH.remove(); ARMED_MID_FLIGHT_CONSUMED.set(false); externalUntrackedTailPending = false; externalUntrackedTailExpiresAtNanos = 0L; @@ -5665,6 +5689,70 @@ public String toString() { } } + /** + * Guards a container session-listener invocation (e.g. + * {@code HttpSessionListener.sessionDestroyed}, + * {@code HttpSessionAttributeListener.attributeRemoved}, + * {@code HttpSessionBindingListener.valueUnbound}). When invoked on a + * thread already inside a tracked request/dispatch or tracked job (such as + * synchronous {@code session.invalidate()} inside a handler), returns + * {@code null} with zero latch and zero contamination. When invoked on a + * background expiry thread outside any tracked request or job, enters + * {@link JobGate} so overlapping test windows are marked contaminated and + * latches {@code asyncExecutors=false}. + * + * @param listener the session listener instance being invoked + * @param eventName the listener method name (e.g. {@code "sessionDestroyed"}) + * @param containerNative {@code true} for container-native listener + * interfaces where exact container-internal bridge listeners are + * skipped; {@code false} for standard Servlet session listener + * interfaces + * @return a token to pass to {@link #exitSessionListener(Object)}, or + * {@code null} when no background tracking was needed + */ + public static Object enterSessionListener(Object listener, String eventName, boolean containerNative) { + if (listener == null) { + return null; + } + String listenerClass = listener.getClass().getName(); + if (containerNative && INTERNAL_CONTAINER_SESSION_LISTENERS.contains(listenerClass)) { + return null; + } + if (!containerNative && INTERNAL_SERVLET_SESSION_LISTENERS.contains(listenerClass)) { + return null; + } + if (isInsideUnarmedRequest()) { + return null; + } + String label = (eventName == null || eventName.isEmpty()) + ? listenerClass + : listenerClass + "#" + eventName; + if (!armed) { + KeployDedupAgent.noteObservedUntrackedAsyncLibrary( + "session listener outside request window (" + label + ")", false); + return enterUnarmed(); + } + if (INSIDE.get() != null + || JobGate.runningAttribution() != null + || JobGate.expiredRunningName() != null) { + return null; + } + return JobGate.enter(label, "session-listener"); + } + + /** + * Completes a background session-listener run started by + * {@link #enterSessionListener(Object, String, boolean)}. + * + * @param token the token returned by {@code enterSessionListener}, or {@code null} + */ + public static void exitSessionListener(Object token) { + if (token == null) { + return; + } + JobGate.exit(token); + } + private static final class HandedSupplier extends Hand implements Supplier { final Supplier task; 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 3be9b217..11b4674f 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -51,6 +51,7 @@ final class ServerEntries implements ClassFileTransformer { static final String RENAMED = "keploy$request$"; static final String JOB_RENAMED = "keploy$job$"; static final String ASYNC_RENAMED = "keploy$async$"; + static final String SESSION_LISTENER_BRIDGE_PREFIX = "keploy$sessionListener$"; private static final String JAVAX_ASYNC_CONTEXT = "javax/servlet/AsyncContext"; private static final String JAKARTA_ASYNC_CONTEXT = "jakarta/servlet/AsyncContext"; private static final String ASYNC_CONTEXT_START_DESC = "(Ljava/lang/Runnable;)V"; @@ -736,6 +737,86 @@ private static Map> buildStageSyncMethods(String ret) { return Collections.unmodifiableMap(m); } + // Container session-listener dispatch classes (Tomcat 8.5/9/10.1/11, + // Jetty 9.4/11/12.0/12.1 + ee8/ee9/core, Undertow 2.2/2.3). Background + // session expiry timers (HouseKeeper, SessionInactivityTimer, + // ContainerBackgroundProcessor, InMemorySessionManager) invoke user + // session listeners through these classes outside any request window; + // wrapping each listener invokeinterface site into RequestGate.enterSessionListener + // contaminates overlapping windows and latches asyncExecutors=false while + // leaving in-request session.invalidate() and no-listener expiries clean. + private static final Set SESSION_LISTENER_DISPATCH_CLASSES = setOf( + "org/apache/catalina/session/StandardSession", + "org/eclipse/jetty/server/session/SessionHandler", + "org/eclipse/jetty/server/session/Session", + "org/eclipse/jetty/ee11/servlet/SessionHandler", + "org/eclipse/jetty/ee10/servlet/SessionHandler", + "org/eclipse/jetty/ee9/nested/SessionHandler", + "org/eclipse/jetty/ee8/nested/SessionHandler", + "org/eclipse/jetty/session/AbstractSessionManager", + "org/eclipse/jetty/session/ManagedSession", + "io/undertow/servlet/core/ApplicationListeners", + "io/undertow/servlet/core/SessionListenerBridge", + "io/undertow/servlet/handlers/SessionRestoringHandler", + "io/undertow/server/session/SessionListeners" + ); + + // The dispatch classes whose own bytes must carry a listener call site: + // one loaded without any is a version whose dispatch moved, and fails + // closed. Jetty 12's ee8/ee9 nested SessionHandler has none of its own: it + // dispatches in its nested CoreSessionManager, which must carry them. + private static final Set SESSION_LISTENER_REQUIRED_CLASSES = requiredSessionListenerClasses(); + + private static Set requiredSessionListenerClasses() { + Set required = new HashSet<>(SESSION_LISTENER_DISPATCH_CLASSES); + for (String ee : new String[] {"ee8", "ee9"}) { + String outer = "org/eclipse/jetty/" + ee + "/nested/SessionHandler"; + required.remove(outer); + required.add(outer + "$CoreSessionManager"); + } + return Collections.unmodifiableSet(required); + } + + private static final Map> SERVLET_SESSION_LISTENER_METHODS = + buildServletSessionListenerMethods(); + private static final Map> CONTAINER_SESSION_LISTENER_METHODS = + buildContainerSessionListenerMethods(); + + private static Map> buildServletSessionListenerMethods() { + Map> m = new HashMap<>(); + Set lifecycle = setOf("sessionDestroyed", "sessionCreated"); + Set attr = setOf("attributeAdded", "attributeRemoved", "attributeReplaced"); + Set binding = setOf("valueBound", "valueUnbound"); + Set activation = setOf("sessionWillPassivate", "sessionDidActivate"); + // A session id changes on a thread outside any request too: Tomcat's + // cluster managers apply a peer's CHANGE_SESSION_ID on their receiver. + Set id = setOf("sessionIdChanged"); + m.put("javax/servlet/http/HttpSessionIdListener", id); + m.put("jakarta/servlet/http/HttpSessionIdListener", id); + m.put("javax/servlet/http/HttpSessionListener", lifecycle); + m.put("jakarta/servlet/http/HttpSessionListener", lifecycle); + m.put("javax/servlet/http/HttpSessionAttributeListener", attr); + m.put("jakarta/servlet/http/HttpSessionAttributeListener", attr); + m.put("javax/servlet/http/HttpSessionBindingListener", binding); + m.put("jakarta/servlet/http/HttpSessionBindingListener", binding); + m.put("javax/servlet/http/HttpSessionActivationListener", activation); + m.put("jakarta/servlet/http/HttpSessionActivationListener", activation); + return Collections.unmodifiableMap(m); + } + + private static Map> buildContainerSessionListenerMethods() { + Map> m = new HashMap<>(); + m.put("org/apache/catalina/SessionListener", setOf("sessionEvent")); + m.put("org/eclipse/jetty/server/Session$LifeCycleListener", + setOf("onSessionDestroyed", "onSessionCreated", "onSessionIdChanged")); + m.put("org/eclipse/jetty/server/Session$ValueListener", + setOf("onSessionAttributeUpdate", "onSessionActivation", "onSessionPassivation")); + m.put("io/undertow/server/session/SessionListener", + setOf("sessionDestroyed", "sessionCreated", "attributeAdded", "attributeRemoved", + "attributeUpdated", "sessionIdChanged")); + return Collections.unmodifiableMap(m); + } + private static Set setOf(String... values) { return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(values))); } @@ -749,6 +830,9 @@ private static Set setOf(String... values) { // Implementations of javax/jakarta AsyncContext whose start(Runnable) was // hooked on load, by their loader: re-applied on retransform. private final Map> asyncContextHooked = new WeakHashMap<>(); + // Container session-listener dispatch classes rewritten on load, by their + // loader: re-applied on retransform. + private final Map> sessionListenerHooked = new WeakHashMap<>(); // Whether servers' requests count (END waits for them); jobs' runs // count either way. private final boolean requests; @@ -987,13 +1071,21 @@ public byte[] transform(ClassLoader loader, String className, Class classBein } byte[] currentBytes = classfileBuffer; boolean hookedAsyncContext = false; + boolean hookedSessionListener = false; if (className != null && !isInternalOrAgentClass(className)) { byte[] asyncCtxWrapped = maybeHookAsyncContextStart(loader, className, protectionDomain, currentBytes); if (asyncCtxWrapped != null) { currentBytes = asyncCtxWrapped; hookedAsyncContext = true; } + byte[] sessionWrapped = maybeHookSessionListenerDispatch(loader, className, protectionDomain, + currentBytes); + if (sessionWrapped != null) { + currentBytes = sessionWrapped; + hookedSessionListener = true; + } } + boolean hookedAny = hookedAsyncContext || hookedSessionListener; if (shouldRewriteExecutorCalls(className)) { scanUnhookedReferences(className, currentBytes, false, false); if (!canAccessGate(loader, protectionDomain)) { @@ -1003,7 +1095,7 @@ public byte[] transform(ClassLoader loader, String className, Class classBein appRewriteFailed = true; } scanUnhookedReferences(className, currentBytes, true, true); - return hookedAsyncContext ? currentBytes : null; + return hookedAny ? currentBytes : null; } try { byte[] updated = wrapExecutorCalls(currentBytes); @@ -1011,11 +1103,11 @@ public byte[] transform(ClassLoader loader, String className, Class classBein recordRewritten(loader, className); return updated; } - return hookedAsyncContext ? currentBytes : null; + return hookedAny ? currentBytes : null; } catch (Throwable t) { appRewriteFailed = true; LOGGER.log(Level.FINE, "Keploy dedup skipped executor call-site wrap for " + className, t); - return hookedAsyncContext ? currentBytes : null; + return hookedAny ? currentBytes : null; } } else if (className != null && !isInternalOrAgentClass(className)) { // Fail-closed read-only constant-pool scan of EVERY non-JDK, @@ -1027,7 +1119,7 @@ public byte[] transform(ClassLoader loader, String className, Class classBein scanUnhookedReferences(className, currentBytes, !isKnownMessagingPoolWrapper(className), checkDispatch); } - return hookedAsyncContext ? currentBytes : null; + return hookedAny ? currentBytes : null; } // With the wait off, servers are left as they are, and so no task // counts as a request's; the executors still count a task a job's @@ -1097,6 +1189,254 @@ private static void noteEntryHookFailure(Entry entry) { } } + private void recordSessionListenerHooked(ClassLoader loader, String className) { + synchronized (sessionListenerHooked) { + Set names = sessionListenerHooked.get(loader); + if (names == null) { + names = new HashSet<>(); + sessionListenerHooked.put(loader, names); + } + names.add(className); + } + } + + private boolean wasSessionListenerHooked(ClassLoader loader, String className) { + if (className == null) { + return false; + } + synchronized (sessionListenerHooked) { + Set names = sessionListenerHooked.get(loader); + return names != null && names.contains(className); + } + } + + private static boolean isSessionListenerPrimaryClass(String className) { + return SESSION_LISTENER_REQUIRED_CLASSES.contains(className); + } + + private static boolean isSessionListenerTargetClass(String className) { + if (SESSION_LISTENER_DISPATCH_CLASSES.contains(className)) { + return true; + } + int dollar = className.indexOf('$'); + return dollar > 0 && SESSION_LISTENER_DISPATCH_CLASSES.contains(className.substring(0, dollar)); + } + + private byte[] maybeHookSessionListenerDispatch(ClassLoader loader, String className, + ProtectionDomain protectionDomain, byte[] classfileBuffer) { + if (classfileBuffer == null || classfileBuffer.length < 16 || !isSessionListenerTargetClass(className)) { + return null; + } + boolean required = isSessionListenerPrimaryClass(className); + String name = className.replace('/', '.'); + try { + if (isInterface(classfileBuffer)) { + return null; + } + if (carriesSessionListenerChange(classfileBuffer)) { + recordSessionListenerHooked(loader, className); + return null; + } + byte[] wrapped = wrapSessionListenerDispatch(classfileBuffer); + if (wrapped == null) { + if (required) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not find session-listener dispatch call sites in " + + name + "; declaring asyncExecutors=false"); + } + return null; + } + if (!canAccessGate(loader, protectionDomain)) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup cannot hook session-listener dispatch on " + name + + ": its loader/module cannot access keploy-sdk.jar"); + return null; + } + recordSessionListenerHooked(loader, className); + LOGGER.log(Level.INFO, "Keploy dedup guards background session listeners (" + name + ")"); + return wrapped; + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not hook session-listener dispatch on " + name, t); + return null; + } + } + + static boolean carriesSessionListenerChange(byte[] classfile) { + final boolean[] carries = {false}; + new ClassReader(classfile).accept(new ClassVisitor(Opcodes.ASM9) { + @Override + public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, + String[] exceptions) { + if (name != null && name.startsWith(SESSION_LISTENER_BRIDGE_PREFIX)) { + carries[0] = true; + } + return null; + } + }, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); + return carries[0]; + } + + private static final class SessionListenerBridgeSpec { + final String bridgeName; + final String bridgeDesc; + final String owner; + final String methodName; + final String methodDesc; + final boolean containerNative; + final Type[] argTypes; + + SessionListenerBridgeSpec(String bridgeName, String bridgeDesc, String owner, String methodName, + String methodDesc, boolean containerNative, Type[] argTypes) { + this.bridgeName = bridgeName; + this.bridgeDesc = bridgeDesc; + this.owner = owner; + this.methodName = methodName; + this.methodDesc = methodDesc; + this.containerNative = containerNative; + this.argTypes = argTypes; + } + } + + private static Boolean lookupSessionListenerNativeFlag(String owner, String methodName) { + Set servletMethods = SERVLET_SESSION_LISTENER_METHODS.get(owner); + if (servletMethods != null && servletMethods.contains(methodName)) { + return Boolean.FALSE; + } + Set containerMethods = CONTAINER_SESSION_LISTENER_METHODS.get(owner); + if (containerMethods != null && containerMethods.contains(methodName)) { + return Boolean.TRUE; + } + return null; + } + + static byte[] wrapSessionListenerDispatch(byte[] classfile) { + ClassReader reader = new ClassReader(classfile); + ClassWriter writer = new ClassWriter(reader, 0); + final String[] ownerHolder = {null}; + final int[] versionHolder = {0}; + final Map bridges = new java.util.LinkedHashMap<>(); + final boolean[] rewroteAny = {false}; + + reader.accept(new ClassVisitor(Opcodes.ASM9, writer) { + @Override + public void visit(int version, int access, String name, String signature, String superName, + String[] interfaces) { + versionHolder[0] = version & 0xFFFF; + ownerHolder[0] = name; + super.visit(version, access, name, signature, superName, interfaces); + } + + @Override + public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, + String[] exceptions) { + MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions); + if (mv == null || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0 + || (name != null && name.startsWith(SESSION_LISTENER_BRIDGE_PREFIX))) { + return mv; + } + return new MethodVisitor(Opcodes.ASM9, mv) { + @Override + public void visitMethodInsn(int opcode, String owner, String mName, String mDesc, + boolean isInterface) { + if (opcode == Opcodes.INVOKEINTERFACE && isInterface) { + Boolean containerNative = lookupSessionListenerNativeFlag(owner, mName); + if (containerNative != null && Type.getReturnType(mDesc).getSort() == Type.VOID) { + Type[] argTypes = Type.getArgumentTypes(mDesc); + boolean allRef = true; + for (Type t : argTypes) { + int sort = t.getSort(); + if (sort != Type.OBJECT && sort != Type.ARRAY) { + allRef = false; + break; + } + } + if (allRef) { + String key = owner + "#" + mName + mDesc + "#" + containerNative; + SessionListenerBridgeSpec spec = bridges.get(key); + if (spec == null) { + String bridgeName = SESSION_LISTENER_BRIDGE_PREFIX + bridges.size(); + String bridgeDesc = "(L" + owner + ";" + mDesc.substring(1); + spec = new SessionListenerBridgeSpec(bridgeName, bridgeDesc, owner, mName, + mDesc, containerNative.booleanValue(), argTypes); + bridges.put(key, spec); + } + rewroteAny[0] = true; + super.visitMethodInsn(Opcodes.INVOKESTATIC, ownerHolder[0], spec.bridgeName, + spec.bridgeDesc, false); + return; + } + } + } + super.visitMethodInsn(opcode, owner, mName, mDesc, isInterface); + } + }; + } + + @Override + public void visitEnd() { + int classVersion = versionHolder[0]; + for (SessionListenerBridgeSpec spec : bridges.values()) { + emitSessionListenerBridge(cv, spec, classVersion); + } + super.visitEnd(); + } + }, 0); + + return rewroteAny[0] ? writer.toByteArray() : null; + } + + private static void emitSessionListenerBridge(ClassVisitor cv, SessionListenerBridgeSpec spec, int classVersion) { + int argc = spec.argTypes.length; + int tokenSlot = argc + 1; + int exSlot = argc + 2; + MethodVisitor mv = cv.visitMethod( + Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC, + spec.bridgeName, spec.bridgeDesc, null, null); + mv.visitCode(); + Label tryStart = new Label(); + Label tryEnd = new Label(); + Label catchAll = new Label(); + mv.visitTryCatchBlock(tryStart, tryEnd, catchAll, null); + + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitLdcInsn(spec.methodName); + mv.visitInsn(spec.containerNative ? Opcodes.ICONST_1 : Opcodes.ICONST_0); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "enterSessionListener", + "(Ljava/lang/Object;Ljava/lang/String;Z)Ljava/lang/Object;", false); + mv.visitVarInsn(Opcodes.ASTORE, tokenSlot); + + mv.visitLabel(tryStart); + for (int i = 0; i <= argc; i++) { + mv.visitVarInsn(Opcodes.ALOAD, i); + } + mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, spec.owner, spec.methodName, spec.methodDesc, true); + mv.visitLabel(tryEnd); + + mv.visitVarInsn(Opcodes.ALOAD, tokenSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "exitSessionListener", "(Ljava/lang/Object;)V", false); + mv.visitInsn(Opcodes.RETURN); + + mv.visitLabel(catchAll); + if (classVersion >= Opcodes.V1_6) { + Object[] frameLocals = new Object[argc + 2]; + frameLocals[0] = spec.owner; + for (int i = 0; i < argc; i++) { + frameLocals[i + 1] = spec.argTypes[i].getInternalName(); + } + frameLocals[argc + 1] = "java/lang/Object"; + mv.visitFrame(Opcodes.F_FULL, frameLocals.length, frameLocals, + 1, new Object[] {"java/lang/Throwable"}); + } + mv.visitVarInsn(Opcodes.ASTORE, exSlot); + mv.visitVarInsn(Opcodes.ALOAD, tokenSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "exitSessionListener", "(Ljava/lang/Object;)V", false); + mv.visitVarInsn(Opcodes.ALOAD, exSlot); + mv.visitInsn(Opcodes.ATHROW); + mv.visitMaxs(Math.max(3, argc + 1), argc + 3); + mv.visitEnd(); + } + private void recordRewritten(ClassLoader loader, String className) { synchronized (rewritten) { Set names = rewritten.get(loader); @@ -1644,6 +1984,21 @@ private byte[] changedAgain(ClassLoader loader, String className, byte[] classfi LOGGER.log(Level.WARNING, "Keploy dedup could not re-hook AsyncContext.start on " + className, t); } } + if (wasSessionListenerHooked(loader, className)) { + try { + if (!carriesSessionListenerChange(currentBytes)) { + byte[] wrapped = wrapSessionListenerDispatch(currentBytes); + if (wrapped != null) { + currentBytes = wrapped; + changedAny = true; + } + } + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not re-hook session listener dispatch on " + + className, t); + } + } if (wasRewritten(loader, className)) { try { byte[] updated = wrapExecutorCalls(currentBytes); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java new file mode 100644 index 00000000..8388313b --- /dev/null +++ b/keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java @@ -0,0 +1,1080 @@ +package io.keploy.dedup; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.jar.Attributes; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; +import org.example.servers.SessionExpiryApp; +import org.jacoco.agent.AgentJar; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; + +/** + * Unit and forked-JVM tests for container session-listener dispatch hooks + * across Tomcat, Jetty, and Undertow. + */ +public class SessionListenerHookTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + @Test + public void enterSessionListenerContaminatesAndLatchesOutsideRequestButIsNoOpInsideRequestOrJob() { + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + try { + // 1. Armed, outside any request or job: contaminates open window AND latches asyncExecutors=false. + RequestGate.open("sess-bg", null); + JobGate.open(); + Object listener = new Object(); + Object token = RequestGate.enterSessionListener(listener, "sessionDestroyed", false); + assertNotNull("background session listener must return tracking token", token); + assertTrue("background session listener must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + assertEquals("JobGate activeRunCount must be 1 while listener executes", 1, JobGate.activeRunCount()); + // Nested listener callback on the same thread is already inside the active JobGate run. + assertNull("nested listener callback inside active session-listener run must be a no-op", + RequestGate.enterSessionListener(listener, "valueUnbound", false)); + RequestGate.exitSessionListener(token); + assertEquals("JobGate activeRunCount must return to 0 after exit", 0, JobGate.activeRunCount()); + List jobs = JobGate.close(); + assertEquals(1, jobs.size()); + assertTrue("open window must be contaminated with session-listener label, got: " + jobs, + jobs.get(0).startsWith("session-listener:") && jobs.get(0).endsWith("#sessionDestroyed")); + + // 2. Armed, inside a tracked HTTP request: returns null, zero latch, zero contamination. + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.open("sess-in-req", null); + JobGate.open(); + Object reqToken = RequestGate.enter(); + try { + assertNull("in-request session listener must return null", + RequestGate.enterSessionListener(listener, "sessionDestroyed", false)); + assertFalse("in-request session listener must not latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + RequestGate.exit(reqToken); + } + assertTrue("in-request session listener must not contaminate JobGate window", + JobGate.close().isEmpty()); + + // 3. Armed, inside an already-tracked JobGate run: returns null without creating duplicate run. + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + JobGate.open(); + Object jobToken = JobGate.enter(new Object(), "scheduled"); + try { + assertEquals(1, JobGate.activeRunCount()); + assertNull("in-job session listener must return null", + RequestGate.enterSessionListener(listener, "attributeRemoved", false)); + assertEquals(1, JobGate.activeRunCount()); + } finally { + JobGate.exit(jobToken); + } + JobGate.close(); + + // 3b. Armed, inside an expired handed-off JobGate run (runningAttribution() == null, + // expiredRunningName() != null): returns null without latching or duplicating a run. + long savedJobBudget = JobGate.handedJobMaxNanos; + java.util.concurrent.ThreadPoolExecutor verifiedPool = new java.util.concurrent.ThreadPoolExecutor( + 1, 1, 0L, TimeUnit.MILLISECONDS, new java.util.concurrent.LinkedBlockingQueue()); + try { + JobGate.handedJobMaxNanos = TimeUnit.MILLISECONDS.toNanos(25); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.open("sess-expired-job", null); + final AtomicBoolean ranInsideExpired = new AtomicBoolean(false); + Runnable expiredHop; + Object outerJob = JobGate.enter(new Object(), "scheduled"); + try { + expiredHop = RequestGate.hand(verifiedPool, () -> { + try { + Thread.sleep(60); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + assertNull("job attribution must have expired", JobGate.runningAttribution()); + assertNotNull("expired job name must still be active on thread", + JobGate.expiredRunningName()); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + assertNull("session listener inside expired job run must return null", + RequestGate.enterSessionListener(listener, "sessionDestroyed", false)); + assertFalse("session listener inside expired job run must not latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + ranInsideExpired.set(true); + }); + } finally { + JobGate.exit(outerJob); + } + JobGate.open(); + expiredHop.run(); + JobGate.close(); + assertTrue("expired job hop must have executed", ranInsideExpired.get()); + } finally { + JobGate.handedJobMaxNanos = savedJobBudget; + verifiedPool.shutdownNow(); + } + + // 4. Unarmed inside an HTTP request (e.g. warmup before arming): zero false latch. + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + Object unarmedReq = RequestGate.enter(); + try { + assertNull("unarmed in-request session listener must not latch", + RequestGate.enterSessionListener(listener, "valueBound", false)); + assertFalse("unarmed in-request session listener must leave latch false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + // Even if armed mid-request, thread is still inside the unarmed request. + RequestGate.arm(); + assertNull("mid-flight-armed in-request session listener must not latch", + RequestGate.enterSessionListener(listener, "sessionDestroyed", false)); + assertFalse("mid-flight-armed in-request session listener must leave latch false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + RequestGate.exit(unarmedReq); + } + + // 5. Unarmed outside any request: latches asyncExecutors=false and returns UNARMED_TOKEN. + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + Object unarmedBg = RequestGate.enterSessionListener(listener, "sessionDestroyed", false); + assertNotNull("unarmed background session listener must return UNARMED_TOKEN", unarmedBg); + assertTrue("unarmed background session listener must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + assertTrue("unarmed in-flight count must increment while running", RequestGate.unarmedInFlight() > 0); + RequestGate.exitSessionListener(unarmedBg); + assertEquals("unarmed in-flight count must return to 0 after exit", 0L, RequestGate.unarmedInFlight()); + } finally { + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + } + } + + @Test + public void containerNativeBridgeSkipOnlyAppliesToExactInternalBridgesWhenFlagIsTrue() throws Exception { + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + try { + // Synthesize a class with the exact internal bridge name io.undertow.servlet.core.SessionListenerBridge + // to prove containerNative=true skips it while containerNative=false NEVER skips it. + ClassLoader cl = new ClassLoader(SessionListenerHookTest.class.getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if ("io.undertow.servlet.core.SessionListenerBridge".equals(name)) { + Class existing = findLoadedClass(name); + if (existing != null) { + return existing; + } + byte[] raw = generateEmptyClass("io/undertow/servlet/core/SessionListenerBridge"); + Class defined = defineClass(name, raw, 0, raw.length); + if (resolve) { + resolveClass(defined); + } + return defined; + } + return super.loadClass(name, resolve); + } + }; + Object bridge = cl.loadClass("io.undertow.servlet.core.SessionListenerBridge") + .getDeclaredConstructor().newInstance(); + + RequestGate.open("sess-bridge", null); + JobGate.open(); + assertNull("containerNative=true must skip exact SessionListenerBridge", + RequestGate.enterSessionListener(bridge, "sessionDestroyed", true)); + assertFalse("skipping SessionListenerBridge must not latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + assertTrue("skipping SessionListenerBridge must not contaminate window", + JobGate.close().isEmpty()); + + // Same object on a non-containerNative (Servlet) interface MUST NOT be skipped. + JobGate.open(); + Object tok = RequestGate.enterSessionListener(bridge, "sessionDestroyed", false); + assertNotNull("containerNative=false must never skip any listener class", tok); + assertTrue("containerNative=false must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + RequestGate.exitSessionListener(tok); + assertFalse("containerNative=false must contaminate window", JobGate.close().isEmpty()); + + // Non-bridge custom object on containerNative=true MUST still latch and contaminate. + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + JobGate.open(); + Object custom = new Object(); + Object customTok = RequestGate.enterSessionListener(custom, "sessionDestroyed", true); + assertNotNull("custom listener on containerNative=true must not be skipped", customTok); + assertTrue("custom listener on containerNative=true must latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + RequestGate.exitSessionListener(customTok); + assertFalse("custom listener on containerNative=true must contaminate window", JobGate.close().isEmpty()); + + // Exact Tomcat default WsSessionListener (registered by Tomcat WsSci in Spring Boot and + // standalone Tomcat) is skipped on Servlet interfaces (containerNative=false), while a + // subclass MUST NOT be skipped. + ClassLoader wsLoader = new ClassLoader(SessionListenerHookTest.class.getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + byte[] raw = null; + if ("org.apache.tomcat.websocket.server.WsSessionListener".equals(name)) { + raw = generateEmptyClass("org/apache/tomcat/websocket/server/WsSessionListener"); + } else if ("org.example.CustomWsSessionListener".equals(name)) { + raw = generateEmptySubclass("org/example/CustomWsSessionListener", + "org/apache/tomcat/websocket/server/WsSessionListener"); + } + if (raw != null) { + Class existing = findLoadedClass(name); + if (existing != null) { + return existing; + } + Class defined = defineClass(name, raw, 0, raw.length); + if (resolve) { + resolveClass(defined); + } + return defined; + } + return super.loadClass(name, resolve); + } + }; + Object wsListener = wsLoader.loadClass("org.apache.tomcat.websocket.server.WsSessionListener") + .getDeclaredConstructor().newInstance(); + Object wsSub = wsLoader.loadClass("org.example.CustomWsSessionListener") + .getDeclaredConstructor().newInstance(); + + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + JobGate.open(); + assertNull("exact Tomcat WsSessionListener must be skipped on Servlet interface", + RequestGate.enterSessionListener(wsListener, "sessionDestroyed", false)); + assertFalse("skipping Tomcat WsSessionListener must not latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + assertTrue("skipping Tomcat WsSessionListener must not contaminate window", + JobGate.close().isEmpty()); + + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + JobGate.open(); + Object wsSubTok = RequestGate.enterSessionListener(wsSub, "sessionDestroyed", false); + assertNotNull("subclass of WsSessionListener must NOT be skipped", wsSubTok); + assertTrue("subclass of WsSessionListener must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + RequestGate.exitSessionListener(wsSubTok); + assertFalse("subclass of WsSessionListener must contaminate window", JobGate.close().isEmpty()); + } finally { + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + } + } + + @Test + public void serverEntriesRewritesAllContainerDispatchClassesIncludingMultiArgAndExceptionCleanup() throws Exception { + final ServerEntries transformer = new ServerEntries(true); + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + try { + String[][] cases = { + // { dispatcherClassInternal, listenerIfaceInternal, methodName, methodDesc, argCount } + { "org/apache/catalina/session/StandardSession", + "javax/servlet/http/HttpSessionListener", "sessionDestroyed", + "(Ljavax/servlet/http/HttpSessionEvent;)V", "1" }, + { "org/apache/catalina/session/StandardSession", + "jakarta/servlet/http/HttpSessionBindingListener", "valueUnbound", + "(Ljakarta/servlet/http/HttpSessionBindingEvent;)V", "1" }, + { "org/apache/catalina/session/StandardSession", + "org/apache/catalina/SessionListener", "sessionEvent", + "(Lorg/apache/catalina/SessionEvent;)V", "1" }, + { "org/eclipse/jetty/server/session/SessionHandler", + "javax/servlet/http/HttpSessionAttributeListener", "attributeRemoved", + "(Ljavax/servlet/http/HttpSessionBindingEvent;)V", "1" }, + { "org/eclipse/jetty/server/session/SessionHandler$2", + "javax/servlet/http/HttpSessionListener", "sessionDestroyed", + "(Ljavax/servlet/http/HttpSessionEvent;)V", "1" }, + { "org/eclipse/jetty/server/session/Session", + "javax/servlet/http/HttpSessionBindingListener", "valueUnbound", + "(Ljavax/servlet/http/HttpSessionBindingEvent;)V", "1" }, + { "org/eclipse/jetty/ee10/servlet/SessionHandler", + "jakarta/servlet/http/HttpSessionListener", "sessionDestroyed", + "(Ljakarta/servlet/http/HttpSessionEvent;)V", "1" }, + { "org/eclipse/jetty/ee11/servlet/SessionHandler", + "jakarta/servlet/http/HttpSessionAttributeListener", "attributeRemoved", + "(Ljakarta/servlet/http/HttpSessionBindingEvent;)V", "1" }, + { "org/eclipse/jetty/ee9/nested/SessionHandler$CoreSessionManager", + "jakarta/servlet/http/HttpSessionBindingListener", "valueUnbound", + "(Ljakarta/servlet/http/HttpSessionBindingEvent;)V", "1" }, + { "org/eclipse/jetty/ee8/nested/SessionHandler$CoreSessionManager", + "javax/servlet/http/HttpSessionListener", "sessionDestroyed", + "(Ljavax/servlet/http/HttpSessionEvent;)V", "1" }, + { "org/eclipse/jetty/session/AbstractSessionManager", + "org/eclipse/jetty/server/Session$LifeCycleListener", "onSessionDestroyed", + "(Lorg/eclipse/jetty/server/Session;)V", "1" }, + { "org/eclipse/jetty/session/ManagedSession", + "org/eclipse/jetty/server/Session$ValueListener", "onSessionAttributeUpdate", + "(Lorg/eclipse/jetty/server/Session;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", "4" }, + { "org/eclipse/jetty/session/ManagedSession", + "org/eclipse/jetty/server/Session$ValueListener", "onSessionActivation", + "(Lorg/eclipse/jetty/server/Session;)V", "1" }, + { "org/eclipse/jetty/session/ManagedSession", + "org/eclipse/jetty/server/Session$ValueListener", "onSessionPassivation", + "(Lorg/eclipse/jetty/server/Session;)V", "1" }, + { "io/undertow/servlet/core/ApplicationListeners", + "jakarta/servlet/http/HttpSessionListener", "sessionDestroyed", + "(Ljakarta/servlet/http/HttpSessionEvent;)V", "1" }, + { "io/undertow/servlet/core/SessionListenerBridge", + "jakarta/servlet/http/HttpSessionBindingListener", "valueUnbound", + "(Ljakarta/servlet/http/HttpSessionBindingEvent;)V", "1" }, + { "io/undertow/servlet/handlers/SessionRestoringHandler", + "jakarta/servlet/http/HttpSessionActivationListener", "sessionWillPassivate", + "(Ljakarta/servlet/http/HttpSessionEvent;)V", "1" }, + { "io/undertow/server/session/SessionListeners", + "io/undertow/server/session/SessionListener", "sessionDestroyed", + "(Lio/undertow/server/session/Session;Lio/undertow/server/HttpServerExchange;Lio/undertow/server/session/SessionListener$SessionDestroyedReason;)V", "3" }, + // HttpSessionIdListener: Tomcat's cluster managers change a session's id on their + // receiver thread, outside any request. + { "org/apache/catalina/session/StandardSession", + "javax/servlet/http/HttpSessionIdListener", "sessionIdChanged", + "(Ljavax/servlet/http/HttpSessionEvent;Ljava/lang/String;)V", "2" }, + { "org/eclipse/jetty/ee9/nested/SessionHandler$CoreSessionManager", + "jakarta/servlet/http/HttpSessionIdListener", "sessionIdChanged", + "(Ljakarta/servlet/http/HttpSessionEvent;Ljava/lang/String;)V", "2" }, + }; + + for (final String[] row : cases) { + final String dispInternal = row[0]; + final String ifaceInternal = row[1]; + final String mName = row[2]; + final String mDesc = row[3]; + final int argc = Integer.parseInt(row[4]); + + ServerEntries.setHookStatusForTests(false, false, false, false, false); + final byte[] ifaceBytes = generateSyntheticInterface(ifaceInternal, mName, mDesc); + final byte[] dispRaw = generateSyntheticDispatcher(dispInternal, ifaceInternal, mName, mDesc, argc); + final byte[] dispWrapped = transformer.transform(SessionListenerHookTest.class.getClassLoader(), + dispInternal, null, SessionListenerHookTest.class.getProtectionDomain(), dispRaw); + assertNotNull("must rewrite session listener dispatch in " + dispInternal, dispWrapped); + assertTrue("rewritten class must carry bridge prefix for " + dispInternal, + ServerEntries.carriesSessionListenerChange(dispWrapped)); + assertFalse("must not fail hook for " + dispInternal, ServerEntries.hadAsyncHookFailure()); + + // Retransform with already-wrapped bytes is idempotent (returns null); + // retransform with raw bytes re-applies the hook! + assertNull("retransform of already-wrapped class must be idempotent for " + dispInternal, + transformer.transform(SessionListenerHookTest.class.getClassLoader(), dispInternal, + Object.class, SessionListenerHookTest.class.getProtectionDomain(), dispWrapped)); + byte[] rewrapped = transformer.transform(SessionListenerHookTest.class.getClassLoader(), dispInternal, + Object.class, SessionListenerHookTest.class.getProtectionDomain(), dispRaw); + assertNotNull("retransform of stripped class must re-apply hook for " + dispInternal, rewrapped); + + // Define synthetic interface + rewritten dispatcher in an isolated child loader and execute it! + final org.objectweb.asm.Type[] argTypes = org.objectweb.asm.Type.getArgumentTypes(mDesc); + ClassLoader execLoader = new ClassLoader(SessionListenerHookTest.class.getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + String internal = name.replace('.', '/'); + byte[] raw = null; + if (ifaceInternal.equals(internal)) { + raw = ifaceBytes; + } else if (dispInternal.equals(internal)) { + raw = dispWrapped; + } else { + for (org.objectweb.asm.Type t : argTypes) { + String ti = t.getInternalName(); + if (ti.equals(internal) && !ti.startsWith("java/")) { + raw = generateEmptyClass(ti); + break; + } + } + } + if (raw != null) { + Class existing = findLoadedClass(name); + if (existing != null) { + return existing; + } + Class c = defineClass(name, raw, 0, raw.length); + if (resolve) { + resolveClass(c); + } + return c; + } + return super.loadClass(name, resolve); + } + }; + + Class ifaceCls = execLoader.loadClass(ifaceInternal.replace('/', '.')); + Class dispCls = execLoader.loadClass(dispInternal.replace('/', '.')); + final AtomicBoolean shouldThrow = new AtomicBoolean(false); + final AtomicInteger invocations = new AtomicInteger(0); + final AtomicBoolean seenActiveJob = new AtomicBoolean(false); + Object proxyListener = java.lang.reflect.Proxy.newProxyInstance(execLoader, + new Class[] {ifaceCls}, + (proxy, method, args) -> { + invocations.incrementAndGet(); + seenActiveJob.set(JobGate.activeRunCount() > 0); + if (shouldThrow.get()) { + throw new IllegalStateException("boom-from-listener"); + } + return null; + }); + Class[] paramTypes = new Class[argc + 1]; + paramTypes[0] = ifaceCls; + Object[] invokeArgs = new Object[argc + 1]; + invokeArgs[0] = proxyListener; + for (int i = 0; i < argc; i++) { + paramTypes[i + 1] = execLoader.loadClass(argTypes[i].getClassName()); + invokeArgs[i + 1] = null; + } + Method dispatchMethod = dispCls.getMethod("dispatch", paramTypes); + + // (a) Background call (armed, outside window/job) -> contaminates window & latches. + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.open("bg-" + dispInternal, null); + JobGate.open(); + dispatchMethod.invoke(null, invokeArgs); + assertEquals(1, invocations.get()); + assertTrue("JobGate run must be active during listener execution for " + dispInternal, + seenActiveJob.get()); + assertEquals("JobGate run must exit cleanly after normal return for " + dispInternal, + 0, JobGate.activeRunCount()); + assertTrue("background listener call must latch asyncExecutors=false for " + dispInternal, + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + List contam = JobGate.close(); + assertTrue("open window must be contaminated for " + dispInternal + ": " + contam, + !contam.isEmpty() && contam.get(0).startsWith("session-listener:") + && contam.get(0).endsWith("#" + mName)); + + // (b) Exception path: try/finally must exit JobGate and propagate the original exception! + shouldThrow.set(true); + JobGate.open(); + try { + dispatchMethod.invoke(null, invokeArgs); + fail("expected listener exception to propagate for " + dispInternal); + } catch (InvocationTargetException expected) { + assertTrue("expected IllegalStateException, got " + expected.getCause(), + expected.getCause() instanceof IllegalStateException); + assertEquals("boom-from-listener", expected.getCause().getMessage()); + } + assertEquals("JobGate run must exit cleanly even when listener throws for " + dispInternal, + 0, JobGate.activeRunCount()); + JobGate.close(); + shouldThrow.set(false); + + // (c) Inside a tracked HTTP request -> zero latch, zero contamination! + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.open("req-" + dispInternal, null); + JobGate.open(); + Object reqToken = RequestGate.enter(); + try { + seenActiveJob.set(false); + dispatchMethod.invoke(null, invokeArgs); + assertFalse("in-request listener must not enter JobGate for " + dispInternal, seenActiveJob.get()); + assertFalse("in-request listener must not latch for " + dispInternal, + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + RequestGate.exit(reqToken); + } + assertTrue("in-request listener must not contaminate window for " + dispInternal, + JobGate.close().isEmpty()); + } + + // Fail-closed 1: primary class with zero matching invokeinterface sites -> asyncHookFailed=true. + ServerEntries.setHookStatusForTests(false, false, false, false, false); + byte[] emptyPrimary = generateEmptyClass("org/apache/catalina/session/StandardSession"); + assertNull(transformer.transform(SessionListenerHookTest.class.getClassLoader(), + "org/apache/catalina/session/StandardSession", null, + SessionListenerHookTest.class.getProtectionDomain(), emptyPrimary)); + assertTrue("primary session-listener class missing call sites must fail closed", + ServerEntries.hadAsyncHookFailure()); + + // Non-primary inner class with zero matching invokeinterface sites -> no failure. + ServerEntries.setHookStatusForTests(false, false, false, false, false); + byte[] emptyInner = generateEmptyClass("org/eclipse/jetty/server/session/SessionHandler$1"); + assertNull(transformer.transform(SessionListenerHookTest.class.getClassLoader(), + "org/eclipse/jetty/server/session/SessionHandler$1", null, + SessionListenerHookTest.class.getProtectionDomain(), emptyInner)); + assertFalse("non-primary inner class without listener call sites must not fail closed", + ServerEntries.hadAsyncHookFailure()); + + // Fail-closed 2: inaccessible classloader (parent=null) -> asyncHookFailed=true. + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ClassLoader isolatedLoader = new ClassLoader(null) { }; + byte[] validDisp = generateSyntheticDispatcher("org/apache/catalina/session/StandardSession", + "javax/servlet/http/HttpSessionListener", "sessionDestroyed", + "(Ljavax/servlet/http/HttpSessionEvent;)V", 1); + assertNull(transformer.transform(isolatedLoader, + "org/apache/catalina/session/StandardSession", null, null, validDisp)); + assertTrue("inaccessible loader for session-listener class must fail closed", + ServerEntries.hadAsyncHookFailure()); + } finally { + RequestGate.disarm(); + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + } + } + + @Test + public void jettyNestedSessionHandlerFailsClosedOnlyWhenItsCoreSessionManagerLacksCallSites() throws Exception { + // Jetty 12's ee8/ee9 nested SessionHandler has no listener call site of its own (its + // nested CoreSessionManager dispatches): loading it must neither change it nor declare + // a hook failure, while a CoreSessionManager without call sites still fails closed. + final ServerEntries transformer = new ServerEntries(true); + ClassLoader loader = SessionListenerHookTest.class.getClassLoader(); + java.security.ProtectionDomain pd = SessionListenerHookTest.class.getProtectionDomain(); + try { + for (String ee : new String[] {"ee8", "ee9"}) { + String outer = "org/eclipse/jetty/" + ee + "/nested/SessionHandler"; + String core = outer + "$CoreSessionManager"; + + ServerEntries.setHookStatusForTests(false, false, false, false, false); + assertNull(transformer.transform(loader, outer, null, pd, generateEmptyClass(outer))); + assertFalse(outer + " without call sites of its own must not declare a hook failure", + ServerEntries.hadAsyncHookFailure()); + + ServerEntries.setHookStatusForTests(false, false, false, false, false); + assertNull(transformer.transform(loader, core, null, pd, generateEmptyClass(core))); + assertTrue(core + " without call sites must fail closed", ServerEntries.hadAsyncHookFailure()); + + ServerEntries.setHookStatusForTests(false, false, false, false, false); + byte[] wrapped = transformer.transform(loader, core, null, pd, generateSyntheticDispatcher(core, + "jakarta/servlet/http/HttpSessionListener", "sessionDestroyed", + "(Ljakarta/servlet/http/HttpSessionEvent;)V", 1)); + assertNotNull(core + " call sites must be rewritten", wrapped); + assertTrue(ServerEntries.carriesSessionListenerChange(wrapped)); + assertFalse(ServerEntries.hadAsyncHookFailure()); + } + } finally { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + } + } + + @Test + public void asmBridgePropagatesContainerNativeFlagAndLoadTimeCarriesCheckIsIdempotent() throws Exception { + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + try { + // 1. Verify the ASM-emitted bridge passes containerNative=true for container-native + // listener interfaces (skipping exact SessionListenerBridge) and containerNative=false + // for Servlet listener interfaces (NEVER skipping SessionListenerBridge). + final ServerEntries transformer = new ServerEntries(true); + ClassLoader pdLoader = SessionListenerHookTest.class.getClassLoader(); + java.security.ProtectionDomain pd = SessionListenerHookTest.class.getProtectionDomain(); + + final String nativeDisp = "io/undertow/server/session/SessionListeners"; + final String nativeIface = "io/undertow/server/session/SessionListener"; + final String nativeDesc = + "(Lio/undertow/server/session/Session;Lio/undertow/server/HttpServerExchange;" + + "Lio/undertow/server/session/SessionListener$SessionDestroyedReason;)V"; + final String servletDisp = "io/undertow/servlet/core/ApplicationListeners"; + final String servletIface = "jakarta/servlet/http/HttpSessionListener"; + final String servletDesc = "(Ljakarta/servlet/http/HttpSessionEvent;)V"; + + final byte[] nativeIfaceBytes = generateSyntheticInterface(nativeIface, "sessionDestroyed", nativeDesc); + final byte[] servletIfaceBytes = generateSyntheticInterface(servletIface, "sessionDestroyed", servletDesc); + final byte[] nativeRaw = generateSyntheticDispatcher(nativeDisp, nativeIface, "sessionDestroyed", + nativeDesc, 3); + final byte[] servletRaw = generateSyntheticDispatcher(servletDisp, servletIface, "sessionDestroyed", + servletDesc, 1); + + ServerEntries.setHookStatusForTests(false, false, false, false, false); + final byte[] nativeWrapped = transformer.transform(pdLoader, nativeDisp, null, pd, nativeRaw); + final byte[] servletWrapped = transformer.transform(pdLoader, servletDisp, null, pd, servletRaw); + assertNotNull("native dispatcher must be rewritten", nativeWrapped); + assertNotNull("servlet dispatcher must be rewritten", servletWrapped); + assertFalse("no hook failure expected", ServerEntries.hadAsyncHookFailure()); + + // 2. Verify initial load (classBeingRedefined == null) on ALREADY-WRAPPED bytes is a + // no-op (returns null without double-wrapping) AND records sessionListenerHooked so a + // subsequent retransform with raw bytes re-applies the hook. + final ServerEntries freshTransformer = new ServerEntries(true); + ServerEntries.setHookStatusForTests(false, false, false, false, false); + assertNull("load-time transform of already-wrapped class must return null (no double-wrap)", + freshTransformer.transform(pdLoader, servletDisp, null, pd, servletWrapped)); + assertFalse("load-time already-wrapped class must not fail hook", + ServerEntries.hadAsyncHookFailure()); + byte[] rehookedAfterLoad = freshTransformer.transform(pdLoader, servletDisp, Object.class, pd, servletRaw); + assertNotNull("retransform of stripped class after load-time already-wrapped must re-apply hook", + rehookedAfterLoad); + assertTrue(ServerEntries.carriesSessionListenerChange(rehookedAfterLoad)); + + // Define a concrete class named io/undertow/servlet/core/SessionListenerBridge implementing + // both synthetic interfaces and run it through BOTH ASM-rewritten dispatchers. + final byte[] bridgeImplBytes = generateDualListenerImpl( + "io/undertow/servlet/core/SessionListenerBridge", + nativeIface, "sessionDestroyed", nativeDesc, + servletIface, "sessionDestroyed", servletDesc); + + ClassLoader execLoader = new ClassLoader(pdLoader) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + String internal = name.replace('.', '/'); + byte[] raw = null; + if (nativeIface.equals(internal)) { + raw = nativeIfaceBytes; + } else if (servletIface.equals(internal)) { + raw = servletIfaceBytes; + } else if (nativeDisp.equals(internal)) { + raw = nativeWrapped; + } else if (servletDisp.equals(internal)) { + raw = servletWrapped; + } else if ("io/undertow/servlet/core/SessionListenerBridge".equals(internal)) { + raw = bridgeImplBytes; + } else if ("io/undertow/server/session/Session".equals(internal) + || "io/undertow/server/HttpServerExchange".equals(internal) + || "io/undertow/server/session/SessionListener$SessionDestroyedReason".equals(internal) + || "jakarta/servlet/http/HttpSessionEvent".equals(internal)) { + raw = generateEmptyClass(internal); + } + if (raw != null) { + Class existing = findLoadedClass(name); + if (existing != null) { + return existing; + } + Class defined = defineClass(name, raw, 0, raw.length); + if (resolve) { + resolveClass(defined); + } + return defined; + } + return super.loadClass(name, resolve); + } + }; + + Object bridgeInstance = execLoader.loadClass("io.undertow.servlet.core.SessionListenerBridge") + .getDeclaredConstructor().newInstance(); + Class nativeDispCls = execLoader.loadClass(nativeDisp.replace('/', '.')); + Class nativeIfaceCls = execLoader.loadClass(nativeIface.replace('/', '.')); + Class sessionCls = execLoader.loadClass("io.undertow.server.session.Session"); + Class exchangeCls = execLoader.loadClass("io.undertow.server.HttpServerExchange"); + Class reasonCls = execLoader.loadClass( + "io.undertow.server.session.SessionListener$SessionDestroyedReason"); + Method nativeDispatch = nativeDispCls.getMethod("dispatch", + nativeIfaceCls, sessionCls, exchangeCls, reasonCls); + + Class servletDispCls = execLoader.loadClass(servletDisp.replace('/', '.')); + Class servletIfaceCls = execLoader.loadClass(servletIface.replace('/', '.')); + Class eventCls = execLoader.loadClass("jakarta.servlet.http.HttpSessionEvent"); + Method servletDispatch = servletDispCls.getMethod("dispatch", servletIfaceCls, eventCls); + + // (a) Container-native ASM bridge MUST pass containerNative=true -> skip SessionListenerBridge! + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.open("asm-native-bridge", null); + JobGate.open(); + nativeDispatch.invoke(null, bridgeInstance, null, null, null); + assertFalse("ASM container-native bridge must pass containerNative=true (must not latch on SessionListenerBridge)", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + assertTrue("ASM container-native bridge must not contaminate on SessionListenerBridge", + JobGate.close().isEmpty()); + + // (b) Servlet ASM bridge MUST pass containerNative=false -> NEVER skip SessionListenerBridge! + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.open("asm-servlet-bridge", null); + JobGate.open(); + servletDispatch.invoke(null, bridgeInstance, null); + assertTrue("ASM servlet bridge must pass containerNative=false (must latch even for SessionListenerBridge)", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + List servletContam = JobGate.close(); + assertFalse("ASM servlet bridge must contaminate window", servletContam.isEmpty()); + } finally { + RequestGate.disarm(); + ServerEntries.setHookStatusForTests(false, false, false, false, false); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + } + } + + @Test(timeout = 180000) + public void forkedTomcatAndJettyAndUndertowBackgroundSessionExpiryContaminatesAndLatches() throws Exception { + for (String server : new String[] {"tomcat", "jetty", "undertow"}) { + for (boolean prefixMode : new boolean[] {false, true}) { + String label = server + " (prefix=" + prefixMode + ")"; + + // 1. Background session expiry WITH app listeners -> W2 contaminated ("session-listener:") + latch! + try (ForkedApp app = startSessionFork(server, "listeners", prefixMode)) { + 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()); + } + 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:")); + + // W2 waits for the container's 1s background timer to fire sessionDestroyed during W2. + String cov2 = app.runHttpTest("se/" + server + "-expire", "/sleep?ms=8000&waitExpiry=true"); + String counts = httpGet(app.port, "/counts"); + assertFalse(label + " listener must actually have fired (counts=" + counts + ")", + counts.startsWith("0,")); + assertTrue(label + " W2 overlapping background session expiry MUST carry session-listener: " + + cov2 + "\nlog:\n" + readFile(app.log), + cov2.contains("session-listener:")); + assertFalse(label + " background session expiry MUST latch asyncExecutors=false: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + + // 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()); + } + } + + // 2. Synchronous in-request session.invalidate() WITH listeners -> ZERO session-listener contamination! + try (ForkedApp app = startSessionFork(server, "listeners", prefixMode)) { + 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()); + } + } + + // 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()); + } + } + } + } + } + + private ForkedApp startSessionFork(String server, String listenerMode, boolean externalJacocoPrefixMode) + throws Exception { + ServerSocket collector = new ServerSocket(0, 1, InetAddress.getLoopbackAddress()); + collector.setSoTimeout(60000); + List cmd = new ArrayList<>(); + cmd.add(new File(System.getProperty("java.home"), "bin/java").getPath()); + cmd.add("-Djava.io.tmpdir=" + tmp.newFolder().getPath()); + if (externalJacocoPrefixMode) { + File jacocoJar = tmp.newFile("jacocoagent-sess-" + System.nanoTime() + ".jar"); + AgentJar.extractTo(jacocoJar); + cmd.add("-javaagent:" + jacocoJar.getPath() + "=includes=org.example.*,output=none"); + } + cmd.add("-javaagent:" + sdkJar().getPath()); + cmd.add("-cp"); + cmd.add(System.getProperty("java.class.path")); + cmd.add(SessionExpiryApp.class.getName()); + cmd.add(server); + cmd.add(listenerMode); + + File log = tmp.newFile("fork-sess-" + server + "-" + listenerMode + "-" + System.nanoTime() + ".log"); + ProcessBuilder pb = new ProcessBuilder(cmd) + .directory(tmp.newFolder()) + .redirectErrorStream(true) + .redirectOutput(log); + Map env = pb.environment(); + env.keySet().removeIf(k -> k.startsWith("KEPLOY_") || k.equals("JAVA_TOOL_OPTIONS") + || k.equals("JDK_JAVA_OPTIONS") || k.equals("_JAVA_OPTIONS")); + if (!externalJacocoPrefixMode) { + File testClasses = new File(SessionExpiryApp.class.getProtectionDomain().getCodeSource() + .getLocation().toURI()); + env.put("KEPLOY_JAVA_CLASS_DIRS", testClasses.getAbsolutePath()); + } + env.put("KEPLOY_COVERAGE_ENDPOINT", "127.0.0.1:" + collector.getLocalPort()); + env.put("KEPLOY_JAVA_DEDUP_WARMUP_DISABLED", "true"); + env.put("KEPLOY_JAVA_END_WAIT_MS", "2000"); + env.put("KEPLOY_DEDUP_POD_UID", "pod-uid-sess"); + env.put("KEPLOY_DEDUP_POD_NAME", "pod-name-sess"); + env.put("KEPLOY_DEDUP_SESSION_ID", "session-sess"); + + Process proc = pb.start(); + try { + int port = waitForPort(log, proc); + Socket sdk = collector.accept(); + sdk.setSoTimeout(60000); + BufferedReader in = new BufferedReader( + new InputStreamReader(sdk.getInputStream(), StandardCharsets.UTF_8)); + OutputStream out = sdk.getOutputStream(); + String hello = in.readLine(); + return new ForkedApp(proc, log, collector, sdk, in, out, port, hello); + } catch (Throwable t) { + proc.destroyForcibly(); + collector.close(); + throw t; + } + } + + private File sdkJar() throws IOException { + File jar = tmp.newFile("keploy-sdk-sess-" + System.nanoTime() + ".jar"); + Manifest manifest = new Manifest(); + manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + manifest.getMainAttributes().putValue("Premain-Class", KeployDedupAgent.class.getName()); + manifest.getMainAttributes().putValue("Can-Retransform-Classes", "true"); + try (JarOutputStream out = new JarOutputStream(new FileOutputStream(jar), manifest)) { + out.putNextEntry(new ZipEntry("META-INF/keploy-test")); + out.closeEntry(); + } + return jar; + } + + private static byte[] generateEmptyClass(String internalName) { + return generateEmptySubclass(internalName, "java/lang/Object"); + } + + private static byte[] generateEmptySubclass(String internalName, String superInternal) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, internalName, null, superInternal, null); + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, superInternal, "", "()V", false); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(0, 0); + init.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateDualListenerImpl(String internalName, + String iface1, String method1, String desc1, + String iface2, String method2, String desc2) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, internalName, null, "java/lang/Object", + new String[] {iface1, iface2}); + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(0, 0); + init.visitEnd(); + MethodVisitor m1 = cw.visitMethod(Opcodes.ACC_PUBLIC, method1, desc1, null, null); + m1.visitCode(); + m1.visitInsn(Opcodes.RETURN); + m1.visitMaxs(0, 0); + m1.visitEnd(); + MethodVisitor m2 = cw.visitMethod(Opcodes.ACC_PUBLIC, method2, desc2, null, null); + m2.visitCode(); + m2.visitInsn(Opcodes.RETURN); + m2.visitMaxs(0, 0); + m2.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateSyntheticInterface(String internalName, String methodName, String desc) { + ClassWriter cw = new ClassWriter(0); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT | Opcodes.ACC_INTERFACE, + internalName, null, "java/lang/Object", null); + cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, methodName, desc, null, null).visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateSyntheticDispatcher(String internalName, String ifaceInternal, String methodName, + String methodDesc, int argc) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, internalName, null, "java/lang/Object", null); + String staticDesc = "(L" + ifaceInternal + ";" + methodDesc.substring(1); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "dispatch", staticDesc, null, null); + mv.visitCode(); + for (int i = 0; i <= argc; i++) { + mv.visitVarInsn(Opcodes.ALOAD, i); + } + mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, ifaceInternal, methodName, methodDesc, true); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(0, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static JsonObject parseHello(String helloLine) { + assertNotNull("HELLO line must not be null", helloLine); + assertTrue("expected HELLO prefix, got: " + helloLine, helloLine.startsWith("HELLO ")); + return JsonParser.parseString(helloLine.substring("HELLO ".length())).getAsJsonObject(); + } + + private static int waitForPort(File log, Process proc) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60); + while (System.nanoTime() < deadline) { + for (String line : Files.readAllLines(log.toPath(), StandardCharsets.UTF_8)) { + if (line.startsWith("PORT ")) { + return Integer.parseInt(line.substring("PORT ".length()).trim()); + } + } + assertTrue("forked JVM exited early:\n" + readFile(log), proc.isAlive()); + Thread.sleep(50); + } + throw new AssertionError("timed out waiting for PORT:\n" + readFile(log)); + } + + private static String readFile(File f) throws IOException { + return new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8); + } + + private static String httpGet(int port, String path) throws IOException { + try (Socket socket = new Socket(InetAddress.getLoopbackAddress(), port)) { + socket.setSoTimeout(30000); + socket.getOutputStream().write(("GET " + path + " HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII)); + InputStream in = socket.getInputStream(); + String status = readHttpLine(in); + assertTrue("expected HTTP 200 for " + path + ", got: " + status, status.contains(" 200 ")); + int length = -1; + String header; + while (!(header = readHttpLine(in)).isEmpty()) { + if (header.toLowerCase(java.util.Locale.ROOT).startsWith("content-length:")) { + length = Integer.parseInt(header.substring("content-length:".length()).trim()); + } + } + if (length >= 0) { + byte[] body = new byte[length]; + int read = 0; + while (read < length) { + int n = in.read(body, read, length - read); + assertTrue(n > 0); + read += n; + } + return new String(body, StandardCharsets.UTF_8); + } + ByteArrayOutputStream rest = new ByteArrayOutputStream(); + byte[] buf = new byte[1024]; + for (int n; (n = in.read(buf)) > 0; ) { + rest.write(buf, 0, n); + } + return new String(rest.toByteArray(), StandardCharsets.UTF_8); + } + } + + private static String readHttpLine(InputStream in) throws IOException { + ByteArrayOutputStream line = new ByteArrayOutputStream(); + int b; + while ((b = in.read()) >= 0 && b != '\n') { + if (b != '\r') { + line.write(b); + } + } + return new String(line.toByteArray(), StandardCharsets.US_ASCII); + } + + private static final class ForkedApp implements Closeable { + final Process proc; + final File log; + final ServerSocket collector; + final Socket sdk; + final BufferedReader in; + final OutputStream out; + final int port; + String lastHello; + + ForkedApp(Process proc, File log, ServerSocket collector, Socket sdk, BufferedReader in, + OutputStream out, int port, String hello) { + this.proc = proc; + this.log = log; + this.collector = collector; + this.sdk = sdk; + this.in = in; + this.out = out; + this.port = port; + this.lastHello = hello; + } + + void send(String cmd) throws IOException { + out.write((cmd + "\n").getBytes(StandardCharsets.UTF_8)); + out.flush(); + } + + String nextNonHello() throws IOException { + while (true) { + String line = in.readLine(); + if (line == null) { + throw new IOException("EOF from agent; log:\n" + readFile(log)); + } + if (line.startsWith("HELLO ")) { + this.lastHello = line; + continue; + } + return line; + } + } + + String runHttpTest(String testId, String path) throws IOException { + send("START " + testId); + assertEquals("ACK", nextNonHello()); + assertEquals("ok", httpGet(port, path)); + send("END " + testId); + String cov = nextNonHello(); + assertTrue("expected COV, got: " + cov, cov != null && cov.startsWith("COV ")); + String line; + while (!(line = nextNonHello()).equals("ACK")) { + assertTrue(line, line.startsWith("CLASSES ") || line.startsWith("MANIFEST ")); + } + return cov.substring("COV ".length()); + } + + @Override + public void close() throws IOException { + try { + sdk.close(); + } catch (IOException ignored) { + } + try { + collector.close(); + } catch (IOException ignored) { + } + proc.destroy(); + try { + if (!proc.waitFor(5, TimeUnit.SECONDS)) { + proc.destroyForcibly(); + } + } catch (InterruptedException e) { + proc.destroyForcibly(); + Thread.currentThread().interrupt(); + } + } + } +} diff --git a/keploy-sdk/src/test/java/org/example/servers/SessionExpiryApp.java b/keploy-sdk/src/test/java/org/example/servers/SessionExpiryApp.java new file mode 100644 index 00000000..d2d1a601 --- /dev/null +++ b/keploy-sdk/src/test/java/org/example/servers/SessionExpiryApp.java @@ -0,0 +1,244 @@ +package org.example.servers; + +import io.undertow.Handlers; +import io.undertow.Undertow; +import io.undertow.servlet.Servlets; +import io.undertow.servlet.api.DeploymentInfo; +import io.undertow.servlet.api.DeploymentManager; +import io.undertow.servlet.api.ListenerInfo; +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionAttributeListener; +import javax.servlet.http.HttpSessionBindingEvent; +import javax.servlet.http.HttpSessionBindingListener; +import javax.servlet.http.HttpSessionEvent; +import javax.servlet.http.HttpSessionListener; +import org.apache.catalina.Context; +import org.apache.catalina.startup.Tomcat; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; + +/** + * Minimal embedded Tomcat 9 / Jetty 9.4 / Undertow 2.2 app used by + * {@code SessionListenerHookTest} to test background HTTP session expiry + * listeners vs synchronous in-request invalidation vs listener-free expiry. + */ +public final class SessionExpiryApp { + + private static volatile CountDownLatch destroyedLatch = new CountDownLatch(1); + private static final AtomicInteger DESTROYED_COUNT = new AtomicInteger(); + private static final AtomicInteger REMOVED_COUNT = new AtomicInteger(); + private static final AtomicInteger UNBOUND_COUNT = new AtomicInteger(); + + public static final class AppSessionListener implements HttpSessionListener { + @Override + public void sessionCreated(HttpSessionEvent se) { + } + + @Override + public void sessionDestroyed(HttpSessionEvent se) { + SessionExpiryTail.hit(); + DESTROYED_COUNT.incrementAndGet(); + destroyedLatch.countDown(); + } + } + + public static final class AppSessionAttrListener implements HttpSessionAttributeListener { + @Override + public void attributeAdded(HttpSessionBindingEvent event) { + } + + @Override + public void attributeRemoved(HttpSessionBindingEvent event) { + SessionExpiryTail.hit(); + REMOVED_COUNT.incrementAndGet(); + } + + @Override + public void attributeReplaced(HttpSessionBindingEvent event) { + } + } + + public static final class AppBindingValue implements HttpSessionBindingListener { + @Override + public void valueBound(HttpSessionBindingEvent event) { + } + + @Override + public void valueUnbound(HttpSessionBindingEvent event) { + SessionExpiryTail.hit(); + UNBOUND_COUNT.incrementAndGet(); + destroyedLatch.countDown(); + } + } + + public static final class AppServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + String path = req.getPathInfo(); + if (path == null) { + path = req.getServletPath(); + } + if ("/clean".equals(path)) { + writeOk(resp, "ok"); + return; + } + if ("/create-session".equals(path)) { + int ttl = parseInt(req.getParameter("ttl"), 1); + boolean bind = !"false".equals(req.getParameter("bind")); + destroyedLatch = new CountDownLatch(1); + HttpSession session = req.getSession(true); + session.setMaxInactiveInterval(ttl); + if (bind) { + session.setAttribute("binding", new AppBindingValue()); + } else { + session.setAttribute("plain", "value"); + } + writeOk(resp, "ok"); + return; + } + if ("/invalidate-sync".equals(path)) { + HttpSession session = req.getSession(true); + session.setAttribute("binding", new AppBindingValue()); + session.invalidate(); + writeOk(resp, "ok"); + return; + } + if ("/sleep".equals(path)) { + long ms = parseLong(req.getParameter("ms"), 2500L); + boolean waitExpiry = "true".equals(req.getParameter("waitExpiry")); + try { + if (waitExpiry) { + destroyedLatch.await(ms, TimeUnit.MILLISECONDS); + // Give the container a brief moment to finish attribute/unbind callbacks too. + Thread.sleep(50L); + } else { + Thread.sleep(ms); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + writeOk(resp, "ok"); + return; + } + if ("/counts".equals(path)) { + writeOk(resp, DESTROYED_COUNT.get() + "," + REMOVED_COUNT.get() + "," + UNBOUND_COUNT.get()); + return; + } + resp.setStatus(404); + writeOk(resp, "not-found:" + path); + } + } + + private static void writeOk(HttpServletResponse resp, String body) throws IOException { + byte[] bytes = body.getBytes("UTF-8"); + resp.setContentType("text/plain"); + resp.setContentLength(bytes.length); + resp.getOutputStream().write(bytes); + } + + private static int parseInt(String value, int fallback) { + if (value == null || value.isEmpty()) { + return fallback; + } + return Integer.parseInt(value); + } + + private static long parseLong(String value, long fallback) { + if (value == null || value.isEmpty()) { + return fallback; + } + return Long.parseLong(value); + } + + public static void main(String[] args) throws Exception { + String serverKind = args.length > 0 ? args[0] : "tomcat"; + boolean withListeners = args.length <= 1 || !"none".equals(args[1]); + int port; + if ("tomcat".equals(serverKind)) { + port = startTomcat(withListeners); + } else if ("jetty".equals(serverKind)) { + port = startJetty(withListeners); + } else if ("undertow".equals(serverKind)) { + port = startUndertow(withListeners); + } else { + throw new IllegalArgumentException("Unknown server: " + serverKind); + } + System.out.println("PORT " + port); + System.out.flush(); + Thread.sleep(Long.MAX_VALUE); + } + + private static int startTomcat(boolean withListeners) throws Exception { + Tomcat tomcat = new Tomcat(); + File base = Files.createTempDirectory("keploy-sess-tomcat").toFile(); + base.deleteOnExit(); + tomcat.setBaseDir(base.getAbsolutePath()); + tomcat.setPort(0); + tomcat.getConnector(); + tomcat.getEngine().setBackgroundProcessorDelay(1); + Context ctx = tomcat.addContext("", base.getAbsolutePath()); + ctx.setBackgroundProcessorDelay(1); + if (withListeners) { + ctx.addApplicationListener(AppSessionListener.class.getName()); + ctx.addApplicationListener(AppSessionAttrListener.class.getName()); + } + Tomcat.addServlet(ctx, "app", new AppServlet()); + ctx.addServletMappingDecoded("/*", "app"); + tomcat.start(); + return tomcat.getConnector().getLocalPort(); + } + + private static int startJetty(boolean withListeners) throws Exception { + Server server = new Server(); + ServerConnector connector = new ServerConnector(server); + connector.setPort(0); + server.addConnector(connector); + ServletContextHandler ctx = new ServletContextHandler(ServletContextHandler.SESSIONS); + ctx.setContextPath("/"); + if (withListeners) { + ctx.getSessionHandler().addEventListener(new AppSessionListener()); + ctx.getSessionHandler().addEventListener(new AppSessionAttrListener()); + } + ctx.addServlet(new ServletHolder(new AppServlet()), "/*"); + server.setHandler(ctx); + server.start(); + if (server.getSessionIdManager() != null && server.getSessionIdManager().getSessionHouseKeeper() != null) { + server.getSessionIdManager().getSessionHouseKeeper().setIntervalSec(1L); + } + return connector.getLocalPort(); + } + + private static int startUndertow(boolean withListeners) throws Exception { + DeploymentInfo di = Servlets.deployment() + .setClassLoader(SessionExpiryApp.class.getClassLoader()) + .setContextPath("/") + .setDeploymentName("sess-expiry.war") + .setDefaultSessionTimeout(1) + .addServlet(Servlets.servlet("app", AppServlet.class).addMapping("/*")); + if (withListeners) { + di.addListener(new ListenerInfo(AppSessionListener.class)); + di.addListener(new ListenerInfo(AppSessionAttrListener.class)); + } + DeploymentManager manager = Servlets.defaultContainer().addDeployment(di); + manager.deploy(); + Undertow undertow = Undertow.builder() + .addHttpListener(0, "127.0.0.1") + .setHandler(Handlers.path().addPrefixPath("/", manager.start())) + .build(); + undertow.start(); + InetSocketAddress addr = (InetSocketAddress) undertow.getListenerInfo().get(0).getAddress(); + return addr.getPort(); + } +} diff --git a/keploy-sdk/src/test/java/org/example/servers/SessionExpiryTail.java b/keploy-sdk/src/test/java/org/example/servers/SessionExpiryTail.java new file mode 100644 index 00000000..0f1641e6 --- /dev/null +++ b/keploy-sdk/src/test/java/org/example/servers/SessionExpiryTail.java @@ -0,0 +1,18 @@ +package org.example.servers; + +/** + * Marker class touched by background session-expiry listeners in + * {@link SessionExpiryApp} so forked tests can verify listener execution. + */ +public final class SessionExpiryTail { + + private static volatile int hits; + + private SessionExpiryTail() { + } + + public static int hit() { + hits = hits + 1; + return hits; + } +} From f882094655ecef7748fe41885fefdd44157c0c9b Mon Sep 17 00:00:00 2001 From: slayerjain Date: Sun, 29 Nov 2026 15:29:04 +0530 Subject: [PATCH 2/2] fix(dedup): skip Undertow JSR-356 LogoutListener on exact class name Skip io.undertow.websockets.jsr.JsrWebSocketFilter$LogoutListener by exact class name on Servlet session-listener interfaces (matching Tomcat's WsSessionListener) so listener-free session expiries on Undertow deployments with WebSocket support (including Spring Boot's starter-undertow defaults) do not falsely contaminate overlapping windows or latch asyncExecutors=false. Subclasses remain tracked. Signed-off-by: slayerjain --- README.md | 2 +- .../java/io/keploy/dedup/RequestGate.java | 14 +++++--- .../keploy/dedup/SessionListenerHookTest.java | 32 +++++++++++++++++++ 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 4384623d..0092e85c 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Executor wrapping is **fail-closed**: only positively verified safe executors (e When Keploy is absent (no collector connected and no control command received), runtime request counting, executor wrapping, and job/listener tracking remain unarmed (zero-allocation static sentinel token, zero task wrapping); every armed window opened while any pre-arming request or job remains in flight (or within the tail window of an unarmed hand-off, plus the first armed window after unarmed traffic ran) is marked contaminated (`"armed-mid-flight"`). If a test records coverage probes while no Tomcat, Jetty, or Undertow request entry ran (for example on Netty/WebFlux, gRPC, Vert.x, Micronaut, JDK `HttpServer`, Armeria, Helidon, Play, or a server loaded before the agent), the record emits `"unverified":["no-server-entry"]` (omitted when empty, and kept separate from `"contaminated"` so older Enterprise collectors keep measuring uncounted servers while v3 collectors fail closed on any non-empty `"unverified"`). -A scheduled job or message listener that runs while a testcase runs puts its lines in that testcase's coverage: JaCoCo's probes do not say which thread hit them. The agent sees each run of a Quartz job (1.x and 2.x, and Spring's Quartz support), a Spring `@Scheduled` method, and Spring Kafka (`KafkaMessageListenerContainer$ListenerConsumer`), RabbitMQ (`AbstractMessageListenerContainer.doInvokeListener`), and JMS (`AbstractMessageListenerContainer.doInvokeListener`) message listeners. Background HTTP session listeners invoked outside any tracked request or job (such as container session-expiry timers firing `HttpSessionListener`, `HttpSessionAttributeListener`, `HttpSessionBindingListener`, `HttpSessionActivationListener`, `HttpSessionIdListener`, or container-native session listeners across Tomcat 8.5–11, Jetty 9.4–12.1 including `ee8`/`ee9`/`ee10`/`ee11`, and Undertow 2.2–2.3) are hooked alike: overlapping windows are marked `"session-listener:#"` and `asyncExecutors=false` is latched so dedup fails closed, while synchronous in-request `HttpSession.invalidate()` and listener-free session expiries (including Tomcat's default `WsSessionListener`) remain clean. A testcase whose window a run overlapped, from its `START` to the read of its probes at `END` (a job already running at the `START` counts), names the jobs and listeners in `"contaminated":["quartz:." | "scheduled:." | "kafka:@" | "listener:@" | "session-listener:#", ...]` after `windowCut`: at most 8 names, then `"+N"` for N more; left out when none ran. Listener attribution (topic/queue/destination and listener bean class) is inspected once per container instance and cached lock-free. The probes stay in the record; a Keploy that reads the key does not judge that testcase (an older one ignores the key). A job that ends before a `START` is not named: the `START` clears what it ran. The work a job's or listener's run hands to verified executors counts as a run of the same job, with the same name, from when the task starts until it returns or throws, whether or not `END` waits: so a testcase whose window the task runs in is named, even when the job itself returned before that testcase's `START`. Chained re-submissions inherit a 30 s budget from hop 1 so a self-resubmitting loop stops propagating attribution past its budget, while any expired handed-off task that is still executing continues marking overlapping windows `"job-tail:"` until it actually exits. `END` does not wait for it. Limits: work on custom unhooked messaging clients (plain `KafkaConsumer.poll`, `reactor-kafka`, Kafka Streams), a `java.util.Timer`, a Spring `SchedulingConfigurer` plain `Runnable`, a reactive/Kotlin `suspend` `@Scheduled` method, or external session-store adapters that dispatch Servlet session listeners outside the servlet container (such as Spring Session's `SessionEventHttpSessionListenerAdapter` / `HttpSessionAdapter`) is not seen. No job or listener run is seen when the agent was never started as a `-javaagent` in the JVM, nor when the target class loaded before the agent started. +A scheduled job or message listener that runs while a testcase runs puts its lines in that testcase's coverage: JaCoCo's probes do not say which thread hit them. The agent sees each run of a Quartz job (1.x and 2.x, and Spring's Quartz support), a Spring `@Scheduled` method, and Spring Kafka (`KafkaMessageListenerContainer$ListenerConsumer`), RabbitMQ (`AbstractMessageListenerContainer.doInvokeListener`), and JMS (`AbstractMessageListenerContainer.doInvokeListener`) message listeners. Background HTTP session listeners invoked outside any tracked request or job (such as container session-expiry timers firing `HttpSessionListener`, `HttpSessionAttributeListener`, `HttpSessionBindingListener`, `HttpSessionActivationListener`, `HttpSessionIdListener`, or container-native session listeners across Tomcat 8.5–11, Jetty 9.4–12.1 including `ee8`/`ee9`/`ee10`/`ee11`, and Undertow 2.2–2.3) are hooked alike: overlapping windows are marked `"session-listener:#"` and `asyncExecutors=false` is latched so dedup fails closed, while synchronous in-request `HttpSession.invalidate()` and listener-free session expiries (including Tomcat's default `WsSessionListener` and Undertow's JSR-356 `JsrWebSocketFilter$LogoutListener`, which Spring Boot's Undertow starter registers by default) remain clean. A testcase whose window a run overlapped, from its `START` to the read of its probes at `END` (a job already running at the `START` counts), names the jobs and listeners in `"contaminated":["quartz:." | "scheduled:." | "kafka:@" | "listener:@" | "session-listener:#", ...]` after `windowCut`: at most 8 names, then `"+N"` for N more; left out when none ran. Listener attribution (topic/queue/destination and listener bean class) is inspected once per container instance and cached lock-free. The probes stay in the record; a Keploy that reads the key does not judge that testcase (an older one ignores the key). A job that ends before a `START` is not named: the `START` clears what it ran. The work a job's or listener's run hands to verified executors counts as a run of the same job, with the same name, from when the task starts until it returns or throws, whether or not `END` waits: so a testcase whose window the task runs in is named, even when the job itself returned before that testcase's `START`. Chained re-submissions inherit a 30 s budget from hop 1 so a self-resubmitting loop stops propagating attribution past its budget, while any expired handed-off task that is still executing continues marking overlapping windows `"job-tail:"` until it actually exits. `END` does not wait for it. Limits: work on custom unhooked messaging clients (plain `KafkaConsumer.poll`, `reactor-kafka`, Kafka Streams), a `java.util.Timer`, a Spring `SchedulingConfigurer` plain `Runnable`, a reactive/Kotlin `suspend` `@Scheduled` method, or external session-store adapters that dispatch Servlet session listeners outside the servlet container (such as Spring Session's `SessionEventHttpSessionListenerAdapter` / `HttpSessionAdapter`) is not seen. No job or listener run is seen when the agent was never started as a `-javaagent` in the JVM, nor when the target class loaded before the agent started. Since 2.2.0 a testcase's record also names, in `"classMismatch":[className, ...]` after its probes, each class whose probes come from bytes other than the ones the agent indexed: a class loader that weaves the bytes it defines (load-time weaving) or an agent listed before JaCoCo's that does not ask to retransform changed the class before JaCoCo saw it, or the JVM loaded a multi-release jar's versioned copy. JaCoCo's id for such a class is not the CRC64 of the indexed bytes, so its probe indices do not belong to the indexed class, and Keploy must not read them against it. The key is left out when there is no such class. Of two copies of one class (loaded twice, from different bytes) that a testcase ran, the record reports the copy the agent indexed, else the one the coverage manifest already names, else the lowest class id compared as an unsigned number; a BACKGROUND record chooses alike, and names such classes in a `classMismatch` of its own. Every class id the agent writes (the coverage manifest's `id`) is 16 lowercase hex digits since 2.2.0; older agents wrote it unpadded, so read it as a hex number. 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 94d18c5e..c53d8866 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -110,12 +110,18 @@ public final class RequestGate { ))); // Exact container-internal Servlet session listener classes auto-registered - // by default container initializers (e.g. Tomcat's WsSci in Spring Boot and - // standalone Tomcat) skipped ONLY on exact class name (never subclasses) so - // listener-free session expiry does not falsely contaminate or latch. + // by default container initializers skipped ONLY on exact class name (never + // subclasses) so listener-free session expiry does not falsely contaminate or + // latch: Tomcat's WsSci (Spring Boot and standalone Tomcat) registers + // WsSessionListener; Undertow's JSR-356 Bootstrap (any deployment with a + // WebSocketDeploymentInfo, which Spring Boot's starter-undertow adds by + // default) registers JsrWebSocketFilter$LogoutListener, whose sessionDestroyed + // only queues close frames (WebSockets.sendClose, no callback) on the + // session's stored WebSocket channels (undertow-websockets-jsr 2.2.37 / 2.3.18). private static final Set INTERNAL_SERVLET_SESSION_LISTENERS = Collections.unmodifiableSet( new java.util.HashSet<>(java.util.Arrays.asList( - "org.apache.tomcat.websocket.server.WsSessionListener" + "org.apache.tomcat.websocket.server.WsSessionListener", + "io.undertow.websockets.jsr.JsrWebSocketFilter$LogoutListener" ))); // Timestamp of the last unarmed async hand-off (zero-allocation, zero // wrapping) so windows opened shortly after arming still carry 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 8388313b..24a696b0 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java @@ -254,6 +254,11 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE } else if ("org.example.CustomWsSessionListener".equals(name)) { raw = generateEmptySubclass("org/example/CustomWsSessionListener", "org/apache/tomcat/websocket/server/WsSessionListener"); + } else if ("io.undertow.websockets.jsr.JsrWebSocketFilter$LogoutListener".equals(name)) { + raw = generateEmptyClass("io/undertow/websockets/jsr/JsrWebSocketFilter$LogoutListener"); + } else if ("org.example.CustomUndertowLogoutListener".equals(name)) { + raw = generateEmptySubclass("org/example/CustomUndertowLogoutListener", + "io/undertow/websockets/jsr/JsrWebSocketFilter$LogoutListener"); } if (raw != null) { Class existing = findLoadedClass(name); @@ -291,6 +296,33 @@ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundE KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); RequestGate.exitSessionListener(wsSubTok); assertFalse("subclass of WsSessionListener must contaminate window", JobGate.close().isEmpty()); + + // Exact Undertow JSR-356 JsrWebSocketFilter$LogoutListener (registered by Undertow's + // websocket Bootstrap, by default in Spring Boot's starter-undertow) is skipped on + // Servlet interfaces, while a subclass MUST NOT be skipped. + Object uLogout = wsLoader.loadClass("io.undertow.websockets.jsr.JsrWebSocketFilter$LogoutListener") + .getDeclaredConstructor().newInstance(); + Object uLogoutSub = wsLoader.loadClass("org.example.CustomUndertowLogoutListener") + .getDeclaredConstructor().newInstance(); + + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + JobGate.open(); + assertNull("exact Undertow JsrWebSocketFilter$LogoutListener must be skipped on Servlet interface", + RequestGate.enterSessionListener(uLogout, "sessionDestroyed", false)); + assertFalse("skipping Undertow LogoutListener must not latch", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + assertTrue("skipping Undertow LogoutListener must not contaminate window", + JobGate.close().isEmpty()); + + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + JobGate.open(); + Object uLogoutSubTok = RequestGate.enterSessionListener(uLogoutSub, "sessionDestroyed", false); + assertNotNull("subclass of Undertow LogoutListener must NOT be skipped", uLogoutSubTok); + assertTrue("subclass of Undertow LogoutListener must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + RequestGate.exitSessionListener(uLogoutSubTok); + assertFalse("subclass of Undertow LogoutListener must contaminate window", + JobGate.close().isEmpty()); } finally { RequestGate.disarm(); KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch);