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.

35.1 KB
Raw Blame
package opensuite.engine;

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

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Tests how a scan's session is picked out of the proxy history and kept up
 * to date, how a login form is read and filled in, and the patterns handed
 * to the engine. The session check is proven against a small application
 * run inside the test.
 */
public final class ScanAuthTest {

    private static LogEntry entry(String tool, HttpService svc, String raw) {
        return new LogEntry(tool, svc, new HttpMessage(Bytes.bytes(raw)));
    }

    private static ScanAuth.Header find(List<ScanAuth.Header> hs, String site, String name) {
        for (ScanAuth.Header h : hs) if (h.site().equals(site) && h.name().equalsIgnoreCase(name)) return h;
        return null;
    }

    public void run() {
        Harness.suite("Scan session");

        HttpService app = HttpService.of("app.test", 443, true), api = HttpService.of("api.test", 443, true),
                other = HttpService.of("elsewhere.test", 443, true);

        Harness.test("session headers are told from ordinary ones", () -> {
            for (String n : List.of("Cookie", "Authorization", "X-Api-Key", "X-Auth-Token", "X-CSRF-Token", "X-XSRF-TOKEN", "apikey"))
                Expect.isTrue(ScanAuth.isAuthHeader(n), n);
            for (String n : List.of("Accept", "User-Agent", "Proxy-Authorization", "Sec-Fetch-Site", "Content-Type", "Referer", "Host"))
                Expect.isFalse(ScanAuth.isAuthHeader(n), n);
        });

        Harness.test("the scan names itself as the browser the session was made in", () -> {
            List<LogEntry> h = new ArrayList<>();
            h.add(entry("proxy", app, "GET / HTTP/1.1\r\nHost: app.test\r\nUser-Agent: OldBrowser/1\r\nCookie: s=1\r\n\r\n"));
            h.add(entry("proxy", app, "GET /a HTTP/1.1\r\nHost: app.test\r\nUser-Agent: NewBrowser/2\r\nCookie: s=2\r\n\r\n"));
            h.add(entry("proxy", other, "GET / HTTP/1.1\r\nHost: elsewhere.test\r\nUser-Agent: Unrelated/9\r\n\r\n"));
            h.add(entry("crawl", app, "GET /b HTTP/1.1\r\nHost: app.test\r\nUser-Agent: Scanner/0\r\n\r\n"));
            Expect.equal(ScanAuth.userAgent(h, Set.of(app.url())), "NewBrowser/2", "the newest the browser sent to the site");
            Expect.isTrue(ScanAuth.userAgent(h, Set.of(api.url())) == null, "none where the browser has not been");
        });

        Harness.test("the newest session of each site is taken from the proxy history", () -> {
            List<LogEntry> h = new ArrayList<>();
            h.add(entry("proxy", app, "GET / HTTP/1.1\r\nHost: app.test\r\nCookie: session=old; theme=dark\r\n\r\n"));
            h.add(entry("proxy", api, "GET /me HTTP/1.1\r\nHost: api.test\r\nAuthorization: Bearer one\r\n\r\n"));
            h.add(entry("proxy", other, "GET / HTTP/1.1\r\nHost: elsewhere.test\r\nCookie: x=1\r\n\r\n"));
            h.add(entry("repeater", app, "GET / HTTP/1.1\r\nHost: app.test\r\nCookie: session=fromrepeater\r\n\r\n"));
            h.add(entry("proxy", app, "GET /cart HTTP/1.1\r\nHost: app.test\r\nCookie: session=new\r\nAccept: */*\r\n\r\n"));
            h.add(entry("proxy", api, "GET /me HTTP/1.1\r\nHost: api.test\r\nAuthorization: Bearer two\r\nX-Api-Key: k1\r\n\r\n"));
            List<ScanAuth.Header> got = ScanAuth.capture(h, Set.of(app.url(), api.url()), 0);
            Expect.equal(find(got, app.url(), "Cookie").value(), "session=new; theme=dark", "cookies merged, newest value first");
            Expect.equal(find(got, api.url(), "Authorization").value(), "Bearer two", "newest token");
            Expect.equal(find(got, api.url(), "X-Api-Key").value(), "k1", "other session headers come too");
            Expect.isNull(find(got, other.url(), "Cookie"), "a site that is not a target is left out");
            Expect.equal(got.size(), 3, "nothing else");
        });

        Harness.test("only entries after the mark are read when following the browser", () -> {
            List<LogEntry> h = new ArrayList<>();
            LogEntry first = entry("proxy", app, "GET / HTTP/1.1\r\nHost: app.test\r\nCookie: session=a\r\n\r\n");
            h.add(first);
            Expect.equal(ScanAuth.capture(h, Set.of(app.url()), first.number()).size(), 0, "nothing new");
            h.add(entry("proxy", app, "GET / HTTP/1.1\r\nHost: app.test\r\nCookie: session=b\r\n\r\n"));
            Expect.equal(ScanAuth.capture(h, Set.of(app.url()), first.number()).get(0).value(), "session=b", "the newer one");
        });

        Harness.test("a newer session replaces the scan's, and only the headers it chose", () -> {
            List<ScanAuth.Header> current = List.of(new ScanAuth.Header("https://app.test", "Cookie", "session=a; csrf=1"),
                    new ScanAuth.Header("https://api.test", "Authorization", "Bearer one"));
            List<ScanAuth.Header> newer = List.of(new ScanAuth.Header("https://app.test", "Cookie", "session=b"),
                    new ScanAuth.Header("https://app.test", "X-Api-Key", "not chosen"));
            List<ScanAuth.Header> m = ScanAuth.merged(current, newer);
            Expect.notNull(m, "changed");
            Expect.equal(m.size(), 2, "no header added");
            Expect.equal(m.get(0).value(), "session=b; csrf=1", "the cookie that changed, with the one that did not");
            Expect.equal(m.get(1).value(), "Bearer one", "untouched");
            Expect.isNull(ScanAuth.merged(m, newer), "the same again changes nothing");
        });

        Harness.test("the check's request loses the browser's session and gains the scan's", () -> {
            ScanAuth.Check c = new ScanAuth.Check(app, new HttpMessage(Bytes.bytes(
                    "GET /account HTTP/1.1\r\nHost: app.test\r\nCookie: session=browser\r\nAuthorization: Bearer browser\r\nIf-None-Match: \"x\"\r\n\r\n")));
            List<ScanAuth.Header> hs = List.of(new ScanAuth.Header("https://app.test", "Cookie", "session=scan"),
                    new ScanAuth.Header("https://api.test", "Authorization", "Bearer api"));
            HttpMessage with = ScanAuth.dressed(c, hs, true), without = ScanAuth.dressed(c, hs, false);
            Expect.equal(with.header("Cookie"), "session=scan", "the scan's cookie");
            Expect.isNull(with.header("Authorization"), "another site's token is not sent here");
            Expect.isNull(with.header("If-None-Match"), "no cached answer");
            Expect.isNull(without.header("Cookie"), "bare without the session");
        });

        Harness.test("a login form is read into a request with the credentials marked", () -> {
            String html = "<html><form action=\"/search\"><input name=q></form>"
                    + "<form method=\"post\" action=\"/session?next=%2Faccount\">"
                    + "<input type=\"hidden\" name=\"csrf\" value=\"abc&amp;1\">"
                    + "<input type=\"email\" name=\"email\"><input type='password' name='pw'>"
                    + "<input type=checkbox name=remember value=1 checked><input type=checkbox name=news value=1>"
                    + "<button type=\"submit\" name=\"go\" value=\"Sign in\">Sign in</button></form></html>";
            LoginFlow.Template t = LoginFlow.formIn(app, "/login", html);
            Expect.notNull(t, "found the form with the password field");
            Expect.equal(t.request.method(), "POST", "method");
            Expect.equal(t.request.requestTarget(), "/session?next=%2Faccount", "action");
            Expect.equal(t.request.bodyText(), "csrf=abc%261&email=" + LoginFlow.USER + "&pw=" + LoginFlow.PASS + "&remember=1&go=Sign+in", "body");
            Expect.equal(t.request.header("Content-Length"), String.valueOf(t.request.body().length), "length set");
            Expect.equal(t.pagePath, "/login", "the page to fetch first");
            Expect.isNull(LoginFlow.formIn(app, "/", "<form><input name=q></form>"), "no password field, no login");
            Expect.isNull(LoginFlow.formIn(app, "/", "<form action='https://sso.other/login'><input type=password name=p></form>"), "a form posting elsewhere");
        });

        Harness.test("a login seen in the proxy history becomes the template", () -> {
            List<LogEntry> h = new ArrayList<>();
            h.add(entry("proxy", app, "POST /login HTTP/1.1\r\nHost: app.test\r\nCookie: pre=1\r\nReferer: https://app.test/signin?x=1\r\n"
                    + "Content-Type: application/x-www-form-urlencoded\r\nContent-Length: 44\r\n\r\ncsrf=old&user=alice%40x.test&pass=s3cr%26t%21"));
            LoginFlow.Template t = LoginFlow.fromHistory(h, Set.of(app.url()), "[email protected]", "s3cr&t!");
            Expect.notNull(t, "found");
            Expect.equal(t.request.bodyText(), "csrf=old&user=" + LoginFlow.USER + "&pass=" + LoginFlow.PASS, "credentials marked");
            Expect.isNull(t.request.header("Cookie"), "the old cookie is dropped");
            Expect.equal(t.pagePath, "/signin?x=1", "the form's page from the referer");
            Expect.isNull(LoginFlow.fromHistory(h, Set.of(app.url()), "[email protected]", "wrong"), "another password is not in it");

            List<LogEntry> j = new ArrayList<>();
            j.add(entry("proxy", api, "POST /auth HTTP/1.1\r\nHost: api.test\r\nContent-Type: application/json\r\nContent-Length: 40\r\n\r\n"
                    + "{\"username\":\"bob\",\"password\":\"p\\\"w\"}"));
            LoginFlow.Template tj = LoginFlow.fromHistory(j, Set.of(api.url()), "bob", "p\"w");
            Expect.notNull(tj, "a JSON login");
            Expect.isTrue(tj.json, "known to be JSON");
            Expect.equal(tj.request.bodyText(), "{\"username\":\"" + LoginFlow.USER + "\",\"password\":\"" + LoginFlow.PASS + "\"}", "marked");
        });

        Harness.test("cookies are taken from a page's answers, and a login form is known", () -> {
            Map<String, String> jar = new LinkedHashMap<>();
            jar.put("pre", "1");
            LoginFlow.learn(new HttpMessage(Bytes.bytes("HTTP/1.1 302 Found\r\nSet-Cookie: session=abc; Path=/; HttpOnly\r\n"
                    + "Set-Cookie: pre=; Max-Age=0\r\nSet-Cookie: lang=en\r\n\r\n")), jar);
            Expect.equal(ScanAuth.cookieHeader(jar), "session=abc; lang=en", "set, and the cleared one dropped");
            Expect.isTrue(LoginFlow.asksForPassword("<form><input name=u><INPUT TYPE='password' name=p></form>"), "a login form");
            Expect.isFalse(LoginFlow.asksForPassword("<p>Your password was changed</p><input type=text name=q>"), "a page that only mentions one");
        });

        Harness.test("the session is valid while the response contains the marked text", () -> {
            ScanAuth.Check c = new ScanAuth.Check(app, new HttpMessage(Bytes.bytes("GET /account HTTP/1.1\r\nHost: app.test\r\n\r\n")));
            c.text = "Alice Marlow";
            Expect.equal(ScanAuth.judge(c, 200, "HTTP/1.1 200 OK\n\nHello Alice Marlow").state(), ScanAuth.State.IN, "the text is there");
            Expect.equal(ScanAuth.judge(c, 200, "HTTP/1.1 200 OK\n\nPlease log in").state(), ScanAuth.State.OUT, "the text is gone");
            // Status code and size decide nothing: applications differ in both.
            Expect.equal(ScanAuth.judge(c, 302, "HTTP/1.1 302 Found\nLocation: /login\n\n").state(), ScanAuth.State.OUT, "a redirect without the text");
            Expect.equal(ScanAuth.judge(c, 401, "HTTP/1.1 401 Unauthorized\n\n{}").state(), ScanAuth.State.OUT, "a refusal without the text");
            Expect.equal(ScanAuth.judge(c, 403, "HTTP/1.1 403 Forbidden\n\nHello Alice Marlow").state(), ScanAuth.State.IN, "any status with the text");
            // A failing target says nothing about the session.
            Expect.equal(ScanAuth.judge(c, 500, "HTTP/1.1 500\n\noops").state(), ScanAuth.State.UNKNOWN, "an error of the target's own");
            Expect.equal(ScanAuth.judge(c, 503, "HTTP/1.1 503\n\n").state(), ScanAuth.State.UNKNOWN, "unavailable");
            Expect.equal(ScanAuth.judge(c, 429, "HTTP/1.1 429\n\n").state(), ScanAuth.State.UNKNOWN, "too many requests");
            Expect.equal(ScanAuth.judge(c, 408, "HTTP/1.1 408\n\n").state(), ScanAuth.State.UNKNOWN, "a time-out");
            Expect.isTrue(ScanAuth.judge(c, 200, "HTTP/1.1 200 OK\n\nnothing").detail().contains("without \"Alice Marlow\""), "the log says what was missing");
            // A check with no text is never used to decide.
            ScanAuth.Check bare = new ScanAuth.Check(app, c.request);
            Expect.equal(ScanAuth.judge(bare, 200, "anything").state(), ScanAuth.State.UNKNOWN, "no text set");
            Expect.equal(ScanAuth.judge(bare, 401, "").state(), ScanAuth.State.UNKNOWN, "nothing is assumed from a status");
            // Text in a header counts: the whole response as shown is searched.
            ScanAuth.Check head = new ScanAuth.Check(app, c.request);
            head.text = "X-User: alice";
            Expect.equal(ScanAuth.judge(head, 204, "HTTP/1.1 204 No Content\nX-User: alice\n\n").state(), ScanAuth.State.IN, "marked in the head");
        });

        Harness.test("a response is shown and searched in one form", () -> {
            HttpMessage r = new HttpMessage(Bytes.bytes("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"user\":{\"email\":\"[email protected]\"}}"));
            String shown = ScanAuth.shown(r);
            Expect.equal(shown, "HTTP/1.1 200 OK\nContent-Type: application/json\n\n{\"user\":{\"email\":\"[email protected]\"}}", "head and body, plain line ends");
            Expect.equal(ScanAuth.quoted("a\nb"), "\"a b\"", "one line in a message");
            Expect.isTrue(ScanAuth.quoted("x".repeat(100)).length() < 70, "cut short when long");
        });

        Harness.test("a check is proven on the application before it is used", () -> {
            try (App site = new App()) {
                List<ScanAuth.Header> session = List.of(new ScanAuth.Header(site.service.url(), "Cookie", "sid=good"));
                // The same status and nearly the same size either way: only the text tells.
                ScanAuth.Check who = site.check("/whoami");
                who.text = "[email protected]";
                ScanAuth.Proof p = ScanAuth.measure(who, session, List.of());
                Expect.isTrue(p.ok() && who.usable, "there with the session, gone without: " + p.said());
                Expect.isTrue(who.measured.startsWith("Verified"), who.measured);
                Expect.equal(site.hits("/whoami"), ScanAuth.TIMES + 1, "three times with the session and once without");
                Expect.equal(who.needs.size(), 1, "it depends on the one session header");
                Expect.equal(ScanAuth.run(who, session).state(), ScanAuth.State.IN, "and reports logged in");
                Expect.equal(ScanAuth.run(who, List.of(new ScanAuth.Header(site.service.url(), "Cookie", "sid=expired"))).state(),
                        ScanAuth.State.OUT, "an ended session is reported");

                // Text that is on the page logged in or not can never report a loss.
                ScanAuth.Check pub = site.check("/public");
                pub.text = "Welcome to the shop";
                ScanAuth.Proof both = ScanAuth.measure(pub, session, List.of());
                Expect.isTrue(!both.ok() && both.misleading() && !pub.usable, "refused: " + both.said());
                Expect.isTrue(both.said().contains("also in the response without the session"), both.said());

                // Text that changes on every request would report losses that are not.
                ScanAuth.Check clock = site.check("/clock");
                clock.text = "request 1";
                ScanAuth.Proof moving = ScanAuth.measure(clock, session, List.of());
                Expect.isTrue(!moving.ok() && !moving.misleading(), "refused: " + moving.said());
                Expect.isTrue(moving.said().contains("request 2 of 3"), moving.said());

                // Text that is not in the response at all.
                ScanAuth.Check wrong = site.check("/whoami");
                wrong.text = "[email protected]";
                Expect.isFalse(ScanAuth.measure(wrong, session, List.of()).ok(), "not there with the session");

                // No text, no check.
                Expect.isFalse(ScanAuth.measure(site.check("/whoami"), session, List.of()).ok(), "nothing marked");

                // Which header it depends on is found by leaving each out.
                List<ScanAuth.Header> two = List.of(new ScanAuth.Header(site.service.url(), "Cookie", "sid=good"),
                        new ScanAuth.Header(site.service.url(), "X-Trace", "abc"));
                ScanAuth.Check again = site.check("/whoami");
                again.text = "[email protected]";
                ScanAuth.measure(again, two, List.of());
                Expect.equal(again.needs, Set.of(two.get(0).key()), "the cookie, not the header that changes nothing");

                // A target that fails is not a lost session.
                ScanAuth.Check down = site.check("/broken");
                down.text = "[email protected]";
                Expect.equal(ScanAuth.run(down, session).state(), ScanAuth.State.UNKNOWN, "an error page proves nothing");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        Harness.test("checks left unwatched are told", () -> {
            ScanAuth.Header cookie = new ScanAuth.Header(app.url(), "Cookie", "s=1");
            ScanAuth.Header token = new ScanAuth.Header("https://api.test", "Authorization", "Bearer x");
            ScanAuth.Check c = new ScanAuth.Check(app, new HttpMessage(Bytes.bytes("GET /account HTTP/1.1\r\nHost: app.test\r\n\r\n")));
            c.usable = true;
            c.needs.add(cookie.key());
            List<ScanAuth.Header> bare = ScanAuth.unwatched(List.of(c), List.of(cookie, token));
            Expect.equal(bare.size(), 1, "one header has no check");
            Expect.equal(bare.get(0).site(), "https://api.test", "the token on the other host");
            c.usable = false;
            Expect.equal(ScanAuth.unwatched(List.of(c), List.of(cookie, token)).size(), 2, "a check that is not usable watches nothing");
        });

        Harness.test("a header the user marks is taken for a session header", () -> {
            Expect.isFalse(ScanAuth.isAuthHeader("X-Acme-Sid"), "a name of the application's own is not known");
            ScanAuth.MARKED.add("x-acme-sid");
            try {
                Expect.isTrue(ScanAuth.isAuthHeader("X-Acme-Sid"), "once marked it is");
                List<LogEntry> h = new ArrayList<>();
                h.add(entry("proxy", app, "GET /a HTTP/1.1\r\nHost: app.test\r\nX-Acme-Sid: 77\r\n\r\n"));
                List<ScanAuth.Header> got = ScanAuth.capture(h, Set.of(app.url()), 0);
                Expect.equal(got.size(), 1, "and it is read from the browser's requests");
                Expect.equal(got.get(0).value(), "77", "with its value");
            } finally {
                ScanAuth.MARKED.remove("x-acme-sid");
            }
        });

        Harness.test("an unticked cookie stays out when the browser sends it again", () -> {
            List<ScanAuth.Header> current = List.of(new ScanAuth.Header(app.url(), "Cookie", "session=old"));
            List<ScanAuth.Header> newer = List.of(new ScanAuth.Header(app.url(), "Cookie", "session=new; tracker=xyz; theme=dark"));
            List<ScanAuth.Header> m = ScanAuth.merged(current, newer, Set.of(app.url() + "\ntracker"));
            Expect.equal(m.get(0).value(), "session=new; theme=dark", "the dropped one is left out, the rest brought up to date");
        });

        Harness.test("addresses to leave alone become patterns", () -> {
            List<String> sites = List.of("https://app.test");
            String path = SessionGuard.avoidPatterns("/account/delete", sites).get(0);
            Expect.isTrue("https://app.test/account/delete".matches(path), "the path");
            Expect.isTrue("https://app.test/account/delete?id=4".matches(path), "with a query");
            Expect.isFalse("https://app.test/account/deleted-items".matches(path), "not a longer path");
            String star = SessionGuard.avoidPatterns("/admin/*", sites).get(0);
            Expect.isTrue("https://app.test/admin/users/3".matches(star), "* is anything");
            Expect.isFalse("https://app.test/account".matches(star), "and nothing else");
            String whole = SessionGuard.avoidPatterns("https://other.test/pay", sites).get(0);
            Expect.isTrue("https://other.test/pay".matches(whole), "a whole address stands for itself");
            String word = SessionGuard.avoidPatterns("password", sites).get(0);
            Expect.isTrue("https://app.test/user/password/change".matches(word.replace("(\\?.*)?", ".*")), "a bare word is looked for after the site");
            Expect.isTrue(SessionGuard.avoidPatterns("  ", sites).isEmpty(), "nothing typed, nothing avoided");
            Expect.isTrue("https://app.test/user/Sign-Out?x=1".matches(SessionGuard.logoutGuess("https://app.test")), "log out links by name");
            Expect.isFalse("https://app.test/blog/about".matches(SessionGuard.logoutGuess("https://app.test")), "not other links");
        });

        Harness.test("a page left alone is left alone over http and https alike", () -> {
            List<String> sites = List.of("http://app.test");
            String picked = SessionGuard.avoidPatterns("http://app.test/logout", sites).get(0);
            Expect.isTrue("http://app.test/logout".matches(picked), "as it was picked");
            Expect.isTrue("https://app.test/logout".matches(picked), "and over https");
            Expect.isTrue("https://app.test:443/logout?next=1".matches(picked), "with the usual port written out, and a query");
            Expect.isFalse("https://app.test/logout-help".matches(picked), "not a longer page");
            Expect.isFalse("https://other.test/logout".matches(picked), "not another host");
            String ported = SessionGuard.avoidPatterns("http://127.0.0.1:8392/logout", sites).get(0);
            Expect.isTrue("https://127.0.0.1:8392/logout".matches(ported), "the same port over https");
            Expect.isTrue("https://127.0.0.1:8443/logout".matches(ported), "https on a port of its own");
            Expect.isTrue("https://127.0.0.1/logout".matches(ported), "and on the usual port");
            Expect.isTrue("http://127.0.0.1:8392/Logout?x=1".matches(ported), "in capitals too");
            Expect.isFalse("http://127.0.0.2:8392/logout".matches(ported), "not another host");
            Expect.isFalse("http://127.0.0.1:8392/logout/all".matches(ported), "not a page beneath it");
            Expect.isTrue("http://127.0.0.1:8392/logout/all".matches(SessionGuard.avoidPatterns("http://127.0.0.1:8392/logout*", sites).get(0)), "unless * says so");
            String path = SessionGuard.avoidPatterns("/signout", sites).get(0);
            Expect.isTrue("https://app.test/signout".matches(path), "a typed path too");
            Expect.isTrue("https://app.test/user/Log-Out".matches(SessionGuard.logoutGuess("http://app.test")), "and log out links by name");
            Expect.equal(SessionGuard.avoidPatterns("/signout", List.of("http://app.test", "https://app.test")).size(), 1, "both schemes of a site make one pattern");
            Expect.isTrue("https://shop.app.test/pay".matches(SessionGuard.avoidPatterns("http://*.app.test/pay", sites).get(0)), "* in a host");
        });

        Harness.test("an address that repeats itself is a crawl loop, and others are not", () -> {
            String loop = SessionGuard.LOOP;
            Expect.isTrue("http://127.0.0.1:3000/x/assets/public/assets/public/assets/public/favicon_js.ico".matches(loop), "two folders, three times");
            Expect.isTrue("http://127.0.0.1:3000/home/linux/router/assets/public/assets/public/assets/public".matches(loop), "ending on the run");
            Expect.isTrue("https://app.test/a/a/a?x=1".matches(loop), "one folder, three times, with a query");
            Expect.isTrue("https://app.test/a/b/c/a/b/c/a/b/c/page".matches(loop), "three folders, three times");
            Expect.isTrue("http://127.0.0.1:3000/assets/public/images/products/assets/public/assets/assets/public/x.js".matches(loop), "the same folder again and again, not in a row");
            Expect.isTrue("https://app.test/a/x/a/y/a".matches(loop), "ending on the third");
            Expect.isFalse("https://app.test/a/x/a/y/ab".matches(loop), "a longer name is another name");
            Expect.isFalse("https://app.test/a/b/c/a/d".matches(loop), "twice is not a loop, apart");
            Expect.isFalse("https://app.test/assets/public/assets/public/logo.png".matches(loop), "twice is not a loop");
            Expect.isFalse("https://app.test/shop/items/shop-items/items".matches(loop), "like names are not a repeat");
            Expect.isFalse("https://app.test/grid/1/1/1".matches(loop), "a run of numbers is not taken for one");
            Expect.isFalse("https://app.test/account/orders?next=/a/a/a".matches(loop), "a query is not a path");
            Expect.isFalse("http://127.0.0.1:3000/rest/products/search?q=".matches(loop), "an ordinary address");
        });

        Harness.test("a place in a source file is not a page", () -> {
            String at = SessionGuard.SOURCE_POSITION;
            Expect.isTrue("http://127.0.0.1:3000/home/app/build/routes/fileServer.js:68:18".matches(at), "file, line and column");
            Expect.isTrue("http://127.0.0.1:3000/home/app/build/routes/fileServer.js:68:18)".matches(at), "with the bracket an error report closes with");
            Expect.isTrue("https://app.test/srv/app/views.py:120".matches(at), "file and line");
            Expect.isFalse("http://127.0.0.1:3000/assets/public/main.js".matches(at), "a script is a page");
            Expect.isFalse("http://127.0.0.1:3000/rest/products/1".matches(at), "a port is not a line number");
            Expect.isFalse("https://app.test/time/12:30".matches(at), "a time is not one either");
            Expect.isFalse("https://app.test/search?q=main.js:68:18".matches(at), "nor is anything in a query");
            Expect.isFalse("http://shop.test:8080".matches(at), "a site named with its port is the site, not a line of a file");
            Expect.isFalse("https://app.example.com:8443".matches(at), "the same over https");
            Expect.isFalse("http://shop.test:8080/".matches(at), "nor its front page");
            Expect.isTrue("http://shop.test:8080/app/file.js:68:18".matches(at), "a place in a file is still caught on such a site");
        });

        Harness.test("this machine's names are one host for a page left alone", () -> {
            String p = SessionGuard.avoidPatterns("http://127.0.0.1:3000/logout", List.of("http://127.0.0.1:3000")).get(0);
            Expect.isTrue("http://localhost:3000/logout".matches(p), "localhost");
            Expect.isTrue("https://127.0.0.1:3000/logout".matches(p), "the address itself, over https");
            Expect.isFalse("http://127.0.0.2:3000/logout".matches(p), "not another machine");
            String q = SessionGuard.avoidPatterns("http://localhost/logout", List.of("http://localhost")).get(0);
            Expect.isTrue("http://127.0.0.1:8080/logout".matches(q), "and the other way round");
        });

        Harness.test("a browser login is judged by what the browser then sent", () -> {
            EngineLogin.Seen page = EngineLogin.seen(new ZapApi.Recorded("11", "GET https://app.test/login HTTP/1.1\r\nHost: app.test\r\n\r\n", "",
                    "HTTP/1.1 200 OK\r\n\r\n", "<form><input type=password name=p></form>"));
            Expect.equal(page.service().url(), "https://app.test", "the service");
            Expect.equal(page.request().requestTarget(), "/login", "the request line is put back to a path");
            Expect.equal(page.status(), 200, "status");
            Expect.isFalse(EngineLogin.judge(List.of(page), "alice").ok(), "nothing was submitted");
            Expect.isTrue(EngineLogin.judge(List.of(page), "alice").detail().contains("no username and password fields"), "and it says why");

            EngineLogin.Seen post = EngineLogin.seen(new ZapApi.Recorded("11", "POST https://app.test/login HTTP/1.1\r\nHost: app.test\r\n\r\n", "u=alice&p=bad",
                    "HTTP/1.1 200 OK\r\n\r\n", "<form><input type=password name=p></form>"));
            EngineLogin.Result refused = EngineLogin.judge(List.of(page, post), "alice");
            Expect.isFalse(refused.ok(), "the form came back and no session was sent");
            Expect.isTrue(refused.detail().contains("not accepted"), refused.detail());
            Expect.isNull(EngineLogin.seen(new ZapApi.Recorded("11", "nonsense", "", "", "")), "an unreadable exchange is skipped");
        });

        Harness.test("links are kept to the site", () -> {
            Expect.equal(LoginFlow.resolve(app, "/a/b", "c?x=1"), "/a/c?x=1", "relative");
            Expect.equal(LoginFlow.resolve(app, "/a/b", "https://app.test/z"), "/z", "absolute to the same site");
            Expect.isNull(LoginFlow.resolve(app, "/a/b", "https://other.test/z"), "another site");
            Expect.isNull(LoginFlow.resolve(app, "/a/b", "http://app.test/z"), "another scheme is another service");
        });

        Harness.test("an unpacked engine is replaced when its add-ons differ", () -> {
            Expect.equal(ZapEngine.marker("2.17.0", "abc123"), "2.17.0 abc123", "version and contents");
            Expect.isFalse("2.17.0".equals(ZapEngine.marker("2.17.0", "abc123")), "an older unpacking marked by version alone no longer matches");
            Expect.equal(ZapEngine.marker("2.17.0", null), "2.17.0", "a build without a fingerprint");
            Expect.isNull(ZapEngine.marker(null, "abc"), "no bundled engine");
            try {
                java.nio.file.Path d = java.nio.file.Files.createTempDirectory("engine-test");
                java.nio.file.Files.createDirectories(d.resolve("plugin"));
                java.nio.file.Files.createDirectories(d.resolve("db"));
                java.nio.file.Files.writeString(d.resolve("zap-2.16.0.jar"), "old");
                java.nio.file.Files.writeString(d.resolve("plugin/spider-release-0.1.zap"), "old");
                java.nio.file.Files.writeString(d.resolve("db/keep.txt"), "kept");
                java.nio.file.Files.writeString(d.resolve("README"), "kept");
                ZapEngine.clearOld(d);
                Expect.isFalse(java.nio.file.Files.exists(d.resolve("zap-2.16.0.jar")), "the old engine jar goes");
                Expect.isFalse(java.nio.file.Files.exists(d.resolve("plugin/spider-release-0.1.zap")), "old add-ons go");
                Expect.isTrue(java.nio.file.Files.exists(d.resolve("db/keep.txt")), "other folders stay");
                Expect.isTrue(java.nio.file.Files.exists(d.resolve("README")), "other files stay");
            } catch (java.io.IOException e) {
                throw new RuntimeException(e);
            }
        });

        Harness.test("patterns handed to the engine match what they should", () -> {
            String site = SessionGuard.regex("https://app.test:8443");
            Expect.isTrue("https://app.test:8443/a?b=1".matches(site + "(/.*)?"), "a page of the site");
            Expect.isTrue("https://app.test:8443".matches(site + "(/.*)?"), "the bare site");
            Expect.isFalse("https://appxtest:8443/a".matches(site + "(/.*)?"), "the dot is a dot");
            Expect.isFalse("https://app.test:84430/a".matches(site + "(/.*)?"), "another port");
            String out = "(?i)" + site + "/[^?#]*(log[-_]?out|sign[-_]?out|log[-_]?off|sign[-_]?off)[^?#]*(\\?.*)?";
            Expect.isTrue("https://app.test:8443/account/Logout".matches(out), "logout");
            Expect.isTrue("https://app.test:8443/sign_out?next=/".matches(out), "sign_out with a query");
            Expect.isFalse("https://app.test:8443/page?next=/logout".matches(out), "only in the path");
            Expect.isFalse("https://app.test:8443/blog/outline".matches(out), "not a log out");
        });

        Harness.test("hidden fields the engine would not take for a token are offered, the usual ones are not", () -> {
            HttpService svc = HttpService.parse("http://app.test");
            LogEntry e = entry("proxy", svc, "GET /form HTTP/1.1\r\nHost: app.test\r\n\r\n");
            String html = "<form><input type=\"hidden\" name=\"xsrf_nonce\" value=\"a1\"><input type='hidden' name='csrf_token' value='b2'>"
                    + "<INPUT name=view_state TYPE=hidden value=c3><input type=\"text\" name=\"comment\"></form>";
            e.setResponse(new HttpMessage(Bytes.bytes("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: " + html.length() + "\r\n\r\n" + html)));
            List<String> found = ScanAuth.hiddenFields(List.of(e), Set.of("http://app.test"), 10);
            Expect.isTrue(found.contains("xsrf_nonce"), "an unusual name is offered");
            Expect.isTrue(found.contains("view_state"), "a name written without quotes is read");
            Expect.isTrue(!found.contains("csrf_token"), "a usual name is not offered");
            Expect.isTrue(!found.contains("comment"), "a field that is not hidden is not offered");
            Expect.equal(ScanAuth.hiddenFields(List.of(e), Set.of("http://other.test"), 10).size(), 0, "another site's forms are not read");
        });
    }

    /** A small application of its own design: one status and one size for nearly everything, so only text tells logged in from out. */
    private static final class App implements AutoCloseable {
        final com.sun.net.httpserver.HttpServer server;
        final HttpService service;
        final java.util.Map<String, Integer> hits = new java.util.concurrent.ConcurrentHashMap<>();

        App() throws Exception {
            server = com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("127.0.0.1", 0), 0);
            server.createContext("/", x -> {
                String path = x.getRequestURI().getPath();
                int n = hits.merge(path, 1, Integer::sum);
                String cookie = x.getRequestHeaders().getFirst("Cookie");
                boolean in = cookie != null && cookie.contains("sid=good");
                int code = 200;
                String body;
                switch (path) {
                    case "/whoami" -> body = in ? "{\"user\":{\"email\":\"[email protected]\"}}" : "{\"user\":{\"email\":\"[email protected]\"}}";
                    case "/public" -> body = "<html><h1>Welcome to the shop</h1></html>";
                    case "/clock" -> body = "<html>" + (in ? "Signed in. " : "") + "This is request " + n + "</html>";
                    case "/broken" -> { code = 500; body = "error"; }
                    default -> { code = 404; body = "none"; }
                }
                byte[] out = body.getBytes(java.nio.charset.StandardCharsets.UTF_8);
                x.sendResponseHeaders(code, out.length);
                x.getResponseBody().write(out);
                x.close();
            });
            server.start();
            service = HttpService.parse("http://127.0.0.1:" + server.getAddress().getPort());
        }

        ScanAuth.Check check(String path) {
            return new ScanAuth.Check(service, new HttpMessage(Bytes.bytes("GET " + path + " HTTP/1.1\r\nHost: 127.0.0.1:" + server.getAddress().getPort() + "\r\n\r\n")));
        }

        int hits(String path) { return hits.getOrDefault(path, 0); }

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