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.5 KB
Raw Blame
package opensuite.core;

import opensuite.testkit.Expect;
import opensuite.testkit.Harness;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/** The send options Repeater's settings drive: redirects, cookies, connection reuse, streaming. */
public final class HttpClientOptionsTest {

    /** A small server: each request is answered by {@code reply}, on a connection kept open between requests. */
    private static final class Server implements AutoCloseable {
        final ServerSocket socket;
        final AtomicInteger connections = new AtomicInteger();
        final List<String> requests = new CopyOnWriteArrayList<>();
        interface Reply { void write(String request, OutputStream out) throws Exception; }

        Server(Reply reply) throws Exception {
            socket = new ServerSocket(0, 20, java.net.InetAddress.getLoopbackAddress());
            Thread t = new Thread(() -> {
                while (!socket.isClosed()) {
                    try {
                        Socket c = socket.accept();
                        connections.incrementAndGet();
                        Thread h = new Thread(() -> serve(c, reply));
                        h.setDaemon(true);
                        h.start();
                    } catch (Exception e) { return; }
                }
            });
            t.setDaemon(true);
            t.start();
        }

        private void serve(Socket c, Reply reply) {
            try (c) {
                InputStream in = c.getInputStream();
                while (true) {
                    StringBuilder sb = new StringBuilder();
                    int b;
                    while ((b = in.read()) >= 0) {
                        sb.append((char) b);
                        if (sb.length() >= 4 && sb.substring(sb.length() - 4).equals("\r\n\r\n")) break;
                    }
                    if (b < 0) return;
                    requests.add(sb.toString());
                    reply.write(sb.toString(), c.getOutputStream());
                    c.getOutputStream().flush();
                }
            } catch (Exception ignored) { }
        }

        int port() { return socket.getLocalPort(); }
        HttpService service() { return new HttpService("127.0.0.1", port(), false); }
        @Override public void close() throws Exception { socket.close(); }
    }

    private static void send(OutputStream out, String text) throws Exception {
        out.write(text.getBytes(StandardCharsets.ISO_8859_1));
    }

    private static HttpMessage get(String path) {
        return new HttpMessage(Bytes.bytes("GET " + path + " HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"));
    }

    private static final String OK = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";

    public void run() {
        Harness.suite("http client options");

        Harness.test("line endings are made CRLF in the headers and the body is left alone", () -> {
            byte[] out = HttpClient.normaliseLineEndings(Bytes.bytes("POST / HTTP/1.1\nHost: a\r\nX: y\n\na\nb"));
            Expect.isTrue("POST / HTTP/1.1\r\nHost: a\r\nX: y\r\n\r\na\nb".equals(Bytes.str(out)), "got " + Bytes.str(out).replace("\r", "<CR>").replace("\n", "<LF>"));
        });

        Harness.test("a redirect's cookies are carried forward over the request's own", () -> {
            HttpMessage resp = new HttpMessage(Bytes.bytes("HTTP/1.1 302 Found\r\nSet-Cookie: b=2; Path=/\r\nSet-Cookie: a=9\r\n\r\n"));
            Expect.isTrue("a=9; c=3; b=2".equals(HttpClient.mergeCookies("a=1; c=3", resp)), "got " + HttpClient.mergeCookies("a=1; c=3", resp));
        });

        Harness.test("the redirect filter decides which redirects are followed", () -> {
            try (Server far = new Server((req, out) -> send(out, OK));
                 Server near = new Server((req, out) -> {
                     if (req.startsWith("GET /away")) send(out, "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:" + far.port() + "/\r\nContent-Length: 0\r\n\r\n");
                     else if (req.startsWith("GET /here")) send(out, "HTTP/1.1 302 Found\r\nLocation: /done\r\nSet-Cookie: sid=7\r\nContent-Length: 0\r\n\r\n");
                     else send(out, OK);
                 })) {
                HttpClient.Options opt = new HttpClient.Options();
                opt.followRedirects = true;
                opt.cookiesInRedirects = true;
                opt.redirectFilter = (from, to) -> from.port() == to.port();
                HttpClient.Result away = new HttpClient().send(near.service(), get("/away"), opt);
                Expect.isTrue(away.ok() && away.response.statusCode() == 302 && away.redirectsFollowed == 0, "the off-site redirect is not followed");
                Expect.isTrue(far.requests.isEmpty(), "and the other server hears nothing");
                HttpClient.Result here = new HttpClient().send(near.service(), get("/here"), opt);
                Expect.isTrue(here.ok() && here.response.statusCode() == 200 && here.redirectsFollowed == 1, "the on-site redirect is followed");
                String last = near.requests.get(near.requests.size() - 1);
                Expect.isTrue(last.startsWith("GET /done") && last.contains("Cookie: sid=7"), "with the cookie it set: " + last);
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("connection reuse sends a second request down the first connection", () -> {
            try (Server s = new Server((req, out) -> send(out, OK))) {
                HttpClient.Options opt = new HttpClient.Options();
                new HttpClient().send(s.service(), get("/1"), opt);
                new HttpClient().send(s.service(), get("/2"), opt);
                Expect.isTrue(s.connections.get() == 2, "without reuse each send connects, got " + s.connections.get());
                opt.keepAlive = true;
                HttpClient.Result a = new HttpClient().send(s.service(), get("/3"), opt);
                HttpClient.Result b = new HttpClient().send(s.service(), get("/4"), opt);
                Expect.isTrue(a.ok() && b.ok() && "ok".equals(Bytes.str(b.response.body())), "both answered");
                Expect.isTrue(s.connections.get() == 3, "with reuse the two share one, got " + s.connections.get());
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("a kept connection the server has dropped is replaced, not reported", () -> {
            AtomicInteger served = new AtomicInteger();
            try (Server s = new Server((req, out) -> {
                send(out, OK);
                out.flush();
                if (served.incrementAndGet() == 1) throw new RuntimeException("drop the connection after the first reply");
            })) {
                HttpClient.Options opt = new HttpClient.Options();
                opt.keepAlive = true;
                new HttpClient().send(s.service(), get("/1"), opt);
                Thread.sleep(150);
                HttpClient.Result again = new HttpClient().send(s.service(), get("/2"), opt);
                Expect.isTrue(again.ok(), "the second send succeeds: " + again.error);
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("a streaming response is returned as far as it got when its timeout passes", () -> {
            try (Server s = new Server((req, out) -> {
                send(out, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\ndata: one\n\n");
                out.flush();
                Thread.sleep(5000);
            })) {
                HttpClient.Options opt = new HttpClient.Options();
                opt.readTimeoutMs = 20_000;
                opt.streamTimeoutMs = 600;
                long t0 = System.currentTimeMillis();
                HttpClient.Result r = new HttpClient().send(s.service(), get("/events"), opt);
                long took = System.currentTimeMillis() - t0;
                Expect.isTrue(r.ok() && Bytes.str(r.response.body()).contains("data: one"), "the part that arrived is kept: " + r.error);
                Expect.isTrue(took >= 500 && took < 3000, "and it stopped at the timeout, took " + took + " ms");
            } catch (Exception e) { throw new RuntimeException(e); }
        });

        Harness.test("the time to the first byte is told apart from the time to the whole response", () -> {
            try (Server s = new Server((req, out) -> {
                out.write("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n".getBytes(StandardCharsets.ISO_8859_1));
                out.flush();
                Thread.sleep(400);
                out.write("body".getBytes(StandardCharsets.ISO_8859_1));
                out.flush();
            })) {
                long before = System.currentTimeMillis();
                HttpClient.Result r = new HttpClient().send(s.service(), get("/slow"), new HttpClient.Options());
                Expect.isTrue(r.ok() && "body".equals(Bytes.str(r.response.body())), "the response arrives whole: " + r.error);
                Expect.isTrue(r.sentAt >= before && r.sentAt <= System.currentTimeMillis(), "the sending time is noted");
                Expect.isTrue(r.firstByteMillis >= 0 && r.firstByteMillis < 300, "the first byte came at once, after " + r.firstByteMillis + " ms");
                Expect.isTrue(r.millis >= 350, "and the whole took the server's pause, " + r.millis + " ms");
            } catch (Exception e) { throw new RuntimeException(e); }
        });
    }
}