From 37e08a2fbed7bac5ba5ea3f2e315df90b0d5c01e Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Tue, 17 Nov 2026 21:37:31 -0700 Subject: [PATCH 01/11] Docs: what TermRest is for The README's opening says what TermRest is, and isn't: not another Postman, but a small client for the 80% of an API client that people use every day, with about 20% of the resources, so that memory and CPU go back to the user's own work. It gives the measured numbers (one executable of about 21 MB; the UI under 90 MB with a workspace open and next to no CPU when idle; about 23 MB for a send), says what it doesn't run (no account, cloud sync, telemetry, update checks or background service; script runtimes only while scripts need them), and what it leaves to Postman and Newman, which open the same files. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 364b4fa..a3fe8b2 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,15 @@ # TermRest -A lightweight terminal REST client for development and testing: +A small terminal REST client for development and testing. **It is not another Postman.** It aims at the 80% of an API client that people use every day, with about 20% of the resources, so that your memory and CPU go back to what you are working on: your own services, your IDE, containers, the browser you test with. + +**Small by design:** + +- One native executable of about 21 MB. Nothing else to install: no runtime, no browser engine. +- The full-screen UI, with a workspace open, takes under 90 MB of memory and next to no CPU when idle (16 ms of CPU time in 10 idle seconds). A `termrest send` takes about 23 MB. *(Working set, measured on Windows x64.)* +- No account, no cloud sync, no telemetry, no update checks, no background service: when you quit, nothing of it keeps running. Script runtimes start only for the scripts that need them, and stop when idle. +- Collections stay Postman's own files, so Postman and Newman open them at any time, for the 20% that TermRest leaves out: mock servers, monitors, team workspaces, API design and documentation, and gRPC and WebSocket requests. + +What it has: - **Full-screen, mouse-friendly UI** in the style of Microsoft Edit: menu bar, resizable panes, tables with checkboxes, context menus. Every action also works from the keyboard. Color themes are built in (Dracula, Nord, Solarized, and more), or you can create your own. - **Postman-compatible storage.** Collections and environments are Postman files, edited in place: v2.1 JSON, or the v3 YAML folders that Postman v12 keeps in Git. TermRest writes them back as Postman would (untouched JSON byte-for-byte; in YAML only the lines you changed) and keeps everything it doesn't understand (examples, unknown fields). From 8ffa5ea052676f13ed4a1aef00658048f7561241 Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Tue, 17 Nov 2026 22:08:06 -0700 Subject: [PATCH 02/11] Core, CLI and TUI: saved examples Saved examples (Postman's saved responses) are shown, edited and saved from responses. In the tree they are listed under their request (e.g. ). Save as example, on the response's status line or in the Request menu, saves the response shown as an example of its request: its status, its headers as the server sent them, its body as text (a binary body is left out, and a body over 1 MB asks first), and the request as the editor has it; a response opened from the history goes to the request it was sent from. Opening an example edits its request (method, URL, parameters, headers and body) in the request editor, without Send, and its response (status code and reason, the body's language, with Beautify for JSON, body and headers) in the response pane's place; an edit writes only what was edited, and a body too long for the editor is shown read-only and kept as it is. Examples are renamed, duplicated and deleted from the tree. In a v2.1 collection they are the item's response entries, edited in place (the rest of each, its id and cookies, stays). In a v3 collection each is an .example.yaml file, read only when its request is first expanded or opened, or the collection is converted or copied, so a collection with many examples opens as fast as one without: an edit rewrites the changed lines of its file, a new example gets a file named for it (a name its file can't have kept in it, as Postman keeps it) and its request an examples key if it had none, a renamed one is renamed (also in case only), a deleted one deleted, and a file that can't be read is left alone and named in Workspace info. convert --to v2.1 includes v3 examples. A request's file is no longer compared with its examples when saving. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 9 +- src/TermRest.Cli/ConvertCommand.cs | 8 +- src/TermRest.Core/Model/ExampleSpec.cs | 49 ++++ src/TermRest.Core/Postman/CollectionNodes.cs | 33 +++ src/TermRest.Core/Postman/ExampleMapper.cs | 154 +++++++++++ .../Postman/PostmanCollection.cs | 144 +++++++++- .../Postman/PostmanRequestMapper.cs | 57 ++-- .../Postman/V3/V3CollectionStorage.cs | 261 ++++++++++++++++-- src/TermRest.Core/Postman/V3/V3Convert.cs | 116 ++++++-- src/TermRest.Core/Postman/V3/V3Names.cs | 1 + src/TermRest.Tui/MainWindow.cs | 243 +++++++++++++++- src/TermRest.Tui/Views/CollectionTree.cs | 18 +- .../Views/ExampleResponseEditor.cs | 199 +++++++++++++ src/TermRest.Tui/Views/RequestEditor.cs | 26 +- src/TermRest.Tui/Views/ResponseView.cs | 19 +- src/TermRest.Tui/Views/TabPanel.cs | 20 +- tests/TermRest.Core.Tests/ExampleTests.cs | 226 +++++++++++++++ tests/TermRest.Tui.Tests/MainWindowTests.cs | 76 +++++ 18 files changed, 1560 insertions(+), 99 deletions(-) create mode 100644 src/TermRest.Core/Model/ExampleSpec.cs create mode 100644 src/TermRest.Core/Postman/ExampleMapper.cs create mode 100644 src/TermRest.Tui/Views/ExampleResponseEditor.cs create mode 100644 tests/TermRest.Core.Tests/ExampleTests.cs diff --git a/README.md b/README.md index a3fe8b2..57c09cd 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ A small terminal REST client for development and testing. **It is not another Po What it has: - **Full-screen, mouse-friendly UI** in the style of Microsoft Edit: menu bar, resizable panes, tables with checkboxes, context menus. Every action also works from the keyboard. Color themes are built in (Dracula, Nord, Solarized, and more), or you can create your own. -- **Postman-compatible storage.** Collections and environments are Postman files, edited in place: v2.1 JSON, or the v3 YAML folders that Postman v12 keeps in Git. TermRest writes them back as Postman would (untouched JSON byte-for-byte; in YAML only the lines you changed) and keeps everything it doesn't understand (examples, unknown fields). +- **Postman-compatible storage.** Collections and environments are Postman files, edited in place: v2.1 JSON, or the v3 YAML folders that Postman v12 keeps in Git. TermRest writes them back as Postman would (untouched JSON byte-for-byte; in YAML only the lines you changed) and keeps everything it doesn't understand (unknown fields). Saved examples are shown under their request and can be edited, and any response can be saved as one. - **Scripts in Python, JavaScript, C# or PowerShell.** Pre-request and test scripts for collections, folders and requests, with variables, request changes and tests. JavaScript scripts use Postman's `pm` object, so Postman collections' scripts run too. Each language runs in the runtime you choose: your project's Python, Node.js or Bun, the .NET SDK, and PowerShell 7, with the packages and modules you installed (NuGet packages for C#). A script can have a version in each language (Postman's JavaScript next to a PowerShell one, say): each request runs one language only, the first of your order that has all its scripts, or the one it chooses. TermRest carries no script engine: a runtime starts for its first script and stops when idle. See [Scripts](#scripts). **Scripts are not sandboxed:** they run with your permissions, so turn them on only for collections you trust (see [Script safety](#script-safety)). - **Request history and cURL import.** Every request you send is kept per workspace, with credentials masked, ready to reopen, send again or save. Paste a curl command (for example from a browser's *Copy as cURL*) into the URL bar to import it. - **Find, filter and color responses.** Ctrl+F finds text in the response. A JSONPath query ([RFC 9535](https://www.rfc-editor.org/rfc/rfc9535)) filters a JSON body, in the UI and with `send --filter`. JSON, XML and HTML bodies are colored, request bodies too. @@ -127,6 +127,8 @@ Everything is clickable: menus, tree items, tabs, buttons, table rows, and check A request that is not in a collection (a new one, an imported curl command, or one from the history) lives in the editor only. If you changed it, opening another request, quitting or switching workspaces asks first; *Add to collection…* keeps it. **Ctrl+N** adds it to a collection too; either way it stays open there, with its response, also one still on its way. A request still on its way when you open another one finishes: its result goes to the history and the status bar instead of under the request now shown. A request runs in the environment that was active when you sent it: switching (F7) while it is on its way changes later requests only, and the variables its scripts set, and the environment its history entry and recording name, are that one's. Edits you make while its scripts run apply to the next send; the history keeps the request as it was sent. +**Saved examples** (Postman's saved responses) are listed under their request in the tree, as `e.g. `. *Save as example* (on the response's status line, or *Request › Save response as example…*) saves the response shown as an example of its request: its status, its headers as the server sent them, its body as text (a binary body is left out, and a body over 1 MB asks first, as it goes into the collection file), and the request as the editor has it; a response opened from the history goes to the request it was sent from. Opening an example shows its request (method, URL, parameters, headers and body) in the request editor and its response in the response pane's place, both editable: the status code and reason, the body's language (with *Beautify* for JSON), the body and the headers. *Ctrl+S* saves them with the rest. An example is not sent; open its request to send it. Rename, duplicate or delete examples from the tree, as requests. In a v3 collection an example is a file of its own (see [Postman v3 (YAML) collections](#postman-v3-yaml-collections)), read only when its request is first expanded or opened. + | Key | Action | Key | Action | |---|---|---|---| | F5 / Enter in URL bar / Ctrl+Enter | Send (press again to cancel) | Esc | Cancel a running request | @@ -584,6 +586,7 @@ my-api/ - **Opening:** open the repository folder (`termrest my-api`) or a collection folder directly; a JSON collection, environment or globals file in `postman/collections`, `postman/environments` or `postman/globals` opens the repository's workspace too (also for `send`, `run`, `history` and `import-curl`). A workspace may mix JSON and YAML collections. A folder in `postman/collections` is a collection when it or its folders hold request files or definitions: Postman writes no `.resources/definition.yaml` for a collection without settings of its own. - **Saving changes only what changed.** An edit rewrites the affected lines of one file and keeps comments, key order, quoting and everything TermRest doesn't use, such as a body in a form it can't read (one without a `type`, or of a type it doesn't know: it shows as *none* or empty, and stays as written until you edit the body). Renaming, moving, reordering and deleting requests and folders renames, moves and deletes their files (with their saved examples) the way Postman does, including the `order` values. Files TermRest doesn't manage are never deleted, never overwritten, and keep their names: a folder given the name of a deleted folder that still holds such files is saved as `-1`, with its real name inside. A leading `.` in a name becomes `-` in its file name, so it doesn't hide the file. - **Lists and maps:** headers, parameters, and collection and folder variables can be a list of entries or, as Postman writes plain ones, a `name: value` map. TermRest reads both and keeps the form a file uses; variables become a list once one of them is disabled, secret or described. +- **Saved examples** are `.example.yaml` files in `.resources/.resources/examples/`, which the request's `examples` key names. TermRest reads a request's examples when it first needs them (its tree item is expanded, or the collection is converted or copied), so a collection with many examples opens as fast as one without. An edit rewrites only the changed lines of its file; a new example gets a file named for it, and the request its `examples` key if it had none; a renamed one is renamed (also in case only), a deleted one deleted. A name a file can't have (a `/` or `:`, more than 64 characters, or one that differs from another in case only) is kept in the file (`name:`), as Postman keeps it. An example file TermRest can't read is not shown and never saved over; *Help › Workspace info* names it. `convert --to v2.1` includes the examples. - **Secrets:** a value marked `secret: true` (as Postman marks it, often leaving the value out of the file) or `type: secret` is secret: masked in the UI, the history and recordings. New secrets are marked the way the file marks its others, and a value the file leaves out stays out while it is empty. - **Disabled values:** an environment value marked `disabled: true`, as Postman marks it, is not used. A value you disable is marked the way the file marks its others: `disabled: true`, or `enabled: false` in a file whose values have `enabled`. - **Saving safely.** A save that fails part-way is undone. If TermRest is stopped in the middle of one, opening the collection reports the `.termrest-saving-…` folder that holds the files it was moving. @@ -610,7 +613,6 @@ my-api/ Not yet supported in v3 collections: - Postman's GraphQL, gRPC and WebSocket request types are not shown; their files are left untouched. HTTP requests with a GraphQL body work. -- Saved examples (`*.example.yaml`) are kept and move with their request, but are not shown, and `convert --to v2.1` leaves them out. Converting to v3 writes a request's saved responses as example files, an example's name in its file (`name:`) where its file name can't hold it (two examples whose names differ in case only, a `/` or `:`, or more than 64 characters), as Postman keeps it. - Converting to v3 writes collection and folder variables as Postman's v3 schema has them: their values as text (`42` becomes `"42"`), without v2.1's other keys (`id`, `name`, `system`), and a secret variable without its value, which Postman keeps out of the collection's files: the value stays in the JSON file it came from, and `convert` and *Import Postman collection* name such variables. Set their values in an environment. - A client certificate pinned on a request (v2.1 `certificate`) has no v3 equivalent; use the certificate registry. - A collection's or folder's auth can be a list of credential sets, each with URL `rules` (`rules: {url: api.example.com}`). Sending honors them: a request uses the first set whose rules match its URL (patterns as for client certificates, `api.example.com`, `https://*.example.com/v1/*` or `*`, variables allowed; a set without rules matches any URL), and a request that no set matches is sent without that auth, with a warning, so credentials never reach a host their rules leave out. TermRest doesn't edit the sets, but a copy of a folder (*Duplicate*) keeps them, rules included. `convert --to v2.1` keeps only the first one, which Postman then sends to every URL (v2.1 has one auth per folder); `convert` warns about it. @@ -752,7 +754,8 @@ On Windows, commands write UTF-8 without a byte order mark to files and pipes, a | Collection v2.0.0 JSON | Read/write (v2.0 auth shape kept) | | Collection v3.0.0 YAML (Postman v12 "Native Git") | Read/write: `postman/collections//` folders with `*.request.yaml` and `definition.yaml`; edits rewrite only the changed lines, and a YAML file without a final line break (an environment's too) is saved without one, unless its last value then ends with a line break (a body or PEM written as a `|` block), which needs one. See [Postman v3 (YAML) collections](#postman-v3-yaml-collections) | | Environments / globals | Read/write: JSON (`*.postman_environment.json`, `*.postman_globals.json`) and YAML (`postman/environments/*.environment.yaml`, `postman/globals/workspace.globals.yaml`) | -| Folders, descriptions, saved examples, `protocolProfileBehavior`, unknown fields | Kept; edited fields are rewritten surgically | +| Folders, descriptions, `protocolProfileBehavior`, unknown fields | Kept; edited fields are rewritten surgically | +| Saved examples | Shown under their request, edited (request, status, headers, body), saved from responses; v2.1 `response` entries and v3 `.example.yaml` files | | Body modes | raw, urlencoded, formdata (text + files), file (binary, or typed and checked: `file.language`), graphql | | Auth | inherit, noauth, basic, bearer, apikey, digest, ntlm, oauth2 (client credentials, password and authorization code with or without PKCE fetched and refreshed, or a token pasted; see [OAuth 2.0](#oauth-20)) — others are kept, not applied | | Scripts | JavaScript (`pm.*`, and the older `postman.*` and `tests[]`) runs in Node.js or Bun, Python (`"type": "text/x-python"`; v3 `language: text/x-python`) in Python, C# (`"type": "text/x-csharp"`) with the .NET SDK, PowerShell (`"type": "text/x-powershell"`) in PowerShell 7; scripts in TermRest's languages are written `"disabled": true` so Postman and Newman skip them; see [Scripts](#scripts) for the `pm` API supported | diff --git a/src/TermRest.Cli/ConvertCommand.cs b/src/TermRest.Cli/ConvertCommand.cs index bf85c96..55cfb64 100644 --- a/src/TermRest.Cli/ConvertCommand.cs +++ b/src/TermRest.Cli/ConvertCommand.cs @@ -126,11 +126,13 @@ private static int ConvertCollection(string path, string? to, string? output, in return 2; } + var warningsBefore = source.LoadWarnings.Count; TextFile.WriteAtomic(file, source.ExportV21Json(), newFileMode: TextFile.CopyMode(path)); // as private as its source - Output.Status($"✓ {source.AllRequests().Count()} request(s) written to {file}", true); - if (Directory.EnumerateFiles(path, "*.example.yaml", SearchOption.AllDirectories).Any()) + var exampleCount = source.AllRequests().Sum(r => source.GetExamples(r).Count); + Output.Status($"✓ {source.AllRequests().Count()} request(s){(exampleCount > 0 ? $" and {exampleCount} example(s)" : "")} written to {file}", true); + foreach (var unreadable in source.LoadWarnings.Skip(warningsBefore)) { - Output.Info(" Saved examples (*.example.yaml) are not included in the v2.1 file."); + Output.Warning($"Example left out: {unreadable}"); } if (source.CredentialSetsLeftOutOfV21() is { Count: > 0 } owners) diff --git a/src/TermRest.Core/Model/ExampleSpec.cs b/src/TermRest.Core/Model/ExampleSpec.cs new file mode 100644 index 0000000..5ba4ce4 --- /dev/null +++ b/src/TermRest.Core/Model/ExampleSpec.cs @@ -0,0 +1,49 @@ +namespace TermRest.Core.Model; + +/// +/// Format-neutral, editable view of a request's saved example (Postman's saved response): the request it was saved with, +/// and the response's status, headers and body. Mapped to and from Postman JSON by , +/// which only rewrites what changed. +/// +public sealed class ExampleSpec +{ + /// The languages an example's body is shown in (Postman's _postman_previewlanguage). + public static readonly string[] Languages = ["json", "xml", "html", "javascript", "text"]; + + public string Name { get; set; } = ""; + + /// The request the example was saved with (Postman's originalRequest). + public HttpRequestSpec Request { get; set; } = new(); + + /// The status code; null when the example has none. + public int? Code { get; set; } = 200; + + /// The reason phrase (Postman's status), such as OK. + public string Status { get; set; } = "OK"; + + public List Headers { get; set; } = []; + + public string Body { get; set; } = ""; + + /// What the body is written in: one of , or what the example says; null when it says nothing. + public string? Language { get; set; } + + public ExampleSpec Clone() => new() + { + Name = Name, + Request = Request.Clone(), + Code = Code, + Status = Status, + Headers = KeyValueEntry.CloneList(Headers), + Body = Body, + Language = Language, + }; + + public bool ContentEquals(ExampleSpec other) => + Name == other.Name && Request.ContentEquals(other.Request) && Code == other.Code && Status == other.Status + && KeyValueEntry.ListEquals(Headers, other.Headers) && Body == other.Body && Language == other.Language; + + /// The response part (status, headers, body and its language) equals 's. + public bool ResponseEquals(ExampleSpec other) => + Code == other.Code && Status == other.Status && KeyValueEntry.ListEquals(Headers, other.Headers) && Body == other.Body && Language == other.Language; +} diff --git a/src/TermRest.Core/Postman/CollectionNodes.cs b/src/TermRest.Core/Postman/CollectionNodes.cs index e527891..299fc2a 100644 --- a/src/TermRest.Core/Postman/CollectionNodes.cs +++ b/src/TermRest.Core/Postman/CollectionNodes.cs @@ -136,4 +136,37 @@ internal RequestNode(PostmanCollection collection, JsonObject json, FolderNode? internal HttpRequestSpec Baseline => _baseline ??= PostmanRequestMapper.Read(Json, Collection.SchemaVersion); internal void ResetBaseline() => _baseline = null; + + /// The nodes of the request's examples so far, by their JSON: each example keeps one node (see ). + internal Dictionary ExampleNodes { get; } = new(ReferenceEqualityComparer.Instance); +} + +/// A saved example of a request (Postman's saved response). Wraps (and edits in place) its JSON in the request's response array. +public sealed class ExampleNode +{ + private ExampleSpec? _baseline; + + internal ExampleNode(RequestNode request, JsonObject json) + { + Request = request; + Json = json; + } + + /// The request the example belongs to. + public RequestNode Request { get; } + + public PostmanCollection Collection => Request.Collection; + + public JsonObject Json { get; } + + public string Name => Json["name"].GetString() is { Length: > 0 } name ? name : "(unnamed)"; + + /// The example as currently stored in the collection JSON (a fresh copy every call). + public ExampleSpec ReadSpec() => Baseline.Clone(); + + internal ExampleSpec Baseline => _baseline ??= ExampleMapper.Read(Json, Collection.SchemaVersion); + + internal void ResetBaseline() => _baseline = null; + + public override string ToString() => Name; } diff --git a/src/TermRest.Core/Postman/ExampleMapper.cs b/src/TermRest.Core/Postman/ExampleMapper.cs new file mode 100644 index 0000000..ed3933f --- /dev/null +++ b/src/TermRest.Core/Postman/ExampleMapper.cs @@ -0,0 +1,154 @@ +using System.Text.Json.Nodes; +using TermRest.Core.Http; +using TermRest.Core.Json; +using TermRest.Core.Model; + +namespace TermRest.Core.Postman; + +/// +/// Maps a Postman saved example (an item's response entry) to and back. Writing is +/// surgical, as for requests (see ): only what changed is written, and the rest of the +/// example (its id, cookies, response time, unknown properties) stays as it is. +/// +public static class ExampleMapper +{ + /// The keys of a saved example, in Postman's order. + internal static readonly string[] ExampleOrder = + ["id", "name", "originalRequest", "status", "code", "_postman_previewlanguage", "header", "cookie", "responseTime", "body"]; + + public static ExampleSpec Read(JsonObject example, PostmanSchemaVersion version) + { + var request = new HttpRequestSpec(); + PostmanRequestMapper.ReadRequest(example["originalRequest"], request, version); + return new ExampleSpec + { + Name = example["name"].GetString() ?? "", + Request = request, + Code = example["code"].GetInt(), + Status = example["status"].GetString() ?? "", + Headers = PostmanRequestMapper.ReadKeyValues(example["header"]), + Body = example["body"].GetString() ?? "", + Language = example["_postman_previewlanguage"].GetString(), + }; + } + + /// Writes the parts of that differ from into the example. + public static void Apply(JsonObject example, ExampleSpec spec, ExampleSpec baseline, PostmanSchemaVersion version) + { + if (spec.Name != baseline.Name) + { + example.SetOrdered("name", spec.Name, ExampleOrder); + } + + if (!spec.Request.ContentEquals(baseline.Request)) + { + var force = false; + if (example["originalRequest"] is not JsonObject request) + { + request = new JsonObject(); + example.SetOrdered("originalRequest", request, ExampleOrder); + force = true; + } + + PostmanRequestMapper.ApplyRequest(request, spec.Request, baseline.Request, version, force); + } + + if (spec.Status != baseline.Status) + { + example.SetOrdered("status", spec.Status, ExampleOrder); + } + + if (spec.Code != baseline.Code) + { + if (spec.Code is { } code) + { + example.SetOrdered("code", code, ExampleOrder); + } + else + { + example.Remove("code"); + } + } + + if (spec.Language != baseline.Language) + { + if (spec.Language is { } language) + { + example.SetOrdered("_postman_previewlanguage", language, ExampleOrder); + } + else + { + example.Remove("_postman_previewlanguage"); + } + } + + if (!KeyValueEntry.ListEquals(spec.Headers, baseline.Headers)) + { + example.SetOrdered("header", PostmanRequestMapper.WriteKeyValues(spec.Headers, KeyValueStyle.Header), ExampleOrder); + } + + if (spec.Body != baseline.Body) + { + example.SetOrdered("body", spec.Body, ExampleOrder); + } + } + + /// A new saved example, written as Postman writes one. + public static JsonObject Create(ExampleSpec spec, PostmanSchemaVersion version) + { + var request = new JsonObject(); + PostmanRequestMapper.ApplyRequest(request, spec.Request, new HttpRequestSpec(), version, force: true); + var example = new JsonObject + { + ["name"] = spec.Name, + ["originalRequest"] = request, + ["status"] = spec.Status, + }; + if (spec.Code is { } code) + { + example["code"] = code; + } + + example["_postman_previewlanguage"] = spec.Language ?? "text"; + example["header"] = PostmanRequestMapper.WriteKeyValues(spec.Headers, KeyValueStyle.Header); + example["cookie"] = new JsonArray(); + example["body"] = spec.Body; + return example; + } + + /// + /// An example of that holds : its status, its headers as the + /// server sent them, and its body as text. A binary body is left out (an example holds text): + /// says so. + /// + public static ExampleSpec FromResponse(string name, HttpRequestSpec request, ResponseSnapshot response, out string? note) + { + var language = BodyFormatter.Language(response.Body, response.ContentType); + note = null; + var body = ""; + if (language == "binary" || BodyFormatter.IsBinary(response.Body, response.ContentType)) + { + note = $"The body ({HttpExchange.FormatSize(response.Body.LongLength)} of {response.ContentType ?? "binary data"}) is not saved: an example holds text."; + language = "text"; + } + else + { + body = BodyFormatter.Decode(response.Body, response.ContentType); + if (response.BodyTruncated) + { + note = "The body was cut at the maximum response size: the example has what was received."; + } + } + + return new ExampleSpec + { + Name = name, + Request = request.Clone(), + Code = response.StatusCode, + Status = response.ReasonPhrase, + Headers = [.. response.Headers.Select(h => new KeyValueEntry { Key = h.Key, Value = h.Value })], + Body = body, + Language = language, + }; + } +} diff --git a/src/TermRest.Core/Postman/PostmanCollection.cs b/src/TermRest.Core/Postman/PostmanCollection.cs index 26446e3..11bf1d4 100644 --- a/src/TermRest.Core/Postman/PostmanCollection.cs +++ b/src/TermRest.Core/Postman/PostmanCollection.cs @@ -161,7 +161,11 @@ public static PostmanCollection Create(string name, string? filePath = null) /// Writes this collection (any format) as a new Postman v3 YAML collection folder and returns it. Long values are /// wrapped at (null or 0: not wrapped). On Unix it is as private as this collection's file. /// - public PostmanCollection ConvertToV3(string directory, int? lineWidth = null) => V3CollectionStorage.ConvertFrom(this, directory, lineWidth); + public PostmanCollection ConvertToV3(string directory, int? lineWidth = null) + { + LoadAllExamples(); + return V3CollectionStorage.ConvertFrom(this, directory, lineWidth); + } /// /// The secret variables (of the collection and its folders) whose values leaves out: Postman's @@ -177,9 +181,10 @@ public List CredentialSetsLeftOutOfV21() => [.. Descendants().OfType().Prepend(RootNode).Where(f => f.Json[V3Convert.AuthSetsProperty] is JsonArray) .Select(f => f is CollectionRootNode ? $"collection '{Name}'" : $"folder '{f.PathInCollection}'")]; - /// The collection as a Postman v2.1 JSON document (for any source format). + /// The collection as a Postman v2.1 JSON document (for any source format), with its saved examples. public string ExportV21Json() { + LoadAllExamples(); var copy = (JsonObject)Root.DeepClone(); if (copy["info"] is JsonObject info) { @@ -373,6 +378,135 @@ public bool UpdateRequest(RequestNode node, HttpRequestSpec spec) return true; } + // ----- saved examples -------------------------------------------------------------------- + + /// + /// Whether a request has saved examples, found without reading files: a v3 collection keeps them in files of their own, + /// read when first needs them. + /// + public bool HasExamples(RequestNode node) => + (node.Json["response"] is JsonArray responses && responses.Any(r => r is JsonObject)) || (_storage?.HasUnloadedExamples(node.Json) ?? false); + + /// + /// The request's saved examples, in order. A v3 collection's are read from their files the first time; files that + /// cannot be read are left out (and alone), with a warning in . + /// + public IReadOnlyList GetExamples(RequestNode node) + { + EnsureOwned(node); + LoadExamples(node); + var examples = new List(); + var current = new HashSet(ReferenceEqualityComparer.Instance); + foreach (var json in (node.Json["response"] as JsonArray ?? []).OfType()) + { + if (!node.ExampleNodes.TryGetValue(json, out var example)) + { + example = new ExampleNode(node, json); + node.ExampleNodes[json] = example; + } + + current.Add(json); + examples.Add(example); + } + + foreach (var gone in node.ExampleNodes.Keys.Where(json => !current.Contains(json)).ToList()) + { + node.ExampleNodes.Remove(gone); + } + + return examples; + } + + /// Adds a saved example to a request, after its others. + public ExampleNode AddExample(RequestNode node, ExampleSpec spec) + { + EnsureOwned(node); + LoadExamples(node); + if (node.Json["response"] is not JsonArray responses) + { + responses = []; + node.Json.SetOrdered("response", responses, PostmanRequestMapper.ItemOrder); + } + + var json = ExampleMapper.Create(spec, SchemaVersion); + responses.Add((JsonNode)json); + MarkDirty(); + return GetExamples(node).First(e => e.Json == json); + } + + /// Writes the parts of that changed back into the example's JSON. + public bool UpdateExample(ExampleNode example, ExampleSpec spec) + { + EnsureOwned(example.Request); + if (spec.ContentEquals(example.Baseline)) + { + return false; + } + + ExampleMapper.Apply(example.Json, spec, example.Baseline, SchemaVersion); + example.ResetBaseline(); + MarkDirty(); + return true; + } + + public void RenameExample(ExampleNode example, string name) + { + var spec = example.ReadSpec(); + spec.Name = name; + UpdateExample(example, spec); + } + + public void RemoveExample(ExampleNode example) + { + EnsureOwned(example.Request); + (example.Request.Json["response"] as JsonArray)?.Remove(example.Json); + example.Request.ExampleNodes.Remove(example.Json); + MarkDirty(); + } + + /// Copies an example, right after it, as "<name> Copy". + public ExampleNode DuplicateExample(ExampleNode example) + { + EnsureOwned(example.Request); + var responses = (JsonArray)example.Request.Json["response"]!; + var clone = (JsonObject)example.Json.DeepClone(); + clone.SetOrdered("name", $"{example.Name} Copy", ExampleMapper.ExampleOrder); + clone.Remove("id"); + responses.Insert(responses.IndexOf(example.Json) + 1, clone); + MarkDirty(); + return GetExamples(example.Request).First(e => e.Json == clone); + } + + /// Loads the request's examples where they are files of their own (see ). + private void LoadExamples(RequestNode node) + { + if (_storage?.LoadExamples(node.Json) is { Count: > 0 } problems) + { + LoadWarnings.AddRange(problems); + } + } + + /// Loads the examples of every request in (all when null), before they are copied whole. + private void LoadAllExamples(CollectionNode? node = null) + { + if (_storage is null) + { + return; + } + + var requests = node switch + { + null => AllRequests(), + RequestNode request => [request], + FolderNode folder => Walk(folder).OfType(), + _ => [], + }; + foreach (var request in requests) + { + LoadExamples(request); + } + } + public RequestNode AddRequest(FolderNode parent, string name, HttpRequestSpec? spec = null) { EnsureOwned(parent); @@ -439,6 +573,7 @@ public CollectionNode Duplicate(CollectionNode node) throw new InvalidOperationException("Duplicate the collection file instead."); } + LoadAllExamples(node); // the copy has them too var clone = (JsonObject)node.Json.DeepClone(); clone["name"] = $"{node.Name} Copy"; StripIds(clone); @@ -526,6 +661,11 @@ private static void StripIds(JsonObject item) { item.Remove("id"); item.Remove("_postman_id"); + foreach (var example in (item["response"] as JsonArray ?? []).OfType()) + { + example.Remove("id"); + } + if (item["item"] is JsonArray children) { foreach (var child in children.OfType()) diff --git a/src/TermRest.Core/Postman/PostmanRequestMapper.cs b/src/TermRest.Core/Postman/PostmanRequestMapper.cs index a758346..a53a4fc 100644 --- a/src/TermRest.Core/Postman/PostmanRequestMapper.cs +++ b/src/TermRest.Core/Postman/PostmanRequestMapper.cs @@ -51,7 +51,17 @@ public static class PostmanRequestMapper public static HttpRequestSpec Read(JsonObject item, PostmanSchemaVersion version) { var spec = new HttpRequestSpec(); - switch (item["request"]) + ReadRequest(item["request"], spec, version); + spec.Settings = ReadSettings(item["protocolProfileBehavior"]); + spec.Scripts = ReadScripts(item["event"]); + spec.ScriptSettings = ReadScriptSettings(item["termrest"]); + return spec; + } + + /// Reads a request object (an item's, or a saved example's originalRequest), or its short form, a URL. + internal static void ReadRequest(JsonNode? node, HttpRequestSpec spec, PostmanSchemaVersion version) + { + switch (node) { case JsonValue shortForm: spec.Url = shortForm.GetString() ?? ""; @@ -69,11 +79,6 @@ public static HttpRequestSpec Read(JsonObject item, PostmanSchemaVersion version spec.Description = ReadDescription(request["description"]); break; } - - spec.Settings = ReadSettings(item["protocolProfileBehavior"]); - spec.Scripts = ReadScripts(item["event"]); - spec.ScriptSettings = ReadScriptSettings(item["termrest"]); - return spec; } internal static List ReadKeyValues(JsonNode? node, bool environmentStyle = false) @@ -359,6 +364,30 @@ public static void Apply(JsonObject item, HttpRequestSpec spec, HttpRequestSpec force = true; } + ApplyRequest(request, spec, baseline, version, force); + if (!spec.Settings.ContentEquals(baseline.Settings)) + { + var settings = WriteSettings(spec.Settings); + if (settings is null) + { + item.Remove("protocolProfileBehavior"); + } + else + { + item.SetOrdered("protocolProfileBehavior", settings, ItemOrder); + } + } + + ApplyScripts(item, spec.Scripts, baseline.Scripts, ItemOrder); + ApplyScriptSettings(item, spec.ScriptSettings, baseline.ScriptSettings); + } + + /// + /// Writes the parts of a request object (an item's, or a saved example's originalRequest) that differ from + /// ; with (a new object) all of them. + /// + internal static void ApplyRequest(JsonObject request, HttpRequestSpec spec, HttpRequestSpec baseline, PostmanSchemaVersion version, bool force) + { if (force || spec.Method != baseline.Method) { request.SetOrdered("method", spec.Method, RequestOrder); @@ -430,22 +459,6 @@ public static void Apply(JsonObject item, HttpRequestSpec spec, HttpRequestSpec request.SetOrdered("description", WriteDescription(request["description"], spec.Description), RequestOrder); } } - - if (!spec.Settings.ContentEquals(baseline.Settings)) - { - var settings = WriteSettings(spec.Settings); - if (settings is null) - { - item.Remove("protocolProfileBehavior"); - } - else - { - item.SetOrdered("protocolProfileBehavior", settings, ItemOrder); - } - } - - ApplyScripts(item, spec.Scripts, baseline.Scripts, ItemOrder); - ApplyScriptSettings(item, spec.ScriptSettings, baseline.ScriptSettings); } /// diff --git a/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs b/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs index f20c90c..56ad90b 100644 --- a/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs +++ b/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs @@ -13,6 +13,18 @@ internal interface ICollectionStorage /// Also write files that changed on disk since they were read (see ). void Save(PostmanCollection collection, bool overwriteChanged); + + /// + /// Whether a request has saved examples that are not loaded yet (into its response array: see + /// ). Answered without reading files. + /// + bool HasUnloadedExamples(JsonObject item); + + /// + /// Loads a request's saved examples into its response array, once (a v3 collection keeps them in files of their + /// own, read only when needed). Returns problems with files that could not be read (they are left alone). + /// + IReadOnlyList LoadExamples(JsonObject item); } /// @@ -29,11 +41,14 @@ internal sealed class V3CollectionStorage : ICollectionStorage private static readonly TextFileInfo NewFile = new(false, true, false); - /// The keys of an example file, in Postman's order. - private static readonly string[] ExampleOrder = ["$kind", "name", "request", "response", "order"]; - private readonly Dictionary _origins = new(ReferenceEqualityComparer.Instance); private readonly Dictionary> _loadedChildren = new(ReferenceEqualityComparer.Instance); + + /// + /// The saved examples of the requests whose examples are loaded (see ), by request: what each + /// example was read from or last written to. The examples of other requests stay on disk, untouched. + /// + private readonly Dictionary> _examples = new(ReferenceEqualityComparer.Instance); private YamlStyle _style = YamlStyle.Default; /// On Unix, the permissions of the files a conversion creates (see ); null: the default. @@ -88,6 +103,101 @@ private sealed class Origin public string? Stem { get; set; } } + /// What was read from (or last written to) disk for one saved example of a request. + private sealed class ExampleOrigin + { + public required string Path { get; set; } + + /// The file as last read or written. + public required YamlFile File { get; set; } + + public FileStamp? Stamp { get; set; } + + public TextFileInfo FileInfo { get; set; } = NewFile; + + /// The v3 content as last read or written. + public required JsonObject V3 { get; set; } + + /// The v2.1 example (as in the request's response array) as last read or written. + public required JsonObject Baseline { get; set; } + } + + // ----- examples ---------------------------------------------------------------------------------- + + public bool HasUnloadedExamples(JsonObject item) => + !_examples.ContainsKey(item) && _origins.TryGetValue(item, out var origin) && origin.V3?["examples"].GetString() is { Length: > 0 }; + + public IReadOnlyList LoadExamples(JsonObject item) + { + if (IsFolder(item) || _examples.ContainsKey(item)) + { + return []; + } + + var loaded = new Dictionary(ReferenceEqualityComparer.Instance); + _examples[item] = loaded; + + // A request not saved yet has its examples in memory only. + if (!_origins.TryGetValue(item, out var origin) || origin.V3?["examples"].GetString() is not { Length: > 0 }) + { + return []; + } + + var folder = ExamplesFolder(origin.Path, origin.V3); + if (!System.IO.Directory.Exists(folder)) + { + return []; + } + + var warnings = new List(); + var examples = new List<(double? Order, string Name, JsonObject Example)>(); + foreach (var file in System.IO.Directory.EnumerateFiles(folder).Where(f => f.EndsWith(V3Names.ExampleSuffix, StringComparison.OrdinalIgnoreCase))) + { + // One that cannot be read, or is not an example, is left alone (and out). + var (yaml, info, stamp, _) = Read(file, warnings, []); + if (yaml is null || (yaml.Json["$kind"].GetString() is { } kind && kind != V3Convert.HttpExampleKind)) + { + continue; + } + + var name = yaml.Json["name"].GetString() is { Length: > 0 } given ? given : Path.GetFileName(file)[..^V3Names.ExampleSuffix.Length]; + var example = V3Convert.ExampleToV21(yaml.Json, name); + loaded[example] = new ExampleOrigin { Path = file, File = yaml, Stamp = stamp, FileInfo = info, V3 = yaml.Json, Baseline = (JsonObject)example.DeepClone() }; + examples.Add((OrderValue(yaml.Json["order"]), name, example)); + } + + if (item["response"] is not JsonArray responses) + { + responses = []; + item.SetOrdered("response", responses, PostmanRequestMapper.ItemOrder); + } + + foreach (var (_, _, example) in examples.OrderBy(e => e.Order ?? double.MaxValue).ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase)) + { + responses.Add((JsonNode)example); + } + + return warnings; + } + + /// + /// The folder of a request's example files: the one its examples reference names (relative to the request's + /// folder) while that is inside the collection, else where Postman puts them. + /// + private string ExamplesFolder(string requestFile, JsonObject? v3) + { + if (v3?["examples"].GetString() is { Length: > 0 } reference) + { + var folder = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(requestFile)!, reference))); + if (folder.StartsWith(Directory + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { + return folder; + } + } + + return Path.Combine(V3Names.ResourcesPath(requestFile), "examples"); + } + // ----- loading --------------------------------------------------------------------------------- public static PostmanCollection Load(string directory) @@ -257,41 +367,134 @@ private static void RemoveWritten(string directory, string? created) } /// - /// Writes the saved responses (v2.1 response) of a request that is new to the folder as v3 example files next to - /// ; returns the request's examples reference to them, or null when it has none. + /// Writes a request's saved examples where they changed: new ones as new files named for them (a name a file can't have + /// is kept in it, as Postman keeps it), edited ones in place (only the edited entries), renamed ones under their new + /// name, and deleted ones removed. The examples of a request that were never loaded are as they were: nothing to write. + /// Files another program changed since they were read are left alone unless that is allowed. Returns the request's + /// examples reference when it has example files and lacks one. /// - private string? WriteExamples(JsonObject item, string requestFile) + private string? SaveExamples(JsonObject item, string requestFile, bool isNew, JsonObject v3, LeftAlone leftAlone) { - if (item["response"] is not JsonArray { Count: > 0 } responses) + if (!_examples.TryGetValue(item, out var loaded)) { - return null; + if (!isNew) + { + return null; + } + + loaded = new Dictionary(ReferenceEqualityComparer.Instance); + _examples[item] = loaded; } - var folder = Path.Combine(V3Names.ResourcesPath(requestFile), "examples"); - CreateFolder(folder); - var taken = new HashSet(StringComparer.OrdinalIgnoreCase); - var order = 0; - foreach (var response in responses.OfType()) + var examples = (item["response"] as JsonArray ?? []).OfType().ToList(); + var folder = ExamplesFolder(requestFile, v3); + + // Moved along with the request's resources folder (the request was renamed or moved). + foreach (var origin in loaded.Values.Where(o => Path.GetDirectoryName(o.Path) != folder)) { - var responseName = response["name"].GetString() is { Length: > 0 } given ? given : "Example"; - var name = V3Names.Unique(V3Names.Safe(responseName), taken); - taken.Add(name); - var example = V3Convert.ExampleToV3(response); + origin.Path = Path.Combine(folder, Path.GetFileName(origin.Path)); + } - // A name its file can't have (cut, made safe or unique) is kept in the file, as Postman keeps it. - if (name != responseName) + var current = new HashSet(examples, ReferenceEqualityComparer.Instance); + foreach (var (json, origin) in loaded.Where(e => !current.Contains(e.Key)).ToList()) + { + if (File.Exists(origin.Path)) { - example.SetOrdered("name", responseName, ExampleOrder); + if (origin.Stamp?.HasChanged(origin.Path) == true && !leftAlone.OverwriteChanged) + { + leftAlone.Changed.Add(origin.Path); + continue; + } + + File.Delete(origin.Path); } - order += 1000; - example["order"] = order; - var path = Path.Combine(folder, name + ".example.yaml"); - var (text, info) = YamlFile.WriteChecked(null, example, Style, path, NewFile, out _); - TextFile.WriteAtomic(path, text, info, _newFileMode); + loaded.Remove(json); + } + + // Names in use, also by files TermRest does not show (one it could not read). + var taken = new HashSet(StringComparer.OrdinalIgnoreCase); + if (System.IO.Directory.Exists(folder)) + { + foreach (var file in System.IO.Directory.EnumerateFiles(folder).Where(f => f.EndsWith(V3Names.ExampleSuffix, StringComparison.OrdinalIgnoreCase))) + { + taken.Add(Path.GetFileName(file)[..^V3Names.ExampleSuffix.Length]); + } } - return order == 0 ? null : $"./{V3Names.ResourcesDirectory}/{V3Names.RequestStem(requestFile)}.resources/examples"; + var order = loaded.Values.Select(o => OrderValue(o.V3["order"])).Max() ?? 0; + foreach (var json in examples) + { + var name = json["name"].GetString() is { Length: > 0 } given ? given : "Example"; + if (loaded.TryGetValue(json, out var origin)) + { + if (JsonNode.DeepEquals(json, origin.Baseline)) + { + continue; + } + + if (File.Exists(origin.Path) && origin.Stamp?.HasChanged(origin.Path) == true && !leftAlone.OverwriteChanged) + { + leftAlone.Changed.Add(origin.Path); + continue; + } + + var stem = Path.GetFileName(origin.Path)[..^V3Names.ExampleSuffix.Length]; + var edited = V3Convert.ExampleToV3(json, origin.V3); + if (origin.Baseline["name"].GetString() != json["name"].GetString()) + { + taken.Remove(stem); + stem = V3Names.Unique(V3Names.Safe(name), taken); + NameExample(edited, name, stem); + } + + taken.Add(stem); + var path = Path.Combine(folder, stem + V3Names.ExampleSuffix); + if (path != origin.Path && File.Exists(origin.Path)) + { + File.Move(origin.Path, path); // a new name, also one that differs in case only + } + + CreateFolder(folder); + var (text, info) = YamlFile.WriteChecked(origin.File, edited, Style, path, origin.FileInfo, out var written); + TextFile.WriteAtomic(path, text, info, out var stamp, _newFileMode); + origin.Path = path; + origin.File = written; + origin.Stamp = stamp; + origin.FileInfo = info; + origin.V3 = edited; + origin.Baseline = (JsonObject)json.DeepClone(); + } + else + { + var stem = V3Names.Unique(V3Names.Safe(name), taken); + taken.Add(stem); + var created = V3Convert.ExampleToV3(json); + NameExample(created, name, stem); + order = (Math.Floor(order / 1000) + 1) * 1000; + created["order"] = order < 1e15 ? JsonValue.Create((long)order) : JsonValue.Create(order); + CreateFolder(folder); + var path = Path.Combine(folder, stem + V3Names.ExampleSuffix); + var (text, info) = YamlFile.WriteChecked(null, created, Style, path, NewFile, out var written); + TextFile.WriteAtomic(path, text, info, out var stamp, _newFileMode); + loaded[json] = new ExampleOrigin { Path = path, File = written, Stamp = stamp, FileInfo = info, V3 = created, Baseline = (JsonObject)json.DeepClone() }; + } + } + + return loaded.Count > 0 && v3["examples"] is null ? $"./{V3Names.ResourcesDirectory}/{V3Names.RequestStem(requestFile)}.resources/examples" : null; + + // A name its file can't have (cut, made safe or unique) is kept in the file, as Postman keeps it. + static void NameExample(JsonObject example, string name, string stem) + { + if (stem != name) + { + example.SetOrdered("name", name, V3Convert.ExampleFileOrder); + } + else + { + example.Remove("name"); + } + } } private (YamlFile? File, TextFileInfo Info, FileStamp? Stamp, string? Error) Read(string path, List warnings, List trees) @@ -585,6 +788,7 @@ bool Changes(JsonObject item) _origins.Remove(item); _loadedChildren.Remove(item); + _examples.Remove(item); } foreach (var (item, origin) in _origins) @@ -750,7 +954,7 @@ private void WriteItem(JsonObject item, bool isRoot, string path, JsonObject? pa } } - if (!isFolder && origin is null && WriteExamples(item, path) is { } examplesFolder) + if (!isFolder && SaveExamples(item, path, origin is null, v3, leftAlone) is { } examplesFolder) { v3.SetOrdered("examples", examplesFolder, order); } @@ -1160,12 +1364,13 @@ private static IEnumerable PreOrder(JsonObject folder) private static bool IsFolder(JsonObject item) => item["item"] is JsonArray; /// The item without its children (folder content changes are tracked per child). + /// An item without its children and saved examples, which have files of their own: what its file is written from. private static JsonObject Snapshot(JsonObject item) { var copy = new JsonObject(); foreach (var (key, value) in item) { - if (key != "item") + if (key is not ("item" or "response")) { copy[key] = value?.DeepClone(); } diff --git a/src/TermRest.Core/Postman/V3/V3Convert.cs b/src/TermRest.Core/Postman/V3/V3Convert.cs index 6403000..1fe1929 100644 --- a/src/TermRest.Core/Postman/V3/V3Convert.cs +++ b/src/TermRest.Core/Postman/V3/V3Convert.cs @@ -1053,43 +1053,116 @@ public static JsonObject EnvironmentToV3(JsonObject env, JsonObject? template) // ----- examples (saved responses) ------------------------------------------------------------ - /// A v2.1 saved response as a v3 http-example file. - public static JsonObject ExampleToV3(JsonObject response) + public const string HttpExampleKind = "http-example"; + + /// The keys of an example file, in Postman's order. + internal static readonly string[] ExampleFileOrder = ["$kind", "name", "request", "response", "order"]; + + private static readonly string[] ExampleRequestOrder = ["url", "method", "headers", "queryParams", "pathVariables", "body"]; + private static readonly string[] ExampleResponseOrder = ["statusCode", "statusText", "headers", "body"]; + private static readonly string[] ExampleBodyOrder = ["type", "content"]; + + /// A v3 http-example file as a v2.1 saved response named . + public static JsonObject ExampleToV21(JsonObject v3, string name) { - var original = response["originalRequest"] as JsonObject; - var request = new JsonObject + var request = v3["request"] as JsonObject; + var original = new JsonObject { - ["url"] = ReadUrl(original?["url"]).Raw, - ["method"] = original?["method"].GetString() ?? "GET", + ["method"] = request?["method"].GetString() ?? "GET", + ["header"] = KeyValuesToV21(request?["headers"]), }; - if (KeyValuesToV3(CleanHeaders(original?["header"]), null, mapWhenNew: true) is { } requestHeaders) + if (BodyToV21(request?["body"]) is { } body) + { + original["body"] = body; + } + + var url = new JsonObject { ["raw"] = request?["url"].GetString() ?? "" }; + if (request?["queryParams"] is JsonArray or JsonObject) { - request["headers"] = requestHeaders; + url["query"] = KeyValuesToV21(request["queryParams"]); } - if (BodyToV3(original?["body"] as JsonObject, null) is { } requestBody) + if (request?["pathVariables"] is JsonArray or JsonObject) { - request["body"] = requestBody; + url["variable"] = KeyValuesToV21(request["pathVariables"]); } - var result = new JsonObject + original["url"] = url; + var response = v3["response"] as JsonObject; + var example = new JsonObject { - ["statusCode"] = response["code"].GetInt() ?? 200, - ["statusText"] = response["status"].GetString() ?? "", + ["name"] = name, + ["originalRequest"] = original, + ["status"] = response?["statusText"].GetString() ?? "", }; - if (KeyValuesToV3(CleanHeaders(response["header"]), null, mapWhenNew: true) is { } headers) + if (response?["statusCode"].GetInt() is { } code) { - result["headers"] = headers; + example["code"] = code; } + var responseBody = response?["body"] as JsonObject; + example["_postman_previewlanguage"] = responseBody?["type"].GetString() ?? "text"; + example["header"] = KeyValuesToV21(response?["headers"]); + example["cookie"] = new JsonArray(); + example["body"] = ContentText(responseBody?["content"]); + return example; + } + + /// + /// A v2.1 saved response as a v3 http-example file, based on (the file as it was + /// read): what did not change stays as the file has it (key order, maps or lists, keys TermRest does not edit). Its + /// name and order are the caller's. + /// + public static JsonObject ExampleToV3(JsonObject response, JsonObject? template = null) + { + var v3 = template is null ? new JsonObject { ["$kind"] = HttpExampleKind } : (JsonObject)template.DeepClone(); + var original = response["originalRequest"] as JsonObject; + var templateRequest = template?["request"] as JsonObject; + var request = templateRequest is null ? new JsonObject() : (JsonObject)templateRequest.DeepClone(); + var (raw, query, variables) = ReadUrl(original?["url"]); + Set(request, "url", raw, ExampleRequestOrder); + Set(request, "method", original?["method"].GetString() ?? "GET", ExampleRequestOrder); + Set(request, "headers", KeyValuesToV3(CleanHeaders(original?["header"]), templateRequest?["headers"], mapWhenNew: true), ExampleRequestOrder); + + // Postman's example files name the URL only; parameters the file lists are kept in step with it. + if (templateRequest?.ContainsKey("queryParams") == true) + { + Set(request, "queryParams", KeyValuesToV3(query, templateRequest["queryParams"], mapWhenNew: false), ExampleRequestOrder); + } + + if (templateRequest?.ContainsKey("pathVariables") == true) + { + Set(request, "pathVariables", KeyValuesToV3(variables, templateRequest["pathVariables"], mapWhenNew: false), ExampleRequestOrder); + } + + var fileBody = templateRequest?["body"]; + Set(request, "body", fileBody is not null && JsonNode.DeepEquals(BodyToV21(fileBody), original?["body"]) + ? fileBody.DeepClone() + : BodyToV3(original?["body"] as JsonObject, fileBody), ExampleRequestOrder); + Set(v3, "request", request, ExampleFileOrder); + + var templateResponse = template?["response"] as JsonObject; + var result = templateResponse is null ? new JsonObject() : (JsonObject)templateResponse.DeepClone(); + var code = response["code"].GetInt() ?? (template is null ? 200 : null); + Set(result, "statusCode", code is { } statusCode ? JsonValue.Create(statusCode) : null, ExampleResponseOrder); + Set(result, "statusText", response["status"].GetString() ?? "", ExampleResponseOrder); + Set(result, "headers", KeyValuesToV3(CleanHeaders(response["header"]), templateResponse?["headers"], mapWhenNew: true), ExampleResponseOrder); + + // A type the file has stays, also one TermRest does not color (csv, say). + var templateBody = templateResponse?["body"] as JsonObject; var language = response["_postman_previewlanguage"].GetString(); - result["body"] = new JsonObject + var type = language is not null && (RawLanguages.Contains(language) || language == "yaml" || language == templateBody?["type"].GetString()) ? language : "text"; + var body = templateBody is null ? new JsonObject() : (JsonObject)templateBody.DeepClone(); + Set(body, "type", type, ExampleBodyOrder); + var content = response["body"].GetString() ?? ""; + if (templateBody is null || ContentText(templateBody["content"]) != content) { - ["type"] = language is not null && (RawLanguages.Contains(language) || language == "yaml") ? language : "text", - ["content"] = response["body"].GetString() ?? "", - }; + Set(body, "content", content, ExampleBodyOrder); + } - return new JsonObject { ["$kind"] = "http-example", ["request"] = request, ["response"] = result }; + Set(result, "body", body, ExampleResponseOrder); + Set(v3, "response", result, ExampleFileOrder); + return v3; static JsonArray? CleanHeaders(JsonNode? node) { @@ -1171,6 +1244,9 @@ private static void DescriptionToText(JsonObject entry) _ => node.ToJsonString(), }; + /// An example body's content as text: v3 keeps it as a string, though a file may hold other YAML there. + private static string ContentText(JsonNode? node) => Text(node) ?? ""; + /// The template's value when it means the same text (keeps e.g. a number unquoted). private static JsonNode? Reuse(JsonNode? template, JsonNode? value) => template is JsonValue t && value is JsonValue v && Text(t) == Text(v) ? t.DeepClone() : value?.DeepClone(); diff --git a/src/TermRest.Core/Postman/V3/V3Names.cs b/src/TermRest.Core/Postman/V3/V3Names.cs index 2140335..0b10a77 100644 --- a/src/TermRest.Core/Postman/V3/V3Names.cs +++ b/src/TermRest.Core/Postman/V3/V3Names.cs @@ -6,6 +6,7 @@ namespace TermRest.Core.Postman.V3; internal static class V3Names { public const string RequestSuffix = ".request.yaml"; + public const string ExampleSuffix = ".example.yaml"; public const string ResourcesDirectory = ".resources"; public const string DefinitionFile = "definition.yaml"; public const string EnvironmentSuffix = ".environment.yaml"; diff --git a/src/TermRest.Tui/MainWindow.cs b/src/TermRest.Tui/MainWindow.cs index 77ec47c..2061b25 100644 --- a/src/TermRest.Tui/MainWindow.cs +++ b/src/TermRest.Tui/MainWindow.cs @@ -35,6 +35,7 @@ internal sealed class MainWindow : Runnable private readonly HistoryView _history; private readonly RequestEditor _editor; private readonly ResponseView _response; + private readonly ExampleResponseEditor _exampleEditor; private readonly Shortcut _environmentShortcut; private readonly RecordingIndicator _recordIndicator; private readonly Shortcut _message; @@ -44,6 +45,9 @@ internal sealed class MainWindow : Runnable private MenuItem? _recordMenuItem; private PostmanCollection? _collection; private RequestNode? _node; + + /// The saved example shown (its request in the editor, its response in the example editor), if any. + private ExampleNode? _example; private PostmanCollection? _scratch; private CancellationTokenSource? _sending; @@ -141,7 +145,8 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) Height = Dim.Fill(1), }; _response = new ResponseView(); - _responseFrame.Add(_response); + _exampleEditor = new ExampleResponseEditor { Visible = false }; + _responseFrame.Add(_response, _exampleEditor); // Window shortcuts, not application-wide ones: they must not act behind an open dialog. Names and messages are // shown as written. @@ -173,6 +178,10 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) { OpenRequest(request); } + else if (item is ExampleNode example && example != _example) + { + OpenExample(example); + } }; _tree.ItemActivated += (_, item) => { @@ -186,6 +195,10 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) _editor.FocusUrl(); } + else if (item is ExampleNode example && OpenExample(example)) + { + _exampleEditor.SetFocus(); + } }; _tree.ContextMenuRequested += (_, position) => ShowContextMenu(position); _tree.DeleteRequested += (_, item) => DeleteItem(item); @@ -199,6 +212,8 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) _history.ContextMenuRequested += (_, position) => ShowHistoryContextMenu(position); _history.DeleteRequested += (_, entry) => DeleteHistoryEntry(entry); _editor.Modified += (_, _) => UpdateTitles(); + _exampleEditor.Modified += (_, _) => UpdateTitles(); + _response.SaveAsExampleRequested += (_, _) => SaveResponseAsExample(); _editor.SendRequested += (_, _) => Send(); _editor.GetTokenRequested += (_, _) => GetNewToken(); _editor.ForgetTokenRequested += (_, _) => ForgetToken(); @@ -276,6 +291,18 @@ internal void ShowRequest(RequestNode node) } } + /// The editor of an example's response (for tests). + internal ExampleResponseEditor ExampleEditor => _exampleEditor; + + /// Selects and opens a saved example (for tests). + internal void ShowExample(ExampleNode example) + { + if (OpenExample(example)) + { + _tree.Select(example); + } + } + /// Sends the current request and shows the result without an event loop (used by snapshots). internal async Task SendAndShowAsync(CancellationToken cancellationToken = default) { @@ -312,6 +339,7 @@ internal async Task SendAndShowAsync(CancellationToken cancellationToken = defau new MenuItem("De_lete…", "", () => DeleteItem(_tree.SelectedItem)), new Line(), new MenuItem("Copy as c_URL", "", CopyAsCurl), + new MenuItem("Save response as e_xample…", "", () => SaveResponseAsExample()), new MenuItem("_Import from cURL…", "", ShowCurlImport), new MenuItem("_History", Key.F9, ToggleHistory), new MenuItem("Focus _URL bar", Key.L.WithCtrl, () => _editor.FocusUrl()), @@ -361,6 +389,7 @@ private bool OpenRequest(RequestNode node) DetachSending(); } + LeaveExample(); _collection = node.Collection; _node = node; _historyEntry = null; @@ -372,8 +401,60 @@ private bool OpenRequest(RequestNode node) return true; } + /// + /// Opens a saved example: its request in the editor (without Send: an example is not sent) and its response in the + /// example editor, in the response pane's place. False when the user keeps the request shown (see ). + /// + private bool OpenExample(ExampleNode example) + { + if (example == _example) + { + return true; + } + + if (!ConfirmDiscardRequest()) + { + return false; + } + + CommitEditor(); + DetachSending(); + _collection = example.Collection; + _node = null; + _historyEntry = null; + _historyOrigin = null; + _detachedName = null; + _example = example; + var spec = example.ReadSpec(); + _editor.ExampleMode = true; + _editor.Load(spec.Request); + _exampleEditor.Load(spec); + _response.Visible = false; + _exampleEditor.Visible = true; + _responseFrame.Title = "Example response"; + UpdateTitles(); + return true; + } + + /// The editor goes back to requests (its changes to the example committed before), and the response pane with it. + private void LeaveExample() + { + if (_example is null && !_editor.ExampleMode) + { + return; + } + + _example = null; + _editor.ExampleMode = false; + _exampleEditor.MarkClean(); + _exampleEditor.Visible = false; + _response.Visible = true; + SetResponseTitle(null); + } + private void StartScratchRequest() { + LeaveExample(); _scratch ??= PostmanCollection.Create("Scratch"); _collection = _scratch; _node = null; @@ -389,6 +470,26 @@ private void StartScratchRequest() /// Writes pending editor changes into the in-memory collection (not to disk). private void CommitEditor() { + if (_example is not null && _collection is not null) + { + if (_editor.IsModified || _exampleEditor.IsModified) + { + var spec = _example.ReadSpec(); + spec.Request = _editor.Spec; + _exampleEditor.ApplyTo(spec); + if (_collection.UpdateExample(_example, spec)) + { + _tree.RefreshItem(_collection); + } + + _editor.MarkClean(); + _exampleEditor.MarkClean(); + UpdateTitles(); + } + + return; + } + if (_node is null || _collection is null || !_editor.IsModified) { return; @@ -409,7 +510,7 @@ private void CommitEditor() /// private bool ConfirmDiscardRequest() { - if (_node is not null || !_editor.IsModified) + if (_node is not null || _example is not null || !_editor.IsModified) { return true; } @@ -476,6 +577,12 @@ private async Task SendAsync() return; } + if (_example is not null) + { + Notify($"An example is not sent: open its request, '{_example.Request.Name}', to send it."); + return; + } + // A curl command typed (or pasted keystroke by keystroke) into the URL bar is imported rather than sent. if (CurlImporter.LooksLikeCurl(_editor.Spec.Url)) { @@ -609,7 +716,7 @@ private void Save() { Notify($"⚠ Not saved: {string.Join(", ", changed)} changed on disk."); } - else if (_node is null && _editor.IsModified) + else if (_node is null && _example is null && _editor.IsModified) { Notify("This request is not in a collection yet: press Ctrl+N (Request > New request) to add it to one."); } @@ -653,13 +760,14 @@ private void Save() PostmanCollection collection => collection.RootNode, FolderNode folder => folder, RequestNode request => request.Parent, + ExampleNode example => example.Request.Parent, _ => _workspace.Collections.FirstOrDefault()?.RootNode, }; } private void NewRequest() { - var adopting = _node is null; // the request in the editor becomes the new one (see AddRequest) + var adopting = _node is null && _example is null; // the request in the editor becomes the new one (see AddRequest) if (AddRequest() is not { } node) { return; @@ -712,7 +820,7 @@ private void NewRequest() CommitEditor(); HttpRequestSpec? spec = null; - if (_node is null) + if (_node is null && _example is null) { // A scratch, imported or history request becomes the new request. spec = _editor.Spec.Clone(); @@ -776,6 +884,11 @@ private void RenameItem(object? item) _tree.RefreshItem(node); _tree.RefreshItem(node.Collection); break; + case ExampleNode example when Ui.PromptText(App!, "Rename example", "Name", example.Name) is { Length: > 0 } name: + example.Collection.RenameExample(example, name.Trim()); + _tree.RefreshItem(example); + _tree.RefreshItem(example.Collection); + break; } UpdateTitles(); @@ -783,6 +896,20 @@ private void RenameItem(object? item) private void DuplicateItem(object? item) { + if (item is ExampleNode example) + { + CommitEditor(); + var copied = example.Collection.DuplicateExample(example); + _tree.RefreshItem(example.Request); + _tree.RefreshItem(example.Collection); + if (OpenExample(copied)) + { + _tree.Select(copied); + } + + return; + } + if (item is not CollectionNode node || node.Parent is null) { return; @@ -805,6 +932,32 @@ private void DeleteItem(object? item) return; } + if (item is ExampleNode example) + { + if (!Ui.Confirm(App!, "Delete", $"Delete example '{example.Name}' of '{example.Request.Name}'? You can undo by not saving (Ctrl+S writes the change).", "Delete", "Cancel")) + { + return; + } + + var wasOpen = example == _example; + if (wasOpen) + { + _example = null; // its edits go with it + _editor.MarkClean(); + } + + example.Collection.RemoveExample(example); + _tree.RefreshItem(example.Request); + _tree.RefreshItem(example.Collection); + if (wasOpen && OpenRequest(example.Request)) + { + _tree.Select(example.Request); + } + + UpdateTitles(); + return; + } + if (item is not CollectionNode node || node.Parent is not { } parent) { return; @@ -816,11 +969,13 @@ private void DeleteItem(object? item) return; } - // Only the request open in the editor makes way: one that is not in a collection stays. - var openDeleted = _node is not null && (_node == node || _node.Ancestors().Contains(node)); + // Only the request open in the editor makes way (or the example of it open): one that is not in a collection stays. + var shown = _node ?? _example?.Request; + var openDeleted = shown is not null && (shown == node || shown.Ancestors().Contains(node)); if (openDeleted) { _node = null; + _example = null; _editor.MarkClean(); } @@ -834,6 +989,7 @@ private void DeleteItem(object? item) if (openDeleted) { DetachSending(); + LeaveExample(); _collection = null; _editor.Load(new HttpRequestSpec()); ClearResponse(); @@ -861,10 +1017,15 @@ private void ShowContextMenu(System.Drawing.Point? position) if (item is not null) { items.Add(new Line()); + if (item is ExampleNode toOpen) + { + items.Add(new MenuItem("_Open", "", () => OpenExample(toOpen))); + } + items.Add(new MenuItem("Re_name…", "", () => RenameItem(item))); } - if (item is CollectionNode) + if (item is CollectionNode or ExampleNode) { items.Add(new MenuItem("_Duplicate", "", () => DuplicateItem(item))); items.Add(new MenuItem("De_lete…", "", () => DeleteItem(item))); @@ -1558,10 +1719,11 @@ internal void ImportCollectionFrom(string path) private void ReloadCollection(PostmanCollection loaded) { - var reopen = _collection == loaded ? _node?.PathInCollection : null; + // An example shown makes way for its request in the reloaded collection. + var reopen = _collection == loaded ? (_node ?? _example?.Request)?.PathInCollection : null; // A request from history stays in the editor, with the reloaded collection's variables. - var fromHistory = _collection == loaded && _node is null; + var fromHistory = _collection == loaded && _node is null && _example is null; // Loaded first: a file that no longer loads throws, and the editor goes on editing its request. var reloaded = _workspace.ReloadCollection(loaded); @@ -1572,6 +1734,7 @@ private void ReloadCollection(PostmanCollection loaded) _node = null; _collection = null; _editor.MarkClean(); + LeaveExample(); } string? originGone = null; @@ -1638,6 +1801,47 @@ private void ImportEnvironment() } } + /// + /// Saves the response shown as an example of its request (Postman's Save Response › Save as example): the request as the + /// editor has it, and the response's status, headers and text. Asks for its name (: for tests). + /// + internal void SaveResponseAsExample(string? name = null) + { + if (_example is not null || _response.Exchange?.Response is not { } response) + { + Notify("No response to save as an example: send the request first."); + return; + } + + // A response of a request from the history goes to the request it was sent from, while that is still there. + if ((_node ?? _historyOrigin) is not { } request) + { + Notify("Examples belong to a request in a collection: add this one to a collection first (Ctrl+N)."); + return; + } + + if (name is null && response.Body.LongLength > ResponseView.MaxShownLength + && !Ui.Confirm(App!, "Save as example", $"The body is {HttpExchange.FormatSize(response.Body.LongLength)}: the collection grows by as much. Save it in the example anyway?", "Save", "Cancel")) + { + return; + } + + name ??= Ui.PromptText(App!, "Save as example", $"Example name (of {request.Name})", $"{response.StatusCode} {response.ReasonPhrase}".Trim()); + if (name?.Trim() is not { Length: > 0 } exampleName) + { + return; + } + + CommitEditor(); + var spec = ExampleMapper.FromResponse(exampleName, _editor.Spec, response, out var note); + var example = request.Collection.AddExample(request, spec); + _tree.RefreshItem(request); + _tree.ExpandItem(request); + _tree.RefreshItem(request.Collection); + UpdateTitles(); + Notify($"Saved example '{example.Name}' of '{request.Name}'; Ctrl+S writes it{(note is null ? "." : $" · ⚠ {note}")}"); + } + private void CopyAsCurl() { // As Send: a request typed into the editor a delete emptied is a scratch request. @@ -1738,6 +1942,7 @@ internal bool OpenHistoryEntry(HistoryEntry entry) CommitEditor(); DetachSending(); _node = null; + LeaveExample(); // Variables keep resolving against the request's collection while it is still in the workspace. When several have its // name and which one it was is not known, the request is sent on its own. @@ -2033,6 +2238,7 @@ private void ApplyImportedCurl(CurlImportResult imported, bool intoCurrent) CommitEditor(); DetachSending(); _node = null; + LeaveExample(); _historyEntry = null; _historyOrigin = null; _collection = _scratch ??= PostmanCollection.Create("Scratch"); @@ -2042,7 +2248,7 @@ private void ApplyImportedCurl(CurlImportResult imported, bool intoCurrent) } UpdateTitles(); - var next = _node is null ? "Ctrl+N adds it to a collection." : "Ctrl+S saves it."; + var next = _node is null && _example is null ? "Ctrl+N adds it to a collection." : "Ctrl+S saves it."; if (imported.Warnings.Count == 0) { Notify($"Imported from cURL: {spec.Method} {spec.Url}. {next}"); @@ -2136,9 +2342,14 @@ private void ShowWorkspaceInfo() $"Proxy: {DescribeProxy()}\n" + $"History: {(_runner.History is { } history ? history.Folder : "off")}\n" + $"Recording: {(_runner.Recorder is { } recorder ? $"on since {recorder.StartedAt:HH:mm:ss}, {recorder.Count} request(s), temporary files in {recorder.TempDirectory}" : $"off (temporary files go to {RequestRecorder.DefaultTempRoot()})")}"; - if (_workspace.LoadErrors.Count > 0) + // With what was found since (an example file that could not be read when its request was first expanded, say). + var problems = _workspace.LoadErrors + .Concat(_workspace.Collections.SelectMany(c => c.LoadWarnings.Select(w => $"{c.Name}: {w}"))) + .Distinct(StringComparer.Ordinal) + .ToList(); + if (problems.Count > 0) { - info += "\n\nProblems while loading:\n" + string.Join('\n', _workspace.LoadErrors); + info += "\n\nProblems while loading:\n" + string.Join('\n', problems); } Ui.ShowText(App!, "Workspace", info); @@ -2197,8 +2408,10 @@ private void ShowPopover(List items, System.Drawing.Point? position) private void UpdateTitles() { - var dirty = _editor.IsModified || _collection?.IsDirty == true ? " ●" : ""; - var title = _node is not null + var dirty = _editor.IsModified || _exampleEditor.IsModified || _collection?.IsDirty == true ? " ●" : ""; + var title = _example is { } example + ? $"Example — {_workspace.DisplayName(example.Collection)} / {example.Request.PathInCollection} / {example.Name}{dirty}" + : _node is not null ? $"Request — {_workspace.DisplayName(_node.Collection)} / {_node.PathInCollection}{dirty}" : _historyEntry is { } entry ? $"Request (from history · {entry.Time.ToLocalTime():yyyy-MM-dd HH:mm:ss}){dirty}" diff --git a/src/TermRest.Tui/Views/CollectionTree.cs b/src/TermRest.Tui/Views/CollectionTree.cs index 124150b..ec8368f 100644 --- a/src/TermRest.Tui/Views/CollectionTree.cs +++ b/src/TermRest.Tui/Views/CollectionTree.cs @@ -131,13 +131,25 @@ public void RefreshAll() public void Select(object item) { - if (item is CollectionNode node) + // An example is under its request: the request's folders and the request open for it. + var node = item switch + { + CollectionNode collectionNode => collectionNode, + ExampleNode example => example.Request, + _ => null, + }; + if (node is not null) { _tree.Expand(node.Collection); foreach (var ancestor in node.Ancestors().Reverse()) { _tree.Expand(ancestor is CollectionRootNode ? node.Collection : ancestor); } + + if (item is ExampleNode) + { + _tree.Expand(node); + } } _tree.SelectedObject = item; @@ -160,16 +172,18 @@ public void Select(object item) { PostmanCollection collection => collection.RootNode.Children, FolderNode folder => folder.Children, + RequestNode request => request.Collection.GetExamples(request), // read when first expanded (a v3 collection's are files) _ => [], }; - private static bool CanExpand(object item) => item is PostmanCollection or FolderNode; + private static bool CanExpand(object item) => item is PostmanCollection or FolderNode || (item is RequestNode request && request.Collection.HasExamples(request)); private string Describe(object item) => Ui.Drawable(item switch { PostmanCollection collection => $"{(collection.IsDirty ? "● " : "")}{_workspace.DisplayName(collection)}", FolderNode folder => folder.Name, RequestNode request => $"{ShortMethod(request.Method),-4} {request.Name}", + ExampleNode example => $"e.g. {example.Name}", _ => item.ToString() ?? "", }); diff --git a/src/TermRest.Tui/Views/ExampleResponseEditor.cs b/src/TermRest.Tui/Views/ExampleResponseEditor.cs new file mode 100644 index 0000000..d80ce97 --- /dev/null +++ b/src/TermRest.Tui/Views/ExampleResponseEditor.cs @@ -0,0 +1,199 @@ +using System.Globalization; +using Terminal.Gui.ViewBase; +using Terminal.Gui.Views; +using TermRest.Core.Http; +using TermRest.Core.Json; +using TermRest.Core.Model; +using TermRest.Tui.Dialogs; + +namespace TermRest.Tui.Views; + +/// +/// Editor of a saved example's response, in the response pane's place while an example is open: its status code and +/// reason, the language of its body, and Body and Headers tabs. writes what was edited into an +/// example; what was not edited stays exactly as the example has it. +/// +internal sealed class ExampleResponseEditor : View +{ + private static readonly string[] LanguageLabels = ["JSON", "XML", "HTML", "JavaScript", "Text"]; + + private readonly TextField _code; + private readonly TextField _status; + private readonly OptionSelector _language; + private readonly Button _beautify; + private readonly Button _wrap; + private readonly Label _bodyNote; + private readonly TextArea _body; + private readonly KeyValueTable _headers; + private List _headerEntries = []; + + /// The body's language as the example says, also one that is not among the choices (yaml, say). + private string? _languageValue; + + private Edits _edited; + private bool _bodyEditable = true; + private bool _loading; + + public ExampleResponseEditor() + { + CanFocus = true; + Width = Dim.Fill(); + Height = Dim.Fill(); + + var statusLabel = new Label { Text = "Status", X = 0, Y = 0 }; + _code = new TextField { X = Pos.Right(statusLabel) + 1, Y = 0, Width = 5 }; + _code.TextChanged += (_, _) => Edited(Edits.Code); + _status = new TextField { X = Pos.Right(_code) + 1, Y = 0, Width = 22 }; + _status.TextChanged += (_, _) => Edited(Edits.Status); + _language = new OptionSelector { X = Pos.Right(_status) + 2, Y = 0, Orientation = Orientation.Horizontal, Labels = LanguageLabels, Value = LanguageLabels.Length - 1 }; + _language.ValueChanged += (_, e) => + { + if (!_loading && e.NewValue is int index) + { + _languageValue = ExampleSpec.Languages[index]; + ColorBody(); + Edited(Edits.Language); + } + }; + + var tabs = new TabPanel { X = 0, Y = 1, Width = Dim.Fill(), Height = Dim.Fill() }; + var bodyTab = new View { Title = "Body", Width = Dim.Fill(), Height = Dim.Fill(), CanFocus = true }; + _beautify = new Button { Text = "Beautify", X = 0, Y = 0, NoDecorations = true, ShadowStyle = null }; + _beautify.Accepted += (_, _) => Beautify(); + _wrap = new Button { Text = "Wrap: off", X = Pos.Right(_beautify) + 2, Y = 0, NoDecorations = true, ShadowStyle = null }; + _wrap.Accepted += (_, _) => + { + _body!.WordWrap = !_body.WordWrap; + _wrap.Text = _body.WordWrap ? "Wrap: on" : "Wrap: off"; + }; + _bodyNote = new Label { HotKeySpecifier = Ui.NoHotKey, X = Pos.Right(_wrap) + 2, Y = 0, Width = Dim.Fill(), Height = 1, Text = "" }; + _body = new TextArea { X = 0, Y = 1, Width = Dim.Fill(), Height = Dim.Fill() }; + _body.UserEdited += (_, _) => Edited(Edits.Body); + bodyTab.Add(_beautify, _wrap, _bodyNote, _body); + + var headersTab = new View { Title = "Headers", Width = Dim.Fill(), Height = Dim.Fill(), CanFocus = true }; + _headers = new KeyValueTable(KeyValueKind.Headers); + _headers.Changed += (_, _) => Edited(Edits.Headers); + headersTab.Add(_headers); + + tabs.AddTabs(bodyTab, headersTab); + Add(statusLabel, _code, _status, _language, tabs); + } + + [Flags] + private enum Edits + { + None = 0, + Code = 1, + Status = 2, + Language = 4, + Headers = 8, + Body = 16, + } + + /// Whether something was edited since or . + public bool IsModified => _edited != Edits.None; + + /// Raised after the user edits something. + public event EventHandler? Modified; + + /// The body as shown (for tests). + internal TextArea BodyArea => _body; + + /// The status code field (for tests). + internal TextField CodeField => _code; + + public void Load(ExampleSpec spec) + { + _loading = true; + try + { + _code.Text = spec.Code?.ToString(CultureInfo.InvariantCulture) ?? ""; + _status.Text = spec.Status; + _languageValue = spec.Language; + var index = Array.IndexOf(ExampleSpec.Languages, spec.Language ?? ""); + _language.Value = index >= 0 ? index : LanguageLabels.Length - 1; + _headerEntries = KeyValueEntry.CloneList(spec.Headers); + _headers.SetEntries(_headerEntries); + + // The editor takes about 90 bytes of memory for each character: a body longer than the response pane shows is + // shown read-only, cut, and kept as it is. + _bodyEditable = spec.Body.Length <= ResponseView.MaxShownLength; + _body.ReadOnly = !_bodyEditable; + _body.SetText(_bodyEditable ? spec.Body : spec.Body[..ResponseView.MaxShownLength]); + _bodyNote.Text = _bodyEditable ? "" : $"⚠ {HttpExchange.FormatSize(spec.Body.Length)}: too long to edit here; shown cut, kept as it is"; + ColorBody(); + } + finally + { + _loading = false; + } + + _edited = Edits.None; + } + + /// Writes what was edited into 's response (a status code that is not a number is not taken). + public void ApplyTo(ExampleSpec spec) + { + if (_edited.HasFlag(Edits.Code)) + { + var text = _code.Text.Trim(); + if (text.Length == 0) + { + spec.Code = null; + } + else if (int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var code)) + { + spec.Code = code; + } + } + + if (_edited.HasFlag(Edits.Status)) + { + spec.Status = _status.Text; + } + + if (_edited.HasFlag(Edits.Language)) + { + spec.Language = _languageValue; + } + + if (_edited.HasFlag(Edits.Headers)) + { + spec.Headers = KeyValueEntry.CloneList(_headerEntries); + } + + if (_edited.HasFlag(Edits.Body) && _bodyEditable) + { + spec.Body = _body.GetText(); + } + } + + public void MarkClean() => _edited = Edits.None; + + private void Edited(Edits what) + { + if (_loading) + { + return; + } + + _edited |= what; + Modified?.Invoke(this, EventArgs.Empty); + } + + private void ColorBody() + { + _body.SyntaxLanguage = _languageValue is "json" or "xml" or "html" or "javascript" ? _languageValue : null; + _beautify.Visible = _languageValue == "json" && _bodyEditable; + } + + private void Beautify() + { + if (_bodyEditable && PostmanJson.TryPrettyPrint(_body.GetText()) is { } pretty) + { + _body.SetText(pretty); + Edited(Edits.Body); + } + } +} diff --git a/src/TermRest.Tui/Views/RequestEditor.cs b/src/TermRest.Tui/Views/RequestEditor.cs index 6255dd8..971ef2b 100644 --- a/src/TermRest.Tui/Views/RequestEditor.cs +++ b/src/TermRest.Tui/Views/RequestEditor.cs @@ -32,8 +32,10 @@ internal sealed class RequestEditor : View private readonly OptionSelector _followRedirects; private readonly Label _certificateInfo; private readonly TextArea _description; + private readonly View[] _exampleTabs; private bool _loading; private bool _syncing; + private bool _exampleMode; public RequestEditor() { @@ -68,7 +70,7 @@ public RequestEditor() }; _url.KeyDown += (_, key) => { - if (key == Key.Enter) + if (key == Key.Enter && !_exampleMode) { SendRequested?.Invoke(this, EventArgs.Empty); key.Handled = true; @@ -158,6 +160,7 @@ public RequestEditor() _description); _tabs.AddTabs(_paramsTab, headersTab, authTab, bodyTab, scriptsTab, settingsTab); + _exampleTabs = [_paramsTab, headersTab, bodyTab]; _tabs.ValueChanged += (_, e) => { if (e.NewValue == settingsTab) @@ -174,6 +177,27 @@ public RequestEditor() public bool IsModified { get; private set; } + /// + /// Edits the request of a saved example: its method, URL, parameters, headers and body, as Postman's example editor + /// does. An example is not sent: Send is hidden, and Enter in the URL bar does nothing. + /// + public bool ExampleMode + { + get => _exampleMode; + set + { + if (_exampleMode == value) + { + return; + } + + _exampleMode = value; + _tabs.ShowOnly(value ? _exampleTabs : null); + _send.Visible = !value; + _url.Width = value ? Dim.Fill() : Dim.Fill(11); + } + } + public event EventHandler? Modified; public event EventHandler? SendRequested; diff --git a/src/TermRest.Tui/Views/ResponseView.cs b/src/TermRest.Tui/Views/ResponseView.cs index 6735f2d..3c4678d 100644 --- a/src/TermRest.Tui/Views/ResponseView.cs +++ b/src/TermRest.Tui/Views/ResponseView.cs @@ -39,6 +39,7 @@ internal sealed class ResponseView : View private const int MinValueColumns = 10; private readonly Label _status; + private readonly Button _saveExample; private readonly TabPanel _tabs; private readonly View _bodyTab; private readonly TextArea _body; @@ -73,7 +74,11 @@ public ResponseView() Width = Dim.Fill(); Height = Dim.Fill(); - _status = new Label { HotKeySpecifier = Ui.NoHotKey, X = 0, Y = 0, Width = Dim.Fill(), Text = "No response yet. Press F5 (or Enter in the URL bar) to send." }; + _status = new Label { HotKeySpecifier = Ui.NoHotKey, X = 0, Y = 0, Width = Dim.Fill(17), Text = "No response yet. Press F5 (or Enter in the URL bar) to send." }; + + // Saves the response shown as an example of its request (Postman's Save Response › Save as example). + _saveExample = new Button { Text = "Save as example", X = Pos.AnchorEnd(15), Y = 0, NoDecorations = true, ShadowStyle = null, Visible = false }; + _saveExample.Accepted += (_, _) => SaveAsExampleRequested?.Invoke(this, EventArgs.Empty); _tabs = new TabPanel { X = 0, Y = 1, Width = Dim.Fill(), Height = Dim.Fill() }; @@ -181,7 +186,7 @@ public ResponseView() }; } - Add(_status, _tabs, _findBar); + Add(_status, _saveExample, _tabs, _findBar); SetHeaders([]); _scripts.SetText(NoScripts); } @@ -197,6 +202,12 @@ public ResponseView() /// Raised with short user-facing notices (copied, saved, …). public event EventHandler? Notice; + /// Save as example was pressed (shown while a response is). + public event EventHandler? SaveAsExampleRequested; + + /// Whether Save as example is offered (for tests). + internal bool OffersSaveAsExample => _saveExample.Visible; + public HttpExchange? Exchange => _exchange; public string StatusText => _status.Text; @@ -226,6 +237,7 @@ public void Clear() { _exchange = null; _fromHistory = false; + _saveExample.Visible = false; _status.Text = "No response yet. Press F5 (or Enter in the URL bar) to send."; _status.SchemeName = null; ShowBody(""); @@ -244,12 +256,14 @@ public void ShowProgress(string text) { _status.Text = text; _status.SchemeName = null; + _saveExample.Visible = false; } public void ShowSending(PreparedRequest request) { _status.Text = $"Sending {request.Method} {request.Url} … (Esc or Send to cancel)"; _status.SchemeName = null; + _saveExample.Visible = false; _timeline.SetText(DescribeRequest(request, null)); } @@ -264,6 +278,7 @@ public void ShowExchange(HttpExchange exchange, bool fromHistory = false) _exchange = exchange; var response = exchange.Response; var scripts = exchange.Scripts; + _saveExample.Visible = response is not null; if (response is null) { _status.Text = exchange.Cancelled ? "Request cancelled." : $"Error: {exchange.ErrorMessage}"; diff --git a/src/TermRest.Tui/Views/TabPanel.cs b/src/TermRest.Tui/Views/TabPanel.cs index 0708782..c4b2b6b 100644 --- a/src/TermRest.Tui/Views/TabPanel.cs +++ b/src/TermRest.Tui/Views/TabPanel.cs @@ -22,6 +22,7 @@ internal sealed class TabPanel : View private readonly TabHeader _header; private readonly List _pages = []; + private readonly List _all = []; private readonly Dictionary _lastFocused = []; private View? _value; @@ -35,7 +36,7 @@ public TabPanel() /// Raised after another page was selected. public event EventHandler>? ValueChanged; - /// The pages, in tab order. A page's labels its tab. + /// The pages shown, in tab order (see ). A page's labels its tab. public IReadOnlyList Pages => _pages; /// Position of the selected page in (-1 without pages). @@ -66,6 +67,7 @@ public void AddTabs(params View[] pages) } }; _pages.Add(page); + _all.Add(page); Add(page); } @@ -77,6 +79,22 @@ public void AddTabs(params View[] pages) _header.SetNeedsDraw(); } + /// + /// Shows the tabs of only, in their order of adding (null: all of them). When the selected + /// page is hidden, the first one shown is selected. + /// + public void ShowOnly(IReadOnlyCollection? pages) + { + _pages.Clear(); + _pages.AddRange(pages is null ? _all : _all.Where(pages.Contains)); + if (_value is not null && !_pages.Contains(_value) && _pages.Count > 0) + { + Select(_pages[0], focusPage: _value.HasFocus); + } + + _header.SetNeedsDraw(); + } + /// Selects ; with also moves the focus into it. internal void Select(View? page, bool focusPage) { diff --git a/tests/TermRest.Core.Tests/ExampleTests.cs b/tests/TermRest.Core.Tests/ExampleTests.cs new file mode 100644 index 0000000..b797419 --- /dev/null +++ b/tests/TermRest.Core.Tests/ExampleTests.cs @@ -0,0 +1,226 @@ +using System.Text.Json.Nodes; +using TermRest.Core.Http; +using TermRest.Core.Model; +using TermRest.Core.Postman; +using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Workspace; +using Xunit; + +namespace TermRest.Core.Tests; + +public class ExampleTests +{ + private const string ListExample = "Widgets/.resources/List widgets.resources/examples/200 OK.example.yaml"; + + private static PostmanCollection OpenV3(string root) => Assert.Single(ApiWorkspace.Open(root).Collections); + + private static string F(string root, string path) => Path.Combine(V3Fixture.CollectionPath(root), path.Replace('/', Path.DirectorySeparatorChar)); + + /// The lines of that are not in , and the reverse. + private static (string[] Added, string[] Removed) Diff(string before, string after) + { + var old = before.Split('\n'); + var now = after.Split('\n'); + return ([.. now.Except(old)], [.. old.Except(now)]); + } + + [Fact] + public void V3_examples_are_read_when_first_needed_and_saved_where_they_changed_only() + { + var root = V3Fixture.Create(); + var collection = OpenV3(root); + var list = collection.FindRequest("Widgets/List widgets")!; + var health = collection.FindRequest("Health")!; + + // Known from the request's examples reference, without reading the example files. + Assert.True(collection.HasExamples(list)); + Assert.False(collection.HasExamples(health)); + Assert.Empty((JsonArray)list.Json["response"]!); + + var example = Assert.Single(collection.GetExamples(list)); + var spec = example.ReadSpec(); + Assert.Equal(("200 OK", 200, "OK", "[]", "json"), (spec.Name, spec.Code, spec.Status, spec.Body, spec.Language)); + Assert.Equal(["Content-Type: application/json"], spec.Headers.Select(h => $"{h.Key}: {h.Value}")); + Assert.Equal("GET", spec.Request.Method); + Assert.Same(example, Assert.Single(collection.GetExamples(list))); + + var before = File.ReadAllText(F(root, ListExample)); + var request = File.ReadAllText(F(root, "Widgets/List widgets.request.yaml")); + spec.Body = "[{\"id\": 1}]"; + Assert.True(collection.UpdateExample(example, spec)); + collection.Save(); + + var (added, removed) = Diff(before, File.ReadAllText(F(root, ListExample))); + Assert.Equal([" content: '[{\"id\": 1}]'"], added); + Assert.Equal([" content: '[]'"], removed); + Assert.Equal(request, File.ReadAllText(F(root, "Widgets/List widgets.request.yaml"))); + + var reopened = OpenV3(root); + Assert.Equal("[{\"id\": 1}]", Assert.Single(reopened.GetExamples(reopened.FindRequest("Widgets/List widgets")!)).ReadSpec().Body); + } + + [Fact] + public void A_new_v3_example_gets_a_file_named_for_it_and_its_request_refers_to_the_folder() + { + var root = V3Fixture.Create(); + var collection = OpenV3(root); + var health = collection.FindRequest("Health")!; + var spec = new ExampleSpec + { + Name = "Up: all/good", + Request = health.ReadSpec(), + Code = 200, + Status = "OK", + Headers = [new KeyValueEntry { Key = "Content-Type", Value = "application/json" }], + Body = "{\"status\": \"up\"}", + Language = "json", + }; + collection.AddExample(health, spec); + collection.Save(); + + var file = F(root, ".resources/Health.resources/examples/Up- all-good.example.yaml"); + Assert.StartsWith("$kind: http-example\nname: \"Up: all/good\"\nrequest:\n url: \"{{baseUrl}}/health\"\n method: GET\nresponse:\n statusCode: 200\n", + File.ReadAllText(file), StringComparison.Ordinal); + Assert.EndsWith("order: 1000\n", File.ReadAllText(file), StringComparison.Ordinal); + Assert.Contains("examples: ./.resources/Health.resources/examples\n", File.ReadAllText(F(root, "Health.request.yaml")), StringComparison.Ordinal); + + var reloaded = OpenV3(root); + var read = Assert.Single(reloaded.GetExamples(reloaded.FindRequest("Health")!)).ReadSpec(); + Assert.Equal(("Up: all/good", 200, "{\"status\": \"up\"}", "json"), (read.Name, read.Code, read.Body, read.Language)); + Assert.Equal("{{baseUrl}}/health", read.Request.Url); + } + + [Fact] + public void Renamed_and_deleted_v3_examples_rename_and_delete_their_files() + { + var root = V3Fixture.Create(); + var collection = OpenV3(root); + var list = collection.FindRequest("Widgets/List widgets")!; + var example = Assert.Single(collection.GetExamples(list)); + + collection.RenameExample(example, "Empty list"); + collection.Save(); + Assert.False(File.Exists(F(root, ListExample))); + var renamed = F(root, "Widgets/.resources/List widgets.resources/examples/Empty list.example.yaml"); + Assert.DoesNotContain("name:", File.ReadAllText(renamed), StringComparison.Ordinal); + + collection.RenameExample(example, "empty LIST"); + collection.Save(); + var recased = Directory.EnumerateFiles(Path.GetDirectoryName(renamed)!).Select(Path.GetFileName); + Assert.Equal(["empty LIST.example.yaml"], recased); + + collection.RemoveExample(example); + collection.Save(); + Assert.Empty(Directory.EnumerateFiles(Path.GetDirectoryName(renamed)!)); + var reopened = OpenV3(root); + Assert.Empty(reopened.GetExamples(reopened.FindRequest("Widgets/List widgets")!)); + } + + [Fact] + public void A_v3_collection_exported_or_copied_takes_its_examples_along() + { + var root = V3Fixture.Create(); + var collection = OpenV3(root); + + var exported = (JsonObject)JsonNode.Parse(collection.ExportV21Json())!; + var widgets = (JsonArray)exported["item"]![1]!["item"]!; + var example = (JsonObject)widgets[0]!["response"]![0]!; + Assert.Equal(("200 OK", 200, "OK", "[]", "json"), + (example["name"]!.GetValue(), example["code"]!.GetValue(), example["status"]!.GetValue(), example["body"]!.GetValue(), + example["_postman_previewlanguage"]!.GetValue())); + + var copy = (RequestNode)collection.Duplicate(collection.FindRequest("Widgets/List widgets")!); + collection.Save(); + Assert.Equal("200 OK", Assert.Single(collection.GetExamples(copy)).Name); + Assert.True(File.Exists(F(root, "Widgets/.resources/List widgets Copy.resources/examples/200 OK.example.yaml"))); + } + + [Fact] + public void Examples_of_a_json_collection_are_edited_in_place() + { + const string json = """ + { + "info": { + "name": "Shop", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "Get item", + "request": { + "method": "GET", + "header": [], + "url": "https://shop.example.com/items/1" + }, + "response": [ + { + "id": "6a1f", + "name": "Found", + "originalRequest": { + "method": "GET", + "header": [], + "url": "https://shop.example.com/items/1" + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "cookie": [], + "body": "{\"id\": 1}" + } + ] + } + ] + } + """; + var collection = PostmanCollection.Parse(json); + var item = collection.FindRequest("Get item")!; + var example = Assert.Single(collection.GetExamples(item)); + var spec = example.ReadSpec(); + spec.Code = 404; + spec.Status = "Not Found"; + Assert.True(collection.UpdateExample(example, spec)); + Assert.Equal(json.Replace("\"OK\"", "\"Not Found\"", StringComparison.Ordinal).Replace("200", "404", StringComparison.Ordinal), collection.Serialize()); + + var created = collection.AddExample(item, new ExampleSpec { Name = "Gone", Request = item.ReadSpec(), Code = 410, Status = "Gone", Language = "text" }); + Assert.Equal(["name", "originalRequest", "status", "code", "_postman_previewlanguage", "header", "cookie", "body"], created.Json.Select(p => p.Key)); + Assert.Equal(["Found", "Gone"], collection.GetExamples(item).Select(e => e.Name)); + + var copy = collection.DuplicateExample(example); + Assert.Equal(["Found", "Found Copy", "Gone"], collection.GetExamples(item).Select(e => e.Name)); + Assert.Null(copy.Json["id"]); + + collection.RemoveExample(created); + collection.RemoveExample(copy); + Assert.Equal(json.Replace("\"OK\"", "\"Not Found\"", StringComparison.Ordinal).Replace("200", "404", StringComparison.Ordinal), collection.Serialize()); + } + + [Fact] + public void An_example_made_from_a_response_holds_its_text_and_says_why_a_binary_body_is_left_out() + { + var request = new HttpRequestSpec { Url = "https://shop.example.com/items/1" }; + var json = new ResponseSnapshot + { + StatusCode = 200, + ReasonPhrase = "OK", + Headers = [KeyValuePair.Create("Content-Type", "application/json; charset=utf-8")], + Body = "{\"name\":\"Zoë\"}"u8.ToArray(), + ContentType = "application/json; charset=utf-8", + }; + var example = ExampleMapper.FromResponse("200 OK", request, json, out var note); + Assert.Null(note); + Assert.Equal(("200 OK", 200, "OK", "{\"name\":\"Zoë\"}", "json"), (example.Name, example.Code, example.Status, example.Body, example.Language)); + Assert.Equal(["Content-Type: application/json; charset=utf-8"], example.Headers.Select(h => $"{h.Key}: {h.Value}")); + Assert.Equal(request.Url, example.Request.Url); + + var image = new ResponseSnapshot { StatusCode = 200, ReasonPhrase = "OK", Body = [0x89, 0x50, 0x4E, 0x47], ContentType = "image/png" }; + var picture = ExampleMapper.FromResponse("Logo", request, image, out note); + Assert.Equal(("", "text"), (picture.Body, picture.Language)); + Assert.Contains("image/png", note, StringComparison.Ordinal); + } +} diff --git a/tests/TermRest.Tui.Tests/MainWindowTests.cs b/tests/TermRest.Tui.Tests/MainWindowTests.cs index 837f800..f6beb1f 100644 --- a/tests/TermRest.Tui.Tests/MainWindowTests.cs +++ b/tests/TermRest.Tui.Tests/MainWindowTests.cs @@ -3014,6 +3014,82 @@ void Next(int index) return screens; } + [Fact] + public async Task Save_as_example_keeps_the_response_under_its_request_where_it_opens_for_editing() + { + await using var server = await LocalEchoServer.StartAsync(); + using var ui = new Harness(_directory, runner => runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"); + var offered = false; + var screens = Drive(ui, () => ui.App.InjectKey(Key.F5), + ("200 OK", () => + { + offered = ui.Window.ResponsePane.OffersSaveAsExample; + ui.Window.SaveResponseAsExample("Echoed"); + ui.App.InjectKey(Key.S.WithCtrl); // saved: stopping asks nothing + ui.App.RequestStop(); + })); + Assert.Single(screens); + Assert.True(offered); + OnScreen("Save as example", screens[0]); + + var collection = ui.Workspace.Collections[0]; + var request = collection.FindRequest("Basics/GET with query")!; + var example = Assert.Single(collection.GetExamples(request)); + var spec = example.ReadSpec(); + Assert.Equal(("Echoed", 200, "OK", "json"), (spec.Name, spec.Code, spec.Status, spec.Language)); + Assert.Contains("/echo/get", spec.Body, StringComparison.Ordinal); + Assert.Equal("{{baseUrl}}/get?foo=bar&source=termrest", spec.Request.Url); + + var token = ui.App.Begin(ui.Window); + ui.Click("e.g. Echoed"); + var screen = ui.Screen(); + OnScreen("Example — TermRest Demo / Basics/GET with query / Echoed", screen); + OnScreen("│Params│Headers│Body│", screen); + OnScreen("Example response", screen); + Assert.True(ui.Window.Editor.ExampleMode); + + ui.Window.ExampleEditor.CodeField.Text = "201"; + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.End(token!); + + var saved = PostmanCollection.Load(collection.FilePath!); + var written = Assert.Single(saved.GetExamples(saved.FindRequest("Basics/GET with query")!)).ReadSpec(); + Assert.Equal(("Echoed", 201, "OK"), (written.Name, written.Code, written.Status)); + Assert.Equal(spec.Body, written.Body); + } + + [Fact] + public void An_example_is_not_sent_and_its_edits_are_saved_until_a_request_is_opened() + { + var file = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + var demo = PostmanCollection.Load(file); + var post = demo.FindRequest("Basics/POST JSON")!; + demo.AddExample(post, new ExampleSpec { Name = "Created", Request = post.ReadSpec(), Code = 201, Status = "Created", Body = "{}", Language = "json" }); + demo.Save(); + + using var ui = new Harness(_directory); + var collection = ui.Workspace.Collections[0]; + var request = collection.FindRequest("Basics/POST JSON")!; + var token = ui.App.Begin(ui.Window); + ui.Window.ShowExample(Assert.Single(collection.GetExamples(request))); + + ui.App.InjectKey(Key.F5); + var notice = ui.Window.StatusMessage; + ui.Window.ExampleEditor.BodyArea.SetFocus(); + ui.Type("["); + ui.App.InjectKey(Key.S.WithCtrl); + ui.Window.ShowRequest(request); + var screen = ui.Screen(); + ui.App.End(token!); + + Assert.Contains("An example is not sent", notice, StringComparison.Ordinal); + Assert.False(ui.Window.Editor.ExampleMode); + OnScreen("│Params│Headers│Auth│Body│Scripts│Settings│", screen); + OnScreen("Request — TermRest Demo / Basics/POST JSON", screen); + var saved = PostmanCollection.Load(file); + Assert.Equal("[{}", Assert.Single(saved.GetExamples(saved.FindRequest("Basics/POST JSON")!)).ReadSpec().Body); + } + [Fact] public void Space_and_clicking_the_checkbox_column_turn_table_rows_on_and_off() { From 819d9cdf1390a37311e5d29071a66e5a19bca61d Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Tue, 17 Nov 2026 22:23:30 -0700 Subject: [PATCH 03/11] Core, CLI and TUI: proxy authentication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A proxy that asks for a user name and password (407 Proxy Authentication Required) gets the ones given for it, answered with Basic, Digest, NTLM or Negotiate as it asks: those typed in Tools › Settings › Proxy sign-in, given with send and run's new --proxy-user (user:password, or user to type the password unseen; DOMAIN\user for NTLM), or in the proxy's URL (http://user:password@host:port, also in HTTPS_PROXY), in that order. Proxy sign-in keeps them for the proxy the settings name (or the system's) in proxy-credentials.json in the user's configuration folder, never in the workspace, which comes with its repository: the file is readable by the user only (mode 600 on Unix), and on Windows its passwords are also encrypted for the user's account with DPAPI (through P/Invoke, as Native AOT has no ProtectedData); a password left masked stays, and clearing the user name forgets them. Without any, a proxy that asks for NTLM or Negotiate, as corporate proxies do, gets the user's own sign-in, as browsers give it; .NET sends it to no Basic or Digest proxy. A 407 that comes back (or a tunnel refused with one) says how to give a sign-in. --proxy (-x) sets the proxy of send and run in place of the workspace's (a URL, host:port as curl takes it, system or none), with no approval needed as the user typed it. OAuth 2.0 token requests sign in to the proxy too. The settings dialog keeps fitting a terminal of 30 rows. The README's roadmap no longer lists saved examples and proxy authentication. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 15 +- src/TermRest.Cli/ConsolePassword.cs | 39 ++++ src/TermRest.Cli/RequestOptions.cs | 55 +++++ src/TermRest.Core/Auth/OAuth2Tokens.cs | 1 + src/TermRest.Core/Http/HttpExecutor.cs | 49 ++++- src/TermRest.Core/Http/PreparedRequest.cs | 3 + src/TermRest.Core/Http/RequestPreparer.cs | 7 + src/TermRest.Core/IO/Dpapi.cs | 68 +++++++ .../Workspace/ProxyCredentialStore.cs | 191 ++++++++++++++++++ src/TermRest.Core/Workspace/RequestRunner.cs | 26 ++- .../Workspace/WorkspaceSettings.cs | 1 + src/TermRest.Tui/Dialogs/SettingsDialog.cs | 19 +- src/TermRest.Tui/TuiApp.cs | 5 + tests/TermRest.Cli.Tests/CommandLineTests.cs | 23 +++ .../TermRest.Cli.Tests.csproj | 1 + .../Infrastructure/SignInProxy.cs | 104 ++++++++++ tests/TermRest.Core.Tests/ProxyTests.cs | 130 ++++++++++++ tests/TermRest.Tui.Tests/MainWindowTests.cs | 37 ++++ 18 files changed, 762 insertions(+), 12 deletions(-) create mode 100644 src/TermRest.Cli/ConsolePassword.cs create mode 100644 src/TermRest.Core/IO/Dpapi.cs create mode 100644 src/TermRest.Core/Workspace/ProxyCredentialStore.cs create mode 100644 tests/TermRest.Core.Tests/Infrastructure/SignInProxy.cs create mode 100644 tests/TermRest.Core.Tests/ProxyTests.cs diff --git a/README.md b/README.md index 57c09cd..19acafb 100644 --- a/README.md +++ b/README.md @@ -117,6 +117,14 @@ A `settings.json` or `certificates.json` that can't be read (invalid JSON, a mer A proxy URL in `.termrest/settings.json` (`proxy`) is used only once you allow it for that workspace folder: the file comes with the repository you clone, and a proxy sees every request, with its credentials. Until then, requests use the system's proxy settings (the OS's, `HTTPS_PROXY`), as with `system`; the status bar and *Help › Workspace info* say so, and `send` and `run` print a warning (the proxy's password masked). Saving in *Tools › Settings* allows the proxy shown there; the dialog shows its password masked too, and keeps it while the mask is left in place (also when only the host or port changes). The approval is kept per workspace folder in your user settings (`allowedProxies`) as a SHA-256 hash, never the proxy's URL, which can hold a password; when the file names another proxy (after a `git pull`, say), that one must be allowed again. `system` and `none` need no approval, and the file's other settings, TLS verification and the CA bundle included, apply as they are. +**Proxy sign-in.** A proxy that asks for a user name and password (407 Proxy Authentication Required) gets the ones given for it, answered with Basic, Digest, NTLM or Negotiate (Kerberos), as the proxy asks: + +- in *Tools › Settings › Proxy sign-in*: kept for that proxy (or for the system's) in `proxy-credentials.json` in your user settings folder, never in the workspace. Only you can read the file, and on Windows the password in it is also encrypted for your account (DPAPI). A password left masked stays as it was; clear the user name to forget them; +- with `--proxy-user user:password` on `send` and `run`, or `--proxy-user user` to type the password (`DOMAIN\user` for NTLM); +- in the proxy's URL, `http://user:password@proxy:3128`, also in `HTTPS_PROXY`. + +Without any, a proxy that asks for NTLM or Negotiate, as corporate proxies do, gets your own sign-in (as browsers give it); one that asks for Basic or Digest gets nothing, and the 407 comes back with a note that says how to give one. `--proxy ` (`-x`; `host:port` works too, as in curl) sets the proxy for `send` and `run` in place of the workspace's. + Requests send body and form-data files only from the workspace folder, also once links are resolved: a collection that comes with a repository could otherwise send any file you can read (SSH keys, cloud credentials) to a server of its choosing, with no script needed. A file outside the folder (an absolute path, a `../` path, or a link in the repository that leads out) stops its request with an error that names it; a path outside the folder as written is not even looked at, by the request or by its Body tab, so a Windows `\\server\share` path doesn't reach that server. For the same reason, on Windows, client certificates and the CA bundle (named by a request, `.termrest/certificates.json` or `.termrest/settings.json`) are not opened from a network share outside the folder, nor through a link that leads there: the request is sent without them, with a warning. To send such files and use such certificates, check *Outside files: Allow files from outside this folder* in *Tools › Settings* (kept per workspace folder in your user settings, `outsideFilesAllowed`), or pass `--allow-outside-files` to `send`, `run` or `certs list`. Variables resolve Postman-style. The highest precedence comes first: `--var`/local, then environment, then collection, then globals. Values may reference other variables, and Postman dynamic variables work, with a new value each time: `{{$guid}}` (also `$randomUUID`), `{{$timestamp}}`, `{{$isoTimestamp}}`, `{{$randomInt}}` (0 to 1000), `$randomBoolean`, `$randomAlphaNumeric` and `$randomHexadecimal` (one character), `$randomFirstName`, `$randomLastName`, `$randomFullName`, `$randomUserName`, `$randomEmail`, `$randomWord` and `$randomPassword`. Scripts resolve them too (`.replaceIn`, `.replace_in`, `.ReplaceIn`): `pm.environment.set('email', pm.variables.replaceIn('{{$randomEmail}}'))` keeps one address for the requests that use `{{email}}`. A variable of the same name takes the place of a dynamic one (`$timestamp` set by a script, say), in requests and scripts alike, as in Postman. Unresolved `{{names}}` are kept and reported as warnings. Replacing variables adds at most 4,194,304 characters to a text: a reference whose value would go past that (a value that references itself several times, say) stays unresolved and is reported. @@ -372,6 +380,7 @@ TermRest runs scripts the way a terminal runs commands: it starts the runtime yo - It never chooses a runtime by itself. Runtimes are chosen per workspace folder and kept in your user settings, never in the workspace, so a cloned repository cannot turn its scripts on. *Find* only looks when you press it, and doesn't run a Python it finds in the workspace. A command such as `node` is looked up in the folders of PATH only, so a `node.exe` that a repository ships never runs in its place. *Find* and *Check* run a runtime in TermRest's cache folder, never in the workspace, whose files would otherwise act before you choose it (a `bunfig.toml` that preloads code into Bun, a `global.json` that points `dotnet` to other SDKs). - It never uses a proxy that a workspace names until you allow it: a proxy URL in `.termrest/settings.json` is allowed per workspace folder in your user settings, never in the workspace (*Tools › Settings › Save*, and again whenever it changes), so a cloned repository cannot send your requests through a proxy of its choosing. +- Proxy passwords are never kept in a workspace either: *Proxy sign-in* keeps them in a file of your user settings that only you can read, encrypted for your account on Windows (see [Proxy sign-in](#workspace-layout)). - It never sends a body or form-data file from outside the workspace folder until you allow it for that folder (*Tools › Settings*, or `--allow-outside-files`), so a cloned repository's requests cannot upload your other files. Until then it doesn't open certificates or a CA bundle on a Windows network share outside the folder either, so a cloned repository cannot make Windows sign in to a server of its choosing with your credentials. Scripts are not bound by this: they can read any file. - Without a runtime, the UI sends requests and skips their scripts (`⚠ scripts not run`). On the command line, scripts without a runtime are an error until one is chosen (in the UI, or with `--python`, `--javascript`, `--csharp` or `--powershell`), or until you pass `--no-scripts`. - `tr` and `pm` cannot change collection, environment or settings files: the values scripts set stay in memory until TermRest closes. Recordings redact secrets, in what scripts print too. @@ -708,6 +717,7 @@ termrest snapshot [] [--send] render the UI headlessly (smoke t : a *.postman_collection.json file or a v3 collection folder common options: -e/--env --var key=value --timeout -k/--insecure --record + -x/--proxy -U/--proxy-user --python --javascript --csharp --powershell --script-order --no-scripts --allow-outside-files send options: -i/--include -v/--verbose -o/--output --raw --filter -f/--fail --curl --no-history @@ -814,10 +824,7 @@ Notes: ## Roadmap -- **Next:** saving responses as Postman examples, and showing them in v3 collections. -- **Phase 2:** - - Proxy authentication. - - Code snippets. +- **Next:** code snippets (a request as code in other languages, besides cURL). - **Packaging:** winget, Homebrew, `.deb`/`.rpm`, and signed binaries. ## License diff --git a/src/TermRest.Cli/ConsolePassword.cs b/src/TermRest.Cli/ConsolePassword.cs new file mode 100644 index 0000000..6aca8b3 --- /dev/null +++ b/src/TermRest.Cli/ConsolePassword.cs @@ -0,0 +1,39 @@ +using System.Text; + +namespace TermRest.Cli; + +/// Reads a password typed in the terminal, without showing it. +internal static class ConsolePassword +{ + /// The password typed after (written to stderr), or null when there is no terminal to type it in. + public static string? Read(string prompt) + { + if (Console.IsInputRedirected) + { + return null; + } + + Console.Error.Write(prompt); + var password = new StringBuilder(); + while (true) + { + var key = Console.ReadKey(intercept: true); + if (key.Key == ConsoleKey.Enter) + { + break; + } + + if (key.Key == ConsoleKey.Backspace) + { + password.Length = Math.Max(0, password.Length - 1); + } + else if (key.KeyChar != '\0' && !char.IsControl(key.KeyChar)) + { + password.Append(key.KeyChar); + } + } + + Console.Error.WriteLine(); + return password.ToString(); + } +} diff --git a/src/TermRest.Cli/RequestOptions.cs b/src/TermRest.Cli/RequestOptions.cs index 9c44410..4efe36b 100644 --- a/src/TermRest.Cli/RequestOptions.cs +++ b/src/TermRest.Cli/RequestOptions.cs @@ -54,6 +54,18 @@ internal sealed class RequestOptions Description = "Also send body and form-data files from outside the workspace folder (default: only where allowed for the workspace in the full-screen UI, Tools › Settings…)", }; + public Option Proxy { get; } = new("--proxy", "-x") + { + Description = "The proxy for every request: a URL (http://host:port), \"system\" (the OS's settings, HTTPS_PROXY) or \"none\" " + + "(default: the workspace's, once allowed in the full-screen UI)", + }; + + public Option ProxyUser { get; } = new("--proxy-user", "-U") + { + Description = "The proxy's user name and password: user:password, or user to be asked for the password (DOMAIN\\user for NTLM). " + + "Default: those in the proxy's URL or kept in the full-screen UI (Tools › Settings › Proxy sign-in), else your own sign-in for NTLM and Negotiate proxies", + }; + public void AddTo(Command command) { command.Options.Add(Environment); @@ -67,6 +79,8 @@ public void AddTo(Command command) command.Options.Add(ScriptOrder); command.Options.Add(NoScripts); command.Options.Add(AllowOutsideFiles); + command.Options.Add(Proxy); + command.Options.Add(ProxyUser); } /// @@ -194,6 +208,47 @@ public bool SaveRecording(ParseResult parseResult, RequestRunner runner, Request } runner.ConfigureProxy(); + if (parseResult.GetValue(Proxy) is { } proxyOverride) + { + var value = proxyOverride.Trim(); + if (WorkspaceSettings.IsProxyUrl(value) && !value.Contains("://", StringComparison.Ordinal)) + { + value = "http://" + value; // host:port, as curl takes it + } + + if (WorkspaceSettings.IsProxyUrl(value) && !(Uri.TryCreate(value, UriKind.Absolute, out var proxyUri) && proxyUri.Scheme is "http" or "https" or "socks4" or "socks4a" or "socks5")) + { + Output.Error($"--proxy expects a URL (http://host:port), \"system\" or \"none\", got '{PostmanUrl.MaskCredentials(value)}'."); + runner.Dispose(); + return null; + } + + runner.ProxyOverride = value; + } + + if (parseResult.GetValue(ProxyUser) is { } proxyUser) + { + var colon = proxyUser.IndexOf(':', StringComparison.Ordinal); + var user = colon < 0 ? proxyUser : proxyUser[..colon]; + var password = colon < 0 ? ConsolePassword.Read($"Proxy password for {user}: ") : proxyUser[(colon + 1)..]; + if (user.Trim().Length == 0 || password is null) + { + Output.Error(password is null + ? "--proxy-user: give the password as user:password, as there is no terminal to type it in." + : "--proxy-user expects user:password, or user to be asked for the password."); + runner.Dispose(); + return null; + } + + runner.ProxyCredentialOverride = ProxyCredentialStore.Credential(user.Trim(), password); + } + + if (runner.ProxyCredentials.LoadError is { } credentialsProblem) + { + Output.Warning(credentialsProblem); + Output.Info(" The proxy user names and passwords kept in the full-screen UI are not used until the file is fixed."); + } + if (runner.BlockedProxy is { } proxy) { Output.Warning($"The proxy in {workspace.SettingsPath} ({PostmanUrl.MaskCredentials(proxy.Trim())}) is not used, as a cloned repository could send " + diff --git a/src/TermRest.Core/Auth/OAuth2Tokens.cs b/src/TermRest.Core/Auth/OAuth2Tokens.cs index d40b4a9..f370661 100644 --- a/src/TermRest.Core/Auth/OAuth2Tokens.cs +++ b/src/TermRest.Core/Auth/OAuth2Tokens.cs @@ -508,6 +508,7 @@ private static PreparedRequest BuildRequest(string url, List SendAsync(PreparedRequest request, CancellationT } headersAt = clock.Elapsed; + if (response.StatusCode == HttpStatusCode.ProxyAuthenticationRequired) + { + request.Warnings.Add(ProxySignInHint); + } + var (body, truncated, received, warning) = await ReadBodyAsync(response, request.MaxResponseBytes, linked.Token).ConfigureAwait(false); exchange.Response = Snapshot(response, body, truncated, received); if (warning is not null) @@ -216,13 +221,22 @@ private SocketsHttpHandler CreateHandler(PreparedRequest request, ConnectionCapt case null or "" or "system": handler.UseProxy = true; capture.Proxy = HttpClient.DefaultProxy; // the one the handler uses + + // Its sign-in: the user name and password given for it, else the user's own, which .NET sends only to an NTLM or + // Negotiate (Kerberos) challenge, never to a Basic or Digest one. A proxy HTTPS_PROXY names with a user and + // password signs in with those. + handler.DefaultProxyCredentials = request.ProxyCredential ?? CredentialCache.DefaultCredentials; break; case "none": handler.UseProxy = false; break; default: handler.UseProxy = true; - handler.Proxy = capture.Proxy = new WebProxy(request.Proxy!.Trim()); + var proxy = request.Proxy!.Trim(); + handler.Proxy = capture.Proxy = new WebProxy(proxy) + { + Credentials = request.ProxyCredential ?? CredentialsInUrl(proxy) ?? CredentialCache.DefaultCredentials, + }; break; } @@ -264,6 +278,27 @@ private SocketsHttpHandler CreateHandler(PreparedRequest request, ConnectionCapt return handler; } + /// + /// The user name and password in a proxy's URL (http://user:password@host:port), as curl and HTTPS_PROXY + /// take them: percent-escapes decoded, a user name with a domain (CONTOSO%5Cada) for NTLM. Null without one. + /// + internal static NetworkCredential? CredentialsInUrl(string proxy) + { + if (!Uri.TryCreate(proxy, UriKind.Absolute, out var uri) || uri.UserInfo.Length == 0) + { + return null; + } + + var colon = uri.UserInfo.IndexOf(':', StringComparison.Ordinal); + var user = Uri.UnescapeDataString(colon < 0 ? uri.UserInfo : uri.UserInfo[..colon]); + return Workspace.ProxyCredentialStore.Credential(user, colon < 0 ? "" : Uri.UnescapeDataString(uri.UserInfo[(colon + 1)..])); + } + + /// What a 407 from the proxy means, and how to give it a user name and password. + internal const string ProxySignInHint = + "The proxy asks for a user name and password (407 Proxy Authentication Required), or did not accept those it got: give them in " + + "Tools › Settings (Proxy sign-in), with --proxy-user, or in the proxy's URL (http://user:password@host:port)."; + /// /// SChannel sends the chain it builds from the certificate stores. Creating a context adds the chain's CA certificates /// that Windows can't find to the intermediate store (CurrentUser\CA), which is how a context's chain gets sent on @@ -670,6 +705,18 @@ private static string DescribeError(Exception ex, ConnectionCapture capture, Uri } summary = MaskUrlPasswords(summary); + + // A tunnel (https through the proxy) that the proxy refused with 407: what it wants. + for (var e = ex; e is not null; e = e.InnerException) + { + if (e is HttpRequestException { StatusCode: HttpStatusCode.ProxyAuthenticationRequired } + || (e is HttpRequestException { HttpRequestError: HttpRequestError.ProxyTunnelError } && e.Message.Contains("'407'", StringComparison.Ordinal))) + { + summary += $". {ProxySignInHint}"; + break; + } + } + return ex is HttpRequestException { HttpRequestError: not HttpRequestError.Unknown } hre ? $"{hre.HttpRequestError}: {summary}" : summary; } diff --git a/src/TermRest.Core/Http/PreparedRequest.cs b/src/TermRest.Core/Http/PreparedRequest.cs index 2a1c06c..aa9aec8 100644 --- a/src/TermRest.Core/Http/PreparedRequest.cs +++ b/src/TermRest.Core/Http/PreparedRequest.cs @@ -309,6 +309,9 @@ public sealed class PreparedRequest /// Null/"system" = OS proxy, "none" = direct, otherwise a proxy URL. public string? Proxy { get; set; } + /// The proxy's user name and password (see ); never recorded. + public System.Net.NetworkCredential? ProxyCredential { get; set; } + public long MaxResponseBytes { get; set; } = 50L * 1024 * 1024; public List Warnings { get; } = []; diff --git a/src/TermRest.Core/Http/RequestPreparer.cs b/src/TermRest.Core/Http/RequestPreparer.cs index b85997f..5e20d41 100644 --- a/src/TermRest.Core/Http/RequestPreparer.cs +++ b/src/TermRest.Core/Http/RequestPreparer.cs @@ -25,6 +25,12 @@ public sealed class ExecutionDefaults public string? Proxy { get; set; } + /// + /// The user name and password for the proxy (see ): given on the command line, or kept for it in the + /// user's settings. Null: those in the proxy's URL, else the user's own sign-in (NTLM and Negotiate only). + /// + public System.Net.NetworkCredential? ProxyCredential { get; set; } + public long MaxResponseBytes { get; set; } = 50L * 1024 * 1024; public string HttpVersion { get; set; } = "1.1"; @@ -184,6 +190,7 @@ public PreparedRequest Prepare(HttpRequestSpec spec, AuthSpec? effectiveAuth, st prepared.UseCookies = !(spec.Settings.DisableCookies ?? false); prepared.Timeout = defaults.Timeout; prepared.Proxy = defaults.Proxy; + prepared.ProxyCredential = defaults.ProxyCredential; prepared.HttpVersion = defaults.HttpVersion; prepared.MaxResponseBytes = defaults.MaxResponseBytes; prepared.ExtraTrustedCertificates = LoadTrust(prepared.Warnings); diff --git a/src/TermRest.Core/IO/Dpapi.cs b/src/TermRest.Core/IO/Dpapi.cs new file mode 100644 index 0000000..1d5af18 --- /dev/null +++ b/src/TermRest.Core/IO/Dpapi.cs @@ -0,0 +1,68 @@ +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Security.Cryptography; + +namespace TermRest.Core.IO; + +/// +/// Windows' Data Protection API (DPAPI): encrypts data for the signed-in user, so that only that user's account can decrypt +/// it. Used through P/Invoke, as Native AOT has no System.Security.Cryptography.ProtectedData. +/// +[SupportedOSPlatform("windows")] +internal static partial class Dpapi +{ + /// CRYPTPROTECT_UI_FORBIDDEN: fail rather than show a prompt. + private const int UiForbidden = 0x1; + + public static byte[] Protect(ReadOnlySpan data, ReadOnlySpan entropy) => Transform(data, entropy, protect: true); + + /// The data was protected for another user or computer, or is damaged. + public static byte[] Unprotect(ReadOnlySpan data, ReadOnlySpan entropy) => Transform(data, entropy, protect: false); + + private static unsafe byte[] Transform(ReadOnlySpan data, ReadOnlySpan entropy, bool protect) + { + fixed (byte* input = data) + fixed (byte* salt = entropy) + { + var inBlob = new Blob { Size = data.Length, Data = (IntPtr)input }; + var saltBlob = new Blob { Size = entropy.Length, Data = (IntPtr)salt }; + var ok = protect + ? CryptProtectData(ref inBlob, IntPtr.Zero, ref saltBlob, IntPtr.Zero, IntPtr.Zero, UiForbidden, out var outBlob) + : CryptUnprotectData(ref inBlob, IntPtr.Zero, ref saltBlob, IntPtr.Zero, IntPtr.Zero, UiForbidden, out outBlob); + if (!ok) + { + throw new CryptographicException(Marshal.GetLastPInvokeError()); + } + + try + { + return new ReadOnlySpan((void*)outBlob.Data, outBlob.Size).ToArray(); + } + finally + { + LocalFree(outBlob.Data); + } + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct Blob + { + public int Size; + public IntPtr Data; + } + + [LibraryImport("crypt32.dll", SetLastError = true)] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CryptProtectData(ref Blob dataIn, IntPtr description, ref Blob entropy, IntPtr reserved, IntPtr prompt, int flags, out Blob dataOut); + + [LibraryImport("crypt32.dll", SetLastError = true)] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool CryptUnprotectData(ref Blob dataIn, IntPtr description, ref Blob entropy, IntPtr reserved, IntPtr prompt, int flags, out Blob dataOut); + + [LibraryImport("kernel32.dll")] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + private static partial IntPtr LocalFree(IntPtr memory); +} diff --git a/src/TermRest.Core/Workspace/ProxyCredentialStore.cs b/src/TermRest.Core/Workspace/ProxyCredentialStore.cs new file mode 100644 index 0000000..9a6d16a --- /dev/null +++ b/src/TermRest.Core/Workspace/ProxyCredentialStore.cs @@ -0,0 +1,191 @@ +using System.Net; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using TermRest.Core.IO; + +namespace TermRest.Core.Workspace; + +/// +/// The user names and passwords the user gave for proxies (Tools › Settings › Proxy sign-in): kept in +/// proxy-credentials.json in the user's configuration folder (see ), never +/// in a workspace, whose settings come with its repository. Only the user can read the file (on Unix it is written with +/// mode 600), and on Windows the passwords in it are encrypted for the user's account (DPAPI) too. +/// +public sealed class ProxyCredentialStore +{ + public const string FileName = "proxy-credentials.json"; + + /// The key of the credentials for the system's proxy (the OS's settings, HTTPS_PROXY). + public const string SystemProxy = "system"; + + private const string DpapiPrefix = "dpapi:"; + private const UnixFileMode PrivateFile = UnixFileMode.UserRead | UnixFileMode.UserWrite; + private static readonly byte[] Entropy = "TermRest proxy credentials"u8.ToArray(); + + private readonly Dictionary _entries; + + private ProxyCredentialStore(Dictionary entries, string? loadError) + { + _entries = entries; + LoadError = loadError; + } + + /// Why the file could not be read (path: problem), if it could not: does not save over it then. + public string? LoadError { get; } + + public static ProxyCredentialStore Empty() => new(new Dictionary(StringComparer.Ordinal), null); + + /// Reads the file from (default: ); empty when there is none. + public static ProxyCredentialStore Load(string? directory = null) + { + var path = Path.Combine(directory ?? UserSettings.DefaultDirectory(), FileName); + if (!File.Exists(path)) + { + return Empty(); + } + + try + { + var (text, _) = TextFile.Read(path); + var file = JsonSerializer.Deserialize(text, CoreJsonContext.Default.ProxyCredentialFile); + return new ProxyCredentialStore(new Dictionary(file?.Proxies ?? new(), StringComparer.Ordinal), null); + } + catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) + { + return new ProxyCredentialStore(new Dictionary(StringComparer.Ordinal), $"{path}: {ex.Message}"); + } + } + + /// + /// The key credentials are kept under for a proxy setting (see ): system for + /// the system's proxy, scheme://host:port for a proxy URL (its user, password and path left out), null for none. + /// + public static string? KeyOf(string? proxy) + { + var value = proxy?.Trim(); + if (string.IsNullOrEmpty(value) || value.Equals("system", StringComparison.OrdinalIgnoreCase)) + { + return SystemProxy; + } + + if (value.Equals("none", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + return Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Host.Length > 0 + ? $"{uri.Scheme}://{uri.Host}:{uri.Port}".ToLowerInvariant() + : value.ToLowerInvariant(); + } + + /// + /// The user name and password kept for , if any. A password that can't be decrypted (encrypted by + /// another account or computer) is none: the user name goes without one. + /// + public NetworkCredential? Find(string? proxy) => + KeyOf(proxy) is { } key && _entries.TryGetValue(key, out var entry) && entry.User.Length > 0 ? Credential(entry.User, Reveal(entry.Password)) : null; + + /// The user name kept for (empty when none), and whether a password is kept with it. + public (string User, bool HasPassword) Describe(string? proxy) => + KeyOf(proxy) is { } key && _entries.TryGetValue(key, out var entry) ? (entry.User, !string.IsNullOrEmpty(entry.Password)) : ("", false); + + /// + /// Keeps and for ; an empty user forgets + /// them, and a null password keeps the one kept. Returns false when nothing changed (there is nothing to save then). + /// + public bool Set(string? proxy, string? user, string? password) + { + if (KeyOf(proxy) is not { } key) + { + return false; + } + + user = user?.Trim() ?? ""; + _entries.TryGetValue(key, out var current); + if (user.Length == 0) + { + return _entries.Remove(key); + } + + if (current is not null && current.User == user && (password is null || Reveal(current.Password) == password)) + { + return false; + } + + _entries[key] = new ProxyCredentialEntry { User = user, Password = password is null ? current?.Password : Conceal(password) }; + return true; + } + + /// + /// Writes the file to (default: ), readable by the + /// user only; deletes it when nothing is kept. + /// + /// Refused with an while the file holds what could not be read (). + public void Save(string? directory = null) + { + directory ??= UserSettings.DefaultDirectory(); + var path = Path.Combine(directory, FileName); + ApiWorkspace.ThrowIfUnreadable(path, LoadError, "then try again"); + if (_entries.Count == 0) + { + File.Delete(path); + return; + } + + Directory.CreateDirectory(directory); + var file = new ProxyCredentialFile { Proxies = new Dictionary(_entries, StringComparer.Ordinal) }; + var json = JsonSerializer.Serialize(file, CoreJsonContext.Default.ProxyCredentialFile).Replace("\r\n", "\n", StringComparison.Ordinal); + TextFile.WriteAtomic(path, json, new TextFileInfo(false, true, false), PrivateFile); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(path, PrivateFile); // a file that existed keeps its mode otherwise + } + } + + /// A credential for , which may name a domain: CONTOSO\ada (or ada@contoso.com, as it is). + public static NetworkCredential Credential(string user, string? password) + { + var slash = user.IndexOf('\\', StringComparison.Ordinal); + return slash > 0 ? new NetworkCredential(user[(slash + 1)..], password ?? "", user[..slash]) : new NetworkCredential(user, password ?? ""); + } + + private static string Conceal(string password) => + OperatingSystem.IsWindows() ? DpapiPrefix + Convert.ToBase64String(Dpapi.Protect(Encoding.UTF8.GetBytes(password), Entropy)) : password; + + private static string? Reveal(string? stored) + { + if (stored is null || !stored.StartsWith(DpapiPrefix, StringComparison.Ordinal)) + { + return stored; + } + + if (!OperatingSystem.IsWindows()) + { + return null; + } + + try + { + return Encoding.UTF8.GetString(Dpapi.Unprotect(Convert.FromBase64String(stored[DpapiPrefix.Length..]), Entropy)); + } + catch (Exception ex) when (ex is FormatException or CryptographicException) + { + return null; + } + } +} + +/// The content of . +internal sealed class ProxyCredentialFile +{ + public Dictionary Proxies { get; set; } = new(); +} + +internal sealed class ProxyCredentialEntry +{ + public string User { get; set; } = ""; + + /// The password: dpapi: and base64 when encrypted for the user (Windows), else as typed. + public string? Password { get; set; } +} diff --git a/src/TermRest.Core/Workspace/RequestRunner.cs b/src/TermRest.Core/Workspace/RequestRunner.cs index 2b25498..9ba4d6b 100644 --- a/src/TermRest.Core/Workspace/RequestRunner.cs +++ b/src/TermRest.Core/Workspace/RequestRunner.cs @@ -51,13 +51,22 @@ public RequestRunner(ApiWorkspace workspace) /// /// The proxy URL of the workspace's settings while it is not the : requests use the system's /// proxy settings then (the OS's, HTTPS_PROXY), as without a proxy setting. Null when the settings name no proxy - /// URL ("system", "none") or the one allowed. + /// URL ("system", "none") or the one allowed, and while replaces it. /// public string? BlockedProxy => - Workspace.Settings.Proxy is var proxy && WorkspaceSettings.IsProxyUrl(proxy) && !string.Equals(proxy.Trim(), AllowedProxy?.Trim(), StringComparison.Ordinal) + ProxyOverride is null && Workspace.Settings.Proxy is var proxy && WorkspaceSettings.IsProxyUrl(proxy) && !string.Equals(proxy.Trim(), AllowedProxy?.Trim(), StringComparison.Ordinal) ? proxy : null; + /// The proxy for every request in place of the workspace's (CLI --proxy: a URL, "system" or "none"); typed by the user, so used as it is. + public string? ProxyOverride { get; set; } + + /// The proxy's user name and password for every request (CLI --proxy-user), in place of those kept for it. + public System.Net.NetworkCredential? ProxyCredentialOverride { get; set; } + + /// The user names and passwords the user keeps for proxies (read by ). + public ProxyCredentialStore ProxyCredentials { get; set; } = ProxyCredentialStore.Empty(); + /// /// Whether requests may send body and form-data files from outside the workspace folder, and open client certificates and /// a CA bundle on network shares outside it: allowed for this workspace folder in the user's settings (read by @@ -107,13 +116,15 @@ public void ConfigureHistory(string? stateDirectory = null) /// /// Sets to the proxy URL of the workspace's settings when the user's settings allow it for - /// this workspace folder (), else to none. + /// this workspace folder (), else to none, and reads the user names and + /// passwords the user keeps for proxies (). /// /// Overrides the user's configuration folder (tests, portable setups). public void ConfigureProxy(string? userSettingsDirectory = null) { var proxy = Workspace.Settings.Proxy; AllowedProxy = WorkspaceSettings.IsProxyUrl(proxy) && UserSettings.Load(userSettingsDirectory).IsProxyAllowed(Workspace.RootPath, proxy) ? proxy : null; + ProxyCredentials = ProxyCredentialStore.Load(userSettingsDirectory); } /// Sets as the user's settings say for this workspace folder. @@ -158,6 +169,10 @@ public ExecutionDefaults CreateDefaults() { var settings = Workspace.Settings; var timeoutMs = TimeoutOverrideMs ?? settings.TimeoutMs; + + // One not allowed: the system's proxy settings, as without one. Trimmed, as requests use it: recordings then find the + // password of a URL written with a space before it. + var proxy = ProxyOverride?.Trim() ?? (BlockedProxy is null ? settings.Proxy?.Trim() : null); return new ExecutionDefaults { StrictSsl = StrictSslOverride ?? settings.StrictSsl, @@ -165,9 +180,8 @@ public ExecutionDefaults CreateDefaults() Timeout = timeoutMs > 0 ? TimeSpan.FromMilliseconds(timeoutMs) : null, FollowRedirects = settings.FollowRedirects, MaxRedirects = settings.MaxRedirects, - // One not allowed: the system's proxy settings, as without one. Trimmed, as requests use it: recordings then find - // the password of a URL written with a space before it. - Proxy = BlockedProxy is null ? settings.Proxy?.Trim() : null, + Proxy = proxy, + ProxyCredential = ProxyCredentialOverride ?? ProxyCredentials.Find(proxy), MaxResponseBytes = Math.Max(1, settings.MaxResponseSizeMb) * 1024L * 1024L, HttpVersion = settings.HttpVersion, FilesFolder = FilesFolder, diff --git a/src/TermRest.Core/Workspace/WorkspaceSettings.cs b/src/TermRest.Core/Workspace/WorkspaceSettings.cs index d25fae3..5977399 100644 --- a/src/TermRest.Core/Workspace/WorkspaceSettings.cs +++ b/src/TermRest.Core/Workspace/WorkspaceSettings.cs @@ -111,5 +111,6 @@ public WorkspaceSettings Clone() UseStringEnumConverter = true)] [JsonSerializable(typeof(WorkspaceSettings))] [JsonSerializable(typeof(UserSettings))] +[JsonSerializable(typeof(ProxyCredentialFile))] [JsonSerializable(typeof(List))] internal sealed partial class CoreJsonContext : JsonSerializerContext; diff --git a/src/TermRest.Tui/Dialogs/SettingsDialog.cs b/src/TermRest.Tui/Dialogs/SettingsDialog.cs index bc47212..a9a1f5c 100644 --- a/src/TermRest.Tui/Dialogs/SettingsDialog.cs +++ b/src/TermRest.Tui/Dialogs/SettingsDialog.cs @@ -64,6 +64,14 @@ public static bool Show(IApplication app, ApiWorkspace workspace, RequestRunner dialog.Add(proxyHint); y += 1; + + // Kept for the proxy in the user's private credentials file, never in the workspace; a password left masked stays. + const string keptPassword = "********"; + var (keptUser, hasPassword) = runner.ProxyCredentials.Describe(settings.Proxy); + var proxyUser = Ui.AddRow(dialog, "Proxy sign-in", new TextField { Text = keptUser, Width = 22 }, y, 22); + var proxyPassword = new TextField { X = Pos.Right(proxyUser) + 11, Y = y, Width = 16, Secret = true, Text = hasPassword ? keptPassword : "" }; + dialog.Add(new Label { Text = "password", X = Pos.Right(proxyUser) + 2, Y = y }, proxyPassword); + y += 1; var http = Ui.AddRow(dialog, "HTTP version", new OptionSelector { Labels = ["HTTP/1.1", "HTTP/2 (when supported)"], Orientation = Orientation.Horizontal, Value = settings.HttpVersion == "2" ? 1 : 0 }, y, 22); y += 1; var maxSize = Ui.AddRow(dialog, "Max response (MB)", new TextField { Text = settings.MaxResponseSizeMb.ToString(CultureInfo.InvariantCulture), Width = 8 }, y, 22); @@ -104,7 +112,7 @@ public static bool Show(IApplication app, ApiWorkspace workspace, RequestRunner var redact = Ui.AddRow(dialog, "Recordings redact", new TextField { Text = string.Join(", ", settings.RecordingRedact ?? []) }, y, 22); y += 1; dialog.Add(Ui.Hint("Extra header, parameter and field names, comma-separated (credentials, cookies and tokens always are).", 24, y)); - y += 2; + y += 1; // no blank line before the last row: with the proxy sign-in, the dialog still fits a terminal of 30 rows var outsideFiles = Ui.AddRow(dialog, "Outside files", new CheckBox { Text = "Allow files from outside this folder", @@ -172,6 +180,15 @@ public static bool Show(IApplication app, ApiWorkspace workspace, RequestRunner settings.RecordingRedact = names.Count == 0 ? null : names; saved = Ui.TrySave(app, workspace.SaveSettings); // applied for this session either way saved &= SaveApprovals(app, workspace, runner, outsideFiles.Value == CheckState.Checked, userDirectory); + + // The sign-in goes with the proxy the settings now name (the system's, or a URL), for this session and in the + // user's credentials file. + var password = proxyPassword.Text == keptPassword && hasPassword ? null : proxyPassword.Text; + if (runner.ProxyCredentials.Set(settings.Proxy, proxyUser.Text, password)) + { + saved &= Ui.TrySave(app, () => runner.ProxyCredentials.Save(userDirectory)); + } + return true; } } diff --git a/src/TermRest.Tui/TuiApp.cs b/src/TermRest.Tui/TuiApp.cs index b15a2df..94a6dc2 100644 --- a/src/TermRest.Tui/TuiApp.cs +++ b/src/TermRest.Tui/TuiApp.cs @@ -60,6 +60,11 @@ public static int Run(string workspacePath, TuiOptions? options = null) runner.ConfigureHistory(); runner.ConfigureScripts(); runner.ConfigureProxy(); + if (runner.ProxyCredentials.LoadError is { } credentialsProblem && !workspace.LoadErrors.Contains(credentialsProblem)) + { + workspace.LoadErrors.Add(credentialsProblem); // no proxy sign-in is used then, and the file is not saved over + } + runner.ConfigureFiles(); using var app = Application.Create(); app.Init(options.Driver); diff --git a/tests/TermRest.Cli.Tests/CommandLineTests.cs b/tests/TermRest.Cli.Tests/CommandLineTests.cs index 27e87ed..0e013b2 100644 --- a/tests/TermRest.Cli.Tests/CommandLineTests.cs +++ b/tests/TermRest.Cli.Tests/CommandLineTests.cs @@ -1115,6 +1115,29 @@ public async Task A_proxy_in_the_workspace_settings_is_not_used_until_it_is_allo Assert.Equal(2, server.Requests); } + [Fact] + public async Task Send_signs_in_to_a_proxy_with_proxy_user_and_says_what_a_proxy_that_wants_a_sign_in_needs() + { + await using var proxy = new SignInProxy("ada", "s3cret"); + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Hello", "GET", "http://api.example.test/hello")]); + + var signedIn = await Termrest.RunAsync(["send", collection, "Hello", "--proxy", proxy.Url, "--proxy-user", "ada:s3cret"]); + var refused = await Termrest.RunAsync(["send", collection, "Hello", "-x", proxy.Url["http://".Length..]]); // host:port, as curl takes it + var noPassword = await Termrest.RunAsync(["send", collection, "Hello", "--proxy", proxy.Url, "--proxy-user", "ada"]); // nobody to type it + var invalid = await Termrest.RunAsync(["send", collection, "Hello", "--proxy", "ftp://proxy:21"]); + + Assert.True(signedIn.ExitCode == 0, signedIn.ToString()); + Assert.Contains("through the proxy", signedIn.Text, StringComparison.Ordinal); + Assert.True(refused.ExitCode == 0, refused.ToString()); // a response: the proxy's 407 + Assert.Contains("407", refused.Error, StringComparison.Ordinal); + Assert.Contains("The proxy asks for a user name and password", refused.Error, StringComparison.Ordinal); + Assert.Equal(2, noPassword.ExitCode); + Assert.Contains("give the password as user:password", noPassword.Error, StringComparison.Ordinal); + Assert.Equal(2, invalid.ExitCode); + Assert.Contains("--proxy expects a URL", invalid.Error, StringComparison.Ordinal); + Assert.Equal(3, proxy.Requests.Count); // the two that reached it: one with a sign-in after the challenge + } + [Fact] public async Task Files_from_outside_the_workspace_are_sent_only_with_allow_outside_files() { diff --git a/tests/TermRest.Cli.Tests/TermRest.Cli.Tests.csproj b/tests/TermRest.Cli.Tests/TermRest.Cli.Tests.csproj index afc001b..f4f03d5 100644 --- a/tests/TermRest.Cli.Tests/TermRest.Cli.Tests.csproj +++ b/tests/TermRest.Cli.Tests/TermRest.Cli.Tests.csproj @@ -24,6 +24,7 @@ + diff --git a/tests/TermRest.Core.Tests/Infrastructure/SignInProxy.cs b/tests/TermRest.Core.Tests/Infrastructure/SignInProxy.cs new file mode 100644 index 0000000..4372ec6 --- /dev/null +++ b/tests/TermRest.Core.Tests/Infrastructure/SignInProxy.cs @@ -0,0 +1,104 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; + +namespace TermRest.Core.Tests.Infrastructure; + +/// +/// An HTTP proxy that asks for Basic sign-in (407 Proxy Authentication Required) until a request brings the +/// Proxy-Authorization of its user and password, and then answers the request itself (200, "through the proxy"). A +/// tunnel (CONNECT) is only ever refused. Each connection serves one request, so every sign-in is a new connection. +/// +internal sealed class SignInProxy : IAsyncDisposable +{ + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _stop = new(); + private readonly string _expected; + private readonly Task _serving; + + public SignInProxy(string user, string password) + { + _expected = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{password}")); + _listener.Start(); + _serving = Task.Run(ServeAsync); + } + + public string Url => $"http://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}"; + + /// Each request: its first line and its Proxy-Authorization ("-" without one). + public List Requests { get; } = []; + + private async Task ServeAsync() + { + while (!_stop.IsCancellationRequested) + { + TcpClient client; + try + { + client = await _listener.AcceptTcpClientAsync(_stop.Token); + } + catch (Exception ex) when (ex is OperationCanceledException or ObjectDisposedException or SocketException) + { + return; + } + + using (client) + { + try + { + var stream = client.GetStream(); + var head = await ReadHeadAsync(stream); + var lines = head.Split("\r\n"); + var authorization = lines.Skip(1).FirstOrDefault(l => l.StartsWith("Proxy-Authorization:", StringComparison.OrdinalIgnoreCase))?["Proxy-Authorization:".Length..].Trim(); + lock (Requests) + { + Requests.Add($"{lines[0]} | {authorization ?? "-"}"); + } + + var response = authorization != _expected + ? "HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm=\"corp\"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + : lines[0].StartsWith("CONNECT ", StringComparison.Ordinal) + ? "HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + : "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 17\r\nConnection: close\r\n\r\nthrough the proxy"; + await stream.WriteAsync(Encoding.ASCII.GetBytes(response), _stop.Token); + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or SocketException) + { + // The client went away. + } + } + } + } + + private async Task ReadHeadAsync(NetworkStream stream) + { + var buffer = new byte[16384]; + var read = 0; + while (read < buffer.Length) + { + var count = await stream.ReadAsync(buffer.AsMemory(read), _stop.Token); + if (count == 0) + { + break; + } + + read += count; + if (Encoding.ASCII.GetString(buffer, 0, read).Contains("\r\n\r\n", StringComparison.Ordinal)) + { + break; + } + } + + var text = Encoding.ASCII.GetString(buffer, 0, read); + var end = text.IndexOf("\r\n\r\n", StringComparison.Ordinal); + return end < 0 ? text : text[..end]; + } + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + await _serving; + _stop.Dispose(); + } +} diff --git a/tests/TermRest.Core.Tests/ProxyTests.cs b/tests/TermRest.Core.Tests/ProxyTests.cs new file mode 100644 index 0000000..15cd765 --- /dev/null +++ b/tests/TermRest.Core.Tests/ProxyTests.cs @@ -0,0 +1,130 @@ +using System.Net; +using TermRest.Core.Http; +using TermRest.Core.Model; +using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Variables; +using TermRest.Core.Workspace; +using Xunit; + +namespace TermRest.Core.Tests; + +public class ProxyTests +{ + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + + private static PreparedRequest Prepare(string url, ExecutionDefaults defaults) => + new RequestPreparer(VariableResolver.Empty, null, defaults).Prepare(new HttpRequestSpec { Url = url }, null, AppContext.BaseDirectory); + + [Fact] + public async Task A_proxy_that_asks_for_basic_sign_in_gets_the_user_name_and_password_given_for_it() + { + await using var proxy = new SignInProxy("CONTOSO\\ada", "p@ss:wörd"); + var executor = new HttpExecutor(); + + // Given for it (kept in the user's settings, or --proxy-user): a user name with a domain goes as typed in Basic. + var given = await executor.SendAsync(Prepare("http://api.example.test/hello", new ExecutionDefaults + { + Proxy = proxy.Url, + ProxyCredential = ProxyCredentialStore.Credential("CONTOSO\\ada", "p@ss:wörd"), + }), _ct); + + // In the proxy's URL, escaped as URLs have it. + var inUrl = await executor.SendAsync(Prepare("http://api.example.test/hello", new ExecutionDefaults + { + Proxy = proxy.Url.Replace("http://", "http://CONTOSO%5Cada:p%40ss%3Aw%C3%B6rd@", StringComparison.Ordinal), + }), _ct); + + // None: the user's own sign-in, which a Basic proxy never gets; the proxy's 407 comes back, with what to do. + var none = await executor.SendAsync(Prepare("http://api.example.test/hello", new ExecutionDefaults { Proxy = proxy.Url }), _ct); + + Assert.Equal((200, "through the proxy"), (given.Response?.StatusCode, System.Text.Encoding.UTF8.GetString(given.Response!.Body))); + Assert.Equal(200, inUrl.Response?.StatusCode); + Assert.Equal(407, none.Response?.StatusCode); + Assert.Contains(none.Request.Warnings, w => w.StartsWith("The proxy asks for a user name and password (407", StringComparison.Ordinal)); + Assert.DoesNotContain(given.Request.Warnings, w => w.Contains("407", StringComparison.Ordinal)); + + // Each signed in after the proxy's challenge, and never sent the password where the request is shown or recorded. + var expected = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("CONTOSO\\ada:p@ss:wörd")); + Assert.Equal( + ["GET http://api.example.test/hello HTTP/1.1 | -", $"GET http://api.example.test/hello HTTP/1.1 | {expected}", + "GET http://api.example.test/hello HTTP/1.1 | -", $"GET http://api.example.test/hello HTTP/1.1 | {expected}", + "GET http://api.example.test/hello HTTP/1.1 | -"], + proxy.Requests); + Assert.DoesNotContain(given.Request.Headers, h => h.Key.Equals("Proxy-Authorization", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public async Task A_tunnel_the_proxy_refuses_until_it_gets_a_sign_in_says_how_to_give_one() + { + await using var proxy = new SignInProxy("ada", "s3cret"); + + var exchange = await new HttpExecutor().SendAsync(Prepare("https://api.example.test/x", new ExecutionDefaults { Proxy = proxy.Url }), _ct); + + Assert.Null(exchange.Response); + Assert.Contains("407", exchange.ErrorMessage, StringComparison.Ordinal); + Assert.Contains("give them in Tools › Settings (Proxy sign-in), with --proxy-user", exchange.ErrorMessage, StringComparison.Ordinal); + } + + [Fact] + public void Proxy_credentials_are_kept_per_proxy_in_a_private_file_with_the_password_encrypted_on_windows() + { + var directory = TestFiles.NewTempDirectory(); + var store = ProxyCredentialStore.Load(directory); + Assert.True(store.Set("http://ada:old@Proxy.Contoso.com:3128/path", "CONTOSO\\ada", "s3cret-pw")); + Assert.True(store.Set(null, "bob", "hunter2-pw")); // the system's proxy + Assert.False(store.Set("none", "carol", "x")); // no proxy: nothing to sign in to + store.Save(directory); + + var file = Path.Combine(directory, ProxyCredentialStore.FileName); + var text = File.ReadAllText(file); + Assert.Contains("\"http://proxy.contoso.com:3128\"", text, StringComparison.Ordinal); + Assert.Contains("\"system\"", text, StringComparison.Ordinal); + if (OperatingSystem.IsWindows()) + { + Assert.DoesNotContain("s3cret-pw", text, StringComparison.Ordinal); + Assert.Contains("\"password\": \"dpapi:", text, StringComparison.Ordinal); + } + else + { + Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(file)); + } + + var read = ProxyCredentialStore.Load(directory); + var contoso = read.Find("http://proxy.contoso.com:3128"); + Assert.Equal(("ada", "s3cret-pw", "CONTOSO"), (contoso?.UserName, contoso?.Password, contoso?.Domain)); + Assert.Equal(("bob", "hunter2-pw"), (read.Find("system")?.UserName, read.Find("")?.Password)); + Assert.Equal(("CONTOSO\\ada", true), read.Describe("HTTP://proxy.contoso.com:3128")); + Assert.Null(read.Find("http://other:3128")); + + // A password left as it was (null) stays; an empty user forgets them; with nothing kept, the file goes. + Assert.True(read.Set("http://proxy.contoso.com:3128", "CONTOSO\\ada2", null)); + Assert.Equal("s3cret-pw", read.Find("http://proxy.contoso.com:3128")?.Password); + Assert.True(read.Set("http://proxy.contoso.com:3128", "", null)); + Assert.True(read.Set("system", " ", null)); + read.Save(directory); + Assert.False(File.Exists(file)); + } + + [Fact] + public void Requests_use_the_proxy_and_sign_in_given_on_the_command_line_over_those_kept() + { + var directory = TestFiles.NewTempDirectory(); + var workspace = ApiWorkspace.Open(directory); + workspace.Settings.Proxy = "http://proxy.contoso.com:3128"; // not allowed for this folder: not used + using var runner = new RequestRunner(workspace); + runner.ConfigureProxy(directory); + runner.ProxyCredentials.Set("system", "kept", "kept-pw"); + + var kept = runner.CreateDefaults(); + runner.ProxyOverride = "http://cli-proxy:8080"; + runner.ProxyCredentials.Set("http://cli-proxy:8080", "kept2", "kept2-pw"); + var overridden = runner.CreateDefaults(); + runner.ProxyCredentialOverride = new NetworkCredential("cli", "cli-pw"); + var given = runner.CreateDefaults(); + + Assert.Equal((null, "kept"), (kept.Proxy, kept.ProxyCredential?.UserName)); + Assert.Null(runner.BlockedProxy); // replaced: nothing to warn about + Assert.Equal(("http://cli-proxy:8080", "kept2"), (overridden.Proxy, overridden.ProxyCredential?.UserName)); + Assert.Equal("cli", given.ProxyCredential?.UserName); + } +} diff --git a/tests/TermRest.Tui.Tests/MainWindowTests.cs b/tests/TermRest.Tui.Tests/MainWindowTests.cs index f6beb1f..4256a2b 100644 --- a/tests/TermRest.Tui.Tests/MainWindowTests.cs +++ b/tests/TermRest.Tui.Tests/MainWindowTests.cs @@ -1189,6 +1189,43 @@ public void Settings_written_by_hand_as_requests_read_them_can_be_saved() Assert.Equal((0, "none"), (ui.Workspace.Settings.MaxRedirects, ui.Workspace.Settings.Proxy)); } + [Fact] + public void A_proxy_sign_in_typed_in_the_settings_is_kept_in_the_users_private_file_not_the_workspace() + { + var userDirectory = TestFiles.NewTempDirectory(); + using var ui = new Harness(_directory, runner => runner.ConfigureProxy(userDirectory)); + var saved = false; + + var screens = Drive(ui, () => + { + SettingsDialog.Show(ui.App, ui.Workspace, ui.Runner, out saved, userDirectory); + ui.App.RequestStop(); + }, + ("Workspace settings", () => + { + var label = ui.Find("Proxy sign-in"); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(label.X + 23, label.Y))); // its user field + ui.Type("CONTOSO\\ada"); + ui.App.InjectKey(Key.Tab); // the password + ui.Type("s3cret-pw"); + ui.Click("► Save ◄"); + })); + + Assert.Single(screens); + Assert.True(saved); + var credential = ui.Runner.CreateDefaults().ProxyCredential; // the system's proxy, used at once + Assert.Equal(("ada", "s3cret-pw", "CONTOSO"), (credential?.UserName, credential?.Password, credential?.Domain)); + var file = File.ReadAllText(Path.Combine(userDirectory, ProxyCredentialStore.FileName)); + Assert.Contains("CONTOSO\\\\ada", file, StringComparison.Ordinal); + if (OperatingSystem.IsWindows()) + { + Assert.DoesNotContain("s3cret-pw", file, StringComparison.Ordinal); + } + + var workspaceSettings = ui.Workspace.SettingsPath; + Assert.False(File.Exists(workspaceSettings) && File.ReadAllText(workspaceSettings).Contains("ada", StringComparison.Ordinal)); + } + [Theory] [InlineData("http://ada:***@proxy:3128", "http://ada:s3cret@proxy:3128")] // left as shown [InlineData("http://ada:***@proxy:8080", "http://ada:s3cret@proxy:8080")] // only the port changed From 4fbb701752085488bd5be5cf9231ffcd634f5e96 Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Tue, 17 Nov 2026 22:35:32 -0700 Subject: [PATCH 04/11] Core and CLI: data-driven runs termrest run -d (--iteration-data, as in Newman) runs the requests once for each row of a data file, each run an iteration: CSV with a header row that names the values (RFC 4180: values with commas, quotes or line breaks in double quotes, "" for a quote; lines without values skipped), or JSON, an array of objects. A row's values are data variables: {{name}} in requests, below this request's variables (--var) and above the environment's, as in Postman, and in scripts pm.iterationData, tr.iteration_data, tr.IterationData and $tr.IterationData (JavaScript and Python get the JSON values with their types), with the iteration in pm.info.iteration and iterationCount (tr.info.iteration and iteration_count, tr.Info.Iteration and IterationCount); pm.variables and the other languages' variables read the data scope in its place, and the legacy data and iteration globals are the row and the iteration. -n (--iteration-count) runs that many iterations, with or without data; past a data file's last row, that row is used again. The file is read through once before anything is sent, so that a row that isn't valid stops the run at once (exit code 2), then one row at a time, so a large file takes no more memory than a row. Output says which iteration runs, and the JSON report has the number of iterations and the iteration of each result. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 24 ++- src/TermRest.Cli/RunCommand.cs | 132 +++++++++--- .../Scripting/CSharpWorkerCode.cs | 21 +- .../Scripting/JavaScriptWorkerCode.cs | 8 +- .../Scripting/PowerShellWorkerCode.cs | 15 +- .../Scripting/PythonWorkerCode.cs | 6 +- .../Workspace/IterationDataFile.cs | 192 ++++++++++++++++++ .../Workspace/RequestRunner.Scripts.cs | 12 +- src/TermRest.Core/Workspace/RequestRunner.cs | 34 ++++ .../Workspace/WorkspaceSettings.cs | 1 + src/TermRest.Tui/MainWindow.cs | 13 +- tests/TermRest.Cli.Tests/CommandLineTests.cs | 30 +++ .../TermRest.Core.Tests/IterationDataTests.cs | 149 ++++++++++++++ 13 files changed, 585 insertions(+), 52 deletions(-) create mode 100644 src/TermRest.Core/Workspace/IterationDataFile.cs create mode 100644 tests/TermRest.Core.Tests/IterationDataTests.cs diff --git a/README.md b/README.md index 19acafb..af6ce7b 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ Without any, a proxy that asks for NTLM or Negotiate, as corporate proxies do, g Requests send body and form-data files only from the workspace folder, also once links are resolved: a collection that comes with a repository could otherwise send any file you can read (SSH keys, cloud credentials) to a server of its choosing, with no script needed. A file outside the folder (an absolute path, a `../` path, or a link in the repository that leads out) stops its request with an error that names it; a path outside the folder as written is not even looked at, by the request or by its Body tab, so a Windows `\\server\share` path doesn't reach that server. For the same reason, on Windows, client certificates and the CA bundle (named by a request, `.termrest/certificates.json` or `.termrest/settings.json`) are not opened from a network share outside the folder, nor through a link that leads there: the request is sent without them, with a warning. To send such files and use such certificates, check *Outside files: Allow files from outside this folder* in *Tools › Settings* (kept per workspace folder in your user settings, `outsideFilesAllowed`), or pass `--allow-outside-files` to `send`, `run` or `certs list`. -Variables resolve Postman-style. The highest precedence comes first: `--var`/local, then environment, then collection, then globals. Values may reference other variables, and Postman dynamic variables work, with a new value each time: `{{$guid}}` (also `$randomUUID`), `{{$timestamp}}`, `{{$isoTimestamp}}`, `{{$randomInt}}` (0 to 1000), `$randomBoolean`, `$randomAlphaNumeric` and `$randomHexadecimal` (one character), `$randomFirstName`, `$randomLastName`, `$randomFullName`, `$randomUserName`, `$randomEmail`, `$randomWord` and `$randomPassword`. Scripts resolve them too (`.replaceIn`, `.replace_in`, `.ReplaceIn`): `pm.environment.set('email', pm.variables.replaceIn('{{$randomEmail}}'))` keeps one address for the requests that use `{{email}}`. A variable of the same name takes the place of a dynamic one (`$timestamp` set by a script, say), in requests and scripts alike, as in Postman. Unresolved `{{names}}` are kept and reported as warnings. Replacing variables adds at most 4,194,304 characters to a text: a reference whose value would go past that (a value that references itself several times, say) stays unresolved and is reported. +Variables resolve Postman-style. The highest precedence comes first: `--var`/local, then the run's iteration data (`run --iteration-data`), then environment, then collection, then globals. Values may reference other variables, and Postman dynamic variables work, with a new value each time: `{{$guid}}` (also `$randomUUID`), `{{$timestamp}}`, `{{$isoTimestamp}}`, `{{$randomInt}}` (0 to 1000), `$randomBoolean`, `$randomAlphaNumeric` and `$randomHexadecimal` (one character), `$randomFirstName`, `$randomLastName`, `$randomFullName`, `$randomUserName`, `$randomEmail`, `$randomWord` and `$randomPassword`. Scripts resolve them too (`.replaceIn`, `.replace_in`, `.ReplaceIn`): `pm.environment.set('email', pm.variables.replaceIn('{{$randomEmail}}'))` keeps one address for the requests that use `{{email}}`. A variable of the same name takes the place of a dynamic one (`$timestamp` set by a script, say), in requests and scripts alike, as in Postman. Unresolved `{{names}}` are kept and reported as warnings. Replacing variables adds at most 4,194,304 characters to a text: a reference whose value would go past that (a value that references itself several times, say) stays unresolved and is reported. ## Using the UI @@ -240,16 +240,17 @@ A collection, a folder and a request can each have a pre-request and a post-resp | Python: the `tr` object | | |---|---| | `tr.environment`, `tr.collection_variables`, `tr.globals` | `.get(name, default)`, `.set(name, value)`, `.unset(name)`, `.has(name)`, `.clear()`, `.to_dict()`, and `tr.environment["name"]`. Values set are kept in memory until TermRest closes (Postman's "current values"); files are never changed. *Tools › Scripts* shows how many there are and clears them. | -| `tr.variables` | Reads every scope (this request, the environment, the collection, the globals: the first that has it). `.set()` is for this request only. `.replace_in("{{base}}/x")` replaces `{{variables}}` and dynamic variables (`{{$guid}}` …) in a text. | +| `tr.variables` | Reads every scope (this request, the run's iteration data, the environment, the collection, the globals: the first that has it). `.set()` is for this request only. `.replace_in("{{base}}/x")` replaces `{{variables}}` and dynamic variables (`{{$guid}}` …) in a text. | +| `tr.iteration_data` | The data of the run's current iteration, a row of its data file (`termrest run --iteration-data`; see [Command line](#command-line)): `.get(name)` …, values with their JSON types. Empty without one. | | `tr.request` | `.method`, `.url`, `.headers` (`.get`, `.get_all`, `.set`, `.add`, `.remove`, `.items()`; as with requests, a dict, another mapping or a list of pairs can replace them), `.body` (raw bodies; bytes are sent as their UTF-8 text, a dict, list, tuple or bool as JSON). Pre-request scripts can change them; `{{variables}}` they contain are replaced afterwards. A request they leave in a state that can't be sent isn't sent, and what they printed, tested and set is kept. Test scripts see the request as it was sent. | | `tr.response` | In test scripts: `.status` (or `.code`), `.reason`, `.headers`, `.time` (ms), `.size`, `.text()`, `.json()`, `.content` (bytes). | | `tr.test(name, fn)`, `@tr.test(name)` | Records a test that fails when `fn` raises, as `assert` does. | -| `tr.info` | `.phase` (`prerequest` or `test`), `.script`, `.request_name`, `.collection`, `.environment`. | +| `tr.info` | `.phase` (`prerequest` or `test`), `.script`, `.request_name`, `.collection`, `.environment`, `.iteration` (from 0) and `.iteration_count` of the run. | | `print(…)` | Goes to the response's *Scripts* tab, and to stderr on the command line. So does `logging`, also through a handler an earlier script set up (`logging.basicConfig()`). | | JavaScript: Postman's `pm` object | | |---|---| -| `pm.environment`, `pm.collectionVariables`, `pm.globals`, `pm.variables`, `pm.iterationData` | `.get`, `.set`, `.unset`, `.has`, `.clear`, `.toObject`, `.replaceIn`, as in Postman. | +| `pm.environment`, `pm.collectionVariables`, `pm.globals`, `pm.variables`, `pm.iterationData` | `.get`, `.set`, `.unset`, `.has`, `.clear`, `.toObject`, `.replaceIn`, as in Postman. `pm.iterationData` holds the run's current row of its data file (`termrest run --iteration-data`), with the values' JSON types; `pm.info.iteration` and `pm.info.iterationCount` say which iteration it is. | | `pm.request` | `.method`, `.url` (`.query.add`, `.toString()`, `.getHost()` …; as in Postman, its `host` and `path` may be set as text), `.headers` (`.add`, `.upsert`, `.remove`, `.get`, `.has`, `.each` …), `.body.raw`. Pre-request scripts can change them, as with `tr.request`; a request they leave in a state that can't be sent (a `query` that is no longer a list) isn't sent, and what they printed, tested and set is kept. | | `pm.response` | `.code`, `.status`, `.headers`, `.responseTime`, `.responseSize`, `.json()`, `.text()`, `.stream`, `.cookies`, and Postman's assertions: `.to.have.status(…)`, `.to.have.header(…)`, `.to.have.body(…)`, `.to.have.jsonBody(…)`, `.to.be.ok`, `.success`, `.clientError`, `.withoutContent`, `.json` …, and `.to.have.jsonSchema(schema)` (with `ajv` installed in the workspace: ajv 6, Postman's, checks formats such as `email` or `date-time` itself; ajv 8 needs `ajv-formats` for them, and a format it doesn't know fails the test, saying so), which also checks any value: `pm.expect(data.items[0]).to.have.jsonSchema(itemSchema)`. | | `pm.test(name, fn)`, `pm.expect(value)` | Tests (also asynchronous: `async` functions, or a `done` callback) and chai's assertions: `equal`, `eql`, `include`, `a`/`an`, `property`, `lengthOf`, `above`/`below`, `oneOf`, `members`, `keys`, `match`, `throw`, `not`, `deep`, `nested` …, with chai's messages. As in Postman, a property no assertion has, such as a misspelled `.to.be.ture`, fails the test (`Invalid Chai property: ture. Did you mean "true"?`) instead of checking nothing. | @@ -269,12 +270,13 @@ A collection, a folder and a request can each have a pre-request and a post-resp | C#: the `tr` object | | |---|---| | `tr.Environment`, `tr.CollectionVariables`, `tr.Globals` | `["name"]` (null when not set; setting null unsets), `.Get(name, fallback)`, `.Set(name, value)`, `.Unset(name)`, `.Has(name)`, `.Clear()`, `.ToDictionary()`. Kept as in Python. | -| `tr.Variables` | Reads every scope (this request, the environment, the collection, the globals). `.Set()` is for this request only. `.ReplaceIn("{{base}}/x")` replaces `{{variables}}` and dynamic variables (`{{$guid}}` …) in a text. | +| `tr.Variables` | Reads every scope (this request, the run's iteration data, the environment, the collection, the globals). `.Set()` is for this request only. `.ReplaceIn("{{base}}/x")` replaces `{{variables}}` and dynamic variables (`{{$guid}}` …) in a text. | +| `tr.IterationData` | The data of the run's current iteration (`termrest run --iteration-data`), as text: `.Get(name)` …. Empty without one. | | `tr.Request` | `.Method`, `.Url`, `.Headers` (`["name"]`, `.Get`, `.GetAll`, `.Set`, `.Add`, `.Remove`, `.Has`), `.Body` (raw bodies). Pre-request scripts can change them. | | `tr.Response` | In test scripts: `.Status` (or `.Code`), `.Reason`, `.Headers`, `.Time` (ms), `.Size`, `.Text()`, `.Json()` (a `JsonNode`: `json["name"]`, `(int)json["id"]`), `.Content` (bytes). | | `tr.Test(name, () => …)` | Records a test that fails when it throws; `async () => …` tests are awaited. Assertion libraries from NuGet work too. | | `tr.Assert(condition)`, `tr.AssertEqual(expected, actual)` | Fail with the code that failed: `assertion failed: tr.Response.Status == 201`, `tr.Response.Code: expected 201, got 200`. `AssertEqual` compares numbers as numbers and JSON as JSON: `tr.AssertEqual("Ada", json["name"])`. | -| `tr.Info` | `.Phase`, `.Script`, `.RequestName`, `.Collection`, `.Environment`. | +| `tr.Info` | `.Phase`, `.Script`, `.RequestName`, `.Collection`, `.Environment`, `.Iteration` (from 0) and `.IterationCount` of the run. | | `Console.WriteLine(…)` | Goes where `print` does. `HttpClient` sends requests of the script's own (TermRest's certificates and proxy settings do not apply). | **PowerShell scripts** @@ -289,12 +291,13 @@ A collection, a folder and a request can each have a pre-request and a post-resp | PowerShell: the `$tr` object | | |---|---| | `$tr.Environment`, `$tr.CollectionVariables`, `$tr.Globals` | `.Get(name)`, `.Get(name, default)`, `.Set(name, value)`, `.Unset(name)`, `.Has(name)`, `.Clear()`, `.ToHashtable()`. Names are case-sensitive, as in Postman. Kept as in Python. | -| `$tr.Variables` | Reads every scope (this request, the environment, the collection, the globals). `.Set()` is for this request only. `.ReplaceIn('{{base}}/x')` replaces `{{variables}}` and dynamic variables (`{{$guid}}` …) in a text. | +| `$tr.Variables` | Reads every scope (this request, the run's iteration data, the environment, the collection, the globals). `.Set()` is for this request only. `.ReplaceIn('{{base}}/x')` replaces `{{variables}}` and dynamic variables (`{{$guid}}` …) in a text. | +| `$tr.IterationData` | The data of the run's current iteration (`termrest run --iteration-data`), as text: `.Get(name)` …. Empty without one. | | `$tr.Request` | `.Method`, `.Url`, `.Headers` (`.Get`, `.GetAll`, `.Set`, `.Add`, `.Remove`, `.Has`, `.Items()`, `.Count`), `.Body` (raw bodies; `$null` for others; bytes are sent as UTF-8 text, a hashtable or object as JSON). Pre-request scripts can change them; a request they leave in a state that can't be sent (`.Headers` set to `$null`) isn't sent, and what they printed, tested and set is kept. | | `$tr.Response` | In test scripts: `.Status` (or `.Code`), `.Reason`, `.Headers`, `.Time` (ms), `.Size`, `.Text()`, `.Json()` (`ConvertFrom-Json`: `$json.name`), `.Content()` (bytes). | | `$tr.Test(name, { … })` | Records a test that fails when the block throws or a command in it fails. | | `$tr.Assert(condition)`, `$tr.AssertEqual(expected, actual)` | Fail with the code that failed: `assertion failed: $tr.Response.Status -eq 201`, `$tr.Response.Code: expected 201, got 200`. `AssertEqual` compares numbers as numbers, text exactly (case included, unlike `-eq`), and JSON objects and hashtables by their members. | -| `$tr.Info` | `.Phase`, `.Script`, `.RequestName`, `.Collection`, `.Environment`. | +| `$tr.Info` | `.Phase`, `.Script`, `.RequestName`, `.Collection`, `.Environment`, `.Iteration` (from 0) and `.IterationCount` of the run. | | `Write-Host …` | Goes where `print` does. `Invoke-RestMethod` sends requests of the script's own (TermRest's certificates and proxy settings do not apply). | ```python @@ -721,7 +724,7 @@ common options: -e/--env --var key=value --timeout -k/- --python --javascript --csharp --powershell --script-order --no-scripts --allow-outside-files send options: -i/--include -v/--verbose -o/--output --raw --filter -f/--fail --curl --no-history -run options: --bail --allow-http-errors --report-json +run options: --bail --allow-http-errors --report-json -d/--iteration-data -n/--iteration-count history options: -n/--limit --show --json --clear import-curl options: --folder --name --dry-run certs list options: --allow-outside-files @@ -732,6 +735,7 @@ snapshot options: --send --request --width --height --them ```sh termrest run "samples/TermRest Demo.postman_collection.json" -e "Postman Echo" --report-json report.json +termrest run api.postman_collection.json -d users.csv # once for each row of users.csv: {{name}}, pm.iterationData.get('name') termrest send api.postman_collection.json "Users/Get user" --var userId=42 -i termrest send api.postman_collection.json "Users/Get user" --curl # print an equivalent curl command (scripts do not run, no OAuth 2.0 token is fetched; none, and exit code 2, if it can't be sent or curl can't send it the same way) termrest send api.postman_collection.json "Users/List users" --filter '$.users[?@.active].email' @@ -748,6 +752,8 @@ Paths on the command line are relative to the current folder, those of `--python The `--report-json` report redacts secrets the way [recordings](#recording-requests) do, test names and errors included. Missing folders are created; on Unix only you can read it. +**Data-driven runs.** `run -d ` (`--iteration-data`, as in Newman) runs the requests once for each row of a data file, each run an iteration: a CSV file with a header row that names the values (values with commas, quotes or line breaks in double quotes, a quote in one written `""`; empty lines are skipped), or JSON, an array of objects (`[{"name": "Ada", "id": 7}, …]`). A row's values are data variables: `{{name}}` in requests, between `--var` and the environment's (above), and `pm.iterationData` in scripts (`tr.iteration_data`, `tr.IterationData`, `$tr.IterationData`), JSON values with their types for JavaScript and Python. `-n ` (`--iteration-count`) runs that many iterations, with or without data; past a data file's last row, that row is used again, as in Postman. Variables that scripts set in the environment, the collection and the globals carry over to the next iteration. The file is read through once before anything is sent, so that a row that isn't valid stops the run at once (exit code 2), and then one row at a time: a large file takes no more memory than a row. The report has the number of `iterations`, and the `iteration` (from 1) of each result. + `send --filter ` prints only the values a JSONPath query ([RFC 9535](https://www.rfc-editor.org/rfc/rfc9535), as in the UI's Filter) selects in a JSON body, as a JSON array: two-space indented, or on one line with `--raw`; with `-o`, it writes them to the file instead of the body. A query that isn't valid JSONPath is a usage error, reported with where it goes wrong before anything is sent; a body that isn't JSON (or binary, or empty) makes `send` exit with code 1. `send` exits with 0 when done; 1 when there was no response, a test or script failed, the body couldn't be saved with `-o` or filtered with `--filter`, the recording wasn't saved, or files of the collection or the workspace settings can't be read; 2 for a usage problem (an unknown or ambiguous request or `-e` environment, one `--curl` can't export, or a `--filter` query that isn't JSONPath); 22 for HTTP status 400 or more with `--fail`; 63 when the response body was cut at the maximum response size (*Tools › Settings*, `maxResponseSizeMb`, 50 MB), so what `-o` or standard output received is only its start; 130 when cancelled. Warnings raised while sending (a redirect not followed, a header left out, a cut body) are printed after the response. A name that matches several requests, in the workspace's collections or in one collection, is reported as ambiguous: give its path (`Folder/Name`) or its collection. So is an `-e` name that several environments of the workspace have: nothing is sent, and the error lists their files; pass one of them with `-e` instead (a JSON or YAML environment file). Without `-e`, the workspace's active environment is used. diff --git a/src/TermRest.Cli/RunCommand.cs b/src/TermRest.Cli/RunCommand.cs index 89e5e1e..bfe479d 100644 --- a/src/TermRest.Cli/RunCommand.cs +++ b/src/TermRest.Cli/RunCommand.cs @@ -18,6 +18,15 @@ public static Command Create(Option insecure) var bail = new Option("--bail") { Description = "Stop at the first failure" }; var allowHttpErrors = new Option("--allow-http-errors") { Description = "Do not treat HTTP 4xx/5xx responses as failures" }; var json = new Option("--report-json") { Description = "Also write a JSON report to this file" }; + var iterationData = new Option("--iteration-data", "-d") + { + Description = "Run the requests once for each row of this data file: CSV with a header row, or JSON (an array of objects); " + + "its values are data variables ({{name}}, pm.iterationData)", + }; + var iterationCount = new Option("--iteration-count", "-n") + { + Description = "Run the requests this many times (default: once, or once for each row of --iteration-data; past its last row, that row is used again)", + }; var options = new RequestOptions(); command.Arguments.Add(collection); command.Options.Add(folder); @@ -25,6 +34,8 @@ public static Command Create(Option insecure) command.Options.Add(bail); command.Options.Add(allowHttpErrors); command.Options.Add(json); + command.Options.Add(iterationData); + command.Options.Add(iterationCount); command.SetAction(async (parseResult, cancellationToken) => { @@ -68,57 +79,121 @@ public static Command Create(Option insecure) var requests = root is CollectionRootNode ? target.AllRequests().ToList() : target.AllRequests().Where(r => r.Ancestors().Contains(root)).ToList(); + + // The data file is read through once first: a row that isn't valid stops the run before anything is sent. + IterationDataFile? data = null; + var rows = 0; + if (parseResult.GetValue(iterationData) is { } dataPath) + { + try + { + data = IterationDataFile.Open(dataPath); + rows = await data.CountAsync(cancellationToken); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) + { + Output.Error($"--iteration-data: {ex.Message}"); + return 2; + } + + if (rows == 0) + { + Output.Error($"--iteration-data: {dataPath} has no rows{(data.IsJson ? "" : " (the first row of a CSV file names the values)")}."); + return 2; + } + } + + var iterations = parseResult.GetValue(iterationCount) ?? Math.Max(1, rows); + if (iterations < 1) + { + Output.Error("--iteration-count: give 1 or more."); + return 2; + } + if (!options.StartRecording(parseResult, opened.Workspace, runner, out var recorder)) { return 2; } - Output.Info($"Running {requests.Count} request(s) from '{target.Name}'{(root is CollectionRootNode ? "" : " / " + root.PathInCollection)}" + - $"{(runner.Environment is { } env ? $" with environment '{env.Name}'" : "")}\n"); + Output.Info($"Running {requests.Count} request(s){(iterations > 1 ? $" × {iterations} iterations" : "")} from '{target.Name}'" + + $"{(root is CollectionRootNode ? "" : " / " + root.PathInCollection)}" + + $"{(runner.Environment is { } env ? $" with environment '{env.Name}'" : "")}" + + $"{(data is null ? "" : $", data from {Path.GetFileName(data.Path)} ({rows} row(s))")}\n"); var reportPath = parseResult.GetValue(json); var results = new RunResults(reportPath is null ? null : new Redactor(opened.Workspace.Settings.RecordingRedact)); var notesShown = new HashSet(StringComparer.Ordinal); var cancelled = false; - foreach (var node in requests) + var stopped = false; + var dataFailed = false; + await using var dataRows = data?.ReadAsync(cancellationToken).GetAsyncEnumerator(cancellationToken); + System.Text.Json.Nodes.JsonObject? row = null; + runner.IterationCount = iterations; + for (var iteration = 0; iteration < iterations && !stopped; iteration++) { - var exchange = await SendSafelyAsync(runner, target, node, cancellationToken); - if (exchange.Cancelled || cancellationToken.IsCancellationRequested) + try { - cancelled = true; - break; + // Past the last row, that row again, as in Postman. + if (dataRows is not null && await dataRows.MoveNextAsync()) + { + row = dataRows.Current; + } } - - // Passing means a response (not an HTTP error, unless allowed), passing tests and no script errors. - var passed = exchange.Response is { } r && (parseResult.GetValue(allowHttpErrors) || r.StatusCode < 400) && exchange.Scripts?.Succeeded != false; - var status = exchange.Response is { } response ? response.StatusCode.ToString(System.Globalization.CultureInfo.InvariantCulture) : "ERR"; - Output.Status($"{(passed ? "✓" : "✗")} {status,-4} {HttpExchange.Format(exchange.Timing.Total),9} {exchange.Request.Method,-7} {node.PathInCollection}", passed); - if (exchange.Response is null) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) { - Output.Info($" {exchange.ErrorMessage}"); + Output.Error($"--iteration-data: {ex.Message}"); + dataFailed = true; + break; } - foreach (var warning in exchange.Request.Warnings) + runner.Iteration = iteration; + runner.IterationData = row; + if (iterations > 1) { - Output.Warning($" {warning}"); + Output.Info($"{(iteration > 0 ? "\n" : "")}Iteration {iteration + 1}/{iterations}"); } - ScriptOutput.Print(exchange, " ", notesShown); - results.Add(node, exchange, passed); - if (!passed && parseResult.GetValue(bail)) + foreach (var node in requests) { - break; + var exchange = await SendSafelyAsync(runner, target, node, cancellationToken); + if (exchange.Cancelled || cancellationToken.IsCancellationRequested) + { + cancelled = stopped = true; + break; + } + + // Passing means a response (not an HTTP error, unless allowed), passing tests and no script errors. + var passed = exchange.Response is { } r && (parseResult.GetValue(allowHttpErrors) || r.StatusCode < 400) && exchange.Scripts?.Succeeded != false; + var status = exchange.Response is { } response ? response.StatusCode.ToString(System.Globalization.CultureInfo.InvariantCulture) : "ERR"; + Output.Status($"{(passed ? "✓" : "✗")} {status,-4} {HttpExchange.Format(exchange.Timing.Total),9} {exchange.Request.Method,-7} {node.PathInCollection}", passed); + if (exchange.Response is null) + { + Output.Info($" {exchange.ErrorMessage}"); + } + + foreach (var warning in exchange.Request.Warnings) + { + Output.Warning($" {warning}"); + } + + ScriptOutput.Print(exchange, " ", notesShown); + results.Add(node, exchange, passed, iteration + 1); + if (!passed && parseResult.GetValue(bail)) + { + stopped = true; + break; + } } } var testSummary = results.TestsPassed + results.TestsFailed == 0 ? "" : $" (tests: {results.TestsPassed} passed, {results.TestsFailed} failed)"; - Output.Info($"\n{(cancelled ? "Run cancelled. " : "")}{results.Count - results.Failed} passed, {results.Failed} failed, {requests.Count - results.Count} skipped{testSummary}"); + Output.Info($"\n{(cancelled ? "Run cancelled. " : "")}{results.Count - results.Failed} passed, {results.Failed} failed, {(requests.Count * iterations) - results.Count} skipped{testSummary}"); var unreadable = RequestOptions.ReportUnreadableFiles(target); // A cancelled run still saves what it recorded, and reports what it did (not tied to the cancellation token). var recorded = options.SaveRecording(parseResult, runner, recorder, cancellationToken.IsCancellationRequested); - var reported = reportPath is null || await WriteReportAsync(reportPath, results.ToJson(target)); - return cancelled ? 130 : results.Failed == 0 && recorded && reported && !unreadable ? 0 : 1; + var reported = reportPath is null || await WriteReportAsync(reportPath, results.ToJson(target, iterations)); + return cancelled ? 130 : results.Failed == 0 && recorded && reported && !unreadable && !dataFailed ? 0 : 1; }); return command; @@ -161,7 +236,7 @@ private sealed class RunResults(Redactor? secrets) public int TestsFailed { get; private set; } - public void Add(RequestNode node, HttpExchange exchange, bool passed) + public void Add(RequestNode node, HttpExchange exchange, bool passed, int iteration) { Count++; Failed += passed ? 0 : 1; @@ -180,6 +255,7 @@ public void Add(RequestNode node, HttpExchange exchange, bool passed) var scripts = exchange.Scripts; _entries.Add(new ReportEntry( node.PathInCollection, + iteration, exchange.Request.Method, redact.Url(exchange.Request.Url, "url"), passed, @@ -192,7 +268,7 @@ public void Add(RequestNode node, HttpExchange exchange, bool passed) } /// The JSON report (UTF-8). - public byte[] ToJson(PostmanCollection collection) + public byte[] ToJson(PostmanCollection collection, int iterations) { using var stream = new MemoryStream(); using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true })) @@ -200,6 +276,7 @@ public byte[] ToJson(PostmanCollection collection) writer.WriteStartObject(); writer.WriteString("collection", collection.Name); writer.WriteString("finishedAt", DateTimeOffset.Now); + writer.WriteNumber("iterations", iterations); writer.WriteNumber("passed", Count - Failed); writer.WriteNumber("failed", Failed); writer.WriteStartArray("results"); @@ -207,6 +284,7 @@ public byte[] ToJson(PostmanCollection collection) { writer.WriteStartObject(); writer.WriteString("request", entry.Request); + writer.WriteNumber("iteration", entry.Iteration); writer.WriteString("method", entry.Method); writer.WriteString("url", entry.Url); writer.WriteBoolean("passed", entry.Passed); @@ -255,9 +333,9 @@ public byte[] ToJson(PostmanCollection collection) } } - /// What the report says of one request, redacted. is null when there was no response (see ). + /// What the report says of one request in one iteration (from 1), redacted. is null when there was no response (see ). private sealed record ReportEntry( - string Request, string Method, string Url, bool Passed, int? Status, long Bytes, string? Error, List? Tests, string? ScriptError, double TotalMs); + string Request, int Iteration, string Method, string Url, bool Passed, int? Status, long Bytes, string? Error, List? Tests, string? ScriptError, double TotalMs); private sealed record ReportTest(string Name, bool Passed, string? Error); diff --git a/src/TermRest.Core/Scripting/CSharpWorkerCode.cs b/src/TermRest.Core/Scripting/CSharpWorkerCode.cs index 9ce8d3c..065b1f6 100644 --- a/src/TermRest.Core/Scripting/CSharpWorkerCode.cs +++ b/src/TermRest.Core/Scripting/CSharpWorkerCode.cs @@ -244,12 +244,13 @@ public sealed class Tr { private readonly JsonArray _tests; - internal Tr(Scope environment, Scope collectionVariables, Scope globals, Variables variables, Request request, Response response, Info info, JsonArray tests) + internal Tr(Scope environment, Scope collectionVariables, Scope globals, Variables variables, Scope iterationData, Request request, Response response, Info info, JsonArray tests) { Environment = environment; CollectionVariables = collectionVariables; Globals = globals; Variables = variables; + IterationData = iterationData; Request = request; Response = response; Info = info; @@ -263,9 +264,12 @@ internal Tr(Scope environment, Scope collectionVariables, Scope globals, Variabl public Scope Globals { get; } - /// Reads every scope (this request, environment, collection, globals); Set is for this request only. + /// Reads every scope (this request, the run's iteration data, environment, collection, globals); Set is for this request only. public Variables Variables { get; } + /// The data of the run's current iteration, a row of its data file (termrest run --iteration-data); empty without one. + public Scope IterationData { get; } + /// The request: change it in pre-request scripts ({{variables}} are not replaced yet). public Request Request { get; } @@ -652,6 +656,8 @@ internal Info(string phase, JsonObject data) RequestName = Host.AsText(data?["request_name"]); Collection = Host.AsText(data?["collection"]); Environment = Host.AsText(data?["environment"]); + Iteration = data?["iteration"] is JsonValue iteration && iteration.TryGetValue(out var number) ? number : 0; + IterationCount = data?["iteration_count"] is JsonValue count && count.TryGetValue(out var total) ? total : 1; } /// "prerequest" or "test". @@ -665,6 +671,12 @@ internal Info(string phase, JsonObject data) public string Collection { get; } public string Environment { get; } + + /// The run's current iteration, from 0. + public int Iteration { get; } + + /// The number of iterations of the run. + public int IterationCount { get; } } /// A failed tr.Assert or tr.AssertEqual: a test shows its message alone. @@ -801,7 +813,7 @@ Dictionary Values(string scope) return values; } - Dictionary environment = Values("environment"), collection = Values("collection"), globals = Values("globals"), local = Values("local"); + Dictionary environment = Values("environment"), collection = Values("collection"), globals = Values("globals"), local = Values("local"), data = Values("data"); var info = new Info(phase, message["info"] as JsonObject); var tests = new JsonArray(); var logs = new JsonArray(); @@ -810,7 +822,8 @@ Dictionary Values(string scope) new Scope(environment, changes["environment"].AsObject()), new Scope(collection, changes["collection"].AsObject()), new Scope(globals, changes["globals"].AsObject()), - new Variables(local, changes["local"].AsObject(), new[] { local, environment, collection, globals }, message["dynamic"] as JsonObject), + new Variables(local, changes["local"].AsObject(), new[] { local, data, environment, collection, globals }, message["dynamic"] as JsonObject), + new Scope(data, new JsonObject()), request, message["response"] is JsonObject response ? new Response(response) : null, info, diff --git a/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs b/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs index da4add1..1e1a224 100644 --- a/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs +++ b/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs @@ -1417,8 +1417,8 @@ function test(name, fn) { const pm = { info: { eventName: phase === 'prerequest' ? 'prerequest' : 'test', - iteration: 0, - iterationCount: 1, + iteration: typeof info.iteration === 'number' ? info.iteration : 0, + iterationCount: typeof info.iteration_count === 'number' ? info.iteration_count : 1, requestName: info.request_name === null ? undefined : info.request_name, requestId: host.uuid(), }, @@ -1532,8 +1532,8 @@ function xml2Json(xml) { xml2Json, environment: pm.environment.toObject(), globals: pm.globals.toObject(), - data: {}, - iteration: 0, + data: pm.iterationData.toObject(), + iteration: pm.info.iteration, request: { url: String(pm.request.url), method: pm.request.method, headers: pm.request.headers.toObject(true, true), data: pm.request.body.raw, name: pm.info.requestName }, }); diff --git a/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs b/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs index 43613d0..86c495b 100644 --- a/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs +++ b/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs @@ -657,6 +657,9 @@ class TrInfo { [object] $RequestName [object] $Collection [object] $Environment + # The run's current iteration, from 0, and the number of its iterations. + [int] $Iteration + [int] $IterationCount = 1 } # What scripts get as $tr: the request, the response, variables, tests. @@ -665,6 +668,8 @@ class Tr { [TrScope] $CollectionVariables [TrScope] $Globals [TrVariables] $Variables + # The data of the run's current iteration, a row of its data file (termrest run --iteration-data); empty without one. + [TrScope] $IterationData [TrRequest] $Request # The response; $null in pre-request scripts. [TrResponse] $Response @@ -848,6 +853,11 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { $collection = Get-TrValues $variables 'collection' $globals = Get-TrValues $variables 'globals' $local = Get-TrValues $variables 'local' + $iterationData = [System.Collections.Generic.Dictionary[string, string]]::new([StringComparer]::Ordinal) + if ($null -ne $variables -and $null -ne $variables['data']) { + foreach ($pair in $variables['data'].GetEnumerator()) { $iterationData[$pair.Key] = [TrText]::Of($pair.Value) } + } + $data = $message['info'] $info = [TrInfo]::new() $info.Phase = $phase @@ -855,13 +865,16 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { $info.RequestName = $data['request_name'] $info.Collection = $data['collection'] $info.Environment = $data['environment'] + if ($null -ne $data['iteration']) { $info.Iteration = [int] $data['iteration'] } + if ($null -ne $data['iteration_count']) { $info.IterationCount = [int] $data['iteration_count'] } } $tr = [Tr]::new() $tr.Environment = [TrScope]::new($environment, $changes['environment']) $tr.CollectionVariables = [TrScope]::new($collection, $changes['collection']) $tr.Globals = [TrScope]::new($globals, $changes['globals']) - $tr.Variables = [TrVariables]::new($local, $changes['local'], @($local, $environment, $collection, $globals), $message['dynamic']) + $tr.Variables = [TrVariables]::new($local, $changes['local'], @($local, $iterationData, $environment, $collection, $globals), $message['dynamic']) + $tr.IterationData = [TrScope]::new($iterationData, [System.Collections.Generic.Dictionary[string, object]]::new([StringComparer]::Ordinal)) $tr.Request = [TrRequest]::new($message['request'], $phase -eq 'prerequest') if ($null -ne $message['response']) { $tr.Response = [TrResponse]::new($message['response']) } $tr.Info = $info diff --git a/src/TermRest.Core/Scripting/PythonWorkerCode.cs b/src/TermRest.Core/Scripting/PythonWorkerCode.cs index 4ab599d..d4f3719 100644 --- a/src/TermRest.Core/Scripting/PythonWorkerCode.cs +++ b/src/TermRest.Core/Scripting/PythonWorkerCode.cs @@ -216,7 +216,7 @@ def __repr__(self): class Variables(Scope): - # tr.variables reads every scope (this request, environment, collection, globals) and sets this request's. + # tr.variables reads every scope (this request, the run's iteration data, environment, collection, globals) and sets this request's. def __init__(self, local, changes, scopes, dynamic=None): super().__init__(local, changes) @@ -439,6 +439,7 @@ def _run(message): variables = message.get("variables") or {} changes = {"environment": {}, "collection": {}, "globals": {}, "local": {}} values = {scope: dict(variables.get(scope) or {}) for scope in changes} + data = dict(variables.get("data") or {}) info = types.SimpleNamespace(phase=phase, script="", **(message.get("info") or {})) tests, logs = [], [] request = Request(message.get("request") or {}, phase == "prerequest") @@ -446,7 +447,8 @@ def _run(message): environment=Scope(values["environment"], changes["environment"]), collection_variables=Scope(values["collection"], changes["collection"]), globals=Scope(values["globals"], changes["globals"]), - variables=Variables(values["local"], changes["local"], [values["local"], values["environment"], values["collection"], values["globals"]], _dynamic(message.get("dynamic") or {})), + variables=Variables(values["local"], changes["local"], [values["local"], data, values["environment"], values["collection"], values["globals"]], _dynamic(message.get("dynamic") or {})), + iteration_data=Scope(data, {}), request=request, response=Response(message["response"]) if message.get("response") else None, info=info, diff --git a/src/TermRest.Core/Workspace/IterationDataFile.cs b/src/TermRest.Core/Workspace/IterationDataFile.cs new file mode 100644 index 0000000..6f6c172 --- /dev/null +++ b/src/TermRest.Core/Workspace/IterationDataFile.cs @@ -0,0 +1,192 @@ +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace TermRest.Core.Workspace; + +/// +/// The data file of a collection run (Newman's --iteration-data): CSV with a header row, or JSON, an array of +/// objects. Each row is the data of one iteration: data variables for its requests ({{name}}) and scripts +/// (pm.iterationData). Rows are read one at a time, as they are needed, so a large file takes no more memory than a row. +/// +public sealed class IterationDataFile +{ + private IterationDataFile(string path, bool isJson) + { + Path = path; + IsJson = isJson; + } + + public string Path { get; } + + /// JSON (values keep their types: numbers, true and false, objects …), else CSV (every value is text). + public bool IsJson { get; } + + private string Name => System.IO.Path.GetFileName(Path); + + /// Opens a data file: JSON when it starts with '[' (after white space and a byte order mark), else CSV. + public static IterationDataFile Open(string path) + { + using var reader = new StreamReader(path, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); + int c; + while ((c = reader.Read()) >= 0 && char.IsWhiteSpace((char)c)) + { + } + + return new IterationDataFile(path, c == '['); + } + + /// The rows, read as they are needed. + /// The file, or a row, is not valid (the message says where). + public IAsyncEnumerable ReadAsync(CancellationToken cancellationToken = default) => + IsJson ? ReadJsonAsync(cancellationToken) : ReadCsv().ToAsyncEnumerable(); + + /// How many rows the file has: read through once, a row at a time. + public async Task CountAsync(CancellationToken cancellationToken = default) + { + var count = 0; + await foreach (var _ in ReadAsync(cancellationToken).ConfigureAwait(false)) + { + count++; + } + + return count; + } + + private async IAsyncEnumerable ReadJsonAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + var stream = File.OpenRead(Path); + await using (stream.ConfigureAwait(false)) + { + var items = JsonSerializer.DeserializeAsyncEnumerable(stream, CoreJsonContext.Default.JsonElement, cancellationToken).GetAsyncEnumerator(cancellationToken); + await using (items.ConfigureAwait(false)) + { + for (var number = 1; ; number++) + { + try + { + if (!await items.MoveNextAsync().ConfigureAwait(false)) + { + yield break; + } + } + catch (JsonException ex) + { + throw new InvalidDataException($"{Name} is not a JSON array of objects: {ex.Message}", ex); + } + + if (items.Current.ValueKind != JsonValueKind.Object) + { + throw new InvalidDataException($"{Name}: item {number} of the array is not an object ({{\"name\": value, …}}) but {items.Current.ValueKind.ToString().ToLowerInvariant()}."); + } + + yield return JsonObject.Create(items.Current)!; + } + } + } + } + + private IEnumerable ReadCsv() + { + using var reader = new StreamReader(Path, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); + string[]? keys = null; + var row = 0; + while (ReadRecord(reader) is { } fields) + { + // Lines without a value (an empty line, or ",,," from a spreadsheet) are not rows. + if (fields.All(f => f.Length == 0)) + { + continue; + } + + if (keys is null) + { + keys = fields; + continue; + } + + row++; + if (fields.Length > keys.Length && fields.Skip(keys.Length).Any(f => f.Length > 0)) + { + throw new InvalidDataException($"{Name}: row {row} has {fields.Length} values, but the header row names {keys.Length}. Put a value with a comma in double quotes."); + } + + var values = new JsonObject(); + for (var i = 0; i < keys.Length; i++) + { + values[keys[i]] = i < fields.Length ? fields[i] : ""; + } + + yield return values; + } + } + + /// + /// One CSV record (RFC 4180): fields separated by commas, a field in double quotes may hold commas and line breaks, and + /// "" in it is a quote. Null at the end of the file. + /// + private static string[]? ReadRecord(TextReader reader) + { + var fields = new List(); + var field = new StringBuilder(); + var quoted = false; + var any = false; + while (true) + { + var c = reader.Read(); + if (c < 0) + { + if (!any) + { + return null; + } + + fields.Add(field.ToString()); + return [.. fields]; + } + + any = true; + if (quoted) + { + if (c != '"') + { + field.Append((char)c); + } + else if (reader.Peek() == '"') + { + reader.Read(); + field.Append('"'); + } + else + { + quoted = false; + } + + continue; + } + + switch (c) + { + case '"' when field.Length == 0: + quoted = true; // a quote inside a value that doesn't start with one is a character + break; + case ',': + fields.Add(field.ToString()); + field.Clear(); + break; + case '\r' or '\n': + if (c == '\r' && reader.Peek() == '\n') + { + reader.Read(); + } + + fields.Add(field.ToString()); + return [.. fields]; + default: + field.Append((char)c); + break; + } + } + } +} diff --git a/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs b/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs index ed8daab..73cc3f4 100644 --- a/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs +++ b/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs @@ -350,10 +350,20 @@ public ScriptPlan PlanScripts(PostmanCollection collection, RequestNode? node, S ["collection"] = Values(collection.GetVariables(), Session.Find(collection)), ["globals"] = Values(Workspace.Globals?.Values, Session.Globals), ["local"] = Values(LocalVariables.Select(v => new KeyValueEntry { Key = v.Key, Value = v.Value }), local), + + // With their JSON types: Postman's iteration data keeps them (pm.iterationData.get('count') is a number). + ["data"] = IterationData?.DeepClone() ?? new JsonObject(), }, ["request"] = request, ["response"] = response, - ["info"] = new JsonObject { ["request_name"] = requestName, ["collection"] = collection.Name, ["environment"] = environment?.Name }, + ["info"] = new JsonObject + { + ["request_name"] = requestName, + ["collection"] = collection.Name, + ["environment"] = environment?.Name, + ["iteration"] = Iteration, + ["iteration_count"] = IterationCount, + }, ["dynamic"] = new JsonObject { ["firstNames"] = PostmanJson.ToJsonArray(VariableResolver.FirstNames.Select(n => (JsonNode?)n)), diff --git a/src/TermRest.Core/Workspace/RequestRunner.cs b/src/TermRest.Core/Workspace/RequestRunner.cs index 9ba4d6b..df8fef0 100644 --- a/src/TermRest.Core/Workspace/RequestRunner.cs +++ b/src/TermRest.Core/Workspace/RequestRunner.cs @@ -33,6 +33,35 @@ public RequestRunner(ApiWorkspace workspace) /// Highest-precedence variables (CLI --var, values captured during a run). public Dictionary LocalVariables { get; } = new(StringComparer.Ordinal); + /// + /// The data of the run's current iteration (a row of its data file, see ): data variables, + /// below this request's variables and above the environment's, as in Postman. Scripts get its values with their JSON + /// types (pm.iterationData); requests get them as text (numbers and true as written, objects as JSON). Null: none. + /// + public System.Text.Json.Nodes.JsonObject? IterationData + { + get => _iterationData; + set + { + _iterationData = value; + _iterationText = value?.ToDictionary(p => p.Key, p => p.Value switch + { + null => "null", + System.Text.Json.Nodes.JsonValue text when text.TryGetValue(out var s) => s, + var other => other.ToJsonString(), + }, StringComparer.Ordinal); + } + } + + /// The run's current iteration, from 0 (pm.info.iteration). + public int Iteration { get; set; } + + /// The number of iterations of the run (pm.info.iterationCount). + public int IterationCount { get; set; } = 1; + + private System.Text.Json.Nodes.JsonObject? _iterationData; + private Dictionary? _iterationText; + /// Overrides the workspace's active environment (e.g. CLI --env file.json). public PostmanEnvironment? EnvironmentOverride { get; set; } @@ -147,6 +176,11 @@ private VariableResolver CreateResolver(PostmanEnvironment? environment, Postman scopes.Add(new OverlayScope(new DictionaryScope("local", LocalVariables), requestVariables)); } + if (_iterationText is { Count: > 0 } data) + { + scopes.Add(new DictionaryScope($"data (iteration {Iteration + 1})", data)); + } + if (environment is not null) { scopes.Add(new OverlayScope(new EntryListScope($"environment '{environment.Name}'", environment.Values), Session.Find(environment))); diff --git a/src/TermRest.Core/Workspace/WorkspaceSettings.cs b/src/TermRest.Core/Workspace/WorkspaceSettings.cs index 5977399..8e6d4ac 100644 --- a/src/TermRest.Core/Workspace/WorkspaceSettings.cs +++ b/src/TermRest.Core/Workspace/WorkspaceSettings.cs @@ -112,5 +112,6 @@ public WorkspaceSettings Clone() [JsonSerializable(typeof(WorkspaceSettings))] [JsonSerializable(typeof(UserSettings))] [JsonSerializable(typeof(ProxyCredentialFile))] +[JsonSerializable(typeof(System.Text.Json.JsonElement))] [JsonSerializable(typeof(List))] internal sealed partial class CoreJsonContext : JsonSerializerContext; diff --git a/src/TermRest.Tui/MainWindow.cs b/src/TermRest.Tui/MainWindow.cs index 2061b25..867a867 100644 --- a/src/TermRest.Tui/MainWindow.cs +++ b/src/TermRest.Tui/MainWindow.cs @@ -1209,12 +1209,14 @@ the one its Scripts tab chooses (Run in), or with Auto the first language of you Python: the tr object tr.environment, tr.collection_variables, tr.globals .get(name), .set(name, value), .unset(name), .has(name), .to_dict(), and tr.environment["name"]. - tr.variables reads every scope (this request, environment, collection, globals); .set() is for this - request only; .replace_in("{{base}}/x") replaces {{variables}} in a text. + tr.variables reads every scope (this request, the run's iteration data, environment, collection, globals); .set() + is for this request only; .replace_in("{{base}}/x") replaces {{variables}} in a text. + tr.iteration_data the run's current row of its data file (termrest run -d users.csv): .get(name) …. tr.request .method, .url, .headers (.get .set .add .remove), .body: change them before sending. tr.response .status (or .code), .reason, .headers, .time (ms), .size, .text(), .json(), .content (bytes). tr.test(name, fn) records a test that fails when fn raises (assert …); also @tr.test("name") on a function. - tr.info .phase ("prerequest" or "test"), .script, .request_name, .collection, .environment. + tr.info .phase ("prerequest" or "test"), .script, .request_name, .collection, .environment, .iteration, + .iteration_count. print(…) output goes to the response's Scripts tab, with the tests and errors. @tr.test("returns the new item") @@ -1223,7 +1225,8 @@ def _(): assert tr.response.json()["name"] == "Ada" JavaScript: Postman's pm object - pm.environment, pm.collectionVariables, pm.globals, pm.variables .get .set .unset .has .toObject .replaceIn + pm.environment, pm.collectionVariables, pm.globals, pm.variables, pm.iterationData (the run's data row) + .get .set .unset .has .toObject .replaceIn pm.request .method, .url (.query, .toString()), .headers (.add .upsert .remove .get), .body.raw pm.response .code, .status, .headers, .responseTime, .json(), .text(), .to.have.status(200), .to.be.ok … pm.test(name, fn), pm.expect(value).to.equal(…) (chai's assertions), pm.sendRequest(…), pm.info, console.log @@ -1245,6 +1248,7 @@ assert tr.response.json()["name"] == "Ada" stops it. tr.Environment, tr.CollectionVariables, tr.Globals ["name"], .Get .Set .Unset .Has .ToDictionary tr.Variables reads every scope; .Set() is for this request only; .ReplaceIn("{{base}}/x"). + tr.IterationData the run's current row of its data file, as text: .Get(name) …. tr.Request .Method, .Url, .Headers (.Get .Set .Add .Remove, ["name"]), .Body: change them before sending. tr.Response .Status (or .Code), .Reason, .Headers, .Time (ms), .Size, .Text(), .Json() (a JsonNode), .Content. tr.Test(name, () => …) (async too), tr.Assert(condition), tr.AssertEqual(expected, actual), tr.Info. @@ -1259,6 +1263,7 @@ tr.Response .Status (or .Code), .Reason, .Headers, .Time (ms), .Size, .Text() PowerShell: the $tr object, as in C# $tr.Environment, $tr.CollectionVariables, $tr.Globals .Get(name) .Set(name, value) .Unset .Has .ToHashtable $tr.Variables reads every scope; .Set() is for this request only; .ReplaceIn('{{base}}/x'). + $tr.IterationData the run's current row of its data file, as text: .Get(name) …. $tr.Request .Method, .Url, .Headers (.Get .Set .Add .Remove .Items()), .Body: change them before sending. $tr.Response .Status (or .Code), .Reason, .Headers, .Time (ms), .Size, .Text(), .Json() (ConvertFrom-Json), .Content(). diff --git a/tests/TermRest.Cli.Tests/CommandLineTests.cs b/tests/TermRest.Cli.Tests/CommandLineTests.cs index 0e013b2..7b81b9f 100644 --- a/tests/TermRest.Cli.Tests/CommandLineTests.cs +++ b/tests/TermRest.Cli.Tests/CommandLineTests.cs @@ -1115,6 +1115,36 @@ public async Task A_proxy_in_the_workspace_settings_is_not_used_until_it_is_allo Assert.Equal(2, server.Requests); } + [Fact] + public async Task Run_sends_the_requests_once_for_each_row_of_a_data_file() + { + await using var server = await TestServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + var collection = WriteCollection(directory, "Api", [("Greet", "GET", server.BaseUrl + "/echo/{{name}}?n={{n}}")]); + var data = Path.Combine(directory, "people.csv"); + File.WriteAllText(data, "name,n\nada,1\n\"grace\",2\n"); + var report = Path.Combine(directory, "report.json"); + + var rows = await Termrest.RunAsync(["run", collection, "-d", data, "--report-json", report]); + var more = await Termrest.RunAsync(["run", collection, "--iteration-data", data, "-n", "3"]); // past the last row: that row again + var missing = await Termrest.RunAsync(["run", collection, "-d", Path.Combine(directory, "missing.csv")]); + + Assert.True(rows.ExitCode == 0, rows.ToString()); + Assert.Contains("Running 1 request(s) × 2 iterations from 'Api', data from people.csv (2 row(s))", rows.ToString(), StringComparison.Ordinal); + Assert.Contains("Iteration 2/2", rows.ToString(), StringComparison.Ordinal); + var json = JsonNode.Parse(File.ReadAllText(report))!; + Assert.Equal(2, (int)json["iterations"]!); + Assert.Equal( + [(1, server.BaseUrl + "/echo/ada?n=1"), (2, server.BaseUrl + "/echo/grace?n=2")], + ((JsonArray)json["results"]!).Select(r => ((int)r!["iteration"]!, (string)r["url"]!))); + Assert.True(more.ExitCode == 0, more.ToString()); + Assert.Contains("Iteration 3/3", more.ToString(), StringComparison.Ordinal); + Assert.Contains("3 passed, 0 failed", more.ToString(), StringComparison.Ordinal); + Assert.Equal(5, server.Requests); + Assert.Equal(2, missing.ExitCode); + Assert.Contains("--iteration-data:", missing.Error, StringComparison.Ordinal); + } + [Fact] public async Task Send_signs_in_to_a_proxy_with_proxy_user_and_says_what_a_proxy_that_wants_a_sign_in_needs() { diff --git a/tests/TermRest.Core.Tests/IterationDataTests.cs b/tests/TermRest.Core.Tests/IterationDataTests.cs new file mode 100644 index 0000000..8f307b5 --- /dev/null +++ b/tests/TermRest.Core.Tests/IterationDataTests.cs @@ -0,0 +1,149 @@ +using System.Text.Json.Nodes; +using TermRest.Core.Http; +using TermRest.Core.Model; +using TermRest.Core.Postman; +using TermRest.Core.Scripting; +using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Workspace; +using Xunit; + +namespace TermRest.Core.Tests; + +public class IterationDataTests +{ + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + + private async Task> RowsAsync(string content, string extension) + { + var path = Path.Combine(TestFiles.NewTempDirectory(), "data" + extension); + await File.WriteAllTextAsync(path, content, _ct); + var rows = new List(); + var relaxed = new System.Text.Json.JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + await foreach (var row in IterationDataFile.Open(path).ReadAsync(_ct)) + { + rows.Add(row.ToJsonString(relaxed)); + } + + return rows; + } + + [Fact] + public async Task A_csv_data_file_has_a_header_row_and_quoted_values_as_rfc_4180_has_them() + { + var rows = await RowsAsync( + "\uFEFFname,note,city\r\n" + + "Ada,\"says \"\"hi\"\", then, bye\",London\r\n" + + "\r\n" + + ",,\r\n" + // a spreadsheet's empty row + "Grace,\"two\nlines\"\n" + // a value missing at the end + "Zoë,x\"y,Paris,\n", // a quote inside a value; an empty value after the last + ".csv"); + + Assert.Equal( + [ + """{"name":"Ada","note":"says \"hi\", then, bye","city":"London"}""", + """{"name":"Grace","note":"two\nlines","city":""}""", + """{"name":"Zoë","note":"x\"y","city":"Paris"}""", + ], rows); + + var bad = Assert.Throws(() => RowsAsync("a,b\n1,2,3\n", ".csv").GetAwaiter().GetResult()); + Assert.Equal("data.csv: row 1 has 3 values, but the header row names 2. Put a value with a comma in double quotes.", bad.Message); + } + + [Fact] + public async Task A_json_data_file_is_an_array_of_objects_whose_values_keep_their_types() + { + var rows = await RowsAsync(""" [ { "id": 7, "admin": true, "tags": ["a"], "name": null }, { "id": 8 } ]""", ".json"); + Assert.Equal(["""{"id":7,"admin":true,"tags":["a"],"name":null}""", """{"id":8}"""], rows); + + // JSON whatever the extension, as its first character says; CSV otherwise. + Assert.Equal(["""{"id":1}"""], await RowsAsync("""[{"id": 1}]""", ".txt")); + + var notObject = Assert.Throws(() => RowsAsync("""[{"id": 1}, 2]""", ".json").GetAwaiter().GetResult()); + Assert.Equal("data.json: item 2 of the array is not an object ({\"name\": value, …}) but number.", notObject.Message); + var broken = Assert.Throws(() => RowsAsync("""[{"id": 1""", ".json").GetAwaiter().GetResult()); + Assert.StartsWith("data.json is not a JSON array of objects:", broken.Message, StringComparison.Ordinal); + } + + [Fact] + public void Data_variables_come_after_this_requests_and_before_the_environments() + { + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var environment = workspace.CreateEnvironment("dev"); + environment.SetValues([new KeyValueEntry { Key = "who", Value = "env" }, new KeyValueEntry { Key = "host", Value = "env.example.com" }]); + workspace.ActiveEnvironment = environment; + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace) { Iteration = 1, IterationCount = 3 }; + runner.IterationData = (JsonObject)JsonNode.Parse("""{ "who": "data", "id": 42, "admin": true, "tags": ["a"] }""")!; + runner.LocalVariables["id"] = "local"; + + var prepared = runner.Prepare(collection, null, new HttpRequestSpec { Url = "https://{{host}}/{{who}}/{{id}}?admin={{admin}}&tags={{tags}}" }); + + Assert.Equal("https://env.example.com/data/local?admin=true&tags=[\"a\"]", prepared.Url); + } + + public static TheoryData Languages => [ScriptLanguage.JavaScript, ScriptLanguage.Python, ScriptLanguage.CSharp, ScriptLanguage.PowerShell]; + + [Theory] + [MemberData(nameof(Languages))] + public async Task Scripts_see_the_iteration_and_its_data(string language) + { + var runtime = language switch + { + ScriptLanguage.JavaScript => TestJavaScript.Require(), + ScriptLanguage.Python => TestPython.Require(), + ScriptLanguage.CSharp => TestCSharp.Require(), + _ => TestPowerShell.Require(), + }; + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + var test = language switch + { + ScriptLanguage.JavaScript => """ + pm.test('data', () => { + pm.expect(pm.iterationData.get('count')).to.equal(3); + pm.expect(pm.iterationData.get('name')).to.equal('Ada'); + pm.expect(pm.variables.get('name')).to.equal('Ada'); + pm.expect([pm.info.iteration, pm.info.iterationCount]).to.eql([1, 2]); + pm.expect(data.name).to.equal('Ada'); + }); + """, + ScriptLanguage.Python => """ + tr.test("data", lambda: None) + assert tr.iteration_data.get("count") == 3 + assert tr.iteration_data.get("name") == "Ada" and tr.variables.get("name") == "Ada" + assert (tr.info.iteration, tr.info.iteration_count) == (1, 2) + """, + ScriptLanguage.CSharp => """ + tr.Test("data", () => { }); + tr.AssertEqual("3", tr.IterationData.Get("count")); + tr.AssertEqual("Ada", tr.Variables.Get("name")); + tr.AssertEqual(1, tr.Info.Iteration); + tr.AssertEqual(2, tr.Info.IterationCount); + """, + _ => """ + $tr.Test('data', { }) + $tr.AssertEqual('3', $tr.IterationData.Get('count')) + $tr.AssertEqual('Ada', $tr.Variables.Get('name')) + $tr.AssertEqual(1, $tr.Info.Iteration) + $tr.AssertEqual(2, $tr.Info.IterationCount) + """, + }; + var request = collection.AddRequest(collection.RootNode, "Echo", new HttpRequestSpec + { + Url = server.Url("echo") + "?name={{name}}", + Scripts = new ScriptSet("", test, language), + }); + using var runner = new RequestRunner(workspace) { Iteration = 1, IterationCount = 2 }; + runner.SetRuntime(language, runtime); + runner.IterationData = (JsonObject)JsonNode.Parse("""{ "name": "Ada", "count": 3 }""")!; + + var exchange = await runner.SendAsync(collection, request, request.ReadSpec(), null, _ct); + + var results = exchange.Scripts!; + Assert.True(results.Error is null, results.Describe()); + Assert.Equal([("data", true)], results.Tests.Select(t => (t.Name, t.Passed))); + Assert.EndsWith("?name=Ada", exchange.Request.Url, StringComparison.Ordinal); + } +} From b0cf3a26fbfad79a0afe4e60d9c0499e69abe021 Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Tue, 17 Nov 2026 23:08:09 -0700 Subject: [PATCH 05/11] Core and TUI: requests that scripts send go through TermRest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pm.sendRequest no longer uses the runtime's own fetch, and Python, C# and PowerShell scripts get the same: tr.send_request(request, **fields), tr.SendRequest(request) and SendRequestAsync, and $tr.SendRequest(request). A request goes out as TermRest's own do: with the workspace's client certificates (matched by URL), CA bundle and SSL verification, proxy and its sign-in, timeout, redirects and response size limit, and the session's cookies; it may fetch an OAuth 2.0 token. It takes a URL, or a request as Postman's pm.sendRequest takes it (url, method, header, body, auth), and what the other languages write naturally: headers as a map or pairs, form fields as a map, a body as text or any other JSON (sent as JSON). As in Postman, {{variables}} are sent as written (a new VariableResolver.Literal), with a hint naming the language's replaceIn when some are; the auth is the request's own, none inherited. Scripts get the response as tr.response has it, or the error (ConnectionError in Python, HttpRequestException in C# and PowerShell), and a line in their output, without the URL's query: POST https://host/login → 200 OK (85 ms). Requests are recorded while recording, not kept in the history. The protocol: the worker writes {"send":{"id":n,"request":…}} (after its reply marker), and ScriptWorker starts the request while it goes on reading; the answer, {"sent":{"id":n,…}}, is a line of the worker's input, written under a lock. JavaScript resolves it as it comes in (several at a time; six are sent at once at most); Python, C# and PowerShell send one at a time and read their answer themselves, and a request started after the scripts ended is refused, so no answer is ever read as the next message. Requests still running when the scripts reply are cancelled once the answer being written is whole, and none is answered after the reply; when the runtime is stopped (time limit, cancel), they are cancelled at once. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 21 ++- .../Scripting/CSharpWorkerCode.cs | 68 +++++++ .../Scripting/JavaScriptWorkerCode.cs | 97 ++++++---- .../Scripting/PowerShellWorkerCode.cs | 34 ++++ .../Scripting/PythonWorkerCode.cs | 45 ++++- src/TermRest.Core/Scripting/ScriptRequest.cs | 159 ++++++++++++++++ src/TermRest.Core/Scripting/ScriptWorker.cs | 172 ++++++++++++++++-- .../Variables/VariableResolver.cs | 29 +++ .../Workspace/RequestRunner.Scripts.cs | 71 +++++++- src/TermRest.Tui/MainWindow.cs | 5 + .../CSharpScriptingTests.cs | 4 +- .../TermRest.Core.Tests/ScriptRequestTests.cs | 167 +++++++++++++++++ 12 files changed, 811 insertions(+), 61 deletions(-) create mode 100644 src/TermRest.Core/Scripting/ScriptRequest.cs create mode 100644 tests/TermRest.Core.Tests/ScriptRequestTests.cs diff --git a/README.md b/README.md index af6ce7b..3ae9218 100644 --- a/README.md +++ b/README.md @@ -223,6 +223,7 @@ A runtime answers in about a millisecond once started; starting takes 0.1–0.3 - **Order:** each phase runs the scripts of the collection, then the folders (outermost first), then the request, one at a time: each script sees the variables and request changes of the ones before it. - **A failing pre-request script stops the request.** This covers an exception, a syntax or compile error, and a timeout. The request is not sent, nor added to the history or a recording, and the error is shown with the script's line. - **Time limit:** each phase may take 30 seconds (building C# scripts does not count); the runtime is then stopped and started again for the next script. *Tools › Scripts › Stop scripts* stops a script that runs at once; its request says it was stopped (`Python was stopped while the scripts ran.`). +- **Requests that scripts send** (`pm.sendRequest`, `tr.send_request`, `tr.SendRequest`, `$tr.SendRequest`) go through TermRest, as its own requests do: with the workspace's client certificates (matched by URL), CA bundle and SSL verification, proxy and its sign-in, timeout, redirects and response size limit, and the session's cookies. They take a URL, or a request as Postman's `pm.sendRequest` takes it: `url`, `method`, `header` (Postman's list, or a map of names to values), `body` (text, Postman's `{mode, raw …}`, or any other JSON, sent as JSON) and `auth` (their own: none is inherited). As in Postman, `{{variables}}` in them are sent as written: replace them first (`replaceIn`, `replace_in`). Each one adds a line to the script's output, without the URL's query (`POST https://api.example.com/login → 200 OK (85 ms)`); they are recorded while you record, and not kept in the history. They count towards the phase's time limit, and those still running when the scripts end are cancelled. JavaScript scripts can send several at a time (six at once, the others wait their turn), the other languages one at a time. - **Working folder:** the runtimes run in the workspace folder, so scripts can import your own modules from it (`import helpers`, `require('./helpers')`, `Import-Module ./Helpers.psm1`) and read its files. Python and PowerShell modules load once per process; *Tools › Scripts › Stop scripts* reloads them. - **Values are text:** a variable or header set to `42` reads back as `"42"` in the next request or phase; a date or time as ISO 8601 text (`2024-01-02T03:04:05+00:00`, `2024-01-02`), and a GUID, URL or decimal as its text; lists and objects as JSON. @@ -244,6 +245,7 @@ A collection, a folder and a request can each have a pre-request and a post-resp | `tr.iteration_data` | The data of the run's current iteration, a row of its data file (`termrest run --iteration-data`; see [Command line](#command-line)): `.get(name)` …, values with their JSON types. Empty without one. | | `tr.request` | `.method`, `.url`, `.headers` (`.get`, `.get_all`, `.set`, `.add`, `.remove`, `.items()`; as with requests, a dict, another mapping or a list of pairs can replace them), `.body` (raw bodies; bytes are sent as their UTF-8 text, a dict, list, tuple or bool as JSON). Pre-request scripts can change them; `{{variables}}` they contain are replaced afterwards. A request they leave in a state that can't be sent isn't sent, and what they printed, tested and set is kept. Test scripts see the request as it was sent. | | `tr.response` | In test scripts: `.status` (or `.code`), `.reason`, `.headers`, `.time` (ms), `.size`, `.text()`, `.json()`, `.content` (bytes). | +| `tr.send_request(request, **fields)` | Sends a request through TermRest (see *Requests that scripts send* above) and returns its response, as `tr.response` has it: a URL, or a dict (`{"url": …, "method": "POST", "headers": {…}, "body": {…}}`), to which fields given by name are added: `tr.send_request(url, method="POST", body={"name": "Ada"})`. Raises `ConnectionError` when it can't be sent. | | `tr.test(name, fn)`, `@tr.test(name)` | Records a test that fails when `fn` raises, as `assert` does. | | `tr.info` | `.phase` (`prerequest` or `test`), `.script`, `.request_name`, `.collection`, `.environment`, `.iteration` (from 0) and `.iteration_count` of the run. | | `print(…)` | Goes to the response's *Scripts* tab, and to stderr on the command line. So does `logging`, also through a handler an earlier script set up (`logging.basicConfig()`). | @@ -254,7 +256,7 @@ A collection, a folder and a request can each have a pre-request and a post-resp | `pm.request` | `.method`, `.url` (`.query.add`, `.toString()`, `.getHost()` …; as in Postman, its `host` and `path` may be set as text), `.headers` (`.add`, `.upsert`, `.remove`, `.get`, `.has`, `.each` …), `.body.raw`. Pre-request scripts can change them, as with `tr.request`; a request they leave in a state that can't be sent (a `query` that is no longer a list) isn't sent, and what they printed, tested and set is kept. | | `pm.response` | `.code`, `.status`, `.headers`, `.responseTime`, `.responseSize`, `.json()`, `.text()`, `.stream`, `.cookies`, and Postman's assertions: `.to.have.status(…)`, `.to.have.header(…)`, `.to.have.body(…)`, `.to.have.jsonBody(…)`, `.to.be.ok`, `.success`, `.clientError`, `.withoutContent`, `.json` …, and `.to.have.jsonSchema(schema)` (with `ajv` installed in the workspace: ajv 6, Postman's, checks formats such as `email` or `date-time` itself; ajv 8 needs `ajv-formats` for them, and a format it doesn't know fails the test, saying so), which also checks any value: `pm.expect(data.items[0]).to.have.jsonSchema(itemSchema)`. | | `pm.test(name, fn)`, `pm.expect(value)` | Tests (also asynchronous: `async` functions, or a `done` callback) and chai's assertions: `equal`, `eql`, `include`, `a`/`an`, `property`, `lengthOf`, `above`/`below`, `oneOf`, `members`, `keys`, `match`, `throw`, `not`, `deep`, `nested` …, with chai's messages. As in Postman, a property no assertion has, such as a misspelled `.to.be.ture`, fails the test (`Invalid Chai property: ture. Did you mean "true"?`) instead of checking nothing. | -| `pm.sendRequest(request, callback)` | With a callback, or `await` it. It uses the runtime's own `fetch`: TermRest's certificates and proxy settings do not apply. | +| `pm.sendRequest(request, callback)` | With a callback, or `await` it; sent through TermRest (see *Requests that scripts send* above), several at a time if you like (`Promise.all`). `fetch` sends requests of the script's own, without TermRest's certificates and proxy settings. | | `pm.info`, `pm.cookies`, `console.log` … | As in Postman; `console` output goes where `print` does, that of the modules and packages scripts `require` too (Node.js's own warnings included). | | The API from before `pm` | `tests["name"] = …`, `postman.setEnvironmentVariable(…)`, `responseBody`, `responseCode`, `responseHeaders`, `responseTime`. | | `require(…)` | Node.js modules, your own files, and the packages installed in the workspace (`npm install lodash crypto-js moment`). Postman's globals `_`, `CryptoJS`, `cheerio` and `tv4` load those packages when first used; `xml2Json` uses `xml2js`. Bun installs packages it cannot find by itself. | @@ -274,10 +276,11 @@ A collection, a folder and a request can each have a pre-request and a post-resp | `tr.IterationData` | The data of the run's current iteration (`termrest run --iteration-data`), as text: `.Get(name)` …. Empty without one. | | `tr.Request` | `.Method`, `.Url`, `.Headers` (`["name"]`, `.Get`, `.GetAll`, `.Set`, `.Add`, `.Remove`, `.Has`), `.Body` (raw bodies). Pre-request scripts can change them. | | `tr.Response` | In test scripts: `.Status` (or `.Code`), `.Reason`, `.Headers`, `.Time` (ms), `.Size`, `.Text()`, `.Json()` (a `JsonNode`: `json["name"]`, `(int)json["id"]`), `.Content` (bytes). | +| `tr.SendRequest(request)`, `await tr.SendRequestAsync(request)` | Sends a request through TermRest (see *Requests that scripts send* above) and returns its response, as `tr.Response` has it: a URL, or `new { url, method = "POST", header = new Dictionary { … }, body = new { name = "Ada" } }`. Throws `HttpRequestException` when it can't be sent. | | `tr.Test(name, () => …)` | Records a test that fails when it throws; `async () => …` tests are awaited. Assertion libraries from NuGet work too. | | `tr.Assert(condition)`, `tr.AssertEqual(expected, actual)` | Fail with the code that failed: `assertion failed: tr.Response.Status == 201`, `tr.Response.Code: expected 201, got 200`. `AssertEqual` compares numbers as numbers and JSON as JSON: `tr.AssertEqual("Ada", json["name"])`. | | `tr.Info` | `.Phase`, `.Script`, `.RequestName`, `.Collection`, `.Environment`, `.Iteration` (from 0) and `.IterationCount` of the run. | -| `Console.WriteLine(…)` | Goes where `print` does. `HttpClient` sends requests of the script's own (TermRest's certificates and proxy settings do not apply). | +| `Console.WriteLine(…)` | Goes where `print` does. `HttpClient` sends requests of the script's own, without TermRest's certificates and proxy settings. | **PowerShell scripts** @@ -295,20 +298,18 @@ A collection, a folder and a request can each have a pre-request and a post-resp | `$tr.IterationData` | The data of the run's current iteration (`termrest run --iteration-data`), as text: `.Get(name)` …. Empty without one. | | `$tr.Request` | `.Method`, `.Url`, `.Headers` (`.Get`, `.GetAll`, `.Set`, `.Add`, `.Remove`, `.Has`, `.Items()`, `.Count`), `.Body` (raw bodies; `$null` for others; bytes are sent as UTF-8 text, a hashtable or object as JSON). Pre-request scripts can change them; a request they leave in a state that can't be sent (`.Headers` set to `$null`) isn't sent, and what they printed, tested and set is kept. | | `$tr.Response` | In test scripts: `.Status` (or `.Code`), `.Reason`, `.Headers`, `.Time` (ms), `.Size`, `.Text()`, `.Json()` (`ConvertFrom-Json`: `$json.name`), `.Content()` (bytes). | +| `$tr.SendRequest(request)` | Sends a request through TermRest (see *Requests that scripts send* above) and returns its response, as `$tr.Response` has it: a URL, or `@{ url = …; method = 'POST'; header = @{ … }; body = @{ name = 'Ada' } }`. Throws `HttpRequestException` when it can't be sent. | | `$tr.Test(name, { … })` | Records a test that fails when the block throws or a command in it fails. | | `$tr.Assert(condition)`, `$tr.AssertEqual(expected, actual)` | Fail with the code that failed: `assertion failed: $tr.Response.Status -eq 201`, `$tr.Response.Code: expected 201, got 200`. `AssertEqual` compares numbers as numbers, text exactly (case included, unlike `-eq`), and JSON objects and hashtables by their members. | | `$tr.Info` | `.Phase`, `.Script`, `.RequestName`, `.Collection`, `.Environment`, `.Iteration` (from 0) and `.IterationCount` of the run. | -| `Write-Host …` | Goes where `print` does. `Invoke-RestMethod` sends requests of the script's own (TermRest's certificates and proxy settings do not apply). | +| `Write-Host …` | Goes where `print` does. `Invoke-RestMethod` sends requests of the script's own, without TermRest's certificates and proxy settings. | ```python # Python: a collection pre-request script that logs in once, then sends the token with every request -import json, urllib.request - if not tr.environment.get("token"): - body = json.dumps({"user": tr.environment.get("user"), "password": tr.environment.get("password")}).encode() - login = urllib.request.Request(tr.variables.replace_in("{{base}}/login"), body, {"Content-Type": "application/json"}) - with urllib.request.urlopen(login) as reply: - tr.environment.set("token", json.load(reply)["token"]) + login = tr.send_request(tr.variables.replace_in("{{base}}/login"), method="POST", + body={"user": tr.environment.get("user"), "password": tr.environment.get("password")}) + tr.environment.set("token", login.json()["token"]) tr.request.headers.set("Authorization", "Bearer " + tr.environment.get("token")) ``` @@ -370,7 +371,7 @@ TermRest runs scripts the way a terminal runs commands: it starts the runtime yo **What a script can do, with nothing to stop it** - Read, change, delete or upload any file you can: source code, SSH keys, cloud credentials (`~/.azure`, `~/.aws`, `~/.kube`), browser profiles. -- See every variable, secret ones included, the requests with their `Authorization` headers, the responses, and TermRest's environment variables (tokens, in CI). It can send them anywhere: `fetch`, `HttpClient`, `urllib`, `Invoke-RestMethod` and `pm.sendRequest` do not go through TermRest. +- See every variable, secret ones included, the requests with their `Authorization` headers, the responses, and TermRest's environment variables (tokens, in CI). It can send them anywhere: with its runtime's own HTTP clients (`fetch`, `HttpClient`, `urllib`, `Invoke-RestMethod`), or through TermRest (`pm.sendRequest`, `tr.send_request` …), with the client certificates and proxy sign-in you set up for the URLs it picks, as the collection's own requests can. - Start programs, which may keep running after TermRest stops the runtime, install software, and change your system's settings. - Run code it brings in: - **C#:** `#:package` restores NuGet packages, and their build steps (MSBuild targets, analyzers) run while the scripts are built, before any script does. `#:sdk`, `#:project` and `#:include` bring in more. diff --git a/src/TermRest.Core/Scripting/CSharpWorkerCode.cs b/src/TermRest.Core/Scripting/CSharpWorkerCode.cs index 065b1f6..9a834ba 100644 --- a/src/TermRest.Core/Scripting/CSharpWorkerCode.cs +++ b/src/TermRest.Core/Scripting/CSharpWorkerCode.cs @@ -287,6 +287,23 @@ public void Test(string name, Action test) => Record(name, () => public void Test(string name, Func test) => Record(name, test); + /// + /// Sends a request through TermRest, with its certificates, proxy and settings, and returns its response (as + /// tr.Response has it); throws HttpRequestException when it can't be sent. The request is a URL, or as Postman's + /// pm.sendRequest takes it: new { url, method, header, body, auth }, where header may be a dictionary of names to + /// values, and body text (raw), JSON (any object without a mode) or Postman's { mode, raw … }. Its {{variables}} + /// are sent as written: tr.Variables.ReplaceIn replaces them. + /// + public Response SendRequest(object request) => Host.Send(request switch + { + string url => JsonValue.Create(url), + JsonNode node => node.DeepClone(), + null => throw new ArgumentNullException(nameof(request)), + _ => JsonSerializer.SerializeToNode(request, request.GetType()), + }); + + public Task SendRequestAsync(object request) => Task.Run(() => SendRequest(request)); + public void Assert(bool condition, string message = null, [CallerArgumentExpression(nameof(condition))] string expression = null) { if (!condition) @@ -696,7 +713,12 @@ internal static partial class Host private static readonly JsonSerializerOptions Options = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; private static readonly UTF8Encoding Utf8 = new(false); private static readonly Capture Output = new(); + private static readonly object SendLock = new(); private static FileStream _nothing; + private static TextReader _input; + private static TextWriter _output; + private static bool _sending; + private static int _sent; private static int Main(string[] args) { @@ -708,6 +730,7 @@ private static int Main(string[] args) } var (input, output) = Channel(); + (_input, _output) = (input, output); Console.SetIn(TextReader.Null); Console.SetOut(Output); Console.SetError(Output); @@ -715,6 +738,11 @@ private static int Main(string[] args) while ((line = input.ReadLine()) is not null) { JsonObject reply; + lock (SendLock) + { + _sending = true; + } + try { reply = Run(JsonNode.Parse(line).AsObject()); @@ -724,6 +752,12 @@ private static int Main(string[] args) reply = new JsonObject { ["fatal"] = error.ToString() }; } + // After a request a task still waits for: its answer comes before the next message. + lock (SendLock) + { + _sending = false; + } + output.Write(Marker + reply.ToJsonString(Options) + "\n"); output.Flush(); } @@ -731,6 +765,40 @@ private static int Main(string[] args) return 0; } + /// + /// tr.SendRequest: asks TermRest to send the request, with a line of output, and reads its answer, a line of + /// input; one at a time, as only the thread that asked may read it. + /// + internal static Response Send(JsonNode request) + { + string line; + lock (SendLock) + { + if (!_sending) + { + throw new InvalidOperationException("The scripts already finished: TermRest sends no more requests for them."); + } + + var send = new JsonObject { ["send"] = new JsonObject { ["id"] = ++_sent, ["request"] = request } }; + _output.Write(Marker + send.ToJsonString(Options) + "\n"); + _output.Flush(); + line = _input.ReadLine(); + } + + var answer = (line is null ? null : JsonNode.Parse(line)?["sent"] as JsonObject) ?? new JsonObject { ["error"] = "TermRest did not answer." }; + if (AsText(answer["log"]) is { } log) + { + Output.Write(log + "\n"); + } + + if (answer["error"] is not null) + { + throw new System.Net.Http.HttpRequestException(AsText(answer["error"])); + } + + return new Response(answer["response"] as JsonObject ?? new JsonObject()); + } + /// /// Requests come on a copy of stdin and answers go to a copy of stdout. Stdin itself then reads nothing and /// stdout goes to stderr, so programs that scripts start can neither take a request nor mix into an answer. diff --git a/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs b/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs index 1e1a224..0748aa0 100644 --- a/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs +++ b/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs @@ -6,6 +6,8 @@ namespace TermRest.Core.Scripting; /// too long for a command line, and no file is written. The worker then reads one JSON message per line, runs the /// scripts in it with Postman's pm object in a fresh vm context, and writes one reply line, marked with /// so that anything else written to stdout (by programs that scripts start) is ignored. +/// Requests the scripts send (pm.sendRequest) go out as marked lines too, and their answers come in as lines of input +/// (see 's RunAsync). /// internal static class JavaScriptWorkerCode { @@ -68,7 +70,7 @@ function compile(context, name, code) { async function run(line) { const context = vm.createContext({}); - const state = { onError: null, console: null }; + const state = { onError: null, console: null, sends: [] }; active = state; try { const start = sandboxScript.runInContext(context); @@ -77,9 +79,17 @@ async function run(line) { compile: (name, code) => compile(context, name, code), onError: handler => { state.onError = handler; }, onConsole: target => { state.console = target; }, + send: request => send(state, request), })); } finally { active = null; + + // Requests still waiting when the scripts end (one failed meanwhile) get no answer: TermRest cancels them. + for (const id of state.sends) { + const resolve = answers.get(id); + answers.delete(id); + if (resolve !== undefined) resolve({ error: 'The scripts finished before the request was answered.' }); + } } } @@ -105,11 +115,34 @@ function uncaught(error) { let queue = Promise.resolve(); let partial = []; + let sendCount = 0; + const answers = new Map(); // what waits for TermRest's answer to a request that scripts sent, by its id // Halves of surrogate pairs (a script's substring of an emoji) are not text: JSON.stringify writes them as escapes // (\ud83d), which JSON readers may refuse. They become U+FFFD; whole pairs are written as they are. + function marked(text) { + return MARKER + text.replace(/\\(\\|ud[89a-f][0-9a-f]{2})/g, (escape, what) => what === '\\' ? escape : '\\ufffd') + '\n'; + } + function reply(text) { - process.stdout.write(MARKER + text.replace(/\\(\\|ud[89a-f][0-9a-f]{2})/g, (escape, what) => what === '\\' ? escape : '\\ufffd') + '\n'); + process.stdout.write(marked(text)); + } + + // A request that scripts send goes through TermRest (its certificates, proxy and settings): a line asks for it, and + // TermRest answers with a line of input of its own, {"sent": …}, while the scripts run (see receive). + function send(state, request) { + return new Promise(resolve => { + if (active !== state) { + resolve({ error: 'The scripts already finished: TermRest sends no more requests for them.' }); + return; + } + + const id = ++sendCount; + const line = marked(JSON.stringify({ send: { id, request } })); + answers.set(id, resolve); + state.sends.push(id); + process.stdout.write(line); + }); } function receive(chunk) { @@ -119,7 +152,12 @@ function receive(chunk) { chunk = chunk.slice(index + 1); const line = partial.join(''); partial = []; - if (line.trim().length > 0) { + if (line.startsWith('{"sent":')) { + const answer = JSON.parse(line).sent; + const resolve = answers.get(answer.id); + answers.delete(answer.id); + if (resolve !== undefined) resolve(answer); + } else if (line.trim().length > 0) { queue = queue.then(() => run(line)).then(reply, error => reply(JSON.stringify({ fatal: error && error.stack ? String(error.stack) : String(error) }))); } } @@ -743,7 +781,7 @@ function makeResponse(data) { return result; } - // ----- pm.sendRequest: the runtime's own fetch --------------------------------------------------- + // ----- pm.sendRequest: sent by TermRest, with its certificates, proxy and settings --------------------- const list = value => Array.isArray(value) ? value : value !== null && typeof value === 'object' && Array.isArray(value.members) ? value.members : []; @@ -767,43 +805,32 @@ function headerPairs(source) { return pairs; } + // As Postman's pm.sendRequest takes it (a URL, or { url, method, header, body, auth }); TermRest reads the rest. Its + // {{variables}} are sent as written, as in Postman: pm.variables.replaceIn replaces them. async function send(options) { if (typeof options === 'string' || options instanceof Url) options = { url: String(options) }; options = options || {}; - const target = options.url !== null && typeof options.url === 'object' && !(options.url instanceof Url) && options.url.raw !== undefined - ? String(options.url.raw) - : String(options.url); - const method = String(options.method || 'GET').toUpperCase(); - const headers = headerPairs(options.header !== undefined ? options.header : options.headers); - const hasHeader = name => headers.some(([key]) => key.toLowerCase() === name); - let body; - const data = options.body; - if (typeof data === 'string') { - body = data; - } else if (data !== null && data !== undefined && typeof data === 'object') { - const mode = data.mode || (data.raw !== undefined ? 'raw' : undefined); - if (mode === 'raw') { - body = typeof data.raw === 'string' ? data.raw : stringify(data.raw); - } else if (mode === 'urlencoded') { - body = list(data.urlencoded).filter(item => item && !item.disabled) - .map(item => encodeURIComponent(item.key) + '=' + encodeURIComponent(item.value === undefined || item.value === null ? '' : item.value)).join('&'); - if (!hasHeader('content-type')) headers.push(['Content-Type', 'application/x-www-form-urlencoded']); - } else if (mode === 'formdata') { - body = new host.FormData(); - for (const item of list(data.formdata)) if (item && !item.disabled) body.append(String(item.key), item.value === undefined || item.value === null ? '' : String(item.value)); - } else if (mode === 'graphql') { - body = stringify(data.graphql || {}); - if (!hasHeader('content-type')) headers.push(['Content-Type', 'application/json']); + const url = options.url instanceof Url ? String(options.url) : options.url; + let body = options.body; + if (body !== null && typeof body === 'object' && !Array.isArray(body)) { + body = Object.assign({}, body); + for (const key of ['urlencoded', 'formdata']) { + const fields = body[key]; + if (fields !== null && typeof fields === 'object' && !Array.isArray(fields) && Array.isArray(fields.members)) body[key] = fields.members; } } - const started = Date.now(); - const answer = await host.fetch(target, { method, headers, body: method === 'GET' || method === 'HEAD' ? undefined : body, redirect: 'follow' }); - const bytes = host.Buffer.from(await answer.arrayBuffer()); - const pairs = []; - answer.headers.forEach((value, key) => { if (key !== 'set-cookie') pairs.push([key, value]); }); - for (const cookie of typeof answer.headers.getSetCookie === 'function' ? answer.headers.getSetCookie() : []) pairs.push(['set-cookie', cookie]); - return makeResponse({ status: answer.status, reason: answer.statusText, headers: pairs, time: Date.now() - started, size: bytes.length, base64: bytes.toString('base64') }); + const request = { + url: url !== null && typeof url === 'object' ? url : url === undefined || url === null ? '' : String(url), + method: options.method === undefined || options.method === null ? 'GET' : String(options.method), + header: headerPairs(options.header !== undefined ? options.header : options.headers).map(([key, value]) => ({ key, value })), + body, + auth: options.auth, + }; + const answer = await host.send(request); + if (answer.log) log(answer.log); + if (answer.error !== undefined) throw new Error(answer.error); + return makeResponse(answer.response); } function sendRequest(options, callback) { diff --git a/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs b/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs index 86c495b..3fb9076 100644 --- a/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs +++ b/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs @@ -45,6 +45,9 @@ internal static class PowerShellWorkerCode [System.Text.UTF8Encoding]::new($false)) $TrMarker = [string][char]0x1E + 'TR ' + # Requests that scripts send ($tr.SendRequest) go out as a line after the marker; TermRest answers each with a line of input. + $TrSends = @{ Sending = $false; Sent = 0; In = $Reader; Out = $TrOut; Marker = $TrMarker } + # What scripts write to the console ([Console]::WriteLine, Out-Host…), kept until the running script's output takes it # (Receive-TrConsole): a .NET writer of its own, locked, as a PowerShell class's methods run only in this runspace, and a # write from another one (ForEach-Object -Parallel, a thread job) would wait for it forever. Up to 4 million characters @@ -675,6 +678,13 @@ class Tr { [TrResponse] $Response [TrInfo] $Info hidden [System.Collections.Generic.List[object]] $Tests = [System.Collections.Generic.List[object]]::new() + hidden [hashtable] $Sends + + # Sends a request through TermRest, with its certificates, proxy and settings, and returns its response (as $tr.Response + # has it); throws when it can't be sent. A URL, or as Postman's pm.sendRequest takes it: @{ url; method; header; body; + # auth }, where header may be a hashtable of names to values, and body text (raw), JSON (a hashtable without mode) or + # @{ mode = 'raw'; raw = … }. Its {{variables}} are sent as written: $tr.Variables.ReplaceIn replaces them. + [TrResponse] SendRequest([object] $request) { return Send-TrRequest $request $this.Sends } # Records a test, which fails when its script block throws ($tr.Assert, $tr.AssertEqual, throw…). [void] Test([string] $name, [scriptblock] $test) { @@ -833,6 +843,26 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { $Items.Dropped += $dropped } + # $tr.SendRequest: asks TermRest to send the request (a line of output) and reads its answer (a line of input). + function Send-TrRequest([object] $Request, [hashtable] $Sends) { + if (-not $Sends.Sending) { throw [System.InvalidOperationException]::new('The scripts already finished: TermRest sends no more requests for them.') } + $Sends.Sent++ + $json = ConvertTo-Json -InputObject $Request -Depth 20 -Compress + $Sends.Out.Write($Sends.Marker + '{"send":{"id":' + $Sends.Sent + ',"request":' + $json + '}}' + "`n") + $Sends.Out.Flush() + $line = $Sends.In.ReadLine() + $answer = $null + if ($null -ne $line) { + $document = [System.Text.Json.JsonDocument]::Parse($line) + try { $answer = (ConvertFrom-TrJson $document.RootElement)['sent'] } finally { $document.Dispose() } + } + + if ($null -eq $answer) { $answer = @{ error = 'TermRest did not answer.' } } + if ($answer['log']) { [Console]::WriteLine([string] $answer['log']) } + if ($null -ne $answer['error']) { throw [System.Net.Http.HttpRequestException]::new([string] $answer['error']) } + return [TrResponse]::new($answer['response']) + } + function Invoke-TrMessage([string] $Line) { $document = [System.Text.Json.JsonDocument]::Parse($Line) try { @@ -878,6 +908,7 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { $tr.Request = [TrRequest]::new($message['request'], $phase -eq 'prerequest') if ($null -ne $message['response']) { $tr.Response = [TrResponse]::new($message['response']) } $tr.Info = $info + $tr.Sends = $TrSends $logs = [System.Collections.Generic.List[object]]::new() $dropped = 0 $failure = $null @@ -978,6 +1009,7 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { while ($true) { $line = $Reader.ReadLine() if ($null -eq $line) { break } + $TrSends.Sending = $true try { $reply = Invoke-TrMessage $line } @@ -985,6 +1017,8 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { $reply = @{ fatal = ($_ | Out-String) + $_.ScriptStackTrace } } + $TrSends.Sending = $false + $TrOut.Write($TrMarker + (ConvertTo-Json -InputObject $reply -Depth 10 -Compress) + "`n") $TrOut.Flush() } diff --git a/src/TermRest.Core/Scripting/PythonWorkerCode.cs b/src/TermRest.Core/Scripting/PythonWorkerCode.cs index d4f3719..05dc5bd 100644 --- a/src/TermRest.Core/Scripting/PythonWorkerCode.cs +++ b/src/TermRest.Core/Scripting/PythonWorkerCode.cs @@ -6,7 +6,8 @@ namespace TermRest.Core.Scripting; /// The Python side of . No file is written: the command line (-c) holds a short bootstrap /// () that reads the worker's code, hex-encoded, from the first line of input () /// and runs it. It reads one JSON message per line, runs the scripts in it with the tr object, and writes one JSON -/// line back. Whatever scripts print is captured, so it cannot corrupt the protocol. +/// line back. Whatever scripts print is captured, so it cannot corrupt the protocol. A request a script sends +/// (tr.send_request) goes out as a line of its own, and its answer comes in as a line of input. /// internal static class PythonWorkerCode { @@ -30,7 +31,7 @@ import sys # With -c, Python looks for modules in the current folder (the workspace) first. The worker's own modules come from # Python itself (a types.py in the workspace must not replace them); the scripts then import the workspace's. _workspace = sys.path.pop(0) if sys.path and sys.path[0] == "" else None - import base64, datetime, decimal, io, json, linecache, os, re, secrets, traceback, types, uuid + import base64, datetime, decimal, io, json, linecache, os, re, secrets, threading, traceback, types, uuid if _workspace is not None: sys.path.insert(0, _workspace) @@ -380,6 +381,42 @@ def __repr__(self): return f"<{self.status} {self.reason}>" + _send_lock = threading.Lock() + _sending = False # while a message's scripts run: the requests they send go through TermRest then + _sent = 0 + + + def _json_default(value): + if isinstance(value, (bytes, bytearray)): + return bytes(value).decode("utf-8", "replace") + if isinstance(value, Headers): + return value.items() + return _text(value) + + + def _send_request(request, **fields): + # tr.send_request: a request that TermRest sends, with its certificates, proxy and settings. As Postman's pm.sendRequest + # takes it: a URL, or a dict with url, method, header (or headers), body and auth; fields given by name are added. Its + # {{variables}} are sent as written (tr.variables.replace_in replaces them). One at a time: TermRest answers each with a + # line of input, which only the thread that asked reads. + global _sent + data = {"url": request} if isinstance(request, str) else dict(request or {}) + data.update(fields) + with _send_lock: + if not _sending: + raise RuntimeError("the scripts already finished: TermRest sends no more requests for them") + _sent += 1 + _out.write(json.dumps({"send": {"id": _sent, "request": data}}, default=_json_default, separators=(",", ":")) + "\n") + _out.flush() + line = _in.readline() + answer = (json.loads(line) if line else {}).get("sent") or {"error": "TermRest did not answer"} + if answer.get("log"): + _capture.write(answer["log"] + "\n") + if "error" in answer: + raise ConnectionError(answer["error"]) + return Response(answer.get("response") or {}) + + def _failure(error): message = _message(error) if isinstance(error, AssertionError): @@ -452,6 +489,7 @@ def _run(message): request=request, response=Response(message["response"]) if message.get("response") else None, info=info, + send_request=_send_request, ) tr.test = _tests(tests, info) error = None @@ -502,10 +540,13 @@ elif isinstance(body, (dict, list, tuple, bool)): for _line in _in: + _sending = True try: _result = _run(json.loads(_line)) except Exception as _error: _result = {"fatal": "".join(traceback.format_exception(type(_error), _error, _error.__traceback__))} + with _send_lock: # after a request a thread still waits for: its answer comes before the next message + _sending = False _out.write(json.dumps(_result) + "\n") _out.flush() """; diff --git a/src/TermRest.Core/Scripting/ScriptRequest.cs b/src/TermRest.Core/Scripting/ScriptRequest.cs new file mode 100644 index 0000000..53064ce --- /dev/null +++ b/src/TermRest.Core/Scripting/ScriptRequest.cs @@ -0,0 +1,159 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using TermRest.Core.Model; +using TermRest.Core.Postman; + +namespace TermRest.Core.Scripting; + +/// +/// A request that a script sends through TermRest (pm.sendRequest, tr.send_request, tr.SendRequest, $tr.SendRequest), as +/// Postman's pm.sendRequest takes it: a URL, or an object with url, method, header, body and +/// auth. What other languages write naturally works too: headers (header or headers) as a map of names +/// to values or as [name, value] pairs, form fields as a map, and a body as text (raw) or as any other JSON without a +/// mode (sent as JSON). +/// +internal static class ScriptRequest +{ + private static readonly JsonSerializerOptions Relaxed = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + private static readonly string[] BodyKeys = ["raw", "urlencoded", "formdata", "file", "graphql"]; + private static readonly string[] FieldKeys = ["urlencoded", "formdata"]; + + public static HttpRequestSpec Read(JsonNode? request) + { + var spec = new HttpRequestSpec(); + PostmanRequestMapper.ReadRequest(ToPostman(request), spec, PostmanSchemaVersion.V21); + return spec; + } + + private static JsonNode ToPostman(JsonNode? request) + { + if (request is not JsonObject source) + { + return JsonValue.Create(Text(request) ?? ""); + } + + var result = new JsonObject + { + ["method"] = Text(source["method"]) is { Length: > 0 } method ? method : "GET", + ["url"] = source["url"] is JsonObject url ? url.DeepClone() : JsonValue.Create(Text(source["url"]) ?? ""), + ["header"] = Entries(source["header"] ?? source["headers"]), + }; + if (source["body"] is { } body) + { + result["body"] = Body(body); + } + + if (source["auth"] is JsonObject auth) + { + result["auth"] = auth.DeepClone(); + } + + return result; + } + + /// Postman's key/value entries, from entries, [name, value] pairs, "Name: value" lines, or a map. + private static JsonNode Entries(JsonNode? node) + { + switch (node) + { + case JsonObject map: + return new JsonArray([.. map.Select(pair => (JsonNode?)Entry(pair.Key, pair.Value))]); + case JsonArray items: + var entries = new JsonArray(); + foreach (var item in items) + { + switch (item) + { + case JsonObject entry: + entries.Add(entry.DeepClone()); + break; + case JsonArray { Count: 2 } pair: + entries.Add((JsonNode)Entry(Text(pair[0]) ?? "", pair[1])); + break; + case JsonValue line when Text(line) is { } text && text.IndexOf(':', StringComparison.Ordinal) is > 0 and var colon: + entries.Add((JsonNode)Entry(text[..colon].Trim(), JsonValue.Create(text[(colon + 1)..].Trim()))); + break; + } + } + + return entries; + case JsonValue lines: + return lines.DeepClone(); // "Name: value" lines, which Postman's reader takes + default: + return new JsonArray(); + } + } + + private static JsonObject Entry(string key, JsonNode? value) => new() { ["key"] = key, ["value"] = Text(value) ?? "" }; + + private static JsonObject Body(JsonNode body) + { + if (body is JsonObject postman && IsPostmanBody(postman)) + { + var result = (JsonObject)postman.DeepClone(); + result["mode"] = Text(result["mode"]) ?? BodyKeys.First(result.ContainsKey); + if (result["raw"] is { } raw && raw.GetValueKind() != JsonValueKind.String) + { + result["raw"] = raw.ToJsonString(Relaxed); + if (raw is not JsonValue) + { + Language(result, "json"); + } + } + + foreach (var key in FieldKeys) + { + if (result[key] is JsonObject map) + { + result[key] = Entries(map); + } + } + + if (result["graphql"] is JsonObject graphql && graphql["variables"] is JsonObject or JsonArray) + { + graphql["variables"] = graphql["variables"]!.ToJsonString(Relaxed); + } + + return result; + } + + if (body is JsonValue value && value.GetValueKind() == JsonValueKind.String) + { + return new JsonObject { ["mode"] = "raw", ["raw"] = value.GetValue() }; + } + + // Any other JSON (a Python dict, a hashtable, an object, a number …) is sent as JSON. + var json = new JsonObject { ["mode"] = "raw", ["raw"] = body.ToJsonString(Relaxed) }; + Language(json, "json"); + return json; + } + + /// A Postman body: one with a mode, or with no other members than a Postman body has ({"raw": "…"}). + private static bool IsPostmanBody(JsonObject body) => + body.ContainsKey("mode") + || (body.Any(member => BodyKeys.Contains(member.Key)) && body.All(member => BodyKeys.Contains(member.Key) || member.Key is "options" or "disabled")); + + private static void Language(JsonObject body, string language) + { + if (body["options"] is not JsonObject options) + { + body["options"] = options = new JsonObject(); + } + + if (options["raw"] is not JsonObject raw) + { + options["raw"] = raw = new JsonObject(); + } + + raw["language"] ??= language; + } + + /// A value as text: a string as it is, null as null, other JSON as JSON (true, 42, {"a":1}). + private static string? Text(JsonNode? node) => node switch + { + null => null, + JsonValue value when value.GetValueKind() == JsonValueKind.String => value.GetValue(), + _ => node.ToJsonString(Relaxed), + }; +} diff --git a/src/TermRest.Core/Scripting/ScriptWorker.cs b/src/TermRest.Core/Scripting/ScriptWorker.cs index 2e958ca..f6a6cb0 100644 --- a/src/TermRest.Core/Scripting/ScriptWorker.cs +++ b/src/TermRest.Core/Scripting/ScriptWorker.cs @@ -109,9 +109,15 @@ public static ScriptWorker For(string language, string runtime, string workingDi /// Scripts that may run next, in the same language (C#: the collection's, built into the same program so that its /// other requests need no new build). /// + /// + /// Sends a request that the scripts send through TermRest (pm.sendRequest, tr.send_request …), given as they gave it, and + /// returns what they get: {"response": …} or {"error": "…"}, with a "log" line for their output. + /// Requests are sent while the scripts wait for them, several at a time when they send several; those still running + /// when the scripts end are cancelled. Null: the scripts get an error. + /// /// The runtime could not start, stopped, or did not answer within . public async Task RunAsync(JsonObject message, TimeSpan timeout, IEnumerable? related = null, - CancellationToken cancellationToken = default) + Func>? send = null, CancellationToken cancellationToken = default) { await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); try @@ -133,7 +139,17 @@ public async Task RunAsync(JsonObject message, TimeSpan timeout, IEn } await WriteAsync(process.StandardInput.BaseStream, message, limit.Token).ConfigureAwait(false); - var line = await ReadReplyAsync(process, limit.Token).ConfigureAwait(false); + var sends = new ScriptSends(process.StandardInput.BaseStream, send, limit.Token); + string? line = null; + try + { + line = await ReadReplyAsync(process, sends, limit.Token).ConfigureAwait(false); + } + finally + { + await sends.EndAsync(answered: line is not null).ConfigureAwait(false); + } + if (line is null) { ObjectDisposedException.ThrowIf(_disposed, this); // stopped while the scripts ran @@ -314,24 +330,35 @@ private static async Task WriteAsync(Utf8JsonWriter writer, JsonNode? node, Canc } } - /// The reply line; with a reply marker, other lines (output of programs that scripts started) are skipped. - private async Task ReadReplyAsync(Process process, CancellationToken cancellationToken) + /// + /// The reply line; with a reply marker, other lines (output of programs that scripts started) are skipped. Lines that + /// send a request (see ) start it, and reading goes on. + /// + private async Task ReadReplyAsync(Process process, ScriptSends sends, CancellationToken cancellationToken) { while (await process.StandardOutput.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) { - if (_replyMarker is null) + var payload = line; + if (_replyMarker is not null) { - return line; + var at = line.IndexOf(_replyMarker, StringComparison.Ordinal); + if (at < 0) + { + Remember(line); + Remember("\n"); + continue; + } + + payload = line[(at + _replyMarker.Length)..]; } - var at = line.IndexOf(_replyMarker, StringComparison.Ordinal); - if (at >= 0) + if (!payload.StartsWith(ScriptSends.Prefix, StringComparison.Ordinal)) { - return line[(at + _replyMarker.Length)..]; + return payload; } - Remember(line); - Remember("\n"); + sends.Start(JsonNode.Parse(WellFormed(payload))?["send"] as JsonObject + ?? throw new JsonException($"{Name} sent a request that is not an object.")); } return null; @@ -547,6 +574,129 @@ private void Stop(bool kill) } } + /// + /// The requests a run's scripts send through TermRest. The runtime writes a line {"send":{"id":n,"request":…}} (after + /// its reply marker) and waits; each is sent at once, while the reading goes on, and answered with a line of input + /// {"sent":{"id":n,"response"|"error":…,"log":"…"}}, under a lock, as several may end together. None is answered + /// once the scripts' reply came: it would be read as the next message. + /// + private sealed class ScriptSends(Stream input, Func>? send, CancellationToken cancellationToken) + : IDisposable + { + public const string Prefix = "{\"send\":"; + + /// How many are sent at once, at most: a script that starts thousands waits for its turn, without as many connections. + private const int AtOnce = 6; + + private readonly SemaphoreSlim _write = new(1, 1); + private readonly SemaphoreSlim _slots = new(AtOnce, AtOnce); + private readonly CancellationTokenSource _cancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + private readonly List _running = []; + private volatile bool _ended; + + public void Start(JsonObject request) + { + _running.RemoveAll(task => task.IsCompleted); + _running.Add(AnswerAsync(request)); + } + + /// + /// Whether the scripts replied: requests still running are cancelled once the answer being written is whole. Else the + /// runtime is stopped: they are cancelled at once and not waited for (a write to a runtime that reads no more never ends). + /// + public async Task EndAsync(bool answered) + { + if (_running.Count == 0) + { + Dispose(); + return; + } + + if (answered) + { + await _write.WaitAsync(CancellationToken.None).ConfigureAwait(false); + _ended = true; + _write.Release(); + } + + _ended = true; + await _cancel.CancelAsync().ConfigureAwait(false); + if (answered) + { + await Task.WhenAll(_running).ConfigureAwait(false); // they end at once: they catch everything + Dispose(); + } + } + + /// Once no request runs: those of a stopped runtime may still (they end soon, and are left to the collector). + public void Dispose() + { + _cancel.Dispose(); + _write.Dispose(); + _slots.Dispose(); + } + + private async Task AnswerAsync(JsonObject request) + { + await Task.Yield(); // the reading goes on meanwhile + var id = request["id"]?.DeepClone(); + JsonObject answer; + try + { + if (send is null) + { + answer = new JsonObject { ["error"] = "TermRest sends no requests for these scripts." }; + } + else + { + await _slots.WaitAsync(_cancel.Token).ConfigureAwait(false); + try + { + answer = await send(request["request"], _cancel.Token).ConfigureAwait(false); + } + finally + { + _slots.Release(); + } + } + } + catch (OperationCanceledException) when (_cancel.IsCancellationRequested) + { + return; // the scripts ended, or were stopped + } + catch (Exception ex) + { + answer = new JsonObject { ["error"] = ex.Message }; + } + + answer["id"] = id; + try + { + await _write.WaitAsync(_cancel.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + + try + { + if (!_ended) + { + await WriteAsync(input, new JsonObject { ["sent"] = answer }, _cancel.Token).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException) + { + // the runtime stopped, or the scripts were: the run says so + } + finally + { + _write.Release(); + } + } + } + // A JSON escape: a surrogate pair, a lone half of one (group 1), or any other (\\, \", \u00e9…), so that the halves are // found in order (\\ud83d is a backslash, then text). [GeneratedRegex(@"\\(?:u(?:d[89ab][0-9a-f]{2}\\ud[c-f][0-9a-f]{2}|(d[89a-f][0-9a-f]{2}))|[\s\S])", RegexOptions.IgnoreCase)] diff --git a/src/TermRest.Core/Variables/VariableResolver.cs b/src/TermRest.Core/Variables/VariableResolver.cs index e23f387..7f96bc4 100644 --- a/src/TermRest.Core/Variables/VariableResolver.cs +++ b/src/TermRest.Core/Variables/VariableResolver.cs @@ -88,6 +88,7 @@ public sealed partial class VariableResolver private readonly IReadOnlyList _scopes; private readonly TimeProvider _time; + private readonly bool _literal; public VariableResolver(IEnumerable scopesHighestPrecedenceFirst, TimeProvider? time = null) { @@ -95,8 +96,17 @@ public VariableResolver(IEnumerable scopesHighestPrecedenceFirst _time = time ?? TimeProvider.System; } + private VariableResolver(bool literal) + : this([]) => _literal = literal; + public static VariableResolver Empty { get; } = new([]); + /// + /// Replaces nothing, not even dynamic variables ({{$guid}}): what a request that a script sends gets, as in Postman, whose + /// pm.sendRequest sends {{references}} as written (scripts replace them with replaceIn). They count as unresolved. + /// + public static VariableResolver Literal { get; } = new(literal: true); + public IReadOnlyList Scopes => _scopes; [GeneratedRegex(@"\{\{([^{}]+)\}\}", RegexOptions.CultureInvariant)] @@ -138,6 +148,19 @@ public string Resolve(string? text, ISet? unresolved = null) return text ?? ""; } + if (_literal) + { + if (unresolved is not null) + { + foreach (var name in FindReferences(text)) + { + unresolved.Add(name); + } + } + + return text; + } + var limit = (long)text.Length + MaxGrowth; var current = text; var full = false; @@ -200,6 +223,12 @@ public string Resolve(string? text, ISet? unresolved = null) /// public bool TryResolve(string name, out string? value, out string? scopeName) { + if (_literal) + { + (value, scopeName) = (null, null); + return false; + } + foreach (var scope in _scopes) { if (scope.TryGetValue(name, out value)) diff --git a/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs b/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs index 73cc3f4..8a1b680 100644 --- a/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs +++ b/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs @@ -377,7 +377,8 @@ public ScriptPlan PlanScripts(PostmanCollection collection, RequestNode? node, S { // Off the caller's thread: starting a runtime (or building C#) takes a moment, and the UI must stay responsive. var related = language == ScriptLanguage.CSharp ? CSharpScriptsOf(collection) : null; - reply = await Task.Run(() => worker.RunAsync(message, ScriptTimeout, related, cancellationToken), cancellationToken).ConfigureAwait(true); + reply = await Task.Run(() => worker.RunAsync(message, ScriptTimeout, related, + (sent, token) => SendForScriptAsync(sent, environment, collection, language, token), cancellationToken), cancellationToken).ConfigureAwait(true); } catch (ScriptException ex) { @@ -535,6 +536,74 @@ private static void ApplyRequestEdits(JsonObject edited, JsonObject original, Ht } } + /// + /// Sends a request that a script sends (pm.sendRequest, tr.send_request …; see ) as TermRest + /// sends its own: with the workspace's client certificates, CA bundle, proxy (and its sign-in), timeout and limits, and the + /// session's cookies. As in Postman, its {{variables}} are sent as written (scripts replace them with replaceIn), and + /// its auth is its own: it inherits none. It is recorded with the requests when they are, not kept in the history. The + /// script gets the response, as its language's response object has it, or the error, and a line for its output. + /// Called off the caller's thread, while the scripts run. + /// + private async Task SendForScriptAsync(JsonNode? request, PostmanEnvironment? environment, PostmanCollection collection, + string language, CancellationToken cancellationToken) + { + var spec = ScriptRequest.Read(request); + var preparer = new RequestPreparer(VariableResolver.Literal, Certificates, CreateDefaults()); + var prepared = preparer.Prepare(spec, spec.Auth is { Type: not "inherit" } own ? own : null, collection.BaseDirectory); + var resolver = CreateResolver(environment, collection, null); + prepared.AddSecretValues(SecretVariableValues(environment, collection, resolver)); + prepared.AddSensitiveValues(VariablesNamedLikeSecrets(environment, collection, resolver, null)); + await AuthorizeAsync(prepared, cancellationToken).ConfigureAwait(false); + var sent = $"{prepared.Method} {Shown(prepared)} →"; + var note = Unreplaced(prepared, language); + if (prepared.Errors.Count > 0) + { + var problem = string.Join(" ", prepared.Errors) + note; + return new JsonObject { ["error"] = problem, ["log"] = $"{sent} not sent: {problem}" }; + } + + var exchange = await Executor.SendAsync(prepared, cancellationToken).ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + Recorder?.Record(exchange, environment?.Name); + if (exchange.Response is not { } response) + { + var problem = (exchange.ErrorMessage ?? "No response.") + note; + return new JsonObject { ["error"] = problem, ["log"] = $"{sent} failed: {problem}" }; + } + + var cut = response.BodyTruncated ? ", body cut at the size limit" : ""; + return new JsonObject + { + ["response"] = ResponseReceived(exchange), + ["log"] = $"{sent} {response.StatusCode} {response.ReasonPhrase} ({exchange.Timing.Total?.TotalMilliseconds ?? 0:0} ms{cut}){note}", + }; + } + + /// Where a request went, for a script's output: without the query, which may hold a key, nor a password. + private static string Shown(PreparedRequest request) => request.Uri is { } uri + ? $"{uri.Scheme}://{uri.Authority}{uri.AbsolutePath}{(uri.Query.Length > 1 ? "?…" : "")}" + : PostmanUrl.MaskCredentials(request.Url); + + /// For a request that a script sent with {{references}} in it: that they went as written, and what replaces them. + private static string Unreplaced(PreparedRequest request, string language) + { + var names = request.UnresolvedVariables; + if (names.Count == 0) + { + return ""; + } + + var replaceIn = language switch + { + ScriptLanguage.Python => "tr.variables.replace_in(…)", + ScriptLanguage.CSharp => "tr.Variables.ReplaceIn(…)", + ScriptLanguage.PowerShell => "$tr.Variables.ReplaceIn(…)", + _ => "pm.variables.replaceIn(…)", + }; + var shown = string.Join(", ", names.Take(3).Select(name => "{{" + name + "}}")) + (names.Count > 3 ? ", …" : ""); + return $" ({shown} sent as written: {replaceIn} replaces variables)"; + } + /// The request as pre-request scripts see it: as written, with {{variables}} not yet replaced. private static JsonObject RequestToSend(HttpRequestSpec spec, string? name) => new() { diff --git a/src/TermRest.Tui/MainWindow.cs b/src/TermRest.Tui/MainWindow.cs index 867a867..bc674e5 100644 --- a/src/TermRest.Tui/MainWindow.cs +++ b/src/TermRest.Tui/MainWindow.cs @@ -1214,6 +1214,8 @@ the one its Scripts tab chooses (Run in), or with Auto the first language of you tr.iteration_data the run's current row of its data file (termrest run -d users.csv): .get(name) …. tr.request .method, .url, .headers (.get .set .add .remove), .body: change them before sending. tr.response .status (or .code), .reason, .headers, .time (ms), .size, .text(), .json(), .content (bytes). + tr.send_request(url or {"url": …, "method": …, "headers": {…}, "body": …}, method="POST", …) + sends a request through TermRest, with its certificates and proxy, and returns its response. tr.test(name, fn) records a test that fails when fn raises (assert …); also @tr.test("name") on a function. tr.info .phase ("prerequest" or "test"), .script, .request_name, .collection, .environment, .iteration, .iteration_count. @@ -1230,6 +1232,7 @@ .get .set .unset .has .toObject .replaceIn pm.request .method, .url (.query, .toString()), .headers (.add .upsert .remove .get), .body.raw pm.response .code, .status, .headers, .responseTime, .json(), .text(), .to.have.status(200), .to.be.ok … pm.test(name, fn), pm.expect(value).to.equal(…) (chai's assertions), pm.sendRequest(…), pm.info, console.log + pm.sendRequest goes through TermRest, with its certificates and proxy; {{variables}} in it are sent as written. The old API works too: tests["name"] = …, postman.setEnvironmentVariable(…), responseBody, responseCode. require() loads Node.js modules and the packages installed in the workspace (npm install lodash crypto-js …); _, CryptoJS, cheerio and tv4 load those packages when first used, as Postman's globals. @@ -1251,6 +1254,7 @@ stops it. tr.IterationData the run's current row of its data file, as text: .Get(name) …. tr.Request .Method, .Url, .Headers (.Get .Set .Add .Remove, ["name"]), .Body: change them before sending. tr.Response .Status (or .Code), .Reason, .Headers, .Time (ms), .Size, .Text(), .Json() (a JsonNode), .Content. + tr.SendRequest(url or new { url, method, header, body }), await tr.SendRequestAsync(…): through TermRest. tr.Test(name, () => …) (async too), tr.Assert(condition), tr.AssertEqual(expected, actual), tr.Info. Console.WriteLine(…) output goes to the Scripts tab. @@ -1267,6 +1271,7 @@ tr.Response .Status (or .Code), .Reason, .Headers, .Time (ms), .Size, .Text() $tr.Request .Method, .Url, .Headers (.Get .Set .Add .Remove .Items()), .Body: change them before sending. $tr.Response .Status (or .Code), .Reason, .Headers, .Time (ms), .Size, .Text(), .Json() (ConvertFrom-Json), .Content(). + $tr.SendRequest(url or @{ url = …; method = …; header = @{…}; body = … }): through TermRest. $tr.Test(name, { … }), $tr.Assert(condition), $tr.AssertEqual(expected, actual), $tr.Info. Output, Write-Host and warnings go to the Scripts tab (output inside $tr.Test blocks is dropped: use Write-Host there). Errors stop the script ($ErrorActionPreference is Stop). Your profile is not loaded; modules load as diff --git a/tests/TermRest.Core.Tests/CSharpScriptingTests.cs b/tests/TermRest.Core.Tests/CSharpScriptingTests.cs index 5760da7..286e928 100644 --- a/tests/TermRest.Core.Tests/CSharpScriptingTests.cs +++ b/tests/TermRest.Core.Tests/CSharpScriptingTests.cs @@ -434,9 +434,9 @@ public async Task Directives_of_another_script_of_the_collection_do_not_break_th JsonObject Message() => new() { ["phase"] = "test", ["scripts"] = new JsonArray(new JsonObject { ["name"] = "request", ["code"] = mine }) }; int Builds() => File.ReadLines(commands).Count(l => l.StartsWith("run ", StringComparison.Ordinal)); - var reply = await worker.RunAsync(Message(), TimeSpan.FromSeconds(30), collection, _ct); + var reply = await worker.RunAsync(Message(), TimeSpan.FromSeconds(30), collection, cancellationToken: _ct); var builds = Builds(); - var again = await worker.RunAsync(Message(), TimeSpan.FromSeconds(30), collection, _ct); + var again = await worker.RunAsync(Message(), TimeSpan.FromSeconds(30), collection, cancellationToken: _ct); Assert.Null(reply["error"]); Assert.Equal("ok", reply["tests"]![0]!["name"]!.GetValue()); diff --git a/tests/TermRest.Core.Tests/ScriptRequestTests.cs b/tests/TermRest.Core.Tests/ScriptRequestTests.cs new file mode 100644 index 0000000..ce86dd8 --- /dev/null +++ b/tests/TermRest.Core.Tests/ScriptRequestTests.cs @@ -0,0 +1,167 @@ +using TermRest.Core.Certificates; +using TermRest.Core.Model; +using TermRest.Core.Scripting; +using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Workspace; +using Xunit; + +namespace TermRest.Core.Tests; + +/// Requests that scripts send (pm.sendRequest, tr.send_request, tr.SendRequest, $tr.SendRequest) go through TermRest. +public sealed class ScriptRequestTests : IDisposable +{ + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + private readonly TestPki _pki = TestPki.Create(); + + public void Dispose() => _pki.Dispose(); + + public static TheoryData Languages => [ScriptLanguage.JavaScript, ScriptLanguage.Python, ScriptLanguage.CSharp, ScriptLanguage.PowerShell]; + + [Theory] + [MemberData(nameof(Languages))] + public async Task A_request_a_script_sends_goes_out_with_the_workspaces_client_certificate(string language) + { + var runtime = language switch + { + ScriptLanguage.JavaScript => TestJavaScript.Require(), + ScriptLanguage.Python => TestPython.Require(), + ScriptLanguage.CSharp => TestCSharp.Require(), + _ => TestPowerShell.Require(), + }; + await using var secure = await EchoServer.StartAsync(_pki.Server, requireClientCertificate: true); + await using var plain = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + workspace.Settings.CaBundle = _pki.CaPemPath; + workspace.Certificates.Entries.Add(new CertificateEntry + { + Name = "client", + Matches = [$"https://localhost:{secure.BaseUri.Port}/*"], + Pfx = new FileSource { Src = _pki.ClientPfxPath }, + Passphrase = TestPki.Passphrase, + }); + var collection = workspace.CreateCollection("API"); + collection.SetVariables([new KeyValueEntry { Key = "secure", Value = secure.Url("echo") }]); + + // A POST with a header and a JSON body, then one with a {{variable}} that is sent as written, which fails. + var script = language switch + { + ScriptLanguage.JavaScript => """ + const url = pm.collectionVariables.get('secure') + '?q=1'; + const [response, again] = await Promise.all([ + pm.sendRequest({ url, method: 'POST', header: { 'X-From': 'script' }, body: { mode: 'raw', raw: { n: 1 } } }), + pm.sendRequest(url), + ]); + const echo = response.json(); + pm.collectionVariables.set('thumb', echo.clientCertificateThumbprint); + pm.collectionVariables.set('body', echo.body); + pm.collectionVariables.set('from', echo.headers['x-from']); + pm.collectionVariables.set('again', again.json().method); + try { await pm.sendRequest('{{nothing}}/x'); } catch (error) { pm.collectionVariables.set('error', error.message); } + """, + ScriptLanguage.Python => """ + response = tr.send_request(tr.collection_variables.get("secure") + "?q=1", method="POST", headers={"X-From": "script"}, body={"n": 1}) + echo = response.json() + tr.collection_variables.set("thumb", echo["clientCertificateThumbprint"]) + tr.collection_variables.set("body", echo["body"]) + tr.collection_variables.set("from", echo["headers"]["x-from"]) + try: + tr.send_request("{{nothing}}/x") + except ConnectionError as error: + tr.collection_variables.set("error", str(error)) + """, + ScriptLanguage.CSharp => """ + var response = tr.SendRequest(new + { + url = tr.CollectionVariables.Get("secure") + "?q=1", + method = "POST", + header = new Dictionary { ["X-From"] = "script" }, + body = new { n = 1 }, + }); + var echo = response.Json(); + tr.CollectionVariables.Set("thumb", (string)echo["clientCertificateThumbprint"]); + tr.CollectionVariables.Set("body", (string)echo["body"]); + tr.CollectionVariables.Set("from", (string)echo["headers"]["x-from"]); + try { await tr.SendRequestAsync("{{nothing}}/x"); } catch (HttpRequestException error) { tr.CollectionVariables.Set("error", error.Message); } + """, + _ => """ + $response = $tr.SendRequest(@{ url = $tr.CollectionVariables.Get('secure') + '?q=1'; method = 'POST'; header = @{ 'X-From' = 'script' }; body = @{ n = 1 } }) + $echo = $response.Json() + $tr.CollectionVariables.Set('thumb', $echo.clientCertificateThumbprint) + $tr.CollectionVariables.Set('body', $echo.body) + $tr.CollectionVariables.Set('from', $echo.headers.'x-from') + try { $null = $tr.SendRequest('{{nothing}}/x') } catch [System.Net.Http.HttpRequestException] { $tr.CollectionVariables.Set('error', $_.Exception.Message) } + """, + }; + var request = collection.AddRequest(collection.RootNode, "Echo", new HttpRequestSpec { Url = plain.Url("echo"), Scripts = new ScriptSet(script, "", language) }); + using var runner = new RequestRunner(workspace); + runner.SetRuntime(language, runtime); + + var exchange = await runner.SendAsync(collection, request, request.ReadSpec(), null, _ct); + + var results = exchange.Scripts!; + Assert.True(results.Error is null, results.Describe()); + Assert.Equal(200, exchange.Response?.StatusCode); + var set = runner.Session.For(collection); + Assert.Equal(_pki.Client.Thumbprint, set["thumb"]); + Assert.Equal("""{"n":1}""", set["body"]); + Assert.Equal("script", set["from"]); + Assert.Equal("'http://{{nothing}}/x' is not a valid http(s) URL. ({{nothing}} sent as written: " + language switch + { + ScriptLanguage.Python => "tr.variables.replace_in(…)", + ScriptLanguage.CSharp => "tr.Variables.ReplaceIn(…)", + ScriptLanguage.PowerShell => "$tr.Variables.ReplaceIn(…)", + _ => "pm.variables.replaceIn(…)", + } + " replaces variables)", set["error"]); + var logs = results.Logs.Select(log => log.Text).ToList(); + Assert.Contains(logs, log => log.StartsWith($"POST https://localhost:{secure.BaseUri.Port}/echo?… → 200 OK (", StringComparison.Ordinal)); + Assert.Contains(logs, log => log.StartsWith("GET http://{{nothing}}/x → not sent: 'http://{{nothing}}/x' is not a valid", StringComparison.Ordinal)); + if (language == ScriptLanguage.JavaScript) + { + Assert.Equal("GET", set["again"]); + } + } + + [Fact] + public async Task A_request_still_running_when_the_scripts_end_is_cancelled_and_the_next_run_goes_on() + { + var node = TestJavaScript.Require(); + using var hold = new ManualResetEventSlim(); + await using var slow = await EchoServer.StartAsync(beforeEcho: () => hold.Wait(TimeSpan.FromSeconds(30))); + await using var fast = await EchoServer.StartAsync(); + try + { + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + collection.SetVariables([new KeyValueEntry { Key = "slow", Value = slow.Url("echo") }, new KeyValueEntry { Key = "fast", Value = fast.Url("echo") }]); + var failing = collection.AddRequest(collection.RootNode, "Failing", new HttpRequestSpec + { + Url = fast.Url("echo"), + Scripts = new ScriptSet("pm.sendRequest(pm.collectionVariables.get('slow'), () => {});\nthrow new Error('boom');", "", ScriptLanguage.JavaScript), + }); + var next = collection.AddRequest(collection.RootNode, "Next", new HttpRequestSpec + { + Url = fast.Url("echo"), + Scripts = new ScriptSet(""" + const response = await pm.sendRequest(pm.collectionVariables.get('fast') + '?n=2'); + pm.collectionVariables.set('n', response.json().query.n); + """, "", ScriptLanguage.JavaScript), + }); + using var runner = new RequestRunner(workspace); + runner.SetJavaScriptRuntime(node); + + var started = System.Diagnostics.Stopwatch.StartNew(); + var failed = await runner.SendAsync(collection, failing, failing.ReadSpec(), null, _ct); + Assert.Contains("boom", failed.Scripts!.Error?.Message, StringComparison.Ordinal); + Assert.True(started.Elapsed < TimeSpan.FromSeconds(20), $"{started.Elapsed}: the scripts waited for the request they left"); + + // The answer to the cancelled request never comes: the runtime reads the next message as one. + var exchange = await runner.SendAsync(collection, next, next.ReadSpec(), null, _ct); + Assert.True(exchange.Scripts!.Error is null, exchange.Scripts.Describe()); + Assert.Equal("2", runner.Session.For(collection)["n"]); + } + finally + { + hold.Set(); + } + } +} From da5e6efabc8e652adb65cb60cfe74c129b8971d3 Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Tue, 17 Nov 2026 23:40:34 -0700 Subject: [PATCH 06/11] Core, CLI and TUI: streaming responses (server-sent events, JSON lines) A response of server-sent events (text/event-stream) or JSON lines (application/x-ndjson, ndjson, jsonl, x-jsonlines, json-seq, stream+json) is read as it arrives, part by part, decoded on the way (gzip, deflate, br; a counting stream keeps the size received), within the maximum response size. A watcher set on the prepared request (IStreamWatcher) gets its head and each part, and can stop it: what arrived is then the response, as a whole one would be (ResponseSnapshot.Stopped, with a warning), so its post-response scripts run on it and it goes to the history and the recording. A request timeout that ends a stream keeps it the same way, and so does a connection that ends before the stream does; cancelling the request still discards it. The full-screen UI shows a stream while it arrives, four times a second at most and only when more came: its status, its headers, and the end of its body (a LiveResponse keeps the last 64 KB, not the stream). Esc, or Stop (the Send button meanwhile), ends it keeping what arrived. Once it ends, server-sent events get an Events tab, one row per event (type, id, the start of its data; Enter shows its data in full, JSON pretty-printed, to copy), read as the HTML standard reads them. An event keeps only where it is in the body (its id too), and the table reads its cells when they are drawn, so a long stream's events take little memory; a large body's events are read in the background. send prints a stream to standard output as it arrives (after its headers with -i), unless -o or --filter take it whole; the first Ctrl+C stops it, keeping what arrived, through a hook in TermRest's own signal handling (CliApp.Interrupt), and a second one cancels as before. run reads streams whole. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 8 +- src/TermRest.Cli/CliApp.cs | 21 +- src/TermRest.Cli/SendCommand.cs | 110 ++++++++- src/TermRest.Core/Http/HttpExchange.cs | 6 + src/TermRest.Core/Http/HttpExecutor.cs | 170 +++++++++++++- src/TermRest.Core/Http/PreparedRequest.cs | 6 + src/TermRest.Core/Http/ResponseStreams.cs | 214 ++++++++++++++++++ src/TermRest.Tui/MainWindow.cs | 66 +++++- src/TermRest.Tui/Views/LiveResponse.cs | 116 ++++++++++ src/TermRest.Tui/Views/RequestEditor.cs | 5 +- src/TermRest.Tui/Views/ResponseView.cs | 170 +++++++++++++- tests/TermRest.Cli.Tests/CommandLineTests.cs | 40 ++++ .../Infrastructure/TestServer.cs | 20 +- .../Infrastructure/EchoServer.cs | 38 ++++ tests/TermRest.Core.Tests/StreamingTests.cs | 142 ++++++++++++ tests/TermRest.Tui.Tests/MainWindowTests.cs | 65 +++++- 16 files changed, 1169 insertions(+), 28 deletions(-) create mode 100644 src/TermRest.Core/Http/ResponseStreams.cs create mode 100644 src/TermRest.Tui/Views/LiveResponse.cs create mode 100644 tests/TermRest.Core.Tests/StreamingTests.cs diff --git a/README.md b/README.md index 3ae9218..935d4ac 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ What it has: - **Scripts in Python, JavaScript, C# or PowerShell.** Pre-request and test scripts for collections, folders and requests, with variables, request changes and tests. JavaScript scripts use Postman's `pm` object, so Postman collections' scripts run too. Each language runs in the runtime you choose: your project's Python, Node.js or Bun, the .NET SDK, and PowerShell 7, with the packages and modules you installed (NuGet packages for C#). A script can have a version in each language (Postman's JavaScript next to a PowerShell one, say): each request runs one language only, the first of your order that has all its scripts, or the one it chooses. TermRest carries no script engine: a runtime starts for its first script and stops when idle. See [Scripts](#scripts). **Scripts are not sandboxed:** they run with your permissions, so turn them on only for collections you trust (see [Script safety](#script-safety)). - **Request history and cURL import.** Every request you send is kept per workspace, with credentials masked, ready to reopen, send again or save. Paste a curl command (for example from a browser's *Copy as cURL*) into the URL bar to import it. - **Find, filter and color responses.** Ctrl+F finds text in the response. A JSONPath query ([RFC 9535](https://www.rfc-editor.org/rfc/rfc9535)) filters a JSON body, in the UI and with `send --filter`. JSON, XML and HTML bodies are colored, request bodies too. +- **Streams as they arrive.** Server-sent events and JSON lines (LLM APIs, event feeds) are shown as they come, until you stop them (Esc, or Ctrl+C for `send`), which keeps what arrived as the response; server-sent events are then listed one a row. See [Streams](#streams). - **Recording.** Press Record (F12) and every request and response you send is recorded. On stop, TermRest asks where to save it as a HAR file (JSON, opens in browser dev tools). Credentials, cookies, tokens and secret variables are redacted, files sent with a request are recorded by path only, and a recording streams to a private temporary file instead of growing in memory. - **Large bodies from files.** Send a file as the body without loading it: it is streamed when the request is sent, and a JSON or XML file is checked first. - **Client certificates (mutual TLS)** are first-class: PEM (including encrypted keys and chains), PFX/PKCS#12, and OS certificate stores. That includes the Windows certificate store with non-exportable keys and the macOS keychain. Certificates bind to URL patterns via a Newman-compatible registry, and a TLS tab shows exactly what was negotiated and presented. @@ -137,9 +138,11 @@ A request that is not in a collection (a new one, an imported curl command, or o **Saved examples** (Postman's saved responses) are listed under their request in the tree, as `e.g. `. *Save as example* (on the response's status line, or *Request › Save response as example…*) saves the response shown as an example of its request: its status, its headers as the server sent them, its body as text (a binary body is left out, and a body over 1 MB asks first, as it goes into the collection file), and the request as the editor has it; a response opened from the history goes to the request it was sent from. Opening an example shows its request (method, URL, parameters, headers and body) in the request editor and its response in the response pane's place, both editable: the status code and reason, the body's language (with *Beautify* for JSON), the body and the headers. *Ctrl+S* saves them with the rest. An example is not sent; open its request to send it. Rename, duplicate or delete examples from the tree, as requests. In a v3 collection an example is a file of its own (see [Postman v3 (YAML) collections](#postman-v3-yaml-collections)), read only when its request is first expanded or opened. +**Streams.** A response of server-sent events (`text/event-stream`) or JSON lines (`application/x-ndjson`, `application/jsonl`, `application/json-seq`, `application/stream+json`) is shown as it arrives: its status, its headers, and the end of its body (the last 64 KB), followed as it grows, four times a second at most. **Esc**, or *Stop* (the Send button meanwhile), ends it and keeps what arrived as its response, as a whole one would be: its post-response scripts run on it, it goes to the history and the recording, and a warning says it was stopped (`· stream stopped` on the status line). A request timeout that ends a stream keeps it the same way (none is set by default), and so does a connection that ends before the stream does. Once it ends, it is shown whole, and server-sent events get an *Events* tab: one row per event (its type, its id and the start of its data); Enter or a double-click shows an event's data in full, JSON pretty-printed, to read or copy. Events keep only where they are in the body, so a long stream's thousands of events take little memory. A stream is decoded as it arrives (gzip, deflate, br), and the maximum response size still applies: it stops a stream that reaches it. On the command line, see `send` below. + | Key | Action | Key | Action | |---|---|---|---| -| F5 / Enter in URL bar / Ctrl+Enter | Send (press again to cancel) | Esc | Cancel a running request | +| F5 / Enter in URL bar / Ctrl+Enter | Send (press again to cancel, or to stop a stream) | Esc | Cancel a running request, or stop a stream, keeping what arrived | | Ctrl+S | Save all changed files | Ctrl+N | New request; adds an imported or history request to a collection | | F2 | Rename tree item | Del / Insert | Delete tree item, table row or history entry / add a table row | | F7 | Switch environment | F8 | Client certificates | @@ -166,6 +169,7 @@ Text editors show tabs 4 columns wide (the Tab key moves to the next field). Eve - **Body:** pretty or raw view, wrap, copy (the whole body as shown, with its own line breaks), save (as received). *Save as…* asks before replacing a file (*Cancel* is the default), and its message says when that is not the body as received: only the start of one the maximum response size cut, or the copy a history entry keeps (secrets masked as `***`, and cut at the history's size limit). A body over 1 MB shows its first 1 MB with a note; Copy and Save as… still give all of it. A large body shows *Formatting…* while it is prepared. XML with a document type (``) is shown as received: its entities are never expanded. JSON, XML, HTML and JavaScript bodies are colored as their Content-Type says, also with words wrapped; so are JSON and markup in a body of another type (`text/plain`) or none. - **Filter:** shows a JSONPath row in the Body tab. Type a query ([RFC 9535](https://www.rfc-editor.org/rfc/rfc9535): `$.items[?@.price < 10].name`, `$..id`, `$.users[-1]`, with the functions `length`, `count`, `match`, `search` and `value`), and the body shows the values it selects as a JSON array (pretty, or on one line with *Pretty: off*), for this response and the ones after it, until you close the row (✕, Esc, or Filter again). The row says how many values the query selects, or why it can't: a query being typed that isn't valid JSONPath yet (the body keeps the last result meanwhile, and the message says where the query goes wrong), or a body that isn't JSON (shown as it is). NDJSON and JSON Lines bodies are filtered as an array of their lines. Copy copies the values (up to 16 MB of them); *Save as…* still saves the body as received. A large body shows *Filtering…* while the query runs. - **Headers:** as the server sent them, `Content-Encoding` and `Content-Length` included. A value too long for the pane ends with `…`: Enter or a double-click on its row shows the whole header, wrapped, to read or select, and *Copy* (the default button) copies its value. gzip, deflate and br bodies are decoded; a body that can't be decoded, or uses another coding, is kept as received, with a warning. The maximum response size applies to the body as received and once decoded. +- **Events:** server-sent events, one a row, for a response of that type (see [Streams](#streams)). - **Timeline:** the exact request sent (with the generated `Accept-Encoding: gzip, deflate, br`, unless you typed one, such as `identity`, which is sent instead), DNS/connect/TLS/TTFB/download timing, and warnings. - **TLS:** protocol and cipher, the client certificate sent and whether the server asked for one, and the server chain with validation details. - **Scripts:** what the scripts did: tests, printed output, errors with their traceback, and the variables they set. Like a body, what is over 1 MB shows its first 1 MB with a note. @@ -757,6 +761,8 @@ The `--report-json` report redacts secrets the way [recordings](#recording-reque `send --filter ` prints only the values a JSONPath query ([RFC 9535](https://www.rfc-editor.org/rfc/rfc9535), as in the UI's Filter) selects in a JSON body, as a JSON array: two-space indented, or on one line with `--raw`; with `-o`, it writes them to the file instead of the body. A query that isn't valid JSONPath is a usage error, reported with where it goes wrong before anything is sent; a body that isn't JSON (or binary, or empty) makes `send` exit with code 1. +`send` prints a response that streams ([server-sent events or JSON lines](#streams)) to standard output as it arrives, after its headers with `-i`, and says so on standard error. The first **Ctrl+C** stops it and keeps what arrived as the response: its tests run, it is recorded, and `send` exits as it does for any response (a second Ctrl+C cancels, a third ends TermRest). With `-o` or `--filter`, the body is written when the stream ends. `run` reads a stream until the server ends it; `--timeout` stops it, keeping what arrived. + `send` exits with 0 when done; 1 when there was no response, a test or script failed, the body couldn't be saved with `-o` or filtered with `--filter`, the recording wasn't saved, or files of the collection or the workspace settings can't be read; 2 for a usage problem (an unknown or ambiguous request or `-e` environment, one `--curl` can't export, or a `--filter` query that isn't JSONPath); 22 for HTTP status 400 or more with `--fail`; 63 when the response body was cut at the maximum response size (*Tools › Settings*, `maxResponseSizeMb`, 50 MB), so what `-o` or standard output received is only its start; 130 when cancelled. Warnings raised while sending (a redirect not followed, a header left out, a cut body) are printed after the response. A name that matches several requests, in the workspace's collections or in one collection, is reported as ambiguous: give its path (`Folder/Name`) or its collection. So is an `-e` name that several environments of the workspace have: nothing is sent, and the error lists their files; pass one of them with `-e` instead (a JSON or YAML environment file). Without `-e`, the workspace's active environment is used. A body counts as binary when its Content-Type isn't text (`text/*`; JSON, XML or JavaScript named as a word of the subtype, as in `application/problem+json`, `application/x-ndjson` or `image/svg+xml`; form data), or, with no Content-Type, when it contains a NUL byte. Office documents (`application/vnd.openxmlformats-officedocument.…`) are ZIP files: binary. A console window shows binary content as a hex dump unless `--raw` asks for the bytes. Text bodies are decoded from the charset their Content-Type names (also one with a stray `;` at its end, which .NET's own parser rejects), legacy code pages included (windows-1252, Shift_JIS, GBK, Big5 …), and UTF-16 without a byte order mark in the byte order its text shows, in `send`, `history --show`, the UI, scripts and recordings. diff --git a/src/TermRest.Cli/CliApp.cs b/src/TermRest.Cli/CliApp.cs index 97f951f..efb86d3 100644 --- a/src/TermRest.Cli/CliApp.cs +++ b/src/TermRest.Cli/CliApp.cs @@ -11,6 +11,18 @@ internal static class CliApp /// Cancelled by the first Ctrl+C or SIGTERM while send or run works (see ). private static readonly CancellationTokenSource Stopping = new(); + private static Action? s_interrupt; + + /// + /// Takes the next Ctrl+C in place of , once: send stops a response that streams with it, + /// keeping what arrived. Null: Ctrl+C stops the command. + /// + internal static Action? Interrupt + { + get => Volatile.Read(ref s_interrupt); + set => Volatile.Write(ref s_interrupt, value); + } + public static async Task RunAsync(string[] args) { var insecure = new Option("--insecure", "-k") { Description = "Do not verify server TLS certificates", Recursive = true }; @@ -71,10 +83,17 @@ public static async Task RunAsync(string[] args) /// /// The first Ctrl+C (or SIGTERM: a cancelled CI job) stops send and run, which still save their recording /// and write their report, however long that takes (System.CommandLine would end the process 2 seconds after the - /// signal); another one ends TermRest at once. + /// signal); another one ends TermRest at once. A Ctrl+C that takes does neither. /// private static void Stop(PosixSignalContext context) { + if (context.Signal == PosixSignal.SIGINT && Interlocked.Exchange(ref s_interrupt, null) is { } interrupt) + { + context.Cancel = true; + interrupt(); + return; + } + context.Cancel = !Stopping.IsCancellationRequested; Stopping.Cancel(); } diff --git a/src/TermRest.Cli/SendCommand.cs b/src/TermRest.Cli/SendCommand.cs index 512704b..b3e655e 100644 --- a/src/TermRest.Cli/SendCommand.cs +++ b/src/TermRest.Cli/SendCommand.cs @@ -125,13 +125,23 @@ public static Command Create(Option insecure) } var printed = 0; - var exchange = await runner.SendAsync(match.Collection, match.Node, spec, prepared => + HttpExchange exchange; + bool streamed; + + // A response that streams is printed as it arrives, unless it goes to a file or a filter; Ctrl+C stops it. + using (var stream = new ConsoleStream(print: query is null && parseResult.GetValue(output) is null, parseResult.GetValue(include))) { - PrintWarnings(prepared); - printed = prepared.Warnings.Count; - }, cancellationToken); + exchange = await runner.SendAsync(match.Collection, match.Node, spec, prepared => + { + PrintWarnings(prepared); + printed = prepared.Warnings.Count; + prepared.StreamWatcher = stream; + }, cancellationToken); + streamed = stream.Printed; + } + var recorded = options.SaveRecording(parseResult, runner, recorder, cancellationToken.IsCancellationRequested); - var code = await ReportAsync(parseResult, exchange, query, verbose, include, output, raw, fail, cancellationToken); + var code = await ReportAsync(parseResult, exchange, query, verbose, include, output, raw, fail, streamed, cancellationToken); // Those raised while it was sent: a redirect not followed, a header left out, a body cut short … PrintWarnings(exchange.Request, printed); @@ -185,9 +195,10 @@ private static void PrintWarnings(PreparedRequest prepared, int from = 0) return []; } + /// The body went to standard output as it arrived (a response that streams; see ). private static async Task ReportAsync( ParseResult parseResult, HttpExchange exchange, JsonPath? query, Option verbose, Option include, Option output, Option raw, - Option fail, CancellationToken cancellationToken) + Option fail, bool streamed, CancellationToken cancellationToken) { if (parseResult.GetValue(verbose)) { @@ -201,7 +212,7 @@ private static async Task ReportAsync( } Output.Status($"{response.StatusCode} {response.ReasonPhrase} · {HttpExchange.Format(exchange.Timing.Total)} · {HttpExchange.FormatSize(response.Body.LongLength)}", response.StatusCode < 400); - if (parseResult.GetValue(include)) + if (parseResult.GetValue(include) && !streamed) { Console.Out.WriteLine($"HTTP/{response.Version} {response.StatusCode} {response.ReasonPhrase}"); foreach (var (key, value) in response.Headers) @@ -233,6 +244,10 @@ private static async Task ReportAsync( Output.Info($"Saved {HttpExchange.FormatSize(response.Body.LongLength)} to {file}"); } + else if (streamed) + { + // printed as it arrived + } else if (Console.IsOutputRedirected ? parseResult.GetValue(raw) || BodyFormatter.IsBinary(response.Body, response.ContentType) : parseResult.GetValue(raw) && !BodyFormatter.LooksLikeText(response.Body, response.ContentType)) @@ -320,4 +335,85 @@ private static void PrintVerbose(HttpExchange exchange) } } } + + /// + /// A response that streams (server-sent events, JSON lines): its body printed to standard output as it arrives (with -i, + /// after its headers), unless print is off (-o, --filter: they get it whole). The first Ctrl+C stops it, keeping + /// what arrived, which is then reported as the response. + /// + private sealed class ConsoleStream(bool print, bool include) : IStreamWatcher, IDisposable + { + private readonly CancellationTokenSource _stop = new(); + private Stream? _stdout; + + public CancellationToken Stopping => _stop.Token; + + /// Whether the body went to standard output as it arrived. + public bool Printed { get; private set; } + + public void Started(ResponseSnapshot head) + { + CliApp.Interrupt = Stop; + Output.Info($"{head.StatusCode} {head.ReasonPhrase} · streaming (Ctrl+C stops it, keeping what arrived)"); + if (!print) + { + return; + } + + if (include) + { + Console.Out.WriteLine($"HTTP/{head.Version} {head.StatusCode} {head.ReasonPhrase}"); + foreach (var (key, value) in head.Headers) + { + Console.Out.WriteLine($"{key}: {value}"); + } + + Console.Out.WriteLine(); + Console.Out.Flush(); + } + + _stdout = Console.OpenStandardOutput(); + Printed = true; + } + + public void Received(ReadOnlySpan data) + { + if (_stdout is null || data.IsEmpty) + { + return; + } + + try + { + _stdout.Write(data); + _stdout.Flush(); + } + catch (IOException) + { + // What reads the output went (| head -n 5): the stream is stopped, as nothing reads it any more. + _stdout = null; + Stop(); + } + } + + /// The request ended: Ctrl+C stops the command again. + public void Dispose() + { + CliApp.Interrupt = null; + _stdout?.Dispose(); + _stop.Dispose(); + } + + private void Stop() + { + try + { + _stop.Cancel(); + } + catch (ObjectDisposedException) + { + // it ended meanwhile + } + } + } } diff --git a/src/TermRest.Core/Http/HttpExchange.cs b/src/TermRest.Core/Http/HttpExchange.cs index 9aeaf0e..ea8bd86 100644 --- a/src/TermRest.Core/Http/HttpExchange.cs +++ b/src/TermRest.Core/Http/HttpExchange.cs @@ -88,6 +88,12 @@ public sealed class ResponseSnapshot public bool BodyTruncated { get; init; } + /// + /// The body streamed (see ) and was stopped before the server ended it: by its watcher, the + /// request timeout, or the connection. It is what arrived until then (a warning says why it stopped). + /// + public bool Stopped { get; init; } + public string? ContentType { get; init; } public Uri? FinalUri { get; init; } diff --git a/src/TermRest.Core/Http/HttpExecutor.cs b/src/TermRest.Core/Http/HttpExecutor.cs index a41d874..9b1ef1a 100644 --- a/src/TermRest.Core/Http/HttpExecutor.cs +++ b/src/TermRest.Core/Http/HttpExecutor.cs @@ -138,16 +138,23 @@ public async Task SendAsync(PreparedRequest request, CancellationT request.Warnings.Add(ProxySignInHint); } - var (body, truncated, received, warning) = await ReadBodyAsync(response, request.MaxResponseBytes, linked.Token).ConfigureAwait(false); - exchange.Response = Snapshot(response, body, truncated, received); - if (warning is not null) + if (Streams(response)) { - request.Warnings.Add(warning); + await ReadStreamAsync(exchange, response, timeoutSource, cancellationToken).ConfigureAwait(false); } - - if (truncated) + else { - request.Warnings.Add($"The response body was truncated at {HttpExchange.FormatSize(request.MaxResponseBytes)}."); + var (body, truncated, received, warning) = await ReadBodyAsync(response, request.MaxResponseBytes, linked.Token).ConfigureAwait(false); + exchange.Response = Snapshot(response, body, truncated, received); + if (warning is not null) + { + request.Warnings.Add(warning); + } + + if (truncated) + { + request.Warnings.Add($"The response body was truncated at {HttpExchange.FormatSize(request.MaxResponseBytes)}."); + } } } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) @@ -554,6 +561,152 @@ private static Uri WithoutUserInfo(Uri uri) => return (body, cut, received.Length, null); } + /// Whether the response's body streams (see ); HEAD, 204 and 304 responses have none. + private static bool Streams(HttpResponseMessage response) => + response.RequestMessage?.Method != HttpMethod.Head && response.StatusCode is not (HttpStatusCode.NoContent or HttpStatusCode.NotModified) + && ResponseStreams.Streams(response.Content.Headers.ContentType?.MediaType ?? RawContentType(response.Content.Headers)); + + /// + /// Reads a body that streams as it arrives, part by part, removing its content codings on the way, and gives each part + /// to the request's watcher. The watcher's stop and the request timeout end it, keeping what arrived, and so does a + /// connection that ends before the stream does; at most the maximum response size is kept (decoded). Cancelling the + /// request discards it, as it does any response. + /// + private static async Task ReadStreamAsync(HttpExchange exchange, HttpResponseMessage response, CancellationTokenSource? timeout, + CancellationToken cancellationToken) + { + var request = exchange.Request; + var watcher = request.StreamWatcher; + watcher?.Started(Snapshot(response, [], truncated: false, received: 0)); + using var stop = CancellationTokenSource.CreateLinkedTokenSource(watcher?.Stopping ?? CancellationToken.None, timeout?.Token ?? CancellationToken.None); + using var reading = CancellationTokenSource.CreateLinkedTokenSource(stop.Token, cancellationToken); + var codings = ContentCodings(response.Content.Headers); + string? warning = null; + if (codings.Find(c => c is not ("gzip" or "x-gzip" or "deflate" or "br")) is { } unknown) + { + warning = $"The body is kept as received: TermRest cannot decode Content-Encoding '{unknown}'."; + codings.Clear(); + } + + var wire = new CountingStream(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)); + Stream source = wire; + for (var i = codings.Count - 1; i >= 0; i--) + { + source = codings[i] switch + { + "br" => new BrotliStream(source, CompressionMode.Decompress), + "deflate" => new ZLibStream(source, CompressionMode.Decompress), + _ => new GZipStream(source, CompressionMode.Decompress), + }; + } + + using var body = new MemoryStream(); + var chunk = ArrayPool.Shared.Rent(16 * 1024); + var (truncated, stopped) = (false, false); + try + { + int read; + while ((read = await source.ReadAsync(chunk.AsMemory(), reading.Token).ConfigureAwait(false)) > 0) + { + var count = (int)Math.Clamp(request.MaxResponseBytes - body.Length, 0, read); + body.Write(chunk, 0, count); + watcher?.Received(chunk.AsSpan(0, count)); + if (count < read) + { + (truncated, stopped) = (true, true); + warning ??= $"The stream was stopped at the maximum response size, {HttpExchange.FormatSize(request.MaxResponseBytes)}: its body is what arrived until then."; + break; + } + } + } + catch (Exception ex) when ((ex is OperationCanceledException or IOException or HttpRequestException) && stop.IsCancellationRequested + && !cancellationToken.IsCancellationRequested) + { + stopped = true; + warning ??= watcher?.Stopping.IsCancellationRequested != true && timeout?.IsCancellationRequested == true + ? $"The stream was stopped at the request timeout ({HttpExchange.Format(request.Timeout)}): its body is what arrived until then." + : "The stream was stopped: its body is what arrived until then."; + } + catch (Exception ex) when ((ex is IOException or HttpRequestException or InvalidDataException) && !cancellationToken.IsCancellationRequested) + { + stopped = true; + warning ??= ex is InvalidDataException + ? $"The rest of the stream could not be decoded (Content-Encoding: {string.Join(", ", codings)}): its body is what was decoded until then." + : $"The connection ended before the stream did ({ex.Message}): its body is what arrived until then."; + } + finally + { + ArrayPool.Shared.Return(chunk); + await source.DisposeAsync().ConfigureAwait(false); + } + + exchange.Response = Snapshot(response, ToArray(body), truncated, wire.Count, stopped); + if (warning is not null) + { + request.Warnings.Add(warning); + } + } + + /// Counts what is read through it: the size of a streamed body as received, before its content codings are removed. + private sealed class CountingStream(Stream inner) : Stream + { + public long Count { get; private set; } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => Counted(inner.Read(buffer, offset, count)); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => + Counted(await inner.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)); + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override async ValueTask DisposeAsync() + { + await inner.DisposeAsync().ConfigureAwait(false); + await base.DisposeAsync().ConfigureAwait(false); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + inner.Dispose(); + } + + base.Dispose(disposing); + } + + private int Counted(int read) + { + Count += read; + return read; + } + } + /// A body's content codings in the order they were applied, leaving out identity (and "none", which some servers send). private static List ContentCodings(HttpContentHeaders headers) { @@ -629,7 +782,7 @@ private static Stream CreateDecoder(string coding, byte[] data) /// The buffer itself when the content fills it exactly, otherwise a copy of the content. private static byte[] ToArray(MemoryStream buffer) => buffer.Length == buffer.Capacity ? buffer.GetBuffer() : buffer.ToArray(); - private static ResponseSnapshot Snapshot(HttpResponseMessage response, byte[] body, bool truncated, long received) + private static ResponseSnapshot Snapshot(HttpResponseMessage response, byte[] body, bool truncated, long received, bool stopped = false) { var headers = new List>(); void AddAll(HttpHeaders source) @@ -655,6 +808,7 @@ void AddAll(HttpHeaders source) Body = body, ReceivedBodySize = received, BodyTruncated = truncated, + Stopped = stopped, // .NET reads no type from a Content-Type it can't parse (a trailing ";", an empty charset …), which servers send: // the header as the server sent it then, as Postman reads it (the charset and media type are read leniently). ContentType = response.Content.Headers.ContentType?.ToString() ?? RawContentType(response.Content.Headers), diff --git a/src/TermRest.Core/Http/PreparedRequest.cs b/src/TermRest.Core/Http/PreparedRequest.cs index aa9aec8..32603a2 100644 --- a/src/TermRest.Core/Http/PreparedRequest.cs +++ b/src/TermRest.Core/Http/PreparedRequest.cs @@ -314,6 +314,12 @@ public sealed class PreparedRequest public long MaxResponseBytes { get; set; } = 50L * 1024 * 1024; + /// + /// Sees the response arrive when it streams (server-sent events, JSON lines), and can stop it, keeping what arrived; see + /// . Null: such a response is read whole, until the server ends it or the timeout stops it. + /// + public IStreamWatcher? StreamWatcher { get; set; } + public List Warnings { get; } = []; /// Problems that prevent sending (invalid URL, missing body file, ...). diff --git a/src/TermRest.Core/Http/ResponseStreams.cs b/src/TermRest.Core/Http/ResponseStreams.cs new file mode 100644 index 0000000..7014824 --- /dev/null +++ b/src/TermRest.Core/Http/ResponseStreams.cs @@ -0,0 +1,214 @@ +using System.Text; + +namespace TermRest.Core.Http; + +/// +/// Watches a response that streams (see ) while it arrives, and can stop it: what arrived is +/// then its body, as a whole response's would be. Set it on before the request +/// goes out; responses that don't stream are read whole, as always. Called on the thread that sends. +/// +public interface IStreamWatcher +{ + /// Cancelled to stop the stream: what arrived is kept as its body (the request is not cancelled). + CancellationToken Stopping { get; } + + /// The response's status and headers arrived, and its body streams: it comes next, part by part. + void Started(ResponseSnapshot head); + + /// A part of the body as it arrived, decoded (gzip …), within the maximum response size. + void Received(ReadOnlySpan data); +} + +/// +/// The responses whose body is read as it arrives, part by part: server-sent events and JSON lines. A watcher sees them +/// arrive and can stop them; a request timeout that ends one keeps what arrived too. +/// +public static class ResponseStreams +{ + private static readonly string[] MediaTypes = + [ + "text/event-stream", + "application/x-ndjson", "application/ndjson", "application/jsonl", "application/x-jsonlines", "application/json-seq", "application/stream+json", + ]; + + /// Whether a response with this Content-Type streams. + public static bool Streams(string? contentType) => MediaType(contentType) is { } type && MediaTypes.Contains(type); + + /// Whether a response with this Content-Type is server-sent events. + public static bool IsEventStream(string? contentType) => MediaType(contentType) == "text/event-stream"; + + private static string? MediaType(string? contentType) => + contentType is null ? null : contentType.AsSpan(0, contentType.IndexOf(';') is >= 0 and var end ? end : contentType.Length).Trim().ToString().ToLowerInvariant(); +} + +/// An event of a server-sent events body: where it is in the body, its type, and where its last event id is. +/// Where its lines start in the body (bytes). +/// How long its lines are, without the blank line that ends it (bytes). +/// Its event:, or message. +/// +/// Where the last id: line so far starts in the body (an earlier event's, maybe: the id carries over to the events +/// that follow, as browsers have it); -1 for none. +/// +public readonly record struct ServerSentEvent(int Start, int Length, string Type, int IdLine) +{ + /// Its last event id, read from the body; null for none. + public string? Id(byte[] body) => IdLine < 0 ? null : ServerSentEvents.FieldAt(body, IdLine).Value; + + /// Its data: the values of its data: lines, joined with line breaks, read from the body (within its first ). + public string Data(byte[] body, int maxBytes = int.MaxValue) + { + var data = new StringBuilder(); + var first = true; + foreach (var (name, value) in ServerSentEvents.Fields(body.AsSpan(Start, Math.Min(Length, maxBytes)))) + { + if (name == "data") + { + data.Append(first ? "" : "\n").Append(value); + first = false; + } + } + + return data.ToString(); + } +} + +/// +/// Reads the events of a server-sent events body (text/event-stream) as the HTML standard does: lines of fields +/// (event:, data:, id:, retry:; a line that starts with a colon is a comment), and an event at +/// each blank line that follows data. An event keeps only where it is in the body, so that a long stream's thousands of +/// events take little memory; its data is read from the body when it is shown. +/// +public static class ServerSentEvents +{ + public static List Parse(byte[] body, CancellationToken cancellationToken = default) + { + var events = new List(); + var types = new Dictionary(StringComparer.Ordinal) { ["message"] = "message" }; + Span typeBuffer = stackalloc char[128]; + var idLine = -1; + string? type = null; + var hasData = false; + var start = body.AsSpan().StartsWith("\uFEFF"u8) ? 3 : 0; + var eventStart = start; + var eventEnd = start; + for (var at = start; at < body.Length;) + { + var next = Line(body, at, out var end); + var line = body.AsSpan(at, end - at); + if (line.Length == 0) + { + if (hasData) + { + events.Add(new ServerSentEvent(eventStart, eventEnd - eventStart, type ?? "message", idLine)); + if ((events.Count & 1023) == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + } + } + + (type, hasData, eventStart) = (null, false, next); + } + else if (line[0] != (byte)':') + { + var colon = line.IndexOf((byte)':'); + var field = colon < 0 ? line : line[..colon]; + if (field.SequenceEqual("data"u8)) + { + hasData = true; + } + else if (field.SequenceEqual("event"u8)) + { + type = Intern(Value(line, colon), types, typeBuffer); + } + else if (field.SequenceEqual("id"u8) && !Value(line, colon).Contains((byte)0)) + { + idLine = at; + } + + eventEnd = at + line.Length; + } + else + { + eventEnd = at + line.Length; // a comment, kept with its event + } + + at = next; + } + + return events; + } + + /// An event type as one string for all the events of that type: a long stream's events don't take one each. + private static string Intern(ReadOnlySpan value, Dictionary types, Span buffer) + { + if (value.Length <= buffer.Length) + { + var length = Encoding.UTF8.GetChars(value, buffer); + if (types.GetAlternateLookup>().TryGetValue(buffer[..length], out var known)) + { + return known; + } + } + + var text = Encoding.UTF8.GetString(value); + return types.TryGetValue(text, out var existing) ? existing : types[text] = text; + } + + /// The field of the line at in . + internal static (string Name, string Value) FieldAt(byte[] body, int at) + { + Line(body, at, out var end); + return Field(body.AsSpan(at, end - at)); + } + + /// A field's value: what follows its colon, a space after it left out; empty without one. + private static ReadOnlySpan Value(ReadOnlySpan line, int colon) + { + if (colon < 0) + { + return []; + } + + var value = line[(colon + 1)..]; + return value.Length > 0 && value[0] == ' ' ? value[1..] : value; + } + + /// The fields of an event's lines, in order (comments left out). + internal static IEnumerable<(string Name, string Value)> Fields(ReadOnlySpan lines) + { + var fields = new List<(string, string)>(); + for (var at = 0; at < lines.Length;) + { + var next = Line(lines, at, out var end); + if (end > at && lines[at] != (byte)':') + { + fields.Add(Field(lines[at..end])); + } + + at = next; + } + + return fields; + } + + /// Where the next line starts; : where the line at ends, before its CRLF, LF or CR. + private static int Line(ReadOnlySpan text, int at, out int end) + { + var length = text[at..].IndexOfAny((byte)'\n', (byte)'\r'); + if (length < 0) + { + end = text.Length; + return text.Length; + } + + end = at + length; + return end + (text[end] == '\r' && end + 1 < text.Length && text[end + 1] == '\n' ? 2 : 1); + } + + /// A field's name and value (a space after the colon is left out); a comment's name is empty. + private static (string Name, string Value) Field(ReadOnlySpan line) + { + var colon = line.IndexOf((byte)':'); + return (Encoding.UTF8.GetString(colon < 0 ? line : line[..colon]), Encoding.UTF8.GetString(Value(line, colon))); + } +} diff --git a/src/TermRest.Tui/MainWindow.cs b/src/TermRest.Tui/MainWindow.cs index bc674e5..4fd18b9 100644 --- a/src/TermRest.Tui/MainWindow.cs +++ b/src/TermRest.Tui/MainWindow.cs @@ -50,6 +50,7 @@ internal sealed class MainWindow : Runnable private ExampleNode? _example; private PostmanCollection? _scratch; private CancellationTokenSource? _sending; + private LiveResponse? _live; // the response of the request on its way, while it streams /// Counts the requests shown in the editor, so that a response arriving for an earlier one is not shown under another. private int _opened; @@ -569,11 +570,50 @@ private async void Send() } } + /// + /// While a request is on its way, shows its response a few times a second once it streams (server-sent events, JSON + /// lines), as long as its request is the one open; the pane is drawn again only when more arrived. + /// + private void WatchLive(LiveResponse live, int opened) + { + var shown = 0; + App?.AddTimeout(TimeSpan.FromMilliseconds(250), () => + { + if (_live != live || _closed) + { + return false; + } + + var version = live.Version; + if (version != shown && opened == _opened) + { + var (head, received, text, cut) = live.Read(); + if (head is not null) + { + shown = version; + _response.ShowLive(head, received, text, cut); + _editor.SetSending(true, streaming: true); + } + } + + return true; + }); + } + private async Task SendAsync() { if (_sending is not null) { - _sending.Cancel(); + // A response that streams is stopped, keeping what arrived; anything else is cancelled. + if (_live is { Streaming: true } streaming) + { + streaming.Stop(); + } + else + { + _sending.Cancel(); + } + return; } @@ -607,6 +647,9 @@ private async Task SendAsync() _editor.SetSending(true); using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(_closing.Token); _sending = cancellation; + using var live = new LiveResponse(); + _live = live; + WatchLive(live, opened); var recorder = _runner.Recorder; var recordedBefore = recorder?.Count ?? 0; HttpExchange exchange; @@ -616,6 +659,7 @@ private async Task SendAsync() exchange = await _runner.SendAsync(collection, SendContext, _editor.Spec, ready => { prepared = ready; + ready.StreamWatcher = live; if (opened == _opened) { _response.ShowSending(ready); @@ -665,6 +709,11 @@ private async Task SendAsync() { _sending = null; } + + if (_live == live) + { + _live = null; + } } // The window may have been closed (quit, workspace switch) while the request was in flight. @@ -2281,7 +2330,7 @@ private void ApplyImportedCurl(CurlImportResult imported, bool intoCurrent) private static readonly (string Keys, string Action)[] Shortcuts = [ ("F5, Ctrl+Enter", "Send (again to cancel)"), - ("Esc", "Cancel a running request"), + ("Esc", "Cancel a request, stop a stream"), ("Ctrl+S", "Save all changes"), ("Ctrl+N", "New request"), ("F2", "Rename tree item"), @@ -2500,10 +2549,19 @@ private bool ConfirmUnsaved() protected override bool OnKeyDown(Key key) { - // Esc is Terminal.Gui's default Quit key; in the main window it cancels a running request instead. + // Esc is Terminal.Gui's default Quit key; in the main window it cancels a running request instead, or stops a + // response that streams, keeping what arrived. if (key == Key.Esc) { - _sending?.Cancel(); + if (_live is { Streaming: true } live) + { + live.Stop(); + } + else + { + _sending?.Cancel(); + } + return true; } diff --git a/src/TermRest.Tui/Views/LiveResponse.cs b/src/TermRest.Tui/Views/LiveResponse.cs new file mode 100644 index 0000000..52d0ebf --- /dev/null +++ b/src/TermRest.Tui/Views/LiveResponse.cs @@ -0,0 +1,116 @@ +using System.Text; +using TermRest.Core.Http; + +namespace TermRest.Tui.Views; + +/// +/// A response that streams (server-sent events, JSON lines) while it arrives, for the response pane: its head, how much has +/// arrived, and the end of its text, the last bytes, which is all the pane shows until the stream ends +/// (then it shows it whole). The sending thread writes it; the UI thread reads it a few times a second (see +/// ). ends the stream, keeping what arrived. +/// +internal sealed class LiveResponse : IStreamWatcher, IDisposable +{ + internal const int Kept = 64 * 1024; + + private readonly Lock _gate = new(); + private readonly CancellationTokenSource _stop = new(); + private readonly byte[] _tail = new byte[Kept]; + private int _tailLength; + private long _received; + private int _version; + private ResponseSnapshot? _head; + + public CancellationToken Stopping => _stop.Token; + + /// Whether the response streams: its head arrived, and its body is arriving. + public bool Streaming + { + get + { + lock (_gate) + { + return _head is not null; + } + } + } + + /// Changes when more arrives: the pane shows it again only then. + public int Version + { + get + { + lock (_gate) + { + return _version; + } + } + } + + /// Ends the stream: what arrived is its body. + public void Stop() + { + try + { + _stop.Cancel(); + } + catch (ObjectDisposedException) + { + // it ended meanwhile + } + } + + public void Started(ResponseSnapshot head) + { + lock (_gate) + { + _head = head; + _version++; + } + } + + public void Received(ReadOnlySpan data) + { + lock (_gate) + { + _received += data.Length; + if (data.Length >= Kept) + { + data[^Kept..].CopyTo(_tail); + _tailLength = Kept; + } + else + { + var keep = Math.Min(_tailLength, Kept - data.Length); + _tail.AsSpan(_tailLength - keep, keep).CopyTo(_tail); + data.CopyTo(_tail.AsSpan(keep)); + _tailLength = keep + data.Length; + } + + _version++; + } + } + + /// What arrived so far: the head (null until it arrives), how many bytes, and the text of the end, from the start of a line when it is cut. + public (ResponseSnapshot? Head, long Received, string Text, bool Cut) Read() + { + lock (_gate) + { + var tail = _tail.AsSpan(0, _tailLength); + var cut = _received > _tailLength; + if (cut) + { + var line = tail.IndexOf((byte)'\n'); + tail = line >= 0 && line < tail.Length - 1 ? tail[(line + 1)..] : tail; + while (tail.Length > 0 && (tail[0] & 0xC0) == 0x80) + { + tail = tail[1..]; // not inside a character + } + } + + return (_head, _received, Encoding.UTF8.GetString(tail), cut); + } + } + + public void Dispose() => _stop.Dispose(); +} diff --git a/src/TermRest.Tui/Views/RequestEditor.cs b/src/TermRest.Tui/Views/RequestEditor.cs index 971ef2b..1791e59 100644 --- a/src/TermRest.Tui/Views/RequestEditor.cs +++ b/src/TermRest.Tui/Views/RequestEditor.cs @@ -347,9 +347,10 @@ public void Replace(HttpRequestSpec spec) MarkModified(); } - public void SetSending(bool sending) + /// The response streams: the button stops it, keeping what arrived. + public void SetSending(bool sending, bool streaming = false) { - _send.Text = sending ? "Cancel" : "Send"; + _send.Text = !sending ? "Send" : streaming ? "Stop" : "Cancel"; SetNeedsDraw(); } diff --git a/src/TermRest.Tui/Views/ResponseView.cs b/src/TermRest.Tui/Views/ResponseView.cs index 3c4678d..d7f62ca 100644 --- a/src/TermRest.Tui/Views/ResponseView.cs +++ b/src/TermRest.Tui/Views/ResponseView.cs @@ -51,6 +51,13 @@ internal sealed class ResponseView : View private readonly TextArea _timeline; private readonly TextArea _tls; private readonly TextArea _scripts; + private readonly View _eventsTab; + private readonly TableView _events; + private readonly View[] _regularTabs; // all but Events, which server-sent events have + private List _shownEvents = []; + private byte[] _eventsBody = []; + private int _eventsVersion; // events read in the background are shown only if no other response replaced them meanwhile + private ResponseSnapshot? _liveHead; // the head of the stream shown as it arrives private readonly View _filterRow; private readonly TextField _filterField; private readonly Label _filterStatus; @@ -141,7 +148,20 @@ public ResponseView() _scripts = new TextArea { ReadOnly = true }; scriptsTab.Add(_scripts); - _tabs.AddTabs(_bodyTab, headersTab, timelineTab, tlsTab, scriptsTab); + // Server-sent events, one a row, once the stream ends; Enter or a double-click shows an event's data in full. + _eventsTab = new View { Title = "Events", Width = Dim.Fill(), Height = Dim.Fill(), CanFocus = true }; + _events = new TableView { Width = Dim.Fill(), Height = Dim.Fill(), FullRowSelect = true }; + _events.Style.ExpandLastColumn = true; + _events.Style.GetOrCreateColumnStyle(3); + _events.FrameChanged += (_, _) => FitDataColumn(); + _events.Accepted += (_, _) => ShowSelectedEvent(); + _events.KeyBindings.Remove(Key.N.WithCtrl); + _events.KeyBindings.Remove(Key.P.WithCtrl); + _eventsTab.Add(_events); + + _tabs.AddTabs(_bodyTab, _eventsTab, headersTab, timelineTab, tlsTab, scriptsTab); + _regularTabs = [_bodyTab, headersTab, timelineTab, tlsTab, scriptsTab]; + _tabs.ShowOnly(_regularTabs); // Find (Ctrl+F): in the text of the tab shown. _findBar = new View { X = 0, Y = Pos.AnchorEnd(1), Width = Dim.Fill(), Height = 1, CanFocus = true, Visible = false }; @@ -246,6 +266,7 @@ public void Clear() _tls.SetText(""); _scripts.SetText(NoScripts); SetHeaders([]); + ShowEvents(null); } /// Pre-request scripts are running: the request is not prepared yet. @@ -267,6 +288,29 @@ public void ShowSending(PreparedRequest request) _timeline.SetText(DescribeRequest(request, null)); } + /// + /// Shows a response that streams while it arrives (see ): its status, its headers, and the end of + /// its text, followed as it grows. Once it ends, or is stopped, shows it whole, with its events. + /// + public void ShowLive(ResponseSnapshot head, long received, string text, bool cut) + { + _exchange = null; // Copy, Save and Filter wait for the whole response + _fromHistory = false; + _saveExample.Visible = false; + _status.Text = $"{head.StatusCode} {head.ReasonPhrase} · streaming · {HttpExchange.FormatSize(received)} so far · Esc stops it"; + _status.SchemeName = null; + if (!ReferenceEquals(_liveHead, head)) + { + _liveHead = head; + SetHeaders(head.Headers); + ShowEvents(null); + SetFilterStatus("", error: false); + } + + ShowBody(cut ? $"… {HttpExchange.FormatSize(received)} so far: the end is shown until the stream ends\n{text}" : text); + _body.MoveEnd(); + } + /// /// It comes from the history (see ), whose copy of a body may be cut /// short and has secrets masked, and which keeps no TLS details, script results, or SSL and redirect settings. @@ -276,6 +320,7 @@ public void ShowExchange(HttpExchange exchange, bool fromHistory = false) // A response shown again (a request that could not be sent puts back the one shown before it) keeps where it came from. _fromHistory = fromHistory || (_fromHistory && ReferenceEquals(exchange, _exchange)); _exchange = exchange; + _liveHead = null; var response = exchange.Response; var scripts = exchange.Scripts; _saveExample.Visible = response is not null; @@ -288,16 +333,18 @@ public void ShowExchange(HttpExchange exchange, bool fromHistory = false) ShowBody(exchange.Cancelled ? "" : scripts?.Error is not null ? ShownScripts($"{exchange.ErrorMessage}\n\n{scripts.Describe()}") : exchange.ErrorMessage ?? ""); SetFilterStatus(_filter is null ? "" : "No response to filter.", error: false); SetHeaders([]); + ShowEvents(null); } else { var http = $"HTTP/{response.Version.Major}{(response.Version.Major < 2 ? "." + response.Version.Minor : "")}"; var warnings = exchange.Request.Warnings.Count > 0 ? $" · ⚠ {exchange.Request.Warnings.Count} warning(s), see Timeline" : ""; var tests = scripts?.Summary is { Length: > 0 } summary ? $" · {summary}" : ""; + var stopped = response.Stopped ? " · stream stopped" : ""; // The history may keep only the start of the body: its entry has the size received. var size = (_fromHistory ? exchange.HistoryEntry?.Size : null) ?? response.Body.LongLength; - _status.Text = $"{response.StatusCode} {response.ReasonPhrase} · {HttpExchange.Format(exchange.Timing.Total)} · {HttpExchange.FormatSize(size)} · {http}{tests}{warnings}"; + _status.Text = $"{response.StatusCode} {response.ReasonPhrase} · {HttpExchange.Format(exchange.Timing.Total)} · {HttpExchange.FormatSize(size)} · {http}{stopped}{tests}{warnings}"; _status.SchemeName = response.StatusCode switch { >= 500 => "Error", @@ -307,6 +354,7 @@ public void ShowExchange(HttpExchange exchange, bool fromHistory = false) }; SetHeaders(response.Headers); RenderBody(); + ShowEvents(BodyNotKept ? null : response); } _scripts.SetText(_fromHistory ? "Script results are not kept in the history." : scripts is null ? NoScripts : ShownScripts(scripts.Describe())); @@ -627,6 +675,124 @@ private void ShowSelectedHeader() } } + /// + /// The Events tab: shown for server-sent events, with the events read from the body (a large one in the background, the + /// tab saying so meanwhile); hidden for other responses ( null: none). + /// + private void ShowEvents(ResponseSnapshot? response) + { + var version = ++_eventsVersion; + if (response is null || !ResponseStreams.IsEventStream(response.ContentType)) + { + SetEvents([], []); + _tabs.ShowOnly(_regularTabs); + return; + } + + _tabs.ShowOnly(null); + var body = response.Body; + if (App is not { } app || body.Length < BackgroundSize) + { + SetEvents(ServerSentEvents.Parse(body), body); + return; + } + + SetEvents([], []); + _eventsTab.Title = "Events (reading)"; + _ = Task.Run(() => ServerSentEvents.Parse(body)).ContinueWith( + task => app.AddTimeout(TimeSpan.Zero, () => + { + if (version == _eventsVersion && !_disposed && task.IsCompletedSuccessfully) + { + SetEvents(task.Result, body); + } + + return false; + }), + TaskScheduler.Default); + } + + private void SetEvents(List events, byte[] body) + { + (_shownEvents, _eventsBody) = (events, body); + _eventsTab.Title = events.Count == 0 ? "Events" : $"Events ({events.Count.ToString("N0", CultureInfo.InvariantCulture)})"; + _events.Table = new EventRows(this); + FitDataColumn(); + _events.Update(); + _tabs.SetNeedsDraw(); + } + + /// The events as the Events tab's rows, each cell read when it is drawn: no copy of a long stream's events. + private sealed class EventRows(ResponseView view) : ITableSource + { + public string[] ColumnNames { get; } = ["#", "Event", "Id", "Data"]; + + public int Columns => ColumnNames.Length; + + public int Rows => view._shownEvents.Count; + + public object this[int row, int col] => col switch + { + 0 => row + 1, + 1 => view._shownEvents[row].Type, + 2 => view._shownEvents[row].Id(view._eventsBody) ?? "", + _ => view.EventPreview(row), + }; + } + + /// The start of an event's data, on one line: a table cell (read from the body when it is drawn). + private string EventPreview(int index) + { + if (index >= _shownEvents.Count) + { + return ""; + } + + var data = _shownEvents[index].Data(_eventsBody, maxBytes: 1024); + var line = data.AsSpan(0, data.IndexOfAny('\r', '\n') is >= 0 and var end ? end : data.Length); + return line.Length > 200 || line.Length < data.Length ? string.Concat(line[..Math.Min(line.Length, 200)], "…") : data; + } + + /// Keeps the Data column within the pane, as does the headers' values. + private void FitDataColumn() + { + var others = Math.Min(_events.MaxCellWidth, 30) + 12; + var width = Math.Max(MinValueColumns, _events.Viewport.Width - others); + var style = _events.Style.GetOrCreateColumnStyle(3); + if (style.MaxWidth != width) + { + style.MaxWidth = width; + _events.Update(); + } + } + + /// The selected event's data in full (Enter or a double-click), JSON pretty-printed, to read, select or copy. + private void ShowSelectedEvent() + { + if (App is null || _events.Value is not { } selection || selection.SelectedCell.Y < 0 || selection.SelectedCell.Y >= _shownEvents.Count) + { + return; + } + + var shown = _shownEvents[selection.SelectedCell.Y]; + var data = shown.Data(_eventsBody); + var start = data.AsSpan().TrimStart(); + var text = start.StartsWith('{') || start.StartsWith('[') ? BodyFormatter.Format(Encoding.UTF8.GetBytes(data), "application/json", pretty: true) : data; + var title = $"Event {selection.SelectedCell.Y + 1}: {shown.Type}{(shown.Id(_eventsBody) is { Length: > 0 } id ? $" (id {id})" : "")}"; + using var dialog = new Dialog { HotKeySpecifier = Ui.NoHotKey, Title = title, Width = Dim.Percent(80), Height = Dim.Percent(60) }; + var area = new TextArea { X = 1, Y = 1, Width = Dim.Fill(1), Height = Dim.Fill(), ReadOnly = true, WordWrap = true }; + area.SyntaxLanguage = ReferenceEquals(text, data) ? null : "json"; + area.SetText(text); + dialog.Add(area); + dialog.AddButton(new Button { Text = "Close" }); + dialog.AddButton(new Button { Text = "Copy" }); + App.Run(dialog); + if (dialog.Result == 1) + { + Notify(Ui.CopyToClipboard(App, data) ? "The event's data copied to the clipboard." : "Clipboard is not available in this terminal."); + } + } + private void SaveBody() { if (_exchange?.Response is not { } response || App is null) diff --git a/tests/TermRest.Cli.Tests/CommandLineTests.cs b/tests/TermRest.Cli.Tests/CommandLineTests.cs index 7b81b9f..5fdb338 100644 --- a/tests/TermRest.Cli.Tests/CommandLineTests.cs +++ b/tests/TermRest.Cli.Tests/CommandLineTests.cs @@ -813,6 +813,46 @@ public async Task Send_writes_binary_bodies_as_received() Assert.Equal(Encoding.UTF8.GetBytes(TestServer.Utf8Json), rawJson.Output); // with --raw as received, no line break added } + [Fact] + public async Task Send_prints_a_stream_as_it_arrives_once() + { + await using var server = await TestServer.StartAsync(); + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Events", "GET", server.BaseUrl + "/events")]); + + var result = await Termrest.RunAsync(["send", collection, "Events", "-i", "--no-history"]); + + Assert.True(result.ExitCode == 0, result.ToString()); + var events = string.Concat(Enumerable.Range(1, 3).Select(n => $"id: {n}\ndata: {{\"n\":{n}}}\n\n")); + var text = result.Text.ReplaceLineEndings("\n"); + Assert.StartsWith("HTTP/1.1 200 OK\n", text, StringComparison.Ordinal); + Assert.EndsWith("Content-Type: text/event-stream\n\n" + events, text, StringComparison.Ordinal); // its headers, then its events, once + Assert.Contains("200 OK · streaming (Ctrl+C stops it, keeping what arrived)", result.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task Ctrl_c_stops_a_stream_that_send_prints_keeping_what_arrived() + { + if (OperatingSystem.IsWindows()) + { + Assert.Skip("Signals a process: Unix only (Ctrl+C needs a console on Windows)."); + } + + await using var server = await TestServer.StartAsync(); + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Events", "GET", server.BaseUrl + "/events?count=0")]); + + var result = await Termrest.RunAsync(["send", collection, "Events", "--no-history"], whileRunning: async process => + { + await server.Waiting.WaitAsync(TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken); + await Task.Delay(200, TestContext.Current.CancellationToken); + using var interrupt = Process.Start("kill", ["-INT", process.Id.ToString(CultureInfo.InvariantCulture)])!; + await interrupt.WaitForExitAsync(TestContext.Current.CancellationToken); + }); + + Assert.True(result.ExitCode == 0, result.ToString()); + Assert.StartsWith("id: 1\ndata: {\"n\":1}\n\nid: 2\n", result.Text, StringComparison.Ordinal); + Assert.Contains("warning: The stream was stopped: its body is what arrived until then.", result.Error, StringComparison.Ordinal); + } + [Fact] public async Task Send_filter_prints_the_values_a_jsonpath_query_selects() { diff --git a/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs b/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs index 7e95a02..402b624 100644 --- a/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs +++ b/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs @@ -10,7 +10,8 @@ namespace TermRest.Cli.Tests.Infrastructure; /// must find its own dependencies). /bytes returns a binary body, /octets and /protobuf binary /// bodies without a NUL byte, /xlsx an Excel workbook, /large 1.5 MB of zeros, /utf8 /// , /token a login (or OAuth 2.0 token) response with , /auth the -/// request's Authorization header, /wait no response until the server stops (see ); any +/// request's Authorization header, /wait no response until the server stops (see ), +/// /events server-sent events, 30 ms apart (?count= of them, 3 by default; 0: until the client goes); any /// other path returns the request as JSON. /// internal sealed class TestServer : IAsyncDisposable @@ -53,7 +54,7 @@ private TestServer() /// How many requests it received. public int Requests => Volatile.Read(ref _requests); - /// Completes when a request to /wait arrives. + /// Completes when a request to /wait arrives, or /events sent its first event. public Task Waiting => _waiting.Task; public static Task StartAsync() => Task.FromResult(new TestServer()); @@ -124,6 +125,21 @@ private async Task RespondAsync(TcpClient client) await Task.Delay(Timeout.Infinite, _stop.Token); } + if (path == "/events") + { + var query = requestLine[1].Contains("count=", StringComparison.Ordinal) ? requestLine[1].Split("count=")[1].Split('&')[0] : "3"; + var count = int.Parse(query, System.Globalization.CultureInfo.InvariantCulture); + await stream.WriteAsync("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n"u8.ToArray(), _stop.Token); + for (var i = 1; count == 0 || i <= count; i++) + { + await stream.WriteAsync(Encoding.UTF8.GetBytes($"id: {i}\ndata: {{\"n\":{i}}}\n\n"), _stop.Token); + _waiting.TrySetResult(); + await Task.Delay(30, _stop.Token); + } + + return; + } + var (body, type) = path switch { "/bytes" => (Bytes, "image/png"), diff --git a/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs b/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs index 1a2a3a2..72977a2 100644 --- a/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs +++ b/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs @@ -110,6 +110,44 @@ Task Echo(HttpContext ctx) ctx.Response.ContentType = ctx.Request.ContentType; await ctx.Request.Body.CopyToAsync(ctx.Response.Body); }); + + // A stream: server-sent events, or JSON lines with ?ndjson; ?count= of them (0: until the client goes), ?delay= ms + // apart, gzip-compressed (flushed after each) with ?gzip. Also /events/{count}/{delay}/…, for a URL that goes on. + async Task Events(HttpContext ctx, int count, int delay) + { + var ndjson = ctx.Request.Query.ContainsKey("ndjson"); + ctx.Response.ContentType = ndjson ? "application/x-ndjson" : "text/event-stream; charset=utf-8"; + var gzip = ctx.Request.Query.ContainsKey("gzip"); + if (gzip) + { + ctx.Response.Headers.ContentEncoding = "gzip"; + } + + await using var body = gzip ? new System.IO.Compression.GZipStream(ctx.Response.Body, System.IO.Compression.CompressionLevel.Fastest, leaveOpen: true) : null; + var output = body ?? ctx.Response.Body; + try + { + for (var i = 1; count == 0 || i <= count; i++) + { + var text = ndjson ? $"{{\"n\":{i}}}\n" : $"id: {i}\nevent: tick\ndata: {{\"n\":{i}}}\n\n"; + await output.WriteAsync(Encoding.UTF8.GetBytes(text), ctx.RequestAborted); + await output.FlushAsync(ctx.RequestAborted); + await ctx.Response.Body.FlushAsync(ctx.RequestAborted); + if (delay > 0) + { + await Task.Delay(delay, ctx.RequestAborted); + } + } + } + catch (OperationCanceledException) + { + // the client went + } + } + + app.Map("/events", (HttpContext ctx) => Events( + ctx, int.TryParse(ctx.Request.Query["count"], out var count) ? count : 3, int.TryParse(ctx.Request.Query["delay"], out var delay) ? delay : 0)); + app.Map("/events/{count:int}/{delay:int}/{**rest}", (HttpContext ctx, int count, int delay) => Events(ctx, count, delay)); app.MapGet("/redirect", () => Results.Redirect("/echo?redirected=true")); // Any method: redirects to ?url= with ?status= (302 by default), setting the cookie in ?cookie= if given. diff --git a/tests/TermRest.Core.Tests/StreamingTests.cs b/tests/TermRest.Core.Tests/StreamingTests.cs new file mode 100644 index 0000000..df19f3f --- /dev/null +++ b/tests/TermRest.Core.Tests/StreamingTests.cs @@ -0,0 +1,142 @@ +using System.Text; +using TermRest.Core.Http; +using TermRest.Core.Model; +using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Variables; +using Xunit; + +namespace TermRest.Core.Tests; + +/// Responses that stream (server-sent events, JSON lines): read as they arrive, and stopped keeping what arrived. +public class StreamingTests +{ + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + + private static PreparedRequest Prepare(string url, TimeSpan? timeout = null) => + new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults { Timeout = timeout }).Prepare(new HttpRequestSpec { Url = url }, null, AppContext.BaseDirectory); + + /// Keeps what it sees; stops the stream once it has seen events (or lines). + private sealed class Watcher(int stopAfter = 0, string separator = "\n\n") : IStreamWatcher, IDisposable + { + private readonly CancellationTokenSource _stop = new(); + private readonly StringBuilder _text = new(); + + public CancellationToken Stopping => _stop.Token; + + public ResponseSnapshot? Head { get; private set; } + + public int Parts { get; private set; } + + public string Text => _text.ToString(); + + public void Started(ResponseSnapshot head) => Head = head; + + public void Dispose() => _stop.Dispose(); + + public void Received(ReadOnlySpan data) + { + Parts++; + _text.Append(Encoding.UTF8.GetString(data)); + if (stopAfter > 0 && Text.Split(separator).Length > stopAfter) + { + _stop.Cancel(); + } + } + } + + [Theory] + [InlineData("events?count=3&delay=30")] + [InlineData("events?count=3&delay=30&gzip")] // decoded as it arrives + public async Task A_stream_is_read_as_it_arrives_and_its_watcher_sees_each_part(string path) + { + await using var server = await EchoServer.StartAsync(); + var request = Prepare(server.Url(path)); + using var watcher = new Watcher(); + request.StreamWatcher = watcher; + + var exchange = await new HttpExecutor().SendAsync(request, _ct); + + var response = exchange.Response!; + Assert.True(exchange.IsSuccess, exchange.ErrorMessage); + Assert.Equal((200, "text/event-stream; charset=utf-8"), (watcher.Head?.StatusCode, watcher.Head?.ContentType)); + Assert.Empty(watcher.Head!.Body); + Assert.True(watcher.Parts >= 3, $"{watcher.Parts} parts"); + var body = Encoding.UTF8.GetString(response.Body); + Assert.Equal(watcher.Text, body); + Assert.Equal(string.Concat(Enumerable.Range(1, 3).Select(n => $"id: {n}\nevent: tick\ndata: {{\"n\":{n}}}\n\n")), body); + Assert.False(response.Stopped); + Assert.Empty(request.Warnings); + if (path.EndsWith("gzip", StringComparison.Ordinal)) + { + Assert.NotEqual(response.Body.LongLength, response.ReceivedBodySize); + } + + var events = ServerSentEvents.Parse(response.Body, _ct); + Assert.Equal(["1", "2", "3"], events.Select(e => e.Id(response.Body))); + Assert.All(events, e => Assert.Equal("tick", e.Type)); + Assert.Equal("{\"n\":2}", events[1].Data(response.Body)); + } + + [Fact] + public async Task A_stream_its_watcher_stops_keeps_what_arrived() + { + await using var server = await EchoServer.StartAsync(); + var request = Prepare(server.Url("events?count=0&delay=10&ndjson")); + using var watcher = new Watcher(stopAfter: 3, separator: "\n"); + request.StreamWatcher = watcher; + + var exchange = await new HttpExecutor().SendAsync(request, _ct); + + Assert.False(exchange.Cancelled); + var response = exchange.Response!; + Assert.True(response.Stopped); + Assert.StartsWith("{\"n\":1}\n{\"n\":2}\n{\"n\":3}\n", Encoding.UTF8.GetString(response.Body), StringComparison.Ordinal); + Assert.Equal(["The stream was stopped: its body is what arrived until then."], request.Warnings); + } + + [Fact] + public async Task The_request_timeout_stops_a_stream_and_keeps_what_arrived() + { + await using var server = await EchoServer.StartAsync(); + var request = Prepare(server.Url("events?count=0&delay=20"), timeout: TimeSpan.FromMilliseconds(400)); + + var exchange = await new HttpExecutor().SendAsync(request, _ct); + + var response = exchange.Response!; + Assert.True(response.Stopped); + Assert.StartsWith("id: 1\nevent: tick\n", Encoding.UTF8.GetString(response.Body), StringComparison.Ordinal); + Assert.Equal(["The stream was stopped at the request timeout (400 ms): its body is what arrived until then."], request.Warnings); + } + + [Fact] + public async Task Cancelling_the_request_while_it_streams_keeps_nothing() + { + await using var server = await EchoServer.StartAsync(); + var request = Prepare(server.Url("events?count=0&delay=10")); + using var cancel = CancellationTokenSource.CreateLinkedTokenSource(_ct); + cancel.CancelAfter(300); + + var exchange = await new HttpExecutor().SendAsync(request, cancel.Token); + + Assert.True(exchange.Cancelled); + Assert.Null(exchange.Response); + } + + [Fact] + public void Server_sent_events_are_read_as_the_html_standard_reads_them() + { + var body = Encoding.UTF8.GetBytes( + "\uFEFF: a comment\r\n" + + "data: first\r\ndata: two lines\r\n\r\n" + + "event: update\nid: 7\ndata: {\"a\":1}\n\n" + + "event: no data\n\n" + + "data: after\rid\r\r" + // an id with no value clears it + "data: the last, never ended\n"); + + var events = ServerSentEvents.Parse(body, _ct); + + Assert.Equal([("message", null), ("update", "7"), ("message", "")], events.Select(e => (e.Type, e.Id(body)))); + Assert.Equal(["first\n two lines", "{\"a\":1}", "after"], events.Select(e => e.Data(body))); + Assert.StartsWith(": a comment", Encoding.UTF8.GetString(body, events[0].Start, events[0].Length), StringComparison.Ordinal); + } +} diff --git a/tests/TermRest.Tui.Tests/MainWindowTests.cs b/tests/TermRest.Tui.Tests/MainWindowTests.cs index 4256a2b..549b4c9 100644 --- a/tests/TermRest.Tui.Tests/MainWindowTests.cs +++ b/tests/TermRest.Tui.Tests/MainWindowTests.cs @@ -572,6 +572,69 @@ private static void OnScreen(string expected, string screen) } } + [Fact] + public async Task A_stream_is_shown_as_it_arrives_and_esc_stops_it_keeping_its_events() + { + await using var server = await TermRest.Core.Tests.Infrastructure.EchoServer.StartAsync(); + using var ui = new Harness(_directory, runner => runner.LocalVariables["baseUrl"] = server.Url("events/0/20")); + var (live, stopped, events) = ("", "", ""); + var deadline = DateTime.UtcNow.AddSeconds(20); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(300), () => + { + ui.App.InjectKey(Key.F5); + return false; + }); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + var screen = ui.Screen(); + if (DateTime.UtcNow > deadline) + { + (live, stopped, events) = (live.Length > 0 ? live : screen, stopped.Length > 0 ? stopped : screen, screen); + ui.App.RequestStop(); + return false; + } + + if (live.Length == 0) + { + if (screen.Contains("200 OK · streaming ·", StringComparison.Ordinal) && screen.Contains("data: {\"n\":", StringComparison.Ordinal)) + { + live = screen; + ui.App.InjectKey(Key.Esc); + } + } + else if (stopped.Length == 0) + { + if (screen.Contains("stream stopped", StringComparison.Ordinal)) + { + stopped = screen; + var tab = ui.Find("│Events ("); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(tab.X + 2, tab.Y))); + } + } + else + { + events = screen; + ui.App.RequestStop(); + return false; + } + + return true; + }); + + ui.App.Run(ui.Window); + + OnScreen("200 OK · streaming ·", live); + OnScreen("so far · Esc stops it", live); + OnScreen("⟦ Stop ⟧", live); + OnScreen("· stream stopped", stopped); + OnScreen("Event", events); + OnScreen("tick", events); + OnScreen("{\"n\":1}", events); + var response = ui.Window.ResponsePane.Exchange!.Response!; + Assert.True(response.Stopped); + Assert.StartsWith("id: 1\nevent: tick\ndata: {\"n\":1}\n\n", System.Text.Encoding.UTF8.GetString(response.Body), StringComparison.Ordinal); + } + /// A screen's text with its lines joined and its box-drawing characters left out, so a check doesn't depend on where a dialog wraps. private static string Unwrapped(string screen) => System.Text.RegularExpressions.Regex.Replace(screen, @"[\s\u2500-\u259F]+", " "); @@ -1894,7 +1957,7 @@ public void Keyboard_help_shows_the_shortcuts_in_aligned_columns() // Each column starts at the same place on every row (a message box would center every line on its own). int Column(params string[] texts) => Assert.Single(texts.Select(t => At(screen, t).X).Distinct()); var keys = Column("F5, Ctrl+Enter", "Esc ", "F2 ", "Insert ", "F8 ", "F9 "); - var actions = Column("Send (again to cancel)", "Cancel a running request", "Rename tree item", "Add a table row", "Client certificates", "Collections ⇄ History"); + var actions = Column("Send (again to cancel)", "Cancel a request, stop a stream", "Rename tree item", "Add a table row", "Client certificates", "Collections ⇄ History"); var moreKeys = Column("F12 ", "Tab, Shift+Tab", "←, → (tab row)", "Shift+F10", "Ctrl+L", "Ctrl+F ", "F3, Shift+F3"); var moreActions = Column("Start / stop recording", "Next / previous field", "Previous / next tab", "Focus the URL bar", "Find in the response", "Next / previous match"); Assert.True(keys < actions && actions < moreKeys && moreKeys < moreActions, screen); From 8ddae4329c38c5300783ee12773d6d152235b9cc Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Wed, 18 Nov 2026 00:35:44 -0700 Subject: [PATCH 07/11] Core, CLI and TUI: fixes from the review of the five features Data runs and proxies: a data file's values named like secrets (apiToken) are redacted in recordings and reports as variables are; a JSON data file with a name twice in one object is refused when it is read, before the run, rather than failing in the middle of it. Proxy sign-in: a password left masked in Settings moves with the sign-in when the proxy setting changes in the same save (also from the system's proxy); the credentials file is read again before each save, so sign-ins another TermRest saved meanwhile stay; an empty password is kept without DPAPI, which refused it, and a password that cannot be encrypted is reported rather than crashing the dialog. --proxy-user and the saved sign-in now take precedence over a user and password in HTTPS_PROXY, which .NET preferred. Streams: once the body is read, Esc, Stop and Ctrl+C cancel the scripts that run on it again (IStreamWatcher.Ended), rather than doing nothing. send writes a stream to a console as text, decoded as UTF-8 across parts, rather than as bytes in the console's code page; to a pipe through its raw handle, so a reader that quits (| head) stops the stream rather than going unnoticed. Opening another request stops a stream still arriving, keeping what arrived. Raw deflate streams are decoded (their first byte tells, as for whole bodies), and an empty event: field leaves the type "message", as browsers have it. Script requests: a client certificate's {{passphrase}} (and a private_key_jwt signing certificate's) is resolved as for any request, and the request's warnings follow its line in the script output; an answer to the runtime is written whole even when the scripts are cancelled meanwhile. Postman v3 examples: a rename followed by a failed write no longer leaves a duplicate, an example saved for a request whose file was deleted writes the request again, and a copied example stays right after its original after a reload. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 10 +- src/TermRest.Cli/SendCommand.cs | 59 ++++++- src/TermRest.Core/Http/HttpExecutor.cs | 107 +++++++++--- src/TermRest.Core/Http/RequestPreparer.cs | 10 +- src/TermRest.Core/Http/ResponseStreams.cs | 9 +- src/TermRest.Core/IO/Dpapi.cs | 6 +- src/TermRest.Core/IO/StandardOutput.cs | 43 +++++ .../Postman/V3/V3CollectionStorage.cs | 56 ++++++- src/TermRest.Core/Scripting/ScriptWorker.cs | 4 +- .../Workspace/IterationDataFile.cs | 42 +++++ .../Workspace/ProxyCredentialStore.cs | 17 +- .../Workspace/RequestRunner.Scripts.cs | 19 ++- src/TermRest.Core/Workspace/RequestRunner.cs | 5 + src/TermRest.Tui/Dialogs/SettingsDialog.cs | 19 ++- src/TermRest.Tui/MainWindow.cs | 15 +- src/TermRest.Tui/Views/LiveResponse.cs | 23 ++- src/TermRest.Tui/Views/ResponseView.cs | 9 +- tests/TermRest.Cli.Tests/CommandLineTests.cs | 27 +++ .../Infrastructure/Termrest.cs | 19 ++- tests/TermRest.Core.Tests/ExampleTests.cs | 47 ++++++ .../Infrastructure/EchoServer.cs | 14 +- .../TermRest.Core.Tests/IterationDataTests.cs | 20 +++ tests/TermRest.Core.Tests/ProxyTests.cs | 10 ++ .../TermRest.Core.Tests/ScriptRequestTests.cs | 6 +- tests/TermRest.Core.Tests/StreamingTests.cs | 15 +- tests/TermRest.Tui.Tests/MainWindowTests.cs | 155 ++++++++++++++++++ 26 files changed, 684 insertions(+), 82 deletions(-) create mode 100644 src/TermRest.Core/IO/StandardOutput.cs diff --git a/README.md b/README.md index 935d4ac..a1124f7 100644 --- a/README.md +++ b/README.md @@ -118,10 +118,10 @@ A `settings.json` or `certificates.json` that can't be read (invalid JSON, a mer A proxy URL in `.termrest/settings.json` (`proxy`) is used only once you allow it for that workspace folder: the file comes with the repository you clone, and a proxy sees every request, with its credentials. Until then, requests use the system's proxy settings (the OS's, `HTTPS_PROXY`), as with `system`; the status bar and *Help › Workspace info* say so, and `send` and `run` print a warning (the proxy's password masked). Saving in *Tools › Settings* allows the proxy shown there; the dialog shows its password masked too, and keeps it while the mask is left in place (also when only the host or port changes). The approval is kept per workspace folder in your user settings (`allowedProxies`) as a SHA-256 hash, never the proxy's URL, which can hold a password; when the file names another proxy (after a `git pull`, say), that one must be allowed again. `system` and `none` need no approval, and the file's other settings, TLS verification and the CA bundle included, apply as they are. -**Proxy sign-in.** A proxy that asks for a user name and password (407 Proxy Authentication Required) gets the ones given for it, answered with Basic, Digest, NTLM or Negotiate (Kerberos), as the proxy asks: +**Proxy sign-in.** A proxy that asks for a user name and password (407 Proxy Authentication Required) gets the ones given for it, answered with Basic, Digest, NTLM or Negotiate (Kerberos), as the proxy asks; the first of: -- in *Tools › Settings › Proxy sign-in*: kept for that proxy (or for the system's) in `proxy-credentials.json` in your user settings folder, never in the workspace. Only you can read the file, and on Windows the password in it is also encrypted for your account (DPAPI). A password left masked stays as it was; clear the user name to forget them; - with `--proxy-user user:password` on `send` and `run`, or `--proxy-user user` to type the password (`DOMAIN\user` for NTLM); +- in *Tools › Settings › Proxy sign-in*: kept for that proxy (or for the system's) in `proxy-credentials.json` in your user settings folder, never in the workspace. Only you can read the file, and on Windows the password in it is also encrypted for your account (DPAPI). A password left masked stays as it was, also when you name another proxy in the same save (the sign-in moves to it); clear the user name to forget them. The file is shared by all your workspaces, and read again before each save, so sign-ins another TermRest saved meanwhile stay; - in the proxy's URL, `http://user:password@proxy:3128`, also in `HTTPS_PROXY`. Without any, a proxy that asks for NTLM or Negotiate, as corporate proxies do, gets your own sign-in (as browsers give it); one that asks for Basic or Digest gets nothing, and the 407 comes back with a note that says how to give one. `--proxy ` (`-x`; `host:port` works too, as in curl) sets the proxy for `send` and `run` in place of the workspace's. @@ -138,7 +138,7 @@ A request that is not in a collection (a new one, an imported curl command, or o **Saved examples** (Postman's saved responses) are listed under their request in the tree, as `e.g. `. *Save as example* (on the response's status line, or *Request › Save response as example…*) saves the response shown as an example of its request: its status, its headers as the server sent them, its body as text (a binary body is left out, and a body over 1 MB asks first, as it goes into the collection file), and the request as the editor has it; a response opened from the history goes to the request it was sent from. Opening an example shows its request (method, URL, parameters, headers and body) in the request editor and its response in the response pane's place, both editable: the status code and reason, the body's language (with *Beautify* for JSON), the body and the headers. *Ctrl+S* saves them with the rest. An example is not sent; open its request to send it. Rename, duplicate or delete examples from the tree, as requests. In a v3 collection an example is a file of its own (see [Postman v3 (YAML) collections](#postman-v3-yaml-collections)), read only when its request is first expanded or opened. -**Streams.** A response of server-sent events (`text/event-stream`) or JSON lines (`application/x-ndjson`, `application/jsonl`, `application/json-seq`, `application/stream+json`) is shown as it arrives: its status, its headers, and the end of its body (the last 64 KB), followed as it grows, four times a second at most. **Esc**, or *Stop* (the Send button meanwhile), ends it and keeps what arrived as its response, as a whole one would be: its post-response scripts run on it, it goes to the history and the recording, and a warning says it was stopped (`· stream stopped` on the status line). A request timeout that ends a stream keeps it the same way (none is set by default), and so does a connection that ends before the stream does. Once it ends, it is shown whole, and server-sent events get an *Events* tab: one row per event (its type, its id and the start of its data); Enter or a double-click shows an event's data in full, JSON pretty-printed, to read or copy. Events keep only where they are in the body, so a long stream's thousands of events take little memory. A stream is decoded as it arrives (gzip, deflate, br), and the maximum response size still applies: it stops a stream that reaches it. On the command line, see `send` below. +**Streams.** A response of server-sent events (`text/event-stream`) or JSON lines (`application/x-ndjson`, `application/jsonl`, `application/json-seq`, `application/stream+json`) is shown as it arrives: its status, its headers, and the end of its body (the last 64 KB), followed as it grows, four times a second at most. **Esc**, or *Stop* (the Send button meanwhile), ends it and keeps what arrived as its response, as a whole one would be: its post-response scripts run on it (Esc or *Cancel* then cancels them, as for any request), it goes to the history and the recording, and a warning says it was stopped (`· stream stopped` on the status line). Opening another request stops a stream still arriving the same way: nothing would show it any more. A request timeout that ends a stream keeps it the same way (none is set by default), and so does a connection that ends before the stream does. Once it ends, it is shown whole, and server-sent events get an *Events* tab: one row per event (its type, its id and the start of its data); Enter or a double-click shows an event's data in full, JSON pretty-printed, to read or copy. Events keep only where they are in the body, so a long stream's thousands of events take little memory. A stream is decoded as it arrives (gzip, deflate, br), and the maximum response size still applies: it stops a stream that reaches it. On the command line, see `send` below. | Key | Action | Key | Action | |---|---|---|---| @@ -227,7 +227,7 @@ A runtime answers in about a millisecond once started; starting takes 0.1–0.3 - **Order:** each phase runs the scripts of the collection, then the folders (outermost first), then the request, one at a time: each script sees the variables and request changes of the ones before it. - **A failing pre-request script stops the request.** This covers an exception, a syntax or compile error, and a timeout. The request is not sent, nor added to the history or a recording, and the error is shown with the script's line. - **Time limit:** each phase may take 30 seconds (building C# scripts does not count); the runtime is then stopped and started again for the next script. *Tools › Scripts › Stop scripts* stops a script that runs at once; its request says it was stopped (`Python was stopped while the scripts ran.`). -- **Requests that scripts send** (`pm.sendRequest`, `tr.send_request`, `tr.SendRequest`, `$tr.SendRequest`) go through TermRest, as its own requests do: with the workspace's client certificates (matched by URL), CA bundle and SSL verification, proxy and its sign-in, timeout, redirects and response size limit, and the session's cookies. They take a URL, or a request as Postman's `pm.sendRequest` takes it: `url`, `method`, `header` (Postman's list, or a map of names to values), `body` (text, Postman's `{mode, raw …}`, or any other JSON, sent as JSON) and `auth` (their own: none is inherited). As in Postman, `{{variables}}` in them are sent as written: replace them first (`replaceIn`, `replace_in`). Each one adds a line to the script's output, without the URL's query (`POST https://api.example.com/login → 200 OK (85 ms)`); they are recorded while you record, and not kept in the history. They count towards the phase's time limit, and those still running when the scripts end are cancelled. JavaScript scripts can send several at a time (six at once, the others wait their turn), the other languages one at a time. +- **Requests that scripts send** (`pm.sendRequest`, `tr.send_request`, `tr.SendRequest`, `$tr.SendRequest`) go through TermRest, as its own requests do: with the workspace's client certificates (matched by URL), CA bundle and SSL verification, proxy and its sign-in, timeout, redirects and response size limit, and the session's cookies. They take a URL, or a request as Postman's `pm.sendRequest` takes it: `url`, `method`, `header` (Postman's list, or a map of names to values), `body` (text, Postman's `{mode, raw …}`, or any other JSON, sent as JSON) and `auth` (their own: none is inherited). As in Postman, `{{variables}}` in them are sent as written: replace them first (`replaceIn`, `replace_in`). Each one adds a line to the script's output, without the URL's query (`POST https://api.example.com/login → 200 OK (85 ms)`), followed by its warnings (a client certificate that could not be loaded …); the workspace's settings, such as a certificate's `{{passphrase}}`, are resolved as for any request. They are recorded while you record, and not kept in the history. They count towards the phase's time limit, and those still running when the scripts end are cancelled. JavaScript scripts can send several at a time (six at once, the others wait their turn), the other languages one at a time. - **Working folder:** the runtimes run in the workspace folder, so scripts can import your own modules from it (`import helpers`, `require('./helpers')`, `Import-Module ./Helpers.psm1`) and read its files. Python and PowerShell modules load once per process; *Tools › Scripts › Stop scripts* reloads them. - **Values are text:** a variable or header set to `42` reads back as `"42"` in the next request or phase; a date or time as ISO 8601 text (`2024-01-02T03:04:05+00:00`, `2024-01-02`), and a GUID, URL or decimal as its text; lists and objects as JSON. @@ -761,7 +761,7 @@ The `--report-json` report redacts secrets the way [recordings](#recording-reque `send --filter ` prints only the values a JSONPath query ([RFC 9535](https://www.rfc-editor.org/rfc/rfc9535), as in the UI's Filter) selects in a JSON body, as a JSON array: two-space indented, or on one line with `--raw`; with `-o`, it writes them to the file instead of the body. A query that isn't valid JSONPath is a usage error, reported with where it goes wrong before anything is sent; a body that isn't JSON (or binary, or empty) makes `send` exit with code 1. -`send` prints a response that streams ([server-sent events or JSON lines](#streams)) to standard output as it arrives, after its headers with `-i`, and says so on standard error. The first **Ctrl+C** stops it and keeps what arrived as the response: its tests run, it is recorded, and `send` exits as it does for any response (a second Ctrl+C cancels, a third ends TermRest). With `-o` or `--filter`, the body is written when the stream ends. `run` reads a stream until the server ends it; `--timeout` stops it, keeping what arrived. +`send` prints a response that streams ([server-sent events or JSON lines](#streams)) to standard output as it arrives, after its headers with `-i`, and says so on standard error. The first **Ctrl+C** stops it and keeps what arrived as the response: its tests run, it is recorded, and `send` exits as it does for any response (a second Ctrl+C cancels, a third ends TermRest). A program that reads only part of it and quits (`| head -n 20`) stops it the same way. With `-o` or `--filter`, the body is written when the stream ends. `run` reads a stream until the server ends it; `--timeout` stops it, keeping what arrived. `send` exits with 0 when done; 1 when there was no response, a test or script failed, the body couldn't be saved with `-o` or filtered with `--filter`, the recording wasn't saved, or files of the collection or the workspace settings can't be read; 2 for a usage problem (an unknown or ambiguous request or `-e` environment, one `--curl` can't export, or a `--filter` query that isn't JSONPath); 22 for HTTP status 400 or more with `--fail`; 63 when the response body was cut at the maximum response size (*Tools › Settings*, `maxResponseSizeMb`, 50 MB), so what `-o` or standard output received is only its start; 130 when cancelled. Warnings raised while sending (a redirect not followed, a header left out, a cut body) are printed after the response. A name that matches several requests, in the workspace's collections or in one collection, is reported as ambiguous: give its path (`Folder/Name`) or its collection. So is an `-e` name that several environments of the workspace have: nothing is sent, and the error lists their files; pass one of them with `-e` instead (a JSON or YAML environment file). Without `-e`, the workspace's active environment is used. diff --git a/src/TermRest.Cli/SendCommand.cs b/src/TermRest.Cli/SendCommand.cs index b3e655e..012cd0c 100644 --- a/src/TermRest.Cli/SendCommand.cs +++ b/src/TermRest.Cli/SendCommand.cs @@ -1,6 +1,8 @@ +using System.Buffers; using System.CommandLine; using System.Text; using TermRest.Core.Http; +using TermRest.Core.IO; using TermRest.Core.Json; using TermRest.Core.Postman; @@ -339,12 +341,15 @@ private static void PrintVerbose(HttpExchange exchange) /// /// A response that streams (server-sent events, JSON lines): its body printed to standard output as it arrives (with -i, /// after its headers), unless print is off (-o, --filter: they get it whole). The first Ctrl+C stops it, keeping - /// what arrived, which is then reported as the response. + /// what arrived, which is then reported as the response; once its body is read, Ctrl+C cancels as before (the scripts + /// that run on it). A console gets it as text, as the rest of the output; a pipe or file the bytes as they are, and a pipe + /// whose reader went (| head -n 5) stops it, as nothing reads it any more. /// private sealed class ConsoleStream(bool print, bool include) : IStreamWatcher, IDisposable { private readonly CancellationTokenSource _stop = new(); private Stream? _stdout; + private Decoder? _text; // a console: UTF-8 parts as text (a character split between two parts too), as Console.Out writes text public CancellationToken Stopping => _stop.Token; @@ -372,30 +377,55 @@ public void Started(ResponseSnapshot head) Console.Out.Flush(); } - _stdout = Console.OpenStandardOutput(); + if (Console.IsOutputRedirected) + { + _stdout = StandardOutput.OpenPipe() ?? Console.OpenStandardOutput(); + } + else + { + _text = Encoding.UTF8.GetDecoder(); + } + Printed = true; } public void Received(ReadOnlySpan data) { - if (_stdout is null || data.IsEmpty) + if (data.IsEmpty) { return; } try { - _stdout.Write(data); - _stdout.Flush(); + if (_text is not null) + { + Write(data, flush: false); + } + else if (_stdout is not null) + { + _stdout.Write(data); + _stdout.Flush(); + } } catch (IOException) { - // What reads the output went (| head -n 5): the stream is stopped, as nothing reads it any more. - _stdout = null; + // What reads the output went: the stream is stopped, as nothing reads it any more. + (_stdout, _text) = (null, null); Stop(); } } + public void Ended() + { + CliApp.Interrupt = null; + if (_text is not null) + { + Write([], flush: true); // the end of a character the stream did not finish + _text = null; + } + } + /// The request ended: Ctrl+C stops the command again. public void Dispose() { @@ -404,6 +434,21 @@ public void Dispose() _stop.Dispose(); } + private void Write(ReadOnlySpan data, bool flush) + { + var chars = ArrayPool.Shared.Rent(Math.Max(1, Encoding.UTF8.GetMaxCharCount(data.Length))); + try + { + var count = _text!.GetChars(data, chars, flush); + Console.Out.Write(chars, 0, count); + Console.Out.Flush(); + } + finally + { + ArrayPool.Shared.Return(chars); + } + } + private void Stop() { try diff --git a/src/TermRest.Core/Http/HttpExecutor.cs b/src/TermRest.Core/Http/HttpExecutor.cs index 9b1ef1a..b67e9d0 100644 --- a/src/TermRest.Core/Http/HttpExecutor.cs +++ b/src/TermRest.Core/Http/HttpExecutor.cs @@ -231,8 +231,13 @@ private SocketsHttpHandler CreateHandler(PreparedRequest request, ConnectionCapt // Its sign-in: the user name and password given for it, else the user's own, which .NET sends only to an NTLM or // Negotiate (Kerberos) challenge, never to a Basic or Digest one. A proxy HTTPS_PROXY names with a user and - // password signs in with those. + // password signs in with those, unless others were given for it: .NET would prefer the URL's. handler.DefaultProxyCredentials = request.ProxyCredential ?? CredentialCache.DefaultCredentials; + if (request.ProxyCredential is { } signIn && capture.Proxy.Credentials is not null) + { + handler.Proxy = capture.Proxy = new SignedInProxy(capture.Proxy, signIn); + } + break; case "none": handler.UseProxy = false; @@ -577,7 +582,6 @@ private static async Task ReadStreamAsync(HttpExchange exchange, HttpResponseMes { var request = exchange.Request; var watcher = request.StreamWatcher; - watcher?.Started(Snapshot(response, [], truncated: false, received: 0)); using var stop = CancellationTokenSource.CreateLinkedTokenSource(watcher?.Stopping ?? CancellationToken.None, timeout?.Token ?? CancellationToken.None); using var reading = CancellationTokenSource.CreateLinkedTokenSource(stop.Token, cancellationToken); var codings = ContentCodings(response.Content.Headers); @@ -588,23 +592,16 @@ private static async Task ReadStreamAsync(HttpExchange exchange, HttpResponseMes codings.Clear(); } - var wire = new CountingStream(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)); - Stream source = wire; - for (var i = codings.Count - 1; i >= 0; i--) - { - source = codings[i] switch - { - "br" => new BrotliStream(source, CompressionMode.Decompress), - "deflate" => new ZLibStream(source, CompressionMode.Decompress), - _ => new GZipStream(source, CompressionMode.Decompress), - }; - } - using var body = new MemoryStream(); var chunk = ArrayPool.Shared.Rent(16 * 1024); var (truncated, stopped) = (false, false); + ReadThrough? wire = null; + Stream? source = null; + watcher?.Started(Snapshot(response, [], truncated: false, received: 0)); try { + wire = new ReadThrough(await response.Content.ReadAsStreamAsync(reading.Token).ConfigureAwait(false)); + source = await DecodingAsync(wire, codings, reading.Token).ConfigureAwait(false); int read; while ((read = await source.ReadAsync(chunk.AsMemory(), reading.Token).ConfigureAwait(false)) > 0) { @@ -637,19 +634,66 @@ private static async Task ReadStreamAsync(HttpExchange exchange, HttpResponseMes finally { ArrayPool.Shared.Return(chunk); - await source.DisposeAsync().ConfigureAwait(false); + if (source is not null) + { + await source.DisposeAsync().ConfigureAwait(false); + } + else if (wire is not null) + { + await wire.DisposeAsync().ConfigureAwait(false); + } + + watcher?.Ended(); } - exchange.Response = Snapshot(response, ToArray(body), truncated, wire.Count, stopped); + exchange.Response = Snapshot(response, ToArray(body), truncated, wire?.Count ?? 0, stopped); if (warning is not null) { request.Warnings.Add(warning); } } - /// Counts what is read through it: the size of a streamed body as received, before its content codings are removed. - private sealed class CountingStream(Stream inner) : Stream + /// + /// A streamed body with its content codings removed as it is read, the last one applied first. Deflate is zlib data, as + /// the standard has it, or raw deflate data, as some servers send: its first byte tells, as for a whole body (see + /// ). + /// + private static async Task DecodingAsync(Stream source, List codings, CancellationToken cancellationToken) { + try + { + for (var i = codings.Count - 1; i >= 0; i--) + { + if (codings[i] == "deflate") + { + var first = new byte[1]; + var read = await source.ReadAsync(first, cancellationToken).ConfigureAwait(false); + source = new ReadThrough(source, first.AsMemory(0, read)); + source = read == 1 && (first[0] & 0x0F) != 8 ? new DeflateStream(source, CompressionMode.Decompress) : new ZLibStream(source, CompressionMode.Decompress); + } + else + { + source = codings[i] == "br" ? new BrotliStream(source, CompressionMode.Decompress) : new GZipStream(source, CompressionMode.Decompress); + } + } + + return source; + } + catch + { + await source.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + /// + /// Reads , after (bytes read from it already, to look at them), and counts + /// what it reads from it: the size of a streamed body as received, before its content codings are removed. + /// + private sealed class ReadThrough(Stream inner, ReadOnlyMemory prefix = default) : Stream + { + private ReadOnlyMemory _prefix = prefix; + public long Count { get; private set; } public override bool CanRead => true; @@ -666,10 +710,12 @@ public override long Position set => throw new NotSupportedException(); } - public override int Read(byte[] buffer, int offset, int count) => Counted(inner.Read(buffer, offset, count)); + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) => _prefix.IsEmpty ? Counted(inner.Read(buffer)) : Replay(buffer); public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => - Counted(await inner.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)); + _prefix.IsEmpty ? Counted(await inner.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) : Replay(buffer.Span); public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); @@ -705,6 +751,27 @@ private int Counted(int read) Count += read; return read; } + + private int Replay(Span buffer) + { + var count = Math.Min(buffer.Length, _prefix.Length); + _prefix.Span[..count].CopyTo(buffer); + _prefix = _prefix[count..]; + return count; + } + } + + /// + /// The system's proxy () with the user name and password given for it: .NET signs in + /// with a proxy's own credentials (those of a user and password in HTTPS_PROXY) before the handler's. + /// + private sealed class SignedInProxy(IWebProxy proxy, ICredentials credentials) : IWebProxy + { + public ICredentials? Credentials { get; set; } = credentials; + + public Uri? GetProxy(Uri destination) => proxy.GetProxy(destination); + + public bool IsBypassed(Uri host) => proxy.IsBypassed(host); } /// A body's content codings in the order they were applied, leaving out identity (and "none", which some servers send). diff --git a/src/TermRest.Core/Http/RequestPreparer.cs b/src/TermRest.Core/Http/RequestPreparer.cs index 5e20d41..fa3b5ba 100644 --- a/src/TermRest.Core/Http/RequestPreparer.cs +++ b/src/TermRest.Core/Http/RequestPreparer.cs @@ -45,7 +45,13 @@ public sealed class ExecutionDefaults } /// Turns an editable into a . -public sealed class RequestPreparer(VariableResolver variables, ClientCertificateProvider? certificates, ExecutionDefaults defaults) +/// +/// The variables of the workspace's own settings, such as a client certificate's {{passphrase}}: those of +/// by default. A request that a script sends replaces none of its own, but its certificates' +/// passphrases are replaced as for any request. +/// +public sealed class RequestPreparer(VariableResolver variables, ClientCertificateProvider? certificates, ExecutionDefaults defaults, + VariableResolver? settingsVariables = null) { private static readonly System.Security.Cryptography.X509Certificates.X509Certificate2Collection EmptyTrust = []; @@ -278,7 +284,7 @@ private static string WithScheme(string url) return Environment.GetEnvironmentVariable(value[4..]); } - return Variables.Resolve(value); + return (settingsVariables ?? Variables).Resolve(value); } /// diff --git a/src/TermRest.Core/Http/ResponseStreams.cs b/src/TermRest.Core/Http/ResponseStreams.cs index 7014824..5cbda71 100644 --- a/src/TermRest.Core/Http/ResponseStreams.cs +++ b/src/TermRest.Core/Http/ResponseStreams.cs @@ -17,6 +17,12 @@ public interface IStreamWatcher /// A part of the body as it arrived, decoded (gzip …), within the maximum response size. void Received(ReadOnlySpan data); + + /// + /// The body has been read: the stream ended, was stopped, or failed. What follows (post-response scripts …) is no longer + /// the stream's: stopping it does nothing now. + /// + void Ended(); } /// @@ -99,7 +105,8 @@ public static List Parse(byte[] body, CancellationToken cancell { if (hasData) { - events.Add(new ServerSentEvent(eventStart, eventEnd - eventStart, type ?? "message", idLine)); + // An empty event: field leaves the type message, as browsers have it. + events.Add(new ServerSentEvent(eventStart, eventEnd - eventStart, type is { Length: > 0 } ? type : "message", idLine)); if ((events.Count & 1023) == 0) { cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/TermRest.Core/IO/Dpapi.cs b/src/TermRest.Core/IO/Dpapi.cs index 1d5af18..5d2017b 100644 --- a/src/TermRest.Core/IO/Dpapi.cs +++ b/src/TermRest.Core/IO/Dpapi.cs @@ -21,8 +21,10 @@ internal static partial class Dpapi private static unsafe byte[] Transform(ReadOnlySpan data, ReadOnlySpan entropy, bool protect) { - fixed (byte* input = data) - fixed (byte* salt = entropy) + // An empty span is pinned as a null pointer, which DPAPI refuses: a byte stands in for it (the size stays 0). + ReadOnlySpan placeholder = [0]; + fixed (byte* input = data.IsEmpty ? placeholder : data) + fixed (byte* salt = entropy.IsEmpty ? placeholder : entropy) { var inBlob = new Blob { Size = data.Length, Data = (IntPtr)input }; var saltBlob = new Blob { Size = entropy.Length, Data = (IntPtr)salt }; diff --git a/src/TermRest.Core/IO/StandardOutput.cs b/src/TermRest.Core/IO/StandardOutput.cs new file mode 100644 index 0000000..fbe9f17 --- /dev/null +++ b/src/TermRest.Core/IO/StandardOutput.cs @@ -0,0 +1,43 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace TermRest.Core.IO; + +/// Standard output as written to by a command that streams what it receives. +public static partial class StandardOutput +{ + /// + /// Standard output, when it is a pipe, as a stream whose writes fail with an once the program + /// reading it has ended (| head -n 5): .NET's console streams take that for a write that succeeded, so a command + /// would go on receiving for nothing. Null when it is not a pipe (a file, a console …). + /// + public static Stream? OpenPipe() + { + try + { + var handle = OperatingSystem.IsWindows() ? new SafeFileHandle(GetStdHandle(-11), ownsHandle: false) : new SafeFileHandle(1, ownsHandle: false); + if (handle.IsInvalid) + { + return null; + } + + var stream = new FileStream(handle, FileAccess.Write, bufferSize: 0); + if (!stream.CanSeek) + { + return stream; + } + + stream.Dispose(); // a file: written as before, where the console stream writes + } + catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException or NotSupportedException) + { + // not a handle a stream can write to: the console stream does + } + + return null; + } + + [LibraryImport("kernel32.dll")] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + private static partial IntPtr GetStdHandle(int handle); +} diff --git a/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs b/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs index 56ad90b..f670a5f 100644 --- a/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs +++ b/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs @@ -366,6 +366,21 @@ private static void RemoveWritten(string directory, string? created) } } + /// + /// Whether saving writes or deletes example files of a request: its examples were loaded, and some are new, edited, + /// renamed or deleted (see ). The snapshot that tells whether a request changed leaves them out. + /// + private bool ExamplesChange(JsonObject item) + { + if (IsFolder(item) || !_examples.TryGetValue(item, out var loaded)) + { + return false; + } + + var examples = (item["response"] as JsonArray ?? []).OfType().ToList(); + return examples.Count != loaded.Count || examples.Any(e => !loaded.TryGetValue(e, out var origin) || !JsonNode.DeepEquals(e, origin.Baseline)); + } + /// /// Writes a request's saved examples where they changed: new ones as new files named for them (a name a file can't have /// is kept in it, as Postman keeps it), edited ones in place (only the edited entries), renamed ones under their new @@ -423,11 +438,14 @@ private static void RemoveWritten(string directory, string? created) } var order = loaded.Values.Select(o => OrderValue(o.V3["order"])).Max() ?? 0; - foreach (var json in examples) + double? previous = null; // the order of the example before, as the request shows them + for (var index = 0; index < examples.Count; index++) { + var json = examples[index]; var name = json["name"].GetString() is { Length: > 0 } given ? given : "Example"; if (loaded.TryGetValue(json, out var origin)) { + previous = OrderValue(origin.V3["order"]) ?? previous; if (JsonNode.DeepEquals(json, origin.Baseline)) { continue; @@ -453,6 +471,7 @@ private static void RemoveWritten(string directory, string? created) if (path != origin.Path && File.Exists(origin.Path)) { File.Move(origin.Path, path); // a new name, also one that differs in case only + origin.Path = path; // where it is now, should writing it fail: the next save finds it there } CreateFolder(folder); @@ -471,8 +490,26 @@ private static void RemoveWritten(string directory, string? created) taken.Add(stem); var created = V3Convert.ExampleToV3(json); NameExample(created, name, stem); - order = (Math.Floor(order / 1000) + 1) * 1000; - created["order"] = order < 1e15 ? JsonValue.Create((long)order) : JsonValue.Create(order); + + // Where the request shows it (a copy right after its original): between its neighbors, after the last in steps of 1000. + var next = examples.Skip(index + 1).Select(e => loaded.TryGetValue(e, out var o) ? OrderValue(o.V3["order"]) : null).FirstOrDefault(v => v is not null); + double value; + if (next is { } high && (previous is null || high > previous)) + { + value = previous is { } low ? low + ((high - low) / 2) : high - 1000; + if (previous is { } below && high - below >= 2) + { + value = Math.Floor(value); + } + } + else + { + order = (Math.Floor(order / 1000) + 1) * 1000; + value = order; + } + + previous = value; + created["order"] = value == Math.Floor(value) && Math.Abs(value) < 1e15 ? JsonValue.Create((long)value) : JsonValue.Create(value); CreateFolder(folder); var path = Path.Combine(folder, stem + V3Names.ExampleSuffix); var (text, info) = YamlFile.WriteChecked(null, created, Style, path, NewFile, out var written); @@ -642,8 +679,9 @@ void WriteAnew(JsonObject item) } } - // Whether this save writes the item or puts it in place: it is new, moved, reordered or edited. A folder without an order - // gets one whenever its siblings change: while it is gone (see below), that alone is no change (see step 4). + // Whether this save writes the item or puts it in place: it is new, moved, reordered or edited, or its examples are. A + // folder without an order gets one whenever its siblings change: while it is gone (see below), that alone is no change + // (see step 4). var changes = new Dictionary(ReferenceEqualityComparer.Instance); bool Changes(JsonObject item) { @@ -651,6 +689,7 @@ bool Changes(JsonObject item) { changed = !pinned.Contains(item) && (!_origins.TryGetValue(item, out var origin) || Moved(item) || !JsonNode.DeepEquals(Snapshot(item), origin.Baseline) + || ExamplesChange(item) || (orders.ContainsKey(item) && (!IsFolder(item) || OrderValue(origin.Order) is not null || System.IO.Directory.Exists(current[item])))); changes[item] = changed; } @@ -915,6 +954,7 @@ private void WriteItem(JsonObject item, bool isRoot, string path, JsonObject? pa var isFolder = IsFolder(item); var file = isFolder ? V3Names.DefinitionPath(path) : path; var snapshot = Snapshot(item); + var examplesChange = ExamplesChange(item); // before they are written JsonObject v3; if (origin is not null && JsonNode.DeepEquals(snapshot, origin.Baseline)) { @@ -960,10 +1000,12 @@ private void WriteItem(JsonObject item, bool isRoot, string path, JsonObject? pa } // Folders get a definition file when they are new, have something to store or had one (also when it is gone: see - // WriteAnew); requests always have a file. + // WriteAnew); requests always have a file. A request whose file is gone stays gone, as a folder does, unless its + // examples are written: they belong to it, so it is written anew. var hadFile = origin?.File is not null; var needsFile = !isFolder || origin is null || origin.V3 is not null || v3.Count > 1; - if (needsFile && !(hadFile && JsonNode.DeepEquals(v3, origin!.V3))) + var writtenAnew = !isFolder && hadFile && examplesChange && !File.Exists(file); + if (needsFile && (writtenAnew || !(hadFile && JsonNode.DeepEquals(v3, origin!.V3)))) { var existing = File.Exists(file); if (existing && origin?.ReadError is { } error) diff --git a/src/TermRest.Core/Scripting/ScriptWorker.cs b/src/TermRest.Core/Scripting/ScriptWorker.cs index f6a6cb0..83231a0 100644 --- a/src/TermRest.Core/Scripting/ScriptWorker.cs +++ b/src/TermRest.Core/Scripting/ScriptWorker.cs @@ -683,7 +683,9 @@ private async Task AnswerAsync(JsonObject request) { if (!_ended) { - await WriteAsync(input, new JsonObject { ["sent"] = answer }, _cancel.Token).ConfigureAwait(false); + // Whole, once begun, even if the scripts are cancelled meanwhile: the rest of a line would join the runtime's + // next message. A runtime that reads no more is stopped, which ends the write. + await WriteAsync(input, new JsonObject { ["sent"] = answer }, CancellationToken.None).ConfigureAwait(false); } } catch (Exception ex) when (ex is IOException or OperationCanceledException or ObjectDisposedException) diff --git a/src/TermRest.Core/Workspace/IterationDataFile.cs b/src/TermRest.Core/Workspace/IterationDataFile.cs index 6f6c172..de15f65 100644 --- a/src/TermRest.Core/Workspace/IterationDataFile.cs +++ b/src/TermRest.Core/Workspace/IterationDataFile.cs @@ -81,12 +81,54 @@ private async IAsyncEnumerable ReadJsonAsync([EnumeratorCancellation throw new InvalidDataException($"{Name}: item {number} of the array is not an object ({{\"name\": value, …}}) but {items.Current.ValueKind.ToString().ToLowerInvariant()}."); } + // Found here, when the file is read through before the run, rather than when the row is used, in the middle of it. + if (RepeatedName(items.Current) is { } repeated) + { + throw new InvalidDataException($"{Name}: item {number} of the array has \"{repeated}\" twice in an object: a name can be there once."); + } + yield return JsonObject.Create(items.Current)!; } } } } + /// A name an object in (or in one it holds) has twice, if any. + private static string? RepeatedName(JsonElement element) + { + switch (element.ValueKind) + { + case JsonValueKind.Object: + var names = new HashSet(StringComparer.Ordinal); + foreach (var property in element.EnumerateObject()) + { + if (!names.Add(property.Name)) + { + return property.Name; + } + + if (RepeatedName(property.Value) is { } inner) + { + return inner; + } + } + + return null; + case JsonValueKind.Array: + foreach (var item in element.EnumerateArray()) + { + if (RepeatedName(item) is { } inner) + { + return inner; + } + } + + return null; + default: + return null; + } + } + private IEnumerable ReadCsv() { using var reader = new StreamReader(Path, Encoding.UTF8, detectEncodingFromByteOrderMarks: true); diff --git a/src/TermRest.Core/Workspace/ProxyCredentialStore.cs b/src/TermRest.Core/Workspace/ProxyCredentialStore.cs index 9a6d16a..ced6c30 100644 --- a/src/TermRest.Core/Workspace/ProxyCredentialStore.cs +++ b/src/TermRest.Core/Workspace/ProxyCredentialStore.cs @@ -92,9 +92,12 @@ public static ProxyCredentialStore Load(string? directory = null) /// /// Keeps and for ; an empty user forgets - /// them, and a null password keeps the one kept. Returns false when nothing changed (there is nothing to save then). + /// them, and a null password keeps the one kept for : 's own by + /// default, or another's when the sign-in goes with a proxy setting that changed (the dialog showed that one's, masked). + /// Returns false when nothing changed (there is nothing to save then). /// - public bool Set(string? proxy, string? user, string? password) + /// The password could not be encrypted for the user (Windows). + public bool Set(string? proxy, string? user, string? password, string? keptFrom = null) { if (KeyOf(proxy) is not { } key) { @@ -108,12 +111,15 @@ public bool Set(string? proxy, string? user, string? password) return _entries.Remove(key); } - if (current is not null && current.User == user && (password is null || Reveal(current.Password) == password)) + // As stored (encrypted for the user on Windows, with the same entropy for every proxy): copied as it is. + var kept = keptFrom is null || KeyOf(keptFrom) is not { } from || from == key ? current?.Password + : _entries.TryGetValue(from, out var source) ? source.Password : null; + if (current is not null && current.User == user && (password is null ? current.Password == kept : Reveal(current.Password) == password)) { return false; } - _entries[key] = new ProxyCredentialEntry { User = user, Password = password is null ? current?.Password : Conceal(password) }; + _entries[key] = new ProxyCredentialEntry { User = user, Password = password is null ? kept : Conceal(password) }; return true; } @@ -150,8 +156,9 @@ public static NetworkCredential Credential(string user, string? password) return slash > 0 ? new NetworkCredential(user[(slash + 1)..], password ?? "", user[..slash]) : new NetworkCredential(user, password ?? ""); } + // An empty password is kept as it is: there is nothing to encrypt. private static string Conceal(string password) => - OperatingSystem.IsWindows() ? DpapiPrefix + Convert.ToBase64String(Dpapi.Protect(Encoding.UTF8.GetBytes(password), Entropy)) : password; + OperatingSystem.IsWindows() && password.Length > 0 ? DpapiPrefix + Convert.ToBase64String(Dpapi.Protect(Encoding.UTF8.GetBytes(password), Entropy)) : password; private static string? Reveal(string? stored) { diff --git a/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs b/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs index 8a1b680..b284887 100644 --- a/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs +++ b/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs @@ -548,9 +548,11 @@ private async Task SendForScriptAsync(JsonNode? request, PostmanEnvi string language, CancellationToken cancellationToken) { var spec = ScriptRequest.Read(request); - var preparer = new RequestPreparer(VariableResolver.Literal, Certificates, CreateDefaults()); - var prepared = preparer.Prepare(spec, spec.Auth is { Type: not "inherit" } own ? own : null, collection.BaseDirectory); + + // Its own URL, headers, body and auth as written; the workspace's settings (a certificate's {{passphrase}}) as for any request. var resolver = CreateResolver(environment, collection, null); + var preparer = new RequestPreparer(VariableResolver.Literal, Certificates, CreateDefaults(), settingsVariables: resolver); + var prepared = preparer.Prepare(spec, spec.Auth is { Type: not "inherit" } own ? own : null, collection.BaseDirectory); prepared.AddSecretValues(SecretVariableValues(environment, collection, resolver)); prepared.AddSensitiveValues(VariablesNamedLikeSecrets(environment, collection, resolver, null)); await AuthorizeAsync(prepared, cancellationToken).ConfigureAwait(false); @@ -559,7 +561,7 @@ private async Task SendForScriptAsync(JsonNode? request, PostmanEnvi if (prepared.Errors.Count > 0) { var problem = string.Join(" ", prepared.Errors) + note; - return new JsonObject { ["error"] = problem, ["log"] = $"{sent} not sent: {problem}" }; + return new JsonObject { ["error"] = problem, ["log"] = $"{sent} not sent: {problem}{Warnings(prepared)}" }; } var exchange = await Executor.SendAsync(prepared, cancellationToken).ConfigureAwait(false); @@ -568,17 +570,24 @@ private async Task SendForScriptAsync(JsonNode? request, PostmanEnvi if (exchange.Response is not { } response) { var problem = (exchange.ErrorMessage ?? "No response.") + note; - return new JsonObject { ["error"] = problem, ["log"] = $"{sent} failed: {problem}" }; + return new JsonObject { ["error"] = problem, ["log"] = $"{sent} failed: {problem}{Warnings(prepared)}" }; } var cut = response.BodyTruncated ? ", body cut at the size limit" : ""; return new JsonObject { ["response"] = ResponseReceived(exchange), - ["log"] = $"{sent} {response.StatusCode} {response.ReasonPhrase} ({exchange.Timing.Total?.TotalMilliseconds ?? 0:0} ms{cut}){note}", + ["log"] = $"{sent} {response.StatusCode} {response.ReasonPhrase} ({exchange.Timing.Total?.TotalMilliseconds ?? 0:0} ms{cut}){note}{Warnings(prepared)}", }; } + /// + /// The warnings of a request that a script sent (a client certificate not used, a redirect not followed …), as lines of + /// the script's output after its own: the line says the unreplaced variables already. + /// + private static string Warnings(PreparedRequest request) => + string.Concat(request.Warnings.Where(w => !w.StartsWith("Unresolved variables:", StringComparison.Ordinal)).Select(w => "\n ⚠ " + w)); + /// Where a request went, for a script's output: without the query, which may hold a key, nor a password. private static string Shown(PreparedRequest request) => request.Uri is { } uri ? $"{uri.Scheme}://{uri.Authority}{uri.AbsolutePath}{(uri.Query.Length > 1 ? "?…" : "")}" diff --git a/src/TermRest.Core/Workspace/RequestRunner.cs b/src/TermRest.Core/Workspace/RequestRunner.cs index df8fef0..f788b1d 100644 --- a/src/TermRest.Core/Workspace/RequestRunner.cs +++ b/src/TermRest.Core/Workspace/RequestRunner.cs @@ -413,6 +413,11 @@ private IEnumerable VariablesNamedLikeSecrets(PostmanEnvironment? enviro .Where(e => e.Enabled) .Select(e => new KeyValuePair(e.Key, e.Value)); variables = variables.Concat(LocalVariables.Select(v => new KeyValuePair(v.Key, v.Value))); + if (_iterationText is { Count: > 0 } data) + { + variables = variables.Concat(data.Select(v => new KeyValuePair(v.Key, v.Value))); // a data file's apiToken column + } + IEnumerable?> setByScripts = [environment is not null ? Session.Find(environment) : null, Session.Find(collection), Session.Globals, requestVariables]; variables = variables.Concat(setByScripts.SelectMany(values => values ?? new Dictionary())); diff --git a/src/TermRest.Tui/Dialogs/SettingsDialog.cs b/src/TermRest.Tui/Dialogs/SettingsDialog.cs index a9a1f5c..2fcbca7 100644 --- a/src/TermRest.Tui/Dialogs/SettingsDialog.cs +++ b/src/TermRest.Tui/Dialogs/SettingsDialog.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Security.Cryptography; using Terminal.Gui.App; using Terminal.Gui.ViewBase; using Terminal.Gui.Views; @@ -67,6 +68,7 @@ public static bool Show(IApplication app, ApiWorkspace workspace, RequestRunner // Kept for the proxy in the user's private credentials file, never in the workspace; a password left masked stays. const string keptPassword = "********"; + var originalProxy = settings.Proxy; var (keptUser, hasPassword) = runner.ProxyCredentials.Describe(settings.Proxy); var proxyUser = Ui.AddRow(dialog, "Proxy sign-in", new TextField { Text = keptUser, Width = 22 }, y, 22); var proxyPassword = new TextField { X = Pos.Right(proxyUser) + 11, Y = y, Width = 16, Secret = true, Text = hasPassword ? keptPassword : "" }; @@ -182,13 +184,24 @@ public static bool Show(IApplication app, ApiWorkspace workspace, RequestRunner saved &= SaveApprovals(app, workspace, runner, outsideFiles.Value == CheckState.Checked, userDirectory); // The sign-in goes with the proxy the settings now name (the system's, or a URL), for this session and in the - // user's credentials file. + // user's credentials file, read again first: another TermRest may have saved sign-ins to it since (it is the + // user's, for every workspace). A password left masked is the one shown: that of the proxy named before. + var credentials = ProxyCredentialStore.Load(userDirectory); var password = proxyPassword.Text == keptPassword && hasPassword ? null : proxyPassword.Text; - if (runner.ProxyCredentials.Set(settings.Proxy, proxyUser.Text, password)) + try { - saved &= Ui.TrySave(app, () => runner.ProxyCredentials.Save(userDirectory)); + if (credentials.Set(settings.Proxy, proxyUser.Text, password, keptFrom: originalProxy ?? ProxyCredentialStore.SystemProxy)) + { + saved &= Ui.TrySave(app, () => credentials.Save(userDirectory)); + } + } + catch (CryptographicException ex) + { + Ui.Error(app, "Proxy sign-in", $"The password could not be encrypted for your account, so the sign-in was not kept: {ex.Message}"); + saved = false; } + runner.ProxyCredentials = credentials; return true; } } diff --git a/src/TermRest.Tui/MainWindow.cs b/src/TermRest.Tui/MainWindow.cs index 4fd18b9..ee48183 100644 --- a/src/TermRest.Tui/MainWindow.cs +++ b/src/TermRest.Tui/MainWindow.cs @@ -587,12 +587,12 @@ private void WatchLive(LiveResponse live, int opened) var version = live.Version; if (version != shown && opened == _opened) { - var (head, received, text, cut) = live.Read(); + var (head, received, text, cut, ended) = live.Read(); if (head is not null) { shown = version; - _response.ShowLive(head, received, text, cut); - _editor.SetSending(true, streaming: true); + _response.ShowLive(head, received, text, cut, ended); + _editor.SetSending(true, streaming: !ended); // once read, Send cancels the scripts that run on it } } @@ -1517,11 +1517,18 @@ private void ClearResponse() /// /// Another request is shown in the editor: a request still on its way for the one before goes on (its response goes - /// to the history and the status bar, not under this one), and Send sends this one. + /// to the history and the status bar, not under this one), and Send sends this one. A response still streaming is stopped, + /// keeping what arrived: nothing would show it any more, nor could stop it. /// private void DetachSending() { _opened++; + if (_live is { } live) + { + live.Stop(); + _live = null; + } + if (_sending is not null) { _sending = null; diff --git a/src/TermRest.Tui/Views/LiveResponse.cs b/src/TermRest.Tui/Views/LiveResponse.cs index 52d0ebf..a2bd145 100644 --- a/src/TermRest.Tui/Views/LiveResponse.cs +++ b/src/TermRest.Tui/Views/LiveResponse.cs @@ -20,17 +20,18 @@ internal sealed class LiveResponse : IStreamWatcher, IDisposable private long _received; private int _version; private ResponseSnapshot? _head; + private bool _ended; public CancellationToken Stopping => _stop.Token; - /// Whether the response streams: its head arrived, and its body is arriving. + /// Whether the response streams now: its head arrived, and its body is arriving (Stop ends it). public bool Streaming { get { lock (_gate) { - return _head is not null; + return _head is not null && !_ended; } } } @@ -91,8 +92,20 @@ public void Received(ReadOnlySpan data) } } - /// What arrived so far: the head (null until it arrives), how many bytes, and the text of the end, from the start of a line when it is cut. - public (ResponseSnapshot? Head, long Received, string Text, bool Cut) Read() + public void Ended() + { + lock (_gate) + { + _ended = true; + _version++; + } + } + + /// + /// What arrived so far: the head (null until it arrives), how many bytes, the text of the end (from the start of a line + /// when it is cut), and whether the body has been read (scripts may still run on it). + /// + public (ResponseSnapshot? Head, long Received, string Text, bool Cut, bool Ended) Read() { lock (_gate) { @@ -108,7 +121,7 @@ public void Received(ReadOnlySpan data) } } - return (_head, _received, Encoding.UTF8.GetString(tail), cut); + return (_head, _received, Encoding.UTF8.GetString(tail), cut, _ended); } } diff --git a/src/TermRest.Tui/Views/ResponseView.cs b/src/TermRest.Tui/Views/ResponseView.cs index d7f62ca..b7b5f6d 100644 --- a/src/TermRest.Tui/Views/ResponseView.cs +++ b/src/TermRest.Tui/Views/ResponseView.cs @@ -290,14 +290,17 @@ public void ShowSending(PreparedRequest request) /// /// Shows a response that streams while it arrives (see ): its status, its headers, and the end of - /// its text, followed as it grows. Once it ends, or is stopped, shows it whole, with its events. + /// its text, followed as it grows. : its body has been read, and scripts may still run on it. Once + /// the request is done, shows it whole, with its events. /// - public void ShowLive(ResponseSnapshot head, long received, string text, bool cut) + public void ShowLive(ResponseSnapshot head, long received, string text, bool cut, bool ended = false) { _exchange = null; // Copy, Save and Filter wait for the whole response _fromHistory = false; _saveExample.Visible = false; - _status.Text = $"{head.StatusCode} {head.ReasonPhrase} · streaming · {HttpExchange.FormatSize(received)} so far · Esc stops it"; + _status.Text = ended + ? $"{head.StatusCode} {head.ReasonPhrase} · {HttpExchange.FormatSize(received)} received … (Esc or Send to cancel)" + : $"{head.StatusCode} {head.ReasonPhrase} · streaming · {HttpExchange.FormatSize(received)} so far · Esc stops it"; _status.SchemeName = null; if (!ReferenceEquals(_liveHead, head)) { diff --git a/tests/TermRest.Cli.Tests/CommandLineTests.cs b/tests/TermRest.Cli.Tests/CommandLineTests.cs index 5fdb338..23801f0 100644 --- a/tests/TermRest.Cli.Tests/CommandLineTests.cs +++ b/tests/TermRest.Cli.Tests/CommandLineTests.cs @@ -829,6 +829,33 @@ public async Task Send_prints_a_stream_as_it_arrives_once() Assert.Contains("200 OK · streaming (Ctrl+C stops it, keeping what arrived)", result.Error, StringComparison.Ordinal); } + [Fact] + public async Task Send_stops_a_stream_once_what_reads_its_output_has_gone() + { + await using var server = await TestServer.StartAsync(); + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Events", "GET", server.BaseUrl + "/events?count=0")]); + + var result = await Termrest.RunAsync(["send", collection, "Events", "--no-history"], outputLimit: 40); // | head -c 40 + + Assert.True(result.ExitCode == 0, result.ToString()); + Assert.Contains("warning: The stream was stopped: its body is what arrived until then.", result.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task Send_signs_in_to_the_system_proxy_with_proxy_user_rather_than_with_the_user_and_password_in_http_proxy() + { + await using var proxy = new SignInProxy("ada", "s3cret"); + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Hello", "GET", "http://api.example.test/hello")]); + var environment = new Dictionary { ["HTTP_PROXY"] = proxy.Url.Replace("http://", "http://ada:old-password@", StringComparison.Ordinal), ["NO_PROXY"] = "" }; + + var given = await Termrest.RunAsync(["send", collection, "Hello", "--proxy-user", "ada:s3cret", "--no-history"], environment); + var fromUrl = await Termrest.RunAsync(["send", collection, "Hello", "--no-history"], environment); + + Assert.True(given.ExitCode == 0, given.ToString()); + Assert.Contains("through the proxy", given.Text, StringComparison.Ordinal); + Assert.Contains("407", fromUrl.Error, StringComparison.Ordinal); // the URL's own, when none is given + } + [Fact] public async Task Ctrl_c_stops_a_stream_that_send_prints_keeping_what_arrived() { diff --git a/tests/TermRest.Cli.Tests/Infrastructure/Termrest.cs b/tests/TermRest.Cli.Tests/Infrastructure/Termrest.cs index 43facc6..f36d1fe 100644 --- a/tests/TermRest.Cli.Tests/Infrastructure/Termrest.cs +++ b/tests/TermRest.Cli.Tests/Infrastructure/Termrest.cs @@ -27,8 +27,9 @@ internal static class Termrest /// Bytes for its standard input (closed right away when null). /// What to do while the command runs (signal it…); its exit is awaited afterwards. /// The command's current folder (the tests' when null). + /// Stop reading standard output once this many bytes came, and close it, as | head -c does. public static async Task RunAsync(IEnumerable arguments, IReadOnlyDictionary? environment = null, byte[]? input = null, - Func? whileRunning = null, string? workingDirectory = null) + Func? whileRunning = null, string? workingDirectory = null, int? outputLimit = null) { var start = new ProcessStartInfo(Dotnet) { @@ -68,7 +69,9 @@ public static async Task RunAsync(IEnumerable arguments, process.StandardInput.Close(); using var output = new MemoryStream(); - var copying = process.StandardOutput.BaseStream.CopyToAsync(output, timeout.Token); + var copying = outputLimit is { } limit + ? ReadSomeAsync(process.StandardOutput.BaseStream, output, limit, timeout.Token) + : process.StandardOutput.BaseStream.CopyToAsync(output, timeout.Token); var error = process.StandardError.ReadToEndAsync(timeout.Token); try { @@ -87,4 +90,16 @@ public static async Task RunAsync(IEnumerable arguments, throw; } } + + private static async Task ReadSomeAsync(Stream output, MemoryStream into, int limit, CancellationToken cancellationToken) + { + var buffer = new byte[4096]; + int read; + while (into.Length < limit && (read = await output.ReadAsync(buffer, cancellationToken)) > 0) + { + into.Write(buffer, 0, read); + } + + await output.DisposeAsync(); // the reader goes + } } diff --git a/tests/TermRest.Core.Tests/ExampleTests.cs b/tests/TermRest.Core.Tests/ExampleTests.cs index b797419..5373fbe 100644 --- a/tests/TermRest.Core.Tests/ExampleTests.cs +++ b/tests/TermRest.Core.Tests/ExampleTests.cs @@ -116,6 +116,53 @@ public void Renamed_and_deleted_v3_examples_rename_and_delete_their_files() Assert.Empty(reopened.GetExamples(reopened.FindRequest("Widgets/List widgets")!)); } + [Fact] + public void A_copy_of_a_v3_example_stays_right_after_its_original() + { + var root = V3Fixture.Create(); + var collection = OpenV3(root); + var list = collection.FindRequest("Widgets/List widgets")!; + var original = Assert.Single(collection.GetExamples(list)); + collection.AddExample(list, new ExampleSpec { Name = "Not found", Request = list.ReadSpec(), Code = 404, Status = "Not Found", Language = "text" }); + collection.Save(); + + collection.DuplicateExample(original); + collection.Save(); + + var reopened = OpenV3(root); + Assert.Equal(["200 OK", "200 OK Copy", "Not found"], reopened.GetExamples(reopened.FindRequest("Widgets/List widgets")!).Select(e => e.Name)); + } + + [Theory] + [InlineData("Widgets")] // its folder, as a git checkout may remove it + [InlineData("Widgets/List widgets.request.yaml")] // its own file + public void An_example_saved_for_a_request_whose_file_went_brings_the_request_back(string gone) + { + var root = V3Fixture.Create(); + var collection = OpenV3(root); + var list = collection.FindRequest("Widgets/List widgets")!; + var example = Assert.Single(collection.GetExamples(list)); + var spec = example.ReadSpec(); + spec.Body = "[1]"; + Assert.True(collection.UpdateExample(example, spec)); + if (Directory.Exists(F(root, gone))) + { + Directory.Delete(F(root, gone), recursive: true); + } + else + { + File.Delete(F(root, gone)); + } + + collection.Save(); + + // The request and its folder as they were (the folder's auth and scripts too), not an example nothing shows. + Assert.True(File.Exists(F(root, "Widgets/List widgets.request.yaml"))); + Assert.True(File.Exists(F(root, "Widgets/.resources/definition.yaml"))); + var reopened = OpenV3(root); + Assert.Equal("[1]", Assert.Single(reopened.GetExamples(reopened.FindRequest("Widgets/List widgets")!)).ReadSpec().Body); + } + [Fact] public void A_v3_collection_exported_or_copied_takes_its_examples_along() { diff --git a/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs b/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs index 72977a2..41b6bb4 100644 --- a/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs +++ b/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs @@ -112,18 +112,22 @@ Task Echo(HttpContext ctx) }); // A stream: server-sent events, or JSON lines with ?ndjson; ?count= of them (0: until the client goes), ?delay= ms - // apart, gzip-compressed (flushed after each) with ?gzip. Also /events/{count}/{delay}/…, for a URL that goes on. + // apart, compressed (flushed after each) with ?gzip, ?deflate or ?rawdeflate. Also /events/{count}/{delay}/…, for a URL that goes on. async Task Events(HttpContext ctx, int count, int delay) { var ndjson = ctx.Request.Query.ContainsKey("ndjson"); ctx.Response.ContentType = ndjson ? "application/x-ndjson" : "text/event-stream; charset=utf-8"; - var gzip = ctx.Request.Query.ContainsKey("gzip"); - if (gzip) + var query = ctx.Request.Query; + var level = System.IO.Compression.CompressionLevel.Fastest; + await using Stream? body = query.ContainsKey("gzip") ? new System.IO.Compression.GZipStream(ctx.Response.Body, level, leaveOpen: true) + : query.ContainsKey("deflate") ? new System.IO.Compression.ZLibStream(ctx.Response.Body, level, leaveOpen: true) + : query.ContainsKey("rawdeflate") ? new System.IO.Compression.DeflateStream(ctx.Response.Body, level, leaveOpen: true) // as some servers send deflate + : null; + if (body is not null) { - ctx.Response.Headers.ContentEncoding = "gzip"; + ctx.Response.Headers.ContentEncoding = query.ContainsKey("gzip") ? "gzip" : "deflate"; } - await using var body = gzip ? new System.IO.Compression.GZipStream(ctx.Response.Body, System.IO.Compression.CompressionLevel.Fastest, leaveOpen: true) : null; var output = body ?? ctx.Response.Body; try { diff --git a/tests/TermRest.Core.Tests/IterationDataTests.cs b/tests/TermRest.Core.Tests/IterationDataTests.cs index 8f307b5..9cc4ea8 100644 --- a/tests/TermRest.Core.Tests/IterationDataTests.cs +++ b/tests/TermRest.Core.Tests/IterationDataTests.cs @@ -63,6 +63,26 @@ public async Task A_json_data_file_is_an_array_of_objects_whose_values_keep_thei Assert.Equal("data.json: item 2 of the array is not an object ({\"name\": value, …}) but number.", notObject.Message); var broken = Assert.Throws(() => RowsAsync("""[{"id": 1""", ".json").GetAwaiter().GetResult()); Assert.StartsWith("data.json is not a JSON array of objects:", broken.Message, StringComparison.Ordinal); + + // Found when the file is read through, before the run, not when the row is used (also in an object a value holds). + var repeated = Assert.Throws(() => RowsAsync("""[{"id": 1}, {"id": 2, "id": 3}]""", ".json").GetAwaiter().GetResult()); + Assert.Equal("data.json: item 2 of the array has \"id\" twice in an object: a name can be there once.", repeated.Message); + var nested = Assert.Throws(() => RowsAsync("""[{"user": [{"name": "a", "name": "b"}]}]""", ".json").GetAwaiter().GetResult()); + Assert.Contains("item 1 of the array has \"name\" twice", nested.Message, StringComparison.Ordinal); + } + + [Fact] + public void Data_values_named_like_secrets_are_redacted_in_recordings_and_reports() + { + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + using var runner = new RequestRunner(workspace); + runner.IterationData = (JsonObject)JsonNode.Parse("""{ "apiToken": "tok-1234567890", "user": "ada" }""")!; + + var prepared = runner.Prepare(workspace.CreateCollection("API"), null, new HttpRequestSpec { Url = "https://api.example.test/items/{{apiToken}}?user={{user}}" }); + + var report = new TermRest.Core.Recording.Redactor().ForReport(new HttpExchange(prepared)).Url(prepared.Url, "url"); + Assert.DoesNotContain("tok-1234567890", report, StringComparison.Ordinal); + Assert.Contains("user=ada", report, StringComparison.Ordinal); } [Fact] diff --git a/tests/TermRest.Core.Tests/ProxyTests.cs b/tests/TermRest.Core.Tests/ProxyTests.cs index 15cd765..0681110 100644 --- a/tests/TermRest.Core.Tests/ProxyTests.cs +++ b/tests/TermRest.Core.Tests/ProxyTests.cs @@ -96,6 +96,16 @@ public void Proxy_credentials_are_kept_per_proxy_in_a_private_file_with_the_pass Assert.Equal(("CONTOSO\\ada", true), read.Describe("HTTP://proxy.contoso.com:3128")); Assert.Null(read.Find("http://other:3128")); + // The sign-in moves with a proxy setting that changes: a password left as it was is the one kept for the proxy before. + Assert.True(read.Set("http://new-proxy:8080", "CONTOSO\\ada", null, keptFrom: "http://proxy.contoso.com:3128")); + Assert.Equal("s3cret-pw", read.Find("http://new-proxy:8080")?.Password); + Assert.False(read.Set("http://new-proxy:8080", "CONTOSO\\ada", null, keptFrom: "http://proxy.contoso.com:3128")); + + // An empty password is kept as it is (DPAPI refuses no data). + Assert.True(read.Set("http://new-proxy:8080", "CONTOSO\\ada", "")); + Assert.Equal(("", ("CONTOSO\\ada", false)), (read.Find("http://new-proxy:8080")?.Password, read.Describe("http://new-proxy:8080"))); + Assert.True(read.Set("http://new-proxy:8080", "", null)); + // A password left as it was (null) stays; an empty user forgets them; with nothing kept, the file goes. Assert.True(read.Set("http://proxy.contoso.com:3128", "CONTOSO\\ada2", null)); Assert.Equal("s3cret-pw", read.Find("http://proxy.contoso.com:3128")?.Password); diff --git a/tests/TermRest.Core.Tests/ScriptRequestTests.cs b/tests/TermRest.Core.Tests/ScriptRequestTests.cs index ce86dd8..21d817c 100644 --- a/tests/TermRest.Core.Tests/ScriptRequestTests.cs +++ b/tests/TermRest.Core.Tests/ScriptRequestTests.cs @@ -32,15 +32,17 @@ public async Task A_request_a_script_sends_goes_out_with_the_workspaces_client_c await using var plain = await EchoServer.StartAsync(); var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); workspace.Settings.CaBundle = _pki.CaPemPath; + + // Its passphrase in a variable, as the README advises: replaced, though the script's own request replaces none. workspace.Certificates.Entries.Add(new CertificateEntry { Name = "client", Matches = [$"https://localhost:{secure.BaseUri.Port}/*"], Pfx = new FileSource { Src = _pki.ClientPfxPath }, - Passphrase = TestPki.Passphrase, + Passphrase = "{{pfxPassphrase}}", }); var collection = workspace.CreateCollection("API"); - collection.SetVariables([new KeyValueEntry { Key = "secure", Value = secure.Url("echo") }]); + collection.SetVariables([new KeyValueEntry { Key = "secure", Value = secure.Url("echo") }, new KeyValueEntry { Key = "pfxPassphrase", Value = TestPki.Passphrase }]); // A POST with a header and a JSON body, then one with a {{variable}} that is sent as written, which fails. var script = language switch diff --git a/tests/TermRest.Core.Tests/StreamingTests.cs b/tests/TermRest.Core.Tests/StreamingTests.cs index df19f3f..518368c 100644 --- a/tests/TermRest.Core.Tests/StreamingTests.cs +++ b/tests/TermRest.Core.Tests/StreamingTests.cs @@ -27,10 +27,14 @@ private sealed class Watcher(int stopAfter = 0, string separator = "\n\n") : ISt public int Parts { get; private set; } + public bool HasEnded { get; private set; } + public string Text => _text.ToString(); public void Started(ResponseSnapshot head) => Head = head; + public void Ended() => HasEnded = true; + public void Dispose() => _stop.Dispose(); public void Received(ReadOnlySpan data) @@ -47,6 +51,8 @@ public void Received(ReadOnlySpan data) [Theory] [InlineData("events?count=3&delay=30")] [InlineData("events?count=3&delay=30&gzip")] // decoded as it arrives + [InlineData("events?count=3&delay=30&deflate")] + [InlineData("events?count=3&delay=30&rawdeflate")] // deflate without its zlib header, as some servers send it public async Task A_stream_is_read_as_it_arrives_and_its_watcher_sees_each_part(string path) { await using var server = await EchoServer.StartAsync(); @@ -66,7 +72,8 @@ public async Task A_stream_is_read_as_it_arrives_and_its_watcher_sees_each_part( Assert.Equal(string.Concat(Enumerable.Range(1, 3).Select(n => $"id: {n}\nevent: tick\ndata: {{\"n\":{n}}}\n\n")), body); Assert.False(response.Stopped); Assert.Empty(request.Warnings); - if (path.EndsWith("gzip", StringComparison.Ordinal)) + Assert.True(watcher.HasEnded); + if (path.Contains("deflate", StringComparison.Ordinal) || path.EndsWith("gzip", StringComparison.Ordinal)) { Assert.NotEqual(response.Body.LongLength, response.ReceivedBodySize); } @@ -88,6 +95,7 @@ public async Task A_stream_its_watcher_stops_keeps_what_arrived() var exchange = await new HttpExecutor().SendAsync(request, _ct); Assert.False(exchange.Cancelled); + Assert.True(watcher.HasEnded); // stopping it now does nothing: what runs next (scripts) is cancelled as for any request var response = exchange.Response!; Assert.True(response.Stopped); Assert.StartsWith("{\"n\":1}\n{\"n\":2}\n{\"n\":3}\n", Encoding.UTF8.GetString(response.Body), StringComparison.Ordinal); @@ -131,12 +139,13 @@ public void Server_sent_events_are_read_as_the_html_standard_reads_them() "event: update\nid: 7\ndata: {\"a\":1}\n\n" + "event: no data\n\n" + "data: after\rid\r\r" + // an id with no value clears it + "event:\ndata: typed nothing\n\n" + // an empty type is message's "data: the last, never ended\n"); var events = ServerSentEvents.Parse(body, _ct); - Assert.Equal([("message", null), ("update", "7"), ("message", "")], events.Select(e => (e.Type, e.Id(body)))); - Assert.Equal(["first\n two lines", "{\"a\":1}", "after"], events.Select(e => e.Data(body))); + Assert.Equal([("message", null), ("update", "7"), ("message", ""), ("message", "")], events.Select(e => (e.Type, e.Id(body)))); + Assert.Equal(["first\n two lines", "{\"a\":1}", "after", "typed nothing"], events.Select(e => e.Data(body))); Assert.StartsWith(": a comment", Encoding.UTF8.GetString(body, events[0].Start, events[0].Length), StringComparison.Ordinal); } } diff --git a/tests/TermRest.Tui.Tests/MainWindowTests.cs b/tests/TermRest.Tui.Tests/MainWindowTests.cs index 549b4c9..d144101 100644 --- a/tests/TermRest.Tui.Tests/MainWindowTests.cs +++ b/tests/TermRest.Tui.Tests/MainWindowTests.cs @@ -635,6 +635,116 @@ public async Task A_stream_is_shown_as_it_arrives_and_esc_stops_it_keeping_its_e Assert.StartsWith("id: 1\nevent: tick\ndata: {\"n\":1}\n\n", System.Text.Encoding.UTF8.GetString(response.Body), StringComparison.Ordinal); } + [Fact] + public async Task Esc_once_a_stream_has_arrived_cancels_the_scripts_that_run_on_it() + { + var node = TestJavaScript.Require(); + await using var server = await TermRest.Core.Tests.Infrastructure.EchoServer.StartAsync(); + var setup = PostmanCollection.Load(Path.Combine(_directory, "TermRest Demo.postman_collection.json")); + var request = setup.FindRequest("Basics/GET with query")!; + var spec = request.ReadSpec(); + spec.Scripts = new ScriptSet("", "await new Promise(resolve => setTimeout(resolve, 30000));", ScriptLanguage.JavaScript); + setup.UpdateRequest(request, spec); + setup.Save(); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.Url("events/2/10"); + runner.SetJavaScriptRuntime(node); + }); + var (running, done) = ("", ""); + var pressed = DateTime.MaxValue; + var deadline = DateTime.UtcNow.AddSeconds(25); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(300), () => + { + ui.App.InjectKey(Key.F5); + return false; + }); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + var screen = ui.Screen(); + if (DateTime.UtcNow > deadline) + { + (running, done) = (running.Length > 0 ? running : screen, screen); + ui.App.RequestStop(); + return false; + } + + if (running.Length == 0) + { + if (screen.Contains(" received …", StringComparison.Ordinal)) + { + running = screen; + pressed = DateTime.UtcNow; + ui.App.InjectKey(Key.Esc); + } + } + else if (!ui.Window.IsSending) + { + done = screen; + ui.App.RequestStop(); + return false; + } + + return true; + }); + + ui.App.Run(ui.Window); + + OnScreen("(Esc or Send to cancel)", running); + OnScreen("⟦ Cancel ⟧", running); + Assert.True(DateTime.UtcNow - pressed < TimeSpan.FromSeconds(15), done); + var exchange = ui.Window.ResponsePane.Exchange!; + Assert.Contains("Cancelled while the test scripts ran.", exchange.Scripts!.Notes); + Assert.Equal(200, exchange.Response!.StatusCode); + } + + [Fact] + public async Task A_stream_still_arriving_when_another_request_is_opened_is_stopped_and_kept_in_the_history() + { + await using var server = await TermRest.Core.Tests.Infrastructure.EchoServer.StartAsync(); + var state = TestFiles.NewTempDirectory(); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.Url("events/0/20"); // until the client goes + runner.ConfigureHistory(state); + }); + var arrived = ""; + var step = 0; + var deadline = DateTime.UtcNow.AddSeconds(20); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(300), () => + { + ui.App.InjectKey(Key.F5); + return false; + }); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + if (DateTime.UtcNow > deadline) + { + ui.App.RequestStop(); + return false; + } + + switch (step) + { + case 0 when ui.Window.ResponsePane.StatusText.Contains("· streaming ·", StringComparison.Ordinal): + ui.Click("POST POST JSON"); + step = 1; + break; + case 1 when ui.Runner.History!.Load().Count == 1: + arrived = ui.Window.StatusMessage; + ui.App.RequestStop(); + return false; + } + + return true; + }); + + ui.App.Run(ui.Window); + + Assert.StartsWith("Earlier request: GET localhost → 200", arrived, StringComparison.Ordinal); + Assert.StartsWith("id: 1\n", System.Text.Encoding.UTF8.GetString(ui.Runner.History!.ReadBody(Assert.Single(ui.Runner.History.Load()))!), StringComparison.Ordinal); + } + /// A screen's text with its lines joined and its box-drawing characters left out, so a check doesn't depend on where a dialog wraps. private static string Unwrapped(string screen) => System.Text.RegularExpressions.Regex.Replace(screen, @"[\s\u2500-\u259F]+", " "); @@ -1289,6 +1399,51 @@ public void A_proxy_sign_in_typed_in_the_settings_is_kept_in_the_users_private_f Assert.False(File.Exists(workspaceSettings) && File.ReadAllText(workspaceSettings).Contains("ada", StringComparison.Ordinal)); } + [Fact] + public void A_proxy_sign_in_left_masked_moves_to_the_new_proxy_and_sign_ins_another_termrest_saved_stay() + { + var userDirectory = TestFiles.NewTempDirectory(); + var kept = ProxyCredentialStore.Load(userDirectory); + kept.Set("system", "CONTOSO\\ada", "s3cret-pw"); + kept.Save(userDirectory); + using var ui = new Harness(_directory, runner => runner.ConfigureProxy(userDirectory)); + + // Another TermRest (another workspace) saves a sign-in for its proxy meanwhile. + var other = ProxyCredentialStore.Load(userDirectory); + other.Set("http://other-proxy:8080", "bob", "hunter2-pw"); + other.Save(userDirectory); + + var saved = false; + var screens = Drive(ui, () => + { + SettingsDialog.Show(ui.App, ui.Workspace, ui.Runner, out saved, userDirectory); + ui.App.RequestStop(); + }, + ("Workspace settings", () => + { + // A proxy URL in place of the system's; its sign-in left as shown, the password masked. + var label = ui.Find("Proxy "); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(label.X + 23, label.Y))); + ui.App.InjectKey(Key.End); + foreach (var _ in "system") + { + ui.App.InjectKey(Key.Backspace); + } + + ui.Type("http://new-proxy:3128"); + ui.Click("► Save ◄"); + })); + + Assert.Single(screens); + Assert.True(saved); + var credential = ui.Runner.CreateDefaults().ProxyCredential; + Assert.Equal(("http://new-proxy:3128", "ada", "s3cret-pw", "CONTOSO"), + (ui.Workspace.Settings.Proxy, credential?.UserName, credential?.Password, credential?.Domain)); + var file = ProxyCredentialStore.Load(userDirectory); + Assert.Equal("hunter2-pw", file.Find("http://other-proxy:8080")?.Password); + Assert.Equal("s3cret-pw", file.Find("http://new-proxy:3128")?.Password); + } + [Theory] [InlineData("http://ada:***@proxy:3128", "http://ada:s3cret@proxy:3128")] // left as shown [InlineData("http://ada:***@proxy:8080", "http://ada:s3cret@proxy:8080")] // only the port changed From de8449421fa333e741e3a1b61f9982bbce83f863 Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Wed, 18 Nov 2026 01:18:46 -0700 Subject: [PATCH 08/11] TUI: a proxy sign-in in Settings is saved only when it was changed The Settings dialog showed the proxy sign-in as TermRest read it when it started, and saving applied it over the credentials file read again, edited or not: a sign-in another TermRest had saved since for the same proxy (the system's, which every workspace without a proxy of its own shares) was deleted, or got this one's user name with its password. The dialog now shows the file as it is when it opens, and saving applies the sign-in only when it was edited, or when the proxy changed while one was shown (it moves to the new proxy, as before); naming a proxy while no sign-in is shown keeps the one kept for that proxy, which was deleted before. A file that cannot be read is not adopted for the session, which keeps its sign-ins. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/TermRest.Tui/Dialogs/SettingsDialog.cs | 38 ++++++++----- tests/TermRest.Tui.Tests/MainWindowTests.cs | 62 +++++++++++++++++++++ 2 files changed, 86 insertions(+), 14 deletions(-) diff --git a/src/TermRest.Tui/Dialogs/SettingsDialog.cs b/src/TermRest.Tui/Dialogs/SettingsDialog.cs index 2fcbca7..52895ce 100644 --- a/src/TermRest.Tui/Dialogs/SettingsDialog.cs +++ b/src/TermRest.Tui/Dialogs/SettingsDialog.cs @@ -66,10 +66,12 @@ public static bool Show(IApplication app, ApiWorkspace workspace, RequestRunner dialog.Add(proxyHint); y += 1; - // Kept for the proxy in the user's private credentials file, never in the workspace; a password left masked stays. + // Kept for the proxy in the user's private credentials file, never in the workspace; a password left masked stays. The + // file is read now, as it is the user's, for every workspace: another TermRest may have saved to it since this one started. const string keptPassword = "********"; var originalProxy = settings.Proxy; - var (keptUser, hasPassword) = runner.ProxyCredentials.Describe(settings.Proxy); + var onDisk = ProxyCredentialStore.Load(userDirectory); + var (keptUser, hasPassword) = (onDisk.LoadError is null ? onDisk : runner.ProxyCredentials).Describe(settings.Proxy); var proxyUser = Ui.AddRow(dialog, "Proxy sign-in", new TextField { Text = keptUser, Width = 22 }, y, 22); var proxyPassword = new TextField { X = Pos.Right(proxyUser) + 11, Y = y, Width = 16, Secret = true, Text = hasPassword ? keptPassword : "" }; dialog.Add(new Label { Text = "password", X = Pos.Right(proxyUser) + 2, Y = y }, proxyPassword); @@ -184,21 +186,29 @@ public static bool Show(IApplication app, ApiWorkspace workspace, RequestRunner saved &= SaveApprovals(app, workspace, runner, outsideFiles.Value == CheckState.Checked, userDirectory); // The sign-in goes with the proxy the settings now name (the system's, or a URL), for this session and in the - // user's credentials file, read again first: another TermRest may have saved sign-ins to it since (it is the - // user's, for every workspace). A password left masked is the one shown: that of the proxy named before. - var credentials = ProxyCredentialStore.Load(userDirectory); - var password = proxyPassword.Text == keptPassword && hasPassword ? null : proxyPassword.Text; - try + // user's credentials file, read again first (another TermRest may have saved to it meanwhile): when it was + // edited, or when the proxy changed and one was shown, which moves to it (its password left masked too). + // Otherwise the file's stay as they are. A file that cannot be read is not saved over: the sign-in then applies + // to this session only, and saving it says why. + var fresh = ProxyCredentialStore.Load(userDirectory); + var credentials = fresh.LoadError is null ? fresh : runner.ProxyCredentials; + var edited = proxyUser.Text.Trim() != keptUser || proxyPassword.Text != (hasPassword ? keptPassword : ""); + var moved = keptUser.Length > 0 && ProxyCredentialStore.KeyOf(settings.Proxy) != ProxyCredentialStore.KeyOf(originalProxy); + if (edited || moved) { - if (credentials.Set(settings.Proxy, proxyUser.Text, password, keptFrom: originalProxy ?? ProxyCredentialStore.SystemProxy)) + var password = proxyPassword.Text == keptPassword && hasPassword ? null : proxyPassword.Text; + try { - saved &= Ui.TrySave(app, () => credentials.Save(userDirectory)); + if (credentials.Set(settings.Proxy, proxyUser.Text, password, keptFrom: originalProxy ?? ProxyCredentialStore.SystemProxy)) + { + saved &= Ui.TrySave(app, () => fresh.Save(userDirectory)); + } + } + catch (CryptographicException ex) + { + Ui.Error(app, "Proxy sign-in", $"The password could not be encrypted for your account, so the sign-in was not kept: {ex.Message}"); + saved = false; } - } - catch (CryptographicException ex) - { - Ui.Error(app, "Proxy sign-in", $"The password could not be encrypted for your account, so the sign-in was not kept: {ex.Message}"); - saved = false; } runner.ProxyCredentials = credentials; diff --git a/tests/TermRest.Tui.Tests/MainWindowTests.cs b/tests/TermRest.Tui.Tests/MainWindowTests.cs index d144101..50a2f99 100644 --- a/tests/TermRest.Tui.Tests/MainWindowTests.cs +++ b/tests/TermRest.Tui.Tests/MainWindowTests.cs @@ -1444,6 +1444,68 @@ public void A_proxy_sign_in_left_masked_moves_to_the_new_proxy_and_sign_ins_anot Assert.Equal("s3cret-pw", file.Find("http://new-proxy:3128")?.Password); } + [Fact] + public void The_settings_show_a_sign_in_another_termrest_saved_since_and_saving_them_keeps_it() + { + var userDirectory = TestFiles.NewTempDirectory(); + using var ui = new Harness(_directory, runner => runner.ConfigureProxy(userDirectory)); + + // Another TermRest saves a sign-in for the system's proxy, which every workspace without a proxy of its own uses. + var other = ProxyCredentialStore.Load(userDirectory); + other.Set("system", "CONTOSO\\ada", "s3cret-pw"); + other.Save(userDirectory); + + var saved = false; + var screens = Drive(ui, () => + { + SettingsDialog.Show(ui.App, ui.Workspace, ui.Runner, out saved, userDirectory); + ui.App.RequestStop(); + }, + ("Workspace settings", () => ui.Click("► Save ◄"))); + + Assert.Contains("CONTOSO\\ada", Assert.Single(screens), StringComparison.Ordinal); + Assert.True(saved); + Assert.Equal("s3cret-pw", ProxyCredentialStore.Load(userDirectory).Find(null)?.Password); + Assert.Equal("ada", ui.Runner.CreateDefaults().ProxyCredential?.UserName); // for this session too + } + + [Fact] + public void Naming_a_proxy_while_no_sign_in_is_shown_keeps_the_one_kept_for_that_proxy() + { + var userDirectory = TestFiles.NewTempDirectory(); + var kept = ProxyCredentialStore.Load(userDirectory); + kept.Set("http://corp-proxy:3128", "bob", "hunter2-pw"); // saved with another workspace + kept.Save(userDirectory); + using var ui = new Harness(_directory, runner => runner.ConfigureProxy(userDirectory)); + + var saved = false; + var screens = Drive(ui, () => + { + SettingsDialog.Show(ui.App, ui.Workspace, ui.Runner, out saved, userDirectory); + ui.App.RequestStop(); + }, + ("Workspace settings", () => + { + // That proxy in place of the system's, for which no sign-in is kept: the sign-in fields stay empty. + var label = ui.Find("Proxy "); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(label.X + 23, label.Y))); + ui.App.InjectKey(Key.End); + foreach (var _ in "system") + { + ui.App.InjectKey(Key.Backspace); + } + + ui.Type("http://corp-proxy:3128"); + ui.Click("► Save ◄"); + })); + + Assert.Single(screens); + Assert.True(saved); + Assert.Equal("hunter2-pw", ProxyCredentialStore.Load(userDirectory).Find("http://corp-proxy:3128")?.Password); + var credential = ui.Runner.CreateDefaults().ProxyCredential; + Assert.Equal(("http://corp-proxy:3128", "bob", "hunter2-pw"), (ui.Workspace.Settings.Proxy, credential?.UserName, credential?.Password)); + } + [Theory] [InlineData("http://ada:***@proxy:3128", "http://ada:s3cret@proxy:3128")] // left as shown [InlineData("http://ada:***@proxy:8080", "http://ada:s3cret@proxy:8080")] // only the port changed From 0bf11b18214b51a54cff180824c80a38ac2c83e6 Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Wed, 18 Nov 2026 01:18:47 -0700 Subject: [PATCH 09/11] TUI: memory given back when idle; the example editor made when first used The full-screen UI kept about 75 MB of private memory while idle, for a managed heap of about 12 MB live: the rest was what starting (reading the workspace, building and drawing the window) left behind, which the GC keeps until its next collection, however long the UI stays idle. UiPace now runs one full, compacting collection that gives memory back (GCCollectionMode.Aggressive) once the UI is idle, a second after it starts and after each time it was in use, when 8 MB or more were allocated since the last one: a few milliseconds while nothing happens. Idle on the samples, the UI takes about 32 MB (working set, Windows x64; about 87 MB before), with no change in CPU at startup or when idle. The editor of an example's response is made when the first example is opened, as most sessions open none: made at startup, it alone added 8 MB to the idle memory. README: the numbers. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 4 +-- src/TermRest.Tui/MainWindow.cs | 48 ++++++++++++++++++++--------- src/TermRest.Tui/TimerResolution.cs | 36 +++++++++++++++++++++- 3 files changed, 70 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index a1124f7..cf53ae9 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ A small terminal REST client for development and testing. **It is not another Po **Small by design:** - One native executable of about 21 MB. Nothing else to install: no runtime, no browser engine. -- The full-screen UI, with a workspace open, takes under 90 MB of memory and next to no CPU when idle (16 ms of CPU time in 10 idle seconds). A `termrest send` takes about 23 MB. *(Working set, measured on Windows x64.)* +- The full-screen UI, with a workspace open, takes about 32 MB of memory and next to no CPU when idle (a few tens of milliseconds of CPU time in 10 idle seconds): once idle, it gives back the memory that starting and working left behind. A `termrest send` takes about 23 MB. *(Working set, measured on Windows x64.)* - No account, no cloud sync, no telemetry, no update checks, no background service: when you quit, nothing of it keeps running. Script runtimes start only for the scripts that need them, and stop when idle. - Collections stay Postman's own files, so Postman and Newman open them at any time, for the 20% that TermRest leaves out: mock servers, monitors, team workspaces, API design and documentation, and gRPC and WebSocket requests. @@ -21,7 +21,7 @@ What it has: - **Large bodies from files.** Send a file as the body without loading it: it is streamed when the request is sent, and a JSON or XML file is checked first. - **Client certificates (mutual TLS)** are first-class: PEM (including encrypted keys and chains), PFX/PKCS#12, and OS certificate stores. That includes the Windows certificate store with non-exportable keys and the macOS keychain. Certificates bind to URL patterns via a Newman-compatible registry, and a TLS tab shows exactly what was negotiated and presented. - **OAuth 2.0 tokens fetched for you** from any standards-based authorization server: client credentials, password, and authorization code with or without PKCE (you sign in with your browser). The client authenticates with its secret, or with a JWT signed by one of your client certificates. Tokens are kept in memory only and refreshed when they expire. See [OAuth 2.0](#oauth-20). -- **One native executable** per platform: Windows, macOS and Linux on x64 and ARM64. Built with .NET 10 Native AOT: about 20 MB, starts in about 50 ms, no runtime to install. +- **One native executable** per platform: Windows, macOS and Linux on x64 and ARM64. Built with .NET 10 Native AOT: about 21 MB, starts in about 50 ms, no runtime to install. - **A headless CLI** (`send`, `run`, `validate`, `convert`, `history`, `import-curl`, `certs`) for scripts and CI, using the same engine. > Status: **first prototype** (v0.1). See [Roadmap](#roadmap) and the original [design proposal](docs/design-proposal.md). diff --git a/src/TermRest.Tui/MainWindow.cs b/src/TermRest.Tui/MainWindow.cs index ee48183..cf11b06 100644 --- a/src/TermRest.Tui/MainWindow.cs +++ b/src/TermRest.Tui/MainWindow.cs @@ -35,7 +35,7 @@ internal sealed class MainWindow : Runnable private readonly HistoryView _history; private readonly RequestEditor _editor; private readonly ResponseView _response; - private readonly ExampleResponseEditor _exampleEditor; + private ExampleResponseEditor? _exampleEditor; // see ExampleEditor private readonly Shortcut _environmentShortcut; private readonly RecordingIndicator _recordIndicator; private readonly Shortcut _message; @@ -146,8 +146,7 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) Height = Dim.Fill(1), }; _response = new ResponseView(); - _exampleEditor = new ExampleResponseEditor { Visible = false }; - _responseFrame.Add(_response, _exampleEditor); + _responseFrame.Add(_response); // Window shortcuts, not application-wide ones: they must not act behind an open dialog. Names and messages are // shown as written. @@ -198,7 +197,7 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) } else if (item is ExampleNode example && OpenExample(example)) { - _exampleEditor.SetFocus(); + ExampleEditor.SetFocus(); } }; _tree.ContextMenuRequested += (_, position) => ShowContextMenu(position); @@ -213,7 +212,6 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) _history.ContextMenuRequested += (_, position) => ShowHistoryContextMenu(position); _history.DeleteRequested += (_, entry) => DeleteHistoryEntry(entry); _editor.Modified += (_, _) => UpdateTitles(); - _exampleEditor.Modified += (_, _) => UpdateTitles(); _response.SaveAsExampleRequested += (_, _) => SaveResponseAsExample(); _editor.SendRequested += (_, _) => Send(); _editor.GetTokenRequested += (_, _) => GetNewToken(); @@ -292,8 +290,24 @@ internal void ShowRequest(RequestNode node) } } - /// The editor of an example's response (for tests). - internal ExampleResponseEditor ExampleEditor => _exampleEditor; + /// + /// The editor of an example's response, in the response pane's place while an example is open. Made when the first one + /// is opened: most sessions open none, and need not build it when they start. + /// + internal ExampleResponseEditor ExampleEditor + { + get + { + if (_exampleEditor is null) + { + _exampleEditor = new ExampleResponseEditor { Visible = false }; + _exampleEditor.Modified += (_, _) => UpdateTitles(); + _responseFrame.Add(_exampleEditor); + } + + return _exampleEditor; + } + } /// Selects and opens a saved example (for tests). internal void ShowExample(ExampleNode example) @@ -429,9 +443,9 @@ private bool OpenExample(ExampleNode example) var spec = example.ReadSpec(); _editor.ExampleMode = true; _editor.Load(spec.Request); - _exampleEditor.Load(spec); + ExampleEditor.Load(spec); _response.Visible = false; - _exampleEditor.Visible = true; + ExampleEditor.Visible = true; _responseFrame.Title = "Example response"; UpdateTitles(); return true; @@ -447,8 +461,12 @@ private void LeaveExample() _example = null; _editor.ExampleMode = false; - _exampleEditor.MarkClean(); - _exampleEditor.Visible = false; + if (_exampleEditor is { } exampleEditor) + { + exampleEditor.MarkClean(); + exampleEditor.Visible = false; + } + _response.Visible = true; SetResponseTitle(null); } @@ -473,18 +491,18 @@ private void CommitEditor() { if (_example is not null && _collection is not null) { - if (_editor.IsModified || _exampleEditor.IsModified) + if (_editor.IsModified || ExampleEditor.IsModified) { var spec = _example.ReadSpec(); spec.Request = _editor.Spec; - _exampleEditor.ApplyTo(spec); + ExampleEditor.ApplyTo(spec); if (_collection.UpdateExample(_example, spec)) { _tree.RefreshItem(_collection); } _editor.MarkClean(); - _exampleEditor.MarkClean(); + ExampleEditor.MarkClean(); UpdateTitles(); } @@ -2474,7 +2492,7 @@ private void ShowPopover(List items, System.Drawing.Point? position) private void UpdateTitles() { - var dirty = _editor.IsModified || _exampleEditor.IsModified || _collection?.IsDirty == true ? " ●" : ""; + var dirty = _editor.IsModified || _exampleEditor?.IsModified == true || _collection?.IsDirty == true ? " ●" : ""; var title = _example is { } example ? $"Example — {_workspace.DisplayName(example.Collection)} / {example.Request.PathInCollection} / {example.Name}{dirty}" : _node is not null diff --git a/src/TermRest.Tui/TimerResolution.cs b/src/TermRest.Tui/TimerResolution.cs index b0bf761..e677475 100644 --- a/src/TermRest.Tui/TimerResolution.cs +++ b/src/TermRest.Tui/TimerResolution.cs @@ -72,21 +72,31 @@ public void Dispose() /// , with 1 ms timer resolution (), from keyboard or /// mouse input until after the last one, and while a request is on its way; otherwise at /// Terminal.Gui's default rate (25 passes a second) and the system's timer resolution. The main loop reads the rate -/// before each pass, so a change applies from the next one. +/// before each pass, so a change applies from the next one. Once the UI is idle, after starting and after use, the memory +/// that what it did left behind is given back (see ). /// internal sealed class UiPace : IDisposable { + /// + /// What must have been allocated since the last trim for the next one to run: below it there is little to give back, + /// and idling costs no collection. + /// + private const long TrimAfter = 8 * 1024 * 1024; + private readonly IApplication _app; private readonly Func _busy; private readonly ushort _idleRate = Application.MaximumIterationsPerSecond; private IDisposable? _timerResolution; private long _activeUntil; + private long _trimAt; // when the UI, idle then, gives back memory (0: not due) + private long _allocatedAtTrim; /// Whether a request is on its way: the UI stays quick until its response is shown. public UiPace(IApplication app, Func? busy = null) { _app = app; _busy = busy ?? (() => false); + _trimAt = Environment.TickCount64 + 1000; // once the window is shown and the workspace read app.Keyboard.KeyDown += OnKeyDown; app.Mouse.MouseEvent += OnMouse; app.Iteration += OnIteration; @@ -114,6 +124,12 @@ private void OnIteration(object? sender, EventArgs e) { if (_timerResolution is null) { + if (_trimAt != 0 && Environment.TickCount64 >= _trimAt && !_busy()) + { + _trimAt = 0; + Trim(); + } + return; } @@ -124,6 +140,7 @@ private void OnIteration(object? sender, EventArgs e) else if (Environment.TickCount64 >= _activeUntil) { Idle(); + _trimAt = Environment.TickCount64; // the next pass, not when disposed } } @@ -146,4 +163,21 @@ private void Idle() _timerResolution = null; } } + + /// + /// Gives back the memory the UI is not using: what it allocated meanwhile (reading the workspace, drawing, responses + /// shown) is garbage now, which the GC would keep until it next runs, as long as the UI stays idle. A full, compacting + /// collection takes a few milliseconds while nothing happens. + /// + private void Trim() + { + var allocated = GC.GetTotalAllocatedBytes(); + if (allocated - _allocatedAtTrim < TrimAfter) + { + return; + } + + GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, blocking: true, compacting: true); + _allocatedAtTrim = GC.GetTotalAllocatedBytes(); + } } From b412897c9730d8bcf037624e78ecb309845b3b3f Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Wed, 18 Nov 2026 01:32:06 -0700 Subject: [PATCH 10/11] Tests: the stream timeout test no longer races the server's first answer On CI runners, a new test server's first answer (its endpoint is built on the first request) took longer than the 400 ms request timeout, which then ended the request before the stream began: no response, and a NullReferenceException in the test. The test now warms the endpoint with a short stream first, gives the timed request 2 s, and reports the exchange's error if there is no response. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/TermRest.Core.Tests/StreamingTests.cs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/TermRest.Core.Tests/StreamingTests.cs b/tests/TermRest.Core.Tests/StreamingTests.cs index 518368c..d835eff 100644 --- a/tests/TermRest.Core.Tests/StreamingTests.cs +++ b/tests/TermRest.Core.Tests/StreamingTests.cs @@ -106,14 +106,17 @@ public async Task A_stream_its_watcher_stops_keeps_what_arrived() public async Task The_request_timeout_stops_a_stream_and_keeps_what_arrived() { await using var server = await EchoServer.StartAsync(); - var request = Prepare(server.Url("events?count=0&delay=20"), timeout: TimeSpan.FromMilliseconds(400)); + + // A new server's first answer can take a while on a busy machine (CI), longer than the timeout would leave the stream. + await new HttpExecutor().SendAsync(Prepare(server.Url("events?count=1")), _ct); + var request = Prepare(server.Url("events?count=0&delay=20"), timeout: TimeSpan.FromSeconds(2)); var exchange = await new HttpExecutor().SendAsync(request, _ct); - var response = exchange.Response!; - Assert.True(response.Stopped); - Assert.StartsWith("id: 1\nevent: tick\n", Encoding.UTF8.GetString(response.Body), StringComparison.Ordinal); - Assert.Equal(["The stream was stopped at the request timeout (400 ms): its body is what arrived until then."], request.Warnings); + Assert.True(exchange.Response is not null, exchange.ErrorMessage); + Assert.True(exchange.Response.Stopped); + Assert.StartsWith("id: 1\nevent: tick\n", Encoding.UTF8.GetString(exchange.Response.Body), StringComparison.Ordinal); + Assert.Equal(["The stream was stopped at the request timeout (2.00 s): its body is what arrived until then."], request.Warnings); } [Fact] From af1f9ed320ac6ab5b7a5af0f6ccd1a33454c3487 Mon Sep 17 00:00:00 2001 From: Shike Chen Date: Wed, 18 Nov 2026 01:42:32 -0700 Subject: [PATCH 11/11] Tests: the stream timeout test connects to 127.0.0.1, where the server listens The test server listens on 127.0.0.1, and its URLs say localhost, which a Windows runner resolves to ::1 first: Windows takes 2 s to give up on a refused connection, which the test's 2 s request timeout did not leave room for. The timed request (and the one before it, which builds the server's endpoint) now goes to 127.0.0.1. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/TermRest.Core.Tests/StreamingTests.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/TermRest.Core.Tests/StreamingTests.cs b/tests/TermRest.Core.Tests/StreamingTests.cs index d835eff..400b414 100644 --- a/tests/TermRest.Core.Tests/StreamingTests.cs +++ b/tests/TermRest.Core.Tests/StreamingTests.cs @@ -107,9 +107,12 @@ public async Task The_request_timeout_stops_a_stream_and_keeps_what_arrived() { await using var server = await EchoServer.StartAsync(); - // A new server's first answer can take a while on a busy machine (CI), longer than the timeout would leave the stream. - await new HttpExecutor().SendAsync(Prepare(server.Url("events?count=1")), _ct); - var request = Prepare(server.Url("events?count=0&delay=20"), timeout: TimeSpan.FromSeconds(2)); + // 127.0.0.1, where the server listens: localhost can resolve to ::1 first (Windows runners), and Windows takes 2 s to + // give up on it. A new server's first answer can take a while on a busy machine (CI) too, longer than the timeout + // would leave the stream. + string Url(string path) => server.Url(path).Replace("localhost", "127.0.0.1", StringComparison.Ordinal); + await new HttpExecutor().SendAsync(Prepare(Url("events?count=1")), _ct); + var request = Prepare(Url("events?count=0&delay=20"), timeout: TimeSpan.FromSeconds(2)); var exchange = await new HttpExecutor().SendAsync(request, _ct);