Repository navigation
Check threads and the code JUnit runs between tests as the policy says - #471
MarkusPaulsen wants to merge 23 commits into
Conversation
With instrumentation, a task submitted to an executor or to CompletableFuture.runAsync was counted at the submit, and then the same submission failed on the JDK's own FutureTask, AsyncRun or worker thread, which no policy names. AspectJ only sees the submit, so the two backends disagreed. A thread operation the JDK reaches while running another one whose check already counted the task is now skipped in the instrumentation backend; a thread that supervised code starts itself, from a callback too, is still checked. The task class search now looks into any JDK collection passed as an argument, as invokeAll takes one, so a task cannot hide in a set. Arrays.parallelSort, parallelPrefix and parallelSetAll ran uncounted under AspectJ and were refused with instrumentation only when the common pool had to start a new worker. Both backends now treat them as the <implicit-thread-op:parallel> operation.
A thread that student code started during a test, or registered as a shutdown hook, kept running after the test, and everything it did then went unchecked: when a test ended, Ares cleared all its settings, and every runtime check returns early once the AOP mode or the supervised package is gone. Such a thread could overwrite a file the policy only let it read, at the end of the run or between two tests. Student code in the argument source of a parameterised test, such as a @MethodSource method, ran unchecked in the same way, because JUnit calls it before any test method is armed. Ending a test now removes every allowance but keeps the AOP mode, the supervised package and the test classes, so any thread the test left running is refused everything, with a reason that says the test has ended. Only the thread that ended the test, which runs JUnit and Ares, goes unchecked until the next test is armed, as all threads did before. A deactivated policy and a class phase without a policy still run unguarded, now by suspending the checks until that phase ends. The container of a template test is armed with the test's policy before JUnit builds its arguments, and closed when the container ends. The walk that tells whether one of Ares' own utilities is reading now stops at the first student frame. It walked the whole stack on every file check, so a recursion doing an allowed read at each level took quadratic time, over three minutes for what runs in under a second without Ares. Stopping there also stops counting a utility as Ares' own when student code sits between it and the read.
The static checks analyse the classes below the withinPath of @Policy, and the runtime checks supervise the classes of the package the policy names. When the two disagreed, one layer checked nothing: a misspelt or foreign package let a forbidden file read through at runtime without any warning, and a withinPath naming a sub-folder or the test output left the production classes of the package outside every static check, reflection included. Before arming, Ares now refuses a run in which a class below the withinPath lies outside the supervised package, or a compiled production class of that package lies outside the withinPath. Exempted test classes, package and module descriptors and Ares' own reserved packages take no part, so a broader parent package still passes.
A Timer starts its own thread as soon as it is built. With instrumentation, that start was checked as a thread of the class java.util.TimerThread, but AspectJ did not look at Timer at all, so under AspectJ a submission could start any number of timer threads beyond its thread allowance. AspectJ now checks every call that builds a Timer, or a subclass of it, as the creation of one java.util.TimerThread, the same thread instrumentation sees. Tasks scheduled on a timer run on that thread and start none of their own, so neither mode counts them.
…ation A request with java.net.http.HttpClient to an address the policy allows failed with instrumentation, because the client starts a selector thread and hands its own tasks to its own pool, and the thread check counted both against the student. AspectJ never sees these JDK-internal calls, so it allowed the same request. The instrumentation thread check now skips a thread start or hand-over that the HttpClient implementation makes itself, with only JDK code between it and the check. Frames are recognised by the module and class loader of their class, which code outside the JDK cannot fake. Student code in between, such as an executor handed to the client builder, still gets counted, and where the client connects stays for the network check to decide. The thread documentation also states how a Timer counts.
Since a test now ends by keeping the mode and the supervised package, every check after a test went on to its expensive steps for the thread that runs JUnit and Ares, which is meant to go unchecked until the next test is armed. Ares reading a class file from memory paid a full stack walk for each byte, so building the next test class's checks took minutes and the WALA and instrumentation run timed out on CI. Each instrumentation check now lets that thread pass right after it reads the supervised package, which is the answer the check reached anyway, only later. The JCE lifecycle probe accepts a mode left behind by a test that ended on its own thread.
Once a test ended, the thread running JUnit went unchecked until the next test was armed, and JUnit runs student code on that thread at such moments: a lazy argument source builds the next argument after the previous invocation has ended, a @testfactory stream builds its tests after the factory has returned, AutoCloseable arguments are closed after their invocation, and a @ParameterizedClass builds its arguments before any of its tests. A forbidden read there went through. So did one in the static initialiser of a test class when something other than its constructor, such as a static @tempdir field, initialised it. A template test, a test factory and a parameterised class are now armed as containers before JUnit runs anything in them, and when a test or phase inside one ends, the container is armed again for what JUnit runs next; it ends when the container ends. A class with a policy is initialised under that policy before anything else touches it, so its static initialiser runs under the class phase rule. This costs one more preparation of the policy each time an invocation inside a container ends.
… are sent Every java.net.http.HttpClient starts a selector thread when it is built. With instrumentation, the previous change let that thread pass uncounted, so building clients in a loop started threads beyond the policy, even with no thread allowed. Building a client now counts as one thread of the class java.net.http.HttpClient in both modes: AspectJ checks HttpClient.newHttpClient() and the build of a JDK client builder, and instrumentation counts the client's selector thread start under that name. The tasks the client hands to its pool, and the pool threads, stay uncounted in both modes, also for a JDK executor the student hands over; the documentation now says so. A request sent with sendAsync is connected on a thread of the client's pool, where no student code is on the stack, so the instrumentation network check never saw it and a forbidden address was reached. The agent and its class matcher skipped every jdk.internal class, including jdk.internal.net.http.HttpClientFacade, the class every JDK-built client is. That one class is now instrumented, so send and sendAsync are checked when the student calls them, as AspectJ does.
Arming a parameterised class without a policy on the class prepared it as a class phase without a policy, which suspends every check on every thread. Since a container is armed again after each of its tests, a thread an earlier run of the class left running could then read any file between the runs. A container is now armed, at its start and again after a test, only when that arms a policy; otherwise the test stays ended and code left running is refused. The documentation and the class comment now say that code left running gets the container's allowances between the tests of a container with a policy, and that the static initialiser escapes the class policy when something initialises the class first, as JUnit does for a class with a static @RegisterExtension or @ExtendWith field.
Under instrumentation the first image stream a student made, such as ImageIO.createImageOutputStream, was refused under a policy without thread permissions, because the JDK then starts its own image clean-up thread, sun.java2d.Disposer. That start is now allowed when only JDK code lies between it and the check, as for the threads of HttpClient. The helper that names the JDK module of a class moves to the abstract toolbox, so every subsystem can read it.
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars.
|
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen I found a security bypass in AspectJ's new collection traversal and a valid-input regression in the parallel-array checks. Please fix both before merging. Several integration checks and Windows unit tests were still running in the captured CI results.
…arallel array operations their token first Under AspectJ the thread check iterated a list, and since the counting of pool tasks any collection handed to invokeAll, without asking whether it is a JDK class. A collection class of the supervised code then ran its own iterator while the check was in progress, where the checks of what that iterator does are paused. AspectJ now refuses such a collection before iterating it, as instrumentation already did. Both backends inspected the arguments of Arrays.parallelSort, parallelPrefix and parallelSetAll before replacing what they found by the <implicit-thread-op:parallel> token. Sorting an array of the supervised code's own lists was therefore refused under instrumentation, and an array that holds itself was inspected without end in all four modes. The arguments of these operations are now not inspected at all; the token alone decides, as before.
On Windows the JDK builds the pipe of a selector over a socket file in the temp folder and deletes that file again. Every HttpClient opens such a selector, and under instrumentation the delete was refused as a delete by the supervised code. The file check now lets that delete pass when only JDK code lies between it and the JDK's pipe class. The stack rule and its unit test are the same as in the network pull request, which also uses them for the pipe's own bind and connect.
…hread The stack rule of the image clean-up exemption now reads the frames it is given, so a unit test can hand it built stacks: the JDK's own start passes, while student code before the Disposer, a missing Disposer, a class outside the JDK named like it and an Ares frame between JDK frames keep the check.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen Thanks, the direct student-set and parallel-array cases are fixed. A [high] bypass remains through delegated collections; I’ve described the concrete case in the existing thread. I also missed two valid-input problems earlier: set-valued submit results are treated as tasks, and the Windows pipe exemption never reaches network checks. Build, documentation, example and CodeQL checks are still unfinished.
Since the counting of pool tasks, both backends searched every collection among the arguments of a thread operation for tasks. A set handed to submit only as the value its future returns was then refused when its class belongs to the supervised code, and a JDK set of tasks used as such a value counted tasks that never run. Any JDK collection is now searched only in the arguments of invokeAll and invokeAny, which take the tasks they run as a collection; other calls search lists only, as before.
On Windows the pipe of every selector, also the one each HttpClient opens, connects a socket channel to a socket file of the JDK's own. Under instrumentation the network check refused that connect, because the supervised code that opened the selector is on the stack. The network check now lets an operation pass when only JDK code lies between it and the JDK's pipe class, the same rule the file check uses for the pipe's socket file. A connect the supervised code asks for itself is still decided by the policy.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen Thanks, the set-valued submit result and Windows selector-pipe cases are fixed. The [high] delegated-collection bypass in the existing thread remains: both backends still iterate JDK wrappers that can call student code while security checks are suppressed. Build, documentation, example and CodeQL checks are still unfinished.
The thread check accepted any JDK collection among the tasks given to invokeAll and invokeAny. A JDK wrapper such as Collections.unmodifiableSet is a JDK class, but iterating it runs the iterator of the collection it wraps, which can be a class of the supervised code, while the check is in progress. Both backends now iterate only the JDK collections that hold their own elements, matched by exact class and listed in one constant: ArrayList, LinkedList, ArrayDeque, Vector, PriorityQueue, HashSet, LinkedHashSet, TreeSet, the lists of Arrays.asList, List.of and Set.of, the empty and singleton collections, and the plain concurrent lists, sets and queues. Any other collection given as the tasks is refused, with a message asking for a plain list or set; a wrapper or view elsewhere in the arguments or in the fields of the receiver is not searched.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen Thanks, the delegating-wrapper bypass and the earlier array, submit-result and selector-pipe issues are fixed. I found a different [high] quota bypass introduced by the new return for non-plain lists: a task that also implements List is silently ignored in both backends. Build, documentation, example and CodeQL checks are still unfinished.
Since the thread check skips a list it cannot read safely, a task class of the supervised code that also extends a list, such as a class that extends ArrayList and implements Runnable, was skipped as a whole, so its class was neither checked against the policy nor counted. Both backends now resolve every value as a task first and only then search it as a collection, so such a task is checked and counted like any other, while its elements are still not iterated.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen Thanks, the list-backed task fix addresses the last reported bypass. I missed two other [high] cases earlier: TreeSet range views can run student comparators with security checks suppressed, and bulk submissions can exceed their task quota under the new instrumentation exemption. Build, documentation, example and CodeQL checks are still running.
A range view of a TreeSet has the exact class TreeSet, and creating its iterator compares the bounds with the set's comparator, which can be a class of the supervised code, while the thread check is in progress. TreeSet is no longer a plain collection in either backend, so a sorted set given as the tasks of invokeAll or invokeAny is refused like any other collection that is not plain. The tasks of invokeAll and invokeAny were counted once per distinct class, so a batch of four tasks of a class allowed three times used one allowance, and instrumentation then let the pool start its threads as part of that counted operation. Each task of such a batch now uses one allowance of its class in both backends; a class found again through the receiver's fields is still counted once.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen Thanks, the TreeSet range-view and oversized-batch fixes address the last two findings. I missed one [medium] valid-input regression earlier: bulk submissions reject allowed callable tasks that also implement Collection. Build, documentation, example and CodeQL checks are still unfinished.
A callable task class of the supervised code that also extends a set, given in a list to invokeAll, was read as a further collection of tasks after its own class was counted, and refused as a collection that is not plain, although the policy allowed it. Both backends now read only the argument of invokeAll or invokeAny as the collection of tasks; each entry counts by its own class, and a value that is itself a task is never searched further, whatever collection it also is.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen Thanks, the collection-backed callable fix addresses the last reported issue. I missed a separate [high] bypass earlier: mutable batches can change after validation, letting replacement tasks run without a class or quota check. Windows Build, Unit Tests, Core Integration Tests, all four enforcement integration checks, Static Code Analysis, both Windows examples and Analyse Java are still unfinished.
| // because the Command/Execute subsystem will check these operations. | ||
| if (isThreadCreationFromCommandExecution() || isThreadCreationFromAresTimeout(restrictedPackage) | ||
| || isJdkShellFolderHandOffWithoutStudentCode()) { | ||
| || isJdkShellFolderHandOffWithoutStudentCode() || isInsideCountedThreadOperation() |
There was a problem hiding this comment.
@MarkusPaulsen [high] This exemption can admit tasks that weren't validated. A student ThreadPoolExecutor subclass can call inherited invokeAll with Arrays.asList(allowed1, allowed2), then replace the second entry with an unlisted callable inside its first newTaskFor override, using a static reference to the list. The JDK's next iteration reads that replacement. When invokeAll later calls execute, the student hook has returned, so this predicate sees only JDK frames and skips validation: the unlisted callable runs unchecked. I missed this case earlier. Please make bulk calls execute the same stable task snapshot that was validated, and cover this synchronous mutation in all four modes.
🤖 Prompt for AI agents
In src/main/java/de/tum/cit/ase/ares/api/aop/java/instrumentation/advice/JavaInstrumentationAdviceThreadSystemToolbox.java, the counted-operation exemption trusts a mutable batch that the JDK reads again after validation, allowing replacement tasks to execute unchecked. Make bulk calls execute the exact stable task snapshot validated by enforcement in both runtime backends, and add regression coverage where a newTaskFor override replaces a later Arrays.asList entry with an unlisted callable.
There was a problem hiding this comment.
The instrumentation case is closed in 90a0f7b. The check of invokeAll and invokeAny now records the tasks it validated, by identity, for the submitting thread and that call only, and the call's end removes them, also when it throws. Inside such a call, a task the JDK hands to the pool (execute, and the completion service's submit for invokeAny) passes only if, after the JDK's own FutureTask, RunnableAdapter and QueueingFuture wrappers, matched by exact class and read without running their code, it is one of those tasks; anything else, such as a FutureTask subclass, a different newTaskFor result or a replaced entry, is checked like any other call, as on main. New cases in ThreadCountedOperationsTest: a pool subclass whose newTaskFor swaps an unlisted callable into an Arrays.asList batch is refused, and a running task that replaces a later entry with list.set before the pool reaches it is refused (deterministic: the pool's only thread is held by a latch, so CallerRunsPolicy runs the first task before the second is read). Both failed on 3ac646c in all four modes. A plain pool with an ArrayList, an invokeAny batch and a pool subclass without a newTaskFor override still run. Under AspectJ the JDK's pool code is not woven, so the same two cases are not checked there; that is the case on main already and is followed up separately, and the two AspectJ variants are marked disabled with that reason.
There was a problem hiding this comment.
Update: AspectJ now covers this too, in 1aba9a7. The invokeAll and invokeAny check reads a copy of the tasks and the pool is handed exactly that copy, refusing the call if the given collection is changed afterwards; what a pool's own newTaskFor or decorateTask returns is checked against the tasks validated for the call in progress, one occurrence each. The AspectJ variants of these tests are no longer disabled and pass in both AspectJ combinations.
…ed it With instrumentation, a thread operation the JDK makes while running an invokeAll or invokeAny whose check already counted the tasks was not checked again. The JDK reads the batch once more while it hands the tasks to the pool, so a task put in place after the check, by a pool's own task wrapping or by a task that already runs, reached the pool unchecked. The check of invokeAll and invokeAny now records the tasks it validated, by identity, for the submitting thread and that call only; the call's end removes them, also when it throws. Inside such a call, a task the JDK hands to the pool passes only if, after the JDK's own FutureTask, RunnableAdapter and QueueingFuture wrappers, matched by exact class and read without running their code, it is one of those tasks. Anything else is checked like any other call. The duplication baseline follows the new shape of the thread advice.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen Thanks, the bulk-call fix now rejects unlisted replacement tasks under instrumentation. Two [high] bypasses remain: substituted tasks in single submissions and excess task occurrences in mutated batches. Build, documentation, example and CodeQL checks are still unfinished.
| */ | ||
| private static boolean isValidatedBatchTask(@Nullable Object handedOver) { | ||
| Set<Object> validated = VALIDATED_BATCHES.get().peek(); | ||
| return validated != null && validated.contains(unwrapJdkTaskWrappers(handedOver)); |
There was a problem hiding this comment.
@MarkusPaulsen [high] Membership alone doesn't preserve the validated occurrence counts. For invokeAll(Arrays.asList(a, b)), where the two different task classes each have one allowance, a pool's first newTaskFor call can replace the second entry with the same object a. Both resulting futures unwrap to a member of this set, so both execute unchecked even though only one occurrence of a's class was charged. The new tests substitute an unlisted identity and miss this quota bypass. Please validate and execute one stable snapshot of the original task occurrences, and cover replacement with an already validated task in both instrumentation combinations.
🤖 Prompt for AI agents
In src/main/java/de/tum/cit/ase/ares/api/aop/java/instrumentation/advice/JavaInstrumentationAdviceThreadSystemToolbox.java, identity-set membership permits a mutable batch to repeat a validated task beyond its class quota. Capture one stable task snapshot for validation and execution, preserving occurrence counts, and add a regression where newTaskFor replaces a later different-class task with an earlier validated object.
There was a problem hiding this comment.
The instrumentation case is closed in 216022a. The validated tasks are now kept with how often each was validated, and each future handed to execute uses up one of those occurrences; a task already handed over as often as it was validated is checked like any other call. A task found again through the receiver's fields is still counted once. New cases in ThreadCountedOperationsTest: a running task allowed once that puts itself in place of a later entry with list.set is refused the second time the pool reaches it (deterministic: the pool's only thread is held by a latch, so CallerRunsPolicy runs the first task before the second is read), under ArchUnit and WALA with instrumentation; both failed on 90a0f7b. Under AspectJ this is not checked, as on main already; it is followed up separately and the AspectJ variants are marked disabled with that reason.
There was a problem hiding this comment.
Update: AspectJ now covers this too, in 1aba9a7. The invokeAll and invokeAny check reads a copy of the tasks and the pool is handed exactly that copy, refusing the call if the given collection is changed afterwards; what a pool's own newTaskFor or decorateTask returns is checked against the tasks validated for the call in progress, one occurrence each. The AspectJ variants of these tests are no longer disabled and pass in both AspectJ combinations.
…that call's check The previous change matched the tasks of invokeAll and invokeAny by membership only, and single submissions not at all. A pool subclass could wrap another task than the one given to submit, and a running task could put an already validated task in place of a later one, so that task ran more often than it was counted. Every counted operation now opens a scope for its call, closed when the call returns or throws: when its check passed, with the tasks it validated and how often; when it was exempt as part of an enclosing operation, sharing that operation's tasks. Inside submit, invokeAll, invokeAny and the completion service of invokeAny, a future handed to execute passes only if it wraps a validated task that has not yet been handed over as often as it was validated. Under a pool of the supervised code that overrides newTaskFor or decorateTask, nothing the JDK does inside the call is exempt, as on main.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen Thanks, the hook-substitution and repeated-handoff fixes address the last two reported instrumentation cases. I missed two cases earlier: concurrent batch replacement can still bypass validation, and deactivated parameterised/factory containers can block their helper threads. Build, documentation, all four example jobs and both CodeQL analyses are still unfinished.
| */ | ||
| @Override | ||
| public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) { | ||
| if (isContainer(extensionContext) && armsAPolicy(extensionContext)) { |
There was a problem hiding this comment.
@MarkusPaulsen [medium] Explicitly deactivated containers are skipped here, so their argument sources and lazy factory streams don't keep supervision suspended. After an active policy has run, endSupervision retains its package and mode, clears its allowances and exempts only the JUnit thread. A @ParameterizedTest @Policy(activated = false) source that starts and joins a helper thread calling student file-reading code therefore gets a SecurityException on that helper, despite enforcement being disabled for the test. This also affects helper threads created while consuming a deactivated factory's stream. Please preserve suspension throughout explicitly deactivated containers, including between invocations, and restore the enclosing state when they close.
🤖 Prompt for AI agents
In src/main/java/de/tum/cit/ase/ares/api/jupiter/JupiterSecurityExtension.java, deactivated containers are excluded from lifecycle tracking, leaving their source and factory helper threads subject to retained restrictions from an earlier active policy. Track explicit deactivation for the full container lifecycle, restore suspension between its invocations and the enclosing state on closure, and add regression coverage following an active policy in all four modes.
There was a problem hiding this comment.
Thanks. How explicitly deactivated containers keep the checks suspended between their invocations, and what state is restored when they close, is taken up as a separate follow-up after this pull request; no code changes for it here.
There was a problem hiding this comment.
@MarkusPaulsen Thanks for clarifying the scope. This regression comes from this PR replacing the reset between invocations with endSupervision(), which retains the previous package and mode while clearing allowances. Deactivated containers are still skipped, and their suspension isn't restored between invocations, so source or factory helper threads can receive a SecurityException despite activated = false. Please preserve suspension throughout their container lifecycle here so correct deactivated tests keep working.
The check of invokeAll and invokeAny read the given collection once to check the classes and allowances and a second time to record the tasks for the call, so a task another thread put into the collection between the two readings was recorded as validated. The check now copies each plain collection once and takes the classes, the allowances and the recorded tasks from that copy; a task put into the collection after the copy is not recorded and is checked when the pool reaches it.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen Thanks, the shared batch snapshot fixes the reported validation race. The existing [medium] deactivated-container issue remains: evaluateExecutionCondition still skips those containers, leaving their source helper threads under restrictions retained from an earlier test. I missed another [high] bypass earlier: a thread factory can substitute an unlisted task before the pool's exempted thread start. Build, documentation, all four example jobs and both CodeQL analyses are still unfinished.
| } | ||
| } | ||
| } | ||
| return true; |
There was a problem hiding this comment.
@MarkusPaulsen [high] An ordinary ThreadPoolExecutor passes this check even when its thread factory substitutes the worker. For example, give it the factory lambda ignored -> new Thread(new UnlistedTask()), then call execute(new AllowedTask()) under a policy allowing only AllowedTask. Thread construction isn't intercepted, and this agent doesn't instrument hidden lambda classes. After the factory returns, addWorker calls Thread.start with only JDK frames between it and the counted execute; the exemption therefore lets the unlisted task run. I missed this case earlier. Please verify the factory's returned thread before exempting its start, and cover the case in both instrumentation combinations.
🤖 Prompt for AI agents
In src/main/java/de/tum/cit/ase/ares/api/aop/java/instrumentation/advice/JavaInstrumentationAdviceThreadSystemToolbox.java, the counted-operation exemption trusts a pool's thread-factory output without checking that the returned thread runs the validated work. Validate the returned thread before exempting its start, and add regression coverage using a thread-factory lambda that returns a thread running an unlisted task in both instrumentation combinations.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen The existing [medium] deactivated-container regression and [high] thread-factory bypass remain: evaluateExecutionCondition still excludes deactivated containers, and takeCountedOperationExemption still exempts Thread.start without validating the factory's returned thread. Please address both here; deferring the container fix leaves correct deactivated tests blocked. Enforcement Integration Tests (ArchUnit + AspectJ) failed, but the captured evidence only reports exit code 1, so I couldn't attribute the failure. Core Integration Tests, Enforcement Integration Tests (WALA + AspectJ), Windows Core Integration Tests and both Windows enforcement checks are still running.
… a pool's own task wrapping returns Under AspectJ, the check of invokeAll and invokeAny now reads a copy of the tasks it is given, and the pool is handed exactly the copied tasks. Each time the pool takes the next one, the given collection must still hold the same task at that place; a collection changed after the check refuses the call with a message saying so. A newTaskFor or decorateTask of a pool the supervised code wrote is woven, so what it returns is now checked: it passes when it is the JDK's own scheduled task, or when it wraps, inside the JDK's FutureTask or RunnableAdapter, a task validated for the pool call in progress, using up one occurrence of it. Anything else is checked like any other thread creation. A pool call that hands over one task keeps that task validated for the call in the same way.
Claudia-Anthropica
left a comment
There was a problem hiding this comment.
@MarkusPaulsen The new AspectJ checks address the reported substitution examples, but I found two additional valid-input regressions and a performance issue below. The earlier [high] thread-factory bypass remains: takeCountedOperationExemption still exempts Thread.start without checking the factory's returned thread. The earlier [medium] deactivated-container regression also remains: evaluateExecutionCondition skips those containers, leaving their helper threads under restrictions retained from an earlier test. Build, documentation, all four example jobs and both CodeQL analyses are still running.
| return tasks; | ||
| } | ||
| TASK_SCOPES.get().push(validated); | ||
| return new GuardedBatch(tasks, copy.toArray()); |
There was a problem hiding this comment.
@MarkusPaulsen [medium] A valid forwarding executor now rejects Ares's own wrapper. If a student ThreadPoolExecutor subclass overrides invokeAll with return super.invokeAll(tasks), the outer advice passes this GuardedBatch to the override. The woven super.invokeAll(tasks) call is checked again, and collectTaskBatch rejects GuardedBatch because it isn't a plain JDK collection, even with quota available. Please preserve the validated batch through forwarding calls and cover this override in both AspectJ combinations.
🤖 Prompt for AI agents
In src/main/java/de/tum/cit/ase/ares/api/aop/java/aspectj/adviceandpointcut/JavaAspectJThreadSystemAdviceDefinitions.aj, a forwarding invokeAll override causes the nested advice to reject Ares's GuardedBatch. Recognise and safely reuse the internal validated batch and its scope across forwarding calls, preserving mutation checks, and add regression coverage for an override that delegates to super.invokeAll.
| */ | ||
| public void checkHandedOverTask(@Nonnull JoinPoint thisJoinPoint, @Nullable Object returned, | ||
| @Nullable Object given) { | ||
| if (given != null && returned == given || consumeHandOver(unwrapJdkTaskWrappers(returned))) { |
There was a problem hiding this comment.
@MarkusPaulsen [medium] Delegating newTaskFor overrides consume the same handoff more than once. With two student pool classes in an inheritance chain, each overriding newTaskFor to return super.newTaskFor(callable), this check runs twice for the same returned FutureTask. The first consumes the callable's identity allowance; the second falls through and checks java.util.concurrent.FutureTask as another task class, rejecting a valid submission whose policy allows the callable. Please validate one handoff across the hook invocation chain, with coverage in both AspectJ combinations.
🤖 Prompt for AI agents
In src/main/java/de/tum/cit/ase/ares/api/aop/java/aspectj/adviceandpointcut/JavaAspectJThreadSystemAdviceDefinitions.aj, nested delegating newTaskFor overrides consume one validated task occurrence repeatedly and then reject the unchanged FutureTask. Track the hook invocation chain so one returned handoff consumes one occurrence, while separate actual handoffs remain checked, and add a regression with two delegating overrides.
| * @param index the place | ||
| */ | ||
| private void requireUnchanged(int index) { | ||
| Object[] now = given.toArray(); |
There was a problem hiding this comment.
@MarkusPaulsen [low] Every iterator next() copies the entire original collection here. An unchanged batch of n tasks therefore performs n² reference copies and allocates n full arrays; 100,000 allowed tasks require ten billion reference copies just for this guard. This can make otherwise valid bulk submissions exceed their time limit. Please compare against the validated snapshot incrementally so traversing an unchanged batch takes linear work.
🤖 Prompt for AI agents
In src/main/java/de/tum/cit/ase/ares/api/aop/java/aspectj/adviceandpointcut/JavaAspectJThreadSystemAdviceDefinitions.aj, GuardedBatch.requireUnchanged copies the whole task collection for every yielded task, causing quadratic work and allocation. Replace repeated full copies with an incremental comparison that preserves validated task identities and the required mutation checks.
Summary
Threads and the JUnit lifecycle are now checked as the policy says. Code a test left running, and code JUnit runs between tests, now gets the policy's answer too. Both runtime modes count a
Timerand anHttpClientthe same, and instrumentation accepts correct pool,HttpClientand image code. AwithinPaththat names other classes than the policy's package is refused instead of being accepted silently.Linked issues
Split from #461
1. Problem
Parts of a run were outside the policy (all modes unless named):
@MethodSourceargument, a@TestFactoryelement, a closed argument, a@ParameterizedClasssource) was not checked.withinPathand a supervised package naming different classes left one layer with nothing to check.TimerorHttpClientwas not counted as a thread, and a student's task collection was iterated during the check.Arrays.parallelSortneeded no parallel allowance (except ArchUnit with instrumentation); over student lists or a self-holding array it was refused or inspected without end.Correct code failed under instrumentation: a pool or
CompletableFuturetask, an allowedHttpClientrequest (on Windows also its selector pipe), and the first image stream. Ares in the runtime layer and its JUnit hook are at fault.2. Improvement from the user's perspective
The policy now also applies to a thread a test leaves behind and to an argument source that JUnit calls outside a test, so a submission is graded under the same rules wherever its code runs. A thread pool,
CompletableFuture,TimerandHttpClientcount the same in both runtime modes, so a policy behaves the same whichever mode the exercise uses, and correct pool, HTTP and image code passes under instrumentation. An instructor whosewithinPathdoes not match the policy's package gets a clear refusal naming a class, instead of a run that silently checks less.3. Improvement from the maintainer's perspective
New tests cover what nothing covered: what a thread left running does after its test, the argument sources and other phases JUnit runs between tests, a mismatched
withinPath, pool and parallel counting, timers, andHttpClientthreads and requests, each in all four modes. A file read in a recursion no longer costs a full stack walk at each level, and the thread that ended a test skips the expensive steps of every check, so a WALA and instrumentation run no longer slows down after the first test class.4. Testing manual
Prerequisites
HttpClienttests then check only what Ares decides, asAGENTS.mdasks). Every command runs from the repository root.mainand this branch once each and keep both, as for any Ares pull request:git switch main, thenmvn -q install -DskipTests -Pwithout-quality-gates, then copy~/.m2/repository/de/tum/cit/ase/ares/2.2.2to a folderares-mainnext to the clone.git switch fix/enforcement/ares-222-threads-lifecycle, then the samemvncommand.~/.m2now holds this branch as 2.2.2.ares-mainback over~/.m2/repository/de/tum/cit/ase/ares/2.2.2; for the branch, run the branch'smvn installagain.examples/ares-exercise-mavenyou are the instructor:PenguinTestandsrc/test/resources/SecurityPolicy.yamlare yours,Penguin.javais what a student hands in. Rungit checkout -- examplesandgit clean -fdx examplesafter each step. These defects do not depend on the build tool; the Gradle example behaves the same.Steps
notes.txtwith one line in the example folder; the policy has no entry for it. Addpublic static String readNotes() throws java.io.IOException { return java.nio.file.Files.readString(java.nio.file.Path.of("notes.txt")); }toPenguin, and toPenguinTestaddstatic java.util.stream.Stream<String> lines() throws Exception { return java.util.stream.Stream.of(Penguin.readNotes()); }and@org.junit.jupiter.params.ParameterizedTest @org.junit.jupiter.params.provider.MethodSource("lines") @de.tum.cit.ase.ares.api.jupiter.Public void printsALine(String line) { System.out.println("READ " + line); }. Runmvn testinexamples/ares-exercise-mavenon main, then on the branch.SecurityPolicy.yamlsetregardingThreadCreationsto one entrycreateTheFollowingNumberOfThreads: 1,ofThisClass: "java.util.TimerThread". Addpublic static void twoTimers() { new java.util.Timer(true).cancel(); new java.util.Timer(true).cancel(); }toPenguinand@PublicTest void secondTimerIsRefused() { assertThrows(SecurityException.class, Penguin::twoTimers); }toPenguinTest. Runmvn teston main, then on the branch. Repeat both withJAVA_USING_MAVEN_ARCHUNIT_AND_INSTRUMENTATION.SecurityPolicy.yamlchangetheSupervisedCodeUsesTheFollowingPackageto"org.exampel". Runmvn teston main, then on the branch.mainand run them there, so the same tests provoke the defects:git reset --hardandgit clean -fd src/testputmainback as it was.ThreadCountedOperationsTestand the lifecycle probe included:Expected result
READwith the line ofnotes.txt: JUnit called the student's read before any test was armed, so the policy did not apply to it. On the branchprintsALinefails before its first invocation with an Ares refusal namingnotes.txt, and the three example tests still pass.secondTimerIsRefusedfails with "Expected java.lang.SecurityException to be thrown, but nothing was thrown": AspectJ never counted a timer. With instrumentation it passes on main already. On the branch it passes in both modes, and a singlenew java.util.Timer(true)still runs.rejectsTheForbiddenFilefails because its read was not refused: the runtime checks watched a package that holds no class. On the branch every test fails before it runs with an Ares refusal saying that a class below the withinPath, such asorg.example.Penguin, lies outside the supervised packageorg.exampel.SupervisionLifecycleTest(8),SupervisionJupiterPhasesTest(24) andSupervisedPackageMismatchTest(4) fails. A thread a test left running can still read after the test ended, an argument source, factory element, closed argument,@ParameterizedClasssource or static initialiser readspom.xmlwithout a refusal, and a foreign package is accepted.ThreadTimerTestfails its two AspectJ cases.ThreadHttpClientTestfails 12 of 24: under instrumentation even one allowed client is refused for itsHttpClientImpl$SelectorManagerthread, and in every mode a second client is not refused. OfThreadCountedOperationsTest#pool*+parallel*, 5 of 16 fail: instrumentation refuses an allowed pool task as "the thread java.util.concurrent.FutureTask", andArrays.parallelSortis not refused without the parallel token. Leave outrunAsync*on main: under AspectJrunAsyncRunsAllowedTaskMavenArchunitAspectJwaits forever.Negative case (what must still be rejected)
secondClientIsRefused*(a secondHttpClientbeyond one allowance),forbiddenAddressIsRefused*andforbiddenAddressIsRefusedWithoutWaiting*(sendandsendAsyncto port 25566),studentExecutorThreadIsRefused*(a thread a student executor starts for the client still counts),poolRefusesFourthTask*,parallelSortRefusedWithoutToken*,parallelSortOfStudentListsRefusedWithoutToken*andinvokeAllRefusesAStudentSetUnread*, all in four modes. On the positive sidesubmitAcceptsAStudentSetAsResult*andsubmitCountsNoTaskInASetResult*(a set used only as the result value is not searched for tasks),invokeAllRunsTasksFromAJdkSet*,parallelSortOfStudentListsAllowedByToken*andparallelSortOfACyclicArrayAllowedByToken*pass. The unit testsJavaInstrumentationImageDisposerSetUpTest,JavaInstrumentationPipeSetUpTestandJavaInstrumentationSelectorPipeNetworkTestcover the image clean-up thread and the Windows selector pipe, whose socket file connect and delete now pass (the positive network case runs on Windows only); Match network hosts by their addresses and check servers students open #469 carries the same pipe helper and test, so the two merge without conflict there.SupervisionLifecycleTestandSupervisionJupiterPhasesTestalso check the positive side: while its test runs, the lingering thread may read the allowed file, and an argument source may read it too. Only a file the policy does not list, or anything after the test ended, is refused.rejectsTheForbiddenFilekeeps passing in every step on the branch with the example's own policy.Modes exercised
Steps 4 and 5 run every case in all four modes. The Windows selector pipe is only exercised by the Windows CI job. The exercise steps were not run for this pull request; steps 4 and 5 were, on main and on this branch.
5. Test case coverage regarding this PR
JavaInstrumentationAdviceThreadSystemToolboxJavaInstrumentationAdviceAbstractToolboxJavaInstrumentationAdviceFileSystemToolboxJavaInstrumentationAdviceNetworkSystemToolboxJavaInstrumentationAdviceCommandSystemToolboxJavaInstrumentationPointcutDefinitionsJavaInstrumentationAgentJupiterSecurityExtensionJavaAOPTestCaseSettingsSupervisedScopeCheckJavaCreatorJavaExecuterThe AspectJ aspects (
JavaAspectJAbstractAdviceDefinitions,JavaAspectJThreadSystemAdviceDefinitions) are woven into the test JVM and are tested by the integration classes of step 5.Breaking changes and migration
java.util.Timercounts as one thread of the classjava.util.TimerThread, and eachjava.net.http.HttpClientas one thread of the classjava.net.http.HttpClient, in both runtime modes. An exercise whose solution builds either needs a thread entry for it.withinPathholds a class outsidetheSupervisedCodeUsesTheFollowingPackage, or whose package has a compiled student class outsidewithinPath. Fix the policy so the two name the same classes.Checklist
documentation/,README.md, Javadoc) was updated where the change is user-facing.Review progress