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 d95d010d..4035b886 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,21 @@ 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(); + private static final ThreadLocal UNARMED_THREAD_DEPTH = new ThreadLocal<>(); + + // 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" + ))); // 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. @@ -432,6 +447,8 @@ static void noteUnarmedActivity() { static Object enterUnarmed() { noteUnarmedActivity(); UNARMED_IN_FLIGHT.increment(); + Integer depth = UNARMED_THREAD_DEPTH.get(); + UNARMED_THREAD_DEPTH.set(depth == null ? Integer.valueOf(1) : Integer.valueOf(depth.intValue() + 1)); return UNARMED_TOKEN; } @@ -441,6 +458,17 @@ static boolean isUnarmedToken(Object token) { static void exitUnarmed() { UNARMED_IN_FLIGHT.decrement(); + Integer depth = UNARMED_THREAD_DEPTH.get(); + if (depth == null || depth.intValue() <= 1) { + UNARMED_THREAD_DEPTH.remove(); + } else { + UNARMED_THREAD_DEPTH.set(Integer.valueOf(depth.intValue() - 1)); + } + } + + static boolean isInsideUnarmedThread() { + Integer depth = UNARMED_THREAD_DEPTH.get(); + return depth != null && depth.intValue() > 0; } static long unarmedInFlight() { @@ -480,6 +508,7 @@ static void disarm() { unarmedEntered = false; pendingArmedMidFlight = false; lastUnarmedHandOffNanos = 0L; + UNARMED_THREAD_DEPTH.remove(); ARMED_MID_FLIGHT_CONSUMED.set(false); externalUntrackedTailPending = false; externalUntrackedTailExpiresAtNanos = 0L; @@ -5513,6 +5542,67 @@ 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 (isInsideUnarmedThread()) { + 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 9ab1ae4c..07e2a538 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"; @@ -626,6 +627,65 @@ 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" + ); + + 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"); + 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))); } @@ -639,6 +699,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; @@ -838,13 +901,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)) { @@ -854,7 +925,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); @@ -862,11 +933,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, @@ -878,7 +949,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 @@ -948,6 +1019,251 @@ 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) { + synchronized (sessionListenerHooked) { + Set names = sessionListenerHooked.get(loader); + return names != null && names.contains(className); + } + } + + private static boolean isSessionListenerPrimaryClass(String className) { + return SESSION_LISTENER_DISPATCH_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); @@ -1304,6 +1620,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..9dc844d1 --- /dev/null +++ b/keploy-sdk/src/test/java/io/keploy/dedup/SessionListenerHookTest.java @@ -0,0 +1,781 @@ +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(); + + // 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()); + } 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", + "jakarta/servlet/http/HttpSessionBindingListener", "valueUnbound", + "(Ljakarta/servlet/http/HttpSessionBindingEvent;)V", "1" }, + { "org/eclipse/jetty/ee8/nested/SessionHandler", + "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" }, + }; + + 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(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) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, internalName, null, "java/lang/Object", null); + 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(); + 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; + } +}