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.

23.0 KB
Raw Blame
package opensuite.organizer;

import opensuite.core.*;
import opensuite.ui.*;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * The Organizer: a shelf for requests worth coming back to. Send items here with
 * "send to organizer", give each a status and notes, and revisit them as a
 * curated set that is saved with the project.
 *
 * <p>Items are filed into collections. Everything lands in the Inbox; further
 * collections are created from the left pane and items are moved between them
 * from the table's context menu.
 */
public class OrganizerTool implements ToolModule {

    private static final String INBOX = "Inbox";

    private SuiteContext ctx;
    private OrganizerStore store;
    private final Model model = new Model();
    private JTable table;
    private MessageEditor reqView, respView;
    private opensuite.ui.MessagePair pair;
    private JTextArea notes;
    private final CardLayout tableCards = new CardLayout();
    private final CardLayout contentsCards = new CardLayout();
    private JPanel contentsArea;
    private JPanel tableArea;

    // The collections pane.
    private final DefaultListModel<String> collectionModel = new DefaultListModel<>();
    private final JList<String> collectionList = new JList<>(collectionModel);
    private final List<String> collections = new ArrayList<>(List.of(INBOX));
    private JTextField collectionSearch;
    private JLabel titleLabel;
    private JButton filterButton;
    private String search = "";
    /** The contents filter: the usual one for a table of requests, with the Organizer's own two groups. */
    private final opensuite.proxy.HistoryFilter filter = new opensuite.proxy.HistoryFilter();
    private final java.util.Map<String, java.util.Map<String, Boolean>> filterGroups = new java.util.LinkedHashMap<>();
    private static final String BY_TOOL = "Filter by tool", BY_STATUS = "Filter by status";
    {
        java.util.Map<String, Boolean> tools = new java.util.LinkedHashMap<>();
        for (String t : new String[]{"Target", "Proxy", "Scanner", "Intruder", "Repeater", "Sequencer", "Logger", "Extensions"}) tools.put(t, true);
        java.util.Map<String, Boolean> statuses = new java.util.LinkedHashMap<>();
        for (String s : new String[]{"New", "Ignored", "In progress", "Done", "Postponed"}) statuses.put(s, true);
        filterGroups.put(BY_TOOL, tools);
        filterGroups.put(BY_STATUS, statuses);
    }

    /** Whether an item passes the filter settings. */
    private boolean passes(OrganizerItem it) {
        for (var t : filterGroups.get(BY_TOOL).entrySet())
            if (!t.getValue() && t.getKey().equalsIgnoreCase(it.sourceTool)) return false;
        Boolean status = filterGroups.get(BY_STATUS).get(it.statusLabel());
        if (status != null && !status) return false;
        if (it.service == null || it.request == null) return true;
        opensuite.core.LogEntry e = new opensuite.core.LogEntry(it.sourceTool, it.service, it.request);
        if (it.response != null) e.setResponse(it.response);
        e.setNotes(it.notes);
        filter.scope = ctx == null ? null : ctx.scope();
        return filter.test(e);
    }

    /** What the filter bar says: what the settings hide, then what the search box narrows to. */
    private String filterText() {
        List<String> parts = new ArrayList<>();
        String usual = filter.summary();
        if (!usual.equals("Showing all items")) parts.add(usual);
        for (var g : filterGroups.entrySet()) {
            List<String> off = new ArrayList<>();
            for (var b : g.getValue().entrySet()) if (!b.getValue()) off.add(b.getKey());
            if (!off.isEmpty()) parts.add((parts.isEmpty() ? "Hiding " : "hiding ") + String.join(", ", off)
                    + (g.getKey().equals(BY_TOOL) ? " items" : " status"));
        }
        if (!search.isEmpty()) parts.add((parts.isEmpty() ? "Showing" : "showing") + " items matching \"" + search + "\"");
        return "Filter settings: " + (parts.isEmpty() ? "Showing all items" : String.join("; ", parts));
    }

    /** The open tool's name as the Tool column shows it: "Proxy", "Repeater". Empty when it cannot be told. */
    private static String sentFrom() {
        for (Frame f : Frame.getFrames()) {
            if (f instanceof opensuite.ui.SuiteFrame sf && f.isVisible()) {
                String t = sf.selectedTool();
                if (t.equals("dashboard")) return "Scanner";
                return t.isEmpty() ? "" : Character.toUpperCase(t.charAt(0)) + t.substring(1);
            }
        }
        return "";
    }

    @Override public String name() { return "organizer"; }

    @Override public void init(SuiteContext ctx) {
        this.ctx = ctx;
        this.store = ctx.organizer();
        ctx.registerSink("organizer", (svc, req, resp, cap) -> {
          // The tool an item came from is the one that was open when it was sent.
          final String from = sentFrom();
          SwingUtilities.invokeLater(() -> {
            OrganizerItem it = new OrganizerItem(svc, req == null ? null : req.copy(),
                    resp == null ? null : resp.copy(), cap, from);
            it.collection = INBOX;
            store.add(it);
          });
        });
        store.addListener(() -> SwingUtilities.invokeLater(() -> {
            syncCollections();
            model.refresh();
            updateEmpty();
        }));
    }

    @Override public Tab[] tabs() {
        table = new JTable(model);
        Ui.styleTable(table);
        // #, time, status, tool, method, host, path, query, param count, status code, length, notes
        Ui.distributeWidths(table, 40, 90, 90, 70, 60, 150, 200, 140, 50, 60, 60, 160);
        Ui.newestFirst(table, 0);
        JComboBox<String> statusEditor = new JComboBox<>(OrganizerItem.STATUSES);
        statusEditor.setFont(Ui.PLAIN);
        table.getColumnModel().getColumn(2).setCellEditor(new DefaultCellEditor(statusEditor));
        table.getSelectionModel().addListSelectionListener(e -> showSelected());
        installRowMenu();

        reqView = new MessageEditor(ctx, MessageEditor.REQUEST, false);
        respView = new MessageEditor(ctx, MessageEditor.RESPONSE, false);
        notes = new JTextArea(3, 40);
        notes.setFont(Ui.PLAIN);
        notes.setLineWrap(true);
        notes.setWrapStyleWord(true);
        notes.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            public void insertUpdate(javax.swing.event.DocumentEvent e)  { saveNotes(); }
            public void removeUpdate(javax.swing.event.DocumentEvent e)  { saveNotes(); }
            public void changedUpdate(javax.swing.event.DocumentEvent e) { saveNotes(); }
        });

        // The table, or a centred empty-state hint when nothing is saved yet.
        tableArea = new JPanel(tableCards);
        tableArea.add(Ui.scroll(table), "table");
        tableArea.add(emptyState(), "empty");

        JPanel notesPanel = new JPanel(new BorderLayout());
        notesPanel.add(Ui.bold(" Notes"), BorderLayout.NORTH);
        notesPanel.add(Ui.scroll(notes), BorderLayout.CENTER);

        opensuite.ui.MessagePair viewers = new opensuite.ui.MessagePair(reqView, respView);
        this.pair = viewers;

        JSplitPane lower = new JSplitPane(JSplitPane.VERTICAL_SPLIT, viewers, notesPanel);
        lower.setDividerSize(1);
        Ui.balance(lower, 0.75);

        JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tableArea, lower);
        split.setDividerSize(1);
        Ui.balance(split, 0.4);

        // The chosen collection's contents, under its own heading and a
        // "Contents" sub-tab, as the reference arranges it.
        JPanel contents = new JPanel(new BorderLayout());
        contents.add(buildFilterBar(), BorderLayout.NORTH);
        contents.add(split, BorderLayout.CENTER);

        // An empty collection shows only a full-pane hint, with no filter bar or
        // message editors, exactly as the reference does; they return with the
        // first saved item.
        contentsArea = new JPanel(contentsCards);
        contentsArea.add(contents, "full");
        contentsArea.add(emptyState(), "collection-empty");

        JTabbedPane sub = new JTabbedPane();
        sub.setFont(Ui.PLAIN);
        sub.addTab("Contents", contentsArea);

        JPanel filled = new JPanel(new BorderLayout());
        filled.add(buildCollectionHeader(), BorderLayout.NORTH);
        filled.add(sub, BorderLayout.CENTER);

        // An empty collection is the hint alone on white, with no heading or tab above it.
        rightArea = new JPanel(rightCards);
        rightArea.add(filled, "filled");
        rightArea.add(emptyState(), "empty");

        JSplitPane outer = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, buildCollections(), rightArea);
        outer.setDividerSize(1);
        outer.setBorder(null);
        outer.setDividerLocation(319 + 32 * Ui.fontGrowth());   // 383 at 13px, as measured

        syncCollections();
        updateEmpty();
        return new Tab[]{ new Tab("organizer", outer) };
    }

    // ---- the collections pane ----------------------------------------------

    private static final int ART_GAP = 40, HINT_DROP = 0, HINT_LIFT = 2;

    private final CardLayout rightCards = new CardLayout();
    private JPanel rightArea;

    private JComponent buildCollections() {
        JButton add = Ui.button("New", "create a collection");
        // At the usual 13px the cross is smaller, further from the word, and the button 2px wider.
        boolean big = Ui.fontGrowth() > 0;
        add.setIcon(Glyphs.trimmed(Glyphs.plus(big ? 12 : 15, Theme.TEXT)));
        add.setIconTextGap(big ? 14 : 11);
        add.setBorder(Ui.pad(0, 0, 0, big ? 8 : 0));
        Ui.sized(add, big ? 83 : 81);
        add.addActionListener(e -> {
            String name = JOptionPane.showInputDialog(collectionList, "Collection name:", "New collection",
                    JOptionPane.PLAIN_MESSAGE);
            if (name == null || name.isBlank()) return;
            if (!collections.contains(name.strip())) collections.add(name.strip());
            syncCollections();
            collectionList.setSelectedValue(name.strip(), true);
        });

        collectionSearch = Ui.searchField(12);
        collectionSearch.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            void go() { syncCollections(); }
            public void insertUpdate(javax.swing.event.DocumentEvent e)  { go(); }
            public void removeUpdate(javax.swing.event.DocumentEvent e)  { go(); }
            public void changedUpdate(javax.swing.event.DocumentEvent e) { go(); }
        });

        collectionList.setFont(Ui.PLAIN);
        collectionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // The chosen collection sits on the control tint with ordinary text, as
        // every other selected row in the suite does.
        collectionList.setSelectionBackground(Theme.BG);
        collectionList.setSelectionForeground(Theme.TEXT);
        collectionList.setBackground(Theme.BG);
        collectionList.setFixedCellHeight(Ui.tall(26));
        collectionList.setCellRenderer(new DefaultListCellRenderer() {
            private boolean band;
            @Override public Component getListCellRendererComponent(JList<?> l, Object v, int i,
                    boolean sel, boolean focus) {
                super.getListCellRendererComponent(l, v, i, false, false);
                band = sel;
                setOpaque(false);
                setIcon(Glyphs.inbox(16, Theme.TEXT));
                setIconTextGap(10);
                setBorder(Ui.pad(0, 14, 0, 6));
                return this;
            }
            // The chosen row is a rounded band 5px in from each side of the pane.
            @Override protected void paintComponent(Graphics g) {
                if (band) {
                    Graphics2D g2 = (Graphics2D) g.create();
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    g2.setColor(Theme.ACCENT_LIGHT);
                    g2.fillRoundRect(5, 0, getWidth() - 10, getHeight(), 8, 8);
                    g2.dispose();
                }
                super.paintComponent(g);
            }
        });
        collectionList.addListSelectionListener(e -> {
            if (e.getValueIsAdjusting()) return;
            if (titleLabel != null) titleLabel.setText(selectedCollection());
            model.refresh();
            updateEmpty();
        });

        // The heading with New at its right, then the search across the pane.
        JPanel head = new JPanel(new BorderLayout(0, 10));
        head.setOpaque(false);
        head.setBorder(Ui.pad(10, 10, 10, 10));
        JPanel row = new JPanel(new BorderLayout());
        row.setOpaque(false);
        row.add(Ui.heading("Collections"), BorderLayout.WEST);
        Ui.sized(row, 10);
        row.add(add, BorderLayout.EAST);
        collectionSearch.setColumns(0);
        Ui.sized(collectionSearch, 10);
        head.add(row, BorderLayout.NORTH);
        head.add(collectionSearch, BorderLayout.CENTER);

        JPanel p = new JPanel(new BorderLayout());
        p.setBackground(Theme.BG);
        p.add(head, BorderLayout.NORTH);
        JScrollPane listScroll = new JScrollPane(collectionList);
        listScroll.setBorder(null);
        listScroll.getViewport().setBackground(Theme.BG);
        p.add(listScroll, BorderLayout.CENTER);
        p.setMinimumSize(new Dimension(200, 100));
        return p;
    }

    /** The chosen collection's icon and name above its contents. */
    private JComponent buildCollectionHeader() {
        titleLabel = new JLabel(INBOX, Glyphs.inbox(18, Theme.ICON), SwingConstants.LEFT);
        titleLabel.setFont(Ui.HEADING.deriveFont(15f));
        titleLabel.setIconTextGap(8);
        titleLabel.setBorder(Ui.pad(8, 10, 6, 10));
        JPanel p = new JPanel(new BorderLayout());
        p.add(titleLabel, BorderLayout.WEST);
        return p;
    }

    private String selectedCollection() {
        String v = collectionList.getSelectedValue();
        return v == null ? INBOX : v;
    }

    /** Rebuild the collection list from the stored items plus any created by hand. */
    private void syncCollections() {
        if (store != null) for (OrganizerItem it : store.all()) {
            if (!collections.contains(it.collection())) collections.add(it.collection());
        }
        String keep = selectedCollection();
        String q = collectionSearch == null ? "" : collectionSearch.getText().strip().toLowerCase();
        collectionModel.clear();
        for (String c : collections) {
            if (q.isEmpty() || c.toLowerCase().contains(q)) collectionModel.addElement(c);
        }
        if (collectionModel.isEmpty()) collectionModel.addElement(INBOX);
        int at = collectionModel.indexOf(keep);
        collectionList.setSelectedIndex(at >= 0 ? at : 0);
    }

    // ---- the contents filter bar -------------------------------------------

    private JComponent buildFilterBar() {
        filterButton = Ui.filterButton();
        filterButton.setText("Filter settings: Showing all items");
        filterButton.addActionListener(e -> new opensuite.proxy.FilterDialog(
                SwingUtilities.getWindowAncestor(filterButton), "Organizer filter", filter, false, filterGroups,
                () -> { model.refresh(); updateEmpty(); refreshFilterText(); }).setVisible(true));
        JTextField find = Ui.searchField(16);
        find.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            void go() { search = find.getText().strip().toLowerCase(); model.refresh(); updateEmpty(); refreshFilterText(); }
            public void insertUpdate(javax.swing.event.DocumentEvent e)  { go(); }
            public void removeUpdate(javax.swing.event.DocumentEvent e)  { go(); }
            public void changedUpdate(javax.swing.event.DocumentEvent e) { go(); }
        });
        JButton help = Ui.helpButton("Organizer",
                "Items sent to the Organizer are stored with the project. Assign each item a status "
                + "and notes, and move it to a collection.");
        JButton kebab = Glyphs.menuButton("Table layout and custom columns", () -> TableLayoutMenu.build(table));
        return Ui.filterBar(filterButton, find, help, kebab);
    }

    private void refreshFilterText() {
        if (filterButton == null) return;
        filterButton.setText(filterText());
    }

    /** Delete, clear and move-to-collection on a row. */
    private void installRowMenu() {
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override public void mousePressed(java.awt.event.MouseEvent e)  { maybe(e); }
            @Override public void mouseReleased(java.awt.event.MouseEvent e) { maybe(e); }
            private void maybe(java.awt.event.MouseEvent e) {
                if (!e.isPopupTrigger()) return;
                int row = table.rowAtPoint(e.getPoint());
                if (row >= 0) table.setRowSelectionInterval(row, row);
                menu().show(table, e.getX(), e.getY());
            }
        });
    }

    private JPopupMenu menu() {
        JPopupMenu m = new JPopupMenu();
        OrganizerItem it = model.at(table.getSelectedRow());
        JMenu move = new JMenu("Move to collection");
        move.setFont(Ui.PLAIN);
        for (String c : collections) {
            JMenuItem mi = new JMenuItem(c);
            mi.setFont(Ui.PLAIN);
            mi.addActionListener(e -> { if (it != null) { it.collection = c; store.changed(); } });
            move.add(mi);
        }
        move.setEnabled(it != null);
        m.add(move);
        m.addSeparator();
        JMenuItem del = new JMenuItem("Delete item");
        del.setFont(Ui.PLAIN);
        del.setEnabled(it != null);
        del.addActionListener(e -> { if (it != null) store.remove(it); });
        m.add(del);
        JMenuItem clear = new JMenuItem("Clear all items");
        clear.setFont(Ui.PLAIN);
        clear.addActionListener(e -> store.clear());
        m.add(clear);
        return m;
    }

    /** A centred hint shown while the chosen collection has nothing in it. */
    private JComponent emptyState() {
        // The illustration stands in a 96px box, and the whole hint sits a
        // little right of centre, as the reference places it.
        javax.swing.Icon art = opensuite.ui.EmptyState.art();
        javax.swing.Icon boxed = new javax.swing.Icon() {
            @Override public int getIconWidth() { return art.getIconWidth(); }
            @Override public int getIconHeight() { return 96; }
            @Override public void paintIcon(Component c, Graphics g, int x, int y) {
                art.paintIcon(c, g, x, y + (96 - art.getIconHeight()) / 2);
            }
        };
        JPanel hint = opensuite.ui.EmptyState.of(boxed, ART_GAP, "Organizer inbox is empty",
                "To get started, send a message to Organizer from anywhere in Open Suite.", 280, Theme.CONTENT,
                opensuite.ui.EmptyState.learnMore());
        hint.setBorder(Ui.pad(HINT_DROP, Ui.fontGrowth() > 0 ? 13 : 15, HINT_LIFT, 0));
        return hint;
    }

    private void updateEmpty() {
        boolean empty = model.getRowCount() == 0;
        if (tableArea != null) tableCards.show(tableArea, empty ? "empty" : "table");
        if (rightArea != null) rightCards.show(rightArea, empty ? "empty" : "filled");
        if (contentsArea != null) contentsCards.show(contentsArea, empty ? "collection-empty" : "full");
    }

    private void showSelected() {
        OrganizerItem it = model.at(table.getSelectedRow());
        pair.setBlank(it == null);
        if (it == null) { reqView.setMessage(new HttpService("", 0, false), new HttpMessage(new byte[0])); return; }
        reqView.setMessage(it.service, it.request == null ? new HttpMessage(new byte[0]) : it.request);
        respView.setMessage(it.service, it.response == null ? new HttpMessage(new byte[0]) : it.response, it.request);
        notes.setText(it.notes);
    }

    private void saveNotes() {
        OrganizerItem it = model.at(table.getSelectedRow());
        if (it != null) it.notes = notes.getText();
    }

    private final class Model extends AbstractTableModel {
        private final String[] cols = {"#", "Time", "Status", "Tool", "Method", "Host", "Path",
                                       "Query", "Param count", "Status code", "Length", "Notes"};
        private List<OrganizerItem> rows = new ArrayList<>();
        private final DateFormat fmt = new java.text.SimpleDateFormat("HH:mm:ss d MMM yyyy");

        Model() { refresh(); }

        /** The items in the chosen collection that pass the contents search. */
        void refresh() {
            List<OrganizerItem> out = new ArrayList<>();
            if (store != null) {
                String want = collectionList == null ? INBOX : selectedCollection();
                for (OrganizerItem it : store.all()) {
                    if (!it.collection().equals(want)) continue;
                    if (!search.isEmpty() && !matches(it)) continue;
                    if (!passes(it)) continue;
                    out.add(it);
                }
            }
            rows = out;
            fireTableDataChanged();
        }

        private boolean matches(OrganizerItem it) {
            return (it.host() + " " + it.path() + " " + it.query() + " " + it.caption + " " + it.notes)
                    .toLowerCase().contains(search);
        }

        OrganizerItem at(int viewRow) {
            if (viewRow < 0) return null;
            int r = table.convertRowIndexToModel(viewRow);
            return r >= 0 && r < rows.size() ? rows.get(r) : null;
        }

        @Override public int getRowCount() { return rows.size(); }
        @Override public int getColumnCount() { return cols.length; }
        @Override public String getColumnName(int c) { return cols[c]; }
        @Override public Class<?> getColumnClass(int c) { return (c == 0 || c == 8) ? Integer.class : String.class; }
        @Override public boolean isCellEditable(int r, int c) { return c == 2 || c == 11; }
        @Override public void setValueAt(Object v, int r, int c) {
            if (r < 0 || r >= rows.size()) return;
            if (c == 2)  rows.get(r).status = String.valueOf(v);
            if (c == 11) rows.get(r).notes  = String.valueOf(v);
            fireTableRowsUpdated(r, r);
        }
        @Override public Object getValueAt(int r, int c) {
            OrganizerItem it = rows.get(r);
            return switch (c) {
                case 0 -> r + 1;
                case 1 -> fmt.format(new java.util.Date(it.time));
                case 2 -> it.statusLabel();
                case 3 -> it.sourceTool;
                case 4 -> it.request == null ? "" : it.request.method();
                case 5 -> it.host();
                case 6 -> it.path();
                case 7 -> it.query();
                case 8 -> it.request == null ? 0 : it.request.parameters().size();
                case 9 -> it.response == null ? "" : String.valueOf(it.response.statusCode());
                case 10 -> it.response == null ? "" : String.valueOf(it.response.body().length);
                default -> it.notes;
            };
        }
    }
}