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.

Repeater: custom actions run, through a script engine (#56)

yahavsass68e9f75a3ed1
diff --git a/CONTRACT.md b/CONTRACT.md
index dc58b8e..c18c007 100644
--- a/CONTRACT.md
+++ b/CONTRACT.md
@@ -171,6 +171,41 @@ OptionsPage.indent(component, px);
## opensuite.ui.ScopeEditor
`new ScopeEditor(ctx, ctx.scope())` or any other Scope instance.
+## Scripts (opensuite.script.api)
+
+Scripts are Java method bodies kept under `~/.opensuite/scripts/<function>/<name>.java`
+and managed in Extensions > Script library. A custom action runs from Repeater's
+Custom actions panel with this signature; its body is the whole file:
+
+```java
+void action(HttpRequestResponse requestResponse, Utilities utilities)
+```
+
+```java
+HttpRequestResponse request() response() (null when none) hasResponse() setRequest(HttpRequest)
+HttpRequest method() path() query() url() header(n) headers() body() bodyText() parameters() service()
+ withHeader(n,v) withRemovedHeader(n) withBody(byte[]) withBody(String) withMethod(m) withPath(p)
+ // each returns a new request; the original is never changed
+HttpResponse statusCode() header(n) headers() body() bodyText() mimeType()
+Utilities log(o) clipboard(s) bytes(s) concat(byte[]...) hex(b) base64Encode/Decode urlEncode/Decode
+ sha256(b) md5(b) hmacSha256(key, data) // hashes take and return bytes
+```
+
+- `body()` is the exact bytes; `bodyText()` and `withBody(String)` use the declared
+ charset, or UTF-8 when none is declared. Sign bytes, not text.
+- A request handed to `setRequest` replaces the one being edited only when the action
+ ends without an error, as one change that a single undo takes back. An action never
+ sends anything.
+- The script API, `java.util.*` and `java.nio.charset.*` are imported. Only
+ `opensuite.script.api` is a supported surface; the suite's other classes can change.
+- Runs happen one at a time on a thread of their own, with a 10 second limit; Run turns
+ into Stop while one is under way. A script that ignores interruption cannot be ended
+ and is left running until Open Suite restarts; with three of those, runs are refused.
+ A script that calls `System.exit`, `Runtime.exit` or `Runtime.halt` is refused when it is compiled.
+- Output is capped at 1,000 lines or 64 KB per run. Errors are reported at the script's
+ own line numbers.
+- Scripts run with the user's own permissions. There is no sandbox: load only code you trust.
+
## Rules
- Package per tool: `opensuite.decoder`, `opensuite.comparer`, etc. One public class implementing `ToolModule`.
- No `System.exit`, no static mutable singletons, no printing to stdout.
diff --git a/ROADMAP.md b/ROADMAP.md
index 617db40..bccdf2f 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -15,16 +15,10 @@ This file is generated from the registry in `src/opensuite/ui/Unbuilt.java`, whi
| Custom scan checks > Running saved checks during an audit | `OT-EXT-SCANCHECK` |
| Script library > Running saved scripts from the tools | `OT-EXT-SCRIPTS` |
-## Message editor
-
-| Feature | Reference |
-|---|---|
-| Custom actions > Running an action on the shown message | `OT-MSG-CUSTOMACTION` |
-
## Decoder
| Feature | Reference |
|---|---|
| Encoding as brotli | `OT-DECODER-BROTLI` |
-6 open items.
+5 open items.
diff --git a/src/opensuite/core/SuiteContext.java b/src/opensuite/core/SuiteContext.java
index fcfb013..d51c63a 100644
--- a/src/opensuite/core/SuiteContext.java
+++ b/src/opensuite/core/SuiteContext.java
@@ -68,6 +68,7 @@ public class SuiteContext {
// The out-of-band collaborator session, shared by the scanner's blind checks
// and the collaborator tab so one registration and one poll loop serve both.
private final opensuite.oast.Collaborator collaborator = new opensuite.oast.Collaborator(settings);
+ private final opensuite.script.ScriptEngine scripts = new opensuite.script.ScriptEngine();
// Session handling: the cookie jar, macros and rules, shared by every tool
// that sends through the HttpClient session hook.
private final opensuite.session.SessionManager sessions = new opensuite.session.SessionManager(this);
@@ -156,6 +157,8 @@ public class SuiteContext {
/** The log files of Settings > Project > Logging. */
public TrafficLog trafficLog() { return trafficLog; }
public opensuite.oast.Collaborator collaborator() { return collaborator; }
+ /** Compiles and runs the script library's scripts, one run at a time. */
+ public opensuite.script.ScriptEngine scripts() { return scripts; }
public opensuite.session.SessionManager sessions() { return sessions; }
public UpstreamProxyManager upstreamProxies() { return upstreamProxies; }
public opensuite.organizer.OrganizerStore organizer() { return organizer; }
diff --git a/src/opensuite/extensions/ExtensionsTool.java b/src/opensuite/extensions/ExtensionsTool.java
index 08e9e54..6498478 100644
--- a/src/opensuite/extensions/ExtensionsTool.java
+++ b/src/opensuite/extensions/ExtensionsTool.java
@@ -3,6 +3,7 @@ package opensuite.extensions;
import opensuite.core.SuiteContext;
import opensuite.core.ToolModule;
import opensuite.ui.SettingsDialog;
+import opensuite.ui.SuiteFrame;
import javax.swing.*;
@@ -33,6 +34,20 @@ public class ExtensionsTool implements ToolModule {
JComponent settings = ctx == null ? new JPanel()
: SettingsDialog.launcher(ctx, "Extensions", "Extensions settings",
"Startup and load behaviour for extensions, and the Java, Python and Ruby runtimes they use, are configured under Settings > Extensions.");
+ ScriptLibraryPanel library = new ScriptLibraryPanel(null,
+ "Script library",
+ "Scripts are small pieces of Java that run from tools across Open Suite to carry out a range of tasks: "
+ + "filters, custom actions, custom columns and scan checks. Use the library to manage your scripts in one "
+ + "place, then load them directly in compatible tools when needed.",
+ "Customize Open Suite with Java-based scripts",
+ "To get started, create or import a new script. Looking for ideas? Use a built-in template to create "
+ + "your script or browse the project's GitHub repository for ready-to-use scripts.",
+ ctx == null ? null : source -> ctx.scripts().compiler().compileCustomAction(source).errors());
+ // "edit script" in a custom actions panel opens the script here.
+ if (ctx != null) ctx.scripts().setLibraryOpener(script -> {
+ if (ctx.frame() instanceof SuiteFrame frame) frame.selectTool(name());
+ library.reveal(script);
+ });
return new Tab[]{
new Tab("Installed", new InstalledPanel(extensions)),
new Tab("Store", new StorePanel()),
@@ -44,15 +59,7 @@ public class ExtensionsTool implements ToolModule {
+ "and its response and reports issues; the scanner runs every enabled check against each audit item.",
"Extend the scanner with custom scan checks",
"Write a check once and the scanner applies it to every audit item. To get started, create a new check or import one.")),
- new Tab("Script library", new ScriptLibraryPanel(
- null,
- "Script library",
- "Scripts are small pieces of Java that run from tools across Open Suite to carry out a range of tasks: "
- + "filters, custom actions, custom columns and scan checks. Use the library to manage your scripts in one "
- + "place, then load them directly in compatible tools when needed.",
- "Customize Open Suite with Java-based scripts",
- "To get started, create or import a new script. Looking for ideas? Use a built-in template to create "
- + "your script or browse the project's GitHub repository for ready-to-use scripts.")),
+ new Tab("Script library", library),
new Tab("Extensions settings", settings),
};
}
diff --git a/src/opensuite/extensions/ScriptLibraryPanel.java b/src/opensuite/extensions/ScriptLibraryPanel.java
index 2aa1777..d176ff5 100644
--- a/src/opensuite/extensions/ScriptLibraryPanel.java
+++ b/src/opensuite/extensions/ScriptLibraryPanel.java
@@ -60,6 +60,8 @@ public final class ScriptLibraryPanel extends JPanel {
private final JTextField nameField = Ui.field("");
private final JComboBox<String> functionBox;
private Script editing;
+ private final java.util.function.Function<String, List<String>> checker; // null: no Check
+ private final JTextArea checkResult = Ui.note("");
private final JButton edit, duplicate, export, delete;
public static Path root() { return Path.of(System.getProperty("user.home", "."), ".opensuite", "scripts"); }
@@ -71,8 +73,15 @@ public final class ScriptLibraryPanel extends JPanel {
* @param emptyTitle the empty-state headline on the right
*/
public ScriptLibraryPanel(Function only, String title, String blurb, String emptyTitle, String emptyText) {
+ this(only, title, blurb, emptyTitle, emptyText, null);
+ }
+
+ /** @param checker the compile errors of a custom action's source, for Check */
+ public ScriptLibraryPanel(Function only, String title, String blurb, String emptyTitle, String emptyText,
+ java.util.function.Function<String, List<String>> checker) {
super(new BorderLayout(0, 8));
this.only = only;
+ this.checker = checker;
setOpaque(false);
setBorder(Ui.pad(10, 12, 10, 12));
@@ -222,11 +231,16 @@ public final class ScriptLibraryPanel extends JPanel {
functionBox.addActionListener(e -> sig.setText(Function.of(String.valueOf(functionBox.getSelectedItem())).signature));
JButton save = Ui.primaryButton("Save", "Save the script to the library");
JButton cancel = Ui.button("Cancel");
+ JButton check = Ui.button("Check", "compile the script and list its errors");
save.addActionListener(e -> save());
cancel.addActionListener(e -> { onSelect(); });
+ check.addActionListener(e -> checkInBackground(check));
+ functionBox.addActionListener(e -> check.setEnabled(checkable()));
+ check.setEnabled(checkable());
+ checkResult.setText("");
JPanel bar = new JPanel(new FlowLayout(FlowLayout.RIGHT, 8, 4));
bar.setOpaque(false);
- bar.add(cancel); bar.add(save);
+ bar.add(check); bar.add(cancel); bar.add(save);
JPanel top = Ui.vbox(form, Box.createVerticalStrut(4), sig);
top.setBorder(Ui.pad(0, 0, 6, 0));
@@ -235,7 +249,7 @@ public final class ScriptLibraryPanel extends JPanel {
p.setBorder(Ui.pad(0, 8, 0, 0));
p.add(top, BorderLayout.NORTH);
p.add(Ui.scroll(editor), BorderLayout.CENTER);
- p.add(bar, BorderLayout.SOUTH);
+ p.add(Ui.vbox(checkResult, bar), BorderLayout.SOUTH);
right.add(p, BorderLayout.CENTER);
right.revalidate();
right.repaint();
@@ -247,6 +261,59 @@ public final class ScriptLibraryPanel extends JPanel {
// ---- actions ----
+ /**
+ * Show the script named {@code name}: this panel's tab is brought to the
+ * front, and the script is selected and opened in the editor.
+ */
+ public void reveal(String name) {
+ for (Container c = getParent(), child = this; c != null; child = c, c = c.getParent()) {
+ if (c instanceof JTabbedPane tabs) { tabs.setSelectedComponent(child); break; }
+ }
+ int row = rowOf(name);
+ if (row < 0) { reload(""); row = rowOf(name); }
+ if (row < 0) return;
+ table.setRowSelectionInterval(row, row);
+ table.scrollRectToVisible(table.getCellRect(row, 0, true));
+ onSelect();
+ }
+
+ private int rowOf(String name) {
+ for (int i = 0; i < scripts.size(); i++) {
+ Script s = scripts.get(i);
+ if (s.name().equals(name) && (only == null || s.function() == only)) return i;
+ }
+ return -1;
+ }
+
+ /** Check works on custom actions, when the panel was given a checker. */
+ private boolean checkable() {
+ return checker != null && Function.of(String.valueOf(functionBox.getSelectedItem())) == Function.CUSTOM_ACTION;
+ }
+
+ /** Compile the editor's text now and show the errors. */
+ List<String> checkNow() {
+ List<String> errors = checker.apply(editor.getText());
+ showCheck(errors);
+ return errors;
+ }
+
+ private void checkInBackground(JButton check) {
+ String text = editor.getText();
+ check.setEnabled(false);
+ checkResult.setText("checking...");
+ Thread t = new Thread(() -> {
+ List<String> errors = checker.apply(text);
+ SwingUtilities.invokeLater(() -> { showCheck(errors); check.setEnabled(checkable()); });
+ }, "opensuite-script-check");
+ t.setDaemon(true);
+ t.start();
+ }
+
+ private void showCheck(List<String> errors) {
+ checkResult.setForeground(errors.isEmpty() ? Theme.MUTED : Ui.ERROR_RED);
+ checkResult.setText(errors.isEmpty() ? "no errors" : String.join("\n", errors));
+ }
+
private Script selected() {
int r = table.getSelectedRow();
return r < 0 || r >= scripts.size() ? null : scripts.get(r);
diff --git a/src/opensuite/script/Compiled.java b/src/opensuite/script/Compiled.java
new file mode 100644
index 0000000..fd416b8
--- /dev/null
+++ b/src/opensuite/script/Compiled.java
@@ -0,0 +1,9 @@
+package opensuite.script;
+
+import java.util.List;
+
+/** A compiled script, or its errors, each as {@code line N: message} at the script's own line. */
+public record Compiled(CustomActionFn fn, String className, List<String> errors) {
+
+ public boolean ok() { return errors.isEmpty(); }
+}
diff --git a/src/opensuite/script/CustomActionFn.java b/src/opensuite/script/CustomActionFn.java
new file mode 100644
index 0000000..dc02147
--- /dev/null
+++ b/src/opensuite/script/CustomActionFn.java
@@ -0,0 +1,9 @@
+package opensuite.script;
+
+import opensuite.script.api.HttpRequestResponse;
+import opensuite.script.api.Utilities;
+
+/** A compiled custom action: the script's body is the body of {@link #action}. */
+public interface CustomActionFn {
+ void action(HttpRequestResponse requestResponse, Utilities utilities) throws Exception;
+}
diff --git a/src/opensuite/script/RequestDiff.java b/src/opensuite/script/RequestDiff.java
new file mode 100644
index 0000000..99289a6
--- /dev/null
+++ b/src/opensuite/script/RequestDiff.java
@@ -0,0 +1,56 @@
+package opensuite.script;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import opensuite.core.HttpMessage;
+
+/**
+ * What changed between two versions of a request, so an action's change is
+ * never silent: headers added ({@code + Name}), changed ({@code ~ Name}) and
+ * removed ({@code - Name}), then the body's size before and after.
+ */
+public final class RequestDiff {
+
+ private RequestDiff() {}
+
+ public static List<String> summarise(HttpMessage before, HttpMessage after) {
+ List<String> out = new ArrayList<>();
+ if (Arrays.equals(before.raw(), after.raw())) return out;
+ if (!before.startLine().equals(after.startLine())) out.add("~ request line");
+
+ Map<String, Header> was = headers(before), now = headers(after);
+ for (Map.Entry<String, Header> e : now.entrySet()) {
+ if (!was.containsKey(e.getKey())) out.add("+ " + e.getValue().name);
+ }
+ for (Map.Entry<String, Header> e : now.entrySet()) {
+ Header old = was.get(e.getKey());
+ if (old != null && !old.values.equals(e.getValue().values)) out.add("~ " + e.getValue().name);
+ }
+ for (Map.Entry<String, Header> e : was.entrySet()) {
+ if (!now.containsKey(e.getKey())) out.add("- " + e.getValue().name);
+ }
+ byte[] b = before.body(), a = after.body();
+ if (!Arrays.equals(b, a)) out.add("body " + b.length + " -> " + a.length + " bytes");
+ return out;
+ }
+
+ /** A header as first spelled, with every value it has, in order. */
+ private record Header(String name, List<String> values) {}
+
+ private static Map<String, Header> headers(HttpMessage m) {
+ Map<String, Header> map = new LinkedHashMap<>();
+ for (String l : m.headerLines()) {
+ int c = l.indexOf(':');
+ if (c <= 0) continue;
+ String name = l.substring(0, c).strip();
+ map.computeIfAbsent(name.toLowerCase(Locale.ROOT), k -> new Header(name, new ArrayList<>()))
+ .values.add(l.substring(c + 1).strip());
+ }
+ return map;
+ }
+}
diff --git a/src/opensuite/script/RunResult.java b/src/opensuite/script/RunResult.java
new file mode 100644
index 0000000..971c3a4
--- /dev/null
+++ b/src/opensuite/script/RunResult.java
@@ -0,0 +1,18 @@
+package opensuite.script;
+
+import java.util.List;
+
+import opensuite.core.HttpMessage;
+
+/**
+ * How one run ended: the output, the error (null when OK), and the request the
+ * script asked for, which is kept only when the run ended OK.
+ */
+public record RunResult(Status status, List<String> log, boolean logCut, String error, long millis, HttpMessage newRequest) {
+
+ public enum Status { OK, FAILED, TIMEOUT, STOPPED }
+
+ static RunResult failed(Status status, String error) {
+ return new RunResult(status, List.of(), false, error, 0, null);
+ }
+}
diff --git a/src/opensuite/script/Samples.java b/src/opensuite/script/Samples.java
new file mode 100644
index 0000000..32d825d
--- /dev/null
+++ b/src/opensuite/script/Samples.java
@@ -0,0 +1,43 @@
+package opensuite.script;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/** The sample custom actions offered by "Add samples", by name, in the order they are listed. */
+public final class Samples {
+
+ private Samples() {}
+
+ private static final String SIGNATURE = "// void action(HttpRequestResponse requestResponse, Utilities utilities)\n";
+
+ public static final Map<String, String> CUSTOM_ACTIONS;
+ static {
+ Map<String, String> m = new LinkedHashMap<>();
+ m.put("Log status code", SIGNATURE
+ + "// Shows the status code of the response.\n"
+ + "if (requestResponse.hasResponse()) utilities.log(\"Status: \" + requestResponse.response().statusCode());\n"
+ + "else utilities.log(\"No response yet\");\n");
+ m.put("Copy response body", SIGNATURE
+ + "// Puts the response body on the clipboard.\n"
+ + "if (requestResponse.hasResponse()) {\n"
+ + " utilities.clipboard(requestResponse.response().bodyText());\n"
+ + " utilities.log(\"Copied \" + requestResponse.response().body().length + \" bytes\");\n"
+ + "} else {\n"
+ + " utilities.log(\"No response yet\");\n"
+ + "}\n");
+ m.put("Set a header", SIGNATURE
+ + "// Sets X-Custom on the request being edited. Nothing is sent until you send it.\n"
+ + "requestResponse.setRequest(requestResponse.request().withHeader(\"X-Custom\", \"1\"));\n");
+ m.put("Re-sign request (HMAC)", SIGNATURE
+ + "// Re-sign the request: X-Timestamp, and X-Signature = hex(HMAC-SHA256(key, timestamp + body)).\n"
+ + "// The key below is stored in this file in plain text.\n"
+ + "byte[] key = utilities.bytes(\"change-me\");\n"
+ + "String ts = String.valueOf(System.currentTimeMillis() / 1000);\n"
+ + "HttpRequest r = requestResponse.request().withHeader(\"X-Timestamp\", ts);\n"
+ + "r = r.withHeader(\"X-Signature\", utilities.hex(utilities.hmacSha256(key, utilities.concat(utilities.bytes(ts), r.body()))));\n"
+ + "requestResponse.setRequest(r);\n"
+ + "utilities.log(\"signed at \" + ts);\n");
+ CUSTOM_ACTIONS = Collections.unmodifiableMap(m);
+ }
+}
diff --git a/src/opensuite/script/ScriptCompiler.java b/src/opensuite/script/ScriptCompiler.java
new file mode 100644
index 0000000..0efbe8f
--- /dev/null
+++ b/src/opensuite/script/ScriptCompiler.java
@@ -0,0 +1,220 @@
+package opensuite.script;
+
+import java.io.ByteArrayOutputStream;
+import java.io.OutputStream;
+import java.io.StringWriter;
+import java.lang.classfile.ClassFile;
+import java.lang.classfile.CodeElement;
+import java.lang.classfile.MethodModel;
+import java.lang.classfile.instruction.InvokeInstruction;
+import java.lang.classfile.instruction.LineNumber;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+
+import javax.tools.Diagnostic;
+import javax.tools.DiagnosticCollector;
+import javax.tools.FileObject;
+import javax.tools.ForwardingJavaFileManager;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.StandardJavaFileManager;
+
+import opensuite.core.Bytes;
+
+/**
+ * Compiles a script body in memory with the JDK's compiler. The body is
+ * wrapped in a generated class with the script API imported, errors are given
+ * at the script's own lines, and results are cached by the source's SHA-256.
+ * Each script is loaded by a class loader of its own, so a replaced one can
+ * be collected.
+ */
+public final class ScriptCompiler {
+
+ private static final String PACKAGE = "opensuite.script.gen";
+ private static final String HEADER_TEMPLATE = "package " + PACKAGE + ";\n"
+ + "import opensuite.script.api.*;\n"
+ + "import opensuite.script.CustomActionFn;\n"
+ + "import java.util.*;\n"
+ + "import java.nio.charset.*;\n"
+ + "public final class %s implements CustomActionFn {\n"
+ + "public void action(HttpRequestResponse requestResponse, Utilities utilities) throws Exception {\n";
+ /** Lines the generated class has before the script's first line. */
+ static final int HEADER_LINES = (int) HEADER_TEMPLATE.chars().filter(c -> c == '\n').count();
+ private static final int CACHE_SIZE = 32;
+ static final String EXIT_MESSAGE = "a script may not exit Open Suite (System.exit / Runtime.halt)";
+ static final String NO_COMPILER = "no Java compiler is available in this runtime";
+
+ private final JavaCompiler compiler;
+ private StandardJavaFileManager files; // one for every compile, under the compiler's lock
+ private final Map<String, Compiled> cache = new LinkedHashMap<>(16, 0.75f, true) {
+ @Override protected boolean removeEldestEntry(Map.Entry<String, Compiled> eldest) { return size() > CACHE_SIZE; }
+ };
+
+ /** @param compiler the JDK compiler, or null when the runtime has none */
+ public ScriptCompiler(JavaCompiler compiler) { this.compiler = compiler; }
+
+ public boolean available() { return compiler != null; }
+
+ /** Compile a custom action, or take it from the cache. */
+ public Compiled compileCustomAction(String source) {
+ String key = sha256(source);
+ synchronized (cache) {
+ Compiled hit = cache.get(key);
+ if (hit != null) return hit;
+ }
+ Compiled c = compile(source, key);
+ synchronized (cache) { cache.put(key, c); }
+ return c;
+ }
+
+ /** The script line of the first frame of {@code className} in a stack trace, or -1. */
+ static int scriptLine(String className, StackTraceElement[] trace) {
+ if (className == null) return -1;
+ for (StackTraceElement e : trace) {
+ String c = e.getClassName();
+ if ((c.equals(className) || c.startsWith(className + "$")) && e.getLineNumber() > 0) {
+ return Math.max(1, e.getLineNumber() - HEADER_LINES);
+ }
+ }
+ return -1;
+ }
+
+ private Compiled compile(String source, String key) {
+ if (compiler == null) return new Compiled(null, null, List.of(NO_COMPILER));
+ String className = PACKAGE + ".S" + key.substring(0, 16);
+ String full = String.format(HEADER_TEMPLATE, className.substring(PACKAGE.length() + 1)) + source + "\n}}\n";
+ int scriptLines = Math.max(1, (int) source.lines().count());
+
+ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
+ Map<String, ByteArrayOutputStream> classes = new HashMap<>();
+ boolean ok;
+ synchronized (compiler) {
+ if (files == null) files = compiler.getStandardFileManager(null, Locale.ROOT, StandardCharsets.UTF_8);
+ List<String> options = List.of("-g", "-proc:none", "-classpath", System.getProperty("java.class.path", ""));
+ ok = compiler.getTask(new StringWriter(), new MemoryFiles(files, classes), diagnostics, options, null,
+ List.of(new Source(className, full))).call();
+ }
+ if (!ok) {
+ Set<String> errors = new LinkedHashSet<>();
+ for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
+ if (d.getKind() != Diagnostic.Kind.ERROR) continue;
+ long line = Math.max(1, Math.min(scriptLines, d.getLineNumber() - HEADER_LINES));
+ errors.add("line " + line + ": " + summary(d.getMessage(Locale.ROOT)));
+ }
+ if (errors.isEmpty()) errors.add("line 1: the script did not compile");
+ return new Compiled(null, null, List.copyOf(errors));
+ }
+ int exitAt = exitCall(classes.values());
+ if (exitAt > 0) {
+ return new Compiled(null, null, List.of("line " + Math.max(1, Math.min(scriptLines, exitAt - HEADER_LINES)) + ": " + EXIT_MESSAGE));
+ }
+ try {
+ ClassLoader loader = new MemoryLoader(classes, ScriptCompiler.class.getClassLoader());
+ CustomActionFn fn = (CustomActionFn) loader.loadClass(className).getDeclaredConstructor().newInstance();
+ return new Compiled(fn, className, List.of());
+ } catch (ReflectiveOperationException | LinkageError e) {
+ return new Compiled(null, null, List.of("line 1: the script could not be loaded: " + e));
+ }
+ }
+
+ /**
+ * The generated line of a call that would end the whole program
+ * (System.exit, Runtime.exit or Runtime.halt), or 0. Read from the
+ * compiled code, so a comment or a string that names them does not count.
+ */
+ private static int exitCall(Iterable<ByteArrayOutputStream> classes) {
+ for (ByteArrayOutputStream b : classes) {
+ for (MethodModel m : ClassFile.of().parse(b.toByteArray()).methods()) {
+ if (m.code().isEmpty()) continue;
+ int line = 0;
+ for (CodeElement e : m.code().get()) {
+ if (e instanceof LineNumber ln) line = ln.line();
+ if (e instanceof InvokeInstruction call) {
+ String owner = call.owner().asInternalName(), name = call.name().stringValue();
+ if (owner.equals("java/lang/System") && name.equals("exit")
+ || owner.equals("java/lang/Runtime") && (name.equals("exit") || name.equals("halt"))) {
+ return Math.max(1, line);
+ }
+ }
+ }
+ }
+ }
+ return 0;
+ }
+
+ /** javac's first line, with the name it could not find when it gives one. */
+ private static String summary(String message) {
+ List<String> lines = message.lines().toList();
+ String first = lines.isEmpty() ? "error" : lines.get(0).strip();
+ for (String l : lines) {
+ String t = l.strip();
+ if (t.startsWith("symbol:")) return first + " (" + t.substring(7).strip().replace("java.lang.", "") + ")";
+ }
+ return first;
+ }
+
+ private static String sha256(String s) {
+ try {
+ return Bytes.toHex(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /** The generated source, held in memory. */
+ private static final class Source extends SimpleJavaFileObject {
+ private final String code;
+ Source(String className, String code) {
+ super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
+ this.code = code;
+ }
+ @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; }
+ }
+
+ /** Class files written to memory instead of disk. */
+ private static final class MemoryFiles extends ForwardingJavaFileManager<JavaFileManager> {
+ private final Map<String, ByteArrayOutputStream> classes;
+ MemoryFiles(JavaFileManager standard, Map<String, ByteArrayOutputStream> classes) {
+ super(standard);
+ this.classes = classes;
+ }
+ @Override public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) {
+ return new SimpleJavaFileObject(URI.create("mem:///" + className.replace('.', '/') + kind.extension), kind) {
+ @Override public OutputStream openOutputStream() {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ classes.put(className, out);
+ return out;
+ }
+ };
+ }
+ // The standard manager is shared by every compile; this wrapper must not close it.
+ @Override public void close() { }
+ }
+
+ /** Loads one script's classes; everything else comes from the suite. */
+ private static final class MemoryLoader extends ClassLoader {
+ private final Map<String, ByteArrayOutputStream> classes;
+ MemoryLoader(Map<String, ByteArrayOutputStream> classes, ClassLoader parent) {
+ super(parent);
+ this.classes = classes;
+ }
+ @Override protected Class<?> findClass(String name) throws ClassNotFoundException {
+ ByteArrayOutputStream b = classes.get(name);
+ if (b == null) throw new ClassNotFoundException(name);
+ byte[] bytes = b.toByteArray();
+ return defineClass(name, bytes, 0, bytes.length);
+ }
+ }
+}
diff --git a/src/opensuite/script/ScriptEngine.java b/src/opensuite/script/ScriptEngine.java
new file mode 100644
index 0000000..e258eae
--- /dev/null
+++ b/src/opensuite/script/ScriptEngine.java
@@ -0,0 +1,127 @@
+package opensuite.script;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.Consumer;
+
+import javax.tools.JavaCompiler;
+import javax.tools.ToolProvider;
+
+import opensuite.core.Debug;
+import opensuite.core.HttpMessage;
+import opensuite.core.HttpService;
+import opensuite.script.api.HttpRequest;
+import opensuite.script.api.HttpRequestResponse;
+import opensuite.script.api.HttpResponse;
+import opensuite.script.api.Utilities;
+
+/**
+ * Compiles and runs the script library's scripts for the whole suite, one run
+ * at a time, never on the caller's thread and within a time limit.
+ */
+public final class ScriptEngine {
+
+ private static final long TIMEOUT_MILLIS = 10_000;
+ private static final String STILL_RUNNING = "; it is still running, restart Open Suite to stop it";
+
+ private final ScriptCompiler compiler;
+ private final ScriptRunner runner;
+ private final ReentrantLock oneAtATime = new ReentrantLock(true);
+ private final AtomicBoolean warmed = new AtomicBoolean();
+ private volatile Consumer<String> libraryOpener = name -> { };
+
+ public ScriptEngine() { this(ToolProvider.getSystemJavaCompiler(), TIMEOUT_MILLIS); }
+
+ /** @param compiler the Java compiler, or null when the runtime has none */
+ public ScriptEngine(JavaCompiler compiler, long timeoutMillis) {
+ this.compiler = new ScriptCompiler(compiler);
+ this.runner = new ScriptRunner(timeoutMillis);
+ }
+
+ public ScriptCompiler compiler() { return compiler; }
+
+ int abandonedThreads() { return runner.abandoned(); }
+
+ /** Load the compiler in the background, once, so the first run does not wait for it. */
+ public void warmUp() {
+ if (!compiler.available() || !warmed.compareAndSet(false, true)) return;
+ Thread t = new Thread(() -> compiler.compileCustomAction("int a = 0;"), "opensuite-script-warmup");
+ t.setDaemon(true);
+ t.start();
+ }
+
+ /** How the script library shows a script by name; set by the tool that holds the library. */
+ public void setLibraryOpener(Consumer<String> opener) { libraryOpener = opener; }
+
+ public void openInLibrary(String name) { libraryOpener.accept(name); }
+
+ /**
+ * Run a custom action on copies of a request and its response. Blocks until
+ * the run ends, so call it off the event thread. It never throws.
+ *
+ * @param response the response beside the request, or null
+ * @param clipboard where the script's clipboard text goes
+ * @param stop set to end this run; a stop given before the run starts is kept
+ */
+ public RunResult runCustomAction(String source, HttpService svc, HttpMessage request, HttpMessage response,
+ Consumer<String> clipboard, AtomicBoolean stop) {
+ try {
+ return run(source, svc, request, response, clipboard, stop);
+ } catch (RuntimeException | LinkageError e) {
+ Debug.error("script engine failed", e);
+ return RunResult.failed(RunResult.Status.FAILED, "internal error: " + describe(e, null));
+ }
+ }
+
+ private RunResult run(String source, HttpService svc, HttpMessage request, HttpMessage response,
+ Consumer<String> clipboard, AtomicBoolean stop) {
+ oneAtATime.lock();
+ try {
+ if (runner.abandoned() >= ScriptRunner.MAX_ABANDONED) {
+ return RunResult.failed(RunResult.Status.FAILED, ScriptRunner.MAX_ABANDONED
+ + " scripts are still running and could not be stopped; restart Open Suite to stop them");
+ }
+ if (stop.get()) return RunResult.failed(RunResult.Status.STOPPED, "stopped");
+ Compiled c = compiler.compileCustomAction(source);
+ if (!c.ok()) return RunResult.failed(RunResult.Status.FAILED, String.join("\n", c.errors()));
+ if (stop.get()) return RunResult.failed(RunResult.Status.STOPPED, "stopped");
+
+ HttpRequestResponse rr = new HttpRequestResponse(HttpRequest.of(svc, request),
+ response == null ? null : HttpResponse.of(response));
+ Utilities utilities = new Utilities(clipboard);
+ Throwable[] thrown = new Throwable[1];
+ int abandonedBefore = runner.abandoned();
+ long start = System.nanoTime();
+ ScriptRunner.Outcome outcome = runner.run(() -> {
+ try {
+ c.fn().action(rr, utilities);
+ } catch (Throwable t) {
+ thrown[0] = t;
+ }
+ }, stop::get);
+ long millis = (System.nanoTime() - start) / 1_000_000;
+ String still = runner.abandoned() > abandonedBefore ? STILL_RUNNING : "";
+
+ RunResult.Status status = switch (outcome) {
+ case DONE -> thrown[0] == null ? RunResult.Status.OK : RunResult.Status.FAILED;
+ case TIMEOUT -> RunResult.Status.TIMEOUT;
+ case STOPPED -> RunResult.Status.STOPPED;
+ };
+ String error = switch (outcome) {
+ case DONE -> thrown[0] == null ? null : describe(thrown[0], c.className());
+ case TIMEOUT -> "stopped after " + Math.max(1, (runner.timeoutMillis() + 999) / 1000) + " s (time limit)" + still;
+ case STOPPED -> "stopped" + still;
+ };
+ HttpMessage newRequest = status == RunResult.Status.OK && rr.replacement() != null ? rr.replacement().message() : null;
+ return new RunResult(status, utilities.logLines(), utilities.logCut(), error, millis, newRequest);
+ } finally {
+ oneAtATime.unlock();
+ }
+ }
+
+ private static String describe(Throwable t, String className) {
+ int line = ScriptCompiler.scriptLine(className, t.getStackTrace());
+ return t.getClass().getSimpleName() + (t.getMessage() == null ? "" : ": " + t.getMessage())
+ + (line > 0 ? " at line " + line : "");
+ }
+}
diff --git a/src/opensuite/script/ScriptRunner.java b/src/opensuite/script/ScriptRunner.java
new file mode 100644
index 0000000..b4f296e
--- /dev/null
+++ b/src/opensuite/script/ScriptRunner.java
@@ -0,0 +1,55 @@
+package opensuite.script;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.function.BooleanSupplier;
+
+/**
+ * Runs a script on a thread of its own within a time limit. At the limit, or
+ * on a stop, the thread is interrupted; one that ignores that cannot be
+ * ended, so it is left running and counted.
+ */
+final class ScriptRunner {
+
+ static final int MAX_ABANDONED = 3;
+ private static final long GRACE_MILLIS = 1000;
+
+ enum Outcome { DONE, TIMEOUT, STOPPED }
+
+ private final long timeoutMillis;
+ private volatile int abandoned;
+
+ ScriptRunner(long timeoutMillis) { this.timeoutMillis = timeoutMillis; }
+
+ long timeoutMillis() { return timeoutMillis; }
+
+ /** Scripts that were stopped but would not end. */
+ int abandoned() { return abandoned; }
+
+ /** Run {@code body} and wait for it, until the limit or until {@code stopped} is true. */
+ Outcome run(Runnable body, BooleanSupplier stopped) {
+ CountDownLatch done = new CountDownLatch(1);
+ Thread t = new Thread(() -> {
+ try { body.run(); } finally { done.countDown(); }
+ }, "opensuite-script");
+ t.setDaemon(true);
+ t.start();
+
+ long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
+ try {
+ while (!done.await(25, TimeUnit.MILLISECONDS)) {
+ boolean stop = stopped.getAsBoolean();
+ if (stop || System.nanoTime() >= deadline) {
+ t.interrupt();
+ if (!done.await(GRACE_MILLIS, TimeUnit.MILLISECONDS)) abandoned++;
+ return stop ? Outcome.STOPPED : Outcome.TIMEOUT;
+ }
+ }
+ } catch (InterruptedException e) {
+ t.interrupt();
+ Thread.currentThread().interrupt();
+ return Outcome.STOPPED;
+ }
+ return Outcome.DONE;
+ }
+}
diff --git a/src/opensuite/script/api/HttpRequest.java b/src/opensuite/script/api/HttpRequest.java
new file mode 100644
index 0000000..32b8cbd
--- /dev/null
+++ b/src/opensuite/script/api/HttpRequest.java
@@ -0,0 +1,95 @@
+package opensuite.script.api;
+
+import java.util.List;
+import java.util.function.Consumer;
+
+import opensuite.core.HttpMessage;
+import opensuite.core.HttpService;
+import opensuite.core.Param;
+
+/**
+ * A request as a script sees it. It never changes: each {@code with...} method
+ * returns a new request, so a script that fails half way has changed nothing.
+ * A request that is not changed keeps its exact bytes.
+ */
+public final class HttpRequest {
+
+ private final HttpService service;
+ private final HttpMessage message;
+
+ private HttpRequest(HttpService service, HttpMessage message) {
+ this.service = service;
+ this.message = message;
+ }
+
+ /** A request over a copy of {@code m}. */
+ public static HttpRequest of(HttpService service, HttpMessage m) {
+ return new HttpRequest(service, m == null ? new HttpMessage(new byte[0]) : m.copy());
+ }
+
+ /** A copy of the request's bytes. */
+ public HttpMessage message() { return message.copy(); }
+
+ /** Where the request is sent; null when there is no target yet. */
+ public HttpService service() { return service; }
+
+ public String method() { return message.method(); }
+
+ /** The path, without the query string. */
+ public String path() { return message.path(); }
+
+ /** The query string without its "?", or "". */
+ public String query() { return message.query(); }
+
+ public String url() {
+ String target = message.requestTarget();
+ if (target.startsWith("http://") || target.startsWith("https://")) return target;
+ return (service == null ? "" : service.url()) + target;
+ }
+
+ /** The first header with this name (any case), or null. */
+ public String header(String name) { return message.header(name); }
+
+ /** The header lines, without the request line. */
+ public List<String> headers() { return Messages.headers(message); }
+
+ /** The body's exact bytes. */
+ public byte[] body() { return message.body(); }
+
+ /** The body as text, in the declared charset or else UTF-8. */
+ public String bodyText() { return Messages.bodyText(message); }
+
+ public List<Param> parameters() { return message.parameters(); }
+
+ /** This request with the header set, replacing any of that name. */
+ public HttpRequest withHeader(String name, String value) { return edit(m -> m.setHeader(name, value)); }
+
+ public HttpRequest withRemovedHeader(String name) { return edit(m -> m.removeHeader(name)); }
+
+ /** This request with a new body and a matching Content-Length. */
+ public HttpRequest withBody(byte[] body) {
+ return edit(m -> {
+ m.setBody(body == null ? new byte[0] : body.clone());
+ m.updateContentLength();
+ });
+ }
+
+ /** This request with a new body as text, encoded as {@link #bodyText()} decodes. */
+ public HttpRequest withBody(String body) {
+ return withBody((body == null ? "" : body).getBytes(Messages.charset(message)));
+ }
+
+ public HttpRequest withMethod(String method) { return edit(m -> m.setMethod(method)); }
+
+ /** This request with a new path; the query string is kept unless {@code path} has one. */
+ public HttpRequest withPath(String path) {
+ String q = message.query();
+ return edit(m -> m.setRequestTarget(path.contains("?") || q.isEmpty() ? path : path + "?" + q));
+ }
+
+ private HttpRequest edit(Consumer<HttpMessage> change) {
+ HttpMessage m = message.copy();
+ change.accept(m);
+ return new HttpRequest(service, m);
+ }
+}
diff --git a/src/opensuite/script/api/HttpRequestResponse.java b/src/opensuite/script/api/HttpRequestResponse.java
new file mode 100644
index 0000000..ab79bf4
--- /dev/null
+++ b/src/opensuite/script/api/HttpRequestResponse.java
@@ -0,0 +1,32 @@
+package opensuite.script.api;
+
+/**
+ * What a custom action is run on: the request being edited and, when there is
+ * one, the response shown beside it. An action changes the request by handing
+ * a new one to {@link #setRequest}; it takes effect only if the action ends
+ * without an error.
+ */
+public final class HttpRequestResponse {
+
+ private final HttpRequest request;
+ private final HttpResponse response;
+ private HttpRequest replacement;
+
+ public HttpRequestResponse(HttpRequest request, HttpResponse response) {
+ this.request = request;
+ this.response = response;
+ }
+
+ public HttpRequest request() { return request; }
+
+ /** The response, or null when there is none yet. */
+ public HttpResponse response() { return response; }
+
+ public boolean hasResponse() { return response != null; }
+
+ /** Put {@code changed} in place of the request being edited, once the action has ended. */
+ public void setRequest(HttpRequest changed) { this.replacement = changed; }
+
+ /** The request handed to {@link #setRequest}, or null. */
+ public HttpRequest replacement() { return replacement; }
+}
diff --git a/src/opensuite/script/api/HttpResponse.java b/src/opensuite/script/api/HttpResponse.java
new file mode 100644
index 0000000..10b81bb
--- /dev/null
+++ b/src/opensuite/script/api/HttpResponse.java
@@ -0,0 +1,35 @@
+package opensuite.script.api;
+
+import java.util.List;
+
+import opensuite.core.HttpMessage;
+
+/** A response as a script sees it: read only, over a copy of the shown response. */
+public final class HttpResponse {
+
+ private final HttpMessage message;
+
+ private HttpResponse(HttpMessage message) { this.message = message; }
+
+ /** A response over a copy of {@code m}. */
+ public static HttpResponse of(HttpMessage m) {
+ return new HttpResponse(m == null ? new HttpMessage(new byte[0]) : m.copy());
+ }
+
+ public int statusCode() { return message.statusCode(); }
+
+ /** The first header with this name (any case), or null. */
+ public String header(String name) { return message.header(name); }
+
+ /** The header lines, without the status line. */
+ public List<String> headers() { return Messages.headers(message); }
+
+ /** The body's exact bytes. */
+ public byte[] body() { return message.body(); }
+
+ /** The body as text, in the declared charset or else UTF-8. */
+ public String bodyText() { return Messages.bodyText(message); }
+
+ /** The body's type in the history's terms, such as "json" or "html". */
+ public String mimeType() { return message.mimeType(); }
+}
diff --git a/src/opensuite/script/api/Messages.java b/src/opensuite/script/api/Messages.java
new file mode 100644
index 0000000..667925c
--- /dev/null
+++ b/src/opensuite/script/api/Messages.java
@@ -0,0 +1,26 @@
+package opensuite.script.api;
+
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+import opensuite.core.HttpMessage;
+
+/** What the request and the response read from a message in the same way. */
+final class Messages {
+
+ private Messages() {}
+
+ static List<String> headers(HttpMessage m) { return List.copyOf(m.headerLines()); }
+
+ static String bodyText(HttpMessage m) { return new String(m.body(), charset(m)); }
+
+ /** The declared charset when Java knows it, else UTF-8. */
+ static Charset charset(HttpMessage m) {
+ String name = m.charsetName();
+ if (!name.isEmpty()) {
+ try { return Charset.forName(name); } catch (RuntimeException ignored) { }
+ }
+ return StandardCharsets.UTF_8;
+ }
+}
diff --git a/src/opensuite/script/api/Utilities.java b/src/opensuite/script/api/Utilities.java
new file mode 100644
index 0000000..51b4420
--- /dev/null
+++ b/src/opensuite/script/api/Utilities.java
@@ -0,0 +1,89 @@
+package opensuite.script.api;
+
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.MessageDigest;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.function.Consumer;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+import opensuite.core.Bytes;
+
+/**
+ * The helpers a script is given: output, the clipboard, encodings and hashes.
+ * Hashes take and return bytes, so a signature covers exactly the bytes sent.
+ */
+public final class Utilities {
+
+ /** The most a run keeps of its output. */
+ public static final int MAX_LINES = 1000, MAX_CHARS = 64 * 1024;
+
+ private final Consumer<String> clipboard;
+ private final List<String> log = new ArrayList<>();
+ private int chars;
+ private boolean cut;
+
+ /** @param clipboard where {@link #clipboard(String)} puts its text */
+ public Utilities(Consumer<String> clipboard) { this.clipboard = clipboard; }
+
+ /** Add a line to the action's output; a line past the limit is kept up to it. */
+ public synchronized void log(Object value) {
+ if (cut || log.size() >= MAX_LINES) { cut = true; return; }
+ String s = String.valueOf(value);
+ if (chars + s.length() > MAX_CHARS) { s = s.substring(0, MAX_CHARS - chars); cut = true; }
+ log.add(s);
+ chars += s.length();
+ }
+
+ /** A copy of the output so far. */
+ public synchronized List<String> logLines() { return List.copyOf(log); }
+
+ /** True when output past the limit was dropped. */
+ public synchronized boolean logCut() { return cut; }
+
+ public void clipboard(String text) { clipboard.accept(text == null ? "" : text); }
+
+ /** UTF-8 bytes of {@code s}. */
+ public byte[] bytes(String s) { return (s == null ? "" : s).getBytes(StandardCharsets.UTF_8); }
+
+ public byte[] concat(byte[]... parts) { return Bytes.concat(parts); }
+
+ /** Lower-case hexadecimal. */
+ public String hex(byte[] b) { return Bytes.toHex(b); }
+
+ public String base64Encode(byte[] b) { return Base64.getEncoder().encodeToString(b); }
+
+ public byte[] base64Decode(String s) { return Base64.getDecoder().decode(s.strip()); }
+
+ public String urlEncode(String s) { return URLEncoder.encode(s, StandardCharsets.UTF_8); }
+
+ public String urlDecode(String s) { return URLDecoder.decode(s, StandardCharsets.UTF_8); }
+
+ public byte[] sha256(byte[] data) { return digest("SHA-256", data); }
+
+ public byte[] md5(byte[] data) { return digest("MD5", data); }
+
+ public byte[] hmacSha256(byte[] key, byte[] data) {
+ try {
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(new SecretKeySpec(key, "HmacSHA256"));
+ return mac.doFinal(data);
+ } catch (GeneralSecurityException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ private static byte[] digest(String algorithm, byte[] data) {
+ try {
+ return MessageDigest.getInstance(algorithm).digest(data);
+ } catch (GeneralSecurityException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+}
diff --git a/src/opensuite/ui/CustomActionsPanel.java b/src/opensuite/ui/CustomActionsPanel.java
index 1152140..3c62005 100644
--- a/src/opensuite/ui/CustomActionsPanel.java
+++ b/src/opensuite/ui/CustomActionsPanel.java
@@ -4,22 +4,49 @@ import javax.swing.*;
import java.awt.*;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import opensuite.core.Debug;
+import opensuite.core.HttpMessage;
+import opensuite.core.HttpService;
+import opensuite.core.SuiteContext;
+import opensuite.script.RequestDiff;
+import opensuite.script.RunResult;
+import opensuite.script.Samples;
/**
* The "Custom actions" side panel of a message editor: scripts that act on
* the shown request or response. Empty until some exist, with Add samples,
- * Load and New; populated, a list of the actions with Run beside each.
- * Actions are scripts of the custom-action function in the script library
- * (Extensions > Script library), so one place manages them.
+ * Load and New; populated, a list of the actions with Run, and the output of
+ * each run. Actions are scripts of the custom-action function in the script
+ * library (Extensions > Script library), so one place manages them.
+ *
+ * <p>An action runs on copies of the request being edited and the response
+ * beside it. A request it hands back replaces the edited one as a single
+ * undoable change. An action never sends anything.
*/
public final class CustomActionsPanel extends JPanel {
private static Path dir() { return Path.of(System.getProperty("user.home", "."), ".opensuite", "scripts", "custom-action"); }
+ private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HH:mm:ss");
+
+ private final MessageEditor host;
private final CardLayout cards = new CardLayout();
private final DefaultListModel<String> model = new DefaultListModel<>();
+ private final JList<String> list = new JList<>(model);
+ private final JButton run = Ui.primaryButton("Run", "run the selected action on this message");
+ private final JTextArea output = new JTextArea(8, 20);
+ private String lastRun;
+ private AtomicBoolean stop; // the run under way, or null
- public CustomActionsPanel() {
+ /** @param host the editor this panel belongs to; actions work on its request source */
+ public CustomActionsPanel(MessageEditor host) {
+ this.host = host;
setLayout(cards);
setOpaque(false);
@@ -38,14 +65,8 @@ public final class CustomActionsPanel extends JPanel {
load.addActionListener(e -> load());
JButton neu = Ui.button("New", "Create a custom action");
neu.setIcon(Glyphs.plus(14, Theme.ICON));
- neu.addActionListener(e -> goToLibrary());
- JLabel learn = new JLabel("<html><u>Learn more</u></html>");
- learn.setFont(Ui.PLAIN);
- learn.setForeground(new Color(0x1A, 0x5F, 0xB4));
- learn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
- learn.addMouseListener(new java.awt.event.MouseAdapter() {
- @Override public void mouseClicked(java.awt.event.MouseEvent e) { Unbuilt.openProject(CustomActionsPanel.this); }
- });
+ neu.addActionListener(e -> goToLibrary(null));
+ JComponent learn = CustomScopePanel.link("Learn more", () -> Unbuilt.openProject(CustomActionsPanel.this));
for (JComponent c : new JComponent[]{icon, h, t, samples, Ui.row(load, neu), learn}) {
c.setAlignmentX(Component.CENTER_ALIGNMENT);
col.add(c);
@@ -56,59 +77,155 @@ public final class CustomActionsPanel extends JPanel {
empty.add(col, new GridBagConstraints());
add(empty, "empty");
- JList<String> list = new JList<>(model);
list.setFont(Ui.PLAIN);
list.setFixedCellHeight(26);
- JButton run = Ui.primaryButton("Run", "run the selected action on this message");
- run.addActionListener(e -> {
- String n = list.getSelectedValue();
- // Nothing runs a saved action yet, so it does not say that one ran.
- if (n != null) Unbuilt.MSG_CUSTOMACTION.showDialog(this);
- });
+ run.addActionListener(e -> { if (stop != null) stop.set(true); else runSelected(); });
JButton edit = Ui.button("Edit");
- edit.addActionListener(e -> goToLibrary());
+ edit.addActionListener(e -> goToLibrary(list.getSelectedValue()));
JButton more = Ui.button("Load");
more.addActionListener(e -> load());
- JPanel full = new JPanel(new BorderLayout(0, 6));
+
+ output.setEditable(false);
+ output.setFont(Ui.MONO);
+ output.setLineWrap(true);
+ JPanel links = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
+ links.setOpaque(false);
+ links.add(CustomScopePanel.link("edit script", () -> goToLibrary(lastRun)));
+ links.add(CustomScopePanel.link("clear", () -> output.setText("")));
+ JPanel outHead = new JPanel(new BorderLayout());
+ outHead.setOpaque(false);
+ outHead.add(Ui.bold("output"), BorderLayout.WEST);
+ outHead.add(links, BorderLayout.EAST);
+ JPanel out = new JPanel(new BorderLayout(0, 4));
+ out.setOpaque(false);
+ out.add(outHead, BorderLayout.NORTH);
+ out.add(Ui.scroll(output), BorderLayout.CENTER);
+
+ JPanel top = new JPanel(new BorderLayout(0, 6));
+ top.setOpaque(false);
+ top.add(Ui.scroll(list), BorderLayout.CENTER);
+ top.add(Ui.row(run, edit, more), BorderLayout.SOUTH);
+ JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, top, out);
+ split.setBorder(null);
+ split.setOpaque(false);
+ split.setResizeWeight(0.5);
+
+ JPanel full = new JPanel(new BorderLayout());
full.setOpaque(false);
full.setBorder(Ui.pad(8, 8, 8, 8));
- full.add(Ui.scroll(list), BorderLayout.CENTER);
- full.add(Ui.row(run, edit, more), BorderLayout.SOUTH);
+ full.add(split, BorderLayout.CENTER);
add(full, "list");
reload();
}
+ /** The compiler loads in the background once the panel is first shown, so the first run is quick. */
+ @Override public void addNotify() {
+ super.addNotify();
+ if (host.context() != null) host.context().scripts().warmUp();
+ }
+
+ private void runSelected() {
+ if (list.getSelectedValue() == null && !model.isEmpty()) list.setSelectedIndex(0);
+ String name = list.getSelectedValue();
+ SuiteContext ctx = host.context();
+ if (name == null || ctx == null) return;
+ String source;
+ try {
+ source = Files.readString(dir().resolve(name + ".java"));
+ } catch (java.io.IOException e) {
+ append(name, List.of(" failed: the script could not be read: " + e.getMessage()));
+ return;
+ }
+ MessageEditor src = host.requestSource();
+ HttpService svc = src.service();
+ HttpMessage request = src.message().copy();
+ HttpMessage response = host != src && host.message().raw().length > 0 ? host.message().copy() : null;
+
+ AtomicBoolean thisRun = new AtomicBoolean();
+ stop = thisRun;
+ lastRun = name;
+ setRunning(true);
+ Thread t = new Thread(() -> {
+ RunResult r = ctx.scripts().runCustomAction(source, svc, request, response, CustomActionsPanel::toClipboard, thisRun);
+ SwingUtilities.invokeLater(() -> finish(name, request, r));
+ }, "opensuite-script-call");
+ t.setDaemon(true);
+ t.start();
+ }
+
+ private void finish(String action, HttpMessage before, RunResult r) {
+ stop = null;
+ setRunning(false);
+ List<String> lines = new ArrayList<>();
+ for (String l : r.log()) lines.add(" " + l);
+ if (r.logCut()) lines.add(" [output cut at 1000 lines / 64 KB]");
+ if (r.status() != RunResult.Status.OK) {
+ String[] err = r.error().split("\n");
+ lines.add(" failed: " + err[0]);
+ for (int i = 1; i < err.length; i++) lines.add(" " + err[i]);
+ } else {
+ List<String> changes = r.newRequest() == null ? List.of() : RequestDiff.summarise(before, r.newRequest());
+ if (!changes.isEmpty()) {
+ host.requestSource().replaceMessageUndoably(r.newRequest());
+ lines.add(" request changed:");
+ for (String c : changes) lines.add(" " + c);
+ }
+ lines.add(" ok in " + r.millis() + " ms");
+ }
+ append(action, lines);
+ }
+
+ private void setRunning(boolean on) {
+ run.setText(on ? "Stop" : "Run");
+ run.setToolTipText(on ? "stop the action that is running" : "run the selected action on this message");
+ }
+
+ private void append(String action, List<String> lines) {
+ StringBuilder sb = new StringBuilder();
+ if (output.getDocument().getLength() > 0) sb.append('\n');
+ sb.append(LocalTime.now().format(TIME)).append(" ").append(action).append('\n');
+ for (String l : lines) sb.append(l).append('\n');
+ output.append(sb.toString());
+ output.setCaretPosition(output.getDocument().getLength());
+ }
+
+ private static void toClipboard(String text) {
+ SwingUtilities.invokeLater(() -> {
+ try {
+ MessageActions.clip(text);
+ } catch (RuntimeException e) {
+ Debug.error("custom action: the clipboard could not be set", e);
+ }
+ });
+ }
+
private void reload() {
+ String selected = list.getSelectedValue();
model.clear();
if (Files.isDirectory(dir())) {
try (var ds = Files.newDirectoryStream(dir(), "*.java")) {
for (Path p : ds) model.addElement(p.getFileName().toString().replaceAll("\\.java$", ""));
} catch (java.io.IOException ignore) { }
}
+ if (selected != null) list.setSelectedValue(selected, true);
cards.show(this, model.isEmpty() ? "empty" : "list");
}
private void addSamples() {
try {
Files.createDirectories(dir());
- write("Add a header", "// void action(HttpRequestResponse requestResponse, Utilities utilities)\n"
- + "requestResponse.request().withAddedHeader(\"X-Custom\", \"1\");\n");
- write("Copy response body", "// void action(HttpRequestResponse requestResponse, Utilities utilities)\n"
- + "utilities.clipboard(requestResponse.response().body());\n");
- write("Log status code", "// void action(HttpRequestResponse requestResponse, Utilities utilities)\n"
- + "utilities.log(\"Status: \" + requestResponse.response().statusCode());\n");
+ for (var e : Samples.CUSTOM_ACTIONS.entrySet()) {
+ Path f = dir().resolve(e.getKey() + ".java");
+ if (!Files.exists(f)) Files.writeString(f, e.getValue());
+ }
} catch (java.io.IOException e) {
JOptionPane.showMessageDialog(this, "Could not write the samples: " + e.getMessage(), "Add samples", JOptionPane.ERROR_MESSAGE);
}
}
- private void write(String name, String body) throws java.io.IOException {
- Path f = dir().resolve(name + ".java");
- if (!Files.exists(f)) Files.writeString(f, body);
- }
-
private void load() {
JFileChooser fc = new opensuite.ui.FileChooser();
+ fc.setDialogTitle("Load a script (scripts run with your permissions; load only code you trust)");
if (fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
try {
Files.createDirectories(dir());
@@ -121,7 +238,9 @@ public final class CustomActionsPanel extends JPanel {
reload();
}
- private void goToLibrary() {
+ /** Open the script library, on {@code script} when one is named. */
+ private void goToLibrary(String script) {
+ if (script != null && host.context() != null) { host.context().scripts().openInLibrary(script); return; }
for (Frame f : Frame.getFrames()) if (f instanceof SuiteFrame sf) { sf.selectTool("extensions"); break; }
}
}
diff --git a/src/opensuite/ui/CustomScopePanel.java b/src/opensuite/ui/CustomScopePanel.java
index 799e267..e397b02 100644
--- a/src/opensuite/ui/CustomScopePanel.java
+++ b/src/opensuite/ui/CustomScopePanel.java
@@ -56,7 +56,7 @@ public final class CustomScopePanel extends JPanel {
add(links, BorderLayout.SOUTH);
}
- private static JComponent link(String text, Runnable action) {
+ static JComponent link(String text, Runnable action) {
JLabel l = new JLabel("<html><u>" + text + "</u></html>");
l.setFont(Ui.PLAIN);
l.setForeground(new Color(0x1A, 0x5F, 0xB4));
diff --git a/src/opensuite/ui/EditorKeys.java b/src/opensuite/ui/EditorKeys.java
index 358d4aa..9fb52ac 100644
--- a/src/opensuite/ui/EditorKeys.java
+++ b/src/opensuite/ui/EditorKeys.java
@@ -2,6 +2,7 @@ package opensuite.ui;
import javax.swing.*;
import javax.swing.text.JTextComponent;
+import javax.swing.undo.CompoundEdit;
import javax.swing.undo.UndoManager;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
@@ -21,13 +22,36 @@ public final class EditorKeys {
private static final int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();
+ /** A component's undo history, and while set, the group its edits gather in instead. */
+ private static final String UNDO = "opensuite.undo", GROUP = "opensuite.undo.group";
+
+ /**
+ * Make the edits {@code change} makes to {@code c} one step in its undo
+ * history, so a single Ctrl+Z takes them all back.
+ */
+ public static void asOneEdit(JTextComponent c, Runnable change) {
+ CompoundEdit group = new CompoundEdit();
+ c.putClientProperty(GROUP, group);
+ try {
+ change.run();
+ } finally {
+ c.putClientProperty(GROUP, null);
+ group.end();
+ if (group.canUndo() && c.getClientProperty(UNDO) instanceof UndoManager undo) undo.addEdit(group);
+ }
+ }
+
/** Install undo/redo (Ctrl+Z / Ctrl+Y) and delete-line (Ctrl+D) on an editable component. */
public static void install(JTextComponent c) {
if (!c.isEditable()) return;
UndoManager undo = new UndoManager();
undo.setLimit(500);
- c.getDocument().addUndoableEditListener(undo);
+ c.getDocument().addUndoableEditListener(e -> {
+ if (c.getClientProperty(GROUP) instanceof CompoundEdit group) group.addEdit(e.getEdit());
+ else undo.addEdit(e.getEdit());
+ });
+ c.putClientProperty(UNDO, undo);
InputMap im = c.getInputMap();
ActionMap am = c.getActionMap();
diff --git a/src/opensuite/ui/MessageEditor.java b/src/opensuite/ui/MessageEditor.java
index fe30314..1a86817 100644
--- a/src/opensuite/ui/MessageEditor.java
+++ b/src/opensuite/ui/MessageEditor.java
@@ -192,7 +192,7 @@ public class MessageEditor extends JPanel {
private final JPanel flyout = new JPanel(new BorderLayout());
private final JTextArea notesArea = new JTextArea();
private VerticalTab inspectorBtn, notesBtn, actionsBtn;
- private final CustomActionsPanel customActions = new CustomActionsPanel();
+ private final CustomActionsPanel customActions = new CustomActionsPanel(this);
private final List<ActionProvider> providers = new ArrayList<>();
private boolean updating;
@@ -885,6 +885,36 @@ public class MessageEditor extends JPanel {
public HttpService service() { return service; }
public byte[] bytes() { return message.raw(); }
+ /** The context this editor was given; null for a viewer not yet given one. */
+ SuiteContext context() { return ctx; }
+
+ /** The editor holding the request a custom action works on: the paired request editor, or this one. */
+ MessageEditor requestSource() { return paired != null ? paired : this; }
+
+ /**
+ * Show {@code m} as one change that a single undo takes back. A text view
+ * has its text replaced and the message takes {@code m}'s exact bytes;
+ * any other view simply shows {@code m}.
+ */
+ void replaceMessageUndoably(HttpMessage m) {
+ Component shown = views.getSelectedComponent();
+ if (!editable || !(shown == prettyView || shown == rawView || shown == null)) { setMessage(service, m); return; }
+ JTextComponent t = activeText();
+ updating = true;
+ try {
+ EditorKeys.asOneEdit(t, () -> {
+ t.setText(textOf(m));
+ // Colouring is recorded by the undo history too; done here, it is part of the same step.
+ if (t == prettyPane) applySyntax();
+ });
+ } finally {
+ updating = false;
+ }
+ t.setCaretPosition(0);
+ message = m.copy();
+ messageChanged();
+ }
+
/**
* The charset the message's text is shown in.
*
@@ -1255,6 +1285,11 @@ public class MessageEditor extends JPanel {
// Re-colour after the current document notification completes, to avoid
// "mutate in notification" from changing attributes mid-edit.
if (activeText() == prettyPane) SwingUtilities.invokeLater(this::reSyntax);
+ messageChanged();
+ }
+
+ /** Tell everything that follows the message that it has changed. */
+ private void messageChanged() {
inspector.rebuild();
for (Runnable r : messageListeners) r.run();
updateSelectionLabel();
diff --git a/src/opensuite/ui/Unbuilt.java b/src/opensuite/ui/Unbuilt.java
index bcbb4e9..ca597f1 100644
--- a/src/opensuite/ui/Unbuilt.java
+++ b/src/opensuite/ui/Unbuilt.java
@@ -51,7 +51,6 @@ public final class Unbuilt {
public static final Unbuilt EXT_STORE = of("OT-EXT-STORE", "Extensions > Store > Installing an add-on from inside the suite");
public static final Unbuilt EXT_SCANCHECK = of("OT-EXT-SCANCHECK", "Extensions > Custom scan checks > Running saved checks during an audit");
public static final Unbuilt EXT_SCRIPTS = of("OT-EXT-SCRIPTS", "Extensions > Script library > Running saved scripts from the tools");
- public static final Unbuilt MSG_CUSTOMACTION = of("OT-MSG-CUSTOMACTION", "Message editor > Custom actions > Running an action on the shown message");
public static final Unbuilt DECODER_BROTLI = of("OT-DECODER-BROTLI", "Decoder > Encoding as brotli");
diff --git a/tests/RunTests.java b/tests/RunTests.java
index 11ff5fe..79e2061 100644
--- a/tests/RunTests.java
+++ b/tests/RunTests.java
@@ -118,6 +118,13 @@ public final class RunTests {
new opensuite.ui.EvidenceMarkTest().run();
new opensuite.core.SuiteContextRegistryTest().run();
new opensuite.extensions.ExtensionLoaderTest().run();
+ new opensuite.script.ScriptApiTest().run();
+ new opensuite.script.ScriptCompilerTest().run();
+ new opensuite.script.ScriptRunnerTest().run();
+ new opensuite.script.RequestDiffTest().run();
+ new opensuite.script.SamplesTest().run();
+ new opensuite.ui.CustomActionRunTest().run();
+ new opensuite.extensions.ScriptLibraryCheckTest().run();
System.exit(Harness.report());
}
diff --git a/tests/opensuite/extensions/ScriptLibraryCheckTest.java b/tests/opensuite/extensions/ScriptLibraryCheckTest.java
new file mode 100644
index 0000000..76e542f
--- /dev/null
+++ b/tests/opensuite/extensions/ScriptLibraryCheckTest.java
@@ -0,0 +1,49 @@
+package opensuite.extensions;
+
+import opensuite.script.ScriptCompiler;
+import opensuite.testkit.Expect;
+import opensuite.testkit.Harness;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import javax.swing.SwingUtilities;
+import javax.tools.ToolProvider;
+
+/** The script library opens a named custom action, and Check lists its compile errors in place. */
+public final class ScriptLibraryCheckTest {
+
+ public void run() {
+ Harness.suite("script library check");
+
+ Harness.test("reveal opens a script, and Check lists its errors", () -> {
+ String home = System.getProperty("user.home");
+ try {
+ Path tmp = Files.createTempDirectory("opensuite-library");
+ System.setProperty("user.home", tmp.toString());
+ Path dir = Files.createDirectories(ScriptLibraryPanel.root().resolve("custom-action"));
+ Files.writeString(dir.resolve("Bad.java"), "utilities.lg(1);\n");
+ Files.writeString(dir.resolve("Good.java"), "utilities.log(1);\n");
+
+ Object[] got = new Object[2];
+ SwingUtilities.invokeAndWait(() -> {
+ ScriptCompiler c = new ScriptCompiler(ToolProvider.getSystemJavaCompiler());
+ ScriptLibraryPanel p = new ScriptLibraryPanel(null, "t", "b", "e", "x",
+ source -> c.compileCustomAction(source).errors());
+ p.reveal("Bad");
+ got[0] = p.checkNow();
+ p.reveal("Good");
+ got[1] = p.checkNow();
+ });
+ @SuppressWarnings("unchecked") List<String> bad = (List<String>) got[0];
+ Expect.equal(bad.size(), 1, "one error: " + bad);
+ Expect.isTrue(bad.get(0).startsWith("line 1:"), "at line 1: " + bad);
+ Expect.equal(got[1], List.of(), "a clean script");
+ } catch (Exception e) {
+ throw new AssertionError(e);
+ } finally {
+ System.setProperty("user.home", home);
+ }
+ });
+ }
+}
diff --git a/tests/opensuite/script/RequestDiffTest.java b/tests/opensuite/script/RequestDiffTest.java
new file mode 100644
index 0000000..1e4a317
--- /dev/null
+++ b/tests/opensuite/script/RequestDiffTest.java
@@ -0,0 +1,39 @@
+package opensuite.script;
+
+import opensuite.core.Bytes;
+import opensuite.core.HttpMessage;
+import opensuite.testkit.Expect;
+import opensuite.testkit.Harness;
+
+import java.util.List;
+
+/** The short account of what an action changed in a request. */
+public final class RequestDiffTest {
+
+ private static HttpMessage m(String s) { return new HttpMessage(Bytes.bytes(s)); }
+
+ public void run() {
+ Harness.suite("request diff");
+
+ Harness.test("nothing changed is an empty list", () -> {
+ Expect.equal(RequestDiff.summarise(m("GET / HTTP/1.1\r\nHost: a\r\n\r\n"), m("GET / HTTP/1.1\r\nHost: a\r\n\r\n")), List.of(), "diff");
+ });
+
+ Harness.test("added, changed and removed headers, then the body", () -> {
+ HttpMessage before = m("POST /p HTTP/1.1\r\nHost: a\r\nX-Old: 1\r\nX-Ts: 1\r\n\r\nabc");
+ HttpMessage after = m("POST /p HTTP/1.1\r\nHost: a\r\nx-ts: 2\r\nX-Sig: f\r\n\r\nabcd");
+ Expect.equal(RequestDiff.summarise(before, after),
+ List.of("+ X-Sig", "~ x-ts", "- X-Old", "body 3 -> 4 bytes"), "diff");
+ });
+
+ Harness.test("a change to the first header is reported", () -> {
+ Expect.equal(RequestDiff.summarise(m("GET / HTTP/1.1\r\nHost: a\r\n\r\n"), m("GET / HTTP/1.1\r\nHost: b\r\n\r\n")),
+ List.of("~ Host"), "diff");
+ });
+
+ Harness.test("a new request line is reported", () -> {
+ Expect.equal(RequestDiff.summarise(m("GET /a HTTP/1.1\r\nHost: a\r\n\r\n"), m("POST /a HTTP/1.1\r\nHost: a\r\n\r\n")),
+ List.of("~ request line"), "diff");
+ });
+ }
+}
diff --git a/tests/opensuite/script/SamplesTest.java b/tests/opensuite/script/SamplesTest.java
new file mode 100644
index 0000000..6df3bdc
--- /dev/null
+++ b/tests/opensuite/script/SamplesTest.java
@@ -0,0 +1,46 @@
+package opensuite.script;
+
+import opensuite.core.Bytes;
+import opensuite.core.HttpMessage;
+import opensuite.core.HttpService;
+import opensuite.script.api.Utilities;
+import opensuite.testkit.Expect;
+import opensuite.testkit.Harness;
+
+import java.util.Map;
+import javax.tools.ToolProvider;
+
+/**
+ * The sample custom actions Open Suite offers compile against the script API
+ * as it is, and the re-signing sample signs what it says it signs.
+ */
+public final class SamplesTest {
+
+ public void run() {
+ Harness.suite("script samples");
+
+ Harness.test("every bundled sample compiles", () -> {
+ ScriptCompiler c = new ScriptCompiler(ToolProvider.getSystemJavaCompiler());
+ Expect.isTrue(Samples.CUSTOM_ACTIONS.size() >= 4, "samples offered");
+ for (Map.Entry<String, String> e : Samples.CUSTOM_ACTIONS.entrySet()) {
+ Expect.equal(c.compileCustomAction(e.getValue()).errors(), java.util.List.of(), e.getKey());
+ Expect.isTrue(e.getValue().startsWith("// void action(HttpRequestResponse requestResponse, Utilities utilities)"), "signature line in " + e.getKey());
+ }
+ });
+
+ Harness.test("the HMAC sample signs the timestamp and the body", () -> {
+ String raw = "POST /api HTTP/1.1\r\nHost: example.test\r\nContent-Length: 7\r\n\r\n{\"a\":1}";
+ RunResult r = new ScriptEngine(ToolProvider.getSystemJavaCompiler(), 5000).runCustomAction(
+ Samples.CUSTOM_ACTIONS.get("Re-sign request (HMAC)"), new HttpService("example.test", 443, true),
+ new HttpMessage(Bytes.bytes(raw)), null, s -> { }, new java.util.concurrent.atomic.AtomicBoolean());
+ Expect.equal(r.status(), RunResult.Status.OK, "status: " + r.error());
+ HttpMessage signed = r.newRequest();
+ String ts = signed.header("X-Timestamp");
+ Expect.notNull(ts, "timestamp");
+ Utilities u = new Utilities(s -> { });
+ String want = u.hex(u.hmacSha256(u.bytes("change-me"), u.concat(u.bytes(ts), signed.body())));
+ Expect.equal(signed.header("X-Signature"), want, "signature");
+ Expect.equal(Bytes.str(signed.body()), "{\"a\":1}", "body unchanged");
+ });
+ }
+}
diff --git a/tests/opensuite/script/ScriptApiTest.java b/tests/opensuite/script/ScriptApiTest.java
new file mode 100644
index 0000000..0cfbda6
--- /dev/null
+++ b/tests/opensuite/script/ScriptApiTest.java
@@ -0,0 +1,128 @@
+package opensuite.script;
+
+import opensuite.core.Bytes;
+import opensuite.core.HttpMessage;
+import opensuite.core.HttpService;
+import opensuite.script.api.HttpRequest;
+import opensuite.script.api.HttpRequestResponse;
+import opensuite.script.api.Utilities;
+import opensuite.testkit.Expect;
+import opensuite.testkit.Harness;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * The request, response and utilities a script works with: copies never touch
+ * the original, an untouched request keeps its exact bytes, and the hashes
+ * match published vectors.
+ */
+public final class ScriptApiTest {
+
+ private static final HttpService SVC = new HttpService("example.test", 443, true);
+
+ private static HttpRequest req(String raw) { return HttpRequest.of(SVC, new HttpMessage(Bytes.bytes(raw))); }
+ private static HttpRequest req(byte[] raw) { return HttpRequest.of(SVC, new HttpMessage(raw)); }
+ private static Utilities utils() { return new Utilities(s -> { }); }
+
+ public void run() {
+ Harness.suite("script api");
+
+ Harness.test("with methods return copies", () -> {
+ HttpRequest r = req("GET /a HTTP/1.1\r\nHost: x\r\n\r\n");
+ HttpRequest r2 = r.withHeader("X-A", "1");
+ Expect.isNull(r.header("X-A"), "original header");
+ Expect.equal(r2.header("X-A"), "1", "copy header");
+ });
+
+ Harness.test("headers lists every header, the first included", () -> {
+ Expect.equal(req("GET / HTTP/1.1\r\nHost: x\r\nX-A: 1\r\n\r\n").headers(), List.of("Host: x", "X-A: 1"), "headers");
+ });
+
+ Harness.test("untouched request round-trips byte-exact", () -> {
+ for (String raw : new String[]{"GET /a HTTP/1.1\r\nHost: x\r\nX-Odd: spaced \r\n\r\n", "GARBAGE\n\nbody"}) {
+ HttpMessage m = new HttpMessage(Bytes.bytes(raw));
+ Expect.isTrue(Arrays.equals(HttpRequest.of(SVC, m).message().raw(), m.raw()), "same bytes for " + raw);
+ }
+ });
+
+ Harness.test("withBody fixes Content-Length", () -> {
+ HttpRequest r = req("POST /p HTTP/1.1\r\nHost: x\r\nContent-Length: 3\r\n\r\nabc").withBody("hello");
+ Expect.equal(r.header("Content-Length"), "5", "content length");
+ Expect.equal(r.bodyText(), "hello", "body");
+ });
+
+ Harness.test("bodyText uses the declared charset, else UTF-8", () -> {
+ byte[] head = Bytes.bytes("POST /p HTTP/1.1\r\nHost: x\r\n\r\n");
+ HttpRequest utf8 = req(Bytes.concat(head, "caf\u00e9".getBytes(StandardCharsets.UTF_8)));
+ Expect.equal(utf8.bodyText(), "caf\u00e9", "utf-8 default");
+ byte[] latinHead = Bytes.bytes("POST /p HTTP/1.1\r\nHost: x\r\nContent-Type: text/plain; charset=ISO-8859-1\r\n\r\n");
+ HttpRequest latin = req(Bytes.concat(latinHead, new byte[]{'c', 'a', 'f', (byte) 0xE9}));
+ Expect.equal(latin.bodyText(), "caf\u00e9", "declared latin-1");
+ });
+
+ Harness.test("binary body hmac is over the raw bytes", () -> {
+ byte[] body = {0x1f, (byte) 0x8b, 0x08, 0x00};
+ HttpRequest r = req(Bytes.concat(Bytes.bytes("POST /p HTTP/1.1\r\nHost: x\r\n\r\n"), body));
+ Utilities u = utils();
+ byte[] key = u.bytes("k");
+ Expect.equal(u.hex(u.hmacSha256(key, r.body())), u.hex(u.hmacSha256(key, body)), "hmac");
+ Expect.isTrue(Arrays.equals(r.message().raw(), r.withHeader("X-A", "1").withRemovedHeader("X-A").message().raw()), "header add then remove keeps the body");
+ });
+
+ Harness.test("hmac sha256 matches RFC 4231 case 2", () -> {
+ Utilities u = utils();
+ Expect.equal(u.hex(u.hmacSha256(u.bytes("Jefe"), u.bytes("what do ya want for nothing?"))),
+ "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843", "hmac");
+ });
+
+ Harness.test("sha256, md5 and base64 match known values", () -> {
+ Utilities u = utils();
+ Expect.equal(u.hex(u.sha256(u.bytes("abc"))), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "sha256");
+ Expect.equal(u.hex(u.md5(u.bytes("abc"))), "900150983cd24fb0d6963f7d28e17f72", "md5");
+ Expect.equal(u.base64Encode(u.bytes("hi")), "aGk=", "base64");
+ Expect.equal(new String(u.base64Decode("aGk="), StandardCharsets.UTF_8), "hi", "base64 decode");
+ Expect.equal(u.urlEncode("a b&c"), "a+b%26c", "url encode");
+ });
+
+ Harness.test("log is capped at 1000 lines", () -> {
+ Utilities u = utils();
+ for (int i = 0; i < 1005; i++) u.log("line " + i);
+ Expect.equal(u.logLines().size(), 1000, "lines kept");
+ Expect.isTrue(u.logCut(), "cut flagged");
+ });
+
+ Harness.test("a line too long for the output is shortened, not dropped", () -> {
+ Utilities u = utils();
+ u.log("x".repeat(70_000));
+ Expect.equal(u.logLines().size(), 1, "lines kept");
+ Expect.equal(u.logLines().get(0).length(), Utilities.MAX_CHARS, "kept up to the limit");
+ Expect.isTrue(u.logCut(), "cut flagged");
+ });
+
+ Harness.test("clipboard goes to the sink", () -> {
+ List<String> got = new ArrayList<>();
+ new Utilities(got::add).clipboard("copied");
+ Expect.equal(got, List.of("copied"), "clipboard");
+ });
+
+ Harness.test("empty request reads safely", () -> {
+ HttpRequest r = req(new byte[0]);
+ Expect.isNull(r.header("Host"), "no host");
+ Expect.equal(r.body().length, 0, "empty body");
+ });
+
+ Harness.test("setRequest is recorded", () -> {
+ HttpRequest r = req("GET / HTTP/1.1\r\nHost: x\r\n\r\n");
+ HttpRequestResponse rr = new HttpRequestResponse(r, null);
+ Expect.isNull(rr.replacement(), "before");
+ Expect.isFalse(rr.hasResponse(), "no response");
+ HttpRequest changed = r.withMethod("POST").withPath("/new");
+ rr.setRequest(changed);
+ Expect.equal(rr.replacement().method(), "POST", "method");
+ Expect.equal(rr.replacement().path(), "/new", "path");
+ });
+ }
+}
diff --git a/tests/opensuite/script/ScriptCompilerTest.java b/tests/opensuite/script/ScriptCompilerTest.java
new file mode 100644
index 0000000..beb29d4
--- /dev/null
+++ b/tests/opensuite/script/ScriptCompilerTest.java
@@ -0,0 +1,109 @@
+package opensuite.script;
+
+import opensuite.core.HttpMessage;
+import opensuite.script.api.HttpRequest;
+import opensuite.script.api.HttpRequestResponse;
+import opensuite.script.api.Utilities;
+import opensuite.testkit.Expect;
+import opensuite.testkit.Harness;
+
+import java.util.List;
+import javax.tools.ToolProvider;
+
+/**
+ * A script body is compiled in memory, its errors are given at the script's
+ * own lines, the same source is compiled once, and a script that would close
+ * Open Suite is refused.
+ */
+public final class ScriptCompilerTest {
+
+ private static ScriptCompiler compiler() { return new ScriptCompiler(ToolProvider.getSystemJavaCompiler()); }
+
+ private static HttpRequestResponse empty() {
+ return new HttpRequestResponse(HttpRequest.of(null, new HttpMessage(new byte[0])), null);
+ }
+
+ private static int lineOf(String error) {
+ Expect.isTrue(error.startsWith("line "), "an error with a line: " + error);
+ return Integer.parseInt(error.substring(5, error.indexOf(':')));
+ }
+
+ public void run() {
+ Harness.suite("script compiler");
+
+ Harness.test("compiles and runs a body", () -> {
+ Compiled c = compiler().compileCustomAction("utilities.log(\"hi\");");
+ Expect.isTrue(c.ok(), "compiled: " + c.errors());
+ Utilities u = new Utilities(s -> { });
+ try { c.fn().action(empty(), u); } catch (Exception e) { throw new AssertionError(e); }
+ Expect.equal(u.logLines(), List.of("hi"), "log");
+ });
+
+ Harness.test("a compile error is given at the script's line", () -> {
+ Compiled c = compiler().compileCustomAction("int a = 1;\nutilities.lg(\"x\");\n");
+ Expect.isFalse(c.ok(), "compiled");
+ Expect.equal(c.errors().size(), 1, "one error: " + c.errors());
+ Expect.equal(lineOf(c.errors().get(0)), 2, "line");
+ });
+
+ Harness.test("an unknown name says which name", () -> {
+ Compiled c = compiler().compileCustomAction("utilities.lg(\"x\");");
+ Expect.equal(c.errors(), List.of("line 1: cannot find symbol (method lg(String))"), "errors");
+ });
+
+ Harness.test("unbalanced braces stay inside the script's lines", () -> {
+ Compiled c = compiler().compileCustomAction("if (true) {\nutilities.log(1);\n");
+ Expect.isFalse(c.ok(), "compiled");
+ for (String e : c.errors()) {
+ int n = lineOf(e);
+ Expect.isTrue(n >= 1 && n <= 2, "line in 1..2: " + e);
+ }
+ });
+
+ Harness.test("a return value in the action is an error at its line", () -> {
+ Compiled c = compiler().compileCustomAction("return 5;");
+ Expect.isFalse(c.ok(), "compiled");
+ Expect.equal(lineOf(c.errors().get(0)), 1, "line");
+ });
+
+ Harness.test("the same source is compiled once", () -> {
+ ScriptCompiler sc = compiler();
+ Compiled first = sc.compileCustomAction("int a = 1;");
+ Expect.isTrue(sc.compileCustomAction("int a = 1;") == first, "the cached result for the same source");
+ Expect.isTrue(sc.compileCustomAction("int a = 2;") != first, "a new result for a changed source");
+ });
+
+ Harness.test("a runtime error is given at the script's line", () -> {
+ Compiled c = compiler().compileCustomAction("utilities.log(1);\nObject o = null;\no.toString();");
+ Expect.isTrue(c.ok(), "compiled: " + c.errors());
+ try {
+ c.fn().action(empty(), new Utilities(s -> { }));
+ throw new AssertionError("expected a NullPointerException");
+ } catch (NullPointerException e) {
+ Expect.equal(ScriptCompiler.scriptLine(c.className(), e.getStackTrace()), 3, "line");
+ } catch (Exception e) {
+ throw new AssertionError(e);
+ }
+ });
+
+ Harness.test("a script that would exit Open Suite is refused", () -> {
+ ScriptCompiler sc = compiler();
+ Compiled c = sc.compileCustomAction("int x = 1;\nSystem.exit(0);");
+ Expect.equal(c.errors(), List.of("line 2: a script may not exit Open Suite (System.exit / Runtime.halt)"), "errors");
+ Expect.isFalse(sc.compileCustomAction("Runtime r = Runtime.getRuntime();\nr.halt(1);").ok(), "halt through a variable");
+ });
+
+ Harness.test("exit named in a comment or a string is not a call", () -> {
+ Compiled c = compiler().compileCustomAction("// System.exit(0) would close Open Suite\nutilities.log(\"System.exit(0)\");");
+ Expect.isTrue(c.ok(), "compiled: " + c.errors());
+ });
+
+ Harness.test("no compiler is reported", () -> {
+ ScriptCompiler sc = new ScriptCompiler(null);
+ Expect.isFalse(sc.available(), "available");
+ Compiled c = sc.compileCustomAction("int a;");
+ Expect.isFalse(c.ok(), "compiled");
+ Expect.equal(c.errors(), List.of("no Java compiler is available in this runtime"), "error");
+ });
+ }
+}
diff --git a/tests/opensuite/script/ScriptRunnerTest.java b/tests/opensuite/script/ScriptRunnerTest.java
new file mode 100644
index 0000000..a14847e
--- /dev/null
+++ b/tests/opensuite/script/ScriptRunnerTest.java
@@ -0,0 +1,171 @@
+package opensuite.script;
+
+import opensuite.core.Bytes;
+import opensuite.core.HttpMessage;
+import opensuite.core.HttpService;
+import opensuite.testkit.Expect;
+import opensuite.testkit.Harness;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import javax.tools.ToolProvider;
+
+/**
+ * Scripts run one at a time, off the caller's thread, within a time limit:
+ * a change is kept only when the run ends well, a loop is stopped or given
+ * up on, and a run that cannot start says why.
+ */
+public final class ScriptRunnerTest {
+
+ private static final HttpService SVC = new HttpService("example.test", 80, false);
+ private static final String RAW = "GET /a HTTP/1.1\r\nHost: example.test\r\n\r\n";
+
+ private static ScriptEngine engine() { return new ScriptEngine(ToolProvider.getSystemJavaCompiler(), 1000); }
+
+ private static RunResult run(ScriptEngine e, String source) { return run(e, source, new AtomicBoolean()); }
+
+ private static RunResult run(ScriptEngine e, String source, AtomicBoolean stop) {
+ return e.runCustomAction(source, SVC, new HttpMessage(Bytes.bytes(RAW)), null, s -> { }, stop);
+ }
+
+ public void run() {
+ Harness.suite("script runner");
+
+ Harness.test("a run returns its output and how long it took", () -> {
+ RunResult r = run(engine(), "utilities.log(\"one\");\nutilities.log(2);");
+ Expect.equal(r.status(), RunResult.Status.OK, "status: " + r.error());
+ Expect.equal(r.log(), List.of("one", "2"), "log");
+ Expect.isTrue(r.millis() >= 0, "millis");
+ Expect.isNull(r.newRequest(), "no change");
+ });
+
+ Harness.test("setRequest gives the new request and leaves the given one", () -> {
+ HttpMessage given = new HttpMessage(Bytes.bytes(RAW));
+ RunResult r = engine().runCustomAction(
+ "requestResponse.setRequest(requestResponse.request().withHeader(\"X-A\", \"1\"));", SVC, given, null, s -> { }, new AtomicBoolean());
+ Expect.equal(r.status(), RunResult.Status.OK, "status: " + r.error());
+ Expect.equal(r.newRequest().header("X-A"), "1", "new header");
+ Expect.isTrue(Arrays.equals(given.raw(), Bytes.bytes(RAW)), "given untouched");
+ });
+
+ Harness.test("a failed run drops the change and gives the line", () -> {
+ RunResult r = run(engine(), "requestResponse.setRequest(requestResponse.request().withHeader(\"X-A\", \"1\"));\nthrow new RuntimeException(\"no\");");
+ Expect.equal(r.status(), RunResult.Status.FAILED, "status");
+ Expect.isNull(r.newRequest(), "change dropped");
+ Expect.equal(r.error(), "RuntimeException: no at line 2", "error");
+ });
+
+ Harness.test("a compile error is reported", () -> {
+ RunResult r = run(engine(), "utilities.lg(1);");
+ Expect.equal(r.status(), RunResult.Status.FAILED, "status");
+ Expect.isTrue(r.error().startsWith("line 1:"), "error: " + r.error());
+ });
+
+ Harness.test("a loop that listens is stopped at the limit, and the next run works", () -> {
+ ScriptEngine e = engine();
+ RunResult r = run(e, "while (!Thread.currentThread().isInterrupted()) { }");
+ Expect.equal(r.status(), RunResult.Status.TIMEOUT, "status");
+ Expect.equal(r.error(), "stopped after 1 s (time limit)", "error");
+ Expect.equal(e.abandonedThreads(), 0, "abandoned");
+ Expect.equal(run(e, "utilities.log(1);").status(), RunResult.Status.OK, "next run");
+ });
+
+ Harness.test("a loop that ignores interruption is given up on; at three, runs are refused", () -> {
+ ScriptEngine e = engine();
+ String stubborn = "while (true) { try { Thread.sleep(5); } catch (InterruptedException x) { } }";
+ for (int i = 1; i <= 3; i++) {
+ RunResult r = run(e, stubborn);
+ Expect.equal(r.status(), RunResult.Status.TIMEOUT, "status " + i);
+ Expect.isTrue(r.error().endsWith("; it is still running, restart Open Suite to stop it"), "error " + i + ": " + r.error());
+ Expect.equal(e.abandonedThreads(), i, "abandoned " + i);
+ }
+ RunResult refused = run(e, "utilities.log(1);");
+ Expect.equal(refused.status(), RunResult.Status.FAILED, "refused");
+ Expect.equal(refused.error(), "3 scripts are still running and could not be stopped; restart Open Suite to stop them", "error");
+ });
+
+ Harness.test("runaway recursion is an exception and the runner carries on", () -> {
+ ScriptEngine e = engine();
+ RunResult r = run(e, "class R { int f(int n) { return f(n + 1); } }\nnew R().f(0);");
+ Expect.equal(r.status(), RunResult.Status.FAILED, "status");
+ Expect.isTrue(r.error().startsWith("StackOverflowError"), "error: " + r.error());
+ Expect.equal(run(e, "utilities.log(1);").status(), RunResult.Status.OK, "next run");
+ });
+
+ Harness.test("stop ends a run", () -> {
+ ScriptEngine e = new ScriptEngine(ToolProvider.getSystemJavaCompiler(), 10_000);
+ AtomicBoolean stop = new AtomicBoolean();
+ AtomicReference<RunResult> out = new AtomicReference<>();
+ Thread t = new Thread(() -> out.set(run(e, "while (!Thread.currentThread().isInterrupted()) { }", stop)));
+ t.start();
+ try {
+ Thread.sleep(1500); // past the first compile
+ stop.set(true);
+ t.join(5000);
+ } catch (InterruptedException x) { throw new AssertionError(x); }
+ Expect.notNull(out.get(), "a result");
+ Expect.equal(out.get().status(), RunResult.Status.STOPPED, "status");
+ Expect.equal(out.get().error(), "stopped", "error");
+ });
+
+ Harness.test("a stop that comes before the run starts is kept", () -> {
+ AtomicBoolean stop = new AtomicBoolean();
+ stop.set(true);
+ RunResult r = run(engine(), "while (!Thread.currentThread().isInterrupted()) { }", stop);
+ Expect.equal(r.status(), RunResult.Status.STOPPED, "status");
+ Expect.isTrue(r.millis() < 500, "stopped at once, not at the limit: " + r.millis());
+ });
+
+ Harness.test("stopping one run leaves another running", () -> {
+ ScriptEngine e = new ScriptEngine(ToolProvider.getSystemJavaCompiler(), 2000);
+ run(e, "int warm = 0;");
+ AtomicReference<RunResult> a = new AtomicReference<>(), b = new AtomicReference<>();
+ AtomicBoolean stopB = new AtomicBoolean();
+ Thread ta = new Thread(() -> a.set(run(e, "while (!Thread.currentThread().isInterrupted()) { }", new AtomicBoolean())));
+ Thread tb = new Thread(() -> b.set(run(e, "utilities.log(1);", stopB)));
+ try {
+ ta.start();
+ Thread.sleep(500);
+ tb.start(); // waits for A's turn to end
+ Thread.sleep(200);
+ stopB.set(true);
+ ta.join(6000); tb.join(6000);
+ } catch (InterruptedException x) { throw new AssertionError(x); }
+ Expect.equal(a.get().status(), RunResult.Status.TIMEOUT, "the other run ran to its limit");
+ Expect.equal(b.get().status(), RunResult.Status.STOPPED, "the stopped run");
+ });
+
+ Harness.test("runs are one at a time", () -> {
+ ScriptEngine e = engine();
+ run(e, "Thread.sleep(1);"); // compile first, so only the runs are timed
+ long start = System.nanoTime();
+ Thread a = new Thread(() -> run(e, "Thread.sleep(200);"));
+ Thread b = new Thread(() -> run(e, "Thread.sleep(200);"));
+ a.start(); b.start();
+ try { a.join(); b.join(); } catch (InterruptedException x) { throw new AssertionError(x); }
+ Expect.isTrue((System.nanoTime() - start) / 1_000_000 >= 400, "serialised");
+ });
+
+ Harness.test("log output past the cap is reported as cut", () -> {
+ RunResult r = run(engine(), "for (int i = 0; i < 1005; i++) utilities.log(i);");
+ Expect.equal(r.log().size(), 1000, "lines");
+ Expect.isTrue(r.logCut(), "cut");
+ });
+
+ Harness.test("a failure inside the engine is a result, not a throw", () -> {
+ javax.tools.JavaCompiler broken = (javax.tools.JavaCompiler) java.lang.reflect.Proxy.newProxyInstance(
+ getClass().getClassLoader(), new Class<?>[]{javax.tools.JavaCompiler.class},
+ (proxy, method, args) -> { throw new IllegalStateException("compiler broke"); });
+ RunResult r = run(new ScriptEngine(broken, 1000), "utilities.log(1);");
+ Expect.equal(r.status(), RunResult.Status.FAILED, "status");
+ Expect.equal(r.error(), "internal error: IllegalStateException: compiler broke", "error");
+ });
+
+ Harness.test("no compiler is reported", () -> {
+ RunResult r = run(new ScriptEngine(null, 1000), "int a;");
+ Expect.equal(r.status(), RunResult.Status.FAILED, "status");
+ });
+ }
+}
diff --git a/tests/opensuite/ui/CustomActionRunTest.java b/tests/opensuite/ui/CustomActionRunTest.java
new file mode 100644
index 0000000..a134b86
--- /dev/null
+++ b/tests/opensuite/ui/CustomActionRunTest.java
@@ -0,0 +1,112 @@
+package opensuite.ui;
+
+import opensuite.core.Bytes;
+import opensuite.core.HttpMessage;
+import opensuite.core.HttpService;
+import opensuite.core.SuiteContext;
+import opensuite.script.RunResult;
+import opensuite.script.ScriptEngine;
+import opensuite.testkit.Expect;
+import opensuite.testkit.Harness;
+
+import java.awt.Component;
+import java.awt.Container;
+import java.util.Arrays;
+import java.util.List;
+import javax.swing.Action;
+import javax.swing.SwingUtilities;
+import javax.swing.text.JTextComponent;
+import javax.tools.ToolProvider;
+
+/**
+ * A custom action's new request lands in the request editor beside the
+ * response, as one change that a single undo takes back.
+ */
+public final class CustomActionRunTest {
+
+ private static final HttpService SVC = new HttpService("example.test", 80, false);
+ private static final String RAW = "GET /a HTTP/1.1\r\nHost: example.test\r\n\r\n";
+
+ private static void onEdt(Runnable r) {
+ try { SwingUtilities.invokeAndWait(r); } catch (Exception e) { throw new AssertionError(e); }
+ }
+
+ /** The editable text component showing {@code containing}. */
+ private static JTextComponent textOf(Container root, String containing) {
+ for (Component c : root.getComponents()) {
+ if (c instanceof JTextComponent t && t.isEditable() && t.getText().contains(containing)) return t;
+ if (c instanceof Container k) {
+ JTextComponent t = textOf(k, containing);
+ if (t != null) return t;
+ }
+ }
+ return null;
+ }
+
+ /** The text component whose text the editor shows now, with its undo action. */
+ private static Action undoOf(Container root, String containing) {
+ for (Component c : root.getComponents()) {
+ if (c instanceof JTextComponent t && t.getText().contains(containing) && t.getActionMap().get("opensuite-undo") != null) {
+ return t.getActionMap().get("opensuite-undo");
+ }
+ if (c instanceof Container k) {
+ Action a = undoOf(k, containing);
+ if (a != null) return a;
+ }
+ }
+ return null;
+ }
+
+ public void run() {
+ Harness.suite("custom action run");
+
+ Harness.test("a new request replaces the edited one, and one undo takes it back", () -> {
+ SuiteContext ctx = new SuiteContext();
+ MessageEditor[] eds = new MessageEditor[2];
+ onEdt(() -> {
+ eds[0] = new MessageEditor(ctx, MessageEditor.REQUEST, true);
+ eds[1] = new MessageEditor(ctx, MessageEditor.RESPONSE, false);
+ eds[1].pairWith(eds[0]);
+ eds[0].setMessage(SVC, new HttpMessage(Bytes.bytes(RAW)));
+ });
+ Expect.isTrue(eds[1].requestSource() == eds[0], "the response's request source is the paired editor");
+ HttpMessage changed = new HttpMessage(Bytes.bytes(RAW));
+ changed.setHeader("X-A", "1");
+ onEdt(() -> eds[0].replaceMessageUndoably(changed));
+ Expect.equal(eds[0].message().header("X-A"), "1", "header after the action");
+ Expect.isTrue(Arrays.equals(eds[0].message().raw(), changed.raw()), "the exact bytes of the new request");
+
+ Action undo = undoOf(eds[0], "X-A");
+ Expect.notNull(undo, "an undo action on the shown text");
+ onEdt(() -> undo.actionPerformed(null));
+ Expect.isNull(eds[0].message().header("X-A"), "header after one undo");
+ Expect.equal(Bytes.str(eds[0].message().raw()), RAW, "the request as it was");
+ });
+
+ Harness.test("typing after an action keeps the request's line endings", () -> {
+ SuiteContext ctx = new SuiteContext();
+ MessageEditor[] ed = new MessageEditor[1];
+ onEdt(() -> {
+ ed[0] = new MessageEditor(ctx, MessageEditor.REQUEST, true);
+ ed[0].setMessage(SVC, new HttpMessage(Bytes.bytes(RAW)));
+ });
+ HttpMessage changed = new HttpMessage(Bytes.bytes(RAW));
+ changed.setHeader("X-A", "1");
+ onEdt(() -> ed[0].replaceMessageUndoably(changed));
+ JTextComponent shown = textOf(ed[0], "X-A");
+ Expect.notNull(shown, "the shown text");
+ onEdt(() -> {
+ try { shown.getDocument().insertString(shown.getDocument().getLength(), "z", null); }
+ catch (javax.swing.text.BadLocationException e) { throw new AssertionError(e); }
+ });
+ Expect.equal(Bytes.str(ed[0].message().raw()), Bytes.str(changed.raw()) + "z", "the request after typing one character");
+ });
+
+ Harness.test("an action on an empty request runs cleanly", () -> {
+ RunResult r = new ScriptEngine(ToolProvider.getSystemJavaCompiler(), 5000).runCustomAction(
+ "utilities.log(requestResponse.request().header(\"Host\"));", null, new HttpMessage(new byte[0]), null, s -> { }, new java.util.concurrent.atomic.AtomicBoolean());
+ Expect.equal(r.status(), RunResult.Status.OK, "status: " + r.error());
+ Expect.equal(r.log(), List.of("null"), "log");
+ });
+ }
+}