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.3 KB
Raw Blame
package opensuite.engine;

import com.sun.net.httpserver.HttpServer;
import opensuite.gate.GateRules;
import opensuite.spider.Cdp.JsonValue;
import opensuite.testkit.Expect;
import opensuite.testkit.Harness;

import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;

/** The engine's alerts are read once each, however many there are. */
public final class AlertFeedTest {

    /** Stands in for the engine: the three calls the feed makes, answered as the engine and the add-on answer them. */
    private static final class Engine implements AutoCloseable {
        final Map<Integer, String> alerts = new TreeMap<>();   // number to URL
        final AtomicInteger wholeListings = new AtomicInteger(), single = new AtomicInteger();
        volatile int gate = 3, most = 2000;
        final HttpServer server;

        Engine() throws Exception {
            server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
            server.createContext("/", x -> {
                String path = x.getRequestURI().getPath();
                Map<String, String> q = new HashMap<>();
                String raw = x.getRequestURI().getRawQuery();
                if (raw != null) for (String kv : raw.split("&")) {
                    int eq = kv.indexOf('=');
                    if (eq > 0) q.put(kv.substring(0, eq), URLDecoder.decode(kv.substring(eq + 1), StandardCharsets.UTF_8));
                }
                String body;
                int code = 200;
                synchronized (alerts) {
                    if (path.contains("/autoupdate/view/installedAddons")) {
                        body = "{\"installedAddons\":[{\"id\":\"opensuitegate\",\"version\":\"" + gate + ".0.0\"}]}";
                    } else if (path.contains("/opensuitegate/view/alertIds")) {
                        String base = q.getOrDefault("baseurl", "");
                        GateRules.Newer n = GateRules.newer(alerts.keySet(), Integer.parseInt(q.get("after")), most,
                                base.isEmpty() ? null : id -> alerts.get(id).startsWith(base));
                        body = "{\"ids\":\"" + n.idList() + "\",\"last\":\"" + n.last() + "\",\"top\":\"" + n.top() + "\"}";
                    } else if (path.contains("/core/view/alerts")) {
                        wholeListings.incrementAndGet();
                        StringBuilder b = new StringBuilder("{\"alerts\":[");
                        for (Map.Entry<Integer, String> a : alerts.entrySet()) {
                            if (b.charAt(b.length() - 1) == '}') b.append(',');
                            b.append(one(a.getKey(), a.getValue()));
                        }
                        body = b.append("]}").toString();
                    } else if (path.contains("/core/view/alert")) {
                        single.incrementAndGet();
                        int id = Integer.parseInt(q.get("id"));
                        if (alerts.containsKey(id)) body = "{\"alert\":" + one(id, alerts.get(id)) + "}";
                        else { code = 400; body = "{\"code\":\"does_not_exist\",\"message\":\"Does Not Exist\"}"; }
                    } else {
                        code = 404; body = "{}";
                    }
                }
                byte[] out = body.getBytes(StandardCharsets.UTF_8);
                x.sendResponseHeaders(code, out.length);
                x.getResponseBody().write(out);
                x.close();
            });
            server.start();
        }

        static String one(int id, String url) { return "{\"id\":\"" + id + "\",\"url\":\"" + url + "\",\"name\":\"Finding\"}"; }

        ZapApi api() { return new ZapApi("http://127.0.0.1:" + server.getAddress().getPort(), "key"); }

        void raise(int id, String url) { synchronized (alerts) { alerts.put(id, url); } }

        @Override public void close() { server.stop(0); }
    }

    private static List<String> ids(List<JsonValue> alerts) {
        List<String> out = new ArrayList<>();
        for (JsonValue a : alerts) out.add(ZapApi.str(a, "id"));
        return out;
    }

    private interface Body { void run() throws Exception; }

    private static void test(String name, Body body) {
        Harness.test(name, () -> {
            try { body.run(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); }
        });
    }

    public void run() {
        Harness.suite("AlertFeed");
        test("the alerts newer than one already had are named in order", () -> {
            GateRules.Newer n = GateRules.newer(List.of(7, 2, 9, 0, 4), 2, 0, null);
            Expect.equal(n.ids(), List.of(4, 7, 9), "rising, and only the newer");
            Expect.equal(n.last(), 9, "looked at up to the newest");
            Expect.equal(n.top(), 9, "the highest there is");
            Expect.equal(n.idList(), "4,7,9", "as the add-on sends them");

            GateRules.Newer capped = GateRules.newer(List.of(1, 2, 3, 4, 5), 0, 2, null);
            Expect.equal(capped.ids(), List.of(1, 2), "no more than asked for");
            Expect.equal(capped.last(), 2, "and the rest are asked for from here");
            Expect.equal(capped.top(), 5, "more are waiting");

            GateRules.Newer some = GateRules.newer(List.of(1, 2, 3, 4), 0, 0, id -> id % 2 == 0);
            Expect.equal(some.ids(), List.of(2, 4), "only the site's own");
            Expect.equal(some.last(), 4, "the others count as looked at");

            GateRules.Newer none = GateRules.newer(List.of(1, 2), 2, 0, null);
            Expect.equal(none.ids(), List.of(), "nothing new");
            Expect.equal(none.last(), 2, "and it stays where it was");
            Expect.equal(GateRules.newer(List.of(), 40, 0, null).top(), -1, "an engine with no alerts");
        });

        test("each alert is read once, and the whole listing is never asked for", () -> {
            try (Engine e = new Engine()) {
                e.raise(0, "http://app.test/a"); e.raise(1, "http://app.test/b"); e.raise(5, "http://app.test/c");   // 2 to 4 were deleted
                AlertFeed feed = new AlertFeed(e.api(), "");
                Expect.equal(ids(feed.next()), List.of("0", "1", "5"), "all there is, oldest first, across a gap");
                Expect.isFalse(feed.more(), "none left");
                Expect.equal(ids(feed.next()), List.of(), "nothing new: nothing read");
                e.raise(6, "http://app.test/d");
                Expect.equal(ids(feed.next()), List.of("6"), "only the new one");
                Expect.equal(e.single.get(), 4, "four alerts, four reads");
                Expect.equal(e.wholeListings.get(), 0, "the engine's own listing is not used");
            }
        });

        test("a scan reads only the alerts of its own site", () -> {
            try (Engine e = new Engine()) {
                e.raise(0, "http://app.test/a"); e.raise(1, "http://other.test/b"); e.raise(2, "http://app.test/c"); e.raise(3, "http://other.test/d");
                AlertFeed feed = new AlertFeed(e.api(), "http://app.test");
                Expect.equal(ids(feed.next()), List.of("0", "2"), "its own");
                Expect.equal(e.single.get(), 2, "the others are not fetched");
                e.raise(4, "http://other.test/e");
                Expect.equal(ids(feed.next()), List.of(), "another site's new alert is passed over");
            }
        });

        test("a long backlog is read in parts", () -> {
            try (Engine e = new Engine()) {
                e.most = 3;
                for (int i = 0; i < 8; i++) e.raise(i, "http://app.test/" + i);
                AlertFeed feed = new AlertFeed(e.api(), "");
                List<String> got = new ArrayList<>();
                int calls = 0;
                do { got.addAll(ids(feed.next())); calls++; } while (feed.more() && calls < 10);
                Expect.equal(got, List.of("0", "1", "2", "3", "4", "5", "6", "7"), "all of them, once each");
                Expect.equal(calls, 3, "three at a time");
            }
        });

        test("an engine that began again is read from its start", () -> {
            try (Engine e = new Engine()) {
                for (int i = 0; i < 6; i++) e.raise(i, "http://app.test/" + i);
                AlertFeed feed = new AlertFeed(e.api(), "");
                Expect.equal(feed.next().size(), 6, "six");
                synchronized (e.alerts) { e.alerts.clear(); }
                e.raise(0, "http://app.test/new");
                Expect.equal(ids(feed.next()), List.of("0"), "its numbers start again, and so does the reading");
            }
        });

        test("an engine with the older add-on is listed whole, as before", () -> {
            try (Engine e = new Engine()) {
                e.gate = 2;
                e.raise(0, "http://app.test/a"); e.raise(1, "http://app.test/b");
                AlertFeed feed = new AlertFeed(e.api(), "");
                Expect.equal(ids(feed.next()), List.of("0", "1"), "the whole listing");
                Expect.isFalse(feed.more(), "in one answer");
                Expect.equal(ids(feed.next()), List.of("0", "1"), "and again: the caller passes over what it has had");
                Expect.equal(e.wholeListings.get(), 2, "by the engine's own listing");
            }
        });
    }
}