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.

Message editor: the right-click menu has the reference's items, in its order

scottsturrock64872c5ae595
diff --git a/src/opensuite/core/BodyEncoding.java b/src/opensuite/core/BodyEncoding.java
index 4047378..e28ae92 100644
--- a/src/opensuite/core/BodyEncoding.java
+++ b/src/opensuite/core/BodyEncoding.java
@@ -55,6 +55,91 @@ public final class BodyEncoding {
return true;
}
+ /** What a request body can be converted to. */
+ public enum Kind { FORM, MULTIPART, JSON }
+
+ /** The encoding the body is in now, read from its Content-Type; a form when it says nothing else. */
+ public static Kind kindOf(HttpMessage req) {
+ if (isMultipart(req)) return Kind.MULTIPART;
+ String ct = req == null ? null : req.header("Content-Type");
+ return ct != null && ct.toLowerCase(java.util.Locale.ROOT).contains("json") ? Kind.JSON : Kind.FORM;
+ }
+
+ /**
+ * Convert the body to {@code target} in place, updating Content-Type and
+ * Content-Length. The body is read as names and values in the encoding it
+ * has now and written again in the other. A request with no body, one
+ * already in that encoding, or one whose body cannot be read is left
+ * alone. Returns true when the message changed.
+ */
+ public static boolean convert(HttpMessage req, Kind target, String boundary) {
+ if (req == null || !req.isRequest() || req.body().length == 0 || target == null) return false;
+ Kind from = kindOf(req);
+ if (from == target) return false;
+ List<String[]> fields;
+ switch (from) {
+ case MULTIPART -> fields = parseMultipart(req.bodyText(), boundaryOf(req.header("Content-Type")));
+ case JSON -> fields = parseJson(req.bodyText());
+ default -> {
+ fields = new ArrayList<>();
+ for (String pair : req.bodyText().split("&")) {
+ if (pair.isEmpty()) continue;
+ int eq = pair.indexOf('=');
+ fields.add(new String[]{decode(eq < 0 ? pair : pair.substring(0, eq)), eq < 0 ? "" : decode(pair.substring(eq + 1))});
+ }
+ }
+ }
+ if (fields == null) return false;
+ StringBuilder sb = new StringBuilder();
+ switch (target) {
+ case FORM -> {
+ for (String[] f : fields) {
+ if (sb.length() > 0) sb.append('&');
+ sb.append(encode(f[0])).append('=').append(encode(f[1]));
+ }
+ req.setHeader("Content-Type", FORM);
+ }
+ case MULTIPART -> {
+ for (String[] f : fields) {
+ sb.append("--").append(boundary).append("\r\n")
+ .append("Content-Disposition: form-data; name=\"").append(f[0].replace("\"", "%22")).append("\"\r\n\r\n")
+ .append(f[1]).append("\r\n");
+ }
+ sb.append("--").append(boundary).append("--\r\n");
+ req.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
+ }
+ case JSON -> {
+ sb.append('{');
+ for (int i = 0; i < fields.size(); i++) {
+ if (i > 0) sb.append(',');
+ sb.append('"').append(opensuite.spider.Cdp.jsonEscape(fields.get(i)[0])).append("\":\"")
+ .append(opensuite.spider.Cdp.jsonEscape(fields.get(i)[1])).append('"');
+ }
+ sb.append('}');
+ req.setHeader("Content-Type", "application/json");
+ }
+ }
+ req.setBody(Bytes.bytes(sb.toString()));
+ req.updateContentLength();
+ return true;
+ }
+
+ /** The top-level names and values of a JSON object, or null when the body is not one. */
+ static List<String[]> parseJson(String body) {
+ try {
+ opensuite.spider.Cdp.JsonValue v = opensuite.spider.Cdp.JsonValue.parse(body);
+ if (v == null || !v.isObject()) return null;
+ List<String[]> out = new ArrayList<>();
+ for (String k : v.keys()) {
+ String value = v.get(k).asString();
+ out.add(new String[]{k, value == null ? "" : value});
+ }
+ return out;
+ } catch (RuntimeException e) {
+ return null;
+ }
+ }
+
/** A boundary unlikely to occur in a form value. */
public static String newBoundary() {
return "----OpenSuiteFormBoundary" + Long.toHexString(System.nanoTime());
diff --git a/src/opensuite/repeater/RepeaterTool.java b/src/opensuite/repeater/RepeaterTool.java
index 5e55480..316ef02 100644
--- a/src/opensuite/repeater/RepeaterTool.java
+++ b/src/opensuite/repeater/RepeaterTool.java
@@ -16,6 +16,17 @@ public class RepeaterTool implements ToolModule {
public RepeaterTool() {}
+ /** Each exchange as its request, a blank line, its response, and a line of equals signs between exchanges. */
+ static void writeHistory(java.util.List<byte[][]> exchanges, java.io.OutputStream out) throws java.io.IOException {
+ byte[] gap = "\n\n".getBytes(java.nio.charset.StandardCharsets.US_ASCII);
+ byte[] rule = "======================================================\n".getBytes(java.nio.charset.StandardCharsets.US_ASCII);
+ for (int i = 0; i < exchanges.size(); i++) {
+ if (i > 0) { out.write(gap); out.write(rule); }
+ out.write(exchanges.get(i)[0]);
+ if (exchanges.get(i)[1] != null) { out.write(gap); out.write(exchanges.get(i)[1]); }
+ }
+ }
+
@Override public String name() { return "repeater"; }
@Override public void init(SuiteContext ctx) {
@@ -293,6 +304,30 @@ public class RepeaterTool implements ToolModule {
versionChip.setText(m == HttpMode.HTTP_2 || m == HttpMode.HTTP_2_IGNORE_ALPN ? "HTTP/2" : "HTTP/1");
}
+ /** Take the target of a URL pasted as a request. */
+ private void useTarget(HttpService target) {
+ hostField.setText(target.host());
+ portField.setText(String.valueOf(target.port()));
+ sslBox.setSelected(target.secure());
+ refreshTarget();
+ }
+
+ /** Every request this tab has sent and the response to each, in order, to one file. */
+ private void saveEntireHistory() {
+ if (history.isEmpty()) {
+ JOptionPane.showMessageDialog(this, "This tab has not sent anything yet.", "Save entire history", JOptionPane.INFORMATION_MESSAGE);
+ return;
+ }
+ JFileChooser fc = new opensuite.ui.FileChooser();
+ fc.setDialogTitle("Save entire history");
+ if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
+ try (java.io.OutputStream out = java.nio.file.Files.newOutputStream(fc.getSelectedFile().toPath())) {
+ writeHistory(history.stream().map(h -> new byte[][]{h.request(), h.response() == null ? null : h.response().raw()}).toList(), out);
+ } catch (java.io.IOException ex) {
+ JOptionPane.showMessageDialog(this, "Could not write the file: " + ex.getMessage(), "Save entire history", JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
private void refreshTarget() {
String host = hostField.getText().trim();
String port = portField.getText().trim();
@@ -452,6 +487,12 @@ public class RepeaterTool implements ToolModule {
super(new BorderLayout());
reqEditor = new MessageEditor(ctx, MessageEditor.REQUEST, true);
respEditor = new MessageEditor(ctx, MessageEditor.RESPONSE, false);
+ // The parts of the editor menu that are Repeater's own.
+ for (MessageEditor ed : new MessageEditor[]{reqEditor, respEditor}) {
+ ed.setToolDocs("Repeater");
+ ed.setHistorySaver(this::saveEntireHistory);
+ }
+ reqEditor.setTargetSetter(this::useTarget);
reqEditor.setMessage(svc, req);
// "Default to HTTP/2 if the server supports it": asked off the event thread, and
// only applied while the tab is still on the protocol it opened with.
diff --git a/src/opensuite/ui/MessageEditor.java b/src/opensuite/ui/MessageEditor.java
index 1a86817..b2952f3 100644
--- a/src/opensuite/ui/MessageEditor.java
+++ b/src/opensuite/ui/MessageEditor.java
@@ -329,6 +329,8 @@ public class MessageEditor extends JPanel {
installPopup(prettyPane);
installPopup(rawArea);
+ installEncodeAsYouType(prettyPane);
+ installEncodeAsYouType(rawArea);
// Editor shortcuts the reference provides: undo/redo and delete-line.
EditorKeys.install(rawArea);
@@ -2100,83 +2102,100 @@ public class MessageEditor extends JPanel {
return shown.isRequest();
}
- /** Build the right-click action menu. */
+ /**
+ * Build the right-click menu. The items and their order are the
+ * reference's message editor menu; the tools only Open Suite sends to
+ * follow the reference's own, and what a view cannot do is left out.
+ */
public JPopupMenu buildMenu() {
JPopupMenu menu = new JPopupMenu();
boolean haveRequest = (flags & REQUEST) != 0 || relatedRequest != null;
boolean haveMessage = message != null && message.raw().length > 0;
+ boolean isRequest = haveMessage && message.isRequest();
+ HttpMessage req = !haveMessage ? relatedRequest : isRequest ? message : relatedRequest;
+ HttpMessage resp = haveMessage && !isRequest ? message : null;
+ int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();
+
+ // Scan.
+ if (ctx != null && service != null && req != null && ctx.hasSink("scanner")) {
+ addItem(menu, "Scan", null, e -> scan(req, resp, true));
+ addItem(menu, "Passive scan selected message", null, e -> scan(req, resp, false));
+ addItem(menu, "Active scan selected message", null, e -> scan(req, resp, true));
+ menu.addSeparator();
+ }
- // "Send to <tool>" for the standard tools, with keyboard shortcuts.
+ // Send to each tool, the reference's in its order, then the collaborator payload.
boolean anySend = false;
- for (String tool : ctx.sinkNames()) {
- if (Engagement.isEngagement(tool)) continue; // engagement tools go in their submenu
- final String t = tool;
- JMenuItem mi = sendItem(t);
- if (mi == null) continue;
- KeyStroke ks = Hotkeys.keyStroke(Hotkeys.bindingOf(settings(), "Send to " + capitalise(t)));
- if (ks != null) mi.setAccelerator(ks);
- menu.add(mi);
+ if (ctx != null) {
+ List<String> sinks = ctx.sinkNames(), ordered = new ArrayList<>();
+ for (String t : List.of("intruder", "repeater", "sequencer", "comparer", "decoder", "organizer")) if (sinks.contains(t)) ordered.add(t);
+ for (String t : sinks) if (!ordered.contains(t) && !Engagement.isEngagement(t) && !t.equals("scanner")) ordered.add(t);
+ for (String t : ordered) {
+ JMenuItem mi = sendItem(t);
+ if (mi == null) continue;
+ mi.setText("Send to " + capitalise(t));
+ KeyStroke ks = Hotkeys.keyStroke(Hotkeys.bindingOf(settings(), "Send to " + capitalise(t)));
+ if (ks != null) mi.setAccelerator(ks);
+ menu.add(mi);
+ anySend = true;
+ }
+ }
+ if (editable && ctx != null) {
+ addItem(menu, "Insert Collaborator payload", null, e -> insertCollaboratorPayload());
anySend = true;
}
if (anySend) menu.addSeparator();
+ if (ctx != null && service != null && haveMessage) {
+ JMenu record = sub("Record an issue");
+ addItem(record, "Create a new issue", null, e -> ManualIssue.record(this, ctx, service, req, resp));
+ menu.add(record);
+ menu.addSeparator();
+ }
+
+ boolean browser = false;
+ if (resp != null && service != null) {
+ addItem(menu, "Open response in browser", null, e -> openResponseInBrowser());
+ browser = true;
+ }
+ if (req != null && service != null) {
+ JMenu inBrowser = sub("Request in browser");
+ addItem(inBrowser, "In original session", null, e -> MessageActions.openRequestInBrowser(this, service, req));
+ addItem(inBrowser, "In current browser session", null, e -> MessageActions.openRequestInBrowser(this, service, req));
+ menu.add(inBrowser);
+ browser = true;
+ }
+ if (browser) menu.addSeparator();
+
// Engagement tools submenu (CSRF PoC, content discovery, ...).
List<String> eng = new ArrayList<>();
- for (String tool : ctx.sinkNames()) if (Engagement.isEngagement(tool)) eng.add(tool);
+ if (ctx != null) for (String tool : ctx.sinkNames()) if (Engagement.isEngagement(tool)) eng.add(tool);
if (!eng.isEmpty() && service != null && haveRequest) {
- JMenu sub = new JMenu("Engagement tools");
- sub.setFont(Ui.PLAIN);
+ JMenu sub = sub("Engagement tools");
for (String t : eng) { JMenuItem mi = sendItem(t); if (mi != null) { mi.setText(Engagement.label(t)); sub.add(mi); } }
menu.add(sub);
menu.addSeparator();
}
- if (service != null && ctx != null && ctx.canScan()) {
- addItem(menu, "Actively scan this host", null, e -> ctx.launchScan(service.url(), true));
- menu.addSeparator();
- }
-
- if ((flags & REQUEST) != 0 && editable) {
- addItem(menu, "Change request method", null, e -> toggleMethod());
- addItem(menu, "Change body encoding", null, e -> toggleBodyEncoding());
- }
- if ((flags & RESPONSE) != 0 && service != null && haveMessage) {
- addItem(menu, "Open response in browser", null, e -> openResponseInBrowser());
- String base = service.url() + (relatedRequest != null ? relatedRequest.requestTarget()
- : message.isRequest() ? message.requestTarget() : "/");
- addItem(menu, "Copy links in response", null, e -> clip(MessageActions.linksIn(message, base)));
- }
-
- addItem(menu, "Copy", KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()), e -> {
+ // Editing.
+ boolean editsRequest = (flags & REQUEST) != 0 && editable;
+ if (editsRequest) addItem(menu, "Change request method", null, e -> toggleMethod());
+ if (editable) addItem(menu, "Cut", KeyStroke.getKeyStroke(KeyEvent.VK_X, mask), e -> activeText().cut());
+ if (editsRequest) addItem(menu, "Paste host / URL as request", null, e -> pasteUrlAsRequest());
+ addItem(menu, "Copy", KeyStroke.getKeyStroke(KeyEvent.VK_C, mask), e -> {
String sel = activeText().getSelectedText();
- String text = (sel == null || sel.isEmpty()) ? activeText().getText() : sel;
- clip(text);
+ clip(sel == null || sel.isEmpty() ? activeText().getText() : sel);
});
+ if (haveMessage) addItem(menu, "Copy prettified", Hotkeys.keyStroke(Hotkeys.bindingOf(settings(), "Copy prettified")), e -> clip(prettified()));
+ addItem(menu, "Save selected text to file", null, e -> copyToFile());
if (editable) {
- int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();
- addItem(menu, "Cut", KeyStroke.getKeyStroke(KeyEvent.VK_X, mask), e -> activeText().cut());
addItem(menu, "Paste", KeyStroke.getKeyStroke(KeyEvent.VK_V, mask), e -> activeText().paste());
- addItem(menu, "Paste from file", null, e -> pasteFromFile());
- }
- addItem(menu, "Copy to file", null, e -> copyToFile());
- if (service != null) {
- addItem(menu, "Copy URL", null, e -> clip(service.url() + (message.isRequest() ? message.requestTarget() : "")));
- if (message.isRequest()) addItem(menu, "Copy as curl command (bash)", null, e -> clip(asCurl()));
- }
+ addItem(menu, "Paste text from file", null, e -> pasteFromFile());
+ JCheckBoxMenuItem asYouType = new JCheckBoxMenuItem("URL-encode as you type", urlEncodeAsYouType);
+ asYouType.setFont(Ui.PLAIN);
+ asYouType.addActionListener(e -> urlEncodeAsYouType = asYouType.isSelected());
+ menu.add(asYouType);
- // Record an issue, open/add the request, as the reference request menu does.
- if (ctx != null && service != null && haveMessage) {
- HttpMessage req = message.isRequest() ? message : relatedRequest;
- HttpMessage resp = message.isRequest() ? null : message;
- menu.addSeparator();
- addItem(menu, "Record an issue", null, e -> ManualIssue.record(this, ctx, service, req, resp));
- if (req != null) {
- addItem(menu, "Request in browser", null, e -> MessageActions.openRequestInBrowser(this, service, req));
- addItem(menu, "Add to site map", null, e -> MessageActions.addToSiteMap(ctx, service, req, resp));
- }
- }
- if (editable) {
- menu.addSeparator();
String sel = activeText().getSelectedText();
JMenu convert = new JMenu("Convert selection");
convert.setFont(Ui.PLAIN);
@@ -2216,6 +2235,34 @@ public class MessageEditor extends JPanel {
menu.add(convert);
}
+ if (editsRequest) {
+ JMenu encoding = sub("Change body encoding");
+ addItem(encoding, "Form URL-encoded", null, e -> changeBodyEncoding(opensuite.core.BodyEncoding.Kind.FORM));
+ addItem(encoding, "Multipart", null, e -> changeBodyEncoding(opensuite.core.BodyEncoding.Kind.MULTIPART));
+ addItem(encoding, "JSON", null, e -> changeBodyEncoding(opensuite.core.BodyEncoding.Kind.JSON));
+ menu.add(encoding);
+ }
+ menu.addSeparator();
+
+ // Saving and copying the item.
+ if (historySaver != null) addItem(menu, "Save entire history", null, e -> historySaver.run());
+ if (service != null && haveMessage) {
+ addItem(menu, "Copy URL", null, e -> clip(service.url() + (req != null ? req.requestTarget() : "")));
+ if (req != null) addItem(menu, "Copy as curl command (bash)", null, e -> clip(MessageActions.curl(service, req)));
+ }
+ if (resp != null && service != null) {
+ String base = service.url() + (req != null ? req.requestTarget() : "/");
+ addItem(menu, "Copy links in response", null, e -> clip(MessageActions.linksIn(resp, base)));
+ }
+ if (haveMessage) addItem(menu, "Save item", null, e -> saveItem(req, resp));
+ if (ctx != null && service != null && req != null) {
+ menu.addSeparator();
+ addItem(menu, "Add to site map", null, e -> MessageActions.addToSiteMap(ctx, service, req, resp));
+ }
+
+ menu.addSeparator();
+ addItem(menu, "Message editor documentation", null, e -> AboutDialog.open(Unbuilt.PROJECT_URL + "#readme"));
+ if (toolDocs != null) addItem(menu, toolDocs + " documentation", null, e -> AboutDialog.open(Unbuilt.PROJECT_URL + "#readme"));
if (!providers.isEmpty()) {
menu.addSeparator();
@@ -2224,6 +2271,102 @@ public class MessageEditor extends JPanel {
return menu;
}
+ // What the tool that owns this editor adds to the menu.
+ private Runnable historySaver;
+ private java.util.function.Consumer<HttpService> targetSetter;
+ private String toolDocs;
+ private boolean urlEncodeAsYouType;
+
+ /** "Save entire history" appears in the menu and runs this; for a tool that keeps a history of what it sent. */
+ public void setHistorySaver(Runnable saver) { this.historySaver = saver; }
+
+ /** Told the target of a URL pasted as a request, by a tool that has a target of its own to set. */
+ public void setTargetSetter(java.util.function.Consumer<HttpService> setter) { this.targetSetter = setter; }
+
+ /** The tool's own documentation item, "Repeater documentation" for "Repeater". */
+ public void setToolDocs(String toolName) { this.toolDocs = toolName; }
+
+ private void scan(HttpMessage req, HttpMessage resp, boolean active) {
+ ctx.sendTo("scanner", service, req.copy(), resp == null ? null : resp.copy(), active ? "active" : "passive");
+ }
+
+ /** Put a fresh collaborator address at the caret, in place of any selection. */
+ private void insertCollaboratorPayload() {
+ String host = ctx.collaborator().payloadHost();
+ if (host == null) {
+ JOptionPane.showMessageDialog(this, "The collaborator is not running. Start it in the Collaborator tab first.",
+ "Insert Collaborator payload", JOptionPane.INFORMATION_MESSAGE);
+ return;
+ }
+ activeText().replaceSelection(host);
+ }
+
+ /** The message as the Pretty view would lay it out. */
+ private String prettified() {
+ String text = textOf(message);
+ try { return PrettyPrint.message(text, message.contentType()); }
+ catch (RuntimeException | StackOverflowError e) { return text; }
+ }
+
+ /** Replace the request with a GET for the address on the clipboard, and set the target to its host. */
+ private void pasteUrlAsRequest() {
+ String text;
+ try { text = String.valueOf(Toolkit.getDefaultToolkit().getSystemClipboard().getData(java.awt.datatransfer.DataFlavor.stringFlavor)).strip(); }
+ catch (Exception e) { return; }
+ HttpMessage made = requestFor(text);
+ if (made == null) {
+ JOptionPane.showMessageDialog(this, "The clipboard does not hold a host or a URL.", "Paste host / URL as request", JOptionPane.INFORMATION_MESSAGE);
+ return;
+ }
+ HttpService svc = HttpService.parse(text.contains("://") ? text : "http://" + text);
+ setMessage(svc, made);
+ if (targetSetter != null) targetSetter.accept(svc);
+ if (changeListener != null) changeListener.run();
+ }
+
+ /** A plain GET for a host or a URL, or null when the text is neither. */
+ static HttpMessage requestFor(String text) {
+ if (text == null || text.isBlank() || text.matches("(?s).*\\s.*")) return null;
+ String url = text.contains("://") ? text : "http://" + text;
+ java.net.URI u;
+ try { u = java.net.URI.create(url); } catch (IllegalArgumentException e) { return null; }
+ if (u.getHost() == null || u.getScheme() == null || !u.getScheme().matches("(?i)https?")) return null;
+ String path = u.getRawPath() == null || u.getRawPath().isEmpty() ? "/" : u.getRawPath();
+ if (u.getRawQuery() != null) path += "?" + u.getRawQuery();
+ boolean tls = u.getScheme().equalsIgnoreCase("https");
+ String host = u.getHost() + (u.getPort() < 0 || u.getPort() == (tls ? 443 : 80) ? "" : ":" + u.getPort());
+ return new HttpMessage(Bytes.bytes("GET " + path + " HTTP/1.1\r\nHost: " + host + "\r\n\r\n"));
+ }
+
+ /** Save the request and, when there is one, the response to a file. */
+ private void saveItem(HttpMessage req, HttpMessage resp) {
+ JFileChooser fc = new opensuite.ui.FileChooser();
+ fc.setDialogTitle("Save item");
+ if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
+ try (java.io.OutputStream out = java.nio.file.Files.newOutputStream(fc.getSelectedFile().toPath())) {
+ if (req != null) out.write(req.raw());
+ if (req != null && resp != null) out.write(Bytes.bytes("\n\n"));
+ if (resp != null) out.write(resp.raw());
+ } catch (java.io.IOException ex) {
+ JOptionPane.showMessageDialog(this, "Could not write the file: " + ex.getMessage(), "Save item", JOptionPane.ERROR_MESSAGE);
+ }
+ }
+
+ /** While "URL-encode as you type" is on, a typed character that has a special meaning in a URL goes in encoded. */
+ private void installEncodeAsYouType(JTextComponent c) {
+ c.addKeyListener(new java.awt.event.KeyAdapter() {
+ @Override public void keyTyped(KeyEvent e) {
+ char ch = e.getKeyChar();
+ if (!urlEncodeAsYouType || !c.isEditable() || ch < 0x20 || ch == 0x7f || ch == KeyEvent.CHAR_UNDEFINED
+ || e.isControlDown() || e.isAltDown() || e.isMetaDown()) return;
+ String encoded = Convert.urlEncodeKey(String.valueOf(ch));
+ if (encoded.equals(String.valueOf(ch))) return;
+ e.consume();
+ c.replaceSelection(encoded);
+ }
+ });
+ }
+
private JMenuItem sendItem(String t) {
boolean haveRequest = (flags & REQUEST) != 0 || relatedRequest != null;
boolean haveMessage = message != null && message.raw().length > 0;
@@ -2329,9 +2472,9 @@ public class MessageEditor extends JPanel {
if (changeListener != null) changeListener.run();
}
- /** Switch the body between URL-encoded and multipart form encoding. */
- private void toggleBodyEncoding() {
- if (!opensuite.core.BodyEncoding.toggle(message, opensuite.core.BodyEncoding.newBoundary())) return;
+ /** Convert the body to another encoding. */
+ private void changeBodyEncoding(opensuite.core.BodyEncoding.Kind to) {
+ if (!opensuite.core.BodyEncoding.convert(message, to, opensuite.core.BodyEncoding.newBoundary())) return;
loadActiveFromMessage();
refreshViews();
if (changeListener != null) changeListener.run();
@@ -2340,28 +2483,28 @@ public class MessageEditor extends JPanel {
/** Save the selection, or the whole message when nothing is selected, to a file. */
private void copyToFile() {
JFileChooser fc = new opensuite.ui.FileChooser();
- fc.setDialogTitle("Copy to file");
+ fc.setDialogTitle("Save selected text to file");
if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return;
String sel = activeText().getSelectedText();
byte[] data = sel == null || sel.isEmpty() ? bytes() : sel.getBytes(charsetOf(message));
try { java.nio.file.Files.write(fc.getSelectedFile().toPath(), data); }
catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Could not write the file: " + ex.getMessage(),
- "Copy to file", JOptionPane.ERROR_MESSAGE);
+ "Save selected text to file", JOptionPane.ERROR_MESSAGE);
}
}
/** Replace the selection (or insert at the caret) with a file's contents. */
private void pasteFromFile() {
JFileChooser fc = new opensuite.ui.FileChooser();
- fc.setDialogTitle("Paste from file");
+ fc.setDialogTitle("Paste text from file");
if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
try {
byte[] data = java.nio.file.Files.readAllBytes(fc.getSelectedFile().toPath());
activeText().replaceSelection(new String(data, charsetOf(message)));
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Could not read the file: " + ex.getMessage(),
- "Paste from file", JOptionPane.ERROR_MESSAGE);
+ "Paste text from file", JOptionPane.ERROR_MESSAGE);
}
}
diff --git a/tests/RunTests.java b/tests/RunTests.java
index 79e2061..be19d5b 100644
--- a/tests/RunTests.java
+++ b/tests/RunTests.java
@@ -37,6 +37,7 @@ public final class RunTests {
new opensuite.engagement.EngagementToolsTest().run();
new opensuite.decoder.DecoderTransformsTest().run();
new opensuite.ui.MessageEditorJsonTest().run();
+ new opensuite.ui.EditorMenuTest().run();
new opensuite.core.HttpMessageTitleTest().run();
new opensuite.csrf.CsrfPocTest().run();
new opensuite.sequencer.SequencerStatsTest().run();
diff --git a/tests/opensuite/core/BodyEncodingTest.java b/tests/opensuite/core/BodyEncodingTest.java
index 504e76b..acbc6a0 100644
--- a/tests/opensuite/core/BodyEncodingTest.java
+++ b/tests/opensuite/core/BodyEncodingTest.java
@@ -14,6 +14,26 @@ public final class BodyEncodingTest {
public void run() {
Harness.suite("body encoding");
+ Harness.test("a form body becomes JSON and comes back the same", () -> {
+ HttpMessage m = new HttpMessage(Bytes.bytes("POST /a HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 13\r\n\r\na=1&b=two+%26"));
+ Expect.isTrue(BodyEncoding.convert(m, BodyEncoding.Kind.JSON, "B"), "converted");
+ Expect.equal(m.bodyText(), "{\"a\":\"1\",\"b\":\"two &\"}", "json body");
+ Expect.equal(m.header("Content-Type"), "application/json", "type");
+ Expect.equal(m.header("Content-Length"), String.valueOf(m.body().length), "length");
+ Expect.isTrue(BodyEncoding.convert(m, BodyEncoding.Kind.FORM, "B"), "back");
+ Expect.equal(m.bodyText(), "a=1&b=two+%26", "form body");
+ });
+
+ Harness.test("JSON becomes multipart; the encoding it already has, or a body that cannot be read, changes nothing", () -> {
+ HttpMessage m = new HttpMessage(Bytes.bytes("POST /a HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n\r\n{\"n\":5,\"s\":\"v\"}"));
+ Expect.isFalse(BodyEncoding.convert(m, BodyEncoding.Kind.JSON, "B"), "already JSON");
+ Expect.isTrue(BodyEncoding.convert(m, BodyEncoding.Kind.MULTIPART, "B"), "converted");
+ Expect.isTrue(m.bodyText().contains("name=\"n\"\r\n\r\n5\r\n") && m.bodyText().contains("name=\"s\"\r\n\r\nv\r\n"), "parts");
+ HttpMessage bad = new HttpMessage(Bytes.bytes("POST /a HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n\r\n[1,2"));
+ Expect.isFalse(BodyEncoding.convert(bad, BodyEncoding.Kind.FORM, "B"), "unreadable JSON");
+ Expect.equal(bad.bodyText(), "[1,2", "left alone");
+ });
+
Harness.test("a URL-encoded body becomes multipart with decoded values", () -> {
HttpMessage m = post("application/x-www-form-urlencoded", "user=a+b&pw=%26x&flag");
Expect.isTrue(BodyEncoding.toggle(m, "XB"), "changed");
diff --git a/tests/opensuite/ui/EditorMenuTest.java b/tests/opensuite/ui/EditorMenuTest.java
new file mode 100644
index 0000000..8a9c968
--- /dev/null
+++ b/tests/opensuite/ui/EditorMenuTest.java
@@ -0,0 +1,53 @@
+package opensuite.ui;
+
+import opensuite.core.Bytes;
+import opensuite.core.HttpMessage;
+import opensuite.core.HttpService;
+import opensuite.testkit.Expect;
+import opensuite.testkit.Harness;
+
+import javax.swing.JMenuItem;
+import javax.swing.JPopupMenu;
+import java.util.ArrayList;
+import java.util.List;
+
+/** The message editor's right-click menu: its items in the reference's order, and the request a pasted URL makes. */
+public final class EditorMenuTest {
+
+ private static List<String> labels(JPopupMenu menu) {
+ List<String> out = new ArrayList<>();
+ for (java.awt.Component c : menu.getComponents()) out.add(c instanceof JMenuItem mi ? mi.getText() : "-");
+ return out;
+ }
+
+ public void run() {
+ Harness.suite("editor menu");
+
+ Harness.test("an editable request has the reference's editing and saving items, in its order", () -> {
+ List<String>[] got = new List[1];
+ try {
+ javax.swing.SwingUtilities.invokeAndWait(() -> {
+ MessageEditor ed = new MessageEditor(null, MessageEditor.REQUEST, true);
+ ed.setMessage(new HttpService("a.test", 443, true), new HttpMessage(Bytes.bytes("GET /p?x=1 HTTP/1.1\r\nHost: a.test\r\n\r\n")));
+ ed.setToolDocs("Repeater");
+ ed.setHistorySaver(() -> { });
+ got[0] = labels(ed.buildMenu());
+ });
+ } catch (Exception e) { throw new RuntimeException(e); }
+ Expect.equal(got[0], List.of(
+ "Request in browser", "-",
+ "Change request method", "Cut", "Paste host / URL as request", "Copy", "Copy prettified",
+ "Save selected text to file", "Paste", "Paste text from file", "URL-encode as you type",
+ "Convert selection", "Change body encoding", "-",
+ "Save entire history", "Copy URL", "Copy as curl command (bash)", "Save item", "-",
+ "Message editor documentation", "Repeater documentation"), "items");
+ });
+
+ Harness.test("a host or a URL becomes a GET for it; other text does not", () -> {
+ Expect.equal(new String(MessageEditor.requestFor("https://a.test/x/y?q=1").raw()), "GET /x/y?q=1 HTTP/1.1\r\nHost: a.test\r\n\r\n", "url");
+ Expect.equal(new String(MessageEditor.requestFor("a.test:8080").raw()), "GET / HTTP/1.1\r\nHost: a.test:8080\r\n\r\n", "host and port");
+ Expect.isTrue(MessageEditor.requestFor("two words") == null, "not an address");
+ Expect.isTrue(MessageEditor.requestFor("ftp://a.test/") == null, "not http");
+ });
+ }
+}
diff --git a/tests/opensuite/ui/SendToComparerTest.java b/tests/opensuite/ui/SendToComparerTest.java
index 441c6bd..8391b62 100644
--- a/tests/opensuite/ui/SendToComparerTest.java
+++ b/tests/opensuite/ui/SendToComparerTest.java
@@ -63,7 +63,7 @@ public final class SendToComparerTest {
// the related request is what the old code smuggled in alongside it
editor.setMessage(service(), message(RESPONSE_TEXT), message(REQUEST_TEXT));
- fire(editor, "Send to comparer");
+ fire(editor, "Send to Comparer");
Expect.equal(comparer.calls, 1, "sends from one click");
Expect.isNull(comparer.requests.get(0), "request handed to the comparer");
@@ -77,7 +77,7 @@ public final class SendToComparerTest {
MessageEditor editor = new MessageEditor(ctx, MessageEditor.REQUEST, true);
editor.setMessage(service(), message(REQUEST_TEXT));
- fire(editor, "Send to comparer");
+ fire(editor, "Send to Comparer");
Expect.equal(comparer.calls, 1, "sends from one click");
Expect.isNull(comparer.responses.get(0), "response handed to the comparer");
@@ -97,12 +97,12 @@ public final class SendToComparerTest {
new MessageEditor(ctx, MessageEditor.REQUEST | MessageEditor.RESPONSE, true);
editor.setMessage(service(), message(RESPONSE_TEXT), message(REQUEST_TEXT));
- fire(editor, "Send to comparer");
+ fire(editor, "Send to Comparer");
Expect.equal(comparer.calls, 1, "sends to the comparer");
Expect.isNull(comparer.requests.get(0), "request handed to the comparer");
Expect.equal(text(comparer.responses.get(0)), RESPONSE_TEXT, "the response sent");
- fire(editor, "Send to repeater");
+ fire(editor, "Send to Repeater");
Expect.equal(text(repeater.requests.get(0)), REQUEST_TEXT,
"the request the repeater receives");
Expect.equal(text(repeater.responses.get(0)), RESPONSE_TEXT,
@@ -116,7 +116,7 @@ public final class SendToComparerTest {
MessageEditor editor = new MessageEditor(ctx, MessageEditor.RESPONSE, false);
editor.setMessage(service(), message(RESPONSE_TEXT), message(REQUEST_TEXT));
- fire(editor, "Send to repeater");
+ fire(editor, "Send to Repeater");
Expect.equal(text(repeater.requests.get(0)), REQUEST_TEXT, "the request sent");
Expect.equal(text(repeater.responses.get(0)), RESPONSE_TEXT, "the response sent");
@@ -127,7 +127,7 @@ public final class SendToComparerTest {
SuiteContext ctx = context(comparer);
MessageEditor editor = new MessageEditor(ctx, MessageEditor.RESPONSE, false);
- Expect.isNull(find(editor.buildMenu(), "Send to comparer"),
+ Expect.isNull(find(editor.buildMenu(), "Send to Comparer"),
"a send entry on an empty view");
});
}