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.

2.5 KB
Raw Blame
package opensuite.engine;

import opensuite.spider.Cdp.JsonValue;

import java.util.ArrayList;
import java.util.List;

/**
 * The engine's alerts as they are raised, each read once.
 *
 * <p>The engine's own listing starts from the first alert on every call and
 * compares each alert with all those before it. Asked every few seconds on an
 * application of some tens of thousands of pages, one call comes to take
 * minutes, and the scan waiting on the engine stops with it. This reads only
 * what is new: Open Suite's add-on names the alerts raised since the last one
 * read, and each is then fetched by its number.
 *
 * <p>An engine whose add-on is older than that is read the old way, the whole
 * listing each time; the caller already passes over the alerts it has had.
 */
public final class AlertFeed {

    /** The add-on version that can name the alerts raised since a given one. */
    public static final int NEEDS_GATE = 3;
    private static final int WHOLE = 100000;

    private final ZapApi api;
    private final String baseurl;
    private int last = -1;
    private boolean more;

    /** @param baseurl the alerts wanted are those on URLs beginning with this; empty for all */
    public AlertFeed(ZapApi api, String baseurl) {
        this.api = api;
        this.baseurl = baseurl == null ? "" : baseurl;
    }

    /**
     * The next alerts not yet given, oldest first. Where {@link #more()} is
     * then true there are others waiting: call again.
     */
    public synchronized List<JsonValue> next() throws Exception {
        more = false;
        if (api.gateVersion() < NEEDS_GATE) return api.alerts(baseurl, 0, WHOLE);
        ZapApi.NewAlerts found = api.alertIdsAfter(last, baseurl);
        if (found.top() < last) {
            // The engine has fewer alerts than were read: it began again. So does this.
            last = -1;
            found = api.alertIdsAfter(last, baseurl);
        }
        List<JsonValue> out = new ArrayList<>(found.ids().size());
        for (int id : found.ids()) {
            JsonValue a = api.alert(id);
            if (a != null) out.add(a);   // one deleted since it was named is not there to read
        }
        // Moved on only now, so a call that failed part way is made again in full.
        more = found.last() > last && found.last() < found.top();
        last = Math.max(last, found.last());
        return out;
    }

    /** Whether the last call left alerts unread. */
    public synchronized boolean more() { return more; }
}