Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

41.3 KB
Raw Blame
package opensuite.extensions;

import hello.HelloExtension;
import libsupport.Greeting;
import needslib.NeedsLibExtension;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.core.Issue;
import opensuite.core.LogEntry;
import opensuite.core.SuiteContext;
import opensuite.core.ToolModule;
import opensuite.testkit.Expect;
import opensuite.testkit.Harness;
import opensuite.ui.StateIO;
import opensuite.ui.ToolHost;
import slowly.SlowExtension;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;

/**
 * A Java extension loaded at run time runs as a tool, on a thread of its own,
 * and nothing it does can hold a suite thread.
 *
 * <p>The extension jars are built during the run, from classes whose packages
 * are outside {@code opensuite.} so that a jar carries no class of the suite's.
 * A recording host stands in for the window, so no window is needed and the
 * suite runs with {@code java.awt.headless} set.
 */
public final class ExtensionLoaderTest {

    private static final HttpService SVC = new HttpService("example.com", 443, true);
    private static final String REQUEST = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";

    /** Waits short enough that a hang costs a test a fraction of a second. */
    private static final ExtensionLoader.Timeouts SHORT = new ExtensionLoader.Timeouts(
            Duration.ofMillis(300), Duration.ofMillis(300), Duration.ofMillis(300), Duration.ofMillis(300), Duration.ofMillis(300), Duration.ofMillis(300));
    /** The same, with the watchdog far away: for the cases that must not be paused while they run. */
    private static final ExtensionLoader.Timeouts PATIENT = new ExtensionLoader.Timeouts(
            Duration.ofMillis(300), Duration.ofMillis(300), Duration.ofMillis(300), Duration.ofMillis(300), Duration.ofSeconds(60), Duration.ofMillis(300));

    /** Stands in for the window, as SuiteFrame does: it enters a tool in the context as it puts it up and takes it out as it takes it down, and it checks it is only ever asked on the event thread. */
    private static final class RecordingHost implements ToolHost {
        final SuiteContext ctx;
        final List<ToolModule> added = new CopyOnWriteArrayList<>();
        final List<ToolModule> removed = new CopyOnWriteArrayList<>();
        volatile boolean offEventThread;
        RecordingHost(SuiteContext ctx) { this.ctx = ctx; }
        @Override public void toolAdded(ToolModule m) {
            if (!SwingUtilities.isEventDispatchThread()) offEventThread = true;
            ctx.registerTool(m);
            added.add(m);
        }
        @Override public void toolRemoved(ToolModule m) {
            if (!SwingUtilities.isEventDispatchThread()) offEventThread = true;
            ctx.unregisterTool(m);
            removed.add(m);
        }
    }

    /** A loader over a context of its own, with the files and threads of one case. */
    private static final class Rig {
        final SuiteContext ctx = new SuiteContext();
        final RecordingHost host;
        final ExtensionLoader loader;
        final List<File> files = new ArrayList<>();
        /** Where this rig's loader keeps its list between runs. */
        final Path list;

        Rig(ExtensionLoader.Timeouts timeouts) {
            host = new RecordingHost(ctx);
            try { list = Files.createTempFile("opensuite-ext-list", ".tsv"); }
            catch (IOException e) { throw new RuntimeException(e); }
            files.add(list.toFile());
            loader = new ExtensionLoader(ctx, host, list, timeouts);
        }

        LoadedExtension add(File jar) {
            LoadedExtension x = loader.add("Java", jar, true);
            await("the load of " + jar.getName(), () -> x.done);
            return x;
        }

        /** What the extension reports, read through the module the suite sees. */
        String state(LoadedExtension x) { return String.valueOf(x.module.saveState()); }

        void close() {
            loader.close();
            for (File f : files) f.delete();
        }
    }

    public void run() {
        Harness.suite("extension loader");

        Harness.test("a hello jar loads as a tool, on a thread of its own", () -> caseHelloLoads());
        Harness.test("Send to hello reaches the extension, and a send returns at once", () -> caseSendTo());
        Harness.test("a listener an extension registers is never kept raw, wherever it registers from", () -> caseNeverRaw());
        Harness.test("Remove shuts the extension down, takes it off the suite and closes its loader", () -> caseRemove());
        Harness.test("unloaded and loaded again, the extension gets a new loader and a new thread", () -> caseReload());
        Harness.test("a file that is not a complete jar is said so, by name and size, each time it is tried", () -> caseNotAJar());
        Harness.test("a jar with no entry point is listed and nothing is installed", () -> caseNoEntryPoint());
        Harness.test("a name already taken is refused", () -> caseNameTaken());
        Harness.test("a listener that sleeps does not delay the suite's thread", () -> caseSleepingListener());
        Harness.test("a listener that throws does not stop the listeners after it", () -> caseThrowingListener());
        Harness.test("a full queue drops events rather than blocking", () -> caseFullQueue());
        Harness.test("an unresponsive extension is marked and paused, and can be resumed", () -> caseUnresponsive());
        Harness.test("a hung init disables the extension, and the suite still comes up", () -> caseHungInit());
        Harness.test("taking down a hung extension does not block the event thread, and its row stays to say so", () -> caseHungRemove());
        Harness.test("a removed extension whose thread ends later goes from the list", () -> caseHungRemoveLater());
        Harness.test("a saveState that hangs is left out within its limit", () -> caseHungSave());
        Harness.test("a restoreState that hangs disables the extension", () -> caseHungRestore());
        Harness.test("a sink that hangs does not block the sender", () -> caseHungSink());
        Harness.test("an extension's saved state goes through a project file, and waits for it if it is not loaded", () -> caseStateThroughProjectFile());
        Harness.test("a saved state a project file may not hold is refused when saved, and the project still opens", () -> caseStateRefused());
        Harness.test("a state a project saved before the extension loaded is given to it as it loads", () -> caseHeldStateAtLoad());
        Harness.test("a held state that does not restore in time has the extension disabled as it loads", () -> caseHeldStateHung());
        Harness.test("the library folder puts its jars on the extension's own class path", () -> caseLibraryFolder());
        Harness.test("the extensions listed last time load again on startup", () -> caseStartup());
    }

    // ---- the cases ----

    private void caseHelloLoads() {
        Rig rig = new Rig(SHORT);
        try {
            LoadedExtension x = rig.add(jar(rig, "hello", HelloExtension.class, hello.Idle.class));
            Expect.equal(x.status, "Loaded", "status");
            Expect.isTrue(x.loaded, "shown as loaded");
            Expect.equal(rig.host.added.size(), 1, "one module given to the shell");
            Expect.isFalse(rig.host.offEventThread, "the shell was asked on the event thread");
            Expect.equal(rig.ctx.tools().size(), 1, "one tool registered with the context");
            ToolModule module = rig.host.added.get(0);
            Expect.equal(module.name(), "hello", "its name");
            Class<?> own = x.target.getClass();
            Expect.isTrue(own.getClassLoader() == x.loader, "the extension's class came from its own loader");
            Expect.isTrue(own.getClassLoader() != HelloExtension.class.getClassLoader(), "and not from the class path the test runs on");
            Expect.isTrue(ToolModule.class.isAssignableFrom(own), "ToolModule is the suite's own class for it");
            Expect.equal(x.thread.threadName(), "opensuite-ext-hello", "its thread is named for the extension");
            Expect.isTrue(x.thread.worker().isDaemon(), "and is a daemon");
            Expect.equal(module.tabs().length, 1, "one tab");
            Expect.equal(module.tabs()[0].title(), "hello", "the tab's title");
            Expect.isTrue(rig.state(x).endsWith("thread=opensuite-ext-hello"), "its code runs on its own thread: " + rig.state(x));
        } finally { rig.close(); }
    }

    private void caseSendTo() {
        Rig rig = new Rig(SHORT);
        try {
            LoadedExtension x = rig.add(jar(rig, "hello", HelloExtension.class));
            Expect.isTrue(rig.ctx.sinkNames().contains("hello"), "a Send to destination, which is what the Send to menus list");
            long started = System.nanoTime();
            rig.ctx.sendTo("hello", SVC, message(REQUEST), null, null);
            long took = millisSince(started);
            Expect.isTrue(took < 100, "the send returned at once: " + took + " ms");
            await("the send reaching the extension", () -> rig.state(x).startsWith("sends=1;"));
        } finally { rig.close(); }
    }

    private void caseNeverRaw() {
        Rig rig = new Rig(SHORT);
        try {
            LoadedExtension x = rig.add(jar(rig, "hello", HelloExtension.class));
            Expect.equal(x.thread.registrations(), 0, "nothing registered from its init");
            // A listener registered on the event thread, from code of the extension's.
            Method listen = x.target.getClass().getMethod("listenFrom", SuiteContext.class);
            SwingUtilities.invokeAndWait(() -> {
                try { listen.invoke(x.target, rig.ctx); }
                catch (Exception e) { throw new RuntimeException(e); }
            });
            Expect.equal(x.thread.registrations(), 1, "a listener registered from the event thread is the extension's own");
            rig.ctx.settings().set("hello.key", "1");
            rig.loader.setLoaded(x, false);
            await("the unload", () -> "Not loaded".equals(x.status));
            Expect.isNull(x.thread, "its thread ended");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally { rig.close(); }
    }

    private void caseRemove() {
        Rig rig = new Rig(SHORT);
        try {
            File file = jar(rig, "hello", HelloExtension.class, hello.Idle.class);
            LoadedExtension x = rig.add(file);
            rig.loader.remove(x);
            Expect.equal(rig.host.removed.size(), 1, "the shell was told at once");
            Expect.isTrue(rig.ctx.tools().isEmpty(), "no longer a tool");
            Expect.isFalse(rig.ctx.sinkNames().contains("hello"), "no longer a Send to destination");
            await("the row leaving the list", () -> rig.loader.items().isEmpty());
            Expect.isTrue(x.loaderClosed, "its class loader was closed");
            Expect.isNull(x.thread, "its thread ended");
            Expect.isTrue(rig.ctx.alerts().stream().anyMatch(a -> "hello".equals(a.tool) && a.message.contains("shutdown")),
                    "shutdown() was called first");
            // A closed loader lets go of its jar; that is what closing means for it, since a later lookup would open the file again.
            // Linux exposes the descriptor count through /proc/self/fd. macOS has no
            // equivalent procfs path, while loaderClosed above remains the portable
            // proof that URLClassLoader.close() completed.
            if (procFdAvailable()) await("the jar's handle being released", () -> openHandles(file) == 0);
        } finally { rig.close(); }
    }

    private void caseReload() {
        Rig rig = new Rig(SHORT);
        try {
            LoadedExtension x = rig.add(jar(rig, "hello", HelloExtension.class));
            ExtensionClassLoader first = x.loader;
            ExtensionThread firstThread = x.thread;
            rig.loader.setLoaded(x, false);
            await("the unload", () -> "Not loaded".equals(x.status));
            Expect.isTrue(x.loaderClosed, "the first loader was closed");
            Expect.equal(rig.host.removed.size(), 1, "the shell was told it left");
            rig.loader.setLoaded(x, true);
            await("the reload", () -> "Loaded".equals(x.status) && x.done);
            Expect.isTrue(x.loader != first, "a new class loader");
            Expect.isTrue(x.thread != firstThread, "a new thread");
            Expect.isFalse(firstThread.isAlive(), "the old thread ended");
            Expect.equal(rig.host.added.size(), 2, "the shell was asked for it twice");
        } finally { rig.close(); }
    }

    private void caseNotAJar() {
        Rig rig = new Rig(SHORT);
        try {
            File empty = Files.createTempFile("opensuite-ext-empty", ".jar").toFile();
            rig.files.add(empty.toPath().toAbsolutePath().toFile());
            rig.files.add(empty);
            Files.write(empty.toPath(), new byte[0]);
            LoadedExtension x = rig.add(empty);
            Expect.equal(x.status, "Failed: not a complete jar", "status for an empty file");
            Expect.isTrue(x.errors.toString().contains(empty.getName() + " is 0 bytes"), "its Errors name the file and its size: " + x.errors);
            Expect.isNull(x.loader, "no class loader was made");
            // Trying again, as ticking Loaded does: a cut-short file this time, and one more line in Errors.
            byte[] cut = new byte[6];
            System.arraycopy("PK\003\004\000\000".getBytes(StandardCharsets.ISO_8859_1), 0, cut, 0, 6);
            Files.write(empty.toPath(), cut);
            rig.loader.setLoaded(x, true);
            await("the second attempt", () -> x.errors.toString().contains(" is 6 bytes"));
            Expect.equal(x.status, "Failed: not a complete jar", "status for a cut-short file");
            Expect.isTrue(x.errors.toString().split("\n").length == 2, "each attempt leaves one line: " + x.errors);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally { rig.close(); }
    }

    private void caseNoEntryPoint() {
        Rig rig = new Rig(SHORT);
        try {
            LoadedExtension x = rig.add(jar(rig, "empty"));
            Expect.equal(x.status, "No entry point", "status");
            Expect.isFalse(x.loaded, "nothing to show as loaded");
            Expect.isTrue(rig.host.added.isEmpty(), "nothing was given to the shell");
            Expect.isTrue(rig.ctx.tools().isEmpty(), "nothing was registered");
            Expect.isNull(x.loader, "no class loader was made");
        } finally { rig.close(); }
    }

    private void caseNameTaken() {
        Rig rig = new Rig(SHORT);
        try {
            rig.add(jar(rig, "hello-a", HelloExtension.class));
            LoadedExtension again = rig.add(jar(rig, "hello-b", HelloExtension.class));
            Expect.equal(again.status, "Failed: the name \"hello\" is already used by a tool", "status");
            Expect.equal(rig.host.added.size(), 1, "still one module");
            Expect.isTrue(rig.ctx.tools().size() == 1, "still one tool");
        } finally { rig.close(); }
    }

    private void caseSleepingListener() {
        Rig rig = new Rig(PATIENT);
        System.setProperty(SlowExtension.MODE, "listener-sleep");
        try {
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class));
            AtomicInteger suiteIssues = new AtomicInteger(), suiteSites = new AtomicInteger();
            rig.ctx.addIssueListener(i -> suiteIssues.incrementAndGet());
            rig.ctx.addSiteMapListener(e -> suiteSites.incrementAndGet());

            long started = System.nanoTime();
            rig.ctx.siteMapChanged(entry());
            long site = millisSince(started);
            started = System.nanoTime();
            rig.ctx.addIssue(issue("/one"));
            long issue = millisSince(started);
            Expect.isTrue(site < 100, "siteMapChanged returned in " + site + " ms with an extension asleep on it");
            Expect.isTrue(issue < 100, "issueAdded returned in " + issue + " ms with an extension asleep on it");
            Expect.equal(suiteSites.get(), 1, "the suite's own site map listener was still called");
            Expect.equal(suiteIssues.get(), 1, "the suite's own issue listener was still called");
            await("the extension's thread taking its first event", () -> x.thread.runningMillis() > 0);
            Expect.isTrue(x.thread.worker().getState() == Thread.State.TIMED_WAITING,
                    "the extension's own thread is the one asleep: " + x.thread.worker().getState());
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    private void caseThrowingListener() {
        Rig rig = new Rig(PATIENT);
        System.setProperty(SlowExtension.MODE, "listener-throws");
        try {
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class));
            AtomicInteger suiteIssues = new AtomicInteger();
            rig.ctx.addIssueListener(i -> suiteIssues.incrementAndGet());
            rig.ctx.addIssue(issue("/one"));
            rig.ctx.addIssue(issue("/two"));
            rig.ctx.settings().set("slowly.key", "1");
            await("both events reaching the extension", () -> rig.state(x).startsWith("issues=2;") && rig.state(x).contains("settings=1;"));
            Expect.isTrue(rig.state(x).contains("later=2;"), "the extension's second listener was called after its first threw");
            Expect.equal(suiteIssues.get(), 2, "the suite's own listener was called both times");
            Expect.isTrue(x.errors.toString().contains("boom from an extension"), "the failure is on the extension's row");
            Expect.isFalse(x.unresponsive, "a listener that throws is not one that hangs");
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    private void caseFullQueue() {
        Rig rig = new Rig(PATIENT);
        System.setProperty(SlowExtension.MODE, "listener-sleep");
        try {
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class));
            int sent = 1300;
            long worst = 0;
            for (int i = 0; i < sent; i++) {
                long started = System.nanoTime();
                rig.ctx.siteMapChanged(entry());
                worst = Math.max(worst, millisSince(started));
            }
            Expect.isTrue(worst < 100, "no call waited for the extension: the slowest took " + worst + " ms");
            // One event is asleep on the thread, ExtensionThread.QUEUE_LIMIT wait behind it, and the rest are dropped.
            long expected = sent - 1 - ExtensionThread.QUEUE_LIMIT;
            await("the drops being counted", () -> x.thread.droppedEvents() == expected);
            long alerts = rig.ctx.alerts().stream().filter(a -> a.message.contains("events have been dropped")).count();
            Expect.equal(alerts, 2L, "one Alert at the first drop and one a thousand drops later");
            Expect.equal(rig.ctx.alerts().stream().filter(a -> a.message.endsWith(": 1 events have been dropped because it is not keeping up.")).count(), 1L,
                    "the first Alert says so");
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    private void caseUnresponsive() {
        Rig rig = new Rig(SHORT);
        System.setProperty(SlowExtension.MODE, "listener-sleep");
        try {
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class));
            rig.ctx.siteMapChanged(entry());
            await("the watchdog", () -> x.unresponsive);
            Expect.equal(x.status, "Unresponsive", "marked in its row");
            Expect.isTrue(x.note.contains("paused"), "the row says events are paused: " + x.note);
            Expect.isTrue(x.thread.isPaused(), "events are paused");
            Expect.isTrue(rig.ctx.alerts().stream().anyMatch(a -> a.message.contains("is unresponsive")), "one Alert in the event log");
            Expect.isTrue(x.errors.toString().contains("unresponsive"), "and a line in its Errors");
            long before = x.thread.droppedEvents();
            rig.ctx.siteMapChanged(entry());
            Expect.equal(x.thread.droppedEvents(), before + 1, "an event raised while it is paused is dropped, not queued");

            rig.loader.resume(x);
            Expect.isFalse(x.thread.isPaused(), "taking events again");
            Expect.equal(x.status, "Loaded", "its row again");
            Expect.equal(x.thread.droppedEvents(), before + 1, "the count of drops stands since it loaded");
            // The same event is still asleep on its thread, so it is marked again after its time is up.
            await("being marked again", () -> x.unresponsive);
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    private void caseHungInit() {
        Rig rig = new Rig(SHORT);
        System.setProperty(SlowExtension.MODE, "init-sleep");
        LoadedExtension hung;
        try {
            hung = rig.add(jar(rig, "slowly", SlowExtension.class));
        } finally {
            System.clearProperty(SlowExtension.MODE);
        }
        try {
            Expect.isTrue(hung.status.startsWith("Disabled: init() did not finish in "), "status: " + hung.status);
            Expect.isFalse(hung.loaded, "not running");
            Expect.isTrue(rig.host.added.isEmpty(), "nothing was given to the shell");
            Expect.isTrue(rig.ctx.tools().isEmpty(), "nothing was registered");
            Expect.isTrue(hung.errors.toString().contains("init() did not finish in 300 ms"), "its Errors say why");
            Expect.isNull(hung.thread, "its thread was interrupted and ended");
            Expect.isTrue(hung.loaderClosed, "and its loader was closed");
            // The suite still comes up.
            System.clearProperty(SlowExtension.MODE);
            LoadedExtension hello = rig.add(jar(rig, "hello", HelloExtension.class));
            Expect.equal(hello.status, "Loaded", "another extension loads afterwards");
            Expect.equal(rig.host.added.size(), 1, "and is the one the shell was given");
        } finally { rig.close(); }
    }

    private void caseHungRemove() {
        Rig rig = new Rig(SHORT);
        System.setProperty(SlowExtension.MODE, "listener-stick");
        try {
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class));
            rig.ctx.siteMapChanged(entry());
            await("the event reaching the extension", () -> x.thread.runningMillis() > 0);
            await("the watchdog", () -> x.unresponsive);
            long marked = alerts(rig, "is unresponsive");
            long[] onEventThread = { 0 };
            SwingUtilities.invokeAndWait(() -> {
                long started = System.nanoTime();
                rig.loader.remove(x);
                onEventThread[0] = millisSince(started);
            });
            Expect.isTrue(onEventThread[0] < 100, "Remove returned on the event thread in " + onEventThread[0] + " ms");
            Expect.isTrue(rig.host.removed.size() == 1 && rig.ctx.tools().isEmpty(), "off the shell and the context at once");
            await("the wait for its thread", () -> "Won't unload until restart".equals(x.status));
            Expect.isTrue(x.thread != null && x.thread.isAlive(), "its thread is still running: it was never stopped");
            Expect.isFalse(x.loaderClosed, "so its class loader is kept");
            Expect.equal(rig.loader.items().size(), 1, "and its row stays, to say so");
            // Long enough for the watchdog to have looked at it several more times.
            Thread.sleep(400);
            Expect.equal(alerts(rig, "is unresponsive"), marked, "it is not reported unresponsive again while it goes");
            Expect.isFalse(x.errors.toString().contains("shutdown() did not finish"), "and nothing waited for a shutdown it could not run: " + x.errors);
            rig.loader.resume(x);
            Expect.equal(x.status, "Won't unload until restart", "there is nothing to resume");
            Expect.isTrue(x.unresponsive, "and it is still marked as it was");
            rig.ctx.siteMapChanged(entry());
            Expect.equal(x.thread.registrations(), 0, "nothing of it is left on the suite's lists");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    private void caseHungRemoveLater() {
        Rig rig = new Rig(SHORT);
        System.setProperty(SlowExtension.MODE, "listener-stick-a-while");
        try {
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class));
            rig.ctx.siteMapChanged(entry());
            await("the event reaching the extension", () -> x.thread.runningMillis() > 0);
            rig.loader.remove(x);
            await("the wait for its thread", () -> "Won't unload until restart".equals(x.status));
            Expect.equal(rig.loader.items().size(), 1, "its row stays while its thread runs");
            // The fixture gives up after a second and a half, ignoring interrupts until then.
            await("its thread ending and the row going", () -> rig.loader.items().isEmpty());
            Expect.isTrue(x.loaderClosed, "then its class loader is closed");
            Expect.isNull(x.thread, "and nothing of it is held");
            Expect.isTrue(rig.host.removed.size() == 1, "the shell was asked once");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    private void caseHungSave() {
        Rig rig = new Rig(SHORT);
        System.setProperty(SlowExtension.MODE, "save-sleep");
        try {
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class));
            long started = System.nanoTime();
            java.io.Serializable state = x.module.saveState();
            long took = millisSince(started);
            Expect.isNull(state, "a state that is not ready in time is left out");
            Expect.isTrue(took >= 250 && took < 2000, "after its limit and no longer: " + took + " ms");
            Expect.isTrue(x.errors.toString().contains("saveState() did not finish in 300 ms"), "its Errors say why");
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    private void caseHungRestore() {
        Rig rig = new Rig(SHORT);
        System.setProperty(SlowExtension.MODE, "restore-sleep");
        try {
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class));
            long started = System.nanoTime();
            x.module.restoreState("saved earlier");
            long took = millisSince(started);
            Expect.isTrue(took >= 250 && took < 2000, "the restore was waited for only as long as its limit: " + took + " ms");
            Expect.isTrue(x.status.startsWith("Disabled: restoring its saved state did not finish in "), "status: " + x.status);
            Expect.isTrue(rig.host.removed.size() == 1 && rig.ctx.tools().isEmpty(), "off the suite");
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    private void caseHungSink() {
        Rig rig = new Rig(SHORT);
        System.setProperty(SlowExtension.MODE, "sink-sleep");
        try {
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class));
            long started = System.nanoTime();
            rig.ctx.sendTo("slowly", SVC, message(REQUEST), null, null);
            long took = millisSince(started);
            Expect.isTrue(took < 100, "the send returned at once: " + took + " ms");
            await("the send reaching the extension", () -> x.thread.runningMillis() > 0);
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    // ---- saved state ----

    private void caseStateThroughProjectFile() {
        Rig first = new Rig(SHORT), second = new Rig(SHORT);
        try {
            LoadedExtension a = first.add(jar(first, "hello", HelloExtension.class));
            first.ctx.sendTo("hello", SVC, message(REQUEST), null, null);
            await("the send being counted", () -> first.state(a).startsWith("sends=1;"));
            Path file = projectFile(first);
            StateIO.save(first.ctx, file.toFile());

            // Opened in a session where the extension is not loaded yet: its state waits for it.
            StateIO.restore(second.ctx, file.toFile());
            Expect.isTrue(second.ctx.tools().isEmpty(), "no tool is registered yet");
            LoadedExtension b = second.add(jar(second, "hello", HelloExtension.class));
            await("the waiting state being given to it", () -> second.state(b).contains("restored=sends=1;"));
            Expect.isTrue(second.state(b).startsWith("sends=0;"), "it starts afresh, with the saved state handed to its restoreState");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            first.close();
            second.close();
        }
    }

    private void caseStateRefused() {
        Rig rig = new Rig(SHORT);
        System.setProperty(SlowExtension.MODE, "save-foreign");
        try {
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class, SlowExtension.Own.class));
            Expect.isNull(x.module.saveState(), "a state of the extension's own class is not saved");
            Expect.isTrue(x.errors.toString().contains("slowly.SlowExtension$Own"), "its Errors name the class: " + x.errors);
            Expect.equal(alerts(rig, "left out of the project file"), 1L, "one Alert");
            Expect.isNull(x.module.saveState(), "and it is left out the next time too");
            Expect.equal(alerts(rig, "left out of the project file"), 1L, "but the event log is not filled with it");
            // The project is saved without it, and opens.
            Path file = projectFile(rig);
            StateIO.save(rig.ctx, file.toFile());
            Rig other = new Rig(SHORT);
            try {
                StateIO.restore(other.ctx, file.toFile());
                Expect.isNull(other.ctx.takeHeldToolState("slowly"), "nothing of that state is in the file");
            } finally { other.close(); }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    private void caseHeldStateAtLoad() {
        Rig rig = new Rig(SHORT);
        try {
            rig.ctx.holdToolState("hello", "kept for it");
            LoadedExtension x = rig.add(jar(rig, "hello", HelloExtension.class));
            Expect.equal(x.status, "Loaded", "status");
            Expect.isTrue(rig.state(x).contains("restored=kept for it"), "it was given the state as it loaded: " + rig.state(x));
            Expect.isNull(rig.ctx.takeHeldToolState("hello"), "taken once");
        } finally { rig.close(); }
    }

    private void caseHeldStateHung() {
        Rig rig = new Rig(SHORT);
        System.setProperty(SlowExtension.MODE, "restore-sleep");
        try {
            rig.ctx.holdToolState("slowly", "saved before it was loaded");
            LoadedExtension x = rig.add(jar(rig, "slowly", SlowExtension.class));
            Expect.isTrue(x.status.startsWith("Disabled: restoring its saved state did not finish in "), "status: " + x.status);
            Expect.isTrue(rig.host.added.isEmpty(), "nothing was given to the shell");
            Expect.isNull(rig.ctx.takeHeldToolState("slowly"), "the state was taken, and not put back");
        } finally {
            System.clearProperty(SlowExtension.MODE);
            rig.close();
        }
    }

    /** An empty project file path for {@code rig}; the store creates the file. */
    private static Path projectFile(Rig rig) throws IOException {
        Path file = Files.createTempFile("opensuite-ext-state", ".osuite");
        rig.files.add(file.toFile());
        Files.delete(file);
        return file;
    }

    // ---- the library folder ----

    private void caseLibraryFolder() {
        Rig rig = new Rig(SHORT);
        Path libs = null;
        try {
            // The suite under test has libsupport on its own class path, so without the folder the extension falls back to that copy.
            LoadedExtension without = rig.add(jar(rig, "needslib", NeedsLibExtension.class));
            Expect.equal(without.status, "Loaded", "status without a library folder");
            Expect.equal(without.name, "needslib-with-suite-library", "it used the suite's copy of the library");

            // The folder: one jar holding the library.
            libs = Files.createTempDirectory("opensuite-ext-libs");
            File library = jar(rig, "libsupport", libsupport.Greeting.class);
            Path inFolder = libs.resolve("libsupport.jar");
            Files.move(library.toPath(), inFolder);
            rig.ctx.settings().set(ExtensionLoader.JAVA_LIBS, libs.toString());
            LoadedExtension with = rig.add(jar(rig, "needslib-with-folder", NeedsLibExtension.class));
            Expect.equal(with.status, "Loaded", "status with the folder");
            Expect.equal(with.name, "needslib-with-own-library", "it used the copy from the library folder, not the suite's");
            Expect.isTrue(with.output.toString().contains("1 library jars on its class path from " + libs), "its Output says so: " + with.output);
            Expect.isTrue(rig.host.added.get(rig.host.added.size() - 1).tabs()[0].title().equals("hello from libsupport"), "and built its tab with it");

            // A folder that is not there is said so, and the extension still loads (with the suite's copy, so the first one makes room for its name).
            rig.loader.remove(without);
            await("the first extension leaving", () -> rig.loader.items().size() == 1);
            rig.ctx.settings().set(ExtensionLoader.JAVA_LIBS, libs.resolve("nowhere").toString());
            LoadedExtension nowhere = rig.add(jar(rig, "needslib-no-folder", NeedsLibExtension.class));
            Expect.equal(nowhere.status, "Loaded", "status with a missing folder");
            Expect.isTrue(nowhere.errors.toString().contains("is not a folder"), "its Errors say the folder is not there: " + nowhere.errors);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            rig.ctx.settings().remove(ExtensionLoader.JAVA_LIBS);
            rig.close();
            if (libs != null) {
                File inFolder = libs.resolve("libsupport.jar").toFile();
                inFolder.delete();
                libs.toFile().delete();
            }
        }
    }

    private static long alerts(Rig rig, String words) {
        return rig.ctx.alerts().stream().filter(a -> a.message.contains(words)).count();
    }

    /** The lines of a file, none if it cannot be read yet. */
    private static List<String> lines(Path file) {
        try { return Files.readAllLines(file); }
        catch (IOException e) { return List.of(); }
    }

    // ---- startup ----

    private void caseStartup() {
        Rig rig = new Rig(SHORT);
        try {
            File hello = jar(rig, "hello", HelloExtension.class);
            File alsoHello = jar(rig, "hello-again", HelloExtension.class);
            File moved = new File(hello.getParentFile(), "moved-away.jar");
            Files.writeString(rig.list, "# Open Suite extensions\nJava\t" + hello + "\ttrue\nJava\t" + moved + "\ttrue\nJava\t" + alsoHello + "\tfalse\n\n");
            rig.loader.reloadOnStartup();
            await("the listed extensions settling", () -> rig.loader.items().size() == 3 && rig.loader.items().stream().allMatch(x -> x.done));
            List<LoadedExtension> items = rig.loader.items();
            Expect.equal(items.get(0).status, "Loaded", "the one that loads again");
            Expect.equal(items.get(1).status, "File not found", "the one whose file has moved is listed as not found");
            Expect.equal(items.get(2).status, "Not loaded", "the one whose Auto-reload is off is listed, and not loaded");
            Expect.equal(rig.host.added.size(), 1, "and only the first was given to the shell");

            // With the setting off, everything is listed and nothing loads.
            rig.ctx.settings().set(ExtensionLoader.RELOAD_ON_STARTUP, "false");
            try {
                Rig off = new Rig(SHORT);
                try {
                    Files.writeString(off.list, "Java\t" + hello + "\ttrue\n");
                    off.loader.reloadOnStartup();
                    Expect.equal(off.loader.items().size(), 1, "listed");
                    Expect.equal(off.loader.items().get(0).status, "Not loaded", "and not loaded");
                    Expect.isTrue(off.host.added.isEmpty(), "nothing was given to the shell");
                } finally { off.close(); }
            } finally { rig.ctx.settings().remove(ExtensionLoader.RELOAD_ON_STARTUP); }

            // The list is written as it changes.
            rig.loader.setAutoReload(items.get(2), true);
            rig.loader.remove(items.get(1));
            await("the list being rewritten", () -> lines(rig.list).size() == 3);
            List<String> lines = lines(rig.list);
            Expect.isTrue(lines.get(0).startsWith("#"), "the first line is the heading: " + lines.get(0));
            Expect.equal(lines.get(1), "Java\t" + hello + "\ttrue", "the first extension");
            Expect.equal(lines.get(2), "Java\t" + alsoHello + "\ttrue", "the second, with its Auto-reload as it now is");
            Expect.equal(lines.size(), 3, "and nothing else");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally { rig.close(); }
    }

    // ---- helpers ----

    /** A jar holding the given classes and nothing else; it is checked to carry nothing of the suite's. */
    private static File jar(Rig rig, String name, Class<?>... classes) {
        Path file = null;
        try {
            file = Files.createTempFile("opensuite-ext-" + name + "-", ".jar");
            rig.files.add(file.toFile());
            try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(file))) {
                for (Class<?> c : classes) {
                    String entry = c.getName().replace('.', '/') + ".class";
                    try (InputStream in = c.getClassLoader().getResourceAsStream(entry)) {
                        Expect.notNull(in, "the compiled class " + entry);
                        out.putNextEntry(new JarEntry(entry));
                        in.transferTo(out);
                        out.closeEntry();
                    }
                }
            }
            try (JarFile check = new JarFile(file.toFile())) {
                for (JarEntry e : Collections.list(check.entries())) {
                    Expect.isFalse(e.getName().startsWith("opensuite/"), "a test extension jar carries a class of the suite's: " + e.getName());
                }
            }
            return file.toFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /** Whether this runtime exposes process file descriptors through Linux procfs. */
    private static boolean procFdAvailable() {
        return Files.isDirectory(Path.of("/proc/self/fd"));
    }

    /** How many of this process's open files are the given file, read from /proc as on Linux; -1 when that cannot be read here. */
    private static int openHandles(File file) {
        Path dir = Path.of("/proc/self/fd");
        if (!procFdAvailable()) return -1;
        int open = 0;
        try (java.nio.file.DirectoryStream<Path> fds = Files.newDirectoryStream(dir)) {
            for (Path fd : fds) {
                try { if (Files.isSameFile(Files.readSymbolicLink(fd), file.toPath())) open++; }
                catch (IOException notThisFile) { }
            }
        } catch (IOException e) {
            return -1;
        }
        return open;
    }

    private static HttpMessage message(String text) { return new HttpMessage(text.getBytes(StandardCharsets.ISO_8859_1)); }

    private static LogEntry entry() {
        return new LogEntry("proxy", SVC, message(REQUEST));
    }

    private static Issue issue(String path) {
        return new Issue("A finding", Issue.Severity.HIGH, Issue.Confidence.FIRM, SVC, path, "", "d", "", "", null, null);
    }

    private static long millisSince(long startedNanos) {
        return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedNanos);
    }

    /** Wait for {@code condition}, failing the case if it does not hold within ten seconds. */
    private static void await(String what, BooleanSupplier condition) {
        long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
        while (!condition.getAsBoolean()) {
            if (System.nanoTime() > deadline) throw new AssertionError("gave up waiting for " + what);
            try { Thread.sleep(5); }
            catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError("interrupted while waiting for " + what); }
        }
    }
}