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.

9.1 KB
Raw Blame
package opensuite.script;

import opensuite.core.Bytes;
import opensuite.core.HttpMessage;
import opensuite.core.HttpService;
import opensuite.testkit.Expect;
import opensuite.testkit.Harness;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.tools.ToolProvider;

/**
 * Scripts run one at a time, off the caller's thread, within a time limit:
 * a change is kept only when the run ends well, a loop is stopped or given
 * up on, and a run that cannot start says why.
 */
public final class ScriptRunnerTest {

    private static final HttpService SVC = new HttpService("example.test", 80, false);
    private static final String RAW = "GET /a HTTP/1.1\r\nHost: example.test\r\n\r\n";

    private static ScriptEngine engine() { return new ScriptEngine(ToolProvider.getSystemJavaCompiler(), 1000); }

    private static RunResult run(ScriptEngine e, String source) { return run(e, source, new AtomicBoolean()); }

    private static RunResult run(ScriptEngine e, String source, AtomicBoolean stop) {
        return e.runCustomAction(source, SVC, new HttpMessage(Bytes.bytes(RAW)), null, s -> { }, stop);
    }

    public void run() {
        Harness.suite("script runner");

        Harness.test("a run returns its output and how long it took", () -> {
            RunResult r = run(engine(), "utilities.log(\"one\");\nutilities.log(2);");
            Expect.equal(r.status(), RunResult.Status.OK, "status: " + r.error());
            Expect.equal(r.log(), List.of("one", "2"), "log");
            Expect.isTrue(r.millis() >= 0, "millis");
            Expect.isNull(r.newRequest(), "no change");
        });

        Harness.test("setRequest gives the new request and leaves the given one", () -> {
            HttpMessage given = new HttpMessage(Bytes.bytes(RAW));
            RunResult r = engine().runCustomAction(
                    "requestResponse.setRequest(requestResponse.request().withHeader(\"X-A\", \"1\"));", SVC, given, null, s -> { }, new AtomicBoolean());
            Expect.equal(r.status(), RunResult.Status.OK, "status: " + r.error());
            Expect.equal(r.newRequest().header("X-A"), "1", "new header");
            Expect.isTrue(Arrays.equals(given.raw(), Bytes.bytes(RAW)), "given untouched");
        });

        Harness.test("a failed run drops the change and gives the line", () -> {
            RunResult r = run(engine(), "requestResponse.setRequest(requestResponse.request().withHeader(\"X-A\", \"1\"));\nthrow new RuntimeException(\"no\");");
            Expect.equal(r.status(), RunResult.Status.FAILED, "status");
            Expect.isNull(r.newRequest(), "change dropped");
            Expect.equal(r.error(), "RuntimeException: no at line 2", "error");
        });

        Harness.test("a compile error is reported", () -> {
            RunResult r = run(engine(), "utilities.lg(1);");
            Expect.equal(r.status(), RunResult.Status.FAILED, "status");
            Expect.isTrue(r.error().startsWith("line 1:"), "error: " + r.error());
        });

        Harness.test("a loop that listens is stopped at the limit, and the next run works", () -> {
            ScriptEngine e = engine();
            RunResult r = run(e, "while (!Thread.currentThread().isInterrupted()) { }");
            Expect.equal(r.status(), RunResult.Status.TIMEOUT, "status");
            Expect.equal(r.error(), "stopped after 1 s (time limit)", "error");
            Expect.equal(e.abandonedThreads(), 0, "abandoned");
            Expect.equal(run(e, "utilities.log(1);").status(), RunResult.Status.OK, "next run");
        });

        Harness.test("a loop that ignores interruption is given up on; at three, runs are refused", () -> {
            ScriptEngine e = engine();
            String stubborn = "while (true) { try { Thread.sleep(5); } catch (InterruptedException x) { } }";
            for (int i = 1; i <= 3; i++) {
                RunResult r = run(e, stubborn);
                Expect.equal(r.status(), RunResult.Status.TIMEOUT, "status " + i);
                Expect.isTrue(r.error().endsWith("; it is still running, restart Open Suite to stop it"), "error " + i + ": " + r.error());
                Expect.equal(e.abandonedThreads(), i, "abandoned " + i);
            }
            RunResult refused = run(e, "utilities.log(1);");
            Expect.equal(refused.status(), RunResult.Status.FAILED, "refused");
            Expect.equal(refused.error(), "3 scripts are still running and could not be stopped; restart Open Suite to stop them", "error");
        });

        Harness.test("runaway recursion is an exception and the runner carries on", () -> {
            ScriptEngine e = engine();
            RunResult r = run(e, "class R { int f(int n) { return f(n + 1); } }\nnew R().f(0);");
            Expect.equal(r.status(), RunResult.Status.FAILED, "status");
            Expect.isTrue(r.error().startsWith("StackOverflowError"), "error: " + r.error());
            Expect.equal(run(e, "utilities.log(1);").status(), RunResult.Status.OK, "next run");
        });

        Harness.test("stop ends a run", () -> {
            ScriptEngine e = new ScriptEngine(ToolProvider.getSystemJavaCompiler(), 10_000);
            AtomicBoolean stop = new AtomicBoolean();
            AtomicReference<RunResult> out = new AtomicReference<>();
            Thread t = new Thread(() -> out.set(run(e, "while (!Thread.currentThread().isInterrupted()) { }", stop)));
            t.start();
            try {
                Thread.sleep(1500);   // past the first compile
                stop.set(true);
                t.join(5000);
            } catch (InterruptedException x) { throw new AssertionError(x); }
            Expect.notNull(out.get(), "a result");
            Expect.equal(out.get().status(), RunResult.Status.STOPPED, "status");
            Expect.equal(out.get().error(), "stopped", "error");
        });

        Harness.test("a stop that comes before the run starts is kept", () -> {
            AtomicBoolean stop = new AtomicBoolean();
            stop.set(true);
            RunResult r = run(engine(), "while (!Thread.currentThread().isInterrupted()) { }", stop);
            Expect.equal(r.status(), RunResult.Status.STOPPED, "status");
            Expect.isTrue(r.millis() < 500, "stopped at once, not at the limit: " + r.millis());
        });

        Harness.test("stopping one run leaves another running", () -> {
            ScriptEngine e = new ScriptEngine(ToolProvider.getSystemJavaCompiler(), 2000);
            run(e, "int warm = 0;");
            AtomicReference<RunResult> a = new AtomicReference<>(), b = new AtomicReference<>();
            AtomicBoolean stopB = new AtomicBoolean();
            Thread ta = new Thread(() -> a.set(run(e, "while (!Thread.currentThread().isInterrupted()) { }", new AtomicBoolean())));
            Thread tb = new Thread(() -> b.set(run(e, "utilities.log(1);", stopB)));
            try {
                ta.start();
                Thread.sleep(500);
                tb.start();          // waits for A's turn to end
                Thread.sleep(200);
                stopB.set(true);
                ta.join(6000); tb.join(6000);
            } catch (InterruptedException x) { throw new AssertionError(x); }
            Expect.equal(a.get().status(), RunResult.Status.TIMEOUT, "the other run ran to its limit");
            Expect.equal(b.get().status(), RunResult.Status.STOPPED, "the stopped run");
        });

        Harness.test("runs are one at a time", () -> {
            ScriptEngine e = engine();
            run(e, "Thread.sleep(1);");   // compile first, so only the runs are timed
            long start = System.nanoTime();
            Thread a = new Thread(() -> run(e, "Thread.sleep(200);"));
            Thread b = new Thread(() -> run(e, "Thread.sleep(200);"));
            a.start(); b.start();
            try { a.join(); b.join(); } catch (InterruptedException x) { throw new AssertionError(x); }
            Expect.isTrue((System.nanoTime() - start) / 1_000_000 >= 400, "serialised");
        });

        Harness.test("log output past the cap is reported as cut", () -> {
            RunResult r = run(engine(), "for (int i = 0; i < 1005; i++) utilities.log(i);");
            Expect.equal(r.log().size(), 1000, "lines");
            Expect.isTrue(r.logCut(), "cut");
        });

        Harness.test("a failure inside the engine is a result, not a throw", () -> {
            javax.tools.JavaCompiler broken = (javax.tools.JavaCompiler) java.lang.reflect.Proxy.newProxyInstance(
                    getClass().getClassLoader(), new Class<?>[]{javax.tools.JavaCompiler.class},
                    (proxy, method, args) -> { throw new IllegalStateException("compiler broke"); });
            RunResult r = run(new ScriptEngine(broken, 1000), "utilities.log(1);");
            Expect.equal(r.status(), RunResult.Status.FAILED, "status");
            Expect.equal(r.error(), "internal error: IllegalStateException: compiler broke", "error");
        });

        Harness.test("no compiler is reported", () -> {
            RunResult r = run(new ScriptEngine(null, 1000), "int a;");
            Expect.equal(r.status(), RunResult.Status.FAILED, "status");
        });
    }
}