diff --git a/keploy-sdk/pom.xml b/keploy-sdk/pom.xml index 12690bdd..cabdebbe 100644 --- a/keploy-sdk/pom.xml +++ b/keploy-sdk/pom.xml @@ -370,6 +370,94 @@ + + copy-jetty11 + generate-test-resources + + copy + + + ${skipTests} + ${project.build.directory}/jetty11 + + org.eclipse.jettyjetty-servlet11.0.24 + org.eclipse.jettyjetty-security11.0.24 + org.eclipse.jettyjetty-server11.0.24 + org.eclipse.jettyjetty-http11.0.24 + org.eclipse.jettyjetty-io11.0.24 + org.eclipse.jettyjetty-util11.0.24 + org.eclipse.jetty.toolchainjetty-jakarta-servlet-api5.0.2 + org.slf4jslf4j-api2.0.9 + + + + + copy-jetty12 + generate-test-resources + + copy + + + ${skipTests} + ${project.build.directory}/jetty12 + + org.eclipse.jetty.ee10jetty-ee10-servlet12.0.16 + org.eclipse.jettyjetty-security12.0.16 + org.eclipse.jettyjetty-session12.0.16 + org.eclipse.jettyjetty-server12.0.16 + org.eclipse.jettyjetty-http12.0.16 + org.eclipse.jettyjetty-io12.0.16 + org.eclipse.jettyjetty-util12.0.16 + jakarta.servletjakarta.servlet-api6.0.0 + org.slf4jslf4j-api2.0.16 + + + + + copy-jetty121 + generate-test-resources + + copy + + + ${skipTests} + ${project.build.directory}/jetty121 + + org.eclipse.jetty.ee11jetty-ee11-servlet12.1.15 + org.eclipse.jettyjetty-security12.1.15 + org.eclipse.jettyjetty-session12.1.15 + org.eclipse.jettyjetty-server12.1.15 + org.eclipse.jettyjetty-http12.1.15 + org.eclipse.jettyjetty-io12.1.15 + org.eclipse.jettyjetty-util12.1.15 + jakarta.servletjakarta.servlet-api6.1.0 + org.slf4jslf4j-api2.0.16 + + + + + copy-undertow23 + generate-test-resources + + copy + + + ${skipTests} + ${project.build.directory}/undertow23 + + io.undertowundertow-servlet2.3.18.Final + io.undertowundertow-core2.3.18.Final + org.jboss.xnioxnio-api3.8.16.Final + org.jboss.xnioxnio-nio3.8.16.Final + org.jboss.threadsjboss-threads3.5.0.Final + org.jboss.loggingjboss-logging3.4.3.Final + org.wildfly.commonwildfly-common1.5.4.Final + org.wildfly.clientwildfly-client-config1.0.1.Final + jakarta.servletjakarta.servlet-api6.0.0 + jakarta.annotationjakarta.annotation-api2.1.1 + + + 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..fd8e93f4 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/RequestGate.java @@ -216,6 +216,11 @@ private static boolean declaresCfMethod(Class type, String name, Class... // for worker growth or SimpleAsyncTaskExecutor). private static final ThreadLocal TRACKED_DISPATCH_DEPTH = new ThreadLocal<>(); + // Scoped depth > 0 on the current thread while inside an unarmed + // RequestGate.enter()..exit() (e.g., an HTTP request arriving on Undertow's + // Connectors.executeRootHandler before a collector connects). + private static final ThreadLocal UNARMED_REQUEST_DEPTH = new ThreadLocal<>(); + // Weak identity set of Keploy's own agent-internal pools (e.g. ProbeScan's // scan pool) so agent work never false-latches JDK sinks. private static final ConcurrentHashMap AGENT_INTERNAL_POOLS = @@ -356,6 +361,63 @@ static void handleUntrackedSink(String sink, Object receiver, Object task, Strin } } + /** + * Entry-point guard injected by {@link ServerEntries} into server-owned + * executor, scheduler, and abstract timeout sinks (Jetty's + * {@code QueuedThreadPool}, {@code ExecutorThreadPool}, + * {@code MonitoredQueuedThreadPool}, {@code ReservedThreadExecutor}, + * {@code TryExecutor$NoTryExecutor}, {@code ScheduledExecutorScheduler}, + * {@code TimerScheduler}, {@code CyclicTimeout}, {@code CyclicTimeouts}, + * {@code IdleTimeout}; Undertow's {@code PipeliningExecutor}; and XNIO's + * {@code WorkerThread}) whose queues bypass JDK sinks or sit in + * {@code SinkAllowlist.SERVER_POOL_CALLERS}. + * + *

Only already-tracked {@link Hand} tasks or exact, cited internal server + * caller frames (and exact internal subclasses for Jetty's public abstract + * timeout bases) in {@link SinkAllowlist} pass cleanly; any unlisted caller + * — including public server forwarding APIs, library callers, or reflective + * hand-offs — contaminates the active window and latches + * {@code asyncExecutors=false} so no task can escape silently. + * + * @param sinkName exact binary name of the hooked server executor/timer sink + * @param receiver sink instance ({@code this}) used to validate exact + * internal subclasses for abstract Jetty timeout bases + * @param task submitted runnable/task (checked for existing {@link Hand} + * tracking), or {@code null} for no-task timer sinks + */ + public static void onServerExecutorSink(String sinkName, Object receiver, Object task) { + if (isTrackedDispatchActive() || isTrackedTask(task)) { + return; + } + String callerFrame = SinkAllowlist.firstExternalCallerFrameSkipping(sinkName); + boolean allowed = SinkAllowlist.isAllowedServerExecutorCaller(sinkName, callerFrame, receiver, task); + SinkAllowlist.audit("server-exec:" + sinkName, allowed, "caller", receiver, task, callerFrame); + if (allowed) { + return; + } + String target = callerFrame != null ? callerFrame + : (receiver != null ? receiver.getClass().getName() + : (task != null ? task.getClass().getName() : "unknown")); + String reason = "untracked-sink:server-executor:" + sinkName + ":" + target; + if (!armed) { + noteUnarmedHandOffIfInFlight(); + noteBackgroundWorkerOutsideWindow(reason, false); + return; + } + Window window = INSIDE.get(); + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + noteBackgroundWorkerOutsideWindow(reason, true); + return; + } + if (task instanceof Future) { + noteTrackedUntrackedAsync(reason, task, false); + } else { + noteUntrackedAsync(reason, 0L); + } + KeployDedupAgent.noteObservedUntrackedAsyncLibrary("untracked async server executor (" + reason + ")", true); + } + // Lock-free weak identity map from submitted Future -> WeakReference, // explicitly removed on BOTH Hand.enter() and Hand.finishRelease(), so // self-referencing patterns (job.future = exec.submit(job)) can never leak @@ -432,6 +494,8 @@ static void noteUnarmedActivity() { static Object enterUnarmed() { noteUnarmedActivity(); UNARMED_IN_FLIGHT.increment(); + Integer cur = UNARMED_REQUEST_DEPTH.get(); + UNARMED_REQUEST_DEPTH.set(cur == null ? Integer.valueOf(1) : Integer.valueOf(cur.intValue() + 1)); return UNARMED_TOKEN; } @@ -440,9 +504,20 @@ static boolean isUnarmedToken(Object token) { } static void exitUnarmed() { + Integer cur = UNARMED_REQUEST_DEPTH.get(); + if (cur == null || cur.intValue() <= 1) { + UNARMED_REQUEST_DEPTH.remove(); + } else { + UNARMED_REQUEST_DEPTH.set(Integer.valueOf(cur.intValue() - 1)); + } UNARMED_IN_FLIGHT.decrement(); } + static boolean isInsideUnarmedRequest() { + Integer cur = UNARMED_REQUEST_DEPTH.get(); + return cur != null && cur.intValue() > 0; + } + static long unarmedInFlight() { return UNARMED_IN_FLIGHT.sum(); } @@ -621,6 +696,74 @@ public static Runnable handAsyncContext(Runnable task) { return handed; } + /** + * Wraps a {@link Runnable} dispatched onto Undertow's {@code org.xnio.XnioWorker} + * so both Undertow's own I/O-to-worker request dispatch (from hooked + * {@code Connectors.executeRootHandler}) and in-request {@code XnioWorker.execute} + * calls hold the active request window's permit. Any call outside an active + * request window, tracked job, or unarmed server request fails closed by + * latching {@code asyncExecutors=false}. + * + * @param task runnable passed to {@code XnioWorker.execute(Runnable)} + * @return wrapped runnable holding the window permit, or {@code task} unchanged + */ + public static Runnable handXnioWorker(Runnable task) { + if (task == null) { + return null; + } + if (!armed) { + noteUnarmedHandOffIfInFlight(); + if (!isInsideUnarmedRequest()) { + noteBackgroundWorkerOutsideWindow("untracked-async:xnio-worker-outside-window", false); + } + return task; + } + if (task instanceof Hand) { + return task; + } + Window window = INSIDE.get(); + JobGate.Attribution job = currentOrExpiredJob(window); + if (window == null && job == null) { + noteBackgroundWorkerOutsideWindow("untracked-async:xnio-worker-outside-window", true); + return task; + } + Handed handed = task instanceof Future + ? new HandedFuture(window, job, task, false) + : new Handed(window, job, task, false); + if (window != null) { + window.running.incrementAndGet(); + } + return handed; + } + + /** + * Enters a tracked dispatch scope around {@code XnioWorker.execute} only when + * the dispatch carries a proven {@link Hand} permit (or belongs to an unarmed + * server request inside {@code Connectors.executeRootHandler}). Outside-window + * calls return {@code false} so downstream JDK sinks still fail closed. + * + * @param handed task returned by {@link #handXnioWorker(Runnable)} + * @return {@code true} if a tracked dispatch scope was entered + */ + public static boolean enterXnioWorkerDispatch(Object handed) { + if (handed instanceof Hand || (!armed && isInsideUnarmedRequest())) { + enterTrackedDispatch(); + return true; + } + return false; + } + + /** + * Exits the tracked dispatch scope entered by {@link #enterXnioWorkerDispatch(Object)}. + * + * @param entered value returned by {@link #enterXnioWorkerDispatch(Object)} + */ + public static void exitXnioWorkerDispatch(boolean entered) { + if (entered) { + exitTrackedDispatch(); + } + } + private static JobGate.Attribution currentOrExpiredJob(Window window) { if (window != null) { return null; @@ -3290,7 +3433,9 @@ public static void noteIfUntrackedExecutor(Object receiver) { if (!(receiver instanceof Executor)) { return; } - if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + if (OrderedPools.isInlineExecutor(receiver) + || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver) + || ServerEntries.isHookedXnioWorker(receiver)) { return; } if (!armed) { @@ -3319,7 +3464,9 @@ public static void noteIfUntrackedSubmit(Object receiver) { && !OrderedPools.isSpringAsyncTaskExecutor(receiver)) { return; } - if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + if (OrderedPools.isInlineExecutor(receiver) + || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver) + || ServerEntries.isHookedXnioWorker(receiver)) { return; } if (!armed) { @@ -3385,10 +3532,11 @@ private static void noteExecutorHandOffOutsideWindow(Object executor, boolean is noteBackgroundWorkerOutsideWindow("untracked-async:executor-outside-window", isArmed); } - private static void noteBackgroundWorkerOutsideWindow(String reason, boolean isArmed) { + // Always latches asyncExecutors=false; logAsInfo only chooses INFO vs FINE log level. + private static void noteBackgroundWorkerOutsideWindow(String reason, boolean logAsInfo) { String label = (reason == null || reason.isEmpty()) ? "background-worker" : reason; KeployDedupAgent.noteObservedUntrackedAsyncLibrary( - "app background worker/scheduler started outside request window (" + label + ")", isArmed); + "app background worker/scheduler started outside request window (" + label + ")", logAsInfo); } private static void recordUntrackedMethodRef(String reason, String target) { @@ -3419,7 +3567,9 @@ public static void noteIfUntrackedExecutorMethodRef(Object receiver) { if (!(receiver instanceof Executor)) { return; } - if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + if (OrderedPools.isInlineExecutor(receiver) + || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver) + || ServerEntries.isHookedXnioWorker(receiver)) { return; } String name = receiver.getClass().getName(); @@ -3444,7 +3594,9 @@ public static void noteIfUntrackedSubmitMethodRef(Object receiver) { && !OrderedPools.isSpringAsyncTaskExecutor(receiver)) { return; } - if (OrderedPools.isInlineExecutor(receiver) || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver)) { + if (OrderedPools.isInlineExecutor(receiver) + || OrderedPools.isHookedAndVerifiedSpringExecutor(receiver) + || ServerEntries.isHookedXnioWorker(receiver)) { return; } String name = receiver.getClass().getName(); 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..3be9b217 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/ServerEntries.java @@ -54,6 +54,8 @@ final class ServerEntries implements ClassFileTransformer { 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"; + private static final String XNIO_WORKER = "org/xnio/XnioWorker"; + private static final String XNIO_EXECUTE_DESC = "(Ljava/lang/Runnable;)V"; private static final String RUNNABLE = "Ljava/lang/Runnable;"; private static final String CALLABLE = "Ljava/util/concurrent/Callable;"; // The type of the executor a task is for, when a method takes it as an @@ -126,12 +128,91 @@ final class ServerEntries implements ClassFileTransformer { "caffeine-async-cache", "get", "getAll", "put"); addLatchOnCall("org/springframework/cache/concurrent/ConcurrentMapCache", "spring-async-cache", "retrieve"); + // Jetty 11/12 interfaces & helpers loaded on every server startup whose + // static dispatch helpers are never invoked during normal HTTP requests; + // fail closed immediately on call if any app or container path uses them. + // Note: LATCH_ON_CALL skips the load-time constant-pool scan for the + // class as a whole so only the named methods latch; for all 6 classes + // below, any other method that touches a JDK executor is still guarded + // at runtime by the JDK sink bridge. + addLatchOnCall("org/eclipse/jetty/util/component/Graceful", + "jetty-graceful-shutdown", "shutdown"); + addLatchOnCall("org/eclipse/jetty/util/VirtualThreads", + "jetty-virtual-threads", "executeOnVirtualThread"); + addLatchOnCall("org/eclipse/jetty/util/thread/ThreadPool", + "jetty-immediate-executor", "executeImmediately"); + addLatchOnCall("org/eclipse/jetty/util/thread/Invocable$InvocationType$1", + "jetty-invocable-blocking", "runWithoutBlocking"); + // Undertow JSR-356 WebSocket container auto-loaded by Spring Boot's + // Undertow starter even on pure HTTP apps; latch on first WebSocket use. + addLatchOnCall("io/undertow/websockets/jsr/ServerWebSocketContainer", + "undertow-websocket", "invokeEndpointMethod", "addEndpoint"); + // Spring Framework 6 reactive multipart reader auto-loaded during Spring + // Boot 3 Servlet MVC autoconfig; latch on first reactive multipart call. + addLatchOnCall("org/springframework/http/codec/multipart/DefaultPartHttpMessageReader", + "spring-reactive-multipart", "read", "setBlockingOperationScheduler"); } private static void addLatchOnCall(String className, String label, String... methods) { LATCH_ON_CALL.put(className, new LatchEntry(label, new HashSet<>(Arrays.asList(methods)))); } + // Server-owned executor/scheduler sinks whose internal queues bypass JDK + // concurrency sinks or sit in SinkAllowlist.SERVER_POOL_CALLERS. Hooked at + // method entry with RequestGate.onServerExecutorSink so internal server + // callers pass while app, library, and reflective callers fail closed. + private static final class ServerExecutorSinkEntry { + final String sinkName; + final Set methods; + // null: hook the named methods whose first parameter is the Runnable handed off. + // Otherwise: hook only the named methods with exactly this descriptor, which take no + // Runnable task (the work is the receiver's own callback), and pass a null task to the gate. + final String noTaskDesc; + + ServerExecutorSinkEntry(String sinkName, Set methods, String noTaskDesc) { + this.sinkName = sinkName; + this.methods = methods; + this.noTaskDesc = noTaskDesc; + } + } + + private static final Map SERVER_EXECUTOR_SINKS = new HashMap<>(); + + static { + addServerExecutorSink("org/eclipse/jetty/util/thread/QueuedThreadPool", "execute", "tryExecute"); + addServerExecutorSink("org/eclipse/jetty/util/thread/MonitoredQueuedThreadPool", "execute"); + addServerExecutorSink("org/eclipse/jetty/util/thread/ExecutorThreadPool", "execute", "tryExecute"); + addServerExecutorSink("org/eclipse/jetty/util/thread/ReservedThreadExecutor", "execute", "tryExecute"); + addServerExecutorSink("org/eclipse/jetty/util/thread/TryExecutor$NoTryExecutor", "execute"); + addServerExecutorSink("org/eclipse/jetty/util/thread/ScheduledExecutorScheduler", "schedule"); + addServerExecutorSink("org/eclipse/jetty/util/thread/TimerScheduler", "schedule"); + // Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15 jetty-io CyclicTimeout.java: public abstract + // timer whose schedule(long, TimeUnit) arms a Wakeup on the connector Scheduler that later + // invokes the subclass's onTimeoutExpired() on a scheduler thread. + SERVER_EXECUTOR_SINKS.put("org/eclipse/jetty/io/CyclicTimeout", new ServerExecutorSinkEntry( + "org.eclipse.jetty.io.CyclicTimeout", + new HashSet<>(Arrays.asList("schedule")), "(JLjava/util/concurrent/TimeUnit;)Z")); + // Jetty 11.0.24 / 12.0.16 / 12.1.15 jetty-io CyclicTimeouts.java: public abstract container + // whose schedule(Expirable) delegates to an internal CyclicTimeout$Wakeup and invokes the + // subclass's onExpired(Expirable) on a scheduler thread. + SERVER_EXECUTOR_SINKS.put("org/eclipse/jetty/io/CyclicTimeouts", new ServerExecutorSinkEntry( + "org.eclipse.jetty.io.CyclicTimeouts", + new HashSet<>(Arrays.asList("schedule")), "(Lorg/eclipse/jetty/io/CyclicTimeouts$Expirable;)V")); + // Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15 jetty-io IdleTimeout.java: public abstract + // timer whose private scheduleIdleTimeout(long) arms IdleTimeout$1 on the Scheduler and + // later invokes the subclass's onIdleExpired(TimeoutException) on a scheduler thread. + SERVER_EXECUTOR_SINKS.put("org/eclipse/jetty/io/IdleTimeout", new ServerExecutorSinkEntry( + "org.eclipse.jetty.io.IdleTimeout", + new HashSet<>(Arrays.asList("scheduleIdleTimeout")), "(J)V")); + addServerExecutorSink("io/undertow/util/PipeliningExecutor", "execute"); + addServerExecutorSink("org/xnio/nio/WorkerThread", "execute", "executeAfter", "executeAtInterval"); + } + + private static void addServerExecutorSink(String internalName, String... methods) { + SERVER_EXECUTOR_SINKS.put(internalName, new ServerExecutorSinkEntry( + internalName.replace('/', '.'), new HashSet<>(Arrays.asList(methods)), null)); + } + // Classes of servers that are not counted, so that the log can name them // and HELLO/caps can report windowCut=false. private static final Map UNCOUNTED = new HashMap<>(); @@ -361,6 +442,10 @@ private static Map> buildDispatchPrimitiveMethods() { "org/eclipse/jetty/io/SelectorManager", "org/eclipse/jetty/io/ssl/SslConnection$DecryptedEndPoint", "org/eclipse/jetty/io/ssl/SslConnection$DecryptedEndPoint$IncompleteWriteCallback", + // Jetty 12.0.16 (jetty-io, SslConnection.java): Jetty 12 rename of DecryptedEndPoint + // & IncompleteWriteCallback; dispatches TLS handshake/fill/flush callbacks on Jetty's pool. + "org/eclipse/jetty/io/ssl/SslConnection$SslEndPoint", + "org/eclipse/jetty/io/ssl/SslConnection$SslEndPoint$IncompleteWriteCallback", "org/eclipse/jetty/server/AbstractConnector", "org/eclipse/jetty/server/AsyncRequestLogWriter", "org/eclipse/jetty/server/AsyncRequestLogWriter$WriterThread", @@ -368,14 +453,28 @@ private static Map> buildDispatchPrimitiveMethods() { "org/eclipse/jetty/server/HttpConnection", "org/eclipse/jetty/server/HttpInput", "org/eclipse/jetty/server/ShutdownMonitor", + // Jetty 12.1.0 (jetty-server, ShutdownService.java): Jetty 12.1 replacement for + // ShutdownMonitor; runs container shutdown lifecycle only, zero user callbacks. + "org/eclipse/jetty/server/ShutdownService", "org/eclipse/jetty/server/handler/ShutdownHandler$1", + // Jetty 12.0.16 (jetty-server, internal/HttpConnection.java): Jetty 12 relocation of + // HttpConnection & its HTTP/1 stream handler; servlet requests enter hooked ServletChannel. + "org/eclipse/jetty/server/internal/HttpConnection", + "org/eclipse/jetty/server/internal/HttpConnection$HttpStreamOverHTTP1", "org/eclipse/jetty/util/thread/ExecutorThreadPool", "org/eclipse/jetty/util/thread/QueuedThreadPool", "org/eclipse/jetty/util/thread/ReservedThreadExecutor", "org/eclipse/jetty/util/thread/ScheduledExecutorScheduler", + // Jetty 12.0.16 (jetty-util, SerializedInvoker.java): internal channel-state callback + // serializer used by HttpChannelState$HttpChannelSerializedInvoker; non-Jetty executors + // remain guarded by the JDK sink bridge. + "org/eclipse/jetty/util/thread/SerializedInvoker$Link", "org/eclipse/jetty/util/thread/ShutdownThread", "org/eclipse/jetty/util/thread/TimerScheduler", "org/eclipse/jetty/util/thread/TryExecutor$NoTryExecutor", + // Jetty 11.0.24 / 12.0.16 (jetty-util, AdaptiveExecutionStrategy.java): Jetty 10+ + // replacement for EatWhatYouKill; dispatches connector I/O onto Jetty's QueuedThreadPool. + "org/eclipse/jetty/util/thread/strategy/AdaptiveExecutionStrategy", "org/eclipse/jetty/util/thread/strategy/EatWhatYouKill", "org/eclipse/jetty/util/thread/strategy/ExecuteProduceConsume", "org/eclipse/jetty/util/thread/strategy/ProduceConsume", @@ -432,13 +531,22 @@ private static Map> buildDispatchPrimitiveMethods() { "io/micrometer/core/instrument/HighCardinalityTagsDetector", "org/springframework/beans/factory/support/DefaultListableBeanFactory", "org/springframework/boot/actuate/context/ShutdownEndpoint", + // Spring Boot 3.4.5 (spring-boot-autoconfigure, BackgroundPreinitializer.java:55-120): + // Spring Boot 3.x counterpart of BackgroundPreinitializingApplicationListener; spawns + // one joined "background-preinit" thread warming built-in initializers, zero user callbacks. + "org/springframework/boot/autoconfigure/BackgroundPreinitializer", "org/springframework/boot/autoconfigure/condition/OnClassCondition$ThreadedOutcomesResolver", "org/springframework/boot/autoconfigure/preinitialize/BackgroundPreinitializingApplicationListener", "org/springframework/boot/autoconfigure/ssl/FileWatcher$WatcherThread", "org/springframework/boot/context/metrics/buffering/BufferingApplicationStartup", + // Spring Boot 4.x (spring-boot-jetty, GracefulShutdown.java) & Spring Boot 3.4.5 + // (spring-boot, web/embedded/jetty/GracefulShutdown.java:50-75): spawns one + // "jetty-shutdown" thread closing Jetty connectors at shutdown, zero user callbacks. + "org/springframework/boot/jetty/GracefulShutdown", "org/springframework/boot/tomcat/GracefulShutdown", "org/springframework/boot/tomcat/TomcatWebServer", "org/springframework/boot/tomcat/TomcatWebServer$1", + "org/springframework/boot/web/embedded/jetty/GracefulShutdown", "org/springframework/boot/web/embedded/tomcat/GracefulShutdown", "org/springframework/boot/web/embedded/tomcat/TomcatWebServer", "org/springframework/boot/web/embedded/tomcat/TomcatWebServer$1", @@ -474,6 +582,7 @@ static Set allowlistedDispatchClasses() { private static final Set SEEN_UNHOOKED_CONSUMERS = new CopyOnWriteArraySet<>(); private static final Set SEEN_UNHOOKED_ASYNC_DISPATCHERS = new CopyOnWriteArraySet<>(); private static final Set HOOKED_SPRING_CLASSES = new CopyOnWriteArraySet<>(); + private static final Map HOOKED_XNIO_WORKER_LOADERS = new WeakHashMap<>(); private static volatile boolean serverHookFailed; private static volatile boolean listenerHookFailed; private static volatile boolean asyncHookFailed; @@ -560,7 +669,8 @@ static Set allowlistedDispatchClasses() { "addListener", "addCallback", "transform", "transformAsync", "catching", "catchingAsync", "poll", "basicConsume", "receive", "setMessageListener", "offer", "put", "transfer", "tryTransfer", - "send", "sendDefault", "convertAndSend", "convertSendAndReceive", "sendAndReceive"))); + "send", "sendDefault", "convertAndSend", "convertSendAndReceive", "sendAndReceive", + "executeAfter", "executeAtInterval"))); // CompletableFuture *Async instance methods rewritten to RequestGate. private static final Map> CF_ASYNC_INSTANCE_METHODS = @@ -714,6 +824,38 @@ static boolean isSpringExecutorHooked(String binaryClassName) { return HOOKED_SPRING_CLASSES.contains(binaryClassName); } + static boolean isHookedXnioWorker(Object receiver) { + if (receiver == null || asyncHookFailed) { + return false; + } + Class cls = receiver.getClass(); + Class xnioBase = null; + for (Class c = cls; c != null && c != Object.class; c = c.getSuperclass()) { + if ("org.xnio.XnioWorker".equals(c.getName())) { + xnioBase = c; + break; + } + } + if (xnioBase == null) { + return false; + } + boolean hooked; + synchronized (HOOKED_XNIO_WORKER_LOADERS) { + hooked = Boolean.TRUE.equals(HOOKED_XNIO_WORKER_LOADERS.get(xnioBase.getClassLoader())); + } + if (!hooked) { + return false; + } + try { + return cls.getMethod("execute", Runnable.class).getDeclaringClass() == xnioBase + && cls.getMethod("submit", Runnable.class).getDeclaringClass() == java.util.concurrent.AbstractExecutorService.class + && cls.getMethod("submit", Runnable.class, Object.class).getDeclaringClass() == java.util.concurrent.AbstractExecutorService.class + && cls.getMethod("submit", java.util.concurrent.Callable.class).getDeclaringClass() == java.util.concurrent.AbstractExecutorService.class; + } catch (Throwable ignored) { + return false; + } + } + static void markSpringExecutorHookedForTests(String binaryClassName) { HOOKED_SPRING_CLASSES.add(binaryClassName); } @@ -822,9 +964,16 @@ public byte[] transform(ClassLoader loader, String className, Class classBein if (SPRING_EVENT_MULTICASTER.equals(className)) { return hookSpringEventMulticaster(loader, className, classfileBuffer); } + if (XNIO_WORKER.equals(className)) { + return hookXnioWorker(loader, className, protectionDomain, classfileBuffer); + } LatchEntry latchEntry = LATCH_ON_CALL.get(className); if (latchEntry != null) { - return hookLatchOnCall(loader, className, classfileBuffer, latchEntry); + return hookLatchOnCall(loader, className, protectionDomain, classfileBuffer, latchEntry); + } + ServerExecutorSinkEntry sinkEntry = SERVER_EXECUTOR_SINKS.get(className); + if (sinkEntry != null) { + return hookServerExecutorSink(loader, className, protectionDomain, classfileBuffer, sinkEntry); } Entry entry = ENTRIES.get(className); if (entry == null) { @@ -1244,6 +1393,160 @@ public void visitEnd() { return targetHolder[0] == null ? null : writer.toByteArray(); } + private byte[] hookXnioWorker(ClassLoader loader, String className, ProtectionDomain protectionDomain, + byte[] classfileBuffer) { + String name = className.replace('/', '.'); + try { + if (!canAccessGate(loader, protectionDomain)) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup cannot hook XnioWorker.execute on " + name + + ": its loader/module cannot access keploy-sdk.jar"); + return null; + } + if (carriesXnioWorkerExecuteChange(classfileBuffer)) { + synchronized (changed) { + Set names = changed.get(loader); + if (names == null) { + names = new HashSet<>(); + changed.put(loader, names); + } + names.add(className); + } + synchronized (HOOKED_XNIO_WORKER_LOADERS) { + HOOKED_XNIO_WORKER_LOADERS.put(loader, Boolean.TRUE); + } + return null; + } + byte[] wrapped = wrapXnioWorkerExecute(classfileBuffer); + if (wrapped == null) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not wrap execute(Runnable) on " + name); + return null; + } + synchronized (changed) { + Set names = changed.get(loader); + if (names == null) { + names = new HashSet<>(); + changed.put(loader, names); + } + names.add(className); + } + synchronized (HOOKED_XNIO_WORKER_LOADERS) { + HOOKED_XNIO_WORKER_LOADERS.put(loader, Boolean.TRUE); + } + LOGGER.log(Level.INFO, "Keploy dedup counts Undertow XNIO worker tasks (" + name + ")"); + return wrapped; + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not hook XnioWorker.execute on " + name, t); + return null; + } + } + + static boolean carriesXnioWorkerExecuteChange(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 ((ASYNC_RENAMED + "execute").equals(name) && XNIO_EXECUTE_DESC.equals(descriptor)) { + carries[0] = true; + } + return null; + } + }, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); + return carries[0]; + } + + static byte[] wrapXnioWorkerExecute(byte[] classfile) { + ClassReader reader = new ClassReader(classfile); + ClassWriter writer = new ClassWriter(reader, 0); + final String[] ownerHolder = {null}; + final int[] versionHolder = {0}; + final Method[] targetHolder = {null}; + 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) { + if ("execute".equals(name) && XNIO_EXECUTE_DESC.equals(descriptor) + && (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE | Opcodes.ACC_STATIC + | Opcodes.ACC_BRIDGE | Opcodes.ACC_SYNTHETIC)) == 0) { + targetHolder[0] = new Method(access, name, descriptor, signature, exceptions); + int renamedAccess = (access & ~(Opcodes.ACC_PUBLIC | Opcodes.ACC_PROTECTED)) + | Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC; + return super.visitMethod(renamedAccess, ASYNC_RENAMED + name, descriptor, signature, exceptions); + } + return super.visitMethod(access, name, descriptor, signature, exceptions); + } + + @Override + public void visitEnd() { + Method method = targetHolder[0]; + if (method != null) { + int access = method.access & ~Opcodes.ACC_SYNCHRONIZED; + MethodVisitor mv = super.visitMethod(access, method.name, method.descriptor, + method.signature, method.exceptions); + mv.visitCode(); + Label start = new Label(); + Label end = new Label(); + Label thrown = new Label(); + mv.visitTryCatchBlock(start, end, thrown, null); + + // Runnable handed = RequestGate.handXnioWorker(r); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "handXnioWorker", + "(Ljava/lang/Runnable;)Ljava/lang/Runnable;", false); + mv.visitVarInsn(Opcodes.ASTORE, 2); + // boolean tracked = RequestGate.enterXnioWorkerDispatch(handed); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "enterXnioWorkerDispatch", + "(Ljava/lang/Object;)Z", false); + mv.visitVarInsn(Opcodes.ISTORE, 3); + mv.visitLabel(start); + // this.keploy$async$execute(handed); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitMethodInsn(Opcodes.INVOKESPECIAL, ownerHolder[0], ASYNC_RENAMED + method.name, + method.descriptor, false); + mv.visitLabel(end); + // RequestGate.exitXnioWorkerDispatch(tracked); + mv.visitVarInsn(Opcodes.ILOAD, 3); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "exitXnioWorkerDispatch", + "(Z)V", false); + mv.visitInsn(Opcodes.RETURN); + + mv.visitLabel(thrown); + if (versionHolder[0] >= Opcodes.V1_6) { + mv.visitFrame(Opcodes.F_FULL, 4, + new Object[] {ownerHolder[0], "java/lang/Runnable", "java/lang/Runnable", + Opcodes.INTEGER}, + 1, new Object[] {"java/lang/Throwable"}); + } + mv.visitVarInsn(Opcodes.ILOAD, 3); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "exitXnioWorkerDispatch", + "(Z)V", false); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, "dropped", + "(Ljava/lang/Object;Ljava/lang/Object;)V", false); + mv.visitInsn(Opcodes.ATHROW); + mv.visitMaxs(3, 4); + mv.visitEnd(); + } + super.visitEnd(); + } + }, 0); + return targetHolder[0] == null ? null : writer.toByteArray(); + } + private boolean wasRewritten(ClassLoader loader, String className) { if (!shouldRewriteExecutorCalls(className)) { return false; @@ -1270,6 +1573,21 @@ private byte[] changedAgain(ClassLoader loader, String className, byte[] classfi return null; } } + if (XNIO_WORKER.equals(className)) { + synchronized (changed) { + Set names = changed.get(loader); + if (names == null || !names.contains(className)) { + return null; + } + } + try { + return carriesXnioWorkerExecuteChange(classfile) ? null : wrapXnioWorkerExecute(classfile); + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not re-hook " + className, t); + return null; + } + } LatchEntry latchEntry = LATCH_ON_CALL.get(className); if (latchEntry != null) { synchronized (changed) { @@ -1286,6 +1604,28 @@ private byte[] changedAgain(ClassLoader loader, String className, byte[] classfi return null; } } + ServerExecutorSinkEntry sinkEntry = SERVER_EXECUTOR_SINKS.get(className); + if (sinkEntry != null) { + synchronized (changed) { + Set names = changed.get(loader); + if (names == null || !names.contains(className)) { + return null; + } + } + try { + byte[] rehooked = wrapServerExecutorSink(classfile, sinkEntry); + if (rehooked == null) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not re-hook " + className + + ": none of " + sinkEntry.methods + " found"); + } + return rehooked; + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not re-hook " + className, t); + return null; + } + } Entry entry = ENTRIES.get(className); if (entry == null) { byte[] currentBytes = classfile; @@ -1623,14 +1963,14 @@ static boolean hasExecutorReference(ClassReader reader) { return false; } - private byte[] hookLatchOnCall(ClassLoader loader, String className, byte[] classfileBuffer, - LatchEntry latchEntry) { + private byte[] hookLatchOnCall(ClassLoader loader, String className, ProtectionDomain protectionDomain, + byte[] classfileBuffer, LatchEntry latchEntry) { String name = className.replace('/', '.'); try { - if (!seesGate(loader)) { + if (!canAccessGate(loader, protectionDomain)) { asyncHookFailed = true; LOGGER.log(Level.WARNING, "Keploy dedup cannot hook " + name - + ": its class loader does not see keploy-sdk.jar", (Throwable) null); + + ": its loader/module cannot access keploy-sdk.jar", (Throwable) null); return null; } byte[] wrapped = wrapLatchOnCall(classfileBuffer, latchEntry); @@ -1714,6 +2054,103 @@ public void visitMaxs(int maxStack, int maxLocals) { return alreadyHooked[0] ? classfile : writer.toByteArray(); } + private byte[] hookServerExecutorSink(ClassLoader loader, String className, ProtectionDomain protectionDomain, + byte[] classfileBuffer, ServerExecutorSinkEntry sinkEntry) { + String name = className.replace('/', '.'); + try { + if (!canAccessGate(loader, protectionDomain)) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup cannot hook server executor sink " + name + + ": its loader/module cannot access keploy-sdk.jar", (Throwable) null); + return null; + } + byte[] wrapped = wrapServerExecutorSink(classfileBuffer, sinkEntry); + if (wrapped == null) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup cannot hook server executor sink " + name + + ": none of " + sinkEntry.methods + " found"); + return null; + } + synchronized (changed) { + Set names = changed.get(loader); + if (names == null) { + names = new HashSet<>(); + changed.put(loader, names); + } + names.add(className); + } + return wrapped; + } catch (Throwable t) { + asyncHookFailed = true; + LOGGER.log(Level.WARNING, "Keploy dedup could not hook server executor sink " + name, t); + return null; + } + } + + static byte[] wrapServerExecutorSink(byte[] classfile, final ServerExecutorSinkEntry sinkEntry) { + ClassReader reader = new ClassReader(classfile); + ClassWriter writer = new ClassWriter(reader, 0); + final boolean[] found = {false}; + final boolean[] alreadyHooked = {false}; + reader.accept(new ClassVisitor(Opcodes.ASM9, writer) { + @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_STATIC | Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0 + || !sinkEntry.methods.contains(name) + || descriptor == null + || (sinkEntry.noTaskDesc != null ? !sinkEntry.noTaskDesc.equals(descriptor) + : !descriptor.startsWith("(Ljava/lang/Runnable;"))) { + return mv; + } + found[0] = true; + return new MethodVisitor(Opcodes.ASM9, mv) { + private boolean injected; + + @Override + public void visitCode() { + super.visitCode(); + if (!injected) { + injected = true; + super.visitLdcInsn(sinkEntry.sinkName); + super.visitVarInsn(Opcodes.ALOAD, 0); + if (sinkEntry.noTaskDesc == null) { + super.visitVarInsn(Opcodes.ALOAD, 1); + } else { + super.visitInsn(Opcodes.ACONST_NULL); + } + super.visitMethodInsn(Opcodes.INVOKESTATIC, GATE, + "onServerExecutorSink", + "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", + false); + } + } + + @Override + public void visitMethodInsn(int opcode, String owner, String mname, String desc, + boolean isInterface) { + if (opcode == Opcodes.INVOKESTATIC && GATE.equals(owner) + && "onServerExecutorSink".equals(mname)) { + alreadyHooked[0] = true; + } + super.visitMethodInsn(opcode, owner, mname, desc, isInterface); + } + + @Override + public void visitMaxs(int maxStack, int maxLocals) { + super.visitMaxs(Math.max(maxStack, 3), maxLocals); + } + }; + } + }, 0); + if (!found[0]) { + return null; + } + return alreadyHooked[0] ? classfile : writer.toByteArray(); + } + private static boolean hasDispatchPrimitiveReference(byte[] classfile) { if (classfile == null || classfile.length < 16) { return false; @@ -1728,7 +2165,12 @@ private static boolean hasDispatchPrimitiveReference(byte[] classfile) { continue; } int tag = reader.readByte(offset - 1); - if (tag == 10 || tag == 11) { + if (tag == 7) { + String referenced = reader.readUTF8(offset, buf); + if (UNHOOKED_ASYNC_DISPATCHERS.containsKey(referenced)) { + return true; + } + } else if (tag == 10 || tag == 11) { String owner = reader.readClass(offset, buf); Set methods = DISPATCH_PRIMITIVE_METHODS.get(owner); if (methods != null) { @@ -1990,6 +2432,14 @@ private static boolean isUntrackedScheduleOrInvokeAny(String mname, String desc) return false; } + // XNIO 3.x org/xnio/XnioExecutor.java: Key executeAfter(Runnable, long, TimeUnit) and + // Key executeAtInterval(Runnable, long, TimeUnit), implemented by XnioIoThread + // (nio WorkerThread queues them on the selector thread's delay queue). + private static boolean isXnioDelayedExecute(String mname, String desc) { + return ("executeAfter".equals(mname) || "executeAtInterval".equals(mname)) + && "(Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)Lorg/xnio/XnioExecutor$Key;".equals(desc); + } + private static boolean isTimerSchedule(String owner, String mname, String desc) { return "java/util/Timer".equals(owner) && ("schedule".equals(mname) || "scheduleAtFixedRate".equals(mname)) @@ -2120,6 +2570,7 @@ private static boolean isAsyncMethodRefTarget(Handle h) { String desc = h.getDesc(); if (isUntrackedScheduleOrInvokeAny(mname, desc) || isTimerSchedule(owner, mname, desc) + || isXnioDelayedExecute(mname, desc) || isForkJoinTaskSubmission(owner, mname, desc)) { return true; } @@ -2583,6 +3034,11 @@ public void visitMethodInsn(int opcode, String owner, String mname, String desc, emitUntrackedFlag("untracked-async:forkjoin-task"); } else if (isTimerSchedule(owner, mname, desc)) { emitUntrackedFlag("untracked-async:timer"); + } else if (isXnioDelayedExecute(mname, desc)) { + // XNIO I/O-thread timers (XnioIoThread / XnioExecutor.executeAfter and + // executeAtInterval) queue onto an I/O selector thread with no JDK sink + // and no window permit: the task can run after END, so flag it. + emitUntrackedFlag("untracked-async:xnio-execute-after"); } else if (isUntrackedScheduleOrInvokeAny(mname, desc)) { if (!"invokeAny".equals(mname) && desc.endsWith(")Ljava/util/concurrent/ScheduledFuture;")) { diff --git a/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java b/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java index f26ac524..896f7bef 100644 --- a/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java +++ b/keploy-sdk/src/main/java/io/keploy/dedup/SinkAllowlist.java @@ -3,7 +3,9 @@ import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; +import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ForkJoinWorkerThread; @@ -230,11 +232,20 @@ final class SinkAllowlist { // ThreadedOutcomesResolver evaluates @ConditionalOnClass checks on a // startup thread joined in resolveOutcomes(); never runs user callbacks. "org.springframework.boot.autoconfigure.condition.OnClassCondition$ThreadedOutcomesResolver", + // Spring Boot AutoConfigure 3.4.5 (BackgroundPreinitializer.java:55-120): + // Spring Boot 3.x counterpart of BackgroundPreinitializingApplicationListener; + // spawns one "background-preinit" startup thread warming built-in framework + // initializers and joined on ApplicationReadyEvent/ApplicationFailedEvent. + "org.springframework.boot.autoconfigure.BackgroundPreinitializer", // Spring Boot AutoConfigure 4.2.0 // (BackgroundPreinitializingApplicationListener.java:70-98): spawns one // "background-preinit" startup thread warming built-in framework // initializers and joined before startup finishes; never runs user tasks. "org.springframework.boot.autoconfigure.preinitialize.BackgroundPreinitializingApplicationListener", + // Spring Boot Jetty 3.4.5 (GracefulShutdown.java:50-75) & 4.x counterpart: + // spawns one "jetty-shutdown" thread closing Jetty connectors on shutdown. + "org.springframework.boot.jetty.GracefulShutdown", + "org.springframework.boot.web.embedded.jetty.GracefulShutdown", // Spring Boot Tomcat 4.2.0 (TomcatWebServer.java:102-141): spawns one // non-daemon "container-0" await thread calling Tomcat.getServer().await(). "org.springframework.boot.tomcat.TomcatWebServer", @@ -268,11 +279,13 @@ final class SinkAllowlist { private static final Object STACK_WALKER; private static final Method STACK_WALKER_WALK; private static final Method STACK_FRAME_GET_CLASS_NAME; + private static final Method STACK_FRAME_GET_METHOD_NAME; static { Object walker = null; Method walkMethod = null; Method getClassNameMethod = null; + Method getMethodNameMethod = null; try { Class swClass = Class.forName("java.lang.StackWalker"); Class sfClass = Class.forName("java.lang.StackWalker$StackFrame"); @@ -283,15 +296,18 @@ final class SinkAllowlist { walker = getInstance.invoke(null, showReflect); walkMethod = swClass.getMethod("walk", Function.class); getClassNameMethod = sfClass.getMethod("getClassName"); + getMethodNameMethod = sfClass.getMethod("getMethodName"); } catch (Throwable ignored) { // JDK 8: fall back to Thread.currentThread().getStackTrace(). walker = null; walkMethod = null; getClassNameMethod = null; + getMethodNameMethod = null; } STACK_WALKER = walker; STACK_WALKER_WALK = walkMethod; STACK_FRAME_GET_CLASS_NAME = getClassNameMethod; + STACK_FRAME_GET_METHOD_NAME = getMethodNameMethod; } private SinkAllowlist() { @@ -511,7 +527,609 @@ private static boolean isBootstrapOrPlatform(Class cls) { } static String firstExternalCaller() { - return firstExternalCaller(false); + return firstExternalCaller(false, null); + } + + static String firstExternalCaller(final boolean skipVirtualThreadFrames) { + return firstExternalCaller(skipVirtualThreadFrames, null); + } + + // Exact, closed, cited allowlists of internal server caller frames ("class#method") + // per hooked server-owned executor/scheduler sink (ServerEntries.SERVER_EXECUTOR_SINKS). + // No package-prefix wildcards are used: any unlisted class or method—including public + // server forwarding APIs and public helper classes such as Jetty Server$ServerContext.execute, + // ContextHandler$ScopedContext.execute, VirtualThreads.execute, Scheduler.schedule(Runnable, + // Duration), SerializedInvoker, Sweeper, LowResourceMonitor, ByteArrayEndPoint, + // Undertow WorkerUtils.executeAfter, HttpServerExchange.dispatch, ParseTimeoutUpdater, + // ConnectionUtils, or XNIO Channels.resumeReadsAsync / EmptyStreamSourceChannel—fails + // closed automatically. + // + // Thin public Jetty/Undertow delegates (EatWhatYouKill, AdaptiveExecutionStrategy, + // SelectorManager#execute, HttpChannel#execute, ServletChannel#execute, + // ContextHandler$ScopedContext#execute, Server$ServerContext#execute, + // VirtualThreads#execute, WorkerUtils, ParseTimeoutUpdater, ConnectionUtils) are + // transparently skipped during stack walking so the real caller above them is validated + // (and Jetty pool callers also validate the exact internal task class and owner chain). + private static final Set JETTY_POOL_BASE_CALLERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + // Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15 jetty-server AbstractConnector.java: + // launches internal Acceptor loop on connector startup (also validates task is + // AbstractConnector$Acceptor whose enclosing connector is exact ServerConnector). + "org.eclipse.jetty.server.AbstractConnector#doStart", + // Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15 jetty-io ManagedSelector.java: + // internal NIO selector startup and private execute() (reached through + // transparently skipped SelectorManager#execute or execution strategies; + // requires exact ManagedSelector task owned by ServerConnectorManager). + "org.eclipse.jetty.io.ManagedSelector#doStart", + "org.eclipse.jetty.io.ManagedSelector#execute", + "org.eclipse.jetty.io.ManagedSelector$Accept#run", + "org.eclipse.jetty.io.ManagedSelector$CreateEndPoint#run", + "org.eclipse.jetty.io.ManagedSelector$DestroyEndPoint#run", + "org.eclipse.jetty.io.ManagedSelector$SelectorProducer#produce", + // Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15: QTP / ReservedThread worker roots + // running already-admitted EatWhatYouKill / AdaptiveExecutionStrategy loops + // (requires exact internal Jetty task + ServerConnector owner chain). + "org.eclipse.jetty.util.thread.QueuedThreadPool$Runner#run", + "org.eclipse.jetty.util.thread.QueuedThreadPool$Runner#doRunJob", + "org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread#run", + // Jetty 9.4.57 / 11.0.24 jetty-server HttpConnection / HttpChannelState / HttpInput: + // internal HTTP/1.1 connection open/complete, async dispatch (HttpChannelState.java: + // scheduleDispatch calls _channel.execute(_channel)), and input wake + // (all require exact internal Jetty task classes). + "org.eclipse.jetty.server.HttpConnection#onOpen", + "org.eclipse.jetty.server.HttpConnection#onCompleted", + "org.eclipse.jetty.server.HttpChannelState#scheduleDispatch", + "org.eclipse.jetty.server.HttpInput#wake", + // Jetty 12.0.16 / 12.1.15 jetty-server internal HttpConnection & ee10/ee11 + // ServletChannelState#scheduleDispatch (reaches QTP via transparently skipped + // ServletChannel#execute -> ScopedContext#execute -> ServerContext/VirtualThreads#execute; + // validates exact ScopedContext$$Lambda wrapping ServletChannel$$Lambda -> ServletChannel). + "org.eclipse.jetty.server.internal.HttpConnection#onOpen", + "org.eclipse.jetty.server.internal.HttpConnection$HttpStreamOverHTTP1#resume", + "org.eclipse.jetty.ee10.servlet.ServletChannelState#scheduleDispatch", + "org.eclipse.jetty.ee11.servlet.ServletChannelState#scheduleDispatch", + // Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15 jetty-util ReservedThreadExecutor.java: + // private startReservedThread() spawns only its own ReservedThread worker. + "org.eclipse.jetty.util.thread.ReservedThreadExecutor#startReservedThread", + // Jetty 9.4 / 11 / 12.0 / 12.1 annotations AnnotationConfiguration.java: + // startup bytecode annotation scan joined before server serves requests. + "org.eclipse.jetty.annotations.AnnotationConfiguration#scanForAnnotations", + "org.eclipse.jetty.ee10.annotations.AnnotationConfiguration#scanForAnnotations", + "org.eclipse.jetty.ee11.annotations.AnnotationConfiguration#scanForAnnotations" + ))); + + // Exact Jetty internal Runnable classes permitted when QTP/ReservedThreadExecutor + // worker loops (or transparently skipped execution strategies / HttpChannel#execute) + // dispatch a task onto Jetty's pool. Never matches an app/library Runnable or lambda. + private static final Set JETTY_INTERNAL_POOL_TASK_CLASSES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "org.eclipse.jetty.util.thread.strategy.EatWhatYouKill", + "org.eclipse.jetty.util.thread.strategy.AdaptiveExecutionStrategy", + "org.eclipse.jetty.io.ChannelEndPoint$1", + "org.eclipse.jetty.io.ChannelEndPoint$2", + "org.eclipse.jetty.io.SelectableChannelEndPoint$1", + "org.eclipse.jetty.io.SelectableChannelEndPoint$2", + "org.eclipse.jetty.io.SocketChannelEndPoint", + "org.eclipse.jetty.io.ManagedSelector$Accept", + "org.eclipse.jetty.io.ManagedSelector$CreateEndPoint", + "org.eclipse.jetty.io.ManagedSelector$DestroyEndPoint", + "org.eclipse.jetty.io.ManagedSelector$Connect", + "org.eclipse.jetty.io.ManagedSelector$CloseConnections", + "org.eclipse.jetty.server.HttpConnection", + "org.eclipse.jetty.server.HttpChannel", + "org.eclipse.jetty.server.HttpChannelOverHttp", + "org.eclipse.jetty.server.AsyncContextState$1", + "org.eclipse.jetty.server.internal.HttpConnection", + "org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint", + "org.eclipse.jetty.io.ssl.SslConnection$SslEndPoint" + ))); + + // Exact ServerConnector classes permitted to start an Acceptor via AbstractConnector#doStart. + private static final Set ALLOWED_JETTY_CONNECTOR_CLASSES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "org.eclipse.jetty.server.ServerConnector", + "org.eclipse.jetty.server.NetworkTrafficServerConnector" + ))); + + // QueuedThreadPool and ExecutorThreadPool also accept internal delegation from the + // already-hooked Jetty pool wrappers (each wrapper validates its own caller on entry). + private static final Set JETTY_BACKING_POOL_CALLERS = unionSets(JETTY_POOL_BASE_CALLERS, Arrays.asList( + "org.eclipse.jetty.util.thread.MonitoredQueuedThreadPool#execute", + "org.eclipse.jetty.util.thread.ReservedThreadExecutor#execute", + "org.eclipse.jetty.util.thread.TryExecutor$NoTryExecutor#execute" + )); + + // ReservedThreadExecutor also accepts tryExecute delegation from the already-hooked + // QueuedThreadPool and ExecutorThreadPool (which validate their own callers on entry). + private static final Set JETTY_RESERVED_EXEC_CALLERS = unionSets(JETTY_POOL_BASE_CALLERS, Arrays.asList( + "org.eclipse.jetty.util.thread.QueuedThreadPool#tryExecute", + "org.eclipse.jetty.util.thread.ExecutorThreadPool#tryExecute" + )); + + // Exact cited internal callers of Jetty ScheduledExecutorScheduler / TimerScheduler. + // Note: Scheduler#schedule(Runnable, Duration), Sweeper#activate, and LowResourceMonitor + // are intentionally ABSENT so calls through those public APIs fail closed automatically. + private static final Set JETTY_SCHEDULER_CALLERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + // Guarded on entry by hooked IdleTimeout#scheduleIdleTimeout (exact EndPoint subclasses only). + "org.eclipse.jetty.io.IdleTimeout#scheduleIdleTimeout", + // Guarded on entry by hooked CyclicTimeout#schedule (exact internal subclasses & callers only). + "org.eclipse.jetty.io.CyclicTimeout$Wakeup#schedule", + // Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15: servlet async request timeout. + "org.eclipse.jetty.server.HttpChannelState#nextAction", + "org.eclipse.jetty.ee10.servlet.ServletChannelState#nextAction", + "org.eclipse.jetty.ee11.servlet.ServletChannelState#nextAction", + // Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15: HTTP session scavenger timer. + "org.eclipse.jetty.server.session.HouseKeeper#startScavenging", + "org.eclipse.jetty.server.session.HouseKeeper$Runner#run", + "org.eclipse.jetty.session.HouseKeeper#startScavenging", + "org.eclipse.jetty.session.HouseKeeper$Runner#run", + // Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15: internal TimerScheduler loop re-arm. + "org.eclipse.jetty.util.thread.TimerScheduler#run" + ))); + + // Exact cited Jetty internal subclasses & callers of public abstract CyclicTimeout. + private static final Set ALLOWED_JETTY_CYCLIC_TIMEOUT_CLASSES = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList( + // Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15 jetty-io CyclicTimeouts.java. + "org.eclipse.jetty.io.CyclicTimeouts$Timeouts", + // Jetty 9.4.57 / 11.0.24 jetty-server Session.java. + "org.eclipse.jetty.server.session.Session$SessionInactivityTimer$1", + // Jetty 12.0.16 / 12.1.15 jetty-session SessionInactivityTimer.java. + "org.eclipse.jetty.session.SessionInactivityTimer$1" + ))); + + private static final Set JETTY_CYCLIC_TIMEOUT_CALLERS = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList( + // Guarded on entry by hooked CyclicTimeouts#schedule(Expirable). + "org.eclipse.jetty.io.CyclicTimeouts#schedule", + "org.eclipse.jetty.server.session.Session$SessionInactivityTimer#schedule", + "org.eclipse.jetty.session.SessionInactivityTimer#schedule" + ))); + + // Exact cited Jetty internal server subclasses & callers of public abstract CyclicTimeouts. + private static final Set ALLOWED_JETTY_CYCLIC_TIMEOUTS_CLASSES = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList( + // Jetty 12.0.16 / 12.1.15 jetty-server QoSHandler.java & DoSHandler.java. + "org.eclipse.jetty.server.handler.QoSHandler$Timeouts", + "org.eclipse.jetty.server.handler.DoSHandler$1" + ))); + + private static final Set JETTY_CYCLIC_TIMEOUTS_CALLERS = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList( + "org.eclipse.jetty.server.handler.QoSHandler#suspend", + "org.eclipse.jetty.server.handler.DoSHandler#newTracker" + ))); + + // Exact cited Jetty internal network EndPoint subclasses of public abstract IdleTimeout. + // ByteArrayEndPoint and LocalConnector$LocalEndPoint are intentionally ABSENT because + // app code can instantiate them directly with arbitrary Callbacks to launder onto Scheduler. + // The classes below can be instantiated by app code too, so each also has to be owned by a + // ServerConnector's ManagedSelector (isServerConnectorOwnedEndPoint). + private static final Set ALLOWED_JETTY_IDLE_TIMEOUT_CLASSES = Collections.unmodifiableSet( + new HashSet<>(Arrays.asList( + "org.eclipse.jetty.io.SocketChannelEndPoint", + "org.eclipse.jetty.io.ChannelEndPoint", + "org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint", + "org.eclipse.jetty.io.ssl.SslConnection$SslEndPoint" + ))); + + // Exact cited internal callers of Undertow/XNIO org.xnio.nio.WorkerThread. + // Note: public forwarders and public callback-bearing helpers (WorkerUtils, + // HttpServerExchange#dispatch, PipeliningExecutor, ChannelListeners, Channels#resume*Async, + // ParseTimeoutUpdater, ConnectionUtils, EmptyStreamSourceChannel, FixedLengthStreamSourceChannel, + // NullStreamSinkChannel, EmptyStreamSourceConduit, NullStreamSinkConduit, IdleTimeoutConduit, + // ReadTimeoutStreamSourceConduit, WriteTimeoutStreamSinkConduit, RateLimitingStreamSinkConduit, + // DeflatingStreamSinkConduit, ReadDispatchChannel/WriteDispatchChannel#invokeListener, SslConduit) + // are intentionally ABSENT; WorkerUtils, ParseTimeoutUpdater, and ConnectionUtils are + // transparently skipped so only internal Undertow HTTP protocol callers above them pass. + private static final Set XNIO_WORKER_THREAD_CALLERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + // XNIO 3.8.16 xnio-nio: package-private TCP accept loop, token/back-off management, + // repeat-key ticks, and WorkerThread#run loop (for already-admitted ParseTimeoutUpdater#run). + "org.xnio.nio.NioTcpServer$1#getConnectionCount", + "org.xnio.nio.NioTcpServerHandle#channelClosed", + "org.xnio.nio.NioTcpServerHandle#executeSetTask", + "org.xnio.nio.NioTcpServerHandle#initializeTokenCount", + "org.xnio.nio.NioTcpServerHandle#resume", + "org.xnio.nio.NioTcpServerHandle#setThreadNewCount", + "org.xnio.nio.NioTcpServerHandle#suspend", + "org.xnio.nio.NioTcpServerHandle#startBackOff", + "org.xnio.nio.QueuedNioTcpServer2#acceptTask", + "org.xnio.nio.QueuedNioTcpServer2#handleReady", + "org.xnio.nio.WorkerThread$RepeatKey#run", + "org.xnio.nio.WorkerThread#run", + // Undertow 2.2.37 / 2.3.18 undertow-core: HTTP/1.1 protocol accept/read/close lifecycle + // (reached directly or through transparently skipped WorkerUtils / ParseTimeoutUpdater / + // ConnectionUtils), internal Date header cache timer, session expiry, and servlet async timeout. + "io.undertow.server.protocol.http.HttpOpenListener#closeConnections", + "io.undertow.server.protocol.http.HttpReadListener#handleEventWithNoRunningRequest", + "io.undertow.server.protocol.http.HttpReadListener#exchangeComplete", + "io.undertow.server.protocol.http.HttpReadListener#newRequest", + "io.undertow.Undertow$ListenerInfo#suspend", + "io.undertow.util.DateUtils#getCurrentDateTime", + "io.undertow.server.session.InMemorySessionManager$SessionImpl#bumpTimeout", + "io.undertow.server.session.InMemorySessionManager$SessionImpl$2$1#run", + "io.undertow.servlet.spec.AsyncContextImpl#updateTimeout" + ))); + + private static final Map> SERVER_EXECUTOR_SINK_CALLERS = buildServerExecutorSinkCallers(); + + private static Map> buildServerExecutorSinkCallers() { + Map> m = new HashMap<>(); + m.put("org.eclipse.jetty.util.thread.QueuedThreadPool", JETTY_BACKING_POOL_CALLERS); + m.put("org.eclipse.jetty.util.thread.ExecutorThreadPool", JETTY_BACKING_POOL_CALLERS); + m.put("org.eclipse.jetty.util.thread.MonitoredQueuedThreadPool", JETTY_POOL_BASE_CALLERS); + m.put("org.eclipse.jetty.util.thread.TryExecutor$NoTryExecutor", JETTY_POOL_BASE_CALLERS); + m.put("org.eclipse.jetty.util.thread.ReservedThreadExecutor", JETTY_RESERVED_EXEC_CALLERS); + m.put("org.eclipse.jetty.util.thread.ScheduledExecutorScheduler", JETTY_SCHEDULER_CALLERS); + m.put("org.eclipse.jetty.util.thread.TimerScheduler", JETTY_SCHEDULER_CALLERS); + m.put("org.eclipse.jetty.io.CyclicTimeout", JETTY_CYCLIC_TIMEOUT_CALLERS); + m.put("org.eclipse.jetty.io.CyclicTimeouts", JETTY_CYCLIC_TIMEOUTS_CALLERS); + // PipeliningExecutor is a public Undertow utility wrapper not invoked by Undertow's + // core HTTP request path; empty allowlist ensures any call fails closed. + m.put("io.undertow.util.PipeliningExecutor", Collections.emptySet()); + m.put("org.xnio.nio.WorkerThread", XNIO_WORKER_THREAD_CALLERS); + return Collections.unmodifiableMap(m); + } + + private static Set unionSets(Set base, java.util.Collection extra) { + Set out = new HashSet<>(base); + out.addAll(extra); + return Collections.unmodifiableSet(out); + } + + static String firstExternalCallerFrameSkipping(final String skipClassName) { + if (STACK_WALKER != null && STACK_WALKER_WALK != null + && STACK_FRAME_GET_CLASS_NAME != null && STACK_FRAME_GET_METHOD_NAME != null) { + try { + Function, String> finder = new Function, String>() { + @Override + public String apply(Stream stream) { + final boolean[] seenSelf = {false}; + Optional found = stream + .map(SinkAllowlist::frameClassAndMethod) + .filter(cm -> { + if (cm == null) { + return false; + } + int hash = cm.indexOf('#'); + String cn = hash >= 0 ? cm.substring(0, hash) : cm; + String mn = hash >= 0 ? cm.substring(hash + 1) : ""; + if (!seenSelf[0]) { + if ("io.keploy.dedup.SinkAllowlist".equals(cn)) { + seenSelf[0] = true; + } + return false; + } + return !isSkippedServerSinkFrame(cn, mn, skipClassName); + }) + .findFirst(); + return found.orElse(null); + } + }; + return (String) STACK_WALKER_WALK.invoke(STACK_WALKER, finder); + } catch (Throwable ignored) { + // Fall back to getStackTrace below. + } + } + StackTraceElement[] frames = Thread.currentThread().getStackTrace(); + for (int i = 1; i < frames.length; i++) { + String cn = frames[i].getClassName(); + String mn = frames[i].getMethodName(); + if (!isSkippedServerSinkFrame(cn, mn, skipClassName)) { + return cn + "#" + mn; + } + } + return null; + } + + static boolean isAllowedServerExecutorCaller(String sinkName, String callerFrame, Object receiver) { + return isAllowedServerExecutorCaller(sinkName, callerFrame, receiver, null); + } + + static boolean isAllowedServerExecutorCaller(String sinkName, String callerFrame, Object receiver, Object task) { + if (sinkName == null) { + return false; + } + if ("org.eclipse.jetty.io.IdleTimeout".equals(sinkName)) { + return receiver != null && ALLOWED_JETTY_IDLE_TIMEOUT_CLASSES.contains(receiver.getClass().getName()) + && isServerConnectorOwnedEndPoint(receiver); + } + if ("org.eclipse.jetty.io.CyclicTimeout".equals(sinkName)) { + if (receiver == null || !ALLOWED_JETTY_CYCLIC_TIMEOUT_CLASSES.contains(receiver.getClass().getName())) { + return false; + } + return callerFrame != null && JETTY_CYCLIC_TIMEOUT_CALLERS.contains(callerFrame); + } + if ("org.eclipse.jetty.io.CyclicTimeouts".equals(sinkName)) { + if (receiver == null || !ALLOWED_JETTY_CYCLIC_TIMEOUTS_CLASSES.contains(receiver.getClass().getName())) { + return false; + } + return callerFrame != null && JETTY_CYCLIC_TIMEOUTS_CALLERS.contains(callerFrame); + } + if (callerFrame == null) { + return false; + } + Set allowed = SERVER_EXECUTOR_SINK_CALLERS.get(sinkName); + if (allowed == null || !allowed.contains(callerFrame)) { + return false; + } + // Extra task/owner guards so neither subclassed AbstractConnector / ManagedSelector / + // SelectorManager / HttpConnection nor worker-loop strategy dispatches can carry an + // arbitrary user Runnable. + if ("org.xnio.nio.WorkerThread#run".equals(callerFrame)) { + // WorkerThread#run is only permitted for already-admitted ParseTimeoutUpdater#run re-arms. + return task != null && "io.undertow.server.protocol.ParseTimeoutUpdater".equals(task.getClass().getName()); + } + if ("org.eclipse.jetty.util.thread.TimerScheduler#run".equals(callerFrame)) { + // TimerScheduler#run only re-arms itself (this.schedule(this, 1, SECONDS)). + return task != null && task == receiver + && "org.eclipse.jetty.util.thread.TimerScheduler".equals(task.getClass().getName()); + } + if ("org.eclipse.jetty.server.AbstractConnector#doStart".equals(callerFrame)) { + return isAllowedJettyAcceptorTask(task); + } + if ("org.eclipse.jetty.server.HttpChannelState#scheduleDispatch".equals(callerFrame)) { + if (task == null) { + return false; + } + String tc = task.getClass().getName(); + return "org.eclipse.jetty.server.HttpChannelOverHttp".equals(tc) + || "org.eclipse.jetty.server.HttpChannel".equals(tc); + } + if ("org.eclipse.jetty.ee10.servlet.ServletChannelState#scheduleDispatch".equals(callerFrame)) { + return isAllowedJettyScopedServletDispatchTask(task, "org.eclipse.jetty.ee10.servlet.ServletChannel"); + } + if ("org.eclipse.jetty.ee11.servlet.ServletChannelState#scheduleDispatch".equals(callerFrame)) { + return isAllowedJettyScopedServletDispatchTask(task, "org.eclipse.jetty.ee11.servlet.ServletChannel"); + } + if (isJettyPoolSink(sinkName) + && !"org.eclipse.jetty.util.thread.ReservedThreadExecutor#startReservedThread".equals(callerFrame) + && !"org.eclipse.jetty.annotations.AnnotationConfiguration#scanForAnnotations".equals(callerFrame) + && !"org.eclipse.jetty.ee10.annotations.AnnotationConfiguration#scanForAnnotations".equals(callerFrame) + && !"org.eclipse.jetty.ee11.annotations.AnnotationConfiguration#scanForAnnotations".equals(callerFrame) + && !"org.eclipse.jetty.util.thread.MonitoredQueuedThreadPool#execute".equals(callerFrame) + && !"org.eclipse.jetty.util.thread.ReservedThreadExecutor#execute".equals(callerFrame) + && !"org.eclipse.jetty.util.thread.TryExecutor$NoTryExecutor#execute".equals(callerFrame) + && !"org.eclipse.jetty.util.thread.QueuedThreadPool#tryExecute".equals(callerFrame) + && !"org.eclipse.jetty.util.thread.ExecutorThreadPool#tryExecute".equals(callerFrame)) { + return isAllowedJettyInternalPoolTask(task); + } + return true; + } + + // Jetty 12.0 / 12.1 ServletChannelState#scheduleDispatch calls + // _servletChannel.execute(_servletChannel::handle, req) -> + // ContextHandler$ScopedContext.execute(runnable, req) -> + // Server$ServerContext.execute / VirtualThreads.execute(pool, scopedLambda). + // Only a ScopedContext lambda wrapping a ServletChannel lambda capturing an exact + // ServletChannel instance is allowed; any app Runnable fails closed. + private static boolean isAllowedJettyScopedServletDispatchTask(Object task, String expectedServletChannelClass) { + if (task == null) { + return false; + } + String taskClass = task.getClass().getName(); + if (!taskClass.startsWith("org.eclipse.jetty.server.handler.ContextHandler$ScopedContext$$Lambda")) { + return false; + } + String expectedStateLambdaPrefix = expectedServletChannelClass + "State$$Lambda"; + String expectedChannelLambdaPrefix = expectedServletChannelClass + "$$Lambda"; + try { + for (java.lang.reflect.Field f : task.getClass().getDeclaredFields()) { + f.setAccessible(true); + Object inner = f.get(task); + if (inner == null) { + continue; + } + String innerClass = inner.getClass().getName(); + if (innerClass.startsWith(expectedStateLambdaPrefix) + || innerClass.startsWith(expectedChannelLambdaPrefix)) { + for (java.lang.reflect.Field innerField : inner.getClass().getDeclaredFields()) { + innerField.setAccessible(true); + Object captured = innerField.get(inner); + if (captured != null && expectedServletChannelClass.equals(captured.getClass().getName())) { + return true; + } + } + } + } + } catch (Throwable ignored) { + return false; + } + return false; + } + + private static boolean isAllowedJettyInternalPoolTask(Object task) { + if (task == null) { + return false; + } + String taskClass = task.getClass().getName(); + if ("org.eclipse.jetty.util.thread.strategy.EatWhatYouKill".equals(taskClass) + || "org.eclipse.jetty.util.thread.strategy.AdaptiveExecutionStrategy".equals(taskClass)) { + return isAllowedJettyExecutionStrategyTask(task); + } + if (taskClass.startsWith("org.eclipse.jetty.io.ManagedSelector$")) { + return isAllowedJettyManagedSelectorTask(task, taskClass); + } + return JETTY_INTERNAL_POOL_TASK_CLASSES.contains(taskClass); + } + + private static boolean isAllowedJettyExecutionStrategyTask(Object strategy) { + try { + Object producer = readField(strategy, "_producer"); + if (producer == null) { + return false; + } + if (!"org.eclipse.jetty.io.ManagedSelector$SelectorProducer".equals(producer.getClass().getName())) { + return false; + } + Object managedSelector = readField(producer, "this$0"); + return isExactServerConnectorManagedSelector(managedSelector); + } catch (Throwable ignored) { + return false; + } + } + + private static boolean isAllowedJettyManagedSelectorTask(Object task, String taskClass) { + try { + if (taskClass.startsWith("org.eclipse.jetty.io.ManagedSelector$$Lambda")) { + for (java.lang.reflect.Field f : task.getClass().getDeclaredFields()) { + f.setAccessible(true); + Object v = f.get(task); + if (v == null) { + continue; + } + String vClass = v.getClass().getName(); + if ("org.eclipse.jetty.io.ManagedSelector".equals(vClass)) { + return isExactServerConnectorManagedSelector(v); + } + if ("org.eclipse.jetty.util.thread.strategy.EatWhatYouKill".equals(vClass) + || "org.eclipse.jetty.util.thread.strategy.AdaptiveExecutionStrategy".equals(vClass)) { + return isAllowedJettyExecutionStrategyTask(v); + } + if ("org.eclipse.jetty.io.ManagedSelector$SelectorProducer".equals(vClass)) { + return isExactServerConnectorManagedSelector(readField(v, "this$0")); + } + } + return false; + } + if (!JETTY_INTERNAL_POOL_TASK_CLASSES.contains(taskClass)) { + return false; + } + Object managedSelector = readField(task, "this$0"); + return isExactServerConnectorManagedSelector(managedSelector); + } catch (Throwable ignored) { + return false; + } + } + + private static boolean isExactServerConnectorManagedSelector(Object managedSelector) { + if (managedSelector == null + || !"org.eclipse.jetty.io.ManagedSelector".equals(managedSelector.getClass().getName())) { + return false; + } + try { + Object selectorManager = readField(managedSelector, "_selectorManager"); + if (selectorManager == null + || !"org.eclipse.jetty.server.ServerConnector$ServerConnectorManager" + .equals(selectorManager.getClass().getName())) { + return false; + } + Object connector = readField(selectorManager, "this$0"); + return connector != null && ALLOWED_JETTY_CONNECTOR_CLASSES.contains(connector.getClass().getName()); + } catch (Throwable ignored) { + return false; + } + } + + // The exact network EndPoint classes in ALLOWED_JETTY_IDLE_TIMEOUT_CLASSES have public + // constructors (SocketChannelEndPoint(SocketChannel, ManagedSelector, SelectionKey, Scheduler) and + // SslConnection(...) in Jetty 9.4.57 / 11.0.24 / 12.0.16 / 12.1.15), so app or library code can build + // one around its own channel with its own Connection and launder that Connection's onIdleExpired + // onto the connector Scheduler, exactly as with ByteArrayEndPoint. Only an endpoint that a + // ServerConnector's own ManagedSelector created passes: ServerConnector#newEndPoint arms its idle + // timeout with _selector set to that ManagedSelector and _key set to the SelectionKey that registers + // _channel with that ManagedSelector's NIO Selector (ManagedSelector#createEndPoint, all four + // versions). An SSL endpoint passes only when its enclosing SslConnection wraps such an endpoint. + private static boolean isServerConnectorOwnedEndPoint(Object endPoint) { + try { + String cls = endPoint.getClass().getName(); + if ("org.eclipse.jetty.io.ssl.SslConnection$DecryptedEndPoint".equals(cls) + || "org.eclipse.jetty.io.ssl.SslConnection$SslEndPoint".equals(cls)) { + Object ssl = readField(endPoint, "this$0"); + if (ssl == null || !"org.eclipse.jetty.io.ssl.SslConnection".equals(ssl.getClass().getName())) { + return false; + } + Object network = readField(ssl, "_endPoint"); + return network != null && network != endPoint + && "org.eclipse.jetty.io.SocketChannelEndPoint".equals(network.getClass().getName()) + && isServerConnectorOwnedEndPoint(network); + } + Object managedSelector = readField(endPoint, "_selector"); + if (!isExactServerConnectorManagedSelector(managedSelector)) { + return false; + } + Object key = readField(endPoint, "_key"); + Object channel = readField(endPoint, "_channel"); + if (!(key instanceof java.nio.channels.SelectionKey) || channel == null) { + return false; + } + java.nio.channels.SelectionKey selectionKey = (java.nio.channels.SelectionKey) key; + Object nioSelector = readField(managedSelector, "_selector"); + return selectionKey.channel() == channel && nioSelector != null && selectionKey.selector() == nioSelector; + } catch (Throwable ignored) { + return false; + } + } + + private static Object readField(Object obj, String fieldName) throws Exception { + Class c = obj.getClass(); + while (c != null) { + try { + java.lang.reflect.Field f = c.getDeclaredField(fieldName); + f.setAccessible(true); + return f.get(obj); + } catch (NoSuchFieldException ignored) { + c = c.getSuperclass(); + } + } + return null; + } + + private static boolean isAllowedJettyAcceptorTask(Object task) { + if (task == null || !"org.eclipse.jetty.server.AbstractConnector$Acceptor".equals(task.getClass().getName())) { + return false; + } + try { + Object connector = readField(task, "this$0"); + return connector != null && ALLOWED_JETTY_CONNECTOR_CLASSES.contains(connector.getClass().getName()); + } catch (Throwable ignored) { + return false; + } + } + + private static boolean isJettyPoolSink(String sinkName) { + return "org.eclipse.jetty.util.thread.QueuedThreadPool".equals(sinkName) + || "org.eclipse.jetty.util.thread.ExecutorThreadPool".equals(sinkName) + || "org.eclipse.jetty.util.thread.MonitoredQueuedThreadPool".equals(sinkName) + || "org.eclipse.jetty.util.thread.ReservedThreadExecutor".equals(sinkName) + || "org.eclipse.jetty.util.thread.TryExecutor$NoTryExecutor".equals(sinkName); + } + + private static boolean isSkippedServerSinkFrame(String cn, String mn, String sinkClassName) { + if (sinkClassName != null) { + if (sinkClassName.equals(cn)) { + // Keep WorkerThread#run visible so already-admitted ParseTimeoutUpdater#run + // re-arms resolve to WorkerThread#run (whereas direct app calls to + // ParseTimeoutUpdater#run resolve to the app caller and fail closed). + if ("org.xnio.nio.WorkerThread".equals(sinkClassName) && "run".equals(mn)) { + return false; + } + if ("org.eclipse.jetty.util.thread.TimerScheduler".equals(sinkClassName) && "run".equals(mn)) { + return false; + } + return true; + } + if ("org.xnio.nio.WorkerThread".equals(sinkClassName) + && ("io.undertow.util.WorkerUtils".equals(cn) + || "io.undertow.server.protocol.ParseTimeoutUpdater".equals(cn) + || "io.undertow.util.ConnectionUtils".equals(cn))) { + return true; + } + if (isJettyPoolSink(sinkClassName)) { + if ("org.eclipse.jetty.util.thread.strategy.EatWhatYouKill".equals(cn) + || "org.eclipse.jetty.util.thread.strategy.AdaptiveExecutionStrategy".equals(cn)) { + return true; + } + if ("execute".equals(mn) + && ("org.eclipse.jetty.io.SelectorManager".equals(cn) + || "org.eclipse.jetty.server.HttpChannel".equals(cn) + || "org.eclipse.jetty.ee10.servlet.ServletChannel".equals(cn) + || "org.eclipse.jetty.ee11.servlet.ServletChannel".equals(cn) + || "org.eclipse.jetty.server.handler.ContextHandler$ScopedContext".equals(cn) + || "org.eclipse.jetty.server.Server$ServerContext".equals(cn) + || "org.eclipse.jetty.util.VirtualThreads".equals(cn))) { + return true; + } + } + } + return isSkippedCallerFrame(cn, false, null); } // Walks the current thread's stack (lazily via JDK 9+ StackWalker, or via @@ -522,7 +1140,7 @@ static String firstExternalCaller() { // Reflection (java.lang.reflect.Method.invoke) and MethodHandles are NEVER // skipped — they return their own class name, which is NOT in any allowlist, // so reflective/MethodHandle dispatch fails closed by construction. - static String firstExternalCaller(final boolean skipVirtualThreadFrames) { + private static String firstExternalCaller(final boolean skipVirtualThreadFrames, final String skipClassName) { if (STACK_WALKER != null && STACK_WALKER_WALK != null && STACK_FRAME_GET_CLASS_NAME != null) { try { Function, String> finder = new Function, String>() { @@ -541,7 +1159,7 @@ public String apply(Stream stream) { } return false; } - return !isSkippedCallerFrame(cn, skipVirtualThreadFrames); + return !isSkippedCallerFrame(cn, skipVirtualThreadFrames, skipClassName); }) .findFirst(); return found.orElse(null); @@ -555,7 +1173,7 @@ public String apply(Stream stream) { StackTraceElement[] frames = Thread.currentThread().getStackTrace(); for (int i = 1; i < frames.length; i++) { String cn = frames[i].getClassName(); - if (!isSkippedCallerFrame(cn, skipVirtualThreadFrames)) { + if (!isSkippedCallerFrame(cn, skipVirtualThreadFrames, skipClassName)) { return cn; } } @@ -570,10 +1188,22 @@ private static String frameClassName(Object stackFrame) { } } - private static boolean isSkippedCallerFrame(String cn, boolean skipVirtualThreadFrames) { - return "io.keploy.dedup.bootstrap.KeploySinkBridge".equals(cn) + private static String frameClassAndMethod(Object stackFrame) { + try { + String cn = (String) STACK_FRAME_GET_CLASS_NAME.invoke(stackFrame); + String mn = (String) STACK_FRAME_GET_METHOD_NAME.invoke(stackFrame); + return cn != null && mn != null ? (cn + "#" + mn) : null; + } catch (Throwable ignored) { + return null; + } + } + + private static boolean isSkippedCallerFrame(String cn, boolean skipVirtualThreadFrames, String skipClassName) { + return (skipClassName != null && skipClassName.equals(cn)) + || "io.keploy.dedup.bootstrap.KeploySinkBridge".equals(cn) || "io.keploy.dedup.SinkAllowlist".equals(cn) || "io.keploy.dedup.SinkAllowlist$1".equals(cn) + || "io.keploy.dedup.SinkAllowlist$2".equals(cn) || "io.keploy.dedup.RequestGate".equals(cn) || "io.keploy.dedup.JdkSinkHandler".equals(cn) || "io.keploy.dedup.JdkSinkBootstrap".equals(cn) diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java index 4a1e0f7e..954f71da 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/ForkedAsyncAndHonestyTest.java @@ -590,18 +590,17 @@ public void forkedServletAsyncContextStartAfterCompleteNeverLeaksAcrossServers() for (boolean prefixMode : new boolean[] {true, false}) { for (String server : servers) { String label = "server=" + server + " mode=" + (prefixMode ? "prefix" : "index"); - boolean isUndertow = "undertow".equals(server); // 1. Short endWait=80ms: post-complete runnable outlives END -> W1 must be // windowCut:true AND W2 must carry tail contamination (zero silent leakage). try (ForkedApp app = startFork(server, "80", prefixMode, false, null, null)) { JsonObject hello = parseHello(app.initialHello); assertTrue(label + " must declare windowCut=true: " + app.initialHello, hello.get("windowCut").getAsBoolean()); - app.runHttpTest("ac/" + server + "-warm", "/clean"); - if (!isUndertow) { - assertTrue(label + " must keep asyncExecutors=true after /clean: " + app.lastHello, - parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); - } + String warmCov = app.runHttpTest("ac/" + server + "-warm", "/clean"); + assertFalse(label + " warm /clean must not be contaminated: " + warmCov, + warmCov.contains("contaminated")); + assertTrue(label + " must keep asyncExecutors=true after /clean: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); String cov1 = app.runHttpTest("ac/" + server + "-cut", "/async-after-complete?ms=400"); assertTrue(label + " W1 must report windowCut:true: " + cov1, cov1.contains("\"windowCut\":true")); @@ -613,39 +612,77 @@ public void forkedServletAsyncContextStartAfterCompleteNeverLeaksAcrossServers() String cov3 = app.runHttpTest("ac/" + server + "-drained", "/clean"); assertFalse(label + " W3 after drain must not be windowCut: " + cov3, cov3.contains("windowCut")); - if (!isUndertow) { - assertFalse(label + " W3 after drain must not carry tail:ac/" + server + "-cut: " + cov3, - cov3.contains("\"tail:ac/" + server + "-cut\"")); - assertFalse(label + " W3 after drain must not be contaminated: " + cov3, - cov3.contains("contaminated")); - } + assertFalse(label + " W3 after drain must not carry tail:ac/" + server + "-cut: " + cov3, + cov3.contains("\"tail:ac/" + server + "-cut\"")); + assertFalse(label + " W3 after drain must not be contaminated: " + cov3, + cov3.contains("contaminated")); } // 2. Sufficient endWait=2000ms: END waits until the post-complete runnable // finishes -> AsyncTail lands IN-WINDOW inside W1 with zero silent leakage! try (ForkedApp app = startFork(server, "2000", prefixMode, false, null, null)) { String warmCov = app.runHttpTest("ac/" + server + "-warm2", "/clean"); + assertFalse(label + " warm2 /clean must not be contaminated: " + warmCov, + warmCov.contains("contaminated")); + assertTrue(label + " must keep asyncExecutors=true on warm2: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); String cov1 = app.runHttpTest("ac/" + server + "-inwindow", "/async-after-complete?ms=250"); assertFalse(label + " sufficient wait must not cut: " + cov1, cov1.contains("windowCut")); + assertFalse(label + " sufficient wait must not contaminate W1: " + cov1, + cov1.contains("contaminated")); assertTrue(label + " post-complete AsyncTail must land IN-WINDOW in W1: " + cov1, cov1.contains("\"" + ASYNC_TAIL + "\"")); String cov2 = app.runHttpTest("ac/" + server + "-clean", "/clean"); assertFalse(label + " W2 must not contain AsyncTail: " + cov2, cov2.contains("\"" + ASYNC_TAIL + "\"")); - if (!isUndertow) { - assertFalse(label + " sufficient wait must not contaminate W1: " + cov1, - cov1.contains("contaminated")); - assertFalse(label + " W2 after in-window completion must be clean: " + cov2, - cov2.contains("contaminated")); - } else { - // Undertow's EnhancedQueueExecutor/JBossThread is NOT allowlisted: either - // the warm request flags untracked-sink:thread-start or startup latched - // asyncExecutors=false. - boolean failClosed = warmCov.contains("untracked-sink:thread-start:") - || !parseHello(app.lastHello).get("asyncExecutors").getAsBoolean(); - assertTrue(label + " Undertow JBossThread must not be allowlisted: warm=" + warmCov - + " hello=" + app.lastHello, failClosed); - } + assertFalse(label + " W2 after in-window completion must be clean: " + cov2, + cov2.contains("contaminated")); + + // 2b. Servlet AsyncContext.dispatch() (Spring MVC Callable & DeferredResult patterns) + // must keep asyncExecutors=true with zero contamination on Tomcat, Jetty, and Undertow. + String covCall = app.runHttpTest("ac/" + server + "-dispatch-callable", "/async-dispatch-callable?ms=20", + "dispatched-ok"); + assertFalse(label + " /async-dispatch-callable must not be contaminated: " + covCall, + covCall.contains("contaminated")); + assertFalse(label + " /async-dispatch-callable must not cut: " + covCall, + covCall.contains("windowCut")); + assertTrue(label + " /async-dispatch-callable must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String covDef = app.runHttpTest("ac/" + server + "-dispatch-deferred", "/async-dispatch-deferred?ms=20", + "dispatched-ok"); + assertFalse(label + " /async-dispatch-deferred must not be contaminated: " + covDef, + covDef.contains("contaminated")); + assertFalse(label + " /async-dispatch-deferred must not cut: " + covDef, + covDef.contains("windowCut")); + assertTrue(label + " /async-dispatch-deferred must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + } + + // 3. Reflective escapes into Jetty 9.4 QueuedThreadPool / ScheduledExecutorScheduler + // and Undertow 2.2 XnioIoThread must fail closed (never silent). + for (String path : new String[] {"/escape-jetty-qtp-reflect?ms=200", "/escape-jetty-sched-reflect?ms=200"}) { + try (ForkedApp app = startFork("jetty", "80", prefixMode, false, null, null)) { + app.runHttpTest("ac/jetty-esc-warm", "/clean"); + assertTrue("jetty94 baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String covEsc = app.runHttpTest("ac/jetty-esc", path); + assertTrue("jetty94 " + path + " must trip server-executor sink (prefix=" + prefixMode + "): " + covEsc, + covEsc.contains("untracked-sink:server-executor:org.eclipse.jetty.util.thread.")); + assertFalse("jetty94 " + path + " must latch asyncExecutors=false: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + } + for (String path : new String[] {"/escape-undertow-io-reflect?ms=200", "/escape-undertow-io-after-reflect?ms=200"}) { + try (ForkedApp app = startFork("undertow", "80", prefixMode, false, null, null)) { + app.runHttpTest("ac/ut22-esc-warm", "/clean"); + assertTrue("undertow22 baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String covEsc = app.runHttpTest("ac/ut22-esc", path); + assertTrue("undertow22 " + path + " must trip server-executor sink (prefix=" + prefixMode + "): " + covEsc, + covEsc.contains("untracked-sink:server-executor:org.xnio.nio.WorkerThread:")); + assertFalse("undertow22 " + path + " must latch asyncExecutors=false: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); } } } @@ -859,6 +896,806 @@ private ForkedApp startJakartaTomcat10Fork(File jakartaClassesDir, File tomcat10 } } + @Test(timeout = 900000) + public void forkedJakartaJetty11Jetty12AndUndertow23DedupSafelyAndFailClosedOnEscapes() throws Exception { + // Spring Boot 3/4 Jakarta Servlet rows: Jetty 11.0.24, Jetty 12.0.16 (ee10), + // Jetty 12.1.15 (ee11), and Undertow 2.3.18 staged by the JDK 17+ Maven profile + // (skipped cleanly on JDK 8/11). + File jetty11Dir = new File("target/jetty11"); + File jetty12Dir = new File("target/jetty12"); + File jetty121Dir = new File("target/jetty121"); + File undertow23Dir = new File("target/undertow23"); + org.junit.Assume.assumeTrue("Jakarta Jetty 11/12/12.1 & Undertow 2.3 rows require JDK 17+ profile", + hasJars(jetty11Dir) && hasJars(jetty12Dir) && hasJars(jetty121Dir) && hasJars(undertow23Dir)); + + // 1. Jetty 11.0.24: asyncExecutors=true, windowCut=true, clean dedup, AsyncContext.start 80ms/2000ms. + verifyJakartaServerFork("jetty11", jetty11Dir, "org.example.jkj11", "JakartaJetty11App", + buildJakartaJetty11Source(), false, false); + + // 2. Jetty 12.0.16 (ee10): asyncExecutors=true, windowCut=true, clean dedup, AsyncContext.start 80ms/2000ms, + // AsyncContext.dispatch (Callable/DeferredResult), AND adversarial escapes fail closed. + verifyJakartaServerFork("jetty12", jetty12Dir, "org.example.jkj12", "JakartaJetty12App", + buildJakartaJetty12Source("org.example.jkj12", "ee10"), true, false); + + // 3. Jetty 12.1.15 (ee11, Spring Boot 4 on Jetty): asyncExecutors=true, windowCut=true, clean dedup, + // AsyncContext.start 80ms/2000ms, AsyncContext.dispatch (Callable/DeferredResult via ee11 + // ServletChannelState#scheduleDispatch + VirtualThreads#execute), AND adversarial escapes fail closed. + verifyJakartaServerFork("jetty121", jetty121Dir, "org.example.jkj121", "JakartaJetty12App", + buildJakartaJetty12Source("org.example.jkj121", "ee11"), true, false); + + // 4. Undertow 2.3.18: asyncExecutors=true, windowCut=true, clean dedup (0 contamination despite lazy + // XNIO-1 task-* worker spawn), AsyncContext.start 80ms/2000ms, AND adversarial escapes: + // - in-window XnioWorker.execute is tracked (no silent leak) + // - outside-window XnioWorker.execute latches asyncExecutors=false + // - user-created EnhancedQueueExecutor still fails closed (never allowlisted). + verifyJakartaServerFork("undertow23", undertow23Dir, "org.example.jkut23", "JakartaUndertow23App", + buildJakartaUndertow23Source(), false, true); + } + + private static boolean hasJars(File dir) { + if (!dir.isDirectory()) { + return false; + } + File[] jars = dir.listFiles((d, name) -> name.endsWith(".jar")); + return jars != null && jars.length > 0; + } + + private void verifyJakartaServerFork(String serverName, File depsDir, String pkg, String mainSimpleName, + String mainSource, boolean checkJettyImmediateEscape, boolean checkUndertowEscapes) throws Exception { + File srcDir = tmp.newFolder("jk-" + serverName + "-src"); + File outDir = tmp.newFolder("jk-" + serverName + "-classes"); + File libDir = tmp.newFolder("jk-" + serverName + "-lib"); + File pkgDir = new File(srcDir, pkg.replace('.', '/')); + assertTrue(pkgDir.mkdirs()); + File tailSrc = new File(pkgDir, "JakartaAsyncTail.java"); + Files.write(tailSrc.toPath(), ( + "package " + pkg + ";\n" + + "public final class JakartaAsyncTail {\n" + + " private static volatile int hits;\n" + + " public static void ran() { hits++; }\n" + + "}\n").getBytes(StandardCharsets.UTF_8)); + File appSrc = new File(pkgDir, mainSimpleName + ".java"); + Files.write(appSrc.toPath(), mainSource.getBytes(StandardCharsets.UTF_8)); + + String depsCp = joinDirJars(depsDir); + javax.tools.JavaCompiler compiler = javax.tools.ToolProvider.getSystemJavaCompiler(); + assertNotNull("JDK compiler required for " + serverName, compiler); + // Compile a non-app third-party helper into libDir (on -cp, NOT in KEPLOY_JAVA_CLASS_DIRS + // and NOT in org.example.*) so ServerEntries never rewrites its call sites. + File libPkgDir = new File(srcDir, "com/thirdparty"); + assertTrue(libPkgDir.mkdirs()); + File libSrc = new File(libPkgDir, "LibHandOff.java"); + if (checkJettyImmediateEscape) { + Files.write(libSrc.toPath(), ( + "package com.thirdparty;\n" + + "import java.util.concurrent.TimeUnit;\n" + + "import org.eclipse.jetty.util.thread.QueuedThreadPool;\n" + + "import org.eclipse.jetty.util.thread.Scheduler;\n" + + "public final class LibHandOff {\n" + + " public static void execQtp(QueuedThreadPool qtp, Runnable r) { qtp.execute(r); }\n" + + " public static void sched(Scheduler s, Runnable r, long ms) { s.schedule(r, ms, TimeUnit.MILLISECONDS); }\n" + + " public static void schedDuration(Scheduler s, Runnable r, long ms) { s.schedule(r, java.time.Duration.ofMillis(ms)); }\n" + + " public static void execContext(org.eclipse.jetty.server.Context c, Runnable r) { c.execute(r); }\n" + + "}\n").getBytes(StandardCharsets.UTF_8)); + assertEquals("compile Jetty LibHandOff", 0, compiler.run(null, null, null, + "-cp", depsCp, "-d", libDir.getAbsolutePath(), libSrc.getAbsolutePath())); + } else if (checkUndertowEscapes) { + Files.write(libSrc.toPath(), ( + "package com.thirdparty;\n" + + "import java.util.concurrent.TimeUnit;\n" + + "import org.xnio.XnioIoThread;\n" + + "public final class LibHandOff {\n" + + " public static void execIo(XnioIoThread io, Runnable r) { io.execute(r); }\n" + + " public static void afterIo(XnioIoThread io, Runnable r, long ms) { io.executeAfter(r, ms, TimeUnit.MILLISECONDS); }\n" + + " public static void workerUtilsAfter(XnioIoThread ioThread, Runnable r, long ms) { io.undertow.util.WorkerUtils.executeAfter(ioThread, r, ms, TimeUnit.MILLISECONDS); }\n" + + "}\n").getBytes(StandardCharsets.UTF_8)); + assertEquals("compile Undertow LibHandOff", 0, compiler.run(null, null, null, + "-cp", depsCp, "-d", libDir.getAbsolutePath(), libSrc.getAbsolutePath())); + } + int rc = compiler.run(null, null, null, "-cp", depsCp + File.pathSeparator + libDir.getAbsolutePath(), + "-d", outDir.getAbsolutePath(), tailSrc.getAbsolutePath(), appSrc.getAbsolutePath()); + assertEquals("compile " + mainSimpleName, 0, rc); + + String tailPath = pkg.replace('.', '/') + "/JakartaAsyncTail"; + String fqcn = pkg + "." + mainSimpleName; + for (boolean prefixMode : new boolean[] {true, false}) { + String label = serverName + " mode=" + (prefixMode ? "prefix" : "index"); + // (a) Short endWait=80ms: clean requests stay uncontaminated with asyncExecutors=true, + // and AsyncContext.start after complete() flags windowCut:true + W2 tail + clean W3 drain. + try (ForkedApp app = startJakartaIsolatedFork(serverName, outDir, libDir, depsDir, fqcn, "80", + prefixMode, null)) { + JsonObject hello = parseHello(app.initialHello); + assertTrue(label + " must declare windowCut=true: " + app.initialHello, + hello.get("windowCut").getAsBoolean()); + String warm1 = app.runHttpTest("jk/" + serverName + "-w1", "/clean"); + assertFalse(label + " W1 /clean must not be contaminated: " + warm1, + warm1.contains("contaminated")); + assertTrue(label + " must keep asyncExecutors=true after W1 /clean: " + app.lastHello + + "\nlog:\n" + readFile(app.log), + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String warm2 = app.runHttpTest("jk/" + serverName + "-w2", "/clean"); + assertFalse(label + " W2 /clean must not be contaminated: " + warm2, + warm2.contains("contaminated")); + String warm3 = app.runHttpTest("jk/" + serverName + "-w3", "/clean"); + assertFalse(label + " W3 /clean must not be contaminated: " + warm3, + warm3.contains("contaminated")); + String lines2 = extractExecutedLines(warm2); + String lines3 = extractExecutedLines(warm3); + assertFalse(label + " /clean must record non-empty executedLinesByFile", + "{}".equals(lines2)); + assertEquals(label + " identical /clean requests must produce identical executedLinesByFile", + lines2, lines3); + + String cov1 = app.runHttpTest("jk/" + serverName + "-cut", "/async-after-complete?ms=400"); + assertTrue(label + " W1 must report windowCut:true: " + cov1, + cov1.contains("\"windowCut\":true")); + String cov2 = app.runHttpTest("jk/" + serverName + "-next", "/clean"); + assertTrue(label + " W2 must carry tail:jk/" + serverName + "-cut: " + cov2, + cov2.contains("\"tail:jk/" + serverName + "-cut\"")); + Thread.sleep(600); + String cov3 = app.runHttpTest("jk/" + serverName + "-drained", "/clean"); + assertFalse(label + " W3 after drain must not be windowCut: " + cov3, cov3.contains("windowCut")); + assertFalse(label + " W3 after drain must not be contaminated: " + cov3, + cov3.contains("contaminated")); + } + + // (b) Sufficient endWait=2000ms: AsyncTail lands IN-WINDOW in W1 with zero contamination. + try (ForkedApp app = startJakartaIsolatedFork(serverName, outDir, libDir, depsDir, fqcn, "2000", + prefixMode, null)) { + String cov1 = app.runHttpTest("jk/" + serverName + "-inwin", "/async-after-complete?ms=250"); + assertFalse(label + " sufficient wait must not cut: " + cov1, cov1.contains("windowCut")); + assertFalse(label + " sufficient wait must not contaminate W1: " + cov1, + cov1.contains("contaminated")); + assertTrue(label + " post-complete JakartaAsyncTail must land IN-WINDOW in W1: " + cov1, + cov1.contains("\"" + tailPath + "\"")); + assertTrue(label + " must keep asyncExecutors=true after in-window async: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String cov2 = app.runHttpTest("jk/" + serverName + "-clean", "/clean"); + assertFalse(label + " W2 must be clean: " + cov2, cov2.contains("contaminated")); + assertFalse(label + " W2 must not contain JakartaAsyncTail: " + cov2, + cov2.contains("\"" + tailPath + "\"")); + + // Servlet AsyncContext.dispatch() (Spring MVC Callable & DeferredResult patterns) + // must keep asyncExecutors=true with zero contamination on Jetty 11/12 & Undertow 2.3. + String covCall = app.runHttpTest("jk/" + serverName + "-dispatch-callable", "/async-dispatch-callable?ms=20", + "dispatched-ok"); + assertFalse(label + " /async-dispatch-callable must not be contaminated: " + covCall, + covCall.contains("contaminated")); + assertFalse(label + " /async-dispatch-callable must not cut: " + covCall, + covCall.contains("windowCut")); + assertTrue(label + " /async-dispatch-callable must keep asyncExecutors=true: " + app.lastHello + + "\nlog:\n" + readFile(app.log), + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String covDef = app.runHttpTest("jk/" + serverName + "-dispatch-deferred", "/async-dispatch-deferred?ms=20", + "dispatched-ok"); + assertFalse(label + " /async-dispatch-deferred must not be contaminated: " + covDef, + covDef.contains("contaminated")); + assertFalse(label + " /async-dispatch-deferred must not cut: " + covDef, + covDef.contains("windowCut")); + assertTrue(label + " /async-dispatch-deferred must keep asyncExecutors=true: " + app.lastHello + + "\nlog:\n" + readFile(app.log), + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + } + + // (c) Adversarial escape rows proving zero false removals on Jetty 12 & Undertow 2.3. + if (checkJettyImmediateEscape) { + try (ForkedApp app = startJakartaIsolatedFork(serverName + "-esc", outDir, libDir, depsDir, fqcn, "2000", + false, null)) { + app.runHttpTest("jk/j12-warm", "/clean"); + assertTrue("Jetty 12 baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String covEsc = app.runHttpTest("jk/j12-imm", "/escape-immediate"); + assertTrue("Jetty 12 ThreadPool.executeImmediately must contaminate W1: " + covEsc, + covEsc.contains("contaminated")); + assertFalse("Jetty 12 ThreadPool.executeImmediately must latch asyncExecutors=false: " + + app.lastHello, parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + // Reflective and non-app-library escapes into Jetty 12 QueuedThreadPool & ScheduledExecutorScheduler. + for (boolean pm : new boolean[] {true, false}) { + for (String path : new String[] { + "/escape-qtp-reflect?ms=200", "/escape-sched-reflect?ms=200", + "/escape-qtp-lib?ms=200", "/escape-sched-lib?ms=200", + "/escape-reserved-try?ms=200", + "/escape-sched-duration-lib?ms=200", "/escape-server-context-lib?ms=200", + "/escape-cyclic-timeout?ms=200", + "/escape-cyclic-timeouts?ms=200", + "/escape-idle-timeout?ms=200", + "/escape-socket-endpoint-idle?ms=200" + }) { + try (ForkedApp app = startJakartaIsolatedFork(serverName + "-srv-esc", outDir, libDir, depsDir, + fqcn, "80", pm, null)) { + app.runHttpTest("jk/j12-srv-warm", "/clean"); + assertTrue("Jetty 12 baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String covEsc = app.runHttpTest("jk/j12-srv-esc", path); + assertTrue("Jetty 12 " + path + " must trip server-executor sink (prefix=" + pm + "): " + covEsc, + covEsc.contains("untracked-sink:server-executor:org.eclipse.jetty.")); + assertFalse("Jetty 12 " + path + " must latch asyncExecutors=false: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + } + } + } + if (checkUndertowEscapes) { + // (c1) Direct in-window XnioWorker.execute is tracked (2000ms IN-WINDOW cleanly). + try (ForkedApp app = startJakartaIsolatedFork(serverName + "-xnio-inwin", outDir, libDir, depsDir, fqcn, + "2000", false, null)) { + String cov = app.runHttpTest("jk/ut-xnio-inwin", "/xnio-exec?ms=200"); + assertFalse("in-window XnioWorker.execute must not cut under 2000ms: " + cov, + cov.contains("windowCut")); + assertFalse("in-window XnioWorker.execute must not contaminate: " + cov, + cov.contains("contaminated")); + assertTrue("in-window XnioWorker.execute must capture JakartaAsyncTail IN-WINDOW: " + cov, + cov.contains("\"" + tailPath + "\"")); + } + // (c2) Outside-window XnioWorker.execute at startup must latch asyncExecutors=false. + try (ForkedApp app = startJakartaIsolatedFork(serverName + "-xnio-boot", outDir, libDir, depsDir, fqcn, + "2000", false, "boot-xnio-outside")) { + app.runHttpTest("jk/ut-boot-warm", "/clean"); + assertFalse("outside-window XnioWorker.execute at startup must latch asyncExecutors=false: " + + app.lastHello, parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + // (c3a) In-window XnioIoThread.executeAfter queues the task on an I/O selector thread + // (no JDK sink, no window permit): it runs after END, so W1 must be flagged and + // the tail must never land silently in a later window, in both modes. + for (boolean pm : new boolean[] {true, false}) { + try (ForkedApp app = startJakartaIsolatedFork(serverName + "-io-after", outDir, libDir, depsDir, fqcn, + "80", pm, null)) { + app.runHttpTest("jk/ut-io-after-warm", "/clean"); + assertTrue("Undertow 2.3 baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String cov1 = app.runHttpTest("jk/ut-io-after", "/xnio-io-after?ms=300"); + assertFalse("executeAfter tail must not run inside W1: " + cov1, + cov1.contains("\"" + tailPath + "\"")); + assertTrue("in-window XnioIoThread.executeAfter must contaminate W1 (prefix=" + pm + "): " + cov1, + cov1.contains("untracked-async:xnio-execute-after") + || cov1.contains("untracked-sink:server-executor:org.xnio.nio.WorkerThread:")); + String cov2 = app.runHttpTest("jk/ut-io-after-next", "/sleep-clean"); + Thread.sleep(500); + String cov3 = app.runHttpTest("jk/ut-io-after-drained", "/clean"); + for (String later : new String[] {cov2, cov3}) { + if (later.contains("\"" + tailPath + "\"")) { + assertTrue("a window holding the executeAfter tail must be flagged: " + later, + later.contains("contaminated") || later.contains("unverified")); + } + } + } + // (c3b) Reflective and non-app-library hand-offs to XnioIoThread.execute / executeAfter + // and Undertow's public WorkerUtils.executeAfter forwarder. + for (String path : new String[] { + "/escape-io-exec-reflect?ms=200", "/escape-io-after-reflect?ms=200", + "/escape-io-exec-lib?ms=200", "/escape-io-after-lib?ms=200", + "/escape-worker-utils-after-lib?ms=200", "/escape-worker-utils-after?ms=200" + }) { + try (ForkedApp app = startJakartaIsolatedFork(serverName + "-io-esc", outDir, libDir, depsDir, fqcn, + "80", pm, null)) { + app.runHttpTest("jk/ut-io-esc-warm", "/clean"); + assertTrue("Undertow 2.3 baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String covEsc = app.runHttpTest("jk/ut-io-esc", path); + assertTrue("Undertow 2.3 " + path + " must trip server-executor sink (prefix=" + pm + "): " + covEsc, + covEsc.contains("untracked-sink:server-executor:org.xnio.nio.WorkerThread:")); + assertFalse("Undertow 2.3 " + path + " must latch asyncExecutors=false: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + } + } + } + // (c3) User-created EnhancedQueueExecutor must STILL fail closed (never allowlisted). + try (ForkedApp app = startJakartaIsolatedFork(serverName + "-eqe-escape", outDir, libDir, depsDir, fqcn, + "2000", false, null)) { + app.runHttpTest("jk/ut-eqe-warm", "/clean"); + assertTrue("Undertow 2.3 baseline must keep asyncExecutors=true: " + app.lastHello, + parseHello(app.lastHello).get("asyncExecutors").getAsBoolean()); + String covEsc = app.runHttpTest("jk/ut-eqe-w1", "/escape-user-eqe"); + assertTrue("user-created EnhancedQueueExecutor must trip JDK Thread.start sink: cov=" + covEsc + + " hello=" + app.lastHello, + covEsc.contains("untracked-sink:thread-start:org.jboss.threads.EnhancedQueueExecutor")); + assertTrue("user-created EnhancedQueueExecutor must mark window contaminated: cov=" + covEsc, + covEsc.contains("\"contaminated\":[")); + } + } + } + + private static String extractExecutedLines(String covJson) { + String json = covJson.startsWith("COV ") ? covJson.substring("COV ".length()) : covJson; + assertTrue("expected COV JSON object, got: " + covJson, json.startsWith("{")); + JsonObject obj = JsonParser.parseString(json).getAsJsonObject(); + assertTrue("expected executedLinesByFile in COV JSON: " + covJson, obj.has("executedLinesByFile")); + return obj.get("executedLinesByFile").toString(); + } + + private static String joinDirJars(File dir) { + File[] jars = dir.listFiles((d, name) -> name.endsWith(".jar")); + assertNotNull("no jars in " + dir, jars); + List paths = new ArrayList<>(); + for (File jar : jars) { + paths.add(jar.getAbsolutePath()); + } + return String.join(File.pathSeparator, paths); + } + + private ForkedApp startJakartaIsolatedFork(String tag, File classesDir, File extraLibDir, File depsDir, + String mainClass, String endWait, boolean externalJacocoPrefixMode, String extraArg) 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-" + tag + "-" + System.nanoTime() + ".jar"); + AgentJar.extractTo(jacocoJar); + cmd.add("-javaagent:" + jacocoJar.getPath() + "=includes=org.example.*,output=none"); + } + cmd.add("-javaagent:" + sdkJar().getPath()); + List cp = new ArrayList<>(); + cp.add(classesDir.getAbsolutePath()); + if (extraLibDir != null) { + cp.add(extraLibDir.getAbsolutePath()); + } + File[] depJars = depsDir.listFiles((d, name) -> name.endsWith(".jar")); + assertNotNull("no jars in " + depsDir, depJars); + for (File jar : depJars) { + cp.add(jar.getAbsolutePath()); + } + for (String entry : System.getProperty("java.class.path").split(File.pathSeparator)) { + String base = new File(entry).getName(); + if (base.startsWith("tomcat-embed-") || base.startsWith("tomcat-annotations-") + || base.startsWith("javax.servlet") || base.startsWith("jakarta.servlet") + || base.startsWith("jakarta.annotation") || base.startsWith("jetty-") + || base.startsWith("undertow-") || base.startsWith("xnio-") + || base.startsWith("jboss-threads-") || base.startsWith("jboss-logging-") + || base.startsWith("wildfly-") || base.startsWith("slf4j-")) { + continue; + } + cp.add(new File(entry).getAbsolutePath()); + } + cmd.add("-cp"); + cmd.add(String.join(File.pathSeparator, cp)); + cmd.add(mainClass); + if (extraArg != null) { + cmd.add(extraArg); + } + + File log = tmp.newFile("fork-" + tag + "-" + 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) { + env.put("KEPLOY_JAVA_CLASS_DIRS", classesDir.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", endWait); + env.put("KEPLOY_DEDUP_POD_UID", "pod-uid-" + tag); + env.put("KEPLOY_DEDUP_POD_NAME", "pod-name-" + tag); + env.put("KEPLOY_DEDUP_SESSION_ID", "session-" + tag); + + 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 static String buildJakartaJetty11Source() { + return "package org.example.jkj11;\n" + + "import jakarta.servlet.AsyncContext;\n" + + "import jakarta.servlet.http.HttpServlet;\n" + + "import jakarta.servlet.http.HttpServletRequest;\n" + + "import jakarta.servlet.http.HttpServletResponse;\n" + + "import java.io.IOException;\n" + + "import java.nio.charset.StandardCharsets;\n" + + "import org.eclipse.jetty.server.Server;\n" + + "import org.eclipse.jetty.server.ServerConnector;\n" + + "import org.eclipse.jetty.servlet.ServletContextHandler;\n" + + "import org.eclipse.jetty.servlet.ServletHolder;\n" + + "public final class JakartaJetty11App {\n" + + " private static final java.util.concurrent.ExecutorService DEFERRED_POOL = java.util.concurrent.Executors.newSingleThreadExecutor(r -> {\n" + + " Thread t = new Thread(r, \"j11-deferred\"); t.setDaemon(true); return t;\n" + + " });\n" + + " public static void main(String[] args) throws Exception {\n" + + " Server server = new Server(0);\n" + + " ServletContextHandler ctx = new ServletContextHandler();\n" + + " ServletHolder h = new ServletHolder(new HttpServlet() {\n" + + " @Override\n" + + " protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {\n" + + " String path = req.getRequestURI();\n" + + " long ms = req.getParameter(\"ms\") == null ? 0L : Long.parseLong(req.getParameter(\"ms\"));\n" + + " if (\"/async-dispatch-callable\".equals(path)) {\n" + + " final AsyncContext ac = req.startAsync();\n" + + " ac.start(() -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " ac.dispatch(\"/async-dispatch-done\");\n" + + " });\n" + + " return;\n" + + " }\n" + + " if (\"/async-dispatch-deferred\".equals(path)) {\n" + + " final AsyncContext ac = req.startAsync();\n" + + " DEFERRED_POOL.submit(() -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " ac.dispatch(\"/async-dispatch-done\");\n" + + " });\n" + + " return;\n" + + " }\n" + + " if (\"/async-dispatch-done\".equals(path)) {\n" + + " byte[] ok = \"dispatched-ok\".getBytes(StandardCharsets.UTF_8);\n" + + " resp.setContentType(\"text/plain\");\n" + + " resp.setContentLength(ok.length);\n" + + " resp.getOutputStream().write(ok);\n" + + " resp.flushBuffer();\n" + + " return;\n" + + " }\n" + + " if (\"/async-after-complete\".equals(path)) {\n" + + " final AsyncContext ac = req.startAsync();\n" + + " ac.start(() -> {\n" + + " try {\n" + + " byte[] ok = \"ok\".getBytes(StandardCharsets.UTF_8);\n" + + " HttpServletResponse ar = (HttpServletResponse) ac.getResponse();\n" + + " ar.setContentType(\"text/plain\");\n" + + " ar.setContentLength(ok.length);\n" + + " ar.getOutputStream().write(ok);\n" + + " ar.flushBuffer();\n" + + " } catch (IOException ignored) {\n" + + " } finally {\n" + + " ac.complete();\n" + + " }\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " return;\n" + + " }\n" + + " byte[] body = \"ok\".getBytes(StandardCharsets.UTF_8);\n" + + " resp.setContentType(\"text/plain\");\n" + + " resp.setContentLength(body.length);\n" + + " resp.getOutputStream().write(body);\n" + + " resp.flushBuffer();\n" + + " }\n" + + " });\n" + + " h.setAsyncSupported(true);\n" + + " ctx.addServlet(h, \"/*\");\n" + + " server.setHandler(ctx);\n" + + " server.start();\n" + + " System.out.println(\"PORT \" + ((ServerConnector) server.getConnectors()[0]).getLocalPort());\n" + + " System.out.flush();\n" + + " while (System.in.read() >= 0) { }\n" + + " server.stop();\n" + + " System.exit(0);\n" + + " }\n" + + "}\n"; + } + + private static String buildJakartaJetty12Source(String pkg, String eePkg) { + return "package " + pkg + ";\n" + + "import jakarta.servlet.AsyncContext;\n" + + "import jakarta.servlet.http.HttpServlet;\n" + + "import jakarta.servlet.http.HttpServletRequest;\n" + + "import jakarta.servlet.http.HttpServletResponse;\n" + + "import java.io.IOException;\n" + + "import java.nio.charset.StandardCharsets;\n" + + "import org.eclipse.jetty." + eePkg + ".servlet.ServletContextHandler;\n" + + "import org.eclipse.jetty." + eePkg + ".servlet.ServletHolder;\n" + + "import org.eclipse.jetty.server.Server;\n" + + "import org.eclipse.jetty.server.ServerConnector;\n" + + "import org.eclipse.jetty.util.thread.ThreadPool;\n" + + "public final class JakartaJetty12App {\n" + + " private static final java.util.concurrent.ExecutorService DEFERRED_POOL = java.util.concurrent.Executors.newSingleThreadExecutor(r -> {\n" + + " Thread t = new Thread(r, \"j12-deferred\"); t.setDaemon(true); return t;\n" + + " });\n" + + " public static void main(String[] args) throws Exception {\n" + + " final Server server = new Server(0);\n" + + " ServletContextHandler ctx = new ServletContextHandler();\n" + + " ServletHolder h = new ServletHolder(new HttpServlet() {\n" + + " @Override\n" + + " protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {\n" + + " String path = req.getRequestURI();\n" + + " long ms = req.getParameter(\"ms\") == null ? 0L : Long.parseLong(req.getParameter(\"ms\"));\n" + + " if (\"/async-dispatch-callable\".equals(path)) {\n" + + " final AsyncContext ac = req.startAsync();\n" + + " ac.start(() -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " ac.dispatch(\"/async-dispatch-done\");\n" + + " });\n" + + " return;\n" + + " }\n" + + " if (\"/async-dispatch-deferred\".equals(path)) {\n" + + " final AsyncContext ac = req.startAsync();\n" + + " DEFERRED_POOL.submit(() -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " ac.dispatch(\"/async-dispatch-done\");\n" + + " });\n" + + " return;\n" + + " }\n" + + " if (\"/async-dispatch-done\".equals(path)) {\n" + + " byte[] ok = \"dispatched-ok\".getBytes(StandardCharsets.UTF_8);\n" + + " resp.setContentType(\"text/plain\");\n" + + " resp.setContentLength(ok.length);\n" + + " resp.getOutputStream().write(ok);\n" + + " resp.flushBuffer();\n" + + " return;\n" + + " }\n" + + " if (\"/async-after-complete\".equals(path)) {\n" + + " final AsyncContext ac = req.startAsync();\n" + + " ac.start(() -> {\n" + + " try {\n" + + " byte[] ok = \"ok\".getBytes(StandardCharsets.UTF_8);\n" + + " HttpServletResponse ar = (HttpServletResponse) ac.getResponse();\n" + + " ar.setContentType(\"text/plain\");\n" + + " ar.setContentLength(ok.length);\n" + + " ar.getOutputStream().write(ok);\n" + + " ar.flushBuffer();\n" + + " } catch (IOException ignored) {\n" + + " } finally {\n" + + " ac.complete();\n" + + " }\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " return;\n" + + " }\n" + + " if (\"/escape-immediate\".equals(path)) {\n" + + " ThreadPool.executeImmediately(server.getThreadPool(), () -> JakartaAsyncTail.ran());\n" + + " }\n" + + " if (\"/escape-qtp-reflect\".equals(path)) {\n" + + " try {\n" + + " Object qtp = server.getThreadPool();\n" + + " java.lang.reflect.Method m = qtp.getClass().getMethod(\"execute\", Runnable.class);\n" + + " m.invoke(qtp, (Runnable) () -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " } catch (Exception e) { throw new IOException(e); }\n" + + " }\n" + + " if (\"/escape-sched-reflect\".equals(path)) {\n" + + " try {\n" + + " Object sched = ((ServerConnector) server.getConnectors()[0]).getScheduler();\n" + + " java.lang.reflect.Method m = sched.getClass().getMethod(\"schedule\", Runnable.class, long.class, java.util.concurrent.TimeUnit.class);\n" + + " m.invoke(sched, (Runnable) () -> JakartaAsyncTail.ran(), Long.valueOf(ms), java.util.concurrent.TimeUnit.MILLISECONDS);\n" + + " } catch (Exception e) { throw new IOException(e); }\n" + + " }\n" + + " if (\"/escape-qtp-lib\".equals(path)) {\n" + + " com.thirdparty.LibHandOff.execQtp((org.eclipse.jetty.util.thread.QueuedThreadPool) server.getThreadPool(), () -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " }\n" + + " if (\"/escape-sched-lib\".equals(path)) {\n" + + " com.thirdparty.LibHandOff.sched(((ServerConnector) server.getConnectors()[0]).getScheduler(), () -> JakartaAsyncTail.ran(), ms);\n" + + " }\n" + + " if (\"/escape-sched-duration-lib\".equals(path)) {\n" + + " com.thirdparty.LibHandOff.schedDuration(((ServerConnector) server.getConnectors()[0]).getScheduler(), () -> JakartaAsyncTail.ran(), ms);\n" + + " }\n" + + " if (\"/escape-server-context-lib\".equals(path)) {\n" + + " com.thirdparty.LibHandOff.execContext(server.getContext(), () -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " }\n" + + " if (\"/escape-cyclic-timeout\".equals(path)) {\n" + + " new org.eclipse.jetty.io.CyclicTimeout(((ServerConnector) server.getConnectors()[0]).getScheduler()) {\n" + + " @Override public void onTimeoutExpired() { JakartaAsyncTail.ran(); }\n" + + " }.schedule(ms, java.util.concurrent.TimeUnit.MILLISECONDS);\n" + + " }\n" + + " if (\"/escape-cyclic-timeouts\".equals(path)) {\n" + + " final long expNano = System.nanoTime() + java.util.concurrent.TimeUnit.MILLISECONDS.toNanos(ms);\n" + + " org.eclipse.jetty.io.CyclicTimeouts.Expirable exp = () -> expNano;\n" + + " new org.eclipse.jetty.io.CyclicTimeouts(((ServerConnector) server.getConnectors()[0]).getScheduler()) {\n" + + " @Override protected java.util.Iterator iterator() { return java.util.Collections.singleton(exp).iterator(); }\n" + + " @Override protected boolean onExpired(org.eclipse.jetty.io.CyclicTimeouts.Expirable e) { JakartaAsyncTail.ran(); return true; }\n" + + " }.schedule(exp);\n" + + " }\n" + + " if (\"/escape-idle-timeout\".equals(path)) {\n" + + " org.eclipse.jetty.io.IdleTimeout it = new org.eclipse.jetty.io.IdleTimeout(((ServerConnector) server.getConnectors()[0]).getScheduler()) {\n" + + " @Override protected void onIdleExpired(java.util.concurrent.TimeoutException t) { JakartaAsyncTail.ran(); }\n" + + " @Override public boolean isOpen() { return true; }\n" + + " };\n" + + " it.setIdleTimeout(ms);\n" + + " it.onOpen();\n" + + " }\n" + + " if (\"/escape-socket-endpoint-idle\".equals(path)) {\n" + + " final java.nio.channels.SocketChannel ch = java.nio.channels.SocketChannel.open();\n" + + " final org.eclipse.jetty.io.SocketChannelEndPoint ep = new org.eclipse.jetty.io.SocketChannelEndPoint(ch, null, null,\n" + + " ((ServerConnector) server.getConnectors()[0]).getScheduler());\n" + + " ep.setConnection(new org.eclipse.jetty.io.AbstractConnection(ep, server.getThreadPool()) {\n" + + " @Override public void onFillable() { }\n" + + " @Override public boolean onIdleExpired(java.util.concurrent.TimeoutException t) {\n" + + " JakartaAsyncTail.ran();\n" + + " try { ch.close(); } catch (IOException ignored) { }\n" + + " return false;\n" + + " }\n" + + " });\n" + + " ep.setIdleTimeout(ms);\n" + + " }\n" + + " if (\"/escape-reserved-try\".equals(path)) {\n" + + " org.eclipse.jetty.util.thread.ReservedThreadExecutor rte = ((org.eclipse.jetty.util.component.Container) server.getThreadPool())\n" + + " .getBean(org.eclipse.jetty.util.thread.ReservedThreadExecutor.class);\n" + + " rte.tryExecute(() -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " }\n" + + " byte[] body = \"ok\".getBytes(StandardCharsets.UTF_8);\n" + + " resp.setContentType(\"text/plain\");\n" + + " resp.setContentLength(body.length);\n" + + " resp.getOutputStream().write(body);\n" + + " resp.flushBuffer();\n" + + " }\n" + + " });\n" + + " h.setAsyncSupported(true);\n" + + " ctx.addServlet(h, \"/*\");\n" + + " server.setHandler(ctx);\n" + + " server.start();\n" + + " System.out.println(\"PORT \" + ((ServerConnector) server.getConnectors()[0]).getLocalPort());\n" + + " System.out.flush();\n" + + " while (System.in.read() >= 0) { }\n" + + " server.stop();\n" + + " System.exit(0);\n" + + " }\n" + + "}\n"; + } + + private static String buildJakartaUndertow23Source() { + return "package org.example.jkut23;\n" + + "import io.undertow.Undertow;\n" + + "import io.undertow.servlet.Servlets;\n" + + "import io.undertow.servlet.api.DeploymentManager;\n" + + "import jakarta.servlet.AsyncContext;\n" + + "import jakarta.servlet.http.HttpServlet;\n" + + "import jakarta.servlet.http.HttpServletRequest;\n" + + "import jakarta.servlet.http.HttpServletResponse;\n" + + "import java.io.IOException;\n" + + "import java.net.InetSocketAddress;\n" + + "import java.nio.charset.StandardCharsets;\n" + + "import java.util.concurrent.CountDownLatch;\n" + + "import java.util.concurrent.TimeUnit;\n" + + "import org.jboss.threads.EnhancedQueueExecutor;\n" + + "import org.xnio.XnioWorker;\n" + + "public final class JakartaUndertow23App {\n" + + " private static final java.util.concurrent.ExecutorService DEFERRED_POOL = java.util.concurrent.Executors.newSingleThreadExecutor(r -> {\n" + + " Thread t = new Thread(r, \"ut23-deferred\"); t.setDaemon(true); return t;\n" + + " });\n" + + " private static volatile XnioWorker WORKER;\n" + + " public static final class S extends HttpServlet {\n" + + " @Override\n" + + " protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {\n" + + " String path = req.getRequestURI();\n" + + " long ms = req.getParameter(\"ms\") == null ? 0L : Long.parseLong(req.getParameter(\"ms\"));\n" + + " if (\"/async-dispatch-callable\".equals(path)) {\n" + + " final AsyncContext ac = req.startAsync();\n" + + " ac.start(() -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " ac.dispatch(\"/async-dispatch-done\");\n" + + " });\n" + + " return;\n" + + " }\n" + + " if (\"/async-dispatch-deferred\".equals(path)) {\n" + + " final AsyncContext ac = req.startAsync();\n" + + " DEFERRED_POOL.submit(() -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " ac.dispatch(\"/async-dispatch-done\");\n" + + " });\n" + + " return;\n" + + " }\n" + + " if (\"/async-dispatch-done\".equals(path)) {\n" + + " byte[] ok = \"dispatched-ok\".getBytes(StandardCharsets.UTF_8);\n" + + " resp.setContentType(\"text/plain\");\n" + + " resp.setContentLength(ok.length);\n" + + " resp.getOutputStream().write(ok);\n" + + " resp.flushBuffer();\n" + + " return;\n" + + " }\n" + + " if (\"/async-after-complete\".equals(path)) {\n" + + " final AsyncContext ac = req.startAsync();\n" + + " ac.start(() -> {\n" + + " try {\n" + + " byte[] ok = \"ok\".getBytes(StandardCharsets.UTF_8);\n" + + " HttpServletResponse ar = (HttpServletResponse) ac.getResponse();\n" + + " ar.setContentType(\"text/plain\");\n" + + " ar.setContentLength(ok.length);\n" + + " ar.getOutputStream().write(ok);\n" + + " ar.flushBuffer();\n" + + " } catch (IOException ignored) {\n" + + " } finally {\n" + + " ac.complete();\n" + + " }\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " return;\n" + + " }\n" + + " if (\"/xnio-exec\".equals(path)) {\n" + + " WORKER.execute(() -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " }\n" + + " if (\"/xnio-io-after\".equals(path)) {\n" + + " WORKER.getIoThread().executeAfter(() -> JakartaAsyncTail.ran(), ms, TimeUnit.MILLISECONDS);\n" + + " }\n" + + " if (\"/escape-io-exec-reflect\".equals(path)) {\n" + + " try {\n" + + " Object io = WORKER.getIoThread();\n" + + " java.lang.reflect.Method m = org.xnio.XnioIoThread.class.getMethod(\"execute\", Runnable.class);\n" + + " m.invoke(io, (Runnable) () -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " } catch (Exception e) { throw new IOException(e); }\n" + + " }\n" + + " if (\"/escape-io-after-reflect\".equals(path)) {\n" + + " try {\n" + + " Object io = WORKER.getIoThread();\n" + + " java.lang.reflect.Method m = org.xnio.XnioIoThread.class.getMethod(\"executeAfter\", Runnable.class, long.class, TimeUnit.class);\n" + + " m.invoke(io, (Runnable) () -> JakartaAsyncTail.ran(), Long.valueOf(ms), TimeUnit.MILLISECONDS);\n" + + " } catch (Exception e) { throw new IOException(e); }\n" + + " }\n" + + " if (\"/escape-io-exec-lib\".equals(path)) {\n" + + " com.thirdparty.LibHandOff.execIo(WORKER.getIoThread(), () -> {\n" + + " try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " JakartaAsyncTail.ran();\n" + + " });\n" + + " }\n" + + " if (\"/escape-io-after-lib\".equals(path)) {\n" + + " com.thirdparty.LibHandOff.afterIo(WORKER.getIoThread(), () -> JakartaAsyncTail.ran(), ms);\n" + + " }\n" + + " if (\"/escape-worker-utils-after-lib\".equals(path)) {\n" + + " com.thirdparty.LibHandOff.workerUtilsAfter(WORKER.getIoThread(), () -> JakartaAsyncTail.ran(), ms);\n" + + " }\n" + + " if (\"/escape-worker-utils-after\".equals(path)) {\n" + + " io.undertow.util.WorkerUtils.executeAfter(WORKER.getIoThread(), () -> JakartaAsyncTail.ran(), ms, TimeUnit.MILLISECONDS);\n" + + " }\n" + + " if (\"/escape-user-eqe\".equals(path)) {\n" + + " EnhancedQueueExecutor userEqe = new EnhancedQueueExecutor.Builder().setCorePoolSize(1).setMaximumPoolSize(1).build();\n" + + " CountDownLatch done = new CountDownLatch(1);\n" + + " userEqe.execute(() -> { JakartaAsyncTail.ran(); done.countDown(); });\n" + + " try { done.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }\n" + + " userEqe.shutdownNow();\n" + + " }\n" + + " byte[] body = \"ok\".getBytes(StandardCharsets.UTF_8);\n" + + " resp.setContentType(\"text/plain\");\n" + + " resp.setContentLength(body.length);\n" + + " resp.getOutputStream().write(body);\n" + + " resp.flushBuffer();\n" + + " }\n" + + " }\n" + + " public static void main(String[] args) throws Exception {\n" + + " DeploymentManager dm = Servlets.defaultContainer().addDeployment(\n" + + " Servlets.deployment().setClassLoader(JakartaUndertow23App.class.getClassLoader())\n" + + " .setContextPath(\"/\").setDeploymentName(\"ut23\")\n" + + " .addServlet(Servlets.servlet(\"ut23\", S.class).setAsyncSupported(true).addMapping(\"/*\")));\n" + + " dm.deploy();\n" + + " Undertow u = Undertow.builder().addHttpListener(0, \"127.0.0.1\").setHandler(dm.start()).build();\n" + + " u.start();\n" + + " WORKER = u.getWorker();\n" + + " if (args.length > 0 && \"boot-xnio-outside\".equals(args[0])) {\n" + + " CountDownLatch done = new CountDownLatch(1);\n" + + " WORKER.execute(() -> { JakartaAsyncTail.ran(); done.countDown(); });\n" + + " done.await(3, TimeUnit.SECONDS);\n" + + " }\n" + + " int port = ((InetSocketAddress) u.getListenerInfo().get(0).getAddress()).getPort();\n" + + " System.out.println(\"PORT \" + port);\n" + + " System.out.flush();\n" + + " while (System.in.read() >= 0) { }\n" + + " u.stop();\n" + + " System.exit(0);\n" + + " }\n" + + "}\n"; + } + @Test(timeout = 420000) public void forkedAppSubPoolsAndReflectiveStartupWorkersFailClosed() throws Exception { // Isolated forks in both prefix and index modes for app/library JDK pool @@ -1201,10 +2038,14 @@ String reconnectAndReadHello() throws IOException { } String runHttpTest(String testId, String path) throws IOException { + return runHttpTest(testId, path, "ok"); + } + + String runHttpTest(String testId, String path, String expectedBody) throws IOException { send("START " + testId); String ack = nextNonHello(); assertEquals("ACK", ack); - assertEquals("ok", httpGet(port, path)); + assertEquals(expectedBody, httpGet(port, path)); send("END " + testId); String cov = nextNonHello(); assertTrue("expected COV, got: " + cov, cov != null && cov.startsWith("COV ")); diff --git a/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java b/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java index b40864f5..7ed3380f 100644 --- a/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java +++ b/keploy-sdk/src/test/java/io/keploy/dedup/JdkSinkBridgeTest.java @@ -3,7 +3,10 @@ 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.assertSame; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import io.keploy.dedup.bootstrap.KeploySinkBridge; import java.lang.reflect.Method; @@ -19,6 +22,7 @@ import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; /** * Unit tests for {@link KeploySinkBridge} re-entrancy / agent-internal guards @@ -226,8 +230,11 @@ public void infraAllowlistContainsOnlyExactCitedZeroCallbackClassesAndExcludesUs "com.zaxxer.hikari.pool.HikariPool", "com.mysql.cj.jdbc.AbandonedConnectionCleanupThread", "org.h2.util.MathUtils", + "org.springframework.boot.autoconfigure.BackgroundPreinitializer", "org.springframework.boot.autoconfigure.condition.OnClassCondition$ThreadedOutcomesResolver", "org.springframework.boot.autoconfigure.preinitialize.BackgroundPreinitializingApplicationListener", + "org.springframework.boot.jetty.GracefulShutdown", + "org.springframework.boot.web.embedded.jetty.GracefulShutdown", "org.springframework.boot.tomcat.TomcatWebServer", "org.springframework.boot.tomcat.GracefulShutdown", "org.springframework.boot.web.embedded.tomcat.TomcatWebServer", @@ -272,8 +279,15 @@ public void infraAllowlistContainsOnlyExactCitedZeroCallbackClassesAndExcludesUs "org.springframework.scheduling.support.DelegatingErrorHandlingRunnable", "org.springframework.scheduling.support.ReschedulingRunnable", "org.xnio.XnioWorker$DefaultThreadPoolExecutor", + "org.jboss.threads.EnhancedQueueExecutor", "org.jboss.threads.ManagedThreadPoolExecutor", "org.jboss.threads.JBossThread", + "org.eclipse.jetty.util.component.Graceful", + "org.eclipse.jetty.util.VirtualThreads", + "org.eclipse.jetty.util.thread.ThreadPool", + "org.eclipse.jetty.util.thread.Invocable$InvocationType$1", + "io.undertow.websockets.jsr.ServerWebSocketContainer", + "org.springframework.http.codec.multipart.DefaultPartHttpMessageReader", "sun.nio.ch.AsynchronousChannelGroupImpl", "reactor.core.scheduler.Schedulers", "io.netty.util.concurrent.SingleThreadEventExecutor", @@ -785,4 +799,1436 @@ public void unarmedHandOffOutsideWindowLatchesAsyncExecutorsFalse() { KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); } } + + @Test + public void xnioWorkerExecuteHookTracksInWindowAndFailsClosedOutsideWindowAndOnUnreadableLoader() throws Exception { + final ServerEntries transformer = new ServerEntries(true); + final byte[] rawWorker = generateSyntheticXnioWorker(); + final byte[][] transformed = {null}; + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + ClassLoader cl = new ClassLoader(JdkSinkBridgeTest.class.getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if ("org.xnio.XnioWorker".equals(name)) { + Class found = findLoadedClass(name); + if (found == null) { + found = findClass(name); + } + if (resolve) { + resolveClass(found); + } + return found; + } + return super.loadClass(name, resolve); + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + if (!"org.xnio.XnioWorker".equals(name)) { + throw new ClassNotFoundException(name); + } + byte[] out = transformer.transform(this, "org/xnio/XnioWorker", null, + JdkSinkBridgeTest.class.getProtectionDomain(), rawWorker); + transformed[0] = out; + byte[] effective = out != null ? out : rawWorker; + return defineClass(name, effective, 0, effective.length); + } + }; + + Class workerCls = cl.loadClass("org.xnio.XnioWorker"); + assertNotNull("org.xnio.XnioWorker.execute(Runnable) must be instrumented", transformed[0]); + assertTrue("transformed XnioWorker must carry keploy$async$execute", + ServerEntries.carriesXnioWorkerExecuteChange(transformed[0])); + + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + try { + // 1. Inside an armed window: execute(r) wraps r in Hand, activates tracked dispatch, + // and keeps window.running == 1 until r completes. + RequestGate.open("xnio-unit-1", null); + Object reqToken = RequestGate.enter(); + final AtomicBoolean trackedDuringExecute = new AtomicBoolean(false); + final AtomicReference capturedTask = new AtomicReference<>(); + final AtomicBoolean throwOnExecute = new AtomicBoolean(false); + Object worker = workerCls.getDeclaredConstructor(AtomicBoolean.class, AtomicReference.class, + AtomicBoolean.class).newInstance(trackedDuringExecute, capturedTask, throwOnExecute); + Method execMethod = workerCls.getMethod("execute", Runnable.class); + + final AtomicBoolean ran = new AtomicBoolean(false); + execMethod.invoke(worker, (Runnable) () -> ran.set(true)); + RequestGate.exit(reqToken); + + assertTrue("tracked dispatch must be active inside XnioWorker.execute in-window", + trackedDuringExecute.get()); + assertFalse("tracked dispatch must exit cleanly after execute returns", + RequestGate.isTrackedDispatchActive()); + assertNotNull("task must reach keploy$async$execute", capturedTask.get()); + assertTrue("task must be wrapped in RequestGate.Hand", + RequestGate.isTrackedTask(capturedTask.get())); + assertEquals("window must stay open until XnioWorker task completes", + 1, RequestGate.running()); + capturedTask.get().run(); + assertTrue("wrapped runnable must execute", ran.get()); + assertEquals("window must drain once XnioWorker task completes", + 0, RequestGate.running()); + + // 2. Idempotence: passing an already-wrapped AsyncContext.start task does not double-count. + reqToken = RequestGate.enter(); + Runnable acWrapped = RequestGate.handAsyncContext(() -> { }); + capturedTask.set(null); + trackedDuringExecute.set(false); + execMethod.invoke(worker, acWrapped); + RequestGate.exit(reqToken); + assertSame("already-wrapped Hand must not be double-wrapped", acWrapped, capturedTask.get()); + assertTrue("already-wrapped Hand must activate tracked dispatch", trackedDuringExecute.get()); + assertEquals("idempotent dispatch must hold exactly 1 permit", 1, RequestGate.running()); + capturedTask.get().run(); + assertEquals("window must drain after idempotent task runs", 0, RequestGate.running()); + + // 3. RejectedExecutionException inside keploy$async$execute releases permit & exits tracked dispatch. + reqToken = RequestGate.enter(); + throwOnExecute.set(true); + try { + execMethod.invoke(worker, (Runnable) () -> { }); + fail("expected RuntimeException from keploy$async$execute"); + } catch (java.lang.reflect.InvocationTargetException expected) { + assertTrue(expected.getCause() instanceof IllegalStateException); + } finally { + throwOnExecute.set(false); + RequestGate.exit(reqToken); + } + assertFalse("tracked dispatch must exit on throw", RequestGate.isTrackedDispatchActive()); + assertEquals("dropped permit must be released on throw", 0, RequestGate.running()); + RequestGate.await(1000); + + // 4. Armed outside any window: execute(r) latches asyncExecutors=false and does NOT enter tracked dispatch. + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + trackedDuringExecute.set(false); + capturedTask.set(null); + execMethod.invoke(worker, (Runnable) () -> { }); + assertFalse("outside-window XnioWorker.execute must NOT enter tracked dispatch", + trackedDuringExecute.get()); + assertFalse("outside-window XnioWorker.execute must NOT wrap in Hand", + RequestGate.isTrackedTask(capturedTask.get())); + assertTrue("outside-window XnioWorker.execute must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // 5. Unarmed inside RequestGate.enter() (server request dispatch before collector connects): + // enters tracked dispatch WITHOUT latching asyncExecutors=false; outside RequestGate.enter() latches! + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + Object unarmedTok = RequestGate.enter(); + trackedDuringExecute.set(false); + try { + execMethod.invoke(worker, (Runnable) () -> { }); + } finally { + RequestGate.exit(unarmedTok); + } + assertTrue("unarmed inside server request must enter tracked dispatch", + trackedDuringExecute.get()); + assertFalse("unarmed inside server request must NOT latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + trackedDuringExecute.set(false); + execMethod.invoke(worker, (Runnable) () -> { }); + assertFalse("unarmed outside request must NOT enter tracked dispatch", + trackedDuringExecute.get()); + assertTrue("unarmed outside request must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // 6. Fail-closed when loader cannot access RequestGate. + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ClassLoader isolatedLoader = new ClassLoader(null) { }; + assertNull("isolated loader cannot access RequestGate", + transformer.transform(isolatedLoader, "org/xnio/XnioWorker", null, null, rawWorker)); + assertTrue("inaccessible XnioWorker loader must set hadAsyncHookFailure()", + ServerEntries.hadAsyncHookFailure()); + } finally { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + RequestGate.disarm(); + } + } + + @Test + public void jettyAndUndertowLatchOnCallHooksFailClosedWhenInvoked() throws Exception { + final ServerEntries transformer = new ServerEntries(true); + String[][] targets = { + {"org/eclipse/jetty/util/component/Graceful", "shutdown", "true", "true"}, + {"org/eclipse/jetty/util/VirtualThreads", "executeOnVirtualThread", "false", "true"}, + {"org/eclipse/jetty/util/thread/ThreadPool", "executeImmediately", "true", "true"}, + {"org/eclipse/jetty/util/thread/Invocable$InvocationType$1", "runWithoutBlocking", "false", "false"}, + {"io/undertow/websockets/jsr/ServerWebSocketContainer", "invokeEndpointMethod", "false", "false"}, + {"org/springframework/http/codec/multipart/DefaultPartHttpMessageReader", "read", "false", "false"}, + }; + + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + try { + for (String[] spec : targets) { + String internalName = spec[0]; + String methodName = spec[1]; + boolean isInterface = Boolean.parseBoolean(spec[2]); + boolean isStatic = Boolean.parseBoolean(spec[3]); + String fqcn = internalName.replace('/', '.'); + + byte[] raw = generateSyntheticLatchTarget(internalName, methodName, isInterface, isStatic); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + ServerEntries.setHookStatusForTests(false, false, false, false, false); + + byte[] out = transformer.transform(JdkSinkBridgeTest.class.getClassLoader(), internalName, null, + JdkSinkBridgeTest.class.getProtectionDomain(), raw); + assertNotNull("LATCH_ON_CALL must instrument " + fqcn + "#" + methodName, out); + assertFalse("loading " + fqcn + " must NOT latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + assertFalse("loading " + fqcn + " must NOT record unhooked async dispatcher", + ServerEntries.hasUnhookedAsyncDispatcher()); + + ClassLoader loader = new ClassLoader(JdkSinkBridgeTest.class.getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (fqcn.equals(name)) { + Class c = findLoadedClass(name); + if (c == null) { + c = defineClass(name, out, 0, out.length); + } + if (resolve) { + resolveClass(c); + } + return c; + } + return super.loadClass(name, resolve); + } + }; + Class cls = loader.loadClass(fqcn); + RequestGate.open("latch-" + methodName, null); + Object tok = RequestGate.enter(); + try { + Method m = cls.getDeclaredMethod(methodName); + Object inst = isStatic ? null : cls.getDeclaredConstructor().newInstance(); + m.invoke(inst); + } finally { + RequestGate.exit(tok); + } + assertTrue("invoking " + fqcn + "#" + methodName + " must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + RequestGate.WindowOutcome outcome = RequestGate.awaitWindow( + TimeUnit.MILLISECONDS.toNanos(1000), true); + assertTrue("invoking " + fqcn + "#" + methodName + " in-window must contaminate window: " + + outcome.contaminations, !outcome.contaminations.isEmpty()); + } + } finally { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + RequestGate.disarm(); + } + } + + private static byte[] generateSyntheticXnioWorker() { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "org/xnio/XnioWorker", null, "java/lang/Object", null); + cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "trackedOut", + "Ljava/util/concurrent/atomic/AtomicBoolean;", null, null).visitEnd(); + cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "taskOut", + "Ljava/util/concurrent/atomic/AtomicReference;", null, null).visitEnd(); + cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "shouldThrow", + "Ljava/util/concurrent/atomic/AtomicBoolean;", null, null).visitEnd(); + + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", + "(Ljava/util/concurrent/atomic/AtomicBoolean;Ljava/util/concurrent/atomic/AtomicReference;" + + "Ljava/util/concurrent/atomic/AtomicBoolean;)V", + null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitVarInsn(Opcodes.ALOAD, 1); + init.visitFieldInsn(Opcodes.PUTFIELD, "org/xnio/XnioWorker", "trackedOut", + "Ljava/util/concurrent/atomic/AtomicBoolean;"); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitVarInsn(Opcodes.ALOAD, 2); + init.visitFieldInsn(Opcodes.PUTFIELD, "org/xnio/XnioWorker", "taskOut", + "Ljava/util/concurrent/atomic/AtomicReference;"); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitVarInsn(Opcodes.ALOAD, 3); + init.visitFieldInsn(Opcodes.PUTFIELD, "org/xnio/XnioWorker", "shouldThrow", + "Ljava/util/concurrent/atomic/AtomicBoolean;"); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(0, 0); + init.visitEnd(); + + MethodVisitor exec = cw.visitMethod(Opcodes.ACC_PUBLIC, "execute", "(Ljava/lang/Runnable;)V", null, null); + exec.visitCode(); + exec.visitVarInsn(Opcodes.ALOAD, 0); + exec.visitFieldInsn(Opcodes.GETFIELD, "org/xnio/XnioWorker", "trackedOut", + "Ljava/util/concurrent/atomic/AtomicBoolean;"); + exec.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JdkSinkBridgeTest.class), + "isTrackedDispatchActiveForTest", "()Z", false); + exec.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/atomic/AtomicBoolean", + "set", "(Z)V", false); + exec.visitVarInsn(Opcodes.ALOAD, 0); + exec.visitFieldInsn(Opcodes.GETFIELD, "org/xnio/XnioWorker", "taskOut", + "Ljava/util/concurrent/atomic/AtomicReference;"); + exec.visitVarInsn(Opcodes.ALOAD, 1); + exec.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/atomic/AtomicReference", + "set", "(Ljava/lang/Object;)V", false); + org.objectweb.asm.Label noThrow = new org.objectweb.asm.Label(); + exec.visitVarInsn(Opcodes.ALOAD, 0); + exec.visitFieldInsn(Opcodes.GETFIELD, "org/xnio/XnioWorker", "shouldThrow", + "Ljava/util/concurrent/atomic/AtomicBoolean;"); + exec.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/concurrent/atomic/AtomicBoolean", + "get", "()Z", false); + exec.visitJumpInsn(Opcodes.IFEQ, noThrow); + exec.visitTypeInsn(Opcodes.NEW, "java/lang/IllegalStateException"); + exec.visitInsn(Opcodes.DUP); + exec.visitLdcInsn("rejected"); + exec.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/IllegalStateException", "", + "(Ljava/lang/String;)V", false); + exec.visitInsn(Opcodes.ATHROW); + exec.visitLabel(noThrow); + exec.visitInsn(Opcodes.RETURN); + exec.visitMaxs(0, 0); + exec.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateSyntheticLatchTarget(String internalName, String methodName, + boolean isInterface, boolean isStatic) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + int classAccess = isInterface ? (Opcodes.ACC_PUBLIC | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT) + : Opcodes.ACC_PUBLIC; + cw.visit(Opcodes.V1_8, classAccess, internalName, null, "java/lang/Object", null); + if (!isInterface) { + 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(); + } + int mAccess = Opcodes.ACC_PUBLIC | (isStatic ? Opcodes.ACC_STATIC : 0); + MethodVisitor mv = cw.visitMethod(mAccess, methodName, "()V", null, null); + mv.visitCode(); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(0, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + @Test + public void serverExecutorSinkHooksAllowInternalServerCallersAndFailClosedOnAppLibraryReflectionAndUnreadableLoader() + throws Exception { + final ServerEntries transformer = new ServerEntries(true); + // {sinkInternal, methodName, desc, exactAllowedCallerInternal (or null if none), exactAllowedCallerMethod, unlistedServerCallerInternal, unlistedServerCallerMethod} + String[][] specs = { + {"org/eclipse/jetty/util/thread/QueuedThreadPool", "execute", "(Ljava/lang/Runnable;)V", + "org/eclipse/jetty/util/thread/ReservedThreadExecutor", "startReservedThread", + "org/eclipse/jetty/server/Server$ServerContext", "execute"}, + {"org/eclipse/jetty/util/thread/QueuedThreadPool", "tryExecute", "(Ljava/lang/Runnable;)Z", + "org/eclipse/jetty/util/thread/ReservedThreadExecutor", "startReservedThread", + "org/eclipse/jetty/server/handler/ContextHandler$ScopedContext", "execute"}, + {"org/eclipse/jetty/util/thread/MonitoredQueuedThreadPool", "execute", "(Ljava/lang/Runnable;)V", + "org/eclipse/jetty/util/thread/ReservedThreadExecutor", "startReservedThread", + "org/eclipse/jetty/util/VirtualThreads", "execute"}, + {"org/eclipse/jetty/util/thread/ExecutorThreadPool", "execute", "(Ljava/lang/Runnable;)V", + "org/eclipse/jetty/util/thread/ReservedThreadExecutor", "startReservedThread", + "org/eclipse/jetty/server/Server$ServerContext", "execute"}, + {"org/eclipse/jetty/util/thread/ExecutorThreadPool", "tryExecute", "(Ljava/lang/Runnable;)Z", + "org/eclipse/jetty/util/thread/ReservedThreadExecutor", "startReservedThread", + "org/eclipse/jetty/util/VirtualThreads", "execute"}, + {"org/eclipse/jetty/util/thread/ReservedThreadExecutor", "execute", "(Ljava/lang/Runnable;)V", + "org/eclipse/jetty/annotations/AnnotationConfiguration", "scanForAnnotations", + "org/eclipse/jetty/server/Server$ServerContext", "execute"}, + {"org/eclipse/jetty/util/thread/ReservedThreadExecutor", "tryExecute", "(Ljava/lang/Runnable;)Z", + "org/eclipse/jetty/util/thread/QueuedThreadPool", "tryExecute", + "org/eclipse/jetty/util/VirtualThreads", "execute"}, + {"org/eclipse/jetty/util/thread/TryExecutor$NoTryExecutor", "execute", "(Ljava/lang/Runnable;)V", + "org/eclipse/jetty/util/thread/ReservedThreadExecutor", "startReservedThread", + "org/eclipse/jetty/server/Server$ServerContext", "execute"}, + {"org/eclipse/jetty/util/thread/ScheduledExecutorScheduler", "schedule", + "(Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;", + "org/eclipse/jetty/server/session/HouseKeeper", "startScavenging", + "org/eclipse/jetty/util/thread/Scheduler", "schedule"}, + {"org/eclipse/jetty/util/thread/TimerScheduler", "schedule", + "(Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;", + "org/eclipse/jetty/server/session/HouseKeeper", "startScavenging", + "org/eclipse/jetty/util/thread/Scheduler", "schedule"}, + {"io/undertow/util/PipeliningExecutor", "execute", "(Ljava/lang/Runnable;)V", + null, null, + "io/undertow/server/HttpServerExchange", "dispatch"}, + {"org/xnio/nio/WorkerThread", "execute", "(Ljava/lang/Runnable;)V", + "io/undertow/server/protocol/http/HttpReadListener", "exchangeComplete", + "io/undertow/server/HttpServerExchange", "dispatch"}, + {"org/xnio/nio/WorkerThread", "executeAfter", + "(Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;", + "io/undertow/util/DateUtils", "getCurrentDateTime", + "io/undertow/util/WorkerUtils", "executeAfter"}, + {"org/xnio/nio/WorkerThread", "executeAtInterval", + "(Ljava/lang/Runnable;JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;", + "org/xnio/nio/WorkerThread$RepeatKey", "run", + "io/undertow/util/WorkerUtils", "executeAfter"}, + }; + + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + try { + for (String[] spec : specs) { + String sinkInternal = spec[0]; + String methodName = spec[1]; + String desc = spec[2]; + String internalCallerName = spec[3]; + String internalCallerMethod = spec[4]; + String unlistedCallerName = spec[5]; + String unlistedCallerMethod = spec[6]; + String sinkFqcn = sinkInternal.replace('/', '.'); + String callerFqcn = internalCallerName != null ? internalCallerName.replace('/', '.') : null; + String unlistedFqcn = unlistedCallerName.replace('/', '.'); + + byte[] rawSink = generateSyntheticServerExecutorSink(sinkInternal, methodName, desc); + byte[] rawCaller = internalCallerName != null + ? generateSyntheticServerCaller(internalCallerName, internalCallerMethod, sinkInternal, methodName, desc) + : null; + byte[] rawUnlisted = generateSyntheticServerCaller(unlistedCallerName, unlistedCallerMethod, + sinkInternal, methodName, desc); + + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + ServerEntries.setHookStatusForTests(false, false, false, false, false); + byte[] transformed = transformer.transform(JdkSinkBridgeTest.class.getClassLoader(), sinkInternal, + null, JdkSinkBridgeTest.class.getProtectionDomain(), rawSink); + assertNotNull("server executor sink must instrument " + sinkFqcn + "#" + methodName, transformed); + assertFalse("transforming " + sinkFqcn + " must not fail", ServerEntries.hadAsyncHookFailure()); + + // Retransform (changedAgain) must be idempotent and never double-hook or fail. + byte[] retransformed = transformer.transform(JdkSinkBridgeTest.class.getClassLoader(), sinkInternal, + Object.class, JdkSinkBridgeTest.class.getProtectionDomain(), transformed); + assertNotNull("retransforming " + sinkFqcn + " must return bytes", retransformed); + assertFalse("retransforming " + sinkFqcn + " must not fail", ServerEntries.hadAsyncHookFailure()); + + ClassLoader cl = new ClassLoader(JdkSinkBridgeTest.class.getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + byte[] bytes = null; + if (sinkFqcn.equals(name)) { + bytes = transformed; + } else if (callerFqcn != null && callerFqcn.equals(name)) { + bytes = rawCaller; + } else if (unlistedFqcn.equals(name)) { + bytes = rawUnlisted; + } + if (bytes != null) { + Class c = findLoadedClass(name); + if (c == null) { + c = defineClass(name, bytes, 0, bytes.length); + } + if (resolve) { + resolveClass(c); + } + return c; + } + return super.loadClass(name, resolve); + } + }; + Class sinkCls = cl.loadClass(sinkFqcn); + Object sinkInst = sinkCls.getDeclaredConstructor().newInstance(); + + // 1. Exact cited internal caller (class#method) inside open window passes cleanly. + if (callerFqcn != null) { + Class internalCallerCls = cl.loadClass(callerFqcn); + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.open("srv-ok-" + methodName, null); + Object tok = RequestGate.enter(); + try { + internalCallerCls.getMethod(internalCallerMethod, Object.class, Runnable.class) + .invoke(null, sinkInst, (Runnable) () -> { }); + } finally { + RequestGate.exit(tok); + } + RequestGate.WindowOutcome okOutcome = RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(1000), true); + assertTrue("internal caller " + callerFqcn + "#" + internalCallerMethod + " -> " + sinkFqcn + "#" + methodName + + " must not contaminate: " + okOutcome.contaminations, + okOutcome.contaminations.isEmpty()); + assertFalse("internal caller must not latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // 1b. Same class with a different (unlisted) method MUST fail closed. + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.open("srv-wrongm-" + methodName, null); + Object tokWm = RequestGate.enter(); + try { + internalCallerCls.getMethod("unlistedMethod", Object.class, Runnable.class) + .invoke(null, sinkInst, (Runnable) () -> { }); + } finally { + RequestGate.exit(tokWm); + } + RequestGate.WindowOutcome wmOutcome = RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(1000), true); + assertTrue("unlisted method on " + callerFqcn + " -> " + sinkFqcn + "#" + methodName + + " must fail closed: " + wmOutcome.contaminations, + wmOutcome.contaminations.toString().contains("untracked-sink:server-executor:" + sinkFqcn + ":")); + assertTrue("unlisted method must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } + + // 1c. Unlisted same-package server forwarder MUST fail closed (no package-prefix trust). + Class unlistedCallerCls = cl.loadClass(unlistedFqcn); + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.open("srv-fwd-" + methodName, null); + Object tokFwd = RequestGate.enter(); + try { + unlistedCallerCls.getMethod(unlistedCallerMethod, Object.class, Runnable.class) + .invoke(null, sinkInst, (Runnable) () -> { }); + } finally { + RequestGate.exit(tokFwd); + } + RequestGate.WindowOutcome fwdOutcome = RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(1000), true); + assertTrue("unlisted server forwarder " + unlistedFqcn + "#" + unlistedCallerMethod + + " -> " + sinkFqcn + "#" + methodName + " must fail closed: " + fwdOutcome.contaminations, + fwdOutcome.contaminations.toString().contains("untracked-sink:server-executor:" + sinkFqcn + ":")); + assertTrue("unlisted server forwarder must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // 2. Reflective / external caller inside open window contaminates AND latches asyncExecutors=false. + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.open("srv-ext-" + methodName, null); + Object tok2 = RequestGate.enter(); + try { + if (desc.startsWith("(Ljava/lang/Runnable;)")) { + sinkCls.getMethod(methodName, Runnable.class).invoke(sinkInst, (Runnable) () -> { }); + } else { + sinkCls.getMethod(methodName, Runnable.class, long.class, TimeUnit.class) + .invoke(sinkInst, (Runnable) () -> { }, Long.valueOf(10L), TimeUnit.MILLISECONDS); + } + } finally { + RequestGate.exit(tok2); + } + RequestGate.WindowOutcome extOutcome = RequestGate.awaitWindow(TimeUnit.MILLISECONDS.toNanos(1000), true); + assertTrue("external/reflective call to " + sinkFqcn + "#" + methodName + + " must contaminate with untracked-sink:server-executor: " + extOutcome.contaminations, + extOutcome.contaminations.toString().contains("untracked-sink:server-executor:" + sinkFqcn + ":")); + assertTrue("external/reflective call to " + sinkFqcn + "#" + methodName + + " must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // 3. External call outside any window latches asyncExecutors=false. + RequestGate.disarm(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + if (desc.startsWith("(Ljava/lang/Runnable;)")) { + sinkCls.getMethod(methodName, Runnable.class).invoke(sinkInst, (Runnable) () -> { }); + } else { + sinkCls.getMethod(methodName, Runnable.class, long.class, TimeUnit.class) + .invoke(sinkInst, (Runnable) () -> { }, Long.valueOf(10L), TimeUnit.MILLISECONDS); + } + assertTrue("outside-window call to " + sinkFqcn + "#" + methodName + " must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // 4. Unreadable loader fails closed (sets hadAsyncHookFailure()). + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ClassLoader isolated = new ClassLoader(null) { }; + assertNull("isolated loader cannot access RequestGate for " + sinkFqcn, + transformer.transform(isolated, sinkInternal, null, null, rawSink)); + assertTrue("inaccessible loader for " + sinkFqcn + " must set hadAsyncHookFailure()", + ServerEntries.hadAsyncHookFailure()); + } + } finally { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + RequestGate.disarm(); + } + } + + @Test + public void jettyAbstractTimeoutSinksRejectAppSubclassesAndUnlistedCallers() throws Exception { + final ServerEntries transformer = new ServerEntries(true); + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + try { + // Verify all three public abstract Jetty timeout sinks (CyclicTimeout, CyclicTimeouts, IdleTimeout) + // instrument cleanly, retransform idempotently, fail closed on unreadable loaders, + // reject app subclasses, and allow only cited Jetty internal subclasses/callers. + String[][] timerSpecs = { + {"org/eclipse/jetty/io/CyclicTimeout", "schedule", "(JLjava/util/concurrent/TimeUnit;)Z", + "org/eclipse/jetty/session/SessionInactivityTimer$1", "org/example/AppCyclicTimeout"}, + {"org/eclipse/jetty/io/CyclicTimeouts", "schedule", "(Lorg/eclipse/jetty/io/CyclicTimeouts$Expirable;)V", + "org/eclipse/jetty/server/handler/QoSHandler$Timeouts", "org/example/AppCyclicTimeouts"}, + {"org/eclipse/jetty/io/IdleTimeout", "scheduleIdleTimeout", "(J)V", + "org/eclipse/jetty/io/SocketChannelEndPoint", "org/example/AppIdleTimeout"}, + }; + for (String[] ts : timerSpecs) { + final String baseInternal = ts[0]; + final String methodName = ts[1]; + final String desc = ts[2]; + final String allowedSubInternal = ts[3]; + final String appSubInternal = ts[4]; + final String baseFqcn = baseInternal.replace('/', '.'); + final String allowedSubFqcn = allowedSubInternal.replace('/', '.'); + final String appSubFqcn = appSubInternal.replace('/', '.'); + + final byte[] rawBase = generateSyntheticNoTaskSink(baseInternal, methodName, desc); + ServerEntries.setHookStatusForTests(false, false, false, false, false); + final byte[] hooked = transformer.transform(JdkSinkBridgeTest.class.getClassLoader(), baseInternal, + null, JdkSinkBridgeTest.class.getProtectionDomain(), rawBase); + assertNotNull("timer sink must instrument " + baseFqcn + "#" + methodName, hooked); + assertFalse("transforming " + baseFqcn + " must not fail", ServerEntries.hadAsyncHookFailure()); + + byte[] rehooked = transformer.transform(JdkSinkBridgeTest.class.getClassLoader(), baseInternal, + Object.class, JdkSinkBridgeTest.class.getProtectionDomain(), hooked); + assertNotNull("retransforming " + baseFqcn + " must succeed", rehooked); + assertFalse("retransforming " + baseFqcn + " must not fail", ServerEntries.hadAsyncHookFailure()); + + ClassLoader isolated = new ClassLoader(null) { }; + assertNull("isolated loader must fail closed for " + baseFqcn, + transformer.transform(isolated, baseInternal, null, null, rawBase)); + assertTrue("inaccessible loader must set hadAsyncHookFailure() for " + baseFqcn, + ServerEntries.hadAsyncHookFailure()); + + // Runtime invocation of hooked synthetic base through an app subclass MUST latch + // asyncExecutors=false, and so must the exact Jetty EndPoint class when no ServerConnector owns it. + final byte[] appSubBytes = generateSyntheticSubclass(appSubInternal, baseInternal); + final byte[] allowedSubBytes = generateSyntheticSubclass(allowedSubInternal, baseInternal); + ClassLoader runtimeLoader = new ClassLoader(JdkSinkBridgeTest.class.getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (baseFqcn.equals(name)) { + Class c = findLoadedClass(name); + if (c == null) { + c = defineClass(name, hooked, 0, hooked.length); + } + if (resolve) { + resolveClass(c); + } + return c; + } + if (appSubFqcn.equals(name)) { + Class c = findLoadedClass(name); + if (c == null) { + c = defineClass(name, appSubBytes, 0, appSubBytes.length); + } + if (resolve) { + resolveClass(c); + } + return c; + } + if (allowedSubFqcn.equals(name)) { + Class c = findLoadedClass(name); + if (c == null) { + c = defineClass(name, allowedSubBytes, 0, allowedSubBytes.length); + } + if (resolve) { + resolveClass(c); + } + return c; + } + return super.loadClass(name, resolve); + } + }; + Class baseCls = Class.forName(baseFqcn, true, runtimeLoader); + Class appSubCls = Class.forName(appSubFqcn, true, runtimeLoader); + Class allowedSubCls = Class.forName(allowedSubFqcn, true, runtimeLoader); + Object appInst = appSubCls.getDeclaredConstructor().newInstance(); + Object allowedInst = allowedSubCls.getDeclaredConstructor().newInstance(); + + // App subclass invoking hooked timer method outside window MUST latch asyncExecutors=false. + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + invokeSyntheticTimerMethod(baseCls, appInst, methodName, desc); + assertTrue("app subclass " + appSubFqcn + " calling hooked " + baseFqcn + "#" + methodName + + " must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + + // For IdleTimeout, the exact Jetty EndPoint class alone is not enough: app code can + // construct a SocketChannelEndPoint itself, so one that no ServerConnector's + // ManagedSelector owns (this synthetic one has no _selector/_key/_channel) must latch; + // for CyclicTimeout / CyclicTimeouts, even the internal subclass must fail closed + // when invoked from an unlisted caller (this test method). + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + invokeSyntheticTimerMethod(baseCls, allowedInst, methodName, desc); + if ("org.eclipse.jetty.io.IdleTimeout".equals(baseFqcn)) { + assertTrue("exact Jetty EndPoint class " + allowedSubFqcn + + " not owned by a ServerConnector ManagedSelector must latch on IdleTimeout", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } else { + assertTrue("unlisted caller invoking " + allowedSubFqcn + " on " + baseFqcn + + " must still fail closed", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } + } + + // Direct unit checks on SinkAllowlist.isAllowedServerExecutorCaller: + // Public forwarders and public callback-bearing helpers MUST fail closed even though + // they live in org.eclipse.jetty / io.undertow / org.xnio. + assertFalse("VirtualThreads#execute must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.util.VirtualThreads#execute", new Object())); + assertFalse("Server$ServerContext#execute must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.server.Server$ServerContext#execute", new Object())); + assertFalse("ContextHandler$ScopedContext#execute must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.server.handler.ContextHandler$ScopedContext#execute", new Object())); + assertFalse("SerializedInvoker$Link#run must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.util.thread.SerializedInvoker$Link#run", new Object())); + assertFalse("EatWhatYouKill#dispatch must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.util.thread.strategy.EatWhatYouKill#dispatch", new Object())); + assertFalse("AdaptiveExecutionStrategy#dispatch must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.util.thread.strategy.AdaptiveExecutionStrategy#dispatch", new Object())); + assertFalse("HttpChannel#execute must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.server.HttpChannel#execute", new Object())); + assertFalse("SelectorManager#execute must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.io.SelectorManager#execute", new Object())); + assertFalse("LocalEndPoint#execute must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.server.LocalConnector$LocalEndPoint#execute", new Object())); + assertFalse("AbstractConnection#failedCallback must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.io.AbstractConnection#failedCallback", new Object())); + assertFalse("AbstractConnector#doStart with arbitrary task must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.server.AbstractConnector#doStart", new Object(), new Object())); + assertFalse("QueuedThreadPool$Runner#run with arbitrary app task must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.util.thread.QueuedThreadPool$Runner#run", new Object(), + (Runnable) () -> { })); + assertFalse("ManagedSelector#execute with arbitrary app task must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.io.ManagedSelector#execute", new Object(), + (Runnable) () -> { })); + assertFalse("ManagedSelector#doStart with arbitrary app task must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.io.ManagedSelector#doStart", new Object(), + (Runnable) () -> { })); + assertFalse("HttpConnection#onOpen with arbitrary/subclassed task must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.server.HttpConnection#onOpen", new Object(), + (Runnable) () -> { })); + assertFalse("AsyncContextState#start must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.server.AsyncContextState#start", new Object(), + (Runnable) () -> { })); + assertFalse("WorkerThread#run with arbitrary task must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "org.xnio.nio.WorkerThread#run", new Object(), + (Runnable) () -> { })); + assertFalse("Scheduler#schedule default method must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler", + "org.eclipse.jetty.util.thread.Scheduler#schedule", new Object())); + assertFalse("Sweeper#activate must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler", + "org.eclipse.jetty.util.thread.Sweeper#activate", new Object())); + assertFalse("LowResourceMonitor#doStart must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.ScheduledExecutorScheduler", + "org.eclipse.jetty.server.LowResourceMonitor#doStart", new Object())); + assertFalse("WorkerUtils#executeAfter must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "io.undertow.util.WorkerUtils#executeAfter", new Object())); + assertFalse("ParseTimeoutUpdater#handleSchedule must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "io.undertow.server.protocol.ParseTimeoutUpdater#handleSchedule", new Object())); + assertFalse("ConnectionUtils#doDrain must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "io.undertow.util.ConnectionUtils#doDrain", new Object())); + assertFalse("Channels#resumeReadsAsync must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "org.xnio.channels.Channels#resumeReadsAsync", new Object())); + assertFalse("EmptyStreamSourceChannel#resumeReads must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "org.xnio.channels.EmptyStreamSourceChannel#resumeReads", new Object())); + assertFalse("EmptyStreamSourceConduit#resumeReads must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "org.xnio.conduits.EmptyStreamSourceConduit#resumeReads", new Object())); + assertFalse("IdleTimeoutConduit#handleResumeTimeout must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "io.undertow.conduits.IdleTimeoutConduit#handleResumeTimeout", new Object())); + assertFalse("ReadDispatchChannel#invokeListener must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "io.undertow.server.HttpServerExchange$ReadDispatchChannel#invokeListener", new Object())); + assertFalse("SslConduit#runTasks must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "io.undertow.protocols.ssl.SslConduit#runTasks", new Object())); + assertFalse("HttpServerExchange#dispatch must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "io.undertow.server.HttpServerExchange#dispatch", new Object())); + assertFalse("ChannelListeners#invokeChannelListener must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.xnio.nio.WorkerThread", + "org.xnio.ChannelListeners#invokeChannelListener", new Object())); + assertFalse("app subclass of CyclicTimeout must fail closed even from allowed caller", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.io.CyclicTimeout", + "org.eclipse.jetty.io.CyclicTimeouts#schedule", new Object())); + assertFalse("app subclass of CyclicTimeouts must fail closed even from allowed caller", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.io.CyclicTimeouts", + "org.eclipse.jetty.server.handler.QoSHandler#suspend", new Object())); + assertFalse("app subclass of IdleTimeout must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.io.IdleTimeout", + "org.eclipse.jetty.io.AbstractEndPoint#onOpen", new Object())); + assertFalse("ByteArrayEndPoint on IdleTimeout must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.io.IdleTimeout", + "org.eclipse.jetty.io.AbstractEndPoint#onOpen", + new org.eclipse.jetty.io.ByteArrayEndPoint())); + // SocketChannelEndPoint has a public constructor too: one that app code builds around its + // own channel, with no ServerConnector ManagedSelector and no SelectionKey, must fail closed, + // and so must the SSL endpoint of an SslConnection that wraps it. + try (java.nio.channels.SocketChannel appChannel = java.nio.channels.SocketChannel.open()) { + org.eclipse.jetty.io.SocketChannelEndPoint appEndPoint = + new org.eclipse.jetty.io.SocketChannelEndPoint(appChannel, null, null, null); + assertFalse("app-built SocketChannelEndPoint on IdleTimeout must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.io.IdleTimeout", + "org.eclipse.jetty.io.AbstractEndPoint#onOpen", appEndPoint)); + org.eclipse.jetty.io.ssl.SslConnection appSsl = new org.eclipse.jetty.io.ssl.SslConnection( + new org.eclipse.jetty.io.ArrayByteBufferPool(), Runnable::run, appEndPoint, + javax.net.ssl.SSLContext.getDefault().createSSLEngine()); + assertFalse("SSL endpoint over an app-built SocketChannelEndPoint on IdleTimeout must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.io.IdleTimeout", + "org.eclipse.jetty.io.AbstractEndPoint#onOpen", appSsl.getDecryptedEndPoint())); + } + + // Even if app code grabs a started ServerConnector's REAL ManagedSelector (reachable via + // public ContainerLifeCycle.getBeans) and passes it to new SocketChannelEndPoint(...) with + // either a null key or a SelectionKey registered on a foreign NIO Selector, IdleTimeout + // MUST fail closed because selectionKey.channel()/_selector ownership does not match. + org.eclipse.jetty.server.Server realServer = new org.eclipse.jetty.server.Server(0); + try { + realServer.start(); + org.eclipse.jetty.server.ServerConnector realConnector = + (org.eclipse.jetty.server.ServerConnector) realServer.getConnectors()[0]; + java.util.Collection realSelectors = + realConnector.getSelectorManager().getBeans(org.eclipse.jetty.io.ManagedSelector.class); + assertFalse("started ServerConnector must expose at least one ManagedSelector", realSelectors.isEmpty()); + org.eclipse.jetty.io.ManagedSelector realManagedSelector = realSelectors.iterator().next(); + try (java.nio.channels.SocketChannel appChannel = java.nio.channels.SocketChannel.open(); + java.nio.channels.Selector foreignSelector = java.nio.channels.Selector.open()) { + appChannel.configureBlocking(false); + java.nio.channels.SelectionKey foreignKey = + appChannel.register(foreignSelector, java.nio.channels.SelectionKey.OP_CONNECT); + org.eclipse.jetty.io.SocketChannelEndPoint epNullKey = + new org.eclipse.jetty.io.SocketChannelEndPoint( + appChannel, realManagedSelector, null, realConnector.getScheduler()); + assertFalse("app-built SocketChannelEndPoint with real ManagedSelector and null key must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.io.IdleTimeout", + "org.eclipse.jetty.io.AbstractEndPoint#onOpen", epNullKey)); + org.eclipse.jetty.io.SocketChannelEndPoint epForeignKey = + new org.eclipse.jetty.io.SocketChannelEndPoint( + appChannel, realManagedSelector, foreignKey, realConnector.getScheduler()); + assertFalse("app-built SocketChannelEndPoint with real ManagedSelector and foreign SelectionKey must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.io.IdleTimeout", + "org.eclipse.jetty.io.AbstractEndPoint#onOpen", epForeignKey)); + } + } finally { + realServer.stop(); + } + + // Subclassed ServerConnector must fail closed on BOTH AbstractConnector#doStart (Acceptor) + // and ManagedSelector/EatWhatYouKill owner walks (even though connector != null). + org.eclipse.jetty.server.Server dummyServer = new org.eclipse.jetty.server.Server(); + org.eclipse.jetty.server.ServerConnector subConnector = new org.eclipse.jetty.server.ServerConnector(dummyServer) { }; + java.lang.reflect.Constructor acceptorCtor = Class.forName("org.eclipse.jetty.server.AbstractConnector$Acceptor") + .getDeclaredConstructor(org.eclipse.jetty.server.AbstractConnector.class, int.class); + acceptorCtor.setAccessible(true); + Object subAcceptor = acceptorCtor.newInstance(subConnector, Integer.valueOf(0)); + assertFalse("Acceptor owned by subclassed ServerConnector must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.server.AbstractConnector#doStart", new Object(), subAcceptor)); + org.eclipse.jetty.io.SelectorManager subManager = subConnector.getSelectorManager(); + org.eclipse.jetty.io.ManagedSelector subManagedSelector = new org.eclipse.jetty.io.ManagedSelector(subManager, 0); + java.lang.reflect.Field strategyField = org.eclipse.jetty.io.ManagedSelector.class.getDeclaredField("_strategy"); + strategyField.setAccessible(true); + Object subStrategy = strategyField.get(subManagedSelector); + assertFalse("ExecutionStrategy owned by subclassed ServerConnector must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.util.thread.QueuedThreadPool$Runner#run", new Object(), subStrategy)); + + // App-built EatWhatYouKill (non-ManagedSelector producer) must fail closed even from QTP Runner#run. + org.eclipse.jetty.util.thread.strategy.EatWhatYouKill appEwyk = + new org.eclipse.jetty.util.thread.strategy.EatWhatYouKill(() -> () -> { }, Runnable::run); + assertFalse("app-built EatWhatYouKill on QueuedThreadPool$Runner#run must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.util.thread.QueuedThreadPool$Runner#run", new Object(), appEwyk)); + + // Servlet scheduleDispatch callers MUST fail closed on arbitrary Runnables (only exact + // HttpChannel/HttpChannelOverHttp or ScopedContext->ServletChannel lambdas pass). + assertFalse("HttpChannelState#scheduleDispatch with arbitrary task must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.server.HttpChannelState#scheduleDispatch", new Object(), + (Runnable) () -> { })); + assertFalse("ee10 ServletChannelState#scheduleDispatch with arbitrary task must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.ee10.servlet.ServletChannelState#scheduleDispatch", new Object(), + (Runnable) () -> { })); + assertFalse("ee11 ServletChannelState#scheduleDispatch with arbitrary task must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.QueuedThreadPool", + "org.eclipse.jetty.ee11.servlet.ServletChannelState#scheduleDispatch", new Object(), + (Runnable) () -> { })); + + // TimerScheduler#run only permits re-arming itself (task == receiver, exact TimerScheduler). + org.eclipse.jetty.util.thread.TimerScheduler tsInst = new org.eclipse.jetty.util.thread.TimerScheduler(); + assertTrue("TimerScheduler#run re-arming itself must pass", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.TimerScheduler", + "org.eclipse.jetty.util.thread.TimerScheduler#run", tsInst, tsInst)); + assertFalse("TimerScheduler#run with arbitrary task must fail closed", + SinkAllowlist.isAllowedServerExecutorCaller( + "org.eclipse.jetty.util.thread.TimerScheduler", + "org.eclipse.jetty.util.thread.TimerScheduler#run", tsInst, (Runnable) () -> { })); + + // Live transformed TimerScheduler: starting it and waiting past its once-a-second + // self-re-arm (TimerScheduler#run -> schedule(this, 1, SECONDS)) MUST NOT latch + // asyncExecutors=false (requires keeping TimerScheduler#run visible on stack walk). + final ClassLoader parentCl = JdkSinkBridgeTest.class.getClassLoader(); + ClassLoader timerLoader = new ClassLoader(parentCl) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if ("org.eclipse.jetty.util.thread.TimerScheduler".equals(name) + || name.startsWith("org.eclipse.jetty.util.thread.TimerScheduler$")) { + Class loaded = findLoadedClass(name); + if (loaded == null) { + String internal = name.replace('.', '/'); + try (java.io.InputStream in = parentCl.getResourceAsStream(internal + ".class")) { + assertNotNull("missing class bytes for " + name, in); + java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int r; + while ((r = in.read(buf)) >= 0) { + baos.write(buf, 0, r); + } + byte[] raw = baos.toByteArray(); + byte[] transformed = transformer.transform(this, internal, null, + JdkSinkBridgeTest.class.getProtectionDomain(), raw); + byte[] def = transformed != null ? transformed : raw; + loaded = defineClass(name, def, 0, def.length); + } catch (Exception e) { + throw new ClassNotFoundException(name, e); + } + } + if (resolve) { + resolveClass(loaded); + } + return loaded; + } + return super.loadClass(name, resolve); + } + }; + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + Object liveTimer = timerLoader.loadClass("org.eclipse.jetty.util.thread.TimerScheduler") + .getDeclaredConstructor(String.class, boolean.class) + .newInstance("keploy-test-timer", Boolean.TRUE); + try { + liveTimer.getClass().getMethod("start").invoke(liveTimer); + Thread.sleep(1350L); + assertFalse("live TimerScheduler self-re-arm must keep asyncExecutors=true (must not latch)", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } finally { + liveTimer.getClass().getMethod("stop").invoke(liveTimer); + } + + // Transparent delegate skip MUST be method-exact: a non-execute method on HttpChannel + // or SelectorManager calling QueuedThreadPool#execute MUST NOT be skipped even when + // invoked by an allowlisted caller (ReservedThreadExecutor#startReservedThread). + final String qtpInternal = "org/eclipse/jetty/util/thread/QueuedThreadPool"; + final byte[] rawQtp = generateSyntheticServerExecutorSink(qtpInternal, "execute", "(Ljava/lang/Runnable;)V"); + final byte[] hookedQtp = transformer.transform(JdkSinkBridgeTest.class.getClassLoader(), qtpInternal, + null, JdkSinkBridgeTest.class.getProtectionDomain(), rawQtp); + for (final String delegateInternal : new String[] { + "org/eclipse/jetty/server/HttpChannel", + "org/eclipse/jetty/io/SelectorManager" + }) { + final String delegateFqcn = delegateInternal.replace('/', '.'); + final byte[] rawDelegate = generateSyntheticServerCaller(delegateInternal, + "nonExecuteHelper", qtpInternal, "execute", "(Ljava/lang/Runnable;)V"); + final byte[] rawAllowedParent = generateSyntheticStaticRelay( + "org/eclipse/jetty/util/thread/ReservedThreadExecutor", "startReservedThread", + delegateInternal, "nonExecuteHelper"); + ClassLoader skipGuardLoader = new ClassLoader(JdkSinkBridgeTest.class.getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + byte[] bytes = null; + if ("org.eclipse.jetty.util.thread.QueuedThreadPool".equals(name)) { + bytes = hookedQtp; + } else if (delegateFqcn.equals(name)) { + bytes = rawDelegate; + } else if ("org.eclipse.jetty.util.thread.ReservedThreadExecutor".equals(name)) { + bytes = rawAllowedParent; + } + if (bytes != null) { + Class c = findLoadedClass(name); + if (c == null) { + c = defineClass(name, bytes, 0, bytes.length); + } + if (resolve) { + resolveClass(c); + } + return c; + } + return super.loadClass(name, resolve); + } + }; + Object qtpObj = skipGuardLoader.loadClass("org.eclipse.jetty.util.thread.QueuedThreadPool") + .getDeclaredConstructor().newInstance(); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(false); + RequestGate.disarm(); + skipGuardLoader.loadClass("org.eclipse.jetty.util.thread.ReservedThreadExecutor") + .getMethod("startReservedThread", Object.class, Runnable.class) + .invoke(null, qtpObj, (Runnable) () -> { }); + assertTrue("non-execute method on " + delegateFqcn + + " must NOT be skipped and must latch asyncExecutors=false", + KeployDedupAgent.observedPreCapturedUntrackedExecutor.get()); + } + } finally { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + RequestGate.disarm(); + } + } + + @Test + public void xnioWorkerOverrideVerificationRejectsSubclassesOverridingExecuteOrSubmit() throws Exception { + final ServerEntries transformer = new ServerEntries(true); + boolean savedLatch = KeployDedupAgent.observedPreCapturedUntrackedExecutor.get(); + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + try { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + byte[] baseBytes = generateSyntheticAbstractExecutorXnioWorker(); + byte[] goodSubBytes = generateSyntheticXnioSubclass("org/example/GoodSubWorker", false, false); + byte[] badExecBytes = generateSyntheticXnioSubclass("org/example/BadExecSubWorker", true, false); + byte[] badSubmitBytes = generateSyntheticXnioSubclass("org/example/BadSubmitSubWorker", false, true); + + ClassLoader holderLoader = new ClassLoader(JdkSinkBridgeTest.class.getClassLoader()) { + private byte[] hookedBase; + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + byte[] raw = null; + if ("org.xnio.XnioWorker".equals(name)) { + if (hookedBase == null) { + hookedBase = transformer.transform(this, "org/xnio/XnioWorker", null, + JdkSinkBridgeTest.class.getProtectionDomain(), baseBytes); + } + raw = hookedBase; + } else if ("org.example.GoodSubWorker".equals(name)) { + raw = goodSubBytes; + } else if ("org.example.BadExecSubWorker".equals(name)) { + raw = badExecBytes; + } else if ("org.example.BadSubmitSubWorker".equals(name)) { + raw = badSubmitBytes; + } + if (raw != null) { + Class c = findLoadedClass(name); + if (c == null) { + c = defineClass(name, raw, 0, raw.length); + } + if (resolve) { + resolveClass(c); + } + return c; + } + return super.loadClass(name, resolve); + } + }; + + Object good = holderLoader.loadClass("org.example.GoodSubWorker").getDeclaredConstructor().newInstance(); + Object badExec = holderLoader.loadClass("org.example.BadExecSubWorker").getDeclaredConstructor().newInstance(); + Object badSubmit = holderLoader.loadClass("org.example.BadSubmitSubWorker").getDeclaredConstructor().newInstance(); + + assertTrue("non-overriding hooked XnioWorker subclass must be accepted", + ServerEntries.isHookedXnioWorker(good)); + assertFalse("XnioWorker subclass overriding execute(Runnable) must be rejected", + ServerEntries.isHookedXnioWorker(badExec)); + assertFalse("XnioWorker subclass overriding submit(Runnable) must be rejected", + ServerEntries.isHookedXnioWorker(badSubmit)); + + ServerEntries.setHookStatusForTests(false, false, false, false, true); + assertFalse("asyncHookFailed=true must fail closed in isHookedXnioWorker", + ServerEntries.isHookedXnioWorker(good)); + } finally { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); + KeployDedupAgent.observedPreCapturedUntrackedExecutor.set(savedLatch); + RequestGate.disarm(); + } + } + + @Test + public void latchOnCallFailsClosedWhenClassReferencesOnlyUnhookedDispatcherTag7AndLacksTargetMethods() { + final ServerEntries transformer = new ServerEntries(true); + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + try { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + // Synthetic DefaultPartHttpMessageReader missing read/setBlockingOperationScheduler + // whose constant pool contains ONLY a CONSTANT_Class (tag 7) reference to + // reactor/core/scheduler/Schedulers (zero tag 10/11 DISPATCH_PRIMITIVE_METHODS refs). + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, + "org/springframework/http/codec/multipart/DefaultPartHttpMessageReader", + null, "java/lang/Object", null); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "other", "()Ljava/lang/Class;", null, null); + mv.visitCode(); + mv.visitLdcInsn(Type.getObjectType("reactor/core/scheduler/Schedulers")); + mv.visitInsn(Opcodes.ARETURN); + mv.visitMaxs(0, 0); + mv.visitEnd(); + cw.visitEnd(); + + byte[] out = transformer.transform(JdkSinkBridgeTest.class.getClassLoader(), + "org/springframework/http/codec/multipart/DefaultPartHttpMessageReader", + null, JdkSinkBridgeTest.class.getProtectionDomain(), cw.toByteArray()); + assertNull("missing latch methods must return null", out); + assertTrue("missing latch methods with tag-7 UNHOOKED_ASYNC_DISPATCHERS ref must set hadAsyncHookFailure()", + ServerEntries.hadAsyncHookFailure()); + } finally { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); + } + } + + @Test + public void newlyAllowlistedJettyAndSpringBootDispatchClassesHaveVerifiedLoadAndSinkBehaviour() { + final ServerEntries transformer = new ServerEntries(true); + String[] jettyEntries = { + "org/eclipse/jetty/io/ssl/SslConnection$SslEndPoint", + "org/eclipse/jetty/io/ssl/SslConnection$SslEndPoint$IncompleteWriteCallback", + "org/eclipse/jetty/server/ShutdownService", + "org/eclipse/jetty/server/internal/HttpConnection", + "org/eclipse/jetty/server/internal/HttpConnection$HttpStreamOverHTTP1", + "org/eclipse/jetty/util/thread/SerializedInvoker$Link", + "org/eclipse/jetty/util/thread/strategy/AdaptiveExecutionStrategy", + }; + String[] springBootInfraEntries = { + "org/springframework/boot/autoconfigure/BackgroundPreinitializer", + "org/springframework/boot/jetty/GracefulShutdown", + "org/springframework/boot/web/embedded/jetty/GracefulShutdown", + }; + java.util.Set savedUnhooked = ServerEntries.snapshotUnhookedAsyncDispatchers(); + try { + for (String internal : jettyEntries) { + String fqcn = internal.replace('/', '.'); + ServerEntries.setHookStatusForTests(false, false, false, false, false); + byte[] synthetic = generateClassReferencingExecutorAndThreadStart(internal); + transformer.transform(JdkSinkBridgeTest.class.getClassLoader(), internal, null, + JdkSinkBridgeTest.class.getProtectionDomain(), synthetic); + assertFalse("load-time scan must exempt allowlisted Jetty internal class " + fqcn, + ServerEntries.hasUnhookedAsyncDispatcher()); + assertFalse("Jetty class " + fqcn + " must NOT be allowlisted in SinkAllowlist thread callers", + SinkAllowlist.isAllowlistedThreadStartCaller(fqcn)); + assertFalse("Jetty class " + fqcn + " must NOT be allowlisted in SinkAllowlist pool callers", + SinkAllowlist.isAllowlistedPoolCaller(fqcn)); + assertFalse("Jetty class " + fqcn + " must NOT be allowlisted in SinkAllowlist FJP", + SinkAllowlist.isAllowlistedFjpSubmit(null, null, fqcn, null)); + assertFalse("Jetty class " + fqcn + " must NOT be allowlisted in SinkAllowlist Timer", + SinkAllowlist.isAllowlistedTimerSched(null, null, fqcn, null)); + } + for (String internal : springBootInfraEntries) { + String fqcn = internal.replace('/', '.'); + ServerEntries.setHookStatusForTests(false, false, false, false, false); + byte[] synthetic = generateClassReferencingExecutorAndThreadStart(internal); + transformer.transform(JdkSinkBridgeTest.class.getClassLoader(), internal, null, + JdkSinkBridgeTest.class.getProtectionDomain(), synthetic); + assertFalse("load-time scan must exempt verified Spring Boot infra class " + fqcn, + ServerEntries.hasUnhookedAsyncDispatcher()); + assertTrue("Spring Boot infra class " + fqcn + " must be allowlisted as INFRA_THREAD_CALLERS", + SinkAllowlist.isAllowlistedThreadStartCaller(fqcn)); + assertFalse("Spring Boot infra class " + fqcn + " must NOT be allowlisted as pool caller", + SinkAllowlist.isAllowlistedPoolCaller(fqcn)); + assertFalse("Spring Boot infra class " + fqcn + " must NOT be allowlisted in FJP", + SinkAllowlist.isAllowlistedFjpSubmit(null, null, fqcn, null)); + assertFalse("Spring Boot infra class " + fqcn + " must NOT be allowlisted in Timer", + SinkAllowlist.isAllowlistedTimerSched(null, null, fqcn, null)); + } + } finally { + ServerEntries.setHookStatusForTests(false, false, false, false, false); + ServerEntries.restoreUnhookedAsyncDispatchers(savedUnhooked); + } + } + + private static byte[] generateSyntheticServerExecutorSink(String internalName, String methodName, String desc) { + 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(); + + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, methodName, desc, null, null); + mv.visitCode(); + if (desc.endsWith(")V")) { + mv.visitInsn(Opcodes.RETURN); + } else if (desc.endsWith(")Z")) { + mv.visitInsn(Opcodes.ICONST_1); + mv.visitInsn(Opcodes.IRETURN); + } else { + mv.visitInsn(Opcodes.ACONST_NULL); + mv.visitInsn(Opcodes.ARETURN); + } + mv.visitMaxs(0, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateSyntheticStaticRelay(String callerInternal, String callerMethodName, + String targetInternal, String targetMethodName) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, callerInternal, null, "java/lang/Object", null); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, callerMethodName, + "(Ljava/lang/Object;Ljava/lang/Runnable;)V", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, targetInternal, targetMethodName, + "(Ljava/lang/Object;Ljava/lang/Runnable;)V", false); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(0, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateSyntheticServerCaller(String callerInternal, String callerMethodName, + String sinkInternal, String methodName, String desc) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, callerInternal, null, "java/lang/Object", null); + for (String cm : new String[] {callerMethodName, "unlistedMethod"}) { + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, cm, + "(Ljava/lang/Object;Ljava/lang/Runnable;)V", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitTypeInsn(Opcodes.CHECKCAST, sinkInternal); + mv.visitVarInsn(Opcodes.ALOAD, 1); + if (!desc.startsWith("(Ljava/lang/Runnable;)")) { + mv.visitLdcInsn(Long.valueOf(10L)); + mv.visitFieldInsn(Opcodes.GETSTATIC, "java/util/concurrent/TimeUnit", "MILLISECONDS", + "Ljava/util/concurrent/TimeUnit;"); + } + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, sinkInternal, methodName, desc, false); + if (!desc.endsWith(")V")) { + mv.visitInsn(Opcodes.POP); + } + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(0, 0); + mv.visitEnd(); + } + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateSyntheticNoTaskSink(String internalName, String methodName, String desc) { + 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(); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, methodName, desc, null, null); + mv.visitCode(); + if (desc.endsWith(")Z")) { + mv.visitInsn(Opcodes.ICONST_1); + mv.visitInsn(Opcodes.IRETURN); + } else if (desc.endsWith(")V")) { + mv.visitInsn(Opcodes.RETURN); + } else { + mv.visitInsn(Opcodes.ACONST_NULL); + mv.visitInsn(Opcodes.ARETURN); + } + mv.visitMaxs(0, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateSyntheticAbstractExecutorXnioWorker() { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "org/xnio/XnioWorker", null, + "java/util/concurrent/AbstractExecutorService", null); + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/util/concurrent/AbstractExecutorService", "", "()V", false); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(0, 0); + init.visitEnd(); + + MethodVisitor exec = cw.visitMethod(Opcodes.ACC_PUBLIC, "execute", "(Ljava/lang/Runnable;)V", null, null); + exec.visitCode(); + exec.visitInsn(Opcodes.RETURN); + exec.visitMaxs(0, 0); + exec.visitEnd(); + + for (String name : new String[] {"shutdown", "isShutdown", "isTerminated"}) { + MethodVisitor m = cw.visitMethod(Opcodes.ACC_PUBLIC, name, + "shutdown".equals(name) ? "()V" : "()Z", null, null); + m.visitCode(); + if ("shutdown".equals(name)) { + m.visitInsn(Opcodes.RETURN); + } else { + m.visitInsn(Opcodes.ICONST_0); + m.visitInsn(Opcodes.IRETURN); + } + m.visitMaxs(0, 0); + m.visitEnd(); + } + MethodVisitor sn = cw.visitMethod(Opcodes.ACC_PUBLIC, "shutdownNow", "()Ljava/util/List;", null, null); + sn.visitCode(); + sn.visitInsn(Opcodes.ACONST_NULL); + sn.visitInsn(Opcodes.ARETURN); + sn.visitMaxs(0, 0); + sn.visitEnd(); + + MethodVisitor at = cw.visitMethod(Opcodes.ACC_PUBLIC, "awaitTermination", + "(JLjava/util/concurrent/TimeUnit;)Z", null, null); + at.visitCode(); + at.visitInsn(Opcodes.ICONST_1); + at.visitInsn(Opcodes.IRETURN); + at.visitMaxs(0, 0); + at.visitEnd(); + + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateSyntheticXnioSubclass(String internalName, boolean overrideExecute, + boolean overrideSubmit) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, internalName, null, "org/xnio/XnioWorker", null); + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, "org/xnio/XnioWorker", "", "()V", false); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(0, 0); + init.visitEnd(); + if (overrideExecute) { + MethodVisitor m = cw.visitMethod(Opcodes.ACC_PUBLIC, "execute", "(Ljava/lang/Runnable;)V", null, null); + m.visitCode(); + m.visitInsn(Opcodes.RETURN); + m.visitMaxs(0, 0); + m.visitEnd(); + } + if (overrideSubmit) { + MethodVisitor m = cw.visitMethod(Opcodes.ACC_PUBLIC, "submit", + "(Ljava/lang/Runnable;)Ljava/util/concurrent/Future;", null, null); + m.visitCode(); + m.visitInsn(Opcodes.ACONST_NULL); + m.visitInsn(Opcodes.ARETURN); + m.visitMaxs(0, 0); + m.visitEnd(); + } + cw.visitEnd(); + return cw.toByteArray(); + } + + private static byte[] generateSyntheticSubclass(String subInternalName, String superInternalName) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, subInternalName, null, superInternalName, null); + MethodVisitor init = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); + init.visitCode(); + init.visitVarInsn(Opcodes.ALOAD, 0); + init.visitMethodInsn(Opcodes.INVOKESPECIAL, superInternalName, "", "()V", false); + init.visitInsn(Opcodes.RETURN); + init.visitMaxs(0, 0); + init.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } + + private static void invokeSyntheticTimerMethod(Class baseCls, Object instance, String methodName, String desc) + throws Exception { + if ("(JLjava/util/concurrent/TimeUnit;)Z".equals(desc)) { + baseCls.getMethod(methodName, long.class, TimeUnit.class) + .invoke(instance, Long.valueOf(10L), TimeUnit.MILLISECONDS); + } else if ("(J)V".equals(desc)) { + baseCls.getMethod(methodName, long.class).invoke(instance, Long.valueOf(10L)); + } else { + // Single-arg reference method (e.g. CyclicTimeouts#schedule(Expirable)). + for (java.lang.reflect.Method m : baseCls.getMethods()) { + if (methodName.equals(m.getName()) && m.getParameterCount() == 1) { + m.invoke(instance, new Object[] { null }); + return; + } + } + throw new NoSuchMethodException(baseCls.getName() + "#" + methodName + desc); + } + } + + private static byte[] generateClassReferencingExecutorAndThreadStart(String internalName) { + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); + cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, internalName, null, "java/lang/Object", null); + MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "ref", + "(Ljava/util/concurrent/Executor;Ljava/lang/Thread;Ljava/lang/Runnable;)V", null, null); + mv.visitCode(); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitVarInsn(Opcodes.ALOAD, 2); + mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/concurrent/Executor", "execute", + "(Ljava/lang/Runnable;)V", true); + mv.visitVarInsn(Opcodes.ALOAD, 1); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Thread", "start", "()V", false); + mv.visitInsn(Opcodes.RETURN); + mv.visitMaxs(0, 0); + mv.visitEnd(); + cw.visitEnd(); + return cw.toByteArray(); + } } diff --git a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java index 4af831f6..1ef7f9d0 100644 --- a/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java +++ b/keploy-sdk/src/test/java/org/example/servers/AsyncHonestyApp.java @@ -76,6 +76,9 @@ private static final class ConcretePoolHolder { private AsyncHonestyApp() { } + private static volatile Server JETTY_SERVER; + private static volatile Undertow UNDERTOW_SERVER; + public static void main(String[] args) throws Exception { String mode = args[0]; AutoCloseable server; @@ -102,6 +105,7 @@ public static void main(String[] args) throws Exception { SinkFixtures.init(mode.substring("sink-".length())); } Server jetty = new Server(0); + JETTY_SERVER = jetty; ServletContextHandler context = new ServletContextHandler(); ServletHolder holder = new ServletHolder(new AsyncServlet()); holder.setAsyncSupported(true); @@ -123,6 +127,7 @@ public static void main(String[] args) throws Exception { .addHttpListener(0, "127.0.0.1") .setHandler(deployment.start()) .build(); + UNDERTOW_SERVER = undertow; undertow.start(); port = ((InetSocketAddress) undertow.getListenerInfo().get(0).getAddress()).getPort(); server = undertow::stop; @@ -188,6 +193,32 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO path = req.getRequestURI() == null ? "/" : req.getRequestURI(); } long ms = req.getParameter("ms") == null ? 0L : Long.parseLong(req.getParameter("ms")); + if ("/async-dispatch-callable".equals(path)) { + // Spring MVC Callable / WebAsyncTask pattern: startAsync -> ac.start -> ac.dispatch. + final javax.servlet.AsyncContext ctx = req.startAsync(); + ctx.start(() -> { + sleepQuietly(ms); + ctx.dispatch("/async-dispatch-done"); + }); + return; + } + if ("/async-dispatch-deferred".equals(path)) { + // Spring MVC DeferredResult pattern: startAsync -> tracked pool completes -> ac.dispatch. + final javax.servlet.AsyncContext ctx = req.startAsync(); + PLAIN_POOL.submit(() -> { + sleepQuietly(ms); + ctx.dispatch("/async-dispatch-done"); + }); + return; + } + if ("/async-dispatch-done".equals(path)) { + byte[] ok = "dispatched-ok".getBytes(StandardCharsets.UTF_8); + resp.setContentType("text/plain"); + resp.setContentLength(ok.length); + resp.getOutputStream().write(ok); + resp.flushBuffer(); + return; + } if ("/async-after-complete".equals(path)) { final javax.servlet.AsyncContext ctx = req.startAsync(); final long delay = ms; @@ -348,6 +379,52 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } else if ("/warm-common-pool".equals(path)) { CompletableFuture.supplyAsync(() -> "warm").join(); Tail.ran(); + } else if ("/escape-jetty-qtp-reflect".equals(path)) { + try { + Object qtp = JETTY_SERVER.getThreadPool(); + Method m = qtp.getClass().getMethod("execute", Runnable.class); + m.invoke(qtp, (Runnable) () -> { + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + AsyncTail.ran(); + }); + } catch (Exception e) { + throw new IOException(e); + } + } else if ("/escape-jetty-sched-reflect".equals(path)) { + try { + Object sched = ((ServerConnector) JETTY_SERVER.getConnectors()[0]).getScheduler(); + Method m = sched.getClass().getMethod("schedule", Runnable.class, long.class, TimeUnit.class); + m.invoke(sched, (Runnable) () -> AsyncTail.ran(), Long.valueOf(ms), TimeUnit.MILLISECONDS); + } catch (Exception e) { + throw new IOException(e); + } + } else if ("/escape-undertow-io-reflect".equals(path)) { + try { + Object io = UNDERTOW_SERVER.getWorker().getIoThread(); + Method m = org.xnio.XnioIoThread.class.getMethod("execute", Runnable.class); + m.invoke(io, (Runnable) () -> { + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + AsyncTail.ran(); + }); + } catch (Exception e) { + throw new IOException(e); + } + } else if ("/escape-undertow-io-after-reflect".equals(path)) { + try { + Object io = UNDERTOW_SERVER.getWorker().getIoThread(); + Method m = org.xnio.XnioIoThread.class.getMethod("executeAfter", Runnable.class, long.class, TimeUnit.class); + m.invoke(io, (Runnable) () -> AsyncTail.ran(), Long.valueOf(ms), TimeUnit.MILLISECONDS); + } catch (Exception e) { + throw new IOException(e); + } } else if ("/untracked-schedule".equals(path)) { SCHED.schedule(() -> AsyncTail.ran(), 1, TimeUnit.MILLISECONDS); } else if ("/untracked-thread".equals(path)) {