diff --git a/README.md b/README.md index c2e01fe..1e13505 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ dotnet publish src/TermRest.Cli -c Release -r win-x64 # or win-arm64, linux ./src/TermRest.Cli/bin/Release/net10.0/win-x64/publish/termrest.exe samples ``` -`termrest` with no command opens the UI in the current directory. You can also pass a workspace folder, a single `*.postman_collection.json` (its folder becomes the workspace), or a Postman v3 collection folder. +`termrest` with no command opens the UI in the current directory. You can also pass a workspace folder, a single `*.postman_collection.json` (its folder becomes the workspace, or for one in `postman/collections` the folder that holds `postman`), or a Postman v3 collection folder. ## Workspace layout @@ -87,24 +87,40 @@ my-api/ ├─ workspace.postman_globals.json ← optional ├─ certs/ ← your certificate files (don't commit private keys) └─ .termrest/ - ├─ settings.json ← active environment, TLS verification, CA bundle, timeout, proxy, history, YAML wrapping, color theme, recording redaction… + ├─ settings.json ← active environment, TLS verification, CA bundle, timeout, proxy (used once you allow it), history, YAML wrapping, color theme, recording redaction… ├─ certificates.json ← client-certificate registry (Newman --ssl-client-cert-list format) └─ themes/ ← optional: color themes shared with the workspace ``` -The collections and environments can also be in Postman's v3 layout (`postman/collections/…`, YAML); see [Postman v3 (YAML) collections](#postman-v3-yaml-collections). +The collections and environments can also be in Postman's v3 layout (`postman/collections/…`, YAML); see [Postman v3 (YAML) collections](#postman-v3-yaml-collections). A folder of the workspace that can't be listed (one you may not read, say), or a link to a folder that is gone (a collection linked from a repository that was moved), is reported when the workspace opens; the rest of the workspace loads. -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: `{{$guid}}`, `{{$timestamp}}`, `{{$isoTimestamp}}`, `{{$randomInt}}`, and others. Unresolved `{{names}}` are kept and reported as warnings. +Environments can share a name (an updated export imported next to the old one, or a JSON environment and the YAML copy `termrest convert` made of it). TermRest remembers the active one by its file (`activeEnvironmentFile` in `.termrest/settings.json`, next to its name in `activeEnvironment`), so it stays the one you picked, also after a restart; the environment menu, the status bar and *Manage environments* show such environments with their file names, or with their paths in the workspace where the file names are the same too (`Local.postman_environment.json` in the workspace folder and in `postman/environments`). When that file is gone, or the settings were written by an earlier version, the first environment with that name is active. + +Collections can share a name the same way (an updated export imported next to the old one is copied in as `Orders API (2).postman_collection.json`; `termrest convert` puts a v3 copy in `postman/collections` next to the JSON one). The tree and the request pane's title show such collections with their file (or v3 folder) names, or with their paths in the workspace where those are the same too, and the history keeps the file each request was sent from (see [Request history](#request-history)). + +The files TermRest creates for new and imported collections, environments and theme copies are named for every OS, as a workspace is shared through Git: characters Windows doesn't allow in a file name (`/ \ : * ? " < > |`, control characters) become `-`, also on Linux and macOS, and so does a leading `.`; a reserved name (`CON`, `NUL`, `COM1` …) gets a `-`, also before an extension (`con.example.org` becomes `con-.example.org`, as Windows reserves `CON` with any extension), and a long name is cut to 64 characters (the name inside the file stays whole). A name that differs only in case from a file already there gets a number, as Windows and macOS don't tell such names apart (`orders API (2).postman_collection.json` next to `Orders API.postman_collection.json`). + +*File › Import Postman environment…* also takes a globals export (`*.postman_globals.json`): it becomes the workspace's globals, saved as `workspace.postman_globals.json` (`postman/globals/workspace.globals.yaml` in the v3 layout). A workspace has one set of globals: while it has some, such an import is refused, and they stay as they are. + +A `settings.json` or `certificates.json` that can't be read (invalid JSON, a merge conflict) is reported when the workspace opens and is never saved over; fix or delete it. The same goes for your user settings (theme, script runtimes, the proxies you allowed); `send` and `run` warn when those can't be read, as the script runtimes and language order chosen in them aren't used then, nor a proxy you allowed. While `.termrest/settings.json` can't be read, `send` and `run` send nothing and exit with code 1 (the file may set the proxy, TLS verification, the history and what recordings redact), and nothing goes into the history. TermRest writes only the settings you change into `.termrest/settings.json` (the active environment's name and file together), into the file as it is then: settings a `git pull` changed meanwhile and ones TermRest doesn't know are kept (comments are not). Nothing is written when nothing changed. + +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. + +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. ## Using the UI -Everything is clickable: menus, tree items, tabs, buttons, table rows, and checkboxes. Drag the right edge of the Collections pane, or the bottom edge of the Request pane, to resize. Right-click a tree item for actions. Double-click a table row to edit it, and click its checkbox to enable or disable it. +Everything is clickable: menus, tree items, tabs, buttons, table rows, and checkboxes. Drag the right edge of the Collections pane, or the bottom edge of the Request pane, to resize. The tree and the lists (environments, color themes, history) show a character outside Unicode's Basic Multilingual Plane (most emoji) as `�`, as Terminal.Gui can't draw one there; names keep it. Help texts and *Workspace info* scroll when taller than the screen (mouse wheel, arrow keys, PgDn). Right-click a tree item for actions (*Send* and *Copy as cURL* act on that request). Double-click a table row to edit it, and click its checkbox to enable or disable it (every click counts, even two quick ones, and moves the cursor to that row; the header's checkbox does every row): a value or description with line breaks (a PEM key, a JSON part) is edited in a text area, and what you leave alone keeps its value. *Bulk edit* shows a table as `key:value` lines: line breaks in values show as `\n`, and secret values are masked (leave the mask to keep the value). Keys may contain `:` themselves (`Api:BaseUrl:https://api.example.com`): a line is read as the row it shows as written (also when rows share a key), else as the row whose key it starts with (the longest such key), else split at its first `:`. A renamed line is the row that was in its place; when it isn't clear which secret a mask stands for, TermRest asks for the value. + +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. | Key | Action | Key | Action | |---|---|---|---| | F5 / Enter in URL bar / Ctrl+Enter | Send (press again to cancel) | Esc | Cancel a running request | | Ctrl+S | Save all changed files | Ctrl+N | New request; adds an imported or history request to a collection | -| F2 | Rename tree item | Del | Delete tree item / table row / history entry | +| F2 | Rename tree item | Del / Insert | Delete tree item, table row or history entry / add a table row | | F7 | Switch environment | F8 | Client certificates | | F9 | Switch the sidebar: Collections ⇄ History | Paste into the URL bar | Import a curl command | | F6 / Shift+F6 | Next / previous pane | Tab / Shift+Tab | Next / previous field | @@ -114,32 +130,34 @@ Everything is clickable: menus, tree items, tabs, buttons, table rows, and check **Request editor tabs** -- **Params:** query parameters (kept in sync with the URL) and path variables (`:id` segments). -- **Headers** -- **Auth:** inherit, none, Basic, Bearer, API key, Digest, NTLM, or an OAuth 2.0 access token. Other Postman auth types are kept but not yet applied. -- **Body:** none, raw (JSON, XML, text, HTML, JavaScript, with Beautify), form-data with files, x-www-form-urlencoded, a file (see [Sending a file as the body](#sending-a-file-as-the-body)), or GraphQL. +- **Params:** query parameters (kept in sync with the URL) and path variables (`:id` segments). Values are sent as typed, except that a `#` in a query parameter, a path variable or a `{{variable}}` in the path, and a `?` in a path variable, are sent percent-encoded (`%23`, `%3F`): they stay part of the value instead of ending the query or path, where the rest would not be sent. +- **Headers:** values are sent as typed, in UTF-8 as curl sends them (`X-User: José` works), and cookies a server set go back in the bytes it sent them in; a value with a line break or NUL is refused (a trailing line break is dropped), so a value can never add a header of its own. Headers that describe a body (`Content-Type`, `Content-Encoding` …) are left out of a request without one, with a warning. +- **Auth:** inherit, none, Basic, Bearer, API key, Digest, NTLM, or an OAuth 2.0 access token. Other Postman auth types are kept but not yet applied. Passwords, tokens and API key values are masked. An empty Bearer token (as a login request's script fills in later) adds no header, as in Postman, and a warning says so: an `Authorization` header the request has stays. Digest and NTLM credentials answer only their own scheme's challenges (NTLM also Negotiate) from the request's origin, never a Basic one. Credentials in the URL (`https://user:password@host`) are sent as Basic auth, as curl and Postman send them, unless the request has an `Authorization` header or an auth helper; as in Postman, a `{{variable}}` there may hold any character: `@ / ? # \` in its value are encoded, so a password with them neither ends the user info nor makes the URL invalid. The history masks the password, or the user name of a URL without one (`https://***@host`), which is then the credential. An API key or OAuth 2.0 token sent in the query is URL-encoded and replaces a parameter of the same name. +- **Body:** none, raw (JSON, XML, text, HTML, JavaScript, with Beautify), form-data with files, x-www-form-urlencoded, a file (see [Sending a file as the body](#sending-a-file-as-the-body)), or GraphQL. Form-data is sent as browsers, curl and Postman send it: field and file names in UTF-8, a field's content type as typed (one with a line break or NUL is refused), and a file without one with the type of its extension (`.gif`, `.jpg`, `.jpeg`, `.png`, `.svg`, `.txt`, `.htm`, `.html`, `.pdf`, `.xml`, `.json`; any other gets `application/octet-stream`). An empty body is no body, sent without a `Content-Type`, as in Postman: raw text that is empty once its `{{variables}}` are replaced, a form with no enabled field, or a file body without a file (a warning says so). - **Scripts:** pre-request and post-response (test) scripts, in Python, JavaScript, C# or PowerShell (see [Scripts](#scripts)). -- **Settings:** per-request SSL verification and redirects, which client certificate applies, and the description. +- **Settings:** per-request SSL verification and redirects, which client certificate applies, and the description. Redirects are followed like `curl -L`: at most *max redirects* (0 follows none; a negative `maxRedirects` on a request, as earlier imports of `--max-redirs -1` saved it, uses the workspace's), never from https to http; 301 and 302 turn a POST into a GET, 303 any method but HEAD, and 307 and 308 send the method and body again. The `Authorization`, `Proxy-Authorization`, `Cookie` and `Host` headers and the auth helper's (such as an API key) go only to the request's origin (scheme, host and port); other headers follow the redirect. The URL a redirect leads to never takes the user and password of the request's URL (they are sent as its `Authorization` header), so it is shown, kept in the history and recorded without them. + +Text editors show tabs 4 columns wide (the Tab key moves to the next field). Every line break, whether CRLF, LF or a lone CR, shows as one, and an edited body, script or description is saved with LF line breaks. **Response tabs** -- **Body:** pretty or raw view, wrap, copy, save. -- **Headers** -- **Timeline:** the exact request sent, DNS/connect/TLS/TTFB/download timing, and warnings. +- **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. +- **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. +- **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. +- **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. ### Sending a file as the body -For a large payload, choose **file** in the Body tab instead of pasting it into the editor. TermRest keeps only the file's path and reads the file each time the request is sent, streaming it: it is never loaded into memory, and you can keep editing it in another program. +For a large payload, choose **file** in the Body tab instead of pasting it into the editor. TermRest keeps only the file's path and reads the file each time the request is sent, streaming it: it is never loaded into memory, and you can keep editing it in another program, even one that keeps it open for writing (Excel, a log writer). Whatever such a program adds while the file is being sent is left out: it is sent as long as it was when sending started (form-data files too). - **Type:** *Binary* sends the file as it is (`application/octet-stream`). *JSON*, *XML*, *Text*, *HTML* and *JavaScript* set the matching Content-Type and check the file first: - **JSON** must be valid, UTF-8 JSON. A byte order mark is fine; UTF-16 is not, and is named as the problem. - - **XML** must be well-formed. Its DTD is never processed, so entities never read other files. + - **XML** must be well-formed, in the encoding its declaration names (legacy ones such as windows-1252, ISO-8859-15 or Shift_JIS included). Its DTD is never processed, so entities never read other files. - **Text, HTML and JavaScript** must look like text (no NUL bytes, no UTF-16). - **When it is checked:** when you choose the file (a file that does not fit the type is turned down, with the line and column of the problem) and again each time the request is sent, since the file may have changed. A file that no longer fits is not sent. Checking streams through a 64 KB buffer: only a single value larger than that, such as a long base64 string, needs more. - **Content-Type:** a `Content-Type` header on the request wins, for example `application/merge-patch+json` with the JSON type. To send deliberately broken JSON, choose *Binary* and set the header yourself. -- **Paths:** a relative path starts at the collection's folder, and `{{variables}}` work. The file is sent byte for byte: `{{variables}}` inside it are not replaced. +- **Paths:** a relative path starts at the collection's folder, and `{{variables}}` work. The file must be in the workspace folder, unless you allow files from outside it (see [Workspace layout](#workspace-layout)); until then, the Body tab doesn't look up a path outside the folder either, and says so. The file is sent byte for byte: `{{variables}}` inside it are not replaced. A typed path is looked up in the background once you pause typing, so a slow or disconnected network drive never holds up the UI. - **Postman:** the body is Postman's binary body (`"mode": "file"`); the type is stored as `"language"` in its `file` object, which Postman ignores. - **Recordings** keep the file's path, not its content (see [Recording requests](#recording-requests)). While recording, the Body tab says so. @@ -167,9 +185,9 @@ A runtime answers in about a millisecond once started; starting takes 0.1–0.3 **Choosing the runtimes** -- **In the UI:** *Tools › Scripts…*, one row for each language. Type a command (`python3`, `node`, `bun`, `dotnet`, `pwsh`) or a path, which may be relative to the workspace (`.venv/bin/python`, `.venv\Scripts\python.exe`). Or press **Find**: for Python, it looks for `.venv`, `venv` and `env` in the workspace, then `python3` and `python` on PATH; for JavaScript, `node` and `bun` on PATH; for C#, `dotnet` on PATH, then `~/.dotnet`; for PowerShell, `pwsh` on PATH, then `C:\Program Files\PowerShell\7` on Windows. **Check** shows the version. Python 3.8, Node.js 18 or Bun 1.1, the .NET 10 SDK, and PowerShell 7.0 or later are needed (for C#, the SDK: a .NET runtime alone cannot build scripts; for PowerShell, `pwsh`: Windows PowerShell 5.1, `powershell.exe`, is too old). +- **In the UI:** *Tools › Scripts…*, one row for each language. Type a command (`python3`, `node`, `bun`, `dotnet`, `pwsh`) or a path, which may be relative to the workspace (`.venv/bin/python`, `.venv\Scripts\python.exe`). A command is looked up in the folders of PATH only (on Windows as `name.exe`, unless the name already ends with a program extension from PATHEXT, such as `.cmd`: `python3.12` is `python3.12.exe`; for pyenv-win's shim, type `python.bat`), never in the workspace or TermRest's own folder. A file picked with *Browse…* in the workspace's own folder is kept as `./name`, a path. Or press **Find**: for Python, it looks for `.venv`, `venv` and `env` in the workspace, then `python3` and `python` on PATH; for JavaScript, `node` and `bun` on PATH; for C#, `dotnet` on PATH, then `~/.dotnet`; for PowerShell, `pwsh` on PATH, then `C:\Program Files\PowerShell\7` on Windows. A Python found in the workspace is filled in without being run, as it may have come with the repository: **Check** runs it and shows the version. Python 3.8, Node.js 18 or Bun 1.1, the .NET 10 SDK, and PowerShell 7.0 or later are needed (for C#, the SDK: a .NET runtime alone cannot build scripts; for PowerShell, `pwsh`: Windows PowerShell 5.1, `powershell.exe`, is too old). - **Your choices are kept per workspace folder in your user settings**, never in the workspace. A cloned repository cannot choose a program for TermRest to run. -- **On the command line:** `--python `, `--javascript `, `--csharp ` and `--powershell ` on `send` and `run`; without them, the UI's choices for that workspace apply. `--script-order ` changes the [language order](#languages) for the run. `--no-scripts` turns scripts off. +- **On the command line:** `--python `, `--javascript `, `--csharp ` and `--powershell ` on `send` and `run`; without them, the UI's choices for that workspace apply. A path there is relative to the current folder, as the command line's other paths are (from a repository's root: `termrest run postman/api.postman_collection.json --python .venv/bin/python`); a command such as `node` is looked up on PATH. `--script-order ` changes the [language order](#languages) for the run. `--no-scripts` turns scripts off. - **No runtime chosen for a language:** in the UI, its scripts are skipped and the request is sent; the status line says `⚠ scripts not run` and the *Scripts* tab says which. On the command line, that is an error (so a CI run never passes without its tests): the request is not sent, and the message says to pass `--python`, `--javascript`, `--csharp`, `--powershell` or `--no-scripts`. A missing runtime does not make a request choose another language: the language depends on the scripts only (see below). **Writing scripts** @@ -179,9 +197,9 @@ A runtime answers in about a millisecond once started; starting takes 0.1–0.3 - **Syntax colors:** the script editors color the syntax of the language shown: comments, strings, numbers and constants, keywords, function calls, types, and PowerShell's variables and parameters, in the [color theme](#color-themes)'s script colors. This is plain highlighting, with no completion or error checking. - **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. +- **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.`). - **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 set to `42` reads back as `"42"` in the next request or phase, and lists and objects become JSON. +- **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. **Languages: one per request** @@ -197,21 +215,21 @@ 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}}` in a text. | -| `tr.request` | `.method`, `.url`, `.headers` (`.get`, `.get_all`, `.set`, `.add`, `.remove`, `.items()`), `.body` (raw bodies). Pre-request scripts can change them; `{{variables}}` they contain are replaced afterwards. Test scripts see the request as it was sent. | +| `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.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`. | -| `print(…)` | Goes to the response's *Scripts* tab, and to stderr on the command line. | +| `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.request` | `.method`, `.url` (`.query.add`, `.toString()`, `.getHost()` …), `.headers` (`.add`, `.upsert`, `.remove`, `.get`, `.has`, `.each` …), `.body.raw`. Pre-request scripts can change them, as with `tr.request`. | -| `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`, `.json` … | -| `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. | +| `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.info`, `pm.cookies`, `console.log` … | As in Postman; `console` output goes where `print` does. | +| `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. | | Not supported | `pm.execution.skipRequest()` (the request is not sent, with an error), `setNextRequest` (requests run in order), `pm.vault`, `pm.require` (Postman's package library), `pm.cookies.jar()`, `pm.visualizer` (ignored). Each script phase runs in a fresh context, as in Postman. | @@ -219,14 +237,14 @@ A collection, a folder and a request can each have a pre-request and a post-resp **C# scripts** - **Built, then run.** TermRest writes the C# scripts of a collection into one small program, each script the body of a method, and your .NET SDK builds it as a C# file without a project (`dotnet run --file`, new in .NET 10). The first build takes a few seconds (more when it restores NuGet packages); a change, about a second. Built programs are kept in TermRest's cache folder, so unchanged scripts start at once, in the next TermRest too: `%LOCALAPPDATA%\TermRest\csharp`, `~/Library/Caches/TermRest/csharp` or `~/.cache/termrest/csharp` (`TERMREST_CACHE_DIR` moves it). The 16 most recently used are kept, a few hundred KB each. -- **A script is the body of an async method:** statements, local functions, `await`, `return`. It may start with `using` directives and the directives of C# files: `#:package Name@1.2.3` (NuGet packages), `#:project path`, `#:property Name=Value`, and `#:include helpers.cs` (SDK 10.0.300 or later) for a file of your own types, as scripts cannot declare classes. Relative paths are relative to the workspace. Besides .NET's usual namespaces (`System`, `System.IO`, `System.Linq`, `System.Net.Http` …), `System.Text`, `System.Text.Json.Nodes` and `System.Text.RegularExpressions` are imported. -- **Compile errors name the script and its line**, as the compiler reports them. The scripts before it still run, and a script that does not compile does not keep the collection's other requests from running theirs. +- **A script is the body of an async method:** statements, local functions, `await`, `return`. It may start with `using` directives and the directives of C# files: `#:package Name@1.2.3` (NuGet packages), `#:project path`, `#:property Name=Value`, and `#:include helpers.cs` (SDK 10.0.300 or later) for a file of your own types, as scripts cannot declare classes. A `global using` applies to all the collection's C# scripts and the files they include, as the `#:` directives do. Relative paths are relative to the workspace, and a change to what `#:include` or `#:project` brings in builds the scripts again: code, resources and build files (`.cs`, `.resx`, `.razor`, project files, `.props`, `.targets` …) in the project's folder and in the projects it references (``, in turn), and the `Directory.Build.props`/`.targets`, `Directory.Packages.props`, `global.json` and `nuget.config` in the folders above them. Not the other files in those folders, such as the database or logs a program writes, and not references whose paths use MSBuild properties (`$(…)`) or wildcards, or files imported from other folders. Besides .NET's usual namespaces (`System`, `System.IO`, `System.Linq`, `System.Net.Http` …), `System.Text`, `System.Text.Json.Nodes` and `System.Text.RegularExpressions` are imported. +- **Compile errors name the script and its line**, as the compiler reports them; one in a file a script brings in (`#:include`, `#:project`) names that file, its line and column. The scripts before it still run, and a script that does not compile does not keep the collection's other requests from running theirs. Nor does one whose `#:package` can't be restored or whose `#:project` is missing: after its first failure, the other requests leave it out at once until TermRest closes (or *Tools › Scripts › Stop scripts*). The directives of all the scripts apply to the whole program: when another request's script breaks a request's own (its `#:property TreatWarningsAsErrors=true` turns a warning in them into an error, say), they are built without the collection's other scripts and report only their own errors. - **Building uses the SDK's compiler server**, which stays for 10 minutes after a build (about 160 MB), as with any `dotnet build`: it makes the next build quick. *Tools › Scripts › Stop scripts* stops it. | 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}}` in a text. | +| `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.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. | @@ -237,16 +255,17 @@ A collection, a folder and a request can each have a pre-request and a post-resp **PowerShell scripts** - **Run by PowerShell 7 (`pwsh`)**, on Windows, Linux and macOS: Windows PowerShell 5.1 does not run them. One `pwsh` runs the scripts of the session, started with `-NoProfile -NonInteractive`: your profile is not loaded, and modules load when a script imports them (`Import-Module`, `using module`, or by using their commands). -- **A script is a script block**, run with `$tr` in its scope. Functions and variables it defines are its own; modules it imports stay loaded for the next scripts. +- **A script is a script block**, run with `$tr` in its scope. Functions and variables it defines are its own; modules it imports stay loaded for the next scripts. `exit` ends the script, not PowerShell; with a code other than 0 it fails it, as `sys.exit(1)` does in Python. `break` and `continue` outside a loop end it too. - **Errors stop the script**, as exceptions do in the other languages: `$ErrorActionPreference` is `Stop`, so a command that reports an error (`Get-Item` of a missing file, say) fails it, with the script's line. Set it to `Continue` in a script that should carry on. -- **What a script writes goes to the *Scripts* tab:** its output (objects as PowerShell formats them), `Write-Host`, warnings, and `Write-Verbose` or `Write-Debug` when their preference lets them through. Output inside `$tr.Test` blocks is dropped; use `Write-Host` there. +- **What a script writes goes to the *Scripts* tab,** in the order it writes it: its output (objects as PowerShell formats them), `Write-Host`, `Out-Host` and `[Console]::WriteLine` (also from `ForEach-Object -Parallel` blocks and thread jobs), warnings, and `Write-Verbose` or `Write-Debug` when their preference lets them through. Tables come without the colors PowerShell 7.2 gives them on a terminal. Output inside `$tr.Test` blocks is dropped; use `Write-Host` there. +- **`$tr` belongs to the script's own runspace:** a `ForEach-Object -Parallel` block or a thread job (`Start-ThreadJob`) runs in another one, where calling `$tr` (`$using:tr`) waits for the script, which waits for the block, until the time limit stops PowerShell. Let such blocks return their results, and use `$tr` after them. - **PowerShell is the heaviest runtime** (see the table above): about 130 MB while scripts are in use, started in about 0.9 s. | 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}}` in a text. | -| `$tr.Request` | `.Method`, `.Url`, `.Headers` (`.Get`, `.GetAll`, `.Set`, `.Add`, `.Remove`, `.Has`, `.Items()`, `.Count`), `.Body` (raw bodies; `$null` for others). Pre-request scripts can change them. | +| `$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.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. | @@ -334,9 +353,12 @@ TermRest runs scripts the way a terminal runs commands: it starts the runtime yo **What TermRest does, and does not do** -- 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. +- 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. +- 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. +- Programs that scripts start get no terminal. On Linux and macOS the runtimes run in a session of their own, without TermRest's terminal, so a program that asks on the terminal (ssh or git for a passphrase, sudo) fails at once instead of drawing over TermRest's screen: use an agent, a credential helper or a token. Node.js and Bun get this on Linux when `setsid` (util-linux) is on PATH; on macOS, programs that JavaScript scripts start can still use the terminal. gpg's pinentry may still appear, as gpg-agent shows it on the terminal named by `GPG_TTY`. On Windows, each runtime has a hidden console of its own. If TermRest is killed while a script runs, that script runs to its end. - It does **not** sandbox, review, sign or limit scripts. - JavaScript gets a fresh context per phase for Postman compatibility, not for isolation: Node.js's `vm` module is not a security boundary. - A timeout stops the runtime, not what a script already did. @@ -345,8 +367,8 @@ TermRest runs scripts the way a terminal runs commands: it starts the runtime yo **Before you turn scripts on** - **Read the scripts first,** in every language (*Language* in the *Scripts* tab: a `•` marks those with scripts): the request's *Scripts* tab, and right-click › *Scripts…* on the collection and on each folder. In the files, they are the `event` entries (`script.exec`) of JSON collections, disabled ones included, and the `scripts` of v3 YAML files. Review changes to them as you review code. -- **Keep collections you did not write, or have not read, in a workspace folder with no runtime chosen.** On the command line, use `--no-scripts` for them. -- **Choose runtimes you installed yourself.** *Find* suggests the workspace's own `.venv`: in a repository you did not create, make sure it is one you made. +- **Keep collections you did not write, or have not read, in a workspace folder with no runtime chosen,** and don't allow files from outside it there. On the command line, use `--no-scripts` for them, without `--allow-outside-files`. +- **Choose runtimes you installed yourself.** *Find* suggests the workspace's own `.venv`: in a repository you did not create, make sure it is one you made before you press **Check** or save. - **Pin package versions** (`#:package Name@1.2.3`, lock files, `Import-Module Name -RequiredVersion 1.2.3`), and prefer package feeds you trust. - **Run collections from unknown sources in a container, a VM or a separate account.** In CI, give the job only the secrets its requests need: scripts see the job's environment. - **To turn scripts off again,** clear the runtime in *Tools › Scripts…* and save, or remove it from `pythonInterpreters`, `javaScriptRuntimes`, `csharpRuntimes` or `powerShellRuntimes` in your `settings.json`. @@ -357,7 +379,7 @@ Choose a theme in *Tools › Color theme…*. Moving through the list previews e - **Built in:** Terminal.Gui's themes (Default uses your terminal's own colors; Dark, Light, TurboPascal 5, Anders, 8-Bit, Green Phosphor, Amber Phosphor) and TermRest's Dracula, Gruvbox Dark, High Contrast, Monokai, Nord, Solarized Dark and Solarized Light. - **Method, status and script colors:** every theme colors the request methods in the tree (GET, POST, PUT, PATCH, DELETE, others), the response status (2xx/3xx, 4xx, 5xx), and the syntax of scripts. -- **Custom themes** are JSON files. *Copy as custom theme…* (or `termrest themes copy`) writes a copy of any theme for you to edit, and *Reload theme files* picks up your edits without a restart. A theme file names a `base` theme and changes some of its palette colors. Every color of the UI is derived from the palette's 28 colors. For full control, `schemes` sets single roles of Terminal.Gui's color schemes: +- **Custom themes** are JSON files. *Copy as custom theme…* (or `termrest themes copy`) writes a copy of any theme for you to edit, and *Reload theme files* picks up your edits without a restart. A copy of a custom theme needs no other theme file, so it looks the same in every workspace: it starts from a built-in theme, and its `schemes` keep the roles the custom theme sets beyond its palette (palette edits don't change those). Its name can't be one another custom theme already has (case aside): only one theme of a name is loaded, so the other would never show. The dialog proposes a free name (`My Dark 2`). A theme file names a `base` theme and changes some of its palette colors. Every color of the UI is derived from the palette's 28 colors. For full control, `schemes` sets single roles of Terminal.Gui's color schemes: ```jsonc { @@ -374,7 +396,7 @@ Choose a theme in *Tools › Color theme…*. Moving through the list previews e } ``` - Palette colors: `background`, `text`, `muted`, `accent` (hot keys), `selection`, `selectionText`, `input` (fields and tables), `bar`, `barText`, `dialog`, `dialogText`, `success`, `warning`, `error`, `get`, `post`, `put`, `patch`, `delete`, `otherMethods`, and for scripts `syntaxComment`, `syntaxKeyword` (with PowerShell's operators such as `-eq`), `syntaxString`, `syntaxNumber` (with constants such as `true` and `None`), `syntaxVariable` (PowerShell's `$name`), `syntaxFunction` (with PowerShell's commands and Python's decorators), `syntaxType` and `syntaxParameter` (PowerShell's `-Name`). A script color set to `None`, or too close to the editor's background to read, is drawn in the editor's text color. Schemes: `Base`, `Menu`, `Dialog`, `Error`, `Accent`, `Success`, `Warning`. Roles: `Normal`, `HotNormal`, `Focus`, `HotFocus`, `Active`, `HotActive`, `Highlight`, `Editable`, `ReadOnly`, `Disabled`. Mistakes such as an unknown key or an invalid color are listed in the dialog and by `termrest themes`, and the rest of the file still applies. + Palette colors: `background`, `text`, `muted`, `accent` (hot keys), `selection`, `selectionText`, `input` (fields and tables), `bar`, `barText`, `dialog`, `dialogText`, `success`, `warning`, `error`, `get`, `post`, `put`, `patch`, `delete`, `otherMethods`, and for scripts `syntaxComment`, `syntaxKeyword` (with PowerShell's operators such as `-eq`), `syntaxString`, `syntaxNumber` (with constants such as `true` and `None`), `syntaxVariable` (PowerShell's `$name`), `syntaxFunction` (with PowerShell's commands and Python's decorators), `syntaxType` and `syntaxParameter` (PowerShell's `-Name`). A script color set to `None`, or too close to the editor's background to read, is drawn in the editor's text color. Schemes: `Base`, `Menu`, `Dialog`, `Error`, `Accent`, `Success`, `Warning`. Roles: `Normal`, `HotNormal`, `Focus`, `HotFocus`, `Active`, `HotActive`, `Highlight`, `Editable`, `ReadOnly`, `Disabled`. A theme keeps the roles its base sets until it changes a surface color (any but the status, method and script colors), which derives its schemes from its palette again; a status scheme likewise until its color changes. Mistakes such as an unknown key or an invalid color are listed in the dialog and by `termrest themes`, and the rest of the file still applies. - **Where theme files go:** your own themes are in the `themes` folder of your TermRest configuration folder. That is `%APPDATA%\TermRest` on Windows, `~/Library/Application Support/TermRest` on macOS, and `$XDG_CONFIG_HOME/termrest` (default `~/.config/termrest`) on Linux. Set `TERMREST_CONFIG_DIR` to move it. Themes in a workspace's `.termrest/themes` folder are shared with everyone who uses the workspace. A custom theme with the name of a built-in one replaces it. - **Which theme is used:** `--theme ` for one session, else `$TERMREST_THEME`, else the workspace's choice (`theme` in `.termrest/settings.json`), else yours (`settings.json` in the configuration folder), else Default. @@ -391,14 +413,17 @@ Every request you send from the UI or with `termrest send` is recorded with its - **Storage:** history is kept per user, outside the workspace, so it never ends up in git. The location is `%LOCALAPPDATA%\TermRest\history` on Windows, `~/Library/Application Support/TermRest/history` on macOS, and `$XDG_STATE_HOME/termrest/history` (default `~/.local/state/termrest/history`) on Linux, with one folder per workspace. Set `TERMREST_STATE_DIR` to move it. On Unix only you can read the files. - **Masking:** secrets are masked before anything is written to disk: - - `Authorization`, `Cookie`, and headers whose names contain token, secret, password or api-key; + - `Authorization`, `Cookie`, and headers named like credentials (as in recordings: token, secret, password, API key, auth key, subscription key, signature, session id …), sent or received; - the value of every `Set-Cookie`; - - the request's auth credentials and the values of variables marked secret, including where a server echoes them back in a response body. + - the request's auth credentials and the values of variables marked secret (the value the request actually used, also when it comes from `--var`, a script's `tr.variables`/`pm.variables`, or another variable it references), including where a server echoes them back in a response body: as they are, URL-encoded (fully, or only where a URL needs it) or JSON-escaped (as .NET, JavaScript, Python, PHP or Go write it); in UTF-8, or in UTF-16 or UTF-32 when the body's charset or byte order mark says so; also where the size limit cuts it. This includes values that test scripts store in variables marked secret, in the very response they came from; + - credentials typed into the request itself (auth fields, such headers, the password in the URL, a client certificate's passphrase), which are stored as `***`; a `Cookie` header keeps its cookie names (`sid=***`). A Basic user name without a password is the credential (an API key, as Stripe takes it: `curl -u sk_test_…:`), and so is the user name of a URL without one: both are stored as `***` (`https://***@host`), and the value is masked wherever it appears, like a password. `{{variable}}` and `env:NAME` references are kept, also when joined by separators (`{{user}}:{{password}}`, `session={{sid}}`). Opening such an entry says so, and sending it or adding it to a collection asks first (*Cancel* is the default): type them again. Auth the request inherited from its folder or collection is stored masked too, but while the request is still in its collection, an entry sent again runs as that request does: with its folders' scripts and the auth it inherits from them. That request is the one at the entry's exact path, never another with the same name (or the same path through slashes in names), in the collection the entry was sent from: the history keeps that collection's file, so another collection of the same name is never taken for it, by *Copy as cURL* and *Go to request in collection* either. Where that file is gone, or for an entry an earlier version recorded, the collection with its name is used while only one has it; while several have that name, the entry is sent on its own, and the status bar says so. Once the request is gone (deleted, or renamed or moved and the collection reloaded), the entry is sent on its own: auth it inherited is put back as it was sent, the status bar says so, and masked credentials ask first; + - the password of a URL in an error message: the proxy's (from the proxy setting or `HTTPS_PROXY`, spaces and letters that aren't ASCII included) when it refuses a connection, `http://user:***@proxy:3128/`, or that of a URL that isn't valid (`'http://user:***@host:{{port}}/x' is not a valid http(s) URL.`), or there the user name of one without a password, the credential (`'https://***@{{host}}/v1' is not a valid http(s) URL.`). Errors show it masked everywhere, in the UI and on stderr too, and so does the warning about a redirect TermRest doesn't follow (`ftp://user:***@host/`). - **In the UI:** press **F9** (or click *History* in the status bar) to switch the sidebar to the history list, and type in *Filter* to narrow it. - - Click an entry to open the request exactly as it was sent, together with its recorded response. - - Right-click an entry for *Send again*, *Save to collection…*, *Copy as cURL*, *Go to request in collection*, *Delete entry* and *Clear history…*. + - Click an entry to open the request exactly as it was sent, together with its recorded response. The status line gives the size of the body as received, also where the history keeps only its start, or none of it (the Body tab says so). TLS details and script results are not kept, and the TLS and Scripts tabs say so; the Timeline shows the auth, SSL verification and redirects as *(not recorded)*, and the client certificate chosen for the request. + - Right-click an entry for *Send again*, *Save to collection…*, *Copy as cURL*, *Go to request in collection*, *Delete entry* and *Clear history…*. On the entry that is open, they use your edits. - **Ctrl+N** adds the opened entry to a collection. -- **Settings:** *Tools › Settings › History* turns recording off and sets how many entries (500) and how many KB of each response body (256) are kept. In `.termrest/settings.json` these are `historyEnabled`, `historyLimit` and `historyResponseKb`. +- **Settings:** *Tools › Settings › History* turns recording off and sets how many entries (500) and how many KB of each response body (256) are kept. In `.termrest/settings.json` these are `historyEnabled`, `historyLimit` and `historyResponseKb`. The History list shows at most that many entries. +- **Clearing:** *Clear history…* and `termrest history … --clear` delete the entries, then their bodies. When another program has the history file open, nothing is deleted; when it has a body open (an antivirus scan), the entries are gone and that body is left for the next clear. Both say so (the command with exit code 1). ```sh termrest history samples # newest first: id, time, status, duration, method, URL, request @@ -413,11 +438,11 @@ termrest send … --no-history # send without recording Click **● Record** at the right end of the menu bar (or press **F12**, or choose *Tools › Start recording*). Every request you send after that is recorded with its response: - **The request:** method, URL, headers, cookies, query parameters, and the body: text and form fields as sent; files by reference only (see below). -- **The response:** status, headers, cookies and the full body. +- **The response:** status, headers, cookies and the full body. A text body that isn't valid UTF-8 is recorded as text, with U+FFFD for the bytes that can't be decoded. A body is text when its Content-Type says so: `text/*`, form data, or a subtype with a text format as one of its words (JSON, XML, YAML, CSV, GraphQL, JavaScript …, as in `application/problem+json`); binary JSON such as `application/ubjson` is recorded as base64. A compressed body is recorded decoded: `bodySize` is its size as received, `content.size` once decoded, and `content.compression` the difference. - **Connection details:** timing, the server address, and TLS (protocol, cipher, server certificate chain, the client certificate sent). - **Failures:** the error of requests that failed. -While recording, the button turns into a red badge with a blinking dot, the time since recording started and the number of requests recorded: **● REC 01:23 · 3 requests · Stop F12**. The Response pane's title shows which request a response was recorded as (**Response · ● recorded #3**). +While recording, the button turns into a red badge with a blinking dot, the time since recording started and the number of requests recorded: **● REC 01:23 · 3 requests · Stop F12**. The Response pane's title shows which request a response was recorded as (**Response · ● recorded #3**). A request that can't be written to the recording (a full disk, say) is reported once in the status bar; the recording goes on. **Files are recorded by reference, never their content.** For a [body sent from a file](#sending-a-file-as-the-body) or a form-data file field, the recording keeps the file's path, size and modification time. The file stays where it is, and the recording stays small. You see this in three places: the Body tab says so while recording, the status line after sending says *● recorded with the file's path, not its content*, and the stop dialog counts the requests that sent files. In the HAR file, such a body has no `text`; it has a `_file` entry that says `"contentRecorded": false`, plus a comment that HAR viewers show: @@ -463,25 +488,26 @@ Click the badge (or press F12) to stop. TermRest asks where to save the recordin ``` - **Secrets are redacted** before anything is written, even to the temporary file. The placeholder `[REDACTED]` keeps the shape of the data, and each entry lists what was redacted, where and why (`_termrest.redacted`). Redacted are: - - `Authorization` and `Proxy-Authorization` credentials. The scheme stays: `Bearer [REDACTED]`. + - `Authorization` and `Proxy-Authorization` credentials. The scheme stays: `Bearer [REDACTED]`. A Basic credential's user name and password are also redacted wherever they appear later (8 characters or more), as the user name can be the key itself (Stripe and Freshdesk take theirs so); `_termrest.auth` gives only `Basic`, never the user name. - Cookie values in `Cookie` and `Set-Cookie`. Names and attributes stay. - - Headers, URL parameters (query and fragment), and JSON and form fields named like credentials: password, secret, token, API key, signature, session id, private key, connection string, client assertion … - - Passwords in URLs (`https://user:[REDACTED]@host`). - - The values of auth credentials, secret variables and variables named like credentials, wherever they appear: URLs, headers, bodies (also URL-encoded or JSON-escaped) and error messages. - - Every value redacted by name, wherever it appears later in the recording. For example, a token from a login response is redacted when a later request sends it. + - Headers, URL parameters (query and fragment), and JSON, form and form-data fields named like credentials: password, secret, token, API key, auth key (`X-Auth-Key`), signature, session id, private key, connection string, client assertion …; in URLs also `key`, `sig` and `auth` (Google API keys, Azure SAS signatures, Firebase tokens). JSON sent as `text/plain` or `text/html`, bodies that aren't entirely UTF-8, and form-data sent as a raw body (a browser's *Copy as cURL*, imported) are covered too. Such a raw form-data body is recorded as text (as base64 if its files are binary); its file parts are kept as sent. + - Passwords in URLs (`https://user:[REDACTED]@host`), and the user name of a URL without a password (`https://[REDACTED]@host`), which is then the credential. + - The values of auth credentials, secret variables (the value the request used, also from `--var` or a script) and variables named like credentials, wherever they appear: URLs, headers, bodies (also URL-encoded, fully or only where a URL needs it, or JSON-escaped as .NET, JavaScript, Python, PHP or Go write it, and in UTF-16 or UTF-32 text, which is recorded as UTF-8) and error messages. Values that test scripts store in such variables are redacted in the response they came from too (a token from a login response). + - Every value redacted by name, wherever it appears later in the recording. For example, a token from a login response is redacted when a later request sends it. A cookie that is set again (a load balancer's, say) is looked for with its latest value only. - Add your own names in *Tools › Settings › Recordings redact* (`recordingRedact` in `.termrest/settings.json`). Names are compared without case and separators, at the end of a name: `Tenant-Key` covers `X-Tenant-Key` and `tenant_key`. + Add your own names in *Tools › Settings › Recordings redact* (`recordingRedact` in `.termrest/settings.json`). Names are compared without case and separators, at the end of a name: `Tenant-Key` covers `X-Tenant-Key` and `tenant_key`. Names you add while recording are redacted in the requests recorded from then on (requests recorded before stay as they are); names you remove are still redacted until the recording stops. While `.termrest/settings.json` can't be read, recording does not start: fix the file, then open the workspace again. - **Memory:** a recording does not grow in memory. - Each request is written to a temporary file as soon as its response arrives, on a background thread. - Bodies are written in 64 KB pieces, and saving copies the temporary file into the HAR file through a small buffer. - Responses are included up to the workspace's maximum response size (*Tools › Settings*, 50 MB). Files sent with a request are never read for the recording. + - If requests come faster than they can be written, sending waits once 4 are waiting. - **Temporary files** are private to you (on Unix, a folder only you can read) and are deleted after saving or discarding: - Windows: `%TEMP%`. - macOS: `$TMPDIR`, which is per user. - Linux: `$TMPDIR` if it is set, otherwise `/tmp`. When `/tmp` is a RAM file system (tmpfs), `/var/tmp` is used instead, so a large recording doesn't take memory after all. Set `TERMREST_TEMP_DIR` to use another folder. On Unix, the saved HAR file is also readable only by you (mode 600). -- **Recovery:** if TermRest closes while recording (a closed terminal, a crash), nothing is lost. The next start says so, and *Tools › Recover unsaved recordings* saves the recording. +- **Recovery:** if TermRest closes while recording (a closed terminal, a crash), nothing is lost. The next start says so, and *Tools › Recover unsaved recordings* saves the recording. Only folders private to you are offered (on Unix, mode 700, as TermRest creates them). - **Command line:** `--record ` on `send` and `run` records the same way, for example as evidence from a CI run: ```sh @@ -489,17 +515,19 @@ termrest run "samples/TermRest Demo.postman_collection.json" -e "Postman Echo" - termrest send api.postman_collection.json "Users/Get user" --record get-user.har ``` +Ctrl+C (or SIGTERM, as a cancelled CI job sends) cancels `send` and `run`: they still save the recording, and `run` still writes its `--report-json` report, however long that takes. A second Ctrl+C ends TermRest at once; *Tools › Recover unsaved recordings* then saves the recording. + ## Importing cURL commands -- **Paste** a curl command into the URL bar. It replaces the current request (method, URL, headers, body, auth, client certificate), as in Postman; **Ctrl+S** saves it. Typing a curl command and pressing Enter does the same. +- **Paste** a curl command into the URL bar. It replaces the current request (method, URL, headers, body, auth, client certificate), as in Postman; **Ctrl+S** saves it. Pasted into a request from the history, it becomes a request of its own, as one imported from the menu: it takes neither the auth nor the scripts of the entry's request or its folders, which aren't meant for the host it names. Typing a curl command and pressing Enter does the same. A URL is never taken for a command, even one whose path ends in `/curl`. - **File › Import cURL command…** (also in the *Request* menu) opens the command as a new request instead. **Ctrl+N** then adds it to a collection. -- **Syntax:** bash, cmd and PowerShell syntax are all understood, so every flavor of the browsers' *Copy as cURL* works, including line continuations, `$'…'` strings and `^` escapes. +- **Syntax:** bash, cmd and PowerShell syntax are all understood (PowerShell's `&` call operator too), so every flavor of the browsers' *Copy as cURL* works, including line continuations, `$'…'` strings, escaped emoji and `^` escapes. - **Options imported:** - - request: `-X`, `-H`, `-A`, `-e`, `-b name=value`, `-r`, `-I`; - - body: `-d`/`--data-*`, `--json`, `-F` (text and files), `-T`, `-G`/`--url-query`; + - request: `-X`, `-H` (`-H 'Name:'` drops one of curl's own headers: with `-H 'Content-Type:'`, as TermRest's export writes for a POST without a body, no type is added for `-d` data), `-A`, `-e`, `-b name=value`, `-r`, `-I`; + - body: `-d`/`--data-*` (`name=value` pairs become form fields; data with an escape that isn't UTF-8, such as `%F6` from a page in windows-1252, stays text and is sent as typed; empty data, as in `-d ''`, gives a request without a body and without curl's default type), `--json` (also `--json @file`), `-F` (text and files), `-T` (a URL without a query whose path is empty or ends with `/` gets the file's name, as curl sends it), `-G`/`--url-query`; - auth: `-u` (Basic, or with `--digest`/`--ntlm`/`--negotiate`) and `--oauth2-bearer`; - client certificates: `--cert`/`--key`/`--pass`/`--cert-type`; - - TLS and redirects: `-k` and `--max-redirs` (TermRest follows redirects by default, as with `-L`). + - TLS and redirects: `-k` and `--max-redirs` (TermRest follows redirects by default, as with `-L`, keeping credentials for the original origin; `--max-redirs 0` follows none, and `--max-redirs -1` (curl's "no limit") keeps the workspace's limit, with a note). `--proto-redir` is skipped: TermRest never follows a redirect from https to http. - **Notes:** options that are workspace settings in TermRest (proxy, timeouts, CA files, HTTP version) and unsupported options are listed as notes after the import. Options that only affect curl's own output, such as `-s`, `-v`, `-o` or `--compressed`, are skipped without a note. ```sh @@ -508,7 +536,16 @@ pbpaste | termrest import-curl postman/collections/Contoso --folder Imported --n termrest import-curl api.postman_collection.json "curl …" --dry-run # show what would be imported ``` -The other direction: `termrest send … --curl`, *Request › Copy as cURL*, and *Copy as cURL* in the history. +The other direction: `termrest send … --curl`, *Request › Copy as cURL*, and *Copy as cURL* in the history. The commands are for POSIX shells (bash, zsh), not cmd or PowerShell. A command sends what TermRest sends: + +- the URL as it goes out (percent-encoded, the host name in ASCII); +- the method, except for a POST, which curl sends anyway for its data (`-X GET` for a GET with a body; a HEAD request gets `--head`); +- the headers as they go out: no typed `Content-Length`, no `Content-Type` and the like without a body, and an empty value as `-H 'Name;'`; +- a request without a body as TermRest sends it: unless its method is GET, HEAD, DELETE, OPTIONS or CONNECT, it goes with `Content-Length: 0` (without one, IIS and others answer a POST with 411 Length Required), which `--data-raw '' -H 'Content-Type:'` sends (empty data, without curl's default type); +- text form fields with `--form-string`, or `-F 'name="text";type=…'` when they have a content type, and form files as `name=@"path";type=…`, so curl reads only that file and sends the type TermRest sends, as typed or the one of the file's extension (a type without a `/`, such as `jpeg`, needs curl 8.12 or later); +- redirects as TermRest follows them: `--location` with TermRest's limit (`--max-redirs`), `--proto-redir '=https'` for an https URL (TermRest never follows a redirect from https to http), and `--post301 --post302` when a method other than POST has a body (or the empty data above). Where TermRest stops at a redirect and shows it, curl ends with an error, and after a 303 curl keeps a PUT, PATCH or DELETE (without its body) where TermRest sends a GET. A request that follows no redirects (following off, or a limit of 0) gets no `--location`. Neither does one whose auth adds a header such as an API key, or that has a `Proxy-Authorization` header, as curl would send that header to every host it is redirected to, nor one with a client-certificate file, which curl would present to every host it is redirected to (TermRest selects the certificate for each URL); a comment line above the command says so. + +A URL with `[]{}` gets `--globoff`, Digest and NTLM credentials keep their scheme (`--digest`, `--ntlm`), client-certificate files are given with full paths (so the command works from any folder), and a certificate from the OS store, which curl can't use, is named in a comment line above the command. A request curl can't send the same way isn't exported, and the reason is shown: a form field whose name contains `=`, or whose content type curl would cut short (at a space, or at a character such as `=` or `(` before the first `;`) or partly read as its own settings, or a HEAD request with a body. Nor is a request TermRest itself wouldn't send, such as one whose body file doesn't exist (a command for it would send no body): its errors are shown instead. ## Postman v3 (YAML) collections @@ -529,10 +566,15 @@ my-api/ └─ .termrest/ ← TermRest settings and certificate registry, as above ``` -- **Opening:** open the repository folder (`termrest my-api`) or a collection folder directly. A workspace may mix JSON and YAML collections. -- **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. 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. -- **New and imported collections:** in a workspace that already uses the v3 layout, new collections and environments are created as YAML, and *File › Import Postman collection* converts JSON collections. The choice is in *Tools › Settings › New collections* (`collectionFormat`: `v3` or `v2.1`). -- **Wrapping long lines:** some earlier Postman versions wrapped long values at 80 columns; current versions write each value on one line. TermRest writes wrapped values exactly as Postman did: text breaks at spaces, URLs break with an escaped `\` line break, and multi-line text becomes a folded `>` block. Choose in *Tools › Settings › Wrap YAML lines*, or set `yamlLineWidth` in `.termrest/settings.json`: +- **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. +- **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. +- **Files TermRest couldn't read.** A `definition.yaml` or request file that couldn't be read when the collection was loaded is never saved over, as that would lose what it holds: saving writes everything else and names it, and the edits that belong in it wait until it is fixed (or deleted) and the collection is opened again. A request or folder whose file was deleted meanwhile (a `git checkout`, say) is written anew when you rename or move it, a folder with everything it held. A deleted folder (the collection's own folder too) also comes back whole, with its definition, as soon as something is saved into it (a request you edit, add, move or import there) or the folder itself changes; saving other changes leaves it deleted. Before writing a YAML file TermRest reads it back: a file that wouldn't read back unchanged is not written, and saving names it. +- **New and imported collections:** in a workspace that already uses the v3 layout, new collections and environments are created as YAML, and *File › Import Postman collection* converts JSON collections. The choice is in *Tools › Settings › New collections* (`collectionFormat`: `v3` or `v2.1`). *Import Postman environment…* loads a file from `postman/environments` where it is; one from elsewhere is saved as a new environment in the workspace's format, converted when needed (a globals export becomes the workspace's globals, `postman/globals/workspace.globals.yaml`; see [Workspace layout](#workspace-layout)). +- **Wrapping long lines:** some earlier Postman versions wrapped long values at 80 columns; current versions write each value on one line. TermRest writes wrapped values exactly as Postman did (except in two cases where Postman's output reads back changed: a line of a single space in a quoted value, and a line of only white space after an indented one; those are written to read back exactly): text breaks at spaces, URLs break with an escaped `\` line break, and multi-line text becomes a folded `>` block. Choose in *Tools › Settings › Wrap YAML lines*, or set `yamlLineWidth` in `.termrest/settings.json`: - *Like the files* (the default, no setting): files that are wrapped stay wrapped, and new files are not wrapped. - *Never* (`0`) or *At column* (for example `80`; 20 to 1000). @@ -544,6 +586,7 @@ my-api/ termrest convert "Contoso API.postman_collection.json" --line-width 80 # wrapped like older Postman versions termrest convert "postman/collections/Contoso API" --to v2.1 -o contoso.postman_collection.json termrest convert dev.postman_environment.json # → postman/environments/dev.environment.yaml + termrest convert postman/environments/dev.postman_environment.json # → postman/environments/dev.environment.yaml too: copies go into the input's workspace termrest validate "postman/collections/Contoso API" # checks that every file converts losslessly ``` @@ -552,9 +595,14 @@ 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. +- 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. -- If a collection or folder defines several auth methods, only the first one can be edited; the others are kept. +- 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. +- A disabled JavaScript script (`"disabled": true` in v2.1) is left out when converting to v3, which can't mark a script disabled; Postman doesn't run it either way. +- A value whose first line is two or more spaces, as Postman writes it (a `|2-` block whose first line holds only spaces), can't be read: the file is reported. TermRest writes such values double-quoted. A value that starts with an empty line, which Postman writes with the block's indentation on that line, reads fine. +- A key that holds a space followed by `*` (`Accept *: v`) reads as text rather than as a key, so TermRest writes such keys double-quoted (`"Accept *": v`). +- Header names over 1,024 characters can't be saved. ## Client certificates (mutual TLS) @@ -584,14 +632,16 @@ Open **Tools › Client certificates** (F8). From there you can add a PEM pair, ``` - **File format:** the same as Newman's `--ssl-client-cert-list` (`name`, `matches`, `cert`/`key`/`pfx` `src`, `passphrase`). `x-store` is a TermRest extension. Relative paths resolve against the workspace folder. -- **Matching:** patterns follow Postman's rules: `scheme://host[:port]/path`, where `*.domain` matches the domain and its subdomains, and a pattern without a port matches any port. The most specific match wins. A `certificate` set on an individual request in the collection (a Postman v2.1 field) takes precedence over the registry. +- **Matching:** patterns follow Postman's rules: `scheme://host[:port]/path`, where `*.domain` matches the domain and its subdomains, and a pattern without a port matches any port. A host can be written in Unicode or in ASCII (punycode): `https://bücher.example/*` and `https://xn--bcher-kva.example/*` match the same URLs. An IPv6 address goes in brackets, in any of its forms: `https://[::1]:8443/*`. The most specific match wins. A `certificate` set on an individual request in the collection (a Postman v2.1 field) takes precedence over the registry; without URL patterns of its own, it goes to the request's own origin only. A redirect target gets the certificate selected for its own URL. - **Passphrases:** avoid storing them in the file. Use `env:NAME` to read an environment variable, or `{{variable}}` to read a (secret) environment value. +- **A certificate that can't be loaded** (a missing, locked or unreadable file, a wrong passphrase, or on Windows a file on a network share outside the workspace folder, until you allow files from outside it: see [Workspace layout](#workspace-layout)) is not used: the request is sent without it, and a warning says why. Likewise an extra CA bundle that can't be read: only the OS trust store is used then. - **OS stores** - *Windows:* `CurrentUser\My` or `LocalMachine\My`. Keys marked non-exportable, and smart-card or TPM-backed keys, work because the TLS handshake signs inside CNG/SChannel. - *macOS:* `CurrentUser\My` is your login keychain (identities with private keys). - *Linux:* use PEM/PFX files. The .NET user store under `~/.dotnet/corefx/cryptography/x509stores/my` also works. -- **Server trust:** the OS trust store by default. Add private or corporate CAs with **Tools › Settings › Extra CA bundle** (PEM). Turn verification off per request in **Settings**, or globally (`--insecure` on the CLI). -- **Accuracy:** TLS session resumption is disabled and client-certificate selection is always explicit, so every request does a full handshake with exactly the certificate shown. Cached credentials from earlier requests are never reused, which is important when testing certificate changes. +- **Server trust:** the OS trust store by default. Add private or corporate CAs with **Tools › Settings › Extra CA bundle** (PEM); it is read once per session and again when the file changes, and a server certificate it vouches for must be issued for server authentication. Turn verification off per request in **Settings**, or globally (`--insecure` on the CLI). +- **Accuracy:** TLS session resumption is disabled and client-certificate selection is always explicit, so every request does a full handshake with exactly the certificate shown. Each request presents only the certificate selected for its URL, never one an earlier request used, which is important when testing certificate changes. +- **Windows intermediate store:** to send a certificate's chain, .NET adds the chain's CA certificates that Windows can't find to your intermediate certificate store (`CurrentUser\CA`). ```sh termrest certs list samples # load every registry entry and show subject, expiry, key status @@ -603,10 +653,10 @@ termrest certs match https://client.badssl.com/ samples ```text termrest [] [--theme ] open the UI (default: current directory) -termrest send [opts] send one request; body to stdout, status/diagnostics to stderr -termrest run [--folder F] [opts] run all requests in order, with their scripts; exit code 1 if any fail +termrest send [opts] send one request; body to stdout (pipes and files get binary bodies, and any body with --raw, exactly as received), status/diagnostics to stderr +termrest run [--folder F] [opts] run all requests in order, with their scripts; exit code 1 if any fail, files of the collection can't be read, or the report or recording can't be written termrest validate check that files (JSON, YAML, v3 folders) round-trip unchanged through TermRest -termrest convert [--to v3|v2.1] [-o O] convert a collection or environment between v2.1 JSON and v3 YAML +termrest convert [--to v3|v2.1] [-o O] convert a collection or environment between v2.1 JSON and v3 YAML; exit code 1, writing nothing, if files of the collection can't be read or the result can't be written. A folder must be a v3 collection (with `.resources/definition.yaml` or `*.request.yaml` files; in `postman/collections`, in its folders too), for `validate` too termrest history [] [opts] requests sent from a workspace, newest first termrest import-curl [] add a request from a curl command (read from stdin when omitted) termrest certs list|store|match client-certificate helpers @@ -616,11 +666,12 @@ 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 --python --javascript --csharp --powershell - --script-order --no-scripts + --script-order --no-scripts --allow-outside-files send options: -i/--include -v/--verbose -o/--output --raw -f/--fail --curl --no-history run options: --bail --allow-http-errors --report-json history options: -n/--limit --show --json --clear import-curl options: --folder --name --dry-run +certs list options: --allow-outside-files convert options: --line-width (wrap YAML output at column n; 0: never) themes options: -w/--workspace --only-here (use) --in-workspace (copy) snapshot options: --send --request --width --height --theme @@ -629,7 +680,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 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) +termrest send api.postman_collection.json "Users/Get user" --curl # print an equivalent curl command (scripts do not run; none, and exit code 2, if it can't be sent or curl can't send it the same way) termrest run api.postman_collection.json --python .venv/bin/python # run the collection's Python scripts and tests termrest run postman-export.json --javascript node # run a Postman collection's pm.* scripts and tests termrest run api.postman_collection.json --csharp dotnet # build and run the collection's C# scripts and tests @@ -638,13 +689,23 @@ termrest run api.postman_collection.json --powershell pwsh --javascript node --s # PowerShell versions of scripts where they all exist, else Postman's ``` +Paths on the command line are relative to the current folder, those of `--python`, `--javascript`, `--csharp` and `--powershell` included (a name without a folder, such as `node`, is looked up on PATH); runtimes chosen in the UI (*Tools › Scripts…*) are relative to the workspace. + +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. + +`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`, 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, or one `--curl` can't export); 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. + +On Windows, commands write UTF-8 without a byte order mark to files and pipes, and read standard input as UTF-8 (a byte order mark is fine). In a console window every character shows, and every character typed or pasted into standard input is read (`import-curl` without a command: end it with a line of Ctrl+Z, then Enter); the code page isn't changed. PowerShell decodes a program's output with `[Console]::OutputEncoding`: before `$u = termrest send …` or `| ConvertFrom-Json`, run `[Console]::OutputEncoding = [Text.UTF8Encoding]::new()`. `>` keeps the bytes in cmd and in PowerShell 7.4 and later. + ## Postman compatibility | Area | Status | |---|---| -| Collection v2.1.0 JSON | Read/write; untouched content round-trips byte-for-byte (tabs, key order, escaping, BOM/CRLF preserved) | +| Collection v2.1.0 JSON | Read/write; untouched content round-trips byte-for-byte (tabs, key order, escaping, BOM/CRLF preserved; a file that mixes CRLF and LF line breaks is saved with the kind most of its lines have) | | 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. See [Postman v3 (YAML) collections](#postman-v3-yaml-collections) | +| 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 | | Body modes | raw, urlencoded, formdata (text + files), file (binary, or typed and checked: `file.language`), graphql | @@ -653,7 +714,9 @@ termrest run api.postman_collection.json --powershell pwsh --javascript node --s | Client certificates | `request.certificate` honoured; Newman certificate-list format for the registry | | cURL | Import (bash, cmd and PowerShell syntax) and export | -Run `termrest validate ` to check that TermRest would save your files without changing them. Saves are atomic, write through symbolic links, and keep file permissions (Unix mode / Windows ACL), so a `chmod 600` environment holding secrets stays private. Importing a collection that is already open reloads it from disk, and asks first if it has unsaved changes. +Run `termrest validate ` to check that TermRest would save your files without changing them. When a file would change, it shows the first line that differs; where only white space differs, it shows `\t` for each tab, `\r` for a carriage return (a CRLF line break in a file whose other lines end in LF, or the reverse) and `·` for each space (Postman indents JSON with tabs, so a file indented with spaces would be rewritten). Saves are atomic, write through symbolic links, and keep file permissions (Unix mode / Windows ACL), so a `chmod 600` environment holding secrets stays private. Imported and converted copies (*Import Postman collection/environment…*, `termrest convert`) are as private as their source from the moment they are created: on Unix they get its read and write permissions, and the folders of a converted collection can be entered only by whoever can read the source. Files must be UTF-8 (a byte order mark is fine); a file in another encoding is reported, never re-encoded. So are a JSON file that repeats a key within an object or holds half of a surrogate pair (`\ud83d`, an emoji cut in two; the error gives the line and column), a file over 256 MB, and anything that isn't a regular file (such as a device a symbolic link points at). Importing a collection that is already open reloads it from disk, and asks first if it has unsaved changes. A collection where the workspace keeps them (a `*.postman_collection.json` file in the workspace folder or in `postman/collections`, or a v3 collection folder there) is loaded where it is. Any other, including a file in the workspace folder under another name such as `collection.json`, is copied in as `.postman_collection.json`, or converted in the v3 layout. + +Saving never silently undoes what another program changed since TermRest read a file (a `git pull`, Postman, an editor): *Ctrl+S* lists those files and asks before overwriting them, with Cancel as the default, and saves the other files either way. *Tools › Client certificates* saves `.termrest/certificates.json` with each change and asks the same way when the file changed on disk; there, Cancel loads the file as it is instead, without your change. A request you renamed or moved whose file changed on disk keeps its name and place, with its examples, until you overwrite; then it is moved and written at once. To keep the other version, quit without saving and open the workspace again (or pick a JSON collection again with *File › Import Postman collection…*). A file that was only touched, with the same content, doesn't count as changed. ## Building native binaries @@ -679,6 +742,7 @@ src/TermRest.Cli `termrest` executable (System.CommandLine): TUI by default + tests/…Core.Tests xUnit v3: fidelity, mapper, URLs, variables, certificates, YAML, Postman v3, history, cURL, recording and redaction, in-process Kestrel HTTP/TLS/mTLS tests tests/…Tui.Tests headless UI tests: renders the real window, injects mouse/keyboard input, asserts on screen text +tests/…Cli.Tests termrest commands run as a process: exit codes, output, and the files they write ``` ```sh @@ -695,8 +759,9 @@ TERMREST_TEST_POWERSHELL= dotnet test # the PowerShell (7+) for PowerSh Notes: - Terminal.Gui 2.5's `TextView` is marked obsolete in favour of the separate `Terminal.Gui.Editor` package. That package has not shipped a build for 2.5 yet, so TermRest uses `TextView` behind a small `TextArea` wrapper, which makes the later switch (folding, for one) a one-file change. `TextArea` also colors scripts: small hand-written lexers (`src/TermRest.Tui/Syntax`) color one line at a time from what the line above leaves open (a string or a comment), so an edit recolors only the lines down to the last one in view. -- Mouse responsiveness: the UI runs Terminal.Gui's main loop at 60 passes per second (its default is 25) and, on Windows, asks for 1 ms timer resolution while it runs (`TimerResolution`), because Windows rounds the loop's and the input poll's sleeps up to 15.6 ms ticks. The request and response tabs use `TabPanel` instead of Terminal.Gui's `Tabs`, which lays out and draws every page on each redraw; it looks the same and makes clicks, drags and resizes about twice as fast to repaint. -- Each request uses a fresh connection, so timing and TLS details are exact. Cookies persist for the session (**Tools › Clear cookies**). +- Mouse responsiveness: while the UI is in use (2 seconds after the last key or mouse event, and while a request is on its way), it runs Terminal.Gui's main loop at 60 passes per second and, on Windows, asks for 1 ms timer resolution (`UiPace`, `TimerResolution`), because Windows rounds the loop's and the input poll's sleeps up to 15.6 ms ticks. When idle, it goes back to Terminal.Gui's 25 passes and the system timer, so it costs next to nothing. The request and response tabs use `TabPanel` instead of Terminal.Gui's `Tabs`, which lays out and draws every page on each redraw; it looks the same and makes clicks, drags and resizes about twice as fast to repaint. +- Unexpected errors in the UI are shown and logged to `errors.log` in TermRest's state folder (where the [history](#request-history) is kept), which only you can read; so are files that fail to save for a reason other than a disk or permission problem. The other files are saved anyway. +- Each request uses a fresh connection, so timing and TLS details are exact; the TLS details are read as soon as the handshake completes, so they are there also for a server that closes the connection after its response (`Connection: close`, HTTP/1.0), and again once the response is in, for a server that asks for the client certificate only then (a TLS 1.2 renegotiation, as IIS does without *Negotiate Client Certificate*). Cookies persist for the session (**Tools › Clear cookies**). ## Roadmap diff --git a/TermRest.slnx b/TermRest.slnx index b2eb523..ffe0c51 100644 --- a/TermRest.slnx +++ b/TermRest.slnx @@ -5,6 +5,7 @@ + diff --git a/src/TermRest.Cli/CliApp.cs b/src/TermRest.Cli/CliApp.cs index 4808c50..97f951f 100644 --- a/src/TermRest.Cli/CliApp.cs +++ b/src/TermRest.Cli/CliApp.cs @@ -1,4 +1,6 @@ using System.CommandLine; +using System.CommandLine.Invocation; +using System.Runtime.InteropServices; using TermRest.Tui; namespace TermRest.Cli; @@ -6,6 +8,9 @@ namespace TermRest.Cli; /// Command-line surface: the TUI by default, plus headless commands for scripts and CI. internal static class CliApp { + /// Cancelled by the first Ctrl+C or SIGTERM while send or run works (see ). + private static readonly CancellationTokenSource Stopping = new(); + public static async Task RunAsync(string[] args) { var insecure = new Option("--insecure", "-k") { Description = "Do not verify server TLS certificates", Recursive = true }; @@ -47,7 +52,31 @@ public static async Task RunAsync(string[] args) root.Subcommands.Add(ThemesCommand.Create()); root.Subcommands.Add(CreateSnapshotCommand()); - return await root.Parse(args).InvokeAsync(); + var parseResult = root.Parse(args); + if (parseResult.Action != root.Action) + { + ConsoleText.UseUnicode(); // a command (the full-screen UI drives the console itself) + } + + if (parseResult.Action is not AsynchronousCommandLineAction) + { + return await parseResult.InvokeAsync(); + } + + using var interrupt = PosixSignalRegistration.Create(PosixSignal.SIGINT, Stop); + using var terminate = PosixSignalRegistration.Create(PosixSignal.SIGTERM, Stop); + return await parseResult.InvokeAsync(new InvocationConfiguration { ProcessTerminationTimeout = null }, Stopping.Token); + } + + /// + /// 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. + /// + private static void Stop(PosixSignalContext context) + { + context.Cancel = !Stopping.IsCancellationRequested; + Stopping.Cancel(); } private static Command CreateSnapshotCommand() diff --git a/src/TermRest.Cli/ConsoleText.cs b/src/TermRest.Cli/ConsoleText.cs new file mode 100644 index 0000000..879af65 --- /dev/null +++ b/src/TermRest.Cli/ConsoleText.cs @@ -0,0 +1,75 @@ +using System.Text; + +namespace TermRest.Cli; + +/// +/// The text of the standard streams on Windows, where .NET would use the console's code page (437, 850, 936 …) and lose +/// every character it lacks. Files and pipes get UTF-8 without a byte order mark (standard input may start with one); a +/// console window gets UTF-16, which shows and reads every character without changing the console's code page. +/// +internal static class ConsoleText +{ + /// For the commands, not the full-screen UI: Terminal.Gui drives the console itself. + public static void UseUnicode() + { + if (!OperatingSystem.IsWindows()) + { + return; // UTF-8 already + } + + var utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + if (Console.IsInputRedirected) + { + Console.SetIn(new StreamReader(Console.OpenStandardInput(), utf8, detectEncodingFromByteOrderMarks: true)); + } + + // .NET writes to a console window with WriteConsoleW while the encoding is UTF-16, which sets no code page: the + // streams are opened then. The encoding is set back afterwards, so that Console.OpenStandardOutput() still writes + // the bytes of a binary body as they are. + var codePage = Console.IsOutputRedirected && Console.IsErrorRedirected ? null : Console.OutputEncoding; + if (codePage is not null) + { + Console.OutputEncoding = Encoding.Unicode; + } + + var output = Console.OpenStandardOutput(); + var error = Console.OpenStandardError(); + if (codePage is not null) + { + Console.OutputEncoding = codePage; + } + + var utf16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false); + Console.SetOut(new StreamWriter(output, Console.IsOutputRedirected ? utf8 : utf16) { AutoFlush = true }); + Console.SetError(new StreamWriter(error, Console.IsErrorRedirected ? utf8 : utf16) { AutoFlush = true }); + } + + /// + /// All of standard input. From a console window on Windows, what is typed or pasted up to a line that starts with + /// Ctrl+Z, read as UTF-16 (as writes): every character comes through. + /// + public static string ReadInput() + { + if (!OperatingSystem.IsWindows() || Console.IsInputRedirected) + { + return Console.In.ReadToEnd(); + } + + // A stream opened while the encoding is UTF-16 reads with ReadConsoleW, which sets no code page; the encoding is + // set back afterwards (to the console's own code page: no change either). + var codePage = Console.InputEncoding; + Console.InputEncoding = Encoding.Unicode; + var input = Console.OpenStandardInput(); + Console.InputEncoding = codePage; + + // ReadConsoleW returns a line of Ctrl+Z, which ends console input, as text (ReadFile returns nothing for it). + using var reader = new StreamReader(input, new UnicodeEncoding(bigEndian: false, byteOrderMark: false)); + var text = new StringBuilder(); + while (reader.ReadLine() is { } line && !line.StartsWith('\u001a')) + { + text.Append(line).Append('\n'); + } + + return text.ToString(); + } +} diff --git a/src/TermRest.Cli/ConvertCommand.cs b/src/TermRest.Cli/ConvertCommand.cs index 50940ca..bf85c96 100644 --- a/src/TermRest.Cli/ConvertCommand.cs +++ b/src/TermRest.Cli/ConvertCommand.cs @@ -1,4 +1,5 @@ using System.CommandLine; +using TermRest.Core.IO; using TermRest.Core.Postman; using TermRest.Core.Workspace; @@ -15,7 +16,7 @@ public static Command Create() var to = new Option("--to") { Description = "Target format: v3 or v2.1 (default: the other one)" }; var output = new Option("--output", "-o") { - Description = "Target folder (v3) or file (v2.1). Default: postman/collections/ next to a v2.1 file; .postman_collection.json in a v3 collection's workspace", + Description = "Target folder (v3) or file (v2.1). Default: postman/collections/ in a v2.1 file's workspace; .postman_collection.json in a v3 collection's workspace", }; var lineWidth = new Option("--line-width") { @@ -96,29 +97,47 @@ private static int ConvertCollection(string path, string? to, string? output, in return 2; } + // Files that could not be read (a definition with the collection's auth, variables and scripts, say) would be + // missing from the converted collection; the note about hidden non-HTTP requests is no such problem. + if (source.HasUnreadableFiles) + { + Output.Error($"Files of '{source.Name}' could not be read (see the warnings above), so nothing was written: the converted collection would lack what they hold."); + return 1; + } + if (toV3) { - var target = output ?? Path.Combine(Path.GetDirectoryName(path)!, ApiWorkspace.PostmanFolder, "collections", SafeName(source.Name)); + var target = output ?? Path.Combine(ApiWorkspace.RootForFile(path), ApiWorkspace.PostmanFolder, "collections", ApiWorkspace.SafeFileName(source.Name)); var converted = source.ConvertToV3(target, lineWidth); var examples = Directory.EnumerateFiles(target, "*.example.yaml", SearchOption.AllDirectories).Count(); Output.Status($"✓ {converted.AllRequests().Count()} request(s){(examples > 0 ? $" and {examples} example(s)" : "")} written to {target}{Wrapping(lineWidth)}", true); + if (source.SecretValuesLeftOutOfV3() is { Count: > 0 } secrets) + { + Output.Info($" The values of secret variables ({string.Join(", ", secrets)}) are not written: Postman's v3 collections keep them out of their files. Set them in an environment."); + } + return 0; } - var file = output ?? Path.Combine(source.BaseDirectory, SafeName(source.Name) + PostmanCollection.FileSuffix); + var file = output ?? Path.Combine(source.BaseDirectory, ApiWorkspace.SafeFileName(source.Name) + PostmanCollection.FileSuffix); if (File.Exists(file)) { Output.Error($"'{file}' already exists; choose another --output."); return 2; } - File.WriteAllText(file, source.ExportV21Json()); + 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()) { Output.Info(" Saved examples (*.example.yaml) are not included in the v2.1 file."); } + if (source.CredentialSetsLeftOutOfV21() is { Count: > 0 } owners) + { + Output.Warning($"The auth of {string.Join(", ", owners)} has credential sets chosen by URL rules, which v2.1 can't hold: the v2.1 file has the first set only, and Postman sends it to every URL."); + } + return 0; } @@ -134,9 +153,9 @@ private static int ConvertEnvironment(string path, string? to, string? output, i var directory = Path.GetDirectoryName(path)!; var target = output ?? (toV3 - ? Path.Combine(directory, ApiWorkspace.PostmanFolder, environment.IsGlobals ? "globals" : "environments", - environment.IsGlobals ? "workspace.globals.yaml" : SafeName(environment.Name) + ".environment.yaml") - : Path.Combine(directory, SafeName(environment.Name) + (environment.IsGlobals ? PostmanEnvironment.GlobalsSuffix : PostmanEnvironment.EnvironmentSuffix))); + ? Path.Combine(ApiWorkspace.RootForFile(path), ApiWorkspace.PostmanFolder, environment.IsGlobals ? "globals" : "environments", + environment.IsGlobals ? "workspace.globals.yaml" : ApiWorkspace.SafeFileName(environment.Name) + ".environment.yaml") + : Path.Combine(directory, ApiWorkspace.SafeFileName(environment.Name) + (environment.IsGlobals ? PostmanEnvironment.GlobalsSuffix : PostmanEnvironment.EnvironmentSuffix))); if (File.Exists(target)) { Output.Error($"'{target}' already exists; choose another --output."); @@ -145,14 +164,8 @@ private static int ConvertEnvironment(string path, string? to, string? output, i Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(target))!); environment.YamlLineWidth = lineWidth; - environment.Save(target); + environment.Save(target); // as private as its source Output.Status($"✓ {environment.Values.Count} value(s) written to {target}{(toV3 ? Wrapping(lineWidth) : "")}", true); return 0; } - - private static string SafeName(string name) - { - var safe = new string(name.Select(c => c is '/' or '\\' or ':' or '*' or '?' or '"' or '<' or '>' or '|' || char.IsControl(c) ? '-' : c).ToArray()).Trim().TrimEnd('.'); - return safe.Length == 0 ? "collection" : safe; - } } diff --git a/src/TermRest.Cli/HistoryCommand.cs b/src/TermRest.Cli/HistoryCommand.cs index f2c2017..e618904 100644 --- a/src/TermRest.Cli/HistoryCommand.cs +++ b/src/TermRest.Cli/HistoryCommand.cs @@ -30,7 +30,7 @@ public static Command Create() ApiWorkspace opened; try { - opened = ApiWorkspace.Open(path); + opened = ApiWorkspace.Open(path, CollectionLoading.None); } catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException) { @@ -41,12 +41,39 @@ public static Command Create() var store = HistoryStore.ForWorkspace(opened.RootPath, opened.Settings.HistoryLimit); if (parseResult.GetValue(clear)) { - store.Clear(); + Exception? bodiesLeft; + try + { + bodiesLeft = store.Clear(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Another program has the history file open (an antivirus scan, Get-Content -Wait): nothing was deleted. + Output.Error($"The history could not be cleared ({store.Folder}): {ex.Message}"); + return 1; + } + + if (bodiesLeft is not null) + { + Output.Error($"History cleared, but some response bodies could not be deleted ({store.BodiesFolder}): {bodiesLeft.Message}"); + return 1; + } + Output.Info($"History cleared ({store.Folder})."); return 0; } - var entries = store.Load(); + List entries; + try + { + entries = store.Load(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Output.Error($"The history could not be read ({store.Folder}): {ex.Message}"); + return 1; + } + if (parseResult.GetValue(show) is { } id) { var matches = entries.Where(e => e.Id.StartsWith(id, StringComparison.OrdinalIgnoreCase)).ToList(); @@ -56,7 +83,16 @@ public static Command Create() return 2; } - Show(matches[0], store, parseResult.GetValue(json)); + try + { + Show(matches[0], store, parseResult.GetValue(json)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Output.Error($"The response body of {ShortId(matches[0].Id)} could not be read ({store.BodiesFolder}): {ex.Message}"); + return 1; + } + return 0; } @@ -83,7 +119,7 @@ public static Command Create() { var status = entry.Status?.ToString(CultureInfo.InvariantCulture) ?? "ERR"; var where = entry.RequestPath is null ? "" : $" ({entry.Collection} / {entry.RequestPath})"; - Console.Out.WriteLine($"{entry.Id[..8]} {entry.Time.ToLocalTime():yyyy-MM-dd HH:mm:ss} {status,-4} {HttpExchange.Format(entry.Timing.Total),9} {entry.Method,-7} {entry.Url}{where}"); + Console.Out.WriteLine($"{ShortId(entry.Id),-8} {entry.Time.ToLocalTime():yyyy-MM-dd HH:mm:ss} {status,-4} {HttpExchange.Format(entry.Timing.Total),9} {entry.Method,-7} {entry.Url}{where}"); } if (entries.Count > listed.Count) @@ -96,6 +132,9 @@ public static Command Create() return command; } + /// An entry's id as listed: its first 8 characters (an id edited by hand may have fewer). + private static string ShortId(string id) => id.Length > 8 ? id[..8] : id; + private static void Show(HistoryEntry entry, HistoryStore store, bool json) { if (json) @@ -127,8 +166,10 @@ private static void Show(HistoryEntry entry, HistoryStore store, bool json) } Console.Out.WriteLine(); - Console.Out.WriteLine(entry.BodySaved - ? BodyFormatter.Format(response.Body, response.ContentType) + (entry.BodyTruncated ? "\n… (truncated)" : "") - : "(response body not kept)"); + + // As the UI says it: the history has no copy of a body that was not empty (it keeps none, or the copy's file is gone). + Console.Out.WriteLine(response.Body.Length == 0 && entry.Size > 0 + ? "(response body not kept)" + : BodyFormatter.Format(response.Body, response.ContentType) + (entry.BodyTruncated ? "\n… (truncated)" : "")); } } diff --git a/src/TermRest.Cli/ImportCurlCommand.cs b/src/TermRest.Cli/ImportCurlCommand.cs index f9869df..7c0c954 100644 --- a/src/TermRest.Cli/ImportCurlCommand.cs +++ b/src/TermRest.Cli/ImportCurlCommand.cs @@ -24,7 +24,7 @@ public static Command Create() command.Options.Add(dryRun); command.SetAction(parseResult => { - var text = parseResult.GetValue(curl) is { } given && given != "-" ? given : Console.In.ReadToEnd(); + var text = parseResult.GetValue(curl) is { } given && given != "-" ? given : ConsoleText.ReadInput(); CurlImportResult imported; try { @@ -67,7 +67,17 @@ public static Command Create() } var node = target.AddRequest(parent, parseResult.GetValue(name) ?? imported.SuggestedName, spec); - target.Save(); + try + { + target.Save(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Changed on disk since it was read a moment ago, read-only, or (v3) holding files that could not be read. + Output.Error($"Saving {target.Name} failed: {ex.Message}"); + return 1; + } + Output.Status($"✓ Added '{node.PathInCollection}' to {target.Name} ({target.FormatName})", true); return 0; }); @@ -79,7 +89,7 @@ public static Command Create() ApiWorkspace workspace; try { - workspace = ApiWorkspace.Open(path); + workspace = ApiWorkspace.Open(path, CollectionLoading.Requested); } catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException) { @@ -87,18 +97,26 @@ public static Command Create() return null; } + foreach (var error in workspace.LoadErrors) + { + Output.Warning(error); + } + if (workspace.FindCollection(path) is { } exact) { return exact; } - if (workspace.Collections.Count == 1) + // A workspace folder may stand for its only collection; a collection that did not load never stands for another. + var isWorkspace = Directory.Exists(path) + && string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)), workspace.RootPath, StringComparison.OrdinalIgnoreCase); + if (isWorkspace && workspace.Collections.Count == 1) { return workspace.Collections[0]; } - Output.Error(workspace.Collections.Count == 0 - ? $"No collection found in '{path}'." + Output.Error(!isWorkspace ? $"'{path}' is not a Postman collection." + : workspace.Collections.Count == 0 ? $"No collection found in '{path}'." : $"'{path}' has {workspace.Collections.Count} collections; pass one of them: {string.Join(", ", workspace.Collections.Select(c => c.FilePath))}"); return null; } diff --git a/src/TermRest.Cli/RequestOptions.cs b/src/TermRest.Cli/RequestOptions.cs index fcf4141..288c587 100644 --- a/src/TermRest.Cli/RequestOptions.cs +++ b/src/TermRest.Cli/RequestOptions.cs @@ -10,7 +10,7 @@ namespace TermRest.Cli; /// Options shared by send and run. internal sealed class RequestOptions { - public Option Environment { get; } = new("--env", "-e") { Description = "Environment name in the workspace, or a *.postman_environment.json file" }; + public Option Environment { get; } = new("--env", "-e") { Description = "Environment name in the workspace, or an environment file (*.postman_environment.json, or a v3 *.environment.yaml)" }; public Option Variables { get; } = new("--var") { Description = "Set a variable (highest precedence): --var key=value (repeatable)" }; @@ -49,6 +49,11 @@ internal sealed class RequestOptions public Option NoScripts { get; } = new("--no-scripts") { Description = "Do not run pre-request and test scripts" }; + public Option AllowOutsideFiles { get; } = new("--allow-outside-files") + { + 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 void AddTo(Command command) { command.Options.Add(Environment); @@ -61,6 +66,7 @@ public void AddTo(Command command) command.Options.Add(PowerShell); command.Options.Add(ScriptOrder); command.Options.Add(NoScripts); + command.Options.Add(AllowOutsideFiles); } /// @@ -94,7 +100,8 @@ public bool StartRecording(ParseResult parseResult, ApiWorkspace workspace, Requ } /// Writes the --record file. Returns false when it could not be written (reported; the recording can still be recovered). - public bool SaveRecording(ParseResult parseResult, RequestRunner runner, RequestRecorder? recorder) + /// Whether the command was cancelled (Ctrl+C): saving a large recording takes a while, so it says what a second Ctrl+C does. + public bool SaveRecording(ParseResult parseResult, RequestRunner runner, RequestRecorder? recorder, bool stopping) { if (recorder is null) { @@ -103,6 +110,12 @@ public bool SaveRecording(ParseResult parseResult, RequestRunner runner, Request runner.Recorder = null; var path = parseResult.GetValue(Record)!; + if (stopping) + { + Output.Info($"Saving the recording to {path}…"); + Output.Info($" Ctrl+C again ends TermRest at once; open TermRest then and use Tools > Recover unsaved recordings ({recorder.TempDirectory})."); + } + try { var result = recorder.Save(path); @@ -120,12 +133,13 @@ public bool SaveRecording(ParseResult parseResult, RequestRunner runner, Request } /// Opens the workspace for a collection file or folder and configures a runner. Returns null on error (already reported). + /// Of the workspace's collections, only the one given is loaded (all of them for a workspace folder). public (ApiWorkspace Workspace, PostmanCollection? Collection, RequestRunner Runner)? Open(ParseResult parseResult, string path, Option insecure) { ApiWorkspace workspace; try { - workspace = ApiWorkspace.Open(path); + workspace = ApiWorkspace.Open(path, CollectionLoading.Requested); } catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException) { @@ -170,19 +184,51 @@ public bool SaveRecording(ParseResult parseResult, RequestRunner runner, Request if (runner.ScriptsEnabled) { - runner.ConfigureScripts(parseResult.GetValue(Python), parseResult.GetValue(JavaScript), parseResult.GetValue(CSharp), parseResult.GetValue(PowerShell), - scriptOrder: scriptOrder); + runner.ConfigureScripts(Runtime(Python), Runtime(JavaScript), Runtime(CSharp), Runtime(PowerShell), scriptOrder: scriptOrder); + if (runner.UserSettingsError is { } problem) + { + Output.Warning(problem); + Output.Info(" The script runtimes chosen for this workspace and your script language order are not used until the file is fixed."); + } } + runner.ConfigureProxy(); + 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 " + + "your requests through a proxy of its choosing; requests use the system's proxy settings. Allow it in the full-screen UI " + + "(Tools > Settings > Save), or set HTTPS_PROXY."); + } + + runner.ConfigureFiles(); + runner.OutsideFilesAllowed |= parseResult.GetValue(AllowOutsideFiles); + if (parseResult.GetValue(Environment) is { } environment) { if (File.Exists(environment)) { - runner.EnvironmentOverride = PostmanEnvironment.Load(environment); + try + { + runner.EnvironmentOverride = PostmanEnvironment.Load(environment); + } + catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidDataException or IOException or UnauthorizedAccessException) + { + Output.Error($"Environment file '{environment}' could not be read: {ex.Message}"); + runner.Dispose(); + return null; + } } - else if (workspace.Environments.FirstOrDefault(e => string.Equals(e.Name, environment, StringComparison.OrdinalIgnoreCase)) is { } named) + else if (workspace.Environments.FindAll(e => string.Equals(e.Name, environment, StringComparison.OrdinalIgnoreCase)) is { Count: > 0 } named) { - runner.EnvironmentOverride = named; + if (named.Count > 1) + { + Output.Error($"Environment '{environment}' is ambiguous: environments in these files have that name\n " + + string.Join("\n ", named.Select(e => e.FilePath)) + "\nPass the file of the one to use with -e instead."); + runner.Dispose(); + return null; + } + + runner.EnvironmentOverride = named[0]; } else { @@ -206,5 +252,47 @@ public bool SaveRecording(ParseResult parseResult, RequestRunner runner, Request } return (workspace, collection, runner); + + // A runtime's path is relative to the current folder, as the other paths of the command line are (the runner takes it + // as relative to the workspace, as it does the UI's choices); a command (node) stays a name, looked up on PATH. + string? Runtime(Option option) + { + var runtime = parseResult.GetValue(option); + var path = runtime?.Trim().Trim('"'); + return path is not null && path.IndexOfAny(['/', '\\']) >= 0 && !Path.IsPathRooted(path) ? Path.GetFullPath(path) : runtime; + } + } + + /// + /// Reports workspace settings that could not be read (their warning is printed when the workspace is opened): no + /// request is sent then, as they may set the proxy and TLS verification, turn the history off and name what + /// recordings and reports redact. + /// + public static bool ReportUnreadableSettings(ApiWorkspace workspace) + { + if (workspace.SettingsError is null) + { + return false; + } + + Output.Error($"The workspace settings could not be read (see the warning above), so no request is sent: they may set the proxy, " + + $"TLS verification, the history and what recordings redact. Fix or delete {workspace.SettingsPath}."); + return true; + } + + /// + /// Reports when files of could not be read (their warnings are printed when the + /// workspace is opened): a v3 request file that was left out, or a definition whose auth and scripts are missing. + /// The send or run fails then; the note about hidden non-HTTP requests is not such a problem. + /// + public static bool ReportUnreadableFiles(PostmanCollection collection) + { + if (!collection.HasUnreadableFiles) + { + return false; + } + + Output.Error($"Files of '{collection.Name}' could not be read (see the warnings above): its requests may lack their auth, scripts and tests."); + return true; } } diff --git a/src/TermRest.Cli/RunCommand.cs b/src/TermRest.Cli/RunCommand.cs index 04ab467..89e5e1e 100644 --- a/src/TermRest.Cli/RunCommand.cs +++ b/src/TermRest.Cli/RunCommand.cs @@ -1,8 +1,8 @@ using System.CommandLine; -using System.Text; using System.Text.Json; using TermRest.Core.Http; using TermRest.Core.Postman; +using TermRest.Core.Recording; using TermRest.Core.Workspace; namespace TermRest.Cli; @@ -35,17 +35,24 @@ public static Command Create(Option insecure) return 2; } - if (options.Open(parseResult, path, insecure) is not { Collection: { } target } opened) + if (options.Open(parseResult, path, insecure) is not { } opened) { - if (Directory.Exists(path)) - { - Output.Error($"'{path}' is not a Postman v3 collection folder; pass the collection itself."); - } - return 2; } using var runner = opened.Runner; + if (opened.Collection is not { } target) + { + // A workspace folder: send finds a request in any of its collections, but run needs one. + Output.Error($"'{path}' is not a Postman v3 collection folder; pass the collection itself."); + return 2; + } + + if (RequestOptions.ReportUnreadableSettings(opened.Workspace)) + { + return 1; + } + FolderNode root = target.RootNode; if (parseResult.GetValue(folder) is { } folderPath) { @@ -69,7 +76,8 @@ public static Command Create(Option insecure) Output.Info($"Running {requests.Count} request(s) from '{target.Name}'{(root is CollectionRootNode ? "" : " / " + root.PathInCollection)}" + $"{(runner.Environment is { } env ? $" with environment '{env.Name}'" : "")}\n"); - var results = new List<(RequestNode Node, HttpExchange Exchange, bool Passed)>(); + 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) @@ -83,7 +91,6 @@ public static Command Create(Option insecure) // 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; - results.Add((node, exchange, passed)); 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) @@ -97,27 +104,21 @@ public static Command Create(Option insecure) } ScriptOutput.Print(exchange, " ", notesShown); + results.Add(node, exchange, passed); if (!passed && parseResult.GetValue(bail)) { break; } } - var failed = results.Count(r => !r.Passed); - var tests = results.SelectMany(r => r.Exchange.Scripts?.Tests ?? []).ToList(); - var testSummary = tests.Count == 0 ? "" : $" (tests: {tests.Count(t => t.Passed)} passed, {tests.Count(t => !t.Passed)} failed)"; - Output.Info($"\n{(cancelled ? "Run cancelled. " : "")}{results.Count - failed} passed, {failed} failed, {requests.Count - results.Count} skipped{testSummary}"); + 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}"); + var unreadable = RequestOptions.ReportUnreadableFiles(target); - // A cancelled run still saves what it recorded. - var recorded = options.SaveRecording(parseResult, runner, recorder); - if (parseResult.GetValue(json) is { } reportPath) - { - // Not tied to the cancellation token: a cancelled run still reports what it did. - await File.WriteAllTextAsync(reportPath, BuildReport(target, results), CancellationToken.None); - Output.Info($"Report written to {reportPath}"); - } - - return cancelled ? 130 : failed == 0 && recorded ? 0 : 1; + // 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; }); return command; @@ -142,65 +143,160 @@ private static async Task SendSafelyAsync(RequestRunner runner, Po } } - private static string BuildReport(PostmanCollection collection, List<(RequestNode Node, HttpExchange Exchange, bool Passed)> results) + /// + /// What a run did: counts and, for --report-json, what the report says of each request. Exchanges are not kept: + /// each holds its response body (up to the maximum response size), and a run's memory must not grow with every + /// response it receives. + /// + /// What the report redacts; null when there is no report. + private sealed class RunResults(Redactor? secrets) { - using var stream = new MemoryStream(); - using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true })) + private readonly List _entries = []; + + public int Count { get; private set; } + + public int Failed { get; private set; } + + public int TestsPassed { get; private set; } + + public int TestsFailed { get; private set; } + + public void Add(RequestNode node, HttpExchange exchange, bool passed) + { + Count++; + Failed += passed ? 0 : 1; + TestsPassed += exchange.Scripts?.Passed ?? 0; + TestsFailed += exchange.Scripts?.Failed ?? 0; + if (secrets is null) + { + return; + } + + // Secrets are redacted as in recordings, since reports are kept as CI artifacts: auth credentials, secret + // variables and variables named like credentials, URL passwords, and the values a recording redacts by name + // (a token in a response, a cookie), wherever they appear, also in the requests that follow. + var redact = secrets.ForReport(exchange); + var response = exchange.Response; + var scripts = exchange.Scripts; + _entries.Add(new ReportEntry( + node.PathInCollection, + exchange.Request.Method, + redact.Url(exchange.Request.Url, "url"), + passed, + response?.StatusCode, + response?.Body.LongLength ?? 0, + response is null && exchange.ErrorMessage is { } message ? redact.Text(message, "error") : null, + scripts?.Tests.Select(t => new ReportTest(redact.Text(t.Name, "tests"), t.Passed, t.Error is null ? null : redact.Text(t.Error, "tests"))).ToList(), + scripts?.Error is { } error ? redact.Text(error.ToString(), "scripts") : null, + exchange.Timing.Total?.TotalMilliseconds ?? 0)); + } + + /// The JSON report (UTF-8). + public byte[] ToJson(PostmanCollection collection) { - writer.WriteStartObject(); - writer.WriteString("collection", collection.Name); - writer.WriteString("finishedAt", DateTimeOffset.Now); - writer.WriteNumber("passed", results.Count(r => r.Passed)); - writer.WriteNumber("failed", results.Count(r => !r.Passed)); - writer.WriteStartArray("results"); - foreach (var (node, exchange, passed) in results) + using var stream = new MemoryStream(); + using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true })) { writer.WriteStartObject(); - writer.WriteString("request", node.PathInCollection); - writer.WriteString("method", exchange.Request.Method); - writer.WriteString("url", exchange.Request.Url); - writer.WriteBoolean("passed", passed); - if (exchange.Response is { } response) - { - writer.WriteNumber("status", response.StatusCode); - writer.WriteNumber("bytes", response.Body.LongLength); - } - else + writer.WriteString("collection", collection.Name); + writer.WriteString("finishedAt", DateTimeOffset.Now); + writer.WriteNumber("passed", Count - Failed); + writer.WriteNumber("failed", Failed); + writer.WriteStartArray("results"); + foreach (var entry in _entries) { - writer.WriteString("error", exchange.ErrorMessage); - } + writer.WriteStartObject(); + writer.WriteString("request", entry.Request); + writer.WriteString("method", entry.Method); + writer.WriteString("url", entry.Url); + writer.WriteBoolean("passed", entry.Passed); + if (entry.Status is { } status) + { + writer.WriteNumber("status", status); + writer.WriteNumber("bytes", entry.Bytes); + } + else + { + writer.WriteString("error", entry.Error); + } - if (exchange.Scripts is { } scripts) - { - writer.WriteStartArray("tests"); - foreach (var test in scripts.Tests) + if (entry.Tests is { } tests) { - writer.WriteStartObject(); - writer.WriteString("name", test.Name); - writer.WriteBoolean("passed", test.Passed); - if (test.Error is not null) + writer.WriteStartArray("tests"); + foreach (var test in tests) { - writer.WriteString("error", test.Error); + writer.WriteStartObject(); + writer.WriteString("name", test.Name); + writer.WriteBoolean("passed", test.Passed); + if (test.Error is not null) + { + writer.WriteString("error", test.Error); + } + + writer.WriteEndObject(); } - writer.WriteEndObject(); + writer.WriteEndArray(); + if (entry.ScriptError is { } scriptError) + { + writer.WriteString("scriptError", scriptError); + } } - writer.WriteEndArray(); - if (scripts.Error is { } error) - { - writer.WriteString("scriptError", error.ToString()); - } + writer.WriteNumber("totalMs", entry.TotalMs); + writer.WriteEndObject(); } - writer.WriteNumber("totalMs", exchange.Timing.Total?.TotalMilliseconds ?? 0); + writer.WriteEndArray(); writer.WriteEndObject(); } - writer.WriteEndArray(); - writer.WriteEndObject(); + return stream.ToArray(); + } + } + + /// What the report says of one request, 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); + + private sealed record ReportTest(string Name, bool Passed, string? Error); + + /// + /// Writes the report, readable only by the user on Unix as recordings are; missing folders are created. Returns false + /// when it could not be written (reported). + /// + private static async Task WriteReportAsync(string path, byte[] report) + { + try + { + if (Path.GetDirectoryName(Path.GetFullPath(path)) is { Length: > 0 } directory) + { + Directory.CreateDirectory(directory); + } + + var options = new FileStreamOptions { Mode = FileMode.Create, Access = FileAccess.Write }; + if (!OperatingSystem.IsWindows()) + { + options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + } + + await using (var file = new FileStream(path, options)) + { + await file.WriteAsync(report); + } + + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); // a file that existed keeps its mode otherwise + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + Output.Error($"The report could not be written to {path}: {ex.Message}"); + return false; } - return Encoding.UTF8.GetString(stream.ToArray()); + Output.Info($"Report written to {path}"); + return true; } } diff --git a/src/TermRest.Cli/ScriptOutput.cs b/src/TermRest.Cli/ScriptOutput.cs index e2a160c..71025d2 100644 --- a/src/TermRest.Cli/ScriptOutput.cs +++ b/src/TermRest.Cli/ScriptOutput.cs @@ -36,7 +36,7 @@ public static void Print(HttpExchange exchange, string indent = "", ISet } else { - Output.Status($"{indent}{(failure.Script.Length == 0 ? "Scripts did not run" : $"Script error in {failure.Script}")}:", false); + Output.Status($"{indent}{failure.Heading}:", false); foreach (var line in failure.Details.Split('\n')) { Output.Info($"{indent} {line.TrimEnd()}"); diff --git a/src/TermRest.Cli/SendCommand.cs b/src/TermRest.Cli/SendCommand.cs index 39f38e3..2e3e7da 100644 --- a/src/TermRest.Cli/SendCommand.cs +++ b/src/TermRest.Cli/SendCommand.cs @@ -1,5 +1,6 @@ using System.CommandLine; using TermRest.Core.Http; +using TermRest.Core.Postman; namespace TermRest.Cli; @@ -38,27 +39,63 @@ public static Command Create(Option insecure) } using var runner = opened.Runner; + if (RequestOptions.ReportUnreadableSettings(opened.Workspace)) + { + return 1; + } + if (!parseResult.GetValue(noHistory)) { runner.ConfigureHistory(); } var requestPath = parseResult.GetValue(request)!; var candidates = opened.Collection is { } single ? [single] : opened.Workspace.Collections; - var match = candidates.Select(c => (Collection: c, Node: c.FindRequest(requestPath))).FirstOrDefault(m => m.Node is not null); - if (match.Node is null) + var matches = FindRequests(candidates, requestPath); + if (matches.Count == 0) { Output.Error($"Request '{requestPath}' was not found. Available:\n " + string.Join("\n ", candidates.SelectMany(c => c.AllRequests().Select(r => r.PathInCollection)))); return 2; } - var spec = match.Node!.ReadSpec(); + if (matches.Count > 1) + { + Output.Error($"Request '{requestPath}' is ambiguous: it matches\n " + + string.Join("\n ", matches.Select(m => $"{m.Node.PathInCollection} ({Path.GetFileName(m.Collection.FilePath) ?? m.Collection.Name})")) + + (matches.DistinctBy(m => m.Collection).Count() > 1 ? "\nGive its path (Folder/Name), or its collection rather than the workspace." : "\nGive its path (Folder/Name).")); + return 2; + } + + var match = matches[0]; + var spec = match.Node.ReadSpec(); if (parseResult.GetValue(curl)) { var prepared = runner.Prepare(match.Collection, match.Node, spec); PrintWarnings(prepared); - Console.Out.WriteLine(CurlExporter.Export(prepared)); - return 0; + if (prepared.Errors.Count > 0) + { + // Not a request TermRest would send (an invalid method or URL, a missing file): no command for it. + foreach (var error in prepared.Errors) + { + Output.Error(error); + } + + return 2; + } + + string command; + try + { + command = CurlExporter.Export(prepared); + } + catch (NotSupportedException ex) + { + Output.Error(ex.Message); + return 2; + } + + Console.Out.WriteLine(command); + return RequestOptions.ReportUnreadableFiles(match.Collection) ? 1 : 0; } if (!options.StartRecording(parseResult, opened.Workspace, runner, out var recorder)) @@ -66,29 +103,67 @@ public static Command Create(Option insecure) return 2; } - var exchange = await runner.SendAsync(match.Collection, match.Node, spec, PrintWarnings, cancellationToken); - var recorded = options.SaveRecording(parseResult, runner, recorder); + var printed = 0; + var exchange = await runner.SendAsync(match.Collection, match.Node, spec, prepared => + { + PrintWarnings(prepared); + printed = prepared.Warnings.Count; + }, cancellationToken); + var recorded = options.SaveRecording(parseResult, runner, recorder, cancellationToken.IsCancellationRequested); var code = await ReportAsync(parseResult, exchange, verbose, include, output, raw, fail, cancellationToken); + + // Those raised while it was sent: a redirect not followed, a header left out, a body cut short … + PrintWarnings(exchange.Request, printed); ScriptOutput.Print(exchange); if (code == 0 && exchange.Scripts is { Succeeded: false }) { code = 1; // a test failed or a script did not run } + if (RequestOptions.ReportUnreadableFiles(match.Collection) && code == 0) + { + code = 1; + } + return recorded || code != 0 ? code : 1; }); return command; } - private static void PrintWarnings(PreparedRequest prepared) + private static void PrintWarnings(PreparedRequest prepared, int from = 0) { - foreach (var warning in prepared.Warnings) + foreach (var warning in prepared.Warnings.Skip(from)) { Output.Warning(warning); } } + /// + /// The requests stands for, found as finds + /// one (by path, else by name), but in all : a request that is not unique is reported + /// rather than taken for another. + /// + private static List<(PostmanCollection Collection, RequestNode Node)> FindRequests(IEnumerable collections, string pathOrName) + { + var requests = collections.SelectMany(c => c.AllRequests().Select(r => (Collection: c, Node: r))).ToList(); + string[] forms = [pathOrName, pathOrName.Trim('/')]; + Func[] keys = [r => r.PathInCollection, r => r.Name]; + foreach (var key in keys) + { + foreach (var form in forms) + { + var found = requests.Where(r => string.Equals(key(r.Node), form, StringComparison.OrdinalIgnoreCase)).ToList(); + if (found.Count > 0) + { + return found; + } + } + } + + return []; + } + private static async Task ReportAsync( ParseResult parseResult, HttpExchange exchange, Option verbose, Option include, Option output, Option raw, Option fail, CancellationToken cancellationToken) @@ -118,15 +193,41 @@ private static async Task ReportAsync( if (parseResult.GetValue(output) is { } file) { - await File.WriteAllBytesAsync(file, response.Body, cancellationToken); + try + { + await File.WriteAllBytesAsync(file, response.Body, cancellationToken); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + Output.Error($"The body could not be saved to {file}: {ex.Message}"); + return 1; + } + Output.Info($"Saved {HttpExchange.FormatSize(response.Body.LongLength)} to {file}"); } + else if (Console.IsOutputRedirected + ? parseResult.GetValue(raw) || BodyFormatter.IsBinary(response.Body, response.ContentType) + : parseResult.GetValue(raw) && !BodyFormatter.LooksLikeText(response.Body, response.ContentType)) + { + // The bytes as received. A pipe or file gets them for binary content (an image, a protobuf message: its declared + // type says so, it need not have a NUL byte) and for any body with --raw; a terminal shows binary content as a + // hex dump unless --raw asks for the bytes. + await using var stdout = Console.OpenStandardOutput(); + await stdout.WriteAsync(response.Body, cancellationToken); + } else { Console.Out.WriteLine(BodyFormatter.Format(response.Body, response.ContentType, pretty: !parseResult.GetValue(raw))); } - return parseResult.GetValue(fail) && response.StatusCode >= 400 ? 22 : 0; + if (parseResult.GetValue(fail) && response.StatusCode >= 400) + { + return 22; + } + + // Only the start of the body was received (a warning says where it was cut): exit as curl does when --max-filesize + // stops a transfer, so that a script does not take what was written for the whole body. + return response.BodyTruncated ? 63 : 0; } private static void PrintVerbose(HttpExchange exchange) diff --git a/src/TermRest.Cli/ThemesCommand.cs b/src/TermRest.Cli/ThemesCommand.cs index 687ac34..cd2eb24 100644 --- a/src/TermRest.Cli/ThemesCommand.cs +++ b/src/TermRest.Cli/ThemesCommand.cs @@ -43,11 +43,7 @@ public static Command Create() private static Option WorkspaceOption() => new("--workspace", "-w") { Description = "Workspace folder (default: current directory): its own themes and theme choice count too" }; - private static string Root(string? workspace) - { - var path = Path.GetFullPath(workspace ?? Environment.CurrentDirectory); - return File.Exists(path) ? Path.GetDirectoryName(path)! : path; - } + private static string Root(string? workspace) => ApiWorkspace.RootFor(workspace ?? Environment.CurrentDirectory); private static IReadOnlyList Load(string root) { @@ -65,7 +61,13 @@ private static int List(string root) { var themes = Load(root); var settings = Directory.Exists(root) ? ApiWorkspace.ReadSettings(root) : new WorkspaceSettings(); - var selected = ThemeCatalog.SelectedName(null, settings, UserSettings.Load()) ?? ThemeCatalog.DefaultName; + var user = UserSettings.Load(); + if (user.LoadError is { } problem) + { + Output.Warning(problem); + } + + var selected = ThemeCatalog.SelectedName(null, settings, user) ?? ThemeCatalog.DefaultName; var nameWidth = themes.Max(t => t.Name.Length) + 2; var sourceWidth = themes.Max(t => t.SourceDescription.Length) + 2; foreach (var theme in themes) @@ -75,17 +77,17 @@ private static int List(string root) } Output.Info(""); - Output.Info($"In use: {selected}{Origin(settings)}"); + Output.Info($"In use: {selected}{Origin(settings, user)}"); Output.Info($"Custom themes: {UserSettings.ThemesDirectory()}"); Output.Info($" and for this workspace: {ThemeCatalog.WorkspaceThemesDirectory(root)}"); Output.Info("Choose with 'termrest themes use ', in the UI (Tools > Color theme), or for one session with --theme ."); return 0; } - private static string Origin(WorkspaceSettings settings) => + private static string Origin(WorkspaceSettings settings, UserSettings user) => Environment.GetEnvironmentVariable(ThemeCatalog.EnvironmentVariable) is { Length: > 0 } ? $" (from ${ThemeCatalog.EnvironmentVariable})" : settings.Theme is not null ? " (chosen for this workspace)" - : UserSettings.Load().Theme is not null ? " (your choice for all workspaces)" + : user.Theme is not null ? " (your choice for all workspaces)" : ""; private static int Use(string root, string name, bool onlyHere) @@ -98,16 +100,34 @@ private static int Use(string root, string name, bool onlyHere) if (onlyHere) { - var workspace = ApiWorkspace.Open(root); - workspace.Settings.Theme = theme.Name; - workspace.SaveSettings(); + try + { + var workspace = ApiWorkspace.Open(root, CollectionLoading.None); + workspace.Settings.Theme = theme.Name; + workspace.SaveSettings(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Output.Error(ex.Message); // also when the settings file could not be read: it is not saved over + return 1; + } + Output.Status($"✓ {theme.Name} is used in {root}", true); return 0; } var user = UserSettings.Load(); user.Theme = string.Equals(theme.Name, ThemeCatalog.DefaultName, StringComparison.OrdinalIgnoreCase) ? null : theme.Name; - user.Save(); + try + { + user.Save(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Output.Error(ex.Message); + return 1; + } + Output.Status($"✓ {theme.Name} is used in all workspaces", true); if (Directory.Exists(root) && ApiWorkspace.ReadSettings(root).Theme is { } own) { @@ -119,12 +139,19 @@ private static int Use(string root, string name, bool onlyHere) private static int Copy(string root, string from, string name, bool inWorkspace) { - if (ThemeCatalog.Find(Load(root), from) is not { } theme) + var themes = Load(root); + if (ThemeCatalog.Find(themes, from) is not { } theme) { Output.Error($"Color theme '{from}' was not found; see 'termrest themes'."); return 2; } + if (ThemeCatalog.FindCustom(themes, name) is { } taken) + { + Output.Error($"A custom theme called '{taken.Name}' exists already ({taken.FilePath}): choose another name."); + return 2; + } + var directory = inWorkspace ? ThemeCatalog.WorkspaceThemesDirectory(root) : UserSettings.ThemesDirectory(); try { diff --git a/src/TermRest.Cli/ValidateAndCertsCommands.cs b/src/TermRest.Cli/ValidateAndCertsCommands.cs index 4e73b98..6dd283f 100644 --- a/src/TermRest.Cli/ValidateAndCertsCommands.cs +++ b/src/TermRest.Cli/ValidateAndCertsCommands.cs @@ -48,21 +48,21 @@ public static Command Create() summary = $"collection '{collection.Name}' (schema {collection.SchemaVersion}), {collection.AllRequests().Count()} request(s)"; } - var expected = Normalize(original, info); - if (serialized == expected) + var written = TextFile.AsWritten(serialized, info); + if (written == original) { Output.Status($"✓ {file}: {summary}; round-trip identical", true); } else { failures++; - var (line, before, after) = FirstDifference(expected, serialized); + var (line, before, after) = FirstDifference(original, written); Output.Status($"✗ {file}: {summary}; differs at line {line}", false); Output.Info($" original: {before}"); Output.Info($" termrest: {after}"); } } - catch (Exception ex) when (ex is IOException or InvalidDataException or System.Text.Json.JsonException) + catch (Exception ex) when (ex is IOException or InvalidDataException or System.Text.Json.JsonException or UnauthorizedAccessException) { failures++; Output.Status($"✗ {file}: {ex.Message}", false); @@ -74,12 +74,6 @@ public static Command Create() return command; } - private static string Normalize(string text, TextFileInfo info) - { - var normalized = info.UsesCrLf ? text.Replace("\r\n", "\n", StringComparison.Ordinal) : text; - return info.HasTrailingNewline ? normalized[..^1] : normalized; - } - /// v3 collection folder or YAML environment: loads, and checks that editing would not change other details. private static bool ValidateV3(string path) { @@ -101,7 +95,7 @@ private static bool ValidateV3(string path) Output.Status($"✓ {path}: {summary}; every file converts losslessly", true); // Unreadable files are reported as load warnings; hidden non-HTTP requests are fine. - return collection.LoadWarnings.All(w => w.Contains("non-HTTP", StringComparison.Ordinal)); + return !collection.HasUnreadableFiles; } Output.Status($"✗ {path}: {summary}; {problems.Count} file(s) would change when edited", false); @@ -135,12 +129,21 @@ private static (int Line, string Before, string After) FirstDifference(string a, var r = i < right.Length ? right[i] : ""; if (l != r) { - return (i + 1, l.Trim(), r.Trim()); + if (l.EndsWith('\r') && r.EndsWith('\r')) + { + (l, r) = (l[..^1], r[..^1]); // CRLF in both: no part of the difference + } + + // Lines that differ in white space only (Postman indents with tabs) show it: \t, \r, and · for a space. + return l.Trim() == r.Trim() ? (i + 1, ShowWhiteSpace(l), ShowWhiteSpace(r)) : (i + 1, l.Trim(), r.Trim()); } } return (0, "", ""); } + + private static string ShowWhiteSpace(string line) => + line.Replace("\t", "\\t", StringComparison.Ordinal).Replace("\r", "\\r", StringComparison.Ordinal).Replace(' ', '·'); } /// termrest certs …: inspect the certificate registry and OS stores. @@ -152,10 +155,24 @@ public static Command Create() var list = new Command("list", "List the workspace certificate registry and test that each certificate loads."); var workspaceArg = new Argument("workspace") { Description = "Workspace folder (default: current directory)", Arity = ArgumentArity.ZeroOrOne }; + var allowOutsideFiles = new Option("--allow-outside-files") + { + Description = "Also open certificate files on network shares outside the workspace folder (default: only where allowed for the workspace in the full-screen UI, Tools › Settings…)", + }; list.Arguments.Add(workspaceArg); + list.Options.Add(allowOutsideFiles); list.SetAction(parseResult => { - var workspace = ApiWorkspace.Open(parseResult.GetValue(workspaceArg) ?? Environment.CurrentDirectory); + if (OpenWorkspace(parseResult.GetValue(workspaceArg)) is not { } workspace) + { + return 2; + } + + if (workspace.CertificatesError is not null) + { + return 1; + } + if (workspace.Certificates.Entries.Count == 0) { Output.Info($"No certificates registered in {workspace.CertificatesPath}."); @@ -164,6 +181,8 @@ public static Command Create() using var provider = new ClientCertificateProvider(workspace.Certificates); using var runner = new RequestRunner(workspace); + runner.ConfigureFiles(); + runner.OutsideFilesAllowed |= parseResult.GetValue(allowOutsideFiles); var resolver = runner.CreateResolver(null); var failures = 0; foreach (var entry in workspace.Certificates.Entries) @@ -174,7 +193,8 @@ public static Command Create() try { var loaded = provider.Load(entry, workspace.RootPath, value => - value is not null && value.StartsWith("env:", StringComparison.OrdinalIgnoreCase) ? Environment.GetEnvironmentVariable(value[4..]) : resolver.Resolve(value)); + value is not null && value.StartsWith("env:", StringComparison.OrdinalIgnoreCase) ? Environment.GetEnvironmentVariable(value[4..]) : resolver.Resolve(value), + runner.FilesFolder); var s = loaded.Summary; Output.Status($" ✓ {s.Subject} · issuer {s.IssuerCommonName} · expires {s.NotAfter:yyyy-MM-dd}{(s.IsExpired ? " (EXPIRED)" : "")} · key {(s.HasPrivateKey ? "ok" : "MISSING")}", !s.IsExpired && s.HasPrivateKey); } @@ -214,7 +234,16 @@ public static Command Create() match.Arguments.Add(matchWorkspace); match.SetAction(parseResult => { - var workspace = ApiWorkspace.Open(parseResult.GetValue(matchWorkspace) ?? Environment.CurrentDirectory); + if (OpenWorkspace(parseResult.GetValue(matchWorkspace)) is not { } workspace) + { + return 2; + } + + if (workspace.CertificatesError is not null) + { + return 1; + } + if (!Uri.TryCreate(parseResult.GetValue(url), UriKind.Absolute, out var uri)) { Output.Error("Enter an absolute URL."); @@ -236,4 +265,37 @@ public static Command Create() command.Subcommands.Add(match); return command; } + + /// + /// Opens a workspace for the certificate commands (its collections are not needed) and reports what could not be + /// read; a registry that could not be read is an error (see ). Null when + /// the workspace does not exist. + /// + private static ApiWorkspace? OpenWorkspace(string? path) + { + ApiWorkspace workspace; + try + { + workspace = ApiWorkspace.Open(path ?? Environment.CurrentDirectory, CollectionLoading.None); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Output.Error(ex.Message); + return null; + } + + foreach (var error in workspace.LoadErrors) + { + if (error == workspace.CertificatesError) + { + Output.Error(error); + } + else + { + Output.Warning(error); + } + } + + return workspace; + } } diff --git a/src/TermRest.Core/Auth/AuthApplier.cs b/src/TermRest.Core/Auth/AuthApplier.cs index 7aa9b71..6bf53a1 100644 --- a/src/TermRest.Core/Auth/AuthApplier.cs +++ b/src/TermRest.Core/Auth/AuthApplier.cs @@ -15,6 +15,12 @@ public sealed class AppliedAuth /// Credentials answered on a 401 challenge (Digest, NTLM, Negotiate). public NetworkCredential? Credential { get; set; } + /// + /// The challenge schemes answers (Digest; NTLM and Negotiate): never Basic, which would send + /// the password in clear text. + /// + public string[] CredentialSchemes { get; set; } = []; + public string Description { get; set; } = "No auth"; public List Warnings { get; } = []; @@ -41,11 +47,19 @@ public static AppliedAuth Apply(AuthSpec? auth, VariableResolver variables, ISet { var user = Get("username"); var password = Get("password"); - var token = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{password}")); + var token = BasicToken(user, password); result.Headers.Add(new("Authorization", $"Basic {token}")); - result.Description = $"Basic ({user})"; + + // The description leaves out the user name, which can be the credential itself: an API key sent with an empty + // or dummy password, as Stripe and Freshdesk take theirs (curl -u sk_test_…:). Without a password, it is a secret. + result.Description = "Basic"; result.Secrets.Add(password); result.Secrets.Add(token); + if (password.Length == 0) + { + result.Secrets.Add(user); + } + break; } @@ -53,13 +67,16 @@ public static AppliedAuth Apply(AuthSpec? auth, VariableResolver variables, ISet { var token = Get("token"); result.Secrets.Add(token); - result.Headers.Add(new("Authorization", $"Bearer {token}")); result.Description = "Bearer token"; if (token.Length == 0) { - result.Warnings.Add("Bearer token is empty."); + // As in Postman: no header then (an Authorization header the request has stays), as for a token that a + // login request's script sets later. + result.Warnings.Add("Bearer token is empty: the request was sent without it."); + break; } + result.Headers.Add(new("Authorization", $"Bearer {token}")); break; } @@ -94,6 +111,7 @@ public static AppliedAuth Apply(AuthSpec? auth, VariableResolver variables, ISet var domain = auth.Type == "ntlm" ? Get("domain") : ""; result.Secrets.Add(password); result.Credential = string.IsNullOrEmpty(domain) ? new NetworkCredential(user, password) : new NetworkCredential(user, password, domain); + result.CredentialSchemes = auth.Type == "ntlm" ? ["NTLM", "Negotiate"] : ["Digest"]; result.Description = auth.Type == "ntlm" ? $"NTLM ({(domain.Length > 0 ? domain + "\\" : "")}{user})" : $"Digest ({user})"; break; } @@ -130,4 +148,7 @@ public static AppliedAuth Apply(AuthSpec? auth, VariableResolver variables, ISet return result; } + + /// The credentials of an Authorization: Basic header (RFC 7617, in UTF-8). + internal static string BasicToken(string user, string password) => Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{password}")); } diff --git a/src/TermRest.Core/Certificates/CertificateLoader.cs b/src/TermRest.Core/Certificates/CertificateLoader.cs index 5fd645e..4e315bf 100644 --- a/src/TermRest.Core/Certificates/CertificateLoader.cs +++ b/src/TermRest.Core/Certificates/CertificateLoader.cs @@ -81,10 +81,11 @@ public static LoadedCertificate LoadPem(string certPath, string? keyPath, string EnsureExists(keyPath, "private key"); } - var keyText = File.ReadAllText(keyPath ?? certPath); - X509Certificate2 leaf; + X509Certificate2? leaf = null; + var chain = new X509Certificate2Collection(); try { + var keyText = File.ReadAllText(keyPath ?? certPath); if (keyText.Contains("Proc-Type: 4,ENCRYPTED", StringComparison.Ordinal)) { throw new CertificateLoadException( @@ -111,33 +112,34 @@ public static LoadedCertificate LoadPem(string certPath, string? keyPath, string { leaf = X509Certificate2.CreateFromPemFile(certPath, keyPath); } - } - catch (CryptographicException ex) - { - throw new CertificateLoadException($"Could not load PEM certificate/key: {ex.Message}", ex); - } - var chain = new X509Certificate2Collection(); - var all = new X509Certificate2Collection(); - all.ImportFromPemFile(certPath); - foreach (var certificate in all) - { - if (certificate.Thumbprint == leaf.Thumbprint) + var all = new X509Certificate2Collection(); + all.ImportFromPemFile(certPath); + foreach (var certificate in all) { - certificate.Dispose(); + if (certificate.Thumbprint == leaf.Thumbprint) + { + certificate.Dispose(); + } + else + { + chain.Add(certificate); + } } - else + + return new LoadedCertificate { - chain.Add(certificate); - } + Certificate = MakeUsableForTls(leaf), + Chain = chain, + Description = $"PEM {Path.GetFileName(certPath)}", + }; } - - return new LoadedCertificate + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or CryptographicException) { - Certificate = MakeUsableForTls(leaf), - Chain = chain, - Description = $"PEM {Path.GetFileName(certPath)}", - }; + leaf?.Dispose(); + DisposeAll(chain); + throw new CertificateLoadException($"Could not load PEM certificate/key: {ex.Message}", ex); + } } public static LoadedCertificate LoadPfx(string pfxPath, string? passphrase) @@ -148,6 +150,10 @@ public static LoadedCertificate LoadPfx(string pfxPath, string? passphrase) { collection = X509CertificateLoader.LoadPkcs12CollectionFromFile(pfxPath, passphrase, KeyStorageFlags); } + catch (Exception ex) when (ReadError(ex) is { } error) + { + throw new CertificateLoadException($"Could not open '{Path.GetFileName(pfxPath)}': {error.Message}", ex); + } catch (CryptographicException ex) { throw new CertificateLoadException($"Could not open '{Path.GetFileName(pfxPath)}' (wrong passphrase?): {ex.Message}", ex); @@ -188,16 +194,17 @@ public static LoadedCertificate LoadFromStore(StoreSource source) } using var store = new X509Store(source.StoreName, location); + X509Certificate2Collection all; try { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); + all = store.Certificates; } - catch (CryptographicException ex) + catch (Exception ex) when (ex is CryptographicException or IOException or UnauthorizedAccessException) { throw new CertificateLoadException($"Cannot open certificate store {source.Location}\\{source.StoreName}: {ex.Message}", ex); } - var all = store.Certificates; X509Certificate2Collection found; if (!string.IsNullOrWhiteSpace(source.Thumbprint)) { @@ -280,14 +287,21 @@ public static X509Certificate2Collection LoadTrustBundle(string path) { EnsureExists(path, "CA bundle"); var collection = new X509Certificate2Collection(); - var text = File.ReadAllText(path); - if (text.Contains("-----BEGIN CERTIFICATE-----", StringComparison.Ordinal)) + try { - collection.ImportFromPemFile(path); + var text = File.ReadAllText(path); + if (text.Contains("-----BEGIN CERTIFICATE-----", StringComparison.Ordinal)) + { + collection.ImportFromPem(text); + } + else + { + collection.Add(X509CertificateLoader.LoadCertificateFromFile(path)); + } } - else + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or CryptographicException) { - collection.Add(X509CertificateLoader.LoadCertificateFromFile(path)); + throw new CertificateLoadException((ReadError(ex) ?? ex).Message, ex); } return collection; @@ -330,6 +344,17 @@ private static void EnsureExists(string path, string what) } } + /// + /// The error reading a file behind , if any: .NET reports one in a PKCS#12 file as a + /// CryptographicException, which would otherwise read as a wrong passphrase. + /// + private static Exception? ReadError(Exception ex) => ex switch + { + IOException or UnauthorizedAccessException => ex, + CryptographicException { InnerException: IOException or UnauthorizedAccessException } => ex.InnerException, + _ => null, + }; + private static void DisposeAll(X509Certificate2Collection collection) { foreach (var c in collection) diff --git a/src/TermRest.Core/Certificates/CertificateRegistry.cs b/src/TermRest.Core/Certificates/CertificateRegistry.cs index 2906abc..5574c80 100644 --- a/src/TermRest.Core/Certificates/CertificateRegistry.cs +++ b/src/TermRest.Core/Certificates/CertificateRegistry.cs @@ -10,6 +10,9 @@ namespace TermRest.Core.Certificates; /// public sealed class CertificateRegistry { + /// What held when it was last read or written; null when it did not exist then. + private FileStamp? _stamp; + public CertificateRegistry(string baseDirectory, string? filePath = null) { BaseDirectory = baseDirectory; @@ -24,20 +27,34 @@ public CertificateRegistry(string baseDirectory, string? filePath = null) public static CertificateRegistry Load(string path, string baseDirectory) { - var (text, _) = TextFile.Read(path); + var (text, _) = TextFile.Read(path, out var stamp); var entries = JsonSerializer.Deserialize(text, CoreJsonContext.Default.ListCertificateEntry) ?? throw new InvalidDataException($"'{path}' does not contain a certificate list."); - return new CertificateRegistry(baseDirectory, path) { Entries = entries }; + return new CertificateRegistry(baseDirectory, path) { Entries = entries, _stamp = stamp }; } public static CertificateRegistry LoadOrEmpty(string path, string baseDirectory) => File.Exists(path) ? Load(path, baseDirectory) : new CertificateRegistry(baseDirectory, path); - public void Save(string? path = null) + /// + /// Writes the entries to (default ). Saving over + /// is refused with a when another program (a git pull, another TermRest) changed + /// or created it since it was read: that would undo its changes. + /// + /// Write the file even when it changed on disk. + public void Save(string? path = null, bool overwriteChanged = false) { path ??= FilePath ?? throw new InvalidOperationException("The registry has no file path."); + var fullPath = Path.GetFullPath(path); + if (!overwriteChanged && FilePath is not null && string.Equals(fullPath, Path.GetFullPath(FilePath), StringComparison.OrdinalIgnoreCase) + && File.Exists(fullPath) && (_stamp is null || _stamp.HasChanged(fullPath))) + { + throw new FileChangedException([fullPath]); + } + var json = JsonSerializer.Serialize(Entries, CoreJsonContext.Default.ListCertificateEntry); - TextFile.WriteAtomic(path, json.Replace("\r\n", "\n", StringComparison.Ordinal), new TextFileInfo(false, true, false)); + TextFile.WriteAtomic(path, json.Replace("\r\n", "\n", StringComparison.Ordinal), new TextFileInfo(false, true, false), out var stamp); + _stamp = stamp; FilePath = path; } diff --git a/src/TermRest.Core/Certificates/ClientCertificateProvider.cs b/src/TermRest.Core/Certificates/ClientCertificateProvider.cs index fad7a9d..a8779a8 100644 --- a/src/TermRest.Core/Certificates/ClientCertificateProvider.cs +++ b/src/TermRest.Core/Certificates/ClientCertificateProvider.cs @@ -1,5 +1,7 @@ using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; using System.Text; +using TermRest.Core.IO; using TermRest.Core.Model; namespace TermRest.Core.Certificates; @@ -8,26 +10,50 @@ public sealed record ClientCertificateSelection(CertificateEntry Entry, LoadedCe { /// Captured at selection time, so diagnostics never touch a certificate that was reloaded (disposed) meanwhile. public CertificateSummary Summary { get; } = Certificate.Summary; + + /// + /// The folder relative paths of are resolved against: the workspace root for a registered + /// certificate, the collection's folder for one pinned on a request (null: unknown). + /// + public string? BaseDirectory { get; init; } + + /// The full path of the file a path of refers to: the file the certificate was loaded from. + public string ResolvePath(string src) => BaseDirectory is null ? src : ClientCertificateProvider.ResolvePath(BaseDirectory, src); } /// /// Chooses and loads the client certificate for a request: a certificate pinned on the request wins, then the most -/// specific registry match. Loaded certificates are cached until their files change. +/// specific registry match. Loaded certificates, and the workspace CA bundle, are cached until their files change. /// public sealed class ClientCertificateProvider(CertificateRegistry registry) : IDisposable { - private readonly Dictionary _cache = new(StringComparer.Ordinal); + /// Why a certificate or CA bundle file on a network share is not opened, and how to allow it. + public const string OnNetworkShare = + "it is on a network share outside the workspace folder, or a link leads there, so it is not opened (Windows would sign in to " + + "that server with your credentials): allow files from outside the folder for this workspace in the full-screen UI " + + "(Tools › Settings…), or with --allow-outside-files."; + + // Keyed by source (see BuildCacheKey); a replaced certificate or bundle may still be in use by a request in flight, + // so it is retired and released with the provider. + private readonly Dictionary _cache = new(StringComparer.Ordinal); private readonly List _retired = []; + private readonly Dictionary _trustBundles = new(StringComparer.Ordinal); + private readonly List _retiredBundles = []; private readonly Lock _gate = new(); public CertificateRegistry Registry { get; } = registry; + /// + /// While set, a certificate file on a network share outside it is not opened (see ): + /// the registry and the requests come with the repository. + /// public ClientCertificateSelection? Select( Uri uri, CertificateSpec? requestCertificate, string requestBaseDirectory, Func resolveSecret, - ICollection warnings) + ICollection warnings, + string? filesFolder = null) { if (requestCertificate is { } pinned && (pinned.CertSrc is not null || pinned.PfxSrc is not null)) { @@ -44,30 +70,43 @@ public sealed class ClientCertificateProvider(CertificateRegistry registry) : ID Pfx = pinned.PfxSrc is null ? null : new FileSource { Src = pinned.PfxSrc }, Passphrase = pinned.Passphrase, }; - return TrySelect(entry, requestBaseDirectory, "pinned on request", resolveSecret, warnings); + return TrySelect(entry, requestBaseDirectory, "pinned on request", resolveSecret, warnings, filesFolder); } } if (Registry.FindBestMatch(uri) is { } match) { - return TrySelect(match.Entry, Registry.BaseDirectory, $"matched {match.Pattern}", resolveSecret, warnings); + return TrySelect(match.Entry, Registry.BaseDirectory, $"matched {match.Pattern}", resolveSecret, warnings, filesFolder); } return null; } /// Loads (or returns the cached) certificate for an entry. Throws . - public LoadedCertificate Load(CertificateEntry entry, string baseDirectory, Func? resolveSecret = null) + /// While set, a file on a network share outside it is not opened (see ). + public LoadedCertificate Load(CertificateEntry entry, string baseDirectory, Func? resolveSecret = null, string? filesFolder = null) { var passphrase = resolveSecret is null ? entry.Passphrase : resolveSecret(entry.Passphrase); - string Resolve(string src) => Path.IsPathRooted(src) ? src : Path.GetFullPath(Path.Combine(baseDirectory, src)); + string Resolve(string src) => ResolvePath(baseDirectory, src); + + // Before the cache looks at the files. + if (filesFolder is not null) + { + foreach (var src in (string?[])[entry.Cert?.Src, entry.Key?.Src, entry.Pfx?.Src]) + { + if (src is not null && Resolve(src) is var path && RealPath.ReachesNetwork(path, filesFolder)) + { + throw new CertificateLoadException($"'{path}': {OnNetworkShare}"); + } + } + } - var key = BuildCacheKey(entry, Resolve, passphrase); + var (source, version) = BuildCacheKey(entry, Resolve, passphrase); lock (_gate) { - if (_cache.TryGetValue(key, out var cached)) + if (_cache.TryGetValue(source, out var cached) && cached.Version == version) { - return cached; + return cached.Certificate; } } @@ -81,23 +120,63 @@ public LoadedCertificate Load(CertificateEntry entry, string baseDirectory, Func lock (_gate) { - foreach (var stale in _cache.Where(kv => kv.Key.StartsWith(entry.Name + "|", StringComparison.Ordinal)).ToList()) + if (_cache.TryGetValue(source, out var stale)) { - _cache.Remove(stale.Key); - _retired.Add(stale.Value); + _retired.Add(stale.Certificate); } - _cache[key] = loaded; + _cache[source] = (version, loaded); } return loaded; } - private ClientCertificateSelection? TrySelect(CertificateEntry entry, string baseDirectory, string origin, Func resolveSecret, ICollection warnings) + /// + /// Loads (or returns the cached) extra CA bundle, parsed again only when the file changes. Throws + /// , also for a failure cached until then. + /// + public X509Certificate2Collection LoadTrustBundle(string path) { + var file = new FileInfo(Path.GetFullPath(path)); + var version = file.Exists ? (file.LastWriteTimeUtc, file.Length) : default; + lock (_gate) + { + if (_trustBundles.TryGetValue(file.FullName, out var cached) && cached.Version == version) + { + return cached.Bundle ?? throw new CertificateLoadException(cached.Error!); + } + } + + X509Certificate2Collection? bundle = null; + string? error = null; try { - var loaded = Load(entry, baseDirectory, resolveSecret); + bundle = CertificateLoader.LoadTrustBundle(path); + } + catch (CertificateLoadException ex) + { + error = ex.Message; + } + + lock (_gate) + { + if (_trustBundles.TryGetValue(file.FullName, out var stale) && stale.Bundle is { } replaced) + { + _retiredBundles.Add(replaced); + } + + _trustBundles[file.FullName] = (version, bundle, error); + } + + return bundle ?? throw new CertificateLoadException(error!); + } + + private ClientCertificateSelection? TrySelect(CertificateEntry entry, string baseDirectory, string origin, Func resolveSecret, + ICollection warnings, string? filesFolder) + { + try + { + var loaded = Load(entry, baseDirectory, resolveSecret, filesFolder); var summary = loaded.Summary; if (summary.IsExpired) { @@ -108,7 +187,7 @@ public LoadedCertificate Load(CertificateEntry entry, string baseDirectory, Func warnings.Add($"Client certificate '{entry.Name}' is not valid until {summary.NotBefore:yyyy-MM-dd}."); } - return new ClientCertificateSelection(entry, loaded, origin); + return new ClientCertificateSelection(entry, loaded, origin) { BaseDirectory = baseDirectory }; } catch (CertificateLoadException ex) { @@ -117,9 +196,18 @@ public LoadedCertificate Load(CertificateEntry entry, string baseDirectory, Func } } - private static string BuildCacheKey(CertificateEntry entry, Func resolve, string? passphrase) + /// The full path of a certificate file: a relative is relative to . + internal static string ResolvePath(string baseDirectory, string src) => + Path.IsPathRooted(src) ? src : Path.GetFullPath(Path.Combine(baseDirectory, src)); + + /// + /// Where a certificate comes from (its kind and files, or its store selector) and the version of that source (file + /// times, passphrase): entries sharing a name do not evict each other, and a changed source replaces its certificate. + /// + private static (string Source, string Version) BuildCacheKey(CertificateEntry entry, Func resolve, string? passphrase) { - var builder = new StringBuilder(entry.Name).Append('|').Append(entry.Kind); + var source = new StringBuilder().Append(entry.Kind); + var version = new StringBuilder(); void AppendFile(string? src) { if (src is null) @@ -128,7 +216,8 @@ void AppendFile(string? src) } var path = resolve(src); - builder.Append('|').Append(path).Append('@').Append(File.Exists(path) ? File.GetLastWriteTimeUtc(path).Ticks : 0); + source.Append('|').Append(path); + version.Append(File.Exists(path) ? File.GetLastWriteTimeUtc(path).Ticks : 0).Append('|'); } AppendFile(entry.Cert?.Src); @@ -136,28 +225,38 @@ void AppendFile(string? src) AppendFile(entry.Pfx?.Src); if (entry.Store is { } store) { - builder.Append('|').Append(store.Location).Append('\\').Append(store.StoreName).Append('|').Append(store.Thumbprint).Append('|').Append(store.Subject); + source.Append('|').Append(store.Location).Append('\\').Append(store.StoreName).Append('|').Append(store.Thumbprint).Append('|').Append(store.Subject); } if (!string.IsNullOrEmpty(passphrase)) { - builder.Append('|').Append(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(passphrase)))); + version.Append(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(passphrase)))); } - return builder.ToString(); + return (source.ToString(), version.ToString()); } public void Dispose() { lock (_gate) { - foreach (var certificate in _cache.Values.Concat(_retired)) + foreach (var certificate in _cache.Values.Select(c => c.Certificate).Concat(_retired)) { certificate.Dispose(); } + foreach (var bundle in _trustBundles.Values.Select(b => b.Bundle).OfType().Concat(_retiredBundles)) + { + foreach (var ca in bundle) + { + ca.Dispose(); + } + } + _cache.Clear(); _retired.Clear(); + _trustBundles.Clear(); + _retiredBundles.Clear(); } } } diff --git a/src/TermRest.Core/Certificates/UrlMatchPattern.cs b/src/TermRest.Core/Certificates/UrlMatchPattern.cs index 4575648..3663513 100644 --- a/src/TermRest.Core/Certificates/UrlMatchPattern.cs +++ b/src/TermRest.Core/Certificates/UrlMatchPattern.cs @@ -1,3 +1,7 @@ +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Text; using System.Text.RegularExpressions; namespace TermRest.Core.Certificates; @@ -10,6 +14,8 @@ namespace TermRest.Core.Certificates; /// public sealed class UrlMatchPattern { + private static readonly IdnMapping Idn = new(); + private readonly string? _scheme; private readonly string _host; private readonly int? _port; @@ -85,6 +91,31 @@ public static bool TryParse(string pattern, out UrlMatchPattern? result) return false; } + // An IPv6 address is matched as Uri.IdnHost gives it: without brackets, in its shortest form ([0:0::1] is ::1). + if (host.StartsWith('[')) + { + if (!host.EndsWith(']') || !IPAddress.TryParse(host[1..^1], out var address) || address.AddressFamily != AddressFamily.InterNetworkV6) + { + return false; + } + + host = address.ToString(); + } + + // URLs are matched by their host in ASCII (Uri.IdnHost), so a host written in Unicode is matched in its ASCII form. + if (!Ascii.IsValid(host)) + { + var wildcard = host.StartsWith("*.", StringComparison.Ordinal) ? "*." : ""; + try + { + host = wildcard + Idn.GetAscii(host[wildcard.Length..]); + } + catch (ArgumentException) + { + return false; // no URL has such a host + } + } + Regex? pathRegex = pathGlob is "/*" or "*" ? null : new Regex("^" + Regex.Escape(pathGlob).Replace(@"\*", ".*", StringComparison.Ordinal) + "$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); diff --git a/src/TermRest.Core/History/HistoryEntry.cs b/src/TermRest.Core/History/HistoryEntry.cs index 9653ef1..35fc7c1 100644 --- a/src/TermRest.Core/History/HistoryEntry.cs +++ b/src/TermRest.Core/History/HistoryEntry.cs @@ -1,10 +1,13 @@ using System.Globalization; +using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using TermRest.Core.Http; using TermRest.Core.Json; using TermRest.Core.Model; using TermRest.Core.Postman; +using TermRest.Core.Recording; +using TermRest.Core.Variables; namespace TermRest.Core.History; @@ -14,9 +17,19 @@ namespace TermRest.Core.History; /// public sealed class HistoryEntry { - /// Header names whose values are always masked in the recorded request headers. + /// + /// Header names whose values are always masked in the recorded request and response headers, besides the names that + /// recordings redact (: Ocp-Apim-Subscription-Key, X-Functions-Key, api_key …). + /// private static readonly string[] SensitiveHeaderParts = ["authorization", "cookie", "token", "secret", "password", "api-key", "apikey", "x-api-key"]; + /// What may stand between {{variable}} references without being a typed secret ({{user}}:{{password}}). + private const string ReferenceSeparators = "=:;,&"; + + // UTF-16 and UTF-32 in either byte order, with their byte order marks (see WideEncodings). + private static readonly Encoding[] Utf16 = [Encoding.Unicode, Encoding.BigEndianUnicode]; + private static readonly Encoding[] Utf32 = [Encoding.UTF32, new UTF32Encoding(bigEndian: true, byteOrderMark: true)]; + public required string Id { get; init; } public required DateTimeOffset Time { get; init; } @@ -29,8 +42,40 @@ public sealed class HistoryEntry /// The request as edited when it was sent: a Postman v2.1 item (name, request, event). public required JsonObject Item { get; init; } + /// + /// Whether credentials typed into the request were masked as *** in : secret auth + /// parameters (and a Basic user name sent without a password, then the credential), headers named like secrets (the + /// values of a Cookie header, keeping the cookie names), the password in the URL (https://user:password@host, or the + /// user name of a URL without one) and the client certificate's passphrase ({{variable}} references are kept). + /// They must be entered again before the request is sent again. + /// + public bool CredentialsMasked { get; init; } + + /// + /// Whether the request inherited its auth from its folders or collection: holds a copy, masked like + /// typed credentials. Re-sending can take the auth from the original request again (see ). + /// + public bool AuthInherited { get; init; } + + /// + /// Whether still holds a credential masked in the history (see ): + /// sent as it is, the server would get *** in its place. + /// + public static bool HasMaskedCredentials(HttpRequestSpec spec) => + spec.Auth?.Params.Any(p => p.ValueAsString == "***") == true + || spec.Headers.Any(h => IsSensitiveHeader(h.Key) && h.Value is { } value && IsMasked(h.Key, value)) + || spec.Certificate?.Passphrase == "***" + || PostmanUrl.Parse(spec.Url) is { AuthPassword: "***" } or { AuthUser: "***" }; + public string? Collection { get; init; } + /// + /// The file of (a v3 collection's folder) in the workspace, relative with "/" (see + /// ): it tells collections of the same name apart. Entries of earlier + /// versions have none. + /// + public string? CollectionFile { get; init; } + public string? RequestPath { get; init; } public string? Environment { get; init; } @@ -77,40 +122,33 @@ public static HistoryEntry Create(HttpExchange exchange, RequestSource source, s var response = exchange.Response; var item = new JsonObject { - ["name"] = source.RequestName ?? $"{request.Method} {PostmanUrl.StripQueryAndHash(source.Spec.Url)}", + ["name"] = source.RequestName ?? $"{request.Method} {MaskUrlPassword(PostmanUrl.StripQueryAndHash(source.Spec.Url))}", ["request"] = new JsonObject { ["method"] = source.Spec.Method, ["header"] = new JsonArray() }, }; PostmanRequestMapper.Apply(item, source.Spec, PostmanRequestMapper.Read(item, PostmanSchemaVersion.V21), PostmanSchemaVersion.V21); + var credentialsMasked = MaskCredentials(item); body = null; var truncated = response?.BodyTruncated == true; if (response is { Body.Length: > 0 } && maxBodyBytes > 0) { - body = response.Body.Length > maxBodyBytes ? response.Body[..maxBodyBytes] : response.Body; - truncated |= response.Body.Length > maxBodyBytes; - - // Servers that echo the request (like postman-echo) would otherwise keep credentials in the history. - if (request.SecretValues.Count > 0 && System.Text.Unicode.Utf8.IsValid(body)) - { - var text = System.Text.Encoding.UTF8.GetString(body); - var redacted = request.Redact(text); - if (redacted != text) - { - body = System.Text.Encoding.UTF8.GetBytes(redacted); - } - } + body = StoredBody(response.Body, response.ContentType, maxBodyBytes, request, out var cut); + truncated |= cut; } var sent = exchange.SentHeaders.Count > 0 ? exchange.SentHeaders : request.Headers; - var finalUrl = response?.FinalUri?.ToString(); + var finalUri = response?.FinalUri; return new HistoryEntry { Id = Guid.NewGuid().ToString("N"), Time = exchange.StartedAt, Method = request.Method, - Url = request.Redact(request.Url), + Url = MaskUrlPassword(request.Redact(request.Url), keepReferences: false), Item = item, + CredentialsMasked = credentialsMasked, + AuthInherited = source.AuthInherited, Collection = source.CollectionName, + CollectionFile = source.CollectionFile, RequestPath = source.RequestPath, Environment = environment, SentHeaders = sent.Select(h => new KeyValuePair(h.Key, RedactHeader(h.Key, h.Value, request))).ToList(), @@ -123,14 +161,18 @@ public static HistoryEntry Create(HttpExchange exchange, RequestSource source, s BodySaved = body is not null, BodyTruncated = truncated, Error = response is null ? request.Redact(exchange.ErrorMessage ?? "Request failed.") : null, - FinalUrl = finalUrl is not null && finalUrl != request.Uri?.ToString() ? request.Redact(finalUrl) : null, + FinalUrl = finalUri is not null && finalUri != request.Uri ? MaskUri(finalUri, request) : null, ClientCertificate = exchange.Tls.Select(t => t.ClientCertificate).FirstOrDefault(c => c is not null)?.ToString() ?? request.ClientCertificate?.Summary.ToString(), Timing = exchange.Timing, }; } - /// Rebuilds an exchange for display in the response pane (no TLS details; body from the store). + /// + /// Rebuilds an exchange for display in the response pane: no TLS details or script results, the request's settings + /// left at their defaults, and the body from the store (maybe only its start). Its + /// is this entry, which has the size of the body and the client certificate. + /// public HttpExchange ToExchange(byte[]? body) { var prepared = new PreparedRequest @@ -141,7 +183,7 @@ public HttpExchange ToExchange(byte[]? body) AuthDescription = "(not recorded)", }; prepared.Headers.AddRange(SentHeaders); - var exchange = new HttpExchange(prepared) { StartedAt = Time, Timing = Timing, ErrorMessage = Error }; + var exchange = new HttpExchange(prepared) { StartedAt = Time, Timing = Timing, ErrorMessage = Error, HistoryEntry = this }; exchange.SentHeaders.AddRange(SentHeaders); if (Status is { } status) { @@ -161,30 +203,357 @@ public HttpExchange ToExchange(byte[]? body) return exchange; } - private static string RedactHeader(string name, string value, PreparedRequest request) + private static string RedactHeader(string name, string value, PreparedRequest request) => + IsSensitiveHeader(name) ? MaskHeader(name, value) : request.Redact(value); + + /// Session cookies keep their name and attributes; the value is masked. Other headers are masked like request headers. + private static string RedactResponseHeader(string name, string value, PreparedRequest request) + { + if (name.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)) + { + var equals = value.IndexOf('=', StringComparison.Ordinal); + var end = value.IndexOf(';', StringComparison.Ordinal); + return equals < 0 ? "***" : value[..(equals + 1)] + "***" + (end > equals ? value[end..] : ""); + } + + return RedactHeader(name, value, request); + } + + private static bool IsSensitiveHeader(string name) { var lower = name.ToLowerInvariant(); - if (SensitiveHeaderParts.Any(part => lower.Contains(part, StringComparison.Ordinal))) + return SensitiveHeaderParts.Any(part => lower.Contains(part, StringComparison.Ordinal)) || SecretNames.IsSecret(name, NameKind.Header); + } + + /// Keeps the scheme of an Authorization header ("Bearer ***") so the entry still says what kind of credential was sent. + private static string MaskHeader(string name, string value) => CredentialStart(name, value) is > 0 and var start ? value[..start] + "***" : "***"; + + /// Where the credential starts in a header value: after the scheme of an Authorization header ("Bearer …"). + private static int CredentialStart(string name, string value) + { + var space = value.IndexOf(' ', StringComparison.Ordinal); + return space > 0 && name.Contains("authorization", StringComparison.OrdinalIgnoreCase) ? space + 1 : 0; + } + + /// + /// with the credential typed into it masked, or null when it has none (only {{variable}} + /// references). A Cookie header is masked cookie by cookie, keeping their names: sid=***; theme={{theme}}. + /// + private static string? MaskTyped(string name, string value) + { + if (!IsCookie(name)) { - // Keep the scheme ("Bearer", "Basic") so the entry still says what kind of credential was sent. - var space = value.IndexOf(' ', StringComparison.Ordinal); - return lower.Contains("authorization", StringComparison.Ordinal) && space > 0 ? value[..space] + " ***" : "***"; + return IsLiteral(value[CredentialStart(name, value)..]) ? MaskHeader(name, value) : null; } - return request.Redact(value); + var pairs = value.Split(';'); + var masked = false; + for (var i = 0; i < pairs.Length; i++) + { + var start = CookieValueStart(pairs[i]); + if (IsLiteral(pairs[i][start..])) + { + pairs[i] = pairs[i][..start] + "***"; + masked = true; + } + } + + return masked ? string.Join(';', pairs) : null; } - /// Session cookies keep their name and attributes; the value is masked. - private static string RedactResponseHeader(string name, string value, PreparedRequest request) + /// Whether a header still has a credential masked in the history (in a Cookie header: one of its cookies). + private static bool IsMasked(string name, string value) => + IsCookie(name) + ? value.Split(';').Any(pair => pair[CookieValueStart(pair)..].Trim() == "***") + : value[CredentialStart(name, value)..] == "***"; + + private static bool IsCookie(string name) => name.Equals("Cookie", StringComparison.OrdinalIgnoreCase); + + /// Where the value starts in a cookie's name=value pair (a pair without a name is all value). + private static int CookieValueStart(string pair) { - if (name.Equals("Set-Cookie", StringComparison.OrdinalIgnoreCase)) + var equals = pair.IndexOf('=', StringComparison.Ordinal); + return equals >= 0 ? equals + 1 : pair.Length - pair.TrimStart().Length; + } + + /// + /// Masks the credentials typed into the request (see ); values that are only + /// {{variable}} references (or env:NAME for the passphrase) hold no secret and are kept, so the request + /// can be sent again. Returns whether anything was masked. + /// + private static bool MaskCredentials(JsonObject item) + { + if (item["request"] is not JsonObject request) { - var equals = value.IndexOf('=', StringComparison.Ordinal); - var end = value.IndexOf(';', StringComparison.Ordinal); - return equals < 0 ? "***" : value[..(equals + 1)] + "***" + (end > equals ? value[end..] : ""); + return false; + } + + var masked = false; + if (request["auth"] is JsonObject auth) + { + foreach (var (type, parameters) in auth) + { + // Basic auth without a password (curl -u sk_test_…:) sends the user name as the credential. + var userIsCredential = type == "basic" && string.IsNullOrEmpty(AuthParameter(parameters, "password")); + + // Postman v2.1 lists the parameters ([{"key": "password", "value": …}]); v2.0 maps them ({"password": …}). + if (parameters is JsonArray list) + { + foreach (var parameter in list.OfType()) + { + masked |= MaskAuthParameter(type, parameter["key"].GetString(), parameter, "value", userIsCredential); + } + } + else if (parameters is JsonObject map) + { + foreach (var key in map.Select(p => p.Key).ToList()) + { + masked |= MaskAuthParameter(type, key, map, key, userIsCredential); + } + } + } + } + + foreach (var header in (request["header"] as JsonArray)?.OfType() ?? []) + { + if (header["key"].GetString() is { } name && IsSensitiveHeader(name) && header["value"].GetString() is { } value + && MaskTyped(name, value) is { } typed) + { + header["value"] = typed; + masked = true; + } + } + + if (request["certificate"] is JsonObject certificate && certificate["passphrase"].GetString() is { } passphrase + && !passphrase.StartsWith("env:", StringComparison.OrdinalIgnoreCase) && IsLiteral(passphrase)) + { + certificate["passphrase"] = "***"; + masked = true; + } + + // Credentials in the URL (https://user:password@host, or a user name alone, then the credential) are sent as Basic + // auth: the URL's text, and its parts in a URL object. + var url = request["url"] as JsonObject; + foreach (var (owner, property) in (IEnumerable<(JsonObject?, string)>)[(request, "url"), (url, "raw")]) + { + if (owner?[property] is JsonValue text && text.GetValueKind() == JsonValueKind.String + && MaskUrlPassword(text.GetValue()) is var maskedUrl && maskedUrl != text.GetValue()) + { + owner[property] = maskedUrl; + masked = true; + } + } + + if (url?["auth"] is JsonObject urlAuth) + { + var part = string.IsNullOrEmpty(urlAuth["password"].GetString()) ? "user" : "password"; + if (urlAuth[part].GetString() is { } credential && credential != "***" && IsLiteral(credential)) + { + urlAuth[part] = "***"; + masked = true; + } + } + + return masked; + } + + /// + /// with the password of its user info (https://user:password@host) masked as ***, or its + /// user name when it has no password (https://user@host, https://user:@host: it is then the credential); one that is + /// only {{variable}} references is kept if . + /// + private static string MaskUrlPassword(string url, bool keepReferences = true) => + PostmanUrl.MaskCredentials(url, keepReferences ? IsLiteral : null); + + /// + /// A URL System.Uri gives (the one a redirect led to), masked like : its password, and the secret + /// values in the forms a URL holds them, as typed, as System.Uri leaves them and URL-encoded. It is kept as + /// , as it was sent: ToString() unescapes part of a value (%20 …), which then matches none. + /// + private static string MaskUri(Uri uri, PreparedRequest request) + { + var url = uri.AbsoluteUri; + var forms = request.SecretValues.Where(s => s.Length >= 4).SelectMany(s => (string[])[s, SecretPatterns.InUrl(s), Uri.EscapeDataString(s)]); + foreach (var form in forms.Distinct(StringComparer.Ordinal).OrderByDescending(f => f.Length)) + { + url = url.Replace(form, "***", StringComparison.Ordinal); + } + + return MaskUrlPassword(url, keepReferences: false); + } + + /// + /// Masks an auth parameter that holds a credential: passwords, tokens, secrets, private keys, access keys and auth keys + /// (named so, see ), the value of an API key, and a Basic user name that is the credential. + /// A number (a hand-written collection's "value": 123456) is sent as its text and masked too; a flag such as + /// JWT's isSecretBase64Encoded holds no credential. + /// + private static bool MaskAuthParameter(string type, string? key, JsonObject owner, string property, bool userIsCredential) + { + if (!((type == "apikey" && key == "value") || (userIsCredential && key == "username") || SecretNames.IsSecret(key, NameKind.Field)) + || owner[property] is not JsonValue value || value.GetValueKind() is not (JsonValueKind.String or JsonValueKind.Number) + || !IsLiteral(value.GetString()!)) + { + return false; + } + + owner[property] = "***"; + return true; + } + + /// The value of an auth parameter, listed (v2.1) or mapped (v2.0); null without one. + private static string? AuthParameter(JsonNode? parameters, string key) => parameters switch + { + JsonArray list => list.OfType().FirstOrDefault(p => p["key"].GetString() == key)?["value"].GetString(), + JsonObject map => map[key].GetString(), + _ => null, + }; + + /// + /// Whether has text of its own besides {{variable}} references. Spaces and separators + /// between references are not ({{user}}:{{password}}). + /// + private static bool IsLiteral(string value) + { + var rest = value; + foreach (var name in VariableResolver.FindReferences(value)) + { + rest = rest.Replace("{{" + name + "}}", "", StringComparison.Ordinal); } - return request.Redact(value); + return rest.Length == value.Length + ? rest.Trim().Length > 0 + : rest.Any(c => !char.IsWhiteSpace(c) && !ReferenceSeparators.Contains(c, StringComparison.Ordinal)); + } + + /// + /// The part of a response body kept in the history (at most ) with every secret value + /// replaced by ***: servers that echo the request (like postman-echo) would otherwise keep credentials in the + /// history. The bytes are searched, in every form a secret takes in text (also URL-encoded or JSON-escaped, see + /// ), in UTF-8 and in the UTF-16 or UTF-32 the body says it is in + /// (see ), so it does not matter which encoding the body has or where the limit cuts it; + /// a secret that the limit would cut is left out entirely. The placeholder is written in the secret's encoding. + /// + private static byte[] StoredBody(byte[] body, string? contentType, int maxBytes, PreparedRequest request, out bool cut) + { + // UTF-8 whatever the body says, as a label can be wrong. + Encoding[] encodings = [Encoding.UTF8, .. WideEncodings(body, contentType)]; + var units = Array.ConvertAll(encodings, encoding => encoding.GetByteCount("*")); + var placeholders = Array.ConvertAll(encodings, encoding => encoding.GetBytes("***")); + var secrets = new List<(byte[] Bytes, int Encoding)>(); + foreach (var value in request.SecretValues.Where(s => s.Length >= 4)) + { + for (var e = 0; e < encodings.Length; e++) + { + foreach (var form in SecretPatterns.Forms(value, encodings[e])) + { + secrets.Add((form, e)); + } + } + } + + var window = body.AsSpan(0, (int)Math.Min(body.Length, (long)maxBytes + secrets.Select(s => s.Bytes.Length).DefaultIfEmpty(1).Max() - 1)); + var spans = new List<(int Start, int End, int Encoding)>(); + foreach (var (secret, encoding) in secrets) + { + for (var offset = 0; ;) + { + var index = window[offset..].IndexOf(secret); + if (index < 0) + { + break; + } + + index += offset; + if (index % units[encoding] != 0) + { + offset = index + 1; // across UTF-16 or UTF-32 characters: other text + continue; + } + + spans.Add((index, index + secret.Length, encoding)); + offset = index + secret.Length; + } + } + + spans.Sort(); + var limit = Math.Min(body.Length, maxBytes); + var replaced = new List<(int Start, int End, int Encoding)>(); + foreach (var (start, end, encoding) in spans) + { + var position = replaced.Count > 0 ? replaced[^1].End : 0; + if (end <= position) + { + continue; // within a secret already replaced + } + + if (Math.Max(start, position) >= limit || end > limit) + { + limit = Math.Clamp(start, position, limit); + break; + } + + if (start < position) + { + replaced[^1] = replaced[^1] with { End = end }; // overlapping secrets are replaced together + } + else + { + replaced.Add((start, end, encoding)); + } + } + + cut = limit < body.Length; + if (replaced.Count == 0) + { + return cut ? body[..limit] : body; + } + + using var output = new MemoryStream(limit); + var copied = 0; + foreach (var (start, end, encoding) in replaced) + { + output.Write(body, copied, start - copied); + output.Write(placeholders[encoding]); + copied = end; + } + + output.Write(body, copied, limit - copied); + return output.ToArray(); + } + + /// + /// The encodings besides UTF-8 that a body may be in, so that the secrets echoed in it are found: UTF-16 or UTF-32 as + /// its byte order mark says, else as its charset says, in either byte order (without a mark, a "utf-16" body may be + /// either). None for other bodies. + /// + private static Encoding[] WideEncodings(byte[] body, string? contentType) + { + // The UTF-32 little-endian mark starts with the UTF-16 one: such a body is searched as both. + var marked = Utf32.Concat(Utf16).Where(encoding => body.AsSpan().StartsWith(encoding.Preamble)).ToArray(); + if (marked.Length > 0) + { + return marked; + } + + if (Http.BodyFormatter.GetCharset(contentType) is not { Length: > 0 } charset) + { + return []; + } + + try + { + return Encoding.GetEncoding(charset).CodePage switch + { + 1200 or 1201 => Utf16, + 12000 or 12001 => Utf32, + _ => [], + }; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException) + { + return []; // a charset .NET does not know (or support, like UTF-7) + } } // ----- JSON Lines ------------------------------------------------------------------------------ @@ -199,9 +568,20 @@ public JsonObject ToJson() ["url"] = Url, }; AddIfNotNull(obj, "collection", Collection); + AddIfNotNull(obj, "collectionFile", CollectionFile); AddIfNotNull(obj, "requestPath", RequestPath); AddIfNotNull(obj, "environment", Environment); obj["item"] = Item.DeepClone(); + if (CredentialsMasked) + { + obj["credentialsMasked"] = true; + } + + if (AuthInherited) + { + obj["authInherited"] = true; + } + obj["sentHeaders"] = WritePairs(SentHeaders); if (Status is { } status) { @@ -251,7 +631,10 @@ public static bool TryParse(string line, out HistoryEntry entry) Method = obj["method"].GetString() ?? "GET", Url = obj["url"].GetString() ?? "", Item = (JsonObject)item.DeepClone(), + CredentialsMasked = obj["credentialsMasked"].GetBool() == true, + AuthInherited = obj["authInherited"].GetBool() == true, Collection = obj["collection"].GetString(), + CollectionFile = obj["collectionFile"].GetString(), RequestPath = obj["requestPath"].GetString(), Environment = obj["environment"].GetString(), SentHeaders = ReadPairs(obj["sentHeaders"]), diff --git a/src/TermRest.Core/History/HistoryStore.cs b/src/TermRest.Core/History/HistoryStore.cs index cbf32c0..a15e3a0 100644 --- a/src/TermRest.Core/History/HistoryStore.cs +++ b/src/TermRest.Core/History/HistoryStore.cs @@ -8,13 +8,17 @@ namespace TermRest.Core.History; /// /// Request history for one workspace, stored per user outside the workspace folder (so it is never committed with /// the collections): history.jsonl (one entry per line, append-only, compacted to ) plus -/// bodies/<id>.bin with the raw response bodies. Files are private to the user on Unix (0600/0700). +/// bodies/<id>.bin with the raw response bodies; history.lock keeps processes from changing them at +/// the same time. Files are private to the user on Unix (0600/0700). /// public sealed class HistoryStore { public const string FileName = "history.jsonl"; public const string StateDirectoryVariable = "TERMREST_STATE_DIR"; + /// Held by a process while it changes the history (see ). + internal const string LockFileName = "history.lock"; + private const UnixFileMode PrivateFile = UnixFileMode.UserRead | UnixFileMode.UserWrite; private const UnixFileMode PrivateDirectory = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; @@ -97,6 +101,7 @@ public void Add(HistoryEntry entry, byte[]? body = null) lock (_gate) { EnsureFolder(); + using var locked = LockFiles(); if (body is not null && entry.BodySaved) { WritePrivateFile(BodyPath(entry.Id), body); @@ -109,8 +114,8 @@ public void Add(HistoryEntry entry, byte[]? body = null) stream.Write(line); }); - _lineCount = _lineCount is { } count ? count + 1 : ReadLines().Count; - if (_lineCount > MaxEntries + Math.Max(10, MaxEntries / 5)) + _lineCount = _lineCount is { } count ? count + 1 : CountLines(); + if (_lineCount > (long)MaxEntries + Math.Max(10, MaxEntries / 5)) { Compact(); } @@ -148,6 +153,12 @@ public bool Delete(string id) { lock (_gate) { + if (!Directory.Exists(Folder)) + { + return false; + } + + using var locked = LockFiles(); var lines = ReadLines(); var kept = lines.Where(line => HistoryEntry.ReadId(line) != id).ToList(); if (kept.Count == lines.Count) @@ -161,17 +172,38 @@ public bool Delete(string id) } } - public void Clear() + /// + /// Deletes all entries, then their bodies. Throws when the entries can't be deleted (another program has the history + /// file open), leaving everything as it was. Once they are gone, a body that can't be deleted (an antivirus scan has it + /// open) is left for the next Clear or compaction, and the reason returned; null when everything was deleted. + /// + public Exception? Clear() { lock (_gate) { - DeleteFile(FilePath); - if (Directory.Exists(BodiesFolder)) + Exception? bodiesLeft = null; + if (Directory.Exists(Folder)) { - Directory.Delete(BodiesFolder, recursive: true); + using var locked = LockFiles(); + Retry(() => File.Delete(FilePath)); + try + { + Retry(() => + { + if (Directory.Exists(BodiesFolder)) + { + Directory.Delete(BodiesFolder, recursive: true); + } + }); + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + bodiesLeft = e; + } } _lineCount = 0; + return bodiesLeft; } } @@ -179,6 +211,18 @@ public void Clear() private string BodyPath(string id) => Path.Combine(BodiesFolder, id + ".bin"); + /// + /// Locks the history against changes by other TermRest processes (the UI and termrest send write the same + /// history) until disposed, so that compacting or deleting never drops an entry, or deletes a body, that another + /// process has just added. Reading needs no lock: the file is only appended to or replaced as a whole. + /// + private FileStream LockFiles() + { + FileStream? stream = null; + Retry(() => stream = new FileStream(Path.Combine(Folder, LockFileName), CreateOptions(FileMode.OpenOrCreate, FileAccess.Write)), attempts: 200); + return stream!; + } + private void Compact() { var lines = ReadLines(); @@ -239,6 +283,31 @@ private List ReadLines() return lines; } + /// Lines in the history file, counted in pieces (not read into memory). + private int CountLines() + { + if (!File.Exists(FilePath)) + { + return 0; + } + + var count = 0; + Retry(() => + { + using var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + var buffer = new byte[64 * 1024]; + var lines = 0; + int read; + while ((read = stream.Read(buffer)) > 0) + { + lines += buffer.AsSpan(0, read).Count((byte)'\n'); + } + + count = lines; + }); + return count; + } + private void EnsureFolder() { if (Directory.Exists(Folder)) @@ -303,7 +372,7 @@ private static void DeleteFile(string path) } } - private static void Retry(Action action) + private static void Retry(Action action, int attempts = 20) { for (var attempt = 0; ; attempt++) { @@ -312,7 +381,7 @@ private static void Retry(Action action) action(); return; } - catch (IOException) when (attempt < 20) + catch (IOException) when (attempt < attempts) { Thread.Sleep(25); // another TermRest process is writing the same history } diff --git a/src/TermRest.Core/Http/BodyFile.cs b/src/TermRest.Core/Http/BodyFile.cs index 2364704..f0324a3 100644 --- a/src/TermRest.Core/Http/BodyFile.cs +++ b/src/TermRest.Core/Http/BodyFile.cs @@ -165,25 +165,66 @@ public static class BodyFile // No DTD processing and no resolver: entities and external references are never followed. var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, XmlResolver = null, CloseInput = false }; - try + for (var attempt = 0; ; attempt++) { - using var reader = XmlReader.Create(stream, settings); - for (var nodes = 1; reader.Read(); nodes++) + try { - if (nodes % 4096 == 0) + using var reader = XmlReader.Create(stream, settings); + for (var nodes = 1; reader.Read(); nodes++) { - cancellationToken.ThrowIfCancellationRequested(); + if (nodes % 4096 == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + } } + + return null; } + catch (XmlException ex) + { + if (attempt == 0 && ex.InnerException is ArgumentException or NotSupportedException && UseCodePages(stream)) + { + stream.Position = 0; // read again, now in the encoding the declaration names + continue; + } - return null; + var message = ex.Message; + var position = message.LastIndexOf(" Line ", StringComparison.Ordinal); + return $"{name} is not well-formed XML: {Describe(position > 0 ? message[..position] : message, ex.LineNumber > 0 ? ex.LineNumber : null, ex.LinePosition)}"; + } } - catch (XmlException ex) + } + + /// + /// Registers the legacy code pages when the XML declaration at the start of names one of them + /// (windows-1252, ISO-8859-15, Shift_JIS …): XmlReader looks the declared encoding up with + /// , which knows them only once they are registered. Only a file that needs + /// them registers them, for the rest of the run (see ). False when they would + /// not help. + /// + private static bool UseCodePages(FileStream stream) + { + string? declared; + try + { + // The declaration is ASCII in the encodings it can name here; a reader of text keeps the encoding it is given. + stream.Position = 0; + using var text = new StreamReader(stream, Encoding.Latin1, detectEncodingFromByteOrderMarks: false, bufferSize: 1024, leaveOpen: true); + using var reader = XmlReader.Create(text, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, XmlResolver = null }); + declared = reader.Read() && reader.NodeType == XmlNodeType.XmlDeclaration ? reader.GetAttribute("encoding") : null; + } + catch (XmlException) { - var message = ex.Message; - var position = message.LastIndexOf(" Line ", StringComparison.Ordinal); - return $"{name} is not well-formed XML: {Describe(position > 0 ? message[..position] : message, ex.LineNumber > 0 ? ex.LineNumber : null, ex.LinePosition)}"; + return false; } + + if (declared is null || CodePagesEncodingProvider.Instance.GetEncoding(declared) is null) + { + return false; + } + + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + return true; } /// Text, HTML and JavaScript: the start of the file must look like text (no UTF-16, no NUL bytes). diff --git a/src/TermRest.Core/Http/BodyFormatter.cs b/src/TermRest.Core/Http/BodyFormatter.cs index 8192e7f..023c804 100644 --- a/src/TermRest.Core/Http/BodyFormatter.cs +++ b/src/TermRest.Core/Http/BodyFormatter.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Globalization; using System.Text; using System.Xml; @@ -9,50 +10,148 @@ namespace TermRest.Core.Http; /// Turns response bytes into displayable text: charset decoding, JSON/XML pretty printing, hex dumps. public static class BodyFormatter { - public static bool IsJson(string? contentType) => - contentType is not null && (contentType.Contains("json", StringComparison.OrdinalIgnoreCase)); + /// What separates the words of a media subtype: "problem+json", "x-amz-json-1.1", "vnd.api+json". + private static readonly SearchValues WordSeparators = SearchValues.Create("+-."); - public static bool IsXml(string? contentType) => - contentType is not null && (contentType.Contains("xml", StringComparison.OrdinalIgnoreCase)); + /// + /// Whether a Content-Type names JSON: a word of its subtype is json (application/json, application/problem+json, + /// application/json-seq, application/x-amz-json-1.1), or it names NDJSON or JSON Lines. + /// + public static bool IsJson(string? contentType) => SubtypeHasWord(contentType, "json", "ndjson", "jsonl", "jsonlines"); - public static bool IsHtml(string? contentType) => - contentType is not null && contentType.Contains("html", StringComparison.OrdinalIgnoreCase); + /// + /// Whether a Content-Type names XML: a word of its subtype is xml (application/xml, image/svg+xml, application/atom+xml). + /// Not an Office document (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet …), which is a ZIP file. + /// + public static bool IsXml(string? contentType) => SubtypeHasWord(contentType, "xml"); + + public static bool IsHtml(string? contentType) => SubtypeHasWord(contentType, "html", "xhtml"); /// A short language label for the body (json, xml, html, text, binary). public static string Language(byte[] body, string? contentType) => IsJson(contentType) ? "json" : IsHtml(contentType) ? "html" : IsXml(contentType) ? "xml" : LooksLikeText(body, contentType) ? "text" : "binary"; - public static bool LooksLikeText(byte[] body, string? contentType) + /// Whether a body is shown as text: its Content-Type declares text, or no NUL byte is near its start. + public static bool LooksLikeText(byte[] body, string? contentType) => IsTextType(contentType) || !HasNulNearStart(body); + + /// + /// Whether a body is binary, to be passed on as the bytes received: its Content-Type declares a type that is not text + /// (application/octet-stream, image/png, application/x-protobuf …), or it declares none and a NUL byte is near its + /// start. Unlike , which decides how a body is shown, it takes a declared type at its word: + /// binary data need not have a NUL byte. + /// + public static bool IsBinary(byte[] body, string? contentType) => + !IsTextType(contentType) && (!string.IsNullOrWhiteSpace(contentType) || HasNulNearStart(body)); + + /// + /// Whether a Content-Type declares text: text/*, JSON, XML, JavaScript or form data. An Excel or Word file, whose type + /// names the XML formats inside it, is binary. + /// + private static bool IsTextType(string? contentType) => + MediaType(contentType).StartsWith("text/", StringComparison.OrdinalIgnoreCase) || IsJson(contentType) || IsXml(contentType) + || SubtypeHasWord(contentType, "javascript") || Subtype(contentType).Equals("x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase); + + /// The media type of a Content-Type, without its parameters: "application/json" in "application/json; charset=utf-8". + private static ReadOnlySpan MediaType(string? contentType) + { + var value = contentType.AsSpan(); + var semicolon = value.IndexOf(';'); + return (semicolon < 0 ? value : value[..semicolon]).Trim(); + } + + /// The subtype of a Content-Type's media type: "problem+json" in "application/problem+json; charset=utf-8". + private static ReadOnlySpan Subtype(string? contentType) { - if (contentType is not null && (contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) || IsJson(contentType) - || IsXml(contentType) || contentType.Contains("javascript", StringComparison.OrdinalIgnoreCase) - || contentType.Contains("x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))) + var media = MediaType(contentType); + var slash = media.IndexOf('/'); + return slash < 0 ? [] : media[(slash + 1)..]; + } + + /// + /// Whether one of the words of a Content-Type's subtype, between '+', '-' and '.', is one of : + /// a word that only contains one (openxmlformats, spreadsheetml, ubjson) names another format. + /// + internal static bool SubtypeHasWord(string? contentType, params ReadOnlySpan words) + { + var subtype = Subtype(contentType); + foreach (var range in subtype.SplitAny(WordSeparators)) { - return true; + foreach (var word in words) + { + if (subtype[range].Equals(word, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } } - var sample = body.AsSpan(0, Math.Min(body.Length, 8192)); - return !sample.Contains((byte)0); + return false; } + private static bool HasNulNearStart(byte[] body) => body.AsSpan(0, Math.Min(body.Length, 8192)).Contains((byte)0); + + /// The body as text in the charset its Content-Type names (see ), else in UTF-8. public static string Decode(byte[] body, string? contentType) { - var encoding = Encoding.UTF8; - var charset = GetCharset(contentType); - if (charset is not null) + var encoding = GetCharset(contentType) is { } charset ? GetEncoding(charset) ?? Encoding.UTF8 : Encoding.UTF8; + var text = InByteOrder(encoding, body).GetString(body); + return text.Length > 0 && text[0] == '\uFEFF' ? text[1..] : text; + } + + /// + /// A UTF-16 encoding in the byte order is written in: the one its byte order mark says, else the + /// one its text shows (an ASCII character's zero byte comes first in big-endian, last in little-endian), as RFC 2781 lets + /// an unmarked "UTF-16" be either. Any other encoding, and a body that shows neither, as it is. + /// + internal static Encoding InByteOrder(Encoding encoding, ReadOnlySpan body) + { + if (encoding.CodePage is not (1200 or 1201)) { - try + return encoding; + } + + if (body.StartsWith(Encoding.Unicode.Preamble) || body.StartsWith(Encoding.BigEndianUnicode.Preamble)) + { + return body[0] == 0xFF ? Encoding.Unicode : Encoding.BigEndianUnicode; + } + + var (zeroFirst, zeroLast) = (0, 0); + var sample = body[..(Math.Min(body.Length, 4096) & ~1)]; + for (var i = 0; i < sample.Length; i += 2) + { + if (sample[i] == 0 && sample[i + 1] != 0) { - encoding = Encoding.GetEncoding(charset); + zeroFirst++; } - catch (ArgumentException) + else if (sample[i] != 0 && sample[i + 1] == 0) { - encoding = Encoding.UTF8; + zeroLast++; } } - var text = encoding.GetString(body); - return text.Length > 0 && text[0] == '\uFEFF' ? text[1..] : text; + return zeroFirst > zeroLast * 4 ? Encoding.BigEndianUnicode : zeroLast > zeroFirst * 4 ? Encoding.Unicode : encoding; + } + + /// + /// The encoding a charset names: one built into .NET (UTF-8, UTF-16, ISO-8859-1 …), else a legacy code page + /// (windows-1252, Shift_JIS, GBK …). The code pages are not registered for the whole application (unless an XML body + /// file declares one, see ), which would cost memory in every run: only a body in one of them + /// loads its table. Null for a charset this platform does not know, or does not support (UTF-7). + /// + internal static Encoding? GetEncoding(string charset) + { + try + { + return Encoding.GetEncoding(charset); + } + catch (ArgumentException) + { + return CodePagesEncodingProvider.Instance.GetEncoding(charset); + } + catch (NotSupportedException) + { + return null; + } } /// Pretty text for display; falls back to raw text, then to a hex dump for binary content. @@ -84,7 +183,10 @@ public static string Format(byte[] body, string? contentType, bool pretty = true { try { - return XDocument.Parse(text, LoadOptions.None).ToString(); + // A document type is not processed (its entities could expand a few hundred bytes into millions of + // characters, on the UI thread): such a body is shown as received. + using var reader = XmlReader.Create(new StringReader(text), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, IgnoreWhitespace = true }); + return XDocument.Load(reader, LoadOptions.None).ToString(); } catch (XmlException) { @@ -125,7 +227,8 @@ public static string HexDump(byte[] body, int maxBytes = 4096) return builder.ToString(); } - private static string? GetCharset(string? contentType) + /// The charset a Content-Type names, read leniently (as servers write it: with a trailing ";", say); null for none. + internal static string? GetCharset(string? contentType) { if (contentType is null) { diff --git a/src/TermRest.Core/Http/CurlExporter.cs b/src/TermRest.Core/Http/CurlExporter.cs index 445df40..a67f0ee 100644 --- a/src/TermRest.Core/Http/CurlExporter.cs +++ b/src/TermRest.Core/Http/CurlExporter.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Text; using TermRest.Core.Certificates; @@ -6,41 +7,119 @@ namespace TermRest.Core.Http; /// Renders a prepared request as a POSIX-shell cURL command. public static class CurlExporter { + /// What ends a form-data part's content type for curl before its first ';'. + private static readonly SearchValues TypeEnds = SearchValues.Create("()<>@,:\\\"[]?= "); + + /// + /// curl cannot send the request as TermRest does (a HEAD request with a body; a form-data field whose name has an '=', + /// or whose content type curl would cut short or read in part as a setting of its own); the message says why. + /// public static string Export(PreparedRequest request, bool multiline = true) { + var body = request.Body; + + // Whether options send a body: curl then sends POST unless the method is named. A HEAD request goes without an + // empty one, as --head allows none and curl would wait for a response body after -X HEAD. + var data = body.Kind switch + { + PreparedBodyKind.Text => request.Method != "HEAD" || !string.IsNullOrEmpty(body.Text), + PreparedBodyKind.FormUrlEncoded => body.Fields.Count > 0, + PreparedBodyKind.Multipart => body.Parts.Count > 0, + PreparedBodyKind.File => true, + _ => false, + }; + if (request.Method == "HEAD" && data) + { + throw new NotSupportedException("A HEAD request with a body cannot be sent with curl: --head sends no body, and after -X HEAD curl waits for a response body that never comes."); + } + + // Without a body, .NET still sends Content-Length: 0 unless the method is GET, HEAD, DELETE, OPTIONS or CONNECT, and + // some servers refuse a POST without one (411 Length Required). curl sends none without data: it gets empty data, + // without the type curl would label it with. + var empty = !data && request.Method is not ("GET" or "HEAD" or "DELETE" or "OPTIONS" or "CONNECT"); + data |= empty; + var parts = new List { "curl" }; - if (request.Method != "GET") + if (request.Method == "HEAD") + { + parts.Add("--head"); + } + else if (request.Method != (data ? "POST" : "GET")) + { + // Not for a POST, which curl sends anyway for its data: after -X POST, curl would also POST to the URL a 301, 302 + // or 303 leads to, where TermRest sends a GET without the body (as curl does otherwise). + // Invalid methods are refused only when sent: one such as "GET;calc" must reach the shell quoted. + var method = request.Method.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.') ? request.Method : Quote(request.Method); + parts.Add($"-X {method}"); + } + + // The URL as TermRest sends it: encoded by System.Uri (curl refuses one with a space), the host name in ASCII (punycode). + var url = request.Uri is not { } uri ? request.Url + : uri.HostNameType == UriHostNameType.Dns && uri.IdnHost != uri.Host ? new UriBuilder(uri) { Host = uri.IdnHost }.Uri.AbsoluteUri + : uri.AbsoluteUri; + + // curl would expand [1-9] and {a,b} in the URL into several requests; TermRest sends it as it is. + if (url.AsSpan().IndexOfAny("[]{}") >= 0) { - parts.Add(request.Method == "HEAD" ? "--head" : $"-X {request.Method}"); + parts.Add("--globoff"); } - parts.Add(Quote(request.Url)); + parts.Add(Quote(url)); foreach (var (key, value) in request.Headers) { - parts.Add($"-H {Quote($"{key}: {value}")}"); + // Left out as TermRest leaves them out: Content-Length, which it computes from the body, and on a request without + // a body the headers that would describe one. + if (key.Equals("Content-Length", StringComparison.OrdinalIgnoreCase) + || (body.Kind == PreparedBodyKind.None && (HttpExecutor.IsContentHeader(key) || key.Equals("Transfer-Encoding", StringComparison.OrdinalIgnoreCase)))) + { + continue; + } + + // curl would leave out a header without a value; written 'Name;', it is sent empty. + parts.Add($"-H {Quote(value.AsSpan().Trim(" \t").IsEmpty ? key + ";" : $"{key}: {value}")}"); } - switch (request.Body.Kind) + switch (body.Kind) { case PreparedBodyKind.Text: - parts.Add($"--data-raw {Quote(request.Body.Text ?? "")}"); - if (request.GetHeader("Content-Type") is null && request.Body.ContentType is { } contentType) + if (data) + { + parts.Add($"--data-raw {Quote(body.Text ?? "")}"); + } + + if (request.GetHeader("Content-Type") is null && body.ContentType is { } contentType) { parts.Add($"-H {Quote($"Content-Type: {contentType}")}"); } break; case PreparedBodyKind.FormUrlEncoded: - parts.AddRange(request.Body.Fields.Select(f => $"--data-urlencode {Quote($"{f.Key}={f.Value}")}")); + parts.AddRange(body.Fields.Select(f => $"--data-urlencode {Quote($"{f.Key}={f.Value}")}")); break; case PreparedBodyKind.Multipart: - parts.AddRange(request.Body.Parts.Select(p => p.FilePath is null ? $"-F {Quote($"{p.Name}={p.Value}")}" : $"-F {Quote($"{p.Name}=@{p.FilePath}")}")); + // curl ends the name at the first '=': the rest would be the value, a file to read if it starts with @ or <. + if (body.Parts.FirstOrDefault(p => p.Name.Contains('=', StringComparison.Ordinal)) is { } part) + { + throw new NotSupportedException($"The form-data field '{part.Name}' cannot be sent with curl, which ends a field's name at the first '='."); + } + + // Text goes as it is: with --form-string, or "quoted" with -F to give it a type (-F reads a file for a value that + // starts with @ or <, but not in quotes). A file's path is quoted for curl, which would take a ';' in it for a + // parameter and a ',' for a list of files, and its type is named: curl knows the types of fewer extensions. + foreach (var p in body.Parts) + { + var type = PartType(p); + parts.Add(p.FilePath is not null ? $"-F {Quote($"{p.Name}=@{FormQuote(p.FilePath)};type={type}")}" + : type is null ? $"--form-string {Quote($"{p.Name}={p.Value}")}" + : $"-F {Quote($"{p.Name}={FormQuote(p.Value ?? "")};type={type}")}"); + } + break; case PreparedBodyKind.File: - parts.Add($"--data-binary {Quote("@" + request.Body.FilePath)}"); + parts.Add($"--data-binary {Quote("@" + body.FilePath)}"); // curl would label the file application/x-www-form-urlencoded: name the type TermRest sends. - if (request.GetHeader("Content-Type") is null && request.Body.ContentType is { } fileType) + if (request.GetHeader("Content-Type") is null && body.ContentType is { } fileType) { parts.Add($"-H {Quote($"Content-Type: {fileType}")}"); } @@ -48,6 +127,11 @@ public static string Export(PreparedRequest request, bool multiline = true) break; } + if (empty) + { + parts.Add("--data-raw '' -H 'Content-Type:'"); + } + if (!request.StrictSsl) { parts.Add("--insecure"); @@ -55,38 +139,111 @@ public static string Export(PreparedRequest request, bool multiline = true) if (request.Credential is { } credential) { - parts.Add($"--anyauth -u {Quote($"{(string.IsNullOrEmpty(credential.Domain) ? "" : credential.Domain + "\\")}{credential.UserName}:{credential.Password}")}"); + // Only the scheme the auth helper uses: --anyauth would also let curl send the password with Basic. + var scheme = request.CredentialSchemes.Contains("Digest") ? "--digest" : request.CredentialSchemes.Contains("NTLM") ? "--ntlm" : "--anyauth"; + parts.Add($"{scheme} -u {Quote($"{(string.IsNullOrEmpty(credential.Domain) ? "" : credential.Domain + "\\")}{credential.UserName}:{credential.Password}")}"); } + var notes = ""; + var certificateFile = false; if (request.ClientCertificate is { } selection) { var entry = selection.Entry; switch (entry.Kind) { case CertificateSourceKind.Pem when entry.Cert is not null: - parts.Add($"--cert {Quote(entry.Cert.Src)}"); + // Full paths: relative ones are relative to the workspace (or the collection), not to curl's folder. + parts.Add($"--cert {Quote(selection.ResolvePath(entry.Cert.Src))}"); if (entry.Key is not null) { - parts.Add($"--key {Quote(entry.Key.Src)}"); + parts.Add($"--key {Quote(selection.ResolvePath(entry.Key.Src))}"); } + certificateFile = true; break; case CertificateSourceKind.Pfx: - parts.Add($"--cert-type P12 --cert {Quote(entry.Pfx!.Src)}"); + parts.Add($"--cert-type P12 --cert {Quote(selection.ResolvePath(entry.Pfx!.Src))}"); + certificateFile = true; break; default: - parts.Add($"# client certificate from OS store: {selection.Summary.Subject} ({selection.Summary.Thumbprint})"); + notes += $"# client certificate from OS store: {QuoteInNote(selection.Summary.Subject)} ({selection.Summary.Thumbprint})\n"; break; } } - if (!request.FollowRedirects) + // TermRest follows no redirect when following is off or its limit is 0. + if (request.FollowRedirects && request.MaxRedirects > 0) + { + // TermRest sends the auth helper's headers (an API key …) and Proxy-Authorization only to the request's own + // origin; curl withholds only Authorization and Cookie (and Host) from other hosts it is redirected to. And + // TermRest selects the client certificate for each URL a redirect leads to, where curl presents the one it is + // given on every connection. + var forwarded = request.Headers.Select(h => h.Key) + .Where(k => (request.AuthHeaderNames.Contains(k) || k.Equals("Proxy-Authorization", StringComparison.OrdinalIgnoreCase)) + && k.ToLowerInvariant() is not ("authorization" or "cookie" or "host")) + .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + List withheld = forwarded.Count > 0 ? [$"send {string.Join(", ", forwarded.Select(QuoteInNote))}"] : []; + if (certificateFile) + { + withheld.Add("present the client certificate"); + } + + if (withheld.Count > 0) + { + notes += $"# redirects are not followed: curl would {string.Join(" and ", withheld)} to every host it is redirected to\n"; + } + else + { + // TermRest's limit (curl's is 50), and from an https URL only to https: TermRest never follows a redirect from + // https to http. Where TermRest stops and shows the redirect, curl ends with an error. From an http URL, curl + // also follows one to ftp, or back to http after https, which TermRest doesn't. '=https' is quoted for zsh, + // which would replace it with the path of a command named https. + var follow = $"--location --max-redirs {request.MaxRedirects}"; + if (request.Uri?.Scheme == Uri.UriSchemeHttps) + { + follow += $" --proto-redir {Quote("=https")}"; + } + + // TermRest resends any method but POST with its body after a 301 or 302, and a GET also after a 303. Still + // different: after a 303, curl keeps any other method (without the body) where TermRest sends GET; a POST + // stays a POST in curl after a 300; and without the body, curl still sends the headers given with -H that + // describe it (Content-Type). + if (data && request.Method != "POST") + { + follow += request.Method == "GET" ? " --post301 --post302 --post303" : " --post301 --post302"; + } + + parts.Add(follow); + } + } + + return notes + Join(parts, multiline); + } + + /// + /// The content type TermRest sends a form-data part with (see ), for -F's + /// ;type=; null for text without one. + /// + private static string? PartType(MultipartPart part) + { + if (part.SentContentType is not { } type) + { + return null; + } + + // curl sends the rest of the value as the type, but ends it at a space or a special character such as '=' or '(' + // before its first ';', reads a filename=, headers= (headers=@file reads a file) or encoder= after a ';' as a setting + // of its own and, after a file, a ',' as the start of another file to send. + var parameters = type.Split(';'); + if (parameters[0].AsSpan().IndexOfAny(TypeEnds) >= 0 || type.AsSpan().IndexOfAny('\r', '\n') >= 0 + || (part.FilePath is not null && type.Contains(',', StringComparison.Ordinal)) + || parameters.Skip(1).Select(p => p.TrimStart(' ', '\t')).Any(p => p.StartsWith("filename=", StringComparison.OrdinalIgnoreCase) + || p.StartsWith("headers=", StringComparison.OrdinalIgnoreCase) || p.StartsWith("encoder=", StringComparison.OrdinalIgnoreCase))) { - return Join(parts, multiline); + throw new NotSupportedException($"The form-data field '{part.Name}' cannot be sent with curl, which would send only part of its content type '{type}', or read part of it as a setting of its own or as another file."); } - parts.Add("--location"); - return Join(parts, multiline); + return type; } private static string Join(List parts, bool multiline) @@ -106,4 +263,14 @@ private static string Join(List parts, bool multiline) } private static string Quote(string value) => "'" + value.Replace("'", "'\\''", StringComparison.Ordinal) + "'"; + + /// + /// A value in a note: on a line of its own above the command (inside it, the comment would swallow the line + /// continuation), and quoted for zsh, where '#' starts no comment at the prompt. + /// + private static string QuoteInNote(string value) => Quote(new string(value.Select(c => char.IsControl(c) ? ' ' : c).ToArray())); + + /// Quotes a -F value or file name for curl, which takes it literally between the quotes (\ and " escaped). + private static string FormQuote(string value) => + "\"" + value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal) + "\""; } diff --git a/src/TermRest.Core/Http/HttpExchange.cs b/src/TermRest.Core/Http/HttpExchange.cs index 46404b9..9aeaf0e 100644 --- a/src/TermRest.Core/Http/HttpExchange.cs +++ b/src/TermRest.Core/Http/HttpExchange.cs @@ -26,10 +26,13 @@ public sealed class HttpExchange(PreparedRequest request) public List Tls { get; } = []; - /// Request headers as sent (including generated ones such as User-Agent and Cookie). + /// Request headers as sent (including generated ones such as User-Agent, Accept-Encoding and Cookie). public List> SentHeaders { get; } = []; - /// The history entry recorded for this exchange, if history is on. + /// + /// The history entry recorded for this exchange, if history is on; for an exchange rebuilt from the history (see + /// ), that entry. + /// public History.HistoryEntry? HistoryEntry { get; set; } /// What the scripts around this request did (tests, output, variables set); null when it has none. @@ -74,10 +77,15 @@ public sealed class ResponseSnapshot public Version Version { get; init; } = HttpVersion.Version11; + /// The headers as the server sent them (Content-Encoding and Content-Length describe the body as received). public List> Headers { get; init; } = []; + /// The body, decoded as its Content-Encoding says (gzip, deflate, br); as received when it could not be. public byte[] Body { get; init; } = []; + /// Size of the body as received, before it was decoded; null when not known (a response from the history). + public long? ReceivedBodySize { get; init; } + public bool BodyTruncated { get; init; } public string? ContentType { get; init; } diff --git a/src/TermRest.Core/Http/HttpExecutor.cs b/src/TermRest.Core/Http/HttpExecutor.cs index cf3f3fc..caeb4f3 100644 --- a/src/TermRest.Core/Http/HttpExecutor.cs +++ b/src/TermRest.Core/Http/HttpExecutor.cs @@ -1,5 +1,7 @@ using System.Buffers; +using System.Buffers.Binary; using System.Diagnostics; +using System.IO.Compression; using System.Net; using System.Net.Http.Headers; using System.Net.Security; @@ -7,6 +9,7 @@ using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; +using System.Text; using TermRest.Core.Certificates; namespace TermRest.Core.Http; @@ -67,20 +70,76 @@ public async Task SendAsync(PreparedRequest request, CancellationT } var clock = Stopwatch.StartNew(); - var capture = new ConnectionCapture(clock); + var target = request.Uri; + var capture = new ConnectionCapture(clock, target, request.ClientCertificate); + var captures = new List { capture }; + var clients = new List(); using var timeoutSource = request.Timeout is { } timeout && timeout > TimeSpan.Zero ? new CancellationTokenSource(timeout) : null; using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutSource?.Token ?? CancellationToken.None); TimeSpan? headersAt = null; - SocketsHttpHandler? handler = null; + HttpRequestMessage? message = null; + HttpResponseMessage? response = null; try { - handler = CreateHandler(request, capture); - using var client = new HttpClient(handler, disposeHandler: false) { Timeout = System.Threading.Timeout.InfiniteTimeSpan }; - using var message = CreateMessage(request, exchange); - using var response = await client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, linked.Token).ConfigureAwait(false); + // Redirects are followed here rather than by the handler: credentials only go to the request's own origin, + // and each URL gets the client certificate selected for it, on a handler of its own. + var credentials = CreateCredentials(request); + var method = request.Method; + var withBody = true; + HttpClient? client = null; + message = CreateMessage(request, target, method, withBody, exchange); + for (var redirects = 0; ; redirects++) + { + if (client is null) + { + client = new HttpClient(CreateHandler(request, capture, credentials)) { Timeout = System.Threading.Timeout.InfiniteTimeSpan }; + clients.Add(client); + } + + response = await client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, linked.Token).ConfigureAwait(false); + if (GetRedirectTarget(request, response, target, redirects) is not { } next) + { + break; + } + + // As browsers and .NET do: 301 and 302 turn a POST into a GET, 303 anything but GET and HEAD; without the body. + var status = (int)response.StatusCode; + if ((status is 300 or 301 or 302 && method == "POST") || (status == 303 && method is not ("GET" or "HEAD"))) + { + (method, withBody) = ("GET", false); + } + + HttpRequestMessage nextMessage; + try + { + nextMessage = CreateMessage(request, next, method, withBody, exchange: null); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + request.Warnings.Add($"The redirect to {next.AbsoluteUri} was not followed: the body could not be read again ({ex.Message})."); + break; + } + + response.Dispose(); + message.Dispose(); + (message, response, target) = (nextMessage, null, next); + var certificate = SelectClientCertificate(request, next); + if (!capture.Serves(next, certificate)) + { + capture = new ConnectionCapture(clock, next, certificate); + captures.Add(capture); + client = null; + } + } + headersAt = clock.Elapsed; - var (body, truncated) = await ReadBodyAsync(response, request.MaxResponseBytes, linked.Token).ConfigureAwait(false); - exchange.Response = Snapshot(response, body, truncated); + 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)}."); @@ -101,59 +160,73 @@ public async Task SendAsync(PreparedRequest request, CancellationT exchange.Exception = ex; exchange.ErrorMessage = ex.InnerException is TimeoutException ? capture.IsConnected - ? $"The TLS handshake with {request.Uri.Authority} did not complete within {HttpExchange.Format(ConnectTimeout)}." - : $"Could not connect to {request.Uri.Authority} within {HttpExchange.Format(ConnectTimeout)}." - : DescribeError(ex, capture); + ? $"The TLS handshake with {target.Authority} did not complete within {HttpExchange.Format(ConnectTimeout)}." + : $"Could not connect to {target.Authority} within {HttpExchange.Format(ConnectTimeout)}." + : DescribeError(ex, capture, target); } catch (Exception ex) when (ex is HttpRequestException or IOException or AuthenticationException or SocketException or InvalidOperationException or NotSupportedException or UnauthorizedAccessException - or FormatException or ArgumentException or CryptographicException) + or FormatException or ArgumentException or CryptographicException or InvalidDataException) { exchange.Exception = ex; - exchange.ErrorMessage = DescribeError(ex, capture); + exchange.ErrorMessage = DescribeError(ex, capture, target); } finally { - exchange.Timing = capture.BuildTiming(headersAt, clock.Elapsed); - exchange.Tls.AddRange(capture.CollectTls(request)); + response?.Dispose(); + message?.Dispose(); + exchange.Timing = captures[0].BuildTiming(headersAt, clock.Elapsed); + foreach (var hop in captures) + { + exchange.Tls.AddRange(hop.CollectTls()); + } - // Disposed last: closing the connections first would hide the TLS details read above. - handler?.Dispose(); + // Disposed last (with their handlers): closing the connections first would hide the TLS details read above. + foreach (var client in clients) + { + client.Dispose(); + } } return exchange; } - private SocketsHttpHandler CreateHandler(PreparedRequest request, ConnectionCapture capture) + private SocketsHttpHandler CreateHandler(PreparedRequest request, ConnectionCapture capture, ICredentials? credentials) { var connectTimeout = ConnectTimeout; var handler = new SocketsHttpHandler { - AllowAutoRedirect = request.FollowRedirects, - MaxAutomaticRedirections = Math.Max(1, request.MaxRedirects), - AutomaticDecompression = DecompressionMethods.All, + AllowAutoRedirect = false, // followed in SendAsync + + // Decoded in ReadBodyAsync: .NET would drop Content-Encoding and Content-Length from the response, and add its + // codings to an Accept-Encoding typed in the request. + AutomaticDecompression = DecompressionMethods.None, UseCookies = request.UseCookies, CookieContainer = Cookies, ConnectTimeout = connectTimeout, - Credentials = request.Credential, + Credentials = credentials, ConnectCallback = capture.ConnectAsync, + PlaintextStreamFilter = capture.RecordSession, + + RequestHeaderEncodingSelector = HeaderEncoding, }; switch (request.Proxy?.Trim().ToLowerInvariant()) { case null or "" or "system": handler.UseProxy = true; + capture.Proxy = HttpClient.DefaultProxy; // the one the handler uses break; case "none": handler.UseProxy = false; break; default: handler.UseProxy = true; - handler.Proxy = new WebProxy(request.Proxy!.Trim()); + handler.Proxy = capture.Proxy = new WebProxy(request.Proxy!.Trim()); break; } - var selection = request.ClientCertificate; + var selection = capture.Selection; var options = new SslClientAuthenticationOptions { RemoteCertificateValidationCallback = (sender, certificate, chain, errors) => capture.Validate(sender, certificate, chain, errors, request), @@ -163,62 +236,99 @@ private SocketsHttpHandler CreateHandler(PreparedRequest request, ConnectionCapt AllowTlsResume = false, }; - if (selection is not null && selection.Certificate.Chain.Count > 0) + if (selection is not null && selection.Certificate.Chain.Count > 0 && !OperatingSystem.IsWindows()) { // An explicit context also sends the intermediates loaded with the certificate. options.ClientCertificateContext = SslStreamCertificateContext.Create( selection.Certificate.Certificate, selection.Certificate.Chain, offline: true); - capture.RecordContextCertificate(selection); + capture.RecordContextCertificate(); } else { + // Windows gets no context: there .NET (up to at least 10.0.15, dotnet/runtime#131992) can cache the credential + // of a connection given one, which holds its certificate, as the process-wide credential of connections + // WITHOUT a certificate. Every later request without one would then present that certificate to any server + // that asks, and this callback would not even be asked. + if (selection is not null && selection.Certificate.Chain.Count > 0) + { + AddChainToWindowsStores(selection.Certificate); + } + // Always answer the selection explicitly: the configured certificate regardless of the server's list of - // acceptable issuers (like curl/Postman), or none at all. Without a callback the platform may fall back to - // a credential cached from an earlier connection to the same host. + // acceptable issuers (like curl/Postman), or none at all. options.LocalCertificateSelectionCallback = (_, _, _, remoteCertificate, acceptableIssuers) => - capture.SelectClientCertificate(selection, remoteCertificate, acceptableIssuers)!; + capture.SelectClientCertificate(remoteCertificate, acceptableIssuers)!; } handler.SslOptions = options; return handler; } - private HttpRequestMessage CreateMessage(PreparedRequest request, HttpExchange exchange) + /// + /// 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 + /// Windows; the context itself is not used. + /// + private static void AddChainToWindowsStores(LoadedCertificate certificate) { - var message = new HttpRequestMessage(new HttpMethod(request.Method), request.Uri) + var context = SslStreamCertificateContext.Create(certificate.Certificate, certificate.Chain, offline: true); + foreach (var copy in context.IntermediateCertificates) + { + copy.Dispose(); + } + } + + /// Records the headers sent and warns about headers left out; null for a redirect. + private HttpRequestMessage CreateMessage(PreparedRequest request, Uri target, string method, bool withBody, HttpExchange? exchange) + { + var message = new HttpRequestMessage(new HttpMethod(method), target) { Version = request.HttpVersion == "2" ? HttpVersion.Version20 : HttpVersion.Version11, VersionPolicy = HttpVersionPolicy.RequestVersionOrLower, }; - var content = request.Body.CreateContent(); + var content = withBody ? request.Body.CreateContent() : null; message.Content = content; + var otherOrigin = !IsSameOrigin(target, request.Uri!); var hasUserAgent = false; var hasAccept = false; + var hasAcceptEncoding = false; foreach (var (key, value) in request.Headers) { hasUserAgent |= key.Equals("User-Agent", StringComparison.OrdinalIgnoreCase); hasAccept |= key.Equals("Accept", StringComparison.OrdinalIgnoreCase); + hasAcceptEncoding |= key.Equals("Accept-Encoding", StringComparison.OrdinalIgnoreCase); if (key.Equals("Content-Length", StringComparison.OrdinalIgnoreCase)) { continue; // always computed from the body } - if (IsContentHeader(key)) + if (otherOrigin && IsOriginBound(request, key)) + { + continue; + } + + if (IsContentHeader(key) || (content is null && key.Equals("Transfer-Encoding", StringComparison.OrdinalIgnoreCase))) { + // Without a body there is nothing to describe, nor to send in chunks (.NET refuses chunked encoding + // without content). if (content is null) { - request.Warnings.Add($"'{key}' was not sent because the request has no body."); + if (exchange is not null) + { + request.Warnings.Add($"'{key}' was not sent because the request has no body."); + } + continue; } content.Headers.Remove(key); - if (!content.Headers.TryAddWithoutValidation(key, value)) + if (!content.Headers.TryAddWithoutValidation(key, value) && exchange is not null) { request.Warnings.Add($"Header '{key}' has an invalid value and was skipped."); } } - else if (!message.Headers.TryAddWithoutValidation(key, value)) + else if (!message.Headers.TryAddWithoutValidation(key, value) && exchange is not null) { request.Warnings.Add($"Header '{key}' is not valid and was skipped."); } @@ -234,6 +344,17 @@ private HttpRequestMessage CreateMessage(PreparedRequest request, HttpExchange e message.Headers.TryAddWithoutValidation("Accept", "*/*"); } + if (!hasAcceptEncoding) + { + // A typed one (identity …) is sent as it is: ReadBodyAsync decodes whatever comes back. + message.Headers.TryAddWithoutValidation("Accept-Encoding", DecodedCodings); + } + + if (exchange is null) + { + return message; + } + foreach (var header in message.Headers.NonValidated) { foreach (var value in header.Value) @@ -261,31 +382,205 @@ private HttpRequestMessage CreateMessage(PreparedRequest request, HttpExchange e return message; } - private static bool IsContentHeader(string name) => name.ToLowerInvariant() switch + /// Headers that describe a body (sent with it, not on their own); the cURL export follows the same rule. + internal static bool IsContentHeader(string name) => name.ToLowerInvariant() switch { "content-type" or "content-encoding" or "content-language" or "content-location" or "content-md5" or "content-range" or "content-disposition" or "expires" or "last-modified" or "allow" => true, _ => false, }; - private static async Task<(byte[] Body, bool Truncated)> ReadBodyAsync(HttpResponseMessage response, long maxBytes, CancellationToken cancellationToken) + /// + /// Headers sent only to the request's own origin, as with curl -L: credentials (including cookies typed in and the + /// auth helper's headers, such as an API key) and Host. Other headers follow redirects. + /// + private static bool IsOriginBound(PreparedRequest request, string name) => + name.ToLowerInvariant() is "authorization" or "proxy-authorization" or "cookie" or "host" || request.AuthHeaderNames.Contains(name); + + private static bool IsSameOrigin(Uri a, Uri b) => + a.Scheme == b.Scheme && a.Port == b.Port && string.Equals(a.IdnHost, b.IdnHost, StringComparison.OrdinalIgnoreCase); + + /// + /// The auth helper's challenge credentials, for the request's own origin and the helper's schemes only: neither a + /// Basic challenge nor another origin gets the password. + /// + private static CredentialCache? CreateCredentials(PreparedRequest request) + { + if (request.Credential is not { } credential) + { + return null; + } + + var credentials = new CredentialCache(); + var origin = new Uri(request.Uri!, "/"); + foreach (var scheme in request.CredentialSchemes) + { + credentials.Add(origin, scheme, credential); + } + + return credentials; + } + + /// + /// Where a response redirects to, if TermRest follows it (never from https to http, as .NET); otherwise null. An http(s) + /// target has no user info: credentials in the request's URL are sent as an Authorization header, to its own origin + /// only (see ), and .NET sends none from a URL. A relative target would otherwise take them + /// from the request's URL, and show its password where the redirect is reported, kept in the history or recorded. + /// + private static Uri? GetRedirectTarget(PreparedRequest request, HttpResponseMessage response, Uri from, int redirects) + { + if (!request.FollowRedirects || (int)response.StatusCode is not (300 or 301 or 302 or 303 or 307 or 308) + || response.Headers.Location is not { } location) + { + return null; + } + + var target = WithoutUserInfo(location.IsAbsoluteUri ? location : new Uri(from, location)); + var refusal = target.Scheme != Uri.UriSchemeHttp && target.Scheme != Uri.UriSchemeHttps ? "TermRest follows only http and https URLs" + : from.Scheme == Uri.UriSchemeHttps && target.Scheme == Uri.UriSchemeHttp ? "it leads from https to http" + : redirects >= request.MaxRedirects ? $"it would exceed the maximum number of redirects ({request.MaxRedirects})" + : null; + if (refusal is null) + { + return target; + } + + // As it is sent (ToString() would unescape part of a value, which recordings then would not find to redact), its + // password masked: a URL that is not http(s) keeps its user info (see WithoutUserInfo). + request.Warnings.Add($"The redirect to {MaskUrlPasswords(target.AbsoluteUri)} was not followed: {refusal}."); + return null; + } + + /// An http(s) URL without its user info (in other URLs, such as mailto:, it can be more than credentials). + private static Uri WithoutUserInfo(Uri uri) => + uri.UserInfo.Length == 0 || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) ? uri + : new Uri(uri.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.UserInfo, UriFormat.UriEscaped)); + + /// The client certificate for a URL a redirect leads to: selected for that URL, never one chosen for another origin. + private static ClientCertificateSelection? SelectClientCertificate(PreparedRequest request, Uri target) => + target.Scheme != Uri.UriSchemeHttps ? null + : request.ClientCertificateSelector is { } select ? select(target) + : IsSameOrigin(target, request.Uri!) ? request.ClientCertificate + : null; + + /// The content codings removes, sent as Accept-Encoding unless the request has its own. + private const string DecodedCodings = "gzip, deflate, br"; + + /// + /// Reads the body and removes the content codings its Content-Encoding lists. At most are + /// read, and as many kept once decoded: a small body that decodes to a huge one stays within the limit. A body that + /// cannot be decoded is kept as received, with a warning saying why. + /// + internal static async Task<(byte[] Body, bool Truncated, long Received, string? Warning)> ReadBodyAsync( + HttpResponseMessage response, long maxBytes, CancellationToken cancellationToken) + { + // HEAD, 204 and 304 responses may declare a length without having a body. + var length = response.RequestMessage?.Method != HttpMethod.Head && response.StatusCode is not (HttpStatusCode.NoContent or HttpStatusCode.NotModified) + ? response.Content.Headers.ContentLength ?? 0 : 0; + byte[] received; + bool truncated; + await using (var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false)) + { + (received, truncated) = await ReadAsync(stream, length, maxBytes, cancellationToken).ConfigureAwait(false); + } + + var codings = ContentCodings(response.Content.Headers); + if (received.Length == 0 || codings.Count == 0) + { + return (received, truncated, received.Length, null); + } + + if (codings.Find(c => c is not ("gzip" or "x-gzip" or "deflate" or "br")) is { } unknown) + { + return (received, truncated, received.Length, $"The body is kept as received: TermRest cannot decode Content-Encoding '{unknown}'."); + } + + // Listed in the order they were applied: the last one is removed first. + var body = received; + var cut = truncated; + for (var i = codings.Count - 1; i >= 0 && body.Length > 0; i--) + { + try + { + // A gzip member ends with the size of its data (modulo 4 GB): a hint for the buffer, as a declared length is. + var size = codings[i] is "gzip" or "x-gzip" && body.Length >= 18 ? BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(^4)) : 0; + await using var decoder = CreateDecoder(codings[i], body); + (body, var more) = await ReadAsync(decoder, size, maxBytes, cancellationToken).ConfigureAwait(false); + cut |= more; + } + catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException) + { + // Such as a plain body labelled gzip by a misconfigured server or proxy (.NET's messages tell no more). + return (received, truncated, received.Length, + $"The body could not be decoded (Content-Encoding: {string.Join(", ", codings)}): it is not valid {codings[i]} data. It is kept as received."); + } + } + + return (body, cut, received.Length, null); + } + + /// 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) + { + var codings = new List(); + if (headers.NonValidated.TryGetValues("Content-Encoding", out var values)) + { + foreach (var value in values) + { + foreach (var coding in value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + if (!coding.Equals("identity", StringComparison.OrdinalIgnoreCase) && !coding.Equals("none", StringComparison.OrdinalIgnoreCase)) + { + codings.Add(coding.ToLowerInvariant()); + } + } + } + } + + return codings; + } + + private static Stream CreateDecoder(string coding, byte[] data) { - await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - using var buffer = new MemoryStream(); + var input = new MemoryStream(data, writable: false); + return coding switch + { + "br" => new BrotliStream(input, CompressionMode.Decompress), + + // The standard deflate coding is zlib data, but some servers send raw deflate data. As .NET does, the first byte + // tells them apart: 8 in its low bits for zlib. + "deflate" when (data[0] & 0x0F) == 8 => new ZLibStream(input, CompressionMode.Decompress), + "deflate" => new DeflateStream(input, CompressionMode.Decompress), + _ => new GZipStream(input, CompressionMode.Decompress), + }; + } + + /// + /// Reads at most from . A body of known length goes into one buffer + /// of that size: growing one allocates about twice the body. The length is only declared, so the buffer takes that size + /// once the first megabyte has actually arrived. + /// + private static async Task<(byte[] Data, bool Truncated)> ReadAsync(Stream stream, long length, long maxBytes, CancellationToken cancellationToken) + { + var expected = (int)Math.Min(Math.Min(length, maxBytes), Array.MaxLength); + using var buffer = new MemoryStream(Math.Min(expected, 1024 * 1024)); var chunk = ArrayPool.Shared.Rent(81920); try { int read; while ((read = await stream.ReadAsync(chunk.AsMemory(), cancellationToken).ConfigureAwait(false)) > 0) { - var room = maxBytes - buffer.Length; - if (read > room) + var count = (int)Math.Clamp(maxBytes - buffer.Length, 0, read); + if (buffer.Length + count > buffer.Capacity && expected > buffer.Capacity) { - buffer.Write(chunk, 0, (int)Math.Max(0, room)); - return (buffer.ToArray(), true); + buffer.Capacity = expected; } - buffer.Write(chunk, 0, read); + buffer.Write(chunk, 0, count); + if (count < read) + { + return (ToArray(buffer), true); + } } } finally @@ -293,10 +588,13 @@ private HttpRequestMessage CreateMessage(PreparedRequest request, HttpExchange e ArrayPool.Shared.Return(chunk); } - return (buffer.ToArray(), false); + return (ToArray(buffer), false); } - private static ResponseSnapshot Snapshot(HttpResponseMessage response, byte[] body, bool truncated) + /// 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) { var headers = new List>(); void AddAll(HttpHeaders source) @@ -320,13 +618,30 @@ void AddAll(HttpHeaders source) Version = response.Version, Headers = headers, Body = body, + ReceivedBodySize = received, BodyTruncated = truncated, - ContentType = response.Content.Headers.ContentType?.ToString(), + // .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), FinalUri = response.RequestMessage?.RequestUri, }; } - private static string DescribeError(Exception ex, ConnectionCapture capture) + /// The Content-Type as the server sent it (null for none). + private static string? RawContentType(HttpContentHeaders headers) + { + if (headers.NonValidated.TryGetValues("Content-Type", out var values)) + { + foreach (var value in values) + { + return value.Trim() is { Length: > 0 } type ? type : null; + } + } + + return null; + } + + private static string DescribeError(Exception ex, ConnectionCapture capture, Uri target) { if (capture.FirstRejected() is { } rejected) { @@ -338,19 +653,102 @@ private static string DescribeError(Exception ex, ConnectionCapture capture) var messages = new List(); for (var e = ex; e is not null; e = e.InnerException) { + // An outer message often repeats the inner one ("Connection refused (host:port)" around "Connection refused"). var text = e.Message.Trim(); - if (text.Length > 0 && !messages.Contains(text)) + if (text.Length > 0 && !messages.Any(m => m.Contains(text, StringComparison.Ordinal))) { messages.Add(text); } } + // .NET writes the proxy's URL as Uri.ToString() does, which unescapes a space in its password, where + // MaskUrlPasswords stops: that URL is masked whole first (looked up only for a message with a URL in it). var summary = string.Join(" → ", messages); + if (summary.Contains("://", StringComparison.Ordinal) && capture.ProxyUri(target) is { } proxy) + { + summary = MaskProxyPassword(summary, proxy); + } + + summary = MaskUrlPasswords(summary); return ex is HttpRequestException { HttpRequestError: not HttpRequestError.Unknown } hre ? $"{hre.HttpRequestError}: {summary}" : summary; } - /// Collects connection timing and TLS details from handler callbacks (which run on pool threads). - private sealed class ConnectionCapture(Stopwatch clock) + /// + /// with the password of 's URL masked as *** wherever the URL is + /// in it as .NET writes it (: a space or a letter that is not ASCII unescaped), as it is sent, + /// or as it was given. The password goes from the first ':' after "://" to the authority's last '@', white space and all. + /// + private static string MaskProxyPassword(string text, Uri proxy) + { + foreach (var url in (string[])[proxy.ToString(), proxy.AbsoluteUri, proxy.OriginalString]) + { + var start = url.IndexOf("://", StringComparison.Ordinal) + 3; + if (start < 3 || !text.Contains(url, StringComparison.Ordinal)) + { + continue; + } + + var end = url.IndexOf('/', start); + var authority = url.AsSpan(start, (end < 0 ? url.Length : end) - start); + var at = authority.LastIndexOf('@'); + var colon = at < 0 ? -1 : authority[..at].IndexOf(':'); + if (colon >= 0 && at > colon + 1) + { + text = text.Replace(url, string.Concat(url.AsSpan(0, start + colon + 1), "***", url.AsSpan(start + at)), StringComparison.Ordinal); + } + } + + return text; + } + + /// + /// with the password of each URL in it masked as ***. .NET puts a proxy's URL in some + /// messages (a tunnel the proxy refused), with the user and password the proxy setting or HTTPS_PROXY gives. + /// + internal static string MaskUrlPasswords(string text) + { + StringBuilder? masked = null; + var copied = 0; + for (var scheme = text.IndexOf("://", StringComparison.Ordinal); scheme >= 0; scheme = text.IndexOf("://", scheme + 3, StringComparison.Ordinal)) + { + var start = scheme + 3; + var end = start; + while (end < text.Length && text[end] is not ('/' or '?' or '#') && !char.IsWhiteSpace(text[end])) + { + end++; + } + + // The user info ends at the authority's last '@' (System.Uri escapes any other); the password follows its first ':'. + var authority = text.AsSpan(start, end - start); + var at = authority.LastIndexOf('@'); + var colon = at < 0 ? -1 : authority[..at].IndexOf(':'); + if (colon >= 0 && at > colon + 1) + { + masked ??= new StringBuilder(text.Length); + masked.Append(text, copied, start + colon + 1 - copied).Append("***"); + copied = start + at; + } + } + + return masked is null ? text : masked.Append(text, copied, text.Length - copied).ToString(); + } + + /// + /// How a header value is sent: as typed, in UTF-8, as curl sends it (.NET would refuse any value that is not ASCII). + /// A Cookie header typed in ASCII, or not typed, carries the jar's cookies as they came: .NET reads response headers, + /// Set-Cookie included, as Latin-1, so Latin-1 gives the server its bytes back. + /// + private static Encoding HeaderEncoding(string name, HttpRequestMessage message) => + name.Equals("Cookie", StringComparison.OrdinalIgnoreCase) + && (!message.Headers.NonValidated.TryGetValues("Cookie", out var typed) || typed.All(value => Ascii.IsValid(value))) + ? Encoding.Latin1 + : Encoding.UTF8; + + /// + /// Collects connection timing and TLS details from the callbacks of one handler (they run on pool threads). A handler + /// serves one origin with one client certificate: redirects elsewhere get handlers (and captures) of their own. + /// + private sealed class ConnectionCapture(Stopwatch clock, Uri target, ClientCertificateSelection? selection) { private readonly Lock _gate = new(); private readonly List<(TlsConnectionInfo Info, SslStream? Stream)> _tls = []; @@ -366,6 +764,28 @@ private sealed class ConnectionCapture(Stopwatch clock) private ClientCertificateSelection? _presented; private bool _presentedViaContext; + /// The client certificate this handler presents (null: none). + public ClientCertificateSelection? Selection { get; } = selection; + + /// The proxy the handler sends through (the system's unless the request names one); null for none. + public IWebProxy? Proxy { get; set; } + + /// + /// The URL of the proxy that a request to goes through, or null. Only for an error: the system's + /// can take long to find (Windows). A lookup that throws means no proxy, as for the handler. + /// + public Uri? ProxyUri(Uri uri) + { + try + { + return Proxy is { } proxy && !proxy.IsBypassed(uri) && proxy.GetProxy(uri) is { IsAbsoluteUri: true } address ? address : null; + } + catch (Exception) + { + return null; + } + } + public bool IsConnected { get @@ -377,29 +797,34 @@ public bool IsConnected } } - public X509Certificate2? SelectClientCertificate(ClientCertificateSelection? selection, X509Certificate? remoteCertificate, string[] acceptableIssuers) + /// Whether a redirect to with can reuse this handler. + public bool Serves(Uri next, ClientCertificateSelection? certificate) => + IsSameOrigin(next, target) && ReferenceEquals(certificate?.Certificate, Selection?.Certificate); + + public X509Certificate2? SelectClientCertificate(X509Certificate? remoteCertificate, string[] acceptableIssuers) { // Windows and macOS call this once before the handshake (no remote certificate yet) and again when the - // server actually requests a client certificate. Linux calls it only before the handshake and reuses its - // answer, so the request shows only in the certificate sent (see CollectTls). + // server actually requests a client certificate, unless (Windows) .NET reuses the credential of an earlier + // connection with the same certificate, which answers itself. Linux calls it only before the handshake and + // reuses its answer. Then the request shows only in the certificate sent (see CollectTls). if (remoteCertificate is not null || acceptableIssuers.Length > 0) { lock (_gate) { _clientCertificateRequested = true; _acceptableIssuers = acceptableIssuers; - _presented = selection; + _presented = Selection; } } - return selection?.Certificate.Certificate; + return Selection?.Certificate.Certificate; } - public void RecordContextCertificate(ClientCertificateSelection selection) + public void RecordContextCertificate() { lock (_gate) { - _presented = selection; + _presented = Selection; _presentedViaContext = true; } } @@ -445,7 +870,7 @@ public bool Validate(object sender, X509Certificate? certificate, X509Chain? cha var stream = sender as SslStream; var info = new TlsConnectionInfo { - Host = stream?.TargetHostName is { Length: > 0 } host ? host : request.Uri?.Host ?? "", + Host = stream?.TargetHostName is { Length: > 0 } host ? host : target.Host, PolicyErrors = errors, }; @@ -535,53 +960,89 @@ public TimingBreakdown BuildTiming(TimeSpan? headersAt, TimeSpan total) } } - public List CollectTls(PreparedRequest request) + public List CollectTls() { lock (_gate) { foreach (var (info, stream) in _tls) { - info.ClientCertificateRequested = _clientCertificateRequested; + info.ClientCertificateRequested |= _clientCertificateRequested; info.AcceptableIssuers.AddRange(_acceptableIssuers); - try + + // Read again while the connection is open: a server may ask for the certificate after the handshake (a + // TLS 1.2 renegotiation), which the selection callback may not see. One that is closed keeps the record. + ReadSession(info, stream); + + // The certificate chosen is shown when the server asked for it, or (sent with its chain, through a + // context) when the handshake did not complete. + if (info.ClientCertificate is null && _presented is { } presented + && (_clientCertificateRequested || (_presentedViaContext && info.Protocol == SslProtocols.None))) { - if (stream is { IsAuthenticated: true }) - { - info.Protocol = stream.SslProtocol; - info.CipherSuite = stream.NegotiatedCipherSuite; - var alpn = stream.NegotiatedApplicationProtocol; - info.ApplicationProtocol = alpn.Protocol.IsEmpty ? null : alpn.ToString(); - if (stream.LocalCertificate is { } local) - { - using var copy = X509CertificateLoader.LoadCertificate(local.GetRawCertData()); - info.ClientCertificate = CertificateSummary.From(copy); - info.ClientCertificateOrigin = request.ClientCertificate?.Origin ?? "selected by the OS"; - - // A client sends its certificate only when the server asks for one, and except on - // macOS LocalCertificate is the certificate sent (there, the one chosen, sent or not). - // This also tells on Linux, where the selection callback never sees the request. - if (!OperatingSystem.IsMacOS()) - { - info.ClientCertificateRequested = true; - } - } - } + info.ClientCertificate = presented.Summary; + info.ClientCertificateOrigin = info.Protocol == SslProtocols.None ? $"{presented.Origin}; handshake did not complete" : presented.Origin; } - catch (Exception ex) when (ex is ObjectDisposedException or InvalidOperationException or CryptographicException) + } + + return _tls.Select(t => t.Info).ToList(); + } + } + + /// + /// The handler's : records the TLS session of a new connection + /// as soon as its handshake has completed. A connection the server closes (Connection: close, HTTP/1.0) is + /// disposed once its response has been read, and its session with it. + /// + public ValueTask RecordSession(SocketsHttpPlaintextStreamFilterContext context, CancellationToken cancellationToken) + { + if (context.PlaintextStream is SslStream stream) + { + lock (_gate) + { + foreach (var (info, tracked) in _tls) { - // The connection (or a certificate reloaded meanwhile) was torn down; keep what the callbacks recorded. + if (ReferenceEquals(tracked, stream)) + { + ReadSession(info, stream); + } } + } + } + + return ValueTask.FromResult(context.PlaintextStream); + } + + /// The protocol, cipher, ALPN and client certificate of a session whose connection is still open. + private void ReadSession(TlsConnectionInfo info, SslStream? stream) + { + try + { + if (stream is not { IsAuthenticated: true }) + { + return; + } + + info.Protocol = stream.SslProtocol; + info.CipherSuite = stream.NegotiatedCipherSuite; + var alpn = stream.NegotiatedApplicationProtocol; + info.ApplicationProtocol = alpn.Protocol.IsEmpty ? null : alpn.ToString(); + if (stream.LocalCertificate is { } local) + { + using var copy = X509CertificateLoader.LoadCertificate(local.GetRawCertData()); + info.ClientCertificate = CertificateSummary.From(copy); + info.ClientCertificateOrigin = Selection?.Origin ?? "selected by the OS"; - if (info.ClientCertificate is null && _presented is { } presented && (_clientCertificateRequested || _presentedViaContext)) + // A client sends its certificate only when the server asks for one, and except on macOS + // LocalCertificate is the certificate sent (there, the one chosen, sent or not). This also tells when + // the selection callback did not see the request. + if (!OperatingSystem.IsMacOS()) { - info.ClientCertificate = presented.Summary; - info.ClientCertificateOrigin = info.Protocol == SslProtocols.None - ? $"{presented.Origin}; handshake did not complete" - : presented.Origin; + info.ClientCertificateRequested = true; } } - - return _tls.Select(t => t.Info).ToList(); + } + catch (Exception ex) when (ex is ObjectDisposedException or InvalidOperationException or CryptographicException) + { + // The connection (or a certificate reloaded meanwhile) was torn down; keep what the callbacks recorded. } } @@ -591,6 +1052,9 @@ private static bool ValidateWithExtraTrust(X509Certificate certificate, X509Chai using var custom = new X509Chain(); custom.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; custom.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + + // Like the OS check: a certificate issued for other purposes does not authenticate a server. + custom.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1")); foreach (var ca in extra) { if (ca.SubjectName.RawData.AsSpan().SequenceEqual(ca.IssuerName.RawData)) diff --git a/src/TermRest.Core/Http/PreparedRequest.cs b/src/TermRest.Core/Http/PreparedRequest.cs index 4fbba1a..b4ccc65 100644 --- a/src/TermRest.Core/Http/PreparedRequest.cs +++ b/src/TermRest.Core/Http/PreparedRequest.cs @@ -24,6 +24,28 @@ public sealed class MultipartPart public string? FilePath { get; init; } public string? ContentType { get; init; } + + /// + /// The content type the part is sent with (recordings and the cURL export give the same): as typed, as curl and Postman + /// send it; for a file without one, the type its extension names, as they choose it (for a few common ones), else + /// application/octet-stream. Null for text without one. + /// + public string? SentContentType => ContentType ?? (FilePath is null ? null : TypeOfFile(FilePath)); + + /// curl's types for file extensions, and JSON's. + private static string TypeOfFile(string path) => Path.GetExtension(path).ToLowerInvariant() switch + { + ".gif" => "image/gif", + ".jpg" or ".jpeg" => "image/jpeg", + ".png" => "image/png", + ".svg" => "image/svg+xml", + ".txt" => "text/plain", + ".htm" or ".html" => "text/html", + ".pdf" => "application/pdf", + ".xml" => "application/xml", + ".json" => "application/json", + _ => "application/octet-stream", + }; } /// A fully resolved request body. Content objects are created on demand so the same request can be re-sent. @@ -55,7 +77,7 @@ public sealed class PreparedBody { PreparedBodyKind.Text => new ByteArrayContent(Encoding.UTF8.GetBytes(Text ?? "")), PreparedBodyKind.FormUrlEncoded => new ByteArrayContent(Encoding.ASCII.GetBytes(EncodeForm(Fields))), - PreparedBodyKind.File => new StreamContent(File.OpenRead(FilePath!)), + PreparedBodyKind.File => new StreamContent(OpenFile(FilePath!)), PreparedBodyKind.Multipart => CreateMultipart(), _ => null, }; @@ -82,39 +104,128 @@ public sealed class PreparedBody public static string EncodeForm(IEnumerable> fields) => string.Join('&', fields.Select(f => $"{WebUtility.UrlEncode(f.Key)}={WebUtility.UrlEncode(f.Value)}")); - private MultipartFormDataContent CreateMultipart() + /// + /// A file to send, opened as opens it: a file another program has open for writing (Excel, + /// a log writer) is sent too, as curl and Postman send it. Sharing it for reading only, Windows would refuse to open it. + /// It is sent as long as it is now (see ); a pipe, which has no length, in chunks. + /// + private static Stream OpenFile(string path) { - var multipart = new MultipartFormDataContent(); - foreach (var part in Parts) + var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + try { - HttpContent partContent; - string? fileName = null; - if (part.FilePath is not null) - { - partContent = new StreamContent(File.OpenRead(part.FilePath)); - fileName = Path.GetFileName(part.FilePath); - partContent.Headers.ContentType = MediaTypeHeaderValue.Parse(part.ContentType ?? "application/octet-stream"); - } - else + return file.CanSeek ? new BoundedFile(file, file.Length) : file; + } + catch + { + file.Dispose(); + throw; + } + } + + /// + /// The parts as browsers, curl and Postman send them: names and file names in UTF-8, in quotes, with only '"', CR and LF + /// escaped (as %22, %0D and %0A); MultipartFormDataContent would write non-ASCII ones as RFC 2047 encoded-words, which + /// form parsers don't decode, add a filename* (which RFC 7578 rules out), and refuse a '"'. + /// + private MultipartContent CreateMultipart() + { + var multipart = new MultipartContent("form-data") { HeaderEncodingSelector = (_, _) => Encoding.UTF8 }; + HttpContent? partContent = null; + try + { + foreach (var part in Parts) { - partContent = new ByteArrayContent(Encoding.UTF8.GetBytes(part.Value ?? "")); - if (part.ContentType is not null && MediaTypeHeaderValue.TryParse(part.ContentType, out var partType)) + var disposition = $"form-data; name={QuoteName(part.Name)}"; + if (part.FilePath is not null) { - partContent.Headers.ContentType = partType; + partContent = new StreamContent(OpenFile(part.FilePath)); + disposition += $"; filename={QuoteName(Path.GetFileName(part.FilePath))}"; + } + else + { + partContent = new ByteArrayContent(Encoding.UTF8.GetBytes(part.Value ?? "")); } - } - if (fileName is null) - { - multipart.Add(partContent, part.Name); + partContent.Headers.TryAddWithoutValidation("Content-Disposition", disposition); + + // As typed (MediaTypeHeaderValue would refuse 'jpeg'); RequestPreparer refuses a line break. + if (part.SentContentType is { } type) + { + partContent.Headers.TryAddWithoutValidation("Content-Type", type); + } + + multipart.Add(partContent); + partContent = null; } - else + } + catch + { + // Not sent: the files opened so far are closed (Windows would keep them locked until a garbage collection). + partContent?.Dispose(); + multipart.Dispose(); + throw; + } + + return multipart; + } + + private static string QuoteName(string name) => + "\"" + name.Replace("\"", "%22", StringComparison.Ordinal).Replace("\r", "%0D", StringComparison.Ordinal).Replace("\n", "%0A", StringComparison.Ordinal) + "\""; + + /// + /// A file read up to the length it had when it was opened, which Content-Length announces: what another program + /// appends while it is sent (a log) stays out, where .NET would fail the request for a body longer than announced. A + /// file that gets shorter still fails it. + /// + private sealed class BoundedFile(FileStream file, long length) : Stream + { + public override bool CanRead => true; + + public override bool CanSeek => true; + + public override bool CanWrite => false; + + public override long Length => length; + + public override long Position + { + get => file.Position; + set => file.Position = value; + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) => file.Read(buffer[..Available(buffer.Length)]); + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => + file.ReadAsync(buffer[..Available(buffer.Length)], cancellationToken); + + public override long Seek(long offset, SeekOrigin origin) => + origin == SeekOrigin.End ? file.Seek(length + offset, SeekOrigin.Begin) : file.Seek(offset, origin); + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) { - multipart.Add(partContent, part.Name, fileName); + file.Dispose(); } + + base.Dispose(disposing); } - return multipart; + private int Available(int count) => (int)Math.Clamp(length - file.Position, 0, count); } } @@ -123,7 +234,13 @@ private MultipartFormDataContent CreateMultipart() /// The saved collection it belongs to (null for scratch requests). /// Its path in the collection (null when not saved). /// Its name (null when not saved). -public sealed record RequestSource(Model.HttpRequestSpec Spec, string? CollectionName, string? RequestPath, string? RequestName); +/// The request inherits its auth (from its folders or collection); holds a copy of it. +/// +/// The file of that collection (a v3 collection's folder) in the workspace, relative with "/": it tells collections of +/// the same name apart. +/// +public sealed record RequestSource(Model.HttpRequestSpec Spec, string? CollectionName, string? RequestPath, string? RequestName, bool AuthInherited = false, + string? CollectionFile = null); /// A request with all variables, auth, body and TLS choices resolved, ready to send. public sealed class PreparedRequest @@ -141,10 +258,31 @@ public sealed class PreparedRequest public NetworkCredential? Credential { get; set; } + /// The challenge schemes answers, on the request's own origin only (see ). + public string[] CredentialSchemes { get; set; } = []; + + /// + /// Headers the auth helper added (an API key …). Like Authorization and Cookie, they are not sent when a redirect + /// leads to another origin. + /// + public HashSet AuthHeaderNames { get; } = new(StringComparer.OrdinalIgnoreCase); + public string AuthDescription { get; set; } = "No auth"; + /// + /// The auth the request was prepared with: its own or the one it inherits, and of credential sets the one its URL + /// selected (see ); null for none. + /// + public Model.AuthSpec? AuthUsed { get; set; } + public ClientCertificateSelection? ClientCertificate { get; set; } + /// + /// Selects the client certificate for a URL a redirect leads to, as was for + /// ; null when there is no certificate registry. + /// + public Func? ClientCertificateSelector { get; set; } + public bool StrictSsl { get; set; } = true; public X509Certificate2Collection? ExtraTrustedCertificates { get; set; } @@ -175,14 +313,56 @@ public sealed class PreparedRequest public RequestSource? Source { get; set; } /// Resolved values of secret variables and auth credentials, masked by . + /// Add to it with , which also adds the form a value is sent in. public HashSet SecretValues { get; } = new(StringComparer.Ordinal); /// /// Resolved values of variables named like credentials (password, token, apiKey …) that are not typed "secret". /// Recordings redact them as well (see ). /// + /// Add to it with , which also adds the form a value is sent in. public HashSet SensitiveValues { get; } = new(StringComparer.Ordinal); + /// Adds secret values (see ) as they are and as they are sent (see ). + public void AddSecretValues(IEnumerable values) => AddForms(SecretValues, values); + + /// Adds values of variables named like credentials (see ), as they are and as they are sent. + public void AddSensitiveValues(IEnumerable values) => AddForms(SensitiveValues, values); + + /// + /// Adds each value, and also without the white space around it: a header value goes without its trailing line break (a + /// token pasted or read with one), and servers that echo a value drop the spaces around it. Only that form may come back. + /// A value with a '#' or a '?' is also added as a URL holds it (see ): with its '#' as %23 + /// (in the path or the query), and also its '?' as %3F (in a path variable); and one with a character the user info + /// of a URL encodes, as it holds it (). + /// + private static void AddForms(HashSet set, IEnumerable values) + { + foreach (var value in values) + { + if (value.Length == 0) + { + continue; + } + + set.Add(value); + var trimmed = value.Trim(); + if (trimmed.Length > 0 && trimmed.Length < value.Length) + { + set.Add(trimmed); + } + + if (value.AsSpan().IndexOfAny('#', '?') >= 0) + { + var inUrl = value.Replace("#", "%23", StringComparison.Ordinal); + set.Add(inUrl); + set.Add(inUrl.Replace("?", "%3F", StringComparison.Ordinal)); + } + + set.Add(RequestPreparer.InUserInfo(value)); + } + } + public string? GetHeader(string name) => Headers.LastOrDefault(h => string.Equals(h.Key, name, StringComparison.OrdinalIgnoreCase)).Value; diff --git a/src/TermRest.Core/Http/RequestPreparer.cs b/src/TermRest.Core/Http/RequestPreparer.cs index ab526e5..df30ec6 100644 --- a/src/TermRest.Core/Http/RequestPreparer.cs +++ b/src/TermRest.Core/Http/RequestPreparer.cs @@ -1,7 +1,9 @@ +using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using TermRest.Core.Auth; using TermRest.Core.Certificates; +using TermRest.Core.IO; using TermRest.Core.Model; using TermRest.Core.Postman; using TermRest.Core.Variables; @@ -26,14 +28,20 @@ public sealed class ExecutionDefaults public long MaxResponseBytes { get; set; } = 50L * 1024 * 1024; public string HttpVersion { get; set; } = "1.1"; + + /// + /// The folder whose body and form-data files requests may send (the workspace's), links resolved; null: any file. A + /// collection from a repository someone else wrote could otherwise send the user's files to a server of its choosing. + /// Client certificates and the CA bundle may be anywhere but on a network share outside it (see + /// ). + /// + public string? FilesFolder { get; set; } } /// Turns an editable into a . public sealed class RequestPreparer(VariableResolver variables, ClientCertificateProvider? certificates, ExecutionDefaults defaults) { private static readonly System.Security.Cryptography.X509Certificates.X509Certificate2Collection EmptyTrust = []; - private System.Security.Cryptography.X509Certificates.X509Certificate2Collection? _trust; - private string? _trustError; public VariableResolver Variables { get; } = variables; @@ -53,10 +61,16 @@ public PreparedRequest Prepare(HttpRequestSpec spec, AuthSpec? effectiveAuth, st prepared.Errors.Add($"'{prepared.Method}' is not a valid HTTP method."); } - // URL: resolve path variables first, then the rest, then rebuild the query from enabled parameters. - var pathValues = spec.PathVariables.Where(p => p.Enabled).GroupBy(p => p.Key).ToDictionary(g => g.Key, g => R(g.Last().Value)); + // URL: resolve path variables first, then the rest, then rebuild the query from enabled parameters. Values are sent + // as typed, as Postman sends them, except that a '#' in a value that goes into the path or the query, and a '?' in a + // path variable, is percent-encoded: there the URL would end its path or query, and silently not send the rest. + var pathValues = spec.PathVariables.Where(p => p.Enabled).GroupBy(p => p.Key) + .ToDictionary(g => g.Key, g => EscapeHash(R(g.Last().Value)).Replace("?", "%3F", StringComparison.Ordinal)); var baseUrl = PostmanUrl.SubstitutePathVariables(PostmanUrl.StripQueryAndHash(spec.Url), name => pathValues.GetValueOrDefault(name)); - baseUrl = R(baseUrl).Trim(); + + // In the path, the values of {{variables}} too (a '?' in one still starts the query, as in Postman). + var pathStart = PostmanUrl.PathStart(baseUrl); + baseUrl = (ResolveAuthority(pathStart < 0 ? baseUrl : baseUrl[..pathStart], R) + (pathStart < 0 ? "" : EscapeHash(R(baseUrl[pathStart..])))).Trim(); // The parameter table is the source of truth (it also holds disabled rows). Specs built in code may only // have the query in the URL text, so fall back to parsing it. var queryEntries = spec.QueryParams.Count > 0 @@ -66,25 +80,37 @@ public PreparedRequest Prepare(HttpRequestSpec spec, AuthSpec? effectiveAuth, st .Select(q => (Key: R(q.Key), Value: q.Value is null ? null : R(q.Value))) .ToList(); - // Auth helpers may add headers, query parameters or challenge credentials. + // Auth helpers may add headers, query parameters or challenge credentials. Of a v3 collection's or folder's credential + // sets, the one the URL selects. + effectiveAuth = ChooseCredentialSet(effectiveAuth, WithScheme(baseUrl), prepared.Warnings); + prepared.AuthUsed = effectiveAuth; var auth = AuthApplier.Apply(effectiveAuth, Variables, unresolved); prepared.AuthDescription = auth.Description; prepared.Credential = auth.Credential; + prepared.CredentialSchemes = auth.CredentialSchemes; prepared.Warnings.AddRange(auth.Warnings); - prepared.SecretValues.UnionWith(auth.Secrets.Where(s => s.Length > 0)); - query.AddRange(auth.QueryParameters.Select(q => (q.Key, (string?)q.Value))); - - var url = baseUrl; - if (query.Count > 0) + prepared.AddSecretValues(auth.Secrets); + foreach (var (key, value) in auth.QueryParameters) { - url += "?" + string.Join('&', query.Select(q => q.Value is null ? q.Key : $"{q.Key}={q.Value}")); + // As in Postman, the helper's parameter replaces one of the same name and is encoded: a & would otherwise end the + // value early, a # end the query, and a + arrive as a space. + if (query.RemoveAll(q => q.Key == key) > 0) + { + prepared.Warnings.Add($"The auth helper replaced the '{key}' query parameter."); + } + + var encoded = Uri.EscapeDataString(value); + prepared.AddSecretValues([encoded]); // the form the URL holds + query.Add((Uri.EscapeDataString(key), encoded)); } - if (url.Length > 0 && !url.Contains("://", StringComparison.Ordinal)) + var url = baseUrl; + if (query.Count > 0) { - url = "http://" + url; + url += "?" + string.Join('&', query.Select(q => q.Value is null ? EscapeHash(q.Key) : $"{EscapeHash(q.Key)}={EscapeHash(q.Value)}")); } + url = WithScheme(url); prepared.Url = url; if (url.Length == 0) { @@ -92,7 +118,9 @@ public PreparedRequest Prepare(HttpRequestSpec spec, AuthSpec? effectiveAuth, st } else if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) { - prepared.Errors.Add($"'{url}' is not a valid http(s) URL."); + // Its password (or a user name without one, then the credential) masked as in the history: only a valid URL's + // credentials are known as secrets (AddUrlCredentials). + prepared.Errors.Add($"'{PostmanUrl.MaskCredentials(url)}' is not a valid http(s) URL."); } else { @@ -112,14 +140,41 @@ public PreparedRequest Prepare(HttpRequestSpec spec, AuthSpec? effectiveAuth, st } prepared.Headers.Add(header); + prepared.AuthHeaderNames.Add(header.Key); } - prepared.Body = PrepareBody(spec.Body, prepared, baseDirectory, R); + // Credentials in the URL (https://user:password@host) go as Basic auth, as curl and Postman send them: .NET would + // leave them out. An Authorization header or an auth helper takes precedence. + if (prepared.Uri is { UserInfo.Length: > 0 } withCredentials && prepared.GetHeader("Authorization") is null + && auth.Headers.Count == 0 && auth.QueryParameters.Count == 0 && auth.Credential is null) + { + AddUrlCredentials(prepared, withCredentials.UserInfo); + } + + // A line break in a value (from a variable, a file …) would end the header early or add headers. A trailing one, + // as in a pasted token, is dropped. + for (var i = 0; i < prepared.Headers.Count; i++) + { + var (key, value) = prepared.Headers[i]; + var trimmed = value.TrimEnd('\r', '\n'); + if (trimmed.AsSpan().IndexOfAny('\r', '\n', '\0') >= 0) + { + prepared.Errors.Add($"Header '{key}' contains a line break or NUL character."); + } + else if (trimmed.Length < value.Length) + { + prepared.Headers[i] = new(key, trimmed); + } + } + + prepared.Body = PrepareBody(spec.Body, prepared, baseDirectory, defaults.FilesFolder, R); // TLS and transport settings: request settings override workspace defaults. prepared.StrictSsl = spec.Settings.StrictSsl ?? defaults.StrictSsl; prepared.FollowRedirects = spec.Settings.FollowRedirects ?? defaults.FollowRedirects; - prepared.MaxRedirects = spec.Settings.MaxRedirects ?? defaults.MaxRedirects; + + // A negative limit (curl's -1 for no limit, as earlier cURL imports kept it) is read as none: the workspace's applies. + prepared.MaxRedirects = spec.Settings.MaxRedirects is int max and >= 0 ? max : defaults.MaxRedirects; prepared.UseCookies = !(spec.Settings.DisableCookies ?? false); prepared.Timeout = defaults.Timeout; prepared.Proxy = defaults.Proxy; @@ -127,9 +182,26 @@ public PreparedRequest Prepare(HttpRequestSpec spec, AuthSpec? effectiveAuth, st prepared.MaxResponseBytes = defaults.MaxResponseBytes; prepared.ExtraTrustedCertificates = LoadTrust(prepared.Warnings); - if (prepared.Uri is { } target && target.Scheme == Uri.UriSchemeHttps && certificates is not null) + if (certificates is not null) { - prepared.ClientCertificate = certificates.Select(target, spec.Certificate, baseDirectory, ResolveSecret, prepared.Warnings); + // Redirects may lead elsewhere: each URL gets the certificate selected for it (see HttpExecutor). + var pinned = spec.Certificate?.Clone(); + var origin = prepared.Uri; + prepared.ClientCertificateSelector = uri => + { + // A certificate pinned without URL patterns goes to the request's own origin only, like its credentials. + var own = pinned is { Matches.Count: 0 } && !(origin is not null && uri.Scheme == origin.Scheme && uri.Port == origin.Port + && string.Equals(uri.IdnHost, origin.IdnHost, StringComparison.OrdinalIgnoreCase)) ? null : pinned; + var warnings = new List(); + var selection = certificates.Select(uri, own, baseDirectory, ResolveSecret, warnings, defaults.FilesFolder); + prepared.Warnings.AddRange(warnings.Except(prepared.Warnings)); + return selection; + }; + + if (prepared.Uri is { } target && target.Scheme == Uri.UriSchemeHttps) + { + prepared.ClientCertificate = certificates.Select(target, pinned, baseDirectory, ResolveSecret, prepared.Warnings, defaults.FilesFolder); + } } if (unresolved.Count > 0) @@ -140,6 +212,46 @@ public PreparedRequest Prepare(HttpRequestSpec spec, AuthSpec? effectiveAuth, st return prepared; } + /// + /// A URL as it is sent: a "://" names a scheme only before the path, query or fragment (localhost:3000/login?next=http://app/ + /// has none); without one, the URL is http://. + /// + private static string WithScheme(string url) + { + var scheme = url.IndexOf("://", StringComparison.Ordinal); + return url.Length > 0 && (scheme < 0 || url.AsSpan(0, scheme).IndexOfAny('/', '?', '#') >= 0) ? "http://" + url : url; + } + + /// + /// Of a v3 collection's or folder's credential sets, the one a request to uses: the first whose + /// rules all match it (a set without rules matches any URL), as Postman's schema says. A url rule's value is a + /// URL pattern as for certificates (api.example.com, https://*.example.com/v1/*, *), and may hold + /// variables; a rule of another kind, or a pattern that isn't one, matches nothing. None matching: no auth (as the + /// history keeps it, so a request sent from there gets none either), so its credentials never reach a host its rules + /// leave out, and a warning says so. Other auth is returned as it is. + /// + private AuthSpec? ChooseCredentialSet(AuthSpec? auth, string url, List warnings) + { + if (auth?.CredentialSets is not { Count: > 0 } sets) + { + return auth; + } + + Uri.TryCreate(url, UriKind.Absolute, out var uri); + foreach (var set in sets) + { + if (set.Rules.All(rule => uri is not null && rule.Key == "url" + && UrlMatchPattern.TryParse(Variables.Resolve(rule.Value), out var pattern) && pattern!.IsMatch(uri))) + { + return set.Auth; + } + } + + var names = string.Join(", ", sets.Select(s => $"'{s.Name}'")); + warnings.Add($"No credential set of the inherited auth ({names}) has rules that match this URL: it is sent without that auth."); + return new AuthSpec { Type = "noauth" }; + } + /// Resolves a secret reference: env:NAME reads an environment variable, {{var}} a workspace variable. public string? ResolveSecret(string? value) { @@ -163,27 +275,30 @@ public PreparedRequest Prepare(HttpRequestSpec spec, AuthSpec? effectiveAuth, st return null; } - if (_trust is null && _trustError is null) + if (defaults.FilesFolder is { } folder && RealPath.ReachesNetwork(defaults.CaBundlePath, folder)) { - try - { - _trust = CertificateLoader.LoadTrustBundle(defaults.CaBundlePath); - } - catch (Exception ex) when (ex is CertificateLoadException or IOException or System.Security.Cryptography.CryptographicException) - { - _trustError = $"CA bundle '{defaults.CaBundlePath}' not loaded: {ex.Message}"; - } + warnings.Add($"CA bundle '{defaults.CaBundlePath}' not loaded: {ClientCertificateProvider.OnNetworkShare}"); + return EmptyTrust; } - if (_trustError is not null) + try { - warnings.Add(_trustError); + // The provider keeps it parsed for the session (a CA bundle can hold hundreds of certificates). + return certificates is null ? CertificateLoader.LoadTrustBundle(defaults.CaBundlePath) : certificates.LoadTrustBundle(defaults.CaBundlePath); + } + catch (CertificateLoadException ex) + { + warnings.Add($"CA bundle '{defaults.CaBundlePath}' not loaded: {ex.Message}"); + return EmptyTrust; } - - return _trust ?? EmptyTrust; } - private static PreparedBody PrepareBody(RequestBody body, PreparedRequest prepared, string baseDirectory, Func resolve) + /// Why a body or form-data file is not sent, and how to send such files. + private static string OutsideFolder(string kind, string path, string where) => + $"{kind} '{path}' {where}, so it is not sent (a collection could otherwise send any of your files): allow files from outside " + + "it for this workspace in the full-screen UI (Tools › Settings…), or with --allow-outside-files."; + + private static PreparedBody PrepareBody(RequestBody body, PreparedRequest prepared, string baseDirectory, string? filesFolder, Func resolve) { if (body.Disabled) { @@ -191,49 +306,110 @@ private static PreparedBody PrepareBody(RequestBody body, PreparedRequest prepar } string? explicitType = prepared.GetHeader("Content-Type"); - string FilePath(string path) => Path.IsPathRooted(path) ? path : Path.GetFullPath(Path.Combine(baseDirectory, path)); + // A path typed or pasted with spaces around it, as the Body tab finds it; with no . or .. left, as it is checked and opened. + string FilePath(string path) + { + try + { + return Path.GetFullPath(Path.IsPathRooted(path = path.Trim()) ? path : Path.Combine(baseDirectory, path)); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return path; // no file has that name (a NUL in it) + } + } + + // A file that is there and, unless any may be sent (see ExecutionDefaults.FilesFolder), in the files' folder, also once + // its links are resolved. Nothing outside the folder is looked at: on Windows, looking at \\server\share sends the + // user's Windows credentials to that server. + string? realFolder = null; + bool Sendable(string kind, string path) + { + if (filesFolder is not null) + { + if (!RealPath.IsWithin(path, filesFolder)) + { + prepared.Errors.Add(OutsideFolder(kind, path, "is outside the workspace folder")); + return false; + } + + if (!RealPath.IsInside(path, filesFolder, realFolder ??= RealPath.Of(filesFolder) ?? filesFolder)) + { + prepared.Errors.Add(OutsideFolder(kind, path, "leads outside the workspace folder through a link")); + return false; + } + } + + if (!File.Exists(path)) + { + prepared.Errors.Add($"{kind} '{path}' does not exist."); + return false; + } + + return true; + } + + // As in Postman, an empty body is no body, sent without a Content-Type (some servers refuse an empty JSON body): raw + // text that is empty once its variables are replaced, a form without an enabled field (with a key), a file body + // without a file. switch (body.Mode) { case BodyMode.Raw: - return new PreparedBody + { + var text = resolve(body.Raw); + return text.Length == 0 ? PreparedBody.None : new PreparedBody { Kind = PreparedBodyKind.Text, - Text = resolve(body.Raw), + Text = text, ContentType = explicitType ?? RequestBody.ContentTypeForLanguage(body.RawLanguage), }; + } case BodyMode.UrlEncoded: - return new PreparedBody + { + var fields = body.UrlEncoded.Where(f => f.Enabled && f.Key.Length > 0).Select(f => new KeyValuePair(resolve(f.Key), resolve(f.Value))).ToList(); + return fields.Count == 0 ? PreparedBody.None : new PreparedBody { Kind = PreparedBodyKind.FormUrlEncoded, - Fields = body.UrlEncoded.Where(f => f.Enabled && f.Key.Length > 0).Select(f => new KeyValuePair(resolve(f.Key), resolve(f.Value))).ToList(), + Fields = fields, ContentType = explicitType ?? "application/x-www-form-urlencoded", }; + } case BodyMode.FormData: { + var fields = body.FormData.Where(f => f.Enabled && f.Key.Length > 0).ToList(); + if (fields.Count == 0) + { + return PreparedBody.None; + } + var parts = new List(); - foreach (var field in body.FormData.Where(f => f.Enabled && f.Key.Length > 0)) + foreach (var field in fields) { + // Sent as typed, as curl and Postman send it: a line break would end the part's header there. + var name = resolve(field.Key); + var type = string.IsNullOrWhiteSpace(field.ContentType) ? null : field.ContentType.Trim(); + if (type is not null && type.AsSpan().IndexOfAny('\r', '\n', '\0') >= 0) + { + prepared.Errors.Add($"The content type of form-data field '{name}' contains a line break or NUL character."); + } + if (field.IsFile) { foreach (var src in (field.Src ?? "").Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { var path = FilePath(resolve(src)); - if (File.Exists(path)) + if (Sendable("Form-data file", path)) { - parts.Add(new MultipartPart { Name = resolve(field.Key), FilePath = path, ContentType = field.ContentType }); - } - else - { - prepared.Errors.Add($"Form-data file '{path}' does not exist."); + parts.Add(new MultipartPart { Name = name, FilePath = path, ContentType = type }); } } } else { - parts.Add(new MultipartPart { Name = resolve(field.Key), Value = resolve(field.Value), ContentType = field.ContentType }); + parts.Add(new MultipartPart { Name = name, Value = resolve(field.Value), ContentType = type }); } } @@ -248,16 +424,16 @@ private static PreparedBody PrepareBody(RequestBody body, PreparedRequest prepar case BodyMode.File: { - if (string.IsNullOrWhiteSpace(body.FileSrc)) + var source = resolve(body.FileSrc); + if (string.IsNullOrWhiteSpace(source)) { - prepared.Errors.Add("Choose a file for the body."); + prepared.Warnings.Add("No file is chosen for the body: the request is sent without one."); return PreparedBody.None; } - var path = FilePath(resolve(body.FileSrc)); - if (!File.Exists(path)) + var path = FilePath(source); + if (!Sendable("Body file", path)) { - prepared.Errors.Add($"Body file '{path}' does not exist."); return PreparedBody.None; } @@ -301,7 +477,90 @@ private static PreparedBody PrepareBody(RequestBody body, PreparedRequest prepar } } + /// Sends the user info of the URL (as escapes it) as Authorization: Basic. + private static void AddUrlCredentials(PreparedRequest prepared, string userInfo) + { + var colon = userInfo.IndexOf(':', StringComparison.Ordinal); + var escapedUser = colon < 0 ? userInfo : userInfo[..colon]; + var user = Uri.UnescapeDataString(escapedUser); + var password = colon < 0 ? "" : userInfo[(colon + 1)..]; + var token = AuthApplier.BasicToken(user, Uri.UnescapeDataString(password)); + prepared.Headers.Add(new("Authorization", "Basic " + token)); + prepared.AuthHeaderNames.Add("Authorization"); + prepared.AuthDescription = "Basic (from the URL)"; // without the user name, as for the auth helper (see AuthApplier) + + // The password also as typed: the history keeps the URL as typed (masked), which System.Uri may escape differently. + var secrets = new List { password, Uri.UnescapeDataString(password), token }; + var url = prepared.Url; + var start = url.IndexOf("://", StringComparison.Ordinal) + 3; + var end = start < 3 ? -1 : url.IndexOf('@', start); + var separator = end < 0 ? -1 : url.IndexOf(':', start, end - start); + if (separator >= 0) + { + secrets.Add(url[(separator + 1)..end]); + } + + // Without a password, the user name is the credential (https://sk_test_…@host, as Stripe takes its key): in every form. + if (password.Length == 0) + { + secrets.AddRange([escapedUser, user]); + if (end >= 0) + { + secrets.Add(url[start..(separator >= 0 ? separator : end)]); + } + } + + prepared.AddSecretValues(secrets); + } + /// RFC 9110 token: what accepts (an unresolved {{variable}} is not). private static bool IsHttpToken(string value) => value.Length > 0 && value.All(c => char.IsAsciiLetterOrDigit(c) || "!#$%&'*+-.^_`|~".Contains(c, StringComparison.Ordinal)); + + /// A path or query value with its '#' percent-encoded (see ). + private static string EscapeHash(string value) => value.Replace("#", "%23", StringComparison.Ordinal); + + /// + /// The authority of a URL as typed (scheme://user:password@host:port) with its {{variables}} replaced. As in Postman, the + /// user info is read before they are, and characters that would end it there are percent-encoded: a '@', '/', '?', '#' + /// or '\' in a password (or base64 token) would make the URL invalid, or send part of it as the host or path. '%' stays, + /// so a value already encoded is sent as it is. + /// + private static string ResolveAuthority(string authority, Func resolve) + { + if (PostmanUrl.FindUserInfo(authority) is not var (start, length)) + { + return resolve(authority); + } + + return string.Concat(resolve(authority[..start]), InUserInfo(resolve(authority.Substring(start, length))), resolve(authority[(start + length)..])); + } + + /// + /// as the user info of a URL holds it (see ): its '@', '/', '?', '#' + /// and '\' percent-encoded. Secret values are known in this form too (). + /// + internal static string InUserInfo(string value) + { + if (value.AsSpan().IndexOfAny("@/?#\\") < 0) + { + return value; + } + + var userInfo = new StringBuilder(value.Length + 8); + foreach (var c in value) + { + _ = c switch + { + '@' => userInfo.Append("%40"), + '/' => userInfo.Append("%2F"), + '?' => userInfo.Append("%3F"), + '#' => userInfo.Append("%23"), + '\\' => userInfo.Append("%5C"), + _ => userInfo.Append(c), + }; + } + + return userInfo.ToString(); + } } diff --git a/src/TermRest.Core/IO/FileChangedException.cs b/src/TermRest.Core/IO/FileChangedException.cs new file mode 100644 index 0000000..874d740 --- /dev/null +++ b/src/TermRest.Core/IO/FileChangedException.cs @@ -0,0 +1,12 @@ +namespace TermRest.Core.IO; + +/// +/// Files that changed on disk since TermRest read them (a git pull, Postman, an editor): saving would undo those +/// changes, so they were not written. Saving again with overwriting allowed writes them anyway. +/// +public sealed class FileChangedException(IReadOnlyList paths) + : IOException($"Changed on disk since TermRest read {(paths.Count == 1 ? "it" : "them")}: {string.Join(", ", paths)}. Saving would undo those changes.") +{ + /// The files that changed (full paths). + public IReadOnlyList Paths { get; } = paths; +} diff --git a/src/TermRest.Core/IO/FileStamp.cs b/src/TermRest.Core/IO/FileStamp.cs new file mode 100644 index 0000000..bef7e84 --- /dev/null +++ b/src/TermRest.Core/IO/FileStamp.cs @@ -0,0 +1,39 @@ +using System.Security.Cryptography; + +namespace TermRest.Core.IO; + +/// +/// What a file held when TermRest last read or wrote it: its length and a hash of its content. Tells whether another +/// program (a git pull, Postman, an editor) changed it since; one that only touched it did not. The content decides +/// also when the file's time is the same: a copy that keeps its time (cp -p, an archive) may hold other content. +/// +internal sealed class FileStamp +{ + private readonly long _length; + private readonly byte[] _hash; + + public FileStamp(ReadOnlySpan content) + { + _length = content.Length; + _hash = SHA256.HashData(content); + } + + /// True when holds other content now, or cannot be read. + public bool HasChanged(string path) + { + try + { + using var stream = TextFile.OpenRead(path); + if (!stream.CanSeek || stream.Length != _length) + { + return true; + } + + return !SHA256.HashData(TextFile.ReadAll(stream, path)).AsSpan().SequenceEqual(_hash); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return true; + } + } +} diff --git a/src/TermRest.Core/IO/RealPath.cs b/src/TermRest.Core/IO/RealPath.cs new file mode 100644 index 0000000..b1ec300 --- /dev/null +++ b/src/TermRest.Core/IO/RealPath.cs @@ -0,0 +1,229 @@ +namespace TermRest.Core.IO; + +/// Paths as the file system follows them: with their symbolic links (on Windows, junctions too) resolved. +public static class RealPath +{ + /// + /// The path of an existing file or folder with every link in it resolved, as realpath(3) gives it; null when it is not + /// there, or its links cannot be read or go round in a loop. + /// + public static string? Of(string path) + { + try + { + var full = Path.GetFullPath(path); + var root = Path.GetPathRoot(full)!; + var (outcome, resolved) = Resolve(root, Names(full[root.Length..]), _ => true); + return outcome == Outcome.Resolved && Path.Exists(resolved) ? resolved : null; // no links left: nothing else is followed + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return null; + } + } + + /// + /// Whether is in also once its links are resolved, as the OS follows + /// them when the file is opened. Nothing outside the folder is looked at: not a path outside it as written, nor where a + /// link that leads out of it goes (on Windows, looking at \\server\share makes Windows sign in to that server with the + /// user's credentials). A path that is not there counts as in the folder: opening it fails. + /// + /// The folder with its own links resolved (), if known. + public static bool IsInside(string path, string folder, string? realFolder = null) + { + try + { + var full = Path.GetFullPath(path); + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)); + if (!IsWithin(full, root)) + { + return false; + } + + var real = realFolder ?? Of(root) ?? root; + + // The folders on the way to it, as written or real, are the user's: a link or a .. may lead through them back in. + bool InReach(string p) => IsWithin(p, real) || IsWithin(real, p) || IsWithin(root, p); + var (outcome, resolved) = Resolve(real, Names(Path.GetRelativePath(root, full)), InReach); + return outcome == Outcome.Resolved && IsWithin(resolved!, real); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + } + + /// + /// Whether opening reaches a network share outside : it is on one + /// (), or a link on the way leads to one, which is not looked at. On Windows, looking at a file + /// there makes Windows sign in to that server with the user's credentials. Never on Linux and macOS. + /// + public static bool ReachesNetwork(string path, string folder) + { + if (!OperatingSystem.IsWindows()) + { + return false; + } + + try + { + var full = Path.GetFullPath(path); + var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)); + bool Local(string p) => !IsNetworkPath(p) || IsWithin(p, root); + if (!Local(full)) + { + return true; + } + + var start = Path.GetPathRoot(full)!; + return Resolve(start, Names(full[start.Length..]), Local).Outcome == Outcome.Stopped; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; // not a path that can be opened + } + } + + /// + /// Whether is on a network share: \\server\share, //server/share, \\?\UNC\server\share, or another + /// device path than a drive's or a volume's (\\?\C:\, \\?\Volume{…}\). Windows only: elsewhere such paths are local. + /// + public static bool IsNetworkPath(string path) + { + if (!OperatingSystem.IsWindows()) + { + return false; + } + + static bool Separator(char c) => c is '\\' or '/'; + var rest = path.AsSpan(); + if (rest.StartsWith(@"\??\", StringComparison.Ordinal)) + { + rest = rest[4..]; + } + else if (rest.Length >= 2 && Separator(rest[0]) && Separator(rest[1])) + { + if (rest.Length < 4 || rest[2] is not ('?' or '.') || !Separator(rest[3])) + { + return true; // \\server\share + } + + rest = rest[4..]; + } + else + { + return false; + } + + // A device path: a drive's or a volume's is local; UNC, GLOBALROOT and the others may not be. + return !((rest.Length >= 2 && char.IsAsciiLetter(rest[0]) && rest[1] == ':') || rest.StartsWith("Volume{", StringComparison.OrdinalIgnoreCase)); + } + + /// Whether is or in it, as they are written (nothing is read). + public static bool IsWithin(string path, string folder) + { + try + { + var relative = Path.GetRelativePath(folder, path); + return relative == "." || (!Path.IsPathRooted(relative) && relative != ".." + && !relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return false; + } + } + + private enum Outcome + { + Resolved, + + /// A path was refused before it was looked at. + Stopped, + + /// A link could not be read, or links go round in a loop. + Unknown, + } + + /// + /// (the first on top) resolved one by one from , a path without + /// links, as the OS resolves a path: a link goes where it leads (an absolute target from its root, a relative one from + /// the link's folder), and a .. to the parent of where the names before it led, not of the path as written. + /// Each path is shown to before it is looked at; a refused one stops the walk. + /// + private static (Outcome Outcome, string? Path) Resolve(string resolved, Stack names, Func mayLookAt) + { + var links = 0; + while (names.TryPop(out var name)) + { + if (name == ".") + { + continue; + } + + if (name == "..") + { + resolved = Path.GetDirectoryName(resolved) ?? resolved; // the root's parent is the root + if (!mayLookAt(resolved)) + { + return (Outcome.Stopped, null); + } + + continue; + } + + var next = Path.Join(resolved, name); + if (!mayLookAt(next)) + { + return (Outcome.Stopped, null); + } + + string? target; + try + { + target = new FileInfo(next).LinkTarget; // the link's own data: where it leads is not looked at + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return (Outcome.Unknown, null); + } + + if (target is null) + { + resolved = next; // not a link, or not there + } + else if (++links > 40 || (Path.IsPathRooted(target) && !Path.IsPathFullyQualified(target))) + { + return (Outcome.Unknown, null); // a loop; or \dir or C:dir, which depend on the current drive or folder + } + else if (Path.IsPathRooted(target)) + { + resolved = Path.GetPathRoot(target)!; + Push(names, target[resolved.Length..]); + } + else + { + Push(names, target); + } + } + + return (Outcome.Resolved, resolved); + } + + private static Stack Names(string path) + { + var names = new Stack(); + Push(names, path); + return names; + } + + /// The names of 's parts onto , the first on top. + private static void Push(Stack names, string path) + { + var parts = path.Split([Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], StringSplitOptions.RemoveEmptyEntries); + for (var i = parts.Length - 1; i >= 0; i--) + { + names.Push(parts[i]); + } + } +} diff --git a/src/TermRest.Core/IO/TextFile.cs b/src/TermRest.Core/IO/TextFile.cs index 85a19f5..642d792 100644 --- a/src/TermRest.Core/IO/TextFile.cs +++ b/src/TermRest.Core/IO/TextFile.cs @@ -10,13 +10,86 @@ public sealed record TextFileInfo(bool HasBom, bool HasTrailingNewline, bool Use public static class TextFile { + /// + /// The largest file TermRest reads: far above real collections (tens of MB with saved examples), it keeps a huge file + /// from exhausting memory. + /// + internal const long MaxSize = 256L * 1024 * 1024; + + private const UnixFileMode ReadPermissions = UnixFileMode.UserRead | UnixFileMode.GroupRead | UnixFileMode.OtherRead; + private const UnixFileMode WritePermissions = UnixFileMode.UserWrite | UnixFileMode.GroupWrite | UnixFileMode.OtherWrite; + + private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + /// + /// Reads a UTF-8 text file; throws for any other encoding, which saving would garble, and + /// for anything that is not a regular file of at most bytes. + /// public static (string Text, TextFileInfo Info) Read(string path) { - var bytes = File.ReadAllBytes(path); + using var stream = OpenRead(path); + return Decode(path, ReadAll(stream, path)); + } + + /// Like , and tells what the file held, to find out later whether another program changed it. + internal static (string Text, TextFileInfo Info) Read(string path, out FileStamp stamp) + { + using var stream = OpenRead(path); + var bytes = ReadAll(stream, path); + stamp = new FileStamp(bytes); + return Decode(path, bytes); + } + + internal static FileStream OpenRead(string path) => new(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 0); + + /// + /// The content of a regular file. A device or a pipe (which a symbolic link in a cloned repository can point at, such + /// as /dev/zero or /dev/stdin) and a file over are refused: reading them would never end, block, + /// or exhaust memory. + /// + internal static byte[] ReadAll(FileStream stream, string path) + { + if (!stream.CanSeek) + { + throw new IOException($"'{path}' is not a regular file."); + } + + var length = stream.Length; + if (length > MaxSize) + { + throw new IOException($"'{path}' is too large ({length / (1024 * 1024)} MB; TermRest reads files of up to {MaxSize / (1024 * 1024)} MB)."); + } + + var bytes = new byte[length]; + stream.ReadExactly(bytes); + if (stream.ReadByte() >= 0) + { + // Devices such as /dev/zero report no length. + throw new IOException($"'{path}' is not a regular file, or it grew while it was read."); + } + + return bytes; + } + + private static (string Text, TextFileInfo Info) Decode(string path, byte[] bytes) + { var hasBom = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF; var offset = hasBom ? 3 : 0; - var text = Encoding.UTF8.GetString(bytes, offset, bytes.Length - offset); - var usesCrLf = text.Contains("\r\n", StringComparison.Ordinal); + string text; + try + { + text = StrictUtf8.GetString(bytes, offset, bytes.Length - offset); + } + catch (DecoderFallbackException ex) + { + var line = 1 + bytes.AsSpan(offset, Math.Clamp(ex.Index, 0, bytes.Length - offset)).Count((byte)'\n'); + throw new IOException($"'{path}' is not UTF-8 text (line {line}); convert it to UTF-8.", ex); + } + + // CRLF only when most line breaks are: saving writes one kind, so a line whose break differs (one a Windows editor + // wrote in an LF file, say) is the only line that changes. + var crlf = text.AsSpan().Count("\r\n"); + var usesCrLf = crlf > text.AsSpan().Count('\n') - crlf; var trailingNewline = text.EndsWith('\n'); return (text, new TextFileInfo(hasBom, trailingNewline, usesCrLf)); } @@ -27,7 +100,25 @@ public static (string Text, TextFileInfo Info) Read(string path) /// and keeps the replaced file's identity: symbolic links are written through, Unix permissions are copied /// (environment and certificate files may hold secrets) and Windows ACLs survive via . /// - public static void WriteAtomic(string path, string text, TextFileInfo? info = null) + /// + /// On Unix, the permissions of the file when it is new, from its first byte (see ); null: the + /// default (0666 minus the umask). A file that exists keeps its own. + /// + public static void WriteAtomic(string path, string text, TextFileInfo? info = null, UnixFileMode? newFileMode = null) => + Write(path, text, info, newFileMode, stamp: false); + + /// + /// Like , and tells what the file holds now, to + /// find out later whether another program changed it. + /// + internal static void WriteAtomic(string path, string text, TextFileInfo? info, out FileStamp stamp, UnixFileMode? newFileMode = null) => + stamp = Write(path, text, info, newFileMode, stamp: true)!; + + /// + /// (LF line endings, no trailing newline) as + /// writes it, but for the byte order mark: with the line endings and trailing newline of . + /// + public static string AsWritten(string text, TextFileInfo? info) { info ??= TextFileInfo.PostmanDefault; if (info.UsesCrLf) @@ -35,30 +126,73 @@ public static void WriteAtomic(string path, string text, TextFileInfo? info = nu text = text.Replace("\n", "\r\n", StringComparison.Ordinal); } - if (info.HasTrailingNewline) + return info.HasTrailingNewline ? text + (info.UsesCrLf ? "\r\n" : "\n") : text; + } + + /// + /// On Unix, the permissions for a file made from (an imported or converted copy): its read and + /// write permissions, so that a private (chmod 600) file stays private. Null on Windows, where a new file inherits the + /// access rules of its folder as copies do, and when does not exist. + /// + public static UnixFileMode? CopyMode(string source) + { + if (OperatingSystem.IsWindows() || !Path.Exists(source)) { - text += info.UsesCrLf ? "\r\n" : "\n"; + return null; } + return File.GetUnixFileMode(source) & (ReadPermissions | WritePermissions); + } + + /// + /// The permissions for a folder of files with : whoever may read them may enter it, and its + /// owner may always add files. + /// + internal static UnixFileMode FolderMode(UnixFileMode fileMode) => + fileMode | (UnixFileMode)((int)(fileMode & ReadPermissions) >> 2) | UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; + + private static FileStamp? Write(string path, string text, TextFileInfo? info, UnixFileMode? newFileMode, bool stamp) + { + info ??= TextFileInfo.PostmanDefault; + text = AsWritten(text, info); + + var encoding = new UTF8Encoding(info.HasBom); + var preamble = encoding.GetPreamble(); + var bytes = new byte[preamble.Length + encoding.GetByteCount(text)]; + preamble.CopyTo(bytes, 0); + encoding.GetBytes(text, bytes.AsSpan(preamble.Length)); + var fullPath = ResolveLinks(Path.GetFullPath(path)); var directory = Path.GetDirectoryName(fullPath)!; Directory.CreateDirectory(directory); var exists = File.Exists(fullPath); var temp = Path.Combine(directory, $".{Path.GetFileName(fullPath)}.{Guid.NewGuid():N}.tmp"); + var written = false; try { - var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write }; + var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, BufferSize = 0 }; UnixFileMode? mode = null; - if (exists && !OperatingSystem.IsWindows()) + if (!OperatingSystem.IsWindows()) { - // Create the temp file with the original permissions so a 0600 secrets file is never world-readable. - mode = File.GetUnixFileMode(fullPath); + // Create the temp file with its final permissions (the original file's, or those asked for a new one) so a + // 0600 secrets file is never world-readable. + mode = exists ? File.GetUnixFileMode(fullPath) : newFileMode; options.UnixCreateMode = mode; } - using (var writer = new StreamWriter(temp, new UTF8Encoding(info.HasBom), options)) + using (var stream = new FileStream(temp, options)) { - writer.Write(text); + stream.Write(bytes); + if (exists) + { + stream.Flush(flushToDisk: true); // a power loss right after the replace must not leave an empty file + } + } + + written = true; + if (mode is { } unixMode && !OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(temp, unixMode); // the create mode is subject to the umask } if (!exists) @@ -67,25 +201,24 @@ public static void WriteAtomic(string path, string text, TextFileInfo? info = nu } else { - if (mode is { } unixMode && !OperatingSystem.IsWindows()) - { - File.SetUnixFileMode(temp, unixMode); // the create mode is subject to the umask - } - try { File.Replace(temp, fullPath, destinationBackupFileName: null, ignoreMetadataErrors: true); } - catch (IOException) when (OperatingSystem.IsWindows() && File.Exists(temp) && File.Exists(fullPath)) + catch (IOException) when (File.Exists(temp) && (OperatingSystem.IsWindows() || !File.Exists(fullPath))) { - // Some file systems (certain network shares and sync drivers) lack ReplaceFile; overwrite instead. + // Some file systems (certain network shares and sync drivers) lack ReplaceFile; overwrite instead. This + // also completes a ReplaceFile that failed after removing the original: the content is in the temp file. File.Move(temp, fullPath, overwrite: true); } } + + return stamp ? new FileStamp(bytes) : null; } finally { - if (File.Exists(temp)) + // Never delete the only copy of the content: the temp file stays when a failed replace removed the original. + if (File.Exists(temp) && !(written && exists && !File.Exists(fullPath))) { File.Delete(temp); } diff --git a/src/TermRest.Core/Import/CurlImporter.cs b/src/TermRest.Core/Import/CurlImporter.cs index 7497d10..5a5e65a 100644 --- a/src/TermRest.Core/Import/CurlImporter.cs +++ b/src/TermRest.Core/Import/CurlImporter.cs @@ -67,7 +67,11 @@ public static class CurlImporter "--user", "--user-agent", "--variable", "--vlan-priority", "--write-out", }; - /// Options that only affect curl's own output, progress or retries: nothing to import, nothing to report. + /// + /// Options that only affect curl's own output, progress or retries, or that TermRest's own redirect rules cover (it + /// follows redirects, changes the method as browsers do, and never follows one from https to http): nothing to + /// import, nothing to report. + /// private static readonly HashSet QuietlyIgnored = new(StringComparer.Ordinal) { "--compressed", "--create-dirs", "--disable", "--dump-header", "--fail", "--fail-early", "--fail-with-body", @@ -79,7 +83,7 @@ public static class CurlImporter "--sslv2", "--sslv3", "--stderr", "--styled-output", "--no-styled-output", "--tcp-fastopen", "--tcp-nodelay", "--tlsv1", "--tlsv1.0", "--tlsv1.1", "--tlsv1.2", "--tlsv1.3", "--trace", "--trace-ascii", "--trace-config", "--trace-ids", "--trace-time", "--verbose", "--write-out", "--xattr", "--clobber", "--no-clobber", - "--remove-on-error", "--skip-existing", "--post301", "--post302", "--post303", "--proxy-insecure", + "--remove-on-error", "--skip-existing", "--post301", "--post302", "--post303", "--proto-redir", "--proxy-insecure", "--suppress-connect-headers", "--keepalive-time", "--keepalive-cnt", "--rate", "--cookie-jar", "--basic", }; @@ -143,7 +147,10 @@ private sealed class ParsedCommand public int? MaxRedirects { get; set; } } - /// True when the text starts like a curl command (optionally after a shell prompt). + /// + /// True when the text starts like a curl command (optionally after a shell prompt, or after comment lines such as the + /// notes above a command TermRest exports). + /// public static bool LooksLikeCurl(string? text) { if (string.IsNullOrWhiteSpace(text)) @@ -151,9 +158,12 @@ public static bool LooksLikeCurl(string? text) return false; } - var start = StripPrompt(text.TrimStart()).TrimStart('&', ' '); + var start = SkipCommentLines(text); + start = StripPrompt(start).TrimStart('&', ' '); var end = start.IndexOfAny([' ', '\t', '\r', '\n']); - return IsCurlProgram(end < 0 ? start : start[..end]); + + // The program, then something to import: a URL whose path ends in /curl is a URL. + return end > 0 && IsCurlProgram(start[..end]) && start[end..].Trim().Length > 0; } /// @@ -175,8 +185,9 @@ public static CurlImportResult Import(string command) { ArgumentNullException.ThrowIfNull(command); - // Terminals and clipboards deliver line breaks as CR, LF or CRLF. - var text = TrimDanglingContinuation(StripPrompt(command.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Trim())); + // Terminals and clipboards deliver line breaks as CR, LF or CRLF. Comment lines above the command (the notes TermRest's + // export writes) come before a prompt to strip, as LooksLikeCurl has them. + var text = TrimDanglingContinuation(StripPrompt(SkipCommentLines(command.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n')).Trim())); var warnings = new List(); var dialect = ShellWords.Detect(text); var args = ShellWords.Split(text, dialect, warnings); @@ -354,6 +365,11 @@ private static void HandleOption(ParsedCommand p, string name, string value, Lis case "--upload-file": p.UploadFile = value; break; + case "--max-redirs" when int.TryParse(value, out var max) && max < 0: + // curl's -1: no limit, which TermRest has not. The request then keeps the workspace's limit. + p.MaxRedirects = null; + warnings.Add($"{name} {value}: curl follows any number of redirects; TermRest follows up to the workspace's maximum (Tools > Settings)."); + break; case "--max-redirs" when int.TryParse(value, out var max): p.MaxRedirects = max; break; @@ -434,6 +450,12 @@ private static CurlImportResult Build(ParsedCommand p, ShellDialect dialect, Lis warnings.Add($"Only the URL {url} was imported; curl was given {p.Urls.Count} URLs."); } + // The file of -T is the body only without -F and -d; curl names it in the URL before adding --url-query. + if (p is { UploadFile: { } uploaded and not ("-" or "."), Forms.Count: 0, Data.Count: 0 }) + { + url = UploadUrl(url, uploaded); + } + foreach (var query in p.UrlQueries) { if (EncodeUrlencodePart(query, warnings) is { } encoded) @@ -464,7 +486,9 @@ private static CurlImportResult Build(ParsedCommand p, ShellDialect dialect, Lis } else if (p.Data.Count > 0) { - BuildDataBody(spec, p.Data, warnings); + // -H 'Content-Type:' drops curl's default type (TermRest's own cURL export writes it for a body-less POST). + var noDefaultType = p.Headers.Any(h => h.Split(':', 2) is [var name, var value] && name.Trim().Equals("Content-Type", StringComparison.OrdinalIgnoreCase) && value.Trim().Length == 0); + BuildDataBody(spec, p.Data, warnings, noDefaultType); hasBody = true; } else if (p.UploadFile is { } upload) @@ -534,12 +558,13 @@ private static void AddHeader(HttpRequestSpec spec, string header, List warnings.Add($"The header '{header}' has no ':' and was ignored."); } - private static void BuildDataBody(HttpRequestSpec spec, List<(DataKind Kind, string Value)> data, List warnings) + /// The command drops curl's default Content-Type: none is added. + private static void BuildDataBody(HttpRequestSpec spec, List<(DataKind Kind, string Value)> data, List warnings, bool noDefaultType) { var contentType = spec.Headers.LastOrDefault(h => h.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase))?.Value; var mediaType = contentType?.Split(';')[0].Trim().ToLowerInvariant(); - if (data is [{ Kind: DataKind.Ascii or DataKind.Binary } single] && single.Value.StartsWith('@')) + if (data is [{ Kind: DataKind.Ascii or DataKind.Binary or DataKind.Json } single] && single.Value.StartsWith('@')) { var path = single.Value[1..]; if (path == "-") @@ -554,9 +579,14 @@ private static void BuildDataBody(HttpRequestSpec spec, List<(DataKind Kind, str warnings.Add($"curl -d @{path} strips line breaks from the file; TermRest sends it unchanged (like --data-binary)."); } - if (contentType is null) + if (contentType is null && !noDefaultType) { - spec.Headers.Add(new KeyValueEntry { Key = "Content-Type", Value = "application/x-www-form-urlencoded" }); + spec.Headers.Add(new KeyValueEntry { Key = "Content-Type", Value = single.Kind == DataKind.Json ? "application/json" : "application/x-www-form-urlencoded" }); + } + + if (single.Kind == DataKind.Json && !spec.Headers.Any(h => h.Key.Equals("Accept", StringComparison.OrdinalIgnoreCase))) + { + spec.Headers.Add(new KeyValueEntry { Key = "Accept", Value = "application/json" }); } return; @@ -564,6 +594,11 @@ private static void BuildDataBody(HttpRequestSpec spec, List<(DataKind Kind, str if (data.Any(d => d.Kind == DataKind.Json)) { + foreach (var (_, value) in data.Where(d => d.Kind is DataKind.Ascii or DataKind.Binary or DataKind.Json && d.Value.StartsWith('@'))) + { + warnings.Add($"The data file '{value[1..]}' cannot be combined with other data; its name was kept as text."); + } + spec.Body = new RequestBody { Mode = BodyMode.Raw, RawLanguage = "json", Raw = string.Concat(data.Select(d => d.Value)) }; if (!spec.Headers.Any(h => h.Key.Equals("Accept", StringComparison.OrdinalIgnoreCase))) { @@ -590,7 +625,10 @@ _ when mediaType.Contains("javascript", StringComparison.Ordinal) => "javascript _ => "text", }; spec.Body = new RequestBody { Mode = BodyMode.Raw, Raw = text, RawLanguage = language }; - if (contentType is null) + + // Empty data is sent as no body (Content-Length: 0 for a POST), without a type: one added would be left out, with a + // warning, at every send. + if (contentType is null && !noDefaultType && text.Length > 0) { if (language == "json") { @@ -603,7 +641,7 @@ _ when mediaType.Contains("javascript", StringComparison.Ordinal) => "javascript } } - /// Reads data that is entirely name=value pairs into urlencoded fields (values decoded, as Postman stores them). + /// Reads data that is entirely name=value pairs, with UTF-8 escapes, into urlencoded fields (values decoded, as Postman stores them). private static bool TryReadFields(List<(DataKind Kind, string Value)> data, out List fields) { fields = []; @@ -639,7 +677,16 @@ private static bool TryReadFields(List<(DataKind Kind, string Value)> data, out return false; } - fields.Add(new KeyValueEntry { Key = WebUtility.UrlDecode(pair[..equals]), Value = WebUtility.UrlDecode(pair[(equals + 1)..]) }); + // An escape that isn't UTF-8 (%F6 for ö, from a page in windows-1252) decodes to U+FFFD, which would be sent + // as %EF%BF%BD: such data is kept as typed. + var key = WebUtility.UrlDecode(pair[..equals]); + var decoded = WebUtility.UrlDecode(pair[(equals + 1)..]); + if (key.AsSpan().Count('\uFFFD') + decoded.AsSpan().Count('\uFFFD') > pair.AsSpan().Count('\uFFFD')) + { + return false; + } + + fields.Add(new KeyValueEntry { Key = key, Value = decoded }); } } @@ -774,11 +821,19 @@ private static (string Value, string? Type, string? FileName) ParseFormValue(str string? fileName = null; while (position < s.Length && s[position] == ';') { - var next = FindFormParameter(s, position + 1); + var afterType = type is not null || s.AsSpan(position + 1).TrimStart().StartsWith("type=", StringComparison.OrdinalIgnoreCase); + var next = FindFormParameter(s, position + 1, afterType); var part = next < 0 ? s[(position + 1)..] : s[(position + 1)..next]; var equals = part.IndexOf('=', StringComparison.Ordinal); var key = (equals < 0 ? part : part[..equals]).Trim().ToLowerInvariant(); - var parameter = equals < 0 ? "" : part[(equals + 1)..].Trim().Trim('"'); + + // Unquoted only when quoted as a whole: a type keeps the quotes of its parameters (charset="utf-8"). + var parameter = equals < 0 ? "" : part[(equals + 1)..].Trim(); + if (parameter is ['"', .., '"']) + { + parameter = parameter[1..^1]; + } + if (key == "type") { type = parameter; @@ -794,12 +849,13 @@ private static (string Value, string? Type, string? FileName) ParseFormValue(str return (value, type, fileName); } - private static int FindFormParameter(string s, int from) + /// From within the type, where curl reads a type= as part of it (application/atom+xml; type=entry). + private static int FindFormParameter(string s, int from, bool afterType = false) { for (var i = s.IndexOf(';', from); i >= 0; i = s.IndexOf(';', i + 1)) { var rest = s.AsSpan(i + 1).TrimStart(); - if (rest.StartsWith("type=", StringComparison.OrdinalIgnoreCase) || rest.StartsWith("filename=", StringComparison.OrdinalIgnoreCase) + if ((!afterType && rest.StartsWith("type=", StringComparison.OrdinalIgnoreCase)) || rest.StartsWith("filename=", StringComparison.OrdinalIgnoreCase) || rest.StartsWith("headers=", StringComparison.OrdinalIgnoreCase) || rest.StartsWith("encoder=", StringComparison.OrdinalIgnoreCase)) { return i; @@ -934,6 +990,18 @@ private static (string Path, string? Password) SplitCertificatePassword(string v // ----- helpers ----------------------------------------------------------------------------- + /// The text from its first line that isn't a # comment (white space before it left out). + private static string SkipCommentLines(string text) + { + var start = text.TrimStart(); + while (start.StartsWith('#') && start.IndexOfAny(['\r', '\n']) is var lineEnd and > 0) + { + start = start[lineEnd..].TrimStart(); + } + + return start; + } + private static string StripPrompt(string text) { if (text.StartsWith("$ ", StringComparison.Ordinal) || text.StartsWith("> ", StringComparison.Ordinal)) @@ -955,6 +1023,11 @@ private static string StripPrompt(string text) private static bool IsCurlProgram(string word) { + if (word.Contains("://", StringComparison.Ordinal) || word.StartsWith("{{", StringComparison.Ordinal)) + { + return false; // a URL (https://api.github.com/repos/curl/curl), not a path to the program + } + var name = word[(word.LastIndexOfAny(['/', '\\']) + 1)..]; return name.Equals("curl", StringComparison.OrdinalIgnoreCase) || name.Equals("curl.exe", StringComparison.OrdinalIgnoreCase); } @@ -997,6 +1070,32 @@ private static string AppendQuery(string url, string query) return head + separator + query + fragment; } + /// + /// The URL curl uploads to (-T): one whose path is empty or ends with '/' gets the file's name + /// (after its last '/' or '\', percent-encoded), unless it has a query. Without a path, a {{variable}} may hold one: + /// such a URL is kept as it is. + /// + private static string UploadUrl(string url, string file) + { + var name = file[(file.LastIndexOfAny(['/', '\\']) + 1)..]; + var hash = PostmanUrl.IndexOutsideBraces(url, '#'); + var head = hash < 0 ? url : url[..hash]; + var question = PostmanUrl.IndexOutsideBraces(head, '?'); + if (name.Length == 0 || (question >= 0 && question < head.Length - 1)) + { + return url; + } + + var path = question < 0 ? head : head[..question]; // curl drops an empty query + var pathStart = PostmanUrl.PathStart(path); + if (pathStart < 0 ? path.Contains("{{", StringComparison.Ordinal) : !path.EndsWith('/')) + { + return url; + } + + return path + (pathStart < 0 ? "/" : "") + Uri.EscapeDataString(name) + (hash < 0 ? "" : url[hash..]); + } + /// The URL path without its leading slash (v1/items), so the request is addressable as Folder/v1/items. private static string SuggestName(string url) { @@ -1008,8 +1107,20 @@ private static string SuggestName(string url) name = "Imported request"; } - return name.Length > 60 ? name[..59] + "…" : name; + return Cut(name, 60); } - private static string Shorten(string text) => text.Length > 40 ? text[..39] + "…" : text; + private static string Shorten(string text) => Cut(text, 40); + + /// cut to characters, the last one "…"; a surrogate pair stays whole. + private static string Cut(string text, int length) + { + if (text.Length <= length) + { + return text; + } + + var keep = char.IsHighSurrogate(text[length - 2]) ? length - 2 : length - 1; + return text[..keep] + "…"; + } } diff --git a/src/TermRest.Core/Import/ShellWords.cs b/src/TermRest.Core/Import/ShellWords.cs index b21aff6..0835900 100644 --- a/src/TermRest.Core/Import/ShellWords.cs +++ b/src/TermRest.Core/Import/ShellWords.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Text; namespace TermRest.Core.Import; @@ -20,25 +21,39 @@ public enum ShellDialect /// public static class ShellWords { - /// Guesses the shell from continuation characters and Windows-only escapes; defaults to POSIX. + /// + /// Guesses the shell from continuation characters and Windows-only escapes outside quoted values (see + /// and ); defaults to POSIX. + /// public static ShellDialect Detect(string text) { - if (HasContinuation(text, '`')) + var marks = FindMarks(text); + if (marks.Backtick) { return ShellDialect.PowerShell; } - if (text.Contains("^\"", StringComparison.Ordinal) || HasContinuation(text, '^')) + if (marks.CaretQuote || marks.Caret) { return ShellDialect.Cmd; } - if (HasContinuation(text, '\\')) + if (marks.Backslash) { return ShellDialect.Posix; } + if (HasPowerShellContinuation(text)) + { + return ShellDialect.PowerShell; + } + var start = text.TrimStart(); + if (start.StartsWith('&')) + { + return ShellDialect.PowerShell; // the call operator: & curl.exe … + } + if (start.StartsWith("curl.exe", StringComparison.OrdinalIgnoreCase)) { return start.Contains('\'', StringComparison.Ordinal) ? ShellDialect.PowerShell : ShellDialect.Cmd; @@ -60,13 +75,99 @@ public static ShellDialect Detect(string text) _ => SplitPosix(text, notes), }; - private static bool HasContinuation(string text, char escape) + /// + /// Which of `, ^ and \ end a line, and whether a word starts with ^" (Chrome's cmd quoting, + /// curl ^"https://…^"), outside quoted values, which say nothing about the shell: '…' (PowerShell's '' inside one + /// ends it and starts another), $'…' (where \ escapes the next character) and "…" (where \ and ` do). Outside them, \, ^ + /// and ` escape the next character, so \' and ^" start no quoted value, and a # that starts a word starts a comment. + /// + private static (bool Backtick, bool Caret, bool Backslash, bool CaretQuote) FindMarks(string text) { - for (var i = text.IndexOf(escape, StringComparison.Ordinal); i >= 0; i = text.IndexOf(escape, i + 1)) + bool backtick = false, caret = false, backslash = false, caretQuote = false; + for (var i = 0; i < text.Length; i++) { - if (NewlineLength(text, i + 1) > 0) + var wordStart = i == 0 || IsBlank(text[i - 1]); + switch (text[i]) { - return true; + case '`' or '^' or '\\': + if (NewlineLength(text, i + 1) > 0) + { + backtick |= text[i] == '`'; + caret |= text[i] == '^'; + backslash |= text[i] == '\\'; + } + + caretQuote |= text[i] == '^' && wordStart && i + 1 < text.Length && text[i + 1] == '"'; + i++; + break; + case '\'': + i = QuotedEnd(text, i + 1, '\'', ""); + break; + case '$' when i + 1 < text.Length && text[i + 1] == '\'': + i = QuotedEnd(text, i + 2, '\'', "\\"); + break; + case '"': + i = QuotedEnd(text, i + 1, '"', "\\`"); + break; + case '#' when wordStart: + while (i + 1 < text.Length && text[i + 1] != '\n') + { + i++; + } + + break; + } + } + + return (backtick, caret, backslash, caretQuote); + } + + /// Where the quoted value whose text starts at ends: its closing quote, or the end of the text. + private static int QuotedEnd(string text, int i, char quote, string escapes) + { + for (; i < text.Length && text[i] != quote; i++) + { + if (escapes.Contains(text[i], StringComparison.Ordinal)) + { + i++; + } + } + + return i; + } + + /// + /// Whether a ` ends a line outside quoted values as PowerShell reads them: '…' ('' inside one ends it and starts another) + /// and "…", where only ` escapes. A \ before the closing quote is a character there ("C:\temp\"), where + /// takes the value for one that goes on, past the ` that ends its line. + /// + private static bool HasPowerShellContinuation(string text) + { + for (var i = 0; i < text.Length; i++) + { + switch (text[i]) + { + case '`': + if (NewlineLength(text, i + 1) > 0) + { + return true; + } + + i++; + break; + case '\'': + i = QuotedEnd(text, i + 1, '\'', ""); + break; + case '"': + i = QuotedEnd(text, i + 1, '"', "`"); + break; + case '#' when i == 0 || IsBlank(text[i - 1]): + while (i + 1 < text.Length && text[i + 1] != '\n') + { + i++; + } + + break; } } @@ -289,6 +390,13 @@ private static int AppendCodePoint(string s, int i, int maxDigits, int radix, St { word.Append(literalIfEmpty); } + else if (value is >= 0xD800 and <= 0xDBFF && maxDigits == 4 && i + 6 <= s.Length && s[i] == '\\' && s[i + 1] == 'u' + && int.TryParse(s.AsSpan(i + 2, 4), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var low) && low is >= 0xDC00 and <= 0xDFFF) + { + // Browsers escape text one UTF-16 unit at a time, so an emoji arrives as a surrogate pair: \ud83d\ude00. + word.Append((char)value).Append((char)low); + i += 6; + } else if (value is >= 0 and <= 0x10FFFF and not (>= 0xD800 and <= 0xDFFF)) { word.Append(char.ConvertFromUtf32(value)); diff --git a/src/TermRest.Core/Json/PostmanJson.cs b/src/TermRest.Core/Json/PostmanJson.cs index a5acbf9..c59bea5 100644 --- a/src/TermRest.Core/Json/PostmanJson.cs +++ b/src/TermRest.Core/Json/PostmanJson.cs @@ -14,6 +14,10 @@ public static class PostmanJson AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip, MaxDepth = 256, + + // A key written twice (a merge conflict resolved by keeping both lines) is a JsonException, reported as a load + // error, rather than an exception on first access. + AllowDuplicateProperties = false, }; private static readonly JsonWriterOptions FileWriterOptions = new() @@ -43,8 +47,26 @@ public static class PostmanJson MaxDepth = 256, }; - public static JsonNode Parse(string json) => - JsonNode.Parse(json, nodeOptions: default, DocumentOptions) ?? throw new JsonException("The JSON document is empty."); + /// + /// Parses a file's JSON (comments and trailing commas allowed). A key written twice and half of a surrogate pair + /// ("\ud83d") are a here rather than an exception on first access to the value. + /// + public static JsonNode Parse(string json) + { + JsonNode? node; + try + { + node = JsonNode.Parse(json, nodeOptions: default, DocumentOptions); + } + catch (JsonException ex) when (ex.Message.Contains("is an invalid JSON literal", StringComparison.Ordinal)) + { + // That message quotes the rest of the text, values (secrets) included. + throw new JsonException($"Invalid JSON at line {ex.LineNumber + 1}: expected true, false or null.", ex.Path, ex.LineNumber, ex.BytePositionInLine); + } + + ThrowIfUnpairedSurrogate(json); + return node ?? throw new JsonException("The JSON document is empty."); + } /// Serializes a node in Postman's on-disk style. No trailing newline is appended. public static string Serialize(JsonNode node) => Write(node, FileWriterOptions); @@ -63,10 +85,102 @@ public static JsonNode Parse(string json) => var node = JsonNode.Parse(text, nodeOptions: default, new JsonDocumentOptions { MaxDepth = 256 }); return node is null ? "null" : SerializeForDisplay(node); } - catch (JsonException) + catch (Exception ex) when (ex is JsonException or InvalidOperationException) { - return null; + return null; // InvalidOperationException: a string holds half of a surrogate pair ("\ud83d") + } + } + + /// + /// Throws a naming the position of a \uXXXX escape in a string of + /// (valid JSON) that is half of a surrogate pair, as JavaScript writes half of an emoji cut in + /// two: System.Text.Json reads it, then throws on first access to the string. + /// + private static void ThrowIfUnpairedSurrogate(string json) + { + // Text read as UTF-8 cannot hold one otherwise: only escapes of \uD800 to \uDFFF need a closer look. + if (!HasSurrogateEscape(json)) + { + return; } + + var line = 1; + var lineStart = 0; + for (var i = 0; i < json.Length; i++) + { + switch (json[i]) + { + case '\n': + line++; + lineStart = i + 1; + break; + case '/' when i + 1 < json.Length && json[i + 1] == '/': + while (i + 1 < json.Length && json[i + 1] != '\n') + { + i++; + } + + break; + case '/' when i + 1 < json.Length && json[i + 1] == '*': + for (i += 2; i + 1 < json.Length && !(json[i] == '*' && json[i + 1] == '/'); i++) + { + if (json[i] == '\n') + { + line++; + lineStart = i + 1; + } + } + + i++; + break; + case '"': + // Strings cannot hold line breaks; an escaped character is skipped with its backslash. + for (i++; json[i] != '"'; i++) + { + if (json[i] != '\\') + { + continue; + } + + if (json[i + 1] != 'u') + { + i++; + continue; + } + + var unit = (char)int.Parse(json.AsSpan(i + 2, 4), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); + if (char.IsHighSurrogate(unit) && json.AsSpan(i + 6).StartsWith("\\u", StringComparison.Ordinal) + && char.IsLowSurrogate((char)int.Parse(json.AsSpan(i + 8, 4), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture))) + { + i += 11; + } + else if (char.IsSurrogate(unit)) + { + throw new JsonException( + $"Unpaired surrogate \"{json.AsSpan(i, 6)}\" at line {line}, column {i - lineStart + 1} (half of a character, such as an emoji cut in two): remove it, or add its other half."); + } + else + { + i += 5; + } + } + + break; + } + } + } + + private static bool HasSurrogateEscape(string json) + { + for (var i = json.IndexOf("\\u", StringComparison.Ordinal); i >= 0; i = json.IndexOf("\\u", i + 2, StringComparison.Ordinal)) + { + if (i + 3 < json.Length && json[i + 2] is 'd' or 'D' && json[i + 3] is >= '8' and <= '9' or >= 'a' and <= 'f' or >= 'A' and <= 'F') + { + return true; + } + } + + return false; } private static string Write(JsonNode node, JsonWriterOptions options) diff --git a/src/TermRest.Core/Model/AuthSpec.cs b/src/TermRest.Core/Model/AuthSpec.cs index af5f52d..9b606d1 100644 --- a/src/TermRest.Core/Model/AuthSpec.cs +++ b/src/TermRest.Core/Model/AuthSpec.cs @@ -24,6 +24,12 @@ public sealed class AuthParam public AuthParam Clone() => new() { Key = Key, Value = Value?.DeepClone(), Type = Type, Source = Source }; } +/// +/// One credential set of a v3 collection's or folder's auth: its name, the rules that select it (key and value; Postman +/// writes url rules, whose value is a URL pattern) and its auth (null: none). +/// +public sealed record CredentialSet(string Name, IReadOnlyList> Rules, AuthSpec? Auth); + /// Postman auth block. A missing block (null spec) means "inherit from parent". public sealed class AuthSpec { @@ -36,6 +42,13 @@ public sealed class AuthSpec public JsonObject? Source { get; set; } + /// + /// The credential sets of a v3 collection's or folder's auth, chosen by URL rules: a request uses the first whose rules + /// all match its URL (see ). This auth is the first set, as shown. Null for one auth. + /// Kept in memory only: auth written to JSON (history entries, collections) never holds them. + /// + public IReadOnlyList? CredentialSets { get; set; } + public string? Get(string key) => Params.FirstOrDefault(p => p.Key == key)?.ValueAsString; public void Set(string key, string? value) @@ -51,7 +64,7 @@ public void Set(string key, string? value) } } - public AuthSpec Clone() => new() { Type = Type, Params = Params.Select(p => p.Clone()).ToList(), Source = Source }; + public AuthSpec Clone() => new() { Type = Type, Params = Params.Select(p => p.Clone()).ToList(), Source = Source, CredentialSets = CredentialSets }; public bool ContentEquals(AuthSpec? other) { diff --git a/src/TermRest.Core/Postman/CollectionNodes.cs b/src/TermRest.Core/Postman/CollectionNodes.cs index 0881e84..e527891 100644 --- a/src/TermRest.Core/Postman/CollectionNodes.cs +++ b/src/TermRest.Core/Postman/CollectionNodes.cs @@ -61,8 +61,23 @@ internal FolderNode(PostmanCollection collection, JsonObject json, FolderNode? p public List Children { get; } = []; - /// Folder-level auth; null means inherit. - public AuthSpec? Auth => PostmanRequestMapper.ReadAuth(Json["auth"], Collection.SchemaVersion); + /// Folder-level auth; null means inherit. A v3 folder's credential sets come with it (see ). + public AuthSpec? Auth + { + get + { + var auth = PostmanRequestMapper.ReadAuth(Json["auth"], Collection.SchemaVersion); + if (auth is not null && Json[V3.V3Convert.AuthSetsProperty] is JsonArray sets) + { + auth.CredentialSets = [.. sets.OfType().Select(set => new CredentialSet( + set["name"].GetString() ?? "", + [.. (set["rules"] as JsonArray ?? []).OfType().Select(rule => KeyValuePair.Create(rule["key"].GetString() ?? "", rule["value"].GetString() ?? ""))], + PostmanRequestMapper.ReadAuth(set["auth"], Collection.SchemaVersion)))]; + } + + return auth; + } + } internal JsonArray EnsureItemArray() { diff --git a/src/TermRest.Core/Postman/PostmanCollection.cs b/src/TermRest.Core/Postman/PostmanCollection.cs index 6fcd72a..26446e3 100644 --- a/src/TermRest.Core/Postman/PostmanCollection.cs +++ b/src/TermRest.Core/Postman/PostmanCollection.cs @@ -19,6 +19,9 @@ public sealed class PostmanCollection private ICollectionStorage? _storage; + /// What the JSON file held when last read or written (see ). + private FileStamp? _stamp; + private PostmanCollection(JsonObject root, string? filePath, TextFileInfo fileInfo) { Root = root; @@ -48,6 +51,13 @@ private PostmanCollection(JsonObject root, string? filePath, TextFileInfo fileIn /// Problems found while loading (files that could not be read, items that are not shown). public List LoadWarnings { get; } = []; + /// + /// Whether files of the collection could not be read (their warnings are in ): it may lack + /// requests, or the auth, variables and scripts of a definition. The note about non-HTTP requests that are not shown is + /// no such problem. + /// + public bool HasUnreadableFiles { get; internal set; } + /// /// For a v3 collection: the column at which new and changed values are wrapped when saving (0: never); null (the /// default) follows the collection's files. See . JSON @@ -96,10 +106,12 @@ public static PostmanCollection Load(string path) return V3CollectionStorage.Load(path); } - var (text, info) = TextFile.Read(path); + var (text, info) = TextFile.Read(path, out var stamp); try { - return Parse(text, path, info); + var collection = Parse(text, path, info); + collection._stamp = stamp; + return collection; } catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidDataException) { @@ -147,10 +159,24 @@ 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). + /// 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); + /// + /// The secret variables (of the collection and its folders) whose values leaves out: Postman's + /// v3 collections keep secret values out of their files. + /// + public List SecretValuesLeftOutOfV3() => IsV3 ? [] : V3Convert.SecretValuesLeftOut(Root); + + /// + /// The collection and folders whose auth is a list of v3 credential sets chosen by URL rules: + /// keeps the first set only (v2.1 has one auth per folder), which Postman then applies to every URL. + /// + 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). public string ExportV21Json() { @@ -170,6 +196,7 @@ static void RemoveV3Markers(JsonNode? node) { case JsonObject obj: obj.Remove("x-v3-type"); + obj.Remove(V3.V3Convert.AuthSetsProperty); // v2.1 has one auth per folder: the first set, in "auth" foreach (var (_, value) in obj) { RemoveV3Markers(value); @@ -187,7 +214,16 @@ static void RemoveV3Markers(JsonNode? node) } } - public void Save(string? path = null) + /// + /// Saves the collection: a JSON file whole, a v3 folder only where it changed. A v3 file that could not be read when + /// the collection was loaded is never saved over: when changes belong in it, everything else is saved and an + /// names it (the collection stays dirty). + /// + /// + /// Write files that changed on disk since they were read too; otherwise they are left alone and + /// names them (the collection stays dirty). + /// + public void Save(string? path = null, bool overwriteChanged = false) { if (_storage is not null) { @@ -196,13 +232,21 @@ public void Save(string? path = null) throw new NotSupportedException("A v3 collection folder is saved in place; use 'termrest convert' to write another format."); } - _storage.Save(this); + _storage.Save(this, overwriteChanged); SetDirty(false); return; } path ??= FilePath ?? throw new InvalidOperationException("The collection has no file path yet."); - TextFile.WriteAtomic(path, Serialize(), FileInfo); + var fullPath = Path.GetFullPath(path); + var samePath = FilePath is not null && string.Equals(fullPath, Path.GetFullPath(FilePath), StringComparison.OrdinalIgnoreCase); + if (!overwriteChanged && samePath && _stamp is not null && File.Exists(fullPath) && _stamp.HasChanged(fullPath)) + { + throw new FileChangedException([fullPath]); + } + + TextFile.WriteAtomic(path, Serialize(), FileInfo, out var stamp); + _stamp = stamp; FilePath = path; SetDirty(false); } diff --git a/src/TermRest.Core/Postman/PostmanEnvironment.cs b/src/TermRest.Core/Postman/PostmanEnvironment.cs index 4056125..9f44d94 100644 --- a/src/TermRest.Core/Postman/PostmanEnvironment.cs +++ b/src/TermRest.Core/Postman/PostmanEnvironment.cs @@ -22,6 +22,9 @@ public sealed class PostmanEnvironment private YamlFile? _yaml; private JsonObject? _v3; + /// What held when last read or written (see ). + private FileStamp? _stamp; + private PostmanEnvironment(JsonObject root, string? filePath, TextFileInfo fileInfo) { Root = root; @@ -71,7 +74,7 @@ public static bool IsYamlPath(string path) => public static PostmanEnvironment Load(string path) { - var (text, info) = TextFile.Read(path); + var (text, info) = TextFile.Read(path, out var stamp); if (IsYamlPath(path)) { YamlFile yaml; @@ -88,15 +91,25 @@ public static PostmanEnvironment Load(string path) var globals = fileName.Contains(".globals.", StringComparison.OrdinalIgnoreCase); var fallbackName = globals ? "Globals" : fileName.Split('.')[0]; var converted = V3Convert.EnvironmentToV21(yaml.Json, fallbackName, globals); - return new PostmanEnvironment(converted, path, info) { _yaml = yaml, _v3 = yaml.Json }; + return new PostmanEnvironment(converted, path, info) { _yaml = yaml, _v3 = yaml.Json, _stamp = stamp }; + } + + JsonNode? parsed; + try + { + parsed = PostmanJson.Parse(text); + } + catch (System.Text.Json.JsonException ex) + { + throw new InvalidDataException($"'{path}' is not a valid Postman environment: {ex.Message}", ex); } - if (PostmanJson.Parse(text) is not JsonObject root) + if (parsed is not JsonObject root) { throw new InvalidDataException($"'{path}' is not a Postman environment file."); } - return new PostmanEnvironment(root, path, info); + return new PostmanEnvironment(root, path, info) { _stamp = stamp }; } public static PostmanEnvironment Create(string name, string? filePath = null, bool globals = false) @@ -149,30 +162,40 @@ public void SetValue(string key, string value) public void MarkDirty() => IsDirty = true; - public void Save(string? path = null) + /// Write even when it changed on disk since it was read (see ). + public void Save(string? path = null, bool overwriteChanged = false) { path ??= FilePath ?? throw new InvalidOperationException("The environment has no file path yet."); + var samePath = FilePath is not null && string.Equals(Path.GetFullPath(path), Path.GetFullPath(FilePath), StringComparison.OrdinalIgnoreCase); // Converting between JSON and YAML writes the target format's defaults, not the source's BOM and line breaks. var info = FilePath is not null && IsYamlPath(FilePath) != IsYamlPath(path) ? IsYamlPath(path) ? NewYamlFile : TextFileInfo.PostmanDefault : FileInfo; + + // A copy saved elsewhere (an imported or converted environment) is as private as the file it was read from; a file + // saved over keeps its own permissions. Also when the path differs only in case, which is another file on Linux. + var newFileMode = FilePath is null ? null : TextFile.CopyMode(FilePath); if (IsYamlPath(path)) { // Only the changed values are rewritten; the rest of the file keeps its exact text. var v3 = V3Convert.EnvironmentToV3(Root, _v3); - if (_yaml is null || !JsonNode.DeepEquals(v3, _v3) || !string.Equals(path, FilePath, StringComparison.OrdinalIgnoreCase)) + if (_yaml is null || !JsonNode.DeepEquals(v3, _v3) || !samePath) { + ThrowIfChanged(path, samePath, overwriteChanged); var style = (_yaml is null ? YamlStyle.Default : YamlStyle.Detect([_yaml.Tree])).WithLineWidth(YamlLineWidth); - var text = _yaml is null ? YamlFile.Write(v3, style) : _yaml.Render(v3, style); - TextFile.WriteAtomic(path, info.HasTrailingNewline ? text[..^1] : text, info); - _yaml = YamlFile.Parse(text); + (var text, info) = YamlFile.WriteChecked(_yaml, v3, style, path, info, out var written); + TextFile.WriteAtomic(path, text, info, out var stamp, newFileMode); + _stamp = stamp; + _yaml = written; _v3 = v3; } } else { - TextFile.WriteAtomic(path, PostmanJson.Serialize(Root), info); + ThrowIfChanged(path, samePath, overwriteChanged); + TextFile.WriteAtomic(path, PostmanJson.Serialize(Root), info, out var stamp, newFileMode); + _stamp = stamp; } FilePath = path; @@ -180,5 +203,14 @@ public void Save(string? path = null) IsDirty = false; } + /// Refuses to save over the file when another program changed it since it was read: that would undo its changes. + private void ThrowIfChanged(string path, bool samePath, bool overwriteChanged) + { + if (!overwriteChanged && samePath && _stamp is not null && File.Exists(path) && _stamp.HasChanged(path)) + { + throw new FileChangedException([Path.GetFullPath(path)]); + } + } + public override string ToString() => Name; } diff --git a/src/TermRest.Core/Postman/PostmanRequestMapper.cs b/src/TermRest.Core/Postman/PostmanRequestMapper.cs index a7db405..a758346 100644 --- a/src/TermRest.Core/Postman/PostmanRequestMapper.cs +++ b/src/TermRest.Core/Postman/PostmanRequestMapper.cs @@ -115,12 +115,7 @@ private static KeyValueEntry ReadEntry(JsonObject obj, bool environmentStyle) string? value = ""; if (obj.TryGetPropertyValue("value", out var valueNode)) { - value = valueNode switch - { - null => null, - JsonValue v => v.GetString() ?? v.ToJsonString(), - _ => valueNode.ToJsonString(), - }; + value = ValueText(valueNode); } return new KeyValueEntry @@ -142,6 +137,14 @@ private static KeyValueEntry ReadEntry(JsonObject obj, bool environmentStyle) _ => node.GetString(), }; + /// A value as the text that is edited: numbers, booleans and objects as their JSON. + private static string? ValueText(JsonNode? node) => node switch + { + null => null, + JsonValue v => v.GetString() ?? v.ToJsonString(), + _ => node.ToJsonString(), + }; + internal static string? ReadDescription(JsonNode? node) => node is JsonObject obj ? obj["content"].GetString() : node.GetString(); private static void ReadUrl(JsonNode? node, HttpRequestSpec spec) @@ -156,13 +159,7 @@ private static void ReadUrl(JsonNode? node, HttpRequestSpec spec) break; case JsonObject obj: var query = obj["query"] is JsonArray ? ReadKeyValues(obj["query"]) : null; - spec.Url = obj["raw"].GetString() ?? PostmanUrl.BuildRaw( - obj["protocol"].GetString(), - ReadParts(obj["host"], '.'), - obj["port"].GetString(), - ReadParts(obj["path"], '/'), - query ?? [], - obj["hash"].GetString()); + spec.Url = RawUrl(obj, query); spec.QueryParams = query ?? QueryFromRaw(spec.Url); var variables = ReadKeyValues(obj["variable"]); foreach (var name in PostmanUrl.PathVariableNames(spec.Url)) @@ -178,6 +175,19 @@ private static void ReadUrl(JsonNode? node, HttpRequestSpec spec) } } + /// + /// The URL of a URL object: its raw text, else built from its parts (Postman allows either). + /// : its query entries when already read. + /// + internal static string RawUrl(JsonObject url, List? query = null) => + url["raw"].GetString() ?? PostmanUrl.BuildRaw( + url["protocol"].GetString(), + ReadParts(url["host"], '.'), + url["port"].GetString(), + ReadParts(url["path"], '/'), + query ?? (url["query"] is JsonArray ? ReadKeyValues(url["query"]) : []), + url["hash"].GetString()); + private static IEnumerable ReadParts(JsonNode? node, char separator) => node switch { JsonArray array => array.Select(n => n.GetString() ?? ""), @@ -528,7 +538,9 @@ private static JsonObject WriteEntry(KeyValueEntry entry, KeyValueStyle style) var obj = entry.Source is { } source ? (JsonObject)source.DeepClone() : new JsonObject(); obj.SetOrdered("key", entry.Key, KeyValueOrder); - var skipValue = style == KeyValueStyle.FormData && entry.IsFile && !obj.ContainsKey("value"); + // An unchanged value keeps its JSON type (a number, boolean or object is edited as its text). + var skipValue = (style == KeyValueStyle.FormData && entry.IsFile && !obj.ContainsKey("value")) + || (obj.TryGetPropertyValue("value", out var value) && ValueText(value) == entry.Value); if (!skipValue) { obj.SetOrdered("value", entry.Value is null ? null : JsonValue.Create(entry.Value), KeyValueOrder); @@ -578,7 +590,11 @@ private static JsonObject WriteEntry(KeyValueEntry entry, KeyValueStyle style) if (style == KeyValueStyle.Environment) { - obj.SetOrdered("enabled", entry.Enabled, KeyValueOrder); + // A value without "enabled" counts as enabled: it only gets one once disabled, so an edit doesn't touch the others. + if (isNew || !entry.Enabled || obj.ContainsKey("enabled")) + { + obj.SetOrdered("enabled", entry.Enabled, KeyValueOrder); + } } else if (!entry.Enabled) { diff --git a/src/TermRest.Core/Postman/PostmanUrl.cs b/src/TermRest.Core/Postman/PostmanUrl.cs index 0446f6b..07c2cf8 100644 --- a/src/TermRest.Core/Postman/PostmanUrl.cs +++ b/src/TermRest.Core/Postman/PostmanUrl.cs @@ -132,6 +132,74 @@ public static string StripQueryAndHash(string raw) return queryIndex >= 0 ? s[..queryIndex] : s; } + /// Where the user info of is (user:password in https://user:password@host), as reads it. + public static (int Start, int Length)? FindUserInfo(string raw) + { + var s = StripQueryAndHash(raw.TrimStart()); + var offset = raw.Length - raw.TrimStart().Length; + var protocol = s.IndexOf("://", StringComparison.Ordinal); + if (protocol > 0 && !s[..protocol].Contains('/', StringComparison.Ordinal)) + { + offset += protocol + 3; + s = s[(protocol + 3)..]; + } + + var slash = IndexOutsideBraces(s, '/'); + var at = LastIndexOutsideBraces(slash >= 0 ? s[..slash] : s, '@'); + return at < 0 ? null : (offset, at); + } + + /// Where the password of 's user info is (https://user:password@host), as reads it. + public static (int Start, int Length)? FindPassword(string raw) + { + if (FindUserInfo(raw) is not var (start, length)) + { + return null; + } + + var colon = raw.IndexOf(':', start, length); + return colon < 0 ? null : (colon + 1, start + length - colon - 1); + } + + /// + /// with the password of its user info (see ) masked as ***; with + /// , only a password it says is one. + /// + public static string MaskPassword(string raw, Func? isSecret = null) => + FindPassword(raw) is var (start, length) && length > 0 && raw.AsSpan(start, length) is not "***" + && (isSecret is null || isSecret(raw.Substring(start, length))) + ? string.Concat(raw.AsSpan(0, start), "***", raw.AsSpan(start + length)) + : raw; + + /// + /// with the credential of its user info masked as ***: the password + /// (https://user:password@host), or the user name when there is no password (https://user@host, https://user:@host: it + /// is then the credential); with , only a value it says is one. + /// + public static string MaskCredentials(string raw, Func? isSecret = null) + { + var parsed = Parse(raw); + if (!string.IsNullOrEmpty(parsed.AuthPassword) || parsed.AuthUser is not { Length: > 0 } user || user == "***" || isSecret?.Invoke(user) == false) + { + return MaskPassword(raw, isSecret); + } + + // The user name starts the authority, after the scheme. + var start = raw.Length - raw.TrimStart().Length + (parsed.Protocol is { } protocol ? protocol.Length + 3 : 0); + return raw.AsSpan(start).StartsWith(user, StringComparison.Ordinal) + ? string.Concat(raw.AsSpan(0, start), "***", raw.AsSpan(start + user.Length)) + : raw; + } + + /// Where the path of (a URL without query and fragment) starts, as reads it: its first '/', or -1. + public static int PathStart(string raw) + { + var start = raw.IndexOf("://", StringComparison.Ordinal); + start = start > 0 && !raw.AsSpan(0, start).Contains('/') ? start + 3 : 0; + var slash = IndexOutsideBraces(raw[start..], '/'); + return slash < 0 ? -1 : start + slash; + } + public static string? GetHash(string raw) { var hashIndex = IndexOutsideBraces(raw, '#'); diff --git a/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs b/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs index 29ce351..f20c90c 100644 --- a/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs +++ b/src/TermRest.Core/Postman/V3/V3CollectionStorage.cs @@ -11,7 +11,8 @@ internal interface ICollectionStorage /// Directory that relative file paths (body files, certificates) are resolved against. string BaseDirectory { get; } - void Save(PostmanCollection collection); + /// Also write files that changed on disk since they were read (see ). + void Save(PostmanCollection collection, bool overwriteChanged); } /// @@ -20,17 +21,24 @@ internal interface ICollectionStorage /// model TermRest edits everywhere; saving writes back only what changed: edited requests (only the edited YAML /// entries), renamed or moved items (their files and .resources move along), new and deleted items, and the /// order of reordered siblings. Files TermRest does not show (GraphQL, gRPC … requests, unreadable files) are -/// never touched. +/// never touched, and files another program changed since they were read are only saved over when that is allowed. /// internal sealed class V3CollectionStorage : ICollectionStorage { + private const string StagingPrefix = ".termrest-saving-"; + 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); - private readonly HashSet _unreadable = new(StringComparer.OrdinalIgnoreCase); private YamlStyle _style = YamlStyle.Default; + /// On Unix, the permissions of the files a conversion creates (see ); null: the default. + private UnixFileMode? _newFileMode; + private V3CollectionStorage(string directory) { Directory = directory; @@ -57,8 +65,15 @@ private sealed class Origin public JsonObject? Parent { get; set; } + /// The file as last read or written; null when there is none, or it could not be read (it is then never overwritten). public YamlFile? File { get; set; } + /// What the file held when last read or written, to tell whether another program changed it since (with ). + public FileStamp? Stamp { get; set; } + + /// Why the file could not be read when the collection was loaded; null when it could, or there was none. + public string? ReadError { get; set; } + public TextFileInfo FileInfo { get; set; } = NewFile; /// The v3 content as last read or written. @@ -68,6 +83,9 @@ private sealed class Origin public required JsonObject Baseline { get; set; } public JsonNode? Order { get; set; } + + /// For requests: the file name (without suffix) was read or written under; its examples path refers to it. + public string? Stem { get; set; } } // ----- loading --------------------------------------------------------------------------------- @@ -80,6 +98,13 @@ public static PostmanCollection Load(string directory) throw new DirectoryNotFoundException($"'{directory}' does not exist."); } + // As the workspace takes them: any other folder (a workspace, a source folder) would be read as one whole collection. + if (!V3Names.IsCollectionDirectory(directory)) + { + throw new IOException($"'{directory}' is not a Postman v3 collection folder: one with a {V3Names.ResourcesDirectory}/{V3Names.DefinitionFile} " + + $"or *{V3Names.RequestSuffix} files (in its folders too, in a postman/collections folder)."); + } + var storage = new V3CollectionStorage(directory); var warnings = new List(); var trees = new List(); @@ -90,23 +115,38 @@ public static PostmanCollection Load(string directory) }; var definitionPath = V3Names.DefinitionPath(directory); - var (definition, info) = storage.Read(definitionPath, warnings, trees); - V3Convert.DefinitionToV21(definition?.Json, root, isRoot: true); - if (definition?.Json["name"].GetString() is { Length: > 0 } name) + var definition = storage.Read(definitionPath, warnings, trees); + V3Convert.DefinitionToV21(definition.File?.Json, root, isRoot: true); + if (definition.File?.Json["name"].GetString() is { Length: > 0 } name) { root["info"]!["name"] = name; } - storage._origins[root] = new Origin { Path = directory, File = definition, FileInfo = info, V3 = definition?.Json, Baseline = Snapshot(root) }; + storage._origins[root] = new Origin + { + Path = directory, File = definition.File, Stamp = definition.Stamp, ReadError = definition.Error, FileInfo = definition.Info, + V3 = definition.File?.Json, Baseline = Snapshot(root), + }; var hidden = storage.LoadChildren(directory, root, warnings, trees); + var unreadable = warnings.Count > 0; if (hidden > 0) { warnings.Add($"{hidden} non-HTTP request(s) (GraphQL, gRPC, WebSocket …) are not shown; their files are left untouched."); } + foreach (var leftover in System.IO.Directory.EnumerateDirectories(directory, StagingPrefix + "*")) + { + if (System.IO.Directory.EnumerateFileSystemEntries(leftover).Any()) + { + warnings.Add($"{Path.GetFileName(leftover)}: a save that did not finish left files here; move them back into the collection."); + unreadable = true; + } + } + storage._style = YamlStyle.Detect(trees); var collection = PostmanCollection.FromStorage(root, directory, storage); collection.LoadWarnings.AddRange(warnings); + collection.HasUnreadableFiles = unreadable; return collection; } @@ -114,13 +154,20 @@ public static PostmanCollection Load(string directory) public static PostmanCollection Create(string directory, string name, int? lineWidth = null) { directory = Path.GetFullPath(directory); + if (System.IO.Directory.Exists(directory) && System.IO.Directory.EnumerateFileSystemEntries(directory).Any()) + { + throw new IOException($"'{directory}' already exists and is not empty."); + } + var definition = new JsonObject { ["$kind"] = V3Convert.CollectionKind }; if (Path.GetFileName(Path.TrimEndingDirectorySeparator(directory)) != name) { definition["name"] = name; } - TextFile.WriteAtomic(V3Names.DefinitionPath(directory), YamlFile.Write(definition, YamlStyle.Default.WithLineWidth(lineWidth)).TrimEnd('\n'), NewFile); + var definitionPath = V3Names.DefinitionPath(directory); + var (text, info) = YamlFile.WriteChecked(null, definition, YamlStyle.Default.WithLineWidth(lineWidth), definitionPath, NewFile, out _); + TextFile.WriteAtomic(definitionPath, text, info); var collection = Load(directory); collection.YamlLineWidth = lineWidth; return collection; @@ -129,7 +176,9 @@ public static PostmanCollection Create(string directory, string name, int? lineW /// /// Writes (any format) as a new v3 collection folder, including saved responses as /// .example.yaml files, and returns the loaded result. Long values are wrapped at - /// (null or 0: not wrapped, like current Postman versions). + /// (null or 0: not wrapped, like current Postman versions). On Unix the folder and its + /// files get the permissions of the source's file (see ) from the start. When writing + /// fails, nothing is left behind: a collection that is only partly written would look complete. /// public static PostmanCollection ConvertFrom(PostmanCollection source, string directory, int? lineWidth = null) { @@ -139,14 +188,38 @@ public static PostmanCollection ConvertFrom(PostmanCollection source, string dir throw new IOException($"'{directory}' already exists and is not empty."); } - System.IO.Directory.CreateDirectory(directory); - var root = (JsonObject)source.Root.DeepClone(); - var storage = new V3CollectionStorage(directory) { LineWidth = lineWidth }; - var collection = PostmanCollection.FromStorage(root, directory, storage); - storage.Save(collection); - foreach (var request in collection.AllRequests()) + // The outermost folder created here (null when the target folder exists): removed again when writing fails. + string? created = null; + for (var missing = directory; missing is not null && !System.IO.Directory.Exists(missing); missing = Path.GetDirectoryName(missing)) { - storage.WriteExamples(request.Json); + created = missing; + } + + var fileMode = source.FilePath is { } sourcePath ? TextFile.CopyMode(sourcePath) : null; + try + { + if (fileMode is { } mode && !OperatingSystem.IsWindows()) + { + // Private from the start for a private source: others never get to read what is being written. + var folderMode = TextFile.FolderMode(mode); + System.IO.Directory.CreateDirectory(Path.GetDirectoryName(directory) ?? directory); + System.IO.Directory.CreateDirectory(directory, folderMode); + File.SetUnixFileMode(directory, folderMode); // the create mode is subject to the umask + } + else + { + System.IO.Directory.CreateDirectory(directory); + } + + var root = (JsonObject)source.Root.DeepClone(); + var storage = new V3CollectionStorage(directory) { LineWidth = lineWidth, _newFileMode = fileMode }; + var collection = PostmanCollection.FromStorage(root, directory, storage); + storage.Save(collection, overwriteChanged: false); // new requests are written with their examples + } + catch + { + RemoveWritten(directory, created); + throw; } var converted = Load(directory); @@ -154,54 +227,91 @@ public static PostmanCollection ConvertFrom(PostmanCollection source, string dir return converted; } - /// Saved responses (v2.1 response) as v3 example files next to the request. - private void WriteExamples(JsonObject item) + /// Removes what a failed conversion wrote: with everything in it, else what is in . + private static void RemoveWritten(string directory, string? created) { - if (item["response"] is not JsonArray { Count: > 0 } responses || !_origins.TryGetValue(item, out var origin)) + try { - return; + if (created is not null) + { + System.IO.Directory.Delete(created, recursive: true); + return; + } + + foreach (var entry in new DirectoryInfo(directory).EnumerateFileSystemInfos()) + { + if (entry is DirectoryInfo folder) + { + folder.Delete(recursive: true); + } + else + { + entry.Delete(); + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Best effort: the error that stopped the conversion is the one to report. + } + } + + /// + /// 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. + /// + private string? WriteExamples(JsonObject item, string requestFile) + { + if (item["response"] is not JsonArray { Count: > 0 } responses) + { + return null; } - var folder = Path.Combine(V3Names.ResourcesPath(origin.Path), "examples"); + 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 name = V3Names.Unique(V3Names.Safe(response["name"].GetString() ?? "Example"), taken); + 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); + + // A name its file can't have (cut, made safe or unique) is kept in the file, as Postman keeps it. + if (name != responseName) + { + example.SetOrdered("name", responseName, ExampleOrder); + } + order += 1000; example["order"] = order; - TextFile.WriteAtomic(Path.Combine(folder, name + ".example.yaml"), YamlFile.Write(example, Style).TrimEnd('\n'), NewFile); + 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); } - var v3 = (JsonObject)origin.V3!.DeepClone(); - v3.SetOrdered("examples", $"./{V3Names.ResourcesDirectory}/{V3Names.RequestStem(origin.Path)}.resources/examples", V3Convert.RequestOrder); - var text = origin.File!.Render(v3, Style); - TextFile.WriteAtomic(origin.Path, text[..^1], origin.FileInfo); - origin.File = YamlFile.Parse(text); - origin.V3 = v3; + return order == 0 ? null : $"./{V3Names.ResourcesDirectory}/{V3Names.RequestStem(requestFile)}.resources/examples"; } - private (YamlFile? File, TextFileInfo Info) Read(string path, List warnings, List trees) + private (YamlFile? File, TextFileInfo Info, FileStamp? Stamp, string? Error) Read(string path, List warnings, List trees) { if (!File.Exists(path)) { - return (null, NewFile); + return (null, NewFile, null, null); } try { - var (text, info) = TextFile.Read(path); + var (text, info) = TextFile.Read(path, out var stamp); var file = YamlFile.Parse(text); trees.Add(file.Tree); - return (file, info); + return (file, info, stamp, null); } catch (Exception ex) when (ex is FormatException or IOException or UnauthorizedAccessException) { - _unreadable.Add(path); warnings.Add($"{Path.GetRelativePath(Directory, path)}: {ex.Message}"); - return (null, NewFile); + return (null, NewFile, null, ex.Message); } } @@ -212,7 +322,7 @@ private int LoadChildren(string directory, JsonObject parent, List warni var children = new List<(double? Order, string Name, JsonObject Item)>(); foreach (var file in System.IO.Directory.EnumerateFiles(directory).Where(V3Names.IsRequestFile)) { - var (yaml, info) = Read(file, warnings, trees); + var (yaml, info, stamp, _) = Read(file, warnings, trees); if (yaml is null) { continue; @@ -228,7 +338,8 @@ private int LoadChildren(string directory, JsonObject parent, List warni var item = V3Convert.RequestToV21(yaml.Json, name); _origins[item] = new Origin { - Path = file, Parent = parent, File = yaml, FileInfo = info, V3 = yaml.Json, Baseline = Snapshot(item), Order = yaml.Json["order"]?.DeepClone(), + Path = file, Parent = parent, File = yaml, Stamp = stamp, FileInfo = info, V3 = yaml.Json, Baseline = Snapshot(item), + Order = yaml.Json["order"]?.DeepClone(), Stem = V3Names.RequestStem(file), }; children.Add((OrderValue(yaml.Json["order"]), name, item)); } @@ -241,14 +352,14 @@ private int LoadChildren(string directory, JsonObject parent, List warni continue; } - var (definition, info) = Read(V3Names.DefinitionPath(sub), warnings, trees); + var (definition, info, stamp, error) = Read(V3Names.DefinitionPath(sub), warnings, trees); var name = definition?.Json["name"].GetString() is { Length: > 0 } explicitName ? explicitName : dirName; var folder = new JsonObject { ["name"] = name, ["item"] = new JsonArray() }; V3Convert.DefinitionToV21(definition?.Json, folder, isRoot: false); _origins[folder] = new Origin { - Path = sub, Parent = parent, File = definition, FileInfo = info, V3 = definition?.Json, Baseline = Snapshot(folder), - Order = definition?.Json["order"]?.DeepClone(), + Path = sub, Parent = parent, File = definition, Stamp = stamp, ReadError = error, FileInfo = info, V3 = definition?.Json, + Baseline = Snapshot(folder), Order = definition?.Json["order"]?.DeepClone(), }; hidden += LoadChildren(sub, folder, warnings, trees); children.Add((OrderValue(definition?.Json["order"]), name, folder)); @@ -268,12 +379,25 @@ private int LoadChildren(string directory, JsonObject parent, List warni // ----- saving ---------------------------------------------------------------------------------- - public void Save(PostmanCollection collection) + public void Save(PostmanCollection collection, bool overwriteChanged) { var root = collection.Root; var parents = new Dictionary(ReferenceEqualityComparer.Instance); var desired = new Dictionary(ReferenceEqualityComparer.Instance) { [root] = Directory }; - AssignPaths(root, Directory, desired, parents); + + // Requests to move or rename whose file another program changed since it was read stay where they are, unwritten, + // unless overwriting is allowed: moved without being written, what they say would no longer match where they are + // (their examples path, say). Their names stay taken. + var pinned = overwriteChanged ? new HashSet(ReferenceEqualityComparer.Instance) : ChangedRequestsToMove(root); + var managed = new HashSet(_origins.Where(o => !pinned.Contains(o.Key)).Select(o => o.Value.Path), StringComparer.OrdinalIgnoreCase); + AssignPaths(root, Directory, desired, parents, managed); + + // New orders depend on where items were loaded from: computed before the moves below update that. + var orders = new Dictionary(ReferenceEqualityComparer.Instance); + foreach (var folder in PreOrder(root).Where(IsFolder)) + { + AssignOrders(folder, orders); + } var current = new Dictionary(ReferenceEqualityComparer.Instance); foreach (var (item, origin) in _origins) @@ -281,126 +405,311 @@ public void Save(PostmanCollection collection) current[item] = origin.Path; } - var staging = Path.Combine(Directory, $".termrest-saving-{Guid.NewGuid():N}"); + var inTree = new HashSet(PreOrder(root), ReferenceEqualityComparer.Instance); + var removed = _origins.Keys.Where(i => !inTree.Contains(i)).ToList(); + var staging = Path.Combine(Directory, $"{StagingPrefix}{Guid.NewGuid():N}"); var staged = new Dictionary(ReferenceEqualityComparer.Instance); var stagedResources = new Dictionary(ReferenceEqualityComparer.Instance); - var oldStems = new Dictionary(ReferenceEqualityComparer.Instance); - // 1. Take out everything that moves or is renamed (a moving folder takes its content along). - foreach (var item in PreOrder(root).Where(i => i != root && _origins.ContainsKey(i))) + // Folders whose folder disappeared and that are written anew (see WriteAnew), and the folders in them: created anew, + // as new ones are. + var writtenAnew = new HashSet(ReferenceEqualityComparer.Instance); + + bool Moved(JsonObject item) => + _origins[item].Parent != parents.GetValueOrDefault(item) || Path.GetFileName(current[item]) != Path.GetFileName(desired[item]); + + // Gone meanwhile (a git checkout, say): written anew where it belongs, with everything a folder held. Examples it had + // stay where they are. + void WriteAnew(JsonObject item) { - var origin = _origins[item]; - var moved = origin.Parent != parents[item] || Path.GetFileName(current[item]) != Path.GetFileName(desired[item]); - if (!moved) + var inside = current[item] + Path.DirectorySeparatorChar; + foreach (var (gone, goneOrigin) in _origins) { - continue; + if (current[gone] == current[item] || current[gone].StartsWith(inside, StringComparison.Ordinal)) + { + goneOrigin.File = null; + goneOrigin.Stamp = null; + goneOrigin.ReadError = null; + goneOrigin.Stem = null; + if (IsFolder(gone)) + { + writtenAnew.Add(gone); + } + } } + } - System.IO.Directory.CreateDirectory(staging); - var target = Path.Combine(staging, staged.Count.ToString(System.Globalization.CultureInfo.InvariantCulture)); - if (IsFolder(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). + var changes = new Dictionary(ReferenceEqualityComparer.Instance); + bool Changes(JsonObject item) + { + if (!changes.TryGetValue(item, out var changed)) { - System.IO.Directory.Move(current[item], target); - Rebase(current, current[item], target); + changed = !pinned.Contains(item) + && (!_origins.TryGetValue(item, out var origin) || Moved(item) || !JsonNode.DeepEquals(Snapshot(item), origin.Baseline) + || (orders.ContainsKey(item) && (!IsFolder(item) || OrderValue(origin.Order) is not null || System.IO.Directory.Exists(current[item])))); + changes[item] = changed; } - else + + return changed; + } + + // A folder that disappeared where it is (the collection's own too) stays gone, unless something is written into it or + // it is written itself: then it is written anew, so that what is written there keeps the folder's definition (its + // auth, scripts …) and the folder on disk holds what TermRest shows. Moved ones are written anew in step 1. + foreach (var folder in PreOrder(root).Where(f => IsFolder(f) && _origins.ContainsKey(f))) + { + if (!writtenAnew.Contains(folder) && !Moved(folder) && !System.IO.Directory.Exists(current[folder]) && PreOrder(folder).Any(Changes)) { - oldStems[item] = V3Names.RequestStem(current[item]); - var resources = V3Names.ResourcesPath(current[item]); - File.Move(current[item], target); - if (System.IO.Directory.Exists(resources)) + WriteAnew(folder); + } + } + + // Every move and created folder, so that a failure moves everything back (To is null for a created folder). + var journal = new List<(string From, string? To)>(); + try + { + // 1. Take out everything that moves or is renamed (a moving folder takes its content along). + foreach (var item in PreOrder(root).Where(i => i != root && _origins.ContainsKey(i) && !pinned.Contains(i))) + { + if (!Moved(item)) { - System.IO.Directory.Move(resources, target + ".resources"); - stagedResources[item] = target + ".resources"; + continue; } - current[item] = target; + if (IsFolder(item) ? !System.IO.Directory.Exists(current[item]) : !File.Exists(current[item])) + { + WriteAnew(item); + continue; + } + + CreateDirectory(staging, journal); + var target = Path.Combine(staging, staged.Count.ToString(System.Globalization.CultureInfo.InvariantCulture)); + if (IsFolder(item)) + { + Move(current[item], target, isDirectory: true, journal); + Rebase(current, current[item], target); + } + else + { + var resources = V3Names.ResourcesPath(current[item]); + Move(current[item], target, isDirectory: false, journal); + current[item] = target; + if (System.IO.Directory.Exists(resources)) + { + Move(resources, target + ".resources", isDirectory: true, journal); + stagedResources[item] = target + ".resources"; + } + } + + staged[item] = target; } - staged[item] = target; - } + // 2. Delete what was removed (moved-out content is already safe in staging). Folders are only removed once + // empty: files TermRest does not show (GraphQL, gRPC … requests) are never deleted. + foreach (var item in removed.Where(i => !IsFolder(i))) + { + DeleteRequestFiles(current[item]); + } - // 2. Delete what was removed (moved-out content is already safe in staging). Folders are only removed once - // empty: files TermRest does not show (GraphQL, gRPC … requests) are never deleted. - var inTree = new HashSet(PreOrder(root), ReferenceEqualityComparer.Instance); - var removed = _origins.Keys.Where(i => !inTree.Contains(i)).ToList(); - foreach (var item in removed.Where(i => !IsFolder(i))) - { - DeleteRequestFiles(current[item]); - } + foreach (var item in removed.Where(IsFolder).OrderByDescending(i => current[i].Length)) + { + DeleteFolderIfEmpty(current[item]); + } + + // 3. Put moved items in place, parents first. No item takes over the place of a deleted folder that is still there (it + // holds files TermRest does not show, or a request held back from moving out) or of anything else TermRest does + // not show: it gets a free name, and what belongs in it follows. New folders, and folders written anew, are checked + // here too, once their parent is in place: such a deleted folder may only have arrived with it. + foreach (var item in PreOrder(root).Where(i => i != root && (staged.ContainsKey(i) || writtenAnew.Contains(i) || (IsFolder(i) && !_origins.ContainsKey(i))))) + { + var target = desired[item]; + if (Path.Exists(target) || (stagedResources.ContainsKey(item) && Path.Exists(V3Names.ResourcesPath(target)))) + { + var free = FreePath(target, IsFolder(item), desired.Where(d => d.Key != item).Select(d => d.Value)); + Rebase(desired, target, free); + target = free; + } + + if (!staged.ContainsKey(item)) + { + continue; // created when its content is written + } + + CreateDirectory(Path.GetDirectoryName(target)!, journal); + if (IsFolder(item)) + { + Move(current[item], target, isDirectory: true, journal); + Rebase(current, current[item], target); + } + else + { + Move(current[item], target, isDirectory: false, journal); + current[item] = target; + if (stagedResources.TryGetValue(item, out var resources)) + { + var resourcesTarget = V3Names.ResourcesPath(target); + CreateDirectory(Path.GetDirectoryName(resourcesTarget)!, journal); + Move(resources, resourcesTarget, isDirectory: true, journal); + } + } + } - foreach (var item in removed.Where(IsFolder).OrderByDescending(i => current[i].Length)) + if (System.IO.Directory.Exists(staging)) + { + System.IO.Directory.Delete(staging, recursive: false); + } + } + catch { - DeleteFolderIfEmpty(current[item]); + Undo(journal, current); + foreach (var (item, origin) in _origins) + { + origin.Path = current[item]; + } + + throw; } + // Everything is in place: remembered now, so that the next save starts from there even if writing fails. A deleted + // folder that still holds a request held back from moving out stays known: a later save deletes it once that request + // has left (else it would come back as an empty folder). + var heldBack = pinned.Select(p => current[p]).ToList(); foreach (var item in removed) { + if (IsFolder(item) && heldBack.Any(p => p.StartsWith(current[item] + Path.DirectorySeparatorChar, StringComparison.Ordinal))) + { + continue; + } + _origins.Remove(item); _loadedChildren.Remove(item); } - // 3. Put moved items in place, parents first. - foreach (var item in PreOrder(root).Where(staged.ContainsKey)) + foreach (var (item, origin) in _origins) { - var target = desired[item]; - System.IO.Directory.CreateDirectory(Path.GetDirectoryName(target)!); - if (IsFolder(item)) + origin.Path = current[item]; + if (!pinned.Contains(item)) { - System.IO.Directory.Move(current[item], target); - Rebase(current, current[item], target); - } - else - { - File.Move(current[item], target); - current[item] = target; - if (stagedResources.TryGetValue(item, out var resources)) - { - var resourcesTarget = V3Names.ResourcesPath(target); - System.IO.Directory.CreateDirectory(Path.GetDirectoryName(resourcesTarget)!); - System.IO.Directory.Move(resources, resourcesTarget); - } + origin.Parent = parents.GetValueOrDefault(item); } } - if (System.IO.Directory.Exists(staging)) + // 4. Write content: new items, edited items, renamed items and reordered siblings. Files that could not be read when + // loading, and ones another program changed since, are left alone and reported once everything else is written. + var leftAlone = new LeftAlone(overwriteChanged); + foreach (var item in pinned) { - System.IO.Directory.Delete(staging, recursive: false); + leftAlone.Changed.Add(current[item]); + leftAlone.Items.Add(item); } - // 4. Write content: new items, edited items, renamed items and reordered siblings. - var orders = new Dictionary(ReferenceEqualityComparer.Instance); - foreach (var folder in PreOrder(root).Where(IsFolder)) + foreach (var item in PreOrder(root)) { - AssignOrders(folder, orders); + // Other folders are in place already, or stay gone (see above). One that stays gone does not keep the order it got as + // it had none (writing that would bring it back): left alone, it gets one again with each save, until it is back. + if (IsFolder(item) && (writtenAnew.Contains(item) || !_origins.ContainsKey(item))) + { + CreateFolder(desired[item]); + } + else if (IsFolder(item) && orders.ContainsKey(item) && !System.IO.Directory.Exists(desired[item])) + { + orders.Remove(item); + leftAlone.Items.Add(item); + } + + if (!pinned.Contains(item)) + { + WriteItem(item, item == root, desired[item], parents.GetValueOrDefault(item), orders, leftAlone); + } } - foreach (var item in PreOrder(root)) + foreach (var folder in PreOrder(root).Where(IsFolder)) { - if (IsFolder(item)) + // Where a child was left alone, its new order is assigned again next time, also when the children are then as they + // were before: the new orders of the others are written. + var children = Children(folder).ToList(); + if (children.Any(leftAlone.Items.Contains)) { - System.IO.Directory.CreateDirectory(desired[item]); + _loadedChildren.Remove(folder); + } + else + { + _loadedChildren[folder] = children; } - - WriteItem(item, item == root, desired[item], parents.GetValueOrDefault(item), orders, oldStems.GetValueOrDefault(item)); } + leftAlone.ThrowIfAny(); + } + + /// Requests whose parent or name changed while another program changed their file since it was read. + private HashSet ChangedRequestsToMove(JsonObject root) + { + var changed = new HashSet(ReferenceEqualityComparer.Instance); foreach (var folder in PreOrder(root).Where(IsFolder)) { - _loadedChildren[folder] = Children(folder).ToList(); + foreach (var request in Children(folder).Where(c => !IsFolder(c))) + { + if (_origins.TryGetValue(request, out var origin) && origin.Stamp is { } stamp + && (origin.Parent != folder || origin.Baseline["name"].GetString() != request["name"].GetString()) + && File.Exists(origin.Path) && stamp.HasChanged(origin.Path)) + { + changed.Add(request); + } + } } + + return changed; } - private void WriteItem(JsonObject item, bool isRoot, string path, JsonObject? parent, Dictionary orders, string? oldStem) + /// What a save did not write: files that could not be read when loading, and ones another program changed since. + private sealed class LeftAlone(bool overwriteChanged) { - _origins.TryGetValue(item, out var origin); - var isFolder = IsFolder(item); - var file = isFolder ? V3Names.DefinitionPath(path) : path; - if (_unreadable.Contains(file)) + /// Write files another program changed since they were read anyway. + public bool OverwriteChanged { get; } = overwriteChanged; + + /// The items not written (also folders that stay gone with a new order): their siblings' orders are assigned again next time. + public HashSet Items { get; } = new(ReferenceEqualityComparer.Instance); + + /// Files that could not be read, with the reason. + public List Unreadable { get; } = []; + + public List Changed { get; } = []; + + /// + /// Reports what was left alone: an when files could not be read (overwriting cannot help + /// there; changed files are named too), else a . + /// + public void ThrowIfAny() { - return; // never overwrite a file that could not be read + if (Unreadable.Count > 0) + { + var (files, it, holds) = Unreadable.Count == 1 ? ("this file", "it", "it holds") : ("these files", "them", "they hold"); + var message = $"{string.Join("\n", Unreadable)}\nTermRest could not read {files} when it loaded the collection, so it did not save over {it} " + + $"(that would lose what {holds}), and the changes that belong in {it} are not saved. Fix {it} and reload the collection, " + + $"or delete {it} and save again."; + if (Changed.Count > 0) + { + var (they, them) = Changed.Count == 1 ? ("it", "it") : ("they", "them"); + message += $"\nNot saved either, as {they} changed on disk since TermRest read {them}: {string.Join(", ", Changed)}."; + } + + throw new IOException(message); + } + + if (Changed.Count > 0) + { + throw new FileChangedException(Changed); + } } + } + private void WriteItem(JsonObject item, bool isRoot, string path, JsonObject? parent, Dictionary orders, LeftAlone leftAlone) + { + _origins.TryGetValue(item, out var origin); + var isFolder = IsFolder(item); + var file = isFolder ? V3Names.DefinitionPath(path) : path; var snapshot = Snapshot(item); JsonObject v3; if (origin is not null && JsonNode.DeepEquals(snapshot, origin.Baseline)) @@ -429,65 +738,107 @@ private void WriteItem(JsonObject item, bool isRoot, string path, JsonObject? pa v3.SetOrdered("order", newOrder.DeepClone(), order); } - if (oldStem is not null && v3["examples"].GetString() is { } examples) + if (origin?.Stem is { } oldStem && oldStem != fileName && v3["examples"].GetString() is { } examples) { - // Examples moved with the request's resources folder. - var oldPrefix = $"./{V3Names.ResourcesDirectory}/{oldStem}.resources"; - if (examples.StartsWith(oldPrefix, StringComparison.Ordinal)) + // Examples moved with the request's resources folder: the path follows it, written as the file writes it (Postman + // writes both "./.resources/…" and ".resources/…"). + var dot = examples.StartsWith("./", StringComparison.Ordinal) ? "./" : ""; + var oldFolder = $"{dot}{V3Names.ResourcesDirectory}/{oldStem}.resources"; + if (examples.StartsWith(oldFolder, StringComparison.Ordinal) && (examples.Length == oldFolder.Length || examples[oldFolder.Length] == '/')) { - v3["examples"] = $"./{V3Names.ResourcesDirectory}/{fileName}.resources{examples[oldPrefix.Length..]}"; + v3["examples"] = $"{dot}{V3Names.ResourcesDirectory}/{fileName}.resources{examples[oldFolder.Length..]}"; } } - var existing = origin?.File is not null && File.Exists(file); + if (!isFolder && origin is null && WriteExamples(item, path) is { } examplesFolder) + { + v3.SetOrdered("examples", examplesFolder, order); + } - // Folders get a definition file when they are new or have something to store; requests always have a file. - var needsFile = !isFolder || existing || origin is null || v3.Count > 1; - if (needsFile && !(existing && JsonNode.DeepEquals(v3, origin!.V3))) + // 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. + 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 text = existing ? origin!.File!.Render(v3, Style) : YamlFile.Write(v3, Style); - var info = origin?.FileInfo ?? NewFile; - TextFile.WriteAtomic(file, text.EndsWith('\n') && info.HasTrailingNewline ? text[..^1] : text, info); - origin = Remember(item, origin, path, parent, YamlFile.Parse(text), info, v3, snapshot); + var existing = File.Exists(file); + if (existing && origin?.ReadError is { } error) + { + // Never overwritten, as it could not be read: it moves along with its folder unchanged. What it would have to + // hold besides its position is not saved, and is reported. + if (v3.Any(p => p.Key is not ("$kind" or "order"))) + { + leftAlone.Unreadable.Add($"{file}: {error}"); + leftAlone.Items.Add(item); + return; + } + + Remember(item, origin, path, parent, null, null, origin.FileInfo, null, snapshot); + return; + } + + // Changed by another program since it was read, or created where there was none: not saved over unless allowed. + if (existing && (!hadFile || origin!.Stamp?.HasChanged(file) == true)) + { + if (origin is null) + { + throw new IOException($"'{file}' already exists."); + } + + if (!leftAlone.OverwriteChanged) + { + leftAlone.Changed.Add(file); + leftAlone.Items.Add(item); + return; + } + } + + var (text, info) = YamlFile.WriteChecked(existing && hadFile ? origin!.File : null, v3, Style, file, origin?.FileInfo ?? NewFile, out var written); + CreateFolder(Path.GetDirectoryName(file)!); // a folder's .resources + TextFile.WriteAtomic(file, text, info, out var stamp, _newFileMode); + Remember(item, origin, path, parent, written, stamp, info, v3, snapshot); return; } - Remember(item, origin, path, parent, origin?.File, origin?.FileInfo ?? NewFile, origin?.V3 ?? (needsFile ? v3 : null), snapshot); + Remember(item, origin, path, parent, origin?.File, origin?.Stamp, origin?.FileInfo ?? NewFile, origin?.V3 ?? (needsFile ? v3 : null), snapshot); } - private Origin Remember(JsonObject item, Origin? origin, string path, JsonObject? parent, YamlFile? file, TextFileInfo info, JsonObject? v3, JsonObject snapshot) + private void Remember(JsonObject item, Origin? origin, string path, JsonObject? parent, YamlFile? file, FileStamp? stamp, TextFileInfo info, JsonObject? v3, JsonObject snapshot) { origin ??= new Origin { Path = path, Baseline = snapshot }; origin.Path = path; origin.Parent = parent; origin.File = file; + origin.Stamp = stamp; + origin.ReadError = file is null ? origin.ReadError : null; origin.FileInfo = info; origin.V3 = v3; origin.Baseline = snapshot; origin.Order = v3?["order"]?.DeepClone(); + origin.Stem = IsFolder(item) ? null : V3Names.RequestStem(path); _origins[item] = origin; - return origin; } /// Desired paths for the current tree. Items keep their current file name while their name is unchanged. - private void AssignPaths(JsonObject folder, string directory, Dictionary desired, Dictionary parents) + private void AssignPaths(JsonObject folder, string directory, Dictionary desired, Dictionary parents, HashSet managed) { var children = Children(folder).ToList(); var takenFiles = new HashSet(StringComparer.OrdinalIgnoreCase); var takenFolders = new HashSet(StringComparer.OrdinalIgnoreCase); - // Files and folders on disk that TermRest does not manage keep their names. - var managed = new HashSet(_origins.Values.Select(o => o.Path), StringComparer.OrdinalIgnoreCase); - if (System.IO.Directory.Exists(directory)) + // Files and folders on disk that TermRest does not manage keep their names. They are where the folder is now (they + // move along with it), or for a new folder where it will be. + var location = _origins.TryGetValue(folder, out var self) ? self.Path : directory; + if (System.IO.Directory.Exists(location)) { - foreach (var file in System.IO.Directory.EnumerateFiles(directory).Where(V3Names.IsRequestFile).Where(f => !managed.Contains(f))) + foreach (var entry in System.IO.Directory.EnumerateFileSystemEntries(location).Where(e => !managed.Contains(e))) { - takenFiles.Add(V3Names.RequestStem(file)); - } - - foreach (var sub in System.IO.Directory.EnumerateDirectories(directory).Where(d => !managed.Contains(d))) - { - takenFolders.Add(Path.GetFileName(sub)); + var entryName = Path.GetFileName(entry); + takenFolders.Add(entryName); + if (V3Names.IsRequestFile(entryName)) + { + takenFiles.Add(V3Names.RequestStem(entryName)); + } } } @@ -519,7 +870,7 @@ private void AssignPaths(JsonObject folder, string directory, Dictionary or else { var step = (high.Value - low) / (count + 1); + if (double.IsInfinity(step)) + { + step = (high.Value / (count + 1)) - (low / (count + 1)); // orders near the limits of a double + } + value = low + (step * k); if (step >= 1) { @@ -650,6 +1006,119 @@ private static void DeleteFolderIfEmpty(string path) } } + /// Creates a folder and its missing parents, noting each in so a failed save removes them. + private static void CreateDirectory(string directory, List<(string From, string? To)> journal) + { + var missing = new Stack(); + for (var d = directory; d is not null && !System.IO.Directory.Exists(d); d = Path.GetDirectoryName(d)) + { + missing.Push(d); + } + + System.IO.Directory.CreateDirectory(directory); + while (missing.TryPop(out var created)) + { + journal.Add((created, null)); + } + } + + /// Creates a folder and its missing parents; in a conversion as private as the converted folder (see ). + private void CreateFolder(string directory) + { + if (_newFileMode is not { } mode || OperatingSystem.IsWindows()) + { + System.IO.Directory.CreateDirectory(directory); + return; + } + + // One by one: Directory.CreateDirectory gives the missing parents the default permissions. + var missing = new Stack(); + for (var d = directory; d is not null && !System.IO.Directory.Exists(d); d = Path.GetDirectoryName(d)) + { + missing.Push(d); + } + + var folderMode = TextFile.FolderMode(mode); + while (missing.TryPop(out var created)) + { + System.IO.Directory.CreateDirectory(created, folderMode); + File.SetUnixFileMode(created, folderMode); // the create mode is subject to the umask + } + } + + /// Moves a file or folder, noting it in so a failed save moves it back. + private static void Move(string from, string to, bool isDirectory, List<(string From, string? To)> journal) + { + if (isDirectory) + { + System.IO.Directory.Move(from, to); + } + else + { + File.Move(from, to); + } + + journal.Add((from, to)); + } + + /// + /// Undoes the moves and created folders of a failed save, last first. What cannot be moved back stays where it is + /// ( says where): the next save moves it from there, and loading reports a staging folder + /// that is left with files. + /// + private static void Undo(List<(string From, string? To)> journal, Dictionary current) + { + for (var i = journal.Count - 1; i >= 0; i--) + { + var (from, to) = journal[i]; + try + { + if (to is null) + { + if (System.IO.Directory.Exists(from) && !System.IO.Directory.EnumerateFileSystemEntries(from).Any()) + { + System.IO.Directory.Delete(from); + } + + continue; + } + + System.IO.Directory.CreateDirectory(Path.GetDirectoryName(from)!); + if (System.IO.Directory.Exists(to)) + { + System.IO.Directory.Move(to, from); + } + else + { + File.Move(to, from); + } + + Rebase(current, to, from); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Left where it is; see above. + } + } + } + + /// The first "name-1", "name-2" … next to that is free on disk and not by another item. + private static string FreePath(string taken, bool isFolder, IEnumerable claimed) + { + var others = new HashSet(claimed, StringComparer.OrdinalIgnoreCase); + var directory = Path.GetDirectoryName(taken)!; + var fileName = Path.GetFileName(taken); + var name = isFolder ? fileName : V3Names.RequestStem(taken); + for (var i = 1; ; i++) + { + var candidate = Path.Combine(directory, $"{name}-{i}{fileName[name.Length..]}"); + if (!Path.Exists(candidate) && !others.Contains(candidate) && (isFolder || !Path.Exists(V3Names.ResourcesPath(candidate)))) + { + return candidate; + } + } + } + private static void Rebase(Dictionary current, string from, string to) { var prefix = from + Path.DirectorySeparatorChar; @@ -707,6 +1176,7 @@ private static JsonObject Snapshot(JsonObject item) private static double? OrderValue(JsonNode? node) => node is JsonValue value && double.TryParse(value.GetString(), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var number) + && double.IsFinite(number) ? number : null; diff --git a/src/TermRest.Core/Postman/V3/V3Convert.cs b/src/TermRest.Core/Postman/V3/V3Convert.cs index c19cb1c..6403000 100644 --- a/src/TermRest.Core/Postman/V3/V3Convert.cs +++ b/src/TermRest.Core/Postman/V3/V3Convert.cs @@ -21,11 +21,11 @@ internal static class V3Convert internal static readonly string[] DefinitionOrder = ["$kind", "id", "name", "description", "auth", "variables", "scripts", "order"]; private static readonly string[] KeyValueOrder = ["key", "value", "description", "disabled", "$type"]; - private static readonly string[] FormDataOrder = ["type", "key", "value", "src", "contentType", "disabled"]; + private static readonly string[] FormDataOrder = ["type", "key", "value", "src", "contentType", "description", "disabled"]; private static readonly string[] AuthOrder = ["id", "type", "name", "rules", "credentials"]; private static readonly string[] ScriptOrder = ["type", "code", "language", "packages", "requests"]; private static readonly string[] VariableOrder = ["key", "value", "disabled", "secret", "description", "source"]; - private static readonly string[] EnvironmentValueOrder = ["key", "value", "enabled", "type", "description"]; + private static readonly string[] EnvironmentValueOrder = ["key", "value", "enabled", "disabled", "type", "description", "secret", "source"]; /// Request settings the v3 schema allows (v2.1 protocolProfileBehavior has a few more). private static readonly HashSet V3Settings = @@ -161,7 +161,7 @@ private static JsonArray KeyValuesToV21(JsonNode? node) return result; } - /// Request, folder or collection auth. "inherit" (or no auth) is null; for several auths only the first is used. + /// Request, folder or collection auth. "inherit" (or no auth) is null; of several credential sets, the first. public static JsonObject? AuthToV21(JsonNode? node) { if (node is JsonArray multiple) @@ -215,6 +215,67 @@ JsonValue v when v.GetValueKind() is JsonValueKind.True or JsonValueKind.False = }, }; + /// + /// A collection's or folder's credential sets selected by rules (a list of auths), for : + /// each with its name, its rules as key/value pairs (Postman writes them as a map, url: api.example.com; its + /// schema as a list of {key, value}) and its auth in v2.1 form. Null for one auth, or a list of one without rules. + /// + public static JsonArray? CredentialSetsToV21(JsonNode? node) + { + if (node is not JsonArray list || list.OfType().ToList() is not { Count: > 0 } sets || (sets.Count == 1 && sets[0]["rules"] is null)) + { + return null; + } + + var result = new JsonArray(); + foreach (var set in sets) + { + var rules = new JsonArray(); + switch (set["rules"]) + { + case null: + break; + case JsonObject map: + foreach (var (key, value) in map) + { + rules.Add((JsonNode)new JsonObject { ["key"] = key, ["value"] = value.GetString() ?? value?.ToJsonString() }); + } + + break; + case JsonArray entries: + foreach (var entry in entries) + { + // An entry that isn't {key, value} (a plain pattern, say) can't be checked: a rule that never matches. + rules.Add((JsonNode)(entry is JsonObject rule + ? new JsonObject { ["key"] = rule["key"].GetString() ?? "", ["value"] = rule["value"].GetString() ?? rule["value"]?.ToJsonString() } + : new JsonObject { ["key"] = "", ["value"] = entry?.ToJsonString() })); + } + + break; + case var other: + // Rules of another shape can't be checked: a rule that never matches, so its credentials go nowhere. + rules.Add((JsonNode)new JsonObject { ["key"] = "", ["value"] = other.ToJsonString() }); + break; + } + + result.Add((JsonNode)new JsonObject + { + ["name"] = set["name"].GetString() ?? set["id"].GetString() ?? Model.AuthSpec.DisplayName(set["type"].GetString() ?? "noauth"), + ["rules"] = rules, + ["auth"] = AuthToV21(set), + ["v3"] = set.DeepClone(), // as the file has it: a copy of the folder is written with it (see DefinitionToV3) + }); + } + + return result; + } + + /// + /// The property of a v2.1 folder (or collection) object that holds its v3 credential sets (see + /// ), next to its auth (the first set). Not written to v2.1 files. + /// + public const string AuthSetsProperty = "x-v3-auth-sets"; + /// /// v3 scripts → v2.1 events. Script types other than HTTP ones keep their v3 name as the event name. Scripts in /// TermRest's other languages than JavaScript become disabled events, as TermRest writes them in v2.1 files: Postman @@ -282,9 +343,20 @@ public static JsonArray ScriptsToEvents(JsonNode? node) return result; } + /// Collection and folder variables: v3 allows a list of entries or, for plain ones, a {name: value} map. public static JsonArray VariablesToV21(JsonNode? node) { var array = new JsonArray(); + if (node is JsonObject map) + { + foreach (var (key, value) in map) + { + array.Add((JsonNode)new JsonObject { ["key"] = key, ["value"] = Text(value) }); + } + + return array; + } + foreach (var variable in (node as JsonArray)?.OfType() ?? []) { var entry = (JsonObject)variable.DeepClone(); @@ -305,7 +377,11 @@ public static JsonArray VariablesToV21(JsonNode? node) public static JsonObject RequestToV3(JsonObject item, JsonObject? template) { var v3 = template is null ? new JsonObject() : (JsonObject)template.DeepClone(); - v3.SetOrdered("$kind", HttpRequestKind, RequestOrder); + if (template is null) + { + v3.SetOrdered("$kind", HttpRequestKind, RequestOrder); // a file keeps its own, or none + } + if (item["request"] is not JsonObject request) { request = new JsonObject { ["method"] = "GET", ["url"] = item["request"]?.DeepClone() }; @@ -315,10 +391,16 @@ public static JsonObject RequestToV3(JsonObject item, JsonObject? template) var (raw, query, variables) = ReadUrl(request["url"]); Set(v3, "url", raw.Length == 0 && template?["url"] is null ? null : JsonValue.Create(raw), RequestOrder); v3.SetOrdered("method", request["method"].GetString() ?? "GET", RequestOrder); - Set(v3, "headers", KeyValuesToV3(request["header"] as JsonArray, template?["headers"], mapWhenNew: true), RequestOrder); + Set(v3, "headers", KeyValuesToV3(HeaderList(request["header"]), template?["headers"], mapWhenNew: true), RequestOrder); Set(v3, "queryParams", KeyValuesToV3(query, template?["queryParams"], mapWhenNew: false), RequestOrder); Set(v3, "pathVariables", KeyValuesToV3(variables, template?["pathVariables"], mapWhenNew: false), RequestOrder); - Set(v3, "body", BodyToV3(request["body"] as JsonObject, template?["body"]), RequestOrder); + + // A body that wasn't edited stays as the file has it, also one TermRest can't read (a type it doesn't know, fields + // under another key): rebuilt from what TermRest read of it, it would be lost. + var fileBody = template?["body"]; + Set(v3, "body", fileBody is not null && JsonNode.DeepEquals(BodyToV21(fileBody), request["body"]) + ? fileBody.DeepClone() + : BodyToV3(request["body"] as JsonObject, fileBody), RequestOrder); Set(v3, "auth", AuthToV3(request["auth"] as JsonObject, template?["auth"]), RequestOrder); Set(v3, "scripts", EventsToScripts(item["event"] as JsonArray, template?["scripts"], http: false), RequestOrder); Set(v3, "termrest", item["termrest"] is JsonObject { Count: > 0 } termrest ? termrest.DeepClone() : null, RequestOrder); @@ -328,10 +410,18 @@ public static JsonObject RequestToV3(JsonObject item, JsonObject? template) private static (string Raw, JsonArray? Query, JsonArray? Variables) ReadUrl(JsonNode? url) => url switch { - JsonObject obj => (obj["raw"].GetString() ?? "", obj["query"] as JsonArray, obj["variable"] as JsonArray), + JsonObject obj => (PostmanRequestMapper.RawUrl(obj), obj["query"] as JsonArray, obj["variable"] as JsonArray), _ => (url.GetString() ?? "", null, null), }; + /// Headers as a list of entries: Postman v2 also allows one "Key: Value\n…" string. + private static JsonArray? HeaderList(JsonNode? node) => node switch + { + JsonArray list => list, + JsonValue => PostmanRequestMapper.WriteKeyValues(PostmanRequestMapper.ReadKeyValues(node), KeyValueStyle.Header), + _ => null, + }; + /// /// Headers, parameters and urlencoded fields keep the form the file used: a {name: value} map (possible while /// every entry is a plain, enabled, unique name/value pair) or a list of entries. New ones use @@ -346,7 +436,8 @@ public static JsonObject RequestToV3(JsonObject item, JsonObject? template) var list = entries.OfType().ToList(); var simple = (template is JsonObject || (template is null && mapWhenNew)) - && list.All(e => e["value"] is JsonValue && e["key"].GetString() is { Length: > 0 } + && list.All(e => (e["value"] is JsonValue || (template is JsonObject && e["value"] is null)) + && e["key"].GetString() is { } key && (key.Length > 0 || template is JsonObject) && e.All(p => p.Key is "key" or "value" or "type" || (p.Key == "disabled" && p.Value.GetBool() == false)) && (e["type"] is null || e["type"].GetString() == "text")) && list.Select(e => e["key"].GetString()).Distinct(StringComparer.Ordinal).Count() == list.Count; @@ -377,6 +468,7 @@ private static JsonArray KeyValueListToV3(JsonArray entries, JsonNode? template) result.Remove("type"); // a v2.1 detail; v3 uses $type } + DescriptionToText(result); Order(result, KeyValueOrder); var match = templates.FirstOrDefault(t => JsonNode.DeepEquals(t, result)); array.Add(match is null ? result : match.DeepClone()); @@ -390,7 +482,8 @@ private static JsonArray KeyValueListToV3(JsonArray entries, JsonNode? template) var mode = body?["mode"].GetString(); if (body is null || mode is null or "none") { - return template is JsonObject t && t["type"].GetString() == "none" ? t.DeepClone() : null; + // A body without a type, which TermRest can't read (one written in v2.1's form, say) and showed as none, is kept. + return template is JsonObject t && t["type"].GetString() is null or "none" ? t.DeepClone() : null; } var type = mode switch @@ -463,7 +556,7 @@ private static JsonArray FormDataToV3(JsonArray fields, JsonNode? template) { var result = (JsonObject)field.DeepClone(); result["type"] = result["type"].GetString() == "file" ? "file" : "text"; - result.Remove("description"); + DescriptionToText(result); if (result["type"].GetString() == "file") { result.Remove("value"); @@ -509,14 +602,25 @@ private static JsonArray FormDataToV3(JsonArray fields, JsonNode? template) return result; } - var parameters = (auth[type] as JsonArray)?.OfType().ToList() ?? []; + // Postman v2.0 stores the parameters as a plain object, v2.1 as a list of entries. + List<(string Key, JsonNode? Value)> parameters = auth[type] switch + { + JsonArray entries => [.. entries.OfType().Select(p => (p["key"].GetString() ?? "", p["value"]))], + JsonObject map => [.. map.Select(p => (p.Key, p.Value))], + _ => [], + }; + if (parameters.Count == 0 && previous is not null && !previous.ContainsKey("credentials")) + { + return result; // as the file has it: no credentials + } + JsonNode credentials; if (previous?["credentials"] is JsonArray) { var array = new JsonArray(); - foreach (var p in parameters) + foreach (var (key, value) in parameters) { - array.Add((JsonNode)new JsonObject { ["key"] = p["key"].GetString() ?? "", ["value"] = p["value"]?.DeepClone() }); + array.Add((JsonNode)new JsonObject { ["key"] = key, ["value"] = value?.DeepClone() }); } credentials = array; @@ -525,10 +629,9 @@ private static JsonArray FormDataToV3(JsonArray fields, JsonNode? template) { var map = new JsonObject(); var previousMap = previous?["credentials"] as JsonObject; - foreach (var p in parameters) + foreach (var (key, value) in parameters) { - var key = p["key"].GetString() ?? ""; - map[key] = Reuse(previousMap?[key], p["value"]); + map[key] = Reuse(previousMap?[key], value); } credentials = map; @@ -540,7 +643,8 @@ private static JsonArray FormDataToV3(JsonArray fields, JsonNode? template) /// /// v2.1 events → v3 scripts (beforeRequest/afterResponse, or http:… on folders): one per type and - /// language, each written over the script of that type and language the file had. + /// language, each written over the script of that type and language the file had. A disabled JavaScript script is + /// left out: v3 cannot mark a script disabled, and Postman does not run it. /// public static JsonArray? EventsToScripts(JsonArray? events, JsonNode? template, bool http) { @@ -548,6 +652,13 @@ private static JsonArray FormDataToV3(JsonArray fields, JsonNode? template) var scripts = new JsonArray(); foreach (var e in events?.OfType() ?? []) { + var script = e["script"] as JsonObject; + var language = ScriptLanguage.FromType(script?["type"].GetString()); + if (language == ScriptLanguage.JavaScript && e["disabled"].GetBool() == true) + { + continue; + } + var listen = e["listen"].GetString() ?? ""; var type = e["x-v3-type"].GetString() is { Length: > 0 } original ? original : listen switch { @@ -555,10 +666,8 @@ private static JsonArray FormDataToV3(JsonArray fields, JsonNode? template) "test" => http ? "http:afterResponse" : "afterResponse", _ => listen, }; - var script = e["script"] as JsonObject; var exec = script?["exec"]; var code = exec is JsonArray lines ? string.Join('\n', lines.Select(l => l.GetString() ?? "")) : exec.GetString() ?? ""; - var language = ScriptLanguage.FromType(script?["type"].GetString()); var previous = templates.FirstOrDefault(t => t["type"].GetString() == type && ScriptLanguage.FromType(t["language"].GetString()) == language); if (previous is not null) { @@ -573,9 +682,13 @@ private static JsonArray FormDataToV3(JsonArray fields, JsonNode? template) result.SetOrdered("type", type, ScriptOrder); result.SetOrdered("code", code, ScriptOrder); - // A script's language comes with its code; an empty one keeps the language the file has (Postman's: JavaScript). + // A script's language comes with its code; an empty one keeps the language the file has (Postman's: JavaScript), + // and a JavaScript one in a file that leaves its language out stays without it. var languageType = code.Trim().Length == 0 && previous?["language"] is { } kept ? kept : script?["type"] ?? previous?["language"]; - result.SetOrdered("language", languageType?.DeepClone() ?? "text/javascript", ScriptOrder); + if (previous is null || previous.ContainsKey("language") || language != ScriptLanguage.JavaScript) + { + result.SetOrdered("language", languageType?.DeepClone() ?? "text/javascript", ScriptOrder); + } foreach (var extra in (string[])["packages", "requests"]) { if (script?[extra] is JsonObject { Count: > 0 } value) @@ -653,9 +766,13 @@ public static void DefinitionToV21(JsonObject? definition, JsonObject target, bo if (AuthToV21(definition["auth"]) is { } auth) { target["auth"] = auth; + if (CredentialSetsToV21(definition["auth"]) is { } sets) + { + target[AuthSetsProperty] = sets; + } } - if (definition["variables"] is JsonArray) + if (definition["variables"] is JsonArray or JsonObject) { target["variable"] = VariablesToV21(definition["variables"]); } @@ -665,16 +782,79 @@ public static void DefinitionToV21(JsonObject? definition, JsonObject target, bo public static JsonObject DefinitionToV3(JsonObject source, JsonObject? template, bool isRoot) { var v3 = template is null ? new JsonObject() : (JsonObject)template.DeepClone(); - v3.SetOrdered("$kind", CollectionKind, DefinitionOrder); + if (template is null) + { + // A file keeps its own: Postman writes "collection", also for folders, but some files say "folder" or have none. + v3.SetOrdered("$kind", CollectionKind, DefinitionOrder); + } + var description = isRoot ? (source["info"] as JsonObject)?["description"] : source["description"]; Set(v3, "description", Description(description, template), DefinitionOrder); - Set(v3, "auth", AuthToV3(source["auth"] as JsonObject, template?["auth"]), DefinitionOrder); + Set(v3, "auth", AuthToV3(source["auth"] as JsonObject, AuthTemplate(source, template)), DefinitionOrder); Set(v3, "variables", source["variable"] is JsonArray variables ? VariablesToV3(variables, template?["variables"]) : null, DefinitionOrder); Set(v3, "scripts", EventsToScripts(source["event"] as JsonArray, template?["scripts"], http: true), DefinitionOrder); return v3; } - private static JsonArray VariablesToV3(JsonArray variables, JsonNode? template) + /// + /// The auth a folder's definition is written over: its file's; for a folder without a file of its own yet (a copy of + /// one), the credential sets it holds (see ) as its original's file has them, with ids + /// of their own, so that the copy keeps their rules and its credentials go no further than the original's. + /// + private static JsonNode? AuthTemplate(JsonObject source, JsonObject? template) + { + if (template?["auth"] is not null || source[AuthSetsProperty] is not JsonArray sets || sets.Any(s => s?["v3"] is not JsonObject)) + { + return template?["auth"]; + } + + var list = new JsonArray(); + foreach (var set in sets) + { + var copy = (JsonObject)set!["v3"]!.DeepClone(); + if (copy.ContainsKey("id")) + { + copy["id"] = Guid.NewGuid().ToString(); + } + + list.Add((JsonNode)copy); + } + + return list; + } + + /// + /// The secret variables (of a v2.1 collection and its folders) whose values a conversion to v3 leaves out: Postman's v3 + /// collections keep secret values out of their files, where a secret variable has no value. + /// + public static List SecretValuesLeftOut(JsonObject collection) + { + var names = new List(); + void Visit(JsonObject node) + { + foreach (var variable in (node["variable"] as JsonArray)?.OfType() ?? []) + { + if (variable["type"].GetString() == "secret" && Text(variable["value"]) is { Length: > 0 } && variable["key"].GetString() is { } key) + { + names.Add(key); + } + } + + foreach (var folder in (node["item"] as JsonArray)?.OfType().Where(i => i["item"] is JsonArray) ?? []) + { + Visit(folder); + } + } + + Visit(collection); + return names; + } + + /// + /// Variables keep the form the file used: a {name: value} map (possible while every variable is a plain, enabled, + /// unique name/value pair, as Postman writes them) or a list of entries. + /// + private static JsonNode VariablesToV3(JsonArray variables, JsonNode? template) { var templates = (template as JsonArray)?.OfType().ToList() ?? []; var array = new JsonArray(); @@ -692,24 +872,72 @@ private static JsonArray VariablesToV3(JsonArray variables, JsonNode? template) result.Remove("secret"); } + // "disabled: false" stays where the file has it (some Postman versions write it for every variable). + var previous = templates.FirstOrDefault(t => t["key"].GetString() == result["key"].GetString()); if (result["disabled"].GetBool() != true) { - result.Remove("disabled"); + if (previous?["disabled"].GetBool() == false) + { + result["disabled"] = false; + } + else + { + result.Remove("disabled"); + } } + DescriptionToText(result); + // Secrets from a vault have no value; TermRest's editor reads a missing value as "". - var previous = templates.FirstOrDefault(t => t["key"].GetString() == result["key"].GetString()); if (previous is not null && !previous.ContainsKey("value") && result["value"].GetString() is "" or null) { result.Remove("value"); } + if (previous is null && template is not JsonObject) + { + // One the file doesn't have yet (a converted collection's) takes the shape of Postman's v3 schema: its value is + // text, a secret variable has none (Postman keeps secret values out of the file; see SecretValuesLeftOut), + // and v2.1's other keys (id, name, system …) have no place there. (A map's entries are plain name/value pairs + // already, kept below as the file writes them.) + foreach (var key in result.Select(p => p.Key).Where(k => !VariableOrder.Contains(k)).ToList()) + { + result.Remove(key); + } + + if (secret || result["value"] is null) + { + result.Remove("value"); + } + else + { + result["value"] = Text(result["value"]); + } + } + Order(result, VariableOrder); var match = templates.FirstOrDefault(t => JsonNode.DeepEquals(t, result)); array.Add(match is null ? result : match.DeepClone()); } - return array; + if (template is not JsonObject map + || !array.All(v => v is JsonObject { Count: 2 } e && e["key"].GetString() is { Length: > 0 } && e.TryGetPropertyValue("value", out var value) && value is JsonValue or null) + || array.Select(v => v!["key"].GetString()).Distinct(StringComparer.Ordinal).Count() != array.Count) + { + return array; + } + + var mapped = new JsonObject(); + foreach (var variable in array.Cast()) + { + var key = variable["key"].GetString()!; + var value = variable["value"]; + + // The file's value when it means the same text: a number stays unquoted, an empty value stays as it was written. + mapped[key] = map.TryGetPropertyValue(key, out var previous) && (Text(previous) ?? "") == (Text(value) ?? "") ? previous?.DeepClone() : value?.DeepClone(); + } + + return mapped; } // ----- environments and globals ------------------------------------------------------------ @@ -718,10 +946,35 @@ public static JsonObject EnvironmentToV21(JsonObject v3, string fallbackName, bo { var env = (JsonObject)v3.DeepClone(); env["name"] ??= fallbackName; - if (env["values"] is not JsonArray) + if (env["values"] is not JsonArray values) { env["values"] = new JsonArray(); } + else + { + // Postman also marks a secret with "secret: true", its value left out of the file; v2.1 has "type: secret". And + // a disabled value with "disabled: true" where values have no "enabled"; v2.1 environments have "enabled: false". + foreach (var value in values.OfType()) + { + if (value["secret"].GetBool() is { } secret) + { + value.Remove("secret"); + if (secret) + { + value["type"] = "secret"; + } + } + + if (value["disabled"].GetBool() is { } disabled) + { + value.Remove("disabled"); + if (disabled) + { + value["enabled"] = false; + } + } + } + } env["_postman_variable_scope"] = globals ? "globals" : "environment"; return env; @@ -732,16 +985,63 @@ public static JsonObject EnvironmentToV3(JsonObject env, JsonObject? template) var v3 = template is null ? new JsonObject() : (JsonObject)template.DeepClone(); v3.SetOrdered("name", env["name"]?.DeepClone() ?? "Environment", ["name", "values"]); var templates = (template?["values"] as JsonArray)?.OfType().ToList() ?? []; + + // Secrets keep the form the file marks them with: "secret: true" (Postman's, also for new ones there) or "type: secret". + var secretKeyForm = templates.Any(t => t.ContainsKey("secret")) && !templates.Any(t => t["type"].GetString() == "secret"); + + // Disabled values too: "disabled: true" in a file whose values have no "enabled" (as Postman writes them), else + // "enabled: false". + var disabledKeyForm = templates.Count > 0 && !templates.Any(t => t.ContainsKey("enabled")); var values = new JsonArray(); foreach (var value in (env["values"] as JsonArray)?.OfType() ?? []) { var result = (JsonObject)value.DeepClone(); var previous = templates.FirstOrDefault(t => t["key"].GetString() == result["key"].GetString()); + if ((previous?.ContainsKey("disabled") ?? false) || (!(previous?.ContainsKey("enabled") ?? false) && disabledKeyForm)) + { + var enabled = result["enabled"].GetBool() ?? true; + result.Remove("enabled"); + if (!enabled) + { + result["disabled"] = true; + } + else if (previous?["disabled"].GetBool() == false) + { + result["disabled"] = false; + } + } + + if (previous is null ? secretKeyForm : previous.ContainsKey("secret") || (secretKeyForm && previous["type"] is null)) + { + if (result["type"].GetString() == "secret") + { + result["secret"] = true; + if (previous?["type"] is { } type && type.GetString() != "secret") + { + result["type"] = type.DeepClone(); + } + else + { + result.Remove("type"); + } + } + else if (previous?["secret"].GetBool() == false) + { + result["secret"] = false; + } + } + if (result["type"].GetString() == "default" && previous?["type"] is null) { result.Remove("type"); // Postman only writes "type" for secrets } + // A value the file leaves out (Postman's, for a secret it keeps elsewhere) stays out while it is empty. + if (previous is not null && !previous.ContainsKey("value") && result["value"].GetString() is "" or null) + { + result.Remove("value"); + } + Order(result, EnvironmentValueOrder); var match = templates.FirstOrDefault(t => JsonNode.DeepEquals(t, result)); values.Add((JsonNode)(match is null ? result : match.DeepClone())); @@ -793,7 +1093,7 @@ public static JsonObject ExampleToV3(JsonObject response) static JsonArray? CleanHeaders(JsonNode? node) { - if (node is not JsonArray { Count: > 0 } headers) + if (HeaderList(node) is not { Count: > 0 } headers) { return null; } @@ -802,7 +1102,7 @@ public static JsonObject ExampleToV3(JsonObject response) foreach (var header in headers.OfType()) { var entry = new JsonObject { ["key"] = header["key"].GetString() ?? header["name"].GetString() ?? "", ["value"] = Text(header["value"]) ?? "" }; - if (header["description"].GetString() is { Length: > 0 } description) + if (DescriptionText(header["description"]) is { Length: > 0 } description) { entry["description"] = description; } @@ -839,10 +1139,30 @@ private static void Set(JsonObject obj, string key, string? value, string[] orde /// A v2.1 description (text or {content}); an empty description the file had stays as written. private static string? Description(JsonNode? node, JsonObject? template) { - var text = Text(node is JsonObject d ? d["content"] : node); + var text = DescriptionText(node); return string.IsNullOrEmpty(text) && template?["description"].GetString() == "" ? "" : text; } + /// A v2.1 description as text: v2.1 also allows a {content, type} object. + private static string? DescriptionText(JsonNode? node) => Text(node is JsonObject d ? d["content"] : node); + + /// + /// Makes the description of a header, parameter, field or variable the text v3 allows: a v2.1 {content, type} + /// object becomes its content, and one without content, or null, is left out. + /// + private static void DescriptionToText(JsonObject entry) + { + switch (entry["description"]) + { + case JsonObject description when DescriptionText(description) is { Length: > 0 } text: + entry["description"] = text; + break; + case JsonObject or null: + entry.Remove("description"); + break; + } + } + /// A scalar as text (v2.1 keeps header and parameter values as strings). private static string? Text(JsonNode? node) => node switch { diff --git a/src/TermRest.Core/Postman/V3/V3Names.cs b/src/TermRest.Core/Postman/V3/V3Names.cs index 5ca4e5e..a7cd869 100644 --- a/src/TermRest.Core/Postman/V3/V3Names.cs +++ b/src/TermRest.Core/Postman/V3/V3Names.cs @@ -13,18 +13,28 @@ internal static class V3Names private static readonly HashSet ReservedNames = new(StringComparer.OrdinalIgnoreCase) { - "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", - "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", + "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM¹", "COM²", "COM³", + "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "LPT¹", "LPT²", "LPT³", }; - /// A file-system-safe name: characters that are invalid on any OS become "-" (like Postman does). + private static readonly string[] CollectionFolders = ["collections"]; + + private static readonly string[] LayoutFolders = ["collections", "environments", "globals"]; + + /// + /// A file-system-safe name: characters that are invalid on any OS become "-" (like Postman does), and so do leading + /// dots, which would hide the file or folder (folders starting with "." are not loaded, and ".resources" is taken). + /// public static string Safe(string name) { var chars = name.Select(c => c is '/' or '\\' or ':' or '*' or '?' or '"' or '<' or '>' or '|' || char.IsControl(c) ? '-' : c).ToArray(); var safe = new string(chars).Trim(); if (safe.Length > MaxLength) { - safe = safe[..MaxLength]; + // Never between the two halves of a surrogate pair (an emoji, say): git cannot add a file whose name ends in + // half a character, and on Unix .NET writes it as U+FFFD. + safe = safe[..(char.IsHighSurrogate(safe[MaxLength - 1]) ? MaxLength - 1 : MaxLength)]; } safe = safe.TrimEnd('.', ' '); @@ -33,7 +43,13 @@ public static string Safe(string name) safe = "untitled"; } - return ReservedNames.Contains(safe.Split('.')[0]) ? safe + "-" : safe; + var dots = safe.Length - safe.TrimStart('.').Length; + safe = new string('-', dots) + safe[dots..]; + + // Windows reserves a device name also with an extension (NUL.txt is NUL), spaces before the dot ignored, and so does + // Git for Windows: the "-" goes right after the name (con.example.org becomes con-.example.org). + var stem = safe.Split('.')[0].TrimEnd(' '); + return ReservedNames.Contains(stem) ? string.Concat(stem, "-", safe.AsSpan(stem.Length)) : safe; } public static bool IsRequestFile(string path) => @@ -52,20 +68,61 @@ public static string RequestStem(string path) public static string ResourcesPath(string requestFile) => Path.Combine(Path.GetDirectoryName(requestFile)!, ResourcesDirectory, RequestStem(requestFile) + ".resources"); - /// A folder is a v3 collection when it has a collection definition or request files of its own. + /// + /// A folder is a v3 collection when it has a collection definition or request files of its own; or, in a workspace's + /// postman/collections folder (where Postman keeps collections, and writes no definition for one without settings + /// of its own), when its folders have them. + /// public static bool IsCollectionDirectory(string directory) => Directory.Exists(directory) - && (File.Exists(DefinitionPath(directory)) - || Directory.EnumerateFiles(directory, "*.request.y*ml").Any(IsRequestFile)); + && (HasContent(directory) || (IsInCollectionsFolder(directory) && FoldersHaveContent(directory, MaxFolderDepth))); + + private const int MaxFolderDepth = 16; + + private static readonly EnumerationOptions FolderSearch = new() { IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint }; + + private static bool HasContent(string directory) => + File.Exists(DefinitionPath(directory)) || Directory.EnumerateFiles(directory, "*.request.y*ml").Any(IsRequestFile); + + /// Whether folders of (not hidden ones, nor links) have definitions or requests. + private static bool FoldersHaveContent(string directory, int depth) + { + try + { + return depth > 0 && Directory.EnumerateDirectories(directory, "*", FolderSearch) + .Any(sub => !Path.GetFileName(sub).StartsWith('.') && (HasContent(sub) || FoldersHaveContent(sub, depth - 1))); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } + + /// Whether is in a postman/collections folder, where Postman keeps collections. + public static bool IsInCollectionsFolder(string directory) + { + var parent = Path.GetDirectoryName(Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory))); + return parent is not null && string.Equals(Path.GetFileName(parent), CollectionFolders[0], StringComparison.OrdinalIgnoreCase) + && string.Equals(Path.GetFileName(Path.GetDirectoryName(parent)), "postman", StringComparison.OrdinalIgnoreCase); + } /// The workspace folder for a collection directory: the folder that holds postman/collections. - public static string WorkspaceRootFor(string collectionDirectory) + public static string WorkspaceRootFor(string collectionDirectory) => WorkspaceRootAbove(collectionDirectory, CollectionFolders); + + /// + /// The workspace folder for a file given on its own: the folder that holds postman for a file in + /// postman/collections, postman/environments or postman/globals, where the workspace keeps such + /// files; else the folder the file is in. + /// + public static string WorkspaceRootForFile(string file) => WorkspaceRootAbove(file, LayoutFolders); + + private static string WorkspaceRootAbove(string path, string[] folders) { - var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(collectionDirectory)); + var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); var parent = Path.GetDirectoryName(full); var grandparent = parent is null ? null : Path.GetDirectoryName(parent); if (parent is not null && grandparent is not null - && Path.GetFileName(parent).Equals("collections", StringComparison.OrdinalIgnoreCase) + && folders.Contains(Path.GetFileName(parent), StringComparer.OrdinalIgnoreCase) && Path.GetFileName(grandparent).Equals("postman", StringComparison.OrdinalIgnoreCase) && Path.GetDirectoryName(grandparent) is { } root) { diff --git a/src/TermRest.Core/Recording/HarEntryWriter.cs b/src/TermRest.Core/Recording/HarEntryWriter.cs index 04aea1f..59cbc83 100644 --- a/src/TermRest.Core/Recording/HarEntryWriter.cs +++ b/src/TermRest.Core/Recording/HarEntryWriter.cs @@ -78,33 +78,49 @@ internal static void WriteBody(Utf8JsonWriter writer, string property, byte[] da } } - /// The bytes to write and how: text bodies in another charset (Latin-1, UTF-16 …) are converted to UTF-8. + /// + /// The bytes to write and how: text bodies in another charset (Latin-1, UTF-16 …) are converted to UTF-8, so that the + /// secrets in them are found. A UTF-16 or UTF-32 byte order mark says which, also when the Content-Type names no charset. + /// internal static (byte[] Data, BodyFormat Format) Classify(byte[] body, string? contentType) { var format = ExchangeRedactor.DetectFormat(contentType, body); - if (format != BodyFormat.Binary || body.Length == 0 || Charset(contentType) is not { } charset - || !ExchangeRedactor.IsTextual(ExchangeRedactor.MediaType(contentType))) + if (body.Length == 0 || !ExchangeRedactor.IsTextual(ExchangeRedactor.MediaType(contentType))) { return (body, format); } - try + if (WideMark(body) is { } marked) { - var encoding = Encoding.GetEncoding(charset); - if (encoding.CodePage == Encoding.UTF8.CodePage) - { - return (body, format); - } + var text = marked.GetString(body, marked.Preamble.Length, body.Length - marked.Preamble.Length); + var bytes = Encoding.UTF8.GetBytes(text); + return (bytes, ExchangeRedactor.DetectFormat(contentType, bytes)); + } - var converted = Encoding.UTF8.GetBytes(encoding.GetString(body)); - return (converted, ExchangeRedactor.DetectFormat(contentType, converted)); + if (Charset(contentType) is not { } charset || (format != BodyFormat.Binary && System.Text.Unicode.Utf8.IsValid(body))) + { + return (body, format); } - catch (ArgumentException) + + // As the body is shown (legacy code pages such as windows-1252 included); a charset this platform does not know, + // or does not support (UTF-7), leaves the bytes as they are. + if (Http.BodyFormatter.GetEncoding(charset) is not { } encoding || encoding.CodePage == Encoding.UTF8.CodePage) { - return (body, format); // a charset this platform does not know + return (body, format); } + + // UTF-16 without a byte order mark in the byte order its text shows, as the body is shown. + var converted = Encoding.UTF8.GetBytes(Http.BodyFormatter.InByteOrder(encoding, body).GetString(body)); + return (converted, ExchangeRedactor.DetectFormat(contentType, converted)); } + /// The UTF-16 or UTF-32 encoding whose byte order mark starts with; null for none. + private static Encoding? WideMark(byte[] body) => WideEncodings.FirstOrDefault(encoding => body.AsSpan().StartsWith(encoding.Preamble)); + + // The UTF-32 little-endian mark starts with the UTF-16 one: it is checked first. + private static readonly Encoding[] WideEncodings = + [Encoding.UTF32, new UTF32Encoding(bigEndian: true, byteOrderMark: true), Encoding.Unicode, Encoding.BigEndianUnicode]; + private static void WriteRequest(Utf8JsonWriter writer, RecordedExchange recorded, string url, List> headers, PostData? postData) { var exchange = recorded.Exchange; @@ -186,6 +202,12 @@ private static void WriteResponse(Utf8JsonWriter writer, HttpExchange exchange, writer.WriteStartObject("content"); writer.WriteNumber("size", response.Body.LongLength); + if (response.ReceivedBodySize is { } received && received != response.Body.LongLength && !response.BodyTruncated) + { + // Decoded (gzip …): the bytes saved, so that size = bodySize + compression. + writer.WriteNumber("compression", response.Body.LongLength - received); + } + writer.WriteString("mimeType", response.ContentType ?? "x-unknown"); if (response.Body.Length > 0) { @@ -202,7 +224,7 @@ private static void WriteResponse(Utf8JsonWriter writer, HttpExchange exchange, writer.WriteEndObject(); writer.WriteString("redirectURL", headers.LastOrDefault(h => h.Key.Equals("Location", StringComparison.OrdinalIgnoreCase)).Value ?? ""); writer.WriteNumber("headersSize", -1); - writer.WriteNumber("bodySize", -1); + writer.WriteNumber("bodySize", response.ReceivedBodySize ?? -1); writer.WriteEndObject(); } @@ -545,9 +567,9 @@ private static void WriteTextSegments(Utf8JsonWriter writer, ReadOnlySpan { while (data.Length > TextChunk) { - // Cut before a UTF-8 continuation byte, never inside a character. + // Cut before a UTF-8 continuation byte, never inside a character (a character has at most three). var cut = TextChunk; - while (cut > 0 && (data[cut] & 0xC0) == 0x80) + while (cut > TextChunk - 3 && (data[cut] & 0xC0) == 0x80) { cut--; } @@ -756,7 +778,7 @@ private static Part TextPart(MultipartPart part, ExchangeRedactor redactor) { Name = part.Name, FileName = Path.GetFileName(part.FilePath), - ContentType = part.ContentType ?? "application/octet-stream", + ContentType = part.SentContentType, File = FileReference.Create(part.FilePath!, redactor, Location), Comment = FileReference.Comment, }; diff --git a/src/TermRest.Core/Recording/Redactor.cs b/src/TermRest.Core/Recording/Redactor.cs index 2a5ed4f..24c04a7 100644 --- a/src/TermRest.Core/Recording/Redactor.cs +++ b/src/TermRest.Core/Recording/Redactor.cs @@ -1,18 +1,20 @@ using System.Net; using System.Text; -using System.Text.Encodings.Web; using System.Text.Json; +using System.Text.RegularExpressions; using System.Text.Unicode; using TermRest.Core.Http; -using TermRest.Core.Json; namespace TermRest.Core.Recording; -/// How a recorded body is written: as text (redacted with JSON or form rules where they apply) or as base64. +/// How a recorded body is written: as text (redacted with JSON, form or form-data rules where they apply) or as base64. public enum BodyFormat { Json, Form, + + /// multipart/form-data that is entirely UTF-8 (one with binary files is ). + Multipart, Text, Binary, } @@ -34,6 +36,9 @@ public sealed class RedactionNote public const string UrlPasswordReason = "URL password"; + /// The user name of a URL without a password: it is then the credential (an API key, as Stripe takes it). + public const string UrlUserReason = "URL user name"; + public required string Location { get; init; } public string? Name { get; init; } @@ -50,7 +55,9 @@ public sealed class RedactionNote /// The secrets of one recording. Values are redacted by name: headers, URL parameters and body fields named like /// credentials (see ), and all cookie values. They are also redacted by value: auth /// credentials, secret variables, variables named like secrets, and every value already redacted by name are replaced -/// wherever they appear (URLs, headers, bodies, error messages), also in later requests of the recording. +/// wherever they appear (URLs, headers, bodies, error messages), also in later requests of the recording (a cookie's +/// value until the cookie is set again). The values are looked for in one pass however many there are (see +/// ), so the work for a request does not grow with the length of the recording. /// public sealed class Redactor { @@ -66,53 +73,207 @@ public sealed class Redactor internal const int MinLearnedLength = 8; private readonly Lock _gate = new(); - private readonly HashSet _learned = new(StringComparer.Ordinal); + + /// The forms of every value redacted by name so far (encoded once, as they are learned). + private readonly SecretPatterns _learned = new(); + + /// The forms of each cookie's latest value. + private readonly Dictionary<(string Host, string Name), byte[][]> _cookies = []; + + /// The normalized extra names: replaced, never changed, when names are added (see ). + private HashSet _extraNames; public Redactor(IEnumerable? extraNames = null) { - ExtraNames = SecretNames.NormalizeAll(extraNames); + _extraNames = SecretNames.NormalizeAll(extraNames); } /// Additional names to redact (normalized), from the workspace settings. - public IReadOnlySet ExtraNames { get; } + public IReadOnlySet ExtraNames + { + get + { + lock (_gate) + { + return _extraNames; + } + } + } - /// Redaction for one exchange: its own secrets plus every value learned earlier in the recording. + /// Whether a value was redacted by name so far (else finds nothing). + internal bool HasLearned + { + get + { + lock (_gate) + { + return _learned.Count > 0; + } + } + } + + /// Redaction for one exchange: its own secrets plus every value learned in the recording (earlier, and while it runs). public ExchangeRedactor For(PreparedRequest request) { - string[] learned; + byte[][] cookies; + HashSet extraNames; lock (_gate) { - learned = [.. _learned]; + cookies = [.. _cookies.Values.SelectMany(forms => forms)]; + extraNames = _extraNames; + } + + return new ExchangeRedactor(this, request, cookies, extraNames); + } + + /// + /// Adds extra names to redact, as when the workspace settings change while recording: the exchanges redacted from now + /// on (see ) redact them too. Names are never removed. + /// + internal void AddExtraNames(IEnumerable names) + { + var extended = SecretNames.NormalizeAll(names); + lock (_gate) + { + // A new set: an exchange being redacted keeps the one it started with. + extended.UnionWith(_extraNames); + _extraNames = extended; + } + } + + /// + /// Redaction for a report about that is not a recording, such as the collection runner's + /// JSON report: , once it has learned what a recording learns while it writes the + /// exchange, in the same order (see ): credentials, cookies, and the values of + /// headers, URL parameters and body fields named like secrets. The report's text (test names and errors …) then + /// loses them as the recording does, and so do the reports of the exchanges that follow. The exchange is not kept. + /// + public ExchangeRedactor ForReport(HttpExchange exchange) + { + const string PostData = "request.postData"; + var request = exchange.Request; + var redactor = For(request); + var headers = exchange.SentHeaders.Count > 0 ? exchange.SentHeaders : request.Headers; + foreach (var (name, value) in headers) + { + redactor.Header(name, value, "request.headers"); + } + + var body = request.Body; + switch (body.Kind) + { + case PreparedBodyKind.Text: + { + var text = Encoding.UTF8.GetBytes(body.Text ?? ""); + var type = headers.LastOrDefault(h => h.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)).Value ?? body.ContentType; + redactor.BodySpans(text, ExchangeRedactor.DetectFormat(type, text), PostData); + break; + } + + case PreparedBodyKind.FormUrlEncoded: + redactor.BodySpans(Encoding.UTF8.GetBytes(PreparedBody.EncodeForm(body.Fields)), BodyFormat.Form, PostData); + break; + case PreparedBodyKind.Multipart: + foreach (var part in body.Parts.Where(p => p.FilePath is null && redactor.IsSecretName(p.Name, NameKind.Field))) + { + redactor.RedactNamed(part.Name, part.Value ?? "", PostData); + } + + break; + } + + redactor.Url(request.Uri?.AbsoluteUri ?? request.Url, "request.url"); + if (exchange.Response is { } response) + { + foreach (var (name, value) in response.Headers) + { + redactor.Header(name, value, "response.headers"); + } + + if (response.Body.Length > 0) + { + var (data, format) = HarEntryWriter.Classify(response.Body, response.ContentType); + redactor.BodySpans(data, format, "response.content"); + } + + if (response.FinalUri is { } final && request.Uri is { } requested && final != requested) + { + redactor.Url(final.AbsoluteUri, "_termrest.finalUrl"); + } + } + + if (!string.IsNullOrWhiteSpace(request.Proxy)) + { + redactor.Url(request.Proxy, "_termrest.settings"); } - return new ExchangeRedactor(this, request, learned); + return redactor; } internal void Learn(string value) { + var forms = SecretPatterns.Forms(value).ToList(); lock (_gate) { - _learned.Add(value); + foreach (var form in forms) + { + _learned.Add(form); + } + } + } + + /// + /// Learns the value of a cookie of (its ). A cookie that is set again + /// replaces its earlier value, which is no longer looked for: load balancer and session cookies (AWSALB, XSRF-TOKEN …) + /// change with every response. Cookie values in Cookie and Set-Cookie headers are always redacted. + /// + internal void LearnCookie(string host, string name, byte[][] forms) + { + lock (_gate) + { + _cookies[(host, name)] = forms; + } + } + + /// Adds where the values redacted by name so far are in . + internal void FindLearned(ReadOnlySpan data, List spans) + { + lock (_gate) + { + _learned.Find(data, spans); } } } /// Redacts the parts of one exchange and notes what was removed (see ). -public sealed class ExchangeRedactor +public sealed partial class ExchangeRedactor { internal static readonly byte[] PlaceholderBytes = Encoding.UTF8.GetBytes(Redactor.Placeholder); internal static readonly byte[] QuotedPlaceholderBytes = Encoding.UTF8.GetBytes($"\"{Redactor.Placeholder}\""); + // The bytes EF BB BF: a "\xEF\xBB\xBF"u8 literal would be the UTF-8 of U+00EF U+00BB U+00BF, six other bytes. + private static ReadOnlySpan Utf8Bom => [0xEF, 0xBB, 0xBF]; + private readonly Redactor _recording; - private readonly HashSet _values = new(StringComparer.Ordinal); - private byte[][]? _patterns; + private readonly string _host; + + /// The recording's extra names when this exchange started to be redacted. + private readonly IReadOnlySet _extraNames; + + /// The forms of this exchange's secrets and of cookie values (values redacted by name are the recording's). + private readonly SecretPatterns _patterns = new(); - internal ExchangeRedactor(Redactor recording, PreparedRequest request, IEnumerable learned) + internal ExchangeRedactor(Redactor recording, PreparedRequest request, IEnumerable cookies, IReadOnlySet extraNames) { _recording = recording; + _host = request.Uri?.Host ?? ""; + _extraNames = extraNames; Add(request.SecretValues, Redactor.MinSecretLength); Add(request.SensitiveValues, Redactor.MinNamedVariableLength); - Add(learned, Redactor.MinLearnedLength); + foreach (var form in cookies) + { + _patterns.Add(form); + } } /// What was redacted so far. @@ -121,15 +282,12 @@ internal ExchangeRedactor(Redactor recording, PreparedRequest request, IEnumerab /// Number of values redacted so far. public int Count => Notes.Sum(n => n.Count); - /// UTF-8 forms of the known secret values as they may appear in text: plain, URL-encoded, JSON-escaped; longest first. - private byte[][] Patterns => _patterns ??= BuildPatterns(); - - public bool IsSecretName(string? name, NameKind kind) => SecretNames.IsSecret(name, kind, _recording.ExtraNames); + public bool IsSecretName(string? name, NameKind kind) => SecretNames.IsSecret(name, kind, _extraNames); /// Replaces the known secret values in . public string Text(string? text, string location, string? name = null) { - if (string.IsNullOrEmpty(text) || Patterns.Length == 0) + if (string.IsNullOrEmpty(text) || (_patterns.Count == 0 && !_recording.HasLearned)) { return text ?? ""; } @@ -147,7 +305,10 @@ public string Text(string? text, string location, string? name = null) return Encoding.UTF8.GetString(Apply(bytes, merged)); } - /// Redacts a URL: a password in the user info, parameters named like secrets (query and fragment), and known secret values. + /// + /// Redacts a URL: the password of its user info, or the user name when it has no password (it is then the credential), + /// parameters named like secrets (query and fragment), and known secret values. + /// public string Url(string? url, string location) { if (string.IsNullOrEmpty(url)) @@ -155,7 +316,7 @@ public string Url(string? url, string location) return url ?? ""; } - var schemeEnd = url.IndexOf("://", StringComparison.Ordinal); + var schemeEnd = SchemeEnd(url); var authorityStart = schemeEnd < 0 ? 0 : schemeEnd + 3; var authorityEnd = url.IndexOfAny(['/', '?', '#'], authorityStart); if (authorityEnd < 0) @@ -166,7 +327,7 @@ public string Url(string? url, string location) var builder = new StringBuilder(url.Length + 16); var authority = url[authorityStart..authorityEnd]; var at = authority.LastIndexOf('@'); - var colon = at < 0 ? -1 : authority.IndexOf(':', StringComparison.Ordinal); + var colon = at < 0 ? -1 : authority.IndexOf(':', 0, at); if (colon >= 0 && colon < at - 1) { // https://user:password@host keeps the user name. @@ -174,6 +335,15 @@ public string Url(string? url, string location) builder.Append(url, 0, authorityStart + colon + 1).Append(Redactor.Placeholder).Append(authority, at, authority.Length - at); Note(location, null, RedactionNote.UrlPasswordReason); } + else if (at > 0 && colon != 0) + { + // https://user@host and https://user:@host send the user name as the credential, with an empty password (as curl + // and Postman do): an API key, as Stripe takes it. + var userEnd = colon < 0 ? at : colon; + Learn(Decode(authority[..userEnd])); + builder.Append(url, 0, authorityStart).Append(Redactor.Placeholder).Append(authority, userEnd, authority.Length - userEnd); + Note(location, null, RedactionNote.UrlUserReason); + } else { builder.Append(url, 0, authorityEnd); @@ -235,8 +405,8 @@ public string Header(string name, string? value, string location) } /// - /// Parts of a body to replace: JSON values and form fields named like secrets (all values inside a secret JSON - /// object or array), then known secret values anywhere. The result is sorted and does not overlap. + /// Parts of a body to replace: JSON values, form fields and form-data parts named like secrets (all values inside a + /// secret JSON object or array), then known secret values anywhere. The result is sorted and does not overlap. /// internal List BodySpans(ReadOnlySpan body, BodyFormat format, string location) { @@ -249,6 +419,11 @@ internal List BodySpans(ReadOnlySpan body, BodyFormat format { FormSpans(body, structural, location); } + else if (format is BodyFormat.Multipart or BodyFormat.Binary) + { + // Form-data with binary files is Binary (written as base64): the bytes of its secret parts are overwritten. + MultipartSpans(body, structural, location); + } var values = new List(); AddValueSpans(body, values); @@ -297,42 +472,52 @@ internal static byte[] Apply(ReadOnlySpan data, IReadOnlyListDetects how a body is written: JSON, form and text bodies as text (UTF-8), anything else as base64. + /// + /// Detects how a body is written: JSON, form, form-data and text bodies as text (UTF-8), anything else as base64. + /// Bodies labelled as JSON, form or text stay text even where they are not UTF-8 (a body cut at the size limit inside + /// a character, a stray Latin-1 byte): such bytes are written as U+FFFD, and the JSON and form rules still apply. + /// Form-data is text only where it is UTF-8, as its files may be binary. + /// public static BodyFormat DetectFormat(string? contentType, ReadOnlySpan body) { var media = MediaType(contentType); - var text = Utf8.IsValid(body) && !body[..Math.Min(body.Length, 8192)].Contains((byte)0); - if (!text) + var unlabelled = media.Length == 0 || media == "application/octet-stream"; + var multipart = media == "multipart/form-data"; + if (body[..Math.Min(body.Length, 8192)].Contains((byte)0) || (unlabelled || multipart ? !IsUtf8(body) : !IsTextual(media))) { return BodyFormat.Binary; } - if (media.Contains("json", StringComparison.Ordinal)) + if (multipart) { - return BodyFormat.Json; + return BodyFormat.Multipart; } - if (media == "application/x-www-form-urlencoded") + if (Http.BodyFormatter.IsJson(media)) { - return BodyFormat.Form; + return BodyFormat.Json; } - if (media.Length == 0 || media == "application/octet-stream") + if (media == "application/x-www-form-urlencoded") { - // No (useful) content type: JSON if it looks like JSON, otherwise readable text stays text. - var start = body.TrimStart(" \t\r\n"u8); - return start.Length > 0 && start[0] is (byte)'{' or (byte)'[' ? BodyFormat.Json : BodyFormat.Text; + return BodyFormat.Form; } - return IsTextual(media) ? BodyFormat.Text : BodyFormat.Binary; + // JSON also comes without a (useful) content type, or as text/plain or text/html: it is recognized by its start, after + // a UTF-8 byte order mark (a PHP file saved with one puts it before what it echoes). + var start = (body.StartsWith(Utf8Bom) ? body[Utf8Bom.Length..] : body).TrimStart(" \t\r\n"u8); + return (unlabelled || media.StartsWith("text/", StringComparison.Ordinal)) && start.Length > 0 && start[0] is (byte)'{' or (byte)'[' + ? BodyFormat.Json + : BodyFormat.Text; } + /// + /// Whether a media type is text: text/*, form data, or a word of its subtype names a text format, as the body is shown + /// (application/problem+json, image/svg+xml; not application/ubjson or an Office document's openxmlformats). + /// internal static bool IsTextual(string media) => media.StartsWith("text/", StringComparison.Ordinal) - || media.Contains("json", StringComparison.Ordinal) || media.Contains("xml", StringComparison.Ordinal) - || media.Contains("javascript", StringComparison.Ordinal) || media.Contains("ecmascript", StringComparison.Ordinal) - || media.Contains("yaml", StringComparison.Ordinal) || media.Contains("graphql", StringComparison.Ordinal) - || media.Contains("csv", StringComparison.Ordinal) || media.Contains("html", StringComparison.Ordinal) + || Http.BodyFormatter.SubtypeHasWord(media, "json", "ndjson", "jsonl", "jsonlines", "xml", "javascript", "ecmascript", "yaml", "graphql", "csv", "html", "xhtml") || media is "application/x-www-form-urlencoded" or "application/x-sh" or "application/sql"; /// The media type of a Content-Type value, lowercase, without parameters. @@ -343,6 +528,25 @@ internal static string MediaType(string? contentType) return (semicolon < 0 ? value : value[..semicolon]).Trim().ToLowerInvariant(); } + /// Whether is UTF-8, allowing a character cut off at the end (a body cut at the size limit). + private static bool IsUtf8(ReadOnlySpan body) + { + if (Utf8.IsValid(body)) + { + return true; + } + + // The first byte of the last character says how many bytes it has. + var lead = body.Length - 1; + while (lead > 0 && lead > body.Length - 4 && (body[lead] & 0xC0) == 0x80) + { + lead--; + } + + var length = body[lead] switch { >= 0xF0 => 4, >= 0xE0 => 3, >= 0xC0 => 2, _ => 1 }; + return body.Length - lead < length && Utf8.IsValid(body[..lead]); + } + internal static List Merge(List spans) { spans.Sort((a, b) => a.Start != b.Start ? a.Start.CompareTo(b.Start) : b.End.CompareTo(a.End)); @@ -409,11 +613,39 @@ private string Credential(string name, string value, string location) // "Bearer ", "Basic ", "AWS4-HMAC-SHA256 Credential=…": the scheme says what kind of credential was sent. var space = value.IndexOf(' ', StringComparison.Ordinal); var scheme = space is > 0 and <= 32 && value[..space].All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.') ? value[..space] : null; - Learn(scheme is null ? value : value[(space + 1)..]); + var credential = scheme is null ? value : value[(space + 1)..]; + Learn(credential); + if (string.Equals(scheme, "Basic", StringComparison.OrdinalIgnoreCase)) + { + LearnBasic(credential); + } + Note(location, name, RedactionNote.CredentialReason); return scheme is null ? Redactor.Placeholder : $"{scheme} {Redactor.Placeholder}"; } + /// + /// Learns the user name and the password of a Basic credential (user:password in base64, RFC 7617): the user name + /// can be the credential itself, an API key sent with an empty or dummy password (as Stripe and Freshdesk take theirs). + /// + private void LearnBasic(string credential) + { + var base64 = credential.Trim(); + var bytes = new byte[base64.Length]; + if (!Convert.TryFromBase64String(base64, bytes, out var length)) + { + return; + } + + var text = Encoding.UTF8.GetString(bytes, 0, length); + var colon = text.IndexOf(':', StringComparison.Ordinal); + Learn(colon < 0 ? text : text[..colon]); + if (colon >= 0) + { + Learn(text[(colon + 1)..]); + } + } + private string Cookies(string value, string location, string headerName) { var parts = value.Split(';'); @@ -426,7 +658,7 @@ private string Cookies(string value, string location, string headerName) continue; } - Learn(parts[i][(equals + 1)..]); + LearnCookie(parts[i][..equals], parts[i][(equals + 1)..]); parts[i] = parts[i][..(equals + 1)] + Redactor.Placeholder; count++; } @@ -449,7 +681,7 @@ private string SetCookie(string value, string location, string headerName) return Text(value, location, headerName); } - Learn(pair[(equals + 1)..]); + LearnCookie(pair[..equals], pair[(equals + 1)..]); Note(location, headerName, RedactionNote.CookieReason); return pair[..(equals + 1)] + Redactor.Placeholder + (end < 0 ? "" : Text(value[end..], location, headerName)); } @@ -479,7 +711,7 @@ private string Parameters(string text, string location) private void JsonSpans(ReadOnlySpan body, List spans, string location) { - var offset = body.StartsWith("\xEF\xBB\xBF"u8) ? 3 : 0; + var offset = body.StartsWith(Utf8Bom) ? Utf8Bom.Length : 0; var reader = new Utf8JsonReader(body[offset..], new JsonReaderOptions { CommentHandling = JsonCommentHandling.Skip, @@ -500,7 +732,7 @@ private void JsonSpans(ReadOnlySpan body, List spans, string switch (reader.TokenType) { case JsonTokenType.PropertyName: - property = reader.GetString(); + property = ReadString(ref reader); propertySecret = parent.Secret || IsSecretName(property, NameKind.Field); break; case JsonTokenType.StartObject or JsonTokenType.StartArray: @@ -523,7 +755,7 @@ private void JsonSpans(ReadOnlySpan body, List spans, string { if (reader.TokenType == JsonTokenType.String) { - Learn(reader.GetString() ?? ""); + Learn(ReadString(ref reader)); } spans.Add(new RedactedSpan(offset + (int)reader.TokenStartIndex, offset + (int)reader.BytesConsumed, true)); @@ -546,6 +778,19 @@ private void JsonSpans(ReadOnlySpan body, List spans, string } } + /// The text of a string token; bytes that are not UTF-8 are read as U+FFFD (as they are written). + private static string ReadString(ref Utf8JsonReader reader) + { + try + { + return reader.GetString() ?? ""; + } + catch (InvalidOperationException) + { + return Encoding.UTF8.GetString(reader.ValueSpan); + } + } + private void FormSpans(ReadOnlySpan body, List spans, string location) { var start = 0; @@ -570,51 +815,111 @@ private void FormSpans(ReadOnlySpan body, List spans, string } } - private void AddValueSpans(ReadOnlySpan data, List spans) + /// + /// The values of form-data parts named like secrets; files (parts with a file name) are kept. The body's first line is + /// the delimiter (--boundary), a part's headers end at a blank line and its Content-Disposition gives its name. + /// Lines may end with CRLF or LF (a body typed in the editor). A body of another shape has no such parts; in one cut + /// off at the size limit, a value that runs to the end is redacted to the end. + /// + private void MultipartSpans(ReadOnlySpan body, List spans, string location) { - foreach (var pattern in Patterns) + // A boundary has at most 70 characters: a longer first line (or none, as in most binary data) is no delimiter. + var firstLine = body.StartsWith("--"u8) ? body[..Math.Min(body.Length, 256)].IndexOf((byte)'\n') : -1; + var boundary = firstLine < 0 ? [] : body[2..firstLine].TrimEnd(" \t\r"u8); + if (boundary.IsEmpty) { - var offset = 0; - while (offset + pattern.Length <= data.Length) + return; + } + + byte[] delimiter = [.. "\n--"u8, .. boundary]; + for (var start = firstLine + 1; start < body.Length;) + { + var length = body[start..].IndexOf(delimiter); + var end = length < 0 ? body.Length : start + length; + var (name, file, content) = ReadPart(body[start..end]); + if (content >= 0 && !file && IsSecretName(name, NameKind.Field)) { - var index = data[offset..].IndexOf(pattern); - if (index < 0) + // The line break before the delimiter belongs to the delimiter. + var valueEnd = length >= 0 && body[end - 1] == '\r' ? end - 1 : end; + if (valueEnd > start + content) { - break; + Learn(Encoding.UTF8.GetString(body[(start + content)..valueEnd])); + spans.Add(new RedactedSpan(start + content, valueEnd, false)); + Note(location, name, RedactionNote.NameReason); } + } - spans.Add(new RedactedSpan(offset + index, offset + index + pattern.Length, false)); - offset += index + pattern.Length; + // The next part starts on the line after the delimiter; "--" right after it ends the body. + var after = end + delimiter.Length; + var lineEnd = length < 0 || body[after..].StartsWith("--"u8) ? -1 : body[after..].IndexOf((byte)'\n'); + if (lineEnd < 0) + { + break; } + + start = after + lineEnd + 1; } } - private byte[][] BuildPatterns() + /// + /// The name a form-data part's Content-Disposition gives it, whether it has a file name, and where its content starts: + /// after the blank line that ends its headers (-1 without one). + /// + private static (string? Name, bool File, int Content) ReadPart(ReadOnlySpan part) { - var variants = new HashSet(StringComparer.Ordinal); - foreach (var value in _values) + var header = "content-disposition:"u8; + string? name = null; + var file = false; + for (var start = 0; part[start..].IndexOf((byte)'\n') is var length and >= 0; start += length + 1) { - variants.Add(value); - variants.Add(Uri.EscapeDataString(value)); - variants.Add(WebUtility.UrlEncode(value)); - variants.Add(JavaScriptEncoder.Default.Encode(value)); - variants.Add(MinimalJsonEncoder.Instance.Encode(value)); - if (value.Contains('/', StringComparison.Ordinal)) + var line = part.Slice(start, length).TrimEnd((byte)'\r'); + if (line.IsEmpty) { - variants.Add(value.Replace("/", "\\/", StringComparison.Ordinal)); + return (name, file, start + length + 1); + } + + if (line.Length > header.Length && Ascii.EqualsIgnoreCase(line[..header.Length], header)) + { + foreach (Match parameter in DispositionParameter().Matches(Encoding.UTF8.GetString(line[header.Length..]))) + { + var key = parameter.Groups[1].Value; + if (key.Equals("name", StringComparison.OrdinalIgnoreCase)) + { + name ??= parameter.Groups[2].Success ? parameter.Groups[2].Value : parameter.Groups[3].Value.Trim(); + } + else if (key.Equals("filename", StringComparison.OrdinalIgnoreCase) || key.Equals("filename*", StringComparison.OrdinalIgnoreCase)) + { + file = true; + } + } } } - return [.. variants.Where(v => v.Length > 0).OrderByDescending(v => v.Length).Select(Encoding.UTF8.GetBytes)]; + return (null, false, -1); + } + + /// A parameter of a Content-Disposition value: ; name="value" or ; name=value. + [GeneratedRegex(""" + ;[ \t]*([^ \t=;]+)[ \t]*=[ \t]*(?:"([^"]*)"|([^;]*)) + """)] + private static partial Regex DispositionParameter(); + + private void AddValueSpans(ReadOnlySpan data, List spans) + { + _patterns.Find(data, spans); + _recording.FindLearned(data, spans); } private void Add(IEnumerable values, int minLength) { foreach (var value in values) { - if (value.Length >= minLength && !string.IsNullOrWhiteSpace(value) && _values.Add(value)) + if (value.Length >= minLength && !string.IsNullOrWhiteSpace(value)) { - _patterns = null; + foreach (var form in SecretPatterns.Forms(value)) + { + _patterns.Add(form); + } } } } @@ -623,19 +928,31 @@ private void Add(IEnumerable values, int minLength) private void Learn(string value) { value = value.Trim(); - if (value.Length < Redactor.MinLearnedLength || value.Contains(Redactor.Placeholder, StringComparison.Ordinal)) + if (IsLearnable(value)) { - return; + _recording.Learn(value); } + } - if (_values.Add(value)) + /// A cookie's value is redacted wherever it appears later, until the cookie is set again (see ). + private void LearnCookie(string name, string value) + { + value = value.Trim(); + if (IsLearnable(value)) { - _patterns = null; - } + byte[][] forms = [.. SecretPatterns.Forms(value)]; + foreach (var form in forms) + { + _patterns.Add(form); + } - _recording.Learn(value); + _recording.LearnCookie(_host, name.Trim(), forms); + } } + private static bool IsLearnable(string value) => + value.Length >= Redactor.MinLearnedLength && !value.Contains(Redactor.Placeholder, StringComparison.Ordinal); + private void Note(string location, string? name, string reason, int count = 1) { var existing = Notes.FirstOrDefault(n => n.Location == location && n.Name == name && n.Reason == reason); @@ -650,4 +967,24 @@ private void Note(string location, string? name, string reason, int count = 1) } private static string Decode(string text) => Uri.UnescapeDataString(text.Replace('+', ' ')); + + /// Where the "://" after a URL's scheme is, or -1 for a relative URL (whose query may hold one: /login?next=https://…). + private static int SchemeEnd(string url) + { + var end = url.IndexOf("://", StringComparison.Ordinal); + if (end <= 0 || !char.IsAsciiLetter(url[0])) + { + return -1; + } + + for (var i = 1; i < end; i++) + { + if (!char.IsAsciiLetterOrDigit(url[i]) && url[i] is not ('+' or '-' or '.')) + { + return -1; + } + } + + return end; + } } diff --git a/src/TermRest.Core/Recording/RequestRecorder.cs b/src/TermRest.Core/Recording/RequestRecorder.cs index 15c75d7..da2592c 100644 --- a/src/TermRest.Core/Recording/RequestRecorder.cs +++ b/src/TermRest.Core/Recording/RequestRecorder.cs @@ -27,8 +27,11 @@ public sealed class RecordingOptions /// A saved recording. public sealed record RecordingResult(string Path, int Requests, long Bytes, int Redactions); -/// A recording whose temporary files were left behind: TermRest was closed or crashed before it was saved. -public sealed record UnsavedRecording(string TempDirectory, DateTimeOffset StartedAt, string? WorkspaceName, string? WorkspaceRoot, int Requests, long Bytes); +/// +/// A recording whose temporary files were left behind: TermRest was closed or crashed before it was saved. Its requests +/// are counted when it is opened (). +/// +public sealed record UnsavedRecording(string TempDirectory, DateTimeOffset StartedAt, string? WorkspaceName, string? WorkspaceRoot, long Bytes); /// Where an entry is in the temporary file. internal readonly record struct SpoolEntry(long Offset, long Length, DateTimeOffset? StartedAt); @@ -38,8 +41,8 @@ public sealed record UnsavedRecording(string TempDirectory, DateTimeOffset Start /// tools and HAR viewers open. /// /// Memory: each exchange is written to a private temporary file when it completes, on a background thread, so a -/// recording never grows in memory. Bodies are written in pieces; saving streams the temporary file into the -/// destination with a small buffer. +/// recording never grows in memory (when several are still waiting to be written, recording the next one waits). +/// Bodies are written in pieces; saving streams the temporary file into the destination with a small buffer. /// Secrets are redacted before anything is written (see ). /// Temporary files (see ) are private to the user and deleted when the recording is /// saved or discarded. If TermRest ends before that, finds them and the recording can @@ -58,9 +61,17 @@ public sealed class RequestRecorder : IDisposable /// Large temporary files on Linux when /tmp is in memory (tmpfs). internal const string LargeTempDirectory = "/var/tmp"; + /// + /// Recorded requests that may wait to be written; waits beyond that, so a recording does not grow + /// in memory when requests are sent faster than they are written. + /// + internal const int MaxPendingWrites = 4; + private const string DeletedMarker = "saved"; private const UnixFileMode PrivateDirectory = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; private const UnixFileMode PrivateFile = UnixFileMode.UserRead | UnixFileMode.UserWrite; + private const UnixFileMode GroupOrOthers = UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute + | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute; private const int BufferSize = 64 * 1024; private const string EntriesMarker = "@@termrest-entries@@"; @@ -70,7 +81,7 @@ public sealed class RequestRecorder : IDisposable private readonly FileStream _spool; private readonly List _entries; private readonly Redactor _redactor; - private readonly RecordingInfo _info; + private RecordingInfo _info; private Task _tail = Task.CompletedTask; private int _pending; private int _redactions; @@ -131,6 +142,18 @@ public int Count } } + /// Requests recorded that are still being written. + internal int PendingWrites + { + get + { + lock (_gate) + { + return _pending; + } + } + } + /// Size of the temporary file. public long Bytes { @@ -173,6 +196,12 @@ public int RequestsWithFiles /// The last problem writing a request, if any (the recording goes on without it). public string? LastError { get; private set; } + /// + /// The extra names it redacts (normalized; see ): those it started with and + /// those added since (), which it keeps until it stops. + /// + public IReadOnlySet ExtraNames => _redactor.ExtraNames; + /// /// The folder for temporary recording files: $TERMREST_TEMP_DIR, else the user's temporary folder on /// Windows (%TEMP%) and macOS ($TMPDIR, private to the user), else $TMPDIR when set, else @@ -239,7 +268,8 @@ public static RequestRecorder Start(RecordingOptions? options = null) /// /// Recordings whose temporary files are left over in (default: , /// plus the system's temporary folder unless $TERMREST_TEMP_DIR is set), oldest first. Recordings that - /// another TermRest is still making are skipped; left-over files without a complete request are deleted. + /// another TermRest is still making are skipped; left-over files without a complete request are deleted. Only + /// folders private to the user are looked at: in a shared folder such as /tmp, others may be another user's. /// public static IReadOnlyList FindUnsaved(string? tempRoot = null) { @@ -261,7 +291,7 @@ public static IReadOnlyList FindUnsaved(string? tempRoot = nul foreach (var directory in directories) { - if (Inspect(directory) is { } unsaved) + if (IsPrivate(directory) && Inspect(directory) is { } unsaved) { found.Add(unsaved); } @@ -289,7 +319,10 @@ public static RequestRecorder Recover(UnsavedRecording unsaved) } } - /// Records an exchange (in the background). Requests that were never sent, such as an invalid URL, are skipped. + /// + /// Records an exchange (in the background; this waits only while several earlier requests are still being written). + /// Requests that were never sent, such as an invalid URL, are skipped. + /// public void Record(HttpExchange exchange, string? environment = null) { var request = exchange.Request; @@ -299,6 +332,7 @@ public void Record(HttpExchange exchange, string? environment = null) } var recorded = RecordedExchange.Capture(exchange, environment); + Task? backlog = null; lock (_gate) { if (!_accepting) @@ -306,6 +340,11 @@ public void Record(HttpExchange exchange, string? environment = null) return; } + if (_pending >= MaxPendingWrites) + { + backlog = _tail; + } + _pending++; if (request.Body.HasFiles) { @@ -316,6 +355,7 @@ public void Record(HttpExchange exchange, string? environment = null) } Changed?.Invoke(this, EventArgs.Empty); + backlog?.Wait(); } /// Completes when every recorded request has been written to the temporary file. @@ -327,6 +367,42 @@ public Task WhenWritten() } } + /// + /// Adds names to redact (see ), as when the workspace settings change while + /// recording: the requests written from now on are redacted with them too, and the recording lists them; requests + /// written already stay as they are. Names are never removed. Returns the names new to the recording (none once it + /// no longer records). + /// + public IReadOnlyList AddRedactNames(IEnumerable names) + { + lock (_gate) + { + if (!_accepting) + { + return []; + } + + var known = SecretNames.NormalizeAll(_info.RedactNames); + List added = [.. names.Where(name => SecretNames.Normalize(name) is { Length: > 0 } normalized && known.Add(normalized))]; + if (added.Count > 0) + { + _redactor.AddExtraNames(added); + _info = _info with { RedactNames = [.. _info.RedactNames, .. added] }; + try + { + WriteInfo(_info); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Read only for a recording recovered after TermRest ended: its HAR file would not list these names, + // though its requests are redacted with them all the same. + } + } + + return added; + } + } + /// /// Stops recording and writes the HAR file to (replacing it; missing folders are created), /// then deletes the temporary files. If saving fails, nothing is lost: the recording can be saved again. @@ -407,37 +483,61 @@ public void Dispose() Finish(deleteFiles: _entries.Count == 0); } - /// Complete entries in a temporary file (each ends with a } line); a cut-off last entry is left out. - internal static List Scan(Stream stream) + /// + /// Complete entries in a temporary file (each ends with a } line), the first of them; a + /// cut-off last entry is left out. Stops reading once it has found them. + /// + internal static List Scan(Stream stream, int max = int.MaxValue) { var entries = new List(); var buffer = new byte[BufferSize]; stream.Position = 0; - long position = 0; + long bufferStart = 0; // where buffer[0] is in the file long start = 0; - byte previous = 0; - byte beforePrevious = 0; + var kept = 0; int read; - while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) + while (entries.Count < max && (read = stream.Read(buffer, kept, buffer.Length - kept)) > 0) { - for (var i = 0; i < read; i++, position++) + var data = buffer.AsSpan(0, kept + read); + + // Strings never contain raw line breaks, so "\n}\n" only ends a whole (indented) entry. + for (var from = 0; entries.Count < max;) { - // Strings never contain raw line breaks, so "\n}\n" only ends a whole (indented) entry. - var current = buffer[i]; - if (current == (byte)'\n' && previous == (byte)'}' && beforePrevious == (byte)'\n') + var index = data[from..].IndexOf("\n}\n"u8); + if (index < 0) { - entries.Add(new SpoolEntry(start, position - start, null)); - start = position + 1; + break; } - beforePrevious = previous; - previous = current; + var end = bufferStart + from + index + 2; // the line break after the "}" + entries.Add(new SpoolEntry(start, end - start, null)); + start = end + 1; + from += index + 2; } + + // The last two bytes may start a "\n}\n" that the next read completes. + kept = Math.Min(2, data.Length); + data[^kept..].CopyTo(buffer); + bufferStart += data.Length - kept; } return entries; } + /// Whether a temporary file ends with a complete entry, as it does unless TermRest ended while writing one. + private static bool EndsWithEntry(Stream stream) + { + if (stream.Length < 3) + { + return false; + } + + Span end = stackalloc byte[3]; + stream.Position = stream.Length - 3; + stream.ReadExactly(end); + return end.SequenceEqual("\n}\n"u8); + } + private void Write(RecordedExchange recorded) { long start = 0; @@ -491,6 +591,19 @@ private void Write(RecordedExchange recorded) } } + /// Replaces the recording's recording.json: written next to it, then moved over it. + private void WriteInfo(RecordingInfo info) + { + var path = Path.Combine(TempDirectory, InfoFileName); + var temp = path + ".tmp"; + using (var file = new FileStream(temp, FileOptions(FileMode.Create, FileAccess.Write, FileShare.None))) + { + file.Write(info.ToJson()); + } + + File.Move(temp, path, overwrite: true); + } + /// Writes the HAR file next to , then moves it into place (an existing file is replaced only when complete). private void WriteHar(string path, List entries, DateTimeOffset stoppedAt) { @@ -673,23 +786,23 @@ private void Finish(bool deleteFiles) return null; // being created right now } - int count; + bool complete; long length; - // Exclusive: fails while a running TermRest records into it. + // Exclusive: fails while a running TermRest records into it. One complete request is enough to offer it. using (var stream = new FileStream(spoolPath, FileMode.Open, FileAccess.Read, FileShare.None)) { - count = Scan(stream).Count; + complete = EndsWithEntry(stream) || Scan(stream, max: 1).Count > 0; length = stream.Length; } - if (count == 0) + if (!complete) { DeleteDirectory(directory); return null; } var info = RecordingInfo.TryRead(Path.Combine(directory, InfoFileName)); - return new UnsavedRecording(directory, info?.StartedAt ?? new DateTimeOffset(Directory.GetCreationTime(directory)), info?.WorkspaceName, info?.WorkspaceRoot, count, length); + return new UnsavedRecording(directory, info?.StartedAt ?? new DateTimeOffset(Directory.GetCreationTime(directory)), info?.WorkspaceName, info?.WorkspaceRoot, length); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { @@ -697,6 +810,23 @@ private void Finish(bool deleteFiles) } } + /// + /// Whether a folder can be one of this user's recordings: TermRest makes them private (0700 on Unix), never links. + /// Others, in a shared folder such as /tmp, may be another user's and are not opened. + /// + private static bool IsPrivate(string directory) + { + try + { + return new DirectoryInfo(directory).LinkTarget is null + && (OperatingSystem.IsWindows() || (File.GetUnixFileMode(directory) & GroupOrOthers) == 0); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } + private static string CreatePrivateDirectory(string root) { if (!Directory.Exists(root)) @@ -819,7 +949,8 @@ public byte[] ToJson() { using var document = JsonDocument.Parse(File.ReadAllBytes(path)); var root = document.RootElement; - if (!root.TryGetProperty("startedAt", out var started) || !DateTimeOffset.TryParse(started.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var startedAt)) + if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("startedAt", out var started) || started.ValueKind != JsonValueKind.String + || !DateTimeOffset.TryParse(started.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var startedAt)) { return null; } @@ -828,12 +959,12 @@ public byte[] ToJson() var redact = root.TryGetProperty("redact", out var names) && names.ValueKind == JsonValueKind.Array ? names.EnumerateArray().Where(n => n.ValueKind == JsonValueKind.String).Select(n => n.GetString()!).ToArray() : []; - var processId = root.TryGetProperty("processId", out var pid) && pid.TryGetInt32(out var id) ? id : 0; + var processId = root.TryGetProperty("processId", out var pid) && pid.ValueKind == JsonValueKind.Number && pid.TryGetInt32(out var id) ? id : 0; return new RecordingInfo(startedAt, Text("workspace"), Text("workspaceRoot"), redact, processId); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException) { - return null; + return null; // missing or damaged: the recording is still offered, without these details } } } diff --git a/src/TermRest.Core/Recording/SecretNames.cs b/src/TermRest.Core/Recording/SecretNames.cs index e364320..49f2cb7 100644 --- a/src/TermRest.Core/Recording/SecretNames.cs +++ b/src/TermRest.Core/Recording/SecretNames.cs @@ -22,12 +22,16 @@ public static class SecretNames private static readonly string[] Ending = [ "token", "authorization", "cookie", "cookies", "apikey", "accesskey", "secretkey", "subscriptionkey", "functionskey", - "masterkey", "sessionkey", "signingkey", "accountkey", "sharedkey", "sessionid", "sessid", "signature", "assertion", - "codeverifier", "pwd", + "masterkey", "sessionkey", "signingkey", "accountkey", "sharedkey", "authkey", "sessionid", "sessid", "signature", + "assertion", "codeverifier", "pwd", ]; - // Short names that are credentials only in URLs: Google API keys (?key=) and Azure SAS signatures (?sig=). - private static readonly string[] QueryOnly = ["key", "sig"]; + // Short names that are credentials only in URLs: Google API keys (?key=), Azure SAS signatures (?sig=) and Firebase + // ID tokens or database secrets (?auth=). + private static readonly string[] QueryOnly = ["key", "sig", "auth"]; + + // Names that look like credentials but never hold one (CORS says whether credentials are allowed: "true"). + private static readonly string[] NotSecret = ["accesscontrolallowcredentials"]; /// Lowercase ASCII letters and digits of , without trailing digits (X-Hub-Signature-256 → xhubsignature). public static string Normalize(string? name) @@ -61,7 +65,8 @@ public static HashSet NormalizeAll(IEnumerable? names) => /// /// Whether values named are credentials. (normalized) are - /// matched like the built-in endings: "tenantkey" matches X-Tenant-Key and tenant_key. + /// matched like the built-in endings: "tenantkey" matches X-Tenant-Key and tenant_key. They win over the names known + /// not to be credentials (Access-Control-Allow-Credentials), which only change the built-in rules. /// public static bool IsSecret(string? name, NameKind kind, IReadOnlySet? extraNames = null) { @@ -76,6 +81,11 @@ public static bool IsSecret(string? name, NameKind kind, IReadOnlySet? e return true; } + if (NotSecret.Contains(normalized, StringComparer.Ordinal)) + { + return false; + } + if (kind == NameKind.QueryParameter && QueryOnly.Contains(normalized, StringComparer.Ordinal)) { return true; diff --git a/src/TermRest.Core/Recording/SecretPatterns.cs b/src/TermRest.Core/Recording/SecretPatterns.cs new file mode 100644 index 0000000..34d1037 --- /dev/null +++ b/src/TermRest.Core/Recording/SecretPatterns.cs @@ -0,0 +1,287 @@ +using System.Net; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Encodings.Web; +using TermRest.Core.Json; + +namespace TermRest.Core.Recording; + +/// +/// Secret values in the forms they take in text (see ), found in one pass over the data however many +/// there are. A few are looked for one by one (that search is vectorized). Beyond that, each is indexed by an 8-byte +/// piece of it that few others share: a scan reads the 8 bytes at each position of the data once, a bit filter lets few +/// of them through, and only the patterns indexed by those are compared. The work for some data then hardly grows with +/// the number of values. +/// +internal sealed class SecretPatterns +{ + private const int PieceLength = 8; + + // Up to this many patterns, looking for each on its own is faster than a scan. + private const int FewPatterns = 16; + + private const ulong Multiplier = 0x9E3779B97F4A7C15; // spreads pieces over the filter (Fibonacci hashing) + private const int MinFilterBits = 12; + private const int MaxFilterBits = 23; + + private readonly HashSet _seen = new(ContentComparer.Instance); + private readonly List _patterns = []; + + // Shorter than a piece (secrets of 4 to 7 characters): always looked for one by one. + private readonly List _short = []; + + // The patterns indexed by each piece, chained: the latest entry, then each entry's Next (-1 ends the chain). + private readonly Dictionary _latest = []; + private readonly List _entries = []; + private ulong[] _filter = []; + private int _filterBits; + private int _indexed; + + public int Count => _patterns.Count; + + /// + /// The forms may take in text, as UTF-8: as it is, URL-encoded, as a URL holds it, JSON-escaped + /// (as .NET, JavaScript, Python, PHP and Go escape it), with "/" escaped as "\/". + /// + public static IEnumerable Forms(string value) => Forms(value, Encoding.UTF8); + + /// The forms may take in text (see ), in . + public static IEnumerable Forms(string value, Encoding encoding) => + ((string[]) + [ + value, Uri.EscapeDataString(value), WebUtility.UrlEncode(value), InUrl(value), JavaScriptEncoder.Default.Encode(value), + MinimalJsonEncoder.Instance.Encode(value), value.Replace("/", "\\/", StringComparison.Ordinal), + LowerHexJson(value, asciiOnly: true), LowerHexJson(value, asciiOnly: true, slash: true), LowerHexJson(value, asciiOnly: false), + ]).Where(form => form.Length > 0).Distinct(StringComparer.Ordinal).Select(encoding.GetBytes); + + /// + /// JSON-escaped as Python, PHP and Go write it, with lower-case hex digits. With + /// , as Python's json.dumps does by default (Flask, Django, httpbin, TermRest's Python + /// scripts): every character outside printable ASCII is a \u escape of its UTF-16 code unit; PHP's json_encode does the + /// same and also escapes "/" (). Otherwise as Go's encoding/json does: besides what JSON + /// requires, only < > & U+2028 and U+2029 are escaped. + /// + private static string LowerHexJson(string value, bool asciiOnly, bool slash = false) + { + const string Hex = "0123456789abcdef"; + var text = new StringBuilder(value.Length + 8); + foreach (var c in value) + { + switch (c) + { + case '"': text.Append("\\\""); break; + case '\\': text.Append("\\\\"); break; + case '/' when slash: text.Append("\\/"); break; + case '\b': text.Append("\\b"); break; + case '\f': text.Append("\\f"); break; + case '\n': text.Append("\\n"); break; + case '\r': text.Append("\\r"); break; + case '\t': text.Append("\\t"); break; + default: + if (c < ' ' || (asciiOnly ? c > '~' : c is '<' or '>' or '&' or '\u2028' or '\u2029')) + { + text.Append("\\u").Append(Hex[c >> 12]).Append(Hex[(c >> 8) & 0xF]).Append(Hex[(c >> 4) & 0xF]).Append(Hex[c & 0xF]); + } + else + { + text.Append(c); + } + + break; + } + } + + return text.ToString(); + } + + /// + /// as leaves it in a URL, and so as it is sent: only what a URL can't hold is + /// escaped (spaces, control and non-ASCII characters, "<>\^`{|} and a % that starts no escape), so + /// P@ss^word is P@ss%5Eword, which neither of the URL encodings gives. A '#' is escaped too, as TermRest + /// sends one in a path or a query (see ). + /// + internal static string InUrl(string value) + { + const string Hex = "0123456789ABCDEF"; + var text = new StringBuilder(value.Length + 8); + Span utf8 = stackalloc byte[4]; + for (var i = 0; i < value.Length; i++) + { + var c = value[i]; + if (c is > ' ' and < '\x7F' and not ('"' or '#' or '<' or '>' or '\\' or '^' or '`' or '{' or '|' or '}') + && (c != '%' || (i + 2 < value.Length && char.IsAsciiHexDigit(value[i + 1]) && char.IsAsciiHexDigit(value[i + 2])))) + { + text.Append(c); + continue; + } + + Rune.DecodeFromUtf16(value.AsSpan(i), out var rune, out var length); // a lone surrogate is U+FFFD + i += length - 1; + foreach (var b in utf8[..rune.EncodeToUtf8(utf8)]) + { + text.Append('%').Append(Hex[b >> 4]).Append(Hex[b & 0xF]); + } + } + + return text.ToString(); + } + + /// Adds unless it is empty or already there. + public void Add(byte[] pattern) + { + if (pattern.Length > 0 && _seen.Add(pattern)) + { + _patterns.Add(pattern); + } + } + + /// Adds where the patterns are in : unsorted, possibly overlapping. + public void Find(ReadOnlySpan data, List spans) + { + if (_patterns.Count <= FewPatterns) + { + foreach (var pattern in _patterns) + { + FindEach(data, pattern, spans); + } + + return; + } + + IndexNew(); + foreach (var pattern in _short) + { + FindEach(data, pattern, spans); + } + + if (_latest.Count == 0) + { + return; + } + + var filter = _filter; + var shift = 64 - _filterBits; + ulong? notIndexed = null; // runs of the same bytes (zeros, indentation) are looked up once + ref var first = ref MemoryMarshal.GetReference(data); + for (var i = 0; i <= data.Length - PieceLength; i++) + { + var piece = Unsafe.ReadUnaligned(ref Unsafe.Add(ref first, i)); + var bit = (piece * Multiplier) >> shift; + if ((filter[(int)(bit >> 6)] & (1UL << (int)bit)) != 0 && piece != notIndexed && !Compare(data, i, piece, spans)) + { + notIndexed = piece; + } + } + } + + /// + /// Compares the patterns indexed by , which is at in + /// ; false when it indexes none. + /// + private bool Compare(ReadOnlySpan data, int position, ulong piece, List spans) + { + if (!_latest.TryGetValue(piece, out var latest)) + { + return false; + } + + for (var e = latest; e >= 0; e = _entries[e].Next) + { + var (pattern, offset, _) = _entries[e]; + var start = position - offset; + if (start >= 0 && data.Length - start >= pattern.Length && data.Slice(start, pattern.Length).SequenceEqual(pattern)) + { + spans.Add(new RedactedSpan(start, start + pattern.Length, false)); + } + } + + return true; + } + + private static void FindEach(ReadOnlySpan data, byte[] pattern, List spans) + { + for (var offset = 0; offset + pattern.Length <= data.Length;) + { + var index = data[offset..].IndexOf(pattern); + if (index < 0) + { + break; + } + + spans.Add(new RedactedSpan(offset + index, offset + index + pattern.Length, false)); + offset += index + pattern.Length; + } + } + + private static ulong Piece(byte[] pattern, int offset) => MemoryMarshal.Read(pattern.AsSpan(offset)); + + /// Indexes the patterns added since the last scan. + private void IndexNew() + { + for (; _indexed < _patterns.Count; _indexed++) + { + var pattern = _patterns[_indexed]; + if (pattern.Length < PieceLength) + { + _short.Add(pattern); + continue; + } + + // The piece fewest patterns are indexed by, looked for from the end: secrets often share their start (eyJhbGciOi…). + var best = 0; + var fewest = int.MaxValue; + for (var offset = pattern.Length - PieceLength; offset >= 0 && fewest > 0; offset--) + { + var count = 0; + for (var e = _latest.GetValueOrDefault(Piece(pattern, offset), -1); e >= 0 && count < fewest; e = _entries[e].Next) + { + count++; + } + + if (count < fewest) + { + (best, fewest) = (offset, count); + } + } + + var piece = Piece(pattern, best); + _entries.Add(new Entry(pattern, best, _latest.GetValueOrDefault(piece, -1))); + _latest[piece] = _entries.Count - 1; + if (_filterBits < MaxFilterBits && (long)_latest.Count * 16 > 1L << _filterBits) + { + // At most one bit in 16 is set, so few positions that index nothing get past the filter. + _filterBits = Math.Max(MinFilterBits, _filterBits + 1); + _filter = new ulong[(1 << _filterBits) / 64]; + foreach (var key in _latest.Keys) + { + Mark(key); + } + } + + Mark(piece); + } + } + + private void Mark(ulong piece) + { + var bit = (piece * Multiplier) >> (64 - _filterBits); + _filter[(int)(bit >> 6)] |= 1UL << (int)bit; + } + + private readonly record struct Entry(byte[] Pattern, int Offset, int Next); + + private sealed class ContentComparer : IEqualityComparer + { + public static readonly ContentComparer Instance = new(); + + public bool Equals(byte[]? x, byte[]? y) => x.AsSpan().SequenceEqual(y); + + public int GetHashCode(byte[] obj) + { + var hash = new HashCode(); + hash.AddBytes(obj); + return hash.ToHashCode(); + } + } +} diff --git a/src/TermRest.Core/Scripting/CSharpPrograms.cs b/src/TermRest.Core/Scripting/CSharpPrograms.cs index f678388..b19829f 100644 --- a/src/TermRest.Core/Scripting/CSharpPrograms.cs +++ b/src/TermRest.Core/Scripting/CSharpPrograms.cs @@ -1,9 +1,11 @@ using System.ComponentModel; using System.Diagnostics; +using System.IO.Enumeration; using System.Security.Cryptography; using System.Text; using System.Text.Json.Nodes; using System.Text.RegularExpressions; +using System.Xml; namespace TermRest.Core.Scripting; @@ -22,9 +24,32 @@ internal sealed partial class CSharpPrograms(string dotnet, string workspaceRoot private static readonly TimeSpan BuildTimeout = TimeSpan.FromMinutes(3); private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false); + /// + /// The files that builds read, by extension or name: code, what is compiled in with it (resources, Razor pages), + /// assemblies, and what directs the build (project files, MSBuild's .props and .targets, global.json, NuGet's + /// settings). Not the others, which a project's own program may write in its folder whenever it runs (a database, logs). + /// + private static readonly HashSet.AlternateLookup> BuildInputs = new HashSet( + [".cs", ".vb", ".fs", ".fsi", ".resx", ".razor", ".cshtml", ".dll", ".csproj", ".vbproj", ".fsproj", ".proj", ".props", ".targets", "global.json", "nuget.config"], + StringComparer.OrdinalIgnoreCase).GetAlternateLookup>(); + + /// + /// The files that MSBuild and NuGet look for in the folders above a project, by these names (NuGet takes these three + /// spellings of nuget.config where names are case-sensitive). The other files there are not read: they may be many. + /// + private static readonly string[] SettingsAbove = + ["Directory.Build.props", "Directory.Build.targets", "Directory.Packages.props", "global.json", "nuget.config", "NuGet.config", "NuGet.Config"]; + /// Programs that did not compile, by key: the same code fails again, so it is not built again. private readonly Dictionary> _failed = new(StringComparer.Ordinal); + /// + /// Programs that did not build while they held scripts besides those that ran (the collection's), by key, whatever the + /// error (a package that cannot be restored, a #:project that is not there): this session leaves those scripts out at + /// once instead of building them again. A program of the scripts that run alone is built again: they may have been fixed. + /// + private readonly Dictionary> _failedWithOthers = new(StringComparer.Ordinal); + /// Whether this TermRest built C# scripts since it last stopped the compiler server. private static int _built; @@ -61,6 +86,23 @@ public static string CacheDirectory() return Path.Combine(root, "csharp"); } + /// , created when it is not there. + internal static string CreateCacheDirectory() + { + var cache = CacheDirectory(); + if (OperatingSystem.IsWindows()) + { + Directory.CreateDirectory(cache); + } + else + { + // The scripts' code is in here: for the user only, as the history is. + Directory.CreateDirectory(cache, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + + return cache; + } + /// /// Makes sure a program can run the scripts of : it holds them and the other scripts /// that may run next (: the collection's), so the next requests need no new build. Each @@ -91,11 +133,10 @@ public static string CacheDirectory() var program = codes.Keys.ToHashSet(StringComparer.Ordinal); var broken = new Dictionary>(StringComparer.Ordinal); var watch = Stopwatch.StartNew(); - var built = false; for (var round = 0; round < 8; round++) { - var (path, errors, compiled) = await BuildAsync(program, codes, cancellationToken).ConfigureAwait(false); - built |= compiled; + var withOthers = program.Any(id => !needed.Contains(id)); + var (path, errors, built) = await BuildAsync(program, codes, withOthers, cancellationToken).ConfigureAwait(false); if (path is not null) { foreach (var script in scripts) @@ -107,11 +148,22 @@ public static string CacheDirectory() } } + // Only when the program that runs was built now: builds that failed leave nothing to start next time, and a + // script of this request that did not build is built again next time (it may have been fixed). var seconds = watch.Elapsed.TotalSeconds.ToString("0.0", System.Globalization.CultureInfo.InvariantCulture); - return (path, built ? $"The C# scripts were built ({seconds} s; they start at once next time)." : null); + var next = broken.Keys.Any(needed.Contains) ? "" : "; they start at once next time"; + return (path, built ? $"The C# scripts were built ({seconds} s{next})." : null); } var inScripts = errors.Where(e => e.Script is not null && program.Contains(e.Script)).GroupBy(e => e.Script!).ToList(); + if (withOthers && inScripts.Any(group => needed.Contains(group.Key))) + { + // Every script's directives (#:property, #:sdk, #:package) apply to the whole program, so another script of + // the collection may break the lines of those that run: built without the others, the errors left are theirs. + program.IntersectWith(needed); + continue; + } + if (inScripts.Count > 0) { foreach (var group in inScripts) @@ -123,7 +175,7 @@ public static string CacheDirectory() continue; } - if (program.Any(id => !needed.Contains(id))) + if (withOthers) { program.IntersectWith(needed); // the cause may be another script of the collection continue; @@ -141,8 +193,7 @@ public static string CacheDirectory() var culprits = 0; foreach (var id in program.ToList()) { - var (_, alone, compiledAlone) = await BuildAsync([id], codes, cancellationToken).ConfigureAwait(false); - built |= compiledAlone; + var (_, alone, _) = await BuildAsync([id], codes, withOthers: false, cancellationToken).ConfigureAwait(false); if (alone.Count > 0) { broken[id] = alone; @@ -176,19 +227,23 @@ public static void Forget(string program) /// /// Stops the .NET SDK's C# compiler server when this TermRest built scripts: builds keep it running for 10 minutes /// (100 MB or more), as every dotnet build does. It starts again for the next build, which then takes a few - /// seconds instead of one. Runs in the background. + /// seconds instead of one. Runs in the background, where the builds run: the SDK that built the scripts stops its + /// server (in TermRest's current folder, a global.json could choose another SDK). /// public static void StopCompilerServer(string dotnet) { - if (Interlocked.Exchange(ref _built, 0) == 0) + if (Interlocked.Exchange(ref _built, 0) == 0 || ScriptRuntimeLocator.Executable(dotnet) is not { } executable) { return; } try { - var info = new ProcessStartInfo(dotnet, ["build-server", "shutdown", "--vbcscompiler"]) + var folder = Path.Combine(CreateCacheDirectory(), "source"); + Directory.CreateDirectory(folder); + var info = new ProcessStartInfo(executable, ["build-server", "shutdown", "--vbcscompiler"]) { + WorkingDirectory = folder, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, @@ -210,17 +265,19 @@ public static void StopCompilerServer(string dotnet) }); } } - catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or PlatformNotSupportedException) + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException or PlatformNotSupportedException or IOException or UnauthorizedAccessException) { - // no SDK to ask + // no SDK to ask, or no folder to ask it in } } /// The program of these scripts: a copy built before, or a new build. Null with the errors when it does not build. + /// Whether the program holds scripts besides those that run (see ). private async Task<(string? Program, List Errors, bool Built)> BuildAsync(IEnumerable ids, Dictionary codes, - CancellationToken cancellationToken) + bool withOthers, CancellationToken cancellationToken) { var source = CSharpWorkerCode.Generate(ids.ToDictionary(id => id, id => codes[id], StringComparer.Ordinal), workspaceRoot); + source += Inputs(source); var key = Convert.ToHexStringLower(SHA256.HashData(Utf8.GetBytes(dotnet + "\n" + source)))[..20]; var cache = CacheDirectory(); var copy = Path.Combine(cache, "programs", key); @@ -231,22 +288,13 @@ public static void StopCompilerServer(string dotnet) lock (_failed) { - if (_failed.TryGetValue(key, out var known)) + if (_failed.TryGetValue(key, out var known) || (withOthers && _failedWithOthers.TryGetValue(key, out known))) { return (null, known, false); } } - if (OperatingSystem.IsWindows()) - { - Directory.CreateDirectory(cache); - } - else - { - // The scripts' code is in here: for the user only, as the history is. - Directory.CreateDirectory(cache, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); - } - + CreateCacheDirectory(); Directory.CreateDirectory(Path.Combine(cache, "programs")); using var gate = await LockAsync(Path.Combine(cache, "build.lock"), cancellationToken).ConfigureAwait(false); if (Ready(copy) is { } builtMeanwhile) @@ -282,28 +330,167 @@ public static void StopCompilerServer(string dotnet) return (Path.Combine(copy, CSharpWorkerCode.AssemblyName + ".dll"), [], true); } - var errors = Errors(output); + var errors = Errors(output, workspaceRoot); if (errors.Count == 0) { errors.Add(new CSharpError(null, 0, 0, "", "", $"dotnet run failed (exit code {exitCode}):\n{string.Join('\n', output.TakeLast(8))}".TrimEnd())); } - if (errors.Any(e => e.Code.StartsWith("CS", StringComparison.Ordinal))) + // Compiler errors come back with the same code; a failed restore may not, but other scripts are left out then. + var compiler = errors.Any(e => e.Code.StartsWith("CS", StringComparison.Ordinal)); + if (compiler || withOthers) { lock (_failed) { - if (_failed.Count > 50) + var failed = compiler ? _failed : _failedWithOthers; + if (failed.Count > 50) { - _failed.Clear(); + failed.Clear(); } - _failed[key] = errors; // compiler errors come back with the same code; a failed restore may not + failed[key] = errors; } } return (null, errors, true); } + /// + /// The files that the program's #:include and #:project directives bring in, as they are now (paths, sizes, times), as a + /// comment for its end: when one of them changes, so does the program, which is then built again (the SDK too sees a + /// changed file) instead of the one built before. For a project, those are the files of its folder, the settings that + /// MSBuild and NuGet find in the folders above it (), and the same for the projects that it + /// references, in turn. In a project's folder and in an #:include with wildcards, only files that builds read count + /// (). Paths with MSBuild properties ($(…)) are not known here. + /// + private static string Inputs(string source) + { + var files = new HashSet(StringComparer.Ordinal); + var projects = new Queue(); + foreach (var (directive, path) in CSharpWorkerCode.PathsOf(source).Where(p => !p.Path.Contains("$(", StringComparison.Ordinal))) + { + var wildcard = path.IndexOfAny(['*', '?']); + if (wildcard >= 0) + { + files.UnionWith(Files(path[..(path[..wildcard].LastIndexOfAny(['/', '\\']) + 1)], Path.GetFileName(path))); + } + else if (directive == "include" && File.Exists(path)) + { + var file = new FileInfo(path); + files.Add($"{path}|{file.Length}|{file.LastWriteTimeUtc.Ticks}"); + } + else + { + projects.Enqueue(path); // a project file, or a folder with one + } + } + + var folders = new HashSet(StringComparer.Ordinal); + var above = new HashSet(StringComparer.Ordinal); + var read = new HashSet(StringComparer.Ordinal); + while (projects.TryDequeue(out var path)) + { + var isFile = File.Exists(path); + var folder = isFile ? Path.GetDirectoryName(path)! : path; + if (folders.Add(folder)) + { + files.UnionWith(Files(folder, "*")); + + // The folders above it, up to the first one already looked at (those above it were, too). + for (var parent = Path.GetDirectoryName(folder); parent is not null && above.Add(parent); parent = Path.GetDirectoryName(parent)) + { + foreach (var name in SettingsAbove) + { + var file = new FileInfo(Path.Combine(parent, name)); + if (file.Exists) + { + files.Add($"{file.FullName}|{file.Length}|{file.LastWriteTimeUtc.Ticks}"); + } + } + } + } + + string[] found = isFile ? [path] + : Directory.Exists(path) ? Directory.GetFiles(path, "*.*proj", new EnumerationOptions { IgnoreInaccessible = true, AttributesToSkip = 0 }) + : []; + foreach (var project in found) + { + if (read.Add(project)) + { + foreach (var reference in References(project)) + { + projects.Enqueue(reference); + } + } + } + } + + if (files.Count == 0) + { + return ""; + } + + var hash = SHA256.HashData(Utf8.GetBytes(string.Join('\n', files.Order(StringComparer.Ordinal)))); + return $"\n// Files of #:include and #:project: {Convert.ToHexStringLower(hash)[..20]}\n"; + } + + /// + /// The projects that a project file references (ProjectReference), with full paths. Those whose path MSBuild works out + /// from properties ($(…)) or wildcards are not known here and are left out: their changes build nothing again. + /// + private static List References(string project) + { + var references = new List(); + try + { + using var stream = File.OpenRead(project); + using var reader = XmlReader.Create(stream, new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, XmlResolver = null, IgnoreComments = true }); + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "ProjectReference" && reader.GetAttribute("Include") is { } include) + { + foreach (var item in include.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + { + if (item.IndexOfAny(['$', '@', '%', '*', '?']) < 0) + { + // Relative to the project; MSBuild takes \ as / on Linux and macOS. + references.Add(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(project)!, item.Replace('\\', '/')))); + } + } + } + } + } + catch (Exception ex) when (ex is XmlException or IOException or UnauthorizedAccessException or ArgumentException) + { + // its build says what is wrong with it + } + + return references; + } + + /// + /// The files that builds read () in a folder and its subfolders whose names match, but in those + /// that builds write (bin, obj), node_modules and hidden ones (.git…). + /// + private static List Files(string folder, string pattern) + { + if (!Directory.Exists(folder)) + { + return [$"{folder}|missing"]; + } + + var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = 0 }; + return + [ + .. new FileSystemEnumerable(folder, (ref FileSystemEntry entry) => $"{entry.ToFullPath()}|{entry.Length}|{entry.LastWriteTimeUtc.Ticks}", options) + { + ShouldIncludePredicate = (ref FileSystemEntry entry) => !entry.IsDirectory && FileSystemName.MatchesSimpleExpression(pattern, entry.FileName) + && (BuildInputs.Contains(Path.GetExtension(entry.FileName)) || BuildInputs.Contains(entry.FileName)), + ShouldRecursePredicate = (ref FileSystemEntry entry) => entry.FileName is not ("bin" or "obj" or "node_modules") && entry.FileName[0] != '.', + }, + ]; + } + private static string? Ready(string copy) { var marker = Path.Combine(copy, ".ok"); @@ -334,32 +521,30 @@ private static void Keep(string output, string copy) Directory.Delete(temporary, recursive: true); } - foreach (var file in Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories)) - { - var target = Path.Combine(temporary, Path.GetRelativePath(output, file)); - Directory.CreateDirectory(Path.GetDirectoryName(target)!); - File.Copy(file, target, overwrite: true); - } - - var moved = true; if (Directory.Exists(copy)) { try { - Directory.Delete(copy, recursive: true); // incomplete, or forgotten + // The program first: while a TermRest runs it, deleting it fails (on Windows) and the folder stays whole. + File.Delete(Path.Combine(copy, CSharpWorkerCode.AssemblyName + ".dll")); } - catch (IOException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - moved = false; // a TermRest runs it: it is complete - Directory.Delete(temporary, recursive: true); + File.WriteAllText(Path.Combine(copy, ".ok"), ""); // it runs, so it is complete + return; } + + Directory.Delete(copy, recursive: true); // incomplete, or forgotten } - if (moved) + foreach (var file in Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories)) { - Directory.Move(temporary, copy); + var target = Path.Combine(temporary, Path.GetRelativePath(output, file)); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Copy(file, target, overwrite: true); } + Directory.Move(temporary, copy); File.WriteAllText(Path.Combine(copy, ".ok"), ""); } @@ -432,7 +617,8 @@ private static async Task LockAsync(string path, CancellationToken c /// Runs dotnet with hidden output; returns its exit code and what it printed. private async Task<(int ExitCode, List Output)> RunAsync(string[] arguments, string workingDirectory, CancellationToken cancellationToken) { - var info = new ProcessStartInfo(dotnet) + var executable = ScriptRuntimeLocator.Executable(dotnet) ?? throw new ScriptException($"The .NET SDK could not be started ({dotnet}): it is not on PATH."); + var info = new ProcessStartInfo(executable) { WorkingDirectory = workingDirectory, RedirectStandardInput = true, @@ -507,20 +693,27 @@ void Add(object sender, DataReceivedEventArgs e) } } - /// The errors in the build output; those in a script's lines name the script. - private static List Errors(List output) + /// + /// The errors in the build output; those in a script's lines name the script, those in a file that a script brings in + /// (#:include, #:project) name that file (relative to the workspace when inside it) and their position. + /// + private static List Errors(List output, string workspaceRoot) { var errors = new List(); foreach (var line in output.Select(l => l.Trim()).Where(l => !Warning().IsMatch(l))) { if (PositionedError().Match(line) is { Success: true } positioned) { - var script = CSharpWorkerCode.ScriptIdOf(positioned.Groups["file"].Value); + var file = positioned.Groups["file"].Value; + var script = CSharpWorkerCode.ScriptIdOf(file); var code = positioned.Groups["code"].Value; var text = positioned.Groups["message"].Value; - errors.Add(new CSharpError(script, int.Parse(positioned.Groups["line"].Value, System.Globalization.CultureInfo.InvariantCulture), - int.Parse(positioned.Groups["column"].Value, System.Globalization.CultureInfo.InvariantCulture), code, text, - script is null ? $"{code}: {text} (at the end of the script)" : $"{code}: {text}")); + var row = int.Parse(positioned.Groups["line"].Value, System.Globalization.CultureInfo.InvariantCulture); + var column = int.Parse(positioned.Groups["column"].Value, System.Globalization.CultureInfo.InvariantCulture); + errors.Add(new CSharpError(script, row, column, code, text, + script is not null ? $"{code}: {text}" + : Path.GetFileName(file).Equals(CSharpWorkerCode.AssemblyName + ".cs", StringComparison.OrdinalIgnoreCase) ? $"{code}: {text} (at the end of the script)" + : $"{code}: {text} ({Shown(file, workspaceRoot)}, line {row}, column {column})")); } else if (OtherError().Match(line) is { Success: true } other) { @@ -533,6 +726,24 @@ private static List Errors(List output) return errors; } + /// + /// relative to the workspace when it is inside it, else as it is. The files of a #:project come + /// by their project's path (), which may be the workspace's real one. + /// + private static string Shown(string file, string workspaceRoot) + { + foreach (var root in (string[])[workspaceRoot, CSharpWorkerCode.ProjectPath(workspaceRoot)]) + { + var relative = Path.GetRelativePath(root, file); + if (!relative.StartsWith("..", StringComparison.Ordinal) && !Path.IsPathRooted(relative)) + { + return relative; + } + } + + return file; + } + /// A script's compiler errors, as Python shows a syntax error: the first in the message, all in the traceback. private static (string Message, string Traceback) Describe(List errors, string name, string code) { diff --git a/src/TermRest.Core/Scripting/CSharpWorkerCode.cs b/src/TermRest.Core/Scripting/CSharpWorkerCode.cs index 76da136..9ce8d3c 100644 --- a/src/TermRest.Core/Scripting/CSharpWorkerCode.cs +++ b/src/TermRest.Core/Scripting/CSharpWorkerCode.cs @@ -1,6 +1,7 @@ using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; +using TermRest.Core.IO; namespace TermRest.Core.Scripting; @@ -75,6 +76,22 @@ public static string Generate(IReadOnlyDictionary scripts, strin text.Append(directive).Append('\n'); } + // Global usings apply to the whole program, as they do in a file-based app (where they also reach #:include files): + // they come before the namespaces, once each. + var globalUsings = new HashSet(StringComparer.Ordinal); + foreach (var (id, script) in parts) + { + foreach (var (line, directive) in script.GlobalUsings.Where(u => globalUsings.Add(u.Text))) + { + text.Append("\n#line ").Append(line).Append(" \"").Append(ScriptFile).Append(id).Append("\"\n").Append(directive); + } + } + + if (globalUsings.Count > 0) + { + text.Append("\n#line default\n"); + } + foreach (var (id, script) in parts) { text.Append("\nnamespace TermRestScripts.S").Append(id).Append("\n{\n") @@ -102,12 +119,16 @@ public static string Generate(IReadOnlyDictionary scripts, strin return text.Append(" };\n }\n}\n\n").Append(Runtime).ToString(); } - /// The directives and using directives at the start of a script, and the rest (the method's body). - private static (List Directives, List<(int Line, string Text)> Usings, string Body) Split(string code, string workspaceRoot) + /// + /// The directives, using directives and global using directives at the start of a script, and the rest (the + /// method's body). + /// + private static (List Directives, List<(int Line, string Text)> Usings, List<(int Line, string Text)> GlobalUsings, string Body) Split(string code, string workspaceRoot) { var lines = Normalize(code).Split('\n'); var directives = new List(); var usings = new List<(int, string)>(); + var globalUsings = new List<(int, string)>(); var comment = false; for (var i = 0; i < lines.Length; i++) { @@ -139,11 +160,12 @@ private static (List Directives, List<(int Line, string Text)> Usings, s break; } - usings.Add((i + 1, line)); + // C# allows a global using only before the namespaces (see Generate). + (line.StartsWith("global", StringComparison.Ordinal) ? globalUsings : usings).Add((i + 1, line)); lines[i] = ""; } - return (directives, usings, string.Join('\n', lines)); + return (directives, usings, globalUsings, string.Join('\n', lines)); } private static string WithFullPath(string directive, string workspaceRoot) @@ -155,11 +177,36 @@ private static string WithFullPath(string directive, string workspaceRoot) } var path = match.Groups[2].Value.Trim(); - return Path.IsPathRooted(path) || path.StartsWith('$') - ? directive - : $"#:{match.Groups[1].Value} {Path.GetFullPath(Path.Combine(workspaceRoot, path))}"; + if (path.StartsWith('$')) + { + return directive; + } + + var full = Path.IsPathRooted(path) ? path : Path.GetFullPath(Path.Combine(workspaceRoot, path)); + + if (match.Groups[1].Value == "project") + { + full = ProjectPath(full); + } + + return full == path ? directive : $"#:{match.Groups[1].Value} {full}"; } + /// + /// A project's path as the build should see it: on Linux and macOS without symbolic links (), + /// as NuGet leaves out the projects that a project references when the path to it goes through a link (on macOS, /var + /// and /tmp are links), and the program then builds without them. + /// + internal static string ProjectPath(string path) => OperatingSystem.IsWindows() ? path : RealPath.Of(path) ?? path; + + + /// The #:include and #:project directives of a program from : which one, and its path. + public static IEnumerable<(string Directive, string Path)> PathsOf(string program) => + program[..Math.Max(0, program.IndexOf("\n\n", StringComparison.Ordinal))].Split('\n') + .Select(line => PathDirective().Match(line)) + .Where(match => match.Success) + .Select(match => (match.Groups[1].Value, match.Groups[2].Value.Trim())); + // using X.Y; using static X.Y; using A = X.Y; (not using statements: using var x = …, using (…), using T x = …) [GeneratedRegex(@"^(?:global\s+)?using\s+(?:static\s+[\w.@<>,\s]+|[A-Za-z_@]\w*\s*=\s*[^;]+|[A-Za-z_@][\w.@]*)\s*;\s*(?://.*)?$")] private static partial Regex UsingDirective(); @@ -338,9 +385,14 @@ public void Clear() public sealed class Variables : Scope { private readonly Dictionary[] _scopes; + private readonly JsonObject _samples; - internal Variables(Dictionary local, JsonObject changes, Dictionary[] scopes) - : base(local, changes) => _scopes = scopes; + internal Variables(Dictionary local, JsonObject changes, Dictionary[] scopes, JsonObject samples) + : base(local, changes) + { + _scopes = scopes; + _samples = samples; + } public override string Get(string name, string fallback = null) { @@ -371,12 +423,16 @@ public override Dictionary ToDictionary() return merged; } - /// Replaces {{name}} with the variables' values; unknown names stay as they are. + /// Replaces {{name}} with the variables' values, and Postman's dynamic variables ({{$guid}}…); unknown names stay as they are. public string ReplaceIn(string text) { for (var i = 0; i < 10 && text is not null; i++) { - var replaced = Host.Reference.Replace(text, m => Get(m.Groups[1].Value.Trim(), m.Value)); + var replaced = Host.Reference.Replace(text, m => + { + var name = m.Groups[1].Value.Trim(); + return Get(name) ?? Host.Dynamic(name, _samples) ?? m.Value; + }); if (replaced == text) { break; @@ -683,6 +739,14 @@ private static (TextReader Input, TextWriter Output) Channel() else { var self = NativeLibrary.GetMainProgramHandle(); + + // A session of its own, without TermRest's terminal: programs that scripts start (ssh, sudo, gpg) + // cannot open /dev/tty to ask over TermRest's screen, and fail at once, as they do without a terminal. + if (NativeLibrary.TryGetExport(self, "setsid", out var setsid)) + { + Marshal.GetDelegateForFunctionPointer(setsid)(); + } + var dup = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(self, "dup")); var dup2 = Marshal.GetDelegateForFunctionPointer(NativeLibrary.GetExport(self, "dup2")); int inputCopy = dup(0), outputCopy = dup(1); @@ -718,6 +782,9 @@ private static (TextReader Input, TextWriter Output) Channel() [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int Dup2(int descriptor, int target); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate int Setsid(); + private static JsonObject Run(JsonObject message) { var phase = AsText(message["phase"]) ?? ""; @@ -743,7 +810,7 @@ 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 }), + new Variables(local, changes["local"].AsObject(), new[] { local, environment, collection, globals }, message["dynamic"] as JsonObject), request, message["response"] is JsonObject response ? new Response(response) : null, info, @@ -787,7 +854,8 @@ Dictionary Values(string scope) var clean = printed.TrimEnd('\r'); if (logs.Count < MaxLines) { - logs.Add(new JsonObject { ["script"] = name, ["text"] = clean.Length > 4000 ? clean[..4000] : clean }); + // Lines are cut at 4,000 characters, not inside a surrogate pair (an emoji). + logs.Add(new JsonObject { ["script"] = name, ["text"] = clean.Length > 4000 ? clean[..(char.IsHighSurrogate(clean[3999]) ? 3999 : 4000)] : clean }); } else { @@ -852,20 +920,35 @@ private static string Traceback(Exception error, string id, string name, string internal static string AsText(JsonNode node) => node is JsonValue value && value.TryGetValue(out var text) ? text : node?.ToJsonString(); - /// Variables and headers are text: strings stay as they are, anything else becomes JSON. + /// + /// Variables and headers are text: strings stay as they are, numbers, dates, GUIDs and the like become their + /// text, anything else becomes JSON; one whose JSON is a string is that string, without the quotes. + /// internal static string ToText(object value) => value switch { null => "", string text => text, bool flag => flag ? "true" : "false", - JsonValue node when node.GetValueKind() == JsonValueKind.String => node.GetValue(), + JsonValue node when node.GetValueKind() == JsonValueKind.String => StringOf(node), JsonNode node => node.ToJsonString(Options), DateTime time => time.ToString("O", CultureInfo.InvariantCulture), DateTimeOffset time => time.ToString("O", CultureInfo.InvariantCulture), + DateOnly date => date.ToString("O", CultureInfo.InvariantCulture), + TimeOnly time => time.ToString("O", CultureInfo.InvariantCulture), + Uri uri => uri.OriginalString, // as written: its ToString() unescapes it (a %20 becomes a space) IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), - _ => JsonSerializer.Serialize(value, value.GetType(), Options), + _ => Unquoted(JsonSerializer.Serialize(value, value.GetType(), Options)), }; + /// A JSON string as the string it holds; other JSON as it is. + private static string Unquoted(string json) => json.StartsWith('"') ? JsonSerializer.Deserialize(json, Options) ?? "" : json; + + /// + /// The text of a JSON string value: also of one made from a GUID, a date or a char (new JsonObject { ["id"] = + /// Guid.NewGuid() }), which GetValue<string>() refuses. + /// + private static string StringOf(JsonValue node) => node.TryGetValue(out var text) ? text : Unquoted(node.ToJsonString(Options)); + internal static bool Same(object expected, object actual) { expected = Plain(expected); @@ -922,7 +1005,7 @@ internal static string Show(object value) private static object Plain(object value) => value is JsonValue node ? node.GetValueKind() switch { - JsonValueKind.String => node.GetValue(), + JsonValueKind.String => StringOf(node), JsonValueKind.True => true, JsonValueKind.False => false, _ => node, @@ -937,6 +1020,51 @@ JsonValue node when node.GetValueKind() == JsonValueKind.Number => double.Parse( private static JsonNode Node(object value) => value as JsonNode ?? JsonSerializer.SerializeToNode(value, value.GetType(), Options); + /// + /// A value of one of Postman's dynamic variables, as requests resolve them, or null for another name; the + /// names and words they pick from come with the message. + /// + internal static string Dynamic(string name, JsonObject samples) + { + const string Alphanumeric = "abcdefghijklmnopqrstuvwxyz0123456789"; + string Pick(string key) + { + var values = (samples?[key] as JsonArray)?.Select(AsText).Where(v => v is not null).ToArray() ?? Array.Empty(); + return values.Length == 0 ? "" : values[global::System.Security.Cryptography.RandomNumberGenerator.GetInt32(values.Length)]; + } + + static int Next(int limit) => global::System.Security.Cryptography.RandomNumberGenerator.GetInt32(limit); + static string RandomText(int length, string alphabet) + { + var letters = new char[length]; + for (var i = 0; i < length; i++) + { + letters[i] = alphabet[Next(alphabet.Length)]; + } + + return new string(letters); + } + + return name switch + { + "$guid" or "$randomUUID" => Guid.NewGuid().ToString(), + "$timestamp" => DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + "$isoTimestamp" => DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture), + "$randomInt" => Next(1001).ToString(CultureInfo.InvariantCulture), + "$randomBoolean" => Next(2) == 1 ? "true" : "false", + "$randomAlphaNumeric" => RandomText(1, Alphanumeric), + "$randomHexadecimal" => RandomText(1, "0123456789abcdef"), + "$randomFirstName" => Pick("firstNames"), + "$randomLastName" => Pick("lastNames"), + "$randomFullName" => Pick("firstNames") + " " + Pick("lastNames"), + "$randomUserName" => Pick("firstNames").ToLowerInvariant() + "." + Pick("lastNames").ToLowerInvariant() + Next(100).ToString(CultureInfo.InvariantCulture), + "$randomEmail" => Pick("firstNames").ToLowerInvariant() + "." + Pick("lastNames").ToLowerInvariant() + "@example.com", + "$randomWord" => Pick("words"), + "$randomPassword" => RandomText(15, Alphanumeric), + _ => null, + }; + } + /// What the running script writes to the console (Console.WriteLine…): its output. private sealed class Capture : TextWriter { diff --git a/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs b/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs index 3a57169..da4add1 100644 --- a/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs +++ b/src/TermRest.Core/Scripting/JavaScriptWorkerCode.cs @@ -58,6 +58,7 @@ function compile(context, name, code) { inspect: value => util.inspect(value, { depth: 3, breakLength: Infinity, maxArrayLength: 20, maxStringLength: 300 }), require: requireFromWorkspace, uuid: () => nodeCrypto.randomUUID(), + randomInt: limit => nodeCrypto.randomInt(limit), fetch: (...args) => fetch(...args), setTimeout, clearTimeout, setInterval, clearInterval, setImmediate, clearImmediate, Buffer, URL, URLSearchParams, TextEncoder, TextDecoder, AbortController, FormData, Headers, @@ -67,7 +68,7 @@ function compile(context, name, code) { async function run(line) { const context = vm.createContext({}); - const state = { onError: null }; + const state = { onError: null, console: null }; active = state; try { const start = sandboxScript.runInContext(context); @@ -75,6 +76,7 @@ async function run(line) { message: line, compile: (name, code) => compile(context, name, code), onError: handler => { state.onError = handler; }, + onConsole: target => { state.console = target; }, })); } finally { active = null; @@ -92,10 +94,22 @@ function uncaught(error) { process.on('uncaughtException', uncaught); process.on('unhandledRejection', uncaught); + // Modules and packages that scripts require run outside the scripts' context, where console is the runtime's own (its + // stdout and stderr, which TermRest does not show): while a script runs, what they log goes to the script's output. + for (const name of ['log', 'info', 'debug', 'trace', 'warn', 'error', 'dir', 'table', 'assert', 'count', 'countReset', 'time', 'timeLog', 'timeEnd', 'group', 'groupCollapsed', 'groupEnd']) { + const own = console[name]; + if (typeof own === 'function') { + console[name] = (...args) => active !== null && active.console !== null ? active.console[name](...args) : own.apply(console, args); + } + } + let queue = Promise.resolve(); let partial = []; + + // 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 reply(text) { - process.stdout.write(MARKER + text + '\n'); + process.stdout.write(MARKER + text.replace(/\\(\\|ud[89a-f][0-9a-f]{2})/g, (escape, what) => what === '\\' ? escape : '\\ufffd') + '\n'); } function receive(chunk) { @@ -144,14 +158,19 @@ function text(value) { if (typeof value === 'string') return value; if (value === null || value === undefined) return ''; if (typeof value === 'object') { - try { return stringify(value); } catch (error) { return String(value); } + let json; + try { json = stringify(value); } catch (error) { return String(value); } + + // One whose JSON is a string (a Date, a URL …) is that string, without the quotes. + return typeof json === 'string' && json.startsWith('"') ? JSON.parse(json) : json; } return String(value); } function log(line) { for (const part of String(line).split(/\r?\n/)) { - if (logs.length < MAX_LINES) logs.push({ script: current, text: part.length > 4000 ? part.slice(0, 4000) : part }); + // Lines are cut at 4,000 characters, not inside a surrogate pair (an emoji). + if (logs.length < MAX_LINES) logs.push({ script: current, text: part.length > 4000 ? part.slice(0, /[\ud800-\udbff]/.test(part[3999]) ? 3999 : 4000) : part }); else dropped++; } } @@ -163,23 +182,39 @@ function notice(line) { } } + // What a script threw may be any value: one without a prototype, a revoked proxy, or getters that throw. Describing + // it never throws (that would fail the whole run instead of the script). + function safeString(value) { + try { return String(value); } catch (ignored) { } + try { return Object.prototype.toString.call(value); } catch (ignored) { return '(a value that cannot be shown)'; } + } + function isError(value) { - return value !== null && typeof value === 'object' && 'message' in value; + try { return value !== null && typeof value === 'object' && 'message' in value; } catch (ignored) { return false; } + } + + function nameOf(error) { + try { return String(error.name || 'Error'); } catch (ignored) { return 'Error'; } + } + + function messageOf(error) { + try { return String(error.message); } catch (ignored) { return '(its message could not be read)'; } } function describe(error) { - if (!isError(error)) return String(error); - const name = error.name || 'Error'; - return name === 'AssertionError' ? String(error.message) : name + ': ' + error.message; + if (!isError(error)) return safeString(error); + const name = nameOf(error); + return name === 'AssertionError' ? messageOf(error) : name + ': ' + messageOf(error); } function fullDescribe(error) { - return isError(error) ? (error.name || 'Error') + ': ' + error.message : String(error); + return isError(error) ? nameOf(error) + ': ' + messageOf(error) : safeString(error); } function traceback(error, name, code) { const source = String(code).split(/\r?\n/); - const stack = isError(error) && typeof error.stack === 'string' ? error.stack : ''; + let stack = ''; + try { if (isError(error) && typeof error.stack === 'string') stack = error.stack; } catch (ignored) { } const pattern = new RegExp(name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ':(\\d+)', 'g'); const frames = []; let match; @@ -280,12 +315,27 @@ function once(schedule, clear, fn, args, delay) { changes[scope] = Object.create(null); } + // Postman's dynamic variables, as requests resolve them; the names and words they pick from come with the message. + const samples = message.dynamic || {}; + const ALPHANUMERIC = 'abcdefghijklmnopqrstuvwxyz0123456789'; + const pick = list => (Array.isArray(list) && list.length > 0 ? String(list[host.randomInt(list.length)]) : ''); + const randomText = (length, alphabet) => Array.from({ length }, () => alphabet[host.randomInt(alphabet.length)]).join(''); const dynamic = { $guid: () => host.uuid(), $randomUUID: () => host.uuid(), $timestamp: () => String(Math.floor(Date.now() / 1000)), $isoTimestamp: () => new Date().toISOString(), - $randomInt: () => String(Math.floor(Math.random() * 1001)), + $randomInt: () => String(host.randomInt(1001)), + $randomBoolean: () => String(host.randomInt(2) === 1), + $randomAlphaNumeric: () => randomText(1, ALPHANUMERIC), + $randomHexadecimal: () => randomText(1, '0123456789abcdef'), + $randomFirstName: () => pick(samples.firstNames), + $randomLastName: () => pick(samples.lastNames), + $randomFullName: () => pick(samples.firstNames) + ' ' + pick(samples.lastNames), + $randomUserName: () => pick(samples.firstNames).toLowerCase() + '.' + pick(samples.lastNames).toLowerCase() + host.randomInt(100), + $randomEmail: () => pick(samples.firstNames).toLowerCase() + '.' + pick(samples.lastNames).toLowerCase() + '@example.com', + $randomWord: () => pick(samples.words), + $randomPassword: () => randomText(15, ALPHANUMERIC), }; function replaceIn(template, lookup) { @@ -477,6 +527,18 @@ class PropertyList { [Symbol.iterator]() { return this.members[Symbol.iterator](); } } + // Postman keeps a URL's host and path as lists, but a script may set either as text (pm.request.url.host = + // 'api.example.com', as Postman allows), and null for any part of it means none. + function isNone(value) { return value === null || value === undefined; } + + function hostText(host) { return Array.isArray(host) ? host.join('.') : isNone(host) ? '' : String(host); } + + function pathSegments(path) { + if (Array.isArray(path)) return path; + const text = isNone(path) ? '' : String(path); + return text.length === 0 ? [] : text.replace(/^\//, '').split('/'); + } + class Url { constructor(raw) { this.update(raw); } @@ -522,11 +584,11 @@ class Url { return this; } - getHost() { return this.host.join('.'); } + getHost() { return hostText(this.host); } - getRemote() { return this.getHost() + (this.port !== undefined ? ':' + this.port : ''); } + getRemote() { return this.getHost() + (isNone(this.port) ? '' : ':' + this.port); } - getPath() { return '/' + this.path.join('/'); } + getPath() { return '/' + pathSegments(this.path).join('/'); } getQueryString() { return this.query.toString(); } @@ -544,12 +606,13 @@ class Url { } toString() { - let result = this.protocol !== undefined ? this.protocol + '://' : ''; + let result = isNone(this.protocol) ? '' : this.protocol + '://'; result += this.getHost(); - if (this.port !== undefined) result += ':' + this.port; - if (this.path.length > 0) result += '/' + this.path.join('/'); + if (!isNone(this.port)) result += ':' + this.port; + const path = pathSegments(this.path); + if (path.length > 0) result += '/' + path.join('/'); if (this.query.count() > 0) result += '?' + this.query.toString(); - if (this.hash !== undefined) result += '#' + this.hash; + if (!isNone(this.hash)) result += '#' + this.hash; return result; } @@ -819,10 +882,13 @@ function readPath(object, path) { return { exists: true, value }; } - function lengthOf(object) { + // A length as chai finds it: a map's or set's size, else the length property, which the value must have. + function lengthOf(assertion) { + const object = assertion._object; const kind = typeOf(object); if (kind === 'map' || kind === 'set') return object.size; - if (object === null || object === undefined) throw new AssertionError('expected ' + inspect(object) + ' to have a length'); + if (object === null || object === undefined) assertion._fail('Target cannot be null or undefined.'); + if (!('length' in Object(object))) assertion._fail('expected ' + inspect(object) + " to have property 'length'"); return object.length; } @@ -853,8 +919,49 @@ class Assertion { } } + // Reading a property that no assertion has throws, as in chai: a misspelled .to.be.ture would otherwise check + // nothing. Like chai, it leaves out then, catch, inspect and toJSON, which await and serializers look for. Only + // the proxies scripts get are checked: chained methods inherit from the objects behind them, which util.inspect + // (console.log) reads past the proxy. + const targets = new WeakMap(); + const unchecked = new Set(['then', 'catch', 'inspect', 'toJSON']); + const checker = { + get(target, key, receiver) { + if (typeof key === 'string' && !unchecked.has(key) && !Reflect.has(target, key)) throw new Error('Invalid Chai property: ' + key + suggestion(key)); + return Reflect.get(target, key, receiver); + }, + }; + + function guard(target) { + const proxy = new Proxy(target, checker); + targets.set(proxy, target); + return proxy; + } + + // chai's hint for a misspelled property: the closest assertion fewer than 4 edits away, the first on a tie. + function suggestion(name) { + let best = null; + let distance = 4; + for (const candidate of Object.getOwnPropertyNames(Assertion.prototype)) { + if (candidate === 'constructor' || candidate.startsWith('_') || Math.abs(candidate.length - name.length) >= distance) continue; + let row = [...Array(candidate.length + 1).keys()]; + for (let i = 1; i <= name.length; i++) { + const next = [i]; + for (let j = 1; j <= candidate.length; j++) next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (name[i - 1] === candidate[j - 1] ? 0 : 1)); + row = next; + } + + if (row[candidate.length] < distance) { + best = candidate; + distance = row[candidate.length]; + } + } + + return best === null ? '' : '. Did you mean "' + best + '"?'; + } + function expect(value, text) { - return new Assertion(value, text); + return guard(new Assertion(value, text)); } expect.fail = text => { throw new AssertionError(text === undefined ? 'expect.fail()' : String(text)); }; @@ -872,12 +979,13 @@ function chainable(assertion, fn, chain) { const callable = function (...args) { return fn.apply(assertion, args); }; delete callable.length; delete callable.name; - Object.setPrototypeOf(callable, assertion); - return callable; + Object.setPrototypeOf(callable, targets.get(assertion) || assertion); + return guard(callable); } - getter(['to', 'be', 'been', 'is', 'that', 'which', 'and', 'has', 'have', 'with', 'at', 'of', 'same', 'but', 'does', 'still', 'also'], function () { return this; }); - getter('not', function () { this._flags.negate = !this._flags.negate; return this; }); + // In chai's order, so that a misspelled property gets the hint chai gives (the first of equally close ones). + getter(['to', 'be', 'been', 'is', 'and', 'has', 'have', 'with', 'that', 'which', 'at', 'of', 'same', 'but', 'does', 'still', 'also'], function () { return this; }); + getter('not', function () { this._flags.negate = true; return this; }); for (const name of ['deep', 'nested', 'own', 'ordered', 'any', 'all']) getter(name, function () { this._flags[name] = true; return this; }); const article = type => (/^[aeiou]/i.test(type) ? 'an ' : 'a ') + type; @@ -911,22 +1019,15 @@ function includeAssertion(value, text) { function lengthAssertion(expected, text) { this._msg(text); - this._flags.length = false; - const length = lengthOf(this._object); - return this._assert(length === expected, 'expected #{this} to have a length of #{exp} but got #{act}', 'expected #{this} to not have a length of #{exp}', expected, length); + const length = lengthOf(this); + // chai compares with ==, so lengthOf('2') passes for two items. + return this._assert(length == expected, 'expected #{this} to have a length of #{exp} but got #{act}', 'expected #{this} to not have a length of #{act}', expected, length); } getter(['a', 'an'], function () { return chainable(this, typeAssertion); }); getter(['include', 'includes', 'contain', 'contains'], function () { return chainable(this, includeAssertion, function () { this._flags.contains = true; }); }); - getter('length', function () { return chainable(this, lengthAssertion, function () { this._flags.length = true; }); }); - method('lengthOf', lengthAssertion); - - // .length.above(2) and the like compare the length. - function useLength(assertion) { - if (assertion._flags.length !== true) return false; - assertion._flags.length = false; - return true; - } + // As in chai, the comparisons after .length or .lengthOf compare the length: .lengthOf.at.least(1).and.at.most(10). + getter(['length', 'lengthOf'], function () { return chainable(this, lengthAssertion, function () { this._flags.length = true; }); }); function eqlAssertion(value, text) { this._msg(text); @@ -936,41 +1037,52 @@ function eqlAssertion(value, text) { method(['equal', 'equals', 'eq'], function (value, text) { this._msg(text); if (this._flags.deep === true) return eqlAssertion.call(this, value); - if (useLength(this)) { - const length = lengthOf(this._object); - return this._assert(length === value, 'expected #{this} to have a length of #{exp} but got #{act}', 'expected #{this} to not have a length of #{exp}', value, length); - } - return this._assert(this._object === value, 'expected #{this} to equal #{exp}', 'expected #{this} to not equal #{exp}', value); }); method(['eql', 'eqls'], eqlAssertion); - function comparison(test, positive, negative) { + // Only numbers and dates are compared: JavaScript would compare null, '' or '42' as numbers. + function numberOrDate(assertion) { + const kind = typeOf(assertion._object); + if (kind !== 'number' && kind !== 'date' && kind !== 'bigint') assertion._fail('expected ' + inspect(assertion._object) + ' to be a number or a date'); + } + + function comparison(name, test, positive, negative) { return function (bound, text) { this._msg(text); - if (useLength(this)) { - const length = lengthOf(this._object); + const kind = typeOf(bound); + if (this._flags.length === true) { + const length = lengthOf(this); + if (kind !== 'number') return this._fail('the argument to ' + name + ' must be a number'); return this._assert(test(length, bound), 'expected #{this} to have a length ' + positive + ' #{exp} but got #{act}', 'expected #{this} to have a length ' + negative + ' #{exp}', bound, length); } - const kind = typeOf(this._object); - if (kind !== 'number' && kind !== 'date' && kind !== 'bigint') return this._fail('expected ' + inspect(this._object) + ' to be a number or a date'); + if (typeOf(this._object) === 'date' && kind !== 'date') return this._fail('the argument to ' + name + ' must be a date'); + if (typeOf(this._object) === 'number' && kind !== 'number') return this._fail('the argument to ' + name + ' must be a number'); + numberOrDate(this); return this._assert(test(this._object, bound), 'expected #{this} to be ' + positive + ' #{exp}', 'expected #{this} to be ' + negative + ' #{exp}', bound); }; } - method(['above', 'gt', 'greaterThan'], comparison((a, b) => a > b, 'above', 'at most')); - method(['least', 'gte', 'greaterThanOrEqual'], comparison((a, b) => a >= b, 'at least', 'below')); - method(['below', 'lt', 'lessThan'], comparison((a, b) => a < b, 'below', 'at least')); - method(['most', 'lte', 'lessThanOrEqual'], comparison((a, b) => a <= b, 'at most', 'above')); + method(['above', 'gt', 'greaterThan'], comparison('above', (a, b) => a > b, 'above', 'at most')); + method(['least', 'gte', 'greaterThanOrEqual'], comparison('least', (a, b) => a >= b, 'at least', 'below')); + method(['below', 'lt', 'lessThan'], comparison('below', (a, b) => a < b, 'below', 'at least')); + method(['most', 'lte', 'lessThanOrEqual'], comparison('most', (a, b) => a <= b, 'at most', 'above')); method('within', function (start, finish, text) { this._msg(text); - const range = start + '..' + finish; - if (useLength(this)) { - const length = lengthOf(this._object); + const dates = typeOf(start) === 'date' && typeOf(finish) === 'date'; + const numbers = typeOf(start) === 'number' && typeOf(finish) === 'number'; + const range = dates ? start.toISOString() + '..' + finish.toISOString() : start + '..' + finish; + if (this._flags.length === true) { + const length = lengthOf(this); + if (!numbers) return this._fail('the arguments to within must be numbers'); return this._assert(length >= start && length <= finish, 'expected #{this} to have a length within ' + range, 'expected #{this} to not have a length within ' + range); } + const kind = typeOf(this._object); + if (kind === 'date' && !dates) return this._fail('the arguments to within must be dates'); + if (kind === 'number' && !numbers) return this._fail('the arguments to within must be numbers'); + numberOrDate(this); return this._assert(this._object >= start && this._object <= finish, 'expected #{this} to be within ' + range, 'expected #{this} to not be within ' + range); }); method(['instanceof', 'instanceOf'], function (constructor, text) { @@ -981,11 +1093,12 @@ function comparison(test, positive, negative) { function propertyAssertion(name, ...rest) { const object = this._object; + if (object === null || object === undefined) return this._fail('Target cannot be null or undefined.'); const flags = this._flags; let exists = false; let value; if (flags.nested === true) ({ exists, value } = readPath(object, name)); - else if (object !== null && object !== undefined) { + else { exists = flags.own === true ? hasOwn(object, name) : name in Object(object); value = exists ? object[name] : undefined; } @@ -1050,7 +1163,7 @@ function propertyAssertion(name, ...rest) { if (pattern !== undefined) { what += ' matching ' + inspect(pattern); - const thrownText = isError(error) ? String(error.message) : String(error); + const thrownText = isError(error) ? messageOf(error) : safeString(error); if (ok) ok = typeOf(pattern) === 'regexp' ? pattern.test(thrownText) : thrownText.includes(String(pattern)); } @@ -1085,6 +1198,11 @@ function propertyAssertion(name, ...rest) { }); method(['closeTo', 'approximately'], function (expected, delta, text) { this._msg(text); + if (typeOf(this._object) !== 'number') return this._fail('expected ' + inspect(this._object) + ' to be a number'); + if (typeof expected !== 'number' || typeof delta !== 'number') { + return this._fail('the arguments to closeTo or approximately must be numbers' + (delta === undefined ? ', and a delta is required' : '')); + } + return this._assert(Math.abs(this._object - expected) <= delta, 'expected #{this} to be close to ' + expected + ' +/- ' + delta, 'expected #{this} not to be close to ' + expected + ' +/- ' + delta); }); method(['satisfy', 'satisfies'], function (matcher, text) { @@ -1098,7 +1216,7 @@ function propertyAssertion(name, ...rest) { getter('undefined', function () { return this._assert(this._object === undefined, 'expected #{this} to be undefined', 'expected #{this} not to be undefined'); }); getter('NaN', function () { return this._assert(Number.isNaN(this._object), 'expected #{this} to be NaN', 'expected #{this} not to be NaN'); }); getter('finite', function () { return this._assert(Number.isFinite(this._object), 'expected #{this} to be a finite number', 'expected #{this} to not be a finite number'); }); - getter('exist', function () { return this._assert(this._object !== null && this._object !== undefined, 'expected #{this} to exist', 'expected #{this} to not exist'); }); + getter(['exist', 'exists'], function () { return this._assert(this._object !== null && this._object !== undefined, 'expected #{this} to exist', 'expected #{this} to not exist'); }); getter('empty', function () { const object = this._object; const kind = typeOf(object); @@ -1109,10 +1227,21 @@ function propertyAssertion(name, ...rest) { else return this._fail('.empty was passed non-string primitive ' + inspect(object)); return this._assert(empty, 'expected #{this} to be empty', 'expected #{this} not to be empty'); }); + getter(['arguments', 'Arguments'], function () { + const object = this._object; + const type = object !== null && typeof object === 'object' ? Object.prototype.toString.call(object).slice(8, -1) : typeOf(object); + return this._assert(type === 'Arguments', 'expected #{this} to be arguments but got ' + type, 'expected #{this} to not be arguments'); + }); + for (const [name, test] of [['extensible', Object.isExtensible], ['sealed', Object.isSealed], ['frozen', Object.isFrozen]]) { + getter(name, function () { return this._assert(test(this._object), 'expected #{this} to be ' + name, 'expected #{this} to not be ' + name); }); + } // Postman's assertions on responses: pm.response.to.have.status(200), .to.be.ok, .to.have.header('Content-Type') … const isResponse = value => value !== null && typeof value === 'object' && value[BRAND] === 'response'; const isRequest = value => value !== null && typeof value === 'object' && value[BRAND] === 'request'; + for (const [name, test, what] of [['postmanRequest', isRequest, 'request'], ['postmanResponse', isResponse, 'response'], ['postmanRequestOrResponse', value => isRequest(value) || isResponse(value), 'request or response']]) { + getter(name, function () { return this._assert(test(this._object), 'expecting a postman ' + what + ' object but got #{this}', 'not expecting a postman ' + what + ' object'); }); + } function responseOf(assertion) { if (!isResponse(assertion._object)) assertion._fail('expected ' + inspect(assertion._object) + ' to be a response'); @@ -1144,7 +1273,7 @@ function statusClass(digit) { const actual = responseOf(this).code; return this._assert(actual >= 400 && actual < 600, 'expected response code to be 4XX or 5XX but found #{act}', 'expected response code to not be 4XX or 5XX but found #{act}', undefined, actual); }); - for (const [names, code] of [['accepted', 202], ['badRequest', 400], [['unauthorized', 'unauthorised'], 401], ['forbidden', 403], ['notFound', 404], ['notAcceptable', 406], ['rateLimited', 429]]) { + for (const [names, code] of [['accepted', 202], ['withoutContent', 204], ['badRequest', 400], [['unauthorized', 'unauthorised'], 401], ['forbidden', 403], ['notFound', 404], ['notAcceptable', 406], ['rateLimited', 429]]) { getter(names, function () { return statusCode(this, code); }); } @@ -1202,13 +1331,34 @@ function statusClass(digit) { if (args.length === 1) return this._assert(exists, 'expected response body json to have path ' + inspect(args[0]), 'expected response body json to not have path ' + inspect(args[0])); return this._assert(exists && deepEqual(value, args[1]), 'expected response body json at ' + inspect(args[0]) + ' to contain #{exp} but got #{act}', 'expected response body json at ' + inspect(args[0]) + ' to not contain #{exp}', args[1], value); }); + // As in Postman: a response's (or request's) JSON body, else the value itself (pm.expect(data).to.have.jsonSchema(schema)). + // Postman's ajv 6 checks formats (email, date-time …) itself, and fails on one it doesn't know. ajv 7 and later check + // them only with the ajv-formats plugin (for those versions only), taken from the workspace when it is there: a + // format ajv doesn't know then fails the test rather than going unchecked. method('jsonSchema', function (schema, options) { - const response = responseOf(this); + if (typeOf(schema) !== 'object') return this._fail('expected ' + inspect(schema) + ' to be an object'); + const object = this._object; + const data = isResponse(object) || (isRequest(object) && typeof object.json === 'function') ? object.json() : object; const ajvModule = host.require('ajv'); const Ajv = ajvModule.default || ajvModule; - const ajv = new Ajv(Object.assign({ allErrors: true, strict: false }, options)); - const valid = ajv.validate(schema, JSON.parse(response.text())); - return this._assert(valid, 'expected response body to match the JSON schema, but ' + ajv.errorsText(), 'expected response body to not match the JSON schema'); + const unknownFormats = []; + const logger = { log() {}, warn(...args) { const message = args.join(' '); if (message.includes('unknown format')) unknownFormats.push(message); }, error() {} }; + const ajv = new Ajv(Object.assign({ allErrors: true, strict: false, logger }, options)); + const pluggable = Boolean(ajv.opts && ajv.opts.code); // ajv 7 and later (ajv 6 has _opts) + let addFormats = null; + if (pluggable) { + try { + addFormats = host.require('ajv-formats'); + } catch (error) { + if (!error || error.code !== 'MODULE_NOT_FOUND' || !String(error.message).includes('ajv-formats')) throw error; + } + + if (addFormats !== null) (addFormats.default || addFormats)(ajv); + } + + const valid = ajv.validate(schema, data); + if (pluggable && unknownFormats.length > 0) return this._fail(unknownFormats[0] + (addFormats === null ? ': install ajv-formats in the workspace (npm install ajv-formats), as Postman checks formats' : '')); + return this._assert(valid && !ajv.errors, 'expected data to satisfy schema but found following errors: \n' + ajv.errorsText(), 'expected data to not satisfy schema'); }); // ----- pm.test ------------------------------------------------------------------------------------ @@ -1359,10 +1509,12 @@ function xml2Json(xml) { return result; } + const scriptConsole = makeConsole(); + host.onConsole(scriptConsole); Object.assign(globalThis, timerFunctions, { pm, postman, - console: makeConsole(), + console: scriptConsole, require: host.require, fetch: (...args) => track(host.fetch(...args)), Buffer: host.Buffer, @@ -1452,14 +1604,22 @@ async function runAll() { if (phase === 'prerequest') { const request = pm.request; - result.request = { - method: String(request.method), - url: String(request.url), - headers: request.headers.members - .filter(member => !member.disabled && String(member.key).length > 0) - .map(member => [String(member.key), member.value === null || member.value === undefined ? '' : String(member.value)]), - body: request.body.raw === undefined || request.body.raw === null ? null : String(request.body.raw), - }; + try { + result.request = { + method: String(request.method), + url: String(request.url), + headers: request.headers.members + .filter(member => !member.disabled && String(member.key).length > 0) + .map(member => [String(member.key), member.value === null || member.value === undefined ? '' : String(member.value)]), + body: request.body.raw === undefined || request.body.raw === null ? null : String(request.body.raw), + }; + } catch (error) { + // What the scripts left in pm.request can't be read (a query that is no longer a list …): as in Python, the + // request isn't sent, and what the scripts printed, tested and set is kept. + if (result.error === null) { + result.error = { script: '', message: 'The pre-request scripts left a request that cannot be sent: ' + fullDescribe(error), traceback: '' }; + } + } } return stringify(result); diff --git a/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs b/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs index c646b0e..43613d0 100644 --- a/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs +++ b/src/TermRest.Core/Scripting/PowerShellWorkerCode.cs @@ -14,9 +14,14 @@ internal static class PowerShellWorkerCode /// Starts each answer: lines without it come from programs that scripts started. public const string ReplyMarker = "\u001eTR "; - /// The command (pwsh -Command): reads the worker from the first line of input and runs it. + /// + /// The command (pwsh -Command): reads the worker from the first line of input and runs it. On Linux and macOS, input is + /// read through a descriptor of its own (/dev/stdin): from .NET 11 (PowerShell 7.7), [Console]::OpenStandardInput() + /// reads descriptor 0 itself, which the worker then gives to programs that scripts start (/dev/null). + /// public const string Bootstrap = - "$i=[IO.StreamReader]::new([Console]::OpenStandardInput(),[Text.UTF8Encoding]::new($false));" + + "$i=[IO.StreamReader]::new($(if($IsWindows){[Console]::OpenStandardInput()}else{try{[IO.File]::Open('/dev/stdin','Open','Read','ReadWrite')}" + + "catch{[Console]::OpenStandardInput()}}),[Text.UTF8Encoding]::new($false));" + "& ([ScriptBlock]::Create([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($i.ReadLine())))) $i"; /// The first line of input: the worker's code, base64-encoded (UTF-8). @@ -25,20 +30,143 @@ internal static class PowerShellWorkerCode private const string Source = """ param([System.IO.TextReader] $Reader) - # Requests come through $Reader (stdin); answers go to a copy of stdout, each after a marker. What scripts write to the - # console ([Console]::WriteLine) is captured, so it cannot mix into the answers. + # Requests come through $Reader (stdin); answers go to a copy of stdout, each after a marker (on Linux and macOS, a + # descriptor of its own, as for $Reader: from .NET 11, [Console]::OpenStandardOutput() writes to descriptor 1 itself, + # which goes to stderr below). What scripts write to the console ([Console]::WriteLine) is captured, so it cannot mix + # into the answers. $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' - $TrOut = [System.IO.StreamWriter]::new([Console]::OpenStandardOutput(), [System.Text.UTF8Encoding]::new($false)) + + # Tables and Out-Host without ANSI colors (PowerShell 7.2 and later add them): the text goes to the Scripts tab, to + # recordings and to logs. + if ($null -ne $PSStyle) { $PSStyle.OutputRendering = 'PlainText' } + $TrOut = [System.IO.StreamWriter]::new($(if ($IsWindows) { [Console]::OpenStandardOutput() } + else { try { [System.IO.File]::Open('/dev/stdout', 'Open', 'Write', 'ReadWrite') } catch { [Console]::OpenStandardOutput() } }), + [System.Text.UTF8Encoding]::new($false)) $TrMarker = [string][char]0x1E + 'TR ' - $TrConsole = [System.IO.StringWriter]::new() + + # 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 + # at a time, as in C#; the lines after them are counted. + $TrConsole = & { + $type = [System.Reflection.Emit.AssemblyBuilder]::DefineDynamicAssembly([System.Reflection.AssemblyName]::new('TermRestConsole'), 'Run').DefineDynamicModule('TermRestConsole').DefineType('TermRestConsole', 'Public, Sealed', [System.IO.TextWriter]) + $text = $type.DefineField('Text', [System.Text.StringBuilder], 'Public') + $limit = $type.DefineField('Limit', [int], 'Public') + $dropped = $type.DefineField('Dropped', [int], 'Public') + [void] $type.DefineDefaultConstructor('Public') + $codes = [System.Reflection.Emit.OpCodes] + $enter = [System.Threading.Monitor].GetMethod('Enter', [type[]] @([object])) + $exit = [System.Threading.Monitor].GetMethod('Exit', [type[]] @([object])) + $length = [System.Text.StringBuilder].GetProperty('Length').GetGetMethod() + $append = [System.Text.StringBuilder].GetMethod('Append', [type[]] @([char])) + $il = $type.DefineMethod('get_Encoding', 'Public, Virtual, HideBySig, SpecialName', [System.Text.Encoding], [type[]] @()).GetILGenerator() + $il.Emit($codes::Call, [System.Text.Encoding].GetProperty('UTF8').GetGetMethod()) + $il.Emit($codes::Ret) + + # Write(char), which TextWriter's other writes come to: lock (this) { if (Text.Length < Limit) Text.Append(c); else if + # (c == '\n') { if (Text[Text.Length - 1] != '\n') Text.Append('\n'); else Dropped++; } }: past the limit, line ends + # are counted, and the first one ends the line kept last. + $il = $type.DefineMethod('Write', 'Public, Virtual, HideBySig', [void], [type[]] @([char])).GetILGenerator() + $full = $il.DefineLabel() + $count = $il.DefineLabel() + $done = $il.DefineLabel() + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Call, $enter) + [void] $il.BeginExceptionBlock() + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Ldfld, $text) + $il.Emit($codes::Callvirt, $length) + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Ldfld, $limit) + $il.Emit($codes::Bge, $full) + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Ldfld, $text) + $il.Emit($codes::Ldarg_1) + $il.Emit($codes::Callvirt, $append) + $il.Emit($codes::Pop) + $il.Emit($codes::Br, $done) + $il.MarkLabel($full) + $il.Emit($codes::Ldarg_1) + $il.Emit($codes::Ldc_I4, [int] 10) + $il.Emit($codes::Bne_Un, $done) + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Ldfld, $text) + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Ldfld, $text) + $il.Emit($codes::Callvirt, $length) + $il.Emit($codes::Ldc_I4_1) + $il.Emit($codes::Sub) + $il.Emit($codes::Callvirt, [System.Text.StringBuilder].GetProperty('Chars').GetGetMethod()) + $il.Emit($codes::Ldc_I4, [int] 10) + $il.Emit($codes::Beq, $count) + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Ldfld, $text) + $il.Emit($codes::Ldc_I4, [int] 10) + $il.Emit($codes::Callvirt, $append) + $il.Emit($codes::Pop) + $il.Emit($codes::Br, $done) + $il.MarkLabel($count) + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Ldfld, $dropped) + $il.Emit($codes::Ldc_I4_1) + $il.Emit($codes::Add) + $il.Emit($codes::Stfld, $dropped) + $il.MarkLabel($done) + $il.BeginFinallyBlock() + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Call, $exit) + $il.EndExceptionBlock() + $il.Emit($codes::Ret) + + # Take(): lock (this) { var taken = Text.ToString(); Text = new StringBuilder(); return taken; } (a new builder: Clear() + # would keep the capacity the largest output gave it), and TakeDropped() for Dropped. + foreach ($taken in 'Take', 'TakeDropped') { + $il = $type.DefineMethod($taken, 'Public, HideBySig', $(if ($taken -eq 'Take') { [string] } else { [int] }), [type[]] @()).GetILGenerator() + [void] $il.DeclareLocal($(if ($taken -eq 'Take') { [string] } else { [int] })) + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Call, $enter) + [void] $il.BeginExceptionBlock() + $il.Emit($codes::Ldarg_0) + if ($taken -eq 'Take') { + $il.Emit($codes::Ldfld, $text) + $il.Emit($codes::Callvirt, [object].GetMethod('ToString')) + $il.Emit($codes::Stloc_0) + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Newobj, [System.Text.StringBuilder].GetConstructor([type[]] @())) + $il.Emit($codes::Stfld, $text) + } + else { + $il.Emit($codes::Ldfld, $dropped) + $il.Emit($codes::Stloc_0) + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Ldc_I4_0) + $il.Emit($codes::Stfld, $dropped) + } + + $il.BeginFinallyBlock() + $il.Emit($codes::Ldarg_0) + $il.Emit($codes::Call, $exit) + $il.EndExceptionBlock() + $il.Emit($codes::Ldloc_0) + $il.Emit($codes::Ret) + } + + $writer = [Activator]::CreateInstance($type.CreateType()) + $writer.Text = [System.Text.StringBuilder]::new() + $writer.Limit = 4000000 + $writer + } + $TrStderr = [Console]::Error [Console]::SetOut($TrConsole) [Console]::SetError($TrConsole) # Requests keep coming through $Reader and answers through $TrOut, which hold the original stdin and stdout. Programs that - # scripts start then read nothing and write to stderr: they can neither take a request nor mix into an answer. PowerShell - # has no command for it, so the two functions of the OS are declared here (no compiler needed); without them, the - # protocol still works. + # scripts start then read nothing and write to stderr: they can neither take a request nor mix into an answer. On Linux and + # macOS, PowerShell also takes a session of its own, without TermRest's terminal: those programs (ssh, sudo, gpg) cannot + # open /dev/tty to ask over TermRest's screen, and fail at once, as they do without a terminal. PowerShell has no command + # for these, so the functions of the OS are declared here (no compiler needed); without them, the protocol still works. $TrNothing = $null try { $module = [System.Reflection.Emit.AssemblyBuilder]::DefineDynamicAssembly([System.Reflection.AssemblyName]::new('TermRestStreams'), 'Run').DefineDynamicModule('TermRestStreams') @@ -56,10 +184,12 @@ internal static class PowerShellWorkerCode try { $type = $module.DefineType('TermRestStreams.' + $library.Replace('.', '_'), 'Public, Abstract, Sealed') $type.DefinePInvokeMethod('dup2', $library, 'Public, Static, PinvokeImpl', 'Standard', [int], [type[]] @([int], [int]), 'Cdecl', 'Ansi').SetImplementationFlags('PreserveSig') + $type.DefinePInvokeMethod('setsid', $library, 'Public, Static, PinvokeImpl', 'Standard', [int], [type[]] @(), 'Cdecl', 'Ansi').SetImplementationFlags('PreserveSig') $native = $type.CreateType() $TrNothing = [System.IO.FileStream]::new('/dev/null', 'Open', 'Read') [void] $native::dup2($TrNothing.SafeFileHandle.DangerousGetHandle().ToInt32(), 0) [void] $native::dup2(2, 1) + [void] $native::setsid() break } catch { @@ -72,6 +202,24 @@ internal static class PowerShellWorkerCode # a nicety: the protocol works without it } + # PowerShell's exit, and break or continue outside a loop, act beyond the script block that runs them: exit would stop + # PowerShell itself, break the loop that runs the scripts. A script runs through this method, which stops them, as a + # script file does: it returns the one that ended the script (exit, with its code), or null. + $TrFlow = & { + $type = [System.Reflection.Emit.AssemblyBuilder]::DefineDynamicAssembly([System.Reflection.AssemblyName]::new('TermRestFlow'), 'Run').DefineDynamicModule('TermRestFlow').DefineType('TermRestFlow', 'Public, Abstract, Sealed') + $il = $type.DefineMethod('Run', 'Public, Static', [Exception], [type[]] @([Action])).GetILGenerator() + [void] $il.DeclareLocal([Exception]) + [void] $il.BeginExceptionBlock() + $il.Emit([System.Reflection.Emit.OpCodes]::Ldarg_0) + $il.Emit([System.Reflection.Emit.OpCodes]::Callvirt, [Action].GetMethod('Invoke')) + $il.BeginCatchBlock([System.Management.Automation.FlowControlException]) + $il.Emit([System.Reflection.Emit.OpCodes]::Stloc_0) + $il.EndExceptionBlock() + $il.Emit([System.Reflection.Emit.OpCodes]::Ldloc_0) + $il.Emit([System.Reflection.Emit.OpCodes]::Ret) + $type.CreateType() + } + $TrMaxLines = 1000 $TrCompiled = [System.Collections.Generic.Dictionary[string, object]]::new([StringComparer]::Ordinal) $TrNames = [System.Collections.Generic.Dictionary[string, string]]::new([StringComparer]::Ordinal) @@ -85,15 +233,81 @@ class TrAssertionException : System.Exception { } } + # What a script writes, as it comes: as many objects as there are lines left to show; the others are only counted, so + # that a script writing without end does not fill the memory. + class TrOutput { + [System.Collections.Generic.List[object]] $Items = [System.Collections.Generic.List[object]]::new() + [int] $Room + [int] $Dropped + + TrOutput([int] $room) { + $this.Room = $room + } + + [void] Add([object] $item) { + if ($this.Items.Count -lt $this.Room) { $this.Items.Add($item) } else { $this.Dropped++ } + } + } + + # Postman's dynamic variables, as requests resolve them; the names and words they pick from come with the message. + class TrDynamic { + # The value of one, or $null for another name ([object]: a [string] method returns '' for $null). + static [object] Value([string] $name, [object] $samples) { + $alphanumeric = 'abcdefghijklmnopqrstuvwxyz0123456789' + switch -CaseSensitive ($name) { + '$guid' { return [guid]::NewGuid().ToString() } + '$randomUUID' { return [guid]::NewGuid().ToString() } + '$timestamp' { return [DateTimeOffset]::UtcNow.ToUnixTimeSeconds().ToString([cultureinfo]::InvariantCulture) } + '$isoTimestamp' { return [DateTime]::UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", [cultureinfo]::InvariantCulture) } + '$randomInt' { return [TrDynamic]::Next(1001).ToString([cultureinfo]::InvariantCulture) } + '$randomBoolean' { if ([TrDynamic]::Next(2) -eq 1) { return 'true' } else { return 'false' } } + '$randomAlphaNumeric' { return [TrDynamic]::Text(1, $alphanumeric) } + '$randomHexadecimal' { return [TrDynamic]::Text(1, '0123456789abcdef') } + '$randomFirstName' { return [TrDynamic]::Pick($samples, 'firstNames') } + '$randomLastName' { return [TrDynamic]::Pick($samples, 'lastNames') } + '$randomFullName' { return [TrDynamic]::Pick($samples, 'firstNames') + ' ' + [TrDynamic]::Pick($samples, 'lastNames') } + '$randomUserName' { return [TrDynamic]::Pick($samples, 'firstNames').ToLowerInvariant() + '.' + [TrDynamic]::Pick($samples, 'lastNames').ToLowerInvariant() + [TrDynamic]::Next(100).ToString([cultureinfo]::InvariantCulture) } + '$randomEmail' { return [TrDynamic]::Pick($samples, 'firstNames').ToLowerInvariant() + '.' + [TrDynamic]::Pick($samples, 'lastNames').ToLowerInvariant() + '@example.com' } + '$randomWord' { return [TrDynamic]::Pick($samples, 'words') } + '$randomPassword' { return [TrDynamic]::Text(15, $alphanumeric) } + } + + return $null + } + + hidden static [int] Next([int] $limit) { return [System.Security.Cryptography.RandomNumberGenerator]::GetInt32($limit) } + + hidden static [string] Text([int] $length, [string] $alphabet) { + $letters = [char[]]::new($length) + for ($i = 0; $i -lt $length; $i++) { $letters[$i] = $alphabet[[TrDynamic]::Next($alphabet.Length)] } + return [string]::new($letters) + } + + hidden static [string] Pick([object] $samples, [string] $key) { + if ($null -eq $samples -or -not $samples.ContainsKey($key) -or $null -eq $samples[$key] -or $samples[$key].Count -eq 0) { return '' } + $values = $samples[$key] + return [string] $values[[TrDynamic]::Next($values.Count)] + } + } + class TrText { - # Variables and headers are text: strings stay as they are, anything else becomes JSON. + # Variables and headers are text: strings stay as they are, numbers, dates, GUIDs and the like become their text + # (as in C# scripts), anything else becomes JSON. static [string] Of([object] $value) { if ($null -eq $value) { return '' } if ($value -is [string]) { return $value } if ($value -is [bool]) { if ($value) { return 'true' } else { return 'false' } } - if ($value -is [datetime]) { return $value.ToString('o', [cultureinfo]::InvariantCulture) } - if ([TrText]::IsNumber($value)) { return ([System.IFormattable] $value).ToString($null, [cultureinfo]::InvariantCulture) } - return ConvertTo-Json -InputObject $value -Depth 20 -Compress + if ($value -is [datetime] -or $value -is [DateTimeOffset]) { return $value.ToString('o', [cultureinfo]::InvariantCulture) } + # DateOnly and TimeOnly too (by name: PowerShell 7.0 and 7.1 run on .NET versions without them). + if ($value.GetType().FullName -in @('System.DateOnly', 'System.TimeOnly')) { return $value.ToString('o', [cultureinfo]::InvariantCulture) } + # A URI as written: its ToString() unescapes it (a %20 becomes a space). + if ($value -is [uri]) { return ([uri] $value).OriginalString } + if ($value -is [System.IFormattable]) { return ([System.IFormattable] $value).ToString($null, [cultureinfo]::InvariantCulture) } + $json = ConvertTo-Json -InputObject $value -Depth 20 -Compress + + # One whose JSON is a string is that string, without the quotes. + if ($json.StartsWith('"')) { return [System.Text.Json.JsonSerializer]::Deserialize($json, [string], [System.Text.Json.JsonSerializerOptions] $null) } + return $json } static [string] Show([object] $value) { @@ -226,9 +440,11 @@ [hashtable] ToHashtable() { # $tr.Variables: this request's variables, then the environment's, the collection's and the globals; Set is for this request. class TrVariables : TrScope { hidden [object[]] $Scopes + hidden [object] $Samples - TrVariables([System.Collections.Generic.Dictionary[string, string]] $local, [System.Collections.Generic.Dictionary[string, object]] $changes, [object[]] $scopes) : base($local, $changes) { + TrVariables([System.Collections.Generic.Dictionary[string, string]] $local, [System.Collections.Generic.Dictionary[string, object]] $changes, [object[]] $scopes, [object] $samples) : base($local, $changes) { $this.Scopes = $scopes + $this.Samples = $samples } [object] Get([string] $name, [object] $default) { @@ -257,7 +473,7 @@ [hashtable] ToHashtable() { return $table } - # Replaces {{name}} with the variables' values; unknown names stay as they are. + # Replaces {{name}} with the variables' values, and Postman's dynamic variables ({{$guid}}…); unknown names stay as they are. [string] ReplaceIn([string] $text) { for ($round = 0; $round -lt 10; $round++) { $found = [regex]::Matches($text, '\{\{([^{}]+)\}\}') @@ -266,7 +482,9 @@ [string] ReplaceIn([string] $text) { $changed = $false foreach ($match in $found) { [void] $builder.Append($text, $last, $match.Index - $last) - $value = $this.Get($match.Groups[1].Value.Trim(), $null) + $name = $match.Groups[1].Value.Trim() + $value = $this.Get($name, $null) + if ($null -eq $value) { $value = [TrDynamic]::Value($name, $this.Samples) } if ($null -eq $value) { [void] $builder.Append($match.Value) } @@ -579,18 +797,35 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { } . $flush - $console = $TrConsole.ToString() - [void] $TrConsole.GetStringBuilder().Clear() - if ($console) { - foreach ($line in $console.TrimEnd("`r", "`n").Split("`n")) { $lines.Add($line.TrimEnd("`r")) } - } - return $lines.ToArray() } # Runs one script with $tr in its scope; what it writes is collected as it comes, so it is kept if the script fails. - function Invoke-TrScript([scriptblock] $TrScript, [Tr] $tr, [System.Collections.Generic.List[object]] $TrItems) { - & $TrScript *>&1 | ForEach-Object { $TrItems.Add($_) } + # Console text written meanwhile goes before each object it writes, so it keeps its place among them. Returns the error + # that stopped it, or what ended it (exit…; see $TrFlow), or nothing. + function Invoke-TrScript([scriptblock] $TrScript, [Tr] $tr, [TrOutput] $TrItems) { + $TrError = [System.Collections.Generic.List[object]]::new() + $TrStop = $TrFlow::Run({ try { & $TrScript *>&1 | ForEach-Object { if ($TrConsole.Text.Length -gt 0) { Receive-TrConsole $TrItems }; $TrItems.Add($_) } } catch { $TrError.Add($_) } }) + if ($TrError.Count -gt 0) { return $TrError[0] } + return $TrStop + } + + # The console's text, as lines of the running script's output ($Items), with the lines past its limit counted; a line + # not ended yet is one too. Between scripts (no $Items), what threads a script started write after it ends goes to stderr. + function Receive-TrConsole([TrOutput] $Items) { + $text = $TrConsole.Take() + $dropped = $TrConsole.TakeDropped() + if ($null -eq $Items) { + if ($text.Length -gt 0) { $TrStderr.Write($text) } + return + } + + if ($text.Length -gt 0) { + if ($text.EndsWith("`n")) { $text = $text.Substring(0, $text.Length - 1) } + foreach ($line in $text.Split("`n")) { $Items.Add($line.TrimEnd("`r")) } + } + + $Items.Dropped += $dropped } function Invoke-TrMessage([string] $Line) { @@ -626,7 +861,7 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { $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)) + $tr.Variables = [TrVariables]::new($local, $changes['local'], @($local, $environment, $collection, $globals), $message['dynamic']) $tr.Request = [TrRequest]::new($message['request'], $phase -eq 'prerequest') if ($null -ne $message['response']) { $tr.Response = [TrResponse]::new($message['response']) } $tr.Info = $info @@ -637,9 +872,15 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { $name = [string] $script['name'] $code = [string] $script['code'] $info.Script = $name - $items = [System.Collections.Generic.List[object]]::new() + $items = [TrOutput]::new($TrMaxLines - $logs.Count) $compiled = $null if (-not $TrCompiled.TryGetValue($code, [ref] $compiled)) { + if ($TrCompiled.Count -ge 500) { + $TrCompiled.Clear() + $TrNames.Clear() + $TrSources.Clear() + } + $file = 'termrest-script-' + $TrCompiled.Count $tokens = $null $errors = $null @@ -652,11 +893,20 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { if ($compiled -is [scriptblock]) { $TrNames[$compiled.File] = $name + Receive-TrConsole $null try { - Invoke-TrScript $compiled $tr $items + $stopped = Invoke-TrScript $compiled $tr $items } - catch { - $failure = [ordered] @{ script = $name; message = Get-TrFailure $_; traceback = Get-TrTraceback $_ } + finally { + Receive-TrConsole $items + } + + if ($stopped -is [System.Management.Automation.ErrorRecord]) { + $failure = [ordered] @{ script = $name; message = Get-TrFailure $stopped; traceback = Get-TrTraceback $stopped } + } + elseif ($stopped -is [System.Management.Automation.ExitException] -and 0 -ne $stopped.Argument) { + # As SystemExit in Python: exit ends the script, and an exit code other than 0 fails it. + $failure = [ordered] @{ script = $name; message = 'ExitException: ' + $stopped.Argument; traceback = '' } } } else { @@ -678,21 +928,35 @@ [void] AssertEqual([object] $expected, [object] $actual, [string] $message) { $failure = [ordered] @{ script = $name; message = 'ParseError: ' + $first.Message + ' (line ' + $first.Extent.StartLineNumber + ')'; traceback = $traceback.ToString().TrimEnd() } } - foreach ($line in @(ConvertTo-TrLines $items)) { + foreach ($line in @(ConvertTo-TrLines $items.Items)) { if ($logs.Count -lt $TrMaxLines) { - $logs.Add([ordered] @{ script = $name; text = if ($line.Length -gt 4000) { $line.Substring(0, 4000) } else { $line } }) + # Lines are cut at 4,000 characters, not inside a surrogate pair (an emoji). + $logs.Add([ordered] @{ script = $name; text = if ($line.Length -gt 4000) { $line.Substring(0, 4000 - [int][char]::IsHighSurrogate($line, 3999)) } else { $line } }) } else { $dropped++ } } + $dropped += $items.Dropped if ($null -ne $failure) { break } } $result = [ordered] @{ changes = $changes; tests = $tr.Tests; logs = $logs; dropped = $dropped; error = $failure } if ($phase -eq 'prerequest') { - $result.request = [ordered] @{ method = $tr.Request.Method; url = $tr.Request.Url; headers = $tr.Request.Headers.ToJson(); body = $tr.Request.Body } + try { + # The raw body is text: bytes are read as UTF-8, other values (a hashtable…) become JSON, as variables do. + $body = $tr.Request.Body + $body = if ($null -eq $body) { $null } elseif ($body -is [byte[]]) { [System.Text.Encoding]::UTF8.GetString($body) } else { [TrText]::Of($body) } + $result.request = [ordered] @{ method = $tr.Request.Method; url = $tr.Request.Url; headers = $tr.Request.Headers.ToJson(); body = $body } + } + catch { + # What the scripts left in $tr.Request can't be read (Headers set to $null …): the request isn't sent, and + # what the scripts printed, tested and set is kept. + if ($null -eq $failure) { + $result.error = [ordered] @{ script = ''; message = 'The pre-request scripts left a request that cannot be sent: ' + (Get-TrFailure $_); traceback = '' } + } + } } return $result diff --git a/src/TermRest.Core/Scripting/PythonWorkerCode.cs b/src/TermRest.Core/Scripting/PythonWorkerCode.cs index e1ee7f3..4ab599d 100644 --- a/src/TermRest.Core/Scripting/PythonWorkerCode.cs +++ b/src/TermRest.Core/Scripting/PythonWorkerCode.cs @@ -1,18 +1,42 @@ +using System.Text; + namespace TermRest.Core.Scripting; /// -/// The Python side of , passed to the interpreter with -c (no file is written). 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. +/// 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. /// internal static class PythonWorkerCode { - public const string Source = """ - import base64, contextlib, io, json, linecache, os, re, sys, traceback, types - - # 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 their output into an answer. - _in = os.fdopen(os.dup(sys.stdin.fileno()), "r", encoding="utf-8") + /// + /// The command (python -c): reads the worker from the first line of a copy of stdin and runs it. The worker reads its + /// messages from the same copy (_in), whose buffer may hold the start of the first one already. A runtime that is + /// a batch file (a pyenv-win shim, python.bat) gets the command through cmd.exe, which ends a command line at its first + /// line break, refuses one over 8,191 characters, and takes " % ! ^ & | < > as its own: the command is a short + /// line without them, with a space so that it is passed in quotes (where cmd.exe leaves parentheses alone). Hex needs no + /// module: one imported here (os is loaded already) could come from the workspace, which the worker leaves out of + /// sys.path while it imports its own. + /// + public const string Bootstrap = "import os;_in=open(os.dup(0),encoding='utf-8');exec(bytes.fromhex(_in.readline()).decode())"; + + /// The first line of input: the worker's code, hex-encoded (UTF-8). + public static string Preamble { get; } = Convert.ToHexString(Encoding.UTF8.GetBytes(Source)); + + private const string Source = """ + 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 + if _workspace is not None: + sys.path.insert(0, _workspace) + + # Requests come on a copy of stdin (_in, which the bootstrap opened) 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 + # their output into an answer. _out = os.fdopen(os.dup(sys.stdout.fileno()), "w", encoding="utf-8", newline="\n") _null = os.open(os.devnull, os.O_RDONLY) os.dup2(_null, sys.stdin.fileno()) @@ -20,6 +44,14 @@ internal static class PythonWorkerCode os.dup2(sys.stderr.fileno(), sys.stdout.fileno()) sys.stdin = io.StringIO() sys.stdout = sys.stderr + + # On Linux and macOS, a session of its own, without TermRest's terminal: programs that scripts start (ssh, sudo, gpg) + # cannot open /dev/tty to ask over TermRest's screen, and fail at once, as they do without a terminal. + if hasattr(os, "setsid"): + try: + os.setsid() + except OSError: + pass _compiled = {} _reference = re.compile(r"\{\{([^{}]+)\}\}") _max_lines = 1000 @@ -34,9 +66,112 @@ def _text(value): return "" if isinstance(value, (int, float)): return str(value) + # Dates and times, UUIDs and decimals are their text, as in the other languages; anything else becomes JSON. + if isinstance(value, (datetime.date, datetime.time)): + return value.isoformat() + if isinstance(value, (uuid.UUID, decimal.Decimal)): + return str(value) return json.dumps(value) + class _Output(io.TextIOBase): + # What a script prints, as lines of up to 4,000 characters, as many as there is room for: the others are only + # counted, so that a script printing without end does not fill the memory. + + def __init__(self, room): + super().__init__() + self.lines, self.dropped, self._room, self._line = [], 0, room, "" + + def writable(self): + return True + + def write(self, text): + parts = text.split("\n") + parts[0] = self._line + parts[0] + for line in parts[:-1]: + self._keep(line.splitlines() or [""]) + self._line = parts[-1][:4000] + return len(text) + + def end(self): + self._keep(self._line.splitlines()) + self._line = "" + + def _keep(self, lines): + for line in lines: + if len(self.lines) < self._room: + self.lines.append(line[:4000]) + else: + self.dropped += 1 + + + class _Capture(io.TextIOBase): + # sys.stdout and sys.stderr from the start: what is written goes to the output of the script that runs, also through + # a stream kept since an earlier script (a logging handler's); between scripts, to stderr. + + def __init__(self, stream): + super().__init__() + self._stream, self._output = stream, None + + def writable(self): + return True + + def begin(self, room): + self._output = _Output(room) + + def end(self): + output, self._output = self._output, None + output.end() + return output + + def write(self, text): + output = self._output + if output is not None: + return output.write(text) + self._stream.write(text) + return len(text) + + def flush(self): + if self._output is None: + self._stream.flush() + + + _capture = _Capture(sys.stderr) + sys.stdout = sys.stderr = _capture + _alphanumeric = "abcdefghijklmnopqrstuvwxyz0123456789" + + + def _dynamic(samples): + # Postman's dynamic variables, as requests resolve them; the names and words they pick from come with the message. + def pick(key): + values = samples.get(key) or [] + return str(values[secrets.randbelow(len(values))]) if values else "" + + def random_text(length, alphabet=_alphanumeric): + return "".join(alphabet[secrets.randbelow(len(alphabet))] for _ in range(length)) + + def now(): + return datetime.datetime.now(datetime.timezone.utc) + + return { + "$guid": lambda: str(uuid.uuid4()), + "$randomUUID": lambda: str(uuid.uuid4()), + "$timestamp": lambda: str(int(now().timestamp())), + "$isoTimestamp": lambda: now().strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z", + "$randomInt": lambda: str(secrets.randbelow(1001)), + "$randomBoolean": lambda: "true" if secrets.randbelow(2) else "false", + "$randomAlphaNumeric": lambda: random_text(1), + "$randomHexadecimal": lambda: random_text(1, "0123456789abcdef"), + "$randomFirstName": lambda: pick("firstNames"), + "$randomLastName": lambda: pick("lastNames"), + "$randomFullName": lambda: pick("firstNames") + " " + pick("lastNames"), + "$randomUserName": lambda: f"{pick('firstNames').lower()}.{pick('lastNames').lower()}{secrets.randbelow(100)}", + "$randomEmail": lambda: f"{pick('firstNames').lower()}.{pick('lastNames').lower()}@example.com", + "$randomWord": lambda: pick("words"), + "$randomPassword": lambda: random_text(15), + } + + class Scope: # The variables of one scope: the environment, the collection, the globals, or this request. @@ -83,9 +218,10 @@ def __repr__(self): class Variables(Scope): # tr.variables reads every scope (this request, environment, collection, globals) and sets this request's. - def __init__(self, local, changes, scopes): + def __init__(self, local, changes, scopes, dynamic=None): super().__init__(local, changes) self._scopes = scopes + self._dynamic = dynamic or {} def get(self, key, default=None): for values in self._scopes: @@ -109,8 +245,16 @@ raise KeyError(key) return value def replace_in(self, text): + def value(match): + name = match.group(1).strip() + found = self.get(name) + if found is not None: + return found + generate = self._dynamic.get(name) + return generate() if generate is not None else match.group(0) + for _ in range(10): - replaced = _reference.sub(lambda m: self.get(m.group(1).strip(), m.group(0)), text) + replaced = _reference.sub(value, text) if replaced == text: break text = replaced @@ -187,9 +331,23 @@ def __init__(self, data, writable): self.name = data.get("name") self.method = data.get("method", "GET") self.url = data.get("url", "") + self._writable = writable self.headers = Headers(data.get("headers", []), writable) self.body = data.get("body") + @property + def headers(self): + return self._headers + + @headers.setter + def headers(self, value): + # As with requests: a dict, any other mapping (requests' CaseInsensitiveDict), or (name, value) pairs + # replaces the headers. + if not isinstance(value, Headers): + pairs = value.items() if callable(getattr(value, "items", None)) else value + value = Headers([(name, _text(item)) for name, item in pairs], self._writable) + self._headers = value + def __repr__(self): return f"<{self.method} {self.url}>" @@ -223,7 +381,7 @@ def __repr__(self): def _failure(error): - message = str(error) + message = _message(error) if isinstance(error, AssertionError): if not message: frame = traceback.extract_tb(error.__traceback__)[-1] @@ -232,6 +390,18 @@ def _failure(error): return f"{type(error).__name__}: {message}" + def _describe(error): + return f"{type(error).__name__}: {_message(error)}" + + + def _message(error): + # An exception's own text, also of one whose __str__ fails (it would fail the whole answer). + try: + return str(error) + except Exception: + return "(its message could not be read)" + + def _tests(results, info): def test(name, fn=None): if fn is None: @@ -276,7 +446,7 @@ 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"]]), + variables=Variables(values["local"], changes["local"], [values["local"], values["environment"], values["collection"], values["globals"]], _dynamic(message.get("dynamic") or {})), request=request, response=Response(message["response"]) if message.get("response") else None, info=info, @@ -286,30 +456,46 @@ def _run(message): dropped = 0 for script in message.get("scripts") or []: info.script = script["name"] - output = io.StringIO() + _capture.begin(max(_max_lines - len(logs), 0)) stdin = sys.stdin try: code = _compile(script["name"], script["code"]) sys.stdin = io.StringIO() - with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output): - exec(code, {"__name__": "__termrest__", "tr": tr}) + sys.stdout = sys.stderr = _capture + exec(code, {"__name__": "__termrest__", "tr": tr}) except SystemExit as stop: if stop.code not in (None, 0): error = {"script": script["name"], "message": f"SystemExit: {stop.code}", "traceback": ""} except BaseException as failure: - error = {"script": script["name"], "message": f"{type(failure).__name__}: {failure}", "traceback": _traceback(failure, script["name"])} + error = {"script": script["name"], "message": _describe(failure), "traceback": _traceback(failure, script["name"])} finally: sys.stdin = stdin - lines = output.getvalue().splitlines() - room = max(_max_lines - len(logs), 0) - logs.extend({"script": script["name"], "text": line[:4000]} for line in lines[:room]) - dropped += max(len(lines) - room, 0) + sys.stdout = sys.stderr = _capture + output = _capture.end() + logs.extend({"script": script["name"], "text": line} for line in output.lines) + dropped += output.dropped if error: break result = {"changes": changes, "tests": tests, "logs": logs, "dropped": dropped, "error": error} if phase == "prerequest": - body = request.body if request.body is None else str(request.body) - result["request"] = {"method": str(request.method), "url": str(request.url), "headers": request.headers._pairs, "body": body} + try: + body = request.body + if isinstance(body, (bytes, bytearray)): + body = bytes(body).decode("utf-8", "replace") # json.dumps(…).encode(): the text, not "b'…'" + elif isinstance(body, (dict, list, tuple, bool)): + try: + body = _text(body) # JSON, as variables get it, not Python's text ({'a': 1}, True) + except (TypeError, ValueError) as failure: + result["error"] = error or {"script": "", "message": f"The pre-request scripts set the request body to a {type(body).__name__} that cannot be sent as JSON: {failure}", "traceback": ""} + body = None + elif body is not None: + body = str(body) + headers = [[str(name), str(value)] for name, value in request.headers._pairs] + result["request"] = {"method": str(request.method), "url": str(request.url), "headers": headers, "body": body} + except Exception as failure: + # What the scripts left in tr.request can't be read (headers that are not a Headers object …): the + # request isn't sent, and what the scripts printed, tested and set is kept. + result["error"] = error or {"script": "", "message": f"The pre-request scripts left a request that cannot be sent: {_describe(failure)}", "traceback": ""} return result diff --git a/src/TermRest.Core/Scripting/ScriptModel.cs b/src/TermRest.Core/Scripting/ScriptModel.cs index f8fce30..7b98d1a 100644 --- a/src/TermRest.Core/Scripting/ScriptModel.cs +++ b/src/TermRest.Core/Scripting/ScriptModel.cs @@ -243,11 +243,18 @@ public sealed record ScriptTest(string Name, bool Passed, string? Error, string public sealed record ScriptLog(string Phase, string Script, string Text); /// -/// Why scripts stopped: the script that failed and its traceback, or (with no ) why they could not -/// run at all. +/// Why scripts stopped: the script that failed and its traceback, or (with no ) what stopped them as a +/// whole: why they could not run at all (), or a runtime that stopped, or a request they left that +/// cannot be sent. /// public sealed record ScriptError(string Script, string Message, string? Traceback = null) { + /// The scripts did not run at all: no runtime is chosen, or no language has them all. + public bool NotRun { get; init; } + + /// What the error is about: the script that failed, or the scripts as a whole. + public string Heading => Script.Length > 0 ? $"Script error in {Script}" : NotRun ? "Scripts did not run" : "Scripts failed"; + /// What the runtime printed: the traceback, or the message alone. public string Details => string.IsNullOrWhiteSpace(Traceback) ? Message : Traceback.TrimEnd(); @@ -327,7 +334,7 @@ public string Describe() if (Error is not null) { - text.Append(Error.Script.Length == 0 ? "Scripts did not run\n" : $"Script error in {Error.Script}\n") + text.Append(Error.Heading).Append('\n') .Append(Indent(Error.Details)).Append("\n\n"); } diff --git a/src/TermRest.Core/Scripting/ScriptRuntimeLocator.cs b/src/TermRest.Core/Scripting/ScriptRuntimeLocator.cs index 98ecb2a..05714f6 100644 --- a/src/TermRest.Core/Scripting/ScriptRuntimeLocator.cs +++ b/src/TermRest.Core/Scripting/ScriptRuntimeLocator.cs @@ -75,33 +75,108 @@ public static IEnumerable Candidates(string language, string workspaceRo yield return "python"; } - /// The first of the that runs, with its description; null when none does. + /// + /// The first of the that runs, with its description; null when none does. Those in the + /// workspace (its .venv's Python) are not run, as they may have come with a repository: the first of them is + /// the answer, unchecked (Checked is false), for the user to check. The others run as + /// runs them: outside the workspace. + /// /// Turns a candidate into what to start (relative paths are relative to the workspace). - public static async Task<(string Runtime, string Description)?> FindAsync(string language, string workspaceRoot, Func resolve, - CancellationToken cancellationToken = default) + public static async Task<(string Runtime, string Description, bool Checked)?> FindAsync(string language, string workspaceRoot, + Func resolve, CancellationToken cancellationToken = default) { foreach (var candidate in Candidates(language, workspaceRoot)) { - var (ok, description) = await CheckAsync(language, resolve(candidate), workspaceRoot, cancellationToken).ConfigureAwait(false); + if (!Path.IsPathRooted(candidate) && candidate.IndexOfAny(['/', '\\']) >= 0) + { + return (candidate, "Found in this workspace, not run: Check runs it.", false); + } + + var (ok, description) = await CheckAsync(language, resolve(candidate), cancellationToken).ConfigureAwait(false); if (ok) { - return (candidate, description); + return (candidate, description, true); + } + } + + return null; + } + + /// + /// The program to start for : a path as it is, and a command (no folder: python3, + /// node) from the folders of PATH, on Windows with .exe unless it ends with an extension that Windows + /// runs (PATHEXT: .exe, .cmd…), so python3.12 is python3.12.exe. Windows and .NET would + /// look in TermRest's own folder and in the current one first (the workspace, often), where a repository may put a + /// node.exe of its own. Null when the command is not on PATH. + /// + /// The folders to look in (PATH when null); relative ones, which are the current folder's, are not. + public static string? Executable(string runtime, string? path = null) + { + if (runtime.IndexOfAny(['/', '\\']) >= 0 || Path.IsPathRooted(runtime)) + { + return runtime; + } + + var name = OperatingSystem.IsWindows() && !IsProgramName(runtime) ? runtime + ".exe" : runtime; + foreach (var folder in (path ?? Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator, StringSplitOptions.TrimEntries)) + { + var directory = folder.Trim('"'); + if (Path.IsPathFullyQualified(directory) && IsProgram(Path.Combine(directory, name))) + { + return Path.Combine(directory, name); } } return null; } - /// Runs the runtime once: its version and location, or why it cannot run scripts. - public static async Task<(bool Ok, string Message)> CheckAsync(string language, string runtime, string workingDirectory, - CancellationToken cancellationToken = default) + /// Whether a command's name ends with an extension of programs on Windows (PATHEXT), as shells take it. + private static bool IsProgramName(string name) { + var extension = Path.GetExtension(name); + var programs = Environment.GetEnvironmentVariable("PATHEXT") is { Length: > 0 } list ? list : ".COM;.EXE;.BAT;.CMD"; + return extension.Length > 1 && (extension.Equals(".exe", StringComparison.OrdinalIgnoreCase) + || programs.Split(';', StringSplitOptions.TrimEntries).Contains(extension, StringComparer.OrdinalIgnoreCase)); + } + + private static bool IsProgram(string file) + { + if (OperatingSystem.IsWindows()) + { + return File.Exists(file); + } + + return File.Exists(file) && (File.GetUnixFileMode(file) & (UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute)) != 0; + } + + /// + /// Runs the runtime once: its version and location, or why it cannot run scripts. It runs in TermRest's cache folder, + /// not in the workspace, whose files it would obey before it is chosen: Bun runs the code that a bunfig.toml + /// preloads, and dotnet lists the SDKs that a global.json points to. + /// + public static async Task<(bool Ok, string Message)> CheckAsync(string language, string runtime, CancellationToken cancellationToken = default) + { + if (Executable(runtime) is not { } executable) + { + return (false, $"{runtime} could not be started: it is not on PATH."); + } + + string folder; + try + { + folder = CSharpPrograms.CreateCacheDirectory(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return (false, $"{runtime} could not be checked: {ex.Message}"); + } + var python = language == ScriptLanguage.Python; var csharp = language == ScriptLanguage.CSharp; var powerShell = language == ScriptLanguage.PowerShell; - var info = new ProcessStartInfo(runtime) + var info = new ProcessStartInfo(executable) { - WorkingDirectory = workingDirectory, + WorkingDirectory = folder, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, diff --git a/src/TermRest.Core/Scripting/ScriptWorker.cs b/src/TermRest.Core/Scripting/ScriptWorker.cs index 705e94a..2e958ca 100644 --- a/src/TermRest.Core/Scripting/ScriptWorker.cs +++ b/src/TermRest.Core/Scripting/ScriptWorker.cs @@ -4,6 +4,7 @@ using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; +using System.Text.RegularExpressions; namespace TermRest.Core.Scripting; @@ -15,24 +16,31 @@ namespace TermRest.Core.Scripting; /// a cancelled one, ends the process; the next run starts a new one. C# scripts are built into a program first /// (), which the process runs; other scripts start another program. /// -public sealed class ScriptWorker : IDisposable +public sealed partial class ScriptWorker : IDisposable { private static readonly JsonSerializerOptions JsonOptions = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; + private static readonly JsonWriterOptions WriterOptions = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; private static readonly UTF8Encoding Utf8 = new(encoderShouldEmitUTF8Identifier: false); + /// How many of the last characters the runtime wrote besides its answers are kept (see ). + private const int Kept = 4000; + private readonly SemaphoreSlim _gate = new(1, 1); private readonly Timer _idleTimer; - private readonly StringBuilder _stderr = new(); + private readonly char[] _said = new char[2 * Kept]; private readonly string _workingDirectory; private readonly string? _preamble; private readonly string? _replyMarker; private readonly CSharpPrograms? _programs; + private readonly bool _ownSession; private string[] _arguments; private Process? _process; + private Task _errorReader = Task.CompletedTask; + private int _saidLength; private volatile bool _disposed; private ScriptWorker(string runtime, string name, string workingDirectory, string[] arguments, string? preamble, string? replyMarker, - CSharpPrograms? programs = null) + CSharpPrograms? programs = null, bool ownSession = false) { Runtime = runtime; Name = name; @@ -41,6 +49,7 @@ private ScriptWorker(string runtime, string name, string workingDirectory, strin _preamble = preamble; _replyMarker = replyMarker; _programs = programs; + _ownSession = ownSession; _idleTimer = new Timer(_ => StopWhenIdle()); } @@ -53,14 +62,27 @@ private ScriptWorker(string runtime, string name, string workingDirectory, strin public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromMinutes(5); /// Whether the runtime's process is running now. - public bool IsRunning => Volatile.Read(ref _process) is { HasExited: false }; + public bool IsRunning + { + get + { + try + { + return Volatile.Read(ref _process) is { HasExited: false }; + } + catch (InvalidOperationException) + { + return false; // stopped (and disposed) just as it was read + } + } + } /// A worker that runs scripts in with . public static ScriptWorker For(string language, string runtime, string workingDirectory) { if (language == ScriptLanguage.Python) { - return new(runtime, "Python", workingDirectory, ["-X", "utf8", "-u", "-c", PythonWorkerCode.Source], null, null); + return new(runtime, "Python", workingDirectory, ["-X", "utf8", "-u", "-c", PythonWorkerCode.Bootstrap], PythonWorkerCode.Preamble, null); } if (language == ScriptLanguage.CSharp) @@ -79,7 +101,7 @@ public static ScriptWorker For(string language, string runtime, string workingDi var name = ScriptLanguage.JavaScriptRuntimeName(runtime); string[] tuning = name == "Node.js" ? ["--max-semi-space-size=1", "--optimize-for-size"] : []; return new(runtime, name, workingDirectory, [.. tuning, "-e", JavaScriptWorkerCode.Bootstrap], - JsonValue.Create(JavaScriptWorkerCode.Source).ToJsonString(JsonOptions), JavaScriptWorkerCode.ReplyMarker); + JsonValue.Create(JavaScriptWorkerCode.Source).ToJsonString(JsonOptions), JavaScriptWorkerCode.ReplyMarker, ownSession: true); } /// Sends one message to the runtime and returns its answer. @@ -97,6 +119,7 @@ public async Task RunAsync(JsonObject message, TimeSpan timeout, IEn ObjectDisposedException.ThrowIf(_disposed, this); _idleTimer.Change(Timeout.Infinite, Timeout.Infinite); var note = _programs is null ? null : await UseProgramAsync(message, related ?? [], cancellationToken).ConfigureAwait(false); + ObjectDisposedException.ThrowIf(_disposed, this); // stopped while C# scripts were built: their program does not start var started = _process is not { HasExited: false }; var process = started ? Start() : _process!; using var limit = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); @@ -106,13 +129,18 @@ public async Task RunAsync(JsonObject message, TimeSpan timeout, IEn if (started && _preamble is not null) { await process.StandardInput.WriteLineAsync(_preamble.AsMemory(), limit.Token).ConfigureAwait(false); + await process.StandardInput.FlushAsync(limit.Token).ConfigureAwait(false); } - await process.StandardInput.WriteLineAsync(message.ToJsonString(JsonOptions).AsMemory(), limit.Token).ConfigureAwait(false); - await process.StandardInput.FlushAsync(limit.Token).ConfigureAwait(false); + await WriteAsync(process.StandardInput.BaseStream, message, limit.Token).ConfigureAwait(false); var line = await ReadReplyAsync(process, limit.Token).ConfigureAwait(false); if (line is null) { + ObjectDisposedException.ThrowIf(_disposed, this); // stopped while the scripts ran + + // Why it stopped is in what it wrote last, which stderr brings soon (at once, unless a program that a + // script started still holds stderr open). + await Task.WhenAny(_errorReader, Task.Delay(TimeSpan.FromSeconds(1), CancellationToken.None)).ConfigureAwait(false); var diagnostics = Diagnostics(); Stop(kill: true); if (started && _programs is not null) @@ -123,7 +151,7 @@ public async Task RunAsync(JsonObject message, TimeSpan timeout, IEn throw new ScriptException($"{Name} stopped.{diagnostics}"); } - var reply = JsonNode.Parse(line) as JsonObject ?? throw new ScriptException($"{Name} answered with something that is not JSON."); + var reply = JsonNode.Parse(WellFormed(line)) as JsonObject ?? throw new ScriptException($"{Name} answered with something that is not JSON."); if (reply["fatal"]?.GetValue() is { } fatal) { throw new ScriptException($"The script runner failed:\n{fatal}"); @@ -146,20 +174,34 @@ public async Task RunAsync(JsonObject message, TimeSpan timeout, IEn Stop(kill: true); // a cancelled script may still be running throw; } - catch (Exception ex) when (ex is IOException or JsonException or InvalidOperationException) + catch (Exception ex) when (ex is IOException or JsonException or InvalidOperationException and not ObjectDisposedException) { Stop(kill: true); + ObjectDisposedException.ThrowIf(_disposed, this); // stopped while the scripts ran, so the pipes closed throw new ScriptException($"{Name} stopped: {ex.Message}{Diagnostics()}", ex); } } finally { - if (!_disposed) + try { - _idleTimer.Change(IdleTimeout, Timeout.InfiniteTimeSpan); + if (_disposed) + { + Stop(kill: false); // stopped meanwhile: a process started since must not outlive the worker + } + else + { + _idleTimer.Change(IdleTimeout, Timeout.InfiniteTimeSpan); + } + } + catch (ObjectDisposedException) + { + Stop(kill: false); // stopped just now, between the check and the timer, which is disposed + } + finally + { + _gate.Release(); // or a run waiting for this one would wait until cancelled } - - _gate.Release(); } } @@ -172,7 +214,10 @@ public void Dispose() _disposed = true; _idleTimer.Dispose(); - Stop(kill: false); + + // A runtime that runs a script reads the end of its input only once the script ends: it is stopped at once instead + // of holding the caller up (Tools › Scripts › Stop scripts, on the UI thread), and the run reports that it was. + Stop(kill: _gate.CurrentCount == 0); } /// @@ -201,6 +246,74 @@ public void Dispose() return note; } + /// + /// Writes the message as one line of UTF-8 JSON, straight to the runtime's input. Long texts (a response body…) and + /// bytes (a binary body, as base64) are written in parts: System.Text.Json would otherwise need a few times their size. + /// + private static async Task WriteAsync(Stream input, JsonObject message, CancellationToken cancellationToken) + { + await using (var writer = new Utf8JsonWriter(input, WriterOptions)) + { + await WriteAsync(writer, message, cancellationToken).ConfigureAwait(false); + await writer.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + await input.WriteAsync("\n"u8.ToArray(), cancellationToken).ConfigureAwait(false); + await input.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + private static async Task WriteAsync(Utf8JsonWriter writer, JsonNode? node, CancellationToken cancellationToken) + { + const int Part = 3 << 15; // characters or bytes (a multiple of 3: whole base64 groups) + switch (node) + { + case JsonObject members: + writer.WriteStartObject(); + foreach (var (name, value) in members) + { + writer.WritePropertyName(name); + await WriteAsync(writer, value, cancellationToken).ConfigureAwait(false); + } + + writer.WriteEndObject(); + break; + case JsonArray items: + writer.WriteStartArray(); + foreach (var item in items) + { + await WriteAsync(writer, item, cancellationToken).ConfigureAwait(false); + } + + writer.WriteEndArray(); + break; + case JsonValue value when value.TryGetValue(out var text) && text.Length > Part: + for (var at = 0; at < text.Length; at += Part) + { + writer.WriteStringValueSegment(text.AsSpan(at, Math.Min(Part, text.Length - at)), at + Part >= text.Length); + await writer.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + break; + case JsonValue value when value.TryGetValue(out var bytes): + var offset = 0; + do + { + var length = Math.Min(Part, bytes.Length - offset); + writer.WriteBase64StringSegment(bytes.AsSpan(offset, length), offset + length == bytes.Length); + offset += length; + await writer.FlushAsync(cancellationToken).ConfigureAwait(false); + } + while (offset < bytes.Length); + break; + case null: + writer.WriteNullValue(); + break; + default: + node.WriteTo(writer); + break; + } + } + /// 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) { @@ -218,14 +331,37 @@ public void Dispose() } Remember(line); + Remember("\n"); } return null; } + /// + /// The reply with escaped halves of surrogate pairs that stand alone (\ud83d: a script's substring of an emoji, as + /// JavaScript and Python write it) as U+FFFD: they are not text, and System.Text.Json refuses to read them as text. + /// + private static string WellFormed(string reply) + { + if (reply.Contains(@"\ud", StringComparison.OrdinalIgnoreCase)) + { + // Whole pairs (emoji, which Python and .NET write as escapes) need no copy: a match of 6 characters is a half. + foreach (var escape in Escape().EnumerateMatches(reply)) + { + if (escape.Length == 6) + { + return Escape().Replace(reply, m => m.Groups[1].Success ? @"\uFFFD" : m.Value); + } + } + } + + return reply; + } + private Process Start() { - var info = new ProcessStartInfo(Runtime) + var executable = ScriptRuntimeLocator.Executable(Runtime) ?? throw new ScriptException($"{Name} could not be started ({Runtime}): it is not on PATH."); + var info = new ProcessStartInfo(executable) { WorkingDirectory = _workingDirectory, RedirectStandardInput = true, @@ -240,15 +376,27 @@ private Process Start() StandardOutputEncoding = Utf8, StandardErrorEncoding = Utf8, }; + + // On Linux and macOS, the workers leave TermRest's terminal themselves, for a session of their own: programs that + // scripts start (ssh, sudo, gpg) then cannot open /dev/tty to ask over TermRest's screen, and fail at once. Node.js + // and Bun cannot, so on Linux setsid starts them in one; as it is not a process group leader, it does not fork but + // becomes the runtime, the process that TermRest stops. + if (_ownSession && OperatingSystem.IsLinux() && ScriptRuntimeLocator.Executable("setsid") is { } setsid) + { + info.FileName = setsid; + info.ArgumentList.Add("--"); + info.ArgumentList.Add(executable); + } + foreach (var argument in _arguments) { info.ArgumentList.Add(argument); } info.Environment["PYTHONIOENCODING"] = "utf-8"; - lock (_stderr) + lock (_said) { - _stderr.Clear(); + _saidLength = 0; } Process process; @@ -261,37 +409,92 @@ private Process Start() throw new ScriptException($"{Name} could not be started ({Runtime}): {ex.Message}", ex); } - process.ErrorDataReceived += (_, e) => + _errorReader = ReadErrorsAsync(process.StandardError); + Volatile.Write(ref _process, process); + return process; + } + + /// + /// Reads stderr, where the runtime says why it stops and where the Python, C# and PowerShell workers send the output of + /// programs that scripts start, until it ends; only its end is kept. Process's own reader would hold each line whole + /// first: a program printing hundreds of megabytes without a newline (curl -s) would take as much memory. + /// + private async Task ReadErrorsAsync(StreamReader reader) + { + var buffer = new char[4096]; + var afterReturn = false; + try { - if (e.Data is { } text) + using (reader) { - Remember(text); + int read; + while ((read = await reader.ReadAsync(buffer).ConfigureAwait(false)) > 0) + { + // Lines end with \n here, as they did from the line reader (\r\n, \r or \n). + var length = 0; + for (var i = 0; i < read; i++) + { + var c = buffer[i]; + if (c != '\n' || !afterReturn) + { + buffer[length++] = c == '\r' ? '\n' : c; + } + + afterReturn = c == '\r'; + } + + Remember(buffer.AsSpan(0, length)); + } } - }; - process.BeginErrorReadLine(); - Volatile.Write(ref _process, process); - return process; + } + catch (Exception ex) when (ex is IOException or ObjectDisposedException) + { + // the runtime is gone + } } - /// Keeps the last 4,000 characters the runtime wrote besides its answers (why it stopped, usually). - private void Remember(string text) + /// Keeps the last 4,000 characters the runtime wrote besides its answers (why it stopped, usually), in a buffer of a fixed size. + private void Remember(ReadOnlySpan text) { - lock (_stderr) + lock (_said) { - _stderr.Append(text).Append('\n'); - if (_stderr.Length > 4000) + if (text.Length > Kept) { - _stderr.Remove(0, _stderr.Length - 4000); + text = text[^Kept..]; } + + if (_saidLength + text.Length > _said.Length) + { + var kept = Kept - text.Length; + _said.AsSpan(_saidLength - kept, kept).CopyTo(_said); + _saidLength = kept; + } + + text.CopyTo(_said.AsSpan(_saidLength)); + _saidLength += text.Length; } } private string Diagnostics() { - lock (_stderr) + lock (_said) { - var text = _stderr.ToString().Trim(); - return text.Length == 0 ? "" : $"\n{text}"; + var text = _said.AsSpan(Math.Max(0, _saidLength - Kept), Math.Min(_saidLength, Kept)); + + // Not half of a surrogate pair (an emoji) where the text was cut, or whose other half is still to be read: it is + // not text, and the UI cannot draw it. + if (text.Length > 0 && char.IsLowSurrogate(text[0])) + { + text = text[1..]; + } + + if (text.Length > 0 && char.IsHighSurrogate(text[^1])) + { + text = text[..^1]; + } + + text = text.Trim(); + return text.Length == 0 ? "" : string.Concat("\n", text); } } @@ -343,4 +546,9 @@ private void Stop(bool kill) process.Dispose(); } } + + // 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)] + private static partial Regex Escape(); } diff --git a/src/TermRest.Core/Variables/VariableResolver.cs b/src/TermRest.Core/Variables/VariableResolver.cs index f00aa63..e23f387 100644 --- a/src/TermRest.Core/Variables/VariableResolver.cs +++ b/src/TermRest.Core/Variables/VariableResolver.cs @@ -67,15 +67,24 @@ public bool TryGetValue(string key, out string? value) /// /// Resolves Postman {{variable}} references. Scopes are searched in order (highest precedence first: /// local/CLI overrides, environment, collection, globals). Values may reference other variables; resolution is -/// repeated up to times. Unknown variables are left as-is, like Postman does. +/// repeated up to times, and adds at most characters. Unknown variables +/// are left as-is, like Postman does. /// public sealed partial class VariableResolver { public const int MaxDepth = 10; - private static readonly string[] FirstNames = ["Ada", "Alan", "Grace", "Linus", "Margaret", "Ken", "Barbara", "Dennis"]; - private static readonly string[] LastNames = ["Lovelace", "Turing", "Hopper", "Torvalds", "Hamilton", "Thompson", "Liskov", "Ritchie"]; - private static readonly string[] Words = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel"]; + /// + /// How many characters resolving a text may add to it. A value that references itself (or others that reference it) + /// several times would multiply the text with every pass: a reference whose value would take the text past this + /// limit stays unresolved, and no further pass is made. + /// + public const int MaxGrowth = 4 * 1024 * 1024; + + // What {{$randomFirstName}} and the like pick from; scripts get them with each message (their replaceIn resolves the same names). + internal static readonly string[] FirstNames = ["Ada", "Alan", "Grace", "Linus", "Margaret", "Ken", "Barbara", "Dennis"]; + internal static readonly string[] LastNames = ["Lovelace", "Turing", "Hopper", "Torvalds", "Hamilton", "Thompson", "Liskov", "Ritchie"]; + internal static readonly string[] Words = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel"]; private readonly IReadOnlyList _scopes; private readonly TimeProvider _time; @@ -93,10 +102,35 @@ public VariableResolver(IEnumerable scopesHighestPrecedenceFirst [GeneratedRegex(@"\{\{([^{}]+)\}\}", RegexOptions.CultureInvariant)] private static partial Regex ReferencePattern(); - public static IEnumerable FindReferences(string? text) => - string.IsNullOrEmpty(text) ? [] : ReferencePattern().Matches(text).Select(m => m.Groups[1].Value).Distinct(StringComparer.Ordinal); + public static IEnumerable FindReferences(string? text) + { + if (string.IsNullOrEmpty(text)) + { + return []; + } + + // Compared before they are copied: a text that MaxGrowth cut short holds the same names many times. + var names = new List(); + var seen = new HashSet(StringComparer.Ordinal); + var lookup = seen.GetAlternateLookup>(); + foreach (var match in ReferencePattern().EnumerateMatches(text)) + { + var name = text.AsSpan(match.Index + 2, match.Length - 4); + if (!lookup.Contains(name)) + { + var copy = name.ToString(); + names.Add(copy); + seen.Add(copy); + } + } + + return names; + } - /// Replaces all resolvable references. Names that cannot be resolved are added to . + /// + /// Replaces all resolvable references, as long as the text grows by at most characters. Names + /// that cannot be resolved, or that are left at that limit, are added to . + /// public string Resolve(string? text, ISet? unresolved = null) { if (string.IsNullOrEmpty(text) || !text.Contains("{{", StringComparison.Ordinal)) @@ -104,23 +138,46 @@ public string Resolve(string? text, ISet? unresolved = null) return text ?? ""; } + var limit = (long)text.Length + MaxGrowth; var current = text; - for (var depth = 0; depth < MaxDepth; depth++) + var full = false; + for (var depth = 0; depth < MaxDepth && !full; depth++) { + var builder = new StringBuilder(); + var end = 0; + var length = (long)current.Length; var replaced = false; - current = ReferencePattern().Replace(current, match => + string? name = null; + foreach (var match in ReferencePattern().EnumerateMatches(current)) { - var name = match.Groups[1].Value; - if (TryResolve(name, out var value, out _)) + // The same name again (as in a text that grew to the limit) is not copied again. + var reference = current.AsSpan(match.Index + 2, match.Length - 4); + name = name is not null && reference.SequenceEqual(name) ? name : reference.ToString(); + if (!TryResolve(name, out var value, out _)) + { + continue; + } + + value ??= ""; + if (length + value.Length - match.Length > limit) { - replaced = true; - return value ?? ""; + full = true; // left as it is; references after it that fit are still replaced + continue; } - return match.Value; - }); + length += value.Length - match.Length; + builder.Append(current, end, match.Index - end).Append(value); + end = match.Index + match.Length; + replaced = true; + } - if (!replaced || !current.Contains("{{", StringComparison.Ordinal)) + if (!replaced) + { + break; + } + + current = builder.Append(current, end, current.Length - end).ToString(); + if (!current.Contains("{{", StringComparison.Ordinal)) { break; } @@ -137,15 +194,12 @@ public string Resolve(string? text, ISet? unresolved = null) return current; } - /// Looks up a single variable (without nested resolution) and reports the scope it came from. + /// + /// Looks up a single variable (without nested resolution) and reports the scope it came from. A variable takes the place + /// of a dynamic one of the same name ($timestamp set by a script), as in Postman and in scripts' replaceIn. + /// public bool TryResolve(string name, out string? value, out string? scopeName) { - if (name.StartsWith('$') && TryDynamic(name, out value)) - { - scopeName = "dynamic"; - return true; - } - foreach (var scope in _scopes) { if (scope.TryGetValue(name, out value)) @@ -155,6 +209,12 @@ public bool TryResolve(string name, out string? value, out string? scopeName) } } + if (name.StartsWith('$') && TryDynamic(name, out value)) + { + scopeName = "dynamic"; + return true; + } + value = null; scopeName = null; return false; diff --git a/src/TermRest.Core/Workspace/ApiWorkspace.cs b/src/TermRest.Core/Workspace/ApiWorkspace.cs index 1fe5331..6486122 100644 --- a/src/TermRest.Core/Workspace/ApiWorkspace.cs +++ b/src/TermRest.Core/Workspace/ApiWorkspace.cs @@ -1,6 +1,8 @@ using System.Text.Json; +using System.Text.Json.Nodes; using TermRest.Core.Certificates; using TermRest.Core.IO; +using TermRest.Core.Json; using TermRest.Core.Postman; using TermRest.Core.Postman.V3; @@ -14,11 +16,18 @@ public sealed class ApiWorkspace { public const string ConfigDirectoryName = ".termrest"; + /// The settings that name the active environment (see ). + private static readonly string[] ActiveEnvironmentKeys = ["activeEnvironment", "activeEnvironmentFile"]; + + /// as last loaded or saved, to save only what changed since. + private JsonObject _savedSettings; + private ApiWorkspace(string rootPath, WorkspaceSettings settings, CertificateRegistry certificates) { RootPath = rootPath; Settings = settings; Certificates = certificates; + _savedSettings = Serialize(settings); } public string RootPath { get; } @@ -36,29 +45,116 @@ private ApiWorkspace(string rootPath, WorkspaceSettings settings, CertificateReg /// Files that could not be loaded (shown to the user instead of failing the whole workspace). public List LoadErrors { get; } = []; + /// + /// Why could not be read, if it could not (also in ): the settings + /// are the defaults then, and does not save over the file. + /// + public string? SettingsError { get; private init; } + + /// + /// Why could not be read, if it could not (also in ): the + /// registry is empty then, and does not save over the file. + /// + public string? CertificatesError { get; private init; } + public string ConfigDirectory => Path.Combine(RootPath, ConfigDirectoryName); public string SettingsPath => Path.Combine(ConfigDirectory, "settings.json"); public string CertificatesPath => Path.Combine(ConfigDirectory, "certificates.json"); + /// + /// The selected environment: the one loaded from , which tells + /// environments of the same name apart; else (settings of earlier versions, a file renamed or deleted meanwhile) the + /// first one named . + /// public PostmanEnvironment? ActiveEnvironment { - get => Settings.ActiveEnvironment is { } name - ? Environments.FirstOrDefault(e => string.Equals(e.Name, name, StringComparison.OrdinalIgnoreCase)) - : null; - set => Settings.ActiveEnvironment = value?.Name; + get + { + if (Settings.ActiveEnvironmentFile is { } file) + { + var path = file.Replace(Path.DirectorySeparatorChar, '/'); + if (Environments.FirstOrDefault(e => string.Equals(SettingsFileOf(e), path, StringComparison.OrdinalIgnoreCase)) is { } selected) + { + return selected; + } + } + + return Settings.ActiveEnvironment is { } name + ? Environments.FirstOrDefault(e => string.Equals(e.Name, name, StringComparison.OrdinalIgnoreCase)) + : null; + } + set + { + Settings.ActiveEnvironment = value?.Name; + Settings.ActiveEnvironmentFile = value is null ? null : SettingsFileOf(value); + } + } + + /// An environment's file as names it. + private string? SettingsFileOf(PostmanEnvironment environment) => + environment.FilePath is { } file ? Path.GetRelativePath(RootPath, file).Replace(Path.DirectorySeparatorChar, '/') : null; + + /// + /// How to name to the user: its name, and its file too where another environment of the + /// workspace has the same name (see ), so that the user can tell which one it is; the + /// file's path in the workspace where their files have the same name too (in the workspace folder and in + /// postman/environments). + /// + public string DisplayName(PostmanEnvironment environment) + { + var file = Path.GetFileName(environment.FilePath); + var namesakes = Environments.Where(e => e != environment && string.Equals(e.Name, environment.Name, StringComparison.OrdinalIgnoreCase)); + if (file is null || !namesakes.Any()) + { + return environment.Name; + } + + return namesakes.Any(e => string.Equals(Path.GetFileName(e.FilePath), file, StringComparison.OrdinalIgnoreCase)) + ? $"{environment.Name} ({SettingsFileOf(environment)})" + : $"{environment.Name} ({file})"; + } + + /// + /// A collection's file (a v3 collection's folder) as the history names it: relative to the workspace, with "/", as + /// names an environment's. Unlike its name, it tells apart + /// collections of the same name (an imported update of a collection, a converted copy). + /// + public string? FileOf(PostmanCollection collection) => + collection.FilePath is { } file ? Path.GetRelativePath(RootPath, file).Replace(Path.DirectorySeparatorChar, '/') : null; + + /// + /// How to name to the user, as names an + /// environment: its name, and its file (a v3 collection's folder) too where another collection of the workspace has + /// the same name; the file's path in the workspace where their files have the same name too. + /// + public string DisplayName(PostmanCollection collection) + { + var namesakes = Collections.Where(c => c != collection && c.Name == collection.Name); + if (collection.FilePath is not { } path || !namesakes.Any()) + { + return collection.Name; + } + + var file = Path.GetFileName(path); + return namesakes.Any(c => string.Equals(Path.GetFileName(c.FilePath), file, StringComparison.OrdinalIgnoreCase)) + ? $"{collection.Name} ({FileOf(collection)})" + : $"{collection.Name} ({file})"; } public bool HasUnsavedChanges => Collections.Any(c => c.IsDirty) || Environments.Any(e => e.IsDirty) || Globals?.IsDirty == true; /// - /// Opens a workspace folder, the folder containing a collection file, or (for a v3 collection folder) the - /// workspace that holds it. Postman v3 projects are found under postman/collections, + /// Opens a workspace folder, or the workspace that holds a collection file or v3 collection folder: the folder above + /// postman for one in postman/collections, else the folder it is in (for a file, see + /// ). Postman v3 projects are found under postman/collections, /// postman/environments and postman/globals. /// - public static ApiWorkspace Open(string path) + /// The workspace folder, or a collection file or v3 collection folder. + /// Which collections to load; the settings, certificates and environments are always loaded. + public static ApiWorkspace Open(string path, CollectionLoading collections = CollectionLoading.All) { var fullPath = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); string root; @@ -66,13 +162,13 @@ public static ApiWorkspace Open(string path) string? explicitFolder = null; if (File.Exists(fullPath)) { - root = Path.GetDirectoryName(fullPath)!; + root = RootForFile(fullPath); explicitFile = fullPath; } else if (Directory.Exists(fullPath)) { root = fullPath; - if (!Directory.Exists(Path.Combine(fullPath, PostmanFolder)) && V3Names.IsCollectionDirectory(fullPath)) + if (IsCollectionFolder(fullPath)) { // A v3 collection folder: open the workspace around it (its settings, environments, certificates). explicitFolder = fullPath; @@ -84,42 +180,35 @@ public static ApiWorkspace Open(string path) throw new DirectoryNotFoundException($"'{path}' does not exist."); } - var errors = new List(); - var settings = LoadSettings(Path.Combine(root, ConfigDirectoryName, "settings.json"), errors); + var settings = LoadSettings(Path.Combine(root, ConfigDirectoryName, "settings.json"), out var settingsError); CertificateRegistry certificates; + string? certificatesError = null; var certificatesPath = Path.Combine(root, ConfigDirectoryName, "certificates.json"); try { certificates = CertificateRegistry.LoadOrEmpty(certificatesPath, root); } - catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException) + catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException or UnauthorizedAccessException) { - errors.Add($"{certificatesPath}: {ex.Message}"); - certificates = new CertificateRegistry(root, certificatesPath); + certificatesError = $"{certificatesPath}: {ex.Message}"; + certificates = new CertificateRegistry(root); // no file to save to: only SaveCertificates could, and it refuses } - var workspace = new ApiWorkspace(root, settings, certificates); - workspace.LoadErrors.AddRange(errors); + var workspace = new ApiWorkspace(root, settings, certificates) { SettingsError = settingsError, CertificatesError = certificatesError }; + workspace.LoadErrors.AddRange(new[] { settingsError, certificatesError }.OfType()); - var collectionsFolder = Path.Combine(root, PostmanFolder, "collections"); - var collectionFiles = Directory.EnumerateFiles(root, "*" + PostmanCollection.FileSuffix) - .Concat(EnumerateFiles(collectionsFolder, "*" + PostmanCollection.FileSuffix)) - .ToList(); - if (explicitFile is not null && !collectionFiles.Contains(explicitFile, StringComparer.OrdinalIgnoreCase) - && !explicitFile.EndsWith(PostmanEnvironment.EnvironmentSuffix, StringComparison.OrdinalIgnoreCase) - && !PostmanEnvironment.IsYamlPath(explicitFile)) + // The collection that was opened: a file (not an environment or globals) or a v3 collection folder. + var opened = explicitFolder ?? (explicitFile is not null && !explicitFile.EndsWith(PostmanEnvironment.EnvironmentSuffix, StringComparison.OrdinalIgnoreCase) + && !explicitFile.EndsWith(PostmanEnvironment.GlobalsSuffix, StringComparison.OrdinalIgnoreCase) + && !PostmanEnvironment.IsYamlPath(explicitFile) ? explicitFile : null); + IEnumerable collectionSources = collections switch { - collectionFiles.Insert(0, explicitFile); - } - - // v3 collection folders: postman/collections/*, plus collection folders kept directly in the workspace. - var collectionFolders = EnumerateDirectories(collectionsFolder).Where(V3Names.IsCollectionDirectory) - .Concat(EnumerateDirectories(root).Where(d => !Path.GetFileName(d).Equals(PostmanFolder, StringComparison.OrdinalIgnoreCase) - && File.Exists(V3Names.DefinitionPath(d)))) - .Concat(explicitFolder is null ? [] : [explicitFolder]) - .Distinct(StringComparer.OrdinalIgnoreCase); + CollectionLoading.None => [], + CollectionLoading.Requested when opened is not null => [opened], + _ => EnumerateCollections(root, opened, workspace.LoadErrors), + }; - foreach (var source in collectionFiles.Concat(collectionFolders).OrderBy(Path.GetFileName, StringComparer.OrdinalIgnoreCase)) + foreach (var source in collectionSources.OrderBy(Path.GetFileName, StringComparer.OrdinalIgnoreCase)) { try { @@ -135,32 +224,38 @@ public static ApiWorkspace Open(string path) var environmentsFolder = Path.Combine(root, PostmanFolder, "environments"); var environmentFiles = Directory.EnumerateFiles(root, "*" + PostmanEnvironment.EnvironmentSuffix) - .Concat(EnumerateFiles(environmentsFolder, "*" + PostmanEnvironment.EnvironmentSuffix)) - .Concat(EnumerateFiles(environmentsFolder, "*.y*ml").Where(PostmanEnvironment.IsYamlPath)); + .Concat(Listing(root, environmentsFolder, workspace.LoadErrors, () => EnumerateFiles(environmentsFolder, "*" + PostmanEnvironment.EnvironmentSuffix) + .Concat(EnumerateFiles(environmentsFolder, "*.y*ml").Where(PostmanEnvironment.IsYamlPath)))); foreach (var file in environmentFiles.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(Path.GetFileName, StringComparer.OrdinalIgnoreCase)) { try { workspace.Environments.Add(PostmanEnvironment.Load(file)); } - catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException) + catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException or UnauthorizedAccessException) { workspace.LoadErrors.Add($"{Path.GetFileName(file)}: {ex.Message}"); } } - var globalsFolder = Path.Combine(root, PostmanFolder, "globals"); - var globalsFile = Directory.EnumerateFiles(root, "*" + PostmanEnvironment.GlobalsSuffix) - .Concat(EnumerateFiles(globalsFolder, "*.y*ml").Where(PostmanEnvironment.IsYamlPath)) - .Concat(EnumerateFiles(globalsFolder, "*" + PostmanEnvironment.GlobalsSuffix)) - .FirstOrDefault(); + string? globalsFile = null; + try + { + LinksToNothing(root, Path.Combine(root, PostmanFolder, "globals"), workspace.LoadErrors); + globalsFile = FindGlobalsFile(root); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + workspace.LoadErrors.Add($"{Path.Combine(PostmanFolder, "globals")}: {ex.Message}"); + } + if (globalsFile is not null) { try { workspace.Globals = PostmanEnvironment.Load(globalsFile); } - catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException) + catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException or UnauthorizedAccessException) { workspace.LoadErrors.Add($"{Path.GetFileName(globalsFile)}: {ex.Message}"); } @@ -172,7 +267,8 @@ public static ApiWorkspace Open(string path) /// /// Passes to every loaded collection and environment (done when - /// loading and by ; call it after changing the setting without saving). + /// loading and by , even when saving fails; call it after changing the setting without + /// saving). /// public void ApplyYamlLineWidth() { @@ -194,7 +290,44 @@ public void ApplyYamlLineWidth() /// The settings in .termrest/settings.json under ; defaults when missing or invalid. public static WorkspaceSettings ReadSettings(string workspaceRoot) => - LoadSettings(Path.Combine(workspaceRoot, ConfigDirectoryName, "settings.json"), []); + LoadSettings(Path.Combine(workspaceRoot, ConfigDirectoryName, "settings.json"), out _); + + /// + /// The workspace folder of a file given on its own (see ): the folder that holds postman for + /// a file in postman/collections, postman/environments or postman/globals, where the workspace keeps + /// such files; else the folder the file is in. + /// + public static string RootForFile(string file) => V3Names.WorkspaceRootForFile(file); + + /// + /// The workspace folder for a path given on its own, as finds it: a file's (see + /// ), the workspace that holds a v3 collection folder, else the folder itself. + /// + public static string RootFor(string path) + { + var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + return File.Exists(full) ? RootForFile(full) + : Directory.Exists(full) && IsCollectionFolder(full) ? V3Names.WorkspaceRootFor(full) + : full; + } + + /// + /// Whether a folder given on its own is a v3 collection, opened in the workspace around it: a folder with a + /// postman folder is a workspace, unless it is in a postman/collections folder (where a collection may have a + /// folder of that name). + /// + private static bool IsCollectionFolder(string fullPath) => + (V3Names.IsInCollectionsFolder(fullPath) || !Directory.Exists(Path.Combine(fullPath, PostmanFolder))) && V3Names.IsCollectionDirectory(fullPath); + + /// The globals file of the workspace in , if it has one: the first one found. + private static string? FindGlobalsFile(string root) + { + var globalsFolder = Path.Combine(root, PostmanFolder, "globals"); + return Directory.EnumerateFiles(root, "*" + PostmanEnvironment.GlobalsSuffix) + .Concat(EnumerateFiles(globalsFolder, "*.y*ml").Where(PostmanEnvironment.IsYamlPath)) + .Concat(EnumerateFiles(globalsFolder, "*" + PostmanEnvironment.GlobalsSuffix)) + .FirstOrDefault(); + } public const string PostmanFolder = "postman"; @@ -217,6 +350,107 @@ private static IEnumerable EnumerateFiles(string directory, string patte private static IEnumerable EnumerateDirectories(string directory) => Directory.Exists(directory) ? Directory.EnumerateDirectories(directory).Where(d => !Path.GetFileName(d).StartsWith('.')) : []; + /// + /// The collection files and v3 collection folders of the workspace in , and the one that was opened. + /// A folder of postman/collections that cannot be listed (a link to a folder that is gone, another user's folder) is + /// kept: loading it fails and says why, as for a file that cannot be read. When postman/collections itself cannot be + /// listed, that is a load error in ; neither ends the whole workspace. + /// + private static IEnumerable EnumerateCollections(string root, string? opened, List errors) + { + var collectionsFolder = Path.Combine(root, PostmanFolder, "collections"); + var collectionFiles = Directory.EnumerateFiles(root, "*" + PostmanCollection.FileSuffix); + + // v3 collection folders: postman/collections/*, plus collection folders kept directly in the workspace. + var inCollectionsFolder = Listing(root, collectionsFolder, errors, () => + { + var gone = ReportLinksToNothing(collectionsFolder, errors); + return EnumerateFiles(collectionsFolder, "*" + PostmanCollection.FileSuffix) + .Concat(EnumerateDirectories(collectionsFolder).Where(d => !gone.Contains(d)).Where(MayBeCollection)); + }); + var collectionFolders = EnumerateDirectories(root).Where(d => !Path.GetFileName(d).Equals(PostmanFolder, StringComparison.OrdinalIgnoreCase) + && File.Exists(V3Names.DefinitionPath(d))); + return collectionFiles.Concat(inCollectionsFolder).Concat(collectionFolders).Concat(opened is null ? [] : [opened]).Distinct(StringComparer.OrdinalIgnoreCase); + + static bool MayBeCollection(string directory) + { + try + { + return V3Names.IsCollectionDirectory(directory); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return true; + } + } + } + + /// + /// What finds in , a folder of the workspace; when the folder cannot be + /// listed, or is a link to a folder that is not there, nothing, and a load error in . + /// + private static List Listing(string root, string folder, List errors, Func> list) + { + try + { + return LinksToNothing(root, folder, errors) ? [] : [.. list()]; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + errors.Add($"{Path.GetRelativePath(root, folder)}: {ex.Message}"); + return []; + } + } + + /// + /// Whether is a link to something that is not there, which a load error in + /// then names (on Linux and macOS such a link is not listed as a folder: it would be left out + /// without a word). + /// + private static bool LinksToNothing(string root, string path, List errors) + { + try + { + // Where it finally leads: on Linux and macOS, File.Exists and Path.Exists are true for the link itself. + var link = new FileInfo(path); + if (link.LinkTarget is { } target && link.ResolveLinkTarget(returnFinalTarget: true) is { Exists: false }) + { + errors.Add($"{Path.GetRelativePath(root, path)}: it links to {target}, which is not there."); + return true; + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // listing it says what is wrong + } + + return false; + } + + /// + /// Load errors for the links of (postman/collections) to collection folders that are not + /// there, a repository that was moved, say; returns them. Links to collection files are files, which fail to load. + /// + private static HashSet ReportLinksToNothing(string folder, List errors) + { + var gone = new HashSet(StringComparer.Ordinal); + if (!Directory.Exists(folder)) + { + return gone; + } + + foreach (var entry in Directory.EnumerateFileSystemEntries(folder)) + { + var name = Path.GetFileName(entry); + if (!name.StartsWith('.') && !name.EndsWith(PostmanCollection.FileSuffix, StringComparison.OrdinalIgnoreCase) && LinksToNothing(folder, entry, errors)) + { + gone.Add(entry); + } + } + + return gone; + } + /// Creates a collection: a v2.1 JSON file, or a v3 folder under postman/collections (see ). public PostmanCollection CreateCollection(string name, bool? v3 = null) { @@ -246,6 +480,12 @@ public PostmanEnvironment CreateEnvironment(string name) return environment; } + /// + /// The file or folder name for a collection or environment called , as the workspace names those + /// it creates in the v3 layout: characters invalid on any OS, and leading dots (which would hide it), become "-". + /// + public static string SafeFileName(string name) => V3Names.Safe(name); + private static string UniqueFolder(string parent, string safe) { var taken = new HashSet(EnumerateDirectories(parent).Select(Path.GetFileName).OfType(), StringComparer.OrdinalIgnoreCase); @@ -260,12 +500,22 @@ private static string UniqueFile(string folder, string safe, string suffix) /// Copies an exported Postman collection into the workspace and loads it. /// - /// A workspace that creates collections in the v3 layout gets a YAML folder under postman/collections, as - /// Postman's Git-connected workspaces do. A file that is already loaded is reloaded from disk; that is refused - /// while it has unsaved changes. + /// A collection where the workspace keeps collections (where loads them) is loaded in place; any + /// other is copied in, or, in a workspace that creates collections in the v3 layout, converted into a YAML folder + /// under postman/collections, as Postman's Git-connected workspaces do. A file that is already loaded is + /// reloaded from disk; that is refused while it has unsaved changes. /// - public PostmanCollection ImportCollection(string sourcePath) + public PostmanCollection ImportCollection(string sourcePath) => ImportCollection(sourcePath, out _); + + /// + /// The exported collection. + /// + /// The secret variables whose values were left out, as the collection was converted into the v3 layout (see + /// ). + /// + public PostmanCollection ImportCollection(string sourcePath, out List secretValuesLeftOut) { + secretValuesLeftOut = []; if (FindCollection(sourcePath) is { } loaded) { ThrowIfDirty(loaded.IsDirty, loaded.Name); @@ -273,10 +523,11 @@ public PostmanCollection ImportCollection(string sourcePath) } var collection = PostmanCollection.Load(sourcePath); - if (!IsInside(sourcePath)) + if (!IsCollectionLocation(Path.TrimEndingDirectorySeparator(Path.GetFullPath(sourcePath)))) { if (UsesV3Layout && !collection.IsV3) { + secretValuesLeftOut = collection.SecretValuesLeftOutOfV3(); collection = collection.ConvertToV3(UniqueFolder(Path.Combine(RootPath, PostmanFolder, "collections"), V3Names.Safe(collection.Name)), Settings.YamlLineWidth); } else @@ -292,11 +543,30 @@ public PostmanCollection ImportCollection(string sourcePath) return collection; } + /// Whether loads the file or v3 collection folder at as a collection. + private bool IsCollectionLocation(string fullPath) + { + var folder = Path.GetDirectoryName(fullPath); + var inRoot = string.Equals(folder, RootPath, StringComparison.OrdinalIgnoreCase); + var inCollections = string.Equals(folder, Path.Combine(RootPath, PostmanFolder, "collections"), StringComparison.OrdinalIgnoreCase); + if (!Directory.Exists(fullPath)) + { + return (inRoot || inCollections) && fullPath.EndsWith(PostmanCollection.FileSuffix, StringComparison.OrdinalIgnoreCase); + } + + var name = Path.GetFileName(fullPath); + return !name.StartsWith('.') && (inCollections + ? V3Names.IsCollectionDirectory(fullPath) + : inRoot && !name.Equals(PostmanFolder, StringComparison.OrdinalIgnoreCase) && File.Exists(V3Names.DefinitionPath(fullPath))); + } + /// The loaded collection stored in , if any. public PostmanCollection? FindCollection(string path) { - var fullPath = Path.GetFullPath(path); - return Collections.FirstOrDefault(c => c.FilePath is { } file && string.Equals(Path.GetFullPath(file), fullPath, StringComparison.OrdinalIgnoreCase)); + // A folder may be given with a trailing separator (as shells complete it); v3 collections are stored without one. + var fullPath = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + return Collections.FirstOrDefault(c => c.FilePath is { } file + && string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(file)), fullPath, StringComparison.OrdinalIgnoreCase)); } /// Re-reads a collection from disk in place of the loaded copy, discarding its unsaved changes. @@ -314,7 +584,15 @@ public PostmanCollection ReloadCollection(PostmanCollection collection) return reloaded; } - /// A file that is already loaded is reloaded from disk; that is refused while it has unsaved changes. + /// Adds an environment file to the workspace and loads it. + /// + /// A file where the workspace keeps environments is loaded in place; any other is saved as a new environment of the + /// workspace, in its format (YAML under postman/environments in the v3 layout, else a JSON file), converted + /// when needed. A file that is already loaded is reloaded from disk; that is refused while it has unsaved changes. + /// A globals file (a Postman globals export) becomes the workspace's the same way, saved where + /// the workspace keeps globals (postman/globals/workspace.globals.yaml in the v3 layout, else + /// workspace.postman_globals.json); that is refused while the workspace has a globals file of its own. + /// public PostmanEnvironment ImportEnvironment(string sourcePath) { var fullSource = Path.GetFullPath(sourcePath); @@ -327,19 +605,58 @@ public PostmanEnvironment ImportEnvironment(string sourcePath) return Environments[loadedIndex] = reloaded; } - var environment = PostmanEnvironment.Load(sourcePath); - var target = IsInside(sourcePath) ? fullSource : UniquePath(environment.Name, PostmanEnvironment.EnvironmentSuffix); - if (!string.Equals(fullSource, target, StringComparison.OrdinalIgnoreCase)) + if (Globals?.FilePath is { } globalsFile && string.Equals(Path.GetFullPath(globalsFile), fullSource, StringComparison.OrdinalIgnoreCase)) { - File.Copy(sourcePath, target); - environment = PostmanEnvironment.Load(target); + ThrowIfDirty(Globals.IsDirty, Globals.Name); + var reloaded = PostmanEnvironment.Load(fullSource); + reloaded.YamlLineWidth = Settings.YamlLineWidth; + return Globals = reloaded; } + var environment = PostmanEnvironment.Load(fullSource); environment.YamlLineWidth = Settings.YamlLineWidth; + if (environment.IsGlobals) + { + // The workspace uses one globals file, the first one Open finds: also one it could not read, or one added since. + var existing = Globals?.FilePath ?? FindGlobalsFile(RootPath); + if (existing is not null && !string.Equals(Path.GetFullPath(existing), fullSource, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException( + $"'{Path.GetFileName(fullSource)}' holds globals, and the workspace has globals of its own already ({Path.GetRelativePath(RootPath, existing)}). " + + "A workspace has one set of globals: edit those, or replace that file with this one."); + } + + if (existing is null) + { + environment.Save(UsesV3Layout + ? Path.Combine(RootPath, PostmanFolder, "globals", "workspace.globals.yaml") + : Path.Combine(RootPath, "workspace" + PostmanEnvironment.GlobalsSuffix)); + } + + return Globals = environment; + } + + if (!IsEnvironmentLocation(fullSource)) + { + environment.Save(UsesV3Layout + ? UniqueFile(Path.Combine(RootPath, PostmanFolder, "environments"), V3Names.Safe(environment.Name), V3Names.EnvironmentSuffix) + : UniquePath(environment.Name, PostmanEnvironment.EnvironmentSuffix)); + } + Environments.Add(environment); return environment; } + /// Whether loads the file at as an environment. + private bool IsEnvironmentLocation(string fullPath) + { + var folder = Path.GetDirectoryName(fullPath); + var environments = Path.Combine(RootPath, PostmanFolder, "environments"); + return fullPath.EndsWith(PostmanEnvironment.EnvironmentSuffix, StringComparison.OrdinalIgnoreCase) + ? string.Equals(folder, RootPath, StringComparison.OrdinalIgnoreCase) || string.Equals(folder, environments, StringComparison.OrdinalIgnoreCase) + : PostmanEnvironment.IsYamlPath(fullPath) && string.Equals(folder, environments, StringComparison.OrdinalIgnoreCase); + } + private static void ThrowIfDirty(bool isDirty, string name) { if (isDirty) @@ -348,20 +665,101 @@ private static void ThrowIfDirty(bool isDirty, string name) } } + /// + /// Saves what changed in since they were loaded or last saved into as + /// it is now: everything else in the file is kept, including settings another program (a git pull) changed meanwhile + /// and ones this version does not know. Writes nothing when nothing changed; the active environment's name and file + /// are written together. Saved or not, the settings apply for this session: + /// is passed to the loaded collections and environments first. + /// + /// + /// Refused with an while the file holds settings that could not be read when loading + /// () or cannot be read now. + /// public void SaveSettings() { - Directory.CreateDirectory(ConfigDirectory); - var json = JsonSerializer.Serialize(Settings, CoreJsonContext.Default.WorkspaceSettings); - TextFile.WriteAtomic(SettingsPath, json.Replace("\r\n", "\n", StringComparison.Ordinal), new TextFileInfo(false, true, false)); ApplyYamlLineWidth(); + var settings = Serialize(Settings); + var changed = settings.Select(p => p.Key).Union(_savedSettings.Select(p => p.Key)) + .Where(key => !JsonNode.DeepEquals(settings[key], _savedSettings[key])) + .ToList(); + if (changed.Intersect(ActiveEnvironmentKeys).Any()) + { + // The name and the file are one choice: written apart, the file could be paired with a name a git pull wrote, + // and the name decides once that file is gone. + changed = [.. changed.Union(ActiveEnvironmentKeys)]; + } + + if (changed.Count > 0) + { + ThrowIfUnreadable(SettingsPath, SettingsError, "then open the workspace again"); + var file = new JsonObject(); + if (File.Exists(SettingsPath)) + { + var (text, _) = TextFile.Read(SettingsPath); + try + { + file = PostmanJson.Parse(text) as JsonObject ?? throw new JsonException("The settings are not a JSON object."); + } + catch (JsonException ex) + { + throw Unreadable($"{SettingsPath}: {ex.Message}", "then save again", ex); // changed since loading, e.g. a merge conflict + } + } + + foreach (var key in changed) + { + if (settings[key] is { } value) + { + file[key] = value.DeepClone(); + } + else + { + file.Remove(key); // not written when null + } + } + + Directory.CreateDirectory(ConfigDirectory); + var json = file.ToJsonString(CoreJsonContext.Default.Options); + TextFile.WriteAtomic(SettingsPath, json.Replace("\r\n", "\n", StringComparison.Ordinal), new TextFileInfo(false, true, false)); + _savedSettings = settings; + } } - public void SaveCertificates() + private static JsonObject Serialize(WorkspaceSettings settings) => + (JsonObject)JsonSerializer.SerializeToNode(settings, CoreJsonContext.Default.WorkspaceSettings)!; + + /// + public void SaveCertificates() => SaveCertificates(overwriteChanged: false); + + /// + /// Saves into ; not over a file another program changed since + /// it was read (a git pull, another TermRest) unless : a + /// says so then (see ). + /// + /// Refused with an while the file holds a registry that could not be read (). + public void SaveCertificates(bool overwriteChanged) { + ThrowIfUnreadable(CertificatesPath, CertificatesError, "then open the workspace again"); Directory.CreateDirectory(ConfigDirectory); - Certificates.Save(CertificatesPath); + Certificates.Save(CertificatesPath, overwriteChanged); + } + + /// Reads again in place of (empty when the file is gone). + public void ReloadCertificates() => Certificates = CertificateRegistry.LoadOrEmpty(CertificatesPath, RootPath); + + /// Refuses to save over a file that could not be read when it was loaded: saving would lose what it holds. + internal static void ThrowIfUnreadable(string path, string? loadError, string then) + { + if (loadError is not null && File.Exists(path)) + { + throw Unreadable(loadError, then); + } } + private static IOException Unreadable(string error, string then, Exception? inner = null) => + new($"{error}\nTermRest could not read this file, so it did not save over it: that would lose what it holds. Fix or delete it, {then}.", inner); + public void SaveAll() { foreach (var collection in Collections.Where(c => c.IsDirty)) @@ -382,28 +780,29 @@ public void SaveAll() public string ResolvePath(string path) => Path.IsPathRooted(path) ? path : Path.GetFullPath(Path.Combine(RootPath, path)); - private bool IsInside(string path) => - string.Equals(Path.GetDirectoryName(Path.GetFullPath(path)), RootPath, StringComparison.OrdinalIgnoreCase); - + /// + /// A new file in the workspace folder for , named as says, so it is + /// valid on every OS (a workspace is shared through Git), and unique ignoring case ("Name (2)"), as Windows and macOS + /// tell names apart. + /// private string UniquePath(string name, string suffix) { - var safe = string.Concat(name.Select(c => Path.GetInvalidFileNameChars().Contains(c) || c is '/' or '\\' or ':' ? '_' : c)).Trim(); - if (safe.Length == 0) - { - safe = "untitled"; - } - - var candidate = Path.Combine(RootPath, safe + suffix); - for (var i = 2; File.Exists(candidate); i++) + var safe = V3Names.Safe(name); + var taken = new HashSet( + Directory.Exists(RootPath) ? Directory.EnumerateFileSystemEntries(RootPath).Select(Path.GetFileName).OfType() : [], + StringComparer.OrdinalIgnoreCase); + var candidate = safe + suffix; + for (var i = 2; taken.Contains(candidate); i++) { - candidate = Path.Combine(RootPath, $"{safe} ({i}){suffix}"); + candidate = $"{safe} ({i}){suffix}"; } - return candidate; + return Path.Combine(RootPath, candidate); } - private static WorkspaceSettings LoadSettings(string path, List errors) + private static WorkspaceSettings LoadSettings(string path, out string? error) { + error = null; if (!File.Exists(path)) { return new WorkspaceSettings(); @@ -414,10 +813,23 @@ private static WorkspaceSettings LoadSettings(string path, List errors) var (text, _) = TextFile.Read(path); return JsonSerializer.Deserialize(text, CoreJsonContext.Default.WorkspaceSettings) ?? new WorkspaceSettings(); } - catch (Exception ex) when (ex is JsonException or IOException) + catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) { - errors.Add($"{path}: {ex.Message}"); + error = $"{path}: {ex.Message}"; return new WorkspaceSettings(); } } } + +/// Which collections loads (parsing them is most of the work). +public enum CollectionLoading +{ + /// Every collection of the workspace (and the one opened, wherever it is). + All, + + /// Only the collection file or v3 collection folder that was opened; every collection when a workspace folder was. + Requested, + + /// None, for what needs only the workspace folder, its settings, certificates and environments. + None, +} diff --git a/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs b/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs index 6eccc49..10795fb 100644 --- a/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs +++ b/src/TermRest.Core/Workspace/RequestRunner.Scripts.cs @@ -1,9 +1,13 @@ +using System.Text; +using System.Text.Json; using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Metadata; using TermRest.Core.Http; using TermRest.Core.Json; using TermRest.Core.Model; using TermRest.Core.Postman; using TermRest.Core.Scripting; +using TermRest.Core.Variables; namespace TermRest.Core.Workspace; @@ -12,6 +16,10 @@ namespace TermRest.Core.Workspace; // per language; a request runs those of one language only (ScriptPlan), one at a time, in one runtime. public sealed partial class RequestRunner { + /// A response body as bytes (base64 for scripts): writes it in parts, with no copy as text. + private static readonly JsonTypeInfo BodyBytes = JsonMetadataServices.CreateValueInfo( + new JsonSerializerOptions { TypeInfoResolver = JsonTypeInfoResolver.Combine() }, JsonMetadataServices.ByteArrayConverter); + private readonly Lock _scriptLock = new(); private readonly Dictionary _runtimes = new(StringComparer.Ordinal); private readonly Dictionary _workers = new(StringComparer.Ordinal); @@ -30,6 +38,12 @@ public sealed partial class RequestRunner /// public bool RequireScriptRuntimes { get; set; } = true; + /// + /// Why the user's settings, which choose the runtimes and the language order, could not be read by + /// ; null when they could (or there are none). Their defaults are used then. + /// + public string? UserSettingsError { get; private set; } + /// The Python that runs Python scripts; null when none is chosen. public string? PythonInterpreter => GetRuntime(ScriptLanguage.Python); @@ -87,13 +101,14 @@ public IReadOnlyList RunningRuntimes /// and (CLI --python, --javascript, /// --csharp, --powershell), else the ones chosen for this workspace in the user's settings (Tools › /// Scripts in the full-screen UI); and the language order: first (CLI - /// --script-order), then the user's. + /// --script-order), then the user's. When the user's settings cannot be read, see . /// /// Overrides the user's configuration folder (tests, portable setups). public void ConfigureScripts(string? python = null, string? javaScript = null, string? cSharp = null, string? powerShell = null, string? userSettingsDirectory = null, IEnumerable? scriptOrder = null) { var settings = UserSettings.Load(userSettingsDirectory); + UserSettingsError = settings.LoadError; Choose(ScriptLanguage.Python, python); Choose(ScriptLanguage.JavaScript, javaScript); Choose(ScriptLanguage.CSharp, cSharp); @@ -139,7 +154,10 @@ public void SetRuntime(string language, string? runtime) public void SetPowerShellRuntime(string? pwsh) => SetRuntime(ScriptLanguage.PowerShell, pwsh); - /// A command name (python3, node, dotnet, pwsh) is looked up on PATH; a relative path is relative to the workspace folder. + /// + /// A command name (python3, node, dotnet, pwsh) stays as it is, to be looked up on PATH only + /// when it starts (); a relative path is relative to the workspace folder. + /// public string ResolveRuntime(string runtime) { runtime = runtime.Trim().Trim('"'); @@ -176,37 +194,43 @@ public void StopScripts(bool compilerServer = false) /// request run first: they can set variables and change the request. A failed one stops the request: it is not sent. /// The request is then prepared ( sees it before it goes out) and sent, and the test /// scripts run on the response, in the same order. Only then is it recorded in and - /// , with what the scripts did in . + /// , with what the scripts did in ; values they kept in + /// variables typed secret or named like secrets count among the request's secrets there (a token from a login). /// The scripts that run are those of one language (), so one runtime runs them, one after /// the other. When no language has all the scripts the request runs, it is not sent. + /// The request is as it is, and runs in the chosen, when this is + /// called: editing the request or switching the environment while it runs changes later requests only. /// Without scripts this is exactly and send. /// public async Task SendAsync(PostmanCollection collection, RequestNode? node, HttpRequestSpec spec, Action? prepared, CancellationToken cancellationToken = default) { // No ConfigureAwait(false) here either: UI callers resume on their own thread. + var environment = Environment; var plan = ScriptsEnabled ? PlanScripts(collection, node, spec.Scripts, spec.ScriptSettings) : ScriptPlan.None; if (plan.IsEmpty && plan.Error is null && plan.Notes.Count == 0) { - var request = Prepare(collection, node, spec); + var request = Prepare(environment, collection, node, spec, spec, null); prepared?.Invoke(request); - return await SendAsync(request, cancellationToken).ConfigureAwait(true); + return await SendAsync(environment, request, cancellationToken).ConfigureAwait(true); } + // Copied before the scripts run: the caller's request may be edited meanwhile (the full-screen UI's editor stays open). + var source = spec.Clone(); var results = new ScriptResults(); results.Notes.AddRange(plan.Notes); var local = new Dictionary(StringComparer.Ordinal); - var working = spec; + var working = source; if (plan.Error is { } planError) { - results.Error = new ScriptError("", planError); + results.Error = new ScriptError("", planError) { NotRun = true }; } else if (plan.PreRequest.Count > 0) { - working = spec.Clone(); + working = source.Clone(); var request = RequestToSend(working, node?.Name); - var reply = await RunScriptsAsync("prerequest", [.. plan.PreRequest], collection, local, request, null, node?.Name, results, cancellationToken) - .ConfigureAwait(true); + var reply = await RunScriptsAsync("prerequest", [.. plan.PreRequest], environment, collection, local, request, null, node?.Name, results, + cancellationToken).ConfigureAwait(true); if (reply?["request"] is JsonObject edited) { ApplyRequestEdits(edited, request, working, results); @@ -215,7 +239,7 @@ public async Task SendAsync(PostmanCollection collection, RequestN if (results.Error is not null || cancellationToken.IsCancellationRequested) { - var request = Prepare(collection, node, spec); + var request = Prepare(environment, collection, node, source, source, null); prepared?.Invoke(request); var notSent = new HttpExchange(request) { Scripts = results }; if (results.Error is { } error) @@ -232,18 +256,24 @@ public async Task SendAsync(PostmanCollection collection, RequestN return notSent; // nothing was sent: not kept in history or recordings } - var ready = Prepare(collection, node, working, spec, local); + var ready = Prepare(environment, collection, node, working, source, local); prepared?.Invoke(ready); var exchange = await Executor.SendAsync(ready, cancellationToken).ConfigureAwait(true); exchange.Scripts = results; if (plan.PostResponse.Count > 0 && exchange.Response is not null && !exchange.Cancelled) { - await RunScriptsAsync("test", [.. plan.PostResponse], collection, local, RequestSent(exchange, node?.Name), ResponseReceived(exchange), node?.Name, - results, cancellationToken).ConfigureAwait(true); + await RunScriptsAsync("test", [.. plan.PostResponse], environment, collection, local, RequestSent(exchange, node?.Name), ResponseReceived(exchange), + node?.Name, results, cancellationToken).ConfigureAwait(true); + + // What they kept in secret variables or variables named like secrets (a token from a login response) is + // redacted in this very exchange too, not only in later ones. + var resolver = CreateResolver(environment, collection, local); + exchange.Request.AddSecretValues(SecretVariableValues(environment, collection, resolver)); + exchange.Request.AddSensitiveValues(VariablesNamedLikeSecrets(environment, collection, resolver, local)); } - Record(exchange); - Recorder?.Record(exchange, Environment?.Name); + Record(exchange, environment?.Name); + Recorder?.Record(exchange, environment?.Name); return exchange; } @@ -265,7 +295,8 @@ public ScriptPlan PlanScripts(PostmanCollection collection, RequestNode? node, S } /// Runs the scripts of one phase, all in one language, and takes in what they did; null when they did not run. - private async Task RunScriptsAsync(string phase, List scripts, PostmanCollection collection, + /// The request's environment (see ): the scripts read and set its variables. + private async Task RunScriptsAsync(string phase, List scripts, PostmanEnvironment? environment, PostmanCollection collection, Dictionary local, JsonObject request, JsonObject? response, string? requestName, ScriptResults results, CancellationToken cancellationToken) { @@ -287,7 +318,7 @@ public ScriptPlan PlanScripts(PostmanCollection collection, RequestNode? node, S }; results.Error ??= new ScriptError("", $"These scripts need {needed}, and none is chosen for this workspace: pass {ScriptLanguage.Option(language)} " + - "(or --no-scripts), or choose one in the full-screen UI (Tools › Scripts…)."); + "(or --no-scripts), or choose one in the full-screen UI (Tools › Scripts…).") { NotRun = true }; } else { @@ -313,14 +344,20 @@ public ScriptPlan PlanScripts(PostmanCollection collection, RequestNode? node, S ["scripts"] = PostmanJson.ToJsonArray(scripts.Select(s => (JsonNode?)new JsonObject { ["name"] = s.Name, ["code"] = s.Code })), ["variables"] = new JsonObject { - ["environment"] = Values(Environment?.Values, Environment is { } environment ? Session.Find(environment) : null), + ["environment"] = Values(environment?.Values, environment is not null ? Session.Find(environment) : null), ["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), }, - ["request"] = request.DeepClone(), - ["response"] = response?.DeepClone(), - ["info"] = new JsonObject { ["request_name"] = requestName, ["collection"] = collection.Name, ["environment"] = Environment?.Name }, + ["request"] = request, + ["response"] = response, + ["info"] = new JsonObject { ["request_name"] = requestName, ["collection"] = collection.Name, ["environment"] = environment?.Name }, + ["dynamic"] = new JsonObject + { + ["firstNames"] = PostmanJson.ToJsonArray(VariableResolver.FirstNames.Select(n => (JsonNode?)n)), + ["lastNames"] = PostmanJson.ToJsonArray(VariableResolver.LastNames.Select(n => (JsonNode?)n)), + ["words"] = PostmanJson.ToJsonArray(VariableResolver.Words.Select(n => (JsonNode?)n)), + }, }; JsonObject reply; @@ -349,7 +386,7 @@ public ScriptPlan PlanScripts(PostmanCollection collection, RequestNode? node, S var error = reply["error"] as JsonObject; var failed = error is null ? -1 : scripts.FindIndex(s => s.Name == Text(error["script"])); results.Ran += failed < 0 ? scripts.Count : failed + 1; - ApplyVariableChanges(reply["changes"] as JsonObject, collection, local, results, language); + ApplyVariableChanges(reply["changes"] as JsonObject, environment, collection, local, results, language); foreach (var test in (reply["tests"] as JsonArray)?.OfType() ?? []) { var passed = test["passed"] is JsonValue value && value.TryGetValue(out var ok) && ok; @@ -384,7 +421,8 @@ public ScriptPlan PlanScripts(PostmanCollection collection, RequestNode? node, S /// listed with the names the script's language uses (collection_variables in Python, collectionVariables /// in JavaScript, CollectionVariables in C# and PowerShell). /// - private void ApplyVariableChanges(JsonObject? changes, PostmanCollection collection, Dictionary local, ScriptResults results, string language) + private void ApplyVariableChanges(JsonObject? changes, PostmanEnvironment? environment, PostmanCollection collection, Dictionary local, + ScriptResults results, string language) { if (changes is null) { @@ -392,7 +430,7 @@ private void ApplyVariableChanges(JsonObject? changes, PostmanCollection collect } var pascal = language is ScriptLanguage.CSharp or ScriptLanguage.PowerShell; - Apply("environment", pascal ? "Environment" : "environment", () => Environment is { } environment ? Session.For(environment) : null); + Apply("environment", pascal ? "Environment" : "environment", () => environment is not null ? Session.For(environment) : null); Apply("collection", language switch { ScriptLanguage.Python => "collection_variables", @@ -465,7 +503,13 @@ private static void ApplyRequestEdits(JsonObject edited, JsonObject original, Ht } var body = Text(edited["body"]); - if (body != Text(original["body"])) + if (edited["body"] is { } bodyNode && body is null) + { + // A raw body is text: anything else would be lost, not sent. + var what = bodyNode switch { JsonObject => "an object", JsonArray => "a list", _ => bodyNode.ToJsonString() }; + results.Error ??= new ScriptError("", $"The pre-request scripts set the request body to {what}, not to text."); + } + else if (body != Text(original["body"])) { if (spec.Body.Mode is BodyMode.Raw or BodyMode.None) { @@ -519,18 +563,45 @@ private static JsonObject ResponseReceived(HttpExchange exchange) ["time"] = Math.Round(exchange.Timing.Total?.TotalMilliseconds ?? 0, 3), ["size"] = response.Body.LongLength, }; - if (BodyFormatter.LooksLikeText(response.Body, response.ContentType)) + var text = BodyFormatter.LooksLikeText(response.Body, response.ContentType) ? BodyFormatter.Decode(response.Body, response.ContentType) : null; + if (text is not null) { - json["text"] = BodyFormatter.Decode(response.Body, response.ContentType); + json["text"] = text; } - else + + // Scripts encode the text as UTF-8 for the bytes: they get the bytes as well when that would not give them back. + if (text is null || !IsUtf8Of(text, response.Body)) { - json["base64"] = Convert.ToBase64String(response.Body); + json["base64"] = JsonValue.Create(response.Body, BodyBytes); } return json; } + /// Whether are in UTF-8, compared a few KB at a time (no copy of a large body). + private static bool IsUtf8Of(string text, byte[] bytes) + { + var encoder = Encoding.UTF8.GetEncoder(); + Span buffer = stackalloc byte[4096]; + var chars = text.AsSpan(); + var offset = 0; + while (true) + { + encoder.Convert(chars, buffer, flush: true, out var used, out var written, out var completed); + if (!bytes.AsSpan(offset).StartsWith(buffer[..written])) + { + return false; + } + + offset += written; + chars = chars[used..]; + if (completed) + { + return offset == bytes.Length; + } + } + } + /// The enabled values of a scope, with the values scripts set on top (null: unset). private static JsonObject Values(IEnumerable? entries, IReadOnlyDictionary? setByScripts) { diff --git a/src/TermRest.Core/Workspace/RequestRunner.cs b/src/TermRest.Core/Workspace/RequestRunner.cs index 383f19f..04af991 100644 --- a/src/TermRest.Core/Workspace/RequestRunner.cs +++ b/src/TermRest.Core/Workspace/RequestRunner.cs @@ -40,6 +40,37 @@ public RequestRunner(ApiWorkspace workspace) public int? TimeoutOverrideMs { get; set; } + /// + /// The proxy URL of the workspace's settings that requests may use: the one the user allowed for this workspace folder + /// (read by ; saved in Tools › Settings of the full-screen UI). The settings come with the + /// repository a workspace is cloned from, and a proxy sees every request: one not allowed is not used (see ). + /// + public string? AllowedProxy { get; set; } + + /// + /// 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. + /// + public string? BlockedProxy => + Workspace.Settings.Proxy is var proxy && WorkspaceSettings.IsProxyUrl(proxy) && !string.Equals(proxy.Trim(), AllowedProxy?.Trim(), StringComparison.Ordinal) + ? proxy + : null; + + /// + /// 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 + /// ; saved in Tools › Settings of the full-screen UI), or by --allow-outside-files. + /// Otherwise see . + /// + public bool OutsideFilesAllowed { get; set; } + + /// + /// The workspace folder while is not set: requests send only its files, and open no + /// file on a network share outside it (); null when they may. + /// + public string? FilesFolder => OutsideFilesAllowed ? null : Workspace.RootPath; + /// Where sent requests are recorded; null turns recording off (see ). public HistoryStore? History { get; set; } @@ -49,19 +80,48 @@ public RequestRunner(ApiWorkspace workspace) /// Largest response body kept with a history entry. public int HistoryMaxBodyBytes { get; set; } = 256 * 1024; + /// + /// The environment requests use: , else the workspace's active one. A request reads it + /// once, when it starts, and keeps it until it is recorded, so switching while it is on its way changes later requests only. + /// public PostmanEnvironment? Environment => EnvironmentOverride ?? Workspace.ActiveEnvironment; - /// Turns history recording on or off according to the workspace settings. + /// + /// Turns history recording on or off according to the workspace settings; off while they cannot be read + /// (), since they may turn it off. + /// /// Overrides the per-user state folder (tests, portable setups). public void ConfigureHistory(string? stateDirectory = null) { var settings = Workspace.Settings; - History = settings.HistoryEnabled ? HistoryStore.ForWorkspace(Workspace.RootPath, settings.HistoryLimit, stateDirectory) : null; - HistoryMaxBodyBytes = Math.Max(0, settings.HistoryResponseKb) * 1024; + History = settings.HistoryEnabled && Workspace.SettingsError is null ? HistoryStore.ForWorkspace(Workspace.RootPath, settings.HistoryLimit, stateDirectory) : null; + HistoryMaxBodyBytes = (int)Math.Min(int.MaxValue, Math.Max(0L, settings.HistoryResponseKb) * 1024); + } + + /// + /// Sets to the proxy URL of the workspace's settings when the user's settings allow it for + /// this workspace folder (), else to none. + /// + /// 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; } + /// Sets as the user's settings say for this workspace folder. + /// Overrides the user's configuration folder (tests, portable setups). + public void ConfigureFiles(string? userSettingsDirectory = null) => + OutsideFilesAllowed = UserSettings.Load(userSettingsDirectory).AreOutsideFilesAllowed(Workspace.RootPath); + + /// The variables of as a request sent now sees them (with the current ). /// Variables scripts set for this request only (tr.variables); null unsets. - public VariableResolver CreateResolver(PostmanCollection? collection, IReadOnlyDictionary? requestVariables = null) + public VariableResolver CreateResolver(PostmanCollection? collection, IReadOnlyDictionary? requestVariables = null) => + CreateResolver(Environment, collection, requestVariables); + + /// The request's environment (see ). + private VariableResolver CreateResolver(PostmanEnvironment? environment, PostmanCollection? collection, + IReadOnlyDictionary? requestVariables) { var scopes = new List(); if (LocalVariables.Count > 0 || requestVariables is { Count: > 0 }) @@ -69,7 +129,7 @@ public VariableResolver CreateResolver(PostmanCollection? collection, IReadOnlyD scopes.Add(new OverlayScope(new DictionaryScope("local", LocalVariables), requestVariables)); } - if (Environment is { } environment) + if (environment is not null) { scopes.Add(new OverlayScope(new EntryListScope($"environment '{environment.Name}'", environment.Values), Session.Find(environment))); } @@ -98,52 +158,66 @@ public ExecutionDefaults CreateDefaults() Timeout = timeoutMs > 0 ? TimeSpan.FromMilliseconds(timeoutMs) : null, FollowRedirects = settings.FollowRedirects, MaxRedirects = settings.MaxRedirects, - Proxy = settings.Proxy, + // 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, MaxResponseBytes = Math.Max(1, settings.MaxResponseSizeMb) * 1024L * 1024L, HttpVersion = settings.HttpVersion, + FilesFolder = FilesFolder, }; } - public PreparedRequest Prepare(PostmanCollection collection, RequestNode? node, HttpRequestSpec spec) => Prepare(collection, node, spec, spec, null); + public PreparedRequest Prepare(PostmanCollection collection, RequestNode? node, HttpRequestSpec spec) => + Prepare(Environment, collection, node, spec, spec, null); + /// The request's environment (see ). /// The request to send (as changed by pre-request scripts). /// The request as written: kept in the history, so re-sending it runs its scripts again. /// Variables set by scripts for this request only. - private PreparedRequest Prepare(PostmanCollection collection, RequestNode? node, HttpRequestSpec spec, HttpRequestSpec source, - IReadOnlyDictionary? requestVariables) + private PreparedRequest Prepare(PostmanEnvironment? environment, PostmanCollection collection, RequestNode? node, HttpRequestSpec spec, + HttpRequestSpec source, IReadOnlyDictionary? requestVariables) { - var preparer = new RequestPreparer(CreateResolver(collection, requestVariables), Certificates, CreateDefaults()); + var preparer = new RequestPreparer(CreateResolver(environment, collection, requestVariables), Certificates, CreateDefaults()); var auth = node is not null ? collection.GetEffectiveAuth(node, spec) : spec.Auth ?? collection.RootNode.Auth; var prepared = preparer.Prepare(spec, auth, collection.BaseDirectory); var saved = node is not null && node.Collection == collection && collection.FilePath is not null && node.Parent is not null; - // History keeps a self-contained copy: inherited auth is stored with the request so it can be re-sent on its own. + // History keeps a self-contained copy: inherited auth is stored with the request so it can be re-sent on its own (of + // credential sets, the one its URL selected). var snapshot = source.Clone(); - snapshot.Auth ??= auth?.Clone(); + var used = prepared.AuthUsed; + var authInherited = snapshot.Auth is null && used is not null; + snapshot.Auth ??= used?.Clone(); prepared.Source = new RequestSource( snapshot, collection.FilePath is null ? null : collection.Name, saved ? node!.PathInCollection : null, - saved ? node!.Name : null); - prepared.SecretValues.UnionWith(SecretVariableValues(collection)); - prepared.SensitiveValues.UnionWith(VariablesNamedLikeSecrets(collection, preparer.Variables, requestVariables)); + saved ? node!.Name : null, + authInherited, + Workspace.FileOf(collection)); + prepared.AddSecretValues(SecretVariableValues(environment, collection, preparer.Variables)); + prepared.AddSensitiveValues(VariablesNamedLikeSecrets(environment, collection, preparer.Variables, requestVariables)); return prepared; } /// Sends a prepared request and records it in and (when on). - public async Task SendAsync(PreparedRequest prepared, CancellationToken cancellationToken = default) + public Task SendAsync(PreparedRequest prepared, CancellationToken cancellationToken = default) => + SendAsync(Environment, prepared, cancellationToken); + + /// The request's environment (see ): the history and recordings name it. + private async Task SendAsync(PostmanEnvironment? environment, PreparedRequest prepared, CancellationToken cancellationToken) { // No ConfigureAwait(false): UI callers resume on their own thread, which also records the entry. var exchange = await Executor.SendAsync(prepared, cancellationToken).ConfigureAwait(true); - Record(exchange); - Recorder?.Record(exchange, Environment?.Name); + Record(exchange, environment?.Name); + Recorder?.Record(exchange, environment?.Name); return exchange; } public Task SendAsync(PostmanCollection collection, RequestNode? node, HttpRequestSpec spec, CancellationToken cancellationToken = default) => SendAsync(collection, node, spec, null, cancellationToken); - private void Record(HttpExchange exchange) + private void Record(HttpExchange exchange, string? environment) { var request = exchange.Request; if (History is not { } history || request.Source is not { } source || exchange.Cancelled @@ -154,7 +228,7 @@ private void Record(HttpExchange exchange) try { - var entry = HistoryEntry.Create(exchange, source, Environment?.Name, HistoryMaxBodyBytes, out var body); + var entry = HistoryEntry.Create(exchange, source, environment, HistoryMaxBodyBytes, out var body); history.Add(entry, body); exchange.HistoryEntry = entry; } @@ -164,11 +238,15 @@ private void Record(HttpExchange exchange) } } - /// Values of variables typed "secret" in the environment, collection and globals, including values scripts set. - private List SecretVariableValues(PostmanCollection collection) + /// + /// Values of variables typed "secret" in the environment, collection and globals: as written, as scripts set them, and + /// as resolves them, which is the value sent (a CLI --var or a value a script set + /// for the request may take precedence, and the value may reference other variables). + /// + private List SecretVariableValues(PostmanEnvironment? environment, PostmanCollection collection, VariableResolver resolver) { var secrets = new List(); - Add(Environment?.Values, Environment is { } environment ? Session.Find(environment) : null); + Add(environment?.Values, environment is not null ? Session.Find(environment) : null); Add(collection.GetVariables(), Session.Find(collection)); Add(Workspace.Globals?.Values, Session.Globals); return secrets; @@ -188,6 +266,13 @@ void Add(IEnumerable? entries, IReadOnlyDictionary? entries, IReadOnlyDictionary /// Resolved values of variables named like credentials (password, token, apiKey … and the workspace's extra - /// names) that are not typed "secret": recordings redact them too. + /// names, with those of the , which keeps the + /// names removed from the settings since it started) that are not typed "secret": recordings redact them too. /// Values set by scripts count as well. /// - private IEnumerable VariablesNamedLikeSecrets(PostmanCollection collection, VariableResolver resolver, + private IEnumerable VariablesNamedLikeSecrets(PostmanEnvironment? environment, PostmanCollection collection, VariableResolver resolver, IReadOnlyDictionary? requestVariables) { var extraNames = SecretNames.NormalizeAll(Workspace.Settings.RecordingRedact); - IEnumerable> variables = (Environment?.Values ?? []) + if (Recorder is { } recorder) + { + extraNames.UnionWith(recorder.ExtraNames); + } + + IEnumerable> variables = (environment?.Values ?? []) .Concat(collection.GetVariables()) .Concat(Workspace.Globals?.Values ?? []) .Where(e => e.Enabled) .Select(e => new KeyValuePair(e.Key, e.Value)); variables = variables.Concat(LocalVariables.Select(v => new KeyValuePair(v.Key, v.Value))); IEnumerable?> setByScripts = - [Environment is { } environment ? Session.Find(environment) : null, Session.Find(collection), Session.Globals, requestVariables]; + [environment is not null ? Session.Find(environment) : null, Session.Find(collection), Session.Globals, requestVariables]; variables = variables.Concat(setByScripts.SelectMany(values => values ?? new Dictionary())); return variables .Where(v => !string.IsNullOrEmpty(v.Value) && SecretNames.IsSecret(v.Key, NameKind.Field, extraNames)) diff --git a/src/TermRest.Core/Workspace/UserSettings.cs b/src/TermRest.Core/Workspace/UserSettings.cs index 67fbe90..ccf4595 100644 --- a/src/TermRest.Core/Workspace/UserSettings.cs +++ b/src/TermRest.Core/Workspace/UserSettings.cs @@ -1,3 +1,5 @@ +using System.Security.Cryptography; +using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using TermRest.Core.IO; @@ -40,6 +42,27 @@ public sealed class UserSettings /// public List? ScriptLanguageOrder { get; set; } + /// + /// The proxy that the user allowed for each workspace folder (), as a SHA-256 + /// hash (sha256:…), never the proxy itself: its URL can hold a password. A workspace's settings come with the + /// repository it was cloned from, so its proxy URL is used only once allowed here, and again after each change. + /// + public Dictionary? AllowedProxies { get; set; } + + /// + /// The workspace folders whose requests may send body and form-data files from outside them. Elsewhere only a + /// workspace's own files are sent: a collection from a repository someone else wrote could otherwise send the user's + /// files (SSH keys, cloud credentials) to a server of its choosing. + /// + public List? OutsideFilesAllowed { get; set; } + + /// + /// Why could not read the file (path: problem), if it could not: these are the defaults then, + /// and does not save over the file. + /// + [JsonIgnore] + public string? LoadError { get; private set; } + /// The language order, with every language (see ). public IReadOnlyList GetScriptLanguageOrder() => ScriptLanguage.Order(ScriptLanguageOrder); @@ -99,6 +122,75 @@ private void SetRuntimes(string language, Dictionary? runtimes) } } + /// Whether is the proxy allowed for the workspace in . + public bool IsProxyAllowed(string workspaceRoot, string? proxy) + { + if (string.IsNullOrWhiteSpace(proxy) || AllowedProxies is null) + { + return false; + } + + var hash = ProxyHash(proxy); + return AllowedProxies.Any(p => SameFolder(p.Key, workspaceRoot) && string.Equals(p.Value, hash, StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Allows for the workspace in , in place of the one allowed + /// before; null or empty forgets that one. Returns false when nothing changed (there is nothing to save then). + /// + public bool AllowProxy(string workspaceRoot, string? proxy) + { + var hash = string.IsNullOrWhiteSpace(proxy) ? null : ProxyHash(proxy); + var keys = AllowedProxies?.Keys.Where(k => SameFolder(k, workspaceRoot)).ToList() ?? []; + if (hash is null ? keys.Count == 0 : keys is [var only] && string.Equals(AllowedProxies![only], hash, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + foreach (var key in keys) + { + AllowedProxies!.Remove(key); + } + + if (hash is not null) + { + AllowedProxies ??= new Dictionary(StringComparer.Ordinal); + AllowedProxies[NormalizeFolder(workspaceRoot)] = hash; + } + + AllowedProxies = AllowedProxies is { Count: 0 } ? null : AllowedProxies; + return true; + } + + private static string ProxyHash(string proxy) => "sha256:" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(proxy.Trim()))); + + /// Whether requests of the workspace in may send files from outside it. + public bool AreOutsideFilesAllowed(string workspaceRoot) => OutsideFilesAllowed?.Any(f => SameFolder(f, workspaceRoot)) == true; + + /// + /// Allows, or no longer allows, the requests of the workspace in to send files from + /// outside it. Returns false when nothing changed (there is nothing to save then). + /// + public bool AllowOutsideFiles(string workspaceRoot, bool allow) + { + if (AreOutsideFilesAllowed(workspaceRoot) == allow) + { + return false; + } + + if (allow) + { + (OutsideFilesAllowed ??= []).Add(NormalizeFolder(workspaceRoot)); + } + else + { + OutsideFilesAllowed!.RemoveAll(f => SameFolder(f, workspaceRoot)); + OutsideFilesAllowed = OutsideFilesAllowed.Count == 0 ? null : OutsideFilesAllowed; + } + + return true; + } + private static bool SameFolder(string a, string b) => string.Equals(NormalizeFolder(a), NormalizeFolder(b), OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); @@ -149,7 +241,10 @@ public static string DefaultDirectory() /// Folder with the user's custom color themes (*.json). public static string ThemesDirectory(string? directory = null) => Path.Combine(directory ?? DefaultDirectory(), "themes"); - /// Reads settings.json from (default: ); defaults when missing or invalid. + /// + /// Reads settings.json from (default: ); defaults when + /// missing or invalid (see ). + /// public static UserSettings Load(string? directory = null) { var path = Path.Combine(directory ?? DefaultDirectory(), "settings.json"); @@ -165,16 +260,19 @@ public static UserSettings Load(string? directory = null) } catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) { - return new UserSettings(); + return new UserSettings { LoadError = $"{path}: {ex.Message}" }; } } /// Writes settings.json to (default: ). + /// Refused with an while the file holds settings that could not be read (). public void Save(string? directory = null) { directory ??= DefaultDirectory(); + var path = Path.Combine(directory, "settings.json"); + ApiWorkspace.ThrowIfUnreadable(path, LoadError, "then try again"); Directory.CreateDirectory(directory); var json = JsonSerializer.Serialize(this, CoreJsonContext.Default.UserSettings).Replace("\r\n", "\n", StringComparison.Ordinal); - TextFile.WriteAtomic(Path.Combine(directory, "settings.json"), json, new TextFileInfo(false, true, false)); + TextFile.WriteAtomic(path, json, new TextFileInfo(false, true, false)); } } diff --git a/src/TermRest.Core/Workspace/WorkspaceSettings.cs b/src/TermRest.Core/Workspace/WorkspaceSettings.cs index e0d4556..d25fae3 100644 --- a/src/TermRest.Core/Workspace/WorkspaceSettings.cs +++ b/src/TermRest.Core/Workspace/WorkspaceSettings.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; using TermRest.Core.Certificates; @@ -15,6 +16,12 @@ public sealed class WorkspaceSettings /// Name of the selected environment. public string? ActiveEnvironment { get; set; } + /// + /// File of the selected environment, relative to the workspace folder with "/" separators: it tells environments of + /// the same name apart. Without it (settings of earlier versions), or when that file is not loaded, the name decides. + /// + public string? ActiveEnvironmentFile { get; set; } + /// Verify server certificates (Postman "SSL certificate verification"). Requests can override with strictSSL. public bool StrictSsl { get; set; } = true; @@ -28,9 +35,15 @@ public sealed class WorkspaceSettings public int MaxRedirects { get; set; } = 10; - /// Null/"system" uses the OS proxy settings, "none" disables proxies, otherwise a proxy URL. + /// + /// Null/"system" uses the OS proxy settings, "none" disables proxies, otherwise a proxy URL: used only once the user + /// allowed it for the workspace folder (), as this file comes with the workspace. + /// public string? Proxy { get; set; } + /// Whether names a proxy (a URL), rather than "system" or "none" (see ). + public static bool IsProxyUrl([NotNullWhen(true)] string? proxy) => proxy?.Trim().ToLowerInvariant() is not (null or "" or "system" or "none"); + /// Responses larger than this are truncated in memory. public int MaxResponseSizeMb { get; set; } = 50; diff --git a/src/TermRest.Core/Yaml/YamlFile.cs b/src/TermRest.Core/Yaml/YamlFile.cs index 19266cb..1e8a254 100644 --- a/src/TermRest.Core/Yaml/YamlFile.cs +++ b/src/TermRest.Core/Yaml/YamlFile.cs @@ -1,4 +1,5 @@ using System.Text.Json.Nodes; +using TermRest.Core.IO; namespace TermRest.Core.Yaml; @@ -37,14 +38,16 @@ public static YamlFile Parse(string text) /// The text for (LF line breaks, ending with one). New scalars are quoted like the ones /// already in this document; applies when it has none (or as many of each). /// - public string Render(JsonObject root, YamlStyle style) + /// Write anew what ends this document, which has no final line break, with a block scalar + /// that keeps its last line break (|), as copied before more lines its value would change. + public string Render(JsonObject root, YamlStyle style, bool rewriteEndBlock = false) { if (Tree.Root is not YamlMappingNode { IsFlow: false, Entries.Count: > 0 } mapping) { return Write(root, style, header: Tree.Root is null ? Tree.Text : null); } - var writer = new YamlWriter(YamlStyle.Detect([Tree], style), Tree); + var writer = new YamlWriter(YamlStyle.Detect([Tree], style), Tree, rewriteEndBlock); var entries = mapping.Entries; writer.Append(Tree.Lines(0, entries[0].FirstLine - 1)); @@ -60,13 +63,13 @@ public string Render(JsonObject root, YamlStyle style) var entry = mapping.Find(key); if (entry is not null && leading.TryGetValue(entry, out var trivia)) { - writer.Append(trivia); + writer.AppendTrivia(trivia, 0); } writer.WriteEntry(key, value, 0, entry); } - writer.Append(Tree.Lines(entries[^1].LastLine + 1, Tree.LineCount - 1)); + writer.AppendTrivia(Tree.Lines(entries[^1].LastLine + 1, Tree.LineCount - 1), 0); return EnsureFinalNewline(writer.ToString()); } @@ -84,5 +87,97 @@ public static string Write(JsonObject root, YamlStyle style, string? header = nu return writer.ToString(); } + /// + /// The text to write to for , rendered over + /// (null for a new file) and read back first exactly as it will be written, so that TermRest never writes a file it + /// cannot read, or would read differently. Long values are written unwrapped when wrapping them would not read back; + /// when the text still would not, an names the file, and nothing must be written. + /// + /// The format of the file (that of a new file for one that doesn't exist yet). + /// + /// The text without its final line break, and the format to write it in (see ): + /// , so a file without a final line break stays without one, unless its last value (a block, + /// | or |+) ends with a line break, which then needs one. + /// + public static (string Text, TextFileInfo Info) WriteChecked(YamlFile? source, JsonObject root, YamlStyle style, string path, TextFileInfo info, out YamlFile written) + { + // Unchanged parts are copied first. A block scalar that ends a source without a final line break can't be copied + // before new lines (its value would gain one): the last attempts write it anew. + List<(YamlStyle Style, bool RewriteEndBlock)> attempts = [(style, false), (style.WithLineWidth(0), false)]; + if (source is not null && !source.Tree.Text.EndsWith('\n')) + { + attempts.AddRange([(style, true), (style.WithLineWidth(0), true)]); + } + + var tried = new HashSet(StringComparer.Ordinal); + var problem = ""; + foreach (var (attempt, rewriteEndBlock) in attempts) + { + var text = source is null ? Write(root, attempt) : source.Render(root, attempt, rewriteEndBlock); + if (!tried.Add(text)) + { + continue; + } + + if (HasLoneSurrogate(text)) + { + // UTF-8 can't hold half of a character (a value wrapped inside an emoji): it would be written as U+FFFD. + problem = "it would hold half of a character"; + continue; + } + + var full = text.EndsWith('\n') ? text : text + "\n"; + var trimmed = full[..^1]; + if (!info.HasTrailingNewline && ReadsBack(trimmed, root, out written, ref problem)) + { + return (trimmed, info); + } + + if (ReadsBack(full, root, out written, ref problem)) + { + return (trimmed, info.HasTrailingNewline ? info : info with { HasTrailingNewline = true }); + } + } + + throw new IOException($"'{path}' was not saved: TermRest cannot write it as YAML that reads back unchanged ({problem})."); + } + + private static bool ReadsBack(string text, JsonObject root, out YamlFile written, ref string problem) + { + try + { + written = Parse(text); + if (JsonNode.DeepEquals(written.Json, root)) + { + return true; + } + + problem = "it would read back changed"; + } + catch (YamlFormatException ex) + { + problem = ex.Message; + } + + written = null!; + return false; + } + + private static bool HasLoneSurrogate(ReadOnlySpan text) + { + for (var at = text.IndexOfAnyInRange('\uD800', '\uDFFF'); at >= 0;) + { + if (!char.IsHighSurrogate(text[at]) || at + 1 >= text.Length || !char.IsLowSurrogate(text[at + 1])) + { + return true; + } + + var next = text[(at + 2)..].IndexOfAnyInRange('\uD800', '\uDFFF'); + at = next < 0 ? -1 : at + 2 + next; + } + + return false; + } + private static string EnsureFinalNewline(string text) => text.Length == 0 || text.EndsWith('\n') ? text : text + "\n"; } diff --git a/src/TermRest.Core/Yaml/YamlFolding.cs b/src/TermRest.Core/Yaml/YamlFolding.cs index ecc4481..60f438d 100644 --- a/src/TermRest.Core/Yaml/YamlFolding.cs +++ b/src/TermRest.Core/Yaml/YamlFolding.cs @@ -54,13 +54,15 @@ public static string FoldDoubleQuoted(string quoted, int indent, int? indentAtSt var builder = new StringBuilder(quoted.Length + 16); var start = 0; + var escapedLeadingSpace = -1; for (var i = 0; i < quoted.Length; i++) { var ch = quoted[i]; if (ch == ' ' && At(quoted, i + 1) == '\\' && At(quoted, i + 2) == 'n') { - // A space before a line break would be lost when the break is folded: escape it. - builder.Append(quoted, start, i - start).Append("\\ "); + // A space before a line break would be lost when the break is folded: escape it, unless it is a line's + // only character, which is escaped already as its leading space (the library escapes it twice). + builder.Append(quoted, start, i - start).Append(i == escapedLeadingSpace ? " " : "\\ "); i += 1; start = i; ch = '\\'; @@ -89,6 +91,7 @@ public static string FoldDoubleQuoted(string quoted, int indent, int? indentAtSt if (At(quoted, i + 2) == ' ') { builder.Append('\\'); // leading spaces of a continuation line would be dropped + escapedLeadingSpace = i + 2; } i += 1; @@ -136,8 +139,9 @@ public static bool LineLengthOverLimit(string text, int lineWidth, int indent) /// /// (which must be writable as a block scalar) as a folded block: the > header line and the /// content lines indented by , without a final line break. Returns null for text that - /// cannot be folded without changing it (its first line starts with white space), and, with - /// , when a line cannot be broken to fit; a literal block is written then. + /// cannot be folded without changing it (its first line starts with white space, or a line of only white space + /// follows a more-indented one), and, with , when a line cannot be broken to + /// fit; a literal block is written then. /// public static string? FoldedBlock(string text, int indent, int lineWidth, bool literalWhenUnfoldable) { @@ -201,6 +205,11 @@ public static bool LineLengthOverLimit(string text, int lineWidth, int indent) start = LineBreaks().Replace(start, m => m.Value + indentText); } + if (HasWhiteLineAfterMoreIndented(value)) + { + return null; + } + var header = (startsWithSpace ? indent > 0 ? "2" : "1" : "") + chomp; // A single line break folds into a space, so every break is doubled, except around more-indented lines, which are @@ -327,6 +336,11 @@ private static string FoldLines(string text, int indent, Mode mode, int? indentA j = escape - 1; // after skipped white space the library can land inside one } + if (j >= 1 && char.IsHighSurrogate(text[j])) + { + j--; // nor between the two halves of a character (an emoji): apart, neither can be written + } + if (j < 1 || (folds.Count > 0 && j <= folds[^1])) { // Only when the indentation leaves no room at all: keep the line long. @@ -383,6 +397,31 @@ private static string FoldLines(string text, int indent, Mode mode, int? indentA return result.ToString(); } + /// + /// Whether a line of only white space follows a more-indented line (empty lines between them or not). The library + /// takes it for an empty line and keeps the doubled line break before it, which adds an empty line to the text. + /// + private static bool HasWhiteLineAfterMoreIndented(string text) + { + var moreIndented = false; + foreach (var line in text.AsSpan().EnumerateLines()) + { + if (line.IsEmpty) + { + continue; + } + + if (moreIndented && line.TrimStart(" \t").IsEmpty) + { + return true; + } + + moreIndented = line[0] is ' ' or '\t'; + } + + return false; + } + /// /// Skips the more-indented lines (white space after the indentation) that follow the line break at /// ; returns the index of the last line break skipped. diff --git a/src/TermRest.Core/Yaml/YamlTree.cs b/src/TermRest.Core/Yaml/YamlTree.cs index 981e259..7c688dd 100644 --- a/src/TermRest.Core/Yaml/YamlTree.cs +++ b/src/TermRest.Core/Yaml/YamlTree.cs @@ -122,22 +122,27 @@ internal sealed class YamlSequenceNode : YamlNode /// A parsed YAML document: LF-normalized source text, its line table and the root node. internal sealed class YamlTree { + /// Collections nested deeper are refused, as in JSON input: reading them would overflow the stack. + private const int MaxDepth = 256; + private readonly int[] _lineStarts; private YamlTree(string text, YamlNode? root) { Text = text; Root = root; + _lineStarts = LineStarts(text); + } + + private static int[] LineStarts(string text) + { var starts = new List { 0 }; - for (var i = 0; i < text.Length; i++) + for (var i = text.IndexOf('\n'); i >= 0; i = text.IndexOf('\n', i + 1)) { - if (text[i] == '\n') - { - starts.Add(i + 1); - } + starts.Add(i + 1); } - _lineStarts = [.. starts]; + return [.. starts]; } public string Text { get; } @@ -180,31 +185,112 @@ public bool StartsLine(int index) /// Parses one YAML document. The text must use LF line breaks. public static YamlTree Parse(string text) { - try + var parsed = text; + int[]? removed = null; // per line: the spaces left out of parsed (see BlankLeadingLines) + while (true) { - var parser = new Parser(new Scanner(new StringReader(text), skipComments: true)); - Expect(parser); - if (parser.Current is StreamEnd) + try { - return new YamlTree(text, null); + var parser = new Parser(new Scanner(new StringReader(parsed), skipComments: true)); + Expect(parser); + if (parser.Current is StreamEnd) + { + return new YamlTree(text, null); + } + + Expect(parser); + var root = ReadNode(parser, 0, removed is null ? m => (int)m.Index : PositionsIn(text, parsed, removed)); + Expect(parser); + if (parser.Current is not StreamEnd) + { + throw new YamlFormatException("Only one YAML document per file is supported."); + } + + var tree = new YamlTree(text, root); + tree.AssignLines(root); + return tree; } + catch (YamlException ex) + { + if (ex is SemanticErrorException && ex.Message.Contains("extra spaces in first line", StringComparison.Ordinal) + && BlankLeadingLines(ref parsed, ref removed, (int)ex.Start.Index)) + { + continue; + } - Expect(parser); - var root = ReadNode(parser); - Expect(parser); - if (parser.Current is not StreamEnd) + throw new YamlFormatException($"Invalid YAML at line {ex.Start.Line}, column {ex.Start.Column}: {ex.Message}", ex); + } + } + } + + /// + /// YamlDotNet refuses a literal block scalar without an indentation indicator whose first line holds only spaces, as + /// Postman's YAML library writes a value that starts with an empty line (code: |-, then a line with just the + /// indentation). YAML allows it: the spaces of the empty lines before a block's first line of content are no part of + /// the value. So those lines are parsed without their spaces. is where the scanner stopped: + /// the start of the block's first non-empty line; the lines above it, up to the block's header, hold spaces only. + /// Returns false when there is nothing to leave out. + /// + private static bool BlankLeadingLines(ref string parsed, ref int[]? removed, int stop) + { + if (stop <= 0 || stop > parsed.Length || parsed[stop - 1] != '\n') + { + return false; + } + + var line = parsed.AsSpan(0, stop).Count('\n'); // the stop line's number + var blank = new List<(int Line, int Start, int Length)>(); + for (var end = stop - 1; end > 0;) + { + var start = parsed.LastIndexOf('\n', end - 1) + 1; + line--; + if (parsed.AsSpan(start, end - start).ContainsAnyExcept(' ')) { - throw new YamlFormatException("Only one YAML document per file is supported."); + break; // the block's header } - var tree = new YamlTree(text, root); - tree.AssignLines(root); - return tree; + if (end > start) + { + blank.Add((line, start, end - start)); + } + + end = start - 1; + } + + if (blank.Count == 0) + { + return false; } - catch (YamlException ex) + + removed ??= new int[parsed.AsSpan().Count('\n') + 1]; + var builder = new System.Text.StringBuilder(parsed.Length); + var copied = 0; + foreach (var (number, start, length) in Enumerable.Reverse(blank)) { - throw new YamlFormatException($"Invalid YAML at line {ex.Start.Line}, column {ex.Start.Column}: {ex.Message}", ex); + builder.Append(parsed, copied, start - copied); + copied = start + length; + removed[number] += length; } + + parsed = builder.Append(parsed, copied, parsed.Length - copied).ToString(); + return true; + } + + /// + /// Where a position in is in : the same lines, but some started with + /// spaces parsed leaves out (, per line). + /// + private static Func PositionsIn(string text, string parsed, int[] removed) + { + var parsedStarts = LineStarts(parsed); + var textStarts = LineStarts(text); + return mark => + { + var index = (int)mark.Index; + var line = Array.BinarySearch(parsedStarts, index); + line = line >= 0 ? line : ~line - 1; + return textStarts[line] + removed[line] + (index - parsedStarts[line]); + }; } private static void Expect(Parser parser) @@ -223,7 +309,7 @@ private static void Expect(Parser parser) parser.MoveNext(); } - private static YamlNode ReadNode(Parser parser) + private static YamlNode ReadNode(Parser parser, int depth, Func at) { switch (parser.Current) { @@ -242,30 +328,31 @@ private static YamlNode ReadNode(Parser parser) _ => YamlScalarStyle.Plain, }, Tag = scalar.Tag.IsEmpty || scalar.Tag.IsNonSpecific ? null : NormalizeTag(scalar.Tag.Value), - Start = (int)scalar.Start.Index, - End = (int)scalar.End.Index, + Start = at(scalar.Start), + End = at(scalar.End), }; } case MappingStart start: { - var mapping = new YamlMappingNode { IsFlow = start.Style == MappingStyle.Flow, Start = (int)start.Start.Index, End = (int)start.End.Index }; + CheckDepth(depth, start); + var mapping = new YamlMappingNode { IsFlow = start.Style == MappingStyle.Flow, Start = at(start.Start), End = at(start.End) }; parser.MoveNext(); while (parser.Current is not MappingEnd) { - if (ReadNode(parser) is not YamlScalarNode key) + if (ReadNode(parser, depth + 1, at) is not YamlScalarNode key) { throw new YamlFormatException("Only plain text mapping keys are supported."); } - var value = ReadNode(parser); + var value = ReadNode(parser, depth + 1, at); mapping.Entries.Add(new YamlEntry { Key = key, Value = value }); mapping.End = Math.Max(mapping.End, ContentEnd(key, value)); } if (mapping.IsFlow) { - mapping.End = (int)parser.Current!.End.Index; + mapping.End = at(parser.Current!.End); } parser.MoveNext(); @@ -274,18 +361,19 @@ private static YamlNode ReadNode(Parser parser) case SequenceStart start: { - var sequence = new YamlSequenceNode { IsFlow = start.Style == SequenceStyle.Flow, Start = (int)start.Start.Index, End = (int)start.End.Index }; + CheckDepth(depth, start); + var sequence = new YamlSequenceNode { IsFlow = start.Style == SequenceStyle.Flow, Start = at(start.Start), End = at(start.End) }; parser.MoveNext(); while (parser.Current is not SequenceEnd) { - var value = ReadNode(parser); + var value = ReadNode(parser, depth + 1, at); sequence.Items.Add(new YamlItem { Value = value }); sequence.End = Math.Max(sequence.End, value.End); } if (sequence.IsFlow) { - sequence.End = (int)parser.Current!.End.Index; + sequence.End = at(parser.Current!.End); } parser.MoveNext(); @@ -300,6 +388,14 @@ private static YamlNode ReadNode(Parser parser) } } + private static void CheckDepth(int depth, ParsingEvent start) + { + if (depth >= MaxDepth) + { + throw new YamlFormatException($"YAML nested more than {MaxDepth} levels deep is not supported (line {start.Start.Line})."); + } + } + private static string NormalizeTag(string tag) => tag switch { "!!str" => "tag:yaml.org,2002:str", @@ -382,7 +478,7 @@ internal static class YamlScalars { return long.TryParse(plain, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var number) ? JsonValue.Create(number) - : JsonValue.Create(double.Parse(plain, CultureInfo.InvariantCulture)); + : ExactInteger(plain); } if (plain.Length > 2 && plain[0] == '0' && plain[1] is 'x' or 'o') @@ -423,8 +519,29 @@ public static bool IsAmbiguous(string text) return true; } - // YAML 1.2 floats that JSON cannot hold (kept as text by Resolve). - return text is ".inf" or "-.inf" or "+.inf" or ".Inf" or "-.Inf" or "+.Inf" or ".INF" or "-.INF" or "+.INF" or ".nan" or ".NaN" or ".NAN"; + // Kept as text by Resolve, but numbers to YAML 1.2 (and to Postman's library): .inf and .nan, which JSON cannot hold, + // and numbers too big for a long or a double (an Ethereum address, 0x and 40 hex digits; 1e400). + return text is ".inf" or "-.inf" or "+.inf" or ".Inf" or "-.Inf" or "+.Inf" or ".INF" or "-.INF" or "+.INF" or ".nan" or ".NaN" or ".NAN" + || IsFloat(text) || IsPrefixedInteger(text); + } + + /// 0x[0-9a-fA-F]+ or 0o[0-7]+, of any size. + private static bool IsPrefixedInteger(string s) + { + if (s.Length <= 2 || s[0] != '0' || s[1] is not ('x' or 'o')) + { + return false; + } + + foreach (var c in s.AsSpan(2)) + { + if (s[1] == 'x' ? !char.IsAsciiHexDigit(c) : c is < '0' or > '7') + { + return false; + } + } + + return true; } private static bool IsDecimalInteger(string s) @@ -433,6 +550,16 @@ private static bool IsDecimalInteger(string s) return s.Length > start && s.AsSpan(start).IndexOfAnyExceptInRange('0', '9') < 0; } + /// + /// An integer too big for a long, as a JSON number with exactly its digits (as JSON files keep them): a double would + /// round it, or be infinite, which JSON cannot hold. + /// + private static JsonNode ExactInteger(string plain) + { + var digits = plain.AsSpan(plain[0] is '-' or '+' ? 1 : 0).TrimStart('0'); + return JsonNode.Parse((plain[0] == '-' ? "-" : "") + (digits.IsEmpty ? "0" : digits.ToString()))!; + } + /// [-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)? private static bool IsFloat(string s) { diff --git a/src/TermRest.Core/Yaml/YamlWriter.cs b/src/TermRest.Core/Yaml/YamlWriter.cs index 791ddf6..651f855 100644 --- a/src/TermRest.Core/Yaml/YamlWriter.cs +++ b/src/TermRest.Core/Yaml/YamlWriter.cs @@ -80,10 +80,25 @@ static void Count(YamlNode? node, ref int single, ref int @double) /// When the original YAML is given as a hint, unchanged entries, items and scalars are copied verbatim, so an edit only /// touches the lines it has to. /// -internal sealed class YamlWriter(YamlStyle style, YamlTree? source) +/// Write anew, rather than copy, what ends a source without a final line break with a block +/// scalar that keeps its last line break (see ). +internal sealed class YamlWriter(YamlStyle style, YamlTree? source, bool rewriteEndBlock = false) { private readonly StringBuilder _out = new(); + /// + /// Whether the output ends with a block scalar: a line after it that is indented like its text would be part of it, and + /// so would blank lines when it keeps them (|+, >+). + /// + private BlockEnd _blockEnd; + + private enum BlockEnd + { + None, + Block, + BlockKeepingBlankLines, + } + public override string ToString() => _out.ToString(); public void Append(string text) => _out.Append(text); @@ -103,6 +118,7 @@ public void WriteEntry(string key, JsonNode? value, int indent, YamlEntry? hint, var formattedKey = FormatKey(key); _out.Append(formattedKey).Append(':'); + _blockEnd = BlockEnd.None; WriteValue(value, indent, hint?.Value, formattedKey.Length); } @@ -114,7 +130,16 @@ public void WriteMapping(JsonObject obj, int indent, YamlNode? hint, bool firstI foreach (var (key, value) in obj) { var entryHint = mapping is { IsFlow: false } ? mapping.Find(key) : null; - WriteEntry(key, value, indent, entryHint, inline: first && firstInline); + var inline = first && firstInline; + if (entryHint is not null && !inline && source!.StartsLine(entryHint.Key.Start)) + { + // Comments and blank lines above an entry move with it, as at the top level. + var index = mapping!.Entries.IndexOf(entryHint); + var start = index > 0 ? mapping.Entries[index - 1].LastLine + 1 : TriviaAbove(entryHint.FirstLine); + AppendTrivia(source.Lines(start, entryHint.FirstLine - 1), indent); + } + + WriteEntry(key, value, indent, entryHint, inline); first = false; } } @@ -150,6 +175,7 @@ private void WriteSequence(JsonArray array, int indent, YamlSequenceNode? hint) { var items = hint is { IsFlow: false } ? hint.Items : []; var used = new bool[items.Count]; + var placed = new bool[items.Count]; for (var i = 0; i < array.Count; i++) { var value = array[i]; @@ -167,18 +193,29 @@ private void WriteSequence(JsonArray array, int indent, YamlSequenceNode? hint) if (equal >= 0) { used[equal] = true; - if (TryCopyItem(items[equal], indent)) - { - continue; - } } - WriteItem(value, indent, equal >= 0 ? items[equal].Value : SimilarItem(items, used, i, value)); + var match = equal >= 0 ? equal : SimilarItem(items, used, i, value); + if (match >= 0 && !placed[match] && items[match].DashColumn >= 0 + && source!.StartsLine(source.LineStart(items[match].FirstLine) + items[match].DashColumn)) + { + // Comments and blank lines above an item move with it. + placed[match] = true; + var start = match > 0 ? items[match - 1].LastLine + 1 : TriviaAbove(items[match].FirstLine); + AppendTrivia(source.Lines(start, items[match].FirstLine - 1), indent); + } + + if (equal >= 0 && TryCopyItem(items[equal], indent)) + { + continue; + } + + WriteItem(value, indent, match >= 0 ? items[match].Value : null); } } - /// The original item that most likely is the edited version of (for formatting hints). - private static YamlNode? SimilarItem(List items, bool[] used, int index, JsonNode? value) + /// The index of the original item that most likely is the edited version of (for formatting hints), or -1. + private static int SimilarItem(List items, bool[] used, int index, JsonNode? value) { if (value is JsonObject obj) { @@ -191,19 +228,20 @@ private void WriteSequence(JsonArray array, int indent, YamlSequenceNode? hint) if (!used[j] && items[j].Value is YamlMappingNode m && m.Find(identity)?.Value is YamlScalarNode s && JsonNode.DeepEquals(s.ToJson(), id)) { - return m; + return j; } } } } } - return index < items.Count && !used[index] ? items[index].Value : null; + return index < items.Count && !used[index] ? index : -1; } private void WriteItem(JsonNode? value, int indent, YamlNode? hint) { _out.Append(' ', indent).Append('-'); + _blockEnd = BlockEnd.None; switch (value) { case JsonObject { Count: 0 }: @@ -231,26 +269,61 @@ private void WriteItem(JsonNode? value, int indent, YamlNode? hint) private bool TryCopyEntry(YamlEntry hint, JsonNode? value, int indent) { if (source is null || source.ColumnOf(hint.Key.Start) != indent || !source.StartsLine(hint.Key.Start) - || !JsonNode.DeepEquals(Json(hint.Value), value)) + || !JsonNode.DeepEquals(Json(hint.Value), value) || EndsWithOpenBlock(hint.Value)) { return false; } AppendLines(hint.FirstLine, hint.LastLine); + _blockEnd = BlockEndOf(hint.Value); return true; } private bool TryCopyItem(YamlItem hint, int indent) { - if (source is null || hint.DashColumn != indent || !source.StartsLine(source.LineStart(hint.FirstLine) + indent)) + if (source is null || hint.DashColumn != indent || !source.StartsLine(source.LineStart(hint.FirstLine) + indent) || EndsWithOpenBlock(hint.Value)) { return false; } AppendLines(hint.FirstLine, hint.LastLine); + _blockEnd = BlockEndOf(hint.Value); return true; } + /// + /// Whether ends a source without a final line break with a block scalar that keeps its last line + /// break (|, >, |+): its value has none there, but copied before more lines it would get one. + /// Only when rewriteEndBlock is set: copied, it is right while it stays last (written without a final line break). + /// + private bool EndsWithOpenBlock(YamlNode node) + { + if (!rewriteEndBlock || source is null || source.Text.EndsWith('\n')) + { + return false; + } + + while (true) + { + switch (node) + { + case YamlMappingNode { IsFlow: false, Entries.Count: > 0 } mapping: + node = mapping.Entries[^1].Value; + break; + case YamlSequenceNode { IsFlow: false, Items.Count: > 0 } sequence: + node = sequence.Items[^1].Value; + break; + case YamlScalarNode { Style: YamlScalarStyle.Literal or YamlScalarStyle.Folded } scalar + when source.Text.AsSpan(scalar.End).IsWhiteSpace(): + var header = source.Text.AsSpan(scalar.Start); + var end = header.IndexOfAny(' ', '\t', '\n'); + return !(end < 0 ? header : header[..end]).Contains('-'); + default: + return false; + } + } + } + private void AppendLines(int first, int last) { var text = source!.Lines(first, last); @@ -261,6 +334,50 @@ private void AppendLines(int first, int last) } } + /// + /// Appends the comment and blank lines that stood above an entry or item now written at . + /// After a block scalar, the first comment moves left to if it is further right, which ends + /// the block scalar; blank lines before it are left out when the block scalar keeps blank lines. + /// + public void AppendTrivia(string lines, int indent) + { + if (_blockEnd != BlockEnd.None) + { + var hash = lines.IndexOf('#'); + var lineStart = hash < 0 ? lines.Length : lines.LastIndexOf('\n', hash) + 1; + var blankLines = _blockEnd == BlockEnd.Block ? new string('\n', lines.AsSpan(0, lineStart).Count('\n')) : ""; + lines = hash < 0 ? blankLines : blankLines + new string(' ', Math.Min(hash - lineStart, indent)) + lines[hash..]; + } + + _out.Append(lines); + } + + /// The first of the comment and blank lines directly above (up to the parent's line). + private int TriviaAbove(int line) + { + while (line > 0 && source!.Lines(line - 1, line - 1).TrimStart(' ') is var text && (text.Length == 0 || text[0] is '\n' or '#')) + { + line--; + } + + return line; + } + + private BlockEnd BlockEndOf(YamlNode node) => node switch + { + YamlScalarNode { Style: YamlScalarStyle.Literal or YamlScalarStyle.Folded } scalar => BlockEndOf(source!.Text.AsSpan(scalar.Start)), + YamlMappingNode { IsFlow: false, Entries.Count: > 0 } mapping => BlockEndOf(mapping.Entries[^1].Value), + YamlSequenceNode { IsFlow: false, Items.Count: > 0 } sequence => BlockEndOf(sequence.Items[^1].Value), + _ => BlockEnd.None, + }; + + /// For a block scalar's text, which starts with its header (such as |2+). + private static BlockEnd BlockEndOf(ReadOnlySpan block) + { + var end = block.IndexOfAny(' ', '\t', '\n'); + return (end < 0 ? block : block[..end]).Contains('+') ? BlockEnd.BlockKeepingBlankLines : BlockEnd.Block; + } + private readonly Dictionary _json = new(ReferenceEqualityComparer.Instance); private JsonNode? Json(YamlNode node) @@ -283,12 +400,14 @@ private void AppendLines(int first, int last) /// private string FormatScalar(JsonNode? value, int indent, YamlScalarNode? hint, bool inSequence, int? keyLength) { - if (hint is not null && source is not null && JsonNode.DeepEquals(Json(hint), value) && CanCopyScalar(hint, indent)) + if (hint is not null && source is not null && JsonNode.DeepEquals(Json(hint), value) && CanCopyScalar(hint, indent) && !EndsWithOpenBlock(hint)) { var raw = source.Text[hint.Start..hint.End]; + _blockEnd = BlockEndOf(hint); return raw.EndsWith('\n') ? raw[..^1] : raw; } + _blockEnd = BlockEnd.None; if (value is not JsonValue scalar) { return "null"; @@ -312,8 +431,9 @@ private string FormatScalar(JsonNode? value, int indent, YamlScalarNode? hint, b if (text.Contains('\n', StringComparison.Ordinal)) { var keep = hint?.Style is YamlScalarStyle.Literal or YamlScalarStyle.Folded ? hint.Style : (YamlScalarStyle?)null; - return BlockScalar(text, contentIndent, inSequence, style.LineWidth, keep) - ?? YamlFolding.FoldDoubleQuoted(DoubleQuoted(text), contentIndent, indentAtStart, style.LineWidth); + var block = BlockScalar(text, contentIndent, inSequence, style.LineWidth, keep); + _blockEnd = block is null ? BlockEnd.None : BlockEndOf(block); + return block ?? YamlFolding.FoldDoubleQuoted(DoubleQuoted(text), contentIndent, indentAtStart, style.LineWidth); } var quote = hint?.Style is YamlScalarStyle.SingleQuoted or YamlScalarStyle.DoubleQuoted ? hint.Style : (YamlScalarStyle?)null; @@ -413,7 +533,8 @@ private string Quoted(string text, YamlScalarStyle? preferred, int contentIndent var indicator = ""; if (firstContent.StartsWith(' ')) { - if (inSequence) + // The YAML reader refuses a block whose first line holds only spaces ("found extra spaces in first line"). + if (inSequence || firstContent.AsSpan().TrimStart(" \t").IsEmpty) { return null; } @@ -536,7 +657,12 @@ public static string DoubleQuoted(string text) return builder.Append('"').ToString(); } - private static string FormatKey(string key) => IsPlainSafe(key) ? key : DoubleQuoted(key); + /// + /// A mapping key as YAML writes it: quoted where a plain one would not read back, also where it holds " *", as + /// YamlDotNet then reads the key, its colon and its value as one string (Accept *: v). + /// + private static string FormatKey(string key) => + IsPlainSafe(key) && !key.Contains(" *", StringComparison.Ordinal) ? key : DoubleQuoted(key); // ----- detecting how a document was wrapped ------------------------------------------------------- diff --git a/src/TermRest.Tui/Dialogs/CertificatesDialog.cs b/src/TermRest.Tui/Dialogs/CertificatesDialog.cs index bafe62e..b93509b 100644 --- a/src/TermRest.Tui/Dialogs/CertificatesDialog.cs +++ b/src/TermRest.Tui/Dialogs/CertificatesDialog.cs @@ -1,10 +1,12 @@ using System.Collections.ObjectModel; using System.Globalization; using System.Text; +using System.Text.Json; using Terminal.Gui.App; using Terminal.Gui.ViewBase; using Terminal.Gui.Views; using TermRest.Core.Certificates; +using TermRest.Core.IO; using TermRest.Core.Workspace; namespace TermRest.Tui.Dialogs; @@ -19,9 +21,9 @@ public static void Show(IApplication app, ApiWorkspace workspace, RequestRunner { var registry = workspace.Certificates; using var dialog = new Dialog { Title = "Client certificates (mutual TLS)", Width = Dim.Percent(92), Height = Dim.Percent(85) }; - var table = new TableView { X = 1, Y = 1, Width = Dim.Fill(1), Height = Dim.Fill(6), FullRowSelect = true }; + var table = new TableView { X = 1, Y = 1, Width = Dim.Fill(1), Height = Dim.Fill(8), FullRowSelect = true }; table.Style.ExpandLastColumn = true; - var details = new Label { X = 1, Y = Pos.AnchorEnd(5), Width = Dim.Fill(1), Height = 3, Text = "" }; + var details = new Label { X = 1, Y = Pos.AnchorEnd(7), Width = Dim.Fill(1), Height = 3, Text = "", HotKeySpecifier = Ui.NoHotKey }; void Refresh(int select) { @@ -46,10 +48,50 @@ void Refresh(int select) void Persist() { - workspace.SaveCertificates(); + try + { + workspace.SaveCertificates(); + } + catch (FileChangedException) + { + // A git pull or another TermRest changed the file: saving the list shown here would undo that. + if (MessageBox.Query(app, "Changed on disk", + $"{Path.GetRelativePath(workspace.RootPath, workspace.CertificatesPath)} changed on disk since TermRest read it (a git pull, another TermRest).\n\n" + + "Saving the list shown here would undo those changes. Choose Cancel to load the file's entries instead: this change is then not saved.", + "Overwrite", "Cancel") != 0) + { + Reload(); + return; + } + + if (!Ui.TrySave(app, () => workspace.SaveCertificates(overwriteChanged: true))) + { + return; + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Ui.Error(app, "Save failed", ex.Message); + return; + } + runner.ReloadCertificates(); } + void Reload() + { + try + { + workspace.ReloadCertificates(); + registry = workspace.Certificates; + runner.ReloadCertificates(); + } + catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException or UnauthorizedAccessException) + { + Ui.Error(app, "Load failed", $"{workspace.CertificatesPath}: {ex.Message}\n\nThe change was not saved."); + } + } + void Add(CertificateEntry? template) { var entry = CertificateEntryDialog.Show(app, workspace, template ?? new CertificateEntry(), suggestedUrl); @@ -61,12 +103,13 @@ void Add(CertificateEntry? template) } } - var addPem = new Button { Text = "Add PEM…", X = 1, Y = Pos.AnchorEnd(1) }; - addPem.Accepted += (_, _) => Add(new CertificateEntry { Cert = new FileSource(), Key = new FileSource() }); - var addPfx = new Button { Text = "Add PFX…", X = Pos.Right(addPem) + 1, Y = Pos.AnchorEnd(1) }; - addPfx.Accepted += (_, _) => Add(new CertificateEntry { Pfx = new FileSource() }); - var addStore = new Button { Text = "Add from OS store…", X = Pos.Right(addPfx) + 1, Y = Pos.AnchorEnd(1) }; - addStore.Accepted += (_, _) => + // Two rows of buttons, adding and changing entries, so that they fit a terminal of 80 columns. + var addPem = new Button { Text = "Add PEM…", X = 1, Y = Pos.AnchorEnd(3) }; + Ui.OnPress(addPem, () => Add(new CertificateEntry { Cert = new FileSource(), Key = new FileSource() })); + var addPfx = new Button { Text = "Add PFX…", X = Pos.Right(addPem) + 1, Y = Pos.AnchorEnd(3) }; + Ui.OnPress(addPfx, () => Add(new CertificateEntry { Pfx = new FileSource() })); + var addStore = new Button { Text = "Add from OS store…", X = Pos.Right(addPfx) + 1, Y = Pos.AnchorEnd(3) }; + Ui.OnPress(addStore, () => { if (StorePickerDialog.Show(app) is { } picked) { @@ -76,9 +119,9 @@ void Add(CertificateEntry? template) Store = new StoreSource { Location = picked.Source?.Split('\\')[0] ?? "CurrentUser", StoreName = "My", Thumbprint = picked.Thumbprint }, }); } - }; - var edit = new Button { Text = "Edit…", X = Pos.Right(addStore) + 1, Y = Pos.AnchorEnd(1) }; - edit.Accepted += (_, _) => + }); + var edit = new Button { Text = "Edit…", X = 1, Y = Pos.AnchorEnd(1) }; + Ui.OnPress(edit, () => { if (Selected() is { } selected && CertificateEntryDialog.Show(app, workspace, selected.Clone(), suggestedUrl) is { } edited) { @@ -87,19 +130,20 @@ void Add(CertificateEntry? template) Persist(); Refresh(index); } - }; + }); var toggle = new Button { Text = "On/Off", X = Pos.Right(edit) + 1, Y = Pos.AnchorEnd(1) }; - toggle.Accepted += (_, _) => + Ui.OnPress(toggle, () => { if (Selected() is { } selected) { + var index = registry.Entries.IndexOf(selected); selected.Disabled = !selected.Disabled; Persist(); - Refresh(registry.Entries.IndexOf(selected)); + Refresh(index); } - }; + }); var remove = new Button { Text = "Remove", X = Pos.Right(toggle) + 1, Y = Pos.AnchorEnd(1) }; - remove.Accepted += (_, _) => + Ui.OnPress(remove, () => { if (Selected() is { } selected && Ui.Confirm(app, "Remove certificate", $"Remove '{selected.Name}' from the workspace registry? (Files and store entries are not deleted.)", "Remove", "Cancel")) { @@ -108,18 +152,21 @@ void Add(CertificateEntry? template) Persist(); Refresh(index); } - }; + }); var test = new Button { Text = "Test", X = Pos.Right(remove) + 1, Y = Pos.AnchorEnd(1) }; - test.Accepted += (_, _) => + Ui.OnPress(test, () => { if (Selected() is { } selected) { details.Text = TestLoad(selected, workspace, runner); } - }; + }); table.ValueChanged += (_, _) => details.Text = Selected() is { } s ? $"{s.Name}: {s.DescribeSource()}\nPress Test to load it and check the private key." : ""; - table.Accepted += (_, _) => + + // Enter or a double-click on a row tests it, rather than closing the dialog. + table.Accepting += (_, e) => { + e.Handled = true; if (Selected() is { } selected) { details.Text = TestLoad(selected, workspace, runner); @@ -150,7 +197,7 @@ private static string TestLoad(CertificateEntry entry, ApiWorkspace workspace, R var loaded = runner.Certificates.Load(entry, workspace.RootPath, value => value is not null && value.StartsWith("env:", StringComparison.OrdinalIgnoreCase) ? Environment.GetEnvironmentVariable(value[4..]) - : resolver.Resolve(value)); + : resolver.Resolve(value), runner.FilesFolder); var summary = loaded.Summary; var builder = new StringBuilder(); builder.Append(CultureInfo.InvariantCulture, $"✓ {summary.Subject} issued by {summary.IssuerCommonName}\n"); @@ -246,7 +293,9 @@ internal static class CertificateEntryDialog result.Store = new StoreSource { Location = location.Value == 1 ? "LocalMachine" : "CurrentUser", - StoreName = "My", + + // Not shown here: an entry for another store (TrustedPeople…) stays in it. + StoreName = entry.Store?.StoreName ?? "My", Thumbprint = string.IsNullOrWhiteSpace(thumbprint.Text) ? null : CertificateLoader.NormalizeThumbprint(thumbprint.Text), Subject = string.IsNullOrWhiteSpace(subject.Text) ? null : subject.Text.Trim(), }; @@ -295,7 +344,7 @@ private static TextField FileRow(Dialog dialog, IApplication app, ApiWorkspace w { var field = Ui.AddRow(dialog, label, new TextField { Text = value, Width = Dim.Fill(13) }, y); var browse = new Button { Text = "Browse…", X = Pos.AnchorEnd(12), Y = y }; - browse.Accepted += (_, _) => + Ui.OnPress(browse, () => { if (Ui.PickFile(app, label, workspace.RootPath) is { } path) { @@ -303,7 +352,7 @@ private static TextField FileRow(Dialog dialog, IApplication app, ApiWorkspace w var relative = Path.GetRelativePath(workspace.RootPath, path); field.Text = relative.StartsWith("..", StringComparison.Ordinal) ? path : relative.Replace('\\', '/'); } - }; + }); dialog.Add(browse); return field; } diff --git a/src/TermRest.Tui/Dialogs/EnvironmentsDialog.cs b/src/TermRest.Tui/Dialogs/EnvironmentsDialog.cs index 064bf36..98d8fdb 100644 --- a/src/TermRest.Tui/Dialogs/EnvironmentsDialog.cs +++ b/src/TermRest.Tui/Dialogs/EnvironmentsDialog.cs @@ -22,7 +22,11 @@ public static bool Show(IApplication app, ApiWorkspace workspace) var list = new ListView { X = 1, Y = 1, Width = 30, Height = Dim.Fill(4) }; list.SetSource(names); var values = new KeyValueTable(KeyValueKind.Variables) { X = Pos.Right(list) + 2, Y = 1, Width = Dim.Fill(1), Height = Dim.Fill(4) }; - var activeLabel = new Label { X = 1, Y = Pos.AnchorEnd(3), Width = Dim.Fill(1) }; + + // With no environment, values would have nowhere to go: the table is hidden until one is created or imported. + var noEnvironment = new Label { Text = "No environments yet: values go into one, so create or import one first.", X = Pos.Right(list) + 2, Y = 1, Visible = false }; + // It names the active environment: an underscore in the name must not make a key, which would press Set active. + var activeLabel = new Label { X = 1, Y = Pos.AnchorEnd(3), Width = Dim.Fill(1), HotKeySpecifier = Ui.NoHotKey }; var scopes = new List(); List? editing = null; @@ -41,10 +45,12 @@ void Refresh(int select) foreach (var environment in scopes) { var marker = environment == workspace.ActiveEnvironment ? "● " : " "; - names.Add(environment.IsGlobals ? $" [globals] {environment.Name}" : marker + environment.Name); + names.Add(Ui.Drawable(environment.IsGlobals ? $" [globals] {environment.Name}" : marker + workspace.DisplayName(environment))); } - activeLabel.Text = $"Active environment: {workspace.ActiveEnvironment?.Name ?? "(none)"} ● marks the active one"; + activeLabel.Text = $"Active environment: {(workspace.ActiveEnvironment is { } active ? workspace.DisplayName(active) : "(none)")} ● marks the active one"; + values.Visible = scopes.Count > 0; + noEnvironment.Visible = scopes.Count == 0; if (scopes.Count > 0) { list.Value = Math.Clamp(select, 0, scopes.Count - 1); @@ -82,33 +88,42 @@ void Load(PostmanEnvironment environment) }; var activate = new Button { Text = "Set active", X = 1, Y = Pos.AnchorEnd(1) }; - activate.Accepted += (_, _) => + Ui.OnPress(activate, () => { if (current is { IsGlobals: false }) { workspace.ActiveEnvironment = current; Refresh(list.Value ?? 0); } - }; + }); var none = new Button { Text = "No environment", X = Pos.Right(activate) + 1, Y = Pos.AnchorEnd(1) }; - none.Accepted += (_, _) => + Ui.OnPress(none, () => { workspace.ActiveEnvironment = null; Refresh(list.Value ?? 0); - }; + }); var create = new Button { Text = "New…", X = Pos.Right(none) + 1, Y = Pos.AnchorEnd(1) }; - create.Accepted += (_, _) => + Ui.OnPress(create, () => { if (Ui.PromptText(app, "New environment", "Name") is { Length: > 0 } name) { - CommitCurrent(); - current = null; - workspace.CreateEnvironment(name.Trim()); - Refresh(workspace.Environments.Count - 1); + try + { + CommitCurrent(); + workspace.CreateEnvironment(name.Trim()); + + // Only now: when it fails, the table goes on editing the environment shown. + current = null; + Refresh(workspace.Environments.Count - 1); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException) + { + Ui.Error(app, "Cannot create environment", ex.Message); + } } - }; + }); var rename = new Button { Text = "Rename…", X = Pos.Right(create) + 1, Y = Pos.AnchorEnd(1) }; - rename.Accepted += (_, _) => + Ui.OnPress(rename, () => { if (current is not null && Ui.PromptText(app, "Rename environment", "Name", current.Name) is { Length: > 0 } name) { @@ -121,43 +136,42 @@ void Load(PostmanEnvironment environment) Refresh(list.Value ?? 0); } - }; + }); var import = new Button { Text = "Import…", X = Pos.Right(rename) + 1, Y = Pos.AnchorEnd(1) }; - import.Accepted += (_, _) => + Ui.OnPress(import, () => { - if (Ui.PickFile(app, "Import Postman environment", workspace.RootPath, false, ("Postman environment", [".json"])) is { } path) + if (Ui.PickFile(app, "Import Postman environment", workspace.RootPath, false, ("Postman environment", [".json", ".yaml", ".yml"])) is { } path) { try { CommitCurrent(); - current = null; var imported = workspace.ImportEnvironment(path); - Refresh(workspace.Environments.IndexOf(imported)); + current = null; + + // Globals are listed after the environments. + Refresh(imported.IsGlobals ? workspace.Environments.Count : workspace.Environments.IndexOf(imported)); } catch (Exception ex) { Ui.Error(app, "Import failed", ex.Message); } } - }; + }); - dialog.Add(new Label { Text = "Environments", X = 1, Y = 0 }, new Label { Text = "Values (secret values are masked)", X = Pos.Right(list) + 2, Y = 0 }, list, values, activeLabel, activate, none, create, rename, import); + dialog.Add(new Label { Text = "Environments", X = 1, Y = 0 }, new Label { Text = "Values (secret values are masked)", X = Pos.Right(list) + 2, Y = 0 }, list, values, noEnvironment, activeLabel, activate, none, create, rename, import); dialog.AddButton(new Button { Text = "Close" }); Refresh(Math.Max(0, workspace.ActiveEnvironment is { } a ? workspace.Environments.IndexOf(a) : 0)); - app.Run(dialog); - - CommitCurrent(); - foreach (var environment in workspace.Environments.Where(e => e.IsDirty)) + try { - environment.Save(); + app.Run(dialog); } - - if (workspace.Globals?.IsDirty == true) + finally { - workspace.Globals.Save(); + // Also when an unexpected error ends the dialog: the changes made in it are not lost. + CommitCurrent(); + Ui.SaveEach(app, workspace.RootPath, MainWindow.SaveItems(workspace, includeCollections: false)); } - workspace.SaveSettings(); return previousActive != workspace.ActiveEnvironment; } } diff --git a/src/TermRest.Tui/Dialogs/KeyValueEntryDialog.cs b/src/TermRest.Tui/Dialogs/KeyValueEntryDialog.cs index 025bef9..c482c84 100644 --- a/src/TermRest.Tui/Dialogs/KeyValueEntryDialog.cs +++ b/src/TermRest.Tui/Dialogs/KeyValueEntryDialog.cs @@ -1,3 +1,4 @@ +using System.Text; using Terminal.Gui.App; using Terminal.Gui.ViewBase; using Terminal.Gui.Views; @@ -15,10 +16,9 @@ internal static class KeyValueEntryDialog var y = 1; var key = Ui.AddRow(dialog, "Key", new TextField { Text = entry.Key, ReadOnly = kind == KeyValueKind.PathVariables }, y); y += 2; - var value = Ui.AddRow(dialog, "Value", new TextField { Text = entry.Value ?? "", Secret = entry.IsSecret }, y); - y += 2; - var description = Ui.AddRow(dialog, "Description", new TextField { Text = entry.Description ?? "" }, y); - y += 2; + var value = new TextInput(dialog, "Value", entry.Value, ref y); + value.Mask(entry.IsSecret); + var description = new TextInput(dialog, "Description", entry.Description, ref y); var enabled = Ui.AddRow(dialog, "Enabled", new CheckBox { Text = "", Value = entry.Enabled ? CheckState.Checked : CheckState.UnChecked, Width = 6 }, y); y += 2; @@ -32,14 +32,14 @@ internal static class KeyValueEntryDialog y += 2; files = Ui.AddRow(dialog, "File(s)", new TextField { Text = (entry.Src ?? "").Replace('\n', ';'), Width = Dim.Fill(14) }, y); var browse = new Button { Text = "Browse…", X = Pos.AnchorEnd(12), Y = y }; - browse.Accepted += (_, _) => + Ui.OnPress(browse, () => { if (Ui.PickFile(app, "Choose file") is { } path) { files.Text = path; partType.Value = 1; } - }; + }); dialog.Add(browse); y += 2; contentType = Ui.AddRow(dialog, "Content-Type", new TextField { Text = entry.ContentType ?? "" }, y); @@ -48,7 +48,7 @@ internal static class KeyValueEntryDialog else if (kind == KeyValueKind.Variables) { secret = Ui.AddRow(dialog, "Secret", new CheckBox { Text = "mask value", Value = entry.IsSecret ? CheckState.Checked : CheckState.UnChecked, Width = 14 }, y); - secret.ValueChanged += (_, _) => value.Secret = secret.Value == CheckState.Checked; + secret.ValueChanged += (_, _) => value.Mask(secret.Value == CheckState.Checked); y += 2; } @@ -61,9 +61,18 @@ internal static class KeyValueEntryDialog return null; } + // Fields left alone keep what they had: line breaks, or no value at all (?flag). entry.Key = key.Text.Trim(); - entry.Value = value.Text; - entry.Description = string.IsNullOrWhiteSpace(description.Text) ? null : description.Text; + if (value.Edited) + { + entry.Value = value.Text; + } + + if (description.Edited) + { + entry.Description = string.IsNullOrWhiteSpace(description.Text) ? null : description.Text; + } + entry.Enabled = enabled.Value == CheckState.Checked; if (partType is not null) { @@ -78,32 +87,109 @@ internal static class KeyValueEntryDialog return entry.Key.Length == 0 && string.IsNullOrEmpty(entry.Value) ? null : entry; } + + /// + /// A value's editor: a text field, or a text area for a value with line breaks or tabs (a text field keeps its first + /// line only, without tabs). tells whether the user changed it. + /// + private sealed class TextInput + { + private readonly TextField? _field; + private readonly TextArea? _area; + private readonly Action _mask; + private readonly string _shown; + + public TextInput(View dialog, string label, string? text, ref int y) + { + if (text is not null && text.AsSpan().ContainsAny('\r', '\n', '\t')) + { + var area = _area = Ui.AddRow(dialog, label, new TextArea { Width = Dim.Fill(1), Height = 5 }, y); + area.SetText(text); + + // A text area cannot mask its text: a secret's is hidden. + var hidden = new Label { Text = "•••••• (untick Secret to see it)", X = area.X, Y = y, Visible = false }; + dialog.Add(hidden); + _mask = masked => (area.Visible, hidden.Visible) = (!masked, masked); + y += 6; + } + else + { + var field = _field = Ui.AddRow(dialog, label, new TextField { Text = text ?? "" }, y); + _mask = masked => field.Secret = masked; + y += 2; + } + + _shown = Text; + } + + public string Text => _field?.Text ?? _area!.GetText(); + + public bool Edited => Text != _shown; + + /// Masks the value (a secret). + public void Mask(bool masked) => _mask(masked); + } } -/// Postman-style bulk edit: one key:value per line, // prefix for disabled rows. +/// +/// Postman-style bulk edit: one key:value per line, // prefix for disabled rows. A value with line breaks +/// shows them as \n (and its backslashes as \\), files are separated by ; as in the row dialog, +/// and secret values are masked. +/// internal static class BulkEditDialog { + /// What a secret value shows, as in the table: left as it is, the value is kept. + internal const string SecretMask = "••••••"; + + /// The rows as edited; null when cancelled, or applied without a change. public static List? Show(IApplication app, string noun, IReadOnlyList entries) { using var dialog = new Dialog { Title = $"Bulk edit {noun}s", Width = Dim.Percent(80), Height = Dim.Percent(70) }; - dialog.Add(new Label { Text = "One per line as key:value. Prefix a line with // to disable it.", X = 1, Y = 0 }); + dialog.Add( + new Label { Text = "One per line as key:value. Prefix a line with // to disable it.", X = 1, Y = 0 }, + new Label { Text = $"Line breaks in values show as \\n. Leave {SecretMask} to keep a secret value.", X = 1, Y = 1 }); var text = new TextArea { X = 1, Y = 2, Width = Dim.Fill(1), Height = Dim.Fill(1) }; text.SetText(Format(entries)); + + // As the editor shows it: Terminal.Gui keeps characters composed (NFC), so the text read back can differ unedited. + var shown = text.GetText(); dialog.Add(text); dialog.AddButton(new Button { Text = "Cancel" }); dialog.AddButton(new Button { Text = "Apply" }); - app.Run(dialog); - return dialog.Canceled ? null : Parse(text.GetText(), entries); + while (true) + { + app.Run(dialog); + var edited = dialog.Canceled ? null : text.GetText(); + if (edited is null || edited == shown) + { + return null; + } + + var unclear = new List(); + var parsed = Parse(edited, entries, unclear); + if (unclear.Count == 0) + { + return parsed; + } + + Ui.Error(app, "Secret values", $"Which secret value {SecretMask} stands for is not clear on these lines: {string.Join(", ", unclear)}.\n" + + "Type the value, or leave the line as it was (with its key)."); + } } public static string Format(IEnumerable entries) => - string.Join('\n', entries.Select(e => $"{(e.Enabled ? "" : "//")}{e.Key}:{(e.IsFile ? e.Src : e.Value)}")); + string.Join('\n', entries.Select(e => $"{(e.Enabled ? "" : "//")}{e.Key}:{FormatValue(e)}")); - /// Parses bulk text, keeping descriptions and unknown JSON of rows whose key did not change. - public static List Parse(string text, IReadOnlyList previous) + /// + /// Parses bulk text, keeping the descriptions and unknown JSON of the rows, and the values of rows that read as they + /// were written. A line is the row it shows as written, else the row with its key; lines whose key changed are the + /// rows that were in their place when as many rows as lines changed there, and a line still showing a secret's mask + /// is else the one secret left. The keys of lines that show the mask for no secret go to + /// (the mask is their value then). + /// + public static List Parse(string text, IReadOnlyList previous, List? unclear = null) { - var result = new List(); - var pool = previous.ToList(); + var texts = new List<(bool Enabled, string Text)>(); foreach (var rawLine in text.Split('\n')) { var line = rawLine.TrimEnd('\r'); @@ -119,29 +205,88 @@ public static List Parse(string text, IReadOnlyList= 0 ? line[..colon] : line).Trim(); - var value = colon >= 0 ? line[(colon + 1)..] : ""; - var match = pool.FirstOrDefault(p => p.Key == key); - KeyValueEntry entry; - if (match is not null) + texts.Add((enabled, line)); + } + + var lines = Split(texts, previous); + + // A row is the one a line shows as written (rows may share a key), else the one with its key. + var taken = new bool[previous.Count]; + var matches = lines.Select(line => line.Row).ToArray(); + foreach (var row in matches.Where(row => row >= 0)) + { + taken[row] = true; + } + + for (var i = 0; i < lines.Count; i++) + { + for (var j = 0; j < previous.Count && matches[i] < 0; j++) { - pool.Remove(match); - entry = match.Clone(); + if (!taken[j] && previous[j].Key == lines[i].Key) + { + matches[i] = j; + taken[j] = true; + } } - else + } + + // Renamed rows: the lines between two rows that kept their key are the rows that were between them, when there are + // as many of each (a row removed there and another renamed would not say which is which). + for (int i = 0, first = 0, after = -1; i <= lines.Count; i++) + { + if (i < lines.Count && matches[i] < 0) { - entry = new KeyValueEntry { Key = key }; + continue; } - entry.Enabled = enabled; - if (entry.IsFile) + var before = i < lines.Count ? matches[i] : previous.Count; + var rows = Enumerable.Range(after + 1, Math.Max(0, before - after - 1)).Where(j => !taken[j]).ToList(); + if (rows.Count == i - first) { - entry.Src = value.Trim(); + for (var k = 0; k < rows.Count; k++) + { + matches[first + k] = rows[k]; + taken[rows[k]] = true; + } } - else + + first = i + 1; + after = before; + } + + // A renamed secret still showing its mask elsewhere: the secret left, when it is the only one. + var masks = Enumerable.Range(0, lines.Count).Where(i => matches[i] < 0 && lines[i].Value == SecretMask).ToList(); + var secrets = Enumerable.Range(0, previous.Count).Where(j => !taken[j] && Masked(previous[j])).ToList(); + if (masks.Count == 1 && secrets.Count == 1) + { + matches[masks[0]] = secrets[0]; + } + + var result = new List(); + for (var i = 0; i < lines.Count; i++) + { + var (enabled, key, value, _) = lines[i]; + var match = matches[i] < 0 ? null : previous[matches[i]]; + var entry = match?.Clone() ?? new KeyValueEntry(); + entry.Key = key; + entry.Enabled = enabled; + + // A row that reads as it was written keeps its value as it was (line breaks, files, secret). + if (match is null || value != FormatValue(match)) { - entry.Value = value; + if (value.Trim() == SecretMask) + { + unclear?.Add(key); + } + + if (entry.IsFile) + { + entry.Src = string.Join('\n', value.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + } + else + { + entry.Value = match is not null && !match.IsFile && !Masked(match) && HasLineBreaks(match.Value) ? Unescape(value) : value; + } } result.Add(entry); @@ -149,4 +294,93 @@ public static List Parse(string text, IReadOnlyList + /// Splits lines into keys and values. Keys may hold ':' themselves (Api:BaseUrl), so a line is split after the key of a + /// row: the row it shows as written, else the longest key it starts with followed by ':' (of the rows no other line + /// was split for), else at its first ':'. Row is the row a line shows as written, else -1. + /// + private static List<(bool Enabled, string Key, string Value, int Row)> Split(List<(bool Enabled, string Text)> lines, IReadOnlyList rows) + { + var used = new bool[rows.Count]; + var keys = new (string Key, int ValueStart, int Row)?[lines.Count]; + var written = rows.Select(r => $"{r.Key}:{FormatValue(r)}").ToList(); + for (var i = 0; i < lines.Count; i++) + { + var row = Enumerable.Range(0, rows.Count).FirstOrDefault(j => !used[j] && written[j] == lines[i].Text, -1); + if (row >= 0) + { + used[row] = true; + keys[i] = (rows[row].Key, rows[row].Key.Length + 1, row); + } + } + + for (var i = 0; i < lines.Count; i++) + { + if (keys[i] is not null) + { + continue; + } + + var line = lines[i].Text; + var start = line.Length - line.TrimStart().Length; + var best = -1; + for (var j = 0; j < rows.Count; j++) + { + var key = rows[j].Key; + if (!used[j] && key.Length > 0 && (best < 0 || key.Length > rows[best].Key.Length) + && line.Length > start + key.Length && line[start + key.Length] == ':' && string.CompareOrdinal(line, start, key, 0, key.Length) == 0) + { + best = j; + } + } + + if (best >= 0) + { + used[best] = true; + keys[i] = (rows[best].Key, start + rows[best].Key.Length + 1, -1); + } + } + + var result = new List<(bool Enabled, string Key, string Value, int Row)>(lines.Count); + for (var i = 0; i < lines.Count; i++) + { + var (enabled, line) = lines[i]; + var colon = line.IndexOf(':', StringComparison.Ordinal); + result.Add(keys[i] is { } key ? (enabled, key.Key, line[key.ValueStart..], key.Row) + : (enabled, (colon >= 0 ? line[..colon] : line).Trim(), colon >= 0 ? line[(colon + 1)..] : "", -1)); + } + + return result; + } + + private static string FormatValue(KeyValueEntry entry) => + entry.IsFile ? (entry.Src ?? "").Replace('\n', ';') + : Masked(entry) ? SecretMask + : HasLineBreaks(entry.Value) ? entry.Value!.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\r", "\\r", StringComparison.Ordinal).Replace("\n", "\\n", StringComparison.Ordinal) + : entry.Value ?? ""; + + private static bool Masked(KeyValueEntry entry) => entry.IsSecret && !string.IsNullOrEmpty(entry.Value); + + private static bool HasLineBreaks(string? value) => value is not null && value.AsSpan().ContainsAny('\r', '\n'); + + /// Turns the \n, \r and \\ of a value written by back into what they stand for. + private static string Unescape(string value) + { + var builder = new StringBuilder(value.Length); + for (var i = 0; i < value.Length; i++) + { + if (value[i] == '\\' && i + 1 < value.Length && value[i + 1] is '\\' or 'n' or 'r') + { + i++; + builder.Append(value[i] switch { 'n' => '\n', 'r' => '\r', _ => '\\' }); + } + else + { + builder.Append(value[i]); + } + } + + return builder.ToString(); + } } diff --git a/src/TermRest.Tui/Dialogs/RecordingDialog.cs b/src/TermRest.Tui/Dialogs/RecordingDialog.cs index 2861d8c..7208590 100644 --- a/src/TermRest.Tui/Dialogs/RecordingDialog.cs +++ b/src/TermRest.Tui/Dialogs/RecordingDialog.cs @@ -50,7 +50,7 @@ public static (RecordingDialogResult Result, RecordingResult? Saved) Show(IAppli : $"{requests} recorded since {recorder.StartedAt:HH:mm:ss} ({Duration(DateTimeOffset.Now - recorder.StartedAt)}), {HttpExchange.FormatSize(recorder.Bytes)} so far."; var redactions = recorder.IsRecovered || recorder.Redactions == 0 ? "" : $" ({recorder.Redactions.ToString(CultureInfo.InvariantCulture)} values)"; dialog.Add( - new Label { Text = summary, X = 1, Y = 1, Width = Dim.Fill(1) }, + new Label { Text = summary, X = 1, Y = 1, Width = Dim.Fill(1), HotKeySpecifier = Ui.NoHotKey }, new Label { Text = $"Secrets are redacted{redactions}: credentials, cookies, tokens and secret variables read {Redactor.Placeholder}.", X = 1, Y = 2, Width = Dim.Fill(1) }); if (recorder.RequestsWithFiles is var withFiles and > 0) { @@ -59,14 +59,14 @@ public static (RecordingDialogResult Result, RecordingResult? Saved) Show(IAppli } var path = Ui.AddRow(dialog, "Save as", new TextField { Text = defaultPath, Width = Dim.Fill(13) }, 4, 8); var browse = new Button { Text = "Browse…", X = Pos.AnchorEnd(12), Y = 4 }; - browse.Accepted += (_, _) => + Ui.OnPress(browse, () => { var folder = Path.GetDirectoryName(path.Text.Trim()); if (Ui.PickSaveFile(app, "Save recording as", folder) is { } chosen) { path.Text = Path.HasExtension(chosen) ? chosen : chosen + ".har"; } - }; + }); dialog.Add( browse, new Label { Text = "JSON in HAR 1.2 format (HTTP Archive): opens in browser dev tools and HAR viewers.", X = 10, Y = 5, Width = Dim.Fill(1) }); diff --git a/src/TermRest.Tui/Dialogs/ScriptsDialog.cs b/src/TermRest.Tui/Dialogs/ScriptsDialog.cs index 427c956..d4c44e3 100644 --- a/src/TermRest.Tui/Dialogs/ScriptsDialog.cs +++ b/src/TermRest.Tui/Dialogs/ScriptsDialog.cs @@ -18,7 +18,7 @@ internal static class ScriptsDialog /// public static ScriptSet? Edit(IApplication app, string owner, ScriptSet scripts, string defaultLanguage) { - using var dialog = new Dialog { Title = $"Scripts of {owner}", Width = Dim.Percent(90), Height = Dim.Percent(80) }; + using var dialog = new Dialog { HotKeySpecifier = Ui.NoHotKey, Title = $"Scripts of {owner}", Width = Dim.Percent(90), Height = Dim.Percent(80) }; dialog.Add(new Label { X = 1, @@ -101,7 +101,9 @@ void Move(RuntimeRow row, int by) var clear = new Button { Text = "Clear values", X = Pos.AnchorEnd(18), Y = y }; dialog.Add(new Label { Text = "This session", X = 1, Y = y }, session, clear); y += 1; - var running = new Label { X = 14, Y = y, Width = Dim.Fill(22) }; + + // A runtime may be named after its file (my_node): an underscore must not make a key that presses Stop scripts. + var running = new Label { X = 14, Y = y, Width = Dim.Fill(22), HotKeySpecifier = Ui.NoHotKey }; var stop = new Button { Text = "Stop scripts", X = Pos.AnchorEnd(18), Y = y }; dialog.Add(running, stop); @@ -142,7 +144,7 @@ void Refresh() } user.SetScriptLanguageOrder(rows.Select(r => r.Language)); - user.Save(userDirectory); + Ui.TrySave(app, () => user.Save(userDirectory)); // applied for this session either way foreach (var language in ScriptLanguage.All) { runner.SetRuntime(language, user.GetScriptRuntime(language, workspace.RootPath)); @@ -198,6 +200,7 @@ private static RuntimeRow AddRuntime(IApplication app, Dialog dialog, ApiWorkspa { X = Pos.Right(check) + 2, Width = Dim.Fill(1), + HotKeySpecifier = Ui.NoHotKey, // paths and versions Text = current.Length == 0 ? $"None chosen: {ScriptLanguage.Label(language)} scripts do not run." : "", }; dialog.Add(find, check, status); @@ -234,7 +237,7 @@ void Run(Func> work) async Task<(string, string?)> Describe(string runtime) { - var (ok, message) = await ScriptRuntimeLocator.CheckAsync(language, runner.ResolveRuntime(runtime), workspace.RootPath).ConfigureAwait(false); + var (ok, message) = await ScriptRuntimeLocator.CheckAsync(language, runner.ResolveRuntime(runtime)).ConfigureAwait(false); return ((ok ? "✓ " : "✗ ") + message, null); } @@ -243,7 +246,11 @@ void Run(Func> work) if (Ui.PickFile(app, $"Choose {name}", workspace.RootPath) is { } path) { var relative = Path.GetRelativePath(workspace.RootPath, path); - field.Text = relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative) ? path : relative; + + // A name alone (bun.exe, in the workspace's own folder) would be a command, looked for on PATH. + field.Text = relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative) ? path + : relative.IndexOfAny(['/', '\\']) < 0 ? "." + Path.DirectorySeparatorChar + relative + : relative; var chosen = field.Text; Run(() => Describe(chosen)); } @@ -272,7 +279,7 @@ void Run(Func> work) }, null); } - return ("✓ " + found.Description, found.Runtime); + return ((found.Checked ? "✓ " : "") + found.Description, found.Runtime); })); return new RuntimeRow(language, label, field, browse, up, down, find, check, status); } diff --git a/src/TermRest.Tui/Dialogs/SettingsDialog.cs b/src/TermRest.Tui/Dialogs/SettingsDialog.cs index f3224f0..bc47212 100644 --- a/src/TermRest.Tui/Dialogs/SettingsDialog.cs +++ b/src/TermRest.Tui/Dialogs/SettingsDialog.cs @@ -2,68 +2,88 @@ using Terminal.Gui.App; using Terminal.Gui.ViewBase; using Terminal.Gui.Views; +using TermRest.Core.Postman; using TermRest.Core.Workspace; +using TermRest.Tui.Theming; namespace TermRest.Tui.Dialogs; /// Workspace settings (.termrest/settings.json): TLS verification, CA bundle, timeouts, redirects, proxy, history, formats. internal static class SettingsDialog { - public static bool Show(IApplication app, ApiWorkspace workspace) + /// + /// Edits the settings; true when they changed, which applies them for this session. says + /// whether they were saved to the file too (when not, an error said why). A proxy URL saved here is the user's own + /// choice: it is allowed for this workspace folder (see ), in the user's + /// settings in (default: ), as is whether + /// requests may send files from outside the folder (). + /// + public static bool Show(IApplication app, ApiWorkspace workspace, RequestRunner runner, out bool saved, string? userDirectory = null) { + saved = false; var settings = workspace.Settings; - using var dialog = new Dialog { Title = "Workspace settings", Width = Dim.Percent(80) }; + + // 80% of the screen, but at least 78 columns (all of a terminal of 80 but a margin): a dialog does not scroll, and + // every control fits in 78. + int Columns() => app.Driver?.Cols ?? 120; + using var dialog = new Dialog { Title = "Workspace settings", Width = Dim.Func(_ => Math.Min(Columns() - 2, Math.Max(78, Columns() * 4 / 5))) }; var y = 1; var strict = Ui.AddRow(dialog, "SSL verification", new CheckBox { Text = "Verify server certificates", Value = settings.StrictSsl ? CheckState.Checked : CheckState.UnChecked, Width = 30 }, y, 22); - y += 2; + y += 1; // a blank line only between groups of settings: the dialog fits a terminal of 30 rows var caBundle = Ui.AddRow(dialog, "Extra CA bundle", new TextField { Text = settings.CaBundle ?? "", Width = Dim.Fill(13) }, y, 22); var browse = new Button { Text = "Browse…", X = Pos.AnchorEnd(12), Y = y }; - browse.Accepted += (_, _) => + Ui.OnPress(browse, () => { if (Ui.PickFile(app, "Choose a PEM file with trusted CA certificates", workspace.RootPath) is { } path) { var relative = Path.GetRelativePath(workspace.RootPath, path); caBundle.Text = relative.StartsWith("..", StringComparison.Ordinal) ? path : relative.Replace('\\', '/'); } - }; + }); dialog.Add(browse); y += 1; - dialog.Add(new Label { Text = "Trusted in addition to the OS trust store (private/corporate CAs).", X = 24, Y = y }); + dialog.Add(Ui.Hint("Trusted in addition to the OS trust store (private/corporate CAs).", 24, y)); y += 2; var timeout = Ui.AddRow(dialog, "Timeout (ms)", new TextField { Text = settings.TimeoutMs.ToString(CultureInfo.InvariantCulture), Width = 12 }, y, 22); - dialog.Add(new Label { Text = "0 = no timeout (press Esc to cancel)", X = 38, Y = y }); - y += 2; + dialog.Add(Ui.Hint("0 = no timeout (press Esc to cancel)", 38, y)); + y += 1; var follow = Ui.AddRow(dialog, "Redirects", new CheckBox { Text = "Follow redirects", Value = settings.FollowRedirects ? CheckState.Checked : CheckState.UnChecked, Width = 20 }, y, 22); var maxRedirects = new TextField { X = 52, Y = y, Width = 6, Text = settings.MaxRedirects.ToString(CultureInfo.InvariantCulture) }; dialog.Add(new Label { Text = "max", X = 47, Y = y }, maxRedirects); - y += 2; - var proxy = Ui.AddRow(dialog, "Proxy", new TextField { Text = settings.Proxy ?? "system" }, y, 22); y += 1; - dialog.Add(new Label { Text = "system (OS / HTTPS_PROXY settings), none, or a URL like http://proxy:8080", X = 24, Y = y }); - y += 2; + // Its password masked, as everywhere else; left masked, it stays as it was (see Unmasked). + var shownProxy = settings.Proxy is { } current ? PostmanUrl.MaskCredentials(current) : "system"; + var proxy = Ui.AddRow(dialog, "Proxy", new TextField { Text = shownProxy }, y, 22); + y += 1; + var proxyHint = Ui.Hint("system (OS / HTTPS_PROXY settings), none, or a URL like http://proxy:8080", 24, y); + if (runner.BlockedProxy is not null) + { + proxyHint.Text = "⚠ Set by the workspace: not used until you save"; + proxyHint.SchemeName = ThemeCatalog.WarningScheme; + } + + dialog.Add(proxyHint); + 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 += 2; + y += 1; var maxSize = Ui.AddRow(dialog, "Max response (MB)", new TextField { Text = settings.MaxResponseSizeMb.ToString(CultureInfo.InvariantCulture), Width = 8 }, y, 22); y += 2; var history = Ui.AddRow(dialog, "History", new CheckBox { Text = "Record sent requests", Value = settings.HistoryEnabled ? CheckState.Checked : CheckState.UnChecked, Width = 24 }, y, 22); - var historyLimit = new TextField { X = 54, Y = y, Width = 6, Text = settings.HistoryLimit.ToString(CultureInfo.InvariantCulture) }; - var historyKb = new TextField { X = Pos.Right(historyLimit) + 22, Y = y, Width = 6, Text = settings.HistoryResponseKb.ToString(CultureInfo.InvariantCulture) }; - dialog.Add( - new Label { Text = "keep", X = 49, Y = y }, - historyLimit, - new Label { Text = "entries, bodies up to", X = Pos.Right(historyLimit) + 1, Y = y }, - historyKb, - new Label { Text = "KB", X = Pos.Right(historyKb) + 1, Y = y }); y += 1; - dialog.Add(new Label { Text = "Stored per user (not in the workspace); credentials and secret variables are masked.", X = 24, Y = y }); + var historyLimit = new TextField { X = 29, Y = y, Width = 6, Text = settings.HistoryLimit.ToString(CultureInfo.InvariantCulture) }; + var bodies = new Label { Text = "entries, bodies up to", X = Pos.Right(historyLimit) + 1, Y = y }; + var historyKb = new TextField { X = Pos.Right(bodies) + 1, Y = y, Width = 6, Text = settings.HistoryResponseKb.ToString(CultureInfo.InvariantCulture) }; + dialog.Add(new Label { Text = "Keep", X = 24, Y = y }, historyLimit, bodies, historyKb, new Label { Text = "KB", X = Pos.Right(historyKb) + 1, Y = y }); + y += 1; + dialog.Add(Ui.Hint("Stored per user (not in the workspace); credentials and secret variables are masked.", 24, y)); y += 2; var format = Ui.AddRow(dialog, "New collections", new OptionSelector { - Labels = ["Like this workspace", "Postman v2.1 JSON", "Postman v3 YAML folder"], + Labels = ["Like this workspace", "v2.1 JSON", "v3 YAML"], Orientation = Orientation.Horizontal, Value = settings.CollectionFormat switch { "v2.1" => 1, "v3" => 2, _ => 0 }, }, y, 22); - y += 2; + y += 1; var wrap = Ui.AddRow(dialog, "Wrap YAML lines", new OptionSelector { Labels = ["Like the files", "Never", "At column"], @@ -79,11 +99,20 @@ public static bool Show(IApplication app, ApiWorkspace workspace) }; dialog.Add(wrapWidth); y += 1; - dialog.Add(new Label { Text = "Postman v3 YAML files: only new and changed values are wrapped. Older Postman versions wrapped at 80.", X = 24, Y = y }); + dialog.Add(Ui.Hint("Postman v3 YAML files: only new and changed values are wrapped. Older Postman versions wrapped at 80.", 24, y)); y += 2; var redact = Ui.AddRow(dialog, "Recordings redact", new TextField { Text = string.Join(", ", settings.RecordingRedact ?? []) }, y, 22); y += 1; - dialog.Add(new Label { Text = "Extra header, parameter and field names, comma-separated (credentials, cookies and tokens always are).", X = 24, Y = y }); + dialog.Add(Ui.Hint("Extra header, parameter and field names, comma-separated (credentials, cookies and tokens always are).", 24, y)); + y += 2; + var outsideFiles = Ui.AddRow(dialog, "Outside files", new CheckBox + { + Text = "Allow files from outside this folder", + Value = runner.OutsideFilesAllowed ? CheckState.Checked : CheckState.UnChecked, + Width = 40, + }, y, 22); + y += 1; + dialog.Add(Ui.Hint("Body files, and certificates on network shares.", 24, y)); dialog.AddButton(new Button { Text = "Cancel" }); dialog.AddButton(new Button { Text = "Save" }); @@ -96,17 +125,22 @@ public static bool Show(IApplication app, ApiWorkspace workspace) } if (!int.TryParse(timeout.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var timeoutMs) || timeoutMs < 0 - || !int.TryParse(maxRedirects.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var redirects) || redirects < 1 + || !int.TryParse(maxRedirects.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var redirects) || redirects < 0 || !int.TryParse(maxSize.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var sizeMb) || sizeMb < 1 || !int.TryParse(historyLimit.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var keep) || keep < 1 || !int.TryParse(historyKb.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var bodyKb) || bodyKb < 0) { - Ui.Error(app, "Invalid settings", "Timeout must be ≥ 0, max redirects ≥ 1, max response size ≥ 1 MB, history ≥ 1 entry and body size ≥ 0 KB."); + Ui.Error(app, "Invalid settings", "Timeout must be ≥ 0, max redirects ≥ 0 (0 follows none), max response size ≥ 1 MB, history ≥ 1 entry and body size ≥ 0 KB."); continue; } - var proxyText = proxy.Text.Trim(); - if (proxyText is not ("" or "system" or "none") && !Uri.TryCreate(proxyText, UriKind.Absolute, out _)) + // "system" and "none" in any case, as requests read them; a URL's credentials left masked as shown, as they were. + var proxyText = Unmasked(proxy.Text.Trim(), shownProxy, settings.Proxy); + if (proxyText.ToLowerInvariant() is "" or "system" or "none") + { + proxyText = proxyText.ToLowerInvariant(); + } + else if (!Uri.TryCreate(proxyText, UriKind.Absolute, out _)) { Ui.Error(app, "Invalid proxy", "Use system, none, or a proxy URL such as http://proxy:8080."); continue; @@ -136,8 +170,42 @@ public static bool Show(IApplication app, ApiWorkspace workspace) settings.YamlLineWidth = wrap.Value switch { 1 => 0, 2 => lineWidth, _ => null }; var names = redact.Text.Split([',', ';'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); settings.RecordingRedact = names.Count == 0 ? null : names; - workspace.SaveSettings(); + saved = Ui.TrySave(app, workspace.SaveSettings); // applied for this session either way + saved &= SaveApprovals(app, workspace, runner, outsideFiles.Value == CheckState.Checked, userDirectory); return true; } } + + /// + /// with the user info it holds as showed it (masked) put back as it was + /// in : a proxy URL whose password was left masked keeps it, its host or port changed or not. + /// + internal static string Unmasked(string typed, string shown, string? original) + { + if (original is null || shown == original + || PostmanUrl.FindUserInfo(typed) is not var (start, length) + || PostmanUrl.FindUserInfo(shown) is not var (shownStart, shownLength) + || PostmanUrl.FindUserInfo(original) is not var (originalStart, originalLength) + || !typed.AsSpan(start, length).SequenceEqual(shown.AsSpan(shownStart, shownLength))) + { + return typed; + } + + return string.Concat(typed.AsSpan(0, start), original.AsSpan(originalStart, originalLength), typed.AsSpan(start + length)); + } + + /// + /// Allows the proxy URL the settings now name, if any, for this workspace folder, in place of the one allowed before, + /// and files from outside the folder or not: for this session, and in the user's settings. False when those could not + /// be saved (an error said why). + /// + private static bool SaveApprovals(IApplication app, ApiWorkspace workspace, RequestRunner runner, bool outsideFiles, string? userDirectory) + { + var proxy = workspace.Settings.Proxy; + runner.AllowedProxy = WorkspaceSettings.IsProxyUrl(proxy) ? proxy : null; + runner.OutsideFilesAllowed = outsideFiles; + var user = UserSettings.Load(userDirectory); + var changed = user.AllowProxy(workspace.RootPath, runner.AllowedProxy) | user.AllowOutsideFiles(workspace.RootPath, outsideFiles); + return !changed || Ui.TrySave(app, () => user.Save(userDirectory)); + } } diff --git a/src/TermRest.Tui/Dialogs/ThemeDialog.cs b/src/TermRest.Tui/Dialogs/ThemeDialog.cs index 967a5d2..1b942b8 100644 --- a/src/TermRest.Tui/Dialogs/ThemeDialog.cs +++ b/src/TermRest.Tui/Dialogs/ThemeDialog.cs @@ -73,7 +73,7 @@ void Fill(string? select) names.Clear(); foreach (var theme in themes) { - names.Add(theme.IsBuiltIn ? theme.Name : $"{theme.Name} *"); + names.Add(Ui.Drawable(theme.IsBuiltIn ? theme.Name : $"{theme.Name} *")); } list.Value = Math.Max(0, themes.FindIndex(t => string.Equals(t.Name, select, StringComparison.OrdinalIgnoreCase))); @@ -103,14 +103,20 @@ void Preview(ColorTheme theme) }; var copy = new Button { Text = "Copy as custom theme…", X = 1, Y = Pos.AnchorEnd(1) }; - copy.Accepted += (_, _) => + Ui.OnPress(copy, () => { var from = Selected(); - if (Ui.PromptText(app, "Copy as custom theme", $"Name of the new theme (a copy of {from.Name} you can edit)", $"My {from.Name}") is not { Length: > 0 } name) + if (Ui.PromptText(app, "Copy as custom theme", $"Name of the new theme (a copy of {from.Name} you can edit)", ThemeCatalog.FreeName(themes, $"My {from.Name}")) is not { Length: > 0 } name) { return; } + if (ThemeCatalog.FindCustom(themes, name) is { } taken) + { + Ui.Error(app, "Copy failed", $"A custom theme called '{taken.Name}' exists already ({taken.FilePath}): choose another name."); + return; + } + try { var path = ThemeCatalog.WriteCopy(from, name, userThemes); @@ -124,32 +130,38 @@ void Preview(ColorTheme theme) { Ui.Error(app, "Copy failed", ex.Message); } - }; + }); var reload = new Button { Text = "Reload theme files", X = Pos.Right(copy) + 1, Y = Pos.AnchorEnd(1) }; - reload.Accepted += (_, _) => + Ui.OnPress(reload, () => { var name = Selected().Name; errors.Clear(); themes = [.. ThemeCatalog.Load(workspace.RootPath, errors, userDirectory)]; Fill(name); - }; + }); dialog.Add(new Label { Text = "Themes (* custom)", X = 1, Y = 0 }, list, details, preview, workspaceOnly, folderLabel, folder, copy, reload); dialog.AddButton(new Button { Text = "Cancel" }); dialog.AddButton(new Button { Text = "Use theme" }); Fill(original.Name); list.SetFocus(); - app.Run(dialog); + ColorTheme? chosen = null; + try + { + app.Run(dialog); + chosen = dialog.Canceled ? null : Selected(); + } + finally + { + // Cancelled, or ended by an unexpected error: the theme shown before comes back, not the one previewed last. + ThemeCatalog.Apply(chosen ?? original); + } - if (dialog.Canceled) + if (chosen is not null) { - ThemeCatalog.Apply(original); - return null; + Ui.TrySave(app, () => Save(workspace, chosen, workspaceOnly.Value == CheckState.Checked, userDirectory)); } - var chosen = Selected(); - ThemeCatalog.Apply(chosen); - Save(workspace, chosen, workspaceOnly.Value == CheckState.Checked, userDirectory); return chosen; } diff --git a/src/TermRest.Tui/Dialogs/Ui.cs b/src/TermRest.Tui/Dialogs/Ui.cs index 5fb5b07..8d7782e 100644 --- a/src/TermRest.Tui/Dialogs/Ui.cs +++ b/src/TermRest.Tui/Dialogs/Ui.cs @@ -1,6 +1,10 @@ +using System.Text; using Terminal.Gui.App; +using Terminal.Gui.Text; using Terminal.Gui.ViewBase; using Terminal.Gui.Views; +using TermRest.Core.IO; +using TermRest.Tui.Views; namespace TermRest.Tui.Dialogs; @@ -13,24 +17,141 @@ public static void Error(IApplication app, string title, string message) => public static void Info(IApplication app, string title, string message) => MessageBox.Query(app, title, message, "OK"); + /// + /// Runs ; false, after saying why, when a file could not be written (or held settings that + /// could not be read, which saving would lose). + /// + public static bool TrySave(IApplication app, Action save) + { + try + { + save(); + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Error(app, "Save failed", ex.Message); + return false; + } + } + + /// A file to save: Save(overwriteChanged). Saves without a name are not listed as saved. + public sealed record SaveItem(string? Name, Action Save); + + /// + /// Saves each item on its own, so one that cannot be saved does not keep the others from being saved, and says once + /// why any could not be. Files another program changed since they were read (a git pull, Postman, an editor) are + /// overwritten only when the user says so (Cancel is the default). Returns the names saved and the names left + /// unsaved because they changed on disk. Errors other than disk and permission problems are bugs: their details are + /// logged where unexpected errors go (). + /// + public static (List Saved, List Changed) SaveEach(IApplication app, string rootPath, IEnumerable items) + { + var saved = new List(); + var failed = new List(); + var changed = new List<(SaveItem Item, IReadOnlyList Paths)>(); + string? log = null; + + bool TryOne(SaveItem item, bool overwrite) + { + try + { + item.Save(overwrite); + if (item.Name is not null) + { + saved.Add(item.Name); + } + + return true; + } + catch (FileChangedException ex) when (!overwrite) + { + changed.Add((item, ex.Paths)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + failed.Add(ex.Message); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + failed.Add(item.Name is null ? ex.Message : $"{item.Name}: {ex.Message}"); + log = LogError(ex) ?? log; + } + + return false; + } + + foreach (var item in items) + { + TryOne(item, overwrite: false); + } + + if (changed.Count > 0 && ConfirmOverwrite(app, rootPath, changed.SelectMany(c => c.Paths))) + { + var overwriting = changed.ToList(); + changed.Clear(); + foreach (var (item, _) in overwriting) + { + TryOne(item, overwrite: true); + } + } + + if (failed.Count > 0) + { + Error(app, "Save failed", string.Join("\n\n", failed) + (log is null ? "" : $"\n\nDetails were written to {log}")); + } + + return (saved, changed.Select(c => c.Item.Name).OfType().ToList()); + } + + /// Logs an unexpected error; returns the log's path, or null when it could not be written either. + private static string? LogError(Exception exception) + { + try + { + return TuiApp.LogUnexpectedError(exception); + } + catch (Exception) + { + return null; // the error is shown all the same + } + } + + private static bool ConfirmOverwrite(IApplication app, string rootPath, IEnumerable paths) + { + const int Shown = 8; + var all = paths.Select(p => Path.GetRelativePath(rootPath, p)).ToList(); + var files = string.Join("\n", all.Take(Shown)) + (all.Count > Shown ? $"\n…and {all.Count - Shown} more" : ""); + return MessageBox.Query(app, "Changed on disk", + $"These files changed on disk since TermRest read them (a git pull, Postman, an editor):\n\n{files}\n\n" + + "Saving would undo those changes. To keep them instead, choose Cancel and load them again: pick a JSON collection " + + "again with File › Import Postman collection…, or quit without saving and start TermRest again. " + + "Your unsaved changes to them are then lost.", + "Overwrite", "Cancel") == 0; + } + /// /// Shows text as written: left-aligned, line by line, so columns and "label: value" lists line up (a message box /// centers each line). Lines wider than the screen wrap at a space or path separator, indented. Underscores are - /// shown as they are, not taken as hotkey markers. + /// shown as they are, not taken as hotkey markers. A text taller than the screen scrolls (wheel, arrows, PgDn). /// public static void ShowText(IApplication app, string title, string text) { var width = Math.Max(20, (app.Driver?.Cols ?? 120) - 8); - var lines = text.ReplaceLineEndings("\n").TrimEnd('\n').Split('\n').SelectMany(line => Wrap(line, width)); + var lines = text.ReplaceLineEndings("\n").TrimEnd('\n').Split('\n').SelectMany(line => Wrap(line, width)).ToList(); using var dialog = new Dialog { Title = title }; - dialog.Add(new Label - { - Text = string.Join('\n', lines), - X = 1, - Y = 1, - TextAlignment = Alignment.Start, - HotKeySpecifier = new System.Text.Rune(0xFFFF), - }); + + // As large as the text, with a column for the scroll bar a taller text shows, and at most as large as the screen; a + // screen made narrower wraps the text again. + dialog.Width = Dim.Auto( + minimumContentDim: Math.Max(lines.Max(line => line.GetColumns()) + 3, title.GetColumns() + 4), + maximumContentDim: Dim.Percent(100) - Dim.Func(_ => dialog.GetAdornmentsThickness().Horizontal)); + dialog.Height = Dim.Auto( + minimumContentDim: lines.Count + 1, + maximumContentDim: Dim.Percent(100) - Dim.Func(_ => dialog.GetAdornmentsThickness().Vertical)); + var area = new TextArea { X = 1, Y = 1, Width = Dim.Fill(1), Height = Dim.Fill(), ReadOnly = true, WordWrap = true }; + area.SetText(string.Join('\n', lines)); + dialog.Add(area); dialog.AddButton(new Button { Text = "OK" }); app.Run(dialog); } @@ -46,7 +167,8 @@ internal static IEnumerable Wrap(string line, int width) var cut = line.LastIndexOfAny([' ', '\\', '/'], width - 1) + 1; if (cut <= width / 2) { - cut = width; + // Not inside a character: half of one can't be shown. + cut = width > 1 && char.IsHighSurrogate(line[width - 1]) ? width - 1 : width; } yield return line[..cut].TrimEnd(); @@ -56,20 +178,65 @@ internal static IEnumerable Wrap(string line, int width) yield return line; } + /// + /// with U+FFFD for each character outside the BMP (most emoji), for Terminal.Gui views that + /// cut text by UTF-16 index and fail on half of a pair: the tree draws each UTF-16 unit of a line in a cell of its own, + /// and a list scrolled sideways cuts its rows at the column scrolled to. + /// + public static string Drawable(string text) + { + if (!text.AsSpan().ContainsAnyInRange('\uD800', '\uDFFF')) + { + return text; + } + + var drawable = new StringBuilder(text.Length); + foreach (var rune in text.EnumerateRunes()) + { + drawable.Append(rune.IsBmp ? (char)rune.Value : '\uFFFD'); + } + + return drawable.ToString(); + } + public static bool Confirm(IApplication app, string title, string message, string yes = "Yes", string no = "No") => MessageBox.Query(app, title, message, no, yes) == 1; - /// Asks for a single line of text. Returns null when cancelled. + /// + /// For : no hotkey, so underscores show as they are. Names, paths and messages + /// must be shown so: else the first underscore (dev_local) is hidden and the letter after it becomes a key that + /// presses something. A frame or dialog sizes its title as it is set: set this before such a title. + /// + public static readonly System.Text.Rune NoHotKey = new(0xFFFF); + + /// + /// Makes a status bar or menu item show its title as written (see ): the item, and the + /// command view that shows its title. + /// + public static T AsWritten(T shortcut) + where T : Shortcut + { + shortcut.HotKeySpecifier = NoHotKey; + shortcut.CommandView?.HotKeySpecifier = NoHotKey; + return shortcut; + } + + /// A label that shows as written: underscores (HTTPS_PROXY) are not hotkey markers. + public static Label Hint(string text, Pos x, Pos y) => new() { Text = text, X = x, Y = y, HotKeySpecifier = NoHotKey }; + + /// Asks for a single line of text, without the spaces around it (spaces alone are no name). Returns null when cancelled. public static string? PromptText(IApplication app, string title, string label, string initial = "", int width = 60) { using var dialog = new Dialog { Title = title }; - var caption = new Label { Text = label, X = 1, Y = 1 }; + + // The label may hold a name: a collection's, a folder's, a theme's. + var caption = new Label { Text = label, X = 1, Y = 1, HotKeySpecifier = NoHotKey }; var field = new TextField { X = 1, Y = 2, Width = width, Text = initial }; dialog.Add(caption, field); dialog.AddButton(new Button { Text = "Cancel" }); dialog.AddButton(new Button { Text = "OK" }); app.Run(dialog); - return dialog.Canceled ? null : field.Text; + return dialog.Canceled ? null : field.Text.Trim(); } /// Shows a file picker. Returns the chosen path or null. diff --git a/src/TermRest.Tui/MainWindow.cs b/src/TermRest.Tui/MainWindow.cs index c0fa9d0..b484f7e 100644 --- a/src/TermRest.Tui/MainWindow.cs +++ b/src/TermRest.Tui/MainWindow.cs @@ -37,11 +37,17 @@ internal sealed class MainWindow : Runnable private readonly Shortcut _environmentShortcut; private readonly RecordingIndicator _recordIndicator; private readonly Shortcut _message; + + /// Cancels the requests still on their way when the window closes, those of requests no longer shown too. + private readonly CancellationTokenSource _closing = new(); private MenuItem? _recordMenuItem; private PostmanCollection? _collection; private RequestNode? _node; private PostmanCollection? _scratch; private CancellationTokenSource? _sending; + + /// Counts the requests shown in the editor, so that a response arriving for an earlier one is not shown under another. + private int _opened; private bool _closed; private PopoverMenu? _popover; private bool _quitConfirmed; @@ -51,12 +57,21 @@ internal sealed class MainWindow : Runnable /// The history entry shown in the editor (a detached request), if any. private HistoryEntry? _historyEntry; + /// + /// The request in its collection that the history entry shown was sent from, while it is still there: a request sent + /// again from history runs with its folders' scripts and inherits their auth (it is not edited). + /// + private RequestNode? _historyOrigin; + /// Name suggested when a detached request (cURL import, history) is added to a collection. private string? _detachedName; /// Where the last recording was saved this session (the next one is suggested there). private string? _recordingFolder; + /// The recording error last shown in the status bar: each is shown once (see ). + private string? _recordingErrorShown; + /// What the tree showed for the current collection when last refreshed it. private (object? Item, bool Dirty, string? Name) _treeTitleState; @@ -86,6 +101,7 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) _requestFrame = new FrameView { + HotKeySpecifier = Ui.NoHotKey, // its title names the request Title = "Request", X = Pos.Right(_sidebar), Y = Pos.Bottom(_menu), @@ -101,8 +117,12 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) // Where a relative body file is looked for when sending: the folder of the collection sending it. BaseDirectory = () => (_collection ?? _scratch)?.BaseDirectory ?? Environment.CurrentDirectory, - // The request's scripts run with those of its collection and folders, in one language. - ScriptPlanner = (scripts, settings) => _collection is { } collection ? _runner.PlanScripts(collection, _node, scripts, settings) : null, + // Body files from outside the workspace folder are not sent, nor looked at, unless allowed (Tools › Settings). + FilesFolder = () => _runner.FilesFolder, + + // The request's scripts run with those of its collection and folders, in one language (a request typed into the + // editor a delete emptied is a scratch request, as Send has it). + ScriptPlanner = (scripts, settings) => _runner.PlanScripts(_collection ?? (_scratch ??= PostmanCollection.Create("Scratch")), SendContext, scripts, settings), DefaultScriptLanguage = _runner.ScriptLanguageOrder[0], }; _requestFrame.Add(_editor); @@ -118,18 +138,20 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) _response = new ResponseView(); _responseFrame.Add(_response); - _environmentShortcut = new Shortcut { Title = EnvironmentLabel(), Key = Key.F7, BindKeyToApplication = true, Action = ShowEnvironmentMenu }; - _message = new Shortcut { Title = "", CanFocus = false }; + // Window shortcuts, not application-wide ones: they must not act behind an open dialog. Names and messages are + // shown as written. + _environmentShortcut = Ui.AsWritten(new Shortcut { Title = EnvironmentLabel(), Key = Key.F7, Action = ShowEnvironmentMenu }); + _message = Ui.AsWritten(new Shortcut { Title = "", CanFocus = false }); var statusBar = new StatusBar( [ - new Shortcut { Title = "Send", Key = Key.F5, BindKeyToApplication = true, Action = Send }, - new Shortcut { Title = "Save", Key = Key.S.WithCtrl, BindKeyToApplication = true, Action = Save }, - new Shortcut { Title = "New", Key = Key.N.WithCtrl, BindKeyToApplication = true, Action = NewRequest }, + new Shortcut { Title = "Send", Key = Key.F5, Action = Send }, + new Shortcut { Title = "Save", Key = Key.S.WithCtrl, Action = Save }, + new Shortcut { Title = "New", Key = Key.N.WithCtrl, Action = NewRequest }, _environmentShortcut, - new Shortcut { Title = "Certs", Key = Key.F8, BindKeyToApplication = true, Action = ShowCertificates }, - new Shortcut { Title = "History", Key = Key.F9, BindKeyToApplication = true, Action = ToggleHistory }, + new Shortcut { Title = "Certs", Key = Key.F8, Action = ShowCertificates }, + new Shortcut { Title = "History", Key = Key.F9, Action = ToggleHistory }, new Shortcut { Title = "Menu", Key = Key.F10 }, - new Shortcut { Title = "Quit", Key = Key.Q.WithCtrl, BindKeyToApplication = true, Action = Quit }, + new Shortcut { Title = "Quit", Key = Key.Q.WithCtrl, Action = Quit }, _message, ]); @@ -151,7 +173,12 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) { if (item is RequestNode request) { - OpenRequest(request); + // The request open already only goes to its URL bar: opening it again would clear its response. + if (request != _node) + { + OpenRequest(request); + } + _editor.FocusUrl(); } }; @@ -188,6 +215,12 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) Notify($"⚠ {workspace.LoadErrors.Count} problem(s) loading files or the color theme (Help > Workspace info)"); } + if (runner.BlockedProxy is not null) + { + const string notice = "The proxy in this workspace's settings (.termrest/settings.json) is not used until you allow it: Tools > Settings > Save"; + Notify(_message.Title.Length > 0 ? $"{_message.Title} · {notice}" : $"⚠ {notice}"); + } + if (RequestRecorder.FindUnsaved().Count is > 0 and var unsaved) { var notice = $"{unsaved} unsaved recording(s) found: Tools > Recover unsaved recordings"; @@ -195,8 +228,11 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) } } - /// Set when the user opens another workspace; the host restarts the UI with it. - public string? NextWorkspacePath { get; private set; } + /// Set when the user opens another workspace (opened already): the host restarts the UI with it. + public ApiWorkspace? NextWorkspace { get; private set; } + + /// Whether the request shown is on its way (the UI stays quick until its response is shown). + internal bool IsSending => _sending is not null; // Test hooks (InternalsVisibleTo TermRest.Tui.Tests). internal RequestEditor Editor => _editor; @@ -224,15 +260,17 @@ public MainWindow(ApiWorkspace workspace, RequestRunner runner) /// Selects and opens a request (used by snapshots and tests). internal void ShowRequest(RequestNode node) { - _tree.Select(node); - OpenRequest(node); + if (OpenRequest(node)) + { + _tree.Select(node); + } } /// Sends the current request and shows the result without an event loop (used by snapshots). internal async Task SendAndShowAsync(CancellationToken cancellationToken = default) { var collection = _collection ?? (_scratch ??= PostmanCollection.Create("Scratch")); - var exchange = await _runner.SendAsync(collection, _node, _editor.Spec, null, cancellationToken).ConfigureAwait(false); + var exchange = await _runner.SendAsync(collection, SendContext, _editor.Spec, null, cancellationToken).ConfigureAwait(false); _response.ShowExchange(exchange); } @@ -297,16 +335,29 @@ internal async Task SendAndShowAsync(CancellationToken cancellationToken = defau // ----- request lifecycle ----------------------------------------------------------------- - private void OpenRequest(RequestNode node) + /// Opens a request in the editor; false when the user keeps the one there (see ). + private bool OpenRequest(RequestNode node) { + if (!ConfirmDiscardRequest()) + { + return false; + } + CommitEditor(); + if (node != _node) + { + DetachSending(); + } + _collection = node.Collection; _node = node; _historyEntry = null; + _historyOrigin = null; _detachedName = null; _editor.Load(node.ReadSpec()); ClearResponse(); UpdateTitles(); + return true; } private void StartScratchRequest() @@ -315,6 +366,7 @@ private void StartScratchRequest() _collection = _scratch; _node = null; _historyEntry = null; + _historyOrigin = null; _detachedName = null; _editor.Load(new HttpRequestSpec { Url = "https://postman-echo.com/get?hello=world" }); ClearResponse(); @@ -339,7 +391,72 @@ private void CommitEditor() UpdateTitles(); } + /// + /// Before the request in the editor makes way for another: one that is not in a collection (scratch, imported, from + /// history) and was changed would be lost, so the user may add it to a collection first. False when the user cancels. + /// + private bool ConfirmDiscardRequest() + { + if (_node is not null || !_editor.IsModified) + { + return true; + } + + return MessageBox.Query(App!, "Unsaved request", "This request is not in a collection, so your changes to it would be lost.", + "Cancel", "Discard", "Add to collection…") switch + { + 2 => AddToCollection(), + 1 => true, + _ => false, + }; + } + + /// Adds the request in the editor to a collection (asking where and its name), then edits it there; false when cancelled. + private bool AddToCollection() + { + if (AddRequest() is not { } node) + { + return false; + } + + Adopt(node); + return true; + } + + /// + /// The request in the editor, now in a collection, is edited there: it keeps its response, and + /// one still on its way is shown under it. What the editor says about its context (inherited auth, scripts) is redone. + /// + private void Adopt(RequestNode node) + { + _collection = node.Collection; + _node = node; + _historyEntry = null; + _historyOrigin = null; + _detachedName = null; + _editor.RefreshContext(); + UpdateTitles(); + } + + /// + /// Sends the request shown, or cancels the one on its way. No exception may leave this async void method: .NET would + /// post it to the UI's synchronization context, which throws it back at once, then throw it on the thread pool, ending + /// TermRest (and losing unsaved changes). It goes where the main loop's unexpected errors go instead: shown and logged. + /// private async void Send() + { + try + { + await SendAsync(); + } + catch (Exception ex) + { + // Once the window no longer runs (quit, another workspace), there is nothing to show it in. + TuiApp.ReportUnexpectedError(IsRunning ? App : null, ex); + } + } + + private async Task SendAsync() { if (_sending is not null) { @@ -354,13 +471,22 @@ private async void Send() return; } + // Sending *** for a password could count as a failed sign-in (and lock the account): Cancel is the default. + if (HasMaskedCredentials + && MessageBox.Query(App!, "Masked credentials", "This request has *** for credentials the history masked. Enter them again before sending it.", + "Send ***", "Cancel") != 0) + { + return; + } + var collection = _collection ?? (_scratch ??= PostmanCollection.Create("Scratch")); var previous = _response.Exchange; + var opened = _opened; PreparedRequest? prepared = null; _response.ShowRunningScripts(); // replaced at once when there are no pre-request scripts SetResponseTitle(null); _editor.SetSending(true); - using var cancellation = new CancellationTokenSource(); + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(_closing.Token); _sending = cancellation; var recorder = _runner.Recorder; var recordedBefore = recorder?.Count ?? 0; @@ -368,10 +494,13 @@ private async void Send() try { // Scripts run first; the request is shown as soon as it is ready to go. - exchange = await _runner.SendAsync(collection, _node, _editor.Spec, ready => + exchange = await _runner.SendAsync(collection, SendContext, _editor.Spec, ready => { prepared = ready; - _response.ShowSending(ready); + if (opened == _opened) + { + _response.ShowSending(ready); + } }, cancellation.Token); } catch (Exception ex) @@ -379,12 +508,22 @@ private async void Send() if (prepared is null) { // It could not even be prepared (a certificate that does not load…): nothing was sent. - _sending = null; + if (_sending == cancellation) + { + _sending = null; + } + if (_closed) { return; } + if (opened != _opened) + { + Notify($"⚠ Earlier request not sent: {ex.Message}"); + return; + } + _editor.SetSending(false); if (previous is null) { @@ -403,7 +542,10 @@ private async void Send() } finally { - _sending = null; + if (_sending == cancellation) + { + _sending = null; + } } // The window may have been closed (quit, workspace switch) while the request was in flight. @@ -412,11 +554,26 @@ private async void Send() return; } - _editor.SetSending(false); - _response.ShowExchange(exchange); + // Another request may have been opened meanwhile: the response is not shown under it (the history has it). + var shown = opened == _opened; + if (shown) + { + _editor.SetSending(false); + _response.ShowExchange(exchange); + } + var recordedAs = recorder is not null && ReferenceEquals(recorder, _runner.Recorder) && recorder.Count > recordedBefore ? recorder.Count : (int?)null; - SetResponseTitle(recordedAs); + if (shown) + { + SetResponseTitle(recordedAs); + } + var result = exchange.Response is null ? "" : $"{exchange.Request.Method} {exchange.Request.Uri?.Host} → {exchange.Response.StatusCode}"; + if (!shown) + { + result = $"Earlier request: {(result.Length > 0 ? result : exchange.ErrorMessage)}"; + } + if (recordedAs is not null && exchange.Request.Body.HasFiles) { result += (result.Length == 0 ? "" : " · ") + "● recorded with the file's path, not its content"; @@ -434,34 +591,12 @@ private async void Send() private void Save() { CommitEditor(); - var saved = new List(); - try - { - foreach (var collection in _workspace.Collections.Where(c => c.IsDirty)) - { - collection.Save(); - saved.Add(Path.GetFileName(collection.FilePath!)); - } - - foreach (var environment in _workspace.Environments.Where(e => e.IsDirty)) - { - environment.Save(); - saved.Add(Path.GetFileName(environment.FilePath!)); - } - - if (_workspace.Globals?.IsDirty == true) - { - _workspace.Globals.Save(); - } - - _workspace.SaveSettings(); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + var (saved, changed) = Ui.SaveEach(App!, _workspace.RootPath, SaveItems(_workspace, includeCollections: true)); + if (changed.Count > 0) { - Ui.Error(App!, "Save failed", ex.Message); + Notify($"⚠ Not saved: {string.Join(", ", changed)} changed on disk."); } - - if (_node is null && _editor.IsModified) + else if (_node is null && _editor.IsModified) { Notify("This request is not in a collection yet: press Ctrl+N (Request > New request) to add it to one."); } @@ -474,6 +609,28 @@ private void Save() UpdateTitles(); } + /// What saving writes: changed collections (when asked), environments and globals, then the settings. + internal static IEnumerable SaveItems(ApiWorkspace workspace, bool includeCollections) + { + var collections = includeCollections ? workspace.Collections.Where(c => c.IsDirty).ToList() : []; + foreach (var collection in collections) + { + yield return new(Path.GetFileName(collection.FilePath!), overwrite => collection.Save(overwriteChanged: overwrite)); + } + + foreach (var environment in workspace.Environments.Where(e => e.IsDirty).ToList()) + { + yield return new(Path.GetFileName(environment.FilePath!), overwrite => environment.Save(overwriteChanged: overwrite)); + } + + if (workspace.Globals is { IsDirty: true } globals) + { + yield return new(Path.GetFileName(globals.FilePath!), overwrite => globals.Save(overwriteChanged: overwrite)); + } + + yield return new(null, _ => workspace.SaveSettings()); + } + // ----- tree operations ------------------------------------------------------------------- private FolderNode? TargetFolder() @@ -489,12 +646,47 @@ private void Save() private void NewRequest() { + var adopting = _node is null; // the request in the editor becomes the new one (see AddRequest) + if (AddRequest() is not { } node) + { + return; + } + + if (adopting) + { + // Before the tree selects it, which would open it as another request (clearing its response, detaching its send). + Adopt(node); + _tree.Select(node); + } + else + { + _tree.Select(node); + OpenRequest(node); + } + + _editor.FocusUrl(); + } + + /// + /// Asks for a name and adds a request to the selected folder (or a new collection): the request in the editor when it + /// is not in a collection yet (scratch, imported, from history), else an empty one. Null when cancelled. + /// + private RequestNode? AddRequest() + { + // The request shown becomes the new one (it is not in a collection): with *** in it, the collection would send ***. + if (HasMaskedCredentials + && MessageBox.Query(App!, "Masked credentials", "This request has *** for credentials the history masked: added to a collection like this, it would keep sending ***. Type them again first.", + "Add with ***", "Cancel") != 0) + { + return null; + } + var folder = TargetFolder(); if (folder is null) { if (!NewCollection()) { - return; + return null; } folder = _workspace.Collections[^1].RootNode; @@ -502,7 +694,7 @@ private void NewRequest() if (Ui.PromptText(App!, "New request", $"Name (in {folder.Collection.Name}{(folder is CollectionRootNode ? "" : " / " + folder.PathInCollection)})", _detachedName ?? "New request") is not { Length: > 0 } name) { - return; + return null; } CommitEditor(); @@ -511,13 +703,12 @@ private void NewRequest() { // A scratch, imported or history request becomes the new request. spec = _editor.Spec.Clone(); + _editor.MarkClean(); } var node = folder.Collection.AddRequest(folder, name.Trim(), spec); _tree.RefreshItem(folder is CollectionRootNode ? folder.Collection : folder); - _tree.Select(node); - OpenRequest(node); - _editor.FocusUrl(); + return node; } private bool NewCollection() @@ -587,10 +778,9 @@ private void DuplicateItem(object? item) CommitEditor(); var copy = node.Collection.Duplicate(node); _tree.RefreshItem(node.Parent is CollectionRootNode ? node.Collection : node.Parent); - _tree.Select(copy); - if (copy is RequestNode request) + if (copy is not RequestNode request || OpenRequest(request)) { - OpenRequest(request); + _tree.Select(copy); } } @@ -613,23 +803,38 @@ private void DeleteItem(object? item) return; } - if (_node is not null && (_node == node || _node.Ancestors().Contains(node))) + // 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)); + if (openDeleted) { _node = null; _editor.MarkClean(); } + // A request from history sent from the deleted request is sent on its own from now on. + var forgetOrigin = _historyOrigin is not null && (_historyOrigin == node || _historyOrigin.Ancestors().Contains(node)); + var originGone = forgetOrigin ? ForgetHistoryOrigin() : null; + node.Collection.Remove(node); _tree.RefreshItem(parent is CollectionRootNode ? parent.Collection : parent); _tree.RefreshItem(node.Collection); - if (_node is null) + if (openDeleted) { + DetachSending(); _collection = null; _editor.Load(new HttpRequestSpec()); ClearResponse(); } + else if (forgetOrigin) + { + _editor.RefreshContext(); // without the folders it inherited auth and scripts from + } UpdateTitles(); + if (originGone is not null) + { + Notify(originGone); + } } private void ShowContextMenu(System.Drawing.Point? position) @@ -658,16 +863,32 @@ private void ShowContextMenu(System.Drawing.Point? position) items.Add(new MenuItem("Scrip_ts…", "", () => EditScripts(TargetFolder()))); } - if (item is RequestNode) + if (item is RequestNode request) { + // On the right-clicked request: the editor may show another one (from history, imported…) while it stays selected. items.Add(new Line()); - items.Add(new MenuItem("_Send", "", Send)); - items.Add(new MenuItem("Copy as c_URL", "", CopyAsCurl)); + items.Add(new MenuItem("_Send", "", () => + { + if (UseRequest(request)) + { + Send(); + } + })); + items.Add(new MenuItem("Copy as c_URL", "", () => + { + if (UseRequest(request)) + { + CopyAsCurl(); + } + })); } ShowPopover(items, position); } + /// Opens a request for an action on it, unless it is open already: then the action takes the changes made to it. + private bool UseRequest(RequestNode request) => request == _node || OpenRequest(request); + // ----- environments, certificates, settings -------------------------------------------- private void ShowEnvironmentMenu() @@ -679,7 +900,7 @@ private void ShowEnvironmentMenu() foreach (var environment in _workspace.Environments) { var env = environment; - items.Add(new MenuItem($"{(env == _workspace.ActiveEnvironment ? "● " : " ")}{env.Name}", "", () => SetEnvironment(env))); + items.Add(Ui.AsWritten(new MenuItem($"{(env == _workspace.ActiveEnvironment ? "● " : " ")}{_workspace.DisplayName(env)}", "", () => SetEnvironment(env)))); } items.Add(new Line()); @@ -690,17 +911,23 @@ private void ShowEnvironmentMenu() private void SetEnvironment(PostmanEnvironment? environment) { _workspace.ActiveEnvironment = environment; - _workspace.SaveSettings(); + Ui.TrySave(App!, _workspace.SaveSettings); _environmentShortcut.Title = EnvironmentLabel(); _editor.RefreshCertificateInfo(); - Notify($"Environment: {environment?.Name ?? "none"}"); + Notify($"Environment: {(environment is null ? "none" : _workspace.DisplayName(environment))}"); } private void ShowEnvironments() { - EnvironmentsDialog.Show(App!, _workspace); - _environmentShortcut.Title = EnvironmentLabel(); - _editor.RefreshCertificateInfo(); + try + { + EnvironmentsDialog.Show(App!, _workspace); + } + finally + { + _environmentShortcut.Title = EnvironmentLabel(); + _editor.RefreshCertificateInfo(); + } } private void ShowCertificates() @@ -721,16 +948,21 @@ private void ShowCertificates() private void ShowSettings() { - if (SettingsDialog.Show(App!, _workspace)) + if (SettingsDialog.Show(App!, _workspace, _runner, out var saved)) { _runner.ConfigureHistory(); + _editor.RefreshBodyFile(); // files from outside the workspace folder may be allowed now, or no longer if (_historyLoaded) { LoadHistory(); UpdateSidebarTitle(); } - Notify("Settings saved."); + // A recording that is on redacts the names added to the settings from now on, and keeps any removed. + var added = _runner.Recorder?.AddRedactNames(_workspace.Settings.RecordingRedact ?? []) ?? []; + var done = saved ? "Settings saved." : "Settings applied for this session, not saved."; + Notify(added.Count == 0 ? done + : $"{done} The recording also redacts {string.Join(", ", added)} from now on; requests already recorded are unchanged."); } } @@ -881,6 +1113,14 @@ private void ToggleRecording() return; } + // The settings may name more values to redact: a recording made without them could keep those secrets. + if (_workspace.SettingsError is { } settingsError) + { + Ui.Error(App!, "Recording", "The recording could not start: the workspace settings could not be read, so the extra names to redact " + + $"(recordingRedact) are unknown. Fix or delete the file, then open the workspace again.\n\n{settingsError}"); + return; + } + RequestRecorder recorder; try { @@ -997,8 +1237,12 @@ private void UpdateRecording() { _recordIndicator.ShowRecording(recorder.StartedAt, recorder.Count); _recordMenuItem?.Title = "Stop _recording and save…"; - if (recorder.LastError is { } error && _message.Title != "⚠ " + error) + + // Once, not again over every later message (a response's status). Compared by reference: each failure sets + // a new message, so a request that cannot be recorded for the same reason again is said again. + if (recorder.LastError is { } error && !ReferenceEquals(error, _recordingErrorShown)) { + _recordingErrorShown = error; Notify("⚠ " + error); } } @@ -1038,6 +1282,20 @@ private void ClearResponse() SetResponseTitle(null); } + /// + /// 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. + /// + private void DetachSending() + { + _opened++; + if (_sending is not null) + { + _sending = null; + _editor.SetSending(false); + } + } + private void OnThemeChanged(object? sender, EventArgs e) => _recordIndicator.SetNeedsDraw(); private void ClearCookies() @@ -1084,37 +1342,60 @@ private string DescribeCertificate(HttpRequestSpec spec) private string DescribeInheritedAuth() { - if (_node is null) + // A v3 collection's or folder's credential sets: the URL selects one when the request is sent. + static string Describe(AuthSpec auth) => auth.CredentialSets is { } sets + ? $"the first of its credential sets ({string.Join(", ", sets.Select(s => s.Name))}) whose URL rules match" + : AuthSpec.DisplayName(auth.Type) ?? auth.Type; + + if (SendContext is not { } node) { - return _collection?.RootNode.Auth is { } rootAuth ? $"Collection auth: {AuthSpec.DisplayName(rootAuth.Type)}" : "No auth is set on the collection."; + return _collection?.RootNode.Auth is { } rootAuth ? $"Collection auth: {Describe(rootAuth)}" : "No auth is set on the collection."; } - foreach (var folder in _node.Ancestors()) + foreach (var folder in node.Ancestors()) { if (folder.Auth is { } auth) { var source = folder is CollectionRootNode ? "the collection" : $"folder '{folder.Name}'"; - return $"Currently: {AuthSpec.DisplayName(auth.Type)} from {source}."; + return auth.CredentialSets is null ? $"Currently: {Describe(auth)} from {source}." : $"Currently: from {source}, {Describe(auth)}."; } } return "No folder or collection auth is set, so no auth is sent."; } - private string EnvironmentLabel() => $"Env: {_workspace.ActiveEnvironment?.Name ?? "none"}"; + private string EnvironmentLabel() => $"Env: {(_workspace.ActiveEnvironment is { } active ? _workspace.DisplayName(active) : "none")}"; // ----- workspace --------------------------------------------------------------------------- private void OpenWorkspace() { - if (Ui.PickFile(App!, "Open workspace folder", _workspace.RootPath, directory: true) is not { } path || !ConfirmUnsaved()) + if (Ui.PickFile(App!, "Open workspace folder", _workspace.RootPath, directory: true) is { } path) + { + OpenWorkspaceFrom(path); + } + } + + /// Opens another workspace (after asking about unsaved changes): the host restarts the UI with it. + internal void OpenWorkspaceFrom(string path) + { + if (!ConfirmUnsaved()) + { + return; + } + + try { + NextWorkspace = ApiWorkspace.Open(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Ui.Error(App!, "Cannot open workspace", ex.Message); return; } - NextWorkspacePath = path; _quitConfirmed = true; - App!.RequestStop(); + RequestStop(); } private void ImportCollection() @@ -1142,10 +1423,11 @@ internal void ImportCollectionFrom(string path) return; } - var collection = _workspace.ImportCollection(path); + var collection = _workspace.ImportCollection(path, out var secretValuesLeftOut); _tree.Reload(_workspace); _tree.Select(collection); - Notify($"Imported '{collection.Name}' into {Path.GetRelativePath(_workspace.RootPath, collection.FilePath!)}"); + var leftOut = secretValuesLeftOut.Count == 0 ? "" : $" · ⚠ the values of its secret variables ({string.Join(", ", secretValuesLeftOut)}) are not written, as in Postman's v3 collections: set them in an environment"; + Notify($"Imported '{collection.Name}' into {Path.GetRelativePath(_workspace.RootPath, collection.FilePath!)}{leftOut}"); } catch (Exception ex) { @@ -1156,15 +1438,37 @@ internal void ImportCollectionFrom(string path) private void ReloadCollection(PostmanCollection loaded) { var reopen = _collection == loaded ? _node?.PathInCollection : null; - if (_collection == loaded) + + // A request from history stays in the editor, with the reloaded collection's variables. + var fromHistory = _collection == loaded && _node is null; + + // Loaded first: a file that no longer loads throws, and the editor goes on editing its request. + var reloaded = _workspace.ReloadCollection(loaded); + var detached = _collection == loaded && !fromHistory; + if (detached) { - // Detach the editor first so nothing is written into the copy being replaced. + // Detach the editor so nothing is written into the copy that was replaced. _node = null; _collection = null; _editor.MarkClean(); } - var reloaded = _workspace.ReloadCollection(loaded); + string? originGone = null; + if (fromHistory) + { + _collection = reloaded; + if (_historyEntry is { } entry && OriginalRequest(entry, reloaded) is { } original) + { + _historyOrigin = original; + } + else + { + originGone = ForgetHistoryOrigin(); + } + + _editor.RefreshContext(); // the reloaded folders' auth and scripts + } + _tree.Reload(_workspace); if (reopen is not null && reloaded.FindRequest(reopen) is { } node) { @@ -1177,20 +1481,23 @@ private void ReloadCollection(PostmanCollection loaded) else { _tree.Select(reloaded); - if (_collection is null) + + // Only the editor this reload detached: a request typed into the one a delete emptied has nothing to do with it. + if (detached) { + DetachSending(); _editor.Load(new HttpRequestSpec()); ClearResponse(); } } UpdateTitles(); - Notify($"Reloaded '{reloaded.Name}' from disk."); + Notify($"Reloaded '{reloaded.Name}' from disk.{(originGone is null ? "" : " " + originGone)}"); } private void ImportEnvironment() { - if (Ui.PickFile(App!, "Import Postman environment", null, false, ("Postman environment", [".json"])) is not { } path) + if (Ui.PickFile(App!, "Import Postman environment", null, false, ("Postman environment", [".json", ".yaml", ".yml"])) is not { } path) { return; } @@ -1198,7 +1505,11 @@ private void ImportEnvironment() try { var environment = _workspace.ImportEnvironment(path); - Notify($"Imported environment '{environment.Name}'"); + + // The active environment's label can change: one of the same name adds its file name, its own file a new name. + _environmentShortcut.Title = EnvironmentLabel(); + _editor.RefreshCertificateInfo(); + Notify(environment.IsGlobals ? $"Imported the workspace's globals: '{environment.Name}'" : $"Imported environment '{_workspace.DisplayName(environment)}'"); } catch (Exception ex) { @@ -1208,16 +1519,32 @@ private void ImportEnvironment() private void CopyAsCurl() { - if (_collection is null && _scratch is null) + // As Send: a request typed into the editor a delete emptied is a scratch request. + var prepared = _runner.Prepare(_collection ?? (_scratch ??= PostmanCollection.Create("Scratch")), SendContext, _editor.Spec); + if (prepared.Errors.Count > 0) + { + // Not a request TermRest would send (an invalid URL, a missing file, a line break in a header): no command for it, + // as on the command line (a command for it would send something else, such as an empty body). + Ui.Error(App!, "Copy as cURL", string.Join("\n", prepared.Errors)); + return; + } + + string curl; + try + { + curl = CurlExporter.Export(prepared); + } + catch (NotSupportedException ex) { + Ui.Error(App!, "Copy as cURL", ex.Message); return; } - var prepared = _runner.Prepare(_collection ?? _scratch!, _node, _editor.Spec); - var curl = CurlExporter.Export(prepared); + var masked = HasMaskedCredentials ? " It has *** for the credentials the history masked." : ""; + var warnings = prepared.Warnings.Count == 0 ? "" : " ⚠ " + string.Join(" ", prepared.Warnings); if (Ui.CopyToClipboard(App, curl)) { - Notify("cURL command copied to the clipboard."); + Notify("cURL command copied to the clipboard." + masked + warnings); } else { @@ -1264,20 +1591,48 @@ private void LoadHistory() Notify($"History could not be read: {ex.Message}"); } + _history.Limit = _runner.History?.MaxEntries ?? int.MaxValue; _history.SetEntries(entries, _runner.History is null ? "History is off (Tools > Settings)." : "No requests yet: send one with F5."); } - /// Shows a sent request and its recorded response; it can be edited and re-sent, or saved with Ctrl+N. - internal void OpenHistoryEntry(HistoryEntry entry) + /// + /// Shows a sent request and its recorded response; it can be edited and re-sent, or saved with Ctrl+N. False when the + /// user keeps the request open now (see ). + /// + internal bool OpenHistoryEntry(HistoryEntry entry) { + // Open already, unchanged: it may be on its way (Send again), and its response is to be shown here. + if (entry == _historyEntry && !_editor.IsModified) + { + return true; + } + + if (!ConfirmDiscardRequest()) + { + return false; + } + CommitEditor(); + DetachSending(); _node = null; - // Variables keep resolving against the request's collection while it is still in the workspace. - _collection = _workspace.Collections.FirstOrDefault(c => c.Name == entry.Collection) ?? (_scratch ??= PostmanCollection.Create("Scratch")); + // 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. + var collection = CollectionOf(entry, out var namesakes); + _collection = collection ?? (_scratch ??= PostmanCollection.Create("Scratch")); _historyEntry = entry; _detachedName = entry.RequestPath is null ? null : entry.Name; - _editor.Load(entry.ReadSpec()); + var spec = entry.ReadSpec(); + + // Sent again, it runs as its request in the collection does (with the scripts of its folders), while that is still + // there. Auth it inherited is taken from its folders again: the history has a masked copy of it. + _historyOrigin = OriginalRequest(entry, collection); + if (entry.AuthInherited && _historyOrigin is not null) + { + spec.Auth = null; + } + + _editor.Load(spec); byte[]? body = null; try { @@ -1288,9 +1643,21 @@ internal void OpenHistoryEntry(HistoryEntry entry) // The entry is still useful without its body. } - _response.ShowExchange(entry.ToExchange(body)); + _response.ShowExchange(entry.ToExchange(body), fromHistory: true); SetResponseTitle(null); UpdateTitles(); + var masked = HasMaskedCredentials ? "Credentials are *** in the history: type them again before sending." : null; + if (namesakes > 1) + { + var unknown = $"{namesakes} collections are named '{entry.Collection}' and which one this request was sent from is not known: it is sent on its own"; + Notify(masked is null ? $"⚠ {unknown}, without their variables and scripts." : $"⚠ {unknown}. {masked}"); + } + else if (masked is not null) + { + Notify("⚠ " + masked); + } + + return true; } private void ShowHistoryContextMenu(System.Drawing.Point? position) @@ -1305,18 +1672,24 @@ private void ShowHistoryContextMenu(System.Drawing.Point? position) new MenuItem("_Open", "", () => OpenHistoryEntry(entry)), new MenuItem("_Send again", "", () => { - OpenHistoryEntry(entry); - Send(); + if (UseHistoryEntry(entry)) + { + Send(); + } }), new MenuItem("Save to _collection…", "", () => { - OpenHistoryEntry(entry); - NewRequest(); + if (UseHistoryEntry(entry)) + { + NewRequest(); + } }), new MenuItem("Copy as c_URL", "", () => { - OpenHistoryEntry(entry); - CopyAsCurl(); + if (UseHistoryEntry(entry)) + { + CopyAsCurl(); + } }), }; if (OriginalRequest(entry) is { } original) @@ -1334,8 +1707,96 @@ private void ShowHistoryContextMenu(System.Drawing.Point? position) ShowPopover(items, position); } - private RequestNode? OriginalRequest(HistoryEntry entry) => - entry.RequestPath is { } path ? _workspace.Collections.FirstOrDefault(c => c.Name == entry.Collection)?.FindRequest(path) : null; + /// + /// The request in its collection a history entry was sent from, while it is there: the one at its exact path. Unlike + /// , never one found by its name alone, which may be another request, in + /// a folder with other auth and scripts. + /// + private RequestNode? OriginalRequest(HistoryEntry entry) => OriginalRequest(entry, CollectionOf(entry, out _)); + + /// The entry's collection, if it is loaded (see ). + private static RequestNode? OriginalRequest(HistoryEntry entry, PostmanCollection? collection) + { + if (entry.RequestPath is not { } path || collection is null) + { + return null; + } + + // Names may hold slashes, so requests in different folders can share a path: then which one it was is not known. + RequestNode? found = null; + foreach (var request in collection.AllRequests()) + { + if (request.PathInCollection == path) + { + if (found is not null && found.Parent != request.Parent) + { + return null; + } + + found ??= request; + } + } + + return found; + } + + /// + /// The collection a history entry was sent from, while it is loaded: the one in its file; else (an entry of an earlier + /// version, a file renamed since) the one with its name, while no other has that name. Null when several do (then + /// says how many): which one it was is not known. + /// + private PostmanCollection? CollectionOf(HistoryEntry entry, out int namesakes) + { + namesakes = 0; + if (entry.CollectionFile is { } file + && _workspace.Collections.FirstOrDefault(c => string.Equals(_workspace.FileOf(c), file, StringComparison.OrdinalIgnoreCase)) is { } collection) + { + return collection; + } + + var named = _workspace.Collections.Where(c => c.Name == entry.Collection).ToList(); + namesakes = named.Count; + return namesakes == 1 ? named[0] : null; + } + + /// Opens a history entry for an action on it, unless it is open already: then the action takes the changes made to it. + private bool UseHistoryEntry(HistoryEntry entry) => entry == _historyEntry || OpenHistoryEntry(entry); + + /// Whether the request shown still has *** for credentials the history masked (see ). + private bool HasMaskedCredentials => _historyEntry is { CredentialsMasked: true } && HistoryEntry.HasMaskedCredentials(_editor.Spec); + + /// The request whose collection context (folder scripts, inherited auth) the request shown is sent in. + private RequestNode? SendContext => _node ?? _historyOrigin; + + /// + /// The request the history entry shown was sent from is gone (deleted, or not found when its collection was reloaded): + /// the entry is sent on its own from now on. When it inherited its auth there and still inherits it, the auth it was + /// sent with is put back: inheriting now would take the collection's auth, which may be meant for another host. Other + /// changes made to the request are kept. Returns what to tell the user, or null when its auth stays as it is. + /// + private string? ForgetHistoryOrigin() + { + _historyOrigin = null; + if (_node is not null || _historyEntry is not { AuthInherited: true } entry || _editor.Spec.Auth is not null + || entry.ReadSpec().Auth is not { } auth) + { + return null; + } + + var spec = _editor.Spec; + spec.Auth = auth; + if (_editor.IsModified) + { + _editor.Replace(spec); + } + else + { + _editor.Load(spec); + } + + var gone = $"'{entry.RequestPath}' is no longer in its collection: this request now has the auth it was sent with"; + return HasMaskedCredentials ? $"⚠ {gone}. Credentials are *** in the history: type them again before sending." : $"{gone} (Auth tab)."; + } private void DeleteHistoryEntry(HistoryEntry entry) { @@ -1360,9 +1821,13 @@ private void ClearHistory() try { - store.Clear(); + var bodiesLeft = store.Clear(); _history.SetEntries([], "History cleared."); UpdateSidebarTitle(); + if (bodiesLeft is not null) + { + Ui.Error(App!, "History", $"History cleared, but some response bodies could not be deleted: {bodiesLeft.Message}"); + } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { @@ -1405,16 +1870,48 @@ private void ApplyImportedCurl(CurlImportResult imported, bool intoCurrent) var spec = imported.Spec; if (intoCurrent) { - spec.Description = _editor.Spec.Description; - spec.Scripts = _editor.Spec.Scripts; - spec.ScriptSettings = _editor.Spec.ScriptSettings; + // Pasted into a request from history, a command is a request of its own, as one imported from the menu: not the + // request the entry was sent from, whose auth and scripts (its own and its folders') are not meant for the host it + // names. + var detach = _node is null && _historyEntry is not null; + var sending = _sending is not null; + if (detach) + { + DetachSending(); // the entry's request, still on its way, goes on as it would for a menu import + _historyEntry = null; + _historyOrigin = null; + _collection = _scratch ??= PostmanCollection.Create("Scratch"); + _detachedName = imported.SuggestedName; + } + else + { + spec.Description = _editor.Spec.Description; + spec.Scripts = _editor.Spec.Scripts; + spec.ScriptSettings = _editor.Spec.ScriptSettings; + } + _editor.Replace(spec); + if (detach) + { + _editor.RefreshContext(); + if (sending) + { + ClearResponse(); // not "Sending…" for the entry's request, which now arrives on its own + } + } } else { + if (!ConfirmDiscardRequest()) + { + return; + } + CommitEditor(); + DetachSending(); _node = null; _historyEntry = null; + _historyOrigin = null; _collection = _scratch ??= PostmanCollection.Create("Scratch"); _detachedName = imported.SuggestedName; _editor.Replace(spec); @@ -1450,6 +1947,7 @@ private static readonly (string Keys, string Action)[] Shortcuts = ("Ctrl+N", "New request"), ("F2", "Rename tree item"), ("Del", "Delete item, row or entry"), + ("Insert", "Add a table row"), ("F7", "Switch environment"), ("F8", "Client certificates"), ("F9", "Collections ⇄ History"), @@ -1510,6 +2008,7 @@ private void ShowWorkspaceInfo() $"Color theme: {ThemeCatalog.Current.Name} ({(ThemeCatalog.Current.FilePath ?? "built in")}){(_workspace.Settings.Theme is null ? "" : ", chosen for this workspace")}\n" + $"Certificates: {_workspace.Certificates.Entries.Count} ({Path.GetRelativePath(_workspace.RootPath, _workspace.CertificatesPath)})\n" + $"SSL verification: {(_workspace.Settings.StrictSsl ? "on" : "off")} · CA bundle: {_workspace.Settings.CaBundle ?? "none"}\n" + + $"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) @@ -1520,6 +2019,20 @@ private void ShowWorkspaceInfo() Ui.ShowText(App!, "Workspace", info); } + /// The proxy requests go through (its password masked), and a proxy of the workspace's settings that is not allowed. + private string DescribeProxy() + { + const string system = "system (OS / HTTPS_PROXY settings)"; + var proxy = _workspace.Settings.Proxy?.Trim(); + if (!WorkspaceSettings.IsProxyUrl(proxy)) + { + return string.Equals(proxy, "none", StringComparison.OrdinalIgnoreCase) ? "none" : system; + } + + var url = PostmanUrl.MaskCredentials(proxy); + return _runner.BlockedProxy is null ? url : $"{system}, not the workspace's {url} until you allow it: Tools > Settings > Save"; + } + /// When wrapping follows the files: the YAML collections whose files are wrapped. private string DescribeDetectedWrapping() { @@ -1561,7 +2074,7 @@ private void UpdateTitles() { var dirty = _editor.IsModified || _collection?.IsDirty == true ? " ●" : ""; var title = _node is not null - ? $"Request — {_node.Collection.Name} / {_node.PathInCollection}{dirty}" + ? $"Request — {_workspace.DisplayName(_node.Collection)} / {_node.PathInCollection}{dirty}" : _historyEntry is { } entry ? $"Request (from history · {entry.Time.ToLocalTime():yyyy-MM-dd HH:mm:ss}){dirty}" : $"Request ({(_detachedName is null ? "scratch" : "imported")}){dirty}"; @@ -1601,7 +2114,7 @@ private void Quit() if (ConfirmUnsaved()) { _quitConfirmed = true; - App?.RequestStop(); + RequestStop(); } } @@ -1609,6 +2122,11 @@ private void Quit() private bool ConfirmUnsaved() { CommitEditor(); + if (!ConfirmDiscardRequest()) + { + return false; + } + if (_runner.Recorder is { } recorder && !StopRecording(recorder, RecordingDialogPurpose.Close)) { return false; @@ -1647,6 +2165,13 @@ protected override bool OnKeyDown(Key key) return true; } + // Also a menu item's key, but Terminal.Gui delivers those only to an open menu. + if (key == Key.L.WithCtrl) + { + _editor.FocusUrl(); + return true; + } + if (key == Key.F12) { ToggleRecording(); @@ -1668,10 +2193,11 @@ protected override bool OnIsRunningChanging(bool oldIsRunning, bool newIsRunning protected override void Dispose(bool disposing) { - if (disposing) + if (disposing && !_closed) { _closed = true; - _sending?.Cancel(); + _closing.Cancel(); + _closing.Dispose(); ThemeCatalog.Changed -= OnThemeChanged; // Closed without saving (normally the user is asked first): the files stay for Tools > Recover. diff --git a/src/TermRest.Tui/Syntax/CSharpLexer.cs b/src/TermRest.Tui/Syntax/CSharpLexer.cs index de61d9e..3bf61b0 100644 --- a/src/TermRest.Tui/Syntax/CSharpLexer.cs +++ b/src/TermRest.Tui/Syntax/CSharpLexer.cs @@ -34,6 +34,8 @@ public override LexState Lex(ReadOnlySpan line, Span kinds, Le _ => 0, }; var name = SyntaxKind.Plain; // the next name: a type after class, new, record … + var noQuoteBefore = 0; // the $ and @ before this index lead to no string: their run was looked at already + var charBudget = (4 * line.Length) + 256; // characters 'c' literals may scan: unclosed ones scan to the line end while (i < line.Length) { var c = line[i]; @@ -51,7 +53,7 @@ public override LexState Lex(ReadOnlySpan line, Span kinds, Le continue; } - if (QuoteOfString(line, i) is var quote and >= 0) + if (i >= noQuoteBefore && QuoteOfString(line, i, out noQuoteBefore) is var quote and >= 0) { i = OpenString(line, kinds, i, quote, ref state); name = SyntaxKind.Plain; @@ -60,7 +62,7 @@ public override LexState Lex(ReadOnlySpan line, Span kinds, Le if (c == '\'') { - var end = CharEnd(line, i); + var end = CharEnd(line, i, ref charBudget); kinds[i..end].Fill(SyntaxKind.String); i = end; continue; @@ -103,8 +105,11 @@ public override LexState Lex(ReadOnlySpan line, Span kinds, Le return state; } - /// Where the quotes are if a string starts at ("…", @"…", $"…", $@"…", """…""", $$"""…"""), else -1. - private static int QuoteOfString(ReadOnlySpan line, int i) + /// + /// Where the quotes are if a string starts at ("…", @"…", $"…", $@"…", """…""", $$"""…"""), else + /// -1; is where its $ and @ end. + /// + private static int QuoteOfString(ReadOnlySpan line, int i, out int runEnd) { var j = i; while (j < line.Length && line[j] is '$' or '@') @@ -112,6 +117,7 @@ private static int QuoteOfString(ReadOnlySpan line, int i) j++; } + runEnd = j; return At(line, j) == '"' ? j : -1; } @@ -212,10 +218,13 @@ private int StringText(ReadOnlySpan line, Span kinds, int i, r return i; } - /// The end of the character at ('a', '\n', '\''); just its quote if it does not close. - private static int CharEnd(ReadOnlySpan line, int i) + /// + /// The end of the character at ('a', '\n', '\''); just its quote if it does not close, or if + /// (characters left to scan on this line) runs out. + /// + private static int CharEnd(ReadOnlySpan line, int i, ref int budget) { - for (var j = i + 1; j < line.Length; j++) + for (var j = i + 1; j < line.Length && budget-- > 0; j++) { if (line[j] == '\\') { diff --git a/src/TermRest.Tui/Syntax/JavaScriptLexer.cs b/src/TermRest.Tui/Syntax/JavaScriptLexer.cs index e6f5ca9..18c9af2 100644 --- a/src/TermRest.Tui/Syntax/JavaScriptLexer.cs +++ b/src/TermRest.Tui/Syntax/JavaScriptLexer.cs @@ -25,6 +25,7 @@ public override LexState Lex(ReadOnlySpan line, Span kinds, Le _ => 0, }; var regex = true; // whether a slash here starts a regular expression + var regexBudget = (4 * line.Length) + 256; // characters regular expressions may scan: failing ones scan to the line end var name = SyntaxKind.Plain; // the next name: a function after function, a type after class or new while (i < line.Length) { @@ -53,7 +54,7 @@ public override LexState Lex(ReadOnlySpan line, Span kinds, Le continue; } - if (c == '/' && regex && RegexEnd(line, i) is var regexEnd and > 0) + if (c == '/' && regex && RegexEnd(line, i, ref regexBudget) is var regexEnd and > 0) { kinds[i..regexEnd].Fill(SyntaxKind.String); i = regexEnd; @@ -159,11 +160,14 @@ private int StringText(ReadOnlySpan line, Span kinds, int i, r return i; } - /// The end of the regular expression at (with its flags), or -1 if it does not close on the line. - private static int RegexEnd(ReadOnlySpan line, int i) + /// + /// The end of the regular expression at (with its flags), or -1 if it does not close on the line + /// or (characters left to scan on this line) runs out. + /// + private static int RegexEnd(ReadOnlySpan line, int i, ref int budget) { var inClass = false; - for (var j = i + 1; j < line.Length; j++) + for (var j = i + 1; j < line.Length && budget-- > 0; j++) { switch (line[j]) { diff --git a/src/TermRest.Tui/Syntax/PowerShellLexer.cs b/src/TermRest.Tui/Syntax/PowerShellLexer.cs index 3ac6711..0ec1056 100644 --- a/src/TermRest.Tui/Syntax/PowerShellLexer.cs +++ b/src/TermRest.Tui/Syntax/PowerShellLexer.cs @@ -10,6 +10,9 @@ internal sealed class PowerShellLexer : SyntaxLexer { public static readonly PowerShellLexer Instance = new(); + /// The longest ${name} colored as a variable. + private const int MaxBracedName = 1024; + private static readonly FrozenSet.AlternateLookup> Keywords = Words( "begin break catch class continue data default do dynamicparam else elseif end enum exit filter finally for foreach function hidden if in param process return static switch throw trap try until using while", ignoreCase: true); @@ -32,6 +35,7 @@ public override LexState Lex(ReadOnlySpan line, Span kinds, Le _ => 0, }; var name = SyntaxKind.Plain; // the next name: a function after function, a type after class + var typeBudget = (4 * line.Length) + 256; // characters [types] may scan: failing ones scan to the line end while (i < line.Length) { var c = line[i]; @@ -88,7 +92,7 @@ public override LexState Lex(ReadOnlySpan line, Span kinds, Le continue; } - if (c == '[' && !(i > 0 && (IsWordPart(line[i - 1]) || line[i - 1] is ']' or ')')) && TypeEnd(line, i) is var typeEnd and > 0) + if (c == '[' && !(i > 0 && (IsWordPart(line[i - 1]) || line[i - 1] is ']' or ')')) && TypeEnd(line, i, ref typeBudget) is var typeEnd and > 0) { kinds[i..typeEnd].Fill(SyntaxKind.Type); i = typeEnd; @@ -222,7 +226,8 @@ private static int VariableEnd(ReadOnlySpan line, int i) var c = At(line, i + 1); if (c == '{') { - var close = line[(i + 2)..].IndexOf('}'); + // Its closing brace is looked for this far only: on a long line of unclosed ${, each would search to its end. + var close = line[(i + 2)..][..Math.Min(MaxBracedName, line.Length - i - 2)].IndexOf('}'); return close < 0 ? -1 : i + 3 + close; } @@ -240,8 +245,11 @@ private static int VariableEnd(ReadOnlySpan line, int i) return At(line, end) == ':' && IsWordStart(At(line, end + 1)) ? WordEnd(line, end + 1) : end; // $env:Path, $script:count } - /// The end of the type at ([int], [System.IO.File], [string[]]), or -1 if it is not one. - private static int TypeEnd(ReadOnlySpan line, int i) + /// + /// The end of the type at ([int], [System.IO.File], [string[]]), or -1 if it is not one or + /// (characters left to scan on this line) runs out. + /// + private static int TypeEnd(ReadOnlySpan line, int i, ref int budget) { if (!IsWordStart(At(line, i + 1))) { @@ -249,7 +257,7 @@ private static int TypeEnd(ReadOnlySpan line, int i) } var depth = 0; - for (var j = i; j < line.Length; j++) + for (var j = i; j < line.Length && budget-- > 0; j++) { var c = line[j]; if (c == '[') diff --git a/src/TermRest.Tui/Syntax/PythonLexer.cs b/src/TermRest.Tui/Syntax/PythonLexer.cs index 4f12af2..746b138 100644 --- a/src/TermRest.Tui/Syntax/PythonLexer.cs +++ b/src/TermRest.Tui/Syntax/PythonLexer.cs @@ -92,7 +92,7 @@ public override LexState Lex(ReadOnlySpan line, Span kinds, Le /// A string that starts at (its prefix) with its quotes at . private int OpenString(ReadOnlySpan line, Span kinds, int start, int quote, StringStyle style, ref LexState state) { - var quotes = Run(line, quote, line[quote]) >= 3 ? 3 : 1; + var quotes = Repeats(line, quote, line[quote], 3) ? 3 : 1; kinds[start..(quote + quotes)].Fill(SyntaxKind.String); state = new LexState(LexMode.String, line[quote], (byte)quotes, quotes == 3 ? style | StringStyle.MultiLine : style); return StringText(line, kinds, quote + quotes, ref state); @@ -122,7 +122,7 @@ private int StringText(ReadOnlySpan line, Span kinds, int i, r continue; } - if (c == state.Quote && Run(line, i, c) >= state.Quotes) + if (c == state.Quote && Repeats(line, i, c, state.Quotes)) { kinds[i..(i + state.Quotes)].Fill(SyntaxKind.String); i += state.Quotes; diff --git a/src/TermRest.Tui/Syntax/SyntaxLexer.cs b/src/TermRest.Tui/Syntax/SyntaxLexer.cs index 672ac5c..478114a 100644 --- a/src/TermRest.Tui/Syntax/SyntaxLexer.cs +++ b/src/TermRest.Tui/Syntax/SyntaxLexer.cs @@ -66,6 +66,16 @@ internal readonly record struct LexState(LexMode Mode, char Quote = '\0', byte Q /// internal abstract class SyntaxLexer { + /// + /// Interpolations nested deeper than this have their code left plain: each level is colored by a nested call, and a + /// line could nest thousands of them. + /// + private const int MaxNesting = 8; + + /// How many interpolations deep the line being colored on this thread is. + [ThreadStatic] + private static int _nesting; + /// The lexer of a script language (), or null for plain text. public static SyntaxLexer? For(string? language) => language switch { @@ -118,6 +128,10 @@ protected static int Run(ReadOnlySpan line, int i, char c) return end - i; } + /// Whether follow each other from (looking no further). + protected static bool Repeats(ReadOnlySpan line, int i, char c, int count) => + line.Length - i >= count && !line.Slice(i, count).ContainsAnyExcept(c); + /// Whether the word at follows a dot: a member (pm.test, x.default), never a keyword. protected static bool IsMember(ReadOnlySpan line, int i) => i > 0 && line[i - 1] == '.'; @@ -173,7 +187,19 @@ protected int Interpolation(ReadOnlySpan line, Span kinds, int var end = ClosingBracket(line, i, open, close, escape, ref depth); var codeEnd = end < 0 ? line.Length : end; kinds[i..codeEnd].Clear(); - Lex(line[i..codeEnd], kinds[i..codeEnd], LexState.Code); + if (_nesting < MaxNesting) + { + _nesting++; + try + { + Lex(line[i..codeEnd], kinds[i..codeEnd], LexState.Code); + } + finally + { + _nesting--; + } + } + if (end < 0) { state = state with { Depth = (byte)Math.Min(depth, byte.MaxValue) }; diff --git a/src/TermRest.Tui/Theming/ThemeCatalog.cs b/src/TermRest.Tui/Theming/ThemeCatalog.cs index 0e75773..048261c 100644 --- a/src/TermRest.Tui/Theming/ThemeCatalog.cs +++ b/src/TermRest.Tui/Theming/ThemeCatalog.cs @@ -66,11 +66,19 @@ public static IReadOnlyList Load(string? workspaceRoot, ICollection< || (Find(themes, baseName) is not null && !pending.Any(other => other != p && Same(other.Name, baseName)))); if (ready < 0) { - // Missing or circular bases: start those from Default. - var (file, path, _) = pending[0]; - errors.Add($"{Path.GetFileName(path)}: base theme '{file.Base}' was not found; using {DefaultName}"); - file.Base = DefaultName; - continue; + var missing = pending.FindIndex(p => Find(themes, p.File.Base) is null); + if (missing >= 0) + { + // Missing or circular bases: start those from Default. + var (file, path, _) = pending[missing]; + errors.Add($"{Path.GetFileName(path)}: base theme '{file.Base}' was not found; using {DefaultName}"); + file.Base = DefaultName; + continue; + } + + // Every base exists, but each waits for another file that replaces it (as after copying Default as + // "Default" twice): build them in file order, each on the theme as it is so far. + ready = 0; } var (readyFile, readyPath, _) = pending[ready]; @@ -94,6 +102,25 @@ public static IReadOnlyList Load(string? workspaceRoot, ICollection< public static ColorTheme? Find(IEnumerable themes, string? name) => name is null ? null : themes.LastOrDefault(t => Same(t.Name, name)); + /// + /// The custom theme called , if there is one. A copy must not take its name: only one theme of a + /// name is loaded, the one read last, so the other would never show. + /// + public static ColorTheme? FindCustom(IEnumerable themes, string name) => + themes.LastOrDefault(t => !t.IsBuiltIn && Same(t.Name, name.Trim())); + + /// , or the first of "name 2", "name 3" … that no custom theme has. + public static string FreeName(IReadOnlyList themes, string name) + { + var candidate = name; + for (var i = 2; FindCustom(themes, candidate) is not null; i++) + { + candidate = $"{name} {i}"; + } + + return candidate; + } + /// /// The theme to use: (the --theme option), else $TERMREST_THEME, else the /// workspace's theme, else the user's; null for . @@ -147,22 +174,22 @@ public static void EnsureApplied() } } - /// Writes a copy of named to ; returns the file. + /// + /// Writes a copy of named to ; returns the + /// file. Its name is valid on every OS and unique ignoring case, as a workspace's themes are shared through Git. + /// public static string WriteCopy(ColorTheme theme, string name, string directory) { Directory.CreateDirectory(directory); - var safe = string.Concat(name.Trim().Select(c => Path.GetInvalidFileNameChars().Contains(c) || c is '/' or '\\' or ':' ? '-' : c)); - if (safe.Length == 0) - { - safe = "theme"; - } - - var path = Path.Combine(directory, safe + ".json"); - for (var i = 2; File.Exists(path); i++) + var safe = name.Trim().Length == 0 ? "theme" : ApiWorkspace.SafeFileName(name); + var taken = new HashSet(Directory.EnumerateFileSystemEntries(directory).Select(Path.GetFileName).OfType(), StringComparer.OrdinalIgnoreCase); + var file = safe + ".json"; + for (var i = 2; taken.Contains(file); i++) { - path = Path.Combine(directory, $"{safe}-{i}.json"); + file = $"{safe}-{i}.json"; } + var path = Path.Combine(directory, file); File.WriteAllText(path, ThemeFile.CopyOf(theme, name.Trim()).ToJson()); return path; } diff --git a/src/TermRest.Tui/Theming/ThemeFile.cs b/src/TermRest.Tui/Theming/ThemeFile.cs index b1ea573..457f56c 100644 --- a/src/TermRest.Tui/Theming/ThemeFile.cs +++ b/src/TermRest.Tui/Theming/ThemeFile.cs @@ -95,8 +95,17 @@ public ColorTheme ToTheme(string path, ColorTheme baseTheme, ICollection var schemes = surfaceChanged ? palette.ToSchemes() : baseTheme.Schemes.ToDictionary(p => p.Key, p => new Scheme(p.Value), StringComparer.Ordinal); - schemes[ThemeCatalog.SuccessScheme] = palette.StatusScheme(palette.Success); - schemes[ThemeCatalog.WarningScheme] = palette.StatusScheme(palette.Warning); + + // A status scheme follows its color: until that changes, the base's stays as it is, with the roles a custom base sets. + if (!palette.Success.Equals(baseTheme.Palette.Success)) + { + schemes[ThemeCatalog.SuccessScheme] = palette.StatusScheme(palette.Success); + } + + if (!palette.Warning.Equals(baseTheme.Palette.Warning)) + { + schemes[ThemeCatalog.WarningScheme] = palette.StatusScheme(palette.Warning); + } foreach (var (schemeKey, roles) in Schemes ?? []) { @@ -107,23 +116,44 @@ public ColorTheme ToTheme(string path, ColorTheme baseTheme, ICollection continue; } - foreach (var (roleKey, value) in roles) + if (roles is null) + { + errors.Add($"{fileName}: {schemeKey}: no roles given (known: {string.Join(", ", ThemeableRoles)})"); + continue; + } + + // Roles are set in the order Terminal.Gui derives them from each other (Focus from Normal, Highlight and ReadOnly + // from Editable …), whatever their order in the file, so that setting one never changes another the file sets. + // Mistakes are listed in the file's order. + var problems = new List<(int Index, string Text)>(); + var known = new List<(int Index, VisualRole Role, string Key, string Value)>(); + foreach (var (index, (roleKey, value)) in roles.Index()) { if (!Enum.TryParse(roleKey, ignoreCase: true, out var role) || !IsThemeableRole(role)) { - errors.Add($"{fileName}: {schemeKey}: unknown role '{roleKey}' (known: {string.Join(", ", ThemeableRoles)})"); + problems.Add((index, $"{fileName}: {schemeKey}: unknown role '{roleKey}' (known: {string.Join(", ", ThemeableRoles)})")); continue; } + known.Add((index, role, roleKey, value)); + } + + foreach (var (index, role, roleKey, value) in known.OrderBy(k => Array.IndexOf(ThemeableRoles, k.Role))) + { if (!TryParseAttribute(value, scheme.GetAttributeForRole(role), out var attribute, out var problem)) { - errors.Add($"{fileName}: {schemeKey}.{roleKey}: {problem}"); + problems.Add((index, $"{fileName}: {schemeKey}.{roleKey}: {problem}")); continue; } scheme = WithRole(scheme, role, attribute); } + foreach (var (_, text) in problems.OrderBy(p => p.Index)) + { + errors.Add(text); + } + schemes[schemeName] = scheme; } @@ -138,38 +168,89 @@ public ColorTheme ToTheme(string path, ColorTheme baseTheme, ICollection }; } - /// A theme file that reproduces : based on it, with all its palette colors to edit. - public static ThemeFile CopyOf(ColorTheme theme, string name) => new() + /// + /// A theme file that reproduces , with all its palette colors to edit. A built-in theme's copy is + /// based on it. A custom theme's copy needs no other theme file (its base may be in a workspace that other workspaces + /// don't have): it is based on the built-in theme of the same Terminal.Gui theme and sets the scheme roles in which the + /// custom theme differs from what its palette gives there. + /// + public static ThemeFile CopyOf(ColorTheme theme, string name) { - Name = name, - Description = $"Based on {theme.Name}", - Base = theme.Name, - Palette = ThemePalette.Keys.ToDictionary(k => k.Key, k => k.Get(theme.Palette).ToString()), - }; + var copy = new ThemeFile + { + Name = name, + Description = $"Based on {theme.Name}", + Base = theme.Name, + Palette = ThemePalette.Keys.ToDictionary(k => k.Key, k => FormatColor(k.Get(theme.Palette))), + }; + if (theme.IsBuiltIn) + { + return copy; + } + + var builtIn = ThemeCatalog.Find(ThemeCatalog.BuiltIn, theme.TerminalGuiTheme) ?? ThemeCatalog.BuiltIn[0]; + copy.Base = builtIn.Name; + var computed = copy.ToTheme(name, builtIn, []).Schemes; + var schemes = new Dictionary>(StringComparer.Ordinal); + foreach (var (schemeName, source) in theme.Schemes) + { + if (!computed.TryGetValue(schemeName, out var scheme)) + { + continue; + } + + // Loading sets the roles in the order written, each on the scheme the ones before it left: compare with that. + var roles = new Dictionary(StringComparer.Ordinal); + foreach (var role in ThemeableRoles) + { + var attribute = source.GetAttributeForRole(role); + if (scheme.GetAttributeForRole(role) != attribute) + { + roles[role.ToString()] = FormatAttribute(attribute); + scheme = WithRole(scheme, role, attribute); + } + } + + if (roles.Count > 0) + { + schemes[FileSchemeName(schemeName)] = roles; + } + } + + copy.Schemes = schemes.Count > 0 ? schemes : null; + return copy; + } public string ToJson() => JsonSerializer.Serialize(this, ThemeJsonContext.Default.ThemeFile).Replace("\r\n", "\n", StringComparison.Ordinal) + "\n"; public static bool TryParseColor(string? text, out Color color) { color = Color.None; - if (string.IsNullOrWhiteSpace(text) || !Color.TryParse(text.Trim(), out Color? parsed) || parsed is not { } value) + try { - return false; - } + if (string.IsNullOrWhiteSpace(text) || !Color.TryParse(text.Trim(), out Color? parsed) || parsed is not { } value) + { + return false; + } - color = value; - return true; + color = value; + return true; + } + catch (Exception ex) when (ex is OverflowException or FormatException or ArgumentException) + { + return false; // Terminal.Gui's TryParse throws for some colors, such as rgb(256,0,0) + } } /// /// Parses "<foreground> [on <background>] [style …]", e.g. "white on #1e1e2e bold underline" or /// "on DarkRed". Parts left out keep 's colors and style; none as a style clears it. /// - public static bool TryParseAttribute(string text, Attribute fallback, out Attribute attribute, out string? problem) + public static bool TryParseAttribute(string? text, Attribute fallback, out Attribute attribute, out string? problem) { attribute = fallback; problem = null; - var tokens = text.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var tokens = text?.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? []; if (tokens.Length == 0) { problem = "empty; use \" on [bold|italic|underline|faint|reverse|strikethrough|blink]\""; @@ -225,10 +306,30 @@ public static bool TryParseAttribute(string text, Attribute fallback, out Attrib private static bool TryParseStyle(string text, out TextStyle style) => Enum.TryParse(text, ignoreCase: true, out style) && !int.TryParse(text, out _); + /// A color as reads it back exactly: a name, #RRGGBB or None (#AARRGGBB if partly transparent). + public static string FormatColor(Color color) + { + var text = color.ToString(); + return TryParseColor(text, out var parsed) && parsed.Equals(color) ? text : $"#{color.A:X2}{color.R:X2}{color.G:X2}{color.B:X2}"; + } + + /// + /// An attribute as reads it back exactly, whatever the fallback, e.g. + /// "White on DarkRed bold" or "None on None none". + /// + public static string FormatAttribute(Attribute attribute) + { + var styles = Enum.GetValues().Where(s => s != TextStyle.None && attribute.Style.HasFlag(s)).ToList(); + var style = styles.Count == 0 ? "none" : string.Join(' ', styles.Select(s => s.ToString().ToLowerInvariant())); + return $"{FormatColor(attribute.Foreground)} on {FormatColor(attribute.Background)} {style}"; + } + + // In the order Terminal.Gui derives roles from each other (Focus from Normal, Highlight and ReadOnly from Editable …), so + // that a copy, setting roles in this order, never changes a role it set or checked before. private static readonly VisualRole[] ThemeableRoles = [ VisualRole.Normal, VisualRole.HotNormal, VisualRole.Focus, VisualRole.HotFocus, VisualRole.Active, VisualRole.HotActive, - VisualRole.Highlight, VisualRole.Editable, VisualRole.ReadOnly, VisualRole.Disabled, + VisualRole.Editable, VisualRole.Highlight, VisualRole.ReadOnly, VisualRole.Disabled, ]; private static bool IsThemeableRole(VisualRole role) => ThemeableRoles.Contains(role); @@ -245,6 +346,13 @@ private static bool TryParseStyle(string text, out TextStyle style) => _ => null, }; + private static string FileSchemeName(string scheme) => scheme switch + { + ThemeCatalog.SuccessScheme => "Success", + ThemeCatalog.WarningScheme => "Warning", + _ => scheme, + }; + private static Scheme WithRole(Scheme scheme, VisualRole role, Attribute attribute) => role switch { VisualRole.Normal => scheme with { Normal = attribute }, diff --git a/src/TermRest.Tui/TimerResolution.cs b/src/TermRest.Tui/TimerResolution.cs index d279886..b0bf761 100644 --- a/src/TermRest.Tui/TimerResolution.cs +++ b/src/TermRest.Tui/TimerResolution.cs @@ -1,12 +1,14 @@ using System.Runtime.InteropServices; +using Terminal.Gui.App; +using Terminal.Gui.Input; namespace TermRest.Tui; /// -/// Asks Windows for 1 ms timer resolution while the UI runs. Terminal.Gui paces its main loop and its input polling -/// with , and Windows rounds such waits up to its default 15.6 ms timer tick: the 20 ms -/// input poll takes 31 ms and a 16 ms frame 27 ms, which makes the mouse feel sluggish. Since Windows 10 2004 the -/// request affects only this process. Other platforms have fine-grained timers already. +/// Asks Windows for 1 ms timer resolution while the UI is in use (see ). Terminal.Gui paces its main +/// loop and its input polling with , and Windows rounds such waits up to its default 15.6 ms +/// timer tick: the 20 ms input poll takes 31 ms and a 16 ms frame 27 ms, which makes the mouse feel sluggish. Since +/// Windows 10 2004 the request affects only this process. Other platforms have fine-grained timers already. /// internal static partial class TimerResolution { @@ -64,3 +66,84 @@ public void Dispose() [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] private static partial uint TimeEndPeriod(uint period); } + +/// +/// Keeps the UI quick while it is in use and cheap while it is not: Terminal.Gui's main loop runs at +/// , 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. +/// +internal sealed class UiPace : IDisposable +{ + private readonly IApplication _app; + private readonly Func _busy; + private readonly ushort _idleRate = Application.MaximumIterationsPerSecond; + private IDisposable? _timerResolution; + private long _activeUntil; + + /// 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); + app.Keyboard.KeyDown += OnKeyDown; + app.Mouse.MouseEvent += OnMouse; + app.Iteration += OnIteration; + } + + /// How long the UI stays quick after the last input (or the end of a request). + public TimeSpan ActiveFor { get; init; } = TimeSpan.FromSeconds(2); + + /// Whether the UI runs at full pace now. + public bool IsActive => _timerResolution is not null; + + public void Dispose() + { + _app.Keyboard.KeyDown -= OnKeyDown; + _app.Mouse.MouseEvent -= OnMouse; + _app.Iteration -= OnIteration; + Idle(); + } + + private void OnKeyDown(object? sender, Key key) => Wake(); + + private void OnMouse(object? sender, Mouse mouse) => Wake(); + + private void OnIteration(object? sender, EventArgs e) + { + if (_timerResolution is null) + { + return; + } + + if (_busy()) + { + Wake(); + } + else if (Environment.TickCount64 >= _activeUntil) + { + Idle(); + } + } + + private void Wake() + { + _activeUntil = Environment.TickCount64 + (long)ActiveFor.TotalMilliseconds; + if (_timerResolution is null) + { + _timerResolution = TimerResolution.Request(); + Application.MaximumIterationsPerSecond = TuiApp.IterationsPerSecond; + } + } + + private void Idle() + { + if (_timerResolution is not null) + { + Application.MaximumIterationsPerSecond = _idleRate; + _timerResolution.Dispose(); + _timerResolution = null; + } + } +} diff --git a/src/TermRest.Tui/TuiApp.cs b/src/TermRest.Tui/TuiApp.cs index dffd94f..547e6da 100644 --- a/src/TermRest.Tui/TuiApp.cs +++ b/src/TermRest.Tui/TuiApp.cs @@ -1,5 +1,7 @@ +using System.Text; using Terminal.Gui.App; using Terminal.Gui.Input; +using TermRest.Core.History; using TermRest.Core.Workspace; using TermRest.Tui.Theming; @@ -20,8 +22,9 @@ public sealed class TuiOptions public static class TuiApp { /// - /// Main loop passes per second. Terminal.Gui's default of 25 handles input and repaints every 40 ms, which lags - /// behind the mouse; 60 keeps up while an idle pass stays well under a millisecond. + /// Main loop passes per second while the UI is in use (see ). Terminal.Gui's default of 25 handles + /// input and repaints every 40 ms, which lags behind the mouse; 60 keeps up while an idle pass stays well under a + /// millisecond. /// internal const ushort IterationsPerSecond = 60; @@ -30,14 +33,20 @@ public static int Run(string workspacePath, TuiOptions? options = null) { options ??= new TuiOptions(); ConfigureKeyBindings(); - Application.MaximumIterationsPerSecond = IterationsPerSecond; - using var timerResolution = TimerResolution.Request(); + ApiWorkspace workspace; + try + { + workspace = ApiWorkspace.Open(workspacePath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Console.Error.WriteLine(ex.Message); + return 2; + } - var path = workspacePath; var requestedTheme = options.Theme; while (true) { - var workspace = ApiWorkspace.Open(path); var themeErrors = new List(); var theme = ResolveTheme(workspace, requestedTheme, themeErrors, out var found); if (!found && requestedTheme is not null) @@ -49,30 +58,47 @@ public static int Run(string workspacePath, TuiOptions? options = null) using var runner = new RequestRunner(workspace) { StrictSslOverride = options.StrictSslOverride, RequireScriptRuntimes = false }; runner.ConfigureHistory(); runner.ConfigureScripts(); + runner.ConfigureProxy(); + runner.ConfigureFiles(); using var app = Application.Create(); app.Init(options.Driver); ThemeCatalog.Apply(theme); workspace.LoadErrors.AddRange(ThemeProblems(themeErrors)); using var window = new MainWindow(workspace, runner); + using var pace = new UiPace(app, () => window.IsSending); app.Run(window, ex => ReportUnexpectedError(app, ex)); - if (window.NextWorkspacePath is not { } next) + if (window.NextWorkspace is not { } next) { return 0; } - path = next; + workspace = next; requestedTheme = null; // the --theme option applies to the first workspace; later ones use the saved choice } } - /// Keeps the UI alive after an unexpected exception: shows it and logs the details. - private static bool ReportUnexpectedError(IApplication app, Exception exception) + /// + /// Keeps the UI alive after an unexpected exception: logs the details and, given a UI (), shows + /// the error there. + /// + internal static bool ReportUnexpectedError(IApplication? app, Exception exception) { - var log = Path.Combine(Path.GetTempPath(), "termrest-errors.log"); try { - File.AppendAllText(log, $"[{DateTimeOffset.Now:O}] {exception}{Environment.NewLine}{Environment.NewLine}"); - Dialogs.Ui.Error(app, "Unexpected error", $"{exception.Message}\n\nDetails were written to {log}"); + string? log; + try + { + log = LogUnexpectedError(exception); + } + catch (Exception) + { + log = null; // the error is shown all the same + } + + if (app is not null) + { + Dialogs.Ui.Error(app, "Unexpected error", exception.Message + (log is null ? "" : $"\n\nDetails were written to {log}")); + } } catch (Exception) { @@ -82,6 +108,30 @@ private static bool ReportUnexpectedError(IApplication app, Exception exception) return true; } + /// + /// Appends to errors.log in the user's state folder (see + /// ), which only the user can read; returns the log's path. + /// + internal static string LogUnexpectedError(Exception exception, string? stateDirectory = null) + { + var folder = stateDirectory ?? HistoryStore.DefaultStateDirectory(); + var options = new FileStreamOptions { Mode = FileMode.Append, Access = FileAccess.Write, Share = FileShare.Read }; + if (OperatingSystem.IsWindows()) + { + Directory.CreateDirectory(folder); // in the user's profile: private already + } + else + { + Directory.CreateDirectory(folder, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + } + + var log = Path.Combine(folder, "errors.log"); + using var stream = new FileStream(log, options); + stream.Write(Encoding.UTF8.GetBytes($"[{DateTimeOffset.Now:O}] {exception}{Environment.NewLine}{Environment.NewLine}")); + return log; + } + /// /// F5 is Terminal.Gui's "refresh screen" key by default; TermRest uses it to send (like Postman), so free it up. /// @@ -117,7 +167,13 @@ private static IEnumerable ThemeProblems(IEnumerable errors) => internal static ColorTheme ResolveTheme(ApiWorkspace workspace, string? requested, List errors, out bool found, string? userDirectory = null) { var themes = ThemeCatalog.Load(workspace.RootPath, errors, userDirectory); - var name = ThemeCatalog.SelectedName(requested, workspace.Settings, UserSettings.Load(userDirectory)); + var user = UserSettings.Load(userDirectory); + if (user.LoadError is { } problem && !workspace.LoadErrors.Contains(problem)) + { + workspace.LoadErrors.Add(problem); // the defaults apply then, and the file is not saved over + } + + var name = ThemeCatalog.SelectedName(requested, workspace.Settings, user); found = name is null || ThemeCatalog.Find(themes, name) is not null; return ThemeCatalog.Resolve(name, themes, errors); } @@ -139,6 +195,8 @@ public static string Snapshot(string workspacePath, int width = 120, int height using var runner = new RequestRunner(workspace) { RequireScriptRuntimes = false }; runner.ConfigureScripts(); + runner.ConfigureProxy(); + runner.ConfigureFiles(); using var app = Application.Create(); app.Init(Terminal.Gui.Drivers.DriverRegistry.Names.ANSI); app.Driver!.SetScreenSize(width, height); diff --git a/src/TermRest.Tui/Views/AuthEditor.cs b/src/TermRest.Tui/Views/AuthEditor.cs index cd49224..f36b6a7 100644 --- a/src/TermRest.Tui/Views/AuthEditor.cs +++ b/src/TermRest.Tui/Views/AuthEditor.cs @@ -1,6 +1,8 @@ +using Terminal.Gui.Input; using Terminal.Gui.ViewBase; using Terminal.Gui.Views; using TermRest.Core.Model; +using TermRest.Tui.Dialogs; namespace TermRest.Tui.Views; @@ -34,6 +36,10 @@ public AuthEditor() Height = Dim.Fill(); _types = new ListView { X = 0, Y = 0, Width = 28, Height = Dim.Fill() }; _types.SetSource(_labels); + + // ListView's Ctrl+N (down) would change the auth type instead of the window's New request; Ctrl+P (up) goes with it. + _types.KeyBindings.Remove(Key.N.WithCtrl); + _types.KeyBindings.Remove(Key.P.WithCtrl); _types.ValueChanged += (_, e) => { if (!_loading && e.NewValue is int index) @@ -52,6 +58,15 @@ public AuthEditor() public AuthSpec? Auth => _auth; + /// Describes again the auth the request inherits (it was added to a collection, or moved to another folder). + public void RefreshInherited() + { + if (_auth is null) + { + BuildFields(); + } + } + public void Load(AuthSpec? auth) { _loading = true; @@ -141,7 +156,8 @@ private void BuildFields() var y = 0; void Note(string text) { - _fields.Add(new Label { Text = text, X = 0, Y = y, Width = Dim.Fill() }); + // A note may name a folder or a collection (the auth inherited from it): shown as written. + _fields.Add(new Label { HotKeySpecifier = Ui.NoHotKey, Text = text, X = 0, Y = y, Width = Dim.Fill() }); y += 2; } @@ -203,15 +219,15 @@ void Choice(string label, string key, string[] values, string[] labels) Field("Domain", "domain"); break; case "bearer": - Field("Token", "token"); + Field("Token", "token", secret: true); break; case "apikey": Field("Key", "key"); - Field("Value", "value"); + Field("Value", "value", secret: true); Choice("Add to", "in", ["header", "query"], ["Header", "Query params"]); break; case "oauth2": - Field("Access token", "accessToken"); + Field("Access token", "accessToken", secret: true); Field("Header prefix", "headerPrefix"); Choice("Add token to", "addTokenTo", ["header", "queryParams"], ["Header", "Query params"]); Note("Paste a token; built-in token acquisition (incl. Entra ID with certificates) is on the roadmap."); diff --git a/src/TermRest.Tui/Views/BodyEditor.cs b/src/TermRest.Tui/Views/BodyEditor.cs index bf7d6be..48d7e25 100644 --- a/src/TermRest.Tui/Views/BodyEditor.cs +++ b/src/TermRest.Tui/Views/BodyEditor.cs @@ -1,6 +1,7 @@ using Terminal.Gui.ViewBase; using Terminal.Gui.Views; using TermRest.Core.Http; +using TermRest.Core.IO; using TermRest.Core.Json; using TermRest.Core.Model; using TermRest.Tui.Dialogs; @@ -16,6 +17,9 @@ internal sealed class BodyEditor : View private static readonly string[] LanguageLabels = ["JSON", "XML", "Text", "HTML", "JavaScript"]; private static readonly string?[] FileLanguages = [null, .. Languages]; + /// How long typing in the file path pauses before the file is looked up: once per typed path, not per key. + private static readonly TimeSpan TypingPause = TimeSpan.FromMilliseconds(300); + private readonly OptionSelector _mode; private readonly OptionSelector _language; private readonly Button _beautify; @@ -63,6 +67,12 @@ public BodyEditor() } ShowMode(); + if (_body.Mode == BodyMode.File) + { + _fileCheck++; + DescribeFile(); + } + RaiseChanged(); } }; @@ -80,9 +90,9 @@ public BodyEditor() _beautify.Accepted += (_, _) => Beautify(); _raw = new TextArea { X = 0, Y = 2, Width = Dim.Fill(), Height = Dim.Fill() }; - _raw.UserEdited += (_, _) => + _raw.UserEdited += (_, text) => { - _body.Raw = _raw.GetText(); + _body.Raw = text; RaiseChanged(); }; @@ -111,19 +121,21 @@ public BodyEditor() _fileCheck++; _body.FileSrc = _filePath.Text; RaiseChanged(); - DescribeFile(); + DescribeFile(TypingPause); } }; var browse = new Button { Text = "Browse…", X = Pos.AnchorEnd(12), Y = 0 }; browse.Accepted += (_, _) => { + // Not in the folder of a path the request won't send: listing it would reach that folder (a network share). var current = string.IsNullOrWhiteSpace(_body.FileSrc) || _body.FileSrc.Contains("{{", StringComparison.Ordinal) ? null : ResolveFile(_body.FileSrc.Trim()); - if (App is not null && Ui.PickFile(App, "Choose the file to send as the body", Path.GetDirectoryName(current) ?? BaseDirectory?.Invoke()) is { } path) + var start = current is null || (FilesFolder?.Invoke() is { } folder && !RealPath.IsWithin(current, folder)) ? null : Path.GetDirectoryName(current); + if (App is not null && Ui.PickFile(App, "Choose the file to send as the body", start ?? BaseDirectory?.Invoke()) is { } path) { ChooseFile(path); } }; - _fileStatus = new Label { X = 0, Y = 2, Width = Dim.Fill(), Text = "" }; + _fileStatus = new Label { HotKeySpecifier = Ui.NoHotKey, X = 0, Y = 2, Width = Dim.Fill(), Text = "" }; _recordingNotice = new Label { X = 0, @@ -143,15 +155,15 @@ public BodyEditor() _graphQLPanel = new View { X = 0, Y = 1, Width = Dim.Fill(), Height = Dim.Fill(), CanFocus = true }; _graphQLQuery = new TextArea { X = 0, Y = 1, Width = Dim.Percent(60), Height = Dim.Fill() }; - _graphQLQuery.UserEdited += (_, _) => + _graphQLQuery.UserEdited += (_, text) => { - _body.GraphQLQuery = _graphQLQuery.GetText(); + _body.GraphQLQuery = text; RaiseChanged(); }; _graphQLVariables = new TextArea { X = Pos.Right(_graphQLQuery) + 1, Y = 1, Width = Dim.Fill(), Height = Dim.Fill() }; - _graphQLVariables.UserEdited += (_, _) => + _graphQLVariables.UserEdited += (_, text) => { - _body.GraphQLVariables = _graphQLVariables.GetText(); + _body.GraphQLVariables = text; RaiseChanged(); }; _graphQLPanel.Add( @@ -171,6 +183,12 @@ public BodyEditor() /// Folder that relative file paths start from: the collection's folder, as when the request is sent. public Func? BaseDirectory { get; set; } + /// + /// The folder whose files the request may send (), or null for any: a file + /// outside it is not looked at, as sending doesn't (on Windows, looking at \\server\share signs in to that server). + /// + public Func? FilesFolder { get; set; } + /// Whether requests are being recorded: the file panel then says that recordings keep the path, not the content. public bool Recording { @@ -197,7 +215,7 @@ public void Load(RequestBody body) _filePath.Text = body.FileSrc ?? ""; _graphQLQuery.SetText(body.GraphQLQuery); _graphQLVariables.SetText(body.GraphQLVariables); - DescribeFile(); + DescribeFile(); // in file mode: another mode's body keeps a file path it doesn't send ShowMode(); } finally @@ -206,23 +224,36 @@ public void Load(RequestBody body) } } + /// + /// Looks the body file up again: a relative path starts at the collection's folder, which may have changed, and files + /// from outside the workspace folder may have been allowed. + /// + internal void RefreshFile() + { + _fileCheck++; + DescribeFile(); + } + /// /// Uses as the body file. With a type, the file must fit it first: a JSON body takes only - /// a valid JSON file. Anything else is turned down and the current file stays. + /// a valid JSON file. Anything else is turned down and the current file stays. A file the request won't send (outside the + /// workspace folder) is not read: it is used, and the Body tab says why it is not sent. /// internal void ChooseFile(string path) { - if (_body.FileLanguage is not { } language) + var folder = FilesFolder?.Invoke(); + if (_body.FileLanguage is not { } language || (folder is not null && !RealPath.IsWithin(path, folder))) { _filePath.Text = path; return; } - CheckFile(path, language, problem => + CheckFile(path, language, folder, problem => { if (problem is null) { _filePath.Text = path; + _fileCheck++; // it was just checked: the lookup the new path started is not needed ShowChecked(path, language); return; } @@ -254,7 +285,7 @@ private string ResolveFile(string path) { try { - return Path.IsPathRooted(path) ? path : Path.GetFullPath(Path.Combine(BaseDirectory?.Invoke() ?? Environment.CurrentDirectory, path)); + return Path.GetFullPath(Path.IsPathRooted(path) ? path : Path.Combine(BaseDirectory?.Invoke() ?? Environment.CurrentDirectory, path)); } catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) { @@ -262,9 +293,20 @@ private string ResolveFile(string path) } } - /// What is known without reading the file: whether it is there, and its size. - private void DescribeFile() + /// + /// What is known about the file: whether it is there, and its size; with , also whether + /// it fits its type. It is looked up in the background, after (the file can be large, or on a + /// slow or disconnected network drive), and only the latest lookup is shown. Only in file mode: a body of another mode + /// keeps a path it doesn't send. A file the request won't send is not looked at. + /// + private void DescribeFile(TimeSpan delay = default, bool checkContent = false) { + if (_body.Mode != BodyMode.File) + { + ShowFileStatus(""); + return; + } + var src = _body.FileSrc?.Trim() ?? ""; if (src.Length == 0) { @@ -278,57 +320,113 @@ private void DescribeFile() return; } - var file = new FileInfo(ResolveFile(src)); - if (!file.Exists) + var path = ResolveFile(src); + var folder = FilesFolder?.Invoke(); + if (folder is not null && !RealPath.IsWithin(path, folder)) { - ShowFileStatus($"✗ {file.FullName} does not exist.", "Error"); + ShowFileStatus($"✗ {path} is outside the workspace folder: {NotSent}", "Error"); return; } - var type = TypeLabel(_body.FileLanguage); - ShowFileStatus($"{file.Name} · {HttpExchange.FormatSize(file.Length)} · {(type is null ? "sent as it is" : $"checked as {type} when sent")}"); - } - - /// After the type changed: checks the chosen file right away, so that a mismatch shows before sending. - private void CheckChosenFile() - { - var src = _body.FileSrc?.Trim() ?? ""; - var path = src.Length == 0 || src.Contains("{{", StringComparison.Ordinal) ? null : ResolveFile(src); - if (_body.FileLanguage is not { } language || path is null || !File.Exists(path)) + var language = _body.FileLanguage; + if (App is not { } app) { - _fileCheck++; - DescribeFile(); + ShowFileStatus(LookUp(path, language, checkContent, folder)); // not shown yet: there is no main loop to come back to return; } - CheckFile(path, language, problem => + var check = _fileCheck; + ShowFileStatus(checkContent && language is not null ? $"Checking {Path.GetFileName(path)}…" : $"Looking for {path}…"); + app.AddTimeout(delay, () => { - if (problem is null) + if (check == _fileCheck) { - ShowChecked(path, language); + _ = Task.Run(() => LookUp(path, language, checkContent, folder)).ContinueWith( + task => app.AddTimeout(TimeSpan.Zero, () => + { + if (check == _fileCheck) + { + ShowFileStatus(task.IsCompletedSuccessfully ? task.Result : ($"✗ {task.Exception?.GetBaseException().Message}", "Error")); + } + + return false; + }), + TaskScheduler.Default); + } + + return false; + }); + } + + /// + /// The file's status, read from the disk: whether it is there and its size, and with + /// whether it fits its type. A file that leads out of through a link is not looked at. + /// + private static (string Text, string? Scheme) LookUp(string path, string? language, bool checkContent, string? folder) + { + try + { + if (folder is not null && !RealPath.IsInside(path, folder)) + { + return ($"✗ {path} leads outside the workspace folder through a link: {NotSent}", "Error"); } - else + + var file = new FileInfo(path); + if (!file.Exists) { - ShowFileStatus($"✗ {problem} It is not sent until it is fixed, or the type is Binary.", "Error"); + return ($"✗ {file.FullName} does not exist.", "Error"); } - }); + + if (checkContent && language is not null) + { + return BodyFile.Check(path, language) is { } problem + ? ($"✗ {problem} It is not sent until it is fixed, or the type is Binary.", "Error") + : (Checked(file, language), ThemeCatalog.SuccessScheme); + } + + var type = TypeLabel(language); + return ($"{file.Name} · {HttpExchange.FormatSize(file.Length)} · {(type is null ? "sent as it is" : $"checked as {type} when sent")}", null); + } + catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException or NotSupportedException) + { + return ($"✗ {ex.Message}", "Error"); // a path no file can have (a NUL in it) + } } - /// Checks a file in the background (it can be large); gets the problem, or null. - private void CheckFile(string path, string language, Action done) + private const string NotSent = "it is not sent unless you allow files from outside it (Tools › Settings…)."; + + /// After the type changed: checks the chosen file right away, so that a mismatch shows before sending. + private void CheckChosenFile() + { + _fileCheck++; + DescribeFile(checkContent: true); + } + + /// + /// Checks a file in the background (it can be large); gets the problem, or null. A file that leads + /// out of through a link is not read: it is used, and the Body tab says why it is not sent. + /// + private void CheckFile(string path, string language, string? folder, Action done) { var check = ++_fileCheck; var app = App; ShowFileStatus($"Checking {Path.GetFileName(path)}…"); - _ = Task.Run(() => BodyFile.Check(path, language)).ContinueWith( + _ = Task.Run(() => folder is not null && !RealPath.IsInside(path, folder) ? (Outside: true, Problem: null) : (Outside: false, Problem: BodyFile.Check(path, language))).ContinueWith( task => { - var problem = task.IsCompletedSuccessfully ? task.Result : task.Exception?.GetBaseException().Message ?? "The check was cancelled."; + var (outside, problem) = task.IsCompletedSuccessfully ? task.Result : (false, task.Exception?.GetBaseException().Message ?? "The check was cancelled."); app?.AddTimeout(TimeSpan.Zero, () => { if (check == _fileCheck) { - done(problem); + if (outside) + { + _filePath.Text = path; + } + else + { + done(problem); + } } return false; @@ -337,11 +435,12 @@ private void CheckFile(string path, string language, Action done) TaskScheduler.Default); } - private void ShowChecked(string path, string language) - { - var file = new FileInfo(path); - ShowFileStatus($"✓ {file.Name} · {HttpExchange.FormatSize(file.Exists ? file.Length : 0)} · checked as {TypeLabel(language)}", ThemeCatalog.SuccessScheme); - } + private void ShowChecked(string path, string language) => ShowFileStatus(Checked(new FileInfo(path), language), ThemeCatalog.SuccessScheme); + + private static string Checked(FileInfo file, string language) => + $"✓ {file.Name} · {HttpExchange.FormatSize(file.Exists ? file.Length : 0)} · checked as {TypeLabel(language)}"; + + private void ShowFileStatus((string Text, string? Scheme) status) => ShowFileStatus(status.Text, status.Scheme); private void ShowFileStatus(string text, string? scheme = null) { diff --git a/src/TermRest.Tui/Views/CollectionTree.cs b/src/TermRest.Tui/Views/CollectionTree.cs index d31bc89..124150b 100644 --- a/src/TermRest.Tui/Views/CollectionTree.cs +++ b/src/TermRest.Tui/Views/CollectionTree.cs @@ -4,6 +4,7 @@ using Terminal.Gui.Views; using TermRest.Core.Postman; using TermRest.Core.Workspace; +using TermRest.Tui.Dialogs; using TermRest.Tui.Theming; using Attribute = Terminal.Gui.Drawing.Attribute; @@ -164,15 +165,15 @@ public void Select(object item) private static bool CanExpand(object item) => item is PostmanCollection or FolderNode; - private static string Describe(object item) => item switch + private string Describe(object item) => Ui.Drawable(item switch { - PostmanCollection collection => $"{(collection.IsDirty ? "● " : "")}{collection.Name}", + PostmanCollection collection => $"{(collection.IsDirty ? "● " : "")}{_workspace.DisplayName(collection)}", FolderNode folder => folder.Name, RequestNode request => $"{ShortMethod(request.Method),-4} {request.Name}", _ => item.ToString() ?? "", - }; + }); - private static string ShortMethod(string method) => method.ToUpperInvariant() switch + private static string ShortMethod(string method) => Ui.Drawable(method).ToUpperInvariant() switch { "DELETE" => "DEL", "OPTIONS" => "OPT", diff --git a/src/TermRest.Tui/Views/HistoryView.cs b/src/TermRest.Tui/Views/HistoryView.cs index 38c1817..bb98f62 100644 --- a/src/TermRest.Tui/Views/HistoryView.cs +++ b/src/TermRest.Tui/Views/HistoryView.cs @@ -4,6 +4,7 @@ using Terminal.Gui.ViewBase; using Terminal.Gui.Views; using TermRest.Core.History; +using TermRest.Tui.Dialogs; namespace TermRest.Tui.Views; @@ -15,9 +16,9 @@ internal sealed class HistoryView : View { private readonly TextField _filter; private readonly ListView _list; - private readonly ObservableCollection _rows = []; private readonly List _all = []; private readonly List _shown = []; + private ObservableCollection _rows = []; private string _emptyText = "No requests sent yet."; private bool _refreshing; @@ -33,6 +34,10 @@ public HistoryView() _list = new ListView { X = 0, Y = 1, Width = Dim.Fill(), Height = Dim.Fill() }; _list.SetSource(_rows); + + // ListView's Ctrl+N (down) would hide the window's New request; Ctrl+P (up) goes with it. + _list.KeyBindings.Remove(Key.N.WithCtrl); + _list.KeyBindings.Remove(Key.P.WithCtrl); _list.ValueChanged += (_, e) => { // Only the user's selection opens an entry; refreshing the list does not replace the editor's request. @@ -102,19 +107,28 @@ public HistoryView() public int Count => _all.Count; + /// Entries listed at most: as many as the history keeps (it deletes older ones, and their response bodies). + public int Limit { get; set; } = int.MaxValue; + public IReadOnlyList Rows => _rows; public void SetEntries(IEnumerable entries, string emptyText) { _all.Clear(); - _all.AddRange(entries); + _all.AddRange(entries.Take(Limit)); _emptyText = emptyText; ApplyFilter(); } + /// Lists a new entry first; the oldest beyond go, as they go from the history. public void Prepend(HistoryEntry entry) { _all.Insert(0, entry); + if (_all.Count > Limit) + { + _all.RemoveRange(Limit, _all.Count - Limit); + } + ApplyFilter(); } @@ -137,19 +151,18 @@ private void ApplyFilter() { _shown.Clear(); _shown.AddRange(filter.Length == 0 ? _all : _all.Where(e => Matches(e, filter))); - _rows.Clear(); - foreach (var entry in _shown) - { - _rows.Add(Format(entry)); - } - if (_shown.Count == 0) + // New rows each time: the list measures all its rows again after each row added to them. + _rows = _shown.Count == 0 ? [filter.Length == 0 ? _emptyText : "No match."] : new ObservableCollection(_shown.Select(Format)); + _list.SetSource(_rows); + if (_shown.Count > 0) { - _rows.Add(filter.Length == 0 ? _emptyText : "No match."); + _list.SelectedItem = previous is null ? 0 : Math.Max(0, _shown.IndexOf(previous)); } else { - _list.SelectedItem = previous is null ? 0 : Math.Max(0, _shown.IndexOf(previous)); + // No row is selected, which would scroll the list to it: back to the top, where the message is. + _list.Viewport = _list.Viewport with { X = 0, Y = 0 }; } } finally @@ -173,6 +186,6 @@ internal static string Format(HistoryEntry entry) var time = local.Date == DateTime.Today ? local.ToString("HH:mm", CultureInfo.InvariantCulture) : local.ToString("MM-dd", CultureInfo.InvariantCulture); var status = entry.Status?.ToString(CultureInfo.InvariantCulture) ?? "ERR"; var target = Uri.TryCreate(entry.Url, UriKind.Absolute, out var uri) ? uri.PathAndQuery : entry.Url; - return $"{time} {status,-3} {entry.Method,-6} {target}"; + return Ui.Drawable($"{time} {status,-3} {entry.Method,-6} {target}"); } } diff --git a/src/TermRest.Tui/Views/KeyValueTable.cs b/src/TermRest.Tui/Views/KeyValueTable.cs index 1d69a37..aad6d3c 100644 --- a/src/TermRest.Tui/Views/KeyValueTable.cs +++ b/src/TermRest.Tui/Views/KeyValueTable.cs @@ -25,6 +25,8 @@ internal sealed class KeyValueTable : View { private readonly KeyValueKind _kind; private readonly TableView _table; + private readonly EntryRows _rows; + private readonly CheckBoxTableSourceWrapperByObject _checkBoxes; private readonly Button _add; private readonly Button _remove; private List _entries = []; @@ -48,8 +50,23 @@ public KeyValueTable(KeyValueKind kind) _table.Style.ExpandLastColumn = true; _table.Style.ShowHorizontalBottomLine = true; _table.Style.AlwaysShowHeaders = true; - _table.Accepted += (_, _) => EditSelected(); + // Enter or a double-click edits the row, handled here: a dialog holding the table (Manage environments) stays open. + _table.Accepting += (_, e) => + { + e.Handled = true; + EditSelected(); + }; _table.KeyDown += OnTableKeyDown; + _table.MouseEvent += OnTableMouseEvent; + + // TableView's Ctrl+N (down) would hide the window's New request; Ctrl+P (up) goes with it. + _table.KeyBindings.Remove(Key.N.WithCtrl); + _table.KeyBindings.Remove(Key.P.WithCtrl); + + // The checkbox column handles the table's Space key for as long as the table lives (Terminal.Gui never unsubscribes + // it), so there is one, over rows that follow the entries. Clicks on it are handled here (OnTableMouseEvent). + _rows = new EntryRows(this); + _checkBoxes = new CheckBoxTableSourceWrapperByObject(_table, _rows, e => e.Enabled, SetEnabled); _add = new Button { Text = "+ Add", X = 0, Y = Pos.AnchorEnd(1), NoDecorations = true, ShadowStyle = null }; _add.Accepted += (_, _) => AddEntry(); @@ -101,15 +118,8 @@ private void Rebind() columns["Description"] = e => e.Description ?? ""; } - var source = new EnumerableTableSource(_entries, columns); - _table.Table = new CheckBoxTableSourceWrapperByObject(_table, source, e => e.Enabled, (e, enabled) => - { - if (e.Enabled != enabled) - { - e.Enabled = enabled; - RaiseChanged(); - } - }); + _rows.SetColumns(columns); + _table.Table = _checkBoxes; _table.Update(); } @@ -135,18 +145,69 @@ private string DisplayValue(KeyValueEntry entry) private void OnTableKeyDown(object? sender, Key key) { + // Path variables follow the URL's :name segments: rows are neither added nor removed here. + if (_kind == KeyValueKind.PathVariables) + { + return; + } + if (key == Key.Delete || key == Key.DeleteChar) { - RemoveSelected(); - key.Handled = true; + key.Handled = RemoveSelected(); } - else if (key == Key.InsertChar || key == Key.N.WithCtrl) + else if (key == Key.InsertChar) { AddEntry(); key.Handled = true; } } + /// + /// Each click on a checkbox turns its row on or off (in the header, all rows) and moves the cursor to the row. + /// Terminal.Gui reports a second quick click only as a double click, which the table would take as Edit, and the + /// checkbox column alone would leave the cursor where it was. + /// + private void OnTableMouseEvent(object? sender, Mouse mouse) + { + if (mouse.Flags is not (MouseFlags.LeftButtonClicked or MouseFlags.LeftButtonDoubleClicked or MouseFlags.LeftButtonTripleClicked) + || mouse.Position is not { } position) + { + return; + } + + var cell = _table.ScreenToCell(position.X, position.Y, out var header); + if (header == 0) + { + var enabled = !_entries.All(e => e.Enabled); + foreach (var entry in _entries) + { + SetEnabled(entry, enabled); + } + } + else if (cell is { X: 0, Y: var row }) + { + SetEnabled(_entries[row], !_entries[row].Enabled); + _table.SetSelection(0, row, false); + _table.Update(); + } + else + { + return; + } + + _table.SetNeedsDraw(); + mouse.Handled = true; + } + + private void SetEnabled(KeyValueEntry entry, bool enabled) + { + if (entry.Enabled != enabled) + { + entry.Enabled = enabled; + RaiseChanged(); + } + } + private void AddEntry() { if (_kind == KeyValueKind.PathVariables || App is null) @@ -186,11 +247,12 @@ private void EditSelected() RaiseChanged(); } - private void RemoveSelected() + /// Removes the selected row; false when there is none (or rows cannot be removed). + private bool RemoveSelected() { if (_kind == KeyValueKind.PathVariables || Selected is not { } entry) { - return; + return false; } var index = _entries.IndexOf(entry); @@ -202,6 +264,7 @@ private void RemoveSelected() } RaiseChanged(); + return true; } private void BulkEdit() @@ -212,7 +275,7 @@ private void BulkEdit() } var edited = BulkEditDialog.Show(App, Noun, _entries); - if (edited is null) + if (edited is null || KeyValueEntry.ListEquals(_entries, edited)) { return; } @@ -240,4 +303,31 @@ private void BulkEdit() KeyValueKind.Variables => "default", _ => null, }; + + /// + /// The table's rows: the current entries, read when they are needed (Terminal.Gui's + /// copies them). + /// + private sealed class EntryRows(KeyValueTable owner) : IEnumerableTableSource + { + private Dictionary> _columns = []; + + public string[] ColumnNames { get; private set; } = []; + + public int Columns => ColumnNames.Length; + + public int Rows => owner._entries.Count; + + public object this[int row, int col] => _columns[ColumnNames[col]](owner._entries[row]); + + public void SetColumns(Dictionary> columns) + { + _columns = columns; + ColumnNames = [.. columns.Keys]; + } + + public IEnumerable GetAllObjects() => owner._entries; + + public KeyValueEntry GetObjectOnRow(int row) => owner._entries[row]; + } } diff --git a/src/TermRest.Tui/Views/RecordingIndicator.cs b/src/TermRest.Tui/Views/RecordingIndicator.cs index a79fea1..1a155ad 100644 --- a/src/TermRest.Tui/Views/RecordingIndicator.cs +++ b/src/TermRest.Tui/Views/RecordingIndicator.cs @@ -119,7 +119,7 @@ private void Update() var badge = new Attribute(red.IsDarkColor() ? Color.White : Color.Black, red, TextStyle.Bold); var elapsed = DateTimeOffset.Now - since; var clock = elapsed.TotalHours >= 1 - ? elapsed.ToString(@"h\:mm\:ss", CultureInfo.InvariantCulture) + ? $"{(int)elapsed.TotalHours}:{elapsed.ToString(@"mm\:ss", CultureInfo.InvariantCulture)}" // past a day too : elapsed.ToString(@"mm\:ss", CultureInfo.InvariantCulture); var dot = _dotVisible ? "●" : " "; var narrow = (SuperView?.Viewport.Width ?? 120) < 100; diff --git a/src/TermRest.Tui/Views/RequestEditor.cs b/src/TermRest.Tui/Views/RequestEditor.cs index 6834f00..d20e6cb 100644 --- a/src/TermRest.Tui/Views/RequestEditor.cs +++ b/src/TermRest.Tui/Views/RequestEditor.cs @@ -6,6 +6,7 @@ using TermRest.Core.Model; using TermRest.Core.Postman; using TermRest.Core.Scripting; +using TermRest.Tui.Dialogs; namespace TermRest.Tui.Views; @@ -135,13 +136,13 @@ public RequestEditor() MarkModified(); } }; - _certificateInfo = new Label { X = 30, Y = 3, Width = Dim.Fill(), Height = 2, Text = "" }; + // Names a certificate and its file; next to Manage certificates…, which a hotkey from it would press. + _certificateInfo = new Label { HotKeySpecifier = Ui.NoHotKey, X = 30, Y = 3, Width = Dim.Fill(), Height = 2, Text = "" }; var manageCertificates = new Button { Text = "Manage certificates…", X = 30, Y = 5 }; manageCertificates.Accepted += (_, _) => ManageCertificatesRequested?.Invoke(this, EventArgs.Empty); _description = new TextArea { X = 0, Y = 8, Width = Dim.Fill(), Height = Dim.Fill() }; - _description.UserEdited += (_, _) => + _description.UserEdited += (_, text) => { - var text = _description.GetText(); Spec.Description = text.Length == 0 ? null : text; MarkModified(); }; @@ -198,6 +199,16 @@ public Func? BaseDirectory set => _body.BaseDirectory = value; } + /// The folder whose files the request may send, or null for any (see ). + public Func? FilesFolder + { + get => _body.FilesFolder; + set => _body.FilesFolder = value; + } + + /// Looks the body file up again (after files from outside the workspace folder were allowed, or no longer). + public void RefreshBodyFile() => _body.RefreshFile(); + /// What the Body tab says about the body file (for tests). internal string BodyFileStatus => _body.FileStatus; @@ -221,6 +232,18 @@ public string DefaultScriptLanguage /// Shows again what the request's scripts run (after its collection's scripts or the language order changed). public void RefreshScripts() => _scripts.Refresh(); + /// + /// Shows again what depends on the request's collection and folders, after it was added to a collection: the auth it + /// inherits, its body file (a relative path), the scripts that run with it, and its client certificate. + /// + public void RefreshContext() + { + _auth.RefreshInherited(); + _body.RefreshFile(); + _scripts.Refresh(); + RefreshCertificateInfo(); + } + /// Whether requests are being recorded: the Body tab then says how body files are recorded. public void SetRecording(bool recording) => _body.Recording = recording; diff --git a/src/TermRest.Tui/Views/ResponseView.cs b/src/TermRest.Tui/Views/ResponseView.cs index 6a9358b..ef18d11 100644 --- a/src/TermRest.Tui/Views/ResponseView.cs +++ b/src/TermRest.Tui/Views/ResponseView.cs @@ -1,5 +1,7 @@ using System.Globalization; using System.Text; +using Terminal.Gui.Input; +using Terminal.Gui.Text; using Terminal.Gui.ViewBase; using Terminal.Gui.Views; using TermRest.Core.Http; @@ -11,6 +13,24 @@ namespace TermRest.Tui.Views; /// Response pane: status line plus Body / Headers / Timeline / TLS tabs. internal sealed class ResponseView : View { + /// + /// The body tab shows this many characters at most (the editor takes about 90 bytes of memory for each); Copy and + /// Save as… give the whole body. + /// + internal const int MaxShownLength = 1_048_576; + + /// Bodies of this many bytes or more are formatted (decoded, pretty printed) in the background. + private const int BackgroundSize = 1_048_576; + + /// The Timeline tab shows this many characters of a request's body at most. + private const int TimelineBodyLength = 4000; + + /// How far back from where a long body is cut a line break is looked for, to cut there instead. + private const int LineBreakSearch = 4096; + + /// The Headers tab's Value column is never narrower than this, however narrow the pane. + private const int MinValueColumns = 10; + private readonly Label _status; private readonly TabPanel _tabs; private readonly View _bodyTab; @@ -18,11 +38,16 @@ internal sealed class ResponseView : View private readonly Button _pretty; private readonly Button _wrap; private readonly TableView _headers; + private List> _shownHeaders = []; + private int _nameColumns; // the widest header name shown private readonly TextArea _timeline; private readonly TextArea _tls; private readonly TextArea _scripts; private HttpExchange? _exchange; + private bool _fromHistory; // the exchange shown came from the history: its body as the history keeps it private bool _prettyOn = true; + private int _bodyVersion; // a body formatted in the background is shown only if no other body replaced it meanwhile + private bool _disposed; public ResponseView() { @@ -30,7 +55,7 @@ public ResponseView() Width = Dim.Fill(); Height = Dim.Fill(); - _status = new Label { 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(), Text = "No response yet. Press F5 (or Enter in the URL bar) to send." }; _tabs = new TabPanel { X = 0, Y = 1, Width = Dim.Fill(), Height = Dim.Fill() }; @@ -49,13 +74,7 @@ public ResponseView() _wrap.Text = _body.WordWrap ? "Wrap: on" : "Wrap: off"; }; var copy = new Button { Text = "Copy", X = Pos.Right(_wrap) + 2, Y = 0, NoDecorations = true, ShadowStyle = null }; - copy.Accepted += (_, _) => - { - if (_exchange?.Response is not null) - { - Notify(Ui.CopyToClipboard(App, _body!.GetText()) ? "Response body copied to the clipboard." : "Clipboard is not available in this terminal."); - } - }; + copy.Accepted += (_, _) => CopyBody(); var save = new Button { Text = "Save as…", X = Pos.Right(copy) + 2, Y = 0, NoDecorations = true, ShadowStyle = null }; save.Accepted += (_, _) => SaveBody(); _body = new TextArea { X = 0, Y = 1, Width = Dim.Fill(), Height = Dim.Fill(), ReadOnly = true }; @@ -64,6 +83,15 @@ public ResponseView() var headersTab = new View { Title = "Headers", Width = Dim.Fill(), Height = Dim.Fill(), CanFocus = true }; _headers = new TableView { Width = Dim.Fill(), Height = Dim.Fill(), FullRowSelect = true }; _headers.Style.ExpandLastColumn = true; + + // A value cut at the pane's edge ends with "…" (a column style's mark); Enter or a double-click shows the whole header. + _headers.Style.GetOrCreateColumnStyle(1); + _headers.FrameChanged += (_, _) => FitValueColumn(); + _headers.Accepted += (_, _) => ShowSelectedHeader(); + + // TableView's Ctrl+N (down) would hide the window's New request; Ctrl+P (up) goes with it. + _headers.KeyBindings.Remove(Key.N.WithCtrl); + _headers.KeyBindings.Remove(Key.P.WithCtrl); headersTab.Add(_headers); var timelineTab = new View { Title = "Timeline", Width = Dim.Fill(), Height = Dim.Fill(), CanFocus = true }; @@ -102,12 +130,22 @@ public ResponseView() /// The Scripts tab's text (for tests). internal string ScriptsText => _scripts.GetText(); + /// The Body tab's text (for tests). + internal string BodyText => _body.GetText(); + + /// The Timeline tab's text (for tests). + internal string TimelineText => _timeline.GetText(); + + /// The TLS tab's text (for tests). + internal string TlsText => _tls.GetText(); + public void Clear() { _exchange = null; + _fromHistory = false; _status.Text = "No response yet. Press F5 (or Enter in the URL bar) to send."; _status.SchemeName = null; - _body.SetText(""); + ShowBody(""); _timeline.SetText(""); _tls.SetText(""); _scripts.SetText(NoScripts); @@ -128,8 +166,14 @@ public void ShowSending(PreparedRequest request) _timeline.SetText(DescribeRequest(request, null)); } - public void ShowExchange(HttpExchange exchange) + /// + /// 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. + /// + 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; var response = exchange.Response; var scripts = exchange.Scripts; @@ -139,7 +183,7 @@ public void ShowExchange(HttpExchange exchange) _status.SchemeName = exchange.Cancelled ? null : "Error"; // When a script stopped the request, its traceback is what the user needs to see. - _body.SetText(exchange.Cancelled ? "" : scripts?.Error is not null ? $"{exchange.ErrorMessage}\n\n{scripts.Describe()}" : exchange.ErrorMessage ?? ""); + ShowBody(exchange.Cancelled ? "" : scripts?.Error is not null ? ShownScripts($"{exchange.ErrorMessage}\n\n{scripts.Describe()}") : exchange.ErrorMessage ?? ""); SetHeaders([]); } else @@ -147,7 +191,10 @@ public void ShowExchange(HttpExchange exchange) 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}" : ""; - _status.Text = $"{response.StatusCode} {response.ReasonPhrase} · {HttpExchange.Format(exchange.Timing.Total)} · {HttpExchange.FormatSize(response.Body.LongLength)} · {http}{tests}{warnings}"; + + // 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.SchemeName = response.StatusCode switch { >= 500 => "Error", @@ -159,15 +206,22 @@ public void ShowExchange(HttpExchange exchange) RenderBody(); } - _scripts.SetText(scripts is null ? NoScripts : scripts.Describe()); + _scripts.SetText(_fromHistory ? "Script results are not kept in the history." : scripts is null ? NoScripts : ShownScripts(scripts.Describe())); - _timeline.SetText(DescribeRequest(exchange.Request, exchange)); - _tls.SetText(exchange.Tls.Count == 0 - ? exchange.Request.Uri?.Scheme == "https" ? "No TLS session was established." : "Plain HTTP (no TLS)." - : string.Join("\n\n", exchange.Tls.Select(t => t.Describe()))); + _timeline.SetText(DescribeRequest(exchange.Request, exchange, _fromHistory)); + _tls.SetText(_fromHistory + ? "TLS details are not kept in the history." + : exchange.Tls.Count == 0 + ? exchange.Request.Uri?.Scheme == "https" ? "No TLS session was established." : "Plain HTTP (no TLS)." + : string.Join("\n\n", exchange.Tls.Select(t => t.Describe()))); SetNeedsDraw(); } + /// + /// Shows the response body, pretty or not, formatted from the response each time (as Copy is): the editor's text has + /// its own line breaks (a lone CR shows as one) and only the start of a long body, and keeping the whole text as well + /// would take memory. A large body is formatted in the background, and shown if nothing replaced it meanwhile. + /// private void RenderBody() { if (_exchange?.Response is not { } response) @@ -175,25 +229,195 @@ private void RenderBody() return; } - var text = BodyFormatter.Format(response.Body, response.ContentType, _prettyOn); - if (response.BodyTruncated) + // The history may have no copy of a body that was not empty (it keeps none, or the copy's file is gone). + if (BodyNotKept) + { + ShowBody("(response body not kept in the history)"); + return; + } + + var pretty = _prettyOn; + if (App is not { } app || response.Body.Length < BackgroundSize) { - text += "\n\n… (truncated)"; + ShowBody(Shown(response, pretty)); + return; } + var version = ShowBody("Formatting…"); + _ = Task.Run(() => Shown(response, pretty)).ContinueWith( + task => app.AddTimeout(TimeSpan.Zero, () => + { + if (version == _bodyVersion && !_disposed) + { + _body.SetText(task.IsCompletedSuccessfully ? task.Result : $"✗ {task.Exception?.GetBaseException().Message}"); + } + + return false; + }), + TaskScheduler.Default); + } + + /// The response comes from the history, which has no copy of its body, though the body was not empty. + private bool BodyNotKept => _fromHistory && _exchange?.Response?.Body.Length == 0 && _exchange.HistoryEntry?.Size > 0; + + /// Shows in the body tab, in place of a body still being formatted. + private int ShowBody(string text) + { _body.SetText(text); + return ++_bodyVersion; + } + + /// Copies the whole body, as formatted (a large one is formatted in the background). + private void CopyBody() + { + if (_exchange?.Response is not { } response) + { + return; + } + + if (BodyNotKept) + { + Notify("The history kept no copy of this response body."); + return; + } + + var pretty = _prettyOn; + if (App is not { } app || response.Body.Length < BackgroundSize) + { + Copied(Whole(response, pretty)); + return; + } + + Notify("Copying the response body…"); + _ = Task.Run(() => Whole(response, pretty)).ContinueWith( + task => app.AddTimeout(TimeSpan.Zero, () => + { + if (task.IsCompletedSuccessfully) + { + Copied(task.Result); + } + else if (!_disposed) + { + Notify($"✗ {task.Exception?.GetBaseException().Message}"); + } + + return false; + }), + TaskScheduler.Default); + } + + private void Copied(string text) + { + if (!_disposed) + { + Notify(Ui.CopyToClipboard(App, text) ? "Response body copied to the clipboard." : "Clipboard is not available in this terminal."); + } + } + + /// The whole body as formatted, with a note when the size limit cut it. + private static string Whole(ResponseSnapshot response, bool pretty) + { + var text = BodyFormatter.Format(response.Body, response.ContentType, pretty); + return response.BodyTruncated ? text + "\n\n… (truncated)" : text; } - private void SetHeaders(IReadOnlyList> headers) + /// + /// The body as the body tab shows it: formatted, and when longer than , its start (up to a + /// line break when one is near) and a note saying so. + /// + internal static string Shown(ResponseSnapshot response, bool pretty) { + var text = BodyFormatter.Format(response.Body, response.ContentType, pretty); + if (text.Length <= MaxShownLength) + { + return response.BodyTruncated ? text + "\n\n… (truncated)" : text; + } + + var truncated = response.BodyTruncated ? " (truncated)" : ""; + return string.Concat( + Start(text), + $"\n\n… showing the first {HttpExchange.FormatSize(MaxShownLength)} of {HttpExchange.FormatSize(text.Length)}{truncated}: Copy and Save as… give the whole body"); + } + + /// + /// What scripts printed (with their tests and errors), as the Scripts tab, or the Body tab of a request a script stopped, + /// shows it: like a body, at most characters. The command line prints it all. + /// + internal static string ShownScripts(string text) => text.Length <= MaxShownLength + ? text + : string.Concat(Start(text), $"\n\n… showing the first {HttpExchange.FormatSize(MaxShownLength)} of {HttpExchange.FormatSize(text.Length)} the scripts wrote"); + + /// + /// The start of a text longer than : up to a line break when one is near, and never inside a + /// character (a surrogate pair). + /// + private static ReadOnlySpan Start(string text) + { + var cut = text.LastIndexOf('\n', MaxShownLength - 1, LineBreakSearch); + if (cut < 0) + { + cut = char.IsHighSurrogate(text[MaxShownLength - 1]) ? MaxShownLength - 1 : MaxShownLength; + } + else if (cut > 0 && text[cut - 1] == '\r') + { + cut--; + } + + return text.AsSpan(0, cut); + } + + private void SetHeaders(List> headers) + { + _shownHeaders = headers; + _nameColumns = headers.Count == 0 ? 0 : headers.Max(h => h.Key.GetColumns()); _headers.Table = new EnumerableTableSource>(headers, new Dictionary, object>> { ["Header"] = h => h.Key, ["Value"] = h => h.Value, }); + FitValueColumn(); _headers.Update(); } + /// + /// Keeps the Value column within the pane, so that a value cut there ends with "…" in sight: Terminal.Gui widens the + /// last column to the pane, but never narrows it, and a longer value would run past the pane's edge, cut unmarked. + /// + private void FitValueColumn() + { + // The widest name (Terminal.Gui measures the rows in view, never wider), and the lines before, between and after the columns. + var names = Math.Min(_headers.MaxCellWidth, Math.Max("Header".Length, _nameColumns)); + var width = Math.Max(MinValueColumns, _headers.Viewport.Width - names - 3); + var style = _headers.Style.GetOrCreateColumnStyle(1); + if (style.MaxWidth != width) + { + style.MaxWidth = width; + _headers.Update(); + } + } + + /// The selected response header in full (Enter or a double-click): its value wrapped, to read, select or copy. + private void ShowSelectedHeader() + { + if (App is null || _headers.Value is not { } selection || selection.SelectedCell.Y < 0 || selection.SelectedCell.Y >= _shownHeaders.Count) + { + return; + } + + var (name, value) = _shownHeaders[selection.SelectedCell.Y]; + using var dialog = new Dialog { HotKeySpecifier = Ui.NoHotKey, Title = name, Width = Dim.Percent(80), Height = Dim.Percent(50) }; + var area = new TextArea { X = 1, Y = 1, Width = Dim.Fill(1), Height = Dim.Fill(), ReadOnly = true, WordWrap = true }; + area.SetText(value); + 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, value) ? $"The value of {name} copied to the clipboard." : "Clipboard is not available in this terminal."); + } + } + private void SaveBody() { if (_exchange?.Response is not { } response || App is null) @@ -201,16 +425,46 @@ private void SaveBody() return; } - if (Ui.PickSaveFile(App, "Save response body") is { } path) + if (BodyNotKept) + { + Notify("The history kept no copy of this response body."); + return; + } + + // Terminal.Gui's save dialog takes an existing file (a collection, when it opens on the workspace folder) without + // asking; Cancel is the default. + if (Ui.PickSaveFile(App, "Save response body") is { } path + && (!File.Exists(path) || MessageBox.Query(App, "Save response body", $"{path} exists. Replace it?", "Replace", "Cancel") == 0)) { - File.WriteAllBytes(path, response.Body); - Notify($"Saved {HttpExchange.FormatSize(response.Body.LongLength)} to {path}"); + try + { + File.WriteAllBytes(path, response.Body); + var saved = $"Saved {HttpExchange.FormatSize(response.Body.LongLength)} to {path}"; + Notify((_fromHistory, response.BodyTruncated) switch + { + (true, true) => $"⚠ {saved}: only the start of the body, as the history keeps it (secrets masked as ***)", + (true, false) => $"{saved}: the body as the history keeps it (secrets masked as ***)", + (false, true) => $"⚠ {saved}: only the start of the body, cut at the maximum response size (Tools > Settings)", + _ => saved, + }); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + Ui.Error(App, "Save response body", $"The response body could not be saved to {path}:\n{ex.Message}"); + } } } private void Notify(string message) => Notice?.Invoke(this, message); - private static string DescribeRequest(PreparedRequest request, HttpExchange? exchange) + protected override void Dispose(bool disposing) + { + _disposed = true; // formatting that finishes later must not touch the disposed views + base.Dispose(disposing); + } + + /// The exchange comes from the history, which has the client certificate but not the request's settings. + private static string DescribeRequest(PreparedRequest request, HttpExchange? exchange, bool fromHistory = false) { var builder = new StringBuilder(); builder.Append(CultureInfo.InvariantCulture, $"{request.Method} {request.Url}\n"); @@ -223,12 +477,32 @@ private static string DescribeRequest(PreparedRequest request, HttpExchange? exc if (request.Body.Kind != PreparedBodyKind.None) { var body = request.Body.Describe(); - builder.Append('\n').Append(body.Length > 4000 ? body[..4000] + "\n… (truncated)" : body).Append('\n'); + builder.Append('\n'); + if (body.Length > TimelineBodyLength) + { + // Not inside a character: half of one can't be shown. + var cut = char.IsHighSurrogate(body[TimelineBodyLength - 1]) ? TimelineBodyLength - 1 : TimelineBodyLength; + builder.Append(body.AsSpan(0, cut)).Append("\n… (truncated)"); + } + else + { + builder.Append(body); + } + + builder.Append('\n'); } builder.Append(CultureInfo.InvariantCulture, $"\nAuth: {request.AuthDescription}\n"); - builder.Append(CultureInfo.InvariantCulture, $"Client certificate: {(request.ClientCertificate is { } c ? $"{c.Entry.Name} — {c.Summary} ({c.Origin})" : "none")}\n"); - builder.Append(CultureInfo.InvariantCulture, $"SSL verification: {(request.StrictSsl ? "on" : "off")} · Redirects: {(request.FollowRedirects ? "follow" : "don't follow")}\n"); + if (fromHistory) + { + builder.Append(CultureInfo.InvariantCulture, $"Client certificate: {exchange?.HistoryEntry?.ClientCertificate ?? "none"}\n"); + builder.Append("SSL verification: (not recorded) · Redirects: (not recorded)\n"); + } + else + { + builder.Append(CultureInfo.InvariantCulture, $"Client certificate: {(request.ClientCertificate is { } c ? $"{c.Entry.Name} — {c.Summary} ({c.Origin})" : "none")}\n"); + builder.Append(CultureInfo.InvariantCulture, $"SSL verification: {(request.StrictSsl ? "on" : "off")} · Redirects: {(request.FollowRedirects ? "follow" : "don't follow")}\n"); + } if (exchange is not null) { diff --git a/src/TermRest.Tui/Views/ScriptsEditor.cs b/src/TermRest.Tui/Views/ScriptsEditor.cs index 22b4b39..a771095 100644 --- a/src/TermRest.Tui/Views/ScriptsEditor.cs +++ b/src/TermRest.Tui/Views/ScriptsEditor.cs @@ -1,6 +1,7 @@ using Terminal.Gui.ViewBase; using Terminal.Gui.Views; using TermRest.Core.Scripting; +using TermRest.Tui.Dialogs; namespace TermRest.Tui.Views; @@ -40,7 +41,7 @@ public ScriptsEditor(bool forRequest = false) Edit(ScriptLanguage.All[index]); } }; - _hint = new Label { X = 0, Y = 1, Width = Dim.Fill(), Height = 1, Text = "" }; + _hint = new Label { HotKeySpecifier = Ui.NoHotKey, X = 0, Y = 1, Width = Dim.Fill(), Height = 1, Text = "" }; Add(new Label { Text = "Language", X = 0, Y = 0 }, _language, _hint); var top = 2; if (forRequest) @@ -66,15 +67,18 @@ public ScriptsEditor(bool forRequest = false) OnChanged(); } }; - _status = new Label { X = Pos.Right(_runIn) + 2, Y = 2, Width = Dim.Fill(), Height = 1, Text = "" }; + _status = new Label { HotKeySpecifier = Ui.NoHotKey, X = Pos.Right(_runIn) + 2, Y = 2, Width = Dim.Fill(), Height = 1, Text = "" }; Add(new Label { Text = "Run in", X = 0, Y = 2, Width = 9 }, _runIn, _status); top = 3; } _preRequest = new TextArea { X = 0, Y = top + 1, Width = Dim.Percent(50), Height = Dim.Fill(), SyntaxLanguage = _editing }; _test = new TextArea { X = Pos.Right(_preRequest) + 1, Y = top + 1, Width = Dim.Fill(), Height = Dim.Fill(), SyntaxLanguage = _editing }; - _preRequest.UserEdited += (_, _) => OnEdited(); - _test.UserEdited += (_, _) => OnEdited(); + + // The other script as stored, not read back from its editor (a full read per key): Terminal.Gui keeps characters + // composed (NFC), so the script left alone would change. + _preRequest.UserEdited += (_, text) => OnEdited(text, _scripts.GetValueOrDefault(_editing)?.Test ?? ""); + _test.UserEdited += (_, text) => OnEdited(_scripts.GetValueOrDefault(_editing)?.PreRequest ?? "", text); if (forRequest) { _runPreRequest = new CheckBox { Text = "Pre-request (before sending)", X = 0, Y = top }; @@ -197,10 +201,10 @@ public void Refresh() bool Runs(ScriptPhase phase) => plan?.Runs(phase) ?? _settings.Runs(phase) ?? scripts.Has(phase); } - private void OnEdited() + private void OnEdited(string preRequest, string test) { var had = _scripts.TryGetValue(_editing, out var before) && !before.IsEmpty; - _scripts[_editing] = new LanguageScripts(_editing, _preRequest.GetText(), _test.GetText()); + _scripts[_editing] = new LanguageScripts(_editing, preRequest, test); if (had == _scripts[_editing].IsEmpty) { _loading = true; diff --git a/src/TermRest.Tui/Views/TextArea.cs b/src/TermRest.Tui/Views/TextArea.cs index e1cc26f..9a08415 100644 --- a/src/TermRest.Tui/Views/TextArea.cs +++ b/src/TermRest.Tui/Views/TextArea.cs @@ -1,9 +1,16 @@ +using System.Runtime.CompilerServices; +using System.Text; using Terminal.Gui.Drawing; +using Terminal.Gui.Drivers; +using Terminal.Gui.Input; +using Terminal.Gui.Text; using Terminal.Gui.ViewBase; using Terminal.Gui.Views; using TermRest.Tui.Syntax; using TermRest.Tui.Theming; using Attribute = Terminal.Gui.Drawing.Attribute; +using Point = System.Drawing.Point; +using Rectangle = System.Drawing.Rectangle; namespace TermRest.Tui.Views; @@ -33,15 +40,127 @@ public TextArea() { Width = Dim.Fill(); Height = Dim.Fill(); - TabKeyAddsTab = false; WordWrap = false; ScrollBars = true; + + // Tab and Shift+Tab move to the next and previous field. (Turning TabKeyAddsTab off instead would also make the + // tabs in the text 0 columns wide.) + KeyBindings.Remove(Key.Tab); + KeyBindings.Remove(Key.Tab.WithShift); + + // TextView's Ctrl+L (a color picker) and Ctrl+N (cursor down) would hide the window's Focus URL bar and New request. + KeyBindings.Remove(Key.L.WithCtrl); + KeyBindings.Remove(Key.N.WithCtrl); + + // TextView builds a selection's text by adding each line to all the text before it, to copy it and once more to + // see that something is selected: seconds for a large selection. These build it in one pass. + AddCommand(Command.Copy, () => CopySelection(cut: false)); + AddCommand(Command.Cut, () => CopySelection(cut: true)); + + // TextView's undo and redo leave a selection on, its start maybe past the text they shorten: the next key would fail. + AddCommand(Command.Undo, () => EndingTheSelection(Undo)); + AddCommand(Command.Redo, () => EndingTheSelection(Redo)); + + // After each move or edit, TextView builds the selected text anew to see whether it may offer completions, a step + // it skips while it draws: seconds for each Shift+arrow on a large selection. TermRest offers no completions and + // TextArea draws by itself, so TextView's "drawing" flag stays set. (A Terminal.Gui without that field is only + // slower.) + try + { + TextViewIsDrawing(this) = true; + } + catch (MissingFieldException) + { + } + + Autocomplete = new Completions(this); + } + + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_isDrawing")] + private static extern ref bool TextViewIsDrawing(TextView view); + + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_copiedText")] + private static extern ref string? TextViewCopiedText(TextView view); + + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_copiedCellsList")] + private static extern ref List> TextViewCopiedLines(TextView view); + + /// + /// Makes TextView paste the text pasted. It keeps the lines it copied, to insert them in place of a pasted text equal to + /// the copied one, though they are lines of the text itself (a copy without a selection keeps the line it is on): the + /// pasted lines would then be the same lines, which change together, or a line edited or emptied since. + /// + private void ForgetCopiedLines() + { + try + { + TextViewCopiedText(this) = null; + TextViewCopiedLines(this) = []; + } + catch (MissingFieldException) + { + } + } + + /// + protected override bool OnPaste(string text) + { + ForgetCopiedLines(); + return base.OnPaste(WithoutLoneSurrogates(text)); + } + + /// Runs with the selection ended first, unless the text can't change. + private bool EndingTheSelection(Func edit) + { + if (!ReadOnly) + { + IsSelecting = false; + } + + return edit(); + } + + /// + /// TextView's completions (TermRest has none). TextView offers them each mouse event right after it measured the + /// selected text, which hides from that measure: this shows it again. + /// + private sealed class Completions(TextArea area) : TextViewAutocomplete + { + /// + /// A key no input produces. TextView takes this key to reopen completions (by default Shift+Space, which would then + /// type no space); keys compare by key code alone, so would also take text that comes with no + /// key (from an IME, or as a kitty terminal's CSI 0;;text u). + /// + public override Key Reopen { get; set; } = new(KeyCode.SpecialMask); + + public override bool OnMouseEvent(Mouse mouse, bool fromHost = false) + { + area.ShowHiddenSelection(); + return base.OnMouseEvent(mouse, fromHost); + } } - /// Raised after the user edits the text (not for programmatic ). - public event EventHandler? UserEdited; + /// Raised with the new text after the user changed it (not for programmatic ). + public event EventHandler? UserEdited + { + add + { + _text ??= GetText(); + _userEdited += value; + } + remove => _userEdited -= value; + } + + private EventHandler? _userEdited; private bool _settingText; + private bool _contentsChanged; + + /// Whether hid the selection, until TextView measured it. + private bool _selectionHidden; + + /// The text as last set or reported by ; kept only while something listens. + private string? _text; /// The script language () whose syntax is colored; null for plain text. public string? SyntaxLanguage @@ -66,9 +185,11 @@ public void SetText(string text) _settingText = true; try { - Text = text.Replace("\r\n", "\n", StringComparison.Ordinal); - InsertionPoint = System.Drawing.Point.Empty; - ClearHistoryChanges(); + // Every line break becomes LF, as when pasted: Terminal.Gui would drop the character before the next LF from a + // line with a lone CR. Setting the text also moves the cursor to the start and clears the undo history. + var normalized = WithoutLoneSurrogates(text.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n')); + Text = normalized; + _text = _userEdited is null ? null : AsHeld(normalized); } finally { @@ -76,14 +197,296 @@ public void SetText(string text) } } + /// + /// , just set, as the editor holds it: Terminal.Gui keeps each character composed (NFC), so a + /// decomposed é (as macOS file names have it) or the ohm sign comes back changed. Read back only when it can be. + /// + private string AsHeld(string text) + { + try + { + if (text.IsNormalized()) + { + return text; + } + } + catch (ArgumentException) + { + // Normalizing refuses some characters (U+FFFE): Terminal.Gui keeps those as they are, and composes the rest. + } + + return GetText(); + } + + /// + /// with U+FFFD in place of each half of a surrogate pair found alone (as a cut by UTF-16 index + /// leaves one), which Terminal.Gui fails on when it loads the text; typing inserts U+FFFD for one too. Copies the text + /// only when it holds one. + /// + private static string WithoutLoneSurrogates(string text) + { + var span = text.AsSpan(); + var at = span.IndexOfAnyInRange('\uD800', '\uDFFF'); + while (at >= 0 && char.IsHighSurrogate(span[at]) && at + 1 < span.Length && char.IsLowSurrogate(span[at + 1])) + { + var next = span[(at + 2)..].IndexOfAnyInRange('\uD800', '\uDFFF'); + at = next < 0 ? -1 : at + 2 + next; + } + + return at < 0 ? text : string.Create(text.Length, (Text: text, First: at), static (chars, state) => + { + state.Text.CopyTo(chars); + for (var i = state.First; i < chars.Length; i++) + { + if (char.IsHighSurrogate(chars[i]) && i + 1 < chars.Length && char.IsLowSurrogate(chars[i + 1])) + { + i++; + } + else if (char.IsSurrogate(chars[i])) + { + chars[i] = '\uFFFD'; + } + } + }); + } + public override void OnContentsChanged() { _linesLexed = 0; + _contentsChanged = true; base.OnContentsChanged(); - if (!_settingText) + if (_settingText || _userEdited is not { } edited) + { + return; + } + + // Terminal.Gui also reports keys that change nothing (Backspace at the start, Delete at the end…). + var text = GetText(); + if (text != _text) + { + _text = text; + edited(this, text); + } + } + + /// + /// + /// Terminal.Gui 2.5 deletes words (Ctrl+Backspace, Ctrl+Delete) and cuts to the start or end of a line + /// (Ctrl+Shift+Backspace, Ctrl+K) without , so their keys run those commands here and + /// report the change. + /// + protected override bool OnKeyDown(Key key) + { + // TextView first offers each key to autocomplete, after measuring the selected text (which it builds anew: seconds + // for a large selection). There is nothing to offer unless suggestions were generated, and TermRest has none. + if (Autocomplete.Suggestions.Count > 0 && base.OnKeyDown(key)) + { + return true; + } + + if (ReadOnly || !KeyBindings.TryGet(key, out var binding) + || !binding.Commands.Any(c => c is Command.KillWordLeft or Command.KillWordRight or Command.CutToStartOfLine or Command.CutToEndOfLine)) + { + return false; + } + + // They only delete: the text changed when it has fewer characters or lines. A selection ends first, as TextView ends it + // for Ctrl+Delete: it would stay on, its start past what is left of the text, and the next key would fail on it. + var size = (Lines, GetAllLines().Sum(line => line.Count)); + _contentsChanged = false; + IsSelecting = false; + InvokeCommands(binding.Commands, binding); + if (!_contentsChanged && (Lines, GetAllLines().Sum(line => line.Count)) != size) + { + OnContentsChanged(); + } + + return true; + } + + /// + /// + /// TextView measures the selected text (building it anew: seconds for a large selection) before it looks at a mouse + /// event, to offer the event to its completions when nothing is selected. The selection is hidden from that measure: + /// the completions show it again, before TextView handles the event. + /// + protected override bool OnMouseEvent(Mouse mouse) + { + if (!IsSelecting) + { + return base.OnMouseEvent(mouse); + } + + _selectionHidden = true; + IsSelecting = false; + try + { + return base.OnMouseEvent(mouse); + } + finally + { + ShowHiddenSelection(); + } + } + + private void ShowHiddenSelection() + { + if (_selectionHidden) + { + _selectionHidden = false; + IsSelecting = true; + } + } + + /// + /// Copies or cuts the selection as TextView does. Without one, TextView's copy takes the current line, and a cut does + /// nothing (TextView's would take the text from where the last selection started, or from the start, to the cursor); + /// in an editor whose words wrap, TextView's own cut and copy also keep its undo history and wrapping right. + /// + private bool CopySelection(bool cut) + { + // TextView's copy and cut also forget the column that Up and Down keep the cursor in; its handling of a key that + // nothing took does only that for a Ctrl key. + base.OnKeyDownNotHandled(Key.C.WithCtrl); + if (cut && !IsSelecting) + { + return true; + } + + if (!IsSelecting || (WordWrap && !ReadOnly) || SelectionText() is not { } text) + { + var done = cut ? Cut() : Copy(); + ForgetCopiedLines(); // they would keep the text's lines in memory too + return done; + } + + // On the clipboard first, as TextView does: a cut that can't get there leaves the text as it was. + App?.Clipboard?.SetClipboardData(text); + if (cut && !ReadOnly) + { + // Deleted as Backspace deletes a selection, from its start: undoing it then puts the cursor back there, as after + // TextView's cut, which also leaves the selection's start there. + var forward = Encode(SelectionStartRow, SelectionStartColumn) < Encode(CurrentRow, CurrentColumn); + if (forward) + { + var (start, viewport) = (new Point(SelectionStartColumn, SelectionStartRow), Viewport); + SetSelectionStart(CurrentRow, CurrentColumn); + InsertionPoint = start; + Viewport = viewport; + } + + DeleteCharLeft(); + if (forward) + { + SetSelectionStart(CurrentRow, CurrentColumn); + IsSelecting = false; + } + } + else if (!ReadOnly) + { + // TextView's copy notes that a selection was copied (a paste then goes in at the cursor, not as a line above + // it) and scrolls to the cursor: it does that at no cost for an empty selection, here kept off the clipboard. + var (row, column) = (SelectionStartRow, SelectionStartColumn); + var driver = App?.Driver; + var clipboard = driver?.Clipboard; + SetSelectionStart(CurrentRow, CurrentColumn); + try + { + driver?.Clipboard = null; + Copy(); + } + finally + { + driver?.Clipboard = clipboard; + SetSelectionStart(row, column); + } + } + else + { + // Read-only: TextView's cut only copies, and ends the selection. Its copy scrolls to the cursor, and so does its + // cut when words wrap (it wraps them again). + IsSelecting = !cut; + SetNeedsDraw(); + if (!cut || WordWrap) + { + InsertionPoint = new Point(CurrentColumn, CurrentRow); + } + } + + ForgetCopiedLines(); + return true; + } + + /// Moves the selection's start, without the scrolling to the cursor that TextView does then. + private void SetSelectionStart(int row, int column) + { + var viewport = Viewport; + SelectionStartRow = row; + SelectionStartColumn = column; + Viewport = viewport; + } + + /// + /// The selected text as TextView's copy makes it: lines joined with . When words wrap, + /// rows are parts of lines; null if they do not add up to the text. + /// + private string? SelectionText() + { + var (anchor, cursor) = (Encode(SelectionStartRow, SelectionStartColumn), Encode(CurrentRow, CurrentColumn)); + var (start, end) = anchor > cursor ? (cursor, anchor) : (anchor, cursor); + var (firstRow, firstColumn, lastRow, lastColumn) = ((int)(start >> 32), (int)(uint)start, (int)(end >> 32), (int)(uint)end); + var selected = new StringBuilder(); + if (!WordWrap) { - UserEdited?.Invoke(this, EventArgs.Empty); + for (var row = firstRow; row <= lastRow; row++) + { + var line = GetLine(row); + if (row > firstRow) + { + selected.Append(Environment.NewLine); + } + + for (var i = row == firstRow ? firstColumn : 0; i < (row == lastRow ? lastColumn : line.Count); i++) + { + selected.Append(line[i].Grapheme); + } + } + + return selected.ToString(); } + + // The line breaks are where the whole text (TextView's Text, unwrapped) has them. + var text = Text; + var at = 0; + for (var row = 0; row <= lastRow; row++) + { + if (row > 0 && text.AsSpan(at).StartsWith(Environment.NewLine, StringComparison.Ordinal)) + { + at += Environment.NewLine.Length; + if (row > firstRow) + { + selected.Append(Environment.NewLine); + } + } + + var line = GetLine(row); + for (var i = 0; i < (row == lastRow ? lastColumn : line.Count); i++) + { + var grapheme = line[i].Grapheme; + if (!text.AsSpan(at).StartsWith(grapheme, StringComparison.Ordinal)) + { + return null; + } + + at += grapheme.Length; + if (row > firstRow || (row == firstRow && i >= firstColumn)) + { + selected.Append(grapheme); + } + } + } + + return selected.ToString(); } /// Text with the editor's line endings normalized to LF. @@ -100,34 +503,217 @@ protected override void OnTextChanged() base.OnTextChanged(); } + /// + /// + /// Draws as does (the same cells, colors and clearing), but only the rows in view: Terminal.Gui + /// 2.5 goes through every line from the top of the view to the end of the text, which takes seconds for a large + /// response. Its colors are set here, not by the OnDraw*Color methods, which look up each cell's place in the + /// unwrapped text when words wrap; the Draw*Color events are not raised. + /// protected override bool OnDrawingContent(DrawContext? context) { - if (Highlighting) + var colors = new CellColors + { + Editable = GetAttributeForRole(VisualRole.Editable), + ReadOnly = GetAttributeForRole(VisualRole.ReadOnly), + Selected = GetAttributeForRole(VisualRole.Active), + Focus = GetAttributeForRole(VisualRole.Focus), + Highlighting = Highlighting, + }; + if (colors.Highlighting) { LexLinesInView(); - var editable = GetAttributeForRole(VisualRole.Editable); var palette = ThemeCatalog.Current.Palette; for (var kind = 0; kind < _syntaxAttributes.Length; kind++) { var color = palette.SyntaxColor((SyntaxKind)kind); var readable = !color.Equals(Color.None) - && (editable.Background.Equals(Color.None) || ThemePalette.Contrast(color, editable.Background) >= MinimumContrast); - _syntaxAttributes[kind] = new Attribute(readable ? color : editable.Foreground, editable.Background, editable.Style); + && (colors.Editable.Background.Equals(Color.None) || ThemePalette.Contrast(color, colors.Editable.Background) >= MinimumContrast); + _syntaxAttributes[kind] = new Attribute(readable ? color : colors.Editable.Foreground, colors.Editable.Background, colors.Editable.Style); } } - return base.OnDrawingContent(context); + if (IsSelecting) + { + var anchor = Encode(SelectionStartRow, SelectionStartColumn); + var cursor = Encode(CurrentRow, CurrentColumn); + (colors.SelectionStart, colors.SelectionEnd) = anchor > cursor ? (cursor, anchor) : (anchor, cursor); + } + + colors.UsedRow = !IsSelecting && !Used && HasFocus ? CurrentRow : -1; + SetAttributeForRole(Enabled ? VisualRole.Editable : VisualRole.Disabled); + var viewport = Viewport; + var row = 0; + for (var index = viewport.Y; index < Lines && row < viewport.Height; index++, row++) + { + DrawLine(GetLine(index), index, row, viewport, colors); + } + + if (row < viewport.Height) + { + SetAttributeForRole(ReadOnly ? VisualRole.ReadOnly : VisualRole.Editable); + ClearCells(0, row, viewport.Width, viewport.Height); + } + + return false; } - protected override void OnDrawNormalColor(List line, int idxCol, int idxRow) + /// The colors of a redraw (they do not change while it draws). + private struct CellColors { - if (Highlighting && idxRow < _linesLexed && idxCol < _lineKinds[idxRow].Length) + public Attribute Editable; + public Attribute ReadOnly; + public Attribute Selected; + public Attribute Focus; + public bool Highlighting; + public long SelectionStart; + public long SelectionEnd; + public int UsedRow; + } + + /// A position as compares them: the row in the high half, the column in the low one. + private static long Encode(int row, int column) => ((long)(uint)row << 32) | (uint)column; + + /// Draws line on of the view, as does. + private void DrawLine(List line, int index, int row, Rectangle viewport, in CellColors colors) + { + var right = viewport.Width; + var count = line.Count; + + // Where the view's left edge cuts the line: TextView takes the widths of the first Viewport.X cells (cells, not + // columns) and starts with the cell that goes past it, at a negative column when it is cut. + var (col, start, before) = (0, 0, 0); + if (viewport.X > 0 && count > 0) { - SetAttribute(_syntaxAttributes[(int)_lineKinds[idxRow][idxCol]]); - return; + var cells = Math.Min(viewport.X, count); + var (sum, previous) = (0, 0); + (col, start, before) = (int.MinValue, cells, 0); + for (var i = 0; i < cells; i++) + { + var grapheme = line[i].Grapheme; + sum += grapheme == "\t" ? (TabWidth > 0 ? TabWidth - (sum % TabWidth) : 0) : Math.Max(grapheme.GetColumns(), 1); + if (sum > viewport.X) + { + (col, start, before) = (previous - viewport.X, i, previous); + break; + } + + previous = sum; + } + + if (col == int.MinValue) + { + (col, before) = (sum - viewport.X, sum); + } } - base.OnDrawNormalColor(line, idxCol, idxRow); + var wideCutOnTheLeft = false; + Move(0, row); + for (var i = start; i < count; i++) + { + var text = line[i].Grapheme; + var cols = text.GetColumns(false); + SetCellColor(line[i], i, index, colors); + if (text == "\t") + { + cols = TabWidth > 0 ? TabWidth - (before % TabWidth) : 0; + if (col + cols > right) + { + cols = right - col; + } + + for (var k = 0; k < cols; k++) + { + if (col + k < right) + { + AddRune(col + k, row, (Rune)' '); + } + } + } + else + { + if (col < 0 && cols > 1) + { + wideCutOnTheLeft = true; + } + else + { + AddStr(col, row, text); + } + + cols = Math.Max(cols, 1); + } + + if (col + cols > viewport.Right) + { + break; + } + + col += cols; + before += cols; + if (i + 1 < count && col + line[i + 1].Grapheme.GetColumns() > right) + { + break; + } + } + + if (wideCutOnTheLeft) + { + AddStr(0, row, " "); + } + + if (col < right) + { + // From the left edge only: the columns left of it are clipped, and a short line ends as far left of it as the view + // is scrolled right (to the end of a long line, maybe a million columns), each a step. + SetAttributeForRole(ReadOnly ? VisualRole.ReadOnly : VisualRole.Editable); + ClearCells(Math.Max(col, 0), row, right, row + 1); + } + } + + /// + /// The color of a cell, chosen as TextView's OnDraw*Color methods do: selected, overwrite cursor, read-only, script + /// colors, normal. + /// + private void SetCellColor(Cell cell, int column, int index, in CellColors colors) + { + if (IsSelecting && Encode(index, column) is var position && position >= colors.SelectionStart && position <= colors.SelectionEnd - 1) + { + var selected = colors.Selected; + SetAttribute(cell.Attribute is { } own ? new Attribute(selected.Foreground, selected.Background, own.Style) : selected); + } + else if (index == colors.UsedRow && column == CurrentColumn) + { + var used = cell.Attribute ?? colors.Focus; + SetAttribute(new Attribute(used.Background, used.Foreground, used.Style)); + } + else if (ReadOnly) + { + var readOnly = cell.Attribute ?? colors.ReadOnly; + SetAttribute(readOnly.Foreground == readOnly.Background + ? new Attribute(readOnly.Foreground, readOnly.Background, readOnly.Style) + : colors.ReadOnly); + } + else if (colors.Highlighting && index < _linesLexed && column < _lineKinds[index].Length) + { + SetAttribute(_syntaxAttributes[(int)_lineKinds[index][column]]); + } + else + { + SetAttribute(cell.Attribute ?? colors.Editable); + } + } + + private void ClearCells(int left, int top, int right, int bottom) + { + for (var row = top; row < bottom; row++) + { + Move(left, row); + for (var col = left; col < right; col++) + { + AddRune(col, row, (Rune)' '); + } + } } /// Colors the lines not colored yet down to the last one in view (a line's colors depend on the lines above it). diff --git a/tests/TermRest.Cli.Tests/CommandLineTests.cs b/tests/TermRest.Cli.Tests/CommandLineTests.cs new file mode 100644 index 0000000..0af3f4f --- /dev/null +++ b/tests/TermRest.Cli.Tests/CommandLineTests.cs @@ -0,0 +1,1080 @@ +using System.Diagnostics; +using System.Globalization; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Text; +using System.Text.Json.Nodes; +using TermRest.Cli.Tests.Infrastructure; +using TermRest.Core.History; +using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Workspace; +using Xunit; + +namespace TermRest.Cli.Tests; + +/// The termrest commands as scripts and CI use them: exit codes, standard output, and the files they write. +public sealed class CommandLineTests +{ + private const string Schema = "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"; + + /// Writes a v2.1 JSON collection of simple requests (name, method, URL) and returns its path. + private static string WriteCollection(string directory, string name, IEnumerable<(string Name, string Method, string Url)> requests, JsonObject? auth = null) + { + var collection = new JsonObject + { + ["info"] = new JsonObject { ["name"] = name, ["schema"] = Schema }, + ["item"] = new JsonArray([.. requests.Select(r => (JsonNode)new JsonObject { ["name"] = r.Name, ["request"] = new JsonObject { ["method"] = r.Method, ["url"] = r.Url } })]), + }; + if (auth is not null) + { + collection["auth"] = auth; + } + + var path = Path.Combine(directory, name + ".postman_collection.json"); + File.WriteAllText(path, collection.ToJsonString()); + return path; + } + + /// Writes files (relative path, content) under . + private static void WriteFiles(string directory, params (string Path, string Content)[] files) + { + foreach (var (path, content) in files) + { + var full = Path.Combine(directory, path.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(full)!); + File.WriteAllText(full, content); + } + } + + private static string HttpRequestYaml(string url) => $"$kind: http-request\nurl: {url}\nmethod: GET\n"; + + /// Denies or allows reading a file to the user who runs the tests. + private static void SetReadable(string path, bool readable) + { + if (OperatingSystem.IsWindows()) + { + var file = new FileInfo(path); + var security = file.GetAccessControl(); + var rule = new FileSystemAccessRule(WindowsIdentity.GetCurrent().User!, FileSystemRights.ReadData, AccessControlType.Deny); + if (readable) + { + security.RemoveAccessRule(rule); + } + else + { + security.AddAccessRule(rule); + } + + file.SetAccessControl(security); + } + else + { + File.SetUnixFileMode(path, readable ? UnixFileMode.UserRead | UnixFileMode.UserWrite : UnixFileMode.None); + } + } + + [Fact] + public async Task Send_curl_prints_no_command_for_a_request_that_cannot_be_sent() + { + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Bad", "GET;CALC", "https://h/x"), ("Good", "GET", "https://h/x")]); + + var bad = await Termrest.RunAsync(["send", collection, "Bad", "--curl"]); + var good = await Termrest.RunAsync(["send", collection, "Good", "--curl"]); + + Assert.True(bad.ExitCode == 2, bad.ToString()); + Assert.Empty(bad.Output); + Assert.Contains("'GET;CALC' is not a valid HTTP method", bad.Error, StringComparison.Ordinal); + Assert.True(good.ExitCode == 0, good.ToString()); + Assert.StartsWith("curl", good.Text, StringComparison.Ordinal); + } + + [Fact] + public async Task Run_and_send_fail_when_files_of_the_collection_cannot_be_read() + { + await using var server = await TestServer.StartAsync(); + var root = TestFiles.NewTempDirectory(); + WriteFiles(root, + ("postman/collections/Api/.resources/definition.yaml", "<<<<<<< HEAD\n$kind: collection\n=======\n$kind: collection\ndescription: theirs\n>>>>>>> theirs\n"), + ("postman/collections/Api/Ping.request.yaml", HttpRequestYaml(server.BaseUrl + "/echo/ping")), + ("postman/collections/Sockets/.resources/definition.yaml", "$kind: collection\n"), + ("postman/collections/Sockets/Stream.request.yaml", "$kind: websocket-request\nurl: wss://h/stream\n"), + ("postman/collections/Named/Ping.request.yaml", HttpRequestYaml(server.BaseUrl + "/echo/ping")), + ("postman/collections/Named/non-HTTP.request.yaml", "<<<<<<< HEAD\n$kind: http-request\n=======\n$kind: http-request\nurl: https://h/theirs\n>>>>>>> theirs\n")); + var broken = Path.Combine(root, "postman", "collections", "Api"); + + var run = await Termrest.RunAsync(["run", broken]); + var send = await Termrest.RunAsync(["send", broken, "Ping"]); + var hiddenRequestsOnly = await Termrest.RunAsync(["run", Path.Combine(root, "postman", "collections", "Sockets")]); + var namedLikeTheNote = await Termrest.RunAsync(["run", Path.Combine(root, "postman", "collections", "Named")]); + + // The request itself passes, but the collection's definition (its auth and scripts) was not read. + Assert.True(run.ExitCode == 1, run.ToString()); + Assert.Contains("1 passed, 0 failed", run.Error, StringComparison.Ordinal); + Assert.Contains("definition.yaml", run.Error, StringComparison.Ordinal); + Assert.True(send.ExitCode == 1, send.ToString()); + Assert.Contains("/echo/ping", send.Text, StringComparison.Ordinal); + Assert.True(hiddenRequestsOnly.ExitCode == 0, hiddenRequestsOnly.ToString()); + + // A file whose name holds "non-HTTP" is no note about hidden requests. + Assert.True(namedLikeTheNote.ExitCode == 1, namedLikeTheNote.ToString()); + Assert.Contains("non-HTTP.request.yaml", namedLikeTheNote.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task Themes_use_never_saves_over_settings_it_cannot_read() + { + var config = TestFiles.NewTempDirectory(); + const string user = "{ \"theme\": \"Dracula\", \"pythonInterpreters\": { \"C:\\work\": \"C:\\Python312\\python.exe\" } }"; + File.WriteAllText(Path.Combine(config, "settings.json"), user); + var workspace = TestFiles.NewTempDirectory(); + const string shared = "{\n<<<<<<< HEAD\n \"activeEnvironment\": \"dev\",\n=======\n \"activeEnvironment\": \"prod\",\n>>>>>>> theirs\n \"proxy\": \"http://proxy:8080\"\n}\n"; + WriteFiles(workspace, (".termrest/settings.json", shared)); + var environment = new Dictionary { ["TERMREST_CONFIG_DIR"] = config }; + + var forUser = await Termrest.RunAsync(["themes", "use", "Nord", "-w", workspace], environment); + var forWorkspace = await Termrest.RunAsync(["themes", "use", "Nord", "--only-here", "-w", workspace], environment); + var listed = await Termrest.RunAsync(["themes", "-w", workspace], environment); + + Assert.True(forUser.ExitCode == 1, forUser.ToString()); + Assert.StartsWith("error: " + Path.Combine(config, "settings.json"), forUser.Error, StringComparison.Ordinal); + Assert.Equal(user, File.ReadAllText(Path.Combine(config, "settings.json"))); + Assert.True(forWorkspace.ExitCode == 1, forWorkspace.ToString()); + Assert.StartsWith("error: " + Path.Combine(workspace, ".termrest", "settings.json"), forWorkspace.Error, StringComparison.Ordinal); + Assert.Equal(shared, File.ReadAllText(Path.Combine(workspace, ".termrest", "settings.json"))); + Assert.StartsWith("warning: " + Path.Combine(config, "settings.json"), listed.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task Certificate_commands_fail_when_the_registry_cannot_be_read() + { + var workspace = TestFiles.NewTempDirectory(); + WriteFiles(workspace, (".termrest/certificates.json", "[\n<<<<<<< HEAD\n { \"name\": \"dev\", \"matches\": [\"https://h/*\"] }\n=======\n]\n")); + + var list = await Termrest.RunAsync(["certs", "list", workspace]); + var match = await Termrest.RunAsync(["certs", "match", "https://h/x", workspace]); + + Assert.True(list.ExitCode == 1, list.ToString()); + Assert.Contains("certificates.json", list.Error, StringComparison.Ordinal); + Assert.DoesNotContain("No certificates registered", list.Error, StringComparison.Ordinal); + Assert.True(match.ExitCode == 1, match.ToString()); + Assert.Contains("certificates.json", match.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task Run_report_masks_secrets_and_is_private() + { + await using var server = await TestServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + var uri = new Uri(server.BaseUrl); + var auth = JsonNode.Parse("""{ "type": "apikey", "apikey": [ { "key": "key", "value": "X-Key" }, { "key": "value", "value": "{{apiKey}}" }, { "key": "in", "value": "query" } ] }""")!.AsObject(); + var collection = WriteCollection(directory, "Api", + [ + ("Ping", "GET", $"http://ada:pa55-w0rd@{uri.Authority}/echo/ping?token={{{{token}}}}"), + ("Broken", "GET", "ftp://h/{{apiKey}}"), + ("No port", "GET", $"http://ada:pw12@{uri.Host}:{{{{port}}}}/echo/ping"), // not valid ({{port}} is unset), so its short password is no known secret + ], auth); + var environment = Path.Combine(directory, "ci.postman_environment.json"); + File.WriteAllText(environment, """ + { "name": "ci", "values": [ + { "key": "apiKey", "value": "sk-live-0123456789", "type": "secret", "enabled": true }, + { "key": "token", "value": "tok-abcdef-98765", "type": "default", "enabled": true } ] } + """); + var report = Path.Combine(directory, "report.json"); + + var run = await Termrest.RunAsync(["run", collection, "-e", environment, "--report-json", report]); + + Assert.True(run.ExitCode == 1, run.ToString()); // Broken is not sent + var text = File.ReadAllText(report); + Assert.Contains("[REDACTED]", text, StringComparison.Ordinal); + Assert.DoesNotContain("sk-live-0123456789", text, StringComparison.Ordinal); + Assert.DoesNotContain("tok-abcdef-98765", text, StringComparison.Ordinal); + Assert.DoesNotContain("pa55-w0rd", text, StringComparison.Ordinal); + Assert.DoesNotContain("pw12", text, StringComparison.Ordinal); + Assert.Contains("is not a valid http(s) URL", text, StringComparison.Ordinal); + if (!OperatingSystem.IsWindows()) + { + Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(report)); + } + } + + [Fact] + public async Task Run_report_redacts_tests_as_the_recording_does() + { + var javaScript = TestJavaScript.Require(); + await using var server = await TestServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + var collection = Path.Combine(directory, "Api.postman_collection.json"); + File.WriteAllText(collection, $$""" + { "info": { "name": "Api", "schema": "{{Schema}}" }, "item": [ + { "name": "Login", "request": { "method": "GET", "url": "{{server.BaseUrl}}/token" }, + "event": [ { "listen": "test", "script": { "type": "text/javascript", "exec": [ + "pm.test('key ' + pm.environment.get('apiKey') + ' ok', () => {});", + "pm.test('token', () => pm.expect(pm.response.json().access_token).to.have.lengthOf(32));" ] } } ] } ] } + """); + var environment = Path.Combine(directory, "ci.postman_environment.json"); + File.WriteAllText(environment, """{ "name": "ci", "values": [ { "key": "apiKey", "value": "sk-live-0123456789", "type": "secret", "enabled": true } ] }"""); + var report = Path.Combine(directory, "report.json"); + var har = Path.Combine(directory, "run.har"); + + var run = await Termrest.RunAsync(["run", collection, "-e", environment, "--javascript", javaScript, "--report-json", report, "--record", har]); + + Assert.True(run.ExitCode == 1, run.ToString()); // the token test fails + var tests = JsonNode.Parse(File.ReadAllText(report))!["results"]![0]!["tests"]!; + var recorded = JsonNode.Parse(File.ReadAllText(har))!["log"]!["entries"]![0]!["_termrest"]!["scripts"]!["tests"]!; + Assert.Equal("key [REDACTED] ok", (string?)tests[0]!["name"]); + + // The token is in no variable: it is redacted because the response has it in a field named like a secret. + Assert.Equal("expected '[REDACTED]' to have a length of 32 but got 40", (string?)tests[1]!["error"]); + Assert.Equal((string?)recorded[0]!["name"], (string?)tests[0]!["name"]); + Assert.Equal((string?)recorded[1]!["error"], (string?)tests[1]!["error"]); + } + + [Fact] + public async Task The_password_of_the_system_proxy_is_masked_in_the_error_of_a_tunnel_it_refused() + { + var ct = TestContext.Current.CancellationToken; + using var proxy = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0); + proxy.Start(); + var url = $"http://ada:P%C3%A4ss%20wort@127.0.0.1:{((System.Net.IPEndPoint)proxy.LocalEndpoint).Port}"; + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Secure", "GET", "https://api.example.com/x")]); + + // The system proxy comes from HTTPS_PROXY here; .NET's error names it unescaped ("Päss wort"). + var sending = Termrest.RunAsync(["send", collection, "Secure"], new Dictionary + { + ["HTTPS_PROXY"] = url, + ["https_proxy"] = url, + ["NO_PROXY"] = "", + ["no_proxy"] = "", + }); + var accepting = proxy.AcceptTcpClientAsync(ct).AsTask(); + if (await Task.WhenAny(accepting, sending) == sending) + { + Assert.Fail($"The request did not go through the proxy: {await sending}"); + } + + using (var connection = await accepting) + { + var stream = connection.GetStream(); + var request = new byte[16384]; + var read = 0; + while (request.AsSpan(0, read).IndexOf("\r\n\r\n"u8) < 0 && await stream.ReadAsync(request.AsMemory(read), ct) is > 0 and var count) + { + read += count; + } + + await stream.WriteAsync("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"u8.ToArray(), ct); + } + + var send = await sending; + Assert.True(send.ExitCode == 1, send.ToString()); + Assert.Contains("'http://ada:***@127.0.0.1:", send.Error, StringComparison.Ordinal); + Assert.DoesNotContain("wort", send.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task A_runtime_path_is_relative_to_the_current_folder_as_the_other_paths_are() + { + var javaScript = TestJavaScript.Require(); + await using var server = await TestServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + var runtime = OperatingSystem.IsWindows() ? "tools/js.cmd" : "tools/js"; // the repository's own, as a .venv's python is + WriteFiles(directory, + ("postman/Api.postman_collection.json", $$""" + { "info": { "name": "Api", "schema": "{{Schema}}" }, "item": [ + { "name": "Ping", "request": { "method": "GET", "url": "{{server.BaseUrl}}/echo/ping" }, + "event": [ { "listen": "test", "script": { "type": "text/javascript", "exec": [ "pm.test('ran', () => {});" ] } } ] } ] } + """), + (runtime, OperatingSystem.IsWindows() ? $"@\"{javaScript}\" %*\r\n" : $"#!/bin/sh\nexec \"{javaScript}\" \"$@\"\n")); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(Path.Combine(directory, runtime), UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + + // Not relative to the collection's folder (the workspace). + var run = await Termrest.RunAsync(["run", "postman/Api.postman_collection.json", "--javascript", runtime], workingDirectory: directory); + + Assert.True(run.ExitCode == 0, run.ToString()); + Assert.Contains("✓ ran", run.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task Run_does_not_keep_the_responses_it_has_counted() + { + await using var server = await TestServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + var collection = WriteCollection(directory, "Exports", Enumerable.Range(1, 80).Select(i => ($"Export {i}", "GET", server.BaseUrl + "/large"))); + var report = Path.Combine(directory, "report.json"); + + // 80 responses of 1.5 MB (120 MB in all), with a heap of at most 64 MB. + var run = await Termrest.RunAsync(["run", collection, "--report-json", report], new Dictionary { ["DOTNET_GCHeapHardLimit"] = "0x4000000" }); + + Assert.True(run.ExitCode == 0, run.ToString()); + Assert.Contains("80 passed, 0 failed", run.Error, StringComparison.Ordinal); + Assert.Equal(80, JsonNode.Parse(File.ReadAllText(report))!["results"]!.AsArray().Count); + } + + [Fact] + public async Task Run_creates_the_folder_of_the_report_and_reports_a_report_it_cannot_write() + { + await using var server = await TestServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + var collection = WriteCollection(directory, "Api", [("Ping", "GET", server.BaseUrl + "/echo/ping")]); + var report = Path.Combine(directory, "out", "report.json"); + var blocked = Path.Combine(collection, "report.json"); // in a "folder" that is a file + + var written = await Termrest.RunAsync(["run", collection, "--report-json", report]); + var notWritten = await Termrest.RunAsync(["run", collection, "--report-json", blocked]); + + Assert.True(written.ExitCode == 0, written.ToString()); + Assert.Equal("Api", (string?)JsonNode.Parse(File.ReadAllText(report))!["collection"]); + Assert.True(notWritten.ExitCode == 1, notWritten.ToString()); + Assert.Contains("1 passed, 0 failed", notWritten.Error, StringComparison.Ordinal); + Assert.Contains("error: The report could not be written to " + blocked, notWritten.Error, StringComparison.Ordinal); + Assert.DoesNotContain("Unhandled exception", notWritten.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task A_cancelled_run_still_saves_its_recording_and_report_however_long_that_takes() + { + if (OperatingSystem.IsWindows()) + { + Assert.Skip("Signals a process, as a cancelled CI job does: Unix only (Ctrl+C needs a console on Windows)."); + } + + await using var server = await TestServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + var collection = WriteCollection(directory, "Api", [("Ping", "GET", server.BaseUrl + "/echo/ping"), ("Slow", "GET", server.BaseUrl + "/wait")]); + var har = Path.Combine(directory, "run.har"); + var report = Path.Combine(directory, "report.json"); + using (var mkfifo = Process.Start("mkfifo", [report])!) + { + await mkfifo.WaitForExitAsync(TestContext.Current.CancellationToken); // writing the report waits until it is read + } + + var written = ""; + var run = await Termrest.RunAsync(["run", collection, "--record", har, "--report-json", report], whileRunning: async process => + { + await server.Waiting.WaitAsync(TimeSpan.FromMinutes(1), TestContext.Current.CancellationToken); + using (var kill = Process.Start("kill", ["-TERM", process.Id.ToString(CultureInfo.InvariantCulture)])!) + { + await kill.WaitForExitAsync(TestContext.Current.CancellationToken); + } + + // Longer than System.CommandLine waits for a command after a signal before it ends the process. + await Task.Delay(TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken); + var reading = Task.Run(() => File.ReadAllText(report)); + if (await Task.WhenAny(reading, Task.Delay(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken)) != reading) + { + // Nothing writes it any more: this ends the reading (sharing the file, as the reader locks it too). + new FileStream(report, FileMode.Open, FileAccess.Write, FileShare.ReadWrite).Dispose(); + } + + written = await reading; + }); + + Assert.True(run.ExitCode == 130, run.ToString()); + Assert.Contains("Run cancelled. 1 passed, 0 failed, 1 skipped", run.Error, StringComparison.Ordinal); + Assert.Contains("Saving the recording to " + har, run.Error, StringComparison.Ordinal); + Assert.Contains("/echo/ping", File.ReadAllText(har), StringComparison.Ordinal); + Assert.True(written.Length > 0, run.ToString()); + Assert.Equal(1, (int?)JsonNode.Parse(written)!["passed"]); + } + + [Fact] + public async Task Run_says_a_folder_is_no_collection_only_when_it_is_none() + { + var root = TestFiles.NewTempDirectory(); + WriteFiles(root, ("postman/collections/Api/Ping.request.yaml", HttpRequestYaml("https://h/ping"))); + + var unknownEnvironment = await Termrest.RunAsync(["run", Path.Combine(root, "postman", "collections", "Api"), "-e", "staging"]); + var workspace = await Termrest.RunAsync(["run", root]); + + Assert.True(unknownEnvironment.ExitCode == 2, unknownEnvironment.ToString()); + Assert.Contains("Environment 'staging' was not found", unknownEnvironment.Error, StringComparison.Ordinal); + Assert.DoesNotContain("collection folder", unknownEnvironment.Error, StringComparison.Ordinal); + Assert.True(workspace.ExitCode == 2, workspace.ToString()); + Assert.Contains($"'{root}' is not a Postman v3 collection folder; pass the collection itself.", workspace.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task An_environment_name_that_several_environments_have_is_refused() + { + await using var server = await TestServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + var collection = WriteCollection(directory, "Api", [("Ping", "GET", server.BaseUrl + "/echo/{{from}}")]); + + // As "termrest convert dev.postman_environment.json" leaves them: both named "dev"; the YAML one is loaded first. + WriteFiles(directory, + ("dev.postman_environment.json", """{ "name": "dev", "values": [ { "key": "from", "value": "json", "enabled": true } ] }"""), + ("postman/environments/dev.environment.yaml", "name: dev\nvalues:\n - key: from\n value: yaml\n enabled: true\n"), + (".termrest/settings.json", """{ "activeEnvironment": "dev", "activeEnvironmentFile": "dev.postman_environment.json" }""")); + var yaml = Path.Combine(directory, "postman", "environments", "dev.environment.yaml"); + + var send = await Termrest.RunAsync(["send", collection, "Ping", "-e", "Dev", "--no-history"]); + var run = await Termrest.RunAsync(["run", collection, "-e", "dev"]); + var sent = server.Requests; + var byFile = await Termrest.RunAsync(["send", collection, "Ping", "-e", yaml, "--no-history"]); + var active = await Termrest.RunAsync(["send", collection, "Ping", "--no-history"]); + + Assert.True(send.ExitCode == 2, send.ToString()); + Assert.Contains("Environment 'Dev' is ambiguous", send.Error, StringComparison.Ordinal); + Assert.Contains(Path.Combine(directory, "dev.postman_environment.json"), send.Error, StringComparison.Ordinal); + Assert.Contains(yaml, send.Error, StringComparison.Ordinal); + Assert.True(run.ExitCode == 2, run.ToString()); + Assert.Equal(0, sent); + Assert.True(byFile.ExitCode == 0, byFile.ToString()); + Assert.Contains("/echo/yaml", byFile.Text, StringComparison.Ordinal); + + // Without -e: the active environment, by its file. + Assert.True(active.ExitCode == 0, active.ToString()); + Assert.Contains("/echo/json", active.Text, StringComparison.Ordinal); + } + + [Fact] + public async Task A_collection_folder_given_with_a_trailing_separator_is_the_one_used() + { + await using var server = await TestServer.StartAsync(); + var root = TestFiles.NewTempDirectory(); + WriteFiles(root, + ("postman/collections/A/Health.request.yaml", HttpRequestYaml(server.BaseUrl + "/echo/a")), + ("postman/collections/B/Health.request.yaml", HttpRequestYaml(server.BaseUrl + "/echo/b"))); + var b = Path.Combine(root, "postman", "collections", "B") + Path.DirectorySeparatorChar; + + var send = await Termrest.RunAsync(["send", b, "Health", "--no-history"]); + var run = await Termrest.RunAsync(["run", b]); + + Assert.True(send.ExitCode == 0, send.ToString()); + Assert.Contains("/echo/b", send.Text, StringComparison.Ordinal); + Assert.True(run.ExitCode == 0, run.ToString()); + Assert.Contains("1 passed", run.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task Import_curl_adds_only_to_the_collection_named() + { + var directory = TestFiles.NewTempDirectory(); + var good = WriteCollection(directory, "Good", [("Ping", "GET", "https://h/ping")]); + var broken = Path.Combine(directory, "Broken.postman_collection.json"); + File.WriteAllText(broken, "<<<<<<< HEAD\n{}\n"); + var before = File.ReadAllText(good); + + var intoBroken = await Termrest.RunAsync(["import-curl", broken, "curl https://h/new"]); + + Assert.True(intoBroken.ExitCode == 2, intoBroken.ToString()); + Assert.Contains("Broken.postman_collection.json", intoBroken.Error, StringComparison.Ordinal); + Assert.Equal(before, File.ReadAllText(good)); + + var intoGood = await Termrest.RunAsync(["import-curl", good, "curl https://h/new"]); + + Assert.True(intoGood.ExitCode == 0, intoGood.ToString()); + Assert.Contains("https://h/new", File.ReadAllText(good), StringComparison.Ordinal); + Assert.DoesNotContain("Broken", intoGood.Error, StringComparison.Ordinal); // the other collection is not even read + } + + [Fact] + public async Task An_environment_file_that_cannot_be_read_is_reported() + { + var directory = TestFiles.NewTempDirectory(); + var collection = WriteCollection(directory, "Api", [("Ping", "GET", "https://h/ping")]); + var environment = Path.Combine(directory, "ci.postman_environment.json"); + File.WriteAllBytes(environment, [0x7B, 0xFF, 0x7D]); // not UTF-8 + + var send = await Termrest.RunAsync(["send", collection, "Ping", "-e", environment, "--no-history"]); + + Assert.True(send.ExitCode == 2, send.ToString()); + Assert.Contains("ci.postman_environment.json", send.Error, StringComparison.Ordinal); + Assert.Contains("not UTF-8", send.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task Convert_keeps_private_files_private() + { + if (OperatingSystem.IsWindows()) + { + Assert.Skip("Unix file modes only."); + return; + } + + const UnixFileMode Private = UnixFileMode.UserRead | UnixFileMode.UserWrite; + var directory = TestFiles.NewTempDirectory(); + var environment = TestFiles.CopyToTemp(TestFiles.DemoEnvironment, directory); + var collection = TestFiles.CopyToTemp(TestFiles.DemoCollection, directory); + File.SetUnixFileMode(environment, Private); + File.SetUnixFileMode(collection, Private); + var yaml = Path.Combine(directory, "postman", "environments", "Postman Echo.environment.yaml"); + var json = Path.Combine(directory, "copy.postman_environment.json"); + var v3 = Path.Combine(directory, "v3"); + var v21 = Path.Combine(directory, "copy.postman_collection.json"); + + CommandResult[] results = + [ + await Termrest.RunAsync(["convert", environment]), + await Termrest.RunAsync(["convert", yaml, "-o", json]), + await Termrest.RunAsync(["convert", collection, "-o", v3]), + await Termrest.RunAsync(["convert", v3, "-o", v21]), + ]; + + Assert.All(results, r => Assert.True(r.ExitCode == 0, r.ToString())); + Assert.Equal(Private, File.GetUnixFileMode(yaml)); + Assert.Equal(Private, File.GetUnixFileMode(json)); + Assert.Equal(Private | UnixFileMode.UserExecute, File.GetUnixFileMode(v3)); // a folder needs x to be entered + foreach (var file in Directory.EnumerateFiles(v3, "*", SearchOption.AllDirectories)) + { + Assert.Equal(Private, File.GetUnixFileMode(file)); + } + + Assert.Equal(Private, File.GetUnixFileMode(v21)); + } + + [Fact] + public async Task Convert_writes_nothing_when_files_of_the_collection_cannot_be_read() + { + var root = TestFiles.NewTempDirectory(); + WriteFiles(root, + ("postman/collections/Api/.resources/definition.yaml", "<<<<<<< HEAD\n$kind: collection\n=======\n$kind: collection\ndescription: theirs\n>>>>>>> theirs\n"), + ("postman/collections/Api/Ping.request.yaml", HttpRequestYaml("https://h/ping")), + ("postman/collections/Sockets/Ping.request.yaml", HttpRequestYaml("https://h/ping")), + ("postman/collections/Sockets/Stream.request.yaml", "$kind: websocket-request\nurl: wss://h/stream\n"), + ("postman/collections/Named/Ping.request.yaml", HttpRequestYaml("https://h/ping")), + ("postman/collections/Named/non-HTTP.request.yaml", "<<<<<<< HEAD\n$kind: http-request\n=======\n$kind: http-request\nurl: https://h/theirs\n>>>>>>> theirs\n")); + var api = Path.Combine(root, "api.postman_collection.json"); + var sockets = Path.Combine(root, "sockets.postman_collection.json"); + var named = Path.Combine(root, "named.postman_collection.json"); + var namedFolder = Path.Combine(root, "postman", "collections", "Named"); + + var broken = await Termrest.RunAsync(["convert", Path.Combine(root, "postman", "collections", "Api"), "-o", api]); + var hiddenRequestsOnly = await Termrest.RunAsync(["convert", Path.Combine(root, "postman", "collections", "Sockets"), "-o", sockets]); + var namedLikeTheNote = await Termrest.RunAsync(["convert", namedFolder, "-o", named]); + var validated = await Termrest.RunAsync(["validate", namedFolder]); + + // The collection's definition (its auth, variables and scripts) was not read: converting it would lose them. + Assert.True(broken.ExitCode == 1, broken.ToString()); + Assert.Contains("definition.yaml", broken.Error, StringComparison.Ordinal); + Assert.False(File.Exists(api)); + Assert.True(hiddenRequestsOnly.ExitCode == 0, hiddenRequestsOnly.ToString()); + Assert.True(File.Exists(sockets)); + + // A file whose name holds "non-HTTP" is no note about hidden requests. + Assert.True(namedLikeTheNote.ExitCode == 1, namedLikeTheNote.ToString()); + Assert.False(File.Exists(named)); + Assert.True(validated.ExitCode == 1, validated.ToString()); + } + + [Fact] + public async Task Convert_and_validate_refuse_a_folder_that_is_not_a_v3_collection() + { + // A workspace folder (with its sources and node_modules) is not one collection: as run, they say so. + var root = TestFiles.NewTempDirectory(); + WriteFiles(root, + ("postman/collections/Api/Ping.request.yaml", HttpRequestYaml("https://h/ping")), + ("src/lib/deep/notes.txt", "x")); + + var convert = await Termrest.RunAsync(["convert", root]); + var validate = await Termrest.RunAsync(["validate", root]); + + Assert.True(convert.ExitCode == 1, convert.ToString()); + Assert.Contains("is not a Postman v3 collection folder", convert.Error, StringComparison.Ordinal); + Assert.Empty(Directory.EnumerateFiles(Path.GetDirectoryName(root)!, Path.GetFileName(root) + "*.json")); + Assert.True(validate.ExitCode == 1, validate.ToString()); + Assert.Contains("is not a Postman v3 collection folder", validate.Text + validate.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task Convert_names_what_it_writes_so_that_the_workspace_loads_it() + { + // A leading dot would hide the converted collection: the workspace does not load folders whose names start with one. + var directory = TestFiles.NewTempDirectory(); + var collection = WriteCollection(directory, ".NET API", [("Ping", "GET", "https://h/ping")]); + var environment = Path.Combine(directory, "dotnet.postman_environment.json"); + File.WriteAllText(environment, """{ "name": ".NET dev", "values": [ { "key": "baseUrl", "value": "https://h", "enabled": true } ] }"""); + + var convertCollection = await Termrest.RunAsync(["convert", collection]); + var convertEnvironment = await Termrest.RunAsync(["convert", environment]); + + Assert.True(convertCollection.ExitCode == 0, convertCollection.ToString()); + Assert.True(convertEnvironment.ExitCode == 0, convertEnvironment.ToString()); + var workspace = ApiWorkspace.Open(directory); + Assert.Contains(workspace.Collections, c => c.IsV3 && c.Name == ".NET API" && c.FilePath == Path.Combine(directory, "postman", "collections", "-NET API")); + Assert.True(File.Exists(Path.Combine(directory, "postman", "environments", "-NET dev.environment.yaml"))); + Assert.Contains(workspace.Environments, e => e.IsYaml && e.Name == ".NET dev"); + } + + [Fact] + public async Task Convert_writes_files_from_the_postman_folders_next_to_them() + { + // JSON files kept where the workspace loads them: the converted copies go into the same workspace. + var root = TestFiles.NewTempDirectory(); + var collection = WriteCollection(Directory.CreateDirectory(Path.Combine(root, "postman", "collections")).FullName, "Smoke", [("Ping", "GET", "https://h/ping")]); + WriteFiles(root, ("postman/environments/staging.postman_environment.json", """{ "name": "staging", "values": [ { "key": "baseUrl", "value": "https://h", "enabled": true } ] }""")); + + var convertCollection = await Termrest.RunAsync(["convert", collection]); + var convertEnvironment = await Termrest.RunAsync(["convert", Path.Combine(root, "postman", "environments", "staging.postman_environment.json")]); + + Assert.True(convertCollection.ExitCode == 0, convertCollection.ToString()); + Assert.True(convertEnvironment.ExitCode == 0, convertEnvironment.ToString()); + var workspace = ApiWorkspace.Open(root); + Assert.Contains(workspace.Collections, c => c.IsV3 && c.FilePath == Path.Combine(root, "postman", "collections", "Smoke")); + Assert.Contains(workspace.Environments, e => e.IsYaml && e.FilePath == Path.Combine(root, "postman", "environments", "staging.environment.yaml")); + Assert.False(Directory.Exists(Path.Combine(root, "postman", "collections", "postman"))); + } + + [Fact] + public async Task A_collection_file_in_postman_collections_is_sent_in_its_workspace() + { + await using var server = await TestServer.StartAsync(); + var root = TestFiles.NewTempDirectory(); + var collection = WriteCollection(Directory.CreateDirectory(Path.Combine(root, "postman", "collections")).FullName, "smoke", [("Ping", "GET", "{{baseUrl}}/echo/{{from}}")]); + string EnvironmentYaml(string name) => $"name: {name}\nvalues:\n - key: baseUrl\n value: {server.BaseUrl}\n enabled: true\n - key: from\n value: {name}\n enabled: true\n"; + WriteFiles(root, + ("postman/environments/local.environment.yaml", EnvironmentYaml("local")), + ("postman/environments/staging.environment.yaml", EnvironmentYaml("staging")), + (".termrest/settings.json", """{ "activeEnvironment": "local" }""")); + var state = new Dictionary { ["TERMREST_STATE_DIR"] = TestFiles.NewTempDirectory() }; + + // The workspace's settings (a theme chosen for it, the active environment, the history) and environments, as for the + // workspace folder. + var theme = await Termrest.RunAsync(["themes", "use", "Nord", "--only-here", "-w", collection]); + var active = await Termrest.RunAsync(["send", collection, "Ping"], state); + var named = await Termrest.RunAsync(["send", collection, "Ping", "-e", "staging", "--no-history"]); + var history = await Termrest.RunAsync(["history", root, "--json"], state); + + Assert.True(theme.ExitCode == 0, theme.ToString()); + Assert.Equal("Nord", ApiWorkspace.Open(root).Settings.Theme); + Assert.True(active.ExitCode == 0, active.ToString()); + Assert.Contains("/echo/local", active.Text, StringComparison.Ordinal); + Assert.True(named.ExitCode == 0, named.ToString()); + Assert.Contains("/echo/staging", named.Text, StringComparison.Ordinal); + Assert.True(history.ExitCode == 0, history.ToString()); + Assert.Contains("/echo/local", history.Text, StringComparison.Ordinal); + + // A v3 collection folder given as the workspace means the workspace that holds it, as for send and the UI. + WriteFiles(root, ("postman/collections/Smoke/.resources/definition.yaml", "$kind: collection\nname: Smoke\n")); + var folder = Path.Combine(root, "postman", "collections", "Smoke"); + var copy = await Termrest.RunAsync(["themes", "copy", "Nord", "Mine", "--in-workspace", "-w", folder]); + Assert.True(copy.ExitCode == 0, copy.ToString()); + Assert.True(Directory.Exists(Path.Combine(root, ".termrest", "themes")), copy.ToString()); + Assert.False(Directory.Exists(Path.Combine(folder, ".termrest"))); + + // A copy can't take a custom theme's name (case aside): only one of them would ever show. + var again = await Termrest.RunAsync(["themes", "copy", "Dark", "MINE", "--in-workspace", "-w", folder]); + Assert.True(again.ExitCode == 2, again.ToString()); + Assert.Contains("A custom theme called 'Mine' exists already", again.Error, StringComparison.Ordinal); + Assert.Single(Directory.GetFiles(Path.Combine(root, ".termrest", "themes"))); + } + + [Fact] + public async Task History_lists_and_shows_an_entry_whose_id_was_edited_short() + { + await using var server = await TestServer.StartAsync(); + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Ping", "GET", server.BaseUrl + "/echo/ping")]); + var workspace = Path.GetDirectoryName(collection)!; + var stateDirectory = TestFiles.NewTempDirectory(); + var state = new Dictionary { ["TERMREST_STATE_DIR"] = stateDirectory }; + var sent = await Termrest.RunAsync(["send", collection, "Ping"], state); + Assert.True(sent.ExitCode == 0, sent.ToString()); + var file = Assert.Single(Directory.GetFiles(stateDirectory, HistoryStore.FileName, SearchOption.AllDirectories)); + var entry = JsonNode.Parse(File.ReadAllText(file))!.AsObject(); + entry["id"] = "a1"; + File.WriteAllText(file, entry.ToJsonString() + "\n"); + + var listed = await Termrest.RunAsync(["history", workspace], state); + var shown = await Termrest.RunAsync(["history", workspace, "--show", "a1"], state); + + Assert.True(listed.ExitCode == 0, listed.ToString()); + Assert.StartsWith("a1 ", listed.Text, StringComparison.Ordinal); + Assert.True(shown.ExitCode == 0, shown.ToString()); + } + + [Fact] + public async Task History_shows_a_response_without_a_body_as_such_and_a_body_whose_copy_is_gone_as_not_kept() + { + await using var server = await TestServer.StartAsync(); + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Probe", "HEAD", server.BaseUrl + "/echo/probe"), ("Ping", "GET", server.BaseUrl + "/echo/ping")]); + var workspace = Path.GetDirectoryName(collection)!; + var stateDirectory = TestFiles.NewTempDirectory(); + var state = new Dictionary { ["TERMREST_STATE_DIR"] = stateDirectory }; + foreach (var name in (string[])["Probe", "Ping"]) + { + var sent = await Termrest.RunAsync(["send", collection, name], state); + Assert.True(sent.ExitCode == 0, sent.ToString()); + } + + var entries = JsonNode.Parse((await Termrest.RunAsync(["history", workspace, "--json"], state)).Text)!.AsArray(); + string Id(string method) => entries.Single(e => e!["method"]!.GetValue() == method)!["id"]!.GetValue(); + File.Delete(Assert.Single(Directory.GetFiles(stateDirectory, "*.bin", SearchOption.AllDirectories))); // the GET's, as by hand + + var probe = await Termrest.RunAsync(["history", workspace, "--show", Id("HEAD")], state); + var ping = await Termrest.RunAsync(["history", workspace, "--show", Id("GET")], state); + + Assert.True(probe.ExitCode == 0, probe.ToString()); + Assert.DoesNotContain("not kept", probe.Text, StringComparison.Ordinal); // there was none to keep + Assert.True(ping.ExitCode == 0, ping.ToString()); + Assert.EndsWith("(response body not kept)", ping.Text.TrimEnd(), StringComparison.Ordinal); + } + + [Fact] + public async Task History_reports_files_another_program_has_open() + { + if (!OperatingSystem.IsWindows()) + { + Assert.Skip("Windows only: elsewhere a file that is open can be read and deleted."); + } + + await using var server = await TestServer.StartAsync(); + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Ping", "GET", server.BaseUrl + "/echo/ping")]); + var workspace = Path.GetDirectoryName(collection)!; + var stateDirectory = TestFiles.NewTempDirectory(); + var state = new Dictionary { ["TERMREST_STATE_DIR"] = stateDirectory }; + var sent = await Termrest.RunAsync(["send", collection, "Ping"], state); + Assert.True(sent.ExitCode == 0, sent.ToString()); + var history = Assert.Single(Directory.GetFiles(stateDirectory, HistoryStore.FileName, SearchOption.AllDirectories)); + var body = Assert.Single(Directory.GetFiles(stateDirectory, "*.bin", SearchOption.AllDirectories)); + + // As an antivirus scan holds them. + CommandResult listed, notCleared, shown, cleared; + using (File.Open(history, FileMode.Open, FileAccess.Read, FileShare.None)) + { + listed = await Termrest.RunAsync(["history", workspace], state); + notCleared = await Termrest.RunAsync(["history", workspace, "--clear"], state); + } + + using (File.Open(body, FileMode.Open, FileAccess.Read, FileShare.None)) + { + shown = await Termrest.RunAsync(["history", workspace, "--show", Path.GetFileNameWithoutExtension(body)], state); + cleared = await Termrest.RunAsync(["history", workspace, "--clear"], state); + } + + foreach (var (result, message) in (ValueTuple[])[(listed, "The history could not be read"), (notCleared, "The history could not be cleared"), + (shown, "could not be read"), (cleared, "History cleared, but some response bodies could not be deleted")]) + { + Assert.True(result.ExitCode == 1, result.ToString()); + Assert.Contains(message, result.Error, StringComparison.Ordinal); + Assert.DoesNotContain(" at ", result.Error, StringComparison.Ordinal); // a message, not a stack trace + } + } + + [Fact] + public async Task Send_writes_binary_bodies_as_received() + { + await using var server = await TestServer.StartAsync(); + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", + [ + ("Image", "GET", server.BaseUrl + "/bytes"), + ("Octets", "GET", server.BaseUrl + "/octets"), + ("Protobuf", "GET", server.BaseUrl + "/protobuf"), + ("Report", "GET", server.BaseUrl + "/xlsx"), + ("Json", "GET", server.BaseUrl + "/echo/json"), + ("User", "GET", server.BaseUrl + "/utf8"), + ]); + + var piped = await Termrest.RunAsync(["send", collection, "Image", "--no-history"]); + var raw = await Termrest.RunAsync(["send", collection, "Image", "--raw", "--no-history"]); + var octets = await Termrest.RunAsync(["send", collection, "Octets", "--no-history"]); + var protobuf = await Termrest.RunAsync(["send", collection, "Protobuf", "--no-history"]); + var report = await Termrest.RunAsync(["send", collection, "Report", "--no-history"]); + var json = await Termrest.RunAsync(["send", collection, "Json", "--no-history"]); + var rawJson = await Termrest.RunAsync(["send", collection, "User", "--raw", "--no-history"]); + + Assert.True(piped.ExitCode == 0, piped.ToString()); + Assert.Equal(TestServer.Bytes, piped.Output); + Assert.Equal(TestServer.Bytes, raw.Output); + + // Binary data need not have a NUL byte: its type says what it is. + Assert.Equal(TestServer.Octets, octets.Output); + Assert.Equal(TestServer.Protobuf, protobuf.Output); + Assert.Equal(TestServer.Workbook, report.Output); // a ZIP file, though its type names XML formats + Assert.Contains("\n \"method\": \"GET\"", json.Text.ReplaceLineEndings("\n"), StringComparison.Ordinal); // text is still pretty-printed + Assert.Equal(Encoding.UTF8.GetBytes(TestServer.Utf8Json), rawJson.Output); // with --raw as received, no line break added + } + + [Fact] + public async Task Send_curl_prints_no_command_that_curl_would_send_differently() + { + var directory = TestFiles.NewTempDirectory(); + File.WriteAllText(Path.Combine(directory, "README.md"), "readme"); + var collection = Path.Combine(directory, "Api.postman_collection.json"); + File.WriteAllText(collection, $$""" + { "info": { "name": "Api", "schema": "{{Schema}}" }, "item": [ + { "name": "Upload", "request": { "method": "POST", "url": "https://h/upload", "body": { "mode": "formdata", + "formdata": [ { "key": "doc=>>>>>> theirs\n}\n")); + var collection = WriteCollection(directory, "Api", [("Ping", "GET", server.BaseUrl + "/echo/ping")]); + var har = Path.Combine(directory, "run.har"); + var report = Path.Combine(directory, "report.json"); + + var send = await Termrest.RunAsync(["send", collection, "Ping"]); + var run = await Termrest.RunAsync(["run", collection, "--record", har, "--report-json", report]); + + // They may turn the history off and name what recordings must redact. + Assert.True(send.ExitCode == 1, send.ToString()); + Assert.Contains("Fix or delete " + Path.Combine(directory, ".termrest", "settings.json"), send.Error, StringComparison.Ordinal); + Assert.Empty(send.Output); + Assert.True(run.ExitCode == 1, run.ToString()); + Assert.False(File.Exists(har)); + Assert.False(File.Exists(report)); + Assert.Equal(0, server.Requests); + + // The full-screen UI goes on with the defaults, without a history. + using var runner = new RequestRunner(ApiWorkspace.Open(directory)); + runner.ConfigureHistory(TestFiles.NewTempDirectory()); + Assert.Null(runner.History); + } + + [Fact] + public async Task Run_warns_when_your_settings_cannot_be_read() + { + await using var server = await TestServer.StartAsync(); + var config = TestFiles.NewTempDirectory(); + File.WriteAllText(Path.Combine(config, "settings.json"), "{\n<<<<<<< HEAD\n \"scriptLanguageOrder\": [\"python\"]\n=======\n}\n"); + var collection = WriteCollection(TestFiles.NewTempDirectory(), "Api", [("Ping", "GET", server.BaseUrl + "/echo/ping")]); + + var run = await Termrest.RunAsync(["run", collection], new Dictionary { ["TERMREST_CONFIG_DIR"] = config }); + + // They choose the runtimes of scripts: without them, a request with scripts fails as if none were chosen. + Assert.True(run.ExitCode == 0, run.ToString()); + Assert.StartsWith("warning: " + Path.Combine(config, "settings.json") + ": ", run.Error, StringComparison.Ordinal); + Assert.Contains("script runtimes chosen for this workspace", run.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task A_proxy_in_the_workspace_settings_is_not_used_until_it_is_allowed() + { + // A cloned repository's settings name a proxy (nothing listens there): requests go without it, and a warning says so. + await using var server = await TestServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + const string proxy = "http://ada:Pr0xy-s3cret@127.0.0.1:1"; + WriteFiles(directory, (".termrest/settings.json", $$"""{ "proxy": "{{proxy}}" }""")); + var collection = WriteCollection(directory, "Api", [("Ping", "GET", server.BaseUrl + "/echo/ping")]); + + var unknown = await Termrest.RunAsync(["send", collection, "Ping"]); + var run = await Termrest.RunAsync(["run", collection]); + + // Allowed for this folder in the UI (Tools > Settings > Save), which keeps that in the user's settings. + var config = TestFiles.NewTempDirectory(); + var user = new UserSettings(); + user.AllowProxy(directory, proxy); + user.Save(config); + var allowed = await Termrest.RunAsync(["send", collection, "Ping"], new Dictionary { ["TERMREST_CONFIG_DIR"] = config }); + + Assert.True(unknown.ExitCode == 0, unknown.ToString()); + Assert.Contains("/echo/ping", unknown.Text, StringComparison.Ordinal); + Assert.Contains("(http://ada:***@127.0.0.1:1) is not used", unknown.Error, StringComparison.Ordinal); + Assert.DoesNotContain("Pr0xy-s3cret", unknown.Error, StringComparison.Ordinal); + Assert.True(run.ExitCode == 0, run.ToString()); + Assert.Contains("(http://ada:***@127.0.0.1:1) is not used", run.Error, StringComparison.Ordinal); + Assert.True(allowed.ExitCode == 1, allowed.ToString()); // the proxy refused the connection + Assert.DoesNotContain("is not used", allowed.Error, StringComparison.Ordinal); + Assert.Equal(2, server.Requests); + } + + [Fact] + public async Task Files_from_outside_the_workspace_are_sent_only_with_allow_outside_files() + { + // A collection someone else wrote, whose body is a file of the user's. + await using var server = await TestServer.StartAsync(); + var directory = TestFiles.NewTempDirectory(); + var secret = Path.Combine(TestFiles.NewTempDirectory(), "credentials"); + File.WriteAllText(secret, "s3cret"); + var collection = Path.Combine(directory, "Api.postman_collection.json"); + File.WriteAllText(collection, $$""" + { "info": { "name": "Api", "schema": "{{Schema}}" }, "item": [ + { "name": "Upload", "request": { "method": "PUT", "url": "{{server.BaseUrl}}/upload", "body": { "mode": "file", + "file": { "src": {{JsonValue.Create(secret).ToJsonString()}} } } } } ] } + """); + + var refused = await Termrest.RunAsync(["send", collection, "Upload"]); + var allowed = await Termrest.RunAsync(["send", collection, "Upload", "--allow-outside-files"]); + + Assert.True(refused.ExitCode == 1, refused.ToString()); + Assert.Contains($"Body file '{secret}' is outside the workspace folder, so it is not sent", refused.Error, StringComparison.Ordinal); + Assert.True(allowed.ExitCode == 0, allowed.ToString()); + Assert.Equal(1, server.Requests); + } +} diff --git a/tests/TermRest.Cli.Tests/Infrastructure/Termrest.cs b/tests/TermRest.Cli.Tests/Infrastructure/Termrest.cs new file mode 100644 index 0000000..43facc6 --- /dev/null +++ b/tests/TermRest.Cli.Tests/Infrastructure/Termrest.cs @@ -0,0 +1,90 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using TermRest.Core.Tests.Infrastructure; +using Xunit; + +namespace TermRest.Cli.Tests.Infrastructure; + +/// What a command did: its exit code, standard output (as bytes) and standard error. +internal sealed record CommandResult(int ExitCode, byte[] Output, string Error) +{ + public string Text => Encoding.UTF8.GetString(Output); + + public override string ToString() => $"exit code {ExitCode}\nstdout: {Text}\nstderr: {Error}"; +} + +/// +/// Runs the termrest built next to the tests as a separate process, as scripts and CI run it: standard output and +/// error are pipes. Each run gets its own user configuration and state folders, so it never touches the user's. +/// +internal static class Termrest +{ + private static readonly string Dotnet = Path.GetFullPath(Path.Combine( + RuntimeEnvironment.GetRuntimeDirectory(), "..", "..", "..", OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet")); + + /// Extra environment variables; TERMREST_CONFIG_DIR replaces the run's own configuration folder. + /// 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). + public static async Task RunAsync(IEnumerable arguments, IReadOnlyDictionary? environment = null, byte[]? input = null, + Func? whileRunning = null, string? workingDirectory = null) + { + var start = new ProcessStartInfo(Dotnet) + { + WorkingDirectory = workingDirectory ?? "", + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardErrorEncoding = Encoding.UTF8, + UseShellExecute = false, + + // No console: on Windows, what the command writes does not depend on the code page of the console the tests + // run in (UTF-8 in some terminals, which would hide text written in another one). + CreateNoWindow = true, + }; + start.ArgumentList.Add("exec"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "termrest.dll")); + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + start.Environment["TERMREST_CONFIG_DIR"] = TestFiles.NewTempDirectory(); + start.Environment["TERMREST_STATE_DIR"] = TestFiles.NewTempDirectory(); + start.Environment["NO_COLOR"] = "1"; + foreach (var (name, value) in environment ?? new Dictionary()) + { + start.Environment[name] = value; + } + + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromMinutes(2)); + using var process = Process.Start(start) ?? throw new InvalidOperationException($"{Dotnet} did not start."); + if (input is not null) + { + await process.StandardInput.BaseStream.WriteAsync(input, timeout.Token); + } + + process.StandardInput.Close(); + using var output = new MemoryStream(); + var copying = process.StandardOutput.BaseStream.CopyToAsync(output, timeout.Token); + var error = process.StandardError.ReadToEndAsync(timeout.Token); + try + { + if (whileRunning is not null) + { + await whileRunning(process); + } + + await process.WaitForExitAsync(timeout.Token); + await copying; + return new CommandResult(process.ExitCode, output.ToArray(), await error); + } + catch (Exception) when (!process.HasExited) + { + process.Kill(entireProcessTree: true); // timed out, or whileRunning failed + throw; + } + } +} diff --git a/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs b/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs new file mode 100644 index 0000000..0dd4f89 --- /dev/null +++ b/tests/TermRest.Cli.Tests/Infrastructure/TestServer.cs @@ -0,0 +1,154 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json.Nodes; + +namespace TermRest.Cli.Tests.Infrastructure; + +/// +/// Minimal HTTP/1.1 server for the commands under test (plain sockets: no web framework next to termrest.dll, which +/// 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 response with , /wait no response until the +/// server stops (see ); any other path returns the request as JSON. +/// +internal sealed class TestServer : IAsyncDisposable +{ + /// The body of /bytes: every byte value, then line breaks and a NUL that text output would change. + public static readonly byte[] Bytes = [.. Enumerable.Range(0, 256).Select(i => (byte)i), .. "\r\n\n\0end"u8]; + + /// The body of /octets (application/octet-stream): bytes that are not UTF-8, line breaks, a byte order mark, an escape sequence. + public static readonly byte[] Octets = + [0xC3, 0x28, 0xA0, 0xA1, 0xE2, 0x28, 0xA1, 0xF0, 0x90, 0x28, 0xBC, 0xFF, 0xFE, 0x0D, 0x0A, 0x0A, 0x7F, 0x80, 0x81, 0x1B, 0x5B, 0x33, 0x31, 0x6D, 0xEF, 0xBB, 0xBF, 0x41, 0x0D, 0x01, 0x02, 0x03]; + + /// The body of /protobuf (application/x-protobuf): field 1 "abc", field 2 150. + public static readonly byte[] Protobuf = [0x0A, 0x03, 0x61, 0x62, 0x63, 0x10, 0x96, 0x01]; + + /// The body of /xlsx: the start of an Excel workbook, a ZIP file, though its type names XML formats. + public static readonly byte[] Workbook = [0x50, 0x4B, 0x03, 0x04, 0x14, 0x00, 0x06, 0x00, 0x08, 0x00, 0x00, 0x00, 0x21, 0x00, 0x8C, 0x5A, 0xED, 0xC1, 0x6E, 0x01, 0x00, 0x00]; + + /// The body of /utf8: characters that no console code page has all of. + public const string Utf8Json = "{\"name\":\"Zoë – 東京 ✓\"}"; + + /// The access token /token returns (40 characters). + public const string Token = "tk_live_51HxQ2eKz8Yb4Rf7Lm0Np3Vs6Wc9Ty2A"; + + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _stop = new(); + private readonly TaskCompletionSource _waiting = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly Task _accepting; + private int _requests; + + private TestServer() + { + _listener.Start(); + BaseUrl = $"http://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}"; + _accepting = AcceptAsync(); + } + + /// Base URL without a trailing slash, e.g. http://127.0.0.1:5123. + public string BaseUrl { get; } + + /// How many requests it received. + public int Requests => Volatile.Read(ref _requests); + + /// Completes when a request to /wait arrives. + public Task Waiting => _waiting.Task; + + public static Task StartAsync() => Task.FromResult(new TestServer()); + + private async Task AcceptAsync() + { + while (true) + { + TcpClient client; + try + { + client = await _listener.AcceptTcpClientAsync(_stop.Token); + } + catch (Exception ex) when (ex is OperationCanceledException or ObjectDisposedException or SocketException) + { + return; + } + + _ = RespondAsync(client); + } + } + + private async Task RespondAsync(TcpClient client) + { + using (client) + { + try + { + var stream = client.GetStream(); + var received = new MemoryStream(); + var buffer = new byte[4096]; + int end; + while ((end = received.GetBuffer().AsSpan(0, (int)received.Length).IndexOf("\r\n\r\n"u8)) < 0) + { + var count = await stream.ReadAsync(buffer, _stop.Token); + if (count == 0) + { + return; + } + + received.Write(buffer, 0, count); + } + + // The body too, which may come with the headers, so that the connection closes cleanly. + var length = Encoding.ASCII.GetString(received.GetBuffer(), 0, end).Split("\r\n") + .Select(line => line.Split(':', 2)) + .Where(parts => parts.Length == 2 && parts[0].Trim().Equals("Content-Length", StringComparison.OrdinalIgnoreCase)) + .Select(parts => long.Parse(parts[1].Trim(), System.Globalization.CultureInfo.InvariantCulture)) + .FirstOrDefault(); + while (received.Length < end + 4 + length) + { + var count = await stream.ReadAsync(buffer, _stop.Token); + if (count == 0) + { + return; + } + + received.Write(buffer, 0, count); + } + + Interlocked.Increment(ref _requests); + var requestLine = Encoding.ASCII.GetString(received.ToArray()).Split("\r\n")[0].Split(' '); + var path = requestLine[1].Split('?')[0]; + if (path == "/wait") + { + _waiting.TrySetResult(); + await Task.Delay(Timeout.Infinite, _stop.Token); + } + + var (body, type) = path switch + { + "/bytes" => (Bytes, "image/png"), + "/octets" => (Octets, "application/octet-stream"), + "/protobuf" => (Protobuf, "application/x-protobuf"), + "/xlsx" => (Workbook, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"), + "/large" => (new byte[1536 * 1024], "application/octet-stream"), + "/utf8" => (Encoding.UTF8.GetBytes(Utf8Json), "application/json; charset=utf-8"), + "/token" => (Encoding.UTF8.GetBytes($"{{\"access_token\":\"{Token}\",\"token_type\":\"Bearer\",\"expires_in\":3600}}"), "application/json"), + _ => (Encoding.UTF8.GetBytes(new JsonObject { ["method"] = requestLine[0], ["path"] = path }.ToJsonString()), "application/json"), + }; + var head = $"HTTP/1.1 200 OK\r\nContent-Type: {type}\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n"; + await stream.WriteAsync(Encoding.ASCII.GetBytes(head), _stop.Token); + await stream.WriteAsync(body, _stop.Token); + } + catch (Exception ex) when (ex is IOException or SocketException or OperationCanceledException) + { + // The client went away, or the server is stopping. + } + } + } + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + await _accepting; + _stop.Dispose(); + } +} diff --git a/tests/TermRest.Cli.Tests/TermRest.Cli.Tests.csproj b/tests/TermRest.Cli.Tests/TermRest.Cli.Tests.csproj new file mode 100644 index 0000000..afc001b --- /dev/null +++ b/tests/TermRest.Cli.Tests/TermRest.Cli.Tests.csproj @@ -0,0 +1,29 @@ + + + + Exe + false + true + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/TermRest.Core.Tests/BodyFileTests.cs b/tests/TermRest.Core.Tests/BodyFileTests.cs index 70a3a62..f93c1a9 100644 --- a/tests/TermRest.Core.Tests/BodyFileTests.cs +++ b/tests/TermRest.Core.Tests/BodyFileTests.cs @@ -101,6 +101,18 @@ public void Xml_must_be_well_formed_and_its_dtd_is_never_followed() Assert.DoesNotContain("TOP-SECRET", entity, StringComparison.Ordinal); } + [Fact] + public void Xml_is_read_in_the_legacy_encoding_its_declaration_names() + { + // .NET knows these only from its code pages. + Assert.Null(Check(Write("jp.xml", [.. "\n"u8, 0x93, 0xFA, 0x96, 0x7B, .. ""u8]), "xml")); + Assert.Contains( + "The 'a' start tag on line 2 position 2 does not match the end tag of 'b'", + Check(Write("bad.xml", [.. "\n"u8, 0xA4, .. ""u8]), "xml"), + StringComparison.Ordinal); + Assert.StartsWith("odd.xml is not well-formed XML: System does not support 'x-odd' encoding", Check(Write("odd.xml", ""), "xml"), StringComparison.Ordinal); + } + [Fact] public void Text_types_turn_down_binary_and_utf16_files() { diff --git a/tests/TermRest.Core.Tests/CSharpScriptingTests.cs b/tests/TermRest.Core.Tests/CSharpScriptingTests.cs index 5e9bb43..5760da7 100644 --- a/tests/TermRest.Core.Tests/CSharpScriptingTests.cs +++ b/tests/TermRest.Core.Tests/CSharpScriptingTests.cs @@ -1,3 +1,4 @@ +using System.Text.Json.Nodes; using TermRest.Core.Http; using TermRest.Core.Model; using TermRest.Core.Postman; @@ -25,6 +26,23 @@ private static (ApiWorkspace Workspace, PostmanCollection Collection) NewWorkspa /// A comment that makes a program no test has built yet (built programs are kept in the cache). private static string Fresh() => "// " + Guid.NewGuid().ToString("N"); + /// A dotnet that runs and writes each command line it gets to the returned file. + private static (string Dotnet, string Commands) LoggingDotnet(string dotnet) + { + var folder = TestFiles.NewTempDirectory(); + var real = ScriptRuntimeLocator.Executable(dotnet)!; + var wrapper = Path.Combine(folder, OperatingSystem.IsWindows() ? "dotnet.cmd" : "dotnet"); + File.WriteAllText(wrapper, OperatingSystem.IsWindows() + ? $"@echo %*>>\"%~dp0commands.txt\"\r\n@\"{real}\" %*\r\n" + : $"#!/bin/sh\necho \"$*\" >> \"$(dirname \"$0\")/commands.txt\"\nexec \"{real}\" \"$@\"\n"); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(wrapper, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + + return (wrapper, Path.Combine(folder, "commands.txt")); + } + [Fact] public async Task CSharp_scripts_run_around_a_request_with_the_tr_object() { @@ -197,7 +215,7 @@ public async Task Programs_that_scripts_start_cannot_disturb_the_program() runner.SetCSharpRuntime(dotnet); // Their output does not get mixed into the answers, and reading input they get nothing (not a request). - var exchange = await runner.SendAsync(collection, null, CSharp(server.Url("echo"), preRequest: "using System.Diagnostics;\n" + Fresh() + """ + var exchange = await runner.SendAsync(collection, null, CSharp(server.Url("echo"), preRequest: "#:property AllowUnsafeBlocks=true\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\n" + Fresh() + """ var echo = OperatingSystem.IsWindows() ? new ProcessStartInfo("cmd.exe", ["/c", "echo from a child process"]) : new ProcessStartInfo("/bin/sh", ["-c", "echo from a child process"]); Process.Start(echo).WaitForExit(); @@ -208,11 +226,94 @@ public async Task Programs_that_scripts_start_cannot_disturb_the_program() child.WaitForExit(); Console.WriteLine($"a child reads [{read.Trim()}]"); Console.WriteLine("captured ünïcödé ✓"); + if (!OperatingSystem.IsWindows()) + { + unsafe + { + var getsid = (delegate* unmanaged)NativeLibrary.GetExport(NativeLibrary.GetMainProgramHandle(), "getsid"); + tr.Globals["session"] = getsid(0) == Environment.ProcessId ? "its own" : "TermRest's"; + } + } """, test: "tr.Test(\"still answers\", () => { });"), _ct); Assert.Equal(200, exchange.Response!.StatusCode); Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); Assert.Equal(["a child reads []", "captured ünïcödé ✓"], exchange.Scripts.Logs.Select(l => l.Text)); + + // Nor can they open TermRest's terminal (/dev/tty) to ask for a password over its screen: the program is in a session + // of its own, which has none (this test may run without a terminal, so trying to open it would tell nothing). + Assert.Equal(OperatingSystem.IsWindows() ? null : "its own", runner.Session.Globals.GetValueOrDefault("session")); + } + + [Fact] + public async Task Halves_of_emoji_do_not_break_the_answer() + { + var dotnet = TestCSharp.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetCSharpRuntime(dotnet); + + // A line cut at 4,000 characters, not inside an emoji, and a script's own substring of one (not text: it becomes U+FFFD). + var exchange = await runner.SendAsync(collection, null, CSharp(server.Url("echo"), test: Fresh() + """ + + Console.WriteLine(new string('a', 3999) + "😀"); + var half = "😀"[..1]; + Console.WriteLine("half " + half + " and a whole 😀"); + tr.Test("test " + half, () => { }); + tr.Globals.Set("name " + half, half); + """), _ct); + + Assert.Equal(200, exchange.Response!.StatusCode); + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal([new string('a', 3999), "half \uFFFD and a whole 😀"], exchange.Scripts.Logs.Select(l => l.Text)); + Assert.Equal(["test \uFFFD"], exchange.Scripts.Tests.Select(t => t.Name)); + Assert.Equal("\uFFFD", runner.Session.Globals["name \uFFFD"]); + } + + [Fact] + public async Task A_global_using_applies_to_the_whole_program() + { + var dotnet = TestCSharp.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetCSharpRuntime(dotnet); + + // C# allows global usings only before the namespaces each script gets. + var exchange = await runner.SendAsync(collection, null, CSharp(server.Url("echo"), + preRequest: "global using System.Net;\nglobal using System.Net;\n" + Fresh(), + test: "global using System.Net;\n" + Fresh() + "\ntr.Test(\"status\", () => tr.Assert(HttpStatusCode.OK == (HttpStatusCode)tr.Response.Code));"), _ct); + + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal(["status"], exchange.Scripts.Tests.Where(t => t.Passed).Select(t => t.Name)); + } + + [Fact] + public async Task Dates_uris_and_json_strings_set_in_scripts_are_their_text() + { + var dotnet = TestCSharp.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetCSharpRuntime(dotnet); + + var exchange = await runner.SendAsync(collection, null, CSharp(server.Url("echo"), test: Fresh() + """ + + tr.CollectionVariables.Set("site", new Uri("https://example.org/a%20b")); + tr.CollectionVariables.Set("name", System.Text.Json.JsonSerializer.SerializeToElement("Ada")); + tr.CollectionVariables.Set("flags", new { on = true }); + tr.CollectionVariables.Set("day", new DateOnly(2024, 1, 2)); + tr.CollectionVariables.Set("at", new TimeOnly(3, 4, 5)); + var order = new JsonObject { ["id"] = Guid.Parse("3f2504e0-4f89-11d3-9a0c-0305e82c3301") }; + tr.CollectionVariables.Set("id", order["id"]); + tr.Test("a GUID held by JSON is its text", () => tr.AssertEqual("3f2504e0-4f89-11d3-9a0c-0305e82c3301", order["id"])); + """), _ct); + + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + var stored = runner.Session.For(collection); + Assert.Equal(("https://example.org/a%20b", "Ada", """{"on":true}"""), (stored["site"], stored["name"], stored["flags"])); + Assert.Equal(("2024-01-02", "03:04:05.0000000", "3f2504e0-4f89-11d3-9a0c-0305e82c3301"), (stored["day"], stored["at"], stored["id"])); } [Fact] @@ -239,14 +340,296 @@ public async Task Requests_in_different_languages_run_in_their_own_runtimes() Assert.Equal([".NET", "Python"], runner.RunningRuntimes.Order(StringComparer.Ordinal)); } + [Fact] + public async Task Stopping_scripts_while_they_are_built_leaves_no_program_running() + { + var dotnet = TestCSharp.Require(); + using var worker = ScriptWorker.For(ScriptLanguage.CSharp, dotnet, TestFiles.NewTempDirectory()); + var message = new JsonObject + { + ["phase"] = "test", + ["scripts"] = new JsonArray(new JsonObject { ["name"] = "request", ["code"] = Fresh() + "\nConsole.WriteLine(1);" }), + }; + + // Tools › Scripts › Stop scripts while the scripts are built: the program does not start once they are. + var run = worker.RunAsync(message, TimeSpan.FromSeconds(30), cancellationToken: _ct); + await Task.Delay(300, _ct); + Assert.False(run.IsCompleted); + worker.Dispose(); + + await Assert.ThrowsAsync(() => run); + Assert.False(worker.IsRunning); + } + + [Fact] + public async Task A_program_that_runs_stays_whole_when_it_is_built_again() + { + var dotnet = TestCSharp.Require(); + var workspace = TestFiles.NewTempDirectory(); + var code = Fresh() + "\ntr.Test(\"ran\", () => { });"; + JsonObject Message() => new() { ["phase"] = "test", ["scripts"] = new JsonArray(new JsonObject { ["name"] = "request", ["code"] = code }) }; + + // A TermRest runs the program while another forgets it (its own run of it ended before it answered) and builds it again. + using var running = ScriptWorker.For(ScriptLanguage.CSharp, dotnet, workspace); + await running.RunAsync(Message(), TimeSpan.FromSeconds(30), cancellationToken: _ct); + Assert.True(running.IsRunning); + var programs = new CSharpPrograms(dotnet, workspace); + var (program, _) = await programs.PrepareAsync(Message(), [], _ct); + var folder = Path.GetDirectoryName(program)!; + var files = Directory.GetFiles(folder, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal).ToList(); + CSharpPrograms.Forget(program); + + var (again, _) = await programs.PrepareAsync(Message(), [], _ct); + + Assert.Equal(program, again); + Assert.Equal(files, Directory.GetFiles(folder, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal)); + using var next = ScriptWorker.For(ScriptLanguage.CSharp, dotnet, workspace); + var reply = await next.RunAsync(Message(), TimeSpan.FromSeconds(30), cancellationToken: _ct); + Assert.Equal("ran", reply["tests"]![0]!["name"]!.GetValue()); + } + + [Fact] + public async Task A_script_of_the_collection_that_does_not_build_is_left_out_at_once_the_next_time() + { + var (dotnet, commands) = LoggingDotnet(TestCSharp.Require()); + var programs = new CSharpPrograms(dotnet, TestFiles.NewTempDirectory()); + var mine = Fresh() + "\ntr.Test(\"ran\", () => { });"; + var theirs = "#:project no-such-project\n" + Fresh(); // another request's script, whose project is not there + ScriptCode[] collection = [new("", mine, ScriptLanguage.CSharp), new("", theirs, ScriptLanguage.CSharp)]; + JsonObject Message(string code) => new() { ["phase"] = "test", ["scripts"] = new JsonArray(new JsonObject { ["name"] = "request", ["code"] = code }) }; + int Builds() => File.Exists(commands) ? File.ReadLines(commands).Count(l => l.StartsWith("run ", StringComparison.Ordinal)) : 0; + var (alone, _) = await programs.PrepareAsync(Message(mine), [], _ct); + + // The collection's program does not build: the script runs in its own program, built before, so nothing was built. + var (program, note) = await programs.PrepareAsync(Message(mine), collection, _ct); + var builds = Builds(); + var (again, noteAgain) = await programs.PrepareAsync(Message(mine), collection, _ct); + + Assert.Equal(alone, program); + Assert.Null(note); + Assert.Equal(alone, again); // without building the collection's program again + Assert.Null(noteAgain); + Assert.Equal(builds, Builds()); + + // The script that does not build fails with its own error, built again each time it runs (it may have been fixed). + var first = Message(theirs); + var (_, firstNote) = await programs.PrepareAsync(first, collection, _ct); + builds = Builds(); + var second = Message(theirs); + await programs.PrepareAsync(second, collection, _ct); + Assert.Contains("no-such-project", first["scripts"]![0]!["error"]!["message"]!.GetValue(), StringComparison.Ordinal); + Assert.Contains("no-such-project", second["scripts"]![0]!["error"]!["message"]!.GetValue(), StringComparison.Ordinal); + Assert.True(Builds() > builds); + Assert.DoesNotContain("start at once next time", firstNote ?? "", StringComparison.Ordinal); + } + + [Fact] + public async Task Directives_of_another_script_of_the_collection_do_not_break_the_scripts_that_run() + { + var (dotnet, commands) = LoggingDotnet(TestCSharp.Require()); + using var worker = ScriptWorker.For(ScriptLanguage.CSharp, dotnet, TestFiles.NewTempDirectory()); + var mine = Fresh() + "\nvar unused = 1;\ntr.Test(\"ok\", () => { });"; + var theirs = "#:property TreatWarningsAsErrors=true\n" + Fresh(); // another request's: it makes the warning in mine (CS0219) an error + ScriptCode[] collection = [new("", mine, ScriptLanguage.CSharp), new("", theirs, ScriptLanguage.CSharp)]; + 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 builds = Builds(); + var again = await worker.RunAsync(Message(), TimeSpan.FromSeconds(30), collection, _ct); + + Assert.Null(reply["error"]); + Assert.Equal("ok", reply["tests"]![0]!["name"]!.GetValue()); + Assert.Null(again["error"]); + Assert.Equal(builds, Builds()); // the program with the other script is not built again to fail + } + + [Fact] + public async Task The_compiler_server_is_stopped_where_the_scripts_are_built() + { + var dotnet = TestCSharp.Require(); + var message = new JsonObject { ["phase"] = "test", ["scripts"] = new JsonArray(new JsonObject { ["name"] = "request", ["code"] = Fresh() }) }; + await new CSharpPrograms(dotnet, TestFiles.NewTempDirectory()).PrepareAsync(message, [], _ct); // this TermRest built scripts + + // Not in TermRest's current folder, whose global.json would choose the SDK: this dotnet tells where it runs. + var folder = TestFiles.NewTempDirectory(); + var fake = Path.Combine(folder, OperatingSystem.IsWindows() ? "dotnet.cmd" : "dotnet"); + await File.WriteAllTextAsync(fake, OperatingSystem.IsWindows() + ? "@cd > \"%~dp0where.tmp\"\r\n@move /y \"%~dp0where.tmp\" \"%~dp0where.txt\" > nul\r\n" + : "#!/bin/sh\nhere=$(dirname \"$0\")\npwd > \"$here/where.tmp\" && mv \"$here/where.tmp\" \"$here/where.txt\"\n", _ct); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(fake, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + + CSharpPrograms.StopCompilerServer(fake); + + var where = Path.Combine(folder, "where.txt"); + for (var i = 0; i < 200 && !File.Exists(where); i++) + { + await Task.Delay(50, _ct); + } + + Assert.EndsWith(Path.Combine("csharp", "source"), (await File.ReadAllTextAsync(where, _ct)).Trim(), StringComparison.Ordinal); + } + + [Fact] + public async Task Changes_to_included_files_build_the_scripts_again() + { + var dotnet = TestCSharp.Require(); + var (_, sdk) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.CSharp, dotnet, _ct); + if (!Version.TryParse(sdk.Split(' ')[2].Split('-')[0], out var version) || version < new Version(10, 0, 300)) + { + Assert.Skip($"#:include needs the .NET SDK 10.0.300 or later ({sdk})."); + } + + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + var helpers = Path.Combine(workspace.RootPath, "helpers.cs"); + using var runner = new RequestRunner(workspace); + runner.SetCSharpRuntime(dotnet); + var spec = CSharp(server.Url("echo"), test: "#:include helpers.cs\n" + Fresh() + "\ntr.Test(Helpers.Name, () => { });"); + async Task Run(string name) + { + await File.WriteAllTextAsync(helpers, $"static class Helpers {{ public static string Name => {name}; }}", _ct); + return (await runner.SendAsync(collection, null, spec, _ct)).Scripts!; + } + + Assert.Equal(["one"], (await Run("\"one\"")).Tests.Select(t => t.Name)); + Assert.Equal(["two!"], (await Run("\"two!\"")).Tests.Select(t => t.Name)); + + // A compile error in the file names the file and its position, and is not reported again once it is fixed. + Assert.Equal("CS0103: The name 'three' does not exist in the current context (helpers.cs, line 1, column 53)", (await Run("three")).Error!.Message); + Assert.Equal(["three"], (await Run("\"three\"")).Tests.Select(t => t.Name)); + } + + [Fact] + public async Task Changes_to_a_referenced_project_build_the_scripts_again() + { + var dotnet = TestCSharp.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + var project = Path.Combine(workspace.RootPath, "lib"); + Directory.CreateDirectory(project); + await File.WriteAllTextAsync(Path.Combine(project, "Lib.csproj"), + """net10.0""", _ct); + using var runner = new RequestRunner(workspace); + runner.SetCSharpRuntime(dotnet); + var spec = CSharp(server.Url("echo"), test: "#:project lib/Lib.csproj\n" + Fresh() + "\ntr.Test(Names.Name, () => { });"); + async Task Run(string name) + { + await File.WriteAllTextAsync(Path.Combine(project, "Names.cs"), $"public static class Names {{ public static string Name => \"{name}\"; }}", _ct); + return (await runner.SendAsync(collection, null, spec, _ct)).Scripts!; + } + + Assert.Equal(["one"], (await Run("one")).Tests.Select(t => t.Name)); + Assert.Equal(["two!"], (await Run("two!")).Tests.Select(t => t.Name)); + + // What builds write in the project's folder (bin, obj) is no change: the program is not built again; nor is what the + // program of the project writes there when it runs (a database, logs). + await File.WriteAllTextAsync(Path.Combine(project, "app.db"), "rows", _ct); + Directory.CreateDirectory(Path.Combine(project, "logs")); + await File.WriteAllTextAsync(Path.Combine(project, "logs", "today.txt"), "GET /users 200", _ct); + var again = (await runner.SendAsync(collection, null, spec, _ct)).Scripts!; + Assert.Equal(["two!"], again.Tests.Select(t => t.Name)); + Assert.DoesNotContain(again.Notes, n => n.StartsWith("The C# scripts were built", StringComparison.Ordinal)); + } + + [Fact] + public async Task Changes_to_the_projects_and_settings_that_a_referenced_project_uses_build_the_scripts_again() + { + var dotnet = TestCSharp.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + var api = Path.Combine(workspace.RootPath, "src", "Api"); + var contracts = Path.Combine(workspace.RootPath, "src", "Contracts"); + Directory.CreateDirectory(api); + Directory.CreateDirectory(contracts); + await File.WriteAllTextAsync(Path.Combine(api, "Api.csproj"), """ + + net10.0 + + + """, _ct); + await File.WriteAllTextAsync(Path.Combine(contracts, "Contracts.csproj"), + """net10.0""", _ct); + using var runner = new RequestRunner(workspace); + runner.SetCSharpRuntime(dotnet); + var spec = CSharp(server.Url("echo"), test: "#:project src/Api/Api.csproj\n" + Fresh() + "\ntr.Test(Names.Name, () => { });"); + async Task Run(string name) + { + await File.WriteAllTextAsync(Path.Combine(contracts, "Names.cs"), + $"public static class Names\n{{\n#if LOUD\n public static string Name => \"{name.ToUpperInvariant()}\";\n#else\n public static string Name => \"{name}\";\n#endif\n}}\n", _ct); + return (await runner.SendAsync(collection, null, spec, _ct)).Scripts!; + } + + Assert.Equal(["one"], (await Run("one")).Tests.Select(t => t.Name)); + + // The code of a project that the referenced one references (src/Contracts, beside it). + Assert.Equal(["two!"], (await Run("two!")).Tests.Select(t => t.Name)); + + // MSBuild's settings in a folder above the projects (the workspace's). + await File.WriteAllTextAsync(Path.Combine(workspace.RootPath, "Directory.Build.props"), + "$(DefineConstants);LOUD", _ct); + var settings = (await runner.SendAsync(collection, null, spec, _ct)).Scripts!; + Assert.Equal(["TWO!"], settings.Tests.Select(t => t.Name)); + + // The other files of the folders above are no change. + await File.WriteAllTextAsync(Path.Combine(workspace.RootPath, "app.db"), "rows", _ct); + var again = (await runner.SendAsync(collection, null, spec, _ct)).Scripts!; + Assert.Equal(["TWO!"], again.Tests.Select(t => t.Name)); + Assert.DoesNotContain(again.Notes, n => n.StartsWith("The C# scripts were built", StringComparison.Ordinal)); + } + + [Fact] + public async Task A_project_reached_through_a_symbolic_link_builds_with_the_projects_it_references() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "Creating symbolic links needs Developer Mode or an administrator on Windows."); + var dotnet = TestCSharp.Require(); + await using var server = await EchoServer.StartAsync(); + var real = TestFiles.NewTempDirectory(); + var contracts = Path.Combine(real, "src", "Contracts"); + Directory.CreateDirectory(Path.Combine(real, "src", "Api")); + Directory.CreateDirectory(contracts); + await File.WriteAllTextAsync(Path.Combine(real, "src", "Api", "Api.csproj"), """ + + net10.0 + + + """, _ct); + await File.WriteAllTextAsync(Path.Combine(contracts, "Contracts.csproj"), + """net10.0""", _ct); + var link = Path.Combine(TestFiles.NewTempDirectory(), "workspace"); + Directory.CreateSymbolicLink(link, real); + var workspace = ApiWorkspace.Open(link); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + runner.SetCSharpRuntime(dotnet); + async Task Run(string name) + { + await File.WriteAllTextAsync(Path.Combine(contracts, "Names.cs"), $"public static class Names {{ public static string Name => {name}; }}", _ct); + var spec = CSharp(server.Url("echo"), test: "#:project src/Api/Api.csproj\n" + Fresh() + "\ntr.Test(Names.Name, () => { });"); + return (await runner.SendAsync(collection, null, spec, _ct)).Scripts!; + } + + // On Linux and macOS (where /var and /tmp are links), NuGet leaves out what a project references when the path to it + // goes through a link: the scripts would not know Names, from src/Contracts. + var built = await Run("\"one\""); + Assert.True(built.Succeeded, built.Describe()); + Assert.Equal(["one"], built.Tests.Select(t => t.Name)); + + // An error in those projects names the file in the workspace, as without the link. + Assert.Contains("(src/Contracts/Names.cs, line 1, column ", (await Run("one")).Error!.Message, StringComparison.Ordinal); + } + [Fact] public async Task The_dotnet_sdk_is_found_and_must_be_dotnet_10_or_later() { var dotnet = TestCSharp.Require(); - var (ok, message) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.CSharp, dotnet, Path.GetTempPath(), _ct); + var (ok, message) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.CSharp, dotnet, _ct); Assert.True(ok, message); Assert.Matches(@"^\.NET SDK \d+\.\d+\.\d+\S* · ", message); - var (missing, why) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.CSharp, "no-such-dotnet-here", Path.GetTempPath(), _ct); + var (missing, why) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.CSharp, "no-such-dotnet-here", _ct); Assert.False(missing); Assert.Contains("could not be started", why, StringComparison.Ordinal); Assert.NotNull(await ScriptRuntimeLocator.FindAsync(ScriptLanguage.CSharp, TestFiles.NewTempDirectory(), r => r, _ct)); @@ -280,5 +663,17 @@ public void Scripts_become_methods_of_one_program_with_their_directives_on_top() Assert.Contains($"#line 1 \"termrest-script-{id}\"\n\n\n\n// a comment\nusing var stream = new MemoryStream();\nConsole.WriteLine(1);\n#line default", program, StringComparison.Ordinal); Assert.Equal(id, CSharpWorkerCode.ScriptIdOf($"C:\\cache\\source\\termrest-script-{id}")); Assert.Null(CSharpWorkerCode.ScriptIdOf("C:\\cache\\source\\termrest-scripts.cs")); + + // Global usings go before the namespaces, once each, mapped to the first script's line. + var withGlobals = CSharpWorkerCode.Generate(new Dictionary + { + ["a"] = "using System.Text;\nglobal using System.Net;\nglobal using static System.Math;", + ["b"] = "global using System.Net;", + }, workspace); + var first = withGlobals.IndexOf("\nnamespace ", StringComparison.Ordinal); + var globals = "\n#line 2 \"termrest-script-a\"\nglobal using System.Net;\n#line 3 \"termrest-script-a\"\nglobal using static System.Math;\n#line default\n"; + Assert.InRange(withGlobals.IndexOf(globals, StringComparison.Ordinal), 0, first); + Assert.Equal(1, withGlobals.Split("global using System.Net;").Length - 1); + Assert.Contains("#line 1 \"termrest-script-a\"\n using System.Text;\n", withGlobals, StringComparison.Ordinal); } } diff --git a/tests/TermRest.Core.Tests/CertificateLoaderTests.cs b/tests/TermRest.Core.Tests/CertificateLoaderTests.cs index 2979e45..89749f8 100644 --- a/tests/TermRest.Core.Tests/CertificateLoaderTests.cs +++ b/tests/TermRest.Core.Tests/CertificateLoaderTests.cs @@ -1,6 +1,8 @@ using TermRest.Core.Certificates; +using TermRest.Core.Http; using TermRest.Core.Model; using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Variables; using Xunit; namespace TermRest.Core.Tests; @@ -69,6 +71,24 @@ public void Missing_files_and_store_entries_produce_clear_errors() Assert.Contains("0011", storeError.Message, StringComparison.Ordinal); } + [Fact] + public void Files_that_cannot_be_read_produce_certificate_errors() + { + // The file exists, but another program holds it locked (or the user may not read it). + static CertificateLoadException WhileLocked(string path, Action load) + { + using var locked = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None); + return Assert.Throws(load); + } + + var pfx = WhileLocked(_pki.ClientPfxPath, () => CertificateLoader.LoadPfx(_pki.ClientPfxPath, TestPki.Passphrase)).Message; + Assert.Contains("client.pfx", pfx, StringComparison.Ordinal); + Assert.DoesNotContain("passphrase", pfx, StringComparison.Ordinal); // .NET reports the file error as a cryptographic one + Assert.Contains("client.key", WhileLocked(_pki.ClientKeyPemPath, () => CertificateLoader.LoadPem(_pki.ClientCertPemPath, _pki.ClientKeyPemPath, null)).Message, StringComparison.Ordinal); + Assert.Contains("client.pem", WhileLocked(_pki.ClientCertPemPath, () => CertificateLoader.LoadPem(_pki.ClientCertPemPath, _pki.ClientKeyPemPath, null)).Message, StringComparison.Ordinal); + Assert.Contains("ca.pem", WhileLocked(_pki.CaPemPath, () => CertificateLoader.LoadTrustBundle(_pki.CaPemPath)).Message, StringComparison.Ordinal); + } + [Fact] public void Provider_prefers_pinned_request_certificate_then_registry_and_resolves_passphrase() { @@ -119,6 +139,27 @@ public void Provider_reports_unusable_certificates_as_warnings() Assert.Contains(warnings, w => w.Contains("broken", StringComparison.Ordinal)); } + [Fact] + public void Certificates_that_share_a_name_are_cached_by_their_source() + { + using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory)); + var warnings = new List(); + LoadedCertificate Select(CertificateSpec spec) => provider.Select(new Uri("https://localhost/"), spec, _pki.Directory, s => s, warnings)!.Certificate; + var pem = new CertificateSpec { Name = "Imported from cURL", CertSrc = "client.pem", KeySrc = "client.key" }; + var pfx = new CertificateSpec { Name = "Imported from cURL", PfxSrc = "client.pfx", Passphrase = TestPki.Passphrase }; + + var first = Select(pem); + var other = Select(pfx); + Assert.Same(first, Select(pem)); + Assert.Same(other, Select(pfx)); + + File.SetLastWriteTimeUtc(_pki.ClientCertPemPath, DateTime.UtcNow.AddMinutes(1)); + var reloaded = Select(pem); + Assert.NotSame(first, reloaded); + Assert.Equal(reloaded.Certificate.Thumbprint, first.Certificate.Thumbprint); // replaced, but still usable by requests in flight + Assert.Empty(warnings); + } + [Fact] public void Trust_bundle_loads_pem_certificates() { @@ -127,5 +168,29 @@ public void Trust_bundle_loads_pem_certificates() Assert.Equal(_pki.Ca.Thumbprint, Assert.Single(bundle).Thumbprint); } + [Fact] + public void The_ca_bundle_is_parsed_once_until_its_file_changes() + { + var path = Path.Combine(_pki.Directory, "bundle.pem"); + File.Copy(_pki.CaPemPath, path); + using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory)); + var defaults = new ExecutionDefaults { CaBundlePath = path }; + PreparedRequest Prepare() => new RequestPreparer(VariableResolver.Empty, provider, defaults).Prepare(new HttpRequestSpec { Url = "https://localhost/" }, null, _pki.Directory); + + var first = Prepare().ExtraTrustedCertificates!; + Assert.Same(first, Prepare().ExtraTrustedCertificates); + + File.AppendAllText(path, "\n" + _pki.Server.ExportCertificatePem()); + var changed = Prepare().ExtraTrustedCertificates!; + Assert.NotSame(first, changed); + Assert.Equal(2, changed.Count); + Assert.Equal(_pki.Ca.Thumbprint, first[0].Thumbprint); // replaced, but still usable by requests in flight + + File.WriteAllText(path, "not a certificate"); + var broken = Prepare(); + Assert.StartsWith($"CA bundle '{path}' not loaded: ", Assert.Single(broken.Warnings), StringComparison.Ordinal); + Assert.Empty(broken.ExtraTrustedCertificates!); + } + public void Dispose() => _pki.Dispose(); } diff --git a/tests/TermRest.Core.Tests/CurlImporterTests.cs b/tests/TermRest.Core.Tests/CurlImporterTests.cs index 5b9e952..4ee5b37 100644 --- a/tests/TermRest.Core.Tests/CurlImporterTests.cs +++ b/tests/TermRest.Core.Tests/CurlImporterTests.cs @@ -1,6 +1,10 @@ +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using TermRest.Core.Certificates; using TermRest.Core.Http; using TermRest.Core.Import; using TermRest.Core.Model; +using TermRest.Core.Tests.Infrastructure; using TermRest.Core.Variables; using Xunit; @@ -35,6 +39,16 @@ public void Imports_a_multi_line_bash_command() Assert.Empty(result.Warnings); } + [Fact] + public void Long_names_and_texts_are_cut_without_splitting_a_character() + { + var name = CurlImporter.Import($"curl 'https://api.example.com/{new string('a', 58)}😀tail'").SuggestedName; + Assert.Equal(new string('a', 58) + "…", name); + + var error = Assert.Throws(() => CurlImporter.Import(new string('b', 38) + "😀more and more words")); + Assert.Contains($"'{new string('b', 38)}…'", error.Message, StringComparison.Ordinal); + } + [Fact] public void Imports_chrome_copy_as_curl_bash_with_ansi_c_quoting() { @@ -108,6 +122,21 @@ public void Form_data_becomes_urlencoded_fields_with_decoded_values() Assert.DoesNotContain(spec.Headers, h => h.Key == "Content-Type"); } + [Fact] + public void Form_data_with_escapes_that_are_not_utf8_is_sent_as_typed() + { + // Copy as cURL on a page in windows-1252: decoded, %F6 would become U+FFFD, sent as %EF%BF%BD. + var preparer = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()); + var latin1 = CurlImporter.Import("curl -d 'city=K%F6ln&zip=50667' https://h/form").Spec; + var utf8 = CurlImporter.Import("curl -d 'city=K%C3%B6ln' https://h/form").Spec; + + Assert.Equal((BodyMode.Raw, "city=K%F6ln&zip=50667"), (latin1.Body.Mode, latin1.Body.Raw)); + Assert.Equal("application/x-www-form-urlencoded", Header(latin1, "Content-Type")); + Assert.Equal("city=K%F6ln&zip=50667", preparer.Prepare(latin1, null, "").Body.Describe()); + Assert.Equal(["city=Köln"], utf8.Body.UrlEncoded.Select(f => $"{f.Key}={f.Value}")); + Assert.Equal("city=K%C3%B6ln", preparer.Prepare(utf8, null, "").Body.Describe()); + } + [Fact] public void Get_moves_data_into_the_query_string() { @@ -158,6 +187,24 @@ public void Body_type_follows_the_content_type_and_curl_defaults() Assert.Equal("HEAD", CurlImporter.Import("curl -I https://h/x").Spec.Method); } + [Theory] + [InlineData("curl -T report.json https://uploads.example.com/inbox/", "https://uploads.example.com/inbox/report.json", "")] + [InlineData("curl -T report.json http://h", "http://h/report.json", "")] + [InlineData("curl -T 'sub/my report.json' https://uploads.example.com/inbox/", "https://uploads.example.com/inbox/my%20report.json", "")] + [InlineData("curl -T 'C:\\data\\a&b.json' 'https://h/in/?#top'", "https://h/in/a%26b.json#top", "")] + [InlineData("curl -T report.json '{{baseUrl}}/inbox/' --url-query a=1", "{{baseUrl}}/inbox/report.json?a=1", "a=1")] + [InlineData("curl -T report.json 'https://uploads.example.com/inbox/?x=1'", "https://uploads.example.com/inbox/?x=1", "x=1")] + [InlineData("curl -T report.json https://h/inbox", "https://h/inbox", "")] + [InlineData("curl -T report.json '{{baseUrl}}'", "{{baseUrl}}", "")] + [InlineData("curl -T - https://h/inbox/", "https://h/inbox/", "")] + public void An_upload_to_a_folder_goes_to_the_file_s_name_as_curl_sends_it(string command, string url, string query) + { + var spec = CurlImporter.Import(command).Spec; + + // curl adds the file's name to a URL whose path is empty or ends with '/' and that has no query. + Assert.Equal(("PUT", url, query), (spec.Method, spec.Url, string.Join('&', spec.QueryParams.Select(q => $"{q.Key}={q.Value}")))); + } + [Theory] [InlineData("curl -u 'ada:s3cret:x' https://h", "basic", "ada", "s3cret:x", null)] [InlineData("curl --digest -u ada:pw https://h", "digest", "ada", "pw", null)] @@ -220,6 +267,11 @@ public void Only_the_first_command_is_imported_and_unquoted_query_strings_surviv Assert.Equal("https://h/?a=1&b=2", CurlImporter.Import("curl https://h/?a=1&b=2").Spec.Url); Assert.Equal("{{baseUrl}}/users", CurlImporter.Import("curl {{baseUrl}}/users").Spec.Url); + + // Notes above a command at a prompt, as a terminal session or a README has them: detected, and imported. + const string Noted = "# list the users\n$ curl https://h/users"; + Assert.True(CurlImporter.LooksLikeCurl(Noted)); + Assert.Equal("https://h/users", CurlImporter.Import(Noted).Spec.Url); } [Fact] @@ -250,6 +302,10 @@ public void Rejects_what_is_not_a_curl_command_with_a_url(string text) [InlineData("curl.exe https://h", true)] [InlineData("https://h", false)] [InlineData("curling", false)] + [InlineData("https://api.github.com/repos/curl/curl", false)] // URLs, sent as they are + [InlineData("{{baseUrl}}/convert/curl", false)] + [InlineData("https://downloads.example.com/curl.exe", false)] + [InlineData("curl", false)] // nothing to import public void Detects_curl_commands(string text, bool expected) { Assert.Equal(expected, CurlImporter.LooksLikeCurl(text)); @@ -284,6 +340,23 @@ static IEnumerable> WithoutContentType(PreparedRequ Assert.Equal(before.StrictSsl, after.StrictSsl); } + [Theory] + [InlineData("```\nit's\n```")] + [InlineData("{\"op\":\"^\"}")] + [InlineData("a^\nb")] + public void Exported_commands_are_read_as_posix_whatever_their_values_hold(string raw) + { + var preparer = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()); + var before = preparer.Prepare(new HttpRequestSpec { Method = "POST", Url = "https://h/x", Body = new RequestBody { Mode = BodyMode.Raw, Raw = raw } }, null, ""); + + var imported = CurlImporter.Import(CurlExporter.Export(before)); + + // A backtick or caret ending a line, or a ^", inside a quoted value says nothing about the shell. + Assert.Equal(ShellDialect.Posix, imported.Dialect); + Assert.Empty(imported.Warnings); + Assert.Equal((before.Url, raw), (imported.Spec.Url, imported.Spec.Body.Raw)); + } + [Fact] public void Exported_form_requests_import_to_the_same_fields() { @@ -308,6 +381,52 @@ public void Exported_form_requests_import_to_the_same_fields() Assert.Equal(before.Body.Describe(), after.Body.Describe()); } + [Theory] + [InlineData("POST")] + [InlineData("PUT")] + public void A_request_without_a_body_comes_back_from_its_curl_command_without_a_content_type(string method) + { + // The export sends Content-Length: 0 as TermRest does, with --data-raw '' -H 'Content-Type:': the import drops curl's + // default type with it, rather than adding a typed one TermRest would then leave out with a warning. + var preparer = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()); + var curl = CurlExporter.Export(preparer.Prepare(new HttpRequestSpec { Method = method, Url = "https://h/jobs/42/cancel" }, null, ""), multiline: false); + Assert.Contains("--data-raw '' -H 'Content-Type:'", curl, StringComparison.Ordinal); + + var imported = CurlImporter.Import(curl).Spec; + var after = preparer.Prepare(imported, imported.Auth, ""); + + Assert.Equal(method, after.Method); + Assert.DoesNotContain(imported.Headers, h => h.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)); + Assert.Equal(PreparedBodyKind.None, after.Body.Kind); + Assert.Empty(after.Warnings); + + // Empty data alone (curl -d '', a common way to send an empty POST) gets no type either. + var empty = CurlImporter.Import($"curl -X {method} -d '' https://h/jobs/42/cancel").Spec; + Assert.DoesNotContain(empty.Headers, h => h.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)); + Assert.Empty(preparer.Prepare(empty, empty.Auth, "").Warnings); + } + + [Theory] + [InlineData("digest", null, "--digest -u 'ada:pw'")] + [InlineData("ntlm", "CORP", "--ntlm -u 'CORP\\ada:pw'")] + public void Challenge_credentials_are_exported_for_their_own_scheme_only(string type, string? domain, string expected) + { + var auth = new AuthSpec { Type = type }; + auth.Set("username", "ada"); + auth.Set("password", "pw"); + if (domain is not null) + { + auth.Set("domain", domain); + } + + var preparer = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()); + var curl = CurlExporter.Export(preparer.Prepare(new HttpRequestSpec { Url = "https://h/x", Auth = auth }, auth, ""), multiline: false); + + Assert.Contains(expected, curl, StringComparison.Ordinal); + var imported = CurlImporter.Import(curl).Spec.Auth!; + Assert.Equal((type, "ada", "pw", domain), (imported.Type, imported.Get("username"), imported.Get("password"), imported.Get("domain"))); + } + [Theory] [InlineData("curl -X POST 'https://api.example.com/items?x=1' \\")] [InlineData("curl -X POST \"https://api.example.com/items?x=1\" ^\r\n")] @@ -319,4 +438,345 @@ public void A_dangling_line_continuation_from_a_partial_copy_is_ignored(string c Assert.Equal(("POST", "https://api.example.com/items?x=1"), (result.Spec.Method, result.Spec.Url)); Assert.Empty(result.Warnings); } + + [Fact] + public void A_single_line_powershell_command_may_start_with_the_call_operator() + { + var result = CurlImporter.Import("& curl.exe https://h/x -H 'X-Note: it''s'"); + + Assert.Equal(ShellDialect.PowerShell, result.Dialect); + Assert.Equal(("https://h/x", "it's"), (result.Spec.Url, Header(result.Spec, "X-Note"))); + } + + [Fact] + public void A_powershell_value_that_ends_in_a_backslash_ends_at_its_quote() + { + // In PowerShell's "…" only ` escapes: \" is a backslash and the closing quote, where the other shells read a quote. + var result = CurlImporter.Import(""" + curl.exe --data-raw "C:\temp\" ` + https://h/upload + """); + + Assert.Equal(ShellDialect.PowerShell, result.Dialect); + Assert.Equal(("https://h/upload", "C:\\temp\\"), (result.Spec.Url, result.Spec.Body.Raw)); + } + + [Fact] + public void Browser_escapes_of_emoji_keep_the_character() + { + // Firefox and Chrome escape text one UTF-16 unit at a time: 😀 is \ud83d\ude00. A lone half is still dropped. + var spec = CurlImporter.Import("""curl 'https://h/x' -H $'X-Mood: \ud83d\ude00!' --data-raw $'{"e":"\ud83d\ude00","lone":"a\ud83db"}'""").Spec; + + Assert.Equal("😀!", Header(spec, "X-Mood")); + Assert.Equal("{\"e\":\"😀\",\"lone\":\"ab\"}", spec.Body.Raw); + } + + [Fact] + public void Json_data_read_from_a_file_becomes_a_file_body() + { + var file = CurlImporter.Import("curl --json @payload.json https://h/x"); + Assert.Equal(("POST", BodyMode.File, "payload.json"), (file.Spec.Method, file.Spec.Body.Mode, file.Spec.Body.FileSrc)); + Assert.Equal(("application/json", "application/json"), (Header(file.Spec, "Content-Type"), Header(file.Spec, "Accept"))); + Assert.Empty(file.Warnings); + + var typed = CurlImporter.Import("curl --json @payload.json -H 'Content-Type: application/vnd.api+json' https://h/x").Spec; + Assert.Equal("application/vnd.api+json", Header(typed, "Content-Type")); + + Assert.Contains(CurlImporter.Import("curl --json @- https://h/x").Warnings, w => w.Contains("standard input", StringComparison.Ordinal)); + Assert.Contains(CurlImporter.Import("curl --json @a.json --json '{}' https://h/x").Warnings, w => w.Contains("a.json", StringComparison.Ordinal)); + } + + [Fact] + public void Exported_commands_are_read_by_the_shell_and_curl_as_written() + { + var photo = Path.Combine(TestFiles.NewTempDirectory(), "photo.png"); + File.WriteAllBytes(photo, [1, 2, 3]); + var preparer = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()); + var prepared = preparer.Prepare(new HttpRequestSpec + { + Method = "post|sh", + Url = "https://h/upload", + Body = new RequestBody + { + Mode = BodyMode.FormData, + FormData = + [ + new() { Key = "key", Value = "@/home/u/.ssh/id_rsa", Type = "text" }, + new() { Key = "note", Value = " !f.IsFile).Select(f => $"{f.Key}={f.Value}")); + Assert.Equal(photo, Assert.Single(imported.Body.FormData, f => f.IsFile).Src); + Assert.StartsWith("curl -X PUT 'https://h/x'", CurlExporter.Export(preparer.Prepare(new HttpRequestSpec { Method = "PUT", Url = "https://h/x" }, null, ""), multiline: false), StringComparison.Ordinal); + + // curl would make three requests of this one. + var globbed = CurlExporter.Export(preparer.Prepare(new HttpRequestSpec { Url = "https://h/items?ids=[1-3]" }, null, ""), multiline: false); + Assert.StartsWith("curl --globoff 'https://h/items?ids=[1-3]'", globbed, StringComparison.Ordinal); + Assert.Equal(("https://h/items?ids=[1-3]", 0), (CurlImporter.Import(globbed).Spec.Url, CurlImporter.Import(globbed).Warnings.Count)); + } + + [Fact] + public void The_note_about_an_os_store_certificate_is_a_line_of_its_own() + { + using var key = RSA.Create(2048); + using var certificate = new CertificateRequest("CN=Ops $(id) & co", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1) + .CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + var prepared = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()).Prepare(new HttpRequestSpec { Url = "https://h/x" }, null, ""); + prepared.ClientCertificate = new ClientCertificateSelection( + new CertificateEntry { Name = "ops", Store = new StoreSource { Thumbprint = certificate.Thumbprint } }, + new LoadedCertificate { Certificate = certificate, Description = "store" }, + "registry"); + + var lines = CurlExporter.Export(prepared).Split('\n'); + + // A comment inside the command would swallow the line continuation (bash), or become curl arguments (zsh, where + // '#' starts no comment at the prompt): the subject is quoted for that case too. + Assert.Equal($"# client certificate from OS store: 'CN=Ops $(id) & co' ({certificate.Thumbprint})", lines[0]); + Assert.Equal(["curl \\", " 'https://h/x' \\", " --location --max-redirs 10 --proto-redir '=https'"], lines[1..]); + } + + [Fact] + public void Form_data_files_are_exported_so_that_curl_reads_only_them() + { + var directory = Path.Combine(TestFiles.NewTempDirectory(), "in;a,b"); + Directory.CreateDirectory(directory); + var file = Path.Combine(directory, OperatingSystem.IsWindows() ? "c;d,e.txt" : "c;d,e \"f\" \\g.txt"); + File.WriteAllText(file, "x"); + var preparer = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()); + HttpRequestSpec Upload(string name) => new() + { + Method = "POST", + Url = "https://h/upload", + Body = new RequestBody { Mode = BodyMode.FormData, FormData = [new() { Key = name, Type = "file", Src = file }] }, + }; + + var curl = CurlExporter.Export(preparer.Prepare(Upload("doc"), null, ""), multiline: false); + + // Quoted for curl, which would take a ';' in the path for a parameter and a ',' for a list of files. + Assert.Contains("-F 'doc=@\"", curl, StringComparison.Ordinal); + Assert.Equal(file, Assert.Single(CurlImporter.Import(curl).Spec.Body.FormData).Src); + + // curl ends a field's name at the first '=': with this one, it would send its own environment instead of the file. + var refused = Assert.Throws(() => CurlExporter.Export(preparer.Prepare(Upload("doc= CurlExporter.Export(preparer.Prepare(new HttpRequestSpec + { + Method = method, + Url = "https://h/_search", + Body = raw is null ? new RequestBody() : new RequestBody { Mode = BodyMode.Raw, Raw = raw, RawLanguage = "json" }, + }, null, ""), multiline: false); + + // A body makes curl send POST, unless the method is named; an empty one is no body, as in Postman. + Assert.Equal("curl 'https://h/_search'", Export("GET", null)); + Assert.Equal("curl 'https://h/_search'", Export("GET", "")); + Assert.Equal("curl -X GET 'https://h/_search' --data-raw ' ' -H 'Content-Type: application/json'", Export("GET", " ")); + Assert.Equal("GET", CurlImporter.Import(Export("GET", "{\"query\":{}}")).Spec.Method); + + // --head takes no body, and after -X HEAD curl waits for a response body: a body can't be sent. + Assert.Equal("curl --head 'https://h/_search'", Export("HEAD", "")); + Assert.Contains("HEAD", Assert.Throws(() => Export("HEAD", "{}")).Message, StringComparison.Ordinal); + } + + [Fact] + public void The_url_is_exported_as_it_is_sent() + { + var preparer = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults { FollowRedirects = false }); + var before = preparer.Prepare(new HttpRequestSpec { Url = "https://bücher.example/search", QueryParams = [new() { Key = "q", Value = "hello world" }] }, null, ""); + + var curl = CurlExporter.Export(before, multiline: false); + + // curl refuses a URL with a space, and may not know how to look up a host name that is not ASCII. + Assert.Equal("curl 'https://xn--bcher-kva.example/search?q=hello%20world'", curl); + var after = preparer.Prepare(CurlImporter.Import(curl).Spec, null, ""); + Assert.Equal((before.Uri!.IdnHost, before.Uri.PathAndQuery), (after.Uri!.IdnHost, after.Uri.PathAndQuery)); + } + + [Fact] + public void Redirects_are_not_followed_where_curl_would_send_credentials_to_other_hosts() + { + var apikey = new AuthSpec { Type = "apikey" }; + apikey.Set("key", "X-API-Key"); + apikey.Set("value", "sk-live"); + var bearer = new AuthSpec { Type = "bearer" }; + bearer.Set("token", "t0k"); + string Export(AuthSpec auth, bool follow = true, KeyValueEntry? header = null) => CurlExporter.Export( + new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults { FollowRedirects = follow }) + .Prepare(new HttpRequestSpec { Url = "https://api.example.com/files/1", Headers = header is null ? [] : [header], Auth = auth }, auth, ""), + multiline: false); + + // TermRest sends an API key (and Proxy-Authorization) to the request's own origin only; curl withholds only + // Authorization and Cookie from the hosts it is redirected to. + var curl = Export(apikey, header: new() { Key = "Proxy-Authorization", Value = "Basic cDpw" }); + + Assert.Equal( + "# redirects are not followed: curl would send 'Proxy-Authorization', 'X-API-Key' to every host it is redirected to\n" + + "curl 'https://api.example.com/files/1' -H 'Proxy-Authorization: Basic cDpw' -H 'X-API-Key: sk-live'", + curl); + Assert.True(CurlImporter.LooksLikeCurl(curl)); + Assert.Equal("sk-live", Header(CurlImporter.Import(curl).Spec, "X-API-Key")); + Assert.EndsWith(" -H 'Authorization: Bearer t0k' --location --max-redirs 10 --proto-redir '=https'", Export(bearer), StringComparison.Ordinal); + Assert.Equal("curl 'https://api.example.com/files/1' -H 'X-API-Key: sk-live'", Export(apikey, follow: false)); + } + + [Fact] + public void Redirects_change_the_method_and_keep_the_body_as_in_termrest() + { + string Export(string method, RequestBody body, bool follow = true) => CurlExporter.Export( + new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults { FollowRedirects = follow }) + .Prepare(new HttpRequestSpec { Method = method, Url = "https://h/login", Body = body }, null, ""), + multiline: false); + var form = new RequestBody { Mode = BodyMode.UrlEncoded, UrlEncoded = [new() { Key = "user", Value = "ada" }] }; + var json = new RequestBody { Mode = BodyMode.Raw, RawLanguage = "json", Raw = "{}" }; + + // The body alone makes curl send POST, and a GET without it after a 301, 302 or 303; after -X POST it would POST again. + var post = Export("POST", form); + Assert.Equal("curl 'https://h/login' --data-urlencode 'user=ada' --location --max-redirs 10 --proto-redir '=https'", post); + Assert.Equal("POST", CurlImporter.Import(post).Spec.Method); + + // TermRest keeps other methods and their body after a 301 or 302, and a GET with its body also after a 303. + Assert.Equal("curl -X PUT 'https://h/login' --data-urlencode 'user=ada' --location --max-redirs 10 --proto-redir '=https' --post301 --post302", Export("PUT", form)); + Assert.EndsWith(" --proto-redir '=https' --post301 --post302 --post303", Export("GET", json), StringComparison.Ordinal); + Assert.EndsWith(" --data-raw '{}' -H 'Content-Type: application/json'", Export("PATCH", json, follow: false), StringComparison.Ordinal); + + // A request without a body goes the same way, with Content-Length: 0, which curl sends for empty data. + Assert.Equal("curl 'https://h/login' --data-raw '' -H 'Content-Type:' --location --max-redirs 10 --proto-redir '=https'", Export("POST", new RequestBody())); + Assert.Equal( + "curl -X PUT 'https://h/login' --data-raw '' -H 'Content-Type:' --location --max-redirs 10 --proto-redir '=https' --post301 --post302", + Export("PUT", new RequestBody())); + } + + [Theory] + [InlineData("https://h/x", true, 5, " --location --max-redirs 5 --proto-redir '=https'")] + [InlineData("http://h/x", true, 5, " --location --max-redirs 5")] + [InlineData("https://h/x", true, 0, "")] + [InlineData("https://h/x", false, 5, "")] + public void Redirects_are_followed_as_far_and_where_termrest_follows_them(string url, bool follow, int max, string expected) + { + var spec = new HttpRequestSpec { Url = url, Settings = new RequestSettings { FollowRedirects = follow, MaxRedirects = max } }; + + var curl = CurlExporter.Export(new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()).Prepare(spec, null, ""), multiline: false); + + // curl would follow up to 50 redirects, also from https to http; with a limit of 0, TermRest follows none. + Assert.Equal($"curl '{url}'{expected}", curl); + var imported = CurlImporter.Import(curl); + Assert.Empty(imported.Warnings); + Assert.Equal(expected.Length > 0 ? max : null, imported.Spec.Settings.MaxRedirects); + } + + [Fact] + public void Max_redirs_minus_one_keeps_the_workspace_limit() + { + var imported = CurlImporter.Import("curl -L --max-redirs -1 https://h/x"); + + // curl's -1 is no limit, which TermRest has not; following none instead would also lose --location when exported. + Assert.Null(imported.Spec.Settings.MaxRedirects); + Assert.Equal("--max-redirs -1: curl follows any number of redirects; TermRest follows up to the workspace's maximum (Tools > Settings).", + Assert.Single(imported.Warnings)); + var prepared = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()).Prepare(imported.Spec, null, ""); + Assert.Equal("curl 'https://h/x' --location --max-redirs 10 --proto-redir '=https'", CurlExporter.Export(prepared, multiline: false)); + } + + [Fact] + public void Headers_are_exported_as_termrest_sends_them() + { + var preparer = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults { FollowRedirects = false }); + string Export(RequestBody body) => CurlExporter.Export(preparer.Prepare(new HttpRequestSpec + { + Method = "POST", + Url = "https://h/x", + Headers = + [ + new() { Key = "Content-Length", Value = "2" }, + new() { Key = "Content-Type", Value = "application/json" }, + new() { Key = "Transfer-Encoding", Value = "chunked" }, + new() { Key = "X-Empty", Value = "" }, + ], + Body = body, + }, null, ""), multiline: false); + + // TermRest computes Content-Length from the body, and sends no headers about a body it doesn't have. + var raw = Export(new RequestBody { Mode = BodyMode.Raw, RawLanguage = "json", Raw = "{\"a\":1}" }); + Assert.Equal("curl 'https://h/x' -H 'Content-Type: application/json' -H 'Transfer-Encoding: chunked' -H 'X-Empty;' --data-raw '{\"a\":1}'", raw); + Assert.Equal("curl 'https://h/x' -H 'X-Empty;' --data-raw '' -H 'Content-Type:'", Export(new RequestBody())); + + // curl would leave out 'X-Empty: ' instead of sending it empty. + Assert.Equal("", Header(CurlImporter.Import(raw).Spec, "X-Empty")); + } + + [Fact] + public void Form_data_parts_are_exported_with_the_content_types_termrest_sends() + { + var photo = Path.Combine(TestFiles.NewTempDirectory(), "photo.png"); + File.WriteAllBytes(photo, [1, 2, 3]); + var prepared = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults { FollowRedirects = false }).Prepare(new HttpRequestSpec + { + Method = "POST", + Url = "https://h/upload", + Body = new RequestBody + { + Mode = BodyMode.FormData, + FormData = + [ + new() { Key = "meta", Value = "<\"a\" \\ b", Type = "text", ContentType = "application/json" }, + new() { Key = "text", Value = "x", Type = "text", ContentType = "text/plain;charset=\"a;b\"" }, + new() { Key = "note", Value = "y", Type = "text" }, + new() { Key = "photo", Type = "file", Src = photo }, + new() { Key = "entry", Type = "file", Src = photo, ContentType = "application/atom+xml;type=entry" }, + new() { Key = "typed", Type = "file", Src = photo, ContentType = "png" }, + ], + }, + }, null, ""); + + var curl = CurlExporter.Export(prepared, multiline: false); + + // --form-string can't carry a type: typed text is "quoted" for -F, which then reads no file for a leading '<' or '@'. + // A type goes as it is typed (curl keeps a ';' in a parameter's value), and a file without one is given the type + // TermRest finds for its extension: curl knows fewer. + var path = photo.Replace("\\", "\\\\", StringComparison.Ordinal); + Assert.Contains("""-F 'meta="<\"a\" \\ b";type=application/json' -F 'text="x";type=text/plain;charset="a;b"' --form-string 'note=y' """, curl, StringComparison.Ordinal); + Assert.Contains($"""-F 'photo=@"{path}";type=image/png' -F 'entry=@"{path}";type=application/atom+xml;type=entry' -F 'typed=@"{path}";type=png'""", curl, StringComparison.Ordinal); + Assert.Equal( + ["meta=<\"a\" \\ b (application/json)", "text=x (text/plain;charset=\"a;b\")", "note=y ()", $"photo={photo} (image/png)", $"entry={photo} (application/atom+xml;type=entry)", $"typed={photo} (png)"], + CurlImporter.Import(curl).Spec.Body.FormData.Select(f => $"{f.Key}={(f.IsFile ? f.Src : f.Value)} ({f.ContentType})")); + } + + [Theory] + [InlineData("text", "text/plain; x=\"a;headers=@/etc/passwd;\"")] + [InlineData("file", "text/plain; x=\"a,/etc/passwd\"")] + [InlineData("file", "text/plain; filename=a.txt")] + [InlineData("text", "not a type")] + public void Form_data_content_types_that_curl_would_misread_are_refused(string type, string contentType) + { + var photo = Path.Combine(TestFiles.NewTempDirectory(), "photo.png"); + File.WriteAllBytes(photo, [1]); + var field = new KeyValueEntry { Key = "part", Value = "v", Type = type, Src = photo, ContentType = contentType }; + var prepared = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()).Prepare(new HttpRequestSpec + { + Method = "POST", + Url = "https://h/upload", + Body = new RequestBody { Mode = BodyMode.FormData, FormData = [field] }, + }, null, ""); + + // curl reads a ';' as the start of a setting (headers=@file reads a file) and, after a file, a ',' as another file to + // send; it ends a type at a space (TermRest sends all of it). + var refused = Assert.Throws(() => CurlExporter.Export(prepared)); + Assert.Contains("'part'", refused.Message, StringComparison.Ordinal); + } } diff --git a/tests/TermRest.Core.Tests/HistoryTests.cs b/tests/TermRest.Core.Tests/HistoryTests.cs index 2d844c5..1cc270e 100644 --- a/tests/TermRest.Core.Tests/HistoryTests.cs +++ b/tests/TermRest.Core.Tests/HistoryTests.cs @@ -1,7 +1,12 @@ +using System.Net; +using System.Text; +using System.Text.Json; using System.Text.Json.Nodes; using TermRest.Core.History; using TermRest.Core.Http; +using TermRest.Core.Json; using TermRest.Core.Model; +using TermRest.Core.Postman; using TermRest.Core.Tests.Infrastructure; using TermRest.Core.Workspace; using Xunit; @@ -104,6 +109,38 @@ public void Entries_can_be_deleted_and_cleared() Assert.Single(store.Load()); } + [Fact] + public void A_history_another_program_has_open_is_not_cleared_but_says_why() + { + if (!OperatingSystem.IsWindows()) + { + Assert.Skip("Windows only: elsewhere a file that is open can be deleted."); + } + + var store = NewStore(); + var entry = Entry("https://h/1", bodySaved: true); + store.Add(entry, [1]); + + using (File.Open(store.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) // as Get-Content -Wait follows it + { + Assert.Throws(store.Clear); + } + + // Nothing is gone: neither the entries nor their bodies. + Assert.Equal([entry.Id], store.Load().Select(e => e.Id)); + Assert.Equal([1], store.ReadBody(entry)); + + // Once the entries are gone, a body another program has open is left and the reason returned; the next Clear deletes it. + using (File.Open(Path.Combine(store.BodiesFolder, entry.Id + ".bin"), FileMode.Open, FileAccess.Read, FileShare.None)) + { + Assert.IsAssignableFrom(store.Clear()); + } + + Assert.Empty(store.Load()); + Assert.Null(store.Clear()); + Assert.False(Directory.Exists(store.BodiesFolder)); + } + [Fact] public void Each_workspace_gets_its_own_history_folder() { @@ -174,6 +211,17 @@ public async Task Runner_records_sent_requests_with_secrets_masked() Assert.Equal(("API", "Echo", "dev", 200), (entry.Collection, entry.RequestPath, entry.Environment, entry.Status)); Assert.Equal("{{base}}?q=1", entry.ReadSpec().Url); Assert.Equal("{{token}}", entry.ReadSpec().Auth!.Get("value")); + Assert.False(entry.CredentialsMasked); + Assert.False(entry.AuthInherited); + + // Auth inherited from the collection is stored with the entry, and said to be inherited. + collection.Root["auth"] = PostmanRequestMapper.WriteAuth(auth, PostmanSchemaVersion.V21); + var inheriting = collection.AddRequest(collection.RootNode, "Inherits", new HttpRequestSpec { Url = "{{base}}" }); + await runner.SendAsync(collection, inheriting, inheriting.ReadSpec(), _ct); + var inherited = runner.History.Load()[0]; + Assert.True(inherited.AuthInherited); + Assert.Equal("{{token}}", inherited.ReadSpec().Auth!.Get("value")); + Assert.True(HistoryEntry.TryParse(PostmanJson.SerializeCompact(inherited.ToJson()), out var reread) && reread.AuthInherited); // The echo server reflects the request: the stored body has the secret masked too. var storedBody = System.Text.Encoding.UTF8.GetString(runner.History.ReadBody(entry)!); @@ -183,6 +231,55 @@ public async Task Runner_records_sent_requests_with_secrets_masked() Assert.DoesNotContain("s3cr3t-token-value", File.ReadAllText(runner.History.FilePath), StringComparison.Ordinal); } + [Fact] + public async Task A_secret_is_masked_as_it_is_sent_without_its_trailing_line_break() + { + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var environment = workspace.CreateEnvironment("dev"); + + // A token pasted, or read from a file, with its line break: the header is sent without it. + environment.SetValues([new KeyValueEntry { Key = "tenant", Value = "tenant-s3cret-42\n", Type = "secret" }]); + workspace.ActiveEnvironment = environment; + var collection = workspace.CreateCollection("API"); + var node = collection.AddRequest(collection.RootNode, "Echo", new HttpRequestSpec + { + Url = server.Url("echo"), + Headers = [new() { Key = "X-Tenant", Value = "{{tenant}}" }], + }); + using var runner = new RequestRunner(workspace) { History = NewStore() }; + + var exchange = await runner.SendAsync(collection, node, node.ReadSpec(), _ct); + + Assert.Contains("tenant-s3cret-42", System.Text.Encoding.UTF8.GetString(exchange.Response!.Body), StringComparison.Ordinal); + var entry = Assert.Single(runner.History!.Load()); + Assert.Equal("***", entry.SentHeaders.Single(h => h.Key == "X-Tenant").Value); + Assert.DoesNotContain("tenant-s3cret-42", System.Text.Encoding.UTF8.GetString(runner.History.ReadBody(entry)!), StringComparison.Ordinal); + Assert.DoesNotContain("tenant-s3cret-42", File.ReadAllText(runner.History.FilePath), StringComparison.Ordinal); + } + + [Fact] + public async Task Secrets_in_the_user_info_of_a_url_are_masked_as_it_holds_them() + { + // An e-mail address as the user name: sent with its '@' encoded, as Postman sends it. + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var environment = workspace.CreateEnvironment("dev"); + environment.SetValues([ + new KeyValueEntry { Key = "username", Value = "ada@example.com", Type = "secret" }, + new KeyValueEntry { Key = "password", Value = "pa55/word", Type = "secret" }, + ]); + workspace.ActiveEnvironment = environment; + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace) { History = NewStore() }; + + var exchange = await runner.SendAsync(collection, null, new HttpRequestSpec { Url = $"http://{{{{username}}}}:{{{{password}}}}@localhost:{server.BaseUri.Port}/echo" }, _ct); + + Assert.True(exchange.IsSuccess, exchange.ErrorMessage); + Assert.Equal($"http://***:***@localhost:{server.BaseUri.Port}/echo", Assert.Single(runner.History!.Load()).Url); + Assert.DoesNotContain("example.com", File.ReadAllText(runner.History.FilePath), StringComparison.Ordinal); + } + [Fact] public async Task Runner_records_failures_but_not_unsent_or_cancelled_requests() { @@ -207,6 +304,45 @@ public async Task Runner_records_failures_but_not_unsent_or_cancelled_requests() Assert.Equal("GET http://127.0.0.1:1/", entry.Name); } + [Fact] + public async Task A_request_is_kept_with_the_environment_it_was_sent_with() + { + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var prod = workspace.CreateEnvironment("prod"); + prod.SetValues([new KeyValueEntry { Key = "base", Value = server.Url("echo/prod") }]); + var sandbox = workspace.CreateEnvironment("partner-sandbox"); + sandbox.SetValues([new KeyValueEntry { Key = "base", Value = server.Url("echo/sandbox") }]); + workspace.ActiveEnvironment = prod; + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace) { History = NewStore() }; + + // Another environment is chosen (F7) as the request goes out, and while a prepared one is on its way. + var exchange = await runner.SendAsync(collection, null, new HttpRequestSpec { Url = "{{base}}" }, _ => workspace.ActiveEnvironment = sandbox, _ct); + workspace.ActiveEnvironment = prod; + var sending = runner.SendAsync(runner.Prepare(collection, null, new HttpRequestSpec { Url = "{{base}}" }), _ct); + workspace.ActiveEnvironment = sandbox; + await sending; + + Assert.EndsWith("/echo/prod", exchange.Request.Url, StringComparison.Ordinal); + Assert.Equal(["prod", "prod"], runner.History.Load().Select(e => e.Environment)); + } + + [Fact] + public async Task A_request_is_kept_with_its_collection_s_file_which_tells_collections_of_the_same_name_apart() + { + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var json = workspace.CreateCollection("API", v3: false); + var converted = workspace.CreateCollection("API", v3: true); + using var runner = new RequestRunner(workspace) { History = NewStore() }; + + await runner.SendAsync(json, null, new HttpRequestSpec { Url = server.Url("echo") }, _ct); + await runner.SendAsync(converted, null, new HttpRequestSpec { Url = server.Url("echo") }, _ct); + + Assert.Equal([("API", "postman/collections/API"), ("API", "API.postman_collection.json")], runner.History.Load().Select(e => (e.Collection, e.CollectionFile))); + } + [Fact] public void Workspace_settings_control_recording() { @@ -224,4 +360,413 @@ public void Workspace_settings_control_recording() runner.ConfigureHistory(stateDirectory); Assert.Null(runner.History); } + + [Theory] + [InlineData(4 * 1024 * 1024)] // 4 GB: 0 bytes in int arithmetic + [InlineData(int.MaxValue)] + public void The_largest_history_sizes_keep_every_body_and_entry(int kb) + { + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + using var runner = new RequestRunner(workspace); + workspace.Settings.HistoryLimit = int.MaxValue; + workspace.Settings.HistoryResponseKb = kb; + runner.ConfigureHistory(TestFiles.NewTempDirectory()); + var history = runner.History!; + + var entry = Record(Sent(new HttpRequestSpec { Url = "https://api.example.com/x" }, "{\"id\":1}"u8.ToArray()), runner.HistoryMaxBodyBytes, out var body); + history.Add(entry, body); + File.AppendAllText(history.FilePath, "{not json\n"); // a damaged line, which compacting the history would drop + history.Add(Entry("https://h/2")); + + Assert.Equal("{\"id\":1}"u8.ToArray(), history.ReadBody(entry)); + Assert.Contains("{not json", File.ReadAllText(history.FilePath), StringComparison.Ordinal); + } + + /// A finished exchange of , built in code (no server needed). + private static HttpExchange Sent(HttpRequestSpec spec, byte[]? body = null, List>? responseHeaders = null, + string? contentType = null) + { + var request = new PreparedRequest { Url = "https://api.example.com/x", Uri = new Uri("https://api.example.com/x"), Source = new RequestSource(spec, null, null, null) }; + return new HttpExchange(request) + { + Response = new ResponseSnapshot { StatusCode = 200, ReasonPhrase = "OK", Headers = responseHeaders ?? [], Body = body ?? [], ContentType = contentType }, + }; + } + + private static HistoryEntry Record(HttpExchange exchange, int maxBodyBytes, out byte[]? body) => + HistoryEntry.Create(exchange, exchange.Request.Source!, null, maxBodyBytes, out body); + + [Fact] + public void Credentials_typed_into_the_request_are_masked_and_variables_are_kept() + { + var auth = new AuthSpec { Type = "basic" }; + auth.Set("username", "alice"); + auth.Set("password", "Hunter2Hunter2"); + var spec = new HttpRequestSpec + { + Url = "https://api.example.com/x", + Auth = auth, + Headers = + [ + new() { Key = "Authorization", Value = "Bearer eyJ-typed-token" }, + new() { Key = "Cookie", Value = "sid=typed-cookie-value" }, + new() { Key = "X-API-Key", Value = "{{apiKey}}" }, + new() { Key = "Accept", Value = "application/json" }, + ], + Certificate = new CertificateSpec { PfxSrc = "client.p12", Passphrase = "Typed-Passphrase" }, + }; + + var line = PostmanJson.SerializeCompact(Record(Sent(spec), 0, out _).ToJson()); + + foreach (var secret in (string[])["Hunter2Hunter2", "eyJ-typed-token", "typed-cookie-value", "Typed-Passphrase"]) + { + Assert.DoesNotContain(secret, line, StringComparison.Ordinal); + } + + Assert.True(HistoryEntry.TryParse(line, out var entry)); + Assert.True(entry.CredentialsMasked); + var stored = entry.ReadSpec(); + Assert.Equal(("alice", "***"), (stored.Auth!.Get("username"), stored.Auth.Get("password"))); + Assert.Equal(["Bearer ***", "sid=***", "{{apiKey}}", "application/json"], stored.Headers.Select(h => h.Value)); + Assert.Equal("***", stored.Certificate!.Passphrase); + Assert.True(HistoryEntry.HasMaskedCredentials(stored)); + stored.Auth.Set("password", "typed again"); + stored.Headers = [.. stored.Headers.Where(h => !h.Value!.EndsWith("***", StringComparison.Ordinal))]; + stored.Certificate.Passphrase = "typed again"; + Assert.False(HistoryEntry.HasMaskedCredentials(stored)); + + // Postman v2.0 maps auth parameters by name. + spec.Auth = PostmanRequestMapper.ReadAuth(JsonNode.Parse("""{"type":"basic","basic":{"username":"alice","password":"Hunter2Hunter2"}}"""), PostmanSchemaVersion.V20); + Assert.Equal("***", Record(Sent(spec), 0, out _).ReadSpec().Auth!.Get("password")); + + // A hand-written collection's number is sent as its text, and masked too; a flag holds no credential. + spec.Auth = PostmanRequestMapper.ReadAuth(JsonNode.Parse("""{"type":"jwt","jwt":[{"key":"secret","value":20250101},{"key":"isSecretBase64Encoded","value":false}]}"""), PostmanSchemaVersion.V21); + var numbers = Record(Sent(spec), 0, out _).ReadSpec().Auth!; + Assert.Equal(("***", "false"), (numbers.Get("secret"), numbers.Get("isSecretBase64Encoded"))); + + // References hold no secret: they are kept, so the request can be sent again as it is. + spec.Auth = auth; + auth.Set("password", "{{password}}"); + spec.Headers = [new() { Key = "Authorization", Value = "Bearer {{token}}" }, new() { Key = "Cookie", Value = "{{cookies}}" }]; + spec.Certificate.Passphrase = "env:CLIENT_PASSPHRASE"; + line = PostmanJson.SerializeCompact(Record(Sent(spec), 0, out _).ToJson()); + Assert.True(HistoryEntry.TryParse(line, out entry)); + Assert.False(entry.CredentialsMasked); + stored = entry.ReadSpec(); + Assert.Equal("{{password}}", stored.Auth!.Get("password")); + Assert.Equal(["Bearer {{token}}", "{{cookies}}"], stored.Headers.Select(h => h.Value)); + Assert.Equal("env:CLIENT_PASSPHRASE", stored.Certificate!.Passphrase); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void A_password_typed_into_the_url_is_masked_and_a_reference_is_kept(bool urlWasString) + { + var spec = new HttpRequestSpec { Url = "https://ada:pw@api.example.com/me?x=1", UrlWasString = urlWasString }; + var request = new PreparedRequest { Url = spec.Url, Uri = new Uri(spec.Url), Source = new RequestSource(spec, null, null, null) }; + + var line = PostmanJson.SerializeCompact(Record(new HttpExchange(request) { Response = new ResponseSnapshot { StatusCode = 200 } }, 0, out _).ToJson()); + + Assert.DoesNotContain(":pw@", line, StringComparison.Ordinal); + Assert.True(HistoryEntry.TryParse(line, out var entry)); + Assert.True(entry.CredentialsMasked); + Assert.Equal(("https://ada:***@api.example.com/me?x=1", "GET https://ada:***@api.example.com/me"), (entry.Url, entry.Name)); + var stored = entry.ReadSpec(); + Assert.Equal("https://ada:***@api.example.com/me?x=1", stored.Url); + Assert.True(HistoryEntry.HasMaskedCredentials(stored)); + stored.Url = "https://ada:typed-again@api.example.com/me"; + Assert.False(HistoryEntry.HasMaskedCredentials(stored)); + + // A reference holds no secret. + spec.Url = "https://ada:{{password}}@api.example.com/me"; + entry = Record(Sent(spec), 0, out _); + Assert.False(entry.CredentialsMasked); + Assert.Equal(spec.Url, entry.ReadSpec().Url); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void A_user_name_sent_without_a_password_is_masked_as_the_credential_it_is(bool urlWasString) + { + // Stripe's documented curl -u sk_test_…: takes the secret key as the user name, without a password; so does a URL's user info. + const string Key = "sk_test_typed-key"; + var auth = new AuthSpec { Type = "basic" }; + auth.Set("username", Key); + auth.Set("password", ""); + var v20 = PostmanRequestMapper.ReadAuth(JsonNode.Parse($$$"""{"type":"basic","basic":{"username":"{{{Key}}}"}}"""), PostmanSchemaVersion.V20); + var specs = (HttpRequestSpec[]) + [ + new() { Url = "https://api.example.com/me", Auth = auth }, + new() { Url = "https://api.example.com/me", Auth = v20 }, + new() { Url = $"https://{Key}:@api.example.com/me", UrlWasString = urlWasString }, + new() { Url = $"https://{Key}@api.example.com/me", UrlWasString = urlWasString }, + ]; + + var entries = specs.Select(spec => Record(Sent(spec), 0, out _)).ToList(); + + foreach (var entry in entries) + { + Assert.DoesNotContain(Key, PostmanJson.SerializeCompact(entry.ToJson()), StringComparison.Ordinal); + Assert.True(entry.CredentialsMasked); + Assert.True(HistoryEntry.HasMaskedCredentials(entry.ReadSpec())); + } + + Assert.Equal(("***", ""), (entries[0].ReadSpec().Auth!.Get("username"), entries[0].ReadSpec().Auth!.Get("password"))); + Assert.Equal(["https://***:@api.example.com/me", "https://***@api.example.com/me"], entries.Skip(2).Select(e => e.ReadSpec().Url)); + + // With a password, the user name is no credential; a reference holds no secret. + auth.Set("password", "{{password}}"); + Assert.Equal(Key, Record(Sent(specs[0]), 0, out _).ReadSpec().Auth!.Get("username")); + auth.Set("username", "{{stripeKey}}"); + auth.Set("password", ""); + var reference = Record(Sent(new HttpRequestSpec { Url = "https://{{stripeKey}}@api.example.com/me", Auth = auth }), 0, out _); + Assert.False(reference.CredentialsMasked); + Assert.Equal(("https://{{stripeKey}}@api.example.com/me", "{{stripeKey}}"), (reference.ReadSpec().Url, reference.ReadSpec().Auth!.Get("username"))); + } + + [Fact] + public void The_url_a_redirect_led_to_is_masked_like_the_url() + { + var spec = new HttpRequestSpec { Url = "https://ada:pw@api.example.com/old" }; + var request = new PreparedRequest { Url = spec.Url, Uri = new Uri(spec.Url), Source = new RequestSource(spec, null, null, null) }; + request.AddSecretValues(["ab&cd #+é", "P@ss^w0rd"]); + var final = new Uri("https://ada:pw@api.example.com/new?api_key=ab%26cd%20%23%2B%C3%A9&sig=P@ss^w0rd"); + + var line = PostmanJson.SerializeCompact(Record(new HttpExchange(request) { Response = new ResponseSnapshot { StatusCode = 200, FinalUri = final } }, 0, out _).ToJson()); + + // A password however short, and secret values as the URL holds them (encoded, or escaped by System.Uri). + Assert.True(HistoryEntry.TryParse(line, out var entry)); + Assert.Equal("https://ada:***@api.example.com/new?api_key=***&sig=***", entry.FinalUrl); + Assert.DoesNotContain(":pw@", line, StringComparison.Ordinal); + } + + [Fact] + public void Headers_that_recordings_redact_by_name_are_masked_too() + { + const string SubscriptionKey = "3f8a9c1e7b2d4f60a5e8c3b1d9f7e2a4"; + var exchange = Sent(new HttpRequestSpec + { + Url = "https://api.example.com/x", + Headers = + [ + new() { Key = "Ocp-Apim-Subscription-Key", Value = SubscriptionKey }, + new() { Key = "X-Functions-Key", Value = "typed-functions-key" }, + new() { Key = "api_key", Value = "{{apiKey}}" }, + ], + }, responseHeaders: [new("X-Hub-Signature-256", "sha256=response-signature")]); + exchange.SentHeaders.AddRange([new("Ocp-Apim-Subscription-Key", SubscriptionKey), new("X-Functions-Key", "typed-functions-key"), new("api_key", "resolved-api-key")]); + + var line = PostmanJson.SerializeCompact(Record(exchange, 0, out _).ToJson()); + + foreach (var secret in (string[])[SubscriptionKey, "typed-functions-key", "resolved-api-key", "response-signature"]) + { + Assert.DoesNotContain(secret, line, StringComparison.Ordinal); + } + + Assert.True(HistoryEntry.TryParse(line, out var entry)); + Assert.True(entry.CredentialsMasked); + Assert.Equal(["***", "***", "{{apiKey}}"], entry.ReadSpec().Headers.Select(h => h.Value)); + Assert.True(HistoryEntry.HasMaskedCredentials(entry.ReadSpec())); + Assert.Equal(["***", "***", "***"], entry.SentHeaders.Select(h => h.Value)); + } + + [Fact] + public void Cookies_are_masked_one_by_one_and_references_with_separators_are_kept() + { + var spec = new HttpRequestSpec + { + Url = "https://api.example.com/x", + Headers = + [ + new() { Key = "Cookie", Value = "session={{sid}}; theme={{theme}}" }, + new() { Key = "Authorization", Value = "Basic {{user}}:{{password}}" }, + new() { Key = "X-Auth-Token", Value = "{{tenant}};{{token}}" }, + ], + }; + + var entry = Record(Sent(spec), 0, out _); + + Assert.False(entry.CredentialsMasked); + Assert.Equal(["session={{sid}}; theme={{theme}}", "Basic {{user}}:{{password}}", "{{tenant}};{{token}}"], entry.ReadSpec().Headers.Select(h => h.Value)); + Assert.False(HistoryEntry.HasMaskedCredentials(entry.ReadSpec())); + + // Typed cookie values are masked; the names and the references stay. + spec.Headers = [new() { Key = "Cookie", Value = "session={{sid}}; csrftoken=typed-csrf-value; theme=dark" }]; + var typed = Record(Sent(spec), 0, out _); + + Assert.True(typed.CredentialsMasked); + var stored = typed.ReadSpec(); + Assert.Equal("session={{sid}}; csrftoken=***; theme=***", stored.Headers[0].Value); + Assert.True(HistoryEntry.HasMaskedCredentials(stored)); + stored.Headers[0].Value = "session={{sid}}; csrftoken=typed-again; theme=dark"; + Assert.False(HistoryEntry.HasMaskedCredentials(stored)); + stored.Headers[0].Value = "***"; // as entries kept before cookies were masked one by one + Assert.True(HistoryEntry.HasMaskedCredentials(stored)); + } + + [Theory] + [InlineData("bearer", "token", null)] + [InlineData("apikey", "value", "key")] + [InlineData("digest", "password", "username")] + [InlineData("oauth2", "accessToken", "tokenName")] + [InlineData("oauth2", "clientSecret", "clientId")] + [InlineData("oauth1", "tokenSecret", "consumerKey")] + [InlineData("awsv4", "secretKey", "region")] + [InlineData("hawk", "authKey", "authId")] + [InlineData("jwt", "privateKey", "algorithm")] + [InlineData("edgegrid", "clientToken", "baseURL")] + public void Auth_credentials_of_every_type_are_masked(string type, string secret, string? plain) + { + var auth = new AuthSpec { Type = type }; + auth.Set(secret, "Typed-Credential-1"); + if (plain is not null) + { + auth.Set(plain, "plain-value"); + } + + var entry = Record(Sent(new HttpRequestSpec { Url = "https://api.example.com/x", Auth = auth }), 0, out _); + + Assert.True(entry.CredentialsMasked); + Assert.Equal("***", entry.ReadSpec().Auth!.Get(secret)); + if (plain is not null) + { + Assert.Equal("plain-value", entry.ReadSpec().Auth!.Get(plain)); + } + } + + [Fact] + public void Echoed_secrets_are_masked_in_the_stored_body_whatever_its_encoding_and_wherever_it_is_cut() + { + const string Secret = "s3cr3t-token-value"; + byte[] Stored(byte[] response, int maxBytes, out bool truncated) + { + var exchange = Sent(new HttpRequestSpec { Url = "https://api.example.com/x" }, response); + exchange.Request.SecretValues.Add(Secret); + var entry = Record(exchange, maxBytes, out var body); + truncated = entry.BodyTruncated; + return body!; + } + + // UTF-8 cut by the limit inside a character ("é" is two bytes). + var cut = Stored(Encoding.UTF8.GetBytes($"{{\"echo\":\"{Secret}\",\"text\":\"{new string('é', 40)}\"}}"), 62, out var truncated); + Assert.StartsWith("{\"echo\":\"***\",\"text\":\"ééé", Encoding.UTF8.GetString(cut), StringComparison.Ordinal); + Assert.True(truncated); + + // Not UTF-8 at all. + Assert.Equal(Encoding.Latin1.GetBytes("café *** café"), Stored(Encoding.Latin1.GetBytes($"café {Secret} café"), 1024, out truncated)); + Assert.False(truncated); + + // A secret that the limit would cut is left out entirely. + Assert.Equal(new string('x', 60), Encoding.UTF8.GetString(Stored(Encoding.UTF8.GetBytes(new string('x', 60) + Secret + "yyyy"), 64, out truncated))); + Assert.True(truncated); + } + + [Fact] + public void Echoed_secrets_are_masked_in_the_stored_body_also_where_they_are_escaped() + { + // A base64 secret with "+" and "/", echoed by ASP.NET Core as \u002B and by Go with & < > as \u0026 \u003c \u003e; one + // with non-ASCII characters, echoed by Python (Flask, Django, httpbin) as lower-case \u escapes, by PHP also with "\/". + const string Secret = "Ab+cd/ef&g"; + const string Pin = "Grüße/2024"; + var echoed = $$"""{"json":{{JsonSerializer.Serialize(Secret)}},"go":"Ab+cd/ef\u0026g\u003ch\u003e","query":"{{Uri.EscapeDataString(Secret)}}","form":"{{WebUtility.UrlEncode(Secret)}}","slashes":"{{Secret.Replace("/", "\\/", StringComparison.Ordinal)}}","python":"Gr\u00fc\u00dfe/2024","php":"Gr\u00fc\u00dfe\/2024"}"""; + var exchange = Sent(new HttpRequestSpec { Url = "https://api.example.com/x" }, Encoding.UTF8.GetBytes(echoed)); + exchange.Request.SecretValues.UnionWith([Secret, Pin]); + + Record(exchange, 1024, out var body); + + Assert.Equal("""{"json":"***","go":"***","query":"***","form":"***","slashes":"***","python":"***","php":"***"}""", Encoding.UTF8.GetString(body!)); + } + + [Fact] + public void Echoed_secrets_are_masked_in_utf16_and_utf32_bodies_in_their_encoding() + { + const string Secret = "s3cr3t-token-value"; + const string Fault = "Token s3cr3t-token-value is not valid"; + byte[] Stored(byte[] response, string? contentType, int maxBytes, out bool truncated, string secret = Secret) + { + var exchange = Sent(new HttpRequestSpec { Url = "https://api.example.com/x" }, response, contentType: contentType); + exchange.Request.SecretValues.Add(secret); + var entry = Record(exchange, maxBytes, out var body); + truncated = entry.BodyTruncated; + return body!; + } + + (Encoding Encoding, string ContentType, bool Marked)[] bodies = + [ + (Encoding.Unicode, "text/xml; charset=utf-16", true), // as .NET's SOAP services answer + (Encoding.BigEndianUnicode, "text/xml; charset=\"UTF-16\"", false), // without a mark, either byte order + (Encoding.Unicode, "text/xml; charset=UTF-16;", false), // a trailing ";", which .NET can't parse + (Encoding.BigEndianUnicode, "text/xml", true), // only the mark says it + (Encoding.UTF32, "application/json; charset=utf-32", false), + (new UTF32Encoding(bigEndian: true, byteOrderMark: true), "text/plain", true), + ]; + foreach (var (encoding, contentType, marked) in bodies) + { + byte[] Bytes(string text) => marked ? [.. encoding.GetPreamble(), .. encoding.GetBytes(text)] : encoding.GetBytes(text); + + Assert.Equal(Bytes(Fault.Replace(Secret, "***", StringComparison.Ordinal)), Stored(Bytes(Fault), contentType, 1024, out var truncated)); + Assert.False(truncated); + } + + // A secret that the limit would cut is left out entirely; the body ends between characters. + var cut = Stored(Encoding.Unicode.GetBytes(new string('x', 30) + Secret + "yyyy"), "text/plain; charset=utf-16le", 64, out var cutShort); + Assert.Equal(Encoding.Unicode.GetBytes(new string('x', 30)), cut); + Assert.True(cutShort); + + // The bytes of a secret across characters are other text: "abcd" in UTF-16LE, one byte into these CJK characters. + var across = Encoding.Unicode.GetBytes("\u6141\u6200\u6300\u6400\u4100"); + Assert.Equal(across, Stored(across, "text/plain; charset=utf-16", 1024, out _, secret: "abcd")); + } + + [Fact] + public void A_body_in_a_charset_dotnet_does_not_support_is_shown_as_utf8() + { + // .NET has UTF-7 disabled: history --show, the response pane and scripts read such a body as UTF-8. + byte[] body = [.. "Hi Mom -+Jjo--! "u8, 0xE9]; + + Assert.Equal("Hi Mom -+Jjo--! \uFFFD", BodyFormatter.Format(body, "text/plain; charset=utf-7")); + } + + [Fact] + public void Response_headers_named_like_secrets_are_masked() + { + var entry = Record(Sent(new HttpRequestSpec { Url = "https://api.example.com/x" }, responseHeaders: + [ + new("X-Subject-Token", "gAAAAABk-subject-token"), + new("access-token", "devise-token-value"), + new("Set-Cookie", "sid=abc123456789; Path=/; HttpOnly"), + new("Content-Type", "application/json"), + ]), 0, out _); + + Assert.Equal(["***", "***", "sid=***; Path=/; HttpOnly", "application/json"], entry.ResponseHeaders.Select(h => h.Value)); + } + + [Fact] + public async Task Changes_wait_while_another_process_changes_the_history() + { + var store = NewStore(); + var first = Entry("https://h/1"); + store.Add(first); + var other = new HistoryStore(store.Folder); // e.g. termrest send while the UI compacts the history + var second = Entry("https://h/2", bodySaved: true); + + Task adding; + Task deleting; + using (new FileStream(Path.Combine(store.Folder, HistoryStore.LockFileName), FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) + { + adding = Task.Run(() => other.Add(second, [2]), _ct); + deleting = Task.Run(() => other.Delete(first.Id), _ct); + await Task.Delay(300, _ct); + + Assert.False(adding.IsCompleted || deleting.IsCompleted); + Assert.Equal([first.Id], store.Load().Select(e => e.Id)); + Assert.Null(store.ReadBody(second)); + } + + await Task.WhenAll(adding, deleting); + Assert.Equal([second.Id], store.Load().Select(e => e.Id)); + Assert.Equal([2], store.ReadBody(second)); + } } diff --git a/tests/TermRest.Core.Tests/HttpExecutorTests.cs b/tests/TermRest.Core.Tests/HttpExecutorTests.cs index e32b706..a467d34 100644 --- a/tests/TermRest.Core.Tests/HttpExecutorTests.cs +++ b/tests/TermRest.Core.Tests/HttpExecutorTests.cs @@ -1,3 +1,5 @@ +using System.Globalization; +using System.IO.Compression; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; @@ -29,6 +31,25 @@ private static JsonObject Json(HttpExchange exchange) return (JsonObject)PostmanJson.Parse(Encoding.UTF8.GetString(exchange.Response!.Body)); } + /// Applies a content coding; raw-deflate is deflate data without its zlib wrapper, as some servers send it. + private static byte[] Encode(string coding, byte[] data) + { + using var output = new MemoryStream(); + using (Stream encoder = coding switch + { + "gzip" or "x-gzip" => new GZipStream(output, CompressionLevel.Fastest, leaveOpen: true), + "deflate" => new ZLibStream(output, CompressionLevel.Fastest, leaveOpen: true), + "raw-deflate" => new DeflateStream(output, CompressionLevel.Fastest, leaveOpen: true), + "br" => new BrotliStream(output, CompressionLevel.Fastest, leaveOpen: true), + _ => throw new ArgumentOutOfRangeException(nameof(coding)), + }) + { + encoder.Write(data); + } + + return output.ToArray(); + } + [Fact] public async Task Sends_method_query_headers_and_json_body() { @@ -84,7 +105,7 @@ public async Task Sends_urlencoded_multipart_and_file_bodies() }), _ct)); Assert.StartsWith("multipart/form-data", multipart["headers"]!["content-type"].GetString(), StringComparison.Ordinal); Assert.Contains("file-content", multipart["body"].GetString(), StringComparison.Ordinal); - Assert.Contains("filename=upload.txt", multipart["body"].GetString(), StringComparison.Ordinal); + Assert.Contains("filename=\"upload.txt\"", multipart["body"].GetString(), StringComparison.Ordinal); var binary = Json(await executor.SendAsync(Prepare(new HttpRequestSpec { @@ -94,6 +115,161 @@ public async Task Sends_urlencoded_multipart_and_file_bodies() }), _ct)); Assert.Equal("file-content", binary["body"].GetString()); Assert.Equal("application/octet-stream", binary["headers"]!["content-type"].GetString()); + + // A path pasted with spaces around it, which the Body tab finds, is sent too. + var spaced = Json(await executor.SendAsync(Prepare(new HttpRequestSpec + { + Method = "PUT", + Url = server.Url("echo"), + Body = new RequestBody { Mode = BodyMode.File, FileSrc = $" {file} " }, + }), _ct)); + Assert.Equal("file-content", spaced["body"].GetString()); + } + + [Fact] + public async Task Form_data_names_and_file_names_are_sent_in_utf8_as_browsers_send_them() + { + await using var server = await EchoServer.StartAsync(); + var file = Path.Combine(_pki.Directory, "résumé.txt"); + await File.WriteAllTextAsync(file, "cv", _ct); + + var echo = Json(await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec + { + Method = "POST", + Url = server.Url("echo"), + Body = new RequestBody + { + Mode = BodyMode.FormData, + FormData = [new() { Key = "名前", Value = "x" }, new() { Key = "say \"hi\"\r\n", Value = "y" }, new() { Key = "cv", Type = "file", Src = file }], + }, + }), _ct)); + + // Form parsers don't decode RFC 2047 encoded-words, and RFC 7578 rules out filename*: only '"', CR and LF are escaped. + var body = echo["body"].GetString(); + Assert.Contains("Content-Disposition: form-data; name=\"名前\"\r\n", body, StringComparison.Ordinal); + Assert.Contains("Content-Disposition: form-data; name=\"say %22hi%22%0D%0A\"\r\n", body, StringComparison.Ordinal); + Assert.Contains("Content-Disposition: form-data; name=\"cv\"; filename=\"résumé.txt\"\r\n", body, StringComparison.Ordinal); + } + + [Fact] + public async Task Form_data_content_types_are_sent_as_typed() + { + await using var server = await EchoServer.StartAsync(); + var photo = Path.Combine(_pki.Directory, "cat.jpg"); + await File.WriteAllTextAsync(photo, "x", _ct); + + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec + { + Method = "POST", + Url = server.Url("echo"), + Body = new RequestBody + { + Mode = BodyMode.FormData, + FormData = [new() { Key = "photo", Type = "file", Src = photo, ContentType = "jpeg" }, new() { Key = "note", Value = "n", ContentType = "not a type" }], + }, + }), _ct); + + // As curl and Postman send them (curl -F 'photo=@cat.jpg;type=jpeg'); .NET would refuse the first. + var body = Json(exchange)["body"].GetString(); + Assert.Contains("filename=\"cat.jpg\"\r\nContent-Type: jpeg\r\n", body, StringComparison.Ordinal); + Assert.Contains("name=\"note\"\r\nContent-Type: not a type\r\n", body, StringComparison.Ordinal); + } + + [Fact] + public async Task A_form_data_file_without_a_content_type_gets_the_type_of_its_extension() + { + await using var server = await EchoServer.StartAsync(); + string Write(string name) + { + var path = Path.Combine(_pki.Directory, name); + File.WriteAllText(path, "x"); + return path; + } + + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec + { + Method = "POST", + Url = server.Url("echo"), + Body = new RequestBody + { + Mode = BodyMode.FormData, + FormData = + [ + new() { Key = "photo", Type = "file", Src = Write("photo.PNG") }, + new() { Key = "data", Type = "file", Src = Write("data.json") }, + new() { Key = "blob", Type = "file", Src = Write("blob.bin") }, + ], + }, + }), _ct); + + // As curl and Postman choose it: an upload endpoint may check it. + var body = Json(exchange)["body"].GetString(); + Assert.Contains("filename=\"photo.PNG\"\r\nContent-Type: image/png\r\n", body, StringComparison.Ordinal); + Assert.Contains("filename=\"data.json\"\r\nContent-Type: application/json\r\n", body, StringComparison.Ordinal); + Assert.Contains("filename=\"blob.bin\"\r\nContent-Type: application/octet-stream\r\n", body, StringComparison.Ordinal); + } + + [Fact] + public void A_form_data_content_type_with_a_line_break_is_refused() + { + var prepared = Prepare(new HttpRequestSpec + { + Method = "POST", + Url = "http://127.0.0.1:1/", + Body = new RequestBody { Mode = BodyMode.FormData, FormData = [new() { Key = "note", Value = "n", ContentType = "text/plain\r\nX-Injected: yes" }] }, + }); + + // Sent as typed, it would add a header to the part. + Assert.Equal("The content type of form-data field 'note' contains a line break or NUL character.", Assert.Single(prepared.Errors)); + } + + [Fact] + public async Task Files_opened_for_a_form_data_body_that_cannot_be_sent_are_closed() + { + var first = Path.Combine(_pki.Directory, "first.txt"); + var second = Path.Combine(_pki.Directory, "second.txt"); + await File.WriteAllTextAsync(first, "1", _ct); + await File.WriteAllTextAsync(second, "2", _ct); + var prepared = Prepare(new HttpRequestSpec + { + Method = "POST", + Url = "http://127.0.0.1:1/", + Body = new RequestBody { Mode = BodyMode.FormData, FormData = [new() { Key = "a", Type = "file", Src = first }, new() { Key = "b", Type = "file", Src = second }] }, + }); + File.Delete(second); // gone by the time the request is sent + + var exchange = await new HttpExecutor().SendAsync(prepared, _ct); + + Assert.Null(exchange.Response); + Assert.Contains("second.txt", exchange.ErrorMessage, StringComparison.Ordinal); + File.Delete(first); // Windows refuses while the file is still open + } + + [Fact] + public async Task A_file_another_program_has_open_for_writing_is_sent() + { + if (!OperatingSystem.IsWindows()) + { + Assert.Skip("Windows refuses to open such a file for a reader that shares it for reading only; Unix does not."); + } + + await using var server = await EchoServer.StartAsync(); + var file = Path.Combine(_pki.Directory, "report.csv"); + await File.WriteAllTextAsync(file, "a,b", _ct); + var executor = new HttpExecutor(); + + // As Excel, or a program writing a log, keeps it open. + await using var writer = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); + var binary = await executor.SendAsync(Prepare(new HttpRequestSpec { Method = "PUT", Url = server.Url("echo"), Body = new RequestBody { Mode = BodyMode.File, FileSrc = file } }), _ct); + var form = await executor.SendAsync(Prepare(new HttpRequestSpec + { + Method = "POST", + Url = server.Url("echo"), + Body = new RequestBody { Mode = BodyMode.FormData, FormData = [new() { Key = "report", Type = "file", Src = file }] }, + }), _ct); + + Assert.Equal("a,b", Json(binary)["body"].GetString()); + Assert.Contains("filename=\"report.csv\"\r\nContent-Type: application/octet-stream\r\n\r\na,b\r\n", Json(form)["body"].GetString(), StringComparison.Ordinal); } [Fact] @@ -128,6 +304,110 @@ public async Task Typed_body_files_are_checked_when_sent_and_get_their_content_t Assert.Single(prepared.Errors); // so history and recordings leave it out } + [Fact] + public async Task An_xml_body_file_in_a_legacy_encoding_is_checked_in_it_and_sent_as_it_is() + { + await using var server = await EchoServer.StartAsync(); + var file = Path.Combine(_pki.Directory, "order.xml"); + byte[] order = [.. "\n"u8]; + await File.WriteAllBytesAsync(file, order, _ct); + + // As legacy SOAP and EDI services send them: .NET knows the encoding only from its code pages. + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec + { + Method = "POST", + Url = server.Url("mirror"), + Body = new RequestBody { Mode = BodyMode.File, FileSrc = file, FileLanguage = "xml" }, + }), _ct); + + Assert.True(exchange.IsSuccess, exchange.ErrorMessage); + Assert.Equal(order, exchange.Response!.Body); + Assert.Equal("application/xml", exchange.Response.ContentType); + } + + [Fact] + public async Task A_file_that_grows_while_it_is_sent_is_sent_as_long_as_it_was() + { + var log = Path.Combine(_pki.Directory, "app.log"); + await File.WriteAllTextAsync(log, "started\n", _ct); + + // With Expect: 100-continue, the body goes when /echo reads it, after the headers: the log grows in between. + await using var server = await EchoServer.StartAsync(beforeEcho: () => File.AppendAllText(log, "more\n")); + var executor = new HttpExecutor(); + HttpRequestSpec Spec(string method, RequestBody body) => new() + { + Method = method, + Url = server.Url("echo"), + Headers = [new() { Key = "Expect", Value = "100-continue" }], + Body = body, + }; + + var binary = await executor.SendAsync(Prepare(Spec("PUT", new RequestBody { Mode = BodyMode.File, FileSrc = log })), _ct); + var form = await executor.SendAsync(Prepare(Spec("POST", new RequestBody { Mode = BodyMode.FormData, FormData = [new() { Key = "log", Type = "file", Src = log }] })), _ct); + + // As long as Content-Length said: .NET fails a request whose body is longer. + Assert.Equal("started\n", Json(binary)["body"].GetString()); + Assert.Contains("filename=\"app.log\"\r\nContent-Type: application/octet-stream\r\n\r\nstarted\nmore\n\r\n--", Json(form)["body"].GetString(), StringComparison.Ordinal); + } + + [Fact] + public async Task An_empty_body_is_no_body_and_has_no_content_type_as_in_postman() + { + await using var server = await EchoServer.StartAsync(); + var executor = new HttpExecutor(); + var variables = new VariableResolver([new DictionaryScope("env", new Dictionary { ["payload"] = "" })]); + var typedJson = new KeyValueEntry { Key = "Content-Type", Value = "application/json" }; + (string Case, RequestBody Body, KeyValueEntry? Header, string? Warning)[] cases = + [ + ("raw", new() { Mode = BodyMode.Raw, RawLanguage = "json", Raw = "" }, null, null), + ("raw, empty once resolved", new() { Mode = BodyMode.Raw, RawLanguage = "json", Raw = "{{payload}}" }, null, null), + ("raw, Content-Type typed", new() { Mode = BodyMode.Raw, RawLanguage = "json", Raw = "" }, typedJson, "'Content-Type' was not sent because the request has no body."), + ("urlencoded", new() { Mode = BodyMode.UrlEncoded, UrlEncoded = [new() { Key = "a", Value = "1", Enabled = false }, new() { Key = "", Value = "x" }] }, null, null), + ("form-data", new() { Mode = BodyMode.FormData, FormData = [new() { Key = "a", Value = "1", Enabled = false }] }, null, null), + ("file", new() { Mode = BodyMode.File, FileLanguage = "json" }, null, "No file is chosen for the body: the request is sent without one."), + ]; + + foreach (var (name, body, header, warning) in cases) + { + var prepared = Prepare(new HttpRequestSpec { Method = "POST", Url = server.Url("echo"), Headers = header is null ? [] : [header], Body = body }, variables: variables); + + var echo = Json(await executor.SendAsync(prepared, _ct)); + + // Some servers refuse an empty JSON body (Fastify answers 400). + Assert.True(echo["headers"]!["content-type"] is null, name); + Assert.Equal((name, "", warning), (name, echo["body"].GetString(), prepared.Warnings.SingleOrDefault())); + Assert.Equal($"curl '{server.Url("echo")}' --data-raw '' -H 'Content-Type:' --location --max-redirs 10", CurlExporter.Export(prepared, multiline: false)); + } + } + + [Fact] + public async Task A_request_without_a_body_is_exported_with_the_content_length_it_is_sent_with() + { + await using var server = await EchoServer.StartAsync(); + var executor = new HttpExecutor(); + var url = server.Url("echo"); + (string Method, string Curl)[] cases = + [ + ("POST", $"curl '{url}' --data-raw '' -H 'Content-Type:'"), + ("PUT", $"curl -X PUT '{url}' --data-raw '' -H 'Content-Type:'"), + ("PURGE", $"curl -X PURGE '{url}' --data-raw '' -H 'Content-Type:'"), + ("DELETE", $"curl -X DELETE '{url}'"), + ("OPTIONS", $"curl -X OPTIONS '{url}'"), + ("GET", $"curl '{url}'"), + ]; + + foreach (var (method, curl) in cases) + { + var prepared = Prepare(new HttpRequestSpec { Method = method, Url = url, Settings = new RequestSettings { FollowRedirects = false } }); + + var echo = Json(await executor.SendAsync(prepared, _ct)); + + // curl sends Content-Length: 0 only with (empty) data; IIS answers a POST without one with 411 Length Required. + Assert.Equal(curl, CurlExporter.Export(prepared, multiline: false)); + Assert.Equal((method, curl.Contains("--data-raw", StringComparison.Ordinal) ? "0" : null), (method, echo["headers"]!["content-length"]?.GetString())); + } + } + [Fact] public async Task Applies_auth_helpers() { @@ -149,6 +429,299 @@ public async Task Applies_auth_helpers() var bearer = new AuthSpec { Type = "bearer" }; bearer.Set("token", "t0k"); Assert.Equal("Bearer t0k", Json(await executor.SendAsync(Prepare(spec, auth: bearer), _ct))["headers"]!["authorization"].GetString()); + + // As in Postman, an empty token (one a login request's script sets later) adds no header: the request's own stays, + // and credentials in the URL apply. + var empty = new AuthSpec { Type = "bearer" }; + empty.Set("token", "{{token}}"); + var variables = new VariableResolver([new DictionaryScope("env", new Dictionary { ["token"] = "" })]); + var typed = new HttpRequestSpec { Url = server.Url("echo"), Headers = [new() { Key = "Authorization", Value = "Token abc" }] }; + var prepared = Prepare(typed, auth: empty, variables: variables); + Assert.Equal("Token abc", Json(await executor.SendAsync(prepared, _ct))["headers"]!["authorization"].GetString()); + Assert.Equal(["Bearer token is empty: the request was sent without it."], prepared.Warnings); + var withUser = Prepare(new HttpRequestSpec { Url = server.Url("echo").Replace("://", "://ada:secret@", StringComparison.Ordinal) }, auth: empty, variables: variables); + Assert.Equal("Basic YWRhOnNlY3JldA==", Json(await executor.SendAsync(withUser, _ct))["headers"]!["authorization"].GetString()); + } + + [Fact] + public async Task An_api_key_or_token_in_the_query_is_encoded_and_replaces_a_parameter_of_the_same_name() + { + await using var server = await EchoServer.StartAsync(); + var executor = new HttpExecutor(); + var apikey = new AuthSpec { Type = "apikey" }; + apikey.Set("key", "api_key"); + apikey.Set("value", "ab&cd #+é"); + apikey.Set("in", "query"); + var oauth = new AuthSpec { Type = "oauth2" }; + oauth.Set("accessToken", "t0k+en/="); + oauth.Set("addTokenTo", "queryParams"); + + var prepared = Prepare(new HttpRequestSpec { Url = server.Url("echo?api_key=old&page=2") }, auth: apikey); + var query = Json(await executor.SendAsync(prepared, _ct))["query"]!; + + Assert.Equal(("ab&cd #+é", "2"), (query["api_key"].GetString(), query["page"].GetString())); + Assert.Equal("The auth helper replaced the 'api_key' query parameter.", Assert.Single(prepared.Warnings)); + Assert.Equal(server.Url("echo?page=2&api_key=***"), prepared.Redact(prepared.Url)); // the URL as the history keeps it + Assert.Equal("t0k+en/=", Json(await executor.SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("echo") }, auth: oauth), _ct))["query"]!["access_token"].GetString()); + } + + [Fact] + public async Task A_hash_in_a_path_or_query_value_and_a_question_mark_in_a_path_variable_are_sent_as_part_of_the_value() + { + await using var server = await EchoServer.StartAsync(); + var executor = new HttpExecutor(); + var variables = new VariableResolver([new DictionaryScope("env", new Dictionary { ["tag"] = "#news", ["name"] = "report#1.pdf" })]); + + // The URL would end its query at a '#': what follows would not be sent. + var query = Json(await executor.SendAsync(Prepare(new HttpRequestSpec + { + Url = server.Url("echo/search"), + QueryParams = [new() { Key = "q", Value = "{{tag}}" }, new() { Key = "color", Value = "#ff0000" }, new() { Key = "page", Value = "2" }], + }, variables: variables), _ct)); + Assert.Equal("?q=%23news&color=%23ff0000&page=2", query["rawQuery"].GetString()); + + // And its path at a '#' or, in a path variable, a '?'; a {{variable}} in the path keeps a '?' (it starts the query, as in Postman). + var prepared = Prepare(new HttpRequestSpec + { + Url = server.BaseUri + "echo/files/:file/{{name}}?page=2", + PathVariables = [new() { Key = "file", Value = "what?#1" }], + QueryParams = [new() { Key = "page", Value = "2" }], + }, variables: variables); + var path = Json(await executor.SendAsync(prepared, _ct)); + Assert.Equal(server.Url("echo/files/what%3F%231/report%231.pdf?page=2"), prepared.Uri!.AbsoluteUri); + Assert.Equal(("/echo/files/what?#1/report#1.pdf", "?page=2"), (path["path"].GetString(), path["rawQuery"].GetString())); + } + + [Theory] + [InlineData("localhost:{0}/echo/oauth/authorize?redirect_uri=http://localhost:4200/cb")] + [InlineData("127.0.0.1:{0}/echo/login?next=https://app.example.com/")] + public async Task A_url_without_a_scheme_is_sent_as_http_also_when_its_query_holds_a_url(string template) + { + await using var server = await EchoServer.StartAsync(); + var url = string.Format(CultureInfo.InvariantCulture, template, server.BaseUri.Port); + var prepared = Prepare(new HttpRequestSpec { Url = url }); + + var echo = Json(await new HttpExecutor().SendAsync(prepared, _ct)); + + // As curl and Postman send it: a "://" in the query names no scheme. + Assert.Equal("http://" + url, prepared.Uri!.AbsoluteUri); + Assert.Equal(url[url.IndexOf('/', StringComparison.Ordinal)..], echo["path"].GetString() + echo["rawQuery"].GetString()); + Assert.Equal($"curl 'http://{url}' --location --max-redirs 10", CurlExporter.Export(prepared, multiline: false)); + } + + [Fact] + public async Task Credentials_in_the_url_are_sent_as_basic_auth_unless_the_request_has_its_own() + { + await using var server = await EchoServer.StartAsync(); + await using var other = await EchoServer.StartAsync(); + var executor = new HttpExecutor(); + var url = $"http://ada:p%40ss%20w0rd@localhost:{server.BaseUri.Port}/echo"; + + var prepared = Prepare(new HttpRequestSpec { Url = url }); + var echo = Json(await executor.SendAsync(prepared, _ct)); + + Assert.Equal("Basic " + Convert.ToBase64String("ada:p@ss w0rd"u8), echo["headers"]!["authorization"].GetString()); + Assert.Equal("Basic (from the URL)", prepared.AuthDescription); + Assert.Equal($"http://ada:***@localhost:{server.BaseUri.Port}/echo", prepared.Redact(prepared.Url)); // the URL as the history keeps it + + // A typed Authorization header, or an auth helper, comes first. + var bearer = new AuthSpec { Type = "bearer" }; + bearer.Set("token", "t0k"); + var typed = Json(await executor.SendAsync(Prepare(new HttpRequestSpec { Url = url, Headers = [new() { Key = "Authorization", Value = "Bearer typed" }] }), _ct)); + Assert.Equal("Bearer typed", typed["headers"]!["authorization"].GetString()); + Assert.Equal("Bearer t0k", Json(await executor.SendAsync(Prepare(new HttpRequestSpec { Url = url }, auth: bearer), _ct))["headers"]!["authorization"].GetString()); + + // Like other credentials, they stay with the request's origin. + var redirect = url.Replace("/echo", "/redirect-to?url=" + Uri.EscapeDataString(other.Url("echo")), StringComparison.Ordinal); + Assert.Null(Json(await executor.SendAsync(Prepare(new HttpRequestSpec { Url = redirect }), _ct))["headers"]!["authorization"]); + } + + [Theory] + [InlineData("Ab1/Xy9zQ")] // in base64, and in passwords + [InlineData("S3cr#t?!x")] + [InlineData("p@ss\\word")] + public async Task Variables_in_the_user_info_of_a_url_are_sent_whatever_they_hold(string password) + { + // As Postman sends them: a '/', '#' or '?' would otherwise end the authority, a '@' start the host. + await using var server = await EchoServer.StartAsync(); + var variables = new VariableResolver([new DictionaryScope("env", new Dictionary { ["user"] = "deploy", ["pw"] = password })]); + + var prepared = Prepare(new HttpRequestSpec { Url = $"http://{{{{user}}}}:{{{{pw}}}}@localhost:{server.BaseUri.Port}/echo" }, variables: variables); + var echo = Json(await new HttpExecutor().SendAsync(prepared, _ct)); + var invalid = Prepare(new HttpRequestSpec { Url = "https://deploy:{{pw}}@{{host}}/v1" }, variables: variables); + + Assert.Equal("Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("deploy:" + password)), echo["headers"]!["authorization"].GetString()); + Assert.Equal("/echo", echo["path"].GetString()); + Assert.Equal("'https://deploy:***@{{host}}/v1' is not a valid http(s) URL.", Assert.Single(invalid.Errors)); + } + + [Fact] + public async Task A_url_a_redirect_leads_to_does_not_take_the_credentials_of_the_request_url() + { + await using var server = await EchoServer.StartAsync(); + var url = $"http://ada:pw@localhost:{server.BaseUri.Port}/redirect-to?url=%2Fecho"; + var followed = Prepare(new HttpRequestSpec { Url = url }); + var stopped = Prepare(new HttpRequestSpec { Url = url, Settings = new RequestSettings { MaxRedirects = 0 } }); + + var exchange = await new HttpExecutor().SendAsync(followed, _ct); + await new HttpExecutor().SendAsync(stopped, _ct); + + // They are sent as an Authorization header, to the request's origin; where the redirect is shown, kept or recorded, + // the target would otherwise hold the password. + Assert.Equal("Basic " + Convert.ToBase64String("ada:pw"u8), Json(exchange)["headers"]!["authorization"].GetString()); + Assert.Equal(server.Url("echo"), exchange.Response!.FinalUri!.AbsoluteUri); + Assert.Equal($"The redirect to {server.Url("echo")} was not followed: it would exceed the maximum number of redirects (0).", Assert.Single(stopped.Warnings)); + } + + [Fact] + public async Task A_redirect_to_a_url_that_is_not_http_is_reported_without_its_password() + { + await using var server = await EchoServer.StartAsync(); + var prepared = Prepare(new HttpRequestSpec { Url = server.Url("redirect-to?url=" + Uri.EscapeDataString("ftp://ada:pw12@files.example.com/report.csv")) }); + + var exchange = await new HttpExecutor().SendAsync(prepared, _ct); + + Assert.Equal(302, exchange.Response!.StatusCode); + Assert.Equal("The redirect to ftp://ada:***@files.example.com/report.csv was not followed: TermRest follows only http and https URLs.", Assert.Single(prepared.Warnings)); + } + + [Fact] + public async Task Header_values_with_line_breaks_are_not_sent_and_a_trailing_line_break_is_dropped() + { + await using var server = await EchoServer.StartAsync(); + var variables = new VariableResolver([new DictionaryScope("env", new Dictionary + { + ["injected"] = "x\r\nX-Injected: yes", + ["nul"] = "x\0y", + ["pasted"] = "t0k\r\n", + })]); + var bearer = new AuthSpec { Type = "bearer" }; + bearer.Set("token", "{{injected}}"); + + var header = Prepare(new HttpRequestSpec { Url = server.Url("echo"), Headers = [new() { Key = "X-Test", Value = "{{injected}}" }] }, variables: variables); + var nul = Prepare(new HttpRequestSpec { Url = server.Url("echo"), Headers = [new() { Key = "X-Test", Value = "{{nul}}" }] }, variables: variables); + var auth = Prepare(new HttpRequestSpec { Url = server.Url("echo") }, auth: bearer, variables: variables); + + Assert.Equal("Header 'X-Test' contains a line break or NUL character.", Assert.Single(header.Errors)); + Assert.Single(nul.Errors); + Assert.Equal("Header 'Authorization' contains a line break or NUL character.", Assert.Single(auth.Errors)); + var refused = await new HttpExecutor().SendAsync(header, _ct); + Assert.Null(refused.Response); + Assert.Null(refused.Timing.Connect); + + bearer.Set("token", "{{pasted}}"); + var pasted = Prepare(new HttpRequestSpec { Url = server.Url("echo") }, auth: bearer, variables: variables); + Assert.Equal("Bearer t0k", Json(await new HttpExecutor().SendAsync(pasted, _ct))["headers"]!["authorization"].GetString()); + } + + [Fact] + public async Task Header_values_that_are_not_ascii_are_sent_in_utf8() + { + await using var server = await EchoServer.StartAsync(); + var file = Path.Combine(_pki.Directory, "cv.pdf"); + await File.WriteAllTextAsync(file, "cv", _ct); + var variables = new VariableResolver([new DictionaryScope("env", new Dictionary { ["name"] = "Zoë" })]); + + // As curl sends them; .NET would refuse the request. + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec + { + Method = "PUT", + Url = server.Url("echo"), + Headers = + [ + new() { Key = "X-User", Value = "José" }, + new() { Key = "X-Name", Value = "{{name}}" }, + new() { Key = "Content-Disposition", Value = "attachment; filename=\"résumé.pdf\"" }, + ], + Body = new RequestBody { Mode = BodyMode.File, FileSrc = file }, + }, variables: variables), _ct); + + var headers = Json(exchange)["headers"]!; + Assert.Equal(("José", "Zoë", "attachment; filename=\"résumé.pdf\""), + (headers["x-user"].GetString(), headers["x-name"].GetString(), headers["content-disposition"].GetString())); + Assert.Contains(new KeyValuePair("X-Name", "Zoë"), exchange.SentHeaders); + } + + [Fact] + public async Task Cookies_from_the_jar_go_back_with_the_bytes_the_server_sent() + { + // One value in UTF-8 and one in Latin-1 (as Node or Python write a non-ASCII header); .NET reads both as Latin-1. + using var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var noContent = "HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n"u8.ToArray(); + var served = ServeRawAsync(listener, + Encoding.Latin1.GetBytes("HTTP/1.1 204 No Content\r\nSet-Cookie: u=Zo\u00C3\u00AB\r\nSet-Cookie: l=caf\u00E9\r\nConnection: close\r\n\r\n"), + noContent, + noContent); + var executor = new HttpExecutor(); + var url = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/"; + + await executor.SendAsync(Prepare(new HttpRequestSpec { Url = url }), _ct); + await executor.SendAsync(Prepare(new HttpRequestSpec { Url = url }), _ct); + await executor.SendAsync(Prepare(new HttpRequestSpec { Url = url, Headers = [new() { Key = "Cookie", Value = "t=✓" }] }), _ct); + var received = await served; + + var second = Encoding.Latin1.GetString(received[1]); + Assert.Contains("u=Zo\u00C3\u00AB", second, StringComparison.Ordinal); + Assert.Contains("l=caf\u00E9", second, StringComparison.Ordinal); + + // A Cookie header typed with characters that are not ASCII is sent in UTF-8, as every header is. + Assert.Contains("t=\u00E2\u009C\u0093", Encoding.Latin1.GetString(received[2]), StringComparison.Ordinal); + } + + /// Answers each connection to with the next response; returns the requests received. + private Task> ServeRawAsync(System.Net.Sockets.TcpListener listener, params byte[][] responses) => Task.Run(async () => + { + var received = new List(); + foreach (var response in responses) + { + using var connection = await listener.AcceptTcpClientAsync(_ct); + var stream = connection.GetStream(); + var request = new byte[16384]; + var read = 0; + int count; + while (request.AsSpan(0, read).IndexOf("\r\n\r\n"u8) < 0 && (count = await stream.ReadAsync(request.AsMemory(read), _ct)) > 0) + { + read += count; + } + + received.Add(request[..read]); + await stream.WriteAsync(response, _ct); + } + + return received; + }, _ct); + + [Theory] + [InlineData("digest")] + [InlineData("ntlm")] + public async Task Challenge_credentials_are_never_sent_as_basic(string type) + { + await using var server = await EchoServer.StartAsync(); + var auth = new AuthSpec { Type = type }; + auth.Set("username", "ada"); + auth.Set("password", "secret"); + + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("challenge/basic") }, auth: auth), _ct); + + Assert.Equal(401, exchange.Response!.StatusCode); + } + + [Fact] + public async Task Digest_credentials_answer_digest_challenges_also_after_a_redirect_on_the_same_origin() + { + await using var server = await EchoServer.StartAsync(); + var executor = new HttpExecutor(); + var digest = new AuthSpec { Type = "digest" }; + digest.Set("username", "ada"); + digest.Set("password", "secret"); + + var direct = await executor.SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("challenge/digest") }, auth: digest), _ct); + var redirected = await executor.SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("redirect-to?url=%2Fchallenge%2Fdigest") }, auth: digest), _ct); + + Assert.Equal((200, 200), (direct.Response?.StatusCode, redirected.Response?.StatusCode)); + Assert.StartsWith("Digest username=\"ada\"", Json(direct)["headers"]!["authorization"].GetString(), StringComparison.Ordinal); + Assert.StartsWith("Digest username=\"ada\"", Json(redirected)["headers"]!["authorization"].GetString(), StringComparison.Ordinal); } [Fact] @@ -167,6 +740,176 @@ public async Task Follows_redirects_and_keeps_cookies() Assert.Contains("session=abc123", Json(await executor.SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("echo") }), _ct))["headers"]!["cookie"].GetString(), StringComparison.Ordinal); } + [Fact] + public async Task A_redirect_to_another_origin_drops_credentials_and_keeps_other_headers() + { + await using var origin = await EchoServer.StartAsync(); + await using var other = await EchoServer.StartAsync(); + var apikey = new AuthSpec { Type = "apikey" }; + apikey.Set("key", "X-API-Key"); + apikey.Set("value", "k1"); + var spec = new HttpRequestSpec + { + Url = origin.Url("redirect-to?url=" + Uri.EscapeDataString(other.Url("echo"))), + Headers = + [ + new() { Key = "Authorization", Value = "Bearer typed" }, + new() { Key = "Cookie", Value = "typed=1" }, + new() { Key = "Host", Value = $"localhost:{origin.BaseUri.Port}" }, + new() { Key = "X-Custom", Value = "kept" }, + ], + }; + + var exchange = await new HttpExecutor().SendAsync(Prepare(spec, auth: apikey), _ct); + + var headers = Json(exchange)["headers"]!; + Assert.Null(headers["x-api-key"]); + Assert.Null(headers["authorization"]); + Assert.Null(headers["cookie"]); + Assert.Equal($"localhost:{other.BaseUri.Port}", headers["host"].GetString()); + Assert.Equal("kept", headers["x-custom"].GetString()); + Assert.Equal(other.Url("echo"), exchange.Response!.FinalUri?.ToString()); + Assert.Equal("k1", exchange.SentHeaders.Single(h => h.Key == "X-API-Key").Value); // what was sent to the origin + Assert.True(exchange.Timing is { Connect: not null, Waiting: not null, Download: not null }, exchange.Timing.ToString()); + } + + [Theory] + [InlineData(307)] + [InlineData(308)] + public async Task A_redirect_on_the_same_origin_keeps_credentials_cookies_method_and_body(int status) + { + await using var server = await EchoServer.StartAsync(); + var bearer = new AuthSpec { Type = "bearer" }; + bearer.Set("token", "t0k"); + var spec = new HttpRequestSpec + { + Method = "POST", + Url = server.Url($"redirect-to?status={status}&cookie=hop%3D1&url=%2Fecho%2Fitems%2F"), + Headers = [new() { Key = "Cookie", Value = "typed=1" }], + Body = new RequestBody { Mode = BodyMode.Raw, RawLanguage = "json", Raw = "{\"a\":1}" }, + }; + + var exchange = await new HttpExecutor().SendAsync(Prepare(spec, auth: bearer), _ct); + + var echo = Json(exchange); + Assert.Equal(("POST", "/echo/items/", "{\"a\":1}"), (echo["method"].GetString(), echo["path"].GetString(), echo["body"].GetString())); + Assert.Equal("Bearer t0k", echo["headers"]!["authorization"].GetString()); + Assert.Contains("typed=1", echo["headers"]!["cookie"].GetString(), StringComparison.Ordinal); + Assert.Contains("hop=1", echo["headers"]!["cookie"].GetString(), StringComparison.Ordinal); + Assert.Equal(server.Url("echo/items/"), exchange.Response!.FinalUri?.ToString()); + } + + [Theory] + [InlineData(301, "POST", "GET")] + [InlineData(302, "POST", "GET")] + [InlineData(303, "PUT", "GET")] + [InlineData(302, "PUT", "PUT")] + public async Task Redirects_change_the_method_like_browsers(int status, string method, string expected) + { + await using var server = await EchoServer.StartAsync(); + var spec = new HttpRequestSpec + { + Method = method, + Url = server.Url($"redirect-to?status={status}&url=%2Fecho"), + Body = new RequestBody { Mode = BodyMode.Raw, RawLanguage = "json", Raw = "{\"a\":1}" }, + }; + + var echo = Json(await new HttpExecutor().SendAsync(Prepare(spec), _ct)); + + Assert.Equal(expected, echo["method"].GetString()); + Assert.Equal(expected == method ? "{\"a\":1}" : "", echo["body"].GetString()); + Assert.Equal(expected == method, echo["headers"]!["content-type"] is not null); + } + + [Fact] + public async Task A_307_redirect_sends_a_file_body_again() + { + await using var server = await EchoServer.StartAsync(); + var file = Path.Combine(_pki.Directory, "upload.bin"); + await File.WriteAllTextAsync(file, "file-content", _ct); + var spec = new HttpRequestSpec { Method = "PUT", Url = server.Url("redirect-to?status=307&url=%2Fecho"), Body = new RequestBody { Mode = BodyMode.File, FileSrc = file } }; + + var echo = Json(await new HttpExecutor().SendAsync(Prepare(spec), _ct)); + + Assert.Equal(("PUT", "file-content"), (echo["method"].GetString(), echo["body"].GetString())); + } + + [Fact] + public async Task A_typed_transfer_encoding_is_left_out_when_the_request_has_no_body() + { + await using var server = await EchoServer.StartAsync(); + var executor = new HttpExecutor(); + HttpRequestSpec Spec(string method, string path, RequestBody body) => new() + { + Method = method, + Url = server.Url(path), + Headers = [new() { Key = "Transfer-Encoding", Value = "chunked" }], + Body = body, + }; + var json = new RequestBody { Mode = BodyMode.Raw, RawLanguage = "json", Raw = "{\"a\":1}" }; + + var chunked = Json(await executor.SendAsync(Prepare(Spec("PUT", "echo", json)), _ct)); + Assert.Equal(("chunked", "{\"a\":1}"), (chunked["headers"]!["transfer-encoding"].GetString(), chunked["body"].GetString())); + + // A 302 turns the POST into a GET without its body. + var redirected = Json(await executor.SendAsync(Prepare(Spec("POST", "redirect-to?status=302&url=%2Fecho", json)), _ct)); + Assert.Equal(("GET", ""), (redirected["method"].GetString(), redirected["body"].GetString())); + Assert.Null(redirected["headers"]!["transfer-encoding"]); + + var get = Prepare(Spec("GET", "echo", new RequestBody())); + Assert.Null(Json(await executor.SendAsync(get, _ct))["headers"]!["transfer-encoding"]); + Assert.Equal("'Transfer-Encoding' was not sent because the request has no body.", Assert.Single(get.Warnings)); + } + + [Fact] + public async Task Max_redirects_limits_the_redirects_followed() + { + await using var server = await EchoServer.StartAsync(); + var executor = new HttpExecutor(); + var twice = server.Url("redirect-to?url=%2Fredirect"); // → /redirect → /echo?redirected=true + PreparedRequest Limited(string url, int max) => Prepare(new HttpRequestSpec { Url = url, Settings = new RequestSettings { MaxRedirects = max } }); + + var zero = Limited(server.Url("redirect"), 0); + Assert.Equal(302, (await executor.SendAsync(zero, _ct)).Response!.StatusCode); + Assert.Contains("The redirect to " + server.Url("echo?redirected=true") + " was not followed", Assert.Single(zero.Warnings), StringComparison.Ordinal); + + var one = Limited(twice, 1); + var stopped = await executor.SendAsync(one, _ct); + Assert.Equal((302, server.Url("redirect")), (stopped.Response!.StatusCode, stopped.Response.FinalUri?.ToString())); + Assert.Contains("maximum number of redirects (1)", Assert.Single(one.Warnings), StringComparison.Ordinal); + + Assert.Equal("true", Json(await executor.SendAsync(Limited(twice, 2), _ct))["query"]!["redirected"].GetString()); + + // A negative limit (curl's -1 for no limit, as earlier cURL imports kept it) leaves the workspace's. + var negative = Limited(twice, -1); + var followed = await executor.SendAsync(negative, _ct); + Assert.Equal((200, server.Url("echo?redirected=true")), (followed.Response!.StatusCode, followed.Response.FinalUri?.ToString())); + Assert.Empty(negative.Warnings); + } + + [Fact] + public async Task The_request_timeout_covers_the_redirects() + { + await using var server = await EchoServer.StartAsync(); + + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("redirect-to?url=%2Fslow") }, new ExecutionDefaults { Timeout = TimeSpan.FromMilliseconds(300) }), _ct); + + Assert.Equal("Request timed out after 300 ms.", exchange.ErrorMessage); + } + + [Fact] + public async Task A_redirect_from_https_to_http_is_not_followed() + { + await using var secure = await EchoServer.StartAsync(_pki.Server); + await using var plain = await EchoServer.StartAsync(); + var prepared = Prepare(new HttpRequestSpec { Url = secure.Url("redirect-to?url=" + Uri.EscapeDataString(plain.Url("echo"))) }, new ExecutionDefaults { CaBundlePath = _pki.CaPemPath }); + + var exchange = await new HttpExecutor().SendAsync(prepared, _ct); + + Assert.Equal(302, exchange.Response!.StatusCode); + Assert.Contains("from https to http", Assert.Single(prepared.Warnings), StringComparison.Ordinal); + } + [Fact] public async Task Reports_status_codes_timeouts_cancellation_and_connection_errors() { @@ -183,7 +926,8 @@ public async Task Reports_status_codes_timeouts_cancellation_and_connection_erro var refused = await executor.SendAsync(Prepare(new HttpRequestSpec { Url = "http://127.0.0.1:1/" }), _ct); Assert.Null(refused.Response); - Assert.False(string.IsNullOrEmpty(refused.ErrorMessage)); + Assert.StartsWith("ConnectionError: ", refused.ErrorMessage, StringComparison.Ordinal); + Assert.DoesNotContain("→", refused.ErrorMessage, StringComparison.Ordinal); // the socket's message is in the outer one already var invalid = await executor.SendAsync(Prepare(new HttpRequestSpec { Url = "{{undefinedBase}}/x" }), _ct); Assert.Contains("not a valid", invalid.ErrorMessage, StringComparison.Ordinal); @@ -220,6 +964,45 @@ public async Task Requests_that_cannot_be_built_report_an_error_instead_of_throw Assert.False(string.IsNullOrEmpty(badProxy.ErrorMessage)); } + [Fact] + public async Task The_error_of_a_url_that_is_not_valid_masks_its_password() + { + // Not valid while its port is unresolved; nothing knows its password as a secret then (a short one escapes reports). + var prepared = Prepare(new HttpRequestSpec { Url = "http://ada:pw12@localhost:{{port}}/x" }); + + var exchange = await new HttpExecutor().SendAsync(prepared, _ct); + + Assert.Equal("'http://ada:***@localhost:{{port}}/x' is not a valid http(s) URL.", Assert.Single(prepared.Errors)); + Assert.Equal(prepared.Errors[0], exchange.ErrorMessage); + + // A user name without a password is the credential (an API key sent as Basic auth), so it is masked instead. + foreach (var (url, shown) in (ReadOnlySpan<(string, string)>)[ + ("https://sk_test_abc@{{host}}/v1/charges", "https://***@{{host}}/v1/charges"), + ("https://sk_test_abc:@api.example.com:{{port}}/v1", "https://***:@api.example.com:{{port}}/v1")]) + { + Assert.Equal($"'{shown}' is not a valid http(s) URL.", Assert.Single(Prepare(new HttpRequestSpec { Url = url }).Errors)); + } + } + + [Theory] + [InlineData("S3cret'Pr0xy", "Pr0xy")] + [InlineData("my pass", "my pass")] // a space, as typed in the proxy setting + [InlineData("P%C3%A4ss%20wort", "Päss wort")] // .NET's message unescapes it + public async Task A_proxy_password_is_masked_in_the_error_of_a_tunnel_the_proxy_refused(string password, string shown) + { + using var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var served = ServeRawAsync(listener, "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"u8.ToArray()); + var proxy = $"http://ada:{password}@127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}"; + + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = "https://api.example.com/x" }, new ExecutionDefaults { Proxy = proxy }), _ct); + + Assert.StartsWith("CONNECT api.example.com:443 ", Encoding.ASCII.GetString(Assert.Single(await served)), StringComparison.Ordinal); + Assert.Null(exchange.Response); + Assert.Contains("'http://ada:***@127.0.0.1:", exchange.ErrorMessage, StringComparison.Ordinal); + Assert.DoesNotContain(shown, exchange.ErrorMessage, StringComparison.Ordinal); + } + [Fact] public async Task Reloading_certificates_does_not_break_a_request_that_already_selected_one() { @@ -307,6 +1090,77 @@ public async Task Mutual_tls_presents_the_matching_client_certificate(string kin Assert.Contains("matched", tls.ClientCertificateOrigin, StringComparison.Ordinal); } + [Theory] + [InlineData("client.pem")] + [InlineData("client-chain.pem")] // with its chain: through a context on Linux + public async Task Tls_details_are_those_of_the_handshake_when_the_server_closes_the_connection(string certificate) + { + // The connection is disposed once the response is read, and its TLS session with it. + await using var server = await EchoServer.StartAsync(_pki.Server, requireClientCertificate: true); + using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory) + { + Entries = [new CertificateEntry { Name = "client", Matches = [$"https://localhost:{server.BaseUri.Port}/*"], Cert = new FileSource { Src = certificate }, Key = new FileSource { Src = "client.key" } }], + }); + + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("close") }, new ExecutionDefaults { CaBundlePath = _pki.CaPemPath }, provider), _ct); + + Assert.Equal(_pki.Client.Thumbprint, Json(exchange)["clientCertificateThumbprint"].GetString()); + Assert.Equal("close", exchange.Response!.Headers.Single(h => h.Key.Equals("Connection", StringComparison.OrdinalIgnoreCase)).Value); + var tls = exchange.Tls.Single(); + Assert.True(tls.Protocol != System.Security.Authentication.SslProtocols.None && tls.CipherSuite is not null, tls.Describe()); + Assert.True(tls.ClientCertificate is not null, tls.Describe()); + Assert.Equal((_pki.Client.Thumbprint, $"matched https://localhost:{server.BaseUri.Port}/*"), (tls.ClientCertificate.Thumbprint, tls.ClientCertificateOrigin)); + if (!OperatingSystem.IsMacOS() || certificate == "client.pem") // there a certificate sent through a context shows no request + { + Assert.True(tls.ClientCertificateRequested, tls.Describe()); + } + } + + [Fact] + public async Task A_client_certificate_the_server_asks_for_after_the_handshake_is_shown_as_sent() + { + // The server renegotiates (TLS 1.2). From the second request on, Windows answers from the credential it cached for the + // certificate, without asking TermRest's selection callback: only the session tells. + await using var server = await EchoServer.StartAsync(_pki.Server, delayClientCertificate: true); + using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory) + { + Entries = [new CertificateEntry { Name = "client", Matches = [$"https://localhost:{server.BaseUri.Port}/*"], Cert = new FileSource { Src = "client.pem" }, Key = new FileSource { Src = "client.key" } }], + }); + + for (var i = 0; i < 2; i++) + { + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("renegotiate") }, new ExecutionDefaults { CaBundlePath = _pki.CaPemPath }, provider), _ct); + + var received = Json(exchange)["clientCertificateThumbprint"].GetString(); + var tls = exchange.Tls.Single(); + if (OperatingSystem.IsWindows()) + { + Assert.Equal(_pki.Client.Thumbprint, received); + } + + if (received is not null) // where the platform renegotiates + { + Assert.True(tls.ClientCertificate?.Thumbprint == received && (tls.ClientCertificateRequested || OperatingSystem.IsMacOS()), $"{i}: {tls.Describe()}"); + } + } + } + + [Fact] + public async Task Mutual_tls_sends_the_intermediates_loaded_with_the_certificate() + { + var (client, intermediate) = _pki.IssueClientViaIntermediate(); + await using var server = await EchoServer.StartAsync(_pki.Server, requireClientCertificate: true); + using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory) + { + Entries = [new CertificateEntry { Name = "chain", Matches = [$"https://localhost:{server.BaseUri.Port}/*"], Cert = new FileSource { Src = "client-intermediate-chain.pem" }, Key = new FileSource { Src = "client-intermediate.key" } }], + }); + + var echo = Json(await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("echo") }, new ExecutionDefaults { CaBundlePath = _pki.CaPemPath }, provider), _ct)); + + Assert.Equal(client, echo["clientCertificateThumbprint"].GetString()); + Assert.Contains(intermediate, echo["clientCertificateChain"]!.AsArray().Select(thumbprint => thumbprint.GetString())); + } + [Fact] public async Task Mutual_tls_without_a_certificate_fails_with_a_clear_error() { @@ -319,11 +1173,13 @@ public async Task Mutual_tls_without_a_certificate_fails_with_a_clear_error() Assert.False(string.IsNullOrEmpty(exchange.ErrorMessage)); } - [Fact] - public async Task A_client_certificate_is_not_reported_as_requested_when_the_server_does_not_ask_for_one() + [Theory] + [InlineData("client.pem")] + [InlineData("client-chain.pem")] // with its chain + public async Task A_client_certificate_is_not_reported_as_requested_when_the_server_does_not_ask_for_one(string certificate) { await using var server = await EchoServer.StartAsync(_pki.Server); - var entry = new CertificateEntry { Name = "unasked", Cert = new FileSource { Src = "client.pem" }, Key = new FileSource { Src = "client.key" } }; + var entry = new CertificateEntry { Name = "unasked", Cert = new FileSource { Src = certificate }, Key = new FileSource { Src = "client.key" } }; entry.Matches = [$"https://localhost:{server.BaseUri.Port}/*"]; using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory) { Entries = [entry] }); @@ -332,8 +1188,41 @@ public async Task A_client_certificate_is_not_reported_as_requested_when_the_ser Assert.Equal(200, exchange.Response?.StatusCode); var tls = exchange.Tls.Single(); Assert.False(tls.ClientCertificateRequested, tls.Describe()); + if (!OperatingSystem.IsMacOS()) // there, the certificate chosen shows even when it was not sent + { + Assert.True(tls.ClientCertificate is null, tls.Describe()); + } } + [Fact] + public async Task A_certificate_sent_with_its_chain_is_not_presented_by_later_requests_without_a_certificate() + { + await using var quiet = await EchoServer.StartAsync(_pki.Server); + await using var asking = await EchoServer.StartAsync(_pki.Server, askForClientCertificate: true); + await using var requiring = await EchoServer.StartAsync(_pki.Server, requireClientCertificate: true); + var defaults = new ExecutionDefaults { CaBundlePath = _pki.CaPemPath }; + using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory) + { + Entries = [new CertificateEntry { Name = "chain", Matches = [$"https://localhost:{quiet.BaseUri.Port}/*"], Cert = new FileSource { Src = "client-chain.pem" }, Key = new FileSource { Src = "client.key" } }], + }); + async Task Send(EchoServer server) => await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("echo") }, defaults, provider), _ct); + + // .NET 10.0.15 on Windows cached the credential of a connection given an SslStreamCertificateContext, certificate + // included, as the one for connections without a certificate, if none was cached yet (as in a new process). + ClearTlsCredentialCache(); + Assert.Null(Json(await Send(quiet))["clientCertificateThumbprint"].GetString()); + + Assert.Null(Json(await Send(asking))["clientCertificateThumbprint"].GetString()); + var refused = await Send(requiring); + Assert.True(refused.Response is null, refused.Response is null ? "" : Encoding.UTF8.GetString(refused.Response.Body)); + } + + /// Empties .NET's process-wide cache of TLS client credentials (used on Windows). + private static void ClearTlsCredentialCache() => + (typeof(System.Net.Security.SslStream).Assembly.GetType("System.Net.Security.SslSessionsCache") + ?.GetField("s_cachedCreds", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static) + ?.GetValue(null) as System.Collections.IDictionary)?.Clear(); + [Fact] public async Task Request_pinned_certificate_is_used() { @@ -350,6 +1239,110 @@ public async Task Request_pinned_certificate_is_used() Assert.Equal(_pki.Client.Thumbprint, Json(exchange)["clientCertificateThumbprint"].GetString()); } + [Fact] + public async Task Each_redirect_gets_the_client_certificate_registered_for_its_own_url() + { + await using var registered = await EchoServer.StartAsync(_pki.Server); + await using var asking = await EchoServer.StartAsync(_pki.Server, askForClientCertificate: true); + await using var plain = await EchoServer.StartAsync(); + var defaults = new ExecutionDefaults { CaBundlePath = _pki.CaPemPath }; + ClientCertificateProvider Registry(EchoServer server) => new(new CertificateRegistry(_pki.Directory) + { + Entries = [new CertificateEntry { Name = "client", Matches = [$"https://localhost:{server.BaseUri.Port}/*"], Pfx = new FileSource { Src = "client.pfx" }, Passphrase = TestPki.Passphrase }], + }); + var toAsking = "redirect-to?url=" + Uri.EscapeDataString(asking.Url("echo")); + + // Registered for the first URL only: not presented to the server the redirect leads to, although it asks for one. + using var forRegistered = Registry(registered); + var elsewhere = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = registered.Url(toAsking) }, defaults, forRegistered), _ct); + Assert.Null(Json(elsewhere)["clientCertificateThumbprint"].GetString()); + Assert.Equal(2, elsewhere.Tls.Count); + Assert.Null(elsewhere.Tls[1].ClientCertificate); + + // Registered for the redirect target: presented there, also when the request started on plain http. + using var forAsking = Registry(asking); + var upgraded = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = plain.Url(toAsking) }, defaults, forAsking), _ct); + Assert.Equal(_pki.Client.Thumbprint, Json(upgraded)["clientCertificateThumbprint"].GetString()); + Assert.Equal(_pki.Client.Thumbprint, upgraded.Tls.Single().ClientCertificate?.Thumbprint); + } + + [Fact] + public async Task A_certificate_pinned_without_url_patterns_is_not_presented_to_another_origin_a_redirect_leads_to() + { + await using var first = await EchoServer.StartAsync(_pki.Server); + await using var asking = await EchoServer.StartAsync(_pki.Server, askForClientCertificate: true); + using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory)); + var defaults = new ExecutionDefaults { CaBundlePath = _pki.CaPemPath }; + HttpRequestSpec Spec(params string[] matches) => new() + { + Url = first.Url("redirect-to?url=" + Uri.EscapeDataString(asking.Url("echo"))), + Certificate = new CertificateSpec { Name = "pinned", CertSrc = _pki.ClientCertPemPath, KeySrc = _pki.ClientKeyPemPath, Matches = [.. matches] }, + }; + + var unpatterned = await new HttpExecutor().SendAsync(Prepare(Spec(), defaults, provider), _ct); + Assert.Null(Json(unpatterned)["clientCertificateThumbprint"].GetString()); + + // URL patterns say where else it goes. + var patterned = await new HttpExecutor().SendAsync(Prepare(Spec($"https://localhost:{first.BaseUri.Port}/*", $"https://localhost:{asking.BaseUri.Port}/*"), defaults, provider), _ct); + Assert.Equal(_pki.Client.Thumbprint, Json(patterned)["clientCertificateThumbprint"].GetString()); + } + + [Fact] + public async Task A_certificate_file_that_cannot_be_read_is_reported_and_the_request_sent_without_it() + { + await using var plain = await EchoServer.StartAsync(); + await using var secure = await EchoServer.StartAsync(_pki.Server); + using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory) + { + Entries = [new CertificateEntry { Name = "locked", Matches = [$"https://localhost:{secure.BaseUri.Port}/*"], Cert = new FileSource { Src = "client.pem" }, Key = new FileSource { Src = "client.key" } }], + }); + var defaults = new ExecutionDefaults { CaBundlePath = _pki.CaPemPath }; + using var locked = new FileStream(_pki.ClientKeyPemPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None); + + // Selected when the request is prepared … + var direct = Prepare(new HttpRequestSpec { Url = secure.Url("echo") }, defaults, provider); + Assert.Null(direct.ClientCertificate); + Assert.StartsWith("Client certificate 'locked' not used: ", Assert.Single(direct.Warnings), StringComparison.Ordinal); + + // … or when a redirect leads to its URL. + var redirected = Prepare(new HttpRequestSpec { Url = plain.Url("redirect-to?url=" + Uri.EscapeDataString(secure.Url("echo"))) }, defaults, provider); + var exchange = await new HttpExecutor().SendAsync(redirected, _ct); + Assert.Null(Json(exchange)["clientCertificateThumbprint"].GetString()); + Assert.StartsWith("Client certificate 'locked' not used: ", Assert.Single(redirected.Warnings), StringComparison.Ordinal); + } + + [Fact] + public async Task The_ca_bundle_does_not_make_a_certificate_issued_for_other_purposes_a_server_certificate() + { + // Kestrel refuses a certificate without the server-auth usage, so a bare TLS listener presents it. + using var clientAuthOnly = _pki.IssueLocalhost("1.3.6.1.5.5.7.3.2"); + using var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); + listener.Start(); + _ = Task.Run(async () => + { + using var connection = await listener.AcceptTcpClientAsync(_ct); + await using var tls = new System.Net.Security.SslStream(connection.GetStream()); + await tls.AuthenticateAsServerAsync(clientAuthOnly); + var request = new byte[4096]; + var read = 0; + int count; + while (request.AsSpan(0, read).IndexOf("\r\n\r\n"u8) < 0 && (count = await tls.ReadAsync(request.AsMemory(read), _ct)) > 0) + { + read += count; + } + + await tls.WriteAsync("HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n"u8.ToArray(), _ct); + }, _ct); + var url = $"https://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/"; + + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = url }, new ExecutionDefaults { CaBundlePath = _pki.CaPemPath }), _ct); + + Assert.Null(exchange.Response); + var tls = Assert.Single(exchange.Tls); + Assert.False(tls.Accepted, tls.Describe()); + Assert.Contains("rejected", exchange.ErrorMessage, StringComparison.Ordinal); + } + /// /// Imports the client certificate into the Windows CurrentUser\My store with a NON-EXPORTABLE key, uses it by /// thumbprint, then removes it. Opt-in because it modifies the user's certificate store. @@ -405,6 +1398,194 @@ public async Task Body_formatter_pretty_prints_json_and_xml() Assert.StartsWith("00000000 00 01 ff", BodyFormatter.Format([0, 1, 255], "application/octet-stream"), StringComparison.Ordinal); } + [Fact] + public void Office_documents_are_binary_though_their_types_name_xml_formats() + { + // The start of a ZIP file, which .xlsx, .docx and .pptx files are. + byte[] zip = [0x50, 0x4B, 0x03, 0x04, 0x14, 0x00, 0x06, 0x00, 0x08, 0x00, 0x00, 0x00, 0x21, 0x00, 0x8C, 0x5A, 0xED, 0xC1]; + foreach (var office in (string[])[ + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/vnd.openxmlformats-officedocument.presentationml.presentation"]) + { + Assert.True(BodyFormatter.IsBinary(zip, office), office); + Assert.StartsWith("00000000 50 4b 03 04", BodyFormatter.Format(zip, office), StringComparison.Ordinal); + } + + // A type is text when a word of its subtype names a text format. + var svg = ""u8.ToArray(); + Assert.False(BodyFormatter.IsBinary(svg, "image/svg+xml")); + Assert.Contains("\n ", BodyFormatter.Format(svg, "image/svg+xml"), StringComparison.Ordinal); + string[] text = ["application/atom+xml; charset=utf-8", "application/problem+json", "application/x-ndjson", "application/x-amz-json-1.1", "text/csv"]; + Assert.DoesNotContain(text, type => BodyFormatter.IsBinary("x"u8.ToArray(), type)); + } + + [Fact] + public void Xml_with_a_document_type_is_shown_as_received_without_expanding_its_entities() + { + // A few hundred bytes whose entities expand to millions of characters. + var entities = string.Concat(Enumerable.Range(1, 6).Select(i => $"")); + var bomb = $"\">{entities}]>&e6;"; + + Assert.Equal(bomb, BodyFormatter.Format(Encoding.UTF8.GetBytes(bomb), "application/xml")); + Assert.Equal("\n x\n", BodyFormatter.Format(" x "u8.ToArray(), "application/xml").ReplaceLineEndings("\n")); + } + + [Fact] + public async Task A_content_type_dotnet_cannot_parse_is_read_as_the_server_sent_it() + { + // A trailing ";", as PHP's header() and servlets write it: .NET reads no type from it, Postman reads its charset. + await using var server = await EchoServer.StartAsync(); + const string Type = "text/html; charset=ISO-8859-1;"; + + var exchange = await new HttpExecutor().SendAsync(Prepare(new HttpRequestSpec { Url = server.Url($"bytes/636166E9?type={Uri.EscapeDataString(Type)}") }), _ct); + + Assert.Equal(Type, exchange.Response!.ContentType); + Assert.Equal("café", BodyFormatter.Format(exchange.Response.Body, exchange.Response.ContentType)); + } + + [Fact] + public void Body_formatter_decodes_legacy_charsets() + { + // Not built into .NET: history --show, send, the response pane and scripts read them with the code page tables. + Assert.Equal("café", BodyFormatter.Format([.. "caf"u8, 0xE9], "text/html; charset=windows-1252")); + Assert.Equal("日本", BodyFormatter.Format([0x93, 0xFA, 0x96, 0x7B], "text/plain; charset=Shift_JIS")); + + // UTF-16 without a byte order mark, in either byte order (RFC 2781). + Assert.Equal("hi", BodyFormatter.Format(Encoding.BigEndianUnicode.GetBytes("hi"), "text/xml; charset=utf-16", pretty: false)); + Assert.Equal("hi", BodyFormatter.Format(Encoding.Unicode.GetBytes("hi"), "text/xml; charset=utf-16", pretty: false)); + } + + [Fact] + public async Task A_body_of_known_length_is_read_into_one_buffer_of_that_size() + { + var data = System.Security.Cryptography.RandomNumberGenerator.GetBytes(4 * 1024 * 1024); + async Task<(byte[] Body, bool Truncated, long Allocated)> Read(HttpResponseMessage response, long maxBytes) + { + // Content over a MemoryStream completes synchronously, so this thread does all the allocations. + var before = GC.GetAllocatedBytesForCurrentThread(); + var task = HttpExecutor.ReadBodyAsync(response, maxBytes, _ct); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.True(task.IsCompletedSuccessfully); + var (body, truncated, _, _) = await task; + return (body, truncated, allocated); + } + + using var full = new HttpResponseMessage { Content = new StreamContent(new MemoryStream(data)) }; + var (body, truncated, allocated) = await Read(full, 50L * 1024 * 1024); + Assert.True(body.AsSpan().SequenceEqual(data) && !truncated); + Assert.True(allocated < data.Length + 1.25 * 1024 * 1024, $"{allocated:N0} bytes allocated to read {data.Length:N0}"); // and a buffer for the first megabyte + + // A declared length is not allocated before the body arrives. + using var lying = new HttpResponseMessage { Content = new StreamContent(new MemoryStream(data, 0, 16 * 1024)) }; + lying.Content.Headers.ContentLength = 8L * data.Length; + (body, truncated, allocated) = await Read(lying, 50L * 1024 * 1024); + Assert.True(body.AsSpan().SequenceEqual(data.AsSpan(0, 16 * 1024)) && !truncated); + Assert.True(allocated < 1.25 * 1024 * 1024, $"{allocated:N0} bytes allocated to read 16 KB of a declared {8L * data.Length:N0}"); + + using var cut = new HttpResponseMessage { Content = new StreamContent(new MemoryStream(data)) }; + (body, truncated, allocated) = await Read(cut, 1024 * 1024); + Assert.True(body.AsSpan().SequenceEqual(data.AsSpan(0, 1024 * 1024)) && truncated); + Assert.True(allocated < 1.25 * 1024 * 1024, $"{allocated:N0} bytes allocated to read 1 MB"); + + // HEAD responses declare the length of a body they do not have. + using var head = new HttpResponseMessage { Content = new ByteArrayContent([]), RequestMessage = new HttpRequestMessage(HttpMethod.Head, "http://localhost/") }; + head.Content.Headers.ContentLength = data.Length; + (body, _, allocated) = await Read(head, 50L * 1024 * 1024); + Assert.Empty(body); + Assert.True(allocated < 256 * 1024, $"{allocated:N0} bytes allocated to read an empty body"); + } + + [Theory] + [InlineData("gzip")] + [InlineData("x-gzip")] + [InlineData("deflate")] // zlib data, as the standard has it + [InlineData("deflate", "raw-deflate")] // as some servers send it + [InlineData("br")] + [InlineData("deflate, gzip")] // applied in that order + [InlineData("identity")] + public async Task Bodies_are_decoded_as_their_content_encoding_says(string header, string? applied = null) + { + var data = Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat("{\"id\":1,\"name\":\"item\"},", 500))); + var encoded = (applied ?? header).Split(", ").Aggregate(data, (bytes, coding) => coding == "identity" ? bytes : Encode(coding, bytes)); + using var response = new HttpResponseMessage { Content = new ByteArrayContent(encoded) }; + response.Content.Headers.TryAddWithoutValidation("Content-Encoding", header); + + var (body, truncated, received, warning) = await HttpExecutor.ReadBodyAsync(response, 50L * 1024 * 1024, _ct); + + Assert.Equal(data, body); + Assert.Equal((false, encoded.Length, null), (truncated, received, warning)); + } + + [Fact] + public async Task A_compressed_body_is_decoded_into_one_buffer_of_its_size_and_within_the_size_limit() + { + var data = new byte[8 * 1024 * 1024]; + var gzip = Encode("gzip", data); + async Task<(byte[] Body, bool Truncated, long Allocated)> Read(long maxBytes) + { + using var response = new HttpResponseMessage { Content = new ByteArrayContent(gzip) }; + response.Content.Headers.ContentEncoding.Add("gzip"); + var before = GC.GetAllocatedBytesForCurrentThread(); + var task = HttpExecutor.ReadBodyAsync(response, maxBytes, _ct); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.True(task.IsCompletedSuccessfully); + var (body, truncated, received, warning) = await task; + Assert.Equal((gzip.Length, null), (received, warning)); + return (body, truncated, allocated); + } + + var (body, truncated, allocated) = await Read(50L * 1024 * 1024); + Assert.True(body.AsSpan().SequenceEqual(data) && !truncated); + Assert.True(allocated < gzip.Length + data.Length + 1.5 * 1024 * 1024, $"{allocated:N0} bytes allocated to decode {data.Length:N0}"); + + // A small body that decodes to a huge one stops at the limit. + (body, truncated, allocated) = await Read(1024 * 1024); + Assert.True(body.Length == 1024 * 1024 && truncated); + Assert.True(allocated < gzip.Length + 1.5 * 1024 * 1024, $"{allocated:N0} bytes allocated to decode 1 MB"); + } + + [Fact] + public async Task Accept_encoding_is_sent_unless_typed_and_a_compressed_response_keeps_its_headers() + { + await using var server = await EchoServer.StartAsync(); + var executor = new HttpExecutor(); + var data = "{\"compressed\":true}"u8.ToArray(); + var gzip = Encode("gzip", data); + + var generated = await executor.SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("echo") }), _ct); + var typed = await executor.SendAsync(Prepare(new HttpRequestSpec { Url = server.Url("echo"), Headers = [new() { Key = "Accept-Encoding", Value = "identity" }] }), _ct); + var compressed = await executor.SendAsync(Prepare(new HttpRequestSpec { Url = server.Url($"bytes/{Convert.ToHexString(gzip)}?type=application/json&encoding=gzip") }), _ct); + + Assert.Equal("gzip, deflate, br", Json(generated)["headers"]!["accept-encoding"].GetString()); + Assert.Equal("gzip, deflate, br", generated.SentHeaders.Single(h => h.Key == "Accept-Encoding").Value); + Assert.Equal("identity", Json(typed)["headers"]!["accept-encoding"].GetString()); + Assert.Equal("identity", typed.SentHeaders.Single(h => h.Key == "Accept-Encoding").Value); + var response = compressed.Response!; + Assert.Equal(data, response.Body); + Assert.Equal(("gzip", gzip.Length.ToString(CultureInfo.InvariantCulture)), (response.GetHeader("Content-Encoding"), response.GetHeader("Content-Length"))); + Assert.Equal(gzip.Length, response.ReceivedBodySize); + Assert.Empty(compressed.Request.Warnings); + } + + [Theory] + [InlineData("gzip", "The body could not be decoded (Content-Encoding: gzip): it is not valid gzip data. It is kept as received.")] + [InlineData("br", "The body could not be decoded (Content-Encoding: br): it is not valid br data. It is kept as received.")] + [InlineData("zstd", "The body is kept as received: TermRest cannot decode Content-Encoding 'zstd'.")] + public async Task A_body_that_cannot_be_decoded_is_kept_as_received_with_the_status_and_headers(string coding, string warning) + { + await using var server = await EchoServer.StartAsync(); + var plain = "{\"plain\":true}"u8.ToArray(); + var prepared = Prepare(new HttpRequestSpec { Url = server.Url($"bytes/{Convert.ToHexString(plain)}?type=application/json&encoding={coding}") }); + + var exchange = await new HttpExecutor().SendAsync(prepared, _ct); + + Assert.True(exchange.IsSuccess, exchange.ErrorMessage); + Assert.Equal((200, coding), (exchange.Response!.StatusCode, exchange.Response.GetHeader("Content-Encoding"))); + Assert.Equal(plain, exchange.Response.Body); + Assert.Equal(warning, Assert.Single(prepared.Warnings)); + } + [Fact] public void Curl_export_quotes_values() { @@ -420,9 +1601,60 @@ public void Curl_export_quotes_values() var curl = CurlExporter.Export(prepared, multiline: false); Assert.Equal( - "curl -X POST 'https://api.example.com/x?q=it'\\''s' -H 'Accept: application/json' --data-raw '{\"a\":\"it'\\''s\"}' -H 'Content-Type: application/json' --insecure --location", + "curl 'https://api.example.com/x?q=it'\\''s' -H 'Accept: application/json' --data-raw '{\"a\":\"it'\\''s\"}' -H 'Content-Type: application/json' --insecure --location --max-redirs 10 --proto-redir '=https'", curl); } + [Fact] + public void Curl_export_gives_client_certificate_files_with_their_full_paths() + { + // Relative to the workspace (registry) or to the collection's folder (pinned on a request), not to curl's folder. + using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory) + { + Entries = + [ + new CertificateEntry { Name = "pem", Matches = ["https://pem.example/*"], Cert = new FileSource { Src = "client.pem" }, Key = new FileSource { Src = "client.key" } }, + new CertificateEntry { Name = "pfx", Matches = ["https://pfx.example/*"], Pfx = new FileSource { Src = "client.pfx" }, Passphrase = TestPki.Passphrase }, + ], + }); + var collection = Directory.CreateDirectory(Path.Combine(_pki.Directory, "collection")).FullName; + File.Copy(_pki.ClientPfxPath, Path.Combine(collection, "pinned.pfx")); + string Export(HttpRequestSpec spec) + { + var prepared = new RequestPreparer(VariableResolver.Empty, provider, new ExecutionDefaults()).Prepare(spec, null, collection); + Assert.NotNull(prepared.ClientCertificate); + return CurlExporter.Export(prepared, multiline: false); + } + + Assert.EndsWith($" --cert '{_pki.ClientCertPemPath}' --key '{_pki.ClientKeyPemPath}'", Export(new HttpRequestSpec { Url = "https://pem.example/" }), StringComparison.Ordinal); + Assert.EndsWith($" --cert-type P12 --cert '{_pki.ClientPfxPath}'", Export(new HttpRequestSpec { Url = "https://pfx.example/" }), StringComparison.Ordinal); + var pinned = new HttpRequestSpec { Url = "https://pem.example/", Certificate = new CertificateSpec { PfxSrc = "pinned.pfx", Passphrase = TestPki.Passphrase } }; + Assert.EndsWith($" --cert-type P12 --cert '{Path.Combine(collection, "pinned.pfx")}'", Export(pinned), StringComparison.Ordinal); + } + + [Fact] + public void Curl_export_follows_no_redirects_with_a_client_certificate_file() + { + using var provider = new ClientCertificateProvider(new CertificateRegistry(_pki.Directory) + { + Entries = [new CertificateEntry { Name = "pem", Matches = ["https://pem.example/*"], Cert = new FileSource { Src = "client.pem" }, Key = new FileSource { Src = "client.key" } }], + }); + var apikey = new AuthSpec { Type = "apikey" }; + apikey.Set("key", "X-API-Key"); + apikey.Set("value", "k1"); + string Export(AuthSpec? auth) => CurlExporter.Export( + new RequestPreparer(VariableResolver.Empty, provider, new ExecutionDefaults()).Prepare(new HttpRequestSpec { Url = "https://pem.example/", Auth = auth }, auth, ""), + multiline: false); + + // curl presents the certificate it is given on every connection; TermRest selects one for each URL a redirect leads to. + Assert.Equal( + "# redirects are not followed: curl would present the client certificate to every host it is redirected to\n" + + $"curl 'https://pem.example/' --cert '{_pki.ClientCertPemPath}' --key '{_pki.ClientKeyPemPath}'", + Export(null)); + Assert.StartsWith( + "# redirects are not followed: curl would send 'X-API-Key' and present the client certificate to every host it is redirected to\ncurl ", + Export(apikey), StringComparison.Ordinal); + } + public void Dispose() => _pki.Dispose(); } diff --git a/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs b/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs index 434bdb6..1a2a3a2 100644 --- a/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs +++ b/tests/TermRest.Core.Tests/Infrastructure/EchoServer.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Text; @@ -15,7 +16,10 @@ namespace TermRest.Core.Tests.Infrastructure; /// /// In-process Kestrel server for integration tests. /echo reflects the request (method, path, query, headers, -/// body, client certificate) as JSON; other endpoints cover redirects, cookies, status codes and slow responses. +/// body, client certificate and the CA certificates sent with it) as JSON; /mirror answers with the request's body +/// and Content-Type as received; /bytes/{hex}?type=…&repeat=…&encoding=… answers with those bytes (labelled +/// with that Content-Encoding, as they are); other endpoints cover redirects, auth challenges, cookies, status codes and +/// slow responses. /// public sealed class EchoServer : IAsyncDisposable { @@ -31,8 +35,13 @@ private EchoServer(WebApplication app, Uri baseUri) public string Url(string path) => new Uri(BaseUri, path).ToString(); - public static async Task StartAsync(X509Certificate2? serverCertificate = null, bool requireClientCertificate = false) + /// Request a client certificate without requiring one. + /// Runs when a request to /echo has come in, before its body is read (with Expect: 100-continue, before it is sent). + /// Ask for a client certificate only on /renegotiate, after the request came in (TLS 1.2). + public static async Task StartAsync(X509Certificate2? serverCertificate = null, bool requireClientCertificate = false, bool askForClientCertificate = false, Action? beforeEcho = null, bool delayClientCertificate = false) { + // The CA certificates each client certificate came with, by its thumbprint (/echo reports them). + var clientChains = new ConcurrentDictionary(StringComparer.Ordinal); var builder = WebApplication.CreateSlimBuilder(); builder.Logging.ClearProviders(); builder.WebHost.ConfigureKestrel(kestrel => @@ -44,10 +53,21 @@ public static async Task StartAsync(X509Certificate2? serverCertific listen.UseHttps(https => { https.ServerCertificate = serverCertificate; - if (requireClientCertificate) + if (requireClientCertificate || askForClientCertificate || delayClientCertificate) { - https.ClientCertificateMode = ClientCertificateMode.RequireCertificate; - https.AllowAnyClientCertificate(); + https.ClientCertificateMode = requireClientCertificate ? ClientCertificateMode.RequireCertificate + : delayClientCertificate ? ClientCertificateMode.DelayCertificate : ClientCertificateMode.AllowCertificate; + if (delayClientCertificate) + { + https.SslProtocols = System.Security.Authentication.SslProtocols.Tls12; // TLS 1.3 has no renegotiation + } + + https.ClientCertificateValidation = (certificate, chain, _) => + { + clientChains[certificate.Thumbprint] = chain is null ? [] + : [.. chain.ChainPolicy.ExtraStore.Select(c => c.Thumbprint).Where(t => t != certificate.Thumbprint)]; + return true; + }; } }); } @@ -55,9 +75,70 @@ public static async Task StartAsync(X509Certificate2? serverCertific }); var app = builder.Build(); + Task Echo(HttpContext ctx) + { + beforeEcho?.Invoke(); + return EchoAsync(ctx, clientChains); + } + app.Map("/echo/{**rest}", Echo); app.Map("/echo", Echo); + + // As openssl s_server -www, Python's http.server and HTTP/1.0 servers do: the connection is closed after the response. + app.Map("/close", (HttpContext ctx) => + { + ctx.Response.Headers.Connection = "close"; + return EchoAsync(ctx, clientChains); + }); + + // As IIS without "Negotiate Client Certificate" and servers that want one for some paths only: the certificate is + // asked for once the request came in. macOS can't renegotiate: there the request is echoed without one. + app.Map("/renegotiate", async (HttpContext ctx) => + { + try + { + await ctx.Connection.GetClientCertificateAsync(ctx.RequestAborted); + } + catch (PlatformNotSupportedException) + { + } + + await EchoAsync(ctx, clientChains); + }); + app.Map("/mirror", async (HttpContext ctx) => + { + ctx.Response.ContentType = ctx.Request.ContentType; + await ctx.Request.Body.CopyToAsync(ctx.Response.Body); + }); 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. + app.Map("/redirect-to", (HttpContext ctx) => + { + ctx.Response.StatusCode = int.TryParse(ctx.Request.Query["status"], out var status) ? status : StatusCodes.Status302Found; + ctx.Response.Headers.Location = ctx.Request.Query["url"].ToString(); + if (ctx.Request.Query["cookie"].ToString() is { Length: > 0 } cookie) + { + ctx.Response.Headers.SetCookie = cookie; + } + + return Task.CompletedTask; + }); + + // Challenges with the scheme (Basic, Digest …) until a request is authorized with it, then echoes that request. + app.Map("/challenge/{scheme}", async (HttpContext ctx, string scheme) => + { + if (ctx.Request.Headers.Authorization.ToString().StartsWith(scheme + " ", StringComparison.OrdinalIgnoreCase)) + { + await Echo(ctx); + return; + } + + ctx.Response.StatusCode = StatusCodes.Status401Unauthorized; + ctx.Response.Headers.WWWAuthenticate = scheme.Equals("digest", StringComparison.OrdinalIgnoreCase) + ? "Digest realm=\"termrest\", nonce=\"5f2b8d1e9c7a4b30\", qop=\"auth\", algorithm=MD5" + : $"{scheme} realm=\"termrest\""; + }); app.MapGet("/set-cookie", (HttpContext ctx) => { ctx.Response.Cookies.Append("session", "abc123"); @@ -70,6 +151,15 @@ public static async Task StartAsync(X509Certificate2? serverCertific return Results.Text("late"); }); app.MapGet("/xml", () => Results.Text("x", "application/xml")); + app.MapGet("/bytes/{hex}", (HttpContext ctx, string hex, string? type, int? repeat, string? encoding) => + { + if (encoding is not null) + { + ctx.Response.Headers.ContentEncoding = encoding; + } + + return Results.Bytes(Enumerable.Repeat(Convert.FromHexString(hex), repeat ?? 1).SelectMany(b => b).ToArray(), type ?? "application/octet-stream"); + }); await app.StartAsync(); var address = app.Services.GetRequiredService().Features.Get()!.Addresses.First(); @@ -77,7 +167,7 @@ public static async Task StartAsync(X509Certificate2? serverCertific return new EchoServer(app, uri); } - private static async Task Echo(HttpContext ctx) + private static async Task EchoAsync(HttpContext ctx, ConcurrentDictionary clientChains) { using var reader = new StreamReader(ctx.Request.Body, Encoding.UTF8); var body = await reader.ReadToEndAsync(); @@ -105,6 +195,9 @@ private static async Task Echo(HttpContext ctx) ["protocol"] = ctx.Request.Protocol, ["clientCertificateSubject"] = clientCertificate?.Subject, ["clientCertificateThumbprint"] = clientCertificate?.Thumbprint, + ["clientCertificateChain"] = clientCertificate is not null && clientChains.TryGetValue(clientCertificate.Thumbprint, out var chain) + ? new JsonArray([.. chain.Select(thumbprint => JsonValue.Create(thumbprint))]) + : null, }; ctx.Response.ContentType = "application/json; charset=utf-8"; await ctx.Response.WriteAsync(result.ToJsonString()); diff --git a/tests/TermRest.Core.Tests/Infrastructure/TestCSharp.cs b/tests/TermRest.Core.Tests/Infrastructure/TestCSharp.cs index 46b81c4..2c09f21 100644 --- a/tests/TermRest.Core.Tests/Infrastructure/TestCSharp.cs +++ b/tests/TermRest.Core.Tests/Infrastructure/TestCSharp.cs @@ -29,6 +29,6 @@ public static string Require() } return candidates.FirstOrDefault(candidate => - ScriptRuntimeLocator.CheckAsync(ScriptLanguage.CSharp, candidate, Path.GetTempPath()).GetAwaiter().GetResult().Ok); + ScriptRuntimeLocator.CheckAsync(ScriptLanguage.CSharp, candidate).GetAwaiter().GetResult().Ok); } } diff --git a/tests/TermRest.Core.Tests/Infrastructure/TestPki.cs b/tests/TermRest.Core.Tests/Infrastructure/TestPki.cs index f257169..7a85107 100644 --- a/tests/TermRest.Core.Tests/Infrastructure/TestPki.cs +++ b/tests/TermRest.Core.Tests/Infrastructure/TestPki.cs @@ -11,6 +11,8 @@ public sealed class TestPki : IDisposable { public const string Passphrase = "test-passphrase"; + private X509Certificate2? _intermediate; + private TestPki(string directory) { Directory = directory; @@ -38,6 +40,10 @@ private TestPki(string directory) public string ClientPfxPath => Path.Combine(Directory, "client.pfx"); + public string ClientViaIntermediateChainPemPath => Path.Combine(Directory, "client-intermediate-chain.pem"); + + public string ClientViaIntermediateKeyPemPath => Path.Combine(Directory, "client-intermediate.key"); + public static TestPki Create() { var directory = Path.Combine(Path.GetTempPath(), "termrest-tests", Guid.NewGuid().ToString("N")[..12]); @@ -76,14 +82,47 @@ private void Generate() } } - private static X509Certificate2 Issue(string subject, bool isServer, DateTimeOffset now, X509Certificate2 issuer, out RSA key) + /// Issues another localhost certificate from the test CA, for one extended key usage (e.g. client authentication only). + public X509Certificate2 IssueLocalhost(string extendedKeyUsage) + { + var certificate = Issue("CN=localhost", isServer: true, DateTimeOffset.UtcNow.AddMinutes(-5), Ca, out var key, extendedKeyUsage); + key.Dispose(); + return certificate; + } + + /// + /// Issues a client certificate from an intermediate CA under the test CA, written with that chain (leaf, intermediate, + /// root) to and with its key to . + /// + public (string ClientThumbprint, string IntermediateThumbprint) IssueClientViaIntermediate() + { + var now = DateTimeOffset.UtcNow.AddMinutes(-5); + using var intermediateKey = RSA.Create(2048); + var request = new CertificateRequest("CN=TermRest Test Intermediate CA, O=TermRest Tests", intermediateKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); + request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, false)); + using var intermediate = request.Create(Ca, now, now.AddDays(20), RandomNumberGenerator.GetBytes(12)); + using var intermediateWithKey = intermediate.CopyWithPrivateKey(intermediateKey); + _intermediate = X509CertificateLoader.LoadCertificate(intermediate.RawData); + using var client = Issue("CN=TermRest Test Client via Intermediate, O=TermRest Tests", isServer: false, now, intermediateWithKey, out var clientKey); + using (clientKey) + { + File.WriteAllText(ClientViaIntermediateChainPemPath, client.ExportCertificatePem() + "\n" + intermediate.ExportCertificatePem() + "\n" + Ca.ExportCertificatePem()); + File.WriteAllText(ClientViaIntermediateKeyPemPath, clientKey.ExportPkcs8PrivateKeyPem()); + } + + return (client.Thumbprint, _intermediate.Thumbprint); + } + + private static X509Certificate2 Issue(string subject, bool isServer, DateTimeOffset now, X509Certificate2 issuer, out RSA key, string? extendedKeyUsage = null) { key = RSA.Create(2048); var request = new CertificateRequest(subject, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true)); request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( - [new Oid(isServer ? "1.3.6.1.5.5.7.3.1" : "1.3.6.1.5.5.7.3.2")], false)); + [new Oid(extendedKeyUsage ?? (isServer ? "1.3.6.1.5.5.7.3.1" : "1.3.6.1.5.5.7.3.2"))], false)); if (isServer) { var san = new SubjectAlternativeNameBuilder(); @@ -105,7 +144,31 @@ private static X509Certificate2 Reimport(X509Certificate2 certificate) => public void Dispose() { + // On Windows, sending a client certificate with its chain makes .NET add the chain (this CA, an intermediate) to + // an intermediate CA store when the OS cannot build it; dozens of same-named test CAs there make chain building fail. + if (OperatingSystem.IsWindows()) + { + foreach (var location in new[] { StoreLocation.LocalMachine, StoreLocation.CurrentUser }) + { + try + { + using var store = new X509Store(StoreName.CertificateAuthority, location); + store.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly); + store.Remove(Ca); + if (_intermediate is not null) + { + store.Remove(_intermediate); + } + } + catch (CryptographicException) + { + // Not writable (LocalMachine without elevation): .NET used the other store. + } + } + } + Ca.Dispose(); + _intermediate?.Dispose(); Server.Dispose(); Client.Dispose(); try diff --git a/tests/TermRest.Core.Tests/Infrastructure/TestPowerShell.cs b/tests/TermRest.Core.Tests/Infrastructure/TestPowerShell.cs index a87045d..307f35d 100644 --- a/tests/TermRest.Core.Tests/Infrastructure/TestPowerShell.cs +++ b/tests/TermRest.Core.Tests/Infrastructure/TestPowerShell.cs @@ -32,6 +32,6 @@ public static string Require() } return candidates.FirstOrDefault(candidate => - ScriptRuntimeLocator.CheckAsync(ScriptLanguage.PowerShell, candidate, Path.GetTempPath()).GetAwaiter().GetResult().Ok); + ScriptRuntimeLocator.CheckAsync(ScriptLanguage.PowerShell, candidate).GetAwaiter().GetResult().Ok); } } diff --git a/tests/TermRest.Core.Tests/JavaScriptScriptingTests.cs b/tests/TermRest.Core.Tests/JavaScriptScriptingTests.cs index c8b5437..8d975f6 100644 --- a/tests/TermRest.Core.Tests/JavaScriptScriptingTests.cs +++ b/tests/TermRest.Core.Tests/JavaScriptScriptingTests.cs @@ -134,6 +134,15 @@ public async Task Expect_has_the_chai_assertions_postman_scripts_use_with_chai_m () => pm.expect('a').to.exist, () => pm.expect(new Date(5)).to.be.a('date'), () => pm.expect({}).to.be.empty, + () => pm.expect([1, 2]).to.have.lengthOf.above(1), + () => pm.expect([1, 2]).to.have.lengthOf.at.least(2), + () => pm.expect([1, 2]).to.have.lengthOf.within(1, 3), + () => pm.expect(Object.freeze({})).to.be.frozen, + () => pm.expect(pm.response).to.be.postmanResponse, + () => pm.expect(1).to.not.be.null.and.not.undefined, + () => pm.expect([1, 2]).to.have.lengthOf.at.least(1).and.at.most(10), + () => pm.expect([1, 2]).to.have.lengthOf(2).and.be.above(1), + () => pm.expect([1, 2]).to.have.lengthOf('2'), ]; const failing = [ [() => pm.expect(404).to.equal(200), 'expected 404 to equal 200'], @@ -150,6 +159,37 @@ public async Task Expect_has_the_chai_assertions_postman_scripts_use_with_chai_m [() => pm.response.to.have.header('X-Missing'), "expected response to have header with key 'X-Missing'"], [() => pm.response.to.be.clientError, 'expected response code to be 4XX but found 200'], [() => pm.expect.fail('boom'), 'boom'], + [() => pm.expect(null).to.be.within(0, 120), 'expected null to be a number or a date'], + [() => pm.expect('42').to.not.be.within(0, 1), "expected '42' to be a number or a date"], + [() => pm.expect(null).to.be.closeTo(1, 0.5), 'expected null to be a number'], + [() => pm.expect('1.5').to.be.closeTo(1.4, 0.2), "expected '1.5' to be a number"], + [() => pm.expect(1.5).to.be.closeTo(1.4), 'the arguments to closeTo or approximately must be numbers, and a delta is required'], + [() => pm.expect([1, 2]).to.have.lengthOf.above(5), 'expected [ 1, 2 ] to have a length above 5 but got 2'], + [() => pm.expect(false).to.be.ture, 'Error: Invalid Chai property: ture. Did you mean "true"?'], + [() => pm.expect([1]).to.be.array, 'Error: Invalid Chai property: array. Did you mean "any"?'], + [() => pm.expect([1]).to.include.membres([1]), 'Error: Invalid Chai property: membres. Did you mean "members"?'], + [() => pm.response.to.be.created, 'Error: Invalid Chai property: created. Did you mean "nested"?'], + [() => pm.response.to.be.withoutContent, 'expected response code to be 204 but found 200'], + [() => pm.expect(null).to.exists, 'expected null to exist'], + [() => pm.expect({}).to.be.sealed, 'expected {} to be sealed'], + [() => pm.expect(undefined).to.not.be.null.and.not.undefined, 'expected undefined not to be undefined'], + [() => pm.expect(1).to.not.not.equal(1), 'expected 1 to not equal 1'], + [() => pm.expect([1, 2]).to.have.lengthOf.at.least(1).and.at.most(1), 'expected [ 1, 2 ] to have a length at most 1 but got 2'], + [() => pm.expect([1, 2]).to.have.length.equal(2), 'expected [ 1, 2 ] to equal 2'], + [() => pm.expect(new Date(5)).to.be.within(1, 9), 'the arguments to within must be dates'], + [() => pm.expect(5).to.not.be.within('1', '9'), 'the arguments to within must be numbers'], + [() => pm.expect([1, 2]).to.have.lengthOf.within('1', 3), 'the arguments to within must be numbers'], + [() => pm.expect(new Date(0)).to.be.within(new Date(5), new Date(9)), 'expected 1970-01-01T00:00:00.000Z to be within 1970-01-01T00:00:00.005Z..1970-01-01T00:00:00.009Z'], + [() => pm.expect(null).to.not.have.property('error'), 'Target cannot be null or undefined.'], + [() => pm.expect(undefined).to.have.nested.property('a.b'), 'Target cannot be null or undefined.'], + [() => pm.expect(null, 'data').to.not.have.own.property('a'), 'data: Target cannot be null or undefined.'], + [() => pm.expect(5).to.be.above('1'), 'the argument to above must be a number'], + [() => pm.expect(5).to.not.be.lte('9'), 'the argument to most must be a number'], + [() => pm.expect(new Date(5)).to.be.below(9), 'the argument to below must be a date'], + [() => pm.expect([1, 2]).to.have.lengthOf.at.least('1'), 'the argument to least must be a number'], + [() => pm.expect([1, 2]).to.not.have.lengthOf('2'), 'expected [ 1, 2 ] to not have a length of 2'], + [() => pm.expect({}).to.have.lengthOf(undefined), "expected {} to have property 'length'"], + [() => pm.expect(null).to.have.lengthOf(0), 'Target cannot be null or undefined.'], ]; passing.forEach((fn, index) => pm.test('passes ' + index, fn)); failing.forEach(([fn, message], index) => pm.test('fails ' + index + '|' + message, fn)); @@ -168,14 +208,180 @@ public async Task Expect_has_the_chai_assertions_postman_scripts_use_with_chai_m var results = exchange.Scripts!; Assert.True(results.Error is null, results.Describe()); var failures = results.Tests.Where(t => t.Name.StartsWith("fails ", StringComparison.Ordinal)).ToList(); - Assert.Equal(14, failures.Count); + Assert.Equal(45, failures.Count); Assert.All(results.Tests.Where(t => !t.Name.StartsWith("fails ", StringComparison.Ordinal)), t => Assert.True(t.Passed, $"{t.Name}: {t.Error}")); - Assert.Equal(31, results.Tests.Count(t => t.Passed)); + Assert.Equal(40, results.Tests.Count(t => t.Passed)); Assert.All(failures, t => { Assert.False(t.Passed, t.Name); Assert.Equal(t.Name[(t.Name.IndexOf('|', StringComparison.Ordinal) + 1)..], t.Error); }); + + var noContent = await runner.SendAsync(collection, null, JavaScript(server.Url("status/204"), test: """ + pm.test('no content', () => pm.response.to.be.withoutContent.and.not.withBody); + """), null, _ct); + + Assert.Equal(204, noContent.Response!.StatusCode); + Assert.True(noContent.Scripts!.Error is null, noContent.Scripts.Describe()); + Assert.Equal([("no content", true)], noContent.Scripts.Tests.Select(t => (t.Name, t.Passed))); + } + + /// + /// A stand-in for ajv in the workspace's node_modules (scripts take it from there): it checks only a schema's + /// type and format. As ajv 8 with strict: false, it logs a format it doesn't know and ignores it; + /// as ajv 6 ( 6), it knows email and throws on a format it doesn't know (unless told to + /// ignore it). With , a stand-in for ajv-formats that adds email: as the real one, it + /// works with ajv 7 and later only (it sets ajv.opts.code.formats). + /// + private static void WriteAjv(string root, bool formats, int version = 8) + { + var ajv = Path.Combine(root, "node_modules", "ajv"); + Directory.CreateDirectory(ajv); + File.WriteAllText(Path.Combine(ajv, "index.js"), version >= 7 + ? """ + module.exports = class Ajv { + constructor(opts) { this.opts = Object.assign({ code: {} }, opts); this.formats = {}; } + addFormat(name, check) { this.formats[name] = check; return this; } + validate(schema, data) { + const type = Array.isArray(data) ? 'array' : data === null ? 'null' : typeof data; + const errors = schema.type === undefined || schema.type === type ? [] : [{ message: 'must be ' + schema.type }]; + if (schema.format !== undefined && this.formats[schema.format] === undefined) { + this.opts.logger.warn('unknown format "' + schema.format + '" ignored in schema at path "#"'); + } else if (schema.format !== undefined && !this.formats[schema.format](data)) { + errors.push({ message: 'must match format "' + schema.format + '"' }); + } + this.errors = errors.length > 0 ? errors : null; + return this.errors === null; + } + errorsText() { return this.errors ? 'data ' + this.errors.map(e => e.message).join(', ') : 'No errors'; } + }; + """ + : """ + module.exports = class Ajv { + constructor(opts) { this._opts = opts; this._formats = { email: s => /^[^@\s]+@[^@\s]+$/.test(s) }; } + validate(schema, data) { + const type = Array.isArray(data) ? 'array' : data === null ? 'null' : typeof data; + const errors = schema.type === undefined || schema.type === type ? [] : [{ message: 'should be ' + schema.type }]; + if (schema.format !== undefined && this._formats[schema.format] === undefined) { + if (this._opts.unknownFormats !== 'ignore') throw new Error('unknown format "' + schema.format + '" is used in schema at path "#"'); + this._opts.logger.warn('unknown format "' + schema.format + '" ignored in schema at path "#"'); + } else if (schema.format !== undefined && !this._formats[schema.format](data)) { + errors.push({ message: 'should match format "' + schema.format + '"' }); + } + this.errors = errors.length > 0 ? errors : null; + return this.errors === null; + } + errorsText() { return this.errors ? 'data ' + this.errors.map(e => e.message).join(', ') : 'No errors'; } + }; + """); + if (formats) + { + var addFormats = Path.Combine(root, "node_modules", "ajv-formats"); + Directory.CreateDirectory(addFormats); + File.WriteAllText(Path.Combine(addFormats, "index.js"), "module.exports = ajv => { ajv.opts.code.formats = {}; ajv.addFormat('email', s => /^[^@\\s]+@[^@\\s]+$/.test(s)); };\n"); + } + } + + [Fact] + public async Task Json_schema_checks_a_response_body_or_any_value_as_in_postman() + { + var node = TestJavaScript.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + WriteAjv(workspace.RootPath, formats: false); + using var runner = new RequestRunner(workspace); + runner.SetJavaScriptRuntime(node); + + var exchange = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), test: """ + const body = pm.response.json(); + pm.test('response', () => pm.response.to.have.jsonSchema({ type: 'object' })); + pm.test('value', () => pm.expect(body).to.have.jsonSchema({ type: 'object' })); + pm.test('part', () => pm.expect([body.method]).to.have.jsonSchema({ type: 'array' })); + pm.test('mismatch', () => pm.expect(body).to.have.jsonSchema({ type: 'array' })); + pm.test('negated', () => pm.expect(body).to.not.have.jsonSchema({ type: 'object' })); + """), null, _ct); + + var results = exchange.Scripts!; + Assert.True(results.Error is null, results.Describe()); + Assert.Equal( + [("response", true, null), ("value", true, null), ("part", true, null), + ("mismatch", false, "expected data to satisfy schema but found following errors: \ndata must be array"), ("negated", false, "expected data to not satisfy schema")], + results.Tests.Select(t => (t.Name, t.Passed, t.Error))); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Json_schema_formats_are_checked_as_in_postman_or_the_test_says_what_to_install(bool formats) + { + // Postman's ajv 6 checks formats; ajv 8 only with ajv-formats, which would otherwise pass anything. + var node = TestJavaScript.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + WriteAjv(workspace.RootPath, formats); + using var runner = new RequestRunner(workspace); + runner.SetJavaScriptRuntime(node); + + var exchange = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), test: """ + pm.test('valid', () => pm.expect('ada@example.com').to.have.jsonSchema({ type: 'string', format: 'email' })); + pm.test('invalid', () => pm.expect('not an email').to.have.jsonSchema({ type: 'string', format: 'email' })); + pm.test('unknown', () => pm.expect('555').to.have.jsonSchema({ type: 'string', format: 'phone' })); + """), null, _ct); + + var results = exchange.Scripts!; + Assert.True(results.Error is null, results.Describe()); + static string Unknown(string format, bool install) => + $"unknown format \"{format}\" ignored in schema at path \"#\"" + (install ? ": install ajv-formats in the workspace (npm install ajv-formats), as Postman checks formats" : ""); + (string, bool, string?)[] expected = formats + ? [("valid", true, null), ("invalid", false, "expected data to satisfy schema but found following errors: \ndata must match format \"email\""), ("unknown", false, Unknown("phone", false))] + : [("valid", false, Unknown("email", true)), ("invalid", false, Unknown("email", true)), ("unknown", false, Unknown("phone", true))]; + Assert.Equal(expected, results.Tests.Select(t => (t.Name, t.Passed, t.Error))); + } + + [Fact] + public async Task Json_schema_uses_an_ajv_6_as_it_is_even_where_ajv_formats_is_installed() + { + // Postman's ajv 6 (or ESLint's) next to ajv-formats (for ajv 8, as npm installs it): ajv 6 checks formats itself. + var node = TestJavaScript.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + WriteAjv(workspace.RootPath, formats: true, version: 6); + using var runner = new RequestRunner(workspace); + runner.SetJavaScriptRuntime(node); + + var exchange = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), test: """ + pm.test('body', () => pm.response.to.have.jsonSchema({ type: 'object' })); + pm.test('invalid', () => pm.expect('not an email').to.have.jsonSchema({ type: 'string', format: 'email' })); + pm.test('unknown', () => pm.expect('555').to.have.jsonSchema({ type: 'string', format: 'phone' })); + pm.test('ignored', () => pm.expect('555').to.have.jsonSchema({ type: 'string', format: 'phone' }, { unknownFormats: 'ignore' })); + """), null, _ct); + + var results = exchange.Scripts!; + Assert.True(results.Error is null, results.Describe()); + Assert.Equal( + [("body", true, null), ("invalid", false, "expected data to satisfy schema but found following errors: \ndata should match format \"email\""), + ("unknown", false, "Error: unknown format \"phone\" is used in schema at path \"#\""), ("ignored", true, null)], + results.Tests.Select(t => (t.Name, t.Passed, t.Error))); + } + + [Fact] + public async Task Dates_and_urls_set_in_scripts_are_their_text() + { + var node = TestJavaScript.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetJavaScriptRuntime(node); + + var exchange = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), test: """ + pm.collectionVariables.set('when', new Date(0)); + pm.collectionVariables.set('site', new URL('https://example.org/a')); + pm.collectionVariables.set('flags', { on: true }); + """), null, _ct); + + Assert.True(exchange.Scripts!.Error is null, exchange.Scripts.Describe()); + var stored = runner.Session.For(collection); + Assert.Equal(("1970-01-01T00:00:00.000Z", "https://example.org/a", """{"on":true}"""), (stored["when"], stored["site"], stored["flags"])); } [Fact] @@ -210,6 +416,20 @@ public async Task Javascript_errors_show_the_script_line_and_a_failing_pre_reque var rejected = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), test: "Promise.reject(new Error('nobody caught this'));"), _ct); Assert.Equal("Error: nobody caught this", rejected.Scripts!.Error!.Message); + // What can't be turned into text fails its script (and its test), not the whole answer: what it logged is kept. + var bare = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), test: "console.log('before');\nthrow Object.create(null);"), _ct); + Assert.Equal("[object Object]", bare.Scripts!.Error!.Message); + Assert.Equal(["before"], bare.Scripts.Logs.Select(l => l.Text)); + var unreadable = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), test: """ + const error = new TypeError(); + Object.defineProperty(error, 'message', { get() { throw new Error('no text'); } }); + pm.test('unreadable', () => { throw error; }); + pm.test('bare', () => { throw Object.create(null); }); + throw error; + """), _ct); + Assert.Equal("TypeError: (its message could not be read)", unreadable.Scripts!.Error!.Message); + Assert.Equal(["TypeError: (its message could not be read)", "[object Object]"], unreadable.Scripts.Tests.Select(t => t.Error)); + var skipped = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), preRequest: "pm.execution.skipRequest();"), _ct); Assert.Null(skipped.Response); Assert.Contains("skipRequest() is not supported by TermRest, so the request is not sent", skipped.ErrorMessage, StringComparison.Ordinal); @@ -218,6 +438,45 @@ public async Task Javascript_errors_show_the_script_line_and_a_failing_pre_reque Assert.True(next.Scripts!.Succeeded, next.Scripts.Describe()); } + [Fact] + public async Task Scripts_may_set_the_host_and_path_of_the_url_as_text_as_in_postman() + { + var node = TestJavaScript.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetJavaScriptRuntime(node); + + var moved = await runner.SendAsync(collection, null, JavaScript("https://api.example.com:8443/v1/items?q=1#top", preRequest: $$""" + pm.request.url.protocol = 'http'; + pm.request.url.host = '{{server.BaseUri.Host}}'; + pm.request.url.port = {{server.BaseUri.Port}}; + pm.request.url.path = '/echo/moved'; + pm.request.url.hash = null; + console.log(pm.request.url.getHost(), pm.request.url.getPath()); + """), _ct); + + Assert.True(moved.Scripts!.Succeeded, moved.Scripts.Describe()); + Assert.Equal([$"{server.BaseUri.Host} /echo/moved"], moved.Scripts.Logs.Select(l => l.Text)); + var echo = JsonNode.Parse(System.Text.Encoding.UTF8.GetString(moved.Response!.Body))!; + Assert.Equal(("/echo/moved", "?q=1"), (echo["path"]!.GetValue(), echo["rawQuery"]!.GetValue())); + + // A request the scripts left unusable fails them, not the whole answer: what they printed, tested and set is kept. + var broken = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), preRequest: """ + console.log('before'); + pm.collectionVariables.set('kept', 'yes'); + pm.test('ran', () => {}); + pm.request.url.query = 'a=1'; + """), _ct); + + Assert.Null(broken.Response); + Assert.StartsWith("The pre-request scripts left a request that cannot be sent: TypeError: ", broken.Scripts!.Error!.Message, StringComparison.Ordinal); + Assert.Contains("\nScripts failed\n The pre-request scripts left", broken.Scripts.Describe(), StringComparison.Ordinal); // they ran + Assert.Equal(["before"], broken.Scripts.Logs.Select(l => l.Text)); + Assert.Equal([("ran", true)], broken.Scripts.Tests.Select(t => (t.Name, t.Passed))); + Assert.Equal("yes", runner.Session.For(collection)["kept"]); + } + [Fact] public async Task Scripts_wait_for_their_requests_timers_and_asynchronous_tests() { @@ -316,6 +575,7 @@ public async Task A_request_runs_its_scripts_in_the_first_language_of_the_order_ var refused = await runner.SendAsync(collection, javaScriptOnly, wrong, null, _ct); Assert.Null(refused.Response); Assert.Equal(0, refused.Scripts!.Ran); + Assert.StartsWith("Scripts did not run\n", refused.Scripts.Describe(), StringComparison.Ordinal); Assert.Equal( "Not sent: This request runs its scripts in Python (its Scripts tab), but there is no Python version of the post-response script of request " + "'Users/JavaScript only'. Write it in Python, choose another language, or turn post-response scripts off in its Scripts tab.", @@ -349,11 +609,23 @@ public async Task The_runtime_is_stopped_when_scripts_take_too_long_and_when_it_ child.spawnSync(require('process').execPath, ['-e', "console.log('stray output')"], { stdio: 'inherit' }); console.log('captured'); pm.test('still answers', () => {}); + const process = require('process'); + if (process.platform === 'linux') { + const stat = require('fs').readFileSync('/proc/self/stat', 'utf8'); + pm.globals.set('session', Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[3]) === process.pid ? 'its own' : "TermRest's"); + } """), _ct); Assert.True(stray.Scripts!.Succeeded, stray.Scripts.Describe()); Assert.Equal(["captured"], stray.Scripts.Logs.Select(l => l.Text)); Assert.True(runner.ScriptsRunning); + // Nor can it open TermRest's terminal (/dev/tty) on Linux, where setsid starts the runtime in a session of its own, + // which has none; setsid then became the runtime, which still runs (it did not fork it off). + if (OperatingSystem.IsLinux() && ScriptRuntimeLocator.Executable("setsid") is not null) + { + Assert.Equal("its own", runner.Session.Globals.GetValueOrDefault("session")); + } + var idle = Stopwatch.StartNew(); while (runner.ScriptsRunning && idle.Elapsed < TimeSpan.FromSeconds(20)) { @@ -365,6 +637,31 @@ public async Task The_runtime_is_stopped_when_scripts_take_too_long_and_when_it_ Assert.True(again.Scripts!.Succeeded, again.Scripts.Describe()); } + [Fact] + public async Task Halves_of_emoji_do_not_break_the_answer() + { + var node = TestJavaScript.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetJavaScriptRuntime(node); + + // A line cut at 4,000 characters, and a script's own substring of an emoji (not text: it becomes U+FFFD). + var exchange = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), test: """ + console.log('a' + '😀'.repeat(2000)); + const half = '😀'.substring(0, 1); + console.log('half ' + half + ' and a whole 😀'); + pm.test('test ' + half, () => {}); + pm.globals.set('name ' + half, half); + """), _ct); + + Assert.Equal(200, exchange.Response!.StatusCode); + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal(["a" + string.Concat(Enumerable.Repeat("😀", 1999)), "half \uFFFD and a whole 😀"], exchange.Scripts.Logs.Select(l => l.Text)); + Assert.Equal(["test \uFFFD"], exchange.Scripts.Tests.Select(t => t.Name)); + Assert.Equal("\uFFFD", runner.Session.Globals["name \uFFFD"]); + } + [Fact] public async Task Scripts_require_modules_from_the_workspace_and_say_how_to_install_missing_packages() { @@ -397,22 +694,43 @@ public async Task Scripts_require_modules_from_the_workspace_and_say_how_to_inst } } + [Fact] + public async Task What_required_modules_log_goes_to_the_scripts_output() + { + var node = TestJavaScript.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + await File.WriteAllTextAsync(Path.Combine(workspace.RootPath, "helpers.js"), + "module.exports.hi = () => { console.log('from helper module'); console.error('and its error'); };", _ct); + using var runner = new RequestRunner(workspace); + runner.SetJavaScriptRuntime(node); + + // Modules run outside the scripts' context, with the runtime's own console. + var exchange = await runner.SendAsync(collection, null, JavaScript(server.Url("echo"), preRequest: "require('./helpers').hi();\nconsole.log('from script');"), _ct); + + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal(["from helper module", "error: and its error", "from script"], exchange.Scripts.Logs.Select(l => l.Text)); + } + [Fact] public async Task The_runtime_check_names_the_runtime_and_its_version() { var node = TestJavaScript.Require(); var directory = TestFiles.NewTempDirectory(); - var (ok, message) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.JavaScript, node, directory, _ct); + var (ok, message) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.JavaScript, node, _ct); Assert.True(ok, message); Assert.Matches(@"^(Node\.js|Bun) \d+\.\d+\.\d+ · .+", message); - var (missingOk, missingMessage) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.JavaScript, "termrest-no-such-runtime", directory, _ct); + var (missingOk, missingMessage) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.JavaScript, "termrest-no-such-runtime", _ct); Assert.False(missingOk); Assert.StartsWith("termrest-no-such-runtime could not be started", missingMessage, StringComparison.Ordinal); var found = await ScriptRuntimeLocator.FindAsync(ScriptLanguage.JavaScript, directory, runtime => runtime, _ct); - Assert.NotNull(found); - Assert.Contains(found.Value.Runtime, (string[])["node", "bun"]); + if (found is not null || node is "node" or "bun") // TERMREST_TEST_JAVASCRIPT may name one that is not on PATH + { + Assert.NotNull(found); + Assert.Contains(found.Value.Runtime, (string[])["node", "bun"]); + } } } diff --git a/tests/TermRest.Core.Tests/MeasuredAloneTests.cs b/tests/TermRest.Core.Tests/MeasuredAloneTests.cs new file mode 100644 index 0000000..113b70d --- /dev/null +++ b/tests/TermRest.Core.Tests/MeasuredAloneTests.cs @@ -0,0 +1,49 @@ +using System.Text.Json.Nodes; +using TermRest.Core.Scripting; +using TermRest.Core.Tests.Infrastructure; +using Xunit; + +namespace TermRest.Core.Tests; + +/// Tests that measure what the whole process allocates run when no other test runs. +[CollectionDefinition("Measured alone", DisableParallelization = true)] +public sealed class MeasuredAloneGroup; + +[Collection("Measured alone")] +public sealed class ScriptOutputMemoryTests +{ + private readonly CancellationToken _ct = TestContext.Current.CancellationToken; + + [Fact] + public async Task TermRest_keeps_only_the_end_of_what_programs_that_scripts_start_print_without_a_newline() + { + var python = TestPython.Require(); + using var worker = ScriptWorker.For(ScriptLanguage.Python, python, TestFiles.NewTempDirectory()); + + // A program that a script starts (curl -s …) prints 64 MB without a newline to Python's stderr; then Python stops. + var message = new JsonObject + { + ["phase"] = "test", + ["scripts"] = new JsonArray(new JsonObject + { + ["name"] = "request", + ["code"] = """ + import os, subprocess, sys + subprocess.run([sys.executable, "-c", "import sys\nfor _ in range(64): sys.stdout.buffer.write(b'x' * (1 << 20))"]) + os.write(2, b"\r\nlast words\r\n") + os._exit(3) + """, + }), + }; + + var allocated = GC.GetTotalAllocatedBytes(precise: true); + var stopped = await Assert.ThrowsAsync(() => worker.RunAsync(message, TimeSpan.FromSeconds(60), cancellationToken: _ct)); + allocated = GC.GetTotalAllocatedBytes(precise: true) - allocated; + + // Its last 4,000 characters are kept, with why Python stopped; the 64 MB were never in memory. + Assert.StartsWith("Python stopped.\nxxx", stopped.Message, StringComparison.Ordinal); + Assert.EndsWith("x\nlast words", stopped.Message, StringComparison.Ordinal); + Assert.Equal("Python stopped.\n".Length + 3999, stopped.Message.Length); + Assert.True(allocated < 64 << 20, $"{allocated:N0} bytes were allocated"); + } +} diff --git a/tests/TermRest.Core.Tests/PostmanFidelityTests.cs b/tests/TermRest.Core.Tests/PostmanFidelityTests.cs index 9548697..c587f2a 100644 --- a/tests/TermRest.Core.Tests/PostmanFidelityTests.cs +++ b/tests/TermRest.Core.Tests/PostmanFidelityTests.cs @@ -50,6 +50,31 @@ public void Save_preserves_bom_crlf_and_trailing_newline() Assert.Equal(before, File.ReadAllBytes(path)); } + [Fact] + public void Saving_a_file_with_mixed_line_breaks_writes_the_kind_most_lines_have() + { + var directory = TestFiles.NewTempDirectory(); + var lf = File.ReadAllText(TestFiles.DemoCollection); + var lines = lf.Split('\n'); + lines[1] += "\r"; // one line saved by a Windows editor, or a merge + var mostlyLf = Path.Combine(directory, "lf.postman_collection.json"); + File.WriteAllText(mostlyLf, string.Join('\n', lines)); + var crlf = lf.Replace("\n", "\r\n", StringComparison.Ordinal); + var mostlyCrLf = Path.Combine(directory, "crlf.postman_collection.json"); + File.WriteAllText(mostlyCrLf, crlf.Replace("\"info\": {\r\n", "\"info\": {\n", StringComparison.Ordinal)); + + foreach (var path in (string[])[mostlyLf, mostlyCrLf]) + { + var collection = PostmanCollection.Load(path); + collection.MarkDirty(); + collection.Save(); + } + + // Only the stray line changes. + Assert.Equal(lf, File.ReadAllText(mostlyLf)); + Assert.Equal(crlf, File.ReadAllText(mostlyCrLf)); + } + [Theory] [InlineData("plain", "\"plain\"")] [InlineData("quote \" and \\ backslash", "\"quote \\\" and \\\\ backslash\"")] diff --git a/tests/TermRest.Core.Tests/PostmanRequestMapperTests.cs b/tests/TermRest.Core.Tests/PostmanRequestMapperTests.cs index 283e9ad..5c6f2e3 100644 --- a/tests/TermRest.Core.Tests/PostmanRequestMapperTests.cs +++ b/tests/TermRest.Core.Tests/PostmanRequestMapperTests.cs @@ -227,6 +227,32 @@ public void Auth_params_keep_non_string_values() Assert.Equal("{\"scope\":\"read\"}", parameters[3]!["value"]!.ToJsonString()); } + [Fact] + public void Untouched_values_keep_their_json_type_when_another_value_changes() + { + var directory = TestFiles.NewTempDirectory(); + var json = Path.Combine(directory, "typed.postman_environment.json"); + File.WriteAllText(json, """ + {"name": "Typed", "values": [ + {"key": "retries", "value": 5, "type": "any", "enabled": true}, + {"key": "verbose", "value": true, "type": "any", "enabled": true}, + {"key": "user", "value": {"id": 1}, "type": "any", "enabled": true}, + {"key": "token", "value": "a", "type": "default", "enabled": true} + ]} + """); + var environment = PostmanEnvironment.Load(json); + environment.SetValue("token", "b"); + environment.Save(); + Assert.Equal(["5", "true", "{\"id\":1}", "\"b\""], PostmanJson.Parse(File.ReadAllText(json))["values"]!.AsArray().Select(v => v!["value"]!.ToJsonString())); + + var yaml = Path.Combine(directory, "Typed.environment.yaml"); + File.WriteAllText(yaml, "name: Typed\nvalues:\n - key: retries\n value: 5\n enabled: true\n - key: token\n value: a\n enabled: true\n"); + environment = PostmanEnvironment.Load(yaml); + environment.SetValue("token", "b"); + environment.Save(); + Assert.Equal("name: Typed\nvalues:\n - key: retries\n value: 5\n enabled: true\n - key: token\n value: b\n enabled: true\n", File.ReadAllText(yaml)); + } + [Fact] public void Legacy_v20_auth_is_read_and_written_in_v20_shape() { diff --git a/tests/TermRest.Core.Tests/PostmanV3Tests.cs b/tests/TermRest.Core.Tests/PostmanV3Tests.cs index c140112..e781c93 100644 --- a/tests/TermRest.Core.Tests/PostmanV3Tests.cs +++ b/tests/TermRest.Core.Tests/PostmanV3Tests.cs @@ -1,5 +1,6 @@ using System.Text.Json.Nodes; using TermRest.Core.Http; +using TermRest.Core.IO; using TermRest.Core.Model; using TermRest.Core.Postman; using TermRest.Core.Postman.V3; @@ -75,6 +76,131 @@ public void Opens_a_postman_v3_workspace() Assert.True(collection.GetVariables()[1].IsSecret); } + [Fact] + public void A_collection_with_a_folder_named_postman_opens_as_a_collection_of_its_workspace() + { + var root = TestFiles.NewTempDirectory(); + var integrations = Path.Combine(root, "postman", "collections", "Integrations"); + foreach (var folder in (string[])["GitHub", "postman"]) + { + Directory.CreateDirectory(Path.Combine(integrations, folder)); + File.WriteAllText(Path.Combine(integrations, folder, "Ping.request.yaml"), $"$kind: http-request\nurl: https://{folder.ToLowerInvariant()}.example.com/ping\nmethod: GET\n"); + } + + var workspace = ApiWorkspace.Open(integrations); + + Assert.Equal(Path.TrimEndingDirectorySeparator(root), Path.TrimEndingDirectorySeparator(workspace.RootPath)); + Assert.Equal(Path.TrimEndingDirectorySeparator(root), ApiWorkspace.RootFor(integrations)); + Assert.Equal(["Integrations"], workspace.Collections.Select(c => c.Name)); + Assert.NotNull(workspace.FindCollection(integrations)); + } + + [Fact] + public void Folders_of_a_workspace_that_cannot_be_listed_are_load_errors_and_the_rest_opens() + { + // As a link to a collection of another repository that was moved, or a folder of another user. + var root = V3Fixture.Create(); + var shared = Directory.CreateDirectory(Path.Combine(root, "postman", "collections", "Shared")).FullName; + var environments = Path.Combine(root, "postman", "environments"); + Listable(shared, false); + Listable(environments, false); + try + { + try + { + Directory.GetFileSystemEntries(environments); + Assert.Skip("This user can list any folder (root)."); + } + catch (UnauthorizedAccessException) + { + // as for other users + } + + var workspace = ApiWorkspace.Open(root); + + Assert.Equal(["Widget API"], workspace.Collections.Select(c => c.Name)); + Assert.NotNull(workspace.Globals); + Assert.Contains(workspace.LoadErrors, e => e.StartsWith("Shared: ", StringComparison.Ordinal)); + Assert.Contains(workspace.LoadErrors, e => e.StartsWith(Path.Combine("postman", "environments") + ": ", StringComparison.Ordinal)); + } + finally + { + Listable(shared, true); + Listable(environments, true); + } + } + + [Fact] + public void Links_of_a_workspace_to_folders_that_are_gone_are_load_errors() + { + // As a collection linked from another repository that was moved: on Linux and macOS, such a link is no folder at all. + var root = V3Fixture.Create(); + var gone = Path.Combine(TestFiles.NewTempDirectory(), "gone"); + var environments = Path.Combine(root, "postman", "environments"); + Directory.Delete(environments, recursive: true); + try + { + Directory.CreateSymbolicLink(environments, gone); + Directory.CreateSymbolicLink(Path.Combine(root, "postman", "collections", "Payments"), gone); + } + catch (Exception e) when (e is UnauthorizedAccessException or IOException) + { + Assert.Skip($"Cannot create symbolic links here (Windows needs Developer Mode or elevation): {e.Message}"); + } + + var workspace = ApiWorkspace.Open(root); + + Assert.Equal(["Widget API"], workspace.Collections.Select(c => c.Name)); + Assert.Contains($"Payments: it links to {gone}, which is not there.", workspace.LoadErrors); + Assert.Contains($"{Path.Combine("postman", "environments")}: it links to {gone}, which is not there.", workspace.LoadErrors); + Assert.DoesNotContain(workspace.LoadErrors, e => e.StartsWith("Payments: ", StringComparison.Ordinal) && !e.Contains("it links to", StringComparison.Ordinal)); + } + + /// Lets the current user list , or not. + private static void Listable(string folder, bool listable) + { + if (OperatingSystem.IsWindows()) + { + var directory = new DirectoryInfo(folder); + var security = directory.GetAccessControl(); + var rule = new System.Security.AccessControl.FileSystemAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().User!, + System.Security.AccessControl.FileSystemRights.ListDirectory, System.Security.AccessControl.AccessControlType.Deny); + if (listable) + { + security.RemoveAccessRule(rule); + } + else + { + security.AddAccessRule(rule); + } + + directory.SetAccessControl(security); + } + else + { + File.SetUnixFileMode(folder, listable ? UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute : UnixFileMode.None); + } + } + + [Fact] + public void A_collection_whose_requests_are_all_in_folders_and_that_has_no_definition_is_loaded() + { + // Postman writes no definition for a collection without settings of its own; a folder of other files is no collection. + var root = TestFiles.NewTempDirectory(); + var shop = Path.Combine(root, "postman", "collections", "Shop"); + Directory.CreateDirectory(Path.Combine(shop, "Cart", "Items")); + File.WriteAllText(Path.Combine(shop, "Cart", "Items", "Add item.request.yaml"), "$kind: http-request\nurl: https://shop.example.com/cart/items\nmethod: POST\n"); + var stray = Path.Combine(root, "postman", "collections", "postman", "environments"); + Directory.CreateDirectory(stray); + File.WriteAllText(Path.Combine(stray, "Dev.environment.yaml"), "name: Dev\nvalues: []\n"); + + var (_, collection) = Open(root); + + Assert.Equal(("Shop", true), (collection.Name, collection.IsV3)); + Assert.Equal(["[Cart]", "[Cart/Items]", "Cart/Items/Add item"], Tree(collection)); + Assert.Throws(() => PostmanCollection.Load(Path.Combine(root, "postman", "collections", "postman"))); + } + [Fact] public void Requests_resolve_inherited_auth_and_variables_like_postman() { @@ -98,6 +224,189 @@ public void Requests_resolve_inherited_auth_and_variables_like_postman() Assert.Equal("{{apiKey}}", collection.RootNode.Auth!.Get("value")); } + [Fact] + public void Credential_sets_are_chosen_by_their_url_rules_and_go_nowhere_else() + { + // Postman writes a set's rules as a map (url: pattern), its schema as a list of {key, value}; values may hold variables. + var root = V3Fixture.Create(); + var definition = Path.Combine(V3Fixture.CollectionPath(root), "Widgets", ".resources", "definition.yaml"); + File.WriteAllText(definition, """ + $kind: collection + auth: + - id: p + type: bearer + name: Production + credentials: + token: prod-token-123 + rules: + url: https://api.example.com/* + - id: s + type: bearer + name: Sandbox + credentials: + token: '{{sandboxToken}}' + rules: + - key: url + value: '{{sandboxHost}}' + order: 2000 + + """.ReplaceLineEndings("\n")); + var (workspace, collection) = Open(root); + using var runner = new RequestRunner(workspace); + runner.LocalVariables["sandboxToken"] = "sandbox-token-456"; + runner.LocalVariables["sandboxHost"] = "sandbox.example.com"; + var node = collection.FindRequest("Widgets/List widgets")!; + PreparedRequest Prepare(string url) + { + var spec = node.ReadSpec(); + spec.Url = url; + spec.QueryParams = []; + return runner.Prepare(collection, node, spec); + } + + var production = Prepare("https://api.example.com/v1/widgets"); + var sandbox = Prepare("https://sandbox.example.com/v1/widgets"); + var elsewhere = Prepare("https://hooks.example.org/notify"); + + Assert.Equal("Bearer prod-token-123", production.GetHeader("Authorization")); + Assert.Equal("Bearer sandbox-token-456", sandbox.GetHeader("Authorization")); + Assert.Null(elsewhere.GetHeader("Authorization")); + Assert.Contains(elsewhere.Warnings, w => w.StartsWith("No credential set of the inherited auth ('Production', 'Sandbox')", StringComparison.Ordinal)); + + // The history keeps the set that was used, and none of the others; where none matched, no auth (not "inherit", which + // an entry sent again on its own would take from the collection). + Assert.Equal("{{sandboxToken}}", sandbox.Source!.Spec.Auth!.Get("token")); + Assert.True(sandbox.Source.AuthInherited); + Assert.Equal("noauth", elsewhere.Source!.Spec.Auth!.Type); + + // The file keeps its sets; a v2.1 copy can hold one auth only, so its first set stands in for them, and says so. + var written = File.ReadAllText(definition); + collection.MarkDirty(); + collection.Save(); + var writtenFile = File.ReadAllText(definition); + Assert.Equal(written, writtenFile); + var exported = collection.ExportV21Json(); + Assert.DoesNotContain(V3Convert.AuthSetsProperty, exported, StringComparison.Ordinal); + Assert.DoesNotContain("sandbox", exported, StringComparison.OrdinalIgnoreCase); + Assert.Equal(["folder 'Widgets'"], collection.CredentialSetsLeftOutOfV21()); + + // A copy of the folder, which has no file to write over, keeps the sets and their rules, with ids of its own. + collection.Duplicate(collection.FindFolder("Widgets")!); + collection.Save(); + var copied = File.ReadAllText(Path.Combine(V3Fixture.CollectionPath(root), "Widgets Copy", ".resources", "definition.yaml")); + Assert.DoesNotContain("id: p\n", copied, StringComparison.Ordinal); + Assert.DoesNotContain("id: s\n", copied, StringComparison.Ordinal); + var (_, reloaded) = Open(root); + var sets = reloaded.FindFolder("Widgets Copy")!.Auth!.CredentialSets!; + Assert.Equal(["Production", "Sandbox"], sets.Select(s => s.Name)); + Assert.Equal([KeyValuePair.Create("url", "https://api.example.com/*")], sets[0].Rules); + Assert.Equal([KeyValuePair.Create("url", "{{sandboxHost}}")], sets[1].Rules); + } + + [Fact] + public void A_file_without_a_final_line_break_is_saved_without_one() + { + var root = V3Fixture.Create(); + var request = Path.Combine(V3Fixture.CollectionPath(root), "Health.request.yaml"); + var environmentFile = Path.Combine(root, "postman", "environments", "Local.environment.yaml"); + foreach (var file in (string[])[request, environmentFile]) + { + File.WriteAllText(file, File.ReadAllText(file).TrimEnd('\n')); + } + + var (workspace, collection) = Open(root); + var health = collection.FindRequest("Health")!; + var spec = health.ReadSpec(); + spec.Description = "Edited."; + collection.UpdateRequest(health, spec); + collection.Save(); + var environment = workspace.Environments[0]; + environment.SetValue("baseUrl", "http://localhost:9090"); + environment.Save(); + + Assert.Contains("description: Edited.", File.ReadAllText(request), StringComparison.Ordinal); + Assert.Contains("http://localhost:9090", File.ReadAllText(environmentFile), StringComparison.Ordinal); + Assert.All((string[])[request, environmentFile], file => Assert.False(File.ReadAllText(file).EndsWith('\n'), file)); + } + + [Fact] + public void A_file_without_a_final_line_break_gets_one_when_its_last_value_ends_with_one() + { + // Its last value is then written as a block (|), whose final line break is part of the value. + var root = V3Fixture.Create(); + var request = Path.Combine(V3Fixture.CollectionPath(root), "Bulk.request.yaml"); + File.WriteAllText(request, "$kind: http-request\nurl: '{{baseUrl}}/_bulk'\nmethod: POST\norder: 3000\nbody:\n type: text\n content: |-\n {\"index\":{}}"); + var environmentFile = Path.Combine(root, "postman", "environments", "Certs.environment.yaml"); + File.WriteAllText(environmentFile, "name: Certs\nvalues:\n - key: pem\n value: none"); + const string Bulk = "{\"index\":{}}\n{\"name\":\"Sprocket\"}\n"; // NDJSON, which must end with a line break + const string Pem = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"; + + var (workspace, collection) = Open(root); + var bulk = collection.FindRequest("Bulk")!; + var spec = bulk.ReadSpec(); + spec.Body!.Raw = Bulk; + collection.UpdateRequest(bulk, spec); + collection.Save(); + var certs = workspace.Environments.Single(e => e.Name == "Certs"); + certs.SetValue("pem", Pem); + certs.Save(); + + var (reopened, reloaded) = Open(root); + Assert.Equal(Bulk, reloaded.FindRequest("Bulk")!.ReadSpec().Body!.Raw); + Assert.Equal(Pem, reopened.Environments.Single(e => e.Name == "Certs").Values.Single(v => v.Key == "pem").Value); + Assert.All((string[])[request, environmentFile], file => Assert.EndsWith("\n", File.ReadAllText(file), StringComparison.Ordinal)); + } + + [Fact] + public void A_file_without_a_final_line_break_that_ends_with_a_block_is_saved_as_it_is() + { + // As an editor that adds no final line break leaves it: the block's value has none either. + var root = V3Fixture.Create(); + var request = Path.Combine(V3Fixture.CollectionPath(root), "Notes.request.yaml"); + File.WriteAllText(request, "$kind: http-request\nurl: '{{baseUrl}}/notes'\nmethod: GET\norder: 3000\ndescription: |\n Notes."); + var environmentFile = Path.Combine(root, "postman", "environments", "Certs.environment.yaml"); + File.WriteAllText(environmentFile, "name: Certs\nvalues:\n - key: host\n value: a\n - key: pem\n value: |\n PEM"); + + var (workspace, collection) = Open(root); + var notes = collection.FindRequest("Notes")!; + var spec = notes.ReadSpec(); + spec.Url = "{{baseUrl}}/notes?all=1"; + collection.UpdateRequest(notes, spec); + collection.Save(); + var certs = workspace.Environments.Single(e => e.Name == "Certs"); + certs.SetValue("host", "b"); + certs.Save(); + + var (reopened, reloaded) = Open(root); + Assert.Equal(("{{baseUrl}}/notes?all=1", "Notes."), (reloaded.FindRequest("Notes")!.ReadSpec().Url, reloaded.FindRequest("Notes")!.ReadSpec().Description)); + Assert.Equal(["b", "PEM"], reopened.Environments.Single(e => e.Name == "Certs").Values.Select(v => v.Value)); + Assert.All((string[])[request, environmentFile], file => Assert.False(File.ReadAllText(file).EndsWith('\n'), file)); + } + + [Fact] + public void A_block_that_ended_a_file_without_a_final_line_break_keeps_its_value_when_something_is_added_after_it() + { + // There its value has no final line break: copied as it is before new lines, it would get one. + var root = V3Fixture.Create(); + var request = Path.Combine(V3Fixture.CollectionPath(root), "Notes.request.yaml"); + File.WriteAllText(request, "$kind: http-request\nurl: '{{baseUrl}}/notes'\nmethod: GET\ndescription: |\n Notes."); // no order + var environmentFile = Path.Combine(root, "postman", "environments", "Certs.environment.yaml"); + File.WriteAllText(environmentFile, "name: Certs\nvalues:\n - key: pem\n value: |\n -----BEGIN-----\n MIIB\n -----END-----"); + + var (workspace, collection) = Open(root); + collection.AddRequest(collection.RootNode, "Zeta", new HttpRequestSpec { Url = "{{baseUrl}}/zeta" }); // Notes gets an order, last + collection.Save(); + var certs = workspace.Environments.Single(e => e.Name == "Certs"); + certs.SetValue("token", "t-1"); // after the PEM + certs.Save(); + + var (reopened, reloaded) = Open(root); + Assert.Equal("Notes.", reloaded.FindRequest("Notes")!.ReadSpec().Description); + Assert.Contains("order:", File.ReadAllText(request), StringComparison.Ordinal); + Assert.Equal(["-----BEGIN-----\nMIIB\n-----END-----", "t-1"], reopened.Environments.Single(e => e.Name == "Certs").Values.Select(v => v.Value)); + Assert.All((string[])[request, environmentFile], file => Assert.False(File.ReadAllText(file).EndsWith('\n'), file)); + } + [Fact] public void Saving_without_changes_writes_nothing() { @@ -135,103 +444,763 @@ public void Editing_a_request_rewrites_only_the_edited_lines() collection.Save(); var after = V3Fixture.Snapshot(root); - var changedFiles = after.Keys.Where(k => !before.TryGetValue(k, out var text) || text != after[k]).ToList(); - Assert.Equal(["postman/collections/Widget API/Widgets/Create widget.request.yaml", "postman/collections/Widget API/Widgets/List widgets.request.yaml"], changedFiles.Order()); - const string list = "postman/collections/Widget API/Widgets/List widgets.request.yaml"; - Assert.Equal( - ["- url: '{{baseUrl}}/v1/widgets?limit=50'", "- Accept: application/json", "+ url: '{{baseUrl}}/v2/widgets?limit=50'", "+ Accept: application/xml"], - TestFiles.ChangedLines(before[list], after[list])); - const string createFile = "postman/collections/Widget API/Widgets/Create widget.request.yaml"; - Assert.Equal(["- disabled: true", "- \"name\": \"Sprocket\",", "+ \"name\": \"Gear\","], TestFiles.ChangedLines(before[createFile], after[createFile])); + var changedFiles = after.Keys.Where(k => !before.TryGetValue(k, out var text) || text != after[k]).ToList(); + Assert.Equal(["postman/collections/Widget API/Widgets/Create widget.request.yaml", "postman/collections/Widget API/Widgets/List widgets.request.yaml"], changedFiles.Order()); + const string list = "postman/collections/Widget API/Widgets/List widgets.request.yaml"; + Assert.Equal( + ["- url: '{{baseUrl}}/v1/widgets?limit=50'", "- Accept: application/json", "+ url: '{{baseUrl}}/v2/widgets?limit=50'", "+ Accept: application/xml"], + TestFiles.ChangedLines(before[list], after[list])); + const string createFile = "postman/collections/Widget API/Widgets/Create widget.request.yaml"; + Assert.Equal(["- disabled: true", "- \"name\": \"Sprocket\",", "+ \"name\": \"Gear\","], TestFiles.ChangedLines(before[createFile], after[createFile])); + + var reloaded = PostmanCollection.Load(V3Fixture.CollectionPath(root)); + Assert.True(spec.ContentEquals(reloaded.FindRequest("List widgets")!.ReadSpec())); + Assert.True(createSpec.ContentEquals(reloaded.FindRequest("Create widget")!.ReadSpec())); + } + + [Fact] + public void File_bodies_keep_their_type_in_yaml() + { + var root = V3Fixture.Create(); + var (_, collection) = Open(root); + var node = collection.FindRequest("Create widget")!; + var spec = node.ReadSpec(); + spec.Body = new RequestBody { Mode = BodyMode.File, FileSrc = "payloads/widget.json", FileLanguage = "json" }; + collection.UpdateRequest(node, spec); + collection.Save(); + + var yaml = File.ReadAllText(Path.Combine(root, "postman/collections/Widget API/Widgets/Create widget.request.yaml")).ReplaceLineEndings("\n"); + Assert.Contains(" type: file\n content:\n src: payloads/widget.json\n language: json\n", yaml, StringComparison.Ordinal); + var reloaded = PostmanCollection.Load(V3Fixture.CollectionPath(root)).FindRequest("Create widget")!.ReadSpec(); + Assert.Equal((BodyMode.File, "payloads/widget.json", "json"), (reloaded.Body.Mode, reloaded.Body.FileSrc, reloaded.Body.FileLanguage)); + } + + [Fact] + public void Form_data_descriptions_are_kept_and_saved() + { + var root = V3Fixture.Create(); + var file = Path.Combine(V3Fixture.CollectionPath(root), "Widgets", "Upload image.request.yaml"); + File.WriteAllText(file, File.ReadAllText(file).Replace(" value: Foo Bar\n", " value: Foo Bar\n description: Shown under the image\n", StringComparison.Ordinal)); + var before = File.ReadAllText(file); + var (_, collection) = Open(root); + Assert.DoesNotContain(collection.Verify(), p => p.Contains("Upload image", StringComparison.Ordinal)); + + var upload = collection.FindRequest("Upload image")!; + var spec = upload.ReadSpec(); + spec.Body.FormData[1].Description = "A PNG or JPEG image"; + collection.UpdateRequest(upload, spec); + collection.Save(); + + var after = File.ReadAllText(file); + Assert.Equal(["+ description: A PNG or JPEG image"], TestFiles.ChangedLines(before, after)); + Assert.Contains(" src: []\n description: A PNG or JPEG image\n disabled: false\n", after, StringComparison.Ordinal); + var reloaded = PostmanCollection.Load(V3Fixture.CollectionPath(root)).FindRequest("Upload image")!.ReadSpec(); + Assert.Equal(["Shown under the image", "A PNG or JPEG image"], reloaded.Body.FormData.Select(f => f.Description)); + } + + [Fact] + public void Renames_moves_deletes_and_additions_update_the_folder_layout() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var (_, collection) = Open(root); + var widgets = collection.FindFolder("Widgets")!; + var admin = collection.FindFolder("Admin")!; + + collection.Rename(collection.FindRequest("List widgets")!, "List all widgets"); + collection.Move(collection.FindRequest("Create widget")!, collection.RootNode, 1); + collection.Remove(collection.FindRequest("Upload image")!); + collection.Rename(admin, "Administration"); + collection.AddRequest(admin, "Audit: who/what?", new HttpRequestSpec { Method = "GET", Url = "{{baseUrl}}/audit" }); + collection.Duplicate(collection.FindRequest("Health")!); + collection.AddFolder(collection.RootNode, "Reports"); + collection.Save(); + + string F(string relative) => Path.Combine(collectionPath, relative.Replace('/', Path.DirectorySeparatorChar)); + Assert.True(File.Exists(F("Widgets/List all widgets.request.yaml"))); + Assert.False(File.Exists(F("Widgets/List widgets.request.yaml"))); + Assert.True(File.Exists(F("Widgets/.resources/List all widgets.resources/examples/200 OK.example.yaml"))); + Assert.False(Directory.Exists(F("Widgets/.resources/List widgets.resources"))); + Assert.Contains("examples: ./.resources/List all widgets.resources/examples", File.ReadAllText(F("Widgets/List all widgets.request.yaml")), StringComparison.Ordinal); + // Moved and new items get orders between their neighbors (Health 1000, Widgets 2000) or after the last one. + Assert.True(File.Exists(F("Create widget.request.yaml"))); + Assert.Contains("order: 1666", File.ReadAllText(F("Create widget.request.yaml")), StringComparison.Ordinal); + Assert.Contains("order: 1333", File.ReadAllText(F("Health Copy.request.yaml")), StringComparison.Ordinal); + Assert.Equal("$kind: collection\norder: 3000\n", File.ReadAllText(F("Administration/.resources/definition.yaml"))); + Assert.Equal("$kind: collection\norder: 4000\n", File.ReadAllText(F("Reports/.resources/definition.yaml"))); + Assert.False(File.Exists(F("Widgets/Upload image.request.yaml"))); + Assert.True(File.Exists(F("Widgets/Subscribe.request.yaml")), "files TermRest does not show are kept"); + Assert.False(Directory.Exists(F("Admin"))); + Assert.True(File.Exists(F("Administration/Reset.request.yaml"))); + Assert.Contains("name: \"Audit: who/what?\"", File.ReadAllText(F("Administration/Audit- who-what-.request.yaml")), StringComparison.Ordinal); + Assert.True(File.Exists(F("Health Copy.request.yaml"))); + Assert.True(File.Exists(F("Reports/.resources/definition.yaml"))); + Assert.Empty(Directory.EnumerateDirectories(collectionPath, ".termrest-saving-*")); + + // What is on disk now reads back as the same tree. + var reloaded = PostmanCollection.Load(collectionPath); + Assert.Equal(Tree(collection), Tree(reloaded)); + foreach (var request in collection.AllRequests()) + { + Assert.True(request.ReadSpec().ContentEquals(reloaded.FindRequest(request.PathInCollection)!.ReadSpec()), request.PathInCollection); + } + + // A second save with no further changes writes nothing. + var snapshot = V3Fixture.Snapshot(root); + collection.MarkDirty(); + collection.Save(); + Assert.Equal(snapshot, V3Fixture.Snapshot(root)); + } + + [Fact] + public void Deleting_a_folder_keeps_requests_termrest_does_not_show() + { + var root = V3Fixture.Create(); + var (_, collection) = Open(root); + + collection.Remove(collection.FindFolder("Widgets")!); + collection.Save(); + + var widgets = Path.Combine(V3Fixture.CollectionPath(root), "Widgets"); + Assert.Equal(["Subscribe.request.yaml"], Directory.EnumerateFiles(widgets).Select(Path.GetFileName)); + Assert.False(File.Exists(Path.Combine(widgets, ".resources", "definition.yaml"))); + } + + [Fact] + public void A_definition_that_could_not_be_read_is_never_overwritten_when_its_folder_moves() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var definition = Path.Combine(collectionPath, "Widgets", ".resources", "definition.yaml"); + var conflicted = File.ReadAllText(definition).Replace( + "description: Widget endpoints.\n", + "<<<<<<< HEAD\ndescription: Widget endpoints.\n=======\ndescription: All widget endpoints.\n>>>>>>> feature\n", + StringComparison.Ordinal); + File.WriteAllText(definition, conflicted); + var (workspace, collection) = Open(root); + Assert.Contains(workspace.LoadErrors, e => e.Contains("definition.yaml", StringComparison.Ordinal)); + + // Moved into another folder and renamed: the file moves along unchanged. + collection.Move(collection.FindFolder("Widgets")!, collection.FindFolder("Admin")!, 0); + collection.Rename(collection.FindFolder("Admin/Widgets")!, "Widgets v2"); + collection.Save(); + Assert.Equal(conflicted, File.ReadAllText(Path.Combine(collectionPath, "Admin", "Widgets v2", ".resources", "definition.yaml"))); + + // Moved along with its parent. + collection.Rename(collection.FindFolder("Admin")!, "Administration"); + collection.Save(); + Assert.Equal(conflicted, File.ReadAllText(Path.Combine(collectionPath, "Administration", "Widgets v2", ".resources", "definition.yaml"))); + Assert.NotNull(PostmanCollection.Load(collectionPath).FindRequest("Administration/Widgets v2/List widgets")); + } + + [Fact] + public void Edits_a_definition_that_could_not_be_read_would_have_to_hold_are_reported_not_dropped() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var definition = Path.Combine(collectionPath, "Widgets", ".resources", "definition.yaml"); + var rootDefinition = Path.Combine(collectionPath, ".resources", "definition.yaml"); + var list = Path.Combine(collectionPath, "Widgets", "List widgets.request.yaml"); + const string conflicted = "<<<<<<< HEAD\n$kind: collection\n=======\n$kind: collection\ndescription: theirs\n>>>>>>> theirs\n"; + File.WriteAllText(definition, conflicted); + File.WriteAllText(rootDefinition, conflicted); + var (_, collection) = Open(root); + + collection.SetScripts(collection.FindFolder("Widgets")!, new ScriptSet("console.log('before');", "", ScriptLanguage.JavaScript)); + collection.Name = "Widget API v2"; // a name only the definition can hold + SetMethod(collection, "Health", "HEAD"); + SetMethod(collection, "Widgets/List widgets", "PUT"); + File.AppendAllText(list, "# changed meanwhile\n"); + + // Everything else is saved; both reasons are told, and overwriting cannot help the files that could not be read. + var error = Assert.Throws(() => collection.Save()); + Assert.All((string[])[definition, rootDefinition, list], file => Assert.Contains(file, error.Message, StringComparison.Ordinal)); + Assert.Equal(conflicted, File.ReadAllText(definition)); + Assert.Equal(conflicted, File.ReadAllText(rootDefinition)); + Assert.Contains("method: HEAD\n", File.ReadAllText(Path.Combine(collectionPath, "Health.request.yaml")), StringComparison.Ordinal); + Assert.True(collection.IsDirty); + Assert.Throws(() => collection.Save(overwriteChanged: true)); + Assert.Contains("method: PUT\n", File.ReadAllText(list), StringComparison.Ordinal); + Assert.Equal(conflicted, File.ReadAllText(definition)); + + // Deleted to start over: saving writes what TermRest has. + File.Delete(definition); + File.Delete(rootDefinition); + collection.Save(); + var reloaded = PostmanCollection.Load(collectionPath); + Assert.Equal("Widget API v2", reloaded.Name); + Assert.Equal("console.log('before');", reloaded.GetScripts(reloaded.FindFolder("Widgets")!).For(ScriptLanguage.JavaScript).PreRequest); + } + + [Fact] + public void Files_changed_on_disk_since_they_were_read_are_not_saved_over() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + string F(string relative) => Path.Combine(collectionPath, relative.Replace('/', Path.DirectorySeparatorChar)); + var (workspace, collection) = Open(root); + var environment = workspace.Environments[0]; + + // A git pull changes files TermRest edits (the first one keeps its length), and one it leaves alone; another is only touched. + var list = F("Widgets/List widgets.request.yaml"); + var definition = F("Widgets/.resources/definition.yaml"); + var upload = F("Widgets/Upload image.request.yaml"); + var pulled = new Dictionary + { + [list] = File.ReadAllText(list).Replace("/v1/widgets", "/v2/widgets", StringComparison.Ordinal), + [definition] = File.ReadAllText(definition).Replace("Widget endpoints.", "All widget endpoints.", StringComparison.Ordinal), + [upload] = File.ReadAllText(upload).Replace("Foo Bar", "Baz", StringComparison.Ordinal), + [environment.FilePath!] = File.ReadAllText(environment.FilePath!).Replace("8080", "9090", StringComparison.Ordinal), + }; + foreach (var (path, text) in pulled) + { + File.WriteAllText(path, text); + File.SetLastWriteTimeUtc(path, DateTime.UtcNow.AddMinutes(1)); + } + + File.SetLastWriteTimeUtc(F("Health.request.yaml"), DateTime.UtcNow.AddMinutes(1)); + environment.MarkDirty(); + environment.Save(); // nothing to write: no conflict + + SetMethod(collection, "Widgets/List widgets", "PUT"); + SetMethod(collection, "Health", "HEAD"); + SetMethod(collection, "Widgets/Create widget", "PATCH"); + collection.SetScripts(collection.FindFolder("Widgets")!, new ScriptSet("console.log('before');", "", ScriptLanguage.JavaScript)); + environment.SetValue("token", "t-1"); + + Assert.Equal([definition, list], Assert.Throws(() => collection.Save()).Paths.Order(StringComparer.Ordinal)); + Assert.Equal([environment.FilePath!], Assert.Throws(() => environment.Save()).Paths); + Assert.All(pulled, p => Assert.Equal(p.Value, File.ReadAllText(p.Key))); + Assert.Contains("method: HEAD\n", File.ReadAllText(F("Health.request.yaml")), StringComparison.Ordinal); + Assert.Contains("method: PATCH\n", File.ReadAllText(F("Widgets/Create widget.request.yaml")), StringComparison.Ordinal); + Assert.True(collection.IsDirty); + Assert.Throws(() => collection.Save()); + + collection.Save(overwriteChanged: true); + environment.Save(overwriteChanged: true); + + Assert.False(collection.IsDirty); + var reloaded = PostmanCollection.Load(collectionPath); + var spec = reloaded.FindRequest("List widgets")!.ReadSpec(); + Assert.Equal(("PUT", "{{baseUrl}}/v1/widgets?limit=50"), (spec.Method, spec.Url)); + Assert.Equal("console.log('before');", reloaded.GetScripts(reloaded.FindFolder("Widgets")!).For(ScriptLanguage.JavaScript).PreRequest); + Assert.Equal(pulled[upload], File.ReadAllText(upload)); + Assert.Equal(["http://localhost:8080", "t-1"], PostmanEnvironment.Load(environment.FilePath!).Values.Take(2).Select(v => v.Value)); + collection.MarkDirty(); + collection.Save(); + } + + [Fact] + public void A_renamed_item_whose_file_disappeared_is_written_anew() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var (_, collection) = Open(root); + SetMethod(collection, "Admin/Reset", "POST"); + collection.Rename(collection.FindRequest("List widgets")!, "List all widgets"); + collection.Rename(collection.FindFolder("Admin")!, "Administration"); + + // A git checkout removes them meanwhile. + File.Delete(Path.Combine(collectionPath, "Widgets", "List widgets.request.yaml")); + Directory.Delete(Path.Combine(collectionPath, "Admin"), recursive: true); + collection.Save(); + + var reloaded = PostmanCollection.Load(collectionPath); + Assert.Equal("{{baseUrl}}/v1/widgets?limit=50", reloaded.FindRequest("Widgets/List all widgets")!.ReadSpec().Url); + Assert.Equal("POST", reloaded.FindRequest("Administration/Reset")!.ReadSpec().Method); + Assert.Empty(Directory.EnumerateDirectories(collectionPath, ".termrest-saving-*")); + } + + [Fact] + public void A_renamed_folder_whose_files_disappeared_is_written_anew_with_everything_it_held() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var archive = Path.Combine(collectionPath, "Widgets", "Archive"); + Directory.CreateDirectory(Path.Combine(archive, ".resources")); + File.WriteAllText(Path.Combine(archive, ".resources", "definition.yaml"), "$kind: collection\ndescription: Old widgets.\n"); + File.WriteAllText(Path.Combine(archive, "Old widget.request.yaml"), "$kind: http-request\nurl: https://h/old\nmethod: GET\n"); + var (_, collection) = Open(root); + var requests = collection.AllRequests().ToDictionary(r => r.PathInCollection.Replace("Widgets/", "Widget endpoints/", StringComparison.Ordinal), r => r.ReadSpec()); + collection.Rename(collection.FindFolder("Widgets")!, "Widget endpoints"); + + // A git checkout removes the folder meanwhile; nothing in it was edited. + Directory.Delete(Path.Combine(collectionPath, "Widgets"), recursive: true); + collection.Save(); + + var reloaded = PostmanCollection.Load(collectionPath); + Assert.Equal(requests.Keys.Order(StringComparer.Ordinal), reloaded.AllRequests().Select(r => r.PathInCollection).Order(StringComparer.Ordinal)); + Assert.All(requests, r => Assert.True(r.Value.ContentEquals(reloaded.FindRequest(r.Key)!.ReadSpec()), r.Key)); + Assert.Equal("bearer", reloaded.FindFolder("Widget endpoints")!.Auth?.Type); + Assert.Equal("Old widgets.", reloaded.FindFolder("Widget endpoints/Archive")!.Json["description"]?.GetValue()); + } + + [Fact] + public void A_folder_deleted_on_disk_stays_deleted_until_something_is_written_into_it_then_comes_back_whole() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var widgets = Path.Combine(collectionPath, "Widgets"); + Directory.CreateDirectory(Path.Combine(widgets, "Drafts")); + var (_, collection) = Open(root); + collection.SetScripts(collection.FindFolder("Widgets")!, new ScriptSet("console.log('widgets');", "", ScriptLanguage.JavaScript)); + collection.Save(); + + // A git checkout removes the folder meanwhile; TermRest still shows it. + Directory.Delete(widgets, recursive: true); + SetMethod(collection, "Health", "HEAD"); + collection.Save(); + Assert.False(Directory.Exists(widgets)); + + // Writing into it brings back its definition, so its auth and scripts still apply, and everything else it held. + SetMethod(collection, "Widgets/Create widget", "PUT"); + collection.Save(); + var reloaded = PostmanCollection.Load(collectionPath); + Assert.Equal("bearer", reloaded.GetEffectiveAuth(reloaded.FindRequest("Widgets/Create widget")!)?.Type); + Assert.Equal("console.log('widgets');", reloaded.GetScripts(reloaded.FindFolder("Widgets")!).For(ScriptLanguage.JavaScript).PreRequest); + Assert.Equal(Tree(collection), Tree(reloaded)); + Assert.All(collection.AllRequests(), r => Assert.True(r.ReadSpec().ContentEquals(reloaded.FindRequest(r.PathInCollection)!.ReadSpec()), r.PathInCollection)); + + var snapshot = V3Fixture.Snapshot(root); + collection.MarkDirty(); + collection.Save(); + Assert.Equal(snapshot, V3Fixture.Snapshot(root)); + } + + [Theory] + [InlineData("add")] + [InlineData("remove")] + [InlineData("move away and back")] + public void A_folder_without_an_order_deleted_on_disk_stays_deleted_when_its_siblings_change(string change) + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var admin = Path.Combine(collectionPath, "Admin"); + var (_, collection) = Open(root); + + // A pull of a teammate's deletion removes Admin, which has no definition, so no order: it gets one now. + Directory.Delete(admin, recursive: true); + switch (change) + { + case "add": + collection.AddRequest(collection.RootNode, "Status", new HttpRequestSpec { Url = "{{baseUrl}}/status" }); + break; + case "remove": + collection.Remove(collection.FindRequest("Health")!); + break; + default: + // Health gets a new order after Widgets, then one before it again. + collection.Move(collection.FindRequest("Health")!, collection.RootNode, 1); + collection.Save(); + collection.Move(collection.FindRequest("Health")!, collection.RootNode, 0); + break; + } + + collection.Save(); + Assert.False(Directory.Exists(admin)); + Assert.Equal(Tree(collection).Where(p => !p.Contains("Admin", StringComparison.Ordinal)), Tree(PostmanCollection.Load(collectionPath))); + + var snapshot = V3Fixture.Snapshot(root); + collection.MarkDirty(); + collection.Save(); + Assert.Equal(snapshot, V3Fixture.Snapshot(root)); + + // Once something is written into it, it comes back where TermRest shows it. + SetMethod(collection, "Admin/Reset", "POST"); + collection.Save(); + Assert.Equal(Tree(collection), Tree(PostmanCollection.Load(collectionPath))); + } + + [Fact] + public void A_request_moved_into_a_folder_deleted_on_disk_brings_the_folder_back_whole() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var (_, collection) = Open(root); + + Directory.Delete(Path.Combine(collectionPath, "Widgets"), recursive: true); // a git checkout, say + collection.Move(collection.FindRequest("Admin/Reset")!, collection.FindFolder("Widgets")!, 0); + collection.Save(); + + var reloaded = PostmanCollection.Load(collectionPath); + Assert.Equal("bearer", reloaded.GetEffectiveAuth(reloaded.FindRequest("Widgets/Reset")!)?.Type); + Assert.Equal(Tree(collection), Tree(reloaded)); + } + + [Fact] + public void A_collection_folder_deleted_on_disk_stays_deleted_until_something_is_written_into_it_then_comes_back_whole() + { + var root = V3Fixture.Create(); + var (workspace, _) = Open(root); + var created = workspace.CreateCollection("Orders API"); + var orders = created.AddFolder(created.RootNode, "Orders"); + created.AddRequest(orders, "List orders", new HttpRequestSpec { Url = "{{baseUrl}}/orders" }); + created.Save(); + + Directory.Delete(created.FilePath!, recursive: true); + created.MarkDirty(); + created.Save(); + Assert.False(Directory.Exists(created.FilePath!)); + + // Its definition comes back too, even with nothing but its kind: it is what makes the folder a collection. + created.AddRequest(orders, "Create order", new HttpRequestSpec { Method = "POST", Url = "{{baseUrl}}/orders" }); + created.Save(); + Assert.Equal(["[Orders]", "Orders/List orders", "Orders/Create order"], Tree(ApiWorkspace.Open(root).FindCollection(created.FilePath!)!)); + } + + [Fact] + public void A_request_whose_file_changed_on_disk_is_not_moved_until_it_may_be_saved_over() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + string F(string relative) => Path.Combine(collectionPath, relative.Replace('/', Path.DirectorySeparatorChar)); + var (_, collection) = Open(root); + var list = F("Widgets/List widgets.request.yaml"); + var pulled = File.ReadAllText(list).Replace("/v1/widgets", "/v2/widgets", StringComparison.Ordinal); + File.WriteAllText(list, pulled); + File.SetLastWriteTimeUtc(list, DateTime.UtcNow.AddMinutes(1)); + + collection.Rename(collection.FindRequest("List widgets")!, "List all widgets"); + collection.AddRequest(collection.FindFolder("Widgets")!, "List widgets", new HttpRequestSpec { Url = "{{baseUrl}}/v1/widgets/new" }); + SetMethod(collection, "Health", "HEAD"); + + // The file stays where it is, with its examples, and keeps its name; the rest is saved. + Assert.Equal([list], Assert.Throws(() => collection.Save()).Paths); + Assert.Equal(pulled, File.ReadAllText(list)); + Assert.True(File.Exists(F("Widgets/.resources/List widgets.resources/examples/200 OK.example.yaml"))); + Assert.False(File.Exists(F("Widgets/List all widgets.request.yaml"))); + Assert.Contains("url: \"{{baseUrl}}/v1/widgets/new\"", File.ReadAllText(F("Widgets/List widgets-1.request.yaml")), StringComparison.Ordinal); + Assert.Contains("method: HEAD\n", File.ReadAllText(F("Health.request.yaml")), StringComparison.Ordinal); + Assert.True(collection.IsDirty); + Assert.Throws(() => collection.Save()); + + // Overwriting moves it and writes it at once: its examples path follows. + collection.Save(overwriteChanged: true); + Assert.False(File.Exists(list)); + Assert.Contains("examples: ./.resources/List all widgets.resources/examples", File.ReadAllText(F("Widgets/List all widgets.request.yaml")), StringComparison.Ordinal); + Assert.True(File.Exists(F("Widgets/.resources/List all widgets.resources/examples/200 OK.example.yaml"))); + var reloaded = PostmanCollection.Load(collectionPath); + Assert.Equal("{{baseUrl}}/v1/widgets?limit=50", reloaded.FindRequest("Widgets/List all widgets")!.ReadSpec().Url); + Assert.Equal("{{baseUrl}}/v1/widgets/new", reloaded.FindRequest("Widgets/List widgets")!.ReadSpec().Url); + collection.MarkDirty(); + collection.Save(); + } + + [Fact] + public void A_deleted_folder_that_holds_a_request_held_back_goes_once_the_request_moves_out() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + string F(string relative) => Path.Combine(collectionPath, relative.Replace('/', Path.DirectorySeparatorChar)); + var reset = F("Admin/Reset.request.yaml"); + File.AppendAllText(reset, "examples: ./.resources/Reset.resources/examples\n"); + Directory.CreateDirectory(F("Admin/.resources/Reset.resources/examples")); + File.WriteAllText(F("Admin/.resources/Reset.resources/examples/Done.example.yaml"), "$kind: http-example\nresponse:\n statusCode: 204\n"); + var (_, collection) = Open(root); + File.WriteAllText(reset, File.ReadAllText(reset).Replace("\"42\"", "\"43\"", StringComparison.Ordinal)); + File.SetLastWriteTimeUtc(reset, DateTime.UtcNow.AddMinutes(1)); + + collection.Move(collection.FindRequest("Admin/Reset")!, collection.RootNode, 0); + collection.Remove(collection.FindFolder("Admin")!); + Assert.Equal([reset], Assert.Throws(() => collection.Save()).Paths); + Assert.True(File.Exists(reset)); + + collection.Save(overwriteChanged: true); + + Assert.False(Directory.Exists(F("Admin"))); + Assert.True(File.Exists(F("Reset.request.yaml"))); + Assert.True(File.Exists(F(".resources/Reset.resources/examples/Done.example.yaml"))); + Assert.Equal(["Reset", "Health", "[Widgets]"], Tree(PostmanCollection.Load(collectionPath)).Where(p => !p.StartsWith("Widgets/", StringComparison.Ordinal))); + } + + [Fact] + public void Values_whose_first_line_holds_only_spaces_are_saved_so_that_they_read_back() + { + var root = V3Fixture.Create(); + var (workspace, collection) = Open(root); + const string body = " \n{\n \"name\": \"x\"\n}"; + var create = collection.FindRequest("Create widget")!; + var spec = create.ReadSpec(); + spec.Body.Raw = body; + collection.UpdateRequest(create, spec); + var environment = workspace.Environments[0]; + environment.SetValue("note", " \nsecond line"); + + collection.Save(); + environment.Save(); + + Assert.False(collection.IsDirty); + Assert.Equal(body, PostmanCollection.Load(V3Fixture.CollectionPath(root)).FindRequest("Create widget")!.ReadSpec().Body.Raw); + Assert.Equal(" \nsecond line", PostmanEnvironment.Load(environment.FilePath!).Values.Single(v => v.Key == "note").Value); + } + + [Fact] + public void A_file_that_would_not_read_back_is_not_written() + { + var root = V3Fixture.Create(); + var (_, collection) = Open(root); + var file = Path.Combine(V3Fixture.CollectionPath(root), "Health.request.yaml"); + var before = File.ReadAllText(file); + + // A YAML key holds at most 1024 characters: such a header name cannot be written in a header map. + var health = collection.FindRequest("Health")!; + var spec = health.ReadSpec(); + spec.Headers.Add(new KeyValueEntry { Key = new string('X', 1100), Value = "1" }); + collection.UpdateRequest(health, spec); + + Assert.Contains(file, Assert.Throws(() => collection.Save()).Message, StringComparison.Ordinal); + Assert.Equal(before, File.ReadAllText(file)); + Assert.True(collection.IsDirty); + } + + [Fact] + public void Converting_to_v3_writes_everything_or_nothing() + { + var source = PostmanCollection.Parse(""" + { "info": { "name": "Scripts", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, + "item": [ + { "name": "Indented", "event": [ { "listen": "test", "script": { "type": "text/javascript", "exec": [ " ", "pm.test('ok', () => {});" ] } } ], + "request": { "method": "GET", "url": "https://h/a" } }, + { "name": "Long header", "request": { "method": "GET", "header": [ { "key": "LONG", "value": "1" } ], "url": "https://h/b" } } ] } + """.Replace("LONG", new string('X', 1100), StringComparison.Ordinal)); + var parent = TestFiles.NewTempDirectory(); + var target = Path.Combine(parent, "postman", "collections", "Scripts"); + + Assert.Throws(() => source.ConvertToV3(target)); + Assert.Empty(Directory.EnumerateFileSystemEntries(parent)); + + source.Remove(source.FindRequest("Long header")!); + var converted = source.ConvertToV3(target); + Assert.Equal(" \npm.test('ok', () => {});", converted.FindRequest("Indented")!.ReadSpec().Scripts.For(ScriptLanguage.JavaScript).Test); + } + + private static void SetMethod(PostmanCollection collection, string request, string method) + { + var node = collection.FindRequest(request)!; + var spec = node.ReadSpec(); + spec.Method = method; + collection.UpdateRequest(node, spec); + } + + [Fact] + public void New_requests_never_take_the_file_of_a_request_termrest_does_not_show() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var subscribe = File.ReadAllText(Path.Combine(collectionPath, "Widgets", "Subscribe.request.yaml")); + var (_, collection) = Open(root); + var widgets = collection.FindFolder("Widgets")!; + + collection.Rename(widgets, "Widget endpoints"); + collection.AddRequest(widgets, "Subscribe", new HttpRequestSpec { Url = "{{baseUrl}}/v1/subscribe" }); + collection.Save(); + + var folder = Path.Combine(collectionPath, "Widget endpoints"); + Assert.Equal(subscribe, File.ReadAllText(Path.Combine(folder, "Subscribe.request.yaml"))); + Assert.Contains("name: Subscribe", File.ReadAllText(Path.Combine(folder, "Subscribe-1.request.yaml")), StringComparison.Ordinal); + } + + [Fact] + public void A_folder_can_take_the_name_of_a_deleted_folder_that_keeps_hidden_requests() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var (_, collection) = Open(root); + + collection.Remove(collection.FindFolder("Widgets")!); + collection.Rename(collection.FindFolder("Admin")!, "Widgets"); + collection.Save(); + + Assert.Equal(["Subscribe.request.yaml"], Directory.EnumerateFiles(Path.Combine(collectionPath, "Widgets")).Select(Path.GetFileName)); + Assert.True(File.Exists(Path.Combine(collectionPath, "Widgets-1", "Reset.request.yaml"))); + Assert.Contains("name: Widgets\n", File.ReadAllText(Path.Combine(collectionPath, "Widgets-1", ".resources", "definition.yaml")), StringComparison.Ordinal); + Assert.Empty(Directory.EnumerateDirectories(collectionPath, ".termrest-saving-*")); + Assert.NotNull(PostmanCollection.Load(collectionPath).FindRequest("Widgets/Reset")); + + var snapshot = V3Fixture.Snapshot(root); + collection.MarkDirty(); + collection.Save(); + Assert.Equal(snapshot, V3Fixture.Snapshot(root)); + } + + [Fact] + public void A_new_folder_never_takes_over_a_deleted_folder_that_keeps_hidden_requests() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var (_, collection) = Open(root); + + collection.Remove(collection.FindFolder("Widgets")!); + var widgets = collection.AddFolder(collection.RootNode, "Widgets"); + collection.AddRequest(widgets, "Ping", new HttpRequestSpec { Url = "{{baseUrl}}/ping" }); + collection.Move(collection.FindRequest("Health")!, widgets, 0); + collection.Save(); + + Assert.Equal(["Subscribe.request.yaml"], Directory.EnumerateFiles(Path.Combine(collectionPath, "Widgets")).Select(Path.GetFileName)); + Assert.Equal(["Health.request.yaml", "Ping.request.yaml"], Directory.EnumerateFiles(Path.Combine(collectionPath, "Widgets-1")).Select(Path.GetFileName).Order(StringComparer.Ordinal)); + Assert.Contains("name: Widgets\n", File.ReadAllText(Path.Combine(collectionPath, "Widgets-1", ".resources", "definition.yaml")), StringComparison.Ordinal); + var reloaded = PostmanCollection.Load(collectionPath); + Assert.NotNull(reloaded.FindRequest("Widgets/Health")); + Assert.NotNull(reloaded.FindRequest("Widgets/Ping")); + + var snapshot = V3Fixture.Snapshot(root); + collection.MarkDirty(); + collection.Save(); + Assert.Equal(snapshot, V3Fixture.Snapshot(root)); + } + + [Fact] + public void A_new_folder_never_takes_over_a_deleted_folder_that_arrives_with_its_renamed_parent() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + string F(string relative) => Path.Combine(collectionPath, relative.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(F("Admin/Widgets/.resources")); + File.WriteAllText(F("Admin/Widgets/.resources/definition.yaml"), "$kind: collection\ndescription: Old widgets.\n"); + File.WriteAllText(F("Admin/Widgets/Subscribe.request.yaml"), "$kind: websocket-request\nurl: wss://api.example.com/stream\n"); + var (_, collection) = Open(root); + + collection.Remove(collection.FindFolder("Admin/Widgets")!); + var widgets = collection.AddFolder(collection.FindFolder("Admin")!, "Widgets"); + collection.AddRequest(widgets, "Ping", new HttpRequestSpec { Url = "{{baseUrl}}/ping" }); + collection.Rename(collection.FindFolder("Admin")!, "Administration"); + collection.Save(); + + Assert.Equal(["Subscribe.request.yaml"], Directory.EnumerateFileSystemEntries(F("Administration/Widgets")).Select(Path.GetFileName)); + Assert.True(File.Exists(F("Administration/Widgets-1/Ping.request.yaml"))); + Assert.Contains("name: Widgets\n", File.ReadAllText(F("Administration/Widgets-1/.resources/definition.yaml")), StringComparison.Ordinal); + Assert.NotNull(PostmanCollection.Load(collectionPath).FindRequest("Administration/Widgets/Ping")); + + var snapshot = V3Fixture.Snapshot(root); + collection.MarkDirty(); + collection.Save(); + Assert.Equal(snapshot, V3Fixture.Snapshot(root)); + } + + [Fact] + public void A_new_folder_keeps_its_definition_once_a_deleted_folder_of_the_same_name_goes() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + string F(string relative) => Path.Combine(collectionPath, relative.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(F("Admin/Widgets")); + File.Move(F("Admin/Reset.request.yaml"), F("Admin/Widgets/Reset.request.yaml")); + var (_, collection) = Open(root); + var reset = F("Admin/Widgets/Reset.request.yaml"); + File.WriteAllText(reset, File.ReadAllText(reset).Replace("\"42\"", "\"43\"", StringComparison.Ordinal)); + File.SetLastWriteTimeUtc(reset, DateTime.UtcNow.AddMinutes(1)); + + // The changed request is held back in the deleted folder, which its renamed parent takes along. + collection.Move(collection.FindRequest("Admin/Widgets/Reset")!, collection.RootNode, 0); + collection.Remove(collection.FindFolder("Admin/Widgets")!); + var widgets = collection.AddFolder(collection.FindFolder("Admin")!, "Widgets"); + collection.SetScripts(widgets, new ScriptSet("console.log('before');", "", ScriptLanguage.JavaScript)); + collection.Rename(collection.FindFolder("Admin")!, "Administration"); + Assert.Equal([F("Administration/Widgets/Reset.request.yaml")], Assert.Throws(() => collection.Save()).Paths); + + collection.Save(overwriteChanged: true); - var reloaded = PostmanCollection.Load(V3Fixture.CollectionPath(root)); - Assert.True(spec.ContentEquals(reloaded.FindRequest("List widgets")!.ReadSpec())); - Assert.True(createSpec.ContentEquals(reloaded.FindRequest("Create widget")!.ReadSpec())); + var reloaded = PostmanCollection.Load(collectionPath); + Assert.Equal("console.log('before');", reloaded.GetScripts(reloaded.FindFolder("Administration/Widgets")!).For(ScriptLanguage.JavaScript).PreRequest); + Assert.False(Directory.Exists(F("Administration/Widgets"))); + Assert.True(File.Exists(F("Reset.request.yaml"))); } [Fact] - public void File_bodies_keep_their_type_in_yaml() + public void A_folder_written_anew_never_takes_over_a_deleted_folder_that_keeps_hidden_requests() { var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + string F(string relative) => Path.Combine(collectionPath, relative.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(F("Admin/Widgets")); + File.WriteAllText(F("Admin/Widgets/Subscribe.request.yaml"), "$kind: websocket-request\nurl: wss://api.example.com/stream\n"); var (_, collection) = Open(root); - var node = collection.FindRequest("Create widget")!; - var spec = node.ReadSpec(); - spec.Body = new RequestBody { Mode = BodyMode.File, FileSrc = "payloads/widget.json", FileLanguage = "json" }; - collection.UpdateRequest(node, spec); + + collection.Remove(collection.FindFolder("Admin/Widgets")!); + collection.Move(collection.FindFolder("Widgets")!, collection.FindFolder("Admin")!, 0); + Directory.Delete(F("Widgets"), recursive: true); // a git checkout, say collection.Save(); - var yaml = File.ReadAllText(Path.Combine(root, "postman/collections/Widget API/Widgets/Create widget.request.yaml")).ReplaceLineEndings("\n"); - Assert.Contains(" type: file\n content:\n src: payloads/widget.json\n language: json\n", yaml, StringComparison.Ordinal); - var reloaded = PostmanCollection.Load(V3Fixture.CollectionPath(root)).FindRequest("Create widget")!.ReadSpec(); - Assert.Equal((BodyMode.File, "payloads/widget.json", "json"), (reloaded.Body.Mode, reloaded.Body.FileSrc, reloaded.Body.FileLanguage)); + Assert.Equal(["Subscribe.request.yaml"], Directory.EnumerateFileSystemEntries(F("Admin/Widgets")).Select(Path.GetFileName)); + Assert.Contains("name: Widgets\n", File.ReadAllText(F("Admin/Widgets-1/.resources/definition.yaml")), StringComparison.Ordinal); + Assert.Equal("{{baseUrl}}/v1/widgets?limit=50", PostmanCollection.Load(collectionPath).FindRequest("Admin/Widgets/List widgets")!.ReadSpec().Url); } [Fact] - public void Renames_moves_deletes_and_additions_update_the_folder_layout() + public void A_failed_save_leaves_files_where_the_next_save_finds_them() { var root = V3Fixture.Create(); var collectionPath = V3Fixture.CollectionPath(root); - var (_, collection) = Open(root); - var widgets = collection.FindFolder("Widgets")!; - var admin = collection.FindFolder("Admin")!; - collection.Rename(collection.FindRequest("List widgets")!, "List all widgets"); - collection.Move(collection.FindRequest("Create widget")!, collection.RootNode, 1); - collection.Remove(collection.FindRequest("Upload image")!); - collection.Rename(admin, "Administration"); - collection.AddRequest(admin, "Audit: who/what?", new HttpRequestSpec { Method = "GET", Url = "{{baseUrl}}/audit" }); - collection.Duplicate(collection.FindRequest("Health")!); - collection.AddFolder(collection.RootNode, "Reports"); - collection.Save(); + // A file where Admin's .resources folder would go makes moving a request with examples into Admin fail. + var blocker = Path.Combine(collectionPath, "Admin", ".resources"); + File.WriteAllText(blocker, ""); + var before = V3Fixture.Snapshot(root); + var (_, collection) = Open(root); + collection.Rename(collection.FindFolder("Widgets")!, "Widget endpoints"); + collection.Move(collection.FindRequest("List widgets")!, collection.FindFolder("Admin")!, 0); - string F(string relative) => Path.Combine(collectionPath, relative.Replace('/', Path.DirectorySeparatorChar)); - Assert.True(File.Exists(F("Widgets/List all widgets.request.yaml"))); - Assert.False(File.Exists(F("Widgets/List widgets.request.yaml"))); - Assert.True(File.Exists(F("Widgets/.resources/List all widgets.resources/examples/200 OK.example.yaml"))); - Assert.False(Directory.Exists(F("Widgets/.resources/List widgets.resources"))); - Assert.Contains("examples: ./.resources/List all widgets.resources/examples", File.ReadAllText(F("Widgets/List all widgets.request.yaml")), StringComparison.Ordinal); - // Moved and new items get orders between their neighbors (Health 1000, Widgets 2000) or after the last one. - Assert.True(File.Exists(F("Create widget.request.yaml"))); - Assert.Contains("order: 1666", File.ReadAllText(F("Create widget.request.yaml")), StringComparison.Ordinal); - Assert.Contains("order: 1333", File.ReadAllText(F("Health Copy.request.yaml")), StringComparison.Ordinal); - Assert.Equal("$kind: collection\norder: 3000\n", File.ReadAllText(F("Administration/.resources/definition.yaml"))); - Assert.Equal("$kind: collection\norder: 4000\n", File.ReadAllText(F("Reports/.resources/definition.yaml"))); - Assert.False(File.Exists(F("Widgets/Upload image.request.yaml"))); - Assert.True(File.Exists(F("Widgets/Subscribe.request.yaml")), "files TermRest does not show are kept"); - Assert.False(Directory.Exists(F("Admin"))); - Assert.True(File.Exists(F("Administration/Reset.request.yaml"))); - Assert.Contains("name: \"Audit: who/what?\"", File.ReadAllText(F("Administration/Audit- who-what-.request.yaml")), StringComparison.Ordinal); - Assert.True(File.Exists(F("Health Copy.request.yaml"))); - Assert.True(File.Exists(F("Reports/.resources/definition.yaml"))); + // Failing while files are moved: every move is undone. + Assert.ThrowsAny(() => collection.Save()); + Assert.Equal(before, V3Fixture.Snapshot(root)); + Assert.False(Directory.Exists(Path.Combine(collectionPath, "Widget endpoints"))); Assert.Empty(Directory.EnumerateDirectories(collectionPath, ".termrest-saving-*")); - // What is on disk now reads back as the same tree. - var reloaded = PostmanCollection.Load(collectionPath); - Assert.Equal(Tree(collection), Tree(reloaded)); - foreach (var request in collection.AllRequests()) - { - Assert.True(request.ReadSpec().ContentEquals(reloaded.FindRequest(request.PathInCollection)!.ReadSpec()), request.PathInCollection); - } + File.Delete(blocker); + collection.Save(); + Assert.True(File.Exists(Path.Combine(collectionPath, "Admin", ".resources", "List widgets.resources", "examples", "200 OK.example.yaml"))); + Assert.True(File.Exists(Path.Combine(collectionPath, "Widget endpoints", "Create widget.request.yaml"))); - // A second save with no further changes writes nothing. - var snapshot = V3Fixture.Snapshot(root); - collection.MarkDirty(); + // Failing after the files moved (here: writing Admin's new definition): the next save starts from where they are now. + Directory.CreateDirectory(Path.Combine(collectionPath, "Admin", ".resources", "definition.yaml")); + collection.Rename(collection.FindFolder("Admin")!, "Admin: tools"); + Assert.ThrowsAny(() => collection.Save()); + var tools = Path.Combine(collectionPath, "Admin- tools"); + Assert.True(File.Exists(Path.Combine(tools, "Reset.request.yaml"))); + + Directory.Delete(Path.Combine(tools, ".resources", "definition.yaml")); collection.Save(); - Assert.Equal(snapshot, V3Fixture.Snapshot(root)); + Assert.NotNull(PostmanCollection.Load(collectionPath).FindRequest("Admin: tools/List widgets")); } [Fact] - public void Deleting_a_folder_keeps_requests_termrest_does_not_show() + public void Files_left_by_an_interrupted_save_are_reported() { var root = V3Fixture.Create(); - var (_, collection) = Open(root); + var leftover = Path.Combine(V3Fixture.CollectionPath(root), ".termrest-saving-0123", "0"); + Directory.CreateDirectory(leftover); + File.WriteAllText(Path.Combine(leftover, "x.request.yaml"), "$kind: http-request\n"); - collection.Remove(collection.FindFolder("Widgets")!); + var (workspace, _) = Open(root); + + Assert.Contains(workspace.LoadErrors, e => e.Contains(".termrest-saving-0123", StringComparison.Ordinal)); + } + + [Fact] + public void Huge_numbers_and_orders_that_are_not_finite_neither_break_loading_nor_saving() + { + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var huge = "1" + new string('0', 309); // beyond even a double + Replace(Path.Combine(collectionPath, "Health.request.yaml"), "order: 1000", $"order: {huge}"); + Replace(Path.Combine(collectionPath, "Widgets", "List widgets.request.yaml"), " Accept: application/json\n", $" Accept: application/json\n X-Big: {huge}\n"); + File.AppendAllText(Path.Combine(collectionPath, "Admin", "Reset.request.yaml"), "order: '1e999'\n"); + File.AppendAllText(Path.Combine(root, "postman", "environments", "Local.environment.yaml"), $" - key: big\n value: {huge}\n"); + + var (workspace, collection) = Open(root); + Assert.Equal(huge, collection.FindRequest("List widgets")!.ReadSpec().Headers.Single(h => h.Key == "X-Big").Value); + Assert.Equal(huge, workspace.Environments[0].Values.Single(v => v.Key == "big").Value); + + collection.AddRequest(collection.FindFolder("Admin")!, "Audit", new HttpRequestSpec { Url = "{{baseUrl}}/audit" }); + collection.AddRequest(collection.RootNode, "Status", new HttpRequestSpec { Url = "{{baseUrl}}/status" }); collection.Save(); - var widgets = Path.Combine(V3Fixture.CollectionPath(root), "Widgets"); - Assert.Equal(["Subscribe.request.yaml"], Directory.EnumerateFiles(widgets).Select(Path.GetFileName)); - Assert.False(File.Exists(Path.Combine(widgets, ".resources", "definition.yaml"))); + var reloaded = PostmanCollection.Load(collectionPath); + Assert.Equal(["Reset", "Audit"], reloaded.FindFolder("Admin")!.Children.Select(c => c.Name)); + Assert.Equal("Status", reloaded.RootNode.Children[^1].Name); + + static void Replace(string path, string text, string replacement) => + File.WriteAllText(path, File.ReadAllText(path).Replace(text, replacement, StringComparison.Ordinal)); } [Fact] @@ -254,6 +1223,93 @@ public void Collection_level_changes_go_to_the_definition_file() Assert.Equal("Widget API v2", PostmanCollection.Load(V3Fixture.CollectionPath(root)).Name); } + [Fact] + public void Variables_written_as_a_map_are_read_and_keep_their_form() + { + // Postman writes plain collection variables as a {name: value} map. + var root = V3Fixture.Create(); + var definition = Path.Combine(V3Fixture.CollectionPath(root), ".resources", "definition.yaml"); + const string Variables = "variables:\n baseUrl: http://localhost:5000\n port: 5000\n token: \"\"\n unset:\n"; + File.WriteAllText(definition, "$kind: collection\n" + Variables); + var (_, collection) = Open(root); + + Assert.Equal(["baseUrl=http://localhost:5000", "port=5000", "token=", "unset="], collection.GetVariables().Select(v => $"{v.Key}={v.Value}")); + + collection.Name = "Widget API v2"; // rewrites the definition + collection.Save(); + Assert.Equal("$kind: collection\nname: Widget API v2\n" + Variables, File.ReadAllText(definition)); + + var variables = collection.GetVariables(); + variables[0].Value = "https://staging.example.com"; + variables.Add(new KeyValueEntry { Key = "added", Value = "1" }); + collection.SetVariables(variables); + collection.Save(); + Assert.Equal(["- baseUrl: http://localhost:5000", "+ baseUrl: https://staging.example.com", "+ added: \"1\""], + TestFiles.ChangedLines("$kind: collection\nname: Widget API v2\n" + Variables, File.ReadAllText(definition))); + + // One a map can't hold makes it a list of entries. + variables = collection.GetVariables(); + variables[2].Type = "secret"; + collection.SetVariables(variables); + collection.Save(); + var reloaded = PostmanCollection.Load(V3Fixture.CollectionPath(root)); + Assert.Equal(["baseUrl=https://staging.example.com", "port=5000", "token= secret", "unset=", "added=1"], + reloaded.GetVariables().Select(v => $"{v.Key}={v.Value}{(v.IsSecret ? " secret" : "")}")); + Assert.Contains("variables:\n - key: baseUrl\n", File.ReadAllText(definition), StringComparison.Ordinal); + } + + [Fact] + public void Definitions_keep_their_kind_and_variables_their_disabled_false() + { + // Some Postman versions write "$kind: folder" for folders and "disabled: false" for every variable. + var root = V3Fixture.Create(); + var definition = Path.Combine(V3Fixture.CollectionPath(root), ".resources", "definition.yaml"); + var folderDefinition = Path.Combine(V3Fixture.CollectionPath(root), "Widgets", ".resources", "definition.yaml"); + File.WriteAllText(definition, "$kind: collection\nvariables:\n - key: baseUrl\n value: https://api.example.com\n disabled: false\n - key: old\n value: x\n disabled: true\n"); + File.WriteAllText(folderDefinition, File.ReadAllText(folderDefinition).Replace("$kind: collection", "$kind: folder", StringComparison.Ordinal)); + var folderBefore = File.ReadAllText(folderDefinition); + var (_, collection) = Open(root); + + collection.Name = "Widget API v2"; + var variables = collection.GetVariables(); + variables[0].Value = "https://staging.example.com"; + collection.SetVariables(variables); + collection.SetScripts(collection.FindFolder("Widgets")!, new ScriptSet([new LanguageScripts(ScriptLanguage.JavaScript, "", "pm.test('ok', () => {});")])); + collection.Save(); + + Assert.Equal( + "$kind: collection\nname: Widget API v2\nvariables:\n - key: baseUrl\n value: https://staging.example.com\n disabled: false\n - key: old\n value: x\n disabled: true\n", + File.ReadAllText(definition)); + Assert.Equal(["+ scripts:", "+ - type: http:afterResponse", "+ code: pm.test('ok', () => {});"], + TestFiles.ChangedLines(folderBefore, File.ReadAllText(folderDefinition)).Where(l => !l.StartsWith("+ language", StringComparison.Ordinal))); + } + + [Theory] + [InlineData("url: https://localhost:7281/api/products?wireless&categoryId=1\nmethod: GET\nqueryParams:\n wireless: null\n categoryId: \"1\"\n")] + [InlineData("url: ?=\nmethod: GET\nqueryParams:\n \"\": \"\"\n")] + [InlineData("url: '{{baseUrl}}/push'\nmethod: POST\nbody:\n mode: raw\n raw: |\n {\"token\": \"x\"}\nauth:\n type: bearer\nscripts:\n - type: afterResponse\n code: pm.test('ok', () => {});\n")] + [InlineData("url: '{{baseUrl}}/login'\nmethod: POST\nbody:\n type: raw\n raw: '{\"user\": \"a\"}'\n")] + [InlineData("url: '{{baseUrl}}/upload'\nmethod: POST\nbody:\n type: formdata\n formdata:\n - key: a\n value: b\n")] + public void An_edit_keeps_the_parts_of_a_request_file_it_does_not_change(string content) + { + // As other tools and Postman versions write them: a query map with a value left out or an empty name, a body in + // v2.1's form or of a type TermRest doesn't know (which it can't read), auth without credentials, a script without + // its language. + var root = V3Fixture.Create(); + var path = Path.Combine(V3Fixture.CollectionPath(root), "Odd.request.yaml"); + var text = "$kind: http-request\n" + content + "order: 3000\n"; + File.WriteAllText(path, text); + var (_, collection) = Open(root); + var node = collection.FindRequest("Odd")!; + + var spec = node.ReadSpec(); + spec.Headers.Add(new KeyValueEntry { Key = "X-Edit", Value = "edited" }); + collection.UpdateRequest(node, spec); + collection.Save(); + + Assert.Equal(["+ headers:", "+ X-Edit: edited"], TestFiles.ChangedLines(text, File.ReadAllText(path))); + } + [Fact] public void Environments_convert_to_yaml_the_way_postman_writes_them() { @@ -294,6 +1350,39 @@ public void Importing_a_json_collection_into_a_v3_workspace_converts_it_to_a_fol ApiWorkspace.Open(root).FindCollection(folder)!.AllRequests().Select(r => r.PathInCollection)); } + [Fact] + public void Importing_into_a_v3_workspace_keeps_private_files_private() + { + if (OperatingSystem.IsWindows()) + { + Assert.Skip("Unix file modes only."); + return; + } + + const UnixFileMode Private = UnixFileMode.UserRead | UnixFileMode.UserWrite; + var (workspace, _) = Open(V3Fixture.Create()); + var outside = TestFiles.NewTempDirectory(); + var environment = TestFiles.CopyToTemp(TestFiles.DemoEnvironment, outside); + var collection = TestFiles.CopyToTemp(TestFiles.Data("complex.postman_collection.json"), outside); // folders and an example + File.SetUnixFileMode(environment, Private); + File.SetUnixFileMode(collection, Private); + + var importedEnvironment = workspace.ImportEnvironment(environment); + var importedCollection = workspace.ImportCollection(collection); + + Assert.Equal(Private, File.GetUnixFileMode(importedEnvironment.FilePath!)); + Assert.Equal(Private | UnixFileMode.UserExecute, File.GetUnixFileMode(importedCollection.FilePath!)); + foreach (var folder in Directory.EnumerateDirectories(importedCollection.FilePath!, "*", SearchOption.AllDirectories)) + { + Assert.Equal(Private | UnixFileMode.UserExecute, File.GetUnixFileMode(folder)); + } + + foreach (var file in Directory.EnumerateFiles(importedCollection.FilePath!, "*", SearchOption.AllDirectories)) + { + Assert.Equal(Private, File.GetUnixFileMode(file)); + } + } + [Fact] public void Long_values_are_wrapped_as_the_workspace_setting_says() { @@ -351,6 +1440,33 @@ call it every few seconds to check the service. Assert.Contains("\"yamlLineWidth\": 0", File.ReadAllText(workspace.SettingsPath), StringComparison.Ordinal); } + [Fact] + public void A_line_width_whose_settings_could_not_be_saved_applies_to_what_is_open_all_the_same() + { + var root = V3Fixture.Create(); + Directory.CreateDirectory(Path.Combine(root, ".termrest")); + File.WriteAllText(Path.Combine(root, ".termrest", "settings.json"), "{ \"yamlLineWidth\": 80 }"); + var (workspace, collection) = Open(root); + + // A merge conflict in the file since it was read: the settings are not saved, but apply for this session. + File.WriteAllText(workspace.SettingsPath, "{ <<<<<<< HEAD"); + workspace.Settings.YamlLineWidth = 0; + Assert.Throws(workspace.SaveSettings); + + var health = collection.FindRequest("Health")!; + var spec = health.ReadSpec(); + spec.Description = "The health endpoint answers without authentication, so monitors can call it every few seconds to check the service."; + collection.UpdateRequest(health, spec); + collection.Save(); + var environment = workspace.Environments[0]; + environment.SetValue("baseUrl", "http://localhost:8080 is where the service listens when it runs on a developer machine with default settings"); + environment.Save(); + + Assert.Contains($"\ndescription: {spec.Description}\n", File.ReadAllText(Path.Combine(V3Fixture.CollectionPath(root), "Health.request.yaml")), StringComparison.Ordinal); + Assert.Contains(" value: 'http://localhost:8080 is where the service listens when it runs on a developer machine with default settings'\n", + File.ReadAllText(environment.FilePath!), StringComparison.Ordinal); + } + [Fact] public void By_default_new_values_are_wrapped_like_the_collection_s_files() { @@ -438,6 +1554,79 @@ public void Yaml_environments_save_only_changed_values() Assert.Equal("name: Staging / EU\nvalues: []\n", File.ReadAllText(created.FilePath!)); } + [Fact] + public void Environment_values_postman_marks_secret_are_secret_and_keep_their_form() + { + // Postman marks them with "secret: true", and leaves the value out of the file. + var root = V3Fixture.Create(); + var path = Path.Combine(root, "postman", "environments", "Dev.environment.yaml"); + const string Text = "name: Dev\nvalues:\n - key: baseUrl\n value: 'http://localhost:8080'\n - key: jwt\n secret: true\n" + + " - key: password\n value: ''\n enabled: true\n secret: true\n - key: plain\n value: x\n secret: false\n"; + File.WriteAllText(path, Text); + var (workspace, _) = Open(root); + var environment = workspace.Environments.Single(e => e.Name == "Dev"); + + Assert.Equal(["baseUrl", "jwt secret", "password secret", "plain"], environment.Values.Select(v => v.Key + (v.IsSecret ? " secret" : ""))); + + // An edit elsewhere leaves them as they are; a new secret is marked the way the file marks them. + var values = KeyValueEntry.CloneList(environment.Values); + values[0].Value = "http://localhost:9090"; + values.Add(new KeyValueEntry { Key = "token", Value = "t", Type = "secret" }); + environment.SetValues(values); + environment.Save(); + + Assert.Equal(Text.Replace("8080", "9090", StringComparison.Ordinal) + " - key: token\n value: t\n enabled: true\n secret: true\n", File.ReadAllText(path)); + Assert.True(PostmanEnvironment.Load(path).Values.Single(v => v.Key == "token").IsSecret); + } + + [Fact] + public void Values_without_an_enabled_key_keep_their_lines_when_another_value_changes() + { + var root = V3Fixture.Create(); + var path = Path.Combine(root, "postman", "environments", "Tools.environment.yaml"); + File.WriteAllText(path, "name: Tools\nvalues:\n - key: base_url\n value: \"http://localhost:4789\"\n - key: token\n value: \"\"\n - key: owner\n value: org\n"); + var (workspace, _) = Open(root); + var environment = workspace.Environments.Single(e => e.Name == "Tools"); + var before = File.ReadAllText(path); + + var values = KeyValueEntry.CloneList(environment.Values); + values[1].Value = "t-1"; + values[2].Enabled = false; + environment.SetValues(values); + environment.Save(); + + // Disabled as Postman marks it in such files: "disabled: true". + Assert.Equal(["- value: \"\"", "+ value: \"t-1\"", "+ disabled: true"], TestFiles.ChangedLines(before, File.ReadAllText(path))); + Assert.Equal([true, true, false], PostmanEnvironment.Load(path).Values.Select(v => v.Enabled)); + } + + [Fact] + public void Environment_values_postman_disabled_are_not_used() + { + // As Postman writes them: "disabled: true", no "enabled". + var root = V3Fixture.Create(); + var path = Path.Combine(root, "postman", "environments", "Test.environment.yaml"); + const string Text = "name: Test\nvalues:\n - key: manualStartDate\n value: '2026-10-30'\n disabled: true\n description: Overwrite start dates\n" + + " - key: baseUrl\n value: 'https://test.example.com'\n"; + File.WriteAllText(path, Text); + var (workspace, _) = Open(root); + var environment = workspace.Environments.Single(e => e.Name == "Test"); + + Assert.Equal([false, true], environment.Values.Select(v => v.Enabled)); + Assert.Equal("{{manualStartDate}} https://test.example.com", + new VariableResolver([new EntryListScope("environment", environment.Values)]).Resolve("{{manualStartDate}} {{baseUrl}}")); + environment.MarkDirty(); + environment.Save(); + Assert.Equal(Text, File.ReadAllText(path)); + + // Enabled again, it loses its "disabled". + var values = KeyValueEntry.CloneList(environment.Values); + values[0].Enabled = true; + environment.SetValues(values); + environment.Save(); + Assert.Equal(Text.Replace(" disabled: true\n", "", StringComparison.Ordinal), File.ReadAllText(path)); + } + [Fact] public void New_collections_follow_the_workspace_layout() { @@ -459,6 +1648,50 @@ public void New_collections_follow_the_workspace_layout() Assert.True(jsonWorkspace.CreateCollection("Forced").IsV3); } + [Fact] + public void Names_starting_with_a_dot_stay_visible() + { + Assert.Equal("-NET API", V3Names.Safe(".NET API")); + Assert.Equal("--resources", V3Names.Safe("..resources")); + Assert.Equal("untitled", V3Names.Safe("...")); + + // A device name Windows reserves, also with an extension: the "-" follows the name. + Assert.Equal(["CON-", "con-.example.org", "aux- .payments", "LPT¹-", "console.log", "con-artist"], + ((string[])["CON", "con.example.org", "aux .payments", "LPT¹", "console.log", "con-artist"]).Select(V3Names.Safe)); + + var root = V3Fixture.Create(); + var (workspace, collection) = Open(root); + var created = workspace.CreateCollection(".NET API"); + var folder = collection.AddFolder(collection.RootNode, ".well-known"); + collection.AddRequest(folder, ".resources", new HttpRequestSpec { Url = "{{baseUrl}}/.well-known/resources" }); + collection.Save(); + + var reopened = ApiWorkspace.Open(root); + Assert.Contains(reopened.Collections, c => c.Name == ".NET API"); + Assert.NotNull(reopened.FindCollection(V3Fixture.CollectionPath(root))!.FindRequest(".well-known/.resources")); + + // Creating a collection never replaces one that is already there. + Assert.Throws(() => V3CollectionStorage.Create(created.FilePath!, "Other")); + Assert.Equal("$kind: collection\nname: .NET API\n", File.ReadAllText(V3Names.DefinitionPath(created.FilePath!))); + } + + [Fact] + public void Names_too_long_for_a_file_name_are_never_cut_inside_a_character() + { + var name = new string('a', 63) + "\U0001F600 tail"; // the emoji is two UTF-16 units, the 64th and 65th + var stem = new string('a', 63); + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var (_, collection) = Open(root); + + var folder = collection.AddFolder(collection.RootNode, name); + collection.AddRequest(folder, name, new HttpRequestSpec { Url = "{{baseUrl}}/smile" }); + collection.Save(); + + Assert.True(File.Exists(Path.Combine(collectionPath, stem, stem + V3Names.RequestSuffix))); + Assert.Equal("{{baseUrl}}/smile", PostmanCollection.Load(collectionPath).FindRequest($"{name}/{name}")!.ReadSpec().Url); + } + [Fact] public void Opening_a_collection_folder_opens_its_workspace() { @@ -474,6 +1707,7 @@ public void Opening_a_collection_folder_opens_its_workspace() [Theory] [InlineData("TermRest Demo.postman_collection.json")] [InlineData("complex.postman_collection.json")] + [InlineData("legacy-v20.postman_collection.json")] public void Converting_v21_to_v3_and_back_keeps_every_request(string file) { var source = PostmanCollection.Load(file.StartsWith("TermRest", StringComparison.Ordinal) ? TestFiles.DemoCollection : TestFiles.Data(file)); @@ -513,4 +1747,142 @@ public void Converting_v21_to_v3_and_back_keeps_every_request(string file) var examples = source.AllRequests().Sum(r => (r.Json["response"] as JsonArray)?.Count ?? 0); Assert.Equal(examples, Directory.EnumerateFiles(target, "*.example.yaml", SearchOption.AllDirectories).Count()); } + + [Fact] + public void Converting_to_v3_keeps_the_other_v2_forms_termrest_reads() + { + var source = PostmanCollection.Parse(""" + { + "info": { "name": "Forms", "schema": "https://schema.getpostman.com/json/collection/v2.0.0/collection.json" }, + "item": [ { + "name": "Users", + "event": [ + { "listen": "prerequest", "disabled": true, "script": { "type": "text/javascript", "exec": [ "pm.variables.set('page', 3);" ] } }, + { "listen": "test", "script": { "type": "text/javascript", "exec": [ "pm.test('ok', () => {});" ] } } + ], + "request": { + "method": "GET", + "header": "Accept: application/json\nX-Trace: 1", + "auth": { "type": "basic", "basic": { "username": "ada", "password": "s3cret" } }, + "url": { "protocol": "https", "host": [ "api", "example", "com" ], "path": [ "users" ], "query": [ { "key": "page", "value": "2" } ] } + }, + "response": [ { "name": "OK", "originalRequest": { "method": "GET", "header": "Accept: application/json", "url": { "host": [ "api", "example", "com" ], "path": [ "users" ] } }, + "code": 200, "status": "OK", "header": [], "body": "[]" } ] + } ] + } + """); + + var converted = source.ConvertToV3(Path.Combine(TestFiles.NewTempDirectory(), "Forms")); + + var spec = converted.FindRequest("Users")!.ReadSpec(); + Assert.Equal("https://api.example.com/users?page=2", spec.Url); + Assert.Equal(["Accept: application/json", "X-Trace: 1"], spec.Headers.Select(h => $"{h.Key}: {h.Value}")); + Assert.Equal(("basic", "ada", "s3cret"), (spec.Auth!.Type, spec.Auth.Get("username"), spec.Auth.Get("password"))); + Assert.Equal(new LanguageScripts(ScriptLanguage.JavaScript, "", "pm.test('ok', () => {});"), Assert.Single(spec.Scripts.Languages)); // a disabled script does not run + var example = File.ReadAllText(Path.Combine(converted.FilePath!, ".resources", "Users.resources", "examples", "OK.example.yaml")); + Assert.Contains(" url: api.example.com/users\n", example, StringComparison.Ordinal); + Assert.Contains(" Accept: application/json\n", example, StringComparison.Ordinal); + } + + [Fact] + public void Converting_to_v3_writes_variables_and_example_names_as_postman_has_them() + { + var source = PostmanCollection.Parse(""" + { + "info": { "name": "Shapes", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, + "variable": [ + { "id": "8f2e", "key": "baseUrl", "value": "https://api.example.com", "type": "string", "name": "Base URL", "system": false }, + { "key": "port", "value": 42 }, + { "key": "debug", "value": true }, + { "key": "apiKey", "value": "sk-live-123", "type": "secret" } + ], + "item": [ { + "name": "Users", + "request": { "method": "GET", "url": "{{baseUrl}}/users" }, + "response": [ + { "name": "OK", "code": 200, "status": "OK", "body": "[]" }, + { "name": "ok", "code": 200, "status": "OK", "body": "[]" }, + { "name": "Created: user / 201", "code": 201, "status": "Created", "body": "{}" } + ] + } ] + } + """); + + var converted = source.ConvertToV3(Path.Combine(TestFiles.NewTempDirectory(), "Shapes")); + + // As Postman's v3 schema has them: values are text, a secret variable has no value (it stays in the JSON file it + // came from), and v2.1's other keys are left out. + Assert.Equal(["apiKey"], source.SecretValuesLeftOutOfV3()); + var definition = File.ReadAllText(Path.Combine(converted.FilePath!, ".resources", "definition.yaml")); + Assert.Contains(" - key: baseUrl\n value: https://api.example.com\n - key: port\n value: \"42\"\n - key: debug\n value: \"true\"\n - key: apiKey\n secret: true\n", definition, StringComparison.Ordinal); + Assert.DoesNotContain("sk-live-123", definition, StringComparison.Ordinal); + Assert.Equal(["baseUrl=https://api.example.com", "port=42", "debug=true", "apiKey="], converted.GetVariables().Select(v => $"{v.Key}={v.Value}")); + + // Example names their files can't have are kept in the files. + var examples = Path.Combine(converted.FilePath!, ".resources", "Users.resources", "examples"); + Assert.DoesNotContain("name:", File.ReadAllText(Path.Combine(examples, "OK.example.yaml")), StringComparison.Ordinal); + Assert.StartsWith("$kind: http-example\nname: ok\nrequest:", File.ReadAllText(Path.Combine(examples, "ok-1.example.yaml")), StringComparison.Ordinal); + Assert.StartsWith("$kind: http-example\nname: \"Created: user / 201\"\nrequest:", File.ReadAllText(Path.Combine(examples, "Created- user - 201.example.yaml")), StringComparison.Ordinal); + } + + [Fact] + public void A_renamed_request_takes_its_examples_path_along_as_the_file_writes_it() + { + // Postman writes the path with "./" and without. + var root = V3Fixture.Create(); + var collectionPath = V3Fixture.CollectionPath(root); + var file = Path.Combine(collectionPath, "Widgets", "List widgets.request.yaml"); + File.WriteAllText(file, File.ReadAllText(file).Replace("examples: ./.resources/", "examples: .resources/", StringComparison.Ordinal)); + Assert.Contains("examples: .resources/List widgets.resources/examples", File.ReadAllText(file), StringComparison.Ordinal); + var (_, collection) = Open(root); + + collection.Rename(collection.FindRequest("List widgets")!, "List all widgets"); + collection.Save(); + + Assert.Contains("examples: .resources/List all widgets.resources/examples\n", File.ReadAllText(Path.Combine(collectionPath, "Widgets", "List all widgets.request.yaml")), StringComparison.Ordinal); + Assert.True(Directory.Exists(Path.Combine(collectionPath, "Widgets", ".resources", "List all widgets.resources", "examples"))); + } + + [Fact] + public void Converting_to_v3_keeps_descriptions_as_text() + { + // Collections that Postman generates from OpenAPI describe fields and parameters with {content, type} objects. + var source = PostmanCollection.Parse(""" + { + "info": { "name": "Uploads", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, + "variable": [ { "key": "baseUrl", "value": "https://api.example.com", "description": { "content": "Where the API runs", "type": "text/plain" } } ], + "item": [ { + "name": "Upload", + "request": { + "method": "POST", + "header": [ { "key": "X-Tenant", "value": "acme", "description": { "content": "Tenant id", "type": "text/plain" } } ], + "body": { "mode": "formdata", "formdata": [ + { "key": "title", "value": "Foo", "type": "text", "description": "(Required) Shown under the image" }, + { "key": "file", "type": "file", "src": [], "description": { "content": "(Required) A PNG or JPEG image", "type": "text/plain" } }, + { "key": "tags", "value": "a", "type": "text", "description": { "content": "", "type": "text/plain" } }, + { "key": "note", "value": "b", "type": "text", "description": null } + ] }, + "url": { "raw": "{{baseUrl}}/upload?dryRun=1", "host": [ "{{baseUrl}}" ], "path": [ "upload" ], + "query": [ { "key": "dryRun", "value": "1", "description": { "content": "Validate only", "type": "text/plain" } } ] } + }, + "response": [ { "name": "OK", "code": 200, "status": "OK", "body": "{}", + "header": [ { "key": "X-Rate-Remaining", "value": "9", "description": { "content": "Uploads left today", "type": "text/plain" } } ] } ] + } ] + } + """); + + var converted = source.ConvertToV3(Path.Combine(TestFiles.NewTempDirectory(), "Uploads")); + + // As read back from the v3 files. + var request = (JsonObject)converted.FindRequest("Upload")!.Json["request"]!; + var parts = ((JsonArray)request["body"]!["formdata"]!).Cast().ToList(); + Assert.Equal(["(Required) Shown under the image", "(Required) A PNG or JPEG image"], parts.Take(2).Select(p => p["description"]!.GetValue())); + Assert.All(parts.Skip(2), p => Assert.False(p.ContainsKey("description"))); + Assert.Equal("Tenant id", request["header"]![0]!["description"]!.GetValue()); + Assert.Equal("Validate only", request["url"]!["query"]![0]!["description"]!.GetValue()); + Assert.Equal("Where the API runs", converted.Root["variable"]![0]!["description"]!.GetValue()); + var example = File.ReadAllText(Path.Combine(converted.FilePath!, ".resources", "Upload.resources", "examples", "OK.example.yaml")); + Assert.Contains(" description: Uploads left today\n", example, StringComparison.Ordinal); + Assert.Empty(converted.Verify()); + } } diff --git a/tests/TermRest.Core.Tests/PowerShellScriptingTests.cs b/tests/TermRest.Core.Tests/PowerShellScriptingTests.cs index aa42624..6e1141b 100644 --- a/tests/TermRest.Core.Tests/PowerShellScriptingTests.cs +++ b/tests/TermRest.Core.Tests/PowerShellScriptingTests.cs @@ -1,3 +1,5 @@ +using System.Globalization; +using System.Text.Json.Nodes; using TermRest.Core.Http; using TermRest.Core.Model; using TermRest.Core.Postman; @@ -193,6 +195,80 @@ First @() Assert.Equal("InvalidOperationException: These headers cannot be changed: change the request in a pre-request script.", sent.Scripts!.Error!.Message); } + [Fact] + public async Task Host_output_keeps_its_place_among_the_script_output_without_colors() + { + var pwsh = TestPowerShell.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetPowerShellRuntime(pwsh); + + var exchange = await runner.SendAsync(collection, null, PowerShell(server.Url("echo"), test: """ + Write-Host 'before' + [pscustomobject] @{ id = 1; name = 'Ada' } | Format-Table id, name | Out-Host + [Console]::Write('console ') + [Console]::WriteLine('line') + Write-Host 'after' + """), _ct); + + Assert.True(exchange.Scripts!.Error is null, exchange.Scripts.Describe()); + var lines = exchange.Scripts.Logs.Select(l => l.Text.TrimEnd()).Where(l => l.Length > 0).ToList(); + Assert.Equal("before", lines[0]); + Assert.Contains("id name", lines); // PowerShell 7.2 and later color table headers on a terminal + Assert.Equal(["console line", "after"], lines.TakeLast(2)); + Assert.DoesNotContain(lines, l => l.Contains('\u001b', StringComparison.Ordinal)); + } + + [Fact] + public async Task Console_writes_from_parallel_blocks_and_thread_jobs_reach_the_scripts_output() + { + var pwsh = TestPowerShell.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetPowerShellRuntime(pwsh); + + // They run in runspaces of their own, where a PowerShell class's methods can't run: such a console writer made them + // wait for the script, which waited for them, until the time limit stopped PowerShell. + var exchange = await runner.SendAsync(collection, null, PowerShell(server.Url("echo"), test: """ + 'a', 'b' | ForEach-Object -Parallel { [Console]::WriteLine("parallel $_") } -ThrottleLimit 2 + Start-ThreadJob { [Console]::Error.WriteLine('thread job') } | Receive-Job -Wait -AutoRemoveJob + Write-Host 'after' + """), _ct); + + Assert.True(exchange.Scripts!.Error is null, exchange.Scripts.Describe()); + var lines = exchange.Scripts.Logs.Select(l => l.Text).ToList(); + Assert.Equal(["parallel a", "parallel b", "thread job"], lines.SkipLast(1).Order()); + Assert.Equal("after", lines[^1]); + } + + [Fact] + public async Task Guids_dates_chars_and_uris_set_in_scripts_are_their_text() + { + var pwsh = TestPowerShell.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetPowerShellRuntime(pwsh); + + var exchange = await runner.SendAsync(collection, null, PowerShell(server.Url("echo"), preRequest: """ + $tr.Request.Headers.Set('X-Id', [guid] '3f2504e0-4f89-11d3-9a0c-0305e82c3301') + $tr.CollectionVariables.Set('when', [DateTimeOffset]::new(2024, 1, 2, 3, 4, 5, [TimeSpan]::Zero)) + $tr.CollectionVariables.Set('letter', [char] 'a') + $tr.CollectionVariables.Set('site', [uri] 'https://example.org/a%20b') + $tr.CollectionVariables.Set('flags', [ordered] @{ on = $true }) + $tr.CollectionVariables.Set('day', [DateOnly]::new(2024, 1, 2)) + $tr.CollectionVariables.Set('at', [TimeOnly]::new(3, 4, 5)) + """), _ct); + + Assert.True(exchange.Scripts!.Error is null, exchange.Scripts.Describe()); + Assert.Equal("3f2504e0-4f89-11d3-9a0c-0305e82c3301", JsonNode.Parse(exchange.Response!.Body)!["headers"]!["x-id"]!.GetValue()); + var stored = runner.Session.For(collection); + Assert.Equal(("2024-01-02T03:04:05.0000000+00:00", "a", "https://example.org/a%20b", """{"on":true}"""), (stored["when"], stored["letter"], stored["site"], stored["flags"])); + Assert.Equal(("2024-01-02", "03:04:05.0000000"), (stored["day"], stored["at"])); + } + [Fact] public async Task Programs_that_scripts_start_cannot_disturb_the_worker() { @@ -212,12 +288,140 @@ public async Task Programs_that_scripts_start_cannot_disturb_the_worker() $taken = if ($IsWindows) { cmd.exe /c echo taken } else { /bin/sh -c 'echo taken' } Write-Host "a child's output, taken: $taken" [Console]::WriteLine('captured ünïcödé ✓') + if ($IsLinux) { + $stat = [System.IO.File]::ReadAllText('/proc/self/stat') + $session = [int] $stat.Substring($stat.LastIndexOf(')') + 2).Split(' ')[3] + $tr.Globals.Set('session', $(if ($session -eq $PID) { 'its own' } else { "TermRest's" })) + } """, test: "$tr.Test('still answers', { })"), _ct); Assert.Equal(200, exchange.Response!.StatusCode); Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); Assert.Equal(["a child reads []", "a child's output, taken: taken", "captured ünïcödé ✓"], exchange.Scripts.Logs.Select(l => l.Text)); Assert.Equal(["still answers"], exchange.Scripts.Tests.Select(t => t.Name)); + + // Nor can they open TermRest's terminal (/dev/tty) to ask for a password over its screen: PowerShell is in a session + // of its own, which has none (this test may run without a terminal, so trying to open it would tell nothing). + Assert.Equal(OperatingSystem.IsLinux() ? "its own" : null, runner.Session.Globals.GetValueOrDefault("session")); + } + + [Fact] + public async Task Exit_break_and_continue_end_the_script_not_PowerShell() + { + var pwsh = TestPowerShell.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + collection.SetScripts(collection.RootNode, new ScriptSet("Write-Host 'collection'\n$tr.Globals.Set('pid', $PID)\nbreak\nWrite-Host 'not reached'", "", + ScriptLanguage.PowerShell)); + var folder = collection.AddFolder(collection.RootNode, "Users"); + collection.SetScripts(folder, new ScriptSet("if ($true) { continue }\nWrite-Host 'not reached'", "", ScriptLanguage.PowerShell)); + var request = collection.AddRequest(folder, "Exit", PowerShell(server.Url("echo"), + preRequest: "Write-Host 'request'\nif ($tr.Request.Method -eq 'GET') { exit }\nWrite-Host 'not reached'", + test: "function Stop { exit 0 }\n$tr.Test('before', { })\nStop\n$tr.Test('not reached', { })")); + using var runner = new RequestRunner(workspace); + runner.SetPowerShellRuntime(pwsh); + + // Each ends its own script quietly, as exit does a script file (and sys.exit() a Python script): the next ones run. + var exchange = await runner.SendAsync(collection, request, request.ReadSpec(), null, _ct); + + Assert.Equal(200, exchange.Response!.StatusCode); + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal(4, exchange.Scripts.Ran); + Assert.Equal(["collection", "request"], exchange.Scripts.Logs.Select(l => l.Text)); + Assert.Equal(["before"], exchange.Scripts.Tests.Select(t => t.Name)); + + // An exit code other than 0 fails the script, and the same PowerShell keeps running. + var failed = await runner.SendAsync(collection, null, PowerShell(server.Url("echo"), preRequest: "$tr.Globals.Set('again', $PID)\nexit 3"), _ct); + Assert.Null(failed.Response); + Assert.Equal(("request", "ExitException: 3"), (failed.Scripts!.Error!.Script, failed.Scripts.Error.Message)); + Assert.Equal(runner.Session.Globals["pid"], runner.Session.Globals["again"]); + } + + [Fact] + public async Task PowerShell_keeps_only_the_output_it_shows() + { + var pwsh = TestPowerShell.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetPowerShellRuntime(pwsh); + + // A script that writes without end: what is not shown is counted, not kept in memory. + var exchange = await runner.SendAsync(collection, null, PowerShell(server.Url("echo"), test: """ + 'first' + $before = [GC]::GetTotalMemory($true) + foreach ($i in 1..200000) { "line $i " + ('x' * 100) } + foreach ($i in 1..50000) { [Console]::WriteLine("console $i " + ('x' * 100)) } + $tr.Globals.Set('kept', [GC]::GetTotalMemory($true) - $before) + """), _ct); + + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal(1000, exchange.Scripts.Logs.Count); + Assert.Equal(("first", "line 999 " + new string('x', 100)), (exchange.Scripts.Logs[0].Text, exchange.Scripts.Logs[^1].Text)); + Assert.Contains("249001 more lines the test scripts printed are not shown.", exchange.Scripts.Notes); + // About 8 MB on Windows and Linux (the console's 4 million characters, until the script's output takes them), 14 MB on + // macOS; all the lines would take 60 MB. + Assert.True(long.Parse(runner.Session.Globals["kept"]!, CultureInfo.InvariantCulture) < 25_000_000, runner.Session.Globals["kept"]); + } + + [Fact] + public async Task Halves_of_emoji_do_not_break_the_answer() + { + var pwsh = TestPowerShell.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetPowerShellRuntime(pwsh); + + // A line cut at 4,000 characters, not inside an emoji, and a script's own substring of one (not text: it becomes U+FFFD). + var exchange = await runner.SendAsync(collection, null, PowerShell(server.Url("echo"), test: """ + Write-Host (('a' * 3999) + '😀') + $half = '😀'.Substring(0, 1) + Write-Host ('half ' + $half + ' and a whole 😀') + $tr.Test('test ' + $half, { }) + $tr.Globals.Set('name ' + $half, $half) + """), _ct); + + Assert.Equal(200, exchange.Response!.StatusCode); + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal([new string('a', 3999), "half \uFFFD and a whole 😀"], exchange.Scripts.Logs.Select(l => l.Text)); + Assert.Equal(["test \uFFFD"], exchange.Scripts.Tests.Select(t => t.Name)); + Assert.Equal("\uFFFD", runner.Session.Globals["name \uFFFD"]); + } + + [Fact] + public async Task A_body_set_to_bytes_or_a_hashtable_is_sent_as_text() + { + var pwsh = TestPowerShell.Require(); + await using var server = await EchoServer.StartAsync(); + var (workspace, collection) = NewWorkspace(); + using var runner = new RequestRunner(workspace); + runner.SetPowerShellRuntime(pwsh); + async Task SentBody(string preRequest) + { + var spec = PowerShell(server.Url("echo"), preRequest: preRequest); + spec.Method = "POST"; + spec.Body = new RequestBody { Mode = BodyMode.Raw, Raw = "original" }; + var exchange = await runner.SendAsync(collection, null, spec, _ct); + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + return JsonNode.Parse(exchange.Response!.Body)!["body"]!.GetValue(); + } + + Assert.Equal("Zoë ✓", await SentBody("$tr.Request.Body = [Text.Encoding]::UTF8.GetBytes('Zoë ✓')")); + Assert.Equal("""{"name":"Zoë","n":1}""", await SentBody("$tr.Request.Body = [ordered] @{ name = 'Zoë'; n = 1 }")); + + // A request the scripts left unusable is not sent, and what they did is kept, as in the other languages. + var broken = await runner.SendAsync(collection, null, PowerShell(server.Url("echo"), preRequest: """ + 'before' + $tr.Test('ran', { }) + $tr.CollectionVariables.Set('kept', 'yes') + $tr.Request.Headers = $null + """), _ct); + Assert.Null(broken.Response); + Assert.StartsWith("The pre-request scripts left a request that cannot be sent: ", broken.Scripts!.Error!.Message, StringComparison.Ordinal); + Assert.Equal(["before"], broken.Scripts.Logs.Select(l => l.Text)); + Assert.Equal(["ran"], broken.Scripts.Tests.Select(t => t.Name)); + Assert.Equal("yes", runner.Session.For(collection)["kept"]); } [Fact] @@ -281,19 +485,22 @@ public async Task Only_the_first_language_with_all_the_scripts_runs_and_without_ public async Task PowerShell_is_found_and_must_be_PowerShell_7_or_later() { var pwsh = TestPowerShell.Require(); - var (ok, message) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.PowerShell, pwsh, Path.GetTempPath(), _ct); + var (ok, message) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.PowerShell, pwsh, _ct); Assert.True(ok, message); Assert.Matches(@"^PowerShell \d+\.\d+\.\d+\S* · \S", message); - var (missing, why) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.PowerShell, "no-such-pwsh-here", Path.GetTempPath(), _ct); + var (missing, why) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.PowerShell, "no-such-pwsh-here", _ct); Assert.False(missing); Assert.Contains("could not be started", why, StringComparison.Ordinal); - Assert.NotNull(await ScriptRuntimeLocator.FindAsync(ScriptLanguage.PowerShell, TestFiles.NewTempDirectory(), r => r, _ct)); + if (ScriptRuntimeLocator.Candidates(ScriptLanguage.PowerShell, Path.GetTempPath()).Contains(pwsh)) // not one that TERMREST_TEST_POWERSHELL names elsewhere + { + Assert.NotNull(await ScriptRuntimeLocator.FindAsync(ScriptLanguage.PowerShell, TestFiles.NewTempDirectory(), r => r, _ct)); + } // Windows PowerShell (5.1) is not PowerShell 7. var windowsPowerShell = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "WindowsPowerShell", "v1.0", "powershell.exe"); if (OperatingSystem.IsWindows() && File.Exists(windowsPowerShell)) { - var (old, text) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.PowerShell, windowsPowerShell, Path.GetTempPath(), _ct); + var (old, text) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.PowerShell, windowsPowerShell, _ct); Assert.False(old); Assert.Matches(@"^PowerShell 5\.1\.\S+ is too old: scripts need PowerShell 7\.0 or later \(.+powershell\.exe\)\.$", text); } diff --git a/tests/TermRest.Core.Tests/RecordingTests.cs b/tests/TermRest.Core.Tests/RecordingTests.cs index 7923339..c7bf6b7 100644 --- a/tests/TermRest.Core.Tests/RecordingTests.cs +++ b/tests/TermRest.Core.Tests/RecordingTests.cs @@ -1,9 +1,11 @@ +using System.IO.Compression; using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; using System.Text.Json.Nodes; using TermRest.Core.Auth; using TermRest.Core.Certificates; +using TermRest.Core.History; using TermRest.Core.Http; using TermRest.Core.Model; using TermRest.Core.Postman; @@ -60,7 +62,7 @@ public async Task A_recording_is_a_har_file_with_every_request_and_response_and_ await using var server = await EchoServer.StartAsync(); var upload = Path.Combine(_root, "upload.txt"); await File.WriteAllTextAsync(upload, "file-content", _ct); - using var runner = new RequestRunner(ApiWorkspace.Open(TestFiles.NewTempDirectory())); + using var runner = new RequestRunner(ApiWorkspace.Open(_root)); // the workspace's file runner.LocalVariables["base"] = server.BaseUri.ToString().TrimEnd('/'); runner.LocalVariables["apiToken"] = "tok-1234567890"; // named like a secret, not typed "secret" var collection = PostmanCollection.Create("Recorded"); @@ -153,6 +155,7 @@ await Send(new HttpRequestSpec Assert.Equal("hello", multipart.Single(p => p!["name"]!.GetValue() == "note")!["value"]!.GetValue()); var file = multipart.Single(p => p!["name"]!.GetValue() == "doc")!; Assert.Equal("upload.txt", file["fileName"]!.GetValue()); + Assert.Equal("text/plain", file["contentType"]!.GetValue()); // as sent: the type of its extension Assert.Null(file["value"]); // files are recorded by reference, not content Assert.Equal((upload, 12, false), (file["_file"]!["path"]!.GetValue(), file["_file"]!["size"]!.GetValue(), file["_file"]!["contentRecorded"]!.GetValue())); Assert.DoesNotContain("file-content", entries[6]!["request"]!.ToJsonString(), StringComparison.Ordinal); @@ -167,7 +170,7 @@ public async Task Files_sent_with_a_request_are_recorded_by_path_never_by_conten await using var server = await EchoServer.StartAsync(); var payload = Path.Combine(_root, "order.json"); await File.WriteAllTextAsync(payload, "{\"item\":\"book\",\"note\":\"Only-In-The-File\"}", _ct); - using var runner = new RequestRunner(ApiWorkspace.Open(TestFiles.NewTempDirectory())); + using var runner = new RequestRunner(ApiWorkspace.Open(_root)); // the workspace's file using var recorder = Start(); runner.Recorder = recorder; var exchange = await runner.SendAsync(runner.Prepare(PostmanCollection.Create("Recorded"), null, new HttpRequestSpec @@ -221,6 +224,37 @@ public async Task Tls_details_and_the_client_certificate_are_recorded() Assert.True(Entries(har)[0]!["timings"]!["ssl"]!.GetValue() >= 0); } + [Fact] + public async Task A_decoded_response_is_recorded_with_the_size_received_and_the_bytes_saved() + { + await using var server = await EchoServer.StartAsync(); + var data = Encoding.UTF8.GetBytes("[" + string.Join(',', Enumerable.Repeat("{\"id\":1}", 100)) + "]"); + using var gzip = new MemoryStream(); + using (var encoder = new GZipStream(gzip, CompressionLevel.Fastest, leaveOpen: true)) + { + encoder.Write(data); + } + + var preparer = new RequestPreparer(VariableResolver.Empty, null, new ExecutionDefaults()); + using var recorder = Start(); + foreach (var path in (string[])[$"bytes/{Convert.ToHexString(gzip.ToArray())}?type=application/json&encoding=gzip", $"bytes/{Convert.ToHexString(data)}?type=application/json"]) + { + recorder.Record(await new HttpExecutor().SendAsync(preparer.Prepare(new HttpRequestSpec { Url = server.Url(path) }, null, _root), _ct)); + } + + var entries = Entries(ReadHar(recorder.Save(Path.Combine(_root, "sizes.har")).Path)); + + var decoded = entries[0]!["response"]!; + var content = decoded["content"]!; + Assert.Equal("gzip", Header(decoded["headers"], "Content-Encoding")); + Assert.Equal(gzip.Length, decoded["bodySize"]!.GetValue()); + Assert.Equal((data.Length, data.Length - gzip.Length), (content["size"]!.GetValue(), content["compression"]!.GetValue())); + Assert.Equal(Encoding.UTF8.GetString(data), content["text"]!.GetValue()); + var plain = entries[1]!["response"]!; + Assert.Equal((data.Length, data.Length), (plain["bodySize"]!.GetValue(), plain["content"]!["size"]!.GetValue())); + Assert.Null(plain["content"]!["compression"]); + } + [Fact] public async Task Large_bodies_are_streamed_to_disk_and_not_kept_in_memory() { @@ -365,6 +399,277 @@ public async Task What_scripts_did_is_recorded_with_secrets_redacted() Assert.DoesNotContain("s3cr3t-value", recorded.ToJsonString(), StringComparison.Ordinal); } + [Fact] + public async Task The_password_of_a_proxy_written_with_a_space_before_it_is_redacted() + { + // A hand-edited .termrest/settings.json whose proxy the user allowed; nothing listens there, so the request fails. + const string Proxy = " http://ada:Pr0xy-s3cret@127.0.0.1:1"; + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + workspace.Settings.Proxy = Proxy; + using var runner = new RequestRunner(workspace) { AllowedProxy = Proxy }; + using var recorder = Start(); + runner.Recorder = recorder; + + var exchange = await runner.SendAsync(PostmanCollection.Create("API"), null, new HttpRequestSpec { Url = "http://api.example.com/x" }, _ct); + + Assert.Null(exchange.Response); + var path = recorder.Save(Path.Combine(_root, "proxy.har")).Path; + Assert.DoesNotContain("Pr0xy-s3cret", await File.ReadAllTextAsync(path, _ct), StringComparison.Ordinal); + Assert.Contains("127.0.0.1:1", Entries(ReadHar(path))[0]!["_termrest"]!["settings"]!["proxy"]!.GetValue(), StringComparison.Ordinal); + } + + [Fact] + public async Task A_token_a_test_script_keeps_is_redacted_in_the_response_it_came_from() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + const string Key = "9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"; + const string Jwt = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6NDJ9.c2lnbmF0dXJlLXZhbHVl"; + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var environment = workspace.CreateEnvironment("dev"); + environment.SetValues([new KeyValueEntry { Key = "session", Value = "", Type = "secret" }]); + workspace.ActiveEnvironment = environment; + using var runner = new RequestRunner(workspace) { History = new HistoryStore(Path.Combine(TestFiles.NewTempDirectory(), "history"), 10) }; + runner.SetPythonInterpreter(python); + using var recorder = Start(); + runner.Recorder = recorder; + + // A login answered as Django REST Framework ({"key": …}) and Strapi ({"jwt": …}) do: neither name says it is a credential. + var login = Encoding.UTF8.GetBytes($"{{\"key\":\"{Key}\",\"jwt\":\"{Jwt}\"}}"); + var exchange = await runner.SendAsync(PostmanCollection.Create("API"), null, new HttpRequestSpec + { + Url = server.Url($"bytes/{Convert.ToHexString(login)}?type=application/json"), + Scripts = new ScriptSet("", "body = tr.response.json()\ntr.environment.set('session', body['key'])\ntr.environment.set('jwtToken', body['jwt'])", ScriptLanguage.Python), + }, _ct); + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + + var path = recorder.Save(Path.Combine(_root, "login.har")).Path; + + var text = await File.ReadAllTextAsync(path, _ct); + Assert.DoesNotContain(Key, text, StringComparison.Ordinal); + Assert.DoesNotContain(Jwt, text, StringComparison.Ordinal); + Assert.Equal("{\"key\":\"[REDACTED]\",\"jwt\":\"[REDACTED]\"}", Entries(ReadHar(path))[0]!["response"]!["content"]!["text"]!.GetValue()); + + // The history masks the value of the variable typed secret, as it masks secrets known before sending. + var entry = Assert.Single(runner.History.Load()); + Assert.StartsWith("{\"key\":\"***\"", Encoding.UTF8.GetString(runner.History.ReadBody(entry)!), StringComparison.Ordinal); + } + + [Fact] + public async Task The_value_sent_for_a_secret_variable_is_redacted_whichever_scope_it_comes_from() + { + await using var server = await EchoServer.StartAsync(); + const string CliKey = "cli-function-key-4f9a2b"; + const string VaultValue = "vault-value-8c1d3e"; + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var environment = workspace.CreateEnvironment("prod"); + environment.SetValues( + [ + new KeyValueEntry { Key = "functionKey", Value = "", Type = "secret" }, + new KeyValueEntry { Key = "signing", Value = "{{fromVault}}", Type = "secret" }, + ]); + workspace.ActiveEnvironment = environment; + var collection = workspace.CreateCollection("API"); + collection.SetVariables([new KeyValueEntry { Key = "fromVault", Value = VaultValue }]); + using var runner = new RequestRunner(workspace) { History = new HistoryStore(Path.Combine(TestFiles.NewTempDirectory(), "history"), 10) }; + runner.LocalVariables["functionKey"] = CliKey; // termrest send … -e prod --var functionKey=… + using var recorder = Start(); + runner.Recorder = recorder; + + // Neither name says it is a credential: only their type does. + var exchange = await runner.SendAsync(collection, null, new HttpRequestSpec { Url = server.Url("echo/orders") + "?code={{functionKey}}&ref={{signing}}" }, _ct); + + Assert.Equal($"?code={CliKey}&ref={VaultValue}", JsonNode.Parse(exchange.Response!.Body)!["rawQuery"]!.GetValue()); + var entry = Assert.Single(runner.History.Load()); + Assert.EndsWith("/echo/orders?code=***&ref=***", entry.Url, StringComparison.Ordinal); + var har = await File.ReadAllTextAsync(recorder.Save(Path.Combine(_root, "secret-variables.har")).Path, _ct); + foreach (var secret in (string[])[CliKey, VaultValue]) + { + Assert.DoesNotContain(secret, Encoding.UTF8.GetString(runner.History.ReadBody(entry)!), StringComparison.Ordinal); + Assert.DoesNotContain(secret, har, StringComparison.Ordinal); + } + } + + [Fact] + public async Task A_secret_sent_in_a_url_is_redacted_as_the_url_holds_it() + { + await using var server = await EchoServer.StartAsync(); + const string Secret = "P@ss^word|1"; // the URL escapes ^ and | but not @: neither URL encoding of the value + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var environment = workspace.CreateEnvironment("prod"); + environment.SetValues([new KeyValueEntry { Key = "pass", Value = Secret, Type = "secret" }]); + workspace.ActiveEnvironment = environment; + using var runner = new RequestRunner(workspace) { History = new HistoryStore(Path.Combine(TestFiles.NewTempDirectory(), "history"), 10) }; + using var recorder = Start(); + runner.Recorder = recorder; + + var exchange = await runner.SendAsync(workspace.CreateCollection("API"), null, new HttpRequestSpec { Url = server.Url("echo/login") + "?user=ada&pass={{pass}}" }, _ct); + + Assert.Equal("?user=ada&pass=P@ss%5Eword%7C1", JsonNode.Parse(exchange.Response!.Body)!["rawQuery"]!.GetValue()); + var har = await File.ReadAllTextAsync(recorder.Save(Path.Combine(_root, "url-form.har")).Path, _ct); + var stored = Encoding.UTF8.GetString(runner.History.ReadBody(Assert.Single(runner.History.Load()))!); + foreach (var form in (string[])[Secret, "P@ss%5Eword%7C1"]) + { + Assert.DoesNotContain(form, har, StringComparison.Ordinal); + Assert.DoesNotContain(form, stored, StringComparison.Ordinal); + } + } + + [Fact] + public async Task A_secret_with_a_hash_or_a_question_mark_is_redacted_as_the_url_holds_it() + { + await using var server = await EchoServer.StartAsync(); + const string Secret = "P@ss#w?rd 1"; + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var environment = workspace.CreateEnvironment("prod"); + environment.SetValues([new KeyValueEntry { Key = "pass", Value = Secret, Type = "secret" }]); + workspace.ActiveEnvironment = environment; + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace) { History = new HistoryStore(Path.Combine(TestFiles.NewTempDirectory(), "history"), 10) }; + using var recorder = Start(); + runner.Recorder = recorder; + + // Its '#' is sent as %23, and in a path variable its '?' as %3F: neither URL encoding of the value gives these forms. + var query = await runner.SendAsync(collection, null, new HttpRequestSpec { Url = server.Url("echo/login") + "?user=ada&pass={{pass}}" }, _ct); + var path = await runner.SendAsync(collection, null, new HttpRequestSpec { Url = server.Url("echo/keys/:id"), PathVariables = [new() { Key = "id", Value = "{{pass}}" }] }, _ct); + + Assert.Equal("?user=ada&pass=P@ss%23w?rd%201", JsonNode.Parse(query.Response!.Body)!["rawQuery"]!.GetValue()); + Assert.Equal(server.BaseUri + "echo/keys/P@ss%23w%3Frd%201", path.Request.Uri!.AbsoluteUri); + var entries = runner.History.Load(); + Assert.Equal([server.Url("echo/keys/***"), server.Url("echo/login") + "?user=ada&pass=***"], entries.Select(e => e.Url)); + var har = await File.ReadAllTextAsync(recorder.Save(Path.Combine(_root, "hash-form.har")).Path, _ct); + var stored = string.Concat(entries.Select(e => Encoding.UTF8.GetString(runner.History.ReadBody(e)!))); + foreach (var form in (string[])[Secret, "P@ss%23w?rd", "P@ss%23w%3Frd"]) + { + Assert.DoesNotContain(form, har, StringComparison.Ordinal); + Assert.DoesNotContain(form, stored, StringComparison.Ordinal); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_key_sent_as_the_basic_user_name_is_in_neither_the_recording_nor_a_report_nor_the_history(bool inUrl) + { + // Stripe's documented curl takes the secret key as the user name, without a password (-u sk_test_…:, imported as Basic + // auth); in the URL, it is its user info. The response quotes the key, as an error message might. (Stripe's sample test + // key, split so that secret scanning doesn't take it for a real one.) + const string Key = "sk_test_" + "4eC39HqLyjWDarjtT1zdp7dc"; + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + using var runner = new RequestRunner(workspace) { History = new HistoryStore(Path.Combine(TestFiles.NewTempDirectory(), "history"), 10) }; + using var recorder = Start(); + runner.Recorder = recorder; + var url = server.Url($"bytes/{Convert.ToHexString(Encoding.UTF8.GetBytes($"{{\"error\":\"No such key: {Key}\"}}"))}?type=application/json"); + var auth = new AuthSpec { Type = "basic" }; + auth.Set("username", Key); + auth.Set("password", ""); + var spec = inUrl ? new HttpRequestSpec { Url = url.Replace("://", $"://{Key}:@", StringComparison.Ordinal) } : new HttpRequestSpec { Url = url, Auth = auth }; + + var exchange = await runner.SendAsync(workspace.CreateCollection("API"), null, spec, _ct); + + Assert.Contains(Key, Encoding.UTF8.GetString(exchange.Response!.Body), StringComparison.Ordinal); + var path = recorder.Save(Path.Combine(_root, "stripe.har")).Path; + var report = new Redactor().ForReport(exchange); // as termrest run --report-json redacts its report + var entry = Assert.Single(runner.History.Load()); + foreach (var text in (string[]) + [ + await File.ReadAllTextAsync(path, _ct), + report.Url(exchange.Request.Url, "url") + report.Text($"expected '{Key}' to be revoked", "tests"), + await File.ReadAllTextAsync(runner.History.FilePath, _ct), + Encoding.UTF8.GetString(runner.History.ReadBody(entry)!), + ]) + { + Assert.DoesNotContain(Key, text, StringComparison.Ordinal); + } + + Assert.Equal(inUrl ? "Basic (from the URL)" : "Basic", Entries(ReadHar(path))[0]!["_termrest"]!["auth"]!.GetValue()); + Assert.True(HistoryEntry.HasMaskedCredentials(entry.ReadSpec())); // sending it again asks for the key + } + + [Fact] + public void A_secret_is_redacted_where_json_escapes_it_as_python_or_go_does() + { + // Python's json.dumps (Flask, Django, httpbin, TermRest's Python scripts) writes non-ASCII characters as lower-case + // \u escapes; Go's encoding/json writes < > & as \u003c \u003e \u0026. + using var recorder = Start(); + var exchange = Exchange("https://example.com/login", """{"form":{"pin":"Gr\u00fc\u00dfe-2024"},"go":"k3y\u003c\u0026\u003ev4lue"}"""u8.ToArray(), method: "POST"); + exchange.Request.Body = new PreparedBody { Kind = PreparedBodyKind.Text, Text = """{"pin": "Gr\u00fc\u00dfe-2024"}""", ContentType = "application/json" }; + exchange.Request.SecretValues.UnionWith(["Grüße-2024", "k3y<&>v4lue"]); + + recorder.Record(exchange); + var entry = Assert.Single(Entries(ReadHar(recorder.Save(Path.Combine(_root, "escaped.har")).Path)))!; + + Assert.Equal("""{"pin": "[REDACTED]"}""", entry["request"]!["postData"]!["text"]!.GetValue()); + Assert.Equal("""{"form":{"pin":"[REDACTED]"},"go":"[REDACTED]"}""", entry["response"]!["content"]!["text"]!.GetValue()); + } + + [Fact] + public void A_body_in_a_charset_dotnet_does_not_support_is_recorded_as_text() + { + using var recorder = Start(); + recorder.Record(Exchange("https://example.com/utf7", [.. "Hi Mom -+Jjo--! "u8, 0xE9], "text/plain; charset=utf-7")); + + var har = ReadHar(recorder.Save(Path.Combine(_root, "utf7.har")).Path); + + Assert.Null(recorder.LastError); + Assert.Equal("Hi Mom -+Jjo--! \uFFFD", Assert.Single(Entries(har))!["response"]!["content"]!["text"]!.GetValue()); + } + + [Fact] + public void A_body_in_a_legacy_code_page_is_recorded_as_the_text_it_is() + { + using var recorder = Start(); + recorder.Record(Exchange("https://example.com/legacy", [.. "caf"u8, 0xE9], "text/plain; charset=windows-1252")); + + var har = ReadHar(recorder.Save(Path.Combine(_root, "legacy.har")).Path); + + Assert.Equal("café", Assert.Single(Entries(har))!["response"]!["content"]!["text"]!.GetValue()); + } + + [Fact] + public void A_text_body_whose_byte_order_mark_says_utf16_or_utf32_is_recorded_as_text_with_its_secrets_redacted() + { + const string Secret = "s3cr3t-wide-value"; + using var recorder = Start(); + foreach (var encoding in (Encoding[])[Encoding.Unicode, Encoding.BigEndianUnicode, Encoding.UTF32]) + { + // No charset: only the mark says how the echoed secret is encoded. + var exchange = Exchange("https://example.com/wide", [.. encoding.Preamble, .. encoding.GetBytes($"{Secret}")], "text/xml"); + exchange.Request.SecretValues.Add(Secret); + recorder.Record(exchange); + } + + var path = recorder.Save(Path.Combine(_root, "wide.har")).Path; + + Assert.All(Entries(ReadHar(path)), entry => + { + var content = entry!["response"]!["content"]!; + Assert.Null(content["encoding"]); + Assert.Equal("[REDACTED]", content["text"]!.GetValue()); + }); + Assert.DoesNotContain(Secret, File.ReadAllText(path), StringComparison.Ordinal); + } + + [Fact] + public void A_utf16_body_without_a_byte_order_mark_is_recorded_in_the_byte_order_its_text_shows() + { + // RFC 2781 lets an unmarked "UTF-16" be either byte order: a SOAP fault, say, that echoes the token. + const string Secret = "s3cr3t-token-value"; + using var recorder = Start(); + foreach (var encoding in (Encoding[])[Encoding.BigEndianUnicode, Encoding.Unicode]) + { + var exchange = Exchange("https://example.com/soap", encoding.GetBytes($"Token {Secret} is not valid"), "text/xml; charset=\"UTF-16\""); + exchange.Request.SecretValues.Add(Secret); + recorder.Record(exchange); + } + + var path = recorder.Save(Path.Combine(_root, "unmarked.har")).Path; + + Assert.All(Entries(ReadHar(path)), entry => + Assert.Equal("Token [REDACTED] is not valid", entry!["response"]!["content"]!["text"]!.GetValue())); + } + [Fact] public void An_empty_recording_is_a_valid_har_file() { @@ -391,6 +696,56 @@ public void Extra_names_from_the_workspace_settings_are_redacted() Assert.Equal("{\"tenantKey\": \"[REDACTED]\"}", entry["response"]!["content"]!["text"]!.GetValue()); } + [Fact] + public async Task Names_added_while_recording_are_redacted_in_the_requests_recorded_from_then_on() + { + var recorder = Start("ssn"); + var before = Exchange("https://example.com/before"); + before.SentHeaders.Add(new("X-Tenant-Key", "t-123456")); + recorder.Record(before); + await recorder.WhenWritten(); + + Assert.Equal(["Tenant-Key"], recorder.AddRedactNames(["SSN", "Tenant-Key"])); + Assert.Empty(recorder.AddRedactNames(["tenant_key"])); // the same name + var after = Exchange("https://example.com/after"); + after.SentHeaders.Add(new("X-Tenant-Key", "t-123456")); + recorder.Record(after); + await recorder.WhenWritten(); + recorder.Dispose(); // TermRest ended: the recording recovered next time lists the names too + + using var recovered = RequestRecorder.Recover(Assert.Single(RequestRecorder.FindUnsaved(_root))); + var har = ReadHar(recovered.Save(Path.Combine(_root, "added.har")).Path); + + Assert.Equal(["t-123456", "[REDACTED]"], Entries(har).Select(e => Header(e!["request"]!["headers"], "X-Tenant-Key"))); + Assert.Equal(["ssn", "Tenant-Key"], har["log"]!["_termrest"]!["redaction"]!["extraNames"]!.AsArray().Select(n => n!.GetValue())); + } + + [Fact] + public async Task Variables_named_like_a_name_removed_from_the_settings_while_recording_stay_redacted() + { + const string tenant = "contoso-7f3a9b2c"; + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + workspace.Settings.RecordingRedact = ["tenant-id"]; + using var runner = new RequestRunner(workspace); + runner.LocalVariables["base"] = server.BaseUri.ToString().TrimEnd('/'); + runner.LocalVariables["tenantId"] = tenant; // not typed "secret": redacted for its name + var collection = PostmanCollection.Create("Recorded"); + using var recorder = Start("tenant-id"); + runner.Recorder = recorder; + var spec = new HttpRequestSpec { Url = "{{base}}/echo/tenants/{{tenantId}}/users" }; + + await runner.SendAsync(runner.Prepare(collection, null, spec), _ct); + workspace.Settings.RecordingRedact = null; // removed in the settings: the recording goes on redacting it + await runner.SendAsync(runner.Prepare(collection, null, spec), _ct); + var path = recorder.Save(Path.Combine(_root, "removed.har")).Path; + + Assert.DoesNotContain(tenant, await File.ReadAllTextAsync(path, _ct), StringComparison.Ordinal); + Assert.Equal( + [$"{server.BaseUri}echo/tenants/[REDACTED]/users", $"{server.BaseUri}echo/tenants/[REDACTED]/users"], + Entries(ReadHar(path)).Select(e => e!["request"]!["url"]!.GetValue())); + } + [Fact] public async Task An_unsaved_recording_is_found_and_saved_after_termrest_ended() { @@ -406,7 +761,7 @@ public async Task An_unsaved_recording_is_found_and_saved_after_termrest_ended() empty.Dispose(); // nothing recorded: nothing to recover var unsaved = Assert.Single(RequestRecorder.FindUnsaved(_root)); - Assert.Equal((recorder.TempDirectory, 2, "tests"), (unsaved.TempDirectory, unsaved.Requests, unsaved.WorkspaceName)); + Assert.Equal((recorder.TempDirectory, "tests"), (unsaved.TempDirectory, unsaved.WorkspaceName)); Assert.False(Directory.Exists(empty.TempDirectory)); using var recovered = RequestRecorder.Recover(unsaved); @@ -436,5 +791,135 @@ public void The_temporary_folder_suits_the_platform(bool privateSystemTemp, stri Assert.Equal(systemTemp, RequestRecorder.ChooseTempRoot(false, null, null, systemTemp, _ => true, _ => false)); // no /var/tmp } + [Fact] + public void Secrets_are_redacted_by_name_in_json_that_is_cut_off_not_utf8_or_labelled_as_text() + { + using var recorder = Start(); + recorder.Record(Exchange("https://example.com/cut", Encoding.UTF8.GetBytes("{\"access_token\":\"tok-Cut-12345678\",\"note\":\"café")[..^1])); + recorder.Record(Exchange("https://example.com/latin1", [.. "{\"name\":\"Caf"u8, 0xE9, .. "\",\"access_token\":\"tok-Latin-12345678\"}"u8])); + recorder.Record(Exchange("https://example.com/html", "{\"access_token\":\"tok-Html-12345678\",\"token_type\":\"Bearer\"}"u8.ToArray(), "text/html")); + + // After a UTF-8 byte order mark: JSON from a file saved with one (as PHP echoes it, as text/html or with no type). + byte[] bom = [0xEF, 0xBB, 0xBF]; + recorder.Record(Exchange("https://example.com/bom", [.. bom, .. "{\"access_token\":\"tok-Bom-12345678\"}"u8], "text/html; charset=UTF-8")); + recorder.Record(Exchange("https://example.com/bom-unlabelled", [.. bom, .. " [{\"access_token\":\"tok-Bare-12345678\"}]"u8], null)); + recorder.Record(Exchange("https://example.com/bom-json", [.. bom, .. "{\"access_token\":\"tok-Json-12345678\"}"u8])); + + var path = recorder.Save(Path.Combine(_root, "text.har")).Path; + + foreach (var entry in Entries(ReadHar(path))) + { + var content = entry!["response"]!["content"]!; + Assert.Null(content["encoding"]); + Assert.Contains("\"access_token\":\"[REDACTED]\"", content["text"]!.GetValue(), StringComparison.Ordinal); + } + + Assert.DoesNotContain("tok-", File.ReadAllText(path), StringComparison.Ordinal); + } + + [Fact] + public void A_raw_form_data_body_is_recorded_as_text_without_the_values_of_parts_named_like_credentials() + { + // A browser's "Copy as cURL" of a login form, imported: a raw body, and the Content-Type with its boundary. + const string Body = "------WebKitFormBoundaryX\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\nHunter2-Secret\r\n" + + "------WebKitFormBoundaryX\r\nContent-Disposition: form-data; name=\"credentials\"; filename=\"credentials.json\"\r\nContent-Type: application/json\r\n\r\n{\"type\":\"service_account\"}\r\n" + + "------WebKitFormBoundaryX--\r\n"; + using var recorder = Start(); + var login = Exchange("https://example.com/login", "{\"echo\":\"Hunter2-Secret\"}"u8.ToArray(), method: "POST"); + login.Request.Body = new PreparedBody { Kind = PreparedBodyKind.Text, Text = Body }; + login.SentHeaders.Add(new("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryX")); + recorder.Record(login); + recorder.Record(Exchange("https://example.com/me?pw=Hunter2-Secret")); + + var path = recorder.Save(Path.Combine(_root, "form-data.har")).Path; + + Assert.DoesNotContain("Hunter2-Secret", File.ReadAllText(path), StringComparison.Ordinal); + var entries = Entries(ReadHar(path)); + var postData = entries[0]!["request"]!["postData"]!; + Assert.Null(postData["_encoding"]); + Assert.Equal(Body.Replace("Hunter2-Secret", "[REDACTED]", StringComparison.Ordinal), postData["text"]!.GetValue()); // the file as sent + Assert.Contains(entries[0]!["_termrest"]!["redacted"]!.AsArray(), n => n!["in"]!.GetValue() == "request.postData" && n["name"]?.GetValue() == "password"); + Assert.Equal("{\"echo\":\"[REDACTED]\"}", entries[0]!["response"]!["content"]!["text"]!.GetValue()); + Assert.Equal("https://example.com/me?pw=[REDACTED]", entries[1]!["request"]!["url"]!.GetValue()); + } + + [Fact] + public async Task A_text_body_that_is_not_utf8_at_all_is_written_as_replacement_characters() + { + var recorder = Start(); // not disposed if writing hangs: disposing would wait for it + recorder.Record(Exchange("https://example.com/garbage", Enumerable.Repeat((byte)0x80, 200_000).ToArray(), "text/plain")); + + await recorder.WhenWritten().WaitAsync(TimeSpan.FromSeconds(30), _ct); + var content = Entries(ReadHar(recorder.Save(Path.Combine(_root, "garbage.har")).Path))[0]!["response"]!["content"]!; + + Assert.Equal(new string('\uFFFD', 200_000), content["text"]!.GetValue()); + } + + [Fact] + public void Only_private_folders_are_recovered_and_damaged_details_are_ignored() + { + string Leftover(string details, bool shared = false) + { + var directory = Path.Combine(_root, RequestRecorder.DirectoryPrefix + Guid.NewGuid().ToString("N")); + if (OperatingSystem.IsWindows()) + { + Directory.CreateDirectory(directory); + } + else + { + // As TermRest makes them (0700), or readable by others (0755): possibly another user's, in a shared /tmp. + var mode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute; + mode |= shared ? UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute : 0; + Directory.CreateDirectory(directory, mode); + File.SetUnixFileMode(directory, mode); + } + + File.WriteAllText(Path.Combine(directory, RequestRecorder.SpoolFileName), "{\n}\n"); + File.WriteAllText(Path.Combine(directory, RequestRecorder.InfoFileName), details); + return directory; + } + + string[] damaged = ["{\"startedAt\": 1}", "{\"startedAt\": \"2026-11-05T13:29:29-07:00\", \"processId\": \"42\"}", "[]", "{"]; + var expected = damaged.Select(details => Leftover(details)).ToList(); + if (!OperatingSystem.IsWindows()) + { + Leftover("{}", shared: true); + } + + Assert.Equal(expected.Order(), RequestRecorder.FindUnsaved(_root).Select(u => u.TempDirectory).Order()); + } + + [Fact] + public void The_temporary_file_is_read_in_pieces_and_finding_a_recording_stops_at_its_first_request() + { + var first = "{\n \"a\": \"" + new string('x', 65_523) + "\"\n}"; // its last line break is the first byte of the second read + var second = "{\n \"b\": 1\n}"; + var spool = Encoding.UTF8.GetBytes(first + "\n" + second + "\n{\n \"cut\": \"off" + new string(' ', 400_000)); + using var stream = new MemoryStream(spool); + + Assert.Equal([(0L, 65_536L), (65_537L, (long)second.Length)], RequestRecorder.Scan(stream).Select(e => (e.Offset, e.Length))); + + Assert.Single(RequestRecorder.Scan(stream, max: 1)); + Assert.True(stream.Position < spool.Length / 2, $"{stream.Position} of {spool.Length} bytes read."); + } + + [Fact] + public void Recording_waits_when_requests_are_sent_faster_than_they_are_written() + { + using var recorder = Start(); + var body = new byte[2 * 1024 * 1024]; + new Random(7).NextBytes(body); + var most = 0; + for (var i = 0; i < 12; i++) + { + recorder.Record(Exchange($"https://example.com/{i}", body, "application/octet-stream")); + most = Math.Max(most, recorder.PendingWrites); + } + + Assert.True(most <= RequestRecorder.MaxPendingWrites, $"{most} requests waited to be written."); + Assert.Equal(12, recorder.Count); + recorder.Discard(); + } + public void Dispose() => _pki.Dispose(); } diff --git a/tests/TermRest.Core.Tests/RedactionTests.cs b/tests/TermRest.Core.Tests/RedactionTests.cs index e485498..504e337 100644 --- a/tests/TermRest.Core.Tests/RedactionTests.cs +++ b/tests/TermRest.Core.Tests/RedactionTests.cs @@ -44,8 +44,10 @@ private static string RedactBody(ExchangeRedactor redactor, string body, BodyFor [InlineData("code_verifier", NameKind.Field)] [InlineData("PHPSESSID", NameKind.Field)] [InlineData("cookies", NameKind.Field)] + [InlineData("X-Auth-Key", NameKind.Header)] [InlineData("key", NameKind.QueryParameter)] [InlineData("sig", NameKind.QueryParameter)] + [InlineData("auth", NameKind.QueryParameter)] [InlineData("X-Amz-Signature", NameKind.QueryParameter)] [InlineData("X-Amz-Credential", NameKind.QueryParameter)] public void Names_of_credentials_are_recognized(string name, NameKind kind) => Assert.True(SecretNames.IsSecret(name, kind), name); @@ -56,6 +58,7 @@ private static string RedactBody(ExchangeRedactor redactor, string body, BodyFor [InlineData("tokenUrl", NameKind.Field)] [InlineData("key", NameKind.Field)] [InlineData("sig", NameKind.Header)] + [InlineData("auth", NameKind.Field)] [InlineData("Content-Type", NameKind.Header)] [InlineData("publicKey", NameKind.Field)] [InlineData("keyId", NameKind.Field)] @@ -63,19 +66,23 @@ private static string RedactBody(ExchangeRedactor redactor, string body, BodyFor [InlineData("username", NameKind.Field)] [InlineData("WWW-Authenticate", NameKind.Header)] [InlineData("Idempotency-Key", NameKind.Header)] + [InlineData("Access-Control-Allow-Credentials", NameKind.Header)] [InlineData("", NameKind.Field)] public void Other_names_are_kept(string name, NameKind kind) => Assert.False(SecretNames.IsSecret(name, kind), name); [Fact] public void Extra_names_from_the_settings_are_compared_without_case_and_separators() { - var extra = SecretNames.NormalizeAll(["Tenant-Key", "ssn"]); + var extra = SecretNames.NormalizeAll(["Tenant-Key", "ssn", "Access-Control-Allow-Credentials"]); Assert.True(SecretNames.IsSecret("x_tenant_key", NameKind.Field, extra)); Assert.True(SecretNames.IsSecret("X-Tenant-Key", NameKind.Header, extra)); Assert.True(SecretNames.IsSecret("SSN", NameKind.Header, extra)); Assert.False(SecretNames.IsSecret("tenant", NameKind.Field, extra)); Assert.False(SecretNames.IsSecret("tenant_key_id", NameKind.Field, extra)); + + // Names added in the settings win over those known not to be credentials. + Assert.True(SecretNames.IsSecret("Access-Control-Allow-Credentials", NameKind.Header, extra)); } [Fact] @@ -135,16 +142,60 @@ public void Form_bodies_lose_the_values_of_secret_fields() Assert.Equal("grant_type=client_credentials&client_id=app&client_secret=[REDACTED]&scope=a+b", redacted); } + [Fact] + public void Form_data_bodies_lose_the_values_of_parts_named_like_credentials_whatever_their_shape() + { + // Typed in the editor: line breaks without CR, padding after the delimiter, a name without quotes, a header in lower case. + var redactor = For("known-secret"); + var typed = RedactBody(redactor, "--b \nContent-Disposition: form-data; name=client_secret\n\nS3cr3t-Value\n--b\ncontent-disposition: form-data; name=\"note\"\n\nknown-secret\n--b--\n", BodyFormat.Multipart); + + Assert.Equal("--b \nContent-Disposition: form-data; name=client_secret\n\n[REDACTED]\n--b\ncontent-disposition: form-data; name=\"note\"\n\n[REDACTED]\n--b--\n", typed); + Assert.Contains(redactor.Notes, n => n is { Name: "client_secret", Reason: RedactionNote.NameReason, Count: 1 }); + + // Cut off at the size limit inside a value, without the blank line, without a delimiter first: nothing known is lost. + Assert.Equal("--b\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\n[REDACTED]", RedactBody(redactor, "--b\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\nhunter2-lo", BodyFormat.Multipart)); + Assert.Equal("--b\r\nContent-Disposition: form-data; name=\"password\"\r\n[REDACTED]", RedactBody(redactor, "--b\r\nContent-Disposition: form-data; name=\"password\"\r\nknown-secret", BodyFormat.Multipart)); + Assert.Equal("password=[REDACTED]", RedactBody(redactor, "password=known-secret", BodyFormat.Multipart)); + + // With a binary file it stays binary (base64), the bytes of a secret part overwritten. + byte[] binary = [.. "--b\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\nhunter2-long\r\n--b\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"a.png\"\r\n\r\n"u8, 0x89, 0x00, 0xFF, .. "\r\n--b--\r\n"u8]; + Assert.Equal(BodyFormat.Binary, ExchangeRedactor.DetectFormat("multipart/form-data; boundary=b", binary)); + var span = Assert.Single(For().BodySpans(binary, BodyFormat.Binary, "request.postData")); + Assert.Equal("hunter2-long", Encoding.UTF8.GetString(binary.AsSpan(span.Start, span.End - span.Start))); + } + [Fact] public void Known_secrets_are_found_in_every_encoding() { var redactor = For("p+ss/w rd\"x"); var redacted = redactor.Text( - "raw p+ss/w rd\"x | uri p%2Bss%2Fw%20rd%22x | form p%2Bss%2Fw+rd%22x | json p\\u002Bss/w rd\\u0022x | minimal p+ss/w rd\\\"x | slash p+ss\\/w rd\"x", + "raw p+ss/w rd\"x | uri p%2Bss%2Fw%20rd%22x | form p%2Bss%2Fw+rd%22x | url p+ss/w%20rd%22x | json p\\u002Bss/w rd\\u0022x | minimal p+ss/w rd\\\"x | slash p+ss\\/w rd\"x", "response.content"); - Assert.Equal("raw [REDACTED] | uri [REDACTED] | form [REDACTED] | json [REDACTED] | minimal [REDACTED] | slash [REDACTED]", redacted); + Assert.Equal("raw [REDACTED] | uri [REDACTED] | form [REDACTED] | url [REDACTED] | json [REDACTED] | minimal [REDACTED] | slash [REDACTED]", redacted); + } + + [Fact] + public void A_secret_is_looked_for_as_a_url_holds_it() + { + // Only what a URL can't hold is escaped there: neither URL encoding of a value gives that form. + foreach (var c in Enumerable.Range(1, 0x7F).Where(i => i != '#').Select(i => ((char)i).ToString()).Concat(["é", "€", "😀"])) + { + var value = $"a{c}b%2F%zz"; + var url = new Uri("https://example.com/p?x=" + value).AbsoluteUri; + Assert.Equal(url[(url.IndexOf("?x=", StringComparison.Ordinal) + 3)..], SecretPatterns.InUrl(value)); + } + } + + [Fact] + public void A_value_redacted_by_name_is_found_in_a_url_with_its_hash_encoded() + { + var redactor = For(); + RedactBody(redactor, "{\"password\":\"P@ss#w0rd!\"}", BodyFormat.Json); + + // TermRest sends a '#' in a path or query value as %23, and leaves '@' and '!' as they are. + Assert.Equal("https://h/users/[REDACTED]?pin=[REDACTED]", redactor.Url("https://h/users/P@ss%23w0rd!?pin=P@ss%23w0rd!", "request.url")); } [Fact] @@ -170,6 +221,27 @@ public void Urls_keep_their_shape() "https://ada:[REDACTED]@api.example.com/v1/[REDACTED]/items?api_key=[REDACTED]&page=2&sig=[REDACTED]#access_token=[REDACTED]&token_type=Bearer", url); Assert.Equal("https://example.com/a?b=1#top", redactor.Url("https://example.com/a?b=1#top", "request.url")); + + // Firebase takes an ID token or a database secret as ?auth=. + Assert.Equal("https://app.firebaseio.com/users.json?print=pretty&auth=[REDACTED]", redactor.Url("https://app.firebaseio.com/users.json?print=pretty&auth=eyJhbGciOiJSUzI1NiJ9.e30.c2ln", "request.url")); + } + + [Fact] + public void A_url_user_name_without_a_password_is_redacted_as_the_credential_it_is() + { + const string Key = "sk_test_" + "4eC39HqLyjWDarjtT1zdp7dc"; // Stripe's sample test key, split for secret scanning + var redactor = For(); + + // Stripe takes its secret key as the user name, with an empty password or none: it is sent as Basic auth. + Assert.Equal("https://[REDACTED]:@api.stripe.com/v1/customers", redactor.Url($"https://{Key}:@api.stripe.com/v1/customers", "request.url")); + Assert.Equal("https://[REDACTED]@api.example.com:8443/a@b", redactor.Url("https://abc@api.example.com:8443/a@b", "request.url")); + foreach (var url in (string[])["https://:@h/", "https://@h/", "https://h:8443/x?y=a@b"]) + { + Assert.Equal(url, redactor.Url(url, "request.url")); + } + + Assert.Contains(redactor.Notes, n => n is { Location: "request.url", Reason: RedactionNote.UrlUserReason, Count: 2 }); + Assert.Equal("[REDACTED] abc", redactor.Text($"{Key} abc", "response.content")); // a short user name is not looked for } [Fact] @@ -192,6 +264,22 @@ public void Headers_keep_the_credential_scheme_and_cookie_names() Assert.Contains(redactor.Notes, n => n is { Location: "request.headers", Name: "Authorization", Reason: RedactionNote.CredentialReason, Count: 2 }); } + [Fact] + public void The_user_name_and_password_of_a_basic_credential_are_redacted_wherever_they_appear_later() + { + const string Key = "Fr3shd3sk-ApiK3y-42"; + static string Encode(string credentials) => Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)); + var recording = new Redactor(); + var first = recording.For(new PreparedRequest()); + + // Freshdesk takes its API key as the user name, with X as the password (typed headers, as Copy as cURL gives them). + Assert.Equal("Basic [REDACTED]", first.Header("Authorization", "Basic " + Encode(Key + ":X"), "request.headers")); + Assert.Equal("basic [REDACTED]", first.Header("Proxy-Authorization", "basic " + Encode("ada:hunter2-long"), "request.headers")); + + // Values shorter than 8 characters (X, ada) are not looked for. + Assert.Equal("[REDACTED] X ada [REDACTED]", recording.For(new PreparedRequest()).Text($"{Key} X ada hunter2-long", "response.content")); + } + [Fact] public void Values_learned_in_one_request_are_redacted_in_later_ones() { @@ -204,6 +292,72 @@ public void Values_learned_in_one_request_are_redacted_in_later_ones() Assert.Equal("https://api.example.com/x/[REDACTED]/items", second.Url("https://api.example.com/x/tok-ABCDEFGH-123/items", "request.url")); } + [Fact] + public void Every_value_learned_in_a_long_recording_is_still_redacted() + { + var recording = new Redactor(); + var tokens = Enumerable.Range(0, 300).Select(i => $"csrf-{i:D4}-{Guid.NewGuid():N}").ToList(); + foreach (var token in tokens) + { + recording.For(new PreparedRequest()).Header("X-CSRF-Token", token, "response.headers"); // a fresh one with every response + } + + var later = recording.For(new PreparedRequest()); + + Assert.Equal(string.Join(' ', tokens.Select(_ => Redactor.Placeholder)), later.Text(string.Join(' ', tokens), "request.headers")); + } + + [Fact] + public void Many_values_are_all_found_in_one_pass() + { + var random = new Random(5); + var patterns = new SecretPatterns(); + var list = new List(); + for (var i = 0; i < 600; i++) + { + var tail = new byte[random.Next(4, 30)]; + random.NextBytes(tail); + + // Values that share their start (JWTs) or their end (base64 padding), and short ones (secrets of 4 to 7 bytes). + byte[] pattern = (i % 4) switch + { + 0 => [.. "eyJhbGciOiJIUzI1NiJ9."u8, .. tail], + 1 => [.. tail, .. "=="u8], + 2 => tail[..Math.Min(tail.Length, 7)], + _ => tail, + }; + list.Add(pattern); + patterns.Add(pattern); + } + + var data = new byte[300_000]; + random.NextBytes(data); + foreach (var pattern in list.Concat(list.Take(100))) + { + pattern.CopyTo(data, random.Next(0, data.Length - pattern.Length)); // some overlap others + } + + var found = new List(); + patterns.Find(data, found); + + var covered = new bool[data.Length]; + foreach (var span in found) + { + Assert.Contains(list, p => p.AsSpan().SequenceEqual(data.AsSpan(span.Start, span.End - span.Start))); + covered.AsSpan(span.Start, span.End - span.Start).Fill(true); + } + + foreach (var pattern in list) + { + for (var at = 0; (at = IndexOf(pattern, at)) >= 0; at++) + { + Assert.True(covered.AsSpan(at, pattern.Length).IndexOf(false) < 0, $"{Convert.ToHexString(pattern)} at {at} was not found."); + } + } + + int IndexOf(byte[] pattern, int from) => data.AsSpan(from).IndexOf(pattern) is var index and >= 0 ? from + index : -1; + } + [Theory] [InlineData("application/json", "{\"a\":1}", BodyFormat.Json)] [InlineData("application/problem+json; charset=utf-8", "{}", BodyFormat.Json)] @@ -214,6 +368,100 @@ public void Values_learned_in_one_request_are_redacted_in_later_ones() [InlineData(null, "plain words", BodyFormat.Text)] [InlineData("image/png", "PNG", BodyFormat.Binary)] [InlineData("text/plain", "a\0b", BodyFormat.Binary)] + [InlineData("text/plain", "{\"access_token\":\"x\"}", BodyFormat.Json)] + [InlineData("text/html; charset=utf-8", " [1]", BodyFormat.Json)] + [InlineData("multipart/form-data; boundary=b", "--b\r\n\r\nx\r\n--b--", BodyFormat.Multipart)] + [InlineData("Multipart/Form-Data; boundary=b", "--b\r\n\r\n\0\r\n--b--", BodyFormat.Binary)] + [InlineData("application/ubjson", "{i\u0003latd", BodyFormat.Binary)] // binary JSON: "json" is not a word of its subtype + [InlineData("application/x-yaml", "a: 1", BodyFormat.Text)] public void Body_formats_are_detected(string? contentType, string body, BodyFormat expected) => Assert.Equal(expected, ExchangeRedactor.DetectFormat(contentType, Encoding.UTF8.GetBytes(body))); + + [Fact] + public void Text_bodies_stay_text_where_they_are_not_utf8() + { + byte[] cut = [.. "{\"note\":\"caf"u8, 0xC3]; // cut at the size limit inside "é" + byte[] latin1 = [.. "{\"name\":\"Caf"u8, 0xE9, .. "\"}"u8]; + + Assert.Equal(BodyFormat.Json, ExchangeRedactor.DetectFormat("application/json", cut)); + Assert.Equal(BodyFormat.Json, ExchangeRedactor.DetectFormat(null, cut)); + Assert.Equal(BodyFormat.Json, ExchangeRedactor.DetectFormat("application/json; charset=utf-8", latin1)); + Assert.Equal(BodyFormat.Text, ExchangeRedactor.DetectFormat("text/plain", [.. "caf"u8, 0xE9])); + Assert.Equal(BodyFormat.Binary, ExchangeRedactor.DetectFormat(null, latin1)); // without a content type, only UTF-8 is text + } + + [Fact] + public void Relative_urls_with_a_url_in_their_query_are_redacted() + { + var redactor = For(); + + Assert.Equal("/reset?return=https://app.example.com/&reset_token=[REDACTED]", + redactor.Header("Location", "/reset?return=https://app.example.com/&reset_token=8f3c1d2e9a7b", "response.headers")); + Assert.Equal("login?next=a://b&password=[REDACTED]", redactor.Url("login?next=a://b&password=hunter2-long", "response.headers")); + } + + [Fact] + public void A_cookie_set_again_is_looked_for_with_its_latest_value_only() + { + var recording = new Redactor(); + var shop = new PreparedRequest { Uri = new Uri("https://shop.example.com/cart") }; + for (var i = 0; i < 50; i++) + { + recording.For(shop).Header("Set-Cookie", $"AWSALB=balancer-{i:D4}-value; Path=/", "response.headers"); + } + + recording.For(new PreparedRequest { Uri = new Uri("https://other.example.com/") }).Header("Cookie", "AWSALB=other-host-value", "request.headers"); + var later = recording.For(shop); + + // Load balancers set their cookie again with every response: earlier values are no longer looked for, so the + // work for each request does not grow with the recording (cookie headers are always redacted). + Assert.Equal("[REDACTED] [REDACTED] balancer-0048-value", later.Text("balancer-0049-value other-host-value balancer-0048-value", "response.content")); + } + + [Fact] + public void A_report_learns_from_an_exchange_what_its_recording_would() + { + const string Password = "hunter2-long"; + const string Session = "sid-0123456789"; + const string Token = "tok-0123456789abcdef"; + var login = new PreparedRequest { Method = "POST", Url = "https://api.example.com/login", Uri = new Uri("https://api.example.com/login") }; + login.Headers.Add(new("Content-Type", "application/json")); + login.Body = new PreparedBody { Kind = PreparedBodyKind.Text, Text = $$"""{"user":"ada","password":"{{Password}}"}""" }; + var exchange = new HttpExchange(login) + { + Response = new ResponseSnapshot + { + StatusCode = 200, + Headers = [new("Set-Cookie", $"session={Session}; Path=/; HttpOnly")], + ContentType = "application/json", + Body = Encoding.UTF8.GetBytes($$"""{"access_token":"{{Token}}","token_type":"Bearer"}"""), + }, + }; + var report = new Redactor(); + + var redact = report.ForReport(exchange); + var next = report.For(new PreparedRequest { Uri = new Uri("https://api.example.com/me") }); + + // Test errors quote values that are in no variable: a field of the request body, a cookie, a field of the response. + Assert.Equal("expected '[REDACTED]' to equal 'x'", redact.Text($"expected '{Password}' to equal 'x'", "tests")); + Assert.Equal("session [REDACTED]", redact.Text($"session {Session}", "tests")); + Assert.Equal("expected '[REDACTED]' to have a length of 32", redact.Text($"expected '{Token}' to have a length of 32", "tests")); + Assert.Equal("token [REDACTED]", next.Text($"token {Token}", "tests")); + } + + [Fact] + public void A_report_learns_the_values_of_form_data_parts_named_like_credentials_in_a_raw_body() + { + var login = new PreparedRequest { Method = "POST", Url = "https://api.example.com/login", Uri = new Uri("https://api.example.com/login") }; + login.Headers.Add(new("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryX")); + login.Body = new PreparedBody + { + Kind = PreparedBodyKind.Text, + Text = "------WebKitFormBoundaryX\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\nHunter2-Secret\r\n------WebKitFormBoundaryX--\r\n", + }; + + var redact = new Redactor().ForReport(new HttpExchange(login)); + + Assert.Equal("expected '[REDACTED]' to equal 'x'", redact.Text("expected 'Hunter2-Secret' to equal 'x'", "tests")); + } } diff --git a/tests/TermRest.Core.Tests/ScriptingTests.cs b/tests/TermRest.Core.Tests/ScriptingTests.cs index 599ffd2..0ce2629 100644 --- a/tests/TermRest.Core.Tests/ScriptingTests.cs +++ b/tests/TermRest.Core.Tests/ScriptingTests.cs @@ -1,13 +1,19 @@ using System.Diagnostics; +using System.Globalization; +using System.Security.Cryptography; +using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; +using System.Text.RegularExpressions; using TermRest.Core.History; using TermRest.Core.Http; using TermRest.Core.Model; using TermRest.Core.Postman; +using TermRest.Core.Recording; using TermRest.Core.Scripting; using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Variables; using TermRest.Core.Workspace; using Xunit; @@ -26,6 +32,9 @@ public class ScriptingTests private static HttpRequestSpec Python(string url, string preRequest = "", string test = "") => new() { Url = url, Scripts = new ScriptSet(preRequest, test, ScriptLanguage.Python) }; + /// Python that waits until the file exists, so a test can act while scripts run. + private static string WaitFor(string flag) => $"import os, time\nwhile not os.path.exists({JsonSerializer.Serialize(flag)}):\n time.sleep(0.01)\n"; + [Fact] public async Task Scripts_run_around_a_request_from_the_collection_down_to_the_request() { @@ -140,6 +149,197 @@ import json Assert.Equal("Hi {{who}}", runner.CreateResolver(collection).Resolve("{{greeting}}")); } + [Fact] + public async Task Dates_uuids_and_decimals_set_in_scripts_are_their_text() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + runner.SetPythonInterpreter(python); + + var exchange = await runner.SendAsync(collection, null, Python(server.Url("echo"), test: """ + import datetime, decimal, uuid + tr.collection_variables.set("when", datetime.datetime(2024, 1, 2, 3, 4, 5, tzinfo=datetime.timezone.utc)) + tr.collection_variables.set("day", datetime.date(2024, 1, 2)) + tr.collection_variables.set("id", uuid.UUID("3f2504e0-4f89-11d3-9a0c-0305e82c3301")) + tr.collection_variables.set("price", decimal.Decimal("1.10")) + tr.collection_variables.set("flags", {"on": True}) + """), null, _ct); + + Assert.True(exchange.Scripts!.Error is null, exchange.Scripts.Describe()); + var stored = runner.Session.For(collection); + Assert.Equal(("2024-01-02T03:04:05+00:00", "2024-01-02", "3f2504e0-4f89-11d3-9a0c-0305e82c3301", "1.10", """{"on": true}"""), + (stored["when"], stored["day"], stored["id"], stored["price"], stored["flags"])); + } + + [Theory] + [InlineData(ScriptLanguage.Python)] + [InlineData(ScriptLanguage.JavaScript)] + [InlineData(ScriptLanguage.CSharp)] + [InlineData(ScriptLanguage.PowerShell)] + public async Task Scripts_replace_dynamic_variables_as_requests_do_so_a_stored_value_stays_one_value(string language) + { + const string Names = "guid randomUUID timestamp isoTimestamp randomInt randomBoolean randomAlphaNumeric randomHexadecimal randomFirstName randomLastName randomFullName randomUserName randomEmail randomWord randomPassword"; + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + var script = language switch + { + ScriptLanguage.Python => "for name in 'NAMES'.split():\n tr.collection_variables.set(name, tr.variables.replace_in('{{$' + name + '}}'))", + ScriptLanguage.JavaScript => "for (const name of 'NAMES'.split(' ')) pm.collectionVariables.set(name, pm.variables.replaceIn('{{$' + name + '}}'));", + ScriptLanguage.CSharp => "foreach (var name in \"NAMES\".Split(' ')) tr.CollectionVariables.Set(name, tr.Variables.ReplaceIn(\"{{$\" + name + \"}}\"));", + _ => "foreach ($name in 'NAMES'.Split(' ')) { $tr.CollectionVariables.Set($name, $tr.Variables.ReplaceIn('{{$' + $name + '}}')) }", + }; + switch (language) + { + case ScriptLanguage.Python: runner.SetPythonInterpreter(TestPython.Require()); break; + case ScriptLanguage.JavaScript: runner.SetJavaScriptRuntime(TestJavaScript.Require()); break; + case ScriptLanguage.CSharp: runner.SetCSharpRuntime(TestCSharp.Require()); break; + default: runner.SetPowerShellRuntime(TestPowerShell.Require()); break; + } + + var exchange = await runner.SendAsync(collection, null, new HttpRequestSpec + { + Url = server.Url("echo"), + Headers = [new() { Key = "X-Email", Value = "{{randomEmail}}" }, new() { Key = "X-Again", Value = "{{randomEmail}}" }], + Scripts = new ScriptSet(script.Replace("NAMES", Names, StringComparison.Ordinal), "", language), + }, _ct); + + Assert.True(exchange.Scripts!.Error is null, exchange.Scripts.Describe()); + var stored = runner.Session.For(collection); + foreach (var name in Names.Split(' ')) + { + AssertDynamicValue(name, VariableResolver.Empty.Resolve("{{$" + name + "}}")); // as requests resolve it + AssertDynamicValue(name, stored[name]); + } + + Assert.Equal((stored["randomEmail"], stored["randomEmail"]), (Header(exchange, "x-email"), Header(exchange, "x-again"))); + } + + /// A value of the dynamic variable $name in the form requests give it. + private static void AssertDynamicValue(string name, string? value) + { + static string[] Lower(string[] names) => [.. names.Select(n => n.ToLowerInvariant())]; + var text = value ?? ""; + var person = Regex.Match(text, @"^([a-z]+)\.([a-z]+)(\d{1,2}|@example\.com)$"); + var valid = name switch + { + "guid" or "randomUUID" => Regex.IsMatch(text, "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"), + "timestamp" => long.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var seconds) + && Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - seconds) < 600, + "isoTimestamp" => Regex.IsMatch(text, @"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$") + && Math.Abs((DateTime.UtcNow - DateTime.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal)).TotalMinutes) < 10, + "randomInt" => int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var number) && number <= 1000, + "randomBoolean" => text is "true" or "false", + "randomAlphaNumeric" => Regex.IsMatch(text, "^[a-z0-9]$"), + "randomHexadecimal" => Regex.IsMatch(text, "^[0-9a-f]$"), + "randomFirstName" => VariableResolver.FirstNames.Contains(text), + "randomLastName" => VariableResolver.LastNames.Contains(text), + "randomFullName" => text.Split(' ') is [var first, var last] && VariableResolver.FirstNames.Contains(first) && VariableResolver.LastNames.Contains(last), + "randomUserName" or "randomEmail" => person.Success && Lower(VariableResolver.FirstNames).Contains(person.Groups[1].Value) + && Lower(VariableResolver.LastNames).Contains(person.Groups[2].Value) && person.Groups[3].Value.StartsWith('@') == (name == "randomEmail"), + "randomWord" => VariableResolver.Words.Contains(text), + "randomPassword" => Regex.IsMatch(text, "^[a-z0-9]{15}$"), + _ => false, + }; + Assert.True(valid, $"${name}: '{value}'"); + } + + [Fact] + public async Task Log_lines_reach_the_script_that_writes_them_through_a_handler_an_earlier_script_made() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + collection.SetScripts(collection.RootNode, new ScriptSet( + "import logging\nlogging.basicConfig(level=logging.INFO, format='%(message)s')\nlogging.info('collection logs')", "", ScriptLanguage.Python)); + var first = collection.AddRequest(collection.RootNode, "First", Python(server.Url("echo"), preRequest: "import logging\nlogging.info('request logs')\nprint('request prints')")); + var second = collection.AddRequest(collection.RootNode, "Second", Python(server.Url("echo"), preRequest: "import logging\nlogging.info('logged again')")); + using var runner = new RequestRunner(workspace); + runner.SetPythonInterpreter(python); + + var sentFirst = await runner.SendAsync(collection, first, first.ReadSpec(), null, _ct); + var sentSecond = await runner.SendAsync(collection, second, second.ReadSpec(), null, _ct); + + // logging.basicConfig keeps the sys.stderr of the script that called it: the same capture for every script. + Assert.Equal(["collection logs", "request logs", "request prints"], sentFirst.Scripts!.Logs.Select(l => l.Text)); + Assert.Equal(["collection logs", "logged again"], sentSecond.Scripts!.Logs.Select(l => l.Text)); + + // An exception whose text can't be read fails its script, not the whole answer: what it printed is kept. + var failing = await runner.SendAsync(collection, null, Python(server.Url("echo"), preRequest: """ + class Unreadable(Exception): + def __str__(self): + raise RuntimeError("no text") + print("before") + raise Unreadable() + """), _ct); + Assert.Equal("Unreadable: (its message could not be read)", failing.Scripts!.Error!.Message); + Assert.Contains("before", failing.Scripts.Logs.Select(l => l.Text)); + } + + [Fact] + public async Task A_body_set_to_bytes_a_dict_or_a_list_is_sent_as_text() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + runner.SetPythonInterpreter(python); + async Task Send(string preRequest) + { + var spec = Python(server.Url("echo"), preRequest: preRequest); + spec.Method = "POST"; + spec.Body = new RequestBody { Mode = BodyMode.Raw, Raw = "original" }; + return await runner.SendAsync(collection, null, spec, _ct); + } + + async Task SentBody(string preRequest) + { + var exchange = await Send(preRequest); + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + return Echoed(exchange)["body"]!.GetValue(); + } + + Assert.Equal("""{"name": "Zoë"}""", await SentBody("import json\ntr.request.body = json.dumps({'name': 'Zoë'}, ensure_ascii=False).encode()")); + + // Objects and lists are sent as JSON, as variables get them, not as Python's text for them. + Assert.Equal("""{"name": "Zo\u00eb", "n": 1}""", await SentBody("tr.request.body = {'name': 'Zoë', 'n': 1}")); + Assert.Equal("[1, true, null]", await SentBody("tr.request.body = (1, True, None)")); + Assert.Equal("true", await SentBody("tr.request.body = True")); + var notJson = await Send("import datetime\ntr.request.body = {'day': datetime.date(2026, 1, 2)}"); + Assert.Null(notJson.Response); + Assert.StartsWith("The pre-request scripts set the request body to a dict that cannot be sent as JSON: ", notJson.Scripts!.Error!.Message, StringComparison.Ordinal); + + // Headers may be given as with requests: a dict (or any other mapping, or pairs) replaces them. + var headers = await Send("tr.request.headers = {'X-Api-Key': 'k-1', 'X-Count': 2}"); + Assert.True(headers.Scripts!.Succeeded, headers.Scripts.Describe()); + Assert.Equal(("k-1", "2"), (Header(headers, "x-api-key"), Header(headers, "x-count"))); + var mapping = await Send("import types\ntr.request.headers = types.MappingProxyType({'X-Api-Key': 'k-2'})"); + Assert.True(mapping.Scripts!.Succeeded, mapping.Scripts.Describe()); + Assert.Equal("k-2", Header(mapping, "x-api-key")); + + // A request the scripts left unusable is not sent, and what they did is kept. + var broken = await Send(""" + class Unreadable: + def __str__(self): + raise ValueError("no text") + print("before") + tr.test("ran", lambda: None) + tr.collection_variables.set("kept", "yes") + tr.request.url = Unreadable() + """); + Assert.Null(broken.Response); + Assert.Equal("The pre-request scripts left a request that cannot be sent: ValueError: no text", broken.Scripts!.Error!.Message); + Assert.Equal(["before"], broken.Scripts.Logs.Select(l => l.Text)); + Assert.Equal(["ran"], broken.Scripts.Tests.Select(t => t.Name)); + Assert.Equal("yes", runner.Session.For(collection)["kept"]); + } + [Fact] public async Task A_failing_pre_request_script_stops_the_request() { @@ -171,6 +371,102 @@ public async Task A_failing_pre_request_script_stops_the_request() Assert.Contains("line 2", syntax.Scripts.Error.Details, StringComparison.Ordinal); } + [Fact] + public async Task The_request_is_sent_and_kept_as_it_was_though_it_is_edited_while_its_scripts_run() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace) { History = new HistoryStore(Path.Combine(TestFiles.NewTempDirectory(), "history"), 10) }; + runner.SetPythonInterpreter(python); + var edited = Path.Combine(TestFiles.NewTempDirectory(), "edited"); + var spec = Python(server.Url("echo/orders/1"), preRequest: WaitFor(edited)); + + // The full-screen UI's editor stays open while the scripts run (the first build of C# scripts takes seconds). + var sending = runner.SendAsync(collection, null, spec, _ct); + spec.Url = server.Url("echo/orders/2"); + await File.WriteAllTextAsync(edited, "", _ct); + var exchange = await sending; + + Assert.Equal("/echo/orders/1", Echoed(exchange)["path"]!.GetValue()); + var entry = Assert.Single(runner.History!.Load()); + Assert.EndsWith("/echo/orders/1", entry.Url, StringComparison.Ordinal); + Assert.EndsWith("/echo/orders/1", entry.ReadSpec().Url, StringComparison.Ordinal); + } + + [Fact] + public async Task A_request_runs_in_the_environment_it_was_sent_with_though_another_is_chosen_meanwhile() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + const string Ticket = "T-8d3f61c2a9"; + var temp = TestFiles.NewTempDirectory(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var login = server.Url($"bytes/{Convert.ToHexString(Encoding.UTF8.GetBytes($"{{\"ticket\":\"{Ticket}\"}}"))}?type=application/json"); + var prod = workspace.CreateEnvironment("prod"); + prod.SetValues([new KeyValueEntry { Key = "login", Value = login }, new KeyValueEntry { Key = "ticket", Value = "", Type = "secret" }]); + var sandbox = workspace.CreateEnvironment("partner-sandbox"); + sandbox.SetValues([new KeyValueEntry { Key = "login", Value = server.Url("echo/sandbox") }]); + workspace.ActiveEnvironment = prod; + var collection = workspace.CreateCollection("API"); + var switched = Path.Combine(temp, "switched"); + var node = collection.AddRequest(collection.RootNode, "Login", Python("{{login}}", + preRequest: WaitFor(switched) + "tr.environment.set('region', 'eu')", + test: "tr.environment.set('ticket', tr.response.json()['ticket'])\nprint('sent in', tr.info.environment)")); + using var runner = new RequestRunner(workspace) { History = new HistoryStore(Path.Combine(temp, "history"), 10) }; + runner.SetPythonInterpreter(python); + using var recorder = RequestRecorder.Start(new RecordingOptions { TempRoot = temp, WorkspaceName = "tests" }); + runner.Recorder = recorder; + + // "partner-sandbox" is chosen (F7) while the pre-request scripts run. + var sending = runner.SendAsync(collection, node, node.ReadSpec(), null, _ct); + workspace.ActiveEnvironment = sandbox; + await File.WriteAllTextAsync(switched, "", _ct); + var exchange = await sending; + + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal(login, exchange.Request.Url); + Assert.Equal(["sent in prod"], exchange.Scripts.Logs.Select(l => l.Text)); + Assert.Equal(("eu", Ticket), (runner.Session.Find(prod)?["region"], runner.Session.Find(prod)?["ticket"])); + Assert.Null(runner.Session.Find(sandbox)); + var entry = Assert.Single(runner.History!.Load()); + Assert.Equal("prod", entry.Environment); + Assert.Equal("{\"ticket\":\"***\"}", Encoding.UTF8.GetString(runner.History.ReadBody(entry)!)); // typed secret in prod + var har = JsonNode.Parse(await File.ReadAllTextAsync(recorder.Save(Path.Combine(temp, "login.har")).Path, _ct))!; + Assert.Equal("prod", har["log"]!["entries"]![0]!["_termrest"]!["environment"]!.GetValue()); + } + + [Fact] + public async Task Values_scripts_give_secret_variables_are_masked_in_the_history() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + const string RequestKey = "request-key-7f3a9c"; + const string Session = "session-4be1d07a9f"; + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var environment = workspace.CreateEnvironment("prod"); + environment.SetValues([new KeyValueEntry { Key = "functionKey", Value = "", Type = "secret" }]); + workspace.ActiveEnvironment = environment; + var collection = workspace.CreateCollection("API"); + collection.SetVariables([new KeyValueEntry { Key = "session", Value = "", Type = "secret" }]); + using var runner = new RequestRunner(workspace) { History = new HistoryStore(Path.Combine(TestFiles.NewTempDirectory(), "history"), 10) }; + runner.SetPythonInterpreter(python); + var login = Encoding.UTF8.GetBytes($"{{\"session\":\"{Session}\"}}"); + + // The key is set for this request only; the session is kept in the environment, where "session" is not typed secret. + var exchange = await runner.SendAsync(collection, null, Python(server.Url($"bytes/{Convert.ToHexString(login)}?type=application/json") + "&code={{functionKey}}", + preRequest: $"tr.variables.set('functionKey', '{RequestKey}')", + test: "tr.environment.set('session', tr.response.json()['session'])"), _ct); + + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.EndsWith($"&code={RequestKey}", exchange.Request.Url, StringComparison.Ordinal); + Assert.Equal(Session, runner.Session.Find(environment)?["session"]); + var entry = Assert.Single(runner.History!.Load()); + Assert.EndsWith("&code=***", entry.Url, StringComparison.Ordinal); + Assert.Equal("{\"session\":\"***\"}", Encoding.UTF8.GetString(runner.History.ReadBody(entry)!)); + } + [Fact] public async Task Scripts_without_a_runtime_stop_the_request_or_are_skipped_with_a_note() { @@ -249,6 +545,36 @@ public async Task Python_is_stopped_when_scripts_take_too_long_and_when_it_is_id Assert.True(again.Scripts!.Succeeded, again.Scripts.Describe()); } + [Fact] + public async Task Stopping_scripts_stops_a_script_that_runs_at_once() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + runner.SetPythonInterpreter(python); + var running = Path.Combine(workspace.RootPath, "running"); + var sending = runner.SendAsync(collection, null, Python(server.Url("echo"), preRequest: "import time\nopen('running', 'w').close()\ntime.sleep(20)"), _ct); + for (var i = 0; i < 600 && !File.Exists(running); i++) + { + await Task.Delay(50, _ct); + } + + Assert.True(File.Exists(running)); + + // Tools › Scripts › Stop scripts, on the UI thread: Python would read the end of its input only after the script. + var watch = Stopwatch.StartNew(); + runner.StopScripts(); + var stopping = watch.Elapsed; + var exchange = await sending; + + Assert.True(stopping < TimeSpan.FromSeconds(1), $"Stopping took {stopping.TotalMilliseconds:0} ms."); + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(10), $"The run ended after {watch.Elapsed.TotalSeconds:0.0} s."); + Assert.Null(exchange.Response); + Assert.Equal("Not sent: Python was stopped while the scripts ran.", exchange.ErrorMessage); + } + [Fact] public async Task Programs_that_scripts_start_cannot_disturb_python() { @@ -267,11 +593,197 @@ public async Task Programs_that_scripts_start_cannot_disturb_python() child = subprocess.run([sys.executable, "-c", "import sys; print(repr(sys.stdin.read()))"], capture_output=True, text=True, timeout=10) print("a child reads", child.stdout.strip()) print("captured", "ünïcödé ✓") + if os.name != "nt": + tr.globals.set("session", "its own" if os.getsid(0) == os.getpid() else "TermRest's") """, test: "tr.test('still answers', lambda: None)"), _ct); Assert.Equal(200, exchange.Response!.StatusCode); Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); Assert.Equal(["a child reads ''", "captured ünïcödé ✓"], exchange.Scripts.Logs.Select(l => l.Text)); + + // Nor can they open TermRest's terminal (/dev/tty) to ask for a password over its screen: Python is in a session of its + // own, which has none (this test may run without a terminal, so trying to open it would tell nothing). + Assert.Equal(OperatingSystem.IsWindows() ? null : "its own", runner.Session.Globals.GetValueOrDefault("session")); + } + + [Fact] + public async Task Workspace_modules_named_like_python_modules_do_not_replace_those_of_the_worker() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + foreach (var name in (string[])["types", "json", "re", "traceback"]) + { + await File.WriteAllTextAsync(Path.Combine(workspace.RootPath, name + ".py"), $"raise ImportError('the workspace has its own {name}')", _ct); + } + + await File.WriteAllTextAsync(Path.Combine(workspace.RootPath, "helpers.py"), "def greet(name):\n return 'hello ' + name\n", _ct); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + runner.SetPythonInterpreter(python); + + // The scripts still import the workspace's modules. + var exchange = await runner.SendAsync(collection, null, Python(server.Url("echo"), test: "import helpers\ntr.test(helpers.greet('Ada'), lambda: None)"), _ct); + + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal(["hello Ada"], exchange.Scripts.Tests.Select(t => t.Name)); + } + + [Fact] + public async Task Python_runs_scripts_through_a_batch_file_that_passes_its_arguments_on() + { + if (!OperatingSystem.IsWindows()) + { + Assert.Skip("Batch files are Windows'."); + } + + var python = TestPython.Require(); + var (ok, description) = await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.Python, python, _ct); + Assert.True(ok, description); + var executable = description.Split(" · ")[1]; + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + + // A batch file that passes its arguments on, as pyenv-win's shims do (python.bat: call pyenv exec python %*, which keeps + // them in a variable and expands them in blocks). cmd.exe runs it, which ends a command line at its first line break. + var shim = Path.Combine(TestFiles.NewTempDirectory(), "python.bat"); + await File.WriteAllTextAsync(shim, + $"@echo off\r\ncall :exec %*\r\nexit /b\r\n:exec\r\nset cmdline=%*\r\nif defined cmdline (\"{executable}\" %cmdline%)\r\n", _ct); + using var runner = new RequestRunner(workspace); + runner.SetPythonInterpreter(shim); + + var exchange = await runner.SendAsync(collection, null, Python(server.Url("echo"), + preRequest: "tr.request.headers.set('X-Ran', 'yes')", test: "tr.test('ran', lambda: None)"), _ct); + + Assert.True(exchange.Scripts!.Succeeded, exchange.ErrorMessage ?? exchange.Scripts.Describe()); + Assert.Equal("yes", Header(exchange, "x-ran")); + Assert.Equal(["ran"], exchange.Scripts.Tests.Select(t => t.Name)); + } + + [Fact] + public async Task Python_keeps_only_the_output_it_shows() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + runner.SetPythonInterpreter(python); + + // A script that prints without end: what is not shown is counted, not kept in memory. + var exchange = await runner.SendAsync(collection, null, Python(server.Url("echo"), test: """ + import tracemalloc + print("first", end="\r\n") + tracemalloc.start() + for i in range(300000): + print(f"line {i} " + "x" * 100) + tr.globals.set("kept", tracemalloc.get_traced_memory()[0]) + tracemalloc.stop() + """), _ct); + + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal(1000, exchange.Scripts.Logs.Count); + Assert.Equal(("first", "line 998 " + new string('x', 100)), (exchange.Scripts.Logs[0].Text, exchange.Scripts.Logs[^1].Text)); + Assert.Contains("299001 more lines the test scripts printed are not shown.", exchange.Scripts.Notes); + Assert.True(long.Parse(runner.Session.Globals["kept"]!, CultureInfo.InvariantCulture) < 2_000_000, runner.Session.Globals["kept"]); + } + + [Fact] + public async Task Scripts_get_the_bytes_of_the_response_as_they_arrived() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + runner.SetPythonInterpreter(python); + async Task Get(string hex, string type) => (await runner.SendAsync(collection, null, + Python(server.Url($"bytes/{hex}?type={Uri.EscapeDataString(type)}"), test: $""" + tr.test(repr(tr.response.text()), lambda: None) + assert tr.response.content == bytes.fromhex("{hex}"), tr.response.content.hex() + assert len(tr.response.content) == tr.response.size + """), _ct)).Scripts!; + + // Protobuf (no zero byte: it looks like text), Latin-1 and a byte order mark: the text is decoded, the bytes stay. + var protobuf = await Get("089601120178", "application/x-protobuf"); + var latin1 = await Get("436166E9", "text/plain; charset=iso-8859-1"); + var bom = await Get("EFBBBF7B7D", "application/json"); + + Assert.True(protobuf.Succeeded, protobuf.Describe()); + Assert.True(latin1.Succeeded, latin1.Describe()); + Assert.True(bom.Succeeded, bom.Describe()); + Assert.Equal(["'Café'", "'{}'"], [latin1.Tests[0].Name, bom.Tests[0].Name]); + } + + [Fact] + public async Task Large_bodies_reach_the_scripts_whole() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + runner.SetPythonInterpreter(python); + var hashes = Python("", test: """ + import hashlib + tr.globals.set("text", hashlib.sha256(tr.response.text().encode()).hexdigest()) + tr.globals.set("bytes", hashlib.sha256(tr.response.content).hexdigest()) + """); + + // They are written to Python in parts: text with escapes and an emoji across the end of a part (5 × 60,000 + // characters), and bytes not in whole groups of 3 for base64. + hashes.Url = server.Url("bytes/225C0AF09F9880?type=text%2Fplain&repeat=60000"); + var text = await runner.SendAsync(collection, null, hashes, _ct); + Assert.True(text.Scripts!.Succeeded, text.Scripts.Describe()); + Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(text.Response!.Body)), runner.Session.Globals["text"]); + Assert.Equal(runner.Session.Globals["text"], runner.Session.Globals["bytes"]); + + hashes.Url = server.Url("bytes/00FF?repeat=150001"); + var bytes = await runner.SendAsync(collection, null, hashes, _ct); + Assert.True(bytes.Scripts!.Succeeded, bytes.Scripts.Describe()); + Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(bytes.Response!.Body)), runner.Session.Globals["bytes"]); + } + + [Fact] + public async Task Halves_of_surrogate_pairs_in_answers_become_replacement_characters() + { + var python = TestPython.Require(); + await using var server = await EchoServer.StartAsync(); + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + runner.SetPythonInterpreter(python); + + // Python's json writes them as escapes (\ud83d), which are not text; whole pairs (😀) stay. + var exchange = await runner.SendAsync(collection, null, Python(server.Url("echo"), test: """ + print("lone \udc00, pair 😀") + tr.test("half \ud83d", lambda: None) + tr.globals.set("name \ud800", "\\ud83d") + """), _ct); + + Assert.Equal(200, exchange.Response!.StatusCode); + Assert.True(exchange.Scripts!.Succeeded, exchange.Scripts.Describe()); + Assert.Equal(["lone \uFFFD, pair 😀"], exchange.Scripts.Logs.Select(l => l.Text)); + Assert.Equal(["half \uFFFD"], exchange.Scripts.Tests.Select(t => t.Name)); + Assert.Equal(@"\ud83d", runner.Session.Globals["name \uFFFD"]); + } + + [Fact] + public async Task What_python_wrote_last_is_kept_without_half_of_an_emoji() + { + var python = TestPython.Require(); + using var worker = ScriptWorker.For(ScriptLanguage.Python, python, TestFiles.NewTempDirectory()); + var message = new JsonObject + { + ["phase"] = "test", + ["scripts"] = new JsonArray(new JsonObject { ["name"] = "request", ["code"] = "import os\nos.write(2, ('😀' * 2500 + 'x').encode())\nos._exit(3)" }), + }; + + // Its last 4,000 characters (UTF-16) start with the second half of an emoji, which is left out. + var stopped = await Assert.ThrowsAsync(() => worker.RunAsync(message, TimeSpan.FromSeconds(30), cancellationToken: _ct)); + + Assert.Equal("Python stopped.\n" + string.Concat(Enumerable.Repeat("😀", 1999)) + "x", stopped.Message); } [Fact] @@ -459,6 +971,83 @@ public void Runtimes_are_chosen_per_workspace_in_the_user_settings() Assert.DoesNotContain("\"scriptLanguageOrder\"", json, StringComparison.Ordinal); } + [Fact] + public async Task A_command_starts_a_runtime_from_the_folders_of_path_only() + { + var folder = TestFiles.NewTempDirectory(); + var name = "termrest-probe-" + Guid.NewGuid().ToString("N")[..8]; + var program = Path.Combine(folder, OperatingSystem.IsWindows() ? name + ".exe" : name); + await File.WriteAllTextAsync(program, "", _ct); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(program, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + + Assert.Equal(program, ScriptRuntimeLocator.Executable(name, string.Join(Path.PathSeparator, TestFiles.NewTempDirectory(), "", folder))); + Assert.Null(ScriptRuntimeLocator.Executable(name, TestFiles.NewTempDirectory())); + Assert.Equal(Path.Combine(".venv", "bin", "python"), ScriptRuntimeLocator.Executable(Path.Combine(".venv", "bin", "python"), "")); + + // A dot in a command's name is not an extension that Windows runs: python3.12 is python3.12.exe there, as in shells. + var dotted = Path.Combine(folder, OperatingSystem.IsWindows() ? name + ".12.exe" : name + ".12"); + File.Copy(program, dotted); + Assert.Equal(dotted, ScriptRuntimeLocator.Executable(name + ".12", folder)); + + // Windows and .NET look in the running program's folder (and in the current one, the workspace often) before PATH: + // a program of that name there is not run. + var command = OperatingSystem.IsWindows() ? name + ".cmd" : name; + var lookalike = Path.Combine(AppContext.BaseDirectory, command); + await File.WriteAllTextAsync(lookalike, OperatingSystem.IsWindows() ? "@echo Python 3.99.0\r\n@echo %~f0\r\n" : "#!/bin/sh\necho Python 3.99.0\necho \"$0\"\n", _ct); + try + { + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(lookalike, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + + Assert.Equal((false, $"{command} could not be started: it is not on PATH."), + await ScriptRuntimeLocator.CheckAsync(ScriptLanguage.Python, command, _ct)); + } + finally + { + File.Delete(lookalike); + } + } + + [Fact] + public async Task Find_proposes_the_python_of_the_workspace_without_running_it() + { + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var venv = OperatingSystem.IsWindows() ? Path.Combine(".venv", "Scripts", "python.exe") : Path.Combine(".venv", "bin", "python"); + Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(workspace.RootPath, venv))!); + await File.WriteAllTextAsync(Path.Combine(workspace.RootPath, venv), "not a program: running it fails", _ct); + using var runner = new RequestRunner(workspace); + + var found = await ScriptRuntimeLocator.FindAsync(ScriptLanguage.Python, workspace.RootPath, runner.ResolveRuntime, _ct); + + Assert.Equal((venv, "Found in this workspace, not run: Check runs it.", false), found); + } + + [Fact] + public async Task Find_runs_runtimes_outside_the_workspace() + { + // In the workspace, a runtime would obey its files before it is chosen: Bun runs what a bunfig.toml preloads, and + // dotnet lists the SDKs that a global.json points to. This runtime tells where it runs. + var workspace = TestFiles.NewTempDirectory(); + var runtime = Path.Combine(TestFiles.NewTempDirectory(), OperatingSystem.IsWindows() ? "where.cmd" : "where"); + await File.WriteAllTextAsync(runtime, OperatingSystem.IsWindows() ? "@echo Node.js 99.0.0\r\n@cd\r\n" : "#!/bin/sh\necho Node.js 99.0.0\npwd\n", _ct); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(runtime, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + + var found = await ScriptRuntimeLocator.FindAsync(ScriptLanguage.JavaScript, workspace, _ => runtime, _ct); + + Assert.NotNull(found); + Assert.True(found.Value.Checked, found.Value.Description); + Assert.StartsWith("Node.js 99.0.0 · ", found.Value.Description, StringComparison.Ordinal); + Assert.DoesNotContain(Path.GetFileName(workspace), found.Value.Description, StringComparison.Ordinal); + } + [Fact] public void The_language_order_is_the_users_for_every_workspace() { diff --git a/tests/TermRest.Core.Tests/TextFileTests.cs b/tests/TermRest.Core.Tests/TextFileTests.cs index d6653e3..9045599 100644 --- a/tests/TermRest.Core.Tests/TextFileTests.cs +++ b/tests/TermRest.Core.Tests/TextFileTests.cs @@ -1,6 +1,7 @@ using System.Security.AccessControl; using TermRest.Core.IO; using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Workspace; using Xunit; namespace TermRest.Core.Tests; @@ -81,4 +82,65 @@ public void Saving_a_new_file_creates_it() Assert.Equal([0xEF, 0xBB, 0xBF, (byte)'{', (byte)'}', (byte)'\r', (byte)'\n'], File.ReadAllBytes(path)); } + + [Fact] + public void A_failed_save_keeps_the_original_and_leaves_no_temp_file() + { + if (!OperatingSystem.IsWindows()) + { + Assert.Skip("Windows file locks only."); + return; + } + + var directory = TestFiles.NewTempDirectory(); + var path = Path.Combine(directory, "locked.postman_environment.json"); + File.WriteAllText(path, "{}"); + using (new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None)) + { + var error = Record.Exception(() => TextFile.WriteAtomic(path, "{\"changed\": true}")); + Assert.True(error is IOException or UnauthorizedAccessException, error?.ToString()); + } + + Assert.Equal("{}", File.ReadAllText(path)); + Assert.Equal([path], Directory.GetFiles(directory)); + } + + [Fact] + public void Files_that_are_not_utf8_are_reported_instead_of_being_garbled() + { + var directory = TestFiles.NewTempDirectory(); + var path = Path.Combine(directory, "dev.postman_environment.json"); + File.WriteAllBytes(path, [.. "{\"name\": \"dev\",\n\"values\": [{\"key\": \"city\", \"value\": \"Z"u8, 0xFC, .. "rich\"}]}"u8]); + + var error = Assert.Throws(() => TextFile.Read(path)); + Assert.Contains("not UTF-8", error.Message, StringComparison.Ordinal); + Assert.Contains("line 2", error.Message, StringComparison.Ordinal); + + var workspace = ApiWorkspace.Open(directory); + Assert.Empty(workspace.Environments); + Assert.Contains(workspace.LoadErrors, e => e.Contains("not UTF-8", StringComparison.Ordinal)); + } + + [Fact] + public void Only_regular_files_of_a_sane_size_are_read() + { + // A symbolic link in a cloned repository can point at a device or a pipe: reading must neither exhaust memory nor block. + var device = OperatingSystem.IsWindows() ? "NUL" : "/dev/zero"; + Assert.Contains("not a regular file", Assert.Throws(() => TextFile.Read(device)).Message, StringComparison.Ordinal); + + var path = Path.Combine(TestFiles.NewTempDirectory(), "huge.postman_collection.json"); + try + { + using (var stream = File.Create(path)) + { + stream.SetLength(TextFile.MaxSize + 1); + } + + Assert.Contains("too large", Assert.Throws(() => TextFile.Read(path)).Message, StringComparison.Ordinal); + } + finally + { + File.Delete(path); + } + } } diff --git a/tests/TermRest.Core.Tests/UrlMatchPatternTests.cs b/tests/TermRest.Core.Tests/UrlMatchPatternTests.cs index 2592b6e..a6cd789 100644 --- a/tests/TermRest.Core.Tests/UrlMatchPatternTests.cs +++ b/tests/TermRest.Core.Tests/UrlMatchPatternTests.cs @@ -28,11 +28,44 @@ public void Matches_like_postman(string pattern, string url, bool expected) [InlineData("")] [InlineData("https://api.*.com/*")] [InlineData("https://host:notaport/*")] + [InlineData("https://bü..example/*")] public void Rejects_invalid_patterns(string pattern) { Assert.False(UrlMatchPattern.TryParse(pattern, out _)); } + [Theory] + [InlineData("https://bücher.example/*", "https://bücher.example/api")] + [InlineData("https://BÜCHER.example/*", "https://xn--bcher-kva.example/api")] + [InlineData("https://*.bücher.example/*", "https://shop.bücher.example/")] + [InlineData("https://xn--bcher-kva.example/*", "https://bücher.example/api")] + public void A_host_matches_whether_written_in_unicode_or_in_ascii(string pattern, string url) + { + Assert.True(UrlMatchPattern.TryParse(pattern, out var parsed)); + Assert.True(parsed!.IsMatch(new Uri(url))); + } + + [Theory] + [InlineData("https://[::1]:8443/*", "https://[::1]:8443/api", true)] + [InlineData("https://[::1]/*", "https://[::1]:8443/api", true)] + [InlineData("https://[0:0::1]:*/*", "https://[::1]:8443/api", true)] + [InlineData("https://[FE80::A]/*", "https://[fe80:0::a]/", true)] + [InlineData("https://[::2]/*", "https://[::1]/", false)] + public void An_ipv6_host_matches_in_any_of_its_forms(string pattern, string url, bool expected) + { + Assert.True(UrlMatchPattern.TryParse(pattern, out var parsed)); + Assert.Equal(expected, parsed!.IsMatch(new Uri(url))); + } + + [Theory] + [InlineData("https://[::1/*")] + [InlineData("https://[1.2.3.4]/*")] + [InlineData("https://[nothex::1]:8443/*")] + public void Rejects_invalid_ipv6_hosts(string pattern) + { + Assert.False(UrlMatchPattern.TryParse(pattern, out _)); + } + [Fact] public void Registry_prefers_the_most_specific_match() { diff --git a/tests/TermRest.Core.Tests/VariableResolverTests.cs b/tests/TermRest.Core.Tests/VariableResolverTests.cs index 8d14970..65edd3b 100644 --- a/tests/TermRest.Core.Tests/VariableResolverTests.cs +++ b/tests/TermRest.Core.Tests/VariableResolverTests.cs @@ -53,6 +53,40 @@ public void Self_references_terminate() Assert.Equal("{{loop}}", resolver.Resolve("{{loop}}")); } + [Fact] + public void Values_that_reference_themselves_several_times_stop_growing() + { + // Each pass would multiply the text by 8 (8^10 references after ten passes): the expansion stops at the limit, + // and the references left are reported as unresolved. + var resolver = new VariableResolver([new DictionaryScope("x", new Dictionary + { + ["baseUrl"] = string.Concat(Enumerable.Repeat("{{baseUrl}}", 8)), + ["host"] = "example.com", + })]); + var unresolved = new HashSet(); + + var result = resolver.Resolve("https://{{host}}/{{baseUrl}}/ping", unresolved); + + Assert.InRange(result.Length, VariableResolver.MaxGrowth / 2, VariableResolver.MaxGrowth + 100); + Assert.StartsWith("https://example.com/", result, StringComparison.Ordinal); + Assert.EndsWith("/ping", result, StringComparison.Ordinal); + Assert.Equal(["baseUrl"], unresolved); + } + + [Fact] + public void A_value_too_long_to_insert_is_left_unresolved_and_others_are_not() + { + var resolver = new VariableResolver([new DictionaryScope("x", new Dictionary + { + ["upload"] = new('A', VariableResolver.MaxGrowth + 100), + ["id"] = "42", + })]); + var unresolved = new HashSet(); + + Assert.Equal("{\"file\":\"{{upload}}\",\"id\":42}", resolver.Resolve("{\"file\":\"{{upload}}\",\"id\":{{id}}}", unresolved)); + Assert.Equal(["upload"], unresolved); + } + [Fact] public void Dynamic_variables_produce_values() { @@ -66,6 +100,20 @@ public void Dynamic_variables_produce_values() Assert.NotEqual(resolver.Resolve("{{$guid}}"), resolver.Resolve("{{$guid}}")); } + [Fact] + public void A_variable_takes_the_place_of_a_dynamic_one_of_its_name() + { + // As in Postman (its dynamic variables are looked up last) and in scripts' replaceIn: a script that signs + // {{$timestamp}} after setting it signs what the request sends. + var resolver = new VariableResolver([new DictionaryScope("local", new Dictionary { ["$timestamp"] = "1700000000" })]); + + Assert.Equal("1700000000", resolver.Resolve("{{$timestamp}}")); + Assert.True(resolver.TryResolve("$timestamp", out _, out var scope)); + Assert.Equal("local", scope); + Assert.True(resolver.TryResolve("$guid", out _, out scope)); + Assert.Equal("dynamic", scope); + } + private sealed class FixedTimeProvider(DateTimeOffset now) : TimeProvider { public override DateTimeOffset GetUtcNow() => now; diff --git a/tests/TermRest.Core.Tests/WorkspaceAndCollectionTests.cs b/tests/TermRest.Core.Tests/WorkspaceAndCollectionTests.cs index e3457e3..e674188 100644 --- a/tests/TermRest.Core.Tests/WorkspaceAndCollectionTests.cs +++ b/tests/TermRest.Core.Tests/WorkspaceAndCollectionTests.cs @@ -1,4 +1,9 @@ +using System.Text; +using System.Text.Json.Nodes; using TermRest.Core.Certificates; +using TermRest.Core.Http; +using TermRest.Core.IO; +using TermRest.Core.Json; using TermRest.Core.Model; using TermRest.Core.Postman; using TermRest.Core.Tests.Infrastructure; @@ -35,6 +40,77 @@ public void Opens_collections_environments_and_persists_settings() Assert.Equal("certs/ca.pem", reopened.Settings.CaBundle); } + [Fact] + public void Environments_of_the_same_name_are_told_apart_by_their_file() + { + var directory = TestFiles.NewTempDirectory(); + File.WriteAllText(Path.Combine(directory, "Staging.postman_environment.json"), """{ "name": "Staging", "values": [ { "key": "baseUrl", "value": "https://old" } ] }"""); + var export = Path.Combine(TestFiles.NewTempDirectory(), "Staging.postman_environment.json"); + File.WriteAllText(export, """{ "name": "Staging", "values": [ { "key": "baseUrl", "value": "https://new" } ] }"""); + var workspace = ApiWorkspace.Open(directory); + + // A teammate's updated export, imported next to the old one: it keeps the name. + var updated = workspace.ImportEnvironment(export); + workspace.ActiveEnvironment = updated; + Assert.Same(updated, workspace.ActiveEnvironment); + workspace.SaveSettings(); + + // Opened again, it is loaded first ("Staging (2)" sorts before "Staging."), and the old one second. + var reopened = ApiWorkspace.Open(directory); + Assert.Equal(["Staging (2).postman_environment.json", "Staging.postman_environment.json"], reopened.Environments.Select(e => Path.GetFileName(e.FilePath!))); + Assert.Equal("https://new", reopened.ActiveEnvironment?.Values[0].Value); + reopened.ActiveEnvironment = reopened.Environments[1]; + reopened.SaveSettings(); + Assert.Equal("https://old", ApiWorkspace.Open(directory).ActiveEnvironment?.Values[0].Value); + + // The name decides when that file is gone (renamed outside TermRest), and in settings of earlier versions. + File.Move(Path.Combine(directory, "Staging.postman_environment.json"), Path.Combine(directory, "Staging-old.postman_environment.json")); + Assert.Equal("https://new", ApiWorkspace.Open(directory).ActiveEnvironment?.Values[0].Value); + File.WriteAllText(workspace.SettingsPath, """{ "activeEnvironment": "staging" }"""); + Assert.Equal("https://new", ApiWorkspace.Open(directory).ActiveEnvironment?.Values[0].Value); + } + + [Fact] + public void Environments_of_the_same_name_are_shown_with_their_file() + { + var directory = TestFiles.NewTempDirectory(); + File.WriteAllText(Path.Combine(directory, "Staging.postman_environment.json"), """{ "name": "Staging", "values": [] }"""); + File.WriteAllText(Path.Combine(directory, "Staging (2).postman_environment.json"), """{ "name": "staging", "values": [] }"""); + File.WriteAllText(Path.Combine(directory, "Prod.postman_environment.json"), """{ "name": "Prod", "values": [] }"""); + + // Where their files have the same name too, with the file's path in the workspace. + var folder = Directory.CreateDirectory(Path.Combine(directory, "postman", "environments")).FullName; + File.WriteAllText(Path.Combine(folder, "Staging.postman_environment.json"), """{ "name": "Staging", "values": [] }"""); + + var workspace = ApiWorkspace.Open(directory); + + Assert.Equal(["Prod", "staging (Staging (2).postman_environment.json)", "Staging (Staging.postman_environment.json)", + "Staging (postman/environments/Staging.postman_environment.json)"], + workspace.Environments.Select(workspace.DisplayName)); + } + + [Fact] + public void The_active_environment_s_name_and_file_are_saved_together() + { + // As "termrest convert dev.postman_environment.json" leaves them: both named "dev". + var directory = TestFiles.NewTempDirectory(); + File.WriteAllText(Path.Combine(directory, "dev.postman_environment.json"), """{ "name": "dev", "values": [] }"""); + var yamlPath = Path.Combine(Directory.CreateDirectory(Path.Combine(directory, "postman", "environments")).FullName, "dev.environment.yaml"); + File.WriteAllText(yamlPath, "name: dev\nvalues: []\n"); + var workspace = ApiWorkspace.Open(directory); + workspace.ActiveEnvironment = workspace.Environments.Single(e => !e.IsYaml); + workspace.SaveSettings(); + + // A git pull changes the settings meanwhile; then the other "dev" is picked. + File.WriteAllText(workspace.SettingsPath, """{ "activeEnvironment": "prod", "activeEnvironmentFile": "prod.postman_environment.json" }"""); + workspace.ActiveEnvironment = workspace.Environments.Single(e => e.IsYaml); + workspace.SaveSettings(); + + var saved = JsonNode.Parse(File.ReadAllText(workspace.SettingsPath))!; + Assert.Equal(("dev", "postman/environments/dev.environment.yaml"), ((string?)saved["activeEnvironment"], (string?)saved["activeEnvironmentFile"])); + Assert.Equal(yamlPath, ApiWorkspace.Open(directory).ActiveEnvironment?.FilePath); + } + [Fact] public void User_settings_are_kept_in_the_user_s_configuration_folder() { @@ -61,6 +137,203 @@ public void User_settings_are_kept_in_the_user_s_configuration_folder() } } + [Fact] + public void A_proxy_in_the_workspace_settings_is_used_once_allowed_for_its_folder_and_again_after_each_change() + { + // A cloned repository's settings: a proxy that would see every request, and the CA it would read them with. + var root = TestFiles.NewTempDirectory(); + var config = TestFiles.NewTempDirectory(); + const string proxy = "http://ada:Pr0xy-s3cret@collect.example:8080"; + var settings = Path.Combine(Directory.CreateDirectory(Path.Combine(root, ".termrest")).FullName, "settings.json"); + File.WriteAllText(settings, $$"""{ "proxy": "{{proxy}}", "caBundle": "certs/ca.pem" }"""); + ExecutionDefaults Defaults(string workspace, out string? blocked) + { + using var runner = new RequestRunner(ApiWorkspace.Open(workspace)); + runner.ConfigureProxy(config); + blocked = runner.BlockedProxy; + return runner.CreateDefaults(); + } + + var defaults = Defaults(root, out var blocked); + Assert.Equal(proxy, blocked); + Assert.Null(defaults.Proxy); // the system's proxy settings + Assert.Equal(Path.Combine(root, "certs", "ca.pem"), defaults.CaBundlePath); // the other settings apply + + var user = UserSettings.Load(config); + Assert.True(user.AllowProxy(root, proxy)); + Assert.False(user.AllowProxy(root + Path.DirectorySeparatorChar, proxy)); // nothing to save + user.Save(config); + var saved = File.ReadAllText(Path.Combine(config, "settings.json")); + Assert.Contains("\"allowedProxies\": {", saved, StringComparison.Ordinal); + Assert.DoesNotContain("Pr0xy-s3cret", saved, StringComparison.Ordinal); + Assert.DoesNotContain("collect.example", saved, StringComparison.Ordinal); + Assert.Equal(proxy, Defaults(root, out blocked).Proxy); + Assert.Null(blocked); + + // The same proxy in another folder, and a changed one (a git pull), must be allowed again. + var clone = TestFiles.NewTempDirectory(); + Directory.CreateDirectory(Path.Combine(clone, ".termrest")); + File.Copy(settings, Path.Combine(clone, ".termrest", "settings.json")); + Assert.Null(Defaults(clone, out blocked).Proxy); + Assert.Equal(proxy, blocked); + File.WriteAllText(settings, """{ "proxy": "http://collect.example:3128" }"""); + Assert.Null(Defaults(root, out blocked).Proxy); + Assert.Equal("http://collect.example:3128", blocked); + + // The system's proxy settings, or none, need no approval. + File.WriteAllText(settings, """{ "proxy": "none" }"""); + Assert.Equal("none", Defaults(root, out blocked).Proxy); + Assert.Null(blocked); + Assert.True(user.AllowProxy(root, null)); + Assert.Null(user.AllowedProxies); + } + + [Fact] + public void Requests_send_only_the_files_of_their_workspace_until_others_are_allowed_for_it() + { + // A collection from a repository someone else wrote could send any file of the user's to a server of its choosing. + var root = TestFiles.NewTempDirectory(); + var config = TestFiles.NewTempDirectory(); + File.WriteAllText(Path.Combine(root, "order.json"), "{}"); + var secret = Path.Combine(TestFiles.NewTempDirectory(), "credentials"); + File.WriteAllText(secret, "s3cret"); + var workspace = ApiWorkspace.Open(root); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + runner.ConfigureFiles(config); + List Errors(BodyMode mode, params string[] files) => runner.Prepare(collection, null, new HttpRequestSpec + { + Method = "POST", + Url = "https://api.example/upload", + Body = new RequestBody + { + Mode = mode, + FileSrc = files[0], + FormData = [.. files.Select(f => new KeyValueEntry { Key = "file", Type = "file", Src = f })], + }, + }).Errors; + + Assert.Empty(Errors(BodyMode.FormData, "order.json", Path.Combine(root, "order.json"))); + var escaping = Path.Combine("..", Path.GetFileName(Path.GetDirectoryName(secret))!, "credentials"); // from the collection's folder + foreach (var outside in (string[])[secret, escaping]) + { + Assert.Equal($"Form-data file '{secret}' is outside the workspace folder, so it is not sent (a collection could otherwise send any of " + + "your files): allow files from outside it for this workspace in the full-screen UI (Tools › Settings…), or with --allow-outside-files.", + Assert.Single(Errors(BodyMode.FormData, outside))); + } + + Assert.StartsWith($"Body file '{secret}' is outside the workspace folder, so it is not sent", Assert.Single(Errors(BodyMode.File, escaping)), StringComparison.Ordinal); + + // Nor through a link in the workspace (a repository can hold one), where links can be made. + var link = Path.Combine(root, "avatar.png"); + try + { + File.CreateSymbolicLink(link, secret); + Assert.StartsWith($"Form-data file '{link}' leads outside the workspace folder through a link, so it is not sent", + Assert.Single(Errors(BodyMode.FormData, "avatar.png")), StringComparison.Ordinal); + } + catch (Exception e) when (e is UnauthorizedAccessException or IOException) + { + // Windows needs Developer Mode or elevation for symbolic links + } + + // Allowed for this workspace folder in the user's settings (Tools › Settings…): any file is sent, there only. + var user = UserSettings.Load(config); + Assert.True(user.AllowOutsideFiles(root, true)); + Assert.False(user.AllowOutsideFiles(root + Path.DirectorySeparatorChar, true)); // nothing to save + user.Save(config); + runner.ConfigureFiles(config); + Assert.Empty(Errors(BodyMode.FormData, secret, escaping)); + using var other = new RequestRunner(ApiWorkspace.Open(TestFiles.NewTempDirectory())); + other.ConfigureFiles(config); + Assert.False(other.OutsideFilesAllowed); + Assert.True(user.AllowOutsideFiles(root, false)); + Assert.Null(user.OutsideFilesAllowed); + } + + [Fact] + public void A_link_that_climbs_out_of_the_workspace_through_another_link_is_not_sent() + { + // The OS takes a .. after a link from where the link leads, not from the path as written: repo/d/../id_rsa, written in + // full in a link, looks like the repository's own decoy, but is the file next to where d leads. + var top = TestFiles.NewTempDirectory(); + var root = Directory.CreateDirectory(Path.Combine(top, "repo")).FullName; + Directory.CreateDirectory(Path.Combine(top, "keys")); + Directory.CreateDirectory(Path.Combine(root, "sub")); + File.WriteAllText(Path.Combine(top, "id_rsa"), "the user's key"); + File.WriteAllText(Path.Combine(root, "id_rsa"), "a decoy"); + File.WriteAllText(Path.Combine(root, "order.json"), "{}"); + try + { + Directory.CreateSymbolicLink(Path.Combine(root, "d"), Path.Combine("..", "keys")); + File.CreateSymbolicLink(Path.Combine(root, "logo.png"), Path.Combine(root, "d", "..", "id_rsa")); + File.CreateSymbolicLink(Path.Combine(root, "sub", "order.json"), Path.Combine("..", "order.json")); + } + catch (Exception e) when (e is UnauthorizedAccessException or IOException) + { + Assert.Skip($"Cannot create symbolic links here (Windows needs Developer Mode or elevation): {e.Message}"); + } + + var workspace = ApiWorkspace.Open(root); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + List Errors(string file) => runner.Prepare(collection, null, new HttpRequestSpec + { + Method = "PUT", + Url = "https://api.example/upload", + Body = new RequestBody { Mode = BodyMode.File, FileSrc = file }, + }).Errors; + + // Linux and macOS read the key there. Windows takes such a .. as text when the link is made: it leads to the decoy. + var leadsOut = File.ReadAllText(Path.Combine(root, "logo.png")) == "the user's key"; + Assert.True(leadsOut || OperatingSystem.IsWindows()); + if (leadsOut) + { + Assert.StartsWith($"Body file '{Path.Combine(root, "logo.png")}' leads outside the workspace folder through a link, so it is not sent", + Assert.Single(Errors("logo.png")), StringComparison.Ordinal); + } + else + { + Assert.Empty(Errors("logo.png")); + } + + Assert.Empty(Errors(Path.Combine("sub", "order.json"))); // a link out of a folder and back into the workspace + } + + [Fact] + public void Certificates_and_a_ca_bundle_on_network_shares_are_not_opened_until_files_from_outside_are_allowed() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), @"Network paths (\\server\share) are Windows'."); + + // A cloned repository's settings and certificate registry, and a request pinning a certificate. On Windows, looking at a + // file on a share signs in to its server with the user's credentials (nothing answers here: a look would wait). + const string share = @"\\termrest.invalid\share"; + var root = TestFiles.NewTempDirectory(); + Directory.CreateDirectory(Path.Combine(root, ".termrest")); + File.WriteAllText(Path.Combine(root, ".termrest", "settings.json"), new JsonObject { ["caBundle"] = share + @"\ca.pem" }.ToJsonString()); + var workspace = ApiWorkspace.Open(root); + workspace.Certificates.Entries.Add(new CertificateEntry { Name = "shared", Matches = [""], Pfx = new FileSource { Src = share + @"\client.pfx" } }); + var collection = workspace.CreateCollection("API"); + using var runner = new RequestRunner(workspace); + + var pinned = runner.Prepare(collection, null, new HttpRequestSpec + { + Url = "https://api.example/", + Certificate = new CertificateSpec { Name = "pinned", CertSrc = share + @"\client.pem", KeySrc = share + @"\client.key" }, + }); + var registered = runner.Prepare(collection, null, new HttpRequestSpec { Url = "https://api.example/" }); + + Assert.Contains($@"CA bundle '{share}\ca.pem' not loaded: {ClientCertificateProvider.OnNetworkShare}", pinned.Warnings); + Assert.Contains($@"Client certificate 'pinned' not used: '{share}\client.pem': {ClientCertificateProvider.OnNetworkShare}", pinned.Warnings); + Assert.Contains($@"Client certificate 'shared' not used: '{share}\client.pfx': {ClientCertificateProvider.OnNetworkShare}", registered.Warnings); + Assert.Null(registered.ClientCertificate); + + Assert.All((string[])[@"\\server\share\c.pem", "//server/share/c.pem", @"\\?\UNC\server\share\c.pem", @"\??\UNC\server\share\c.pem", @"\\.\pipe\x"], + path => Assert.True(RealPath.IsNetworkPath(path), path)); + Assert.All((string[])[@"C:\certs\c.pem", @"\\?\C:\certs\c.pem", @"\??\C:\c.pem", @"\\?\Volume{0a1b2c3d-0000-0000-0000-000000000000}\c.pem", @"certs\c.pem", @"\certs"], + path => Assert.False(RealPath.IsNetworkPath(path), path)); + } + [Fact] public void Runner_resolves_environment_over_collection_variables() { @@ -155,6 +428,26 @@ public void New_collection_and_environment_files_use_postman_format() Assert.Contains("\"type\": \"default\",\n\t\t\t\"enabled\": true", envText, StringComparison.Ordinal); } + [Fact] + public void New_collection_and_environment_files_get_names_valid_on_every_os() + { + // A workspace is shared through Git: Windows can't check out a name with | or ?, nor two names differing in case. + var root = TestFiles.NewTempDirectory(); + var workspace = ApiWorkspace.Open(root); + + var collection = workspace.CreateCollection("Orders | v2?"); + var environment = workspace.CreateEnvironment("CON"); + var sameButCase = workspace.CreateCollection("orders | V2?"); + var longName = workspace.CreateEnvironment(new string('x', 300)); // too long for a file name: the name inside keeps it + + Assert.Equal(Path.Combine(root, "Orders - v2-.postman_collection.json"), collection.FilePath); + Assert.Equal(Path.Combine(root, "CON-.postman_environment.json"), environment.FilePath); + Assert.Equal(Path.Combine(root, "orders - V2- (2).postman_collection.json"), sameButCase.FilePath); + Assert.Equal(Path.Combine(root, new string('x', 64) + ".postman_environment.json"), longName.FilePath); + Assert.Equal(["Orders | v2?", "orders | V2?"], ApiWorkspace.Open(root).Collections.Select(c => c.Name).Order(StringComparer.Ordinal)); + Assert.Contains(ApiWorkspace.Open(root).Environments, e => e.Name == new string('x', 300)); + } + [Fact] public void Certificate_registry_round_trips_newman_format() { @@ -180,6 +473,31 @@ public void Certificate_registry_round_trips_newman_format() Assert.Equal(CertificateSourceKind.Store, reopened.Certificates.Entries[1].Kind); } + [Fact] + public void Certificates_changed_on_disk_since_they_were_read_are_saved_over_only_when_told_to() + { + var directory = TestFiles.NewTempDirectory(); + var workspace = ApiWorkspace.Open(directory); // no registry yet + workspace.Certificates.Entries.Add(new CertificateEntry { Name = "mine", Matches = ["https://mine.example/*"] }); + var teammate = ApiWorkspace.Open(directory); // a git pull, or another TermRest + teammate.Certificates.Entries.Add(new CertificateEntry { Name = "theirs", Matches = ["https://theirs.example/*"] }); + teammate.SaveCertificates(); + var pulled = File.ReadAllText(workspace.CertificatesPath); + + Assert.Equal([workspace.CertificatesPath], Assert.Throws(workspace.SaveCertificates).Paths); + Assert.Equal(pulled, File.ReadAllText(workspace.CertificatesPath)); + + workspace.ReloadCertificates(); + workspace.Certificates.Entries[0].Disabled = true; + workspace.SaveCertificates(); + Assert.True(Assert.Single(ApiWorkspace.Open(directory).Certificates.Entries).Disabled); + + teammate.Certificates.Entries.Add(new CertificateEntry { Name = "more", Matches = ["https://more.example/*"] }); + Assert.Throws(teammate.SaveCertificates); + teammate.SaveCertificates(overwriteChanged: true); + Assert.Equal([("theirs", false), ("more", false)], ApiWorkspace.Open(directory).Certificates.Entries.Select(e => (e.Name, e.Disabled))); + } + [Fact] public void Importing_an_open_collection_reloads_it_but_never_drops_unsaved_changes() { @@ -207,6 +525,34 @@ public void Importing_an_open_collection_reloads_it_but_never_drops_unsaved_chan Assert.Same(again, workspace.FindCollection(Path.Combine(workspace.RootPath, ".", Path.GetFileName(again.FilePath!)))); } + [Fact] + public void Importing_a_collection_the_workspace_would_not_load_where_it_is_copies_it_in() + { + // A v2.1 export saved under another name (as "openapi2postmanv2 -o collection.json" writes it), in the workspace folder. + var directory = TestFiles.NewTempDirectory(); + var workspace = ApiWorkspace.Open(directory); + var export = Path.Combine(directory, "collection.json"); + File.Copy(TestFiles.DemoCollection, export); + + Assert.Equal(Path.Combine(directory, "TermRest Demo.postman_collection.json"), workspace.ImportCollection(export).FilePath); + + // Added by a git pull where the workspace keeps collections: loaded where it is. + var pulled = Path.Combine(directory, "Pulled.postman_collection.json"); + File.WriteAllText(pulled, """{ "info": { "name": "Pulled", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, "item": [] }"""); + Assert.Equal(pulled, workspace.ImportCollection(pulled).FilePath); + Assert.Equal(["Pulled", "TermRest Demo"], ApiWorkspace.Open(directory).Collections.Select(c => c.Name)); + + // In the v3 layout it is converted, as a JSON collection from elsewhere is. + var root = V3Fixture.Create(); + var v3 = ApiWorkspace.Open(root); + var rootExport = Path.Combine(root, "collection.json"); + File.Copy(TestFiles.DemoCollection, rootExport); + var converted = v3.ImportCollection(rootExport); + Assert.True(converted.IsV3); + Assert.Equal(Path.Combine(root, "postman", "collections", "TermRest Demo"), converted.FilePath); + Assert.NotNull(ApiWorkspace.Open(root).FindCollection(converted.FilePath!)); + } + [Fact] public void Importing_an_open_environment_refuses_to_drop_unsaved_changes() { @@ -223,4 +569,368 @@ public void Importing_an_open_environment_refuses_to_drop_unsaved_changes() Assert.Same(reloaded, Assert.Single(workspace.Environments)); Assert.Equal("changed", Assert.Single(reloaded.Values).Key); } + + [Fact] + public void A_collection_folder_is_found_with_a_trailing_separator() + { + var folder = V3Fixture.CollectionPath(V3Fixture.Create()); + var workspace = ApiWorkspace.Open(folder + Path.DirectorySeparatorChar); + + var collection = workspace.FindCollection(folder + Path.DirectorySeparatorChar); + Assert.NotNull(collection); + Assert.Same(collection, workspace.FindCollection(folder + Path.AltDirectorySeparatorChar)); + Assert.Same(collection, workspace.FindCollection(folder)); + } + + [Fact] + public void Settings_and_certificates_that_cannot_be_read_are_never_saved_over() + { + var directory = TestFiles.NewTempDirectory(); + var config = Directory.CreateDirectory(Path.Combine(directory, ApiWorkspace.ConfigDirectoryName)).FullName; + const string settings = "{ \"caBundle\": \"C:\\certs\\ca.pem\", \"proxy\": \"http://proxy:8080\" }"; // a Windows path typed in: invalid JSON + const string certificates = "<<<<<<< HEAD\n[]\n=======\n[]\n>>>>>>> theirs\n"; + File.WriteAllText(Path.Combine(config, "settings.json"), settings); + File.WriteAllText(Path.Combine(config, "certificates.json"), certificates); + + var workspace = ApiWorkspace.Open(directory); + + Assert.Equal([workspace.SettingsError, workspace.CertificatesError], workspace.LoadErrors); + Assert.StartsWith(workspace.SettingsPath, workspace.SettingsError, StringComparison.Ordinal); + Assert.StartsWith(workspace.CertificatesPath, workspace.CertificatesError, StringComparison.Ordinal); + workspace.Settings.Theme = "Nord"; + Assert.Contains(workspace.SettingsPath, Assert.Throws(workspace.SaveSettings).Message, StringComparison.Ordinal); + workspace.Certificates.Entries.Add(new CertificateEntry { Name = "new", Matches = ["https://h/*"] }); + Assert.Contains(workspace.CertificatesPath, Assert.Throws(workspace.SaveCertificates).Message, StringComparison.Ordinal); + Assert.Equal(settings, File.ReadAllText(workspace.SettingsPath)); + Assert.Equal(certificates, File.ReadAllText(workspace.CertificatesPath)); + + // A file deleted meanwhile (to start over) holds nothing to lose. + File.Delete(workspace.SettingsPath); + workspace.SaveSettings(); + Assert.Equal("Nord", ApiWorkspace.Open(directory).Settings.Theme); + } + + [Fact] + public void Files_with_a_duplicate_key_are_reported_instead_of_crashing() + { + // A merge conflict resolved by keeping both lines. + var directory = TestFiles.NewTempDirectory(); + File.WriteAllText(Path.Combine(directory, "Api.postman_collection.json"), """ + { "info": { "name": "Api", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, + "item": [ { "name": "Ping", "description": "ours", "description": "theirs", "request": { "method": "GET", "url": "https://h/ping" } } ] } + """); + File.WriteAllText(Path.Combine(directory, "dev.postman_environment.json"), """ + { "name": "dev", "values": [ { "key": "baseUrl", "value": "https://ours", "value": "https://theirs", "enabled": true } ] } + """); + + var workspace = ApiWorkspace.Open(directory); + + Assert.Empty(workspace.Collections); + Assert.Empty(workspace.Environments); + Assert.Equal(2, workspace.LoadErrors.Count(e => e.Contains("Duplicate property", StringComparison.Ordinal))); + } + + [Fact] + public void Files_with_half_of_a_surrogate_pair_are_reported_instead_of_crashing() + { + // JavaScript's JSON.stringify writes half of an emoji that was cut in two as an escape. + var directory = TestFiles.NewTempDirectory(); + File.WriteAllText(Path.Combine(directory, "Api.postman_collection.json"), """ + { "info": { "name": "Api", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, + // a comment may hold "\ud83d", and so may a string whose backslash is escaped: + "item": [ { "name": "Ping \\ud83d", "request": { "method": "GET", "url": "https://h/ping" } }, + { "name": "Pong \ud83d\ude00", "request": { "method": "GET", "url": "https://h/pong" } } ] } + """); + File.WriteAllText(Path.Combine(directory, "dev.postman_environment.json"), """ + { "name": "dev", + "values": [ { "key": "greeting", "value": "Hi \ud83d", "enabled": true } ] } + """); + File.WriteAllText(Path.Combine(directory, "workspace.postman_globals.json"), "{ \"name\": \"Globals\", \"values\": [ { \"key\": \"x\\uDE00\", \"value\": \"\" } ] }"); + + var workspace = ApiWorkspace.Open(directory); + + Assert.Equal(["Ping \\ud83d", "Pong 😀"], Assert.Single(workspace.Collections).AllRequests().Select(r => r.Name)); + Assert.Empty(workspace.Environments); + Assert.Null(workspace.Globals); + Assert.Equal(2, workspace.LoadErrors.Count); + Assert.StartsWith("dev.postman_environment.json: ", workspace.LoadErrors[0], StringComparison.Ordinal); + Assert.Contains("\"\\ud83d\" at line 2, column 49", workspace.LoadErrors[0], StringComparison.Ordinal); + Assert.Contains("\"\\uDE00\" at line 1, column 45", workspace.LoadErrors[1], StringComparison.Ordinal); + Assert.Null(PostmanJson.TryPrettyPrint("{ \"a\": \"\\ud83d\" }")); + } + + [Fact] + public void Importing_an_environment_writes_it_in_the_workspace_s_format() + { + var root = V3Fixture.Create(); + var workspace = ApiWorkspace.Open(root); + var outside = TestFiles.NewTempDirectory(); + + // Added by a git pull where the workspace keeps environments: loaded where it is. + var pulled = Path.Combine(root, "postman", "environments", "Staging.environment.yaml"); + File.WriteAllText(pulled, "name: Staging\nvalues:\n - key: token\n value: s3cret\n enabled: true\n"); + Assert.Equal(pulled, workspace.ImportEnvironment(pulled).FilePath); + + // From elsewhere: converted to YAML in the v3 layout. + var json = TestFiles.CopyToTemp(TestFiles.DemoEnvironment, outside); + var imported = workspace.ImportEnvironment(json); + Assert.Equal(Path.Combine(root, "postman", "environments", "Postman Echo.environment.yaml"), imported.FilePath); + Assert.Equal(PostmanEnvironment.Load(json).Values.Select(v => v.Key), PostmanEnvironment.Load(imported.FilePath!).Values.Select(v => v.Key)); + + // And to JSON in a JSON workspace. + var plain = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var converted = plain.ImportEnvironment(pulled); + Assert.Equal(Path.Combine(plain.RootPath, "Staging.postman_environment.json"), converted.FilePath); + Assert.Equal("s3cret", PostmanEnvironment.Load(converted.FilePath!).Values[0].Value); + + // A file that cannot be loaded leaves nothing behind, and the error does not show its values. + var broken = Path.Combine(outside, "Broken.postman_environment.json"); + File.WriteAllText(broken, "name: Broken\nvalues:\n - key: token\n value: s3cret\n"); + Assert.DoesNotContain("s3cret", Assert.Throws(() => plain.ImportEnvironment(broken)).Message, StringComparison.Ordinal); + Assert.Equal([converted.FilePath], Directory.GetFiles(plain.RootPath)); + Assert.Equal(["Local", "Staging", "Postman Echo"], workspace.Environments.Select(e => e.Name)); + Assert.DoesNotContain(ApiWorkspace.Open(root).LoadErrors, e => !e.Contains("non-HTTP", StringComparison.Ordinal)); + } + + [Fact] + public void Importing_a_globals_export_makes_it_the_workspace_s_globals() + { + var export = Path.Combine(TestFiles.NewTempDirectory(), "My Workspace.postman_globals.json"); + File.WriteAllText(export, """{ "name": "My Workspace Globals", "values": [ { "key": "tenant", "value": "acme", "enabled": true } ], "_postman_variable_scope": "globals" }"""); + + // A JSON workspace keeps its globals in workspace.postman_globals.json. + var plain = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + var globals = plain.ImportEnvironment(export); + Assert.Same(globals, plain.Globals); + Assert.Empty(plain.Environments); + Assert.Equal(Path.Combine(plain.RootPath, "workspace.postman_globals.json"), globals.FilePath); + Assert.Equal("acme", ApiWorkspace.Open(plain.RootPath).Globals?.Values.Single().Value); + + // The v3 layout in postman/globals/workspace.globals.yaml, where Postman keeps them. + var root = V3Fixture.Create(); + File.Delete(Path.Combine(root, "postman", "globals", "workspace.globals.yaml")); + ApiWorkspace.Open(root).ImportEnvironment(export); + var reopened = ApiWorkspace.Open(root); + Assert.Equal(Path.Combine(root, "postman", "globals", "workspace.globals.yaml"), reopened.Globals?.FilePath); + Assert.Equal("acme", reopened.Globals?.Values.Single().Value); + Assert.Equal(["Local"], reopened.Environments.Select(e => e.Name)); + } + + [Fact] + public void Importing_globals_is_refused_while_the_workspace_has_its_own() + { + var export = Path.Combine(TestFiles.NewTempDirectory(), "My Workspace.postman_globals.json"); + File.WriteAllText(export, """{ "name": "My Workspace Globals", "values": [], "_postman_variable_scope": "globals" }"""); + var root = V3Fixture.Create(); + var workspace = ApiWorkspace.Open(root); + var own = workspace.Globals!; + var before = V3Fixture.Snapshot(root); + + var error = Assert.Throws(() => workspace.ImportEnvironment(export)); + + Assert.Contains(Path.Combine("postman", "globals", "workspace.globals.yaml"), error.Message, StringComparison.Ordinal); + Assert.Same(own, workspace.Globals); + Assert.Equal(["Local"], workspace.Environments.Select(e => e.Name)); + Assert.Equal(before, V3Fixture.Snapshot(root)); + + // Also one that could not be read: it is not saved over, nor joined by another that Open might load in its place. + var directory = TestFiles.NewTempDirectory(); + File.WriteAllText(Path.Combine(directory, "team.postman_globals.json"), "<<<<<<< HEAD\n"); + var conflicted = ApiWorkspace.Open(directory); + Assert.Null(conflicted.Globals); + Assert.Contains("team.postman_globals.json", Assert.Throws(() => conflicted.ImportEnvironment(export)).Message, StringComparison.Ordinal); + Assert.Equal(["team.postman_globals.json"], Directory.GetFiles(directory).Select(Path.GetFileName)); + + // Its own file is reloaded, as an open environment file is, but never over unsaved changes. + own.SetValue("tenant", "acme"); + Assert.Contains("unsaved changes", Assert.Throws(() => workspace.ImportEnvironment(own.FilePath!)).Message, StringComparison.Ordinal); + Assert.Same(own, workspace.Globals); + own.Save(); + var reloaded = workspace.ImportEnvironment(own.FilePath!); + Assert.Same(reloaded, workspace.Globals); + Assert.Equal(("tenant", "acme"), (reloaded.Values.Single().Key, reloaded.Values.Single().Value)); + Assert.Equal(["Local"], workspace.Environments.Select(e => e.Name)); + } + + [Fact] + public void Saving_settings_writes_only_what_changed_and_keeps_the_rest_of_the_file() + { + var directory = TestFiles.NewTempDirectory(); + var path = Path.Combine(Directory.CreateDirectory(Path.Combine(directory, ApiWorkspace.ConfigDirectoryName)).FullName, "settings.json"); + File.WriteAllText(path, "{\n // shared with the team\n \"strictSsl\": false,\n \"proxy\": \"http://proxy:8080\",\n \"futureSetting\": [1, 2],\n}\n"); + var workspace = ApiWorkspace.Open(directory); + + // Nothing changed: nothing written. + var written = File.GetLastWriteTimeUtc(path); + var text = File.ReadAllText(path); + workspace.SaveSettings(); + Assert.Equal((text, written), (File.ReadAllText(path), File.GetLastWriteTimeUtc(path))); + + // A git pull changes the file meanwhile; this session changes other settings. + File.WriteAllText(path, "{ \"strictSsl\": true, \"proxy\": \"http://proxy:8080\", \"futureSetting\": [1, 2], \"recordingRedact\": [\"X-Tenant-Key\"] }"); + workspace.Settings.Theme = "Nord"; + workspace.Settings.Proxy = null; + workspace.SaveSettings(); + + var saved = JsonNode.Parse(File.ReadAllText(path))!.AsObject(); + Assert.Equal(["strictSsl", "futureSetting", "recordingRedact", "theme"], saved.Select(p => p.Key)); + Assert.Equal("""{"strictSsl":true,"futureSetting":[1,2],"recordingRedact":["X-Tenant-Key"],"theme":"Nord"}""", saved.ToJsonString()); + Assert.False(workspace.Settings.StrictSsl, "the settings in use are not reloaded"); + + // A file that cannot be read now (a merge conflict) is not saved over. + const string conflicted = "<<<<<<< HEAD\n{ \"theme\": \"Nord\" }\n=======\n{ \"theme\": \"Dracula\" }\n>>>>>>> theirs\n"; + File.WriteAllText(path, conflicted); + workspace.Settings.TimeoutMs = 5000; + Assert.Contains(path, Assert.Throws(workspace.SaveSettings).Message, StringComparison.Ordinal); + Assert.Equal(conflicted, File.ReadAllText(path)); + } + + [Fact] + public void Json_files_changed_on_disk_since_they_were_read_are_not_saved_over() + { + var workspace = OpenSampleCopy(); + var collection = workspace.Collections[0]; + var environment = workspace.Environments[0]; + + // A git pull changes both files; TermRest's edits meanwhile must not undo that silently. + var pulledCollection = File.ReadAllText(collection.FilePath!).Replace("\"name\": \"TermRest Demo\"", "\"name\": \"TermRest Demo v2\"", StringComparison.Ordinal); + File.WriteAllText(collection.FilePath!, pulledCollection); + var pulledEnvironment = File.ReadAllText(environment.FilePath!).Replace("env-token-123", "env-token-456", StringComparison.Ordinal); // as long + File.WriteAllText(environment.FilePath!, pulledEnvironment); + File.SetLastWriteTimeUtc(environment.FilePath!, DateTime.UtcNow.AddMinutes(1)); + var node = collection.FindRequest("Basics/GET with query")!; + var spec = node.ReadSpec(); + spec.Method = "HEAD"; + collection.UpdateRequest(node, spec); + environment.SetValue("baseUrl", "http://localhost:5000"); + + Assert.Equal([Path.GetFullPath(collection.FilePath!)], Assert.Throws(() => collection.Save()).Paths); + Assert.Equal([Path.GetFullPath(environment.FilePath!)], Assert.Throws(() => environment.Save()).Paths); + Assert.Equal(pulledCollection, File.ReadAllText(collection.FilePath!)); + Assert.Equal(pulledEnvironment, File.ReadAllText(environment.FilePath!)); + Assert.True(collection.IsDirty && environment.IsDirty); + + collection.Save(overwriteChanged: true); + environment.Save(overwriteChanged: true); + Assert.False(collection.IsDirty || environment.IsDirty); + var reloaded = PostmanCollection.Load(collection.FilePath!); + Assert.Equal(("TermRest Demo", "HEAD"), (reloaded.Name, reloaded.FindRequest("Basics/GET with query")!.ReadSpec().Method)); + Assert.Equal("http://localhost:5000", PostmanEnvironment.Load(environment.FilePath!).Values[0].Value); + + // Only touched: not a change. + File.SetLastWriteTimeUtc(collection.FilePath!, DateTime.UtcNow.AddMinutes(2)); + collection.MarkDirty(); + collection.Save(); + } + + [Fact] + public void A_file_replaced_by_one_of_the_same_length_and_time_is_not_saved_over() + { + // A copy that keeps its time (cp -p, rsync -t, an archive) changes neither the length nor the time of the file. + var environment = OpenSampleCopy().Environments[0]; + var path = environment.FilePath!; + var time = File.GetLastWriteTimeUtc(path); + var original = File.ReadAllBytes(path); + var replaced = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(original).Replace("env-token-123", "env-token-456", StringComparison.Ordinal)); + Assert.Equal(original.Length, replaced.Length); + File.WriteAllBytes(path, replaced); + File.SetLastWriteTimeUtc(path, time); + environment.SetValue("baseUrl", "http://localhost:5000"); + + Assert.Equal([Path.GetFullPath(path)], Assert.Throws(() => environment.Save()).Paths); + Assert.Equal(replaced, File.ReadAllBytes(path)); + } + + [Fact] + public void An_environment_saved_under_a_name_that_differs_only_in_case_is_as_private_as_its_source() + { + if (OperatingSystem.IsWindows()) + { + Assert.Skip("Unix file modes only."); + return; + } + + const UnixFileMode Private = UnixFileMode.UserRead | UnixFileMode.UserWrite; + var directory = TestFiles.NewTempDirectory(); + var source = Path.Combine(directory, "dev.postman_environment.json"); + File.WriteAllText(source, """{ "name": "dev", "values": [ { "key": "token", "value": "a-secret-token", "enabled": true } ] }"""); + File.SetUnixFileMode(source, Private); + + // On Linux that is another file; on macOS, as on Windows, the same one. + var copy = Path.Combine(directory, "DEV.postman_environment.json"); + PostmanEnvironment.Load(source).Save(copy); + + Assert.Equal(Private, File.GetUnixFileMode(copy)); + } + + [Fact] + public void User_settings_that_cannot_be_read_are_reported_and_never_saved_over() + { + var directory = TestFiles.NewTempDirectory(); + var path = Path.Combine(directory, "settings.json"); + const string text = "{ \"pythonInterpreters\": { \"C:\\work\": \"C:\\Python312\\python.exe\" } }"; + File.WriteAllText(path, text); + + var settings = UserSettings.Load(directory); + settings.Theme = "Nord"; + + Assert.StartsWith(path + ": ", settings.LoadError, StringComparison.Ordinal); + Assert.Contains(path, Assert.Throws(() => settings.Save(directory)).Message, StringComparison.Ordinal); + Assert.Equal(text, File.ReadAllText(path)); + Assert.Null(UserSettings.Load(TestFiles.NewTempDirectory()).LoadError); + } + + [Fact] + public void Commands_can_open_a_workspace_without_its_other_collections() + { + var directory = TestFiles.NewTempDirectory(); + var collection = TestFiles.CopyToTemp(TestFiles.DemoCollection, directory); + TestFiles.CopyToTemp(TestFiles.DemoEnvironment, directory); + File.WriteAllText(Path.Combine(directory, "Broken.postman_collection.json"), "<<<<<<< HEAD"); + + var all = ApiWorkspace.Open(collection); + Assert.Single(all.Collections); + Assert.Single(all.LoadErrors); + + var requested = ApiWorkspace.Open(collection, CollectionLoading.Requested); + Assert.Equal("TermRest Demo", Assert.Single(requested.Collections).Name); + Assert.Empty(requested.LoadErrors); + Assert.Equal("Postman Echo", Assert.Single(requested.Environments).Name); + Assert.Single(ApiWorkspace.Open(directory, CollectionLoading.Requested).LoadErrors); // a workspace folder: every collection + + var none = ApiWorkspace.Open(collection, CollectionLoading.None); + Assert.Equal((directory, 0, 0, 1), (none.RootPath, none.Collections.Count, none.LoadErrors.Count, none.Environments.Count)); + } + + [Fact] + public void A_file_in_the_postman_folders_opens_the_workspace_that_holds_them() + { + // A JSON collection kept in postman/collections belongs to the workspace there, as a v3 collection does. + var root = TestFiles.NewTempDirectory(); + var config = Directory.CreateDirectory(Path.Combine(root, ApiWorkspace.ConfigDirectoryName)).FullName; + File.WriteAllText(Path.Combine(config, "settings.json"), """{ "activeEnvironment": "staging", "proxy": "http://proxy:8080" }"""); + var collection = TestFiles.CopyToTemp(TestFiles.DemoCollection, Directory.CreateDirectory(Path.Combine(root, "postman", "collections")).FullName); + var environment = Path.Combine(Directory.CreateDirectory(Path.Combine(root, "postman", "environments")).FullName, "staging.environment.yaml"); + File.WriteAllText(environment, "name: staging\nvalues: []\n"); + var globals = Path.Combine(Directory.CreateDirectory(Path.Combine(root, "postman", "globals")).FullName, "workspace.postman_globals.json"); + File.WriteAllText(globals, """{ "name": "Globals", "values": [], "_postman_variable_scope": "globals" }"""); + + var workspace = ApiWorkspace.Open(collection, CollectionLoading.Requested); + + Assert.Equal((root, "http://proxy:8080", environment), (workspace.RootPath, workspace.Settings.Proxy, workspace.ActiveEnvironment?.FilePath)); + Assert.Same(Assert.Single(workspace.Collections), workspace.FindCollection(collection)); + Assert.Empty(workspace.LoadErrors); + + // So do environment and globals files there (a globals file is no collection). + foreach (var file in new[] { environment, globals }) + { + var opened = ApiWorkspace.Open(file, CollectionLoading.Requested); + Assert.Equal((root, globals, 0), (opened.RootPath, opened.Globals?.FilePath, opened.LoadErrors.Count)); + } + + // A collection anywhere else opens the folder it is in, as before. + Assert.Equal(root, ApiWorkspace.Open(TestFiles.CopyToTemp(TestFiles.DemoCollection, root)).RootPath); + var exports = Directory.CreateDirectory(Path.Combine(root, "postman", "exports")).FullName; + Assert.Equal(exports, ApiWorkspace.Open(TestFiles.CopyToTemp(TestFiles.DemoCollection, exports)).RootPath); + } } diff --git a/tests/TermRest.Core.Tests/YamlTests.cs b/tests/TermRest.Core.Tests/YamlTests.cs index 60c3b6b..8220799 100644 --- a/tests/TermRest.Core.Tests/YamlTests.cs +++ b/tests/TermRest.Core.Tests/YamlTests.cs @@ -126,6 +126,60 @@ public void Adding_and_removing_entries_keeps_the_rest() Assert.True(JsonNode.DeepEquals(changed, YamlFile.Parse(text).Json)); } + [Fact] + public void Comments_inside_an_edited_block_stay_with_their_entries() + { + const string source = """ + headers: + # used by the gateway + X-Api-Key: abc + + # content negotiation + Accept: application/json + queryParams: + # paging + - key: limit + value: '50' + # from the previous page + - key: cursor + value: x + order: 1000 + + """; + var file = YamlFile.Parse(source.ReplaceLineEndings("\n")); + var changed = (JsonObject)file.Json.DeepClone(); + changed["headers"]!["Accept"] = "application/xml"; + changed["queryParams"]![1]!["value"] = "y"; + + Assert.Equal( + source.ReplaceLineEndings("\n").Replace("Accept: application/json", "Accept: application/xml", StringComparison.Ordinal).Replace("value: x", "value: y", StringComparison.Ordinal), + file.Render(changed, YamlStyle.Default)); + + // Removed entries and items take their comments along; the others keep theirs. + ((JsonObject)changed["headers"]!).Remove("X-Api-Key"); + ((JsonArray)changed["queryParams"]!).RemoveAt(0); + Assert.Equal( + "headers:\n\n # content negotiation\n Accept: application/xml\nqueryParams:\n # from the previous page\n - key: cursor\n value: y\norder: 1000\n", + file.Render(changed, YamlStyle.Default)); + + // A blank line after a value that becomes a block scalar would become part of its text: it is dropped. + var blocks = YamlFile.Parse("headers:\n A: x\n\n B: y\nnote: x\n\nlast: z\n"); + var edited = (JsonObject)blocks.Json.DeepClone(); + edited["headers"]!["A"] = "two\nlines\n\n"; + edited["note"] = "two\nlines\n\n"; + var text = blocks.Render(edited, YamlStyle.Default); + Assert.True(JsonNode.DeepEquals(edited, YamlFile.Parse(text).Json), text); + + // Comments after a block scalar stay, moved left of its text when needed; so do blank lines it does not keep. + var commented = YamlFile.Parse("body: x\n\n# next part\nnote: x\n\n # deep\nlast: z\n"); + var rewritten = (JsonObject)commented.Json.DeepClone(); + rewritten["body"] = "two\nlines\n"; + rewritten["note"] = "two\nlines\n\n"; + var rendered = commented.Render(rewritten, YamlStyle.Default); + Assert.Equal("body: |\n two\n lines\n\n# next part\nnote: |+\n two\n lines\n\n# deep\nlast: z\n", rendered); + Assert.True(JsonNode.DeepEquals(rewritten, YamlFile.Parse(rendered).Json), rendered); + } + [Theory] [InlineData("plain text")] [InlineData("")] @@ -152,6 +206,8 @@ public void Adding_and_removing_entries_keeps_the_rest() [InlineData("line1\n\n\n")] [InlineData("\nstarts with a break")] [InlineData(" indented first line\nsecond")] + [InlineData(" \n{\n \"name\": \"x\"\n}")] + [InlineData(" \nfirst line of only spaces")] [InlineData("ends with spaces\n ")] [InlineData("tab\there")] [InlineData("crlf\r\nline")] @@ -163,6 +219,8 @@ public void Adding_and_removing_entries_keeps_the_rest() [InlineData("@at")] [InlineData("`tick")] [InlineData("12:30")] + [InlineData("Accept *")] + [InlineData("a *b")] public void Written_strings_read_back_unchanged(string value) { foreach (var style in (YamlStyle[])[YamlStyle.Default, new YamlStyle(PreferSingleQuotes: true)]) @@ -171,6 +229,7 @@ public void Written_strings_read_back_unchanged(string value) { ["value"] = value, ["list"] = new JsonArray(value, new JsonObject { ["nested"] = value }), + ["map"] = new JsonObject { [value] = "as a key" }, }; var text = YamlFile.Write(root, style); @@ -249,6 +308,41 @@ public void Invalid_or_unsupported_yaml_is_reported(string yaml) Assert.ThrowsAny(() => YamlFile.Parse(yaml)); } + [Fact] + public void A_value_starting_with_an_empty_line_reads_as_postman_writes_it() + { + // Postman's YAML library writes the first, empty line of such a block with the block's indentation. + const string Text = "scripts:\n - type: afterResponse\n code: |\n \n pm.test('ok', () => {});\n" + + "variables:\n product: |-\n \n\n Insurance\n newline: |+\n \n after: x\n"; + var file = YamlFile.Parse(Text); + + Assert.Equal("\npm.test('ok', () => {});\n", file.Json["scripts"]![0]!["code"]!.GetValue()); + Assert.Equal(("\n\nInsurance", "\n", "x"), + (file.Json["variables"]!["product"]!.GetValue(), file.Json["variables"]!["newline"]!.GetValue(), file.Json["variables"]!["after"]!.GetValue())); + + // An edit elsewhere keeps those lines as they are. + var edited = (JsonObject)file.Json.DeepClone(); + edited["variables"]!["after"] = "y"; + Assert.Equal(Text[..^"x\n".Length] + "y\n", file.Render(edited, YamlStyle.Detect([file.Tree]))); + } + + [Fact] + public void Deeply_nested_yaml_is_reported_instead_of_overflowing_the_stack() + { + Assert.ThrowsAny(() => YamlFile.Parse("url: " + new string('[', 100_000))); + Assert.ThrowsAny(() => YamlFile.Parse(string.Concat(Enumerable.Range(0, 300).Select(i => new string(' ', i) + "a:\n")))); + + var node = YamlFile.Parse("a: " + new string('[', 200) + new string(']', 200)).Json["a"]; + var depth = 0; + while (node is JsonArray array) + { + depth++; + node = array.Count > 0 ? array[0] : null; + } + + Assert.Equal(200, depth); + } + [Fact] public void Json_equality_ignores_key_order_and_number_spelling() { @@ -257,6 +351,16 @@ public void Json_equality_ignores_key_order_and_number_spelling() Assert.True(JsonNode.DeepEquals(YamlFile.Parse("a: 1000").Json, new JsonObject { ["a"] = 1000 })); } + [Fact] + public void Integers_too_big_for_a_long_keep_their_digits() + { + var huge = "1" + new string('0', 309); // beyond even a double + var json = YamlFile.Parse($"a: {huge}\nb: -{huge}\nc: 12345678901234567890\n").Json; + + Assert.Equal([huge, "-" + huge, "12345678901234567890"], json.Select(p => p.Value!.ToJsonString())); + Assert.Equal($"a: {huge}\n", YamlFile.Write(new JsonObject { ["a"] = json["a"]!.DeepClone() }, YamlStyle.Default)); + } + // ----- wrapping long values ------------------------------------------------------------------------ private const string LongHeaderName = "X-An-Extremely-Long-Header-Name-That-Keeps-Going-And-Going-Forever"; @@ -471,6 +575,12 @@ public static TheoryData LongStrings() => string.Concat(Enumerable.Repeat("\\x", 120)), "escapes right after a space \u0001\u0002 " + string.Join(" \u0003", Enumerable.Repeat("ab", 40)), string.Join(' ', Enumerable.Repeat("\u0007\u0008\u001b", 40)), + + // A line of a single space (a leading and a trailing space at once), and a line of only white space after a + // more-indented one: Postman's library writes both so that they read back changed. + "pm.test('status', () => {\n \n pm.response.to.have.status(200);\n});\n ", + "// " + string.Join(' ', Enumerable.Repeat("word", 25)) + "\nif (a) {\n x();\n \n}\n", + "// " + string.Join(' ', Enumerable.Repeat("word", 25)) + "\nif (a) {\n\tx();\n\n\t\n}\n", ]; [Theory] @@ -504,6 +614,46 @@ public void Wrapped_values_read_back_unchanged(string value) } } + [Fact] + public void Text_that_yaml_reads_as_a_number_of_any_size_is_quoted() + { + // Postman's library reads these as numbers (an Ethereum address as 1.2488751460129641e+48): they must stay text. + var root = new JsonObject + { + ["address"] = "0xdAC17F958D2ee523a2206206994597C13D831ec7", + ["octal"] = "0o" + new string('7', 30), + ["huge"] = "1e400", + ["plain"] = "0xyz", + }; + + var text = YamlFile.Write(root, YamlStyle.Default); + + Assert.DoesNotContain("address: 0x", text, StringComparison.Ordinal); + Assert.DoesNotContain("octal: 0o", text, StringComparison.Ordinal); + Assert.DoesNotContain("huge: 1e400", text, StringComparison.Ordinal); + Assert.Contains("plain: 0xyz", text, StringComparison.Ordinal); + Assert.True(JsonNode.DeepEquals(root, YamlFile.Parse(text).Json), text); + } + + [Fact] + public void Wrapping_never_splits_a_character_outside_the_bmp() + { + // A double-quoted value without spaces is broken with an escaped line break, never between the halves of an emoji: + // UTF-8 can't hold them apart (they would be written as U+FFFD). + for (var shift = 0; shift < 4; shift++) + { + var root = new JsonObject { ["url"] = "{{baseUrl}}/v1/widgets?name=" + new string('a', shift) + string.Concat(Enumerable.Repeat("😀b", 80)) }; + foreach (var width in (int[])[20, 40, 80]) + { + var text = YamlFile.Write(root, new YamlStyle(false).WithLineWidth(width)); + + Assert.Contains("\\\n", text, StringComparison.Ordinal); + Assert.Equal(text, System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(text))); + Assert.True(JsonNode.DeepEquals(root, YamlFile.Parse(text).Json), text); + } + } + } + [Fact] public void Line_width_is_detected_from_how_files_were_written() { diff --git a/tests/TermRest.Tui.Tests/BulkEditTests.cs b/tests/TermRest.Tui.Tests/BulkEditTests.cs new file mode 100644 index 0000000..f915432 --- /dev/null +++ b/tests/TermRest.Tui.Tests/BulkEditTests.cs @@ -0,0 +1,113 @@ +using TermRest.Core.Model; +using TermRest.Tui.Dialogs; +using Xunit; + +namespace TermRest.Tui.Tests; + +public sealed class BulkEditTests +{ + private static List Rows() => + [ + new() { Key = "cert", Value = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----", Type = "default" }, + new() { Key = "json", Value = "{\r\n \"note\": \"a\\nb\"\r\n}" }, + new() { Key = "path", Value = @"C:\new\temp" }, + new() { Key = "flag", Value = null }, + new() { Key = "files", Type = "file", Src = "a.png\nb.png" }, + new() { Key = "token", Value = "s3cr3t", Type = "secret", Enabled = false }, + ]; + + [Fact] + public void Applying_the_text_unchanged_keeps_every_row_as_it_was() + { + var rows = Rows(); + + var text = BulkEditDialog.Format(rows); + var parsed = BulkEditDialog.Parse(text, rows); + + Assert.Equal(rows.Count, text.Split('\n').Length); + Assert.DoesNotContain("s3cr3t", text, StringComparison.Ordinal); + Assert.True(KeyValueEntry.ListEquals(rows, parsed), string.Join('\n', parsed)); + } + + [Fact] + public void Edited_rows_keep_their_line_breaks_files_and_secrets() + { + var rows = Rows(); + var lines = BulkEditDialog.Format(rows).Split('\n'); + Assert.Equal("cert:-----BEGIN CERTIFICATE-----\\nMIIB\\n-----END CERTIFICATE-----", lines[0]); + Assert.Equal("files:a.png;b.png", lines[4]); + lines[0] = lines[0].Replace("MIIB", "MIIC", StringComparison.Ordinal); + lines[4] = "files:a.png; c.png"; + lines[5] = lines[5].Replace("token:", "Token2:", StringComparison.Ordinal); // renamed, value left masked + + var parsed = BulkEditDialog.Parse(string.Join('\n', lines), rows); + + Assert.Equal("-----BEGIN CERTIFICATE-----\nMIIC\n-----END CERTIFICATE-----", parsed[0].Value); + Assert.Equal("a.png\nc.png", parsed[4].Src); + Assert.Equal(("Token2", "s3cr3t", true, false), (parsed[5].Key, parsed[5].Value, parsed[5].IsSecret, parsed[5].Enabled)); + } + + [Fact] + public void Keys_holding_colons_keep_their_rows_unchanged_and_edited() + { + List rows = + [ + new() { Key = "Api", Value = "BaseUrl:https://old.example.com" }, // its line starts like the next row's + new() { Key = "Api:BaseUrl", Value = "https://api.example.com" }, + new() { Key = "Db:Password", Value = "hunter2", Type = "secret" }, + ]; + var lines = BulkEditDialog.Format(rows).Split('\n'); + + var unchanged = BulkEditDialog.Parse(string.Join('\n', lines), rows); + lines[1] = lines[1].Replace("api.example", "api2.example", StringComparison.Ordinal); + var edited = BulkEditDialog.Parse(string.Join('\n', lines), rows); + + Assert.True(KeyValueEntry.ListEquals(rows, unchanged), string.Join('\n', unchanged)); + Assert.Equal( + ["Api = BaseUrl:https://old.example.com", "Api:BaseUrl = https://api2.example.com", "Db:Password = hunter2 (secret)"], + edited.Select(e => $"{e.Key} = {e.Value}{(e.IsSecret ? " (secret)" : "")}")); + } + + [Fact] + public void A_renamed_row_is_the_row_in_its_place_and_a_mask_keeps_a_secret_only_when_it_is_clear_which() + { + var rows = Rows(); + var lines = BulkEditDialog.Format(rows).Split('\n'); + lines[0] = "client_" + lines[0]; // cert renamed, its value left as shown + + var renamed = BulkEditDialog.Parse(string.Join('\n', lines), rows); + + Assert.Equal(("client_cert", rows[0].Value), (renamed[0].Key, renamed[0].Value)); + + List secrets = [new() { Key = "api_key", Value = "K", Type = "secret" }, new() { Key = "password", Value = "P", Type = "secret" }]; + var mask = BulkEditDialog.SecretMask; + List unclear = [], clear = []; + + var removedAndRenamed = BulkEditDialog.Parse($"admin_password:{mask}", secrets, unclear); // which one is it? + var renamedAndKept = BulkEditDialog.Parse($"admin_password:{mask}\napi_key:{mask}", secrets, clear); + + Assert.Equal(["admin_password"], unclear); + Assert.Equal(mask, Assert.Single(removedAndRenamed).Value); + Assert.Empty(clear); + Assert.Equal(["P", "K"], renamedAndKept.Select(e => e.Value)); + } + + [Fact] + public void A_line_left_as_written_is_its_own_row_where_rows_share_a_key() + { + List parts = [new() { Key = "file", Type = "file", Src = "a.png" }, new() { Key = "file", Value = "x", Type = "text" }]; + List tags = [new() { Key = "tag", Value = "a", Description = "first" }, new() { Key = "tag", Value = "b", Description = "second" }]; + List variables = [new() { Key = "X", Value = "p" }, new() { Key = "X", Value = "s3cr3t", Type = "secret" }]; + var unclear = new List(); + + // The first line deleted, or the lines swapped. + var part = Assert.Single(BulkEditDialog.Parse(BulkEditDialog.Format(parts).Split('\n')[1], parts)); + var swapped = BulkEditDialog.Parse(string.Join('\n', BulkEditDialog.Format(tags).Split('\n').Reverse()), tags); + var secret = Assert.Single(BulkEditDialog.Parse(BulkEditDialog.Format(variables).Split('\n')[1], variables, unclear)); + + Assert.Equal(("x", null, false), (part.Value, part.Src, part.IsFile)); + Assert.Equal(["b second", "a first"], swapped.Select(e => $"{e.Value} {e.Description}")); + Assert.Equal(("s3cr3t", true), (secret.Value, secret.IsSecret)); + Assert.Empty(unclear); + } +} diff --git a/tests/TermRest.Tui.Tests/CollectionTreeTests.cs b/tests/TermRest.Tui.Tests/CollectionTreeTests.cs new file mode 100644 index 0000000..61bb5a3 --- /dev/null +++ b/tests/TermRest.Tui.Tests/CollectionTreeTests.cs @@ -0,0 +1,79 @@ +using Terminal.Gui.App; +using Terminal.Gui.Drivers; +using Terminal.Gui.ViewBase; +using Terminal.Gui.Views; +using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Workspace; +using TermRest.Tui.Views; +using Xunit; + +namespace TermRest.Tui.Tests; + +/// The sidebar tree of collections, folders and requests. +[Collection("TUI")] +public sealed class CollectionTreeTests +{ + [Fact] + public void Characters_outside_the_BMP_in_names_and_methods_show_as_replacement_characters() + { + var directory = TestFiles.NewTempDirectory(); + File.WriteAllText(Path.Combine(directory, "Emoji.postman_collection.json"), """ + { + "info": { "name": "Emoji 🚀", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, + "item": [ + { "name": "📁 Docs", "item": [] }, + { "name": "Deploy 🚀 now", "request": { "method": "GET", "url": "https://example.com" } }, + { "name": "Custom", "request": { "method": "abc😀e", "url": "https://example.com" } } + ] + } + """); + using var app = Application.Create(); + app.Init(DriverRegistry.Names.ANSI); + app.Driver!.SetScreenSize(60, 10); + using var window = new Window { Width = Dim.Fill(), Height = Dim.Fill() }; + window.Add(new CollectionTree(ApiWorkspace.Open(directory))); + var token = app.Begin(window); + + // Terminal.Gui's tree draws each UTF-16 unit in a cell of its own, and fails on half of a pair. + app.LayoutAndDraw(forceRedraw: true); + var screen = app.Driver.ToString(); + app.End(token!); + + Assert.Contains("Emoji \uFFFD", screen, StringComparison.Ordinal); + Assert.Contains("\uFFFD Docs", screen, StringComparison.Ordinal); + Assert.Contains("GET Deploy \uFFFD now", screen, StringComparison.Ordinal); + Assert.Contains("ABC\uFFFD Custom", screen, StringComparison.Ordinal); + } + + [Fact] + public void Collections_of_the_same_name_show_their_files() + { + // An imported update (copied in as "… (2)"), a copy in postman/collections and one converted into a v3 folder. + var directory = TestFiles.NewTempDirectory(); + const string Collection = """{ "info": { "name": "NAME", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, "item": [] }"""; + var collections = Path.Combine(directory, "postman", "collections"); + Directory.CreateDirectory(collections); + File.WriteAllText(Path.Combine(directory, "Orders API.postman_collection.json"), Collection.Replace("NAME", "Orders API", StringComparison.Ordinal)); + File.WriteAllText(Path.Combine(directory, "Orders API (2).postman_collection.json"), Collection.Replace("NAME", "Orders API", StringComparison.Ordinal)); + File.WriteAllText(Path.Combine(collections, "Orders API.postman_collection.json"), Collection.Replace("NAME", "Orders API", StringComparison.Ordinal)); + File.WriteAllText(Path.Combine(directory, "Billing.postman_collection.json"), Collection.Replace("NAME", "Billing", StringComparison.Ordinal)); + ApiWorkspace.Open(directory).CreateCollection("Orders API", v3: true); + using var app = Application.Create(); + app.Init(DriverRegistry.Names.ANSI); + app.Driver!.SetScreenSize(100, 10); + using var window = new Window { Width = Dim.Fill(), Height = Dim.Fill() }; + window.Add(new CollectionTree(ApiWorkspace.Open(directory))); + var token = app.Begin(window); + + app.LayoutAndDraw(forceRedraw: true); + var screen = app.Driver.ToString(); + app.End(token!); + + Assert.Contains("Orders API (Orders API.postman_collection.json)", screen, StringComparison.Ordinal); + Assert.Contains("Orders API (Orders API (2).postman_collection.json)", screen, StringComparison.Ordinal); + Assert.Contains("Orders API (postman/collections/Orders API.postman_collection.json)", screen, StringComparison.Ordinal); + Assert.Contains("Orders API (Orders API)", screen, StringComparison.Ordinal); + Assert.Contains("Billing", screen, StringComparison.Ordinal); + Assert.DoesNotContain("Billing (", screen, StringComparison.Ordinal); + } +} diff --git a/tests/TermRest.Tui.Tests/Infrastructure/LocalEchoServer.cs b/tests/TermRest.Tui.Tests/Infrastructure/LocalEchoServer.cs index dde27d8..2b06c65 100644 --- a/tests/TermRest.Tui.Tests/Infrastructure/LocalEchoServer.cs +++ b/tests/TermRest.Tui.Tests/Infrastructure/LocalEchoServer.cs @@ -15,11 +15,13 @@ namespace TermRest.Tui.Tests.Infrastructure; public sealed class LocalEchoServer : IAsyncDisposable { private readonly WebApplication _app; + private readonly TaskCompletionSource _held; - private LocalEchoServer(WebApplication app, string baseUrl) + private LocalEchoServer(WebApplication app, string baseUrl, TaskCompletionSource held) { _app = app; BaseUrl = baseUrl; + _held = held; } /// Base URL without a trailing slash, e.g. http://127.0.0.1:5123. @@ -31,27 +33,41 @@ public static async Task StartAsync() builder.Logging.ClearProviders(); builder.WebHost.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 0)); var app = builder.Build(); - app.Map("/echo/{**rest}", async (HttpContext ctx) => + var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + app.Map("/echo/{**rest}", Echo); + + // Like /echo, once Release is called: keeps a request on its way as long as a test needs. + app.Map("/hold/{**rest}", async (HttpContext ctx) => { - using var reader = new StreamReader(ctx.Request.Body, Encoding.UTF8); - var json = new JsonObject - { - ["method"] = ctx.Request.Method, - ["path"] = ctx.Request.Path.Value, - ["query"] = ctx.Request.QueryString.Value, - ["body"] = await reader.ReadToEndAsync(), - }; - ctx.Response.ContentType = "application/json"; - await ctx.Response.WriteAsync(json.ToJsonString()); + await held.Task; + await Echo(ctx); }); await app.StartAsync(); var address = app.Services.GetRequiredService().Features.Get()!.Addresses.First(); - return new LocalEchoServer(app, address.TrimEnd('/')); + return new LocalEchoServer(app, address.TrimEnd('/'), held); } + /// Answers the requests to /hold/… that wait, and every later one at once. + public void Release() => _held.TrySetResult(); + public async ValueTask DisposeAsync() { + Release(); await _app.StopAsync(); await _app.DisposeAsync(); } + + private static async Task Echo(HttpContext ctx) + { + using var reader = new StreamReader(ctx.Request.Body, Encoding.UTF8); + var json = new JsonObject + { + ["method"] = ctx.Request.Method, + ["path"] = ctx.Request.Path.Value, + ["query"] = ctx.Request.QueryString.Value, + ["body"] = await reader.ReadToEndAsync(), + }; + ctx.Response.ContentType = "application/json"; + await ctx.Response.WriteAsync(json.ToJsonString()); + } } diff --git a/tests/TermRest.Tui.Tests/KeyValueTableTests.cs b/tests/TermRest.Tui.Tests/KeyValueTableTests.cs new file mode 100644 index 0000000..28f22d0 --- /dev/null +++ b/tests/TermRest.Tui.Tests/KeyValueTableTests.cs @@ -0,0 +1,113 @@ +using System.Drawing; +using Terminal.Gui.App; +using Terminal.Gui.Drivers; +using Terminal.Gui.Input; +using Terminal.Gui.Testing; +using Terminal.Gui.ViewBase; +using Terminal.Gui.Views; +using TermRest.Core.Model; +using TermRest.Tui.Views; +using Xunit; + +namespace TermRest.Tui.Tests; + +/// The key/value grid's checkbox column, clicked with the mouse. +[Collection("TUI")] +public sealed class KeyValueTableTests : IDisposable +{ + private readonly IApplication _app; + private readonly Window _window = new() { Width = Dim.Fill(), Height = Dim.Fill() }; + private readonly KeyValueTable _table = new(KeyValueKind.QueryParams); + private readonly List _entries = + [ + new() { Key = "foo", Value = "bar" }, + new() { Key = "source", Value = "termrest" }, + new() { Key = "debug", Value = "1", Enabled = false }, + ]; + + private readonly List _dialogs = []; + private readonly SessionToken? _token; + private int _changes; + + public KeyValueTableTests() + { + _app = Application.Create(); + _app.Init(DriverRegistry.Names.ANSI); + _app.Driver!.SetScreenSize(80, 20); + _table.SetEntries(_entries); + _table.Changed += (_, _) => _changes++; + _window.Add(_table); + _token = _app.Begin(_window); + _table.SubViews.OfType().Single().SetFocus(); + _app.LayoutAndDraw(forceRedraw: true); + + // Runs only while a dialog is open: notes its title and closes it. + _app.AddTimeout(TimeSpan.FromMilliseconds(50), () => + { + if (_app.TopRunnableView is Dialog dialog) + { + _dialogs.Add(dialog.Title); + _app.RequestStop(); + } + + return true; + }); + } + + /// Where the checkbox of the row (or the header) that shows is. + private Point CheckBoxOf(string text) + { + _app.LayoutAndDraw(forceRedraw: true); + var lines = (_app.Driver!.ToString() ?? "").Split('\n'); + var y = Array.FindIndex(lines, line => line.Contains(text, StringComparison.Ordinal)); + Assert.True(y >= 0, $"'{text}' is not on screen"); + return new Point(lines[y].IndexOf(text, StringComparison.Ordinal) - 2, y); + } + + private KeyValueEntry? Selected => + _table.SubViews.OfType().Single().Value?.SelectedCell.Y is { } row && row < _table.Entries.Count ? _table.Entries[row] : null; + + [Fact] + public void Two_quick_clicks_on_a_checkbox_turn_it_on_and_off_again_and_edit_nothing() + { + _app.InjectSequence(InputInjectionExtensions.LeftButtonDoubleClick(CheckBoxOf("debug"))); + var (enabled, selected, changes) = (_entries[2].Enabled, Selected?.Key, _changes); + _app.InjectKey(Key.Delete); + + Assert.Empty(_dialogs); // no Edit query parameter + Assert.Equal((false, "debug", 2), (enabled, selected, changes)); + Assert.Equal(["foo", "source"], _table.Entries.Select(e => e.Key)); // Delete removed the clicked row + } + + [Fact] + public void A_click_on_a_checkbox_moves_the_cursor_to_its_row() + { + _app.InjectSequence(InputInjectionExtensions.LeftButtonClick(CheckBoxOf("debug"))); + var (enabled, selected) = (_entries[2].Enabled, Selected?.Key); + _app.InjectKey(Key.Delete); + + Assert.Equal((true, "debug"), (enabled, selected)); + Assert.Equal(["foo", "source"], _table.Entries.Select(e => e.Key)); + } + + [Fact] + public void Two_quick_clicks_on_the_header_s_checkbox_toggle_every_row_twice_and_edit_nothing() + { + _app.InjectSequence(InputInjectionExtensions.LeftButtonDoubleClick(CheckBoxOf("Key"))); + + Assert.Empty(_dialogs); + Assert.Equal([false, false, false], _entries.Select(e => e.Enabled)); // all on (debug was off), then all off + Assert.Equal(4, _changes); + } + + public void Dispose() + { + if (_token is not null) + { + _app.End(_token); + } + + _window.Dispose(); + _app.Dispose(); + } +} diff --git a/tests/TermRest.Tui.Tests/MainWindowTests.cs b/tests/TermRest.Tui.Tests/MainWindowTests.cs index 9111e20..ad2155e 100644 --- a/tests/TermRest.Tui.Tests/MainWindowTests.cs +++ b/tests/TermRest.Tui.Tests/MainWindowTests.cs @@ -189,6 +189,86 @@ public void Importing_the_open_collection_again_reloads_it_and_the_editor_stays_ Assert.EndsWith("&after=reload", saved.FindRequest("Basics/GET with query")!.ReadSpec().Url, StringComparison.Ordinal); } + [Fact] + public void Saving_over_a_collection_changed_on_disk_asks_first_and_the_other_files_are_saved_anyway() + { + var path = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + using var ui = new Harness(_directory); + var environment = ui.Workspace.Environments[0]; + + // A git pull changes the collection while it is open. + var pulled = File.ReadAllText(path).Replace("\"name\": \"TermRest Demo\"", "\"name\": \"TermRest Demo v2\"", StringComparison.Ordinal); + File.WriteAllText(path, pulled); + string? notice = null; + var onDiskAfterCancel = ""; + var environmentSaved = false; + + var screens = Drive(ui, () => + { + ui.Click("{{baseUrl}}/get?foo=bar&source=termrest"); + ui.App.InjectKey(Key.End); + ui.Type("&page=2"); + environment.SetValue("baseUrl", "http://localhost:5000"); + ui.App.InjectKey(Key.S.WithCtrl); // asks: Enter is Cancel + notice = ui.Window.StatusMessage; + onDiskAfterCancel = File.ReadAllText(path); + environmentSaved = !environment.IsDirty; + ui.App.InjectKey(Key.S.WithCtrl); // asks, and overwrites + ui.App.RequestStop(); + }, + ("Changed on disk", () => ui.App.InjectKey(Key.Enter)), + ("Changed on disk", () => ui.Click("Overwrite"))); + + Assert.Equal(2, screens.Count); + OnScreen("TermRest Demo.postman_collection.json", screens[0]); + Assert.Equal(pulled, onDiskAfterCancel); + Assert.Contains("Not saved: TermRest Demo.postman_collection.json changed on disk", notice, StringComparison.Ordinal); + Assert.True(environmentSaved); + Assert.Equal("http://localhost:5000", PostmanEnvironment.Load(environment.FilePath!).Values.Single(v => v.Key == "baseUrl").Value); + var saved = PostmanCollection.Load(path); + Assert.Equal(("TermRest Demo", "{{baseUrl}}/get?foo=bar&source=termrest&page=2"), (saved.Name, saved.FindRequest("Basics/GET with query")!.ReadSpec().Url)); + Assert.StartsWith("Saved TermRest Demo.postman_collection.json", ui.Window.StatusMessage, StringComparison.Ordinal); + } + + [Fact] + public void Saving_goes_on_after_a_file_fails_for_any_reason_and_logs_the_unexpected_failures() + { + var state = Path.Combine(_directory, "state"); + var previousState = Environment.GetEnvironmentVariable(TermRest.Core.History.HistoryStore.StateDirectoryVariable); + Environment.SetEnvironmentVariable(TermRest.Core.History.HistoryStore.StateDirectoryVariable, state); + try + { + using var ui = new Harness(_directory); + var written = new List(); + List saved = []; + + var screens = Drive(ui, () => + { + (saved, _) = Dialogs.Ui.SaveEach(ui.App, _directory, + [ + new("Broken.postman_collection.json", _ => throw new InvalidOperationException("A value could not be written.")), + new("Locked.postman_environment.json", _ => throw new UnauthorizedAccessException("Access to Locked is denied.")), + new("Dev.postman_environment.json", _ => written.Add("Dev")), + new(null, _ => written.Add("settings")), + ]); + ui.App.RequestStop(); + }, + ("Save failed", () => ui.Click("► OK ◄"))); + + OnScreen("Broken.postman_collection.json: A value could not be written.", Assert.Single(screens)); + OnScreen("Access to Locked is denied.", screens[0]); + Assert.Equal(["Dev", "settings"], written); + Assert.Equal(["Dev.postman_environment.json"], saved); + var log = File.ReadAllText(Path.Combine(state, "errors.log")); + Assert.Contains("System.InvalidOperationException: A value could not be written.", log, StringComparison.Ordinal); + Assert.DoesNotContain("Locked", log, StringComparison.Ordinal); // a disk or permission problem is no bug + } + finally + { + Environment.SetEnvironmentVariable(TermRest.Core.History.HistoryStore.StateDirectoryVariable, previousState); + } + } + [Fact] public async Task F5_sends_the_request_and_shows_the_response() { @@ -221,6 +301,31 @@ public async Task F5_sends_the_request_and_shows_the_response() Assert.Equal(200, ui.Window.ResponsePane.Exchange?.Response?.StatusCode); } + [Fact] + public async Task Enter_on_the_request_open_in_the_tree_goes_to_its_url_bar_and_keeps_its_response() + { + await using var server = await LocalEchoServer.StartAsync(); + using var ui = new Harness(_directory, runner => runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"); + TermRest.Core.Http.HttpExchange? sent = null, shown = null; + Terminal.Gui.ViewBase.View? focused = null; + + var screens = Drive(ui, () => ui.App.InjectKey(Key.F5), + ("200 OK", () => + { + sent = ui.Window.ResponsePane.Exchange; + ui.Click("GET GET with query"); // the request sent, open already + ui.App.InjectKey(Key.Enter); + shown = ui.Window.ResponsePane.Exchange; + focused = ui.App.Navigation!.GetFocused(); + ui.App.RequestStop(); + })); + + Assert.Single(screens); + Assert.NotNull(sent); + Assert.Same(sent, shown); + Assert.Equal("{{baseUrl}}/get?foo=bar&source=termrest", Assert.IsAssignableFrom(focused).Text); + } + [Fact] public void Environment_menu_switches_the_active_environment() { @@ -239,6 +344,97 @@ public void Environment_menu_switches_the_active_environment() Assert.Equal("Postman Echo", ApiWorkspace.Open(_directory).ActiveEnvironment?.Name); } + [Fact] + public void Names_are_shown_as_written_and_their_underscores_make_no_hotkeys() + { + // Terminal.Gui takes the first _ of a view's text as a hotkey marker: it hides it and the next letter becomes a key. + var setup = ApiWorkspace.Open(_directory); + setup.CreateEnvironment("prod"); + setup.ActiveEnvironment = setup.CreateEnvironment("dev_local"); + setup.SaveSettings(); + var demo = setup.Collections[0]; + var request = demo.AddRequest(demo.RootNode, "get_pets").PathInCollection; + demo.Save(); + using var ui = new Harness(_directory); + var main = ""; + var afterAltL = ""; + var saved = ""; + Terminal.Gui.ViewBase.View? focused = null, afterAltP = null; + + var screens = Drive(ui, () => + { + ui.Window.ShowRequest(ui.Workspace.Collections[0].FindRequest(request)!); + ui.Window.ShowHistory(false); // the tree has the focus + main = ui.Screen(); + focused = ui.App.Navigation!.GetFocused(); + ui.App.InjectKey(Key.P.WithAlt); // the letter after the _ of the request's name, in the pane's title + afterAltP = ui.App.Navigation.GetFocused(); + ui.App.InjectKey(Key.L.WithAlt); // the letter after the _ of the environment's name, in the status bar + afterAltL = ui.Screen(); + ui.App.InjectKey(Key.F7); + }, + ("Manage environments…", () => ui.Click("Manage environments…")), + ("Active environment:", () => + { + // The label naming the active environment is followed by Set active, which its hotkey would press. + ui.Click(" prod"); + ui.App.InjectKey(Key.L.WithAlt); + Descendants(ui.App.TopRunnableView!).OfType().Single(b => b.Text == "Rename…").SetFocus(); + ui.App.InjectKey(Key.L); + ui.Click("Close"); + }), + ("Env:", () => + { + ui.App.Driver!.SetScreenSize(180, 45); // room for the status bar's message + ui.Window.Editor.FocusUrl(); + ui.Type("x"); + ui.App.InjectKey(Key.S.WithCtrl); + saved = ui.Screen(); + ui.App.RequestStop(); + })); + + Assert.Equal(3, screens.Count); + OnScreen("Request — TermRest Demo / get_pets", main); + OnScreen("Env: dev_local", main); + Assert.Same(focused, afterAltP); + Assert.DoesNotContain("Manage environments…", afterAltL, StringComparison.Ordinal); + OnScreen("● dev_local", screens[0]); + OnScreen("Active environment: dev_local", screens[1]); + OnScreen("Env: dev_local", screens[2]); + OnScreen("Saved TermRest Demo.postman_collection.json", saved); + Assert.Equal("dev_local", ApiWorkspace.Open(_directory).ActiveEnvironment?.Name); + } + + [Fact] + public void A_certificate_s_name_is_shown_as_written_and_makes_no_hotkey_of_its_underscore() + { + // The label naming the request's certificate is followed by Manage certificates…, which its hotkey would press. + var setup = ApiWorkspace.Open(_directory); + setup.Certificates.Entries.Add(new TermRest.Core.Certificates.CertificateEntry + { + Name = "dev_cert", + Matches = ["https://localhost/*"], + Pfx = new TermRest.Core.Certificates.FileSource { Src = "missing.pfx" }, + }); + setup.SaveCertificates(); + using var ui = new Harness(_directory, runner => runner.LocalVariables["baseUrl"] = "https://localhost/echo"); + var settings = ""; + + var screens = Drive(ui, () => + { + var tab = ui.Find("│Settings│"); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(tab.X + 2, tab.Y))); + settings = ui.Screen(); + ui.App.InjectKey(Key.C.WithAlt); // the letter after the _ of the certificate's name + ui.App.InjectKey(Key.C); + ui.App.RequestStop(); + }, + ("Registry:", () => ui.Click("Close"))); + + OnScreen("dev_cert", settings); + Assert.Empty(screens); // the certificates dialog never opened + } + [Fact] public void Right_click_on_the_tree_opens_a_context_menu() { @@ -327,6 +523,9 @@ private static void OnScreen(string expected, string screen) } } + /// 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]+", " "); + [Fact] public async Task History_pane_lists_sent_requests_and_reopens_them() { @@ -384,6 +583,52 @@ public async Task History_pane_lists_sent_requests_and_reopens_them() Assert.False(ui.Window.ShowingHistory); } + [Fact] + public async Task The_history_pane_lists_no_more_entries_than_the_history_keeps() + { + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + runner.History!.MaxEntries = 2; + }); + var sent = 0; + var screen = ""; + var deadline = DateTime.UtcNow.AddSeconds(20); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + if (ui.Window.IsSending && DateTime.UtcNow < deadline) + { + return true; + } + + if (sent == 0) + { + ui.App.InjectKey(Key.F9); // listed while the requests are sent + } + + if (sent < 3 && DateTime.UtcNow < deadline) + { + ui.App.InjectKey(Key.F5); + sent++; + return true; + } + + screen = ui.Screen(); + ui.App.RequestStop(); + return false; + }); + + ui.App.Run(ui.Window); + + Assert.Equal(3, sent); + Assert.StartsWith("GET 127.0.0.1 → 200", ui.Window.StatusMessage, StringComparison.Ordinal); + Assert.Equal((2, 2), (ui.Window.HistoryPane.Count, ui.Window.HistoryPane.Rows.Count)); + OnScreen("History (2)", screen); + } + [Fact] public void Pasting_a_curl_command_into_the_url_bar_imports_it() { @@ -440,6 +685,7 @@ public void Imported_curl_commands_open_as_new_requests() ui.Window.ImportCurl("curl https://api.example.com/v1/users/42 -H 'Accept: application/json' -u ada:secret", intoCurrent: false); var screen = ui.Screen(); + ui.Window.Editor.MarkClean(); // closing would ask about the imported request, which is in no collection ui.App.End(token!); OnScreen("Request (imported) ●", screen); @@ -678,6 +924,281 @@ private static void SaveWhenStopDialogShows(Harness ui, Action dialogSho }); } + [Fact] + public async Task A_request_that_could_not_be_recorded_is_said_once_and_not_over_every_later_message() + { + await using var server = await LocalEchoServer.StartAsync(); + using var ui = new Harness(_directory, runner => runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"); + const string Failed = "A request could not be recorded: There is not enough space on the disk."; + string first = "", second = ""; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F12); + + // As when writing a request failed (the disk was full for a moment): the recording goes on. + typeof(RequestRecorder).GetProperty(nameof(RequestRecorder.LastError))!.SetValue(ui.Runner.Recorder, Failed); + ui.App.InjectKey(Key.F5); + }, + ("· 1 request ·", () => + { + first = ui.Window.StatusMessage; + ui.App.InjectKey(Key.F5); + }), + ("· 2 requests ·", () => + { + second = ui.Window.StatusMessage; + var recorder = ui.Runner.Recorder!; + ui.Runner.Recorder = null; // not asked about when closing + recorder.Discard(); + ui.App.RequestStop(); + })); + + Assert.Equal(2, screens.Count); + Assert.Equal("⚠ " + Failed, first); + Assert.StartsWith("GET 127.0.0.1 → 200", second, StringComparison.Ordinal); + } + + [Fact] + public async Task Names_added_to_the_settings_while_recording_are_redacted_from_then_on() + { + await using var server = await LocalEchoServer.StartAsync(); + var setup = PostmanCollection.Load(Path.Combine(_directory, "TermRest Demo.postman_collection.json")); + var node = setup.FindRequest("Basics/GET with query")!; + var spec = node.ReadSpec(); + spec.Headers.Add(new KeyValueEntry { Key = "X-Tenant-Key", Value = "t-123456" }); + setup.UpdateRequest(node, spec); + setup.Save(); + + // Saving the settings turns the history on: it is kept in this test's folder. + var previousState = Environment.GetEnvironmentVariable(TermRest.Core.History.HistoryStore.StateDirectoryVariable); + Environment.SetEnvironmentVariable(TermRest.Core.History.HistoryStore.StateDirectoryVariable, Path.Combine(_directory, "state")); + try + { + using var ui = new Harness(_directory, runner => runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"); + var har = Path.Combine(_directory, "recorded.har"); + var notice = ""; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F12); + ui.Click("Tools"); + ui.Click("Settings…"); // returns once the dialog is closed + notice = ui.Window.StatusMessage; + ui.App.InjectKey(Key.F5); + }, + ("Workspace settings", () => + { + var label = ui.Find("Recordings redact"); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(label.X + 23, label.Y))); + ui.Type("Tenant-Key"); + ui.Click("► Save ◄"); + }), + ("· 1 request ·", () => + { + var recorder = ui.Runner.Recorder!; + ui.Runner.Recorder = null; // not asked about when closing + recorder.Save(har); + ui.App.RequestStop(); + })); + + Assert.Equal(2, screens.Count); + Assert.Equal("Settings saved. The recording also redacts Tenant-Key from now on; requests already recorded are unchanged.", notice); + var text = File.ReadAllText(har); + Assert.DoesNotContain("t-123456", text, StringComparison.Ordinal); + var log = System.Text.Json.Nodes.JsonNode.Parse(text)!["log"]!; + Assert.Contains(log["entries"]![0]!["request"]!["headers"]!.AsArray(), + h => h!["name"]!.GetValue() == "X-Tenant-Key" && h["value"]!.GetValue() == "[REDACTED]"); + Assert.Equal(["Tenant-Key"], log["_termrest"]!["redaction"]!["extraNames"]!.AsArray().Select(n => n!.GetValue())); + } + finally + { + Environment.SetEnvironmentVariable(TermRest.Core.History.HistoryStore.StateDirectoryVariable, previousState); + } + } + + [Fact] + public void Settings_that_could_not_be_saved_apply_for_the_session_and_are_not_said_to_be_saved() + { + using var ui = new Harness(_directory); + var notice = ""; + + var screens = Drive(ui, () => + { + // A merge conflict in the file since TermRest read it: saving over it is refused. + Directory.CreateDirectory(ui.Workspace.ConfigDirectory); + File.WriteAllText(ui.Workspace.SettingsPath, "{ <<<<<<< HEAD"); + ui.Click("Tools"); + ui.Click("Settings…"); // returns once the dialog is closed + notice = ui.Window.StatusMessage; + ui.App.RequestStop(); + }, + ("Workspace settings", () => + { + ui.Click("Verify server certificates"); + ui.Click("► Save ◄"); + }), + ("Save failed", () => ui.App.InjectKey(Key.Enter))); + + Assert.Equal(2, screens.Count); + Assert.Equal("Settings applied for this session, not saved.", notice); + Assert.False(ui.Workspace.Settings.StrictSsl); + } + + [Fact] + public void A_proxy_that_came_with_the_workspace_is_used_once_the_settings_are_saved() + { + // A cloned repository's settings: its proxy is not used (the system's is), and the UI says so. + const string proxy = "http://ada:Pr0xy-s3cret@127.0.0.1:1"; + Directory.CreateDirectory(Path.Combine(_directory, ".termrest")); + File.WriteAllText(Path.Combine(_directory, ".termrest", "settings.json"), $$"""{ "proxy": "{{proxy}}" }"""); + var userDirectory = TestFiles.NewTempDirectory(); + using var ui = new Harness(_directory, runner => runner.ConfigureProxy(userDirectory)); + var notice = ui.Window.StatusMessage; + var unused = ui.Runner.CreateDefaults().Proxy; + string info = "", dialog = ""; + var saved = false; + + var screens = Drive(ui, () => + { + ui.Click("Help"); + ui.Click("Workspace info"); // returns once the dialog is closed + SettingsDialog.Show(ui.App, ui.Workspace, ui.Runner, out saved, userDirectory); + ui.App.RequestStop(); + }, + ("Proxy: system", () => + { + info = ui.Screen(); + ui.App.InjectKey(Key.Enter); // OK + }), + ("Workspace settings", () => + { + dialog = ui.Screen(); + ui.Click("► Save ◄"); // the user's own choice now: allowed for this folder + })); + + Assert.Equal(2, screens.Count); + Assert.Contains("The proxy in this workspace's settings (.termrest/settings.json) is not used until you allow it: Tools > Settings > Save", notice, StringComparison.Ordinal); + Assert.Null(unused); + // Joined: the dialog wraps long lines where the screen's width has it (Terminal.Gui may set 120 columns again on Windows). + OnScreen("Proxy: system (OS / HTTPS_PROXY settings), not the workspace's http://ada:***@127.0.0.1:1 until you allow it: Tools > Settings > Save", Unwrapped(info)); + Assert.DoesNotContain("Pr0xy-s3cret", info, StringComparison.Ordinal); + OnScreen("⚠ Set by the workspace: not used until you save", dialog); + OnScreen("http://ada:***@127.0.0.1:1", dialog); // its password masked, as everywhere; saved as it was + Assert.DoesNotContain("Pr0xy-s3cret", dialog, StringComparison.Ordinal); + Assert.True(saved); + Assert.Null(ui.Runner.BlockedProxy); + Assert.Equal(proxy, ui.Runner.CreateDefaults().Proxy); + Assert.True(UserSettings.Load(userDirectory).IsProxyAllowed(_directory, proxy)); + Assert.DoesNotContain("Pr0xy-s3cret", File.ReadAllText(Path.Combine(userDirectory, "settings.json")), StringComparison.Ordinal); + } + + [Fact] + public void Files_from_outside_the_workspace_are_sent_once_allowed_in_the_settings() + { + var userDirectory = TestFiles.NewTempDirectory(); + using var ui = new Harness(_directory, runner => runner.ConfigureFiles(userDirectory)); + var only = ui.Runner.CreateDefaults().FilesFolder; + 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("Allow files from outside this folder"); + ui.Click("► Save ◄"); + })); + + Assert.Single(screens); + Assert.Equal(ui.Workspace.RootPath, only); + Assert.True(saved); + Assert.Null(ui.Runner.CreateDefaults().FilesFolder); + Assert.True(UserSettings.Load(userDirectory).AreOutsideFilesAllowed(ui.Workspace.RootPath)); + } + + [Fact] + public void Settings_written_by_hand_as_requests_read_them_can_be_saved() + { + // No redirects followed (0) and a proxy keyword in another case: valid settings that the dialog must not refuse. + Directory.CreateDirectory(Path.Combine(_directory, ".termrest")); + File.WriteAllText(Path.Combine(_directory, ".termrest", "settings.json"), """{ "maxRedirects": 0, "proxy": "None" }"""); + using var ui = new Harness(_directory); + var (changed, saved) = (false, false); + + var screens = Drive(ui, () => + { + changed = SettingsDialog.Show(ui.App, ui.Workspace, ui.Runner, out saved, TestFiles.NewTempDirectory()); + ui.App.RequestStop(); + }, + ("Workspace settings", () => ui.Click("► Save ◄"))); + + Assert.Single(screens); + Assert.True(changed && saved); + Assert.Equal((0, "none"), (ui.Workspace.Settings.MaxRedirects, ui.Workspace.Settings.Proxy)); + } + + [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 + [InlineData("http://bob:***@proxy:3128", "http://bob:***@proxy:3128")] // another user: as typed + [InlineData("http://ada:n3w@proxy:3128", "http://ada:n3w@proxy:3128")] // a new password + [InlineData("none", "none")] + public void A_proxy_password_left_masked_in_the_settings_stays_as_it_was(string typed, string saved) + { + const string Original = "http://ada:s3cret@proxy:3128"; + + Assert.Equal(saved, SettingsDialog.Unmasked(typed, PostmanUrl.MaskCredentials(Original), Original)); + Assert.Equal("http://tok3n@proxy:3128", SettingsDialog.Unmasked("http://***@proxy:3128", "http://***@proxy:3128", "http://tok3n@proxy:3128")); // a user name alone: the credential + } + + [Fact] + public void The_settings_and_certificates_dialogs_show_every_control_on_terminals_of_80_and_100_columns() + { + using var ui = new Harness(_directory); + var shown = new List(); + var cut = new List(); + + // A dialog does not scroll: each control must be in its content area (its buttons within its border), and it on screen. + void Check() + { + foreach (var columns in (int[])[80, 100]) + { + ui.App.Driver!.SetScreenSize(columns, 30); // set here: an answer to Terminal.Gui's size query sets 120×30 again now and then + shown.Add(ui.Screen()); + var dialog = (Terminal.Gui.Views.Dialog)ui.App.TopRunnableView!; + var frame = dialog.FrameToScreen(); + var content = dialog.ViewportToScreen(); + var controls = Descendants(dialog).Skip(1).Where(v => v.CanFocus && v.Visible).Select(v => (View: v, Area: content)) + .Concat(dialog.Buttons.Select(b => (View: (Terminal.Gui.ViewBase.View)b, Area: Rectangle.Inflate(frame, -1, -1)))); + cut.AddRange(controls.Where(c => !c.Area.Contains(c.View.ViewportToScreen())) + .Select(c => $"{columns} columns, {dialog.Title}: {c.View.GetType().Name} '{c.View.Text}' at {c.View.ViewportToScreen()}, not in {c.Area}")); + if (!new Rectangle(0, 0, columns, 30).Contains(frame)) + { + cut.Add($"{columns} columns: {dialog.Title} at {frame}"); + } + } + + ui.App.InjectKey(Key.Esc); + } + + var screens = Drive(ui, () => + { + ui.Click("Tools"); + ui.Click("Settings…"); // returns once the dialog is closed + ui.App.InjectKey(Key.F8); // the client certificates, likewise + ui.App.RequestStop(); + }, + ("Workspace settings", Check), + ("Client certificates", Check)); + + Assert.Equal(2, screens.Count); + Assert.True(cut.Count == 0, string.Join('\n', cut.Concat(shown))); + OnScreen("system (OS / HTTPS_PROXY settings)", shown[0]); // an underscore in a hint is not a hotkey marker + } + [Fact] public async Task A_json_body_file_must_be_valid_json_and_recordings_keep_only_its_path() { @@ -1119,9 +1640,17 @@ public void Collection_scripts_are_edited_from_the_tree() } [Fact] - public void The_scripts_dialog_chooses_a_runtime_for_each_language() + public async Task The_scripts_dialog_chooses_a_runtime_for_each_language() { TestCSharp.Require(); + + // Find takes dotnet on PATH, else the .NET installed for the user (~/.dotnet); TERMREST_TEST_DOTNET may name another. + var sdk = (await ScriptRuntimeLocator.FindAsync(ScriptLanguage.CSharp, _directory, r => r, TestContext.Current.CancellationToken))?.Runtime; + if (sdk is null) + { + Assert.Skip("Find looks for dotnet on PATH and in ~/.dotnet, and neither is a .NET SDK 10 or later."); + } + var settings = TestFiles.NewTempDirectory(); using var ui = new Harness(_directory); string dialog = "", found = ""; @@ -1170,8 +1699,8 @@ public void The_scripts_dialog_chooses_a_runtime_for_each_language() OnScreen("None chosen: C# scripts do not run.", dialog); OnScreen("None chosen: PowerShell scripts do not run.", dialog); Assert.True(found.Contains("✓ .NET SDK", StringComparison.Ordinal), $"{dialog}\n----\n{found}"); - Assert.Equal("dotnet", UserSettings.Load(settings).GetScriptRuntime(ScriptLanguage.CSharp, ui.Workspace.RootPath)); - Assert.Equal("dotnet", ui.Runner.CSharpRuntime); + Assert.Equal(sdk, UserSettings.Load(settings).GetScriptRuntime(ScriptLanguage.CSharp, ui.Workspace.RootPath)); + Assert.Equal(sdk, ui.Runner.CSharpRuntime); Assert.Null(ui.Runner.PythonInterpreter); } @@ -1278,10 +1807,10 @@ 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 ", "F8 ", "F9 "); - var actions = Column("Send (again to cancel)", "Cancel a running request", "Rename tree item", "Client certificates", "Collections ⇄ History"); - var moreKeys = Column("F12 ", "Tab, Shift+Tab", "←, → (tab row)", "Shift+F10", "Ctrl+L"); - var moreActions = Column("Start / stop recording", "Next / previous field", "Previous / next tab", "Focus the URL bar"); + var keys = Column("F5, Ctrl+Enter", "Esc ", "F2 ", "Insert ", "F8 "); + var actions = Column("Send (again to cancel)", "Cancel a running request", "Rename tree item", "Add a table row", "Client certificates"); + var moreKeys = Column("F9 ", "F12 ", "Tab, Shift+Tab", "←, → (tab row)", "Shift+F10", "Ctrl+L"); + var moreActions = Column("Collections ⇄ History", "Start / stop recording", "Next / previous field", "Previous / next tab", "Focus the URL bar"); Assert.True(keys < actions && actions < moreKeys && moreKeys < moreActions, screen); Assert.Equal(At(screen, "Esc ").Y + 1, At(screen, "Ctrl+S ").Y); OnScreen("Right-click the tree or the history for actions", screen); @@ -1293,7 +1822,7 @@ public void Keyboard_help_uses_one_column_on_narrow_screens() var wide = MainWindow.KeysHelp(120).Split('\n'); var narrow = MainWindow.KeysHelp(80).Split('\n'); - Assert.Equal(wide.Length + 8, narrow.Length); + Assert.Equal(wide.Length + 9, narrow.Length); Assert.Contains(" F12 Start / stop recording", narrow); Assert.All(narrow.TakeWhile(l => l.Length > 0), l => Assert.True(l.Length <= 60, l)); Assert.All(wide, l => Assert.True(l.Length <= 92, l)); @@ -1330,6 +1859,41 @@ public void Text_dialogs_keep_lines_left_aligned_and_wrap_long_ones() Assert.Equal(20, System.Text.RegularExpressions.Regex.Count(screen, "folder_name")); // wrapped, not cut; underscores kept } + [Fact] + public void A_help_text_taller_than_the_screen_scrolls_to_its_end() + { + using var ui = new Harness(_directory); + string top = "", end = ""; + var closed = false; + + var screens = Drive(ui, () => + { + ui.App.Driver!.SetScreenSize(120, 30); + ui.Click("Help"); + ui.Click("Scripting"); + ui.App.RequestStop(); + }, + ("Scripts run in a runtime you choose", () => + { + top = ui.Screen(); + for (var i = 0; i < 6; i++) + { + ui.App.InjectKey(Key.PageDown); + } + + end = ui.Screen(); + ui.App.InjectKey(Key.Enter); // OK + closed = ui.App.TopRunnable is { StopRequested: true }; + })); + + Assert.Single(screens); + Assert.DoesNotContain("PowerShell: the $tr object", top, StringComparison.Ordinal); + OnScreen("PowerShell: the $tr object, as in C#", end); + OnScreen("permissions: choose runtimes only for workspaces whose collections you trust.", end); + OnScreen("► OK ◄", end); + Assert.True(closed); + } + [Fact] public void Clicking_a_tab_opens_its_page_and_returns_to_the_control_last_focused_there() { @@ -1399,6 +1963,2431 @@ public void Arrow_keys_on_the_tab_row_switch_tabs() OnScreen("SSL certificate verification", screen); } + [Fact] + public void Certificate_dialog_buttons_do_their_job_and_leave_the_dialog_open() + { + var setup = ApiWorkspace.Open(_directory); + setup.Certificates.Entries.Add(new TermRest.Core.Certificates.CertificateEntry + { + Name = "Team cert", + Matches = ["https://localhost/*"], + Pfx = new TermRest.Core.Certificates.FileSource { Src = "missing.pfx" }, + }); + setup.SaveCertificates(); + using var ui = new Harness(_directory); + + var screens = Drive(ui, () => + { + CertificatesDialog.Show(ui.App, ui.Workspace, ui.Runner, "https://localhost/api"); + ui.App.RequestStop(); + }, + ("Team cert", () => + { + ui.Click("Team cert"); + ui.App.InjectKey(Key.Enter); // tests the certificate + }), + ("✗", () => ui.Click("On/Off")), + ("Team cert", () => ui.Click("Add PEM…")), + ("Leave the key empty", () => ui.Click("Browse…")), + ("Filename (▲)", () => ui.App.InjectKey(Key.Esc)), + ("Leave the key empty", () => ui.Click("Cancel")), + ("Registry:", () => ui.Click("Close"))); + + Assert.Equal(7, screens.Count); + OnScreen("missing.pfx", screens[1].Split('\n').Single(l => l.Contains('✗', StringComparison.Ordinal))); + Assert.Contains("off", screens[2].Split('\n').First(l => l.Contains("Team cert", StringComparison.Ordinal)), StringComparison.Ordinal); + Assert.True(Assert.Single(ApiWorkspace.Open(_directory).Certificates.Entries).Disabled); + } + + [Fact] + public void The_certificate_dialog_asks_before_saving_over_a_registry_changed_on_disk_and_cancel_loads_it() + { + var setup = ApiWorkspace.Open(_directory); + setup.Certificates.Entries.Add(new TermRest.Core.Certificates.CertificateEntry + { + Name = "Team cert", + Matches = ["https://localhost/*"], + Pfx = new TermRest.Core.Certificates.FileSource { Src = "team.pfx" }, + }); + setup.SaveCertificates(); + using var ui = new Harness(_directory); + + // A git pull adds a teammate's certificate while TermRest is open. + setup.Certificates.Entries.Add(new TermRest.Core.Certificates.CertificateEntry + { + Name = "Partner cert", + Matches = ["https://partner.example.com/*"], + Pfx = new TermRest.Core.Certificates.FileSource { Src = "partner.pfx" }, + }); + setup.SaveCertificates(); + var pulled = File.ReadAllText(setup.CertificatesPath); + var afterCancel = ""; + + var screens = Drive(ui, () => + { + CertificatesDialog.Show(ui.App, ui.Workspace, ui.Runner, null); + ui.App.RequestStop(); + }, + ("Team cert", () => + { + ui.Click("Team cert"); + ui.Click("On/Off"); + }), + ("Changed on disk", () => ui.App.InjectKey(Key.Enter)), // Cancel, the default + ("Partner cert", () => + { + afterCancel = File.ReadAllText(setup.CertificatesPath); + ui.Click("Team cert"); + ui.Click("On/Off"); // read since: saved without asking + }), + ("Registry:", () => ui.Click("Close"))); + + Assert.Equal(4, screens.Count); + OnScreen("certificates.json", screens[1]); + OnScreen("Overwrite", screens[1]); + Assert.Equal(pulled, afterCancel); + Assert.Equal([("Team cert", true), ("Partner cert", false)], ApiWorkspace.Open(_directory).Certificates.Entries.Select(e => (e.Name, e.Disabled))); + } + + [Fact] + public void Environment_dialog_buttons_do_their_job_and_leave_the_dialog_open() + { + using var ui = new Harness(_directory); + + var screens = Drive(ui, () => + { + EnvironmentsDialog.Show(ui.App, ui.Workspace); + ui.App.RequestStop(); + }, + ("Active environment: (none)", () => ui.Click("New…")), + ("New environment", () => + { + ui.Type("Staging"); + ui.Click("► OK ◄"); + }), + ("Staging", () => ui.Click("Set active")), + ("Active environment: Staging", () => ui.Click("Close"))); + + Assert.Equal(4, screens.Count); + var saved = ApiWorkspace.Open(_directory); + Assert.Equal(["Postman Echo", "Staging"], saved.Environments.Select(e => e.Name).Order()); + Assert.Equal("Staging", saved.ActiveEnvironment?.Name); + } + + [Fact] + public void Without_an_environment_the_dialog_takes_no_values_until_one_is_created() + { + // Values typed before an environment exists would have nowhere to go. + var empty = TestFiles.NewTempDirectory(); + using var ui = new Harness(empty); + + var screens = Drive(ui, () => + { + EnvironmentsDialog.Show(ui.App, ui.Workspace); + ui.App.RequestStop(); + }, + ("No environments yet", () => ui.Click("New…")), + ("New environment", () => + { + ui.App.RaisePasteEvent("Local"); + ui.Click("► OK ◄"); + }), + ("+ Add", () => ui.Click("Close"))); + + Assert.Equal(3, screens.Count); + Assert.DoesNotContain("+ Add", screens[0], StringComparison.Ordinal); + Assert.DoesNotContain("No environments yet", screens[2], StringComparison.Ordinal); + Assert.Equal("Local", Assert.Single(ApiWorkspace.Open(empty).Environments).Name); + } + + [Fact] + public void The_environment_dialog_goes_on_editing_its_environment_when_new_or_import_fails() + { + var file = Path.Combine(_directory, "Postman Echo.postman_environment.json"); + using var ui = new Harness(_directory); + + var screens = Drive(ui, () => + { + EnvironmentsDialog.Show(ui.App, ui.Workspace); + ui.App.RequestStop(); + }, + ("Active environment: (none)", () => + { + // New environments go to postman/environments, a folder that can't be made under a file of that name. + ui.Workspace.Settings.CollectionFormat = "v3"; + File.WriteAllText(Path.Combine(_directory, "postman"), ""); + ui.Click("New…"); + }), + ("New environment", () => + { + ui.App.RaisePasteEvent("Staging"); + ui.Click("► OK ◄"); + }), + ("Cannot create environment", () => + { + ui.Workspace.Settings.CollectionFormat = null; + File.Delete(Path.Combine(_directory, "postman")); + ui.Click("► OK ◄"); + }), + ("Active environment: (none)", () => + { + ui.Click("unused"); + ui.App.InjectKey(Key.Space); // on + ui.Click("Import…"); // its own file, changed here: refused + }), + ("Filename (▲)", () => + { + ui.App.RaisePasteEvent(file); // over the folder the picker shows + ui.App.InjectKey(Key.Enter); + }), + ("Import failed", () => ui.Click("► OK ◄")), + ("Active environment: (none)", () => + { + ui.Click("token"); + ui.App.InjectKey(Key.Space); // off + ui.Click("Set active"); + }), + ("Active environment: Postman Echo", () => ui.Click("Close"))); + + Assert.Equal(8, screens.Count); + OnScreen("already open", screens[5]); + Assert.Equal([true, false, true], PostmanEnvironment.Load(file).Values.Select(v => v.Enabled)); + var saved = ApiWorkspace.Open(_directory); + Assert.Equal("Postman Echo", Assert.Single(saved.Environments).Name); + Assert.Equal("Postman Echo", saved.ActiveEnvironment?.Name); + } + + [Fact] + public void Lists_scrolled_sideways_show_characters_outside_the_BMP_as_replacement_characters() + { + // Terminal.Gui's lists cut a row scrolled sideways at a UTF-16 index: inside an emoji, drawing it failed. + var setup = ApiWorkspace.Open(_directory); + setup.CreateEnvironment("Prod 🚀"); + setup.CreateEnvironment("Prod 🚀"); // both show their file names then: wider than the list + var themes = ThemeCatalog.WorkspaceThemesDirectory(_directory); + Directory.CreateDirectory(themes); + File.WriteAllText(Path.Combine(themes, "rocket.json"), """{ "name": "Rocket 🚀 at night, a theme with a long name", "base": "Nord" }"""); + using var ui = new Harness(_directory); + string environments = "", custom = "", themeList = ""; + void ScrollRight() + { + var list = Descendants(ui.App.TopRunnableView!).OfType().Single(); + for (var i = 0; i < 8; i++) + { + ui.App.InjectMouse(new Mouse { ScreenPosition = list.FrameToScreen().Location, Flags = MouseFlags.WheeledRight }); + } + } + + try + { + var screens = Drive(ui, () => + { + EnvironmentsDialog.Show(ui.App, ui.Workspace); + ThemeDialog.Show(ui.App, ui.Workspace, Path.Combine(_directory, "user-config")); + ui.App.RequestStop(); + }, + ("Active environment:", () => + { + ScrollRight(); + environments = ui.Screen(); + ui.Click("Close"); + }), + ("Themes (* custom)", () => + { + ui.App.InjectKey(Key.End); // custom themes come last + custom = ui.Screen(); + ScrollRight(); + themeList = ui.Screen(); + ui.Click("Cancel"); + })); + + Assert.Equal(2, screens.Count); + OnScreen(" Prod \uFFFD (Prod \uFFFD", screens[0]); + OnScreen(" (Prod \uFFFD.postman_environment", environments); // scrolled past the name's own \uFFFD + OnScreen("Rocket \uFFFD at night", custom); + Assert.DoesNotContain("Rocket \uFFFD", themeList, StringComparison.Ordinal); + } + finally + { + ThemeCatalog.Apply(ThemeCatalog.BuiltIn[0]); + } + } + + [Fact] + public void An_unexpected_error_in_a_dialog_loses_none_of_its_changes() + { + // The error goes on to the handler of unexpected errors, as any error in the main loop does; here it is caught + // where the dialog was opened. + var file = Path.Combine(_directory, "Postman Echo.postman_environment.json"); + var userDirectory = Path.Combine(_directory, "user-config"); + var original = ThemeCatalog.Current.Name; + Exception? environmentsError = null, themeError = null; + string statusBar = "", previewed = "", restored = ""; + List saved = []; + string? active = null; + using (var ui = new Harness(_directory)) + { + Drive(ui, () => ui.App.InjectKey(Key.F7), + ("Manage environments…", () => + { + environmentsError = Record.Exception(() => ui.Click("Manage environments…")); + statusBar = ui.Screen(); + saved = [.. PostmanEnvironment.Load(file).Values.Select(v => v.Enabled)]; + active = ApiWorkspace.Open(_directory).ActiveEnvironment?.Name; + ui.App.RequestStop(); + }), + ("Active environment:", () => + { + ui.Click("token"); + ui.App.InjectKey(Key.Space); // off + ui.Click("Set active"); + throw new InvalidOperationException("Unexpected"); + })); + } + + using (var ui = new Harness(_directory)) + { + try + { + Drive(ui, () => + { + themeError = Record.Exception(() => ThemeDialog.Show(ui.App, ui.Workspace, userDirectory)); + restored = ThemeCatalog.Current.Name; + ui.App.RequestStop(); + }, + ("Themes (* custom)", () => + { + ui.Click("Dracula"); + previewed = ThemeCatalog.Current.Name; + throw new InvalidOperationException("Unexpected"); + })); + } + finally + { + ThemeCatalog.Apply(ThemeCatalog.BuiltIn[0]); + } + } + + Assert.IsType(environmentsError); + OnScreen("Env: Postman Echo", statusBar); + Assert.Equal([true, false, false], saved); + Assert.Equal("Postman Echo", active); + Assert.IsType(themeError); + Assert.Equal(("Dracula", original), (previewed, restored)); + } + + [Fact] + public void Importing_an_environment_named_as_the_active_one_names_its_file_in_the_status_bar() + { + var setup = ApiWorkspace.Open(_directory); + var active = setup.CreateEnvironment("Production"); + setup.ActiveEnvironment = active; + setup.SaveSettings(); + var exported = Path.Combine(_directory, "exports", "Production.postman_environment.json"); + Directory.CreateDirectory(Path.GetDirectoryName(exported)!); + File.Copy(active.FilePath!, exported); + using var ui = new Harness(_directory); + var imported = ""; + + var screens = Drive(ui, () => + { + ui.Click("File"); + ui.Click("Import Postman environment…"); // returns once it is imported + ui.App.Driver!.SetScreenSize(200, 45); // room for the status bar's message + imported = ui.Screen(); + ui.App.RequestStop(); + }, + ("Filename (▲)", () => + { + ui.App.RaisePasteEvent(exported); + ui.App.InjectKey(Key.Enter); + })); + + Assert.Single(screens); + Assert.Equal(2, ui.Workspace.Environments.Count(e => e.Name == "Production")); + OnScreen("Env: Production (Production.postman_environment.json)", imported); + } + + [Fact] + public void Editing_a_certificate_from_an_os_store_keeps_its_store() + { + const string Thumbprint = "0123456789ABCDEF0123456789ABCDEF01234567"; + var setup = ApiWorkspace.Open(_directory); + setup.Certificates.Entries.Add(new TermRest.Core.Certificates.CertificateEntry + { + Name = "Partner cert", + Matches = ["https://partner.example.com/*"], + Store = new TermRest.Core.Certificates.StoreSource { StoreName = "TrustedPeople", Thumbprint = Thumbprint }, + }); + setup.SaveCertificates(); + using var ui = new Harness(_directory); + + var screens = Drive(ui, () => + { + CertificatesDialog.Show(ui.App, ui.Workspace, ui.Runner, null); + ui.App.RequestStop(); + }, + ("Partner cert", () => + { + ui.Click("Partner cert"); + ui.Click("Edit…"); + }), + ("Store location", () => ui.Click("► Save ◄")), + ("Registry:", () => ui.Click("Close"))); + + Assert.Equal(3, screens.Count); + var store = Assert.Single(ApiWorkspace.Open(_directory).Certificates.Entries).Store; + Assert.Equal(("CurrentUser", "TrustedPeople", Thumbprint), (store?.Location, store?.StoreName, store?.Thumbprint)); + } + + [Fact] + public void Browse_buttons_open_the_file_picker_and_leave_their_dialog_open() + { + using var ui = new Harness(_directory); + bool? settingsSaved = null; + var field = new KeyValueEntry(); + + var screens = Drive(ui, () => + { + settingsSaved = SettingsDialog.Show(ui.App, ui.Workspace, ui.Runner, out _); + field = KeyValueEntryDialog.Show(ui.App, "Edit form field", new KeyValueEntry { Key = "avatar", Type = "text" }, Views.KeyValueKind.FormData); + ui.App.RequestStop(); + }, + ("Workspace settings", () => + { + ui.Click("Verify server certificates"); // not saved: the dialog is cancelled + ui.Click("Browse…"); + }), + ("Filename (▲)", () => ui.App.InjectKey(Key.Esc)), + ("Workspace settings", () => ui.Click("Cancel")), + ("Edit form field", () => ui.Click("Browse…")), + ("Filename (▲)", () => ui.App.InjectKey(Key.Esc)), + ("Edit form field", () => ui.Click("Cancel"))); + + Assert.Equal(6, screens.Count); + Assert.False(settingsSaved); + Assert.True(ui.Workspace.Settings.StrictSsl); + Assert.True(ApiWorkspace.ReadSettings(_directory).StrictSsl); + Assert.Null(field); + } + + [Fact] + public void Browse_in_the_recording_dialog_does_not_end_the_recording() + { + using var ui = new Harness(_directory); + using var recorder = RequestRecorder.Start(new RecordingOptions { WorkspaceRoot = _directory }); + var result = RecordingDialogResult.Saved; + + var screens = Drive(ui, () => + { + (result, _) = RecordingDialog.Show(ui.App, recorder, RecordingDialog.DefaultPath(_directory, recorder.StartedAt), RecordingDialogPurpose.Stop); + ui.App.RequestStop(); + }, + ("Stop recording", () => ui.Click("Browse…")), + ("Filename (▲)", () => ui.App.InjectKey(Key.Esc)), + ("Stop recording", () => ui.Click("Keep recording"))); + var recording = recorder.IsRecording; + if (recording) + { + recorder.Discard(); + } + + Assert.Equal(3, screens.Count); + Assert.Equal(RecordingDialogResult.Kept, result); + Assert.True(recording); + Assert.Empty(Directory.GetFiles(_directory, "*.har")); + } + + [Fact] + public void Theme_dialog_buttons_leave_the_dialog_open() + { + var userDirectory = Path.Combine(_directory, "user-config"); + using var ui = new Harness(_directory); + ColorTheme? chosen = ThemeCatalog.Current; + try + { + var screens = Drive(ui, () => + { + chosen = ThemeDialog.Show(ui.App, ui.Workspace, userDirectory); + ui.App.RequestStop(); + }, + ("Themes (* custom)", () => ui.Click("Reload theme files")), + ("Themes (* custom)", () => ui.Click("Copy as custom theme…")), + ("Name of the new theme", () => ui.Click("Cancel")), + ("Themes (* custom)", () => ui.Click("Cancel"))); + + Assert.Equal(4, screens.Count); + Assert.Null(chosen); + } + finally + { + ThemeCatalog.Apply(ThemeCatalog.BuiltIn[0]); + } + } + + [Fact] + public void A_theme_copy_never_takes_the_name_of_a_custom_theme() + { + // Only one theme of a name is loaded, the one read last: a copy named like another custom theme would never show. + var userDirectory = Path.Combine(_directory, "user-config"); + var themesFolder = UserSettings.ThemesDirectory(userDirectory); + ThemeCatalog.Apply(ThemeCatalog.BuiltIn[0]); + var taken = $"My {ThemeCatalog.BuiltIn[0].Name}"; + ThemeCatalog.WriteCopy(ThemeCatalog.BuiltIn[0], taken, themesFolder); + using var ui = new Harness(_directory); + try + { + var screens = Drive(ui, () => + { + ThemeDialog.Show(ui.App, ui.Workspace, userDirectory); + ui.App.RequestStop(); + }, + ("Themes (* custom)", () => ui.Click("Copy as custom theme…")), + ("Name of the new theme", () => + { + ui.App.InjectKey(Key.End); + ui.App.InjectKey(Key.Backspace); + ui.App.InjectKey(Key.Backspace); // the name proposed without its " 2": the taken one + ui.Click("► OK ◄"); + }), + ("exists already", () => ui.Click("► OK ◄")), + ("Themes (* custom)", () => ui.Click("Copy as custom theme…")), + ("Name of the new theme", () => ui.Click("► OK ◄")), + ("Custom theme created", () => ui.Click("► OK ◄")), + ("Themes (* custom)", () => ui.Click("Cancel"))); + + Assert.Equal(7, screens.Count); + OnScreen($"{taken} 2", screens[1]); + Assert.Equal([$"{taken} 2.json", $"{taken}.json"], Directory.GetFiles(themesFolder).Select(Path.GetFileName).Order(StringComparer.Ordinal)); + } + finally + { + ThemeCatalog.Apply(ThemeCatalog.BuiltIn[0]); + } + } + + [Fact] + public async Task A_response_that_arrives_after_another_request_was_opened_is_not_shown_there() + { + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/hold"; // answered once released + runner.ConfigureHistory(state); + }); + string opened = "", arrivedStatus = ""; + TermRest.Core.Http.HttpExchange? shownOnArrival = null, sent = null; + var step = 0; + var deadline = DateTime.UtcNow.AddSeconds(20); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(300), () => + { + ui.App.InjectKey(Key.F5); // GET with query + return false; + }); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + if (DateTime.UtcNow > deadline) + { + server.Release(); + ui.App.RequestStop(); + return false; + } + + switch (step) + { + case 0 when ui.Window.ResponsePane.StatusText.StartsWith("Sending GET", StringComparison.Ordinal): + ui.Click("POST POST JSON"); + opened = ui.Screen(); + server.Release(); + step = 1; + break; + case 1 when ui.Runner.History!.Load().Count == 1: + shownOnArrival = ui.Window.ResponsePane.Exchange; + arrivedStatus = ui.Window.StatusMessage; + ui.App.InjectKey(Key.F5); // sends POST JSON + step = 2; + break; + case 2 when ui.Window.ResponsePane.Exchange is { } exchange: + sent = exchange; + ui.App.RequestStop(); + return false; + } + + return true; + }); + + ui.App.Run(ui.Window); + + OnScreen("POST ▼ {{baseUrl}}/post", opened); + OnScreen("No response yet", opened); + Assert.DoesNotContain("Cancel", opened, StringComparison.Ordinal); // the Send button is POST JSON's + Assert.Null(shownOnArrival); + Assert.Equal("Response", ui.Window.ResponseTitle); + Assert.StartsWith("Earlier request: GET 127.0.0.1 → 200", arrivedStatus, StringComparison.Ordinal); + Assert.Equal("/hold/post", System.Text.Json.Nodes.JsonNode.Parse(sent!.Response!.Body)!["path"]!.GetValue()); + Assert.Equal(["/hold/post", "/hold/get?foo=bar&source=termrest"], ui.Runner.History!.Load().Select(e => new Uri(e.Url).PathAndQuery)); + } + + [Fact] + public async Task A_request_added_to_a_collection_with_Ctrl_N_keeps_its_response_and_its_send() + { + await using var server = await LocalEchoServer.StartAsync(); + using var ui = new Harness(_directory); + var arrived = ""; + + var screens = Drive(ui, () => + { + ui.Window.ImportCurl($"curl {server.BaseUrl}/hold/imported", intoCurrent: false); + ui.App.InjectKey(Key.F5); + }, + ("Sending GET", () => ui.App.InjectKey(Key.N.WithCtrl)), // while it is on its way + ("Name (in TermRest Demo / Basics)", () => + { + ui.Click("► OK ◄"); + server.Release(); + }), + ("200 OK", () => + { + arrived = ui.Window.StatusMessage; + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.RequestStop(); + })); + + Assert.Equal(3, screens.Count); + Assert.StartsWith("GET 127.0.0.1 → 200", arrived, StringComparison.Ordinal); // not "Earlier request: …" + Assert.Equal("/hold/imported", ui.Window.ResponsePane.Exchange!.Request.Uri!.AbsolutePath); + var saved = PostmanCollection.Load(Path.Combine(_directory, "TermRest Demo.postman_collection.json")); + Assert.Contains($"{server.BaseUrl}/hold/imported", saved.AllRequests().Select(r => r.ReadSpec().Url)); + } + + [Fact] + public void A_request_added_to_a_collection_with_Ctrl_N_says_what_it_inherits_there() + { + using var ui = new Harness(_directory); + IEnumerable AuthNotes() => Descendants(ui.Window.Editor).OfType().Single().SubViews + .SelectMany(Descendants).OfType().Select(l => l.Text); + List imported = [], added = []; + + var screens = Drive(ui, () => + { + ui.Window.ShowRequest(ui.Workspace.Collections[0].FindRequest("Auth/Auth inherited from folder")!); // its folder is the target + ui.Window.ImportCurl("curl https://api.example.com/v1/me", intoCurrent: false); + imported = [.. AuthNotes()]; + ui.App.InjectKey(Key.N.WithCtrl); + }, + ("Name (in TermRest Demo / Auth)", () => ui.Click("► OK ◄")), + ("Request — TermRest Demo / Auth/", () => + { + added = [.. AuthNotes()]; + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.RequestStop(); + })); + + Assert.Equal(2, screens.Count); + Assert.Contains("No auth is set on the collection.", imported); // a scratch request's + Assert.Contains("Currently: Bearer Token from folder 'Auth'.", added); + Assert.DoesNotContain("No auth is set on the collection.", added); + } + + [Fact] + public void Changes_to_a_request_outside_a_collection_are_not_lost_without_asking() + { + const string Imported = "https://api.example.com/v1/users/42"; + using var ui = new Harness(_directory); + string afterCancel = "", afterDelete = "", afterDiscard = ""; + + var screens = Drive(ui, () => + { + ui.Window.ImportCurl($"curl {Imported} -H 'Accept: application/json'", intoCurrent: false); + ui.Click("POST POST JSON"); // asks: Cancel keeps the imported request + afterCancel = ui.Window.Editor.Spec.Url; + ui.Click("Request"); + ui.Click("Delete…"); // POST JSON, selected in the tree but not open + afterDelete = ui.Window.Editor.Spec.Url; + ui.Click("GET GET with query"); // asks: Discard opens it + afterDiscard = ui.Window.Editor.Spec.Url; + ui.Window.ImportCurl($"curl {Imported} -H 'Accept: application/json'", intoCurrent: false); + ui.App.InjectKey(Key.Q.WithCtrl); // asks: Add to collection…, then saving quits + }, + ("Unsaved request", () => ui.Click("Cancel")), + ("Delete request 'POST JSON'?", () => ui.Click("► Delete ◄")), + ("Unsaved request", () => ui.Click("Discard")), + ("Unsaved request", () => ui.Click("Add to collection…")), + ("Name (in TermRest Demo / Basics)", () => ui.Click("► OK ◄")), + ("Unsaved changes", () => ui.Click("► Save ◄"))); + + Assert.Equal(6, screens.Count); + Assert.Equal((Imported, Imported), (afterCancel, afterDelete)); + Assert.Equal("{{baseUrl}}/get?foo=bar&source=termrest", afterDiscard); + Assert.False(ui.Window.IsRunning); + var saved = PostmanCollection.Load(Path.Combine(_directory, "TermRest Demo.postman_collection.json")); + Assert.Null(saved.FindRequest("Basics/POST JSON")); + Assert.StartsWith("Basics/", saved.AllRequests().Single(r => r.ReadSpec().Url == Imported).PathInCollection, StringComparison.Ordinal); + } + + [Fact] + public async Task Saving_an_edited_history_request_to_a_collection_keeps_the_changes() + { + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + + var screens = Drive(ui, () => ui.App.InjectKey(Key.F5), + ("200 OK", () => + { + ui.App.InjectKey(Key.F9); + ui.Click("200 GET /echo/get"); + ui.Click("{{baseUrl}}/get?foo=bar&source=termrest"); + ui.App.InjectKey(Key.End); + ui.Type("&edited=1"); + ui.App.InjectSequence(InputInjectionExtensions.RightButtonClick(ui.Find("200 GET /echo/get"))); + ui.Click("Save to collection…"); + }), + ("Name (in TermRest Demo / Basics)", () => ui.Click("► OK ◄")), + ("Request — TermRest Demo / Basics/", () => + { + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.RequestStop(); + })); + + Assert.Equal(3, screens.Count); + var saved = PostmanCollection.Load(Path.Combine(_directory, "TermRest Demo.postman_collection.json")); + Assert.Contains("{{baseUrl}}/get?foo=bar&source=termrest&edited=1", saved.AllRequests().Select(r => r.ReadSpec().Url)); + } + + [Fact] + public async Task A_history_request_whose_credentials_were_masked_asks_before_it_is_sent_again() + { + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => runner.ConfigureHistory(state)); + var auth = new AuthSpec { Type = "basic" }; + auth.Set("username", "ada"); + auth.Set("password", "typed-s3cret"); + await ui.Runner.SendAsync(PostmanCollection.Create("Scratch"), null, new HttpRequestSpec { Url = server.BaseUrl + "/echo/masked", Auth = auth }, null, + TestContext.Current.CancellationToken); + string? notice = null; + var sentAfterCancel = -1; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/masked"); + notice = ui.Window.StatusMessage; + ui.App.InjectKey(Key.F5); // asks, and is cancelled + ui.App.InjectKey(Key.F5); // asks: Enter is Cancel + sentAfterCancel = ui.Runner.History!.Load().Count; + ui.App.InjectKey(Key.F5); // asks, and is sent + }, + ("Masked credentials", () => ui.App.InjectKey(Key.Esc)), + ("Masked credentials", () => ui.App.InjectKey(Key.Enter)), + ("Masked credentials", () => ui.Click("Send ***")), + ("200 OK", () => ui.App.RequestStop())); + + Assert.Equal(4, screens.Count); + Assert.Contains("***", notice, StringComparison.Ordinal); + Assert.Equal(1, sentAfterCancel); + Assert.Equal(2, ui.Runner.History!.Load().Count); + } + + [Fact] + public void Names_are_taken_without_the_spaces_around_them() + { + using var ui = new Harness(_directory); + List names = []; + + var screens = Drive(ui, () => + { + names.Add(Dialogs.Ui.PromptText(ui.App, "First name", "Name")); + names.Add(Dialogs.Ui.PromptText(ui.App, "Second name", "Name")); + ui.App.RequestStop(); + }, + ("First name", () => + { + ui.Type(" Ada "); + ui.Click("► OK ◄"); + }), + ("Second name", () => + { + ui.Type(" "); + ui.Click("► OK ◄"); + })); + + Assert.Equal(2, screens.Count); + Assert.Equal(["Ada", ""], names); // spaces alone are no name: New request, Rename … then do nothing + } + + [Fact] + public void The_recording_clock_counts_hours_past_a_day() + { + using var ui = new Harness(_directory); + var indicator = new Views.RecordingIndicator(); + ui.Window.Add(indicator); + + indicator.ShowRecording(DateTimeOffset.Now - new TimeSpan(25, 3, 0), 2); + + Assert.Contains(" REC 25:03:0", indicator.Caption, StringComparison.Ordinal); + } + + [Fact] + public void Status_bar_shortcuts_do_not_act_behind_a_dialog() + { + using var ui = new Harness(_directory); + string? name = null; + var stillRunning = false; + + var screens = Drive(ui, () => + { + name = Dialogs.Ui.PromptText(ui.App, "Name it", "Name"); + stillRunning = ui.Window.IsRunning; + ui.App.InjectKey(Key.Q.WithCtrl); // in the main window, it quits + }, + ("Name it", () => ui.App.InjectKey(Key.Q.WithCtrl)), + ("Name it", () => + { + ui.App.InjectKey(Key.F5); + ui.App.InjectKey(Key.F8); + }), + ("Name it", () => + { + ui.Type("Ada"); + ui.Click("► OK ◄"); + })); + + Assert.Equal(3, screens.Count); + Assert.Equal("Ada", name); + Assert.True(stillRunning); + Assert.StartsWith("No response yet", ui.Window.ResponsePane.StatusText, StringComparison.Ordinal); + Assert.False(ui.Window.IsRunning); + } + + [Fact] + public void A_workspace_folder_that_cannot_be_opened_leaves_the_current_one_open() + { + var other = Path.Combine(_directory, "other"); + Directory.CreateDirectory(other); + var missing = Path.Combine(_directory, "missing"); + using var ui = new Harness(_directory); + var stayed = false; + + var screens = Drive(ui, () => + { + ui.Window.OpenWorkspaceFrom(missing); + stayed = ui.Window.IsRunning && ui.Window.NextWorkspace is null; + ui.Window.OpenWorkspaceFrom(other); + }, + ("Cannot open workspace", () => ui.Click("► OK ◄"))); + + OnScreen("does not exist", Assert.Single(screens)); + Assert.True(stayed); + Assert.False(ui.Window.IsRunning); + Assert.Equal(other, ui.Window.NextWorkspace?.RootPath); + Assert.Equal(2, TuiApp.Run(missing)); // nor does the first one end the program + } + + [Fact] + public void Unexpected_errors_are_logged_in_the_users_own_state_folder() + { + var state = Path.Combine(_directory, "state"); + + var log = TuiApp.LogUnexpectedError(new InvalidOperationException("first"), state); + TuiApp.LogUnexpectedError(new InvalidOperationException("second"), state); + + Assert.Equal(Path.Combine(state, "errors.log"), log); + var text = File.ReadAllText(log); + Assert.Contains("System.InvalidOperationException: first", text, StringComparison.Ordinal); + Assert.Contains("System.InvalidOperationException: second", text, StringComparison.Ordinal); + if (!OperatingSystem.IsWindows()) + { + Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(log)); + Assert.Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute, File.GetUnixFileMode(state)); + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] // the state folder can't be written: the error is shown all the same + public async Task An_unexpected_error_after_sending_is_shown_and_logged_and_TermRest_goes_on(bool canLog) + { + var state = Path.Combine(_directory, "state"); + if (!canLog) + { + File.WriteAllText(state, "a file where the folder would be"); + } + + var previousState = Environment.GetEnvironmentVariable(TermRest.Core.History.HistoryStore.StateDirectoryVariable); + Environment.SetEnvironmentVariable(TermRest.Core.History.HistoryStore.StateDirectoryVariable, state); + try + { + await using var server = await LocalEchoServer.StartAsync(); + using var ui = new Harness(_directory, runner => runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"); + + // Once the response is in, a step fails (saying the result in the status bar): an exception that leaves the + // async void method sending the request would end the process. + var failed = false; + foreach (var shortcut in Descendants(ui.Window).OfType()) + { + shortcut.TitleChanged += (_, e) => + { + if (!failed && e.Value.Contains("→ 200", StringComparison.Ordinal)) + { + failed = true; + throw new InvalidOperationException("The result could not be shown."); + } + }; + } + + var goesOn = false; + var screens = Drive(ui, () => ui.App.InjectKey(Key.F5), + ("Unexpected error", () => ui.Click("► OK ◄")), + ("200 OK", () => + { + goesOn = ui.Window.IsRunning && !ui.Window.IsSending; + ui.App.RequestStop(); + })); + + Assert.Equal(2, screens.Count); + OnScreen("The result could not be shown.", screens[0]); + Assert.True(goesOn); + if (!canLog) + { + Assert.DoesNotContain("Details were", screens[0], StringComparison.Ordinal); + return; + } + + OnScreen("Details were", screens[0]); + Assert.Contains("System.InvalidOperationException: The result could not be shown.", File.ReadAllText(Path.Combine(state, "errors.log")), + StringComparison.Ordinal); + } + finally + { + Environment.SetEnvironmentVariable(TermRest.Core.History.HistoryStore.StateDirectoryVariable, previousState); + } + } + + [Fact] + public void The_ui_runs_at_full_pace_only_while_it_is_in_use() + { + using var ui = new Harness(_directory); + var idle = Application.MaximumIterationsPerSecond; + var busy = false; + var seen = new List<(bool Active, ushort Rate)>(); + using var pace = new UiPace(ui.App, () => busy) { ActiveFor = TimeSpan.FromMilliseconds(300) }; + void Note() => seen.Add((pace.IsActive, Application.MaximumIterationsPerSecond)); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + Note(); + ui.Click("Collections"); + Note(); + busy = true; // a request is on its way + return false; + }); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(900), () => + { + Note(); + busy = false; + return false; + }); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(1700), () => + { + Note(); + ui.App.RequestStop(); + return false; + }); + + ui.App.Run(ui.Window); + + (bool, ushort)[] expected = [(false, idle), (true, TuiApp.IterationsPerSecond), (true, TuiApp.IterationsPerSecond), (false, idle)]; + Assert.Equal(expected, seen); + } + + /// + /// Runs from the main loop while answer the dialogs it opens: each + /// step waits until its text is on screen (and no dialog is closing), then acts; the screens they saw are returned + /// (fewer than the steps when one did not come). The next step is scheduled before a step acts, as an action that + /// opens a dialog returns only once that is closed. After 20 s whatever is open is closed, without unsaved changes, + /// so a test fails instead of hanging. + /// + private static List Drive(Harness ui, Action act, params (string WaitFor, Action Act)[] steps) + { + var screens = new List(); + var deadline = DateTime.UtcNow.AddSeconds(20); + void Next(int index) + { + if (index == steps.Length) + { + return; + } + + ui.App.AddTimeout(TimeSpan.FromMilliseconds(50), () => + { + var screen = ui.Screen(); + if (ui.App.TopRunnable is { StopRequested: true } || !screen.Contains(steps[index].WaitFor, StringComparison.Ordinal)) + { + return DateTime.UtcNow < deadline; + } + + screens.Add(screen); + Next(index + 1); + steps[index].Act(); + return false; + }); + } + + ui.App.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + Next(0); + act(); + return false; + }); + ui.App.AddTimeout(TimeSpan.FromSeconds(1), () => + { + if (DateTime.UtcNow > deadline) + { + if (ui.App.TopRunnableView == ui.Window) + { + ui.Window.Editor.MarkClean(); + ui.App.InjectKey(Key.S.WithCtrl); + } + + ui.App.RequestStop(); + } + + return true; + }); + + ui.App.Run(ui.Window); + return screens; + } + + [Fact] + public void Space_and_clicking_the_checkbox_column_turn_table_rows_on_and_off() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + var debug = ui.Find("debug"); // the disabled query parameter; foo is two rows above it + + ui.Click("debug"); + ui.App.InjectKey(Key.Space); + var afterSpace = ui.Window.Editor.Spec.Clone(); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(debug.X - 2, debug.Y - 2))); + var afterClick = ui.Window.Editor.Spec.Clone(); + var screen = ui.Screen(); + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.End(token!); + + Assert.True(afterSpace.QueryParams.Single(q => q.Key == "debug").Enabled); + Assert.Equal("{{baseUrl}}/get?foo=bar&source=termrest&debug=1", afterSpace.Url); + Assert.False(afterClick.QueryParams.Single(q => q.Key == "foo").Enabled); + Assert.Equal("{{baseUrl}}/get?source=termrest&debug=1", afterClick.Url); + OnScreen("☐│foo", screen); + OnScreen("☑│debug", screen); + var saved = PostmanCollection.Load(Path.Combine(_directory, "TermRest Demo.postman_collection.json")).FindRequest("Basics/GET with query")!.ReadSpec(); + Assert.Equal([false, true, true], saved.QueryParams.Select(q => q.Enabled)); + } + + [Fact] + public void The_history_filter_stays_quick_with_thousands_of_entries() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + var entries = Enumerable.Range(0, 5_000).Select(i => new TermRest.Core.History.HistoryEntry + { + Id = i.ToString(System.Globalization.CultureInfo.InvariantCulture), + Time = DateTimeOffset.Now, + Method = "GET", + Url = $"https://api.example.com/items/{i}", + Item = new System.Text.Json.Nodes.JsonObject { ["name"] = $"Item {i}" }, + Status = 200, + }).ToList(); + ui.App.InjectKey(Key.F9); + var filter = ui.Find("Filter:"); + + var watch = System.Diagnostics.Stopwatch.StartNew(); + ui.Window.HistoryPane.SetEntries(entries, "No requests sent yet."); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(filter.X + 9, filter.Y))); + ui.Type("/49"); + watch.Stop(); + var rows = ui.Window.HistoryPane.Rows.ToList(); + var screen = ui.Screen(); + ui.App.End(token!); + + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(5), $"Filtering took {watch.Elapsed}."); // 0.3 s here; 96 s when each row was added on its own + Assert.Equal(111, rows.Count); // items/49, items/490…499 and items/4900…4999 + Assert.EndsWith("200 GET /items/49", rows[0], StringComparison.Ordinal); + OnScreen("200 GET /items/49 ", screen); + } + + [Fact] + public void Deleting_words_and_cutting_lines_in_a_text_editor_change_the_request() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + ui.Click("POST POST JSON"); + ui.Click("Body"); + ui.Click("Ada Lovelace"); + var editor = Assert.IsType(ui.App.Navigation!.GetFocused()); + var bodies = new List<(string Editor, string Request)>(); + foreach (var key in (Key[])[Key.Delete.WithCtrl, Key.K.WithCtrl, Key.Backspace.WithCtrl, Key.Backspace.WithCtrl.WithShift]) + { + ui.App.InjectKey(key); + bodies.Add((editor.GetText(), ui.Window.Editor.Spec.Body.Raw)); + } + + var modified = ui.Window.Editor.IsModified; + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.End(token!); + + Assert.Equal(4, bodies.Select(b => b.Editor).Distinct().Count()); // each key changed the text + Assert.All(bodies, body => Assert.Equal(body.Editor, body.Request)); + Assert.True(modified); + var saved = PostmanCollection.Load(Path.Combine(_directory, "TermRest Demo.postman_collection.json")).FindRequest("Basics/POST JSON")!.ReadSpec(); + Assert.Equal(bodies[^1].Editor, saved.Body.Raw); + } + + [Fact] + public void Ctrl_L_and_Ctrl_N_are_left_to_the_window_in_text_editors() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + var dialogs = new List(); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + // Runs only while a dialog is open: notes what it shows and closes it. + dialogs.Add(ui.Screen()); + ui.App.InjectKey(Key.Esc); + return true; + }); + ui.Click("POST POST JSON"); + ui.Click("Body"); + ui.Click("Ada Lovelace"); + var editor = Assert.IsType(ui.App.Navigation!.GetFocused()); + + var ctrlLHandled = editor.NewKeyDownEvent(Key.L.WithCtrl); + ui.App.InjectKey(Key.N.WithCtrl); + editor.SetFocus(); + ui.App.InjectKey(Key.L.WithCtrl); + var focused = ui.App.Navigation!.GetFocused(); + ui.App.End(token!); + + Assert.False(ctrlLHandled); // left to the window (Focus URL bar), not TextView's color picker + OnScreen("Name (in TermRest Demo / Basics)", Assert.Single(dialogs)); // New request, not the cursor moving down + Assert.Equal("UrlField", focused?.GetType().Name); + } + + [Fact] + public void Auth_tokens_and_key_values_are_masked_like_passwords() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + ui.Click("POST POST JSON"); + ui.Click("Auth"); + var shown = new List(); + (string Type, string Field, string Secret)[] fields = [("Bearer Token", "Token", "bearer-s3cret"), ("API Key", "Value", "apikey-s3cret"), ("OAuth 2.0 (access token)", "Access token", "oauth-s3cret")]; + foreach (var (type, field, secret) in fields) + { + ui.Click(type); + var label = ui.Find(field); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(label.X + 17, label.Y))); + ui.Type(secret); + shown.Add(ui.Screen()); + } + + var auth = ui.Window.Editor.Spec.Auth; + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.End(token!); + + Assert.All(shown, screen => Assert.DoesNotContain("s3cret", screen, StringComparison.Ordinal)); + Assert.Equal(("oauth2", "oauth-s3cret"), (auth?.Type, auth?.Get("accessToken"))); + } + + [Fact] + public void Enter_on_an_environment_value_edits_it_and_the_dialog_stays_open() + { + using var ui = new Harness(_directory); + + var screens = Drive(ui, () => + { + EnvironmentsDialog.Show(ui.App, ui.Workspace); + ui.App.RequestStop(); + }, + ("Active environment:", () => + { + ui.Click("disabled values are ignored"); // a value only this dialog shows + ui.App.InjectKey(Key.Enter); // returns once the row's editor is closed + }), + ("Edit variable", () => ui.App.InjectKey(Key.Esc)), + ("Active environment:", () => ui.Click("Close"))); + + Assert.Equal(3, screens.Count); // the Environments dialog was still open to close + } + + [Fact] + public void Editing_a_row_keeps_what_was_left_alone_whole() + { + const string Pem = "-----BEGIN PRIVATE KEY-----\nMIIB\n-----END PRIVATE KEY-----"; + var setup = ApiWorkspace.Open(_directory); + var echo = Assert.Single(setup.Environments); + echo.SetValues([.. echo.Values, new KeyValueEntry { Key = "client_key", Value = Pem, Description = "PEM\nPKCS#8", Type = "default" }]); + echo.Save(); + using var ui = new Harness(_directory); + KeyValueEntry? flag = null; + + var screens = Drive(ui, () => + { + EnvironmentsDialog.Show(ui.App, ui.Workspace); + flag = KeyValueEntryDialog.Show(ui.App, "Edit query parameter", new KeyValueEntry { Key = "flag", Value = null }, Views.KeyValueKind.QueryParams); + ui.App.RequestStop(); + }, + ("client_key", () => ui.App.InjectSequence(InputInjectionExtensions.LeftButtonDoubleClick(ui.Find("client_key")))), + ("Edit variable", () => + { + ui.Click("mask value"); + ui.Click("► OK ◄"); + }), + ("Active environment:", () => ui.Click("Close")), + ("Edit query parameter", () => ui.App.InjectKey(Key.Enter))); + + Assert.Equal(4, screens.Count); + OnScreen("MIIB", screens[1]); // all of it, to edit + var saved = Assert.Single(ApiWorkspace.Open(_directory).Environments).Values.Single(v => v.Key == "client_key"); + Assert.Equal((Pem, "PEM\nPKCS#8", true), (saved.Value, saved.Description, saved.IsSecret)); + Assert.Equal(("flag", null), (flag?.Key, flag?.Value)); // not ?flag= + } + + [Fact] + public void Bulk_edit_applied_without_a_change_changes_no_row() + { + // Terminal.Gui keeps each character composed (NFC): the bulk text read back is not the text it was given. + const string Decomposed = "Cafe\u0301 \u2126"; + var setup = PostmanCollection.Load(Path.Combine(_directory, "TermRest Demo.postman_collection.json")); + var request = setup.FindRequest("Basics/POST JSON")!; + var spec = request.ReadSpec(); + spec.Headers.Add(new KeyValueEntry { Key = "X-Note", Value = Decomposed }); + setup.UpdateRequest(request, spec); + setup.Save(); + using var ui = new Harness(_directory); + bool blankLine = true, edited = false; + (bool Modified, string? Value) unchanged = default; + var headers = new List(); + + var screens = Drive(ui, () => + { + ui.Click("GET GET with query"); + ui.Click("Bulk edit"); + blankLine = ui.Window.Editor.IsModified; + ui.Click("POST POST JSON"); + ui.Click("Headers"); + ui.Click("Bulk edit"); + unchanged = (ui.Window.Editor.IsModified, ui.Window.Editor.Spec.Headers.Single(h => h.Key == "X-Note").Value); + ui.Click("Bulk edit"); + (edited, headers) = (ui.Window.Editor.IsModified, ui.Window.Editor.Spec.Headers.Select(h => $"{h.Key}:{h.Value}").ToList()); + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.RequestStop(); + }, + ("Bulk edit query parameters", () => + { + ui.App.InjectKey(Key.End.WithCtrl); + ui.App.InjectKey(Key.Enter); // a blank line: the same rows + ui.Click("► Apply ◄"); + }), + ("Bulk edit headers", () => ui.Click("► Apply ◄")), + ("Bulk edit headers", () => + { + ui.App.InjectKey(Key.End.WithCtrl); + ui.App.InjectKey(Key.Enter); + ui.Type("X-New:1"); + ui.Click("► Apply ◄"); + })); + + Assert.Equal(3, screens.Count); + Assert.False(blankLine); + Assert.Equal((false, Decomposed), unchanged); + Assert.True(edited); + Assert.Contains("X-New:1", headers); + } + + [Fact] + public async Task The_tree_s_context_menu_sends_the_request_right_clicked() + { + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + await ui.Runner.SendAsync(PostmanCollection.Create("Scratch"), null, new HttpRequestSpec { Method = "DELETE", Url = server.BaseUrl + "/echo/users/42" }, null, + TestContext.Current.CancellationToken); + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/users/42"); // GET with query stays selected in the tree + ui.App.InjectKey(Key.F9); + ui.App.InjectSequence(InputInjectionExtensions.RightButtonClick(ui.Find("GET GET with query"))); + var copy = ui.Find("Copy as cURL"); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(copy.X, copy.Y - 1))); // Send + }, + ("200 OK", () => ui.App.RequestStop())); + + Assert.Single(screens); + Assert.Equal("{{baseUrl}}/get?foo=bar&source=termrest", ui.Window.Editor.Spec.Url); + Assert.Equal(["/echo/get?foo=bar&source=termrest", "/echo/users/42"], ui.Runner.History!.Load().Select(e => new Uri(e.Url).PathAndQuery)); + } + + [Fact] + public void Copy_as_curl_says_why_when_curl_cannot_send_the_request_the_same_way() + { + var path = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + var setup = PostmanCollection.Load(path); + var node = setup.FindRequest("Basics/GET with query")!; + var spec = node.ReadSpec(); + spec.Method = "POST"; + spec.Body = new RequestBody { Mode = BodyMode.FormData, FormData = [new() { Key = "doc= runner.LocalVariables["baseUrl"] = "https://api.example.com"); + ui.App.Driver!.Clipboard = new FakeClipboard(); + + var screens = Drive(ui, () => + { + ui.App.InjectSequence(InputInjectionExtensions.RightButtonClick(ui.Find("POST GET with query"))); + ui.Click("Copy as cURL"); + ui.App.RequestStop(); + }, + ("cannot be sent with curl", () => ui.Click("► OK ◄"))); + + Assert.Single(screens); + OnScreen("'doc= runner.LocalVariables["baseUrl"] = "https://api.example.com"); + ui.App.Driver!.Clipboard = new FakeClipboard(); + var message = ""; + + var screens = Drive(ui, () => + { + ui.App.InjectSequence(InputInjectionExtensions.RightButtonClick(ui.Find("PUT GET with query"))); + ui.Click("Copy as cURL"); + ui.App.RequestStop(); + }, + ("► OK ◄", () => + { + message = ui.App.TopRunnableView!.Text; + ui.Click("► OK ◄"); + })); + + Assert.Single(screens); + Assert.Matches(@"^Body file '.*missing-user\.json' does not exist\.$", message); + Assert.DoesNotContain("copied", ui.Window.StatusMessage ?? "", StringComparison.Ordinal); + Assert.True(string.IsNullOrEmpty(ui.App.Clipboard!.GetClipboardData())); + } + + [Fact] + public void A_request_typed_where_a_deleted_one_was_is_a_scratch_request_that_reloads_leave_alone() + { + const string Typed = "https://typed.example.com/items"; + var zoo = Path.Combine(_directory, "Zoo.postman_collection.json"); // after TermRest Demo, whose first request is open + File.WriteAllText(zoo, """ + { + "info": { "name": "Zoo", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, + "item": [{ "name": "Health", "request": { "method": "GET", "url": "https://zoo.example.com/health" } }] + } + """); + using var ui = new Harness(_directory); + ui.App.Driver!.Clipboard = new FakeClipboard(); + string copied = "", url = "", status = ""; + var modified = false; + + var screens = Drive(ui, () => + { + ui.Click("Request"); + ui.Click("Delete…"); // GET with query, open in the editor, which it empties + status = ui.Window.Editor.ScriptsTab.Status; + ui.App.InjectKey(Key.L.WithCtrl); + ui.Type(Typed); + ui.Click("Request"); + ui.Click("Copy as cURL"); + copied = ui.App.Clipboard!.GetClipboardData() ?? ""; + ui.Window.ImportCollectionFrom(zoo); // reloads Zoo + (url, modified) = (ui.Window.Editor.Spec.Url, ui.Window.Editor.IsModified); + ui.Window.Editor.MarkClean(); + ui.App.RequestStop(); + }, + ("Delete request 'GET with query'?", () => ui.Click("► Delete ◄")), + ("Unsaved changes", () => ui.Click("Don't save"))); + + Assert.Equal(2, screens.Count); + Assert.Equal("→ runs no scripts", status); + Assert.Contains(Typed, copied, StringComparison.Ordinal); + Assert.Equal((Typed, true), (url, modified)); + } + + [Fact] + public async Task A_curl_command_pasted_into_a_request_from_history_is_sent_on_its_own() + { + // Not as the request the entry was sent from: its token, and its script that adds another, are not meant for the + // host the command names. + var path = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + File.WriteAllText(path, File.ReadAllText(path).Replace("\"value\": \"{{token}}\"", "\"value\": \"folder-s3cret\"", StringComparison.Ordinal)); // the Auth folder's + var setup = PostmanCollection.Load(path); + var node = setup.FindRequest("Auth/Auth inherited from folder")!; + var withScript = node.ReadSpec(); + withScript.Scripts = new ScriptSet("tr.request.headers.set('X-Signature', 'request-s3cret')", "", ScriptLanguage.Python); + setup.UpdateRequest(node, withScript); + setup.Save(); + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + var collection = Assert.Single(ui.Workspace.Collections); + var request = collection.FindRequest("Auth/Auth inherited from folder")!; + await ui.Runner.SendAsync(collection, request, request.ReadSpec(), TestContext.Current.CancellationToken); + ScriptSet? historyScripts = null, pastedScripts = null; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/headers"); // its history entry, which takes its auth from the folder + historyScripts = ui.Window.Editor.Spec.Scripts; + ui.Click("{{baseUrl}}/headers"); + ui.App.RaisePasteEvent($"curl '{server.BaseUrl}/echo/pasted'"); + pastedScripts = ui.Window.Editor.Spec.Scripts; + ui.App.InjectKey(Key.F5); + }, + ("200 OK", () => ui.App.RequestStop()), + ("Unsaved request", () => ui.Click("Discard"))); + + Assert.Equal(2, screens.Count); + OnScreen("Request (imported)", screens[0]); + Assert.True(historyScripts!.Has(ScriptPhase.PreRequest)); + Assert.True(pastedScripts!.IsEmpty); + var sent = ui.Window.ResponsePane.Exchange!.Request; + Assert.EndsWith("/echo/pasted", sent.Url, StringComparison.Ordinal); + Assert.DoesNotContain(sent.Headers, h => h.Key.Equals("Authorization", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public async Task A_curl_command_pasted_into_a_request_from_history_on_its_way_leaves_that_request_to_arrive_on_its_own() + { + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + var collection = Assert.Single(ui.Workspace.Collections); + var request = collection.FindRequest("Basics/GET with query")!; + await ui.Runner.SendAsync(collection, request, request.ReadSpec(), TestContext.Current.CancellationToken); + ui.Runner.LocalVariables["baseUrl"] = server.BaseUrl + "/hold"; // sent again, it waits + var sending = true; + string arrived = "", pane = ""; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/get"); + ui.App.InjectKey(Key.F5); + }, + ("Sending GET", () => + { + ui.Click("{{baseUrl}}/get?foo=bar&source=termrest"); + ui.App.RaisePasteEvent($"curl '{server.BaseUrl}/echo/pasted'"); + sending = ui.Window.IsSending; // F5 would cancel that request, not send this one + pane = ui.Window.ResponsePane.StatusText; + server.Release(); + }), + ("History (2)", () => + { + arrived = ui.Window.StatusMessage; + ui.App.RequestStop(); + }), + ("Unsaved request", () => ui.Click("Discard"))); + + Assert.Equal(3, screens.Count); + Assert.False(sending); + Assert.StartsWith("No response yet", pane, StringComparison.Ordinal); // not "Sending…" for a request it no longer shows + Assert.StartsWith("Earlier request: GET 127.0.0.1 → 200", arrived, StringComparison.Ordinal); // not under the pasted one + } + + [Fact] + public void A_collection_that_no_longer_loads_is_not_reloaded_and_the_editor_goes_on_editing_its_request() + { + var path = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + using var ui = new Harness(_directory); + var edited = ""; + + var screens = Drive(ui, () => + { + File.WriteAllText(path, "<<<<<<< HEAD\n" + File.ReadAllText(path) + "\n=======\n>>>>>>> theirs\n"); + ui.Window.ImportCollectionFrom(path); // reloads it, and fails + ui.Click("{{baseUrl}}/get?foo=bar&source=termrest"); + ui.App.InjectKey(Key.End); + ui.Type("&kept=1"); + edited = ui.Screen(); + ui.Click("POST POST JSON"); + ui.App.RequestStop(); + }, + ("Import failed", () => ui.Click("► OK ◄")), + ("Unsaved changes", () => ui.Click("Don't save"))); + + Assert.Equal(2, screens.Count); + OnScreen("TermRest Demo / Basics/GET with query ●", edited); + Assert.EndsWith("&kept=1", Assert.Single(ui.Workspace.Collections).FindRequest("Basics/GET with query")!.ReadSpec().Url, StringComparison.Ordinal); + Assert.Equal("{{baseUrl}}/post", ui.Window.Editor.Spec.Url); + } + + [Fact] + public async Task Clicking_the_history_entry_being_sent_again_leaves_its_response_to_come_there() + { + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + var collection = Assert.Single(ui.Workspace.Collections); + var request = collection.FindRequest("Basics/GET with query")!; + await ui.Runner.SendAsync(collection, request, request.ReadSpec(), TestContext.Current.CancellationToken); + ui.Runner.LocalVariables["baseUrl"] = server.BaseUrl + "/hold"; // sent again, it waits + var sending = false; + var status = ""; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/get"); + ui.App.InjectKey(Key.F5); + }, + ("Sending GET", () => + { + ui.Click("/echo/get"); // its row, still the selected one + sending = ui.Window.IsSending; + server.Release(); + }), + ("History (2)", () => + { + status = ui.Window.StatusMessage; + ui.App.RequestStop(); + })); + + Assert.Equal(2, screens.Count); + Assert.True(sending); + Assert.StartsWith("GET 127.0.0.1 → 200", status, StringComparison.Ordinal); + Assert.Equal("/hold/get", System.Text.Json.Nodes.JsonNode.Parse(ui.Window.ResponsePane.Exchange!.Response!.Body)!["path"]!.GetValue()); + } + + [Fact] + public async Task A_history_request_with_masked_credentials_goes_into_a_collection_only_when_confirmed() + { + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => runner.ConfigureHistory(state)); + var auth = new AuthSpec { Type = "basic" }; + auth.Set("username", "alice"); + auth.Set("password", "typed-s3cret"); + await ui.Runner.SendAsync(PostmanCollection.Create("Scratch"), null, new HttpRequestSpec { Url = server.BaseUrl + "/echo/masked", Auth = auth }, null, + TestContext.Current.CancellationToken); + var collection = Assert.Single(ui.Workspace.Collections); + var requests = collection.AllRequests().Count(); + var afterCancel = -1; + + void SaveToCollection() + { + ui.App.InjectSequence(InputInjectionExtensions.RightButtonClick(ui.Find("200 GET /echo/masked"))); + ui.Click("Save to collection…"); + } + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/masked"); + SaveToCollection(); // asks: Enter is Cancel + afterCancel = collection.AllRequests().Count(); + SaveToCollection(); // asks, and is added + }, + ("Masked credentials", () => ui.App.InjectKey(Key.Enter)), + ("Masked credentials", () => ui.Click("Add with ***")), + ("Name (in TermRest Demo / Basics)", () => ui.Click("► OK ◄")), + ("Request — TermRest Demo / Basics/", () => + { + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.RequestStop(); + })); + + Assert.Equal(4, screens.Count); + Assert.Equal(requests, afterCancel); + Assert.Equal("***", collection.AllRequests().Single(r => r.ReadSpec().Url.EndsWith("/echo/masked", StringComparison.Ordinal)).ReadSpec().Auth?.Get("password")); + } + + [Fact] + public async Task Sending_again_a_request_that_inherited_its_auth_takes_that_auth_from_its_folder_again() + { + var path = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + File.WriteAllText(path, File.ReadAllText(path).Replace("\"value\": \"{{token}}\"", "\"value\": \"folder-s3cret\"", StringComparison.Ordinal)); // the Auth folder's + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + var collection = Assert.Single(ui.Workspace.Collections); + var request = collection.FindRequest("Auth/Auth inherited from folder")!; + await ui.Runner.SendAsync(collection, request, request.ReadSpec(), TestContext.Current.CancellationToken); + var entry = Assert.Single(ui.Runner.History!.Load()); + var notice = ""; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/headers"); + notice = ui.Window.StatusMessage; + ui.App.InjectKey(Key.F5); // sent without asking + }, + ("200 OK", () => ui.App.RequestStop())); + + Assert.Single(screens); + Assert.True(entry is { AuthInherited: true, CredentialsMasked: true }); + Assert.DoesNotContain("***", notice, StringComparison.Ordinal); + Assert.Equal(2, ui.Runner.History!.Load().Count); + Assert.Contains(new KeyValuePair("Authorization", "Bearer folder-s3cret"), ui.Window.ResponsePane.Exchange!.Request.Headers); + + // Sent as its request in the collection: the new entry inherits too, so sending it again works the same way. + var resent = ui.Runner.History!.Load()[0]; + Assert.True(resent is { AuthInherited: true, RequestPath: "Auth/Auth inherited from folder" }, $"{resent.AuthInherited} {resent.RequestPath}"); + } + + [Fact] + public async Task A_history_request_says_what_it_inherits_from_its_collection_once_that_is_reloaded() + { + var path = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + var collection = Assert.Single(ui.Workspace.Collections); + var request = collection.FindRequest("Auth/Auth inherited from folder")!; + await ui.Runner.SendAsync(collection, request, request.ReadSpec(), TestContext.Current.CancellationToken); + IEnumerable AuthNotes() => Descendants(ui.Window.Editor).OfType().Single().SubViews + .SelectMany(Descendants).OfType().Select(l => l.Text); + List before = [], after = []; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/headers"); + before = [.. AuthNotes()]; + + // A pull gives the folder an API key instead of its bearer token, and the collection is reloaded. + File.WriteAllText(path, File.ReadAllText(path).Replace("\"type\": \"bearer\"", "\"type\": \"apikey\"", StringComparison.Ordinal) + .Replace("\"bearer\": [", "\"apikey\": [", StringComparison.Ordinal)); + ui.Window.ImportCollectionFrom(path); + after = [.. AuthNotes()]; + ui.App.RequestStop(); + }); + + Assert.Empty(screens); + Assert.Contains("Currently: Bearer Token from folder 'Auth'.", before); + Assert.Contains("Currently: API Key from folder 'Auth'.", after); + } + + [Fact] + public async Task A_history_request_no_longer_runs_the_scripts_of_the_folder_its_deleted_request_was_in() + { + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + var collection = Assert.Single(ui.Workspace.Collections); + var request = collection.FindRequest("Auth/Basic auth")!; // its own auth: deleting it leaves the editor's request as it is + await ui.Runner.SendAsync(collection, request, request.ReadSpec(), TestContext.Current.CancellationToken); + collection.SetScripts(collection.FindFolder("Auth")!, new ScriptSet("console.log('folder')", "", ScriptLanguage.JavaScript)); + string before = "", after = ""; + + var screens = Drive(ui, () => + { + ui.Window.ShowRequest(request); + ui.App.InjectKey(Key.F9); + ui.Click("/echo/b"); // its history entry (/echo/basic-auth), which the folder's script runs for + before = ui.Window.Editor.ScriptsTab.Status; + ui.App.InjectKey(Key.F9); // the request is still selected in the tree + ui.App.InjectKey(Key.Delete); + after = ui.Window.Editor.ScriptsTab.Status; + ui.App.RequestStop(); + }, + ("Delete request 'Basic auth'?", () => ui.Click("► Delete ◄")), + ("Unsaved changes", () => ui.Click("Don't save"))); + + Assert.Equal(2, screens.Count); + Assert.Equal("→ runs JavaScript", before); + Assert.Equal("→ runs no scripts", after); + } + + [Fact] + public async Task A_history_request_that_inherited_its_auth_is_sent_with_that_auth_once_its_request_is_deleted() + { + AuthFolderOverridingTheCollectionsAuth(); + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + var collection = Assert.Single(ui.Workspace.Collections); + var request = collection.FindRequest("Auth/Auth inherited from folder")!; + await ui.Runner.SendAsync(collection, request, request.ReadSpec(), TestContext.Current.CancellationToken); + AuthSpec? auth = null; + var notice = ""; + + var screens = Drive(ui, () => + { + ui.Window.ShowRequest(request); + ui.App.InjectKey(Key.F9); + ui.Click("/echo/headers"); // its history entry, which takes its auth from the folder + ui.App.InjectKey(Key.F9); // the request is still selected in the tree + ui.App.InjectKey(Key.Delete); + auth = ui.Window.Editor.Spec.Auth; + notice = ui.Window.StatusMessage; + ui.App.InjectKey(Key.F9); + ui.App.InjectKey(Key.F5); // asks: its token is *** + }, + ("Delete request 'Auth inherited from folder'?", () => ui.Click("► Delete ◄")), + ("Masked credentials", () => ui.Click("Send ***")), + ("History (2)", () => ui.App.RequestStop()), + ("Unsaved changes", () => ui.Click("Don't save"))); + + Assert.Equal(4, screens.Count); + Assert.Equal(("bearer", "***"), (auth?.Type, auth?.Get("token"))); + Assert.StartsWith("⚠ 'Auth/Auth inherited from folder' is no longer in its collection", notice, StringComparison.Ordinal); + var sent = ui.Window.ResponsePane.Exchange!.Request.Headers; + Assert.Contains(new KeyValuePair("Authorization", "Bearer ***"), sent); + Assert.DoesNotContain(sent, h => h.Key == "X-Service-A"); + } + + [Fact] + public async Task A_history_request_that_inherited_its_auth_keeps_that_auth_and_its_changes_when_a_reload_loses_its_request() + { + var file = AuthFolderOverridingTheCollectionsAuth(); + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + var collection = Assert.Single(ui.Workspace.Collections); + var request = collection.FindRequest("Auth/Auth inherited from folder")!; + await ui.Runner.SendAsync(collection, request, request.ReadSpec(), TestContext.Current.CancellationToken); + var token = ui.App.Begin(ui.Window); + + ui.App.InjectKey(Key.F9); + ui.Click("/echo/headers"); + var inherited = ui.Window.Editor.Spec.Auth; + ui.Click("{{baseUrl}}/headers"); + ui.App.InjectKey(Key.End); + ui.Type("?edited=1"); + File.WriteAllText(file, File.ReadAllText(file).Replace("Auth inherited from folder", "Renamed by a pull", StringComparison.Ordinal)); + ui.Window.ImportCollectionFrom(file); // reloads it + var (auth, url, modified, status) = (ui.Window.Editor.Spec.Auth, ui.Window.Editor.Spec.Url, ui.Window.Editor.IsModified, ui.Window.StatusMessage); + ui.Window.Editor.MarkClean(); + ui.App.End(token!); + + Assert.Null(inherited); + Assert.Equal(("bearer", "***"), (auth?.Type, auth?.Get("token"))); + Assert.Equal(("{{baseUrl}}/headers?edited=1", true), (url, modified)); + Assert.StartsWith("Reloaded 'TermRest Demo' from disk. ⚠ 'Auth/Auth inherited from folder' is no longer in its collection", status, StringComparison.Ordinal); + } + + [Fact] + public async Task A_history_request_is_not_sent_as_another_request_that_has_its_name() + { + File.WriteAllText(Path.Combine(_directory, "Ops.postman_collection.json"), """ + { + "info": { "name": "Ops", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, + "item": [ + { "name": "Health", "request": { "method": "GET", "url": "{{baseUrl}}/health" } }, + { + "name": "Admin", + "auth": { "type": "bearer", "bearer": [{ "key": "token", "value": "admin-s3cret", "type": "string" }] }, + "item": [{ "name": "Health", "request": { "method": "GET", "url": "{{baseUrl}}/admin/health" } }] + } + ] + } + """); + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + var ops = ui.Workspace.Collections.Single(c => c.Name == "Ops"); + var health = ops.FindRequest("Health")!; + await ui.Runner.SendAsync(ops, health, health.ReadSpec(), TestContext.Current.CancellationToken); + + var screens = Drive(ui, () => + { + ui.Click("GET Health"); // the one sent; Admin/Health is in its folder, closed + ui.App.InjectKey(Key.Delete); + ui.App.InjectKey(Key.F9); + ui.Click("/echo/health"); + ui.App.InjectKey(Key.F5); + }, + ("Delete request 'Health'?", () => ui.Click("► Delete ◄")), + ("History (2)", () => ui.App.RequestStop()), + ("Unsaved changes", () => ui.Click("Don't save"))); + + Assert.Equal(3, screens.Count); + Assert.Equal("/echo/health", ui.Window.ResponsePane.Exchange!.Request.Uri?.AbsolutePath); + Assert.DoesNotContain(ui.Window.ResponsePane.Exchange.Request.Headers, h => h.Key == "Authorization"); + } + + [Fact] + public async Task A_history_request_whose_path_another_request_shares_is_sent_on_its_own() + { + // Names may hold slashes: Admin › v2 › Health and Admin › "v2/Health" are both Admin/v2/Health. + File.WriteAllText(Path.Combine(_directory, "Ops.postman_collection.json"), """ + { + "info": { "name": "Ops", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, + "item": [{ + "name": "Admin", + "item": [ + { + "name": "v2", + "auth": { "type": "bearer", "bearer": [{ "key": "token", "value": "admin-s3cret", "type": "string" }] }, + "item": [{ "name": "Health", "request": { "method": "GET", "url": "{{baseUrl}}/admin/health" } }] + }, + { "name": "v2/Health", "request": { "method": "GET", "url": "{{baseUrl}}/health" } } + ] + }] + } + """); + await using var server = await LocalEchoServer.StartAsync(); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => + { + runner.LocalVariables["baseUrl"] = server.BaseUrl + "/echo"; + runner.ConfigureHistory(state); + }); + var ops = ui.Workspace.Collections.Single(c => c.Name == "Ops"); + var health = ops.AllRequests().Single(r => r.Name == "v2/Health"); + await ui.Runner.SendAsync(ops, health, health.ReadSpec(), TestContext.Current.CancellationToken); + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/health"); + ui.App.InjectKey(Key.F5); + }, + ("History (2)", () => ui.App.RequestStop())); + + Assert.Single(screens); + Assert.Equal("/echo/health", ui.Window.ResponsePane.Exchange!.Request.Uri?.AbsolutePath); + Assert.DoesNotContain(ui.Window.ResponsePane.Exchange.Request.Headers, h => h.Key == "Authorization"); + } + + [Fact] + public async Task A_history_request_is_sent_again_in_its_own_collection_when_another_has_its_name() + { + // An updated export, imported next to the collection it updates: both are 'Orders API', with other hosts and tokens. + await using var server = await LocalEchoServer.StartAsync(); + File.WriteAllText(Path.Combine(_directory, "Orders API.postman_collection.json"), OrdersApi(server.BaseUrl + "/echo/v1", "v1-s3cret")); + var export = Path.Combine(_directory, "exports", "Orders API.postman_collection.json"); + Directory.CreateDirectory(Path.GetDirectoryName(export)!); + File.WriteAllText(export, OrdersApi(server.BaseUrl + "/echo/v2", "v2-s3cret")); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => runner.ConfigureHistory(state)); + var token = ui.App.Begin(ui.Window); + ui.Window.ImportCollectionFrom(export); + ui.App.End(token!); + var update = ui.Workspace.Collections[^1]; + var request = update.FindRequest("Get order")!; + await ui.Runner.SendAsync(update, request, request.ReadSpec(), TestContext.Current.CancellationToken); + TermRest.Core.Http.HttpExchange? resent = null; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/v2/order"); // the sidebar cuts the row off + ui.App.InjectKey(Key.F5); + }, + ("History (2)", () => + { + resent = ui.Window.ResponsePane.Exchange; + ui.App.InjectSequence(InputInjectionExtensions.RightButtonClick(ui.Find("/echo/v2/order"))); + ui.Click("Go to request in collection"); + ui.App.InjectKey(Key.F5); + }), + ("200 OK", () => ui.App.RequestStop())); + + Assert.Equal(2, screens.Count); + Assert.Equal("Orders API (2).postman_collection.json", Path.GetFileName(update.FilePath)); + Assert.Equal("/echo/v2/orders/1", resent?.Request.Uri?.AbsolutePath); + Assert.Contains(new KeyValuePair("Authorization", "Bearer v2-s3cret"), resent!.Request.Headers); + Assert.Equal("Orders API (2).postman_collection.json", ui.Runner.History!.Load()[0].CollectionFile); + + // Go to request opened the request in the update: sent from there, it goes to the update's host. + Assert.Equal("/echo/v2/orders/1", ui.Window.ResponsePane.Exchange!.Request.Uri?.AbsolutePath); + } + + [Fact] + public async Task A_history_request_from_an_earlier_version_is_sent_on_its_own_when_collections_share_its_name() + { + await using var server = await LocalEchoServer.StartAsync(); + File.WriteAllText(Path.Combine(_directory, "Orders API.postman_collection.json"), OrdersApi(server.BaseUrl + "/echo/v1", "v1-s3cret")); + File.WriteAllText(Path.Combine(_directory, "Orders API (2).postman_collection.json"), OrdersApi(server.BaseUrl + "/echo/v2", "v2-s3cret")); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => runner.ConfigureHistory(state)); + var original = ui.Workspace.Collections.Single(c => Path.GetFileName(c.FilePath) == "Orders API.postman_collection.json"); + var request = original.FindRequest("Get order")!; + await ui.Runner.SendAsync(original, request, request.ReadSpec(), TestContext.Current.CancellationToken); + + // As earlier versions wrote it: the entry names its collection, not the collection's file. + var history = ui.Runner.History!.FilePath; + File.WriteAllText(history, System.Text.RegularExpressions.Regex.Replace(File.ReadAllText(history), "\"collectionFile\":\"[^\"]*\",", "")); + var status = ""; + AuthSpec? auth = null; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F9); + ui.Click("/echo/v1/order"); + (status, auth) = (ui.Window.StatusMessage, ui.Window.Editor.Spec.Auth); + ui.App.InjectKey(Key.F5); // asks: its token is *** + }, + ("Masked credentials", () => ui.App.InjectKey(Key.Enter)), + ("Request (from history", () => ui.App.RequestStop())); + + Assert.Equal(2, screens.Count); + Assert.Null(Assert.Single(ui.Runner.History.Load()).CollectionFile); + Assert.StartsWith("⚠ 2 collections are named 'Orders API' and which one this request was sent from is not known: it is sent on its own. Credentials are ***", + status, StringComparison.Ordinal); + Assert.Equal(("bearer", "***"), (auth?.Type, auth?.Get("token"))); + } + + [Fact] + public void Save_as_asks_before_replacing_a_file_and_says_when_it_saved_only_the_start_of_the_body() + { + // The save dialog may open on the workspace folder, where a click picks a collection. + var file = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + var collection = File.ReadAllText(file); + var copy = Path.Combine(_directory, "history-copy.txt"); + var state = Path.Combine(_directory, ".state"); + using var ui = new Harness(_directory, runner => runner.ConfigureHistory(state)); + var cut = new TermRest.Core.Http.HttpExchange(new TermRest.Core.Http.PreparedRequest { Method = "GET", Url = "https://api.example.com/log" }) + { + Response = new TermRest.Core.Http.ResponseSnapshot { StatusCode = 200, ReasonPhrase = "OK", ContentType = "text/plain", Body = "the start"u8.ToArray(), BodyTruncated = true }, + }; + var entry = new TermRest.Core.History.HistoryEntry + { + Id = "cut", + Time = DateTimeOffset.Now, + Method = "GET", + Url = "https://api.example.com/log", + Item = new System.Text.Json.Nodes.JsonObject { ["name"] = "Log", ["request"] = new System.Text.Json.Nodes.JsonObject { ["method"] = "GET", ["url"] = "https://api.example.com/log" } }, + Status = 200, + BodySaved = true, + BodyTruncated = true, + }; + ui.Runner.History!.Add(entry, "token=***"u8.ToArray()); + var (afterCancel, replaced, fromHistory) = ("", "", ""); + + void Choose(string path) + { + ui.App.RaisePasteEvent(path); + ui.App.InjectKey(Key.Enter); + } + + void ClickReplace() + { + // The button, not the question's "Replace it?" above it. + var lines = ui.Screen().Split('\n'); + var y = Array.FindLastIndex(lines, line => line.Contains("Replace", StringComparison.Ordinal)); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(lines[y].IndexOf("Replace", StringComparison.Ordinal), y))); + } + + var screens = Drive(ui, () => + { + ui.Window.ResponsePane.ShowExchange(cut); + ui.Click("Save as…"); // returns once it is answered + afterCancel = File.ReadAllText(file); + ui.Click("Save as…"); + replaced = ui.Window.StatusMessage; + ui.Window.OpenHistoryEntry(entry); + ui.Click("Save as…"); + fromHistory = ui.Window.StatusMessage; + ui.App.RequestStop(); + }, + ("Filename (▲)", () => Choose(file)), + ("exists.", () => ui.App.InjectKey(Key.Enter)), // Cancel + ("Filename (▲)", () => Choose(file)), + ("exists.", ClickReplace), + ("Filename (▲)", () => Choose(copy))); + + Assert.Equal(5, screens.Count); + Assert.Equal(collection, afterCancel); + Assert.Equal("the start", File.ReadAllText(file)); + Assert.Equal($"⚠ Saved 9 B to {file}: only the start of the body, cut at the maximum response size (Tools > Settings)", replaced); + Assert.Equal("token=***", File.ReadAllText(copy)); + Assert.Equal($"⚠ Saved 9 B to {copy}: only the start of the body, as the history keeps it (secrets masked as ***)", fromHistory); + } + + /// + /// The sample collection with auth for another service on the collection, which the Auth folder overrides with a + /// bearer token typed in (so the history masks it). Returns the collection's file. + /// + private string AuthFolderOverridingTheCollectionsAuth() + { + var file = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + var root = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(file))!; + root["auth"] = System.Text.Json.Nodes.JsonNode.Parse(""" + { "type": "apikey", "apikey": [{ "key": "key", "value": "X-Service-A" }, { "key": "value", "value": "service-a-s3cret" }, { "key": "in", "value": "header" }] } + """); + root["item"]![1]!["auth"]!["bearer"]![0]!["value"] = "folder-s3cret"; + File.WriteAllText(file, root.ToJsonString()); + return file; + } + + /// A collection named 'Orders API' whose request goes to with the bearer token it inherits. + private static string OrdersApi(string baseUrl, string token) => """ + { + "info": { "name": "Orders API", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, + "auth": { "type": "bearer", "bearer": [{ "key": "token", "value": "TOKEN", "type": "string" }] }, + "item": [{ "name": "Get order", "request": { "method": "GET", "url": "{{baseUrl}}/orders/1" } }], + "variable": [{ "key": "baseUrl", "value": "BASE_URL" }] + } + """.Replace("TOKEN", token, StringComparison.Ordinal).Replace("BASE_URL", baseUrl, StringComparison.Ordinal); + + [Fact] + public void Recording_does_not_start_while_the_workspace_settings_cannot_be_read() + { + Directory.CreateDirectory(Path.Combine(_directory, ".termrest")); + File.WriteAllText(Path.Combine(_directory, ".termrest", "settings.json"), "{ \"recordingRedact\": [\"X-Tenant\" "); + using var ui = new Harness(_directory); + RequestRecorder? recorder = null; + + var screens = Drive(ui, () => + { + ui.App.InjectKey(Key.F12); + recorder = ui.Runner.Recorder; + ui.Runner.Recorder = null; // one that started anyway is not asked about when closing + ui.App.RequestStop(); + }, + ("recordingRedact", () => ui.Click("► OK ◄"))); + recorder?.Discard(); + + Assert.Single(screens); + Assert.Null(recorder); + } + + [Fact] + public void Tabs_take_their_width_and_the_tab_key_still_moves_to_the_next_field() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + ui.Window.ResponsePane.ShowExchange(TextResponse("id\tname\n1\tAda")); + var left = new List(); + ui.Click("name"); + var screen = ui.Screen(); + var response = Assert.IsType(ui.Window.MostFocused); + foreach (var key in (Key[])[Key.Tab, Key.Tab.WithShift]) + { + response.SetFocus(); + ui.App.InjectKey(key); + left.Add(ui.Window.MostFocused != response); + } + + ui.Click("POST POST JSON"); + ui.Click("Body"); + ui.Click("Ada Lovelace"); + var body = Assert.IsType(ui.Window.MostFocused); + ui.App.InjectKey(Key.Tab); + left.Add(ui.Window.MostFocused != body); + var (raw, modified) = (body.GetText(), ui.Window.Editor.IsModified); + ui.App.InjectKey(Key.S.WithCtrl); // closing must not ask, even if this fails + ui.App.End(token!); + + OnScreen("id name", screen); // a tab moves on to the next multiple of 4 columns + OnScreen("1 Ada", screen); + Assert.Equal([true, true, true], left); + Assert.DoesNotContain('\t', raw); // no tab typed + Assert.False(modified); + } + + [Fact] + public void A_lone_carriage_return_is_a_line_break_and_nothing_next_to_it_is_lost() + { + var file = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + File.WriteAllText(file, File.ReadAllText(file).Replace("Ada Lovelace", "Ada\\rLovelace", StringComparison.Ordinal)); + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + ui.App.Driver!.Clipboard = new FakeClipboard(); + ui.Window.ResponsePane.ShowExchange(TextResponse("10%\r20%\ndone")); + ui.Click("Copy"); + var (copied, response) = (ui.App.Clipboard!.GetClipboardData(), ui.Screen()); + + ui.Click("POST POST JSON"); + ui.Click("Body"); + var body = ui.Screen(); + ui.Click("Lovelace"); + ui.Type("!"); + var edited = ui.Window.Editor.Spec.Body.Raw; + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.End(token!); + + Assert.Equal(At(response, "10%") with { Y = At(response, "10%").Y + 1 }, At(response, "20%")); + Assert.Equal("10%\r20%\ndone", copied); // as it came, not as shown + Assert.Equal(At(body, "\"name\": \"Ada").Y + 1, At(body, "Lovelace\",").Y); + const string Expected = "{\n \"id\": \"{{$guid}}\",\n \"name\": \"Ada\n!Lovelace\",\n \"sentAt\": \"{{$isoTimestamp}}\"\n}"; + Assert.Equal(Expected, edited); + Assert.Equal(Expected, PostmanCollection.Load(file).FindRequest("Basics/POST JSON")!.ReadSpec().Body.Raw); + } + + [Fact] + public void A_response_header_too_long_for_the_pane_is_marked_cut_and_opens_whole_to_read_and_copy() + { + const string Value = "Bearer error=\"invalid_token\", error_description=\"The token expired at '11/13/2026 21:32:45'\", scope=\"orders.read orders.write\", realm=\"orders\""; + using var ui = new Harness(_directory); + ui.App.Driver!.Clipboard = new FakeClipboard(); + string table = "", shown = "", titled = ""; + + var screens = Drive(ui, () => + { + ui.Window.ResponsePane.ShowExchange(TextResponse("ok", new("WWW-Authenticate", Value), new("X_Request_Id", "7f3a"))); + var tabs = ui.Find("Timeline"); // the response's tabs: the request has a Headers tab too + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(ui.Screen().Split('\n')[tabs.Y].IndexOf("Headers", StringComparison.Ordinal), tabs.Y))); + table = ui.Screen(); + ui.Click("WWW-Authenticate"); + ui.App.InjectKey(Key.Enter); // returns once the dialog is closed + ui.Click("X_Request_Id"); + ui.App.InjectKey(Key.Enter); + ui.App.RequestStop(); + }, + ("realm=\"orders\"", () => + { + shown = ui.Screen(); + ui.Click("► Copy ◄"); + }), + ("► Copy ◄", () => + { + titled = ui.Screen(); + ui.App.InjectKey(Key.Esc); + })); + + Assert.Equal(2, screens.Count); + var row = table.Split('\n').Single(l => l.Contains("WWW-Authenticate", StringComparison.Ordinal)); + Assert.Contains("…", row, StringComparison.Ordinal); + Assert.DoesNotContain("realm", table, StringComparison.Ordinal); + OnScreen(Value, Unwrapped(shown)); + Assert.Equal(Value, ui.App.Clipboard!.GetClipboardData()); + Assert.Equal("The value of WWW-Authenticate copied to the clipboard.", ui.Window.StatusMessage); + OnScreen("┥X_Request_Id┝", titled); // the name as written, its _ no hotkey + } + + [Fact] + public void Keys_that_delete_nothing_leave_the_request_unmodified() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + ui.App.Driver!.Clipboard = new FakeClipboard(); + ui.Click("Scripts"); + var label = ui.Find("Pre-request (before sending)"); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(label.X, label.Y + 1))); + var script = Assert.IsType(ui.Window.MostFocused); + foreach (var key in (Key[])[Key.Backspace, Key.Delete, Key.Backspace.WithCtrl, Key.Delete.WithCtrl, Key.K.WithCtrl, Key.Backspace.WithCtrl.WithShift]) + { + ui.App.InjectKey(key); + } + + var emptyScript = (script.GetText(), ui.Window.Editor.IsModified); + ui.Click("POST POST JSON"); + ui.Click("Body"); + ui.Click("Ada Lovelace"); + foreach (var key in (Key[])[Key.Home.WithCtrl, Key.Backspace, Key.Backspace.WithCtrl, Key.End.WithCtrl, Key.Delete, Key.Delete.WithCtrl]) + { + ui.App.InjectKey(key); + } + + var (body, unsaved, screen) = (ui.Window.Editor.IsModified, ui.Workspace.HasUnsavedChanges, ui.Screen()); + ui.App.InjectKey(Key.S.WithCtrl); // closing must not ask, even if this fails + ui.App.End(token!); + + Assert.Equal(("", false), emptyScript); + Assert.False(body); + Assert.False(unsaved); + OnScreen("Request — TermRest Demo / Basics/POST JSON", screen); + Assert.DoesNotContain("POST JSON ●", screen, StringComparison.Ordinal); + } + + [Fact] + public void Characters_the_editor_keeps_composed_are_no_edit_and_a_script_left_alone_keeps_its_bytes() + { + // Terminal.Gui keeps each character composed (NFC): a decomposed é (as macOS file names have it) and the ohm sign + // come back from an editor changed. U+FFFE (a byte order mark read the wrong way) is one normalizing refuses. + const string Decomposed = "Cafe\u0301 \u2126"; + const string Body = $"{{\"name\": \"{Decomposed}\", \"bom\": \"\uFFFE\"}}"; + var path = Path.Combine(_directory, "TermRest Demo.postman_collection.json"); + var setup = PostmanCollection.Load(path); + var request = setup.FindRequest("Basics/POST JSON")!; + var spec = request.ReadSpec(); + spec.Body.Raw = Body; + spec.Scripts = new ScriptSet($"# {Decomposed}", $"# {Decomposed}", ScriptLanguage.Python); + setup.UpdateRequest(request, spec); + setup.Save(); + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + ui.Click("POST POST JSON"); + ui.Click("Body"); + ui.Click("\"name\""); + foreach (var key in (Key[])[Key.Home.WithCtrl, Key.Backspace, Key.End.WithCtrl, Key.Delete]) + { + ui.App.InjectKey(key); + } + + var body = (ui.Window.Editor.IsModified, ui.Workspace.HasUnsavedChanges, ui.Window.Editor.Spec.Body.Raw); + ui.Click("Scripts"); + var label = ui.Find("Pre-request (before sending)"); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(label.X, label.Y + 1))); + ui.App.InjectKey(Key.Home.WithCtrl); + ui.Type("x"); + var scripts = ui.Window.Editor.Spec.Scripts.For(ScriptLanguage.Python); + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.End(token!); + + Assert.Equal((false, false, Body), body); + Assert.Equal($"x# {Decomposed.Normalize()}", scripts.PreRequest); // edited: as the editor holds it + Assert.Equal($"# {Decomposed}", scripts.Test); + Assert.Equal($"# {Decomposed}", PostmanCollection.Load(path).FindRequest("Basics/POST JSON")!.ReadSpec().Scripts.For(ScriptLanguage.Python).Test); + } + + [Fact] + public void Ctrl_N_makes_a_new_request_from_lists_and_tables_and_Insert_adds_rows() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + var dialogs = new List(); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + // Runs only while a dialog is open: notes what it shows and closes it. + dialogs.Add(ui.Screen()); + ui.App.InjectKey(Key.Esc); + return true; + }); + var pressed = new List(); + void CtrlN() + { + pressed.Add(ui.Window.MostFocused?.GetType().Name ?? ""); + ui.App.InjectKey(Key.N.WithCtrl); + } + + ui.Click("GET GET with query"); + CtrlN(); + ui.Click("debug"); + CtrlN(); + ui.Click("Headers"); + ui.Click("Accept"); + CtrlN(); + ui.App.InjectKey(Key.InsertChar); + ui.Click("Auth"); + ui.Click("Inherit auth from parent"); + CtrlN(); + ui.Click("GET Status by path"); + ui.Click("Params"); + Descendants(ui.Window).OfType().Single(t => t.Entries.Any(e => e.Key == "code")).SubViews.OfType().Single().SetFocus(); + CtrlN(); + ui.App.InjectKey(Key.InsertChar); // path variables follow the URL: nothing to add or remove + ui.App.InjectKey(Key.Delete); + var pathVariables = ui.Window.Editor.Spec.PathVariables.Select(v => v.Key).ToList(); + ui.Window.ResponsePane.ShowExchange(TextResponse("ok", new KeyValuePair("X-Trace", "7"))); + var tabs = ui.Find("Timeline"); // the response's tabs: the request has a Headers tab too + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(ui.Screen().Split('\n')[tabs.Y].IndexOf("Headers", StringComparison.Ordinal), tabs.Y))); + ui.Click("X-Trace"); + CtrlN(); + ui.App.InjectKey(Key.F9); + ui.Window.HistoryPane.SetEntries(HistoryEntries(3), "No requests sent yet."); + ui.Click("/items/1"); + var opened = ui.Window.HistoryPane.Selected; + CtrlN(); + var (selected, url) = (ui.Window.HistoryPane.Selected, ui.Window.Editor.Spec.Url); + var unsaved = ui.Workspace.HasUnsavedChanges || ui.Window.Editor.IsModified; + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.End(token!); + + Assert.Equal(["TreeView`1", "TableView", "TableView", "ListView", "TableView", "TableView", "ListView"], pressed); + Assert.Equal(8, dialogs.Count); + Assert.Equal(7, dialogs.Count(d => d.Contains("Name (in TermRest Demo / Basics)", StringComparison.Ordinal))); + OnScreen("Add header", dialogs[3]); // Insert, after the third Ctrl+N + Assert.Equal(["code"], pathVariables); + Assert.Equal(opened, selected); // not the next entry + Assert.Equal("https://api.example.com/items/1", url); + Assert.False(unsaved); + } + + [Fact] + public void The_history_filter_says_when_nothing_matches_even_after_scrolling_down() + { + using var ui = new Harness(_directory); + var token = ui.App.Begin(ui.Window); + ui.App.InjectKey(Key.F9); + ui.Window.HistoryPane.SetEntries(HistoryEntries(100), "No requests sent yet."); + var list = ui.Find("/items/0"); + for (var i = 0; i < 80; i++) + { + ui.App.InjectMouse(new Mouse { ScreenPosition = list, Flags = MouseFlags.WheeledDown }); + } + + var scrolled = ui.Screen(); + var filter = ui.Find("Filter:"); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(filter.X + 9, filter.Y))); + ui.Type("no-such-request"); + var (rows, selected, screen) = (ui.Window.HistoryPane.Rows.ToList(), ui.Window.HistoryPane.Selected, ui.Screen()); + ui.App.End(token!); + + Assert.DoesNotContain("/items/0 ", scrolled, StringComparison.Ordinal); + Assert.Equal(["No match."], rows); + Assert.Null(selected); + OnScreen("No match.", screen); + } + + [Fact] + public void A_typed_body_file_is_looked_up_in_the_background_once_typing_pauses() + { + using var ui = new Harness(_directory); + var path = Path.Combine(_directory, "order.json"); + File.WriteAllText(path, "{\"item\": 1}"); + string typing = "", found = "", missing = ""; + var step = 0; + var deadline = DateTime.UtcNow.AddSeconds(20); + ui.App.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + if (DateTime.UtcNow > deadline) + { + ui.Window.Editor.MarkClean(); + ui.App.RequestStop(); + return false; + } + + switch (step) + { + case 0: + ui.Click("POST POST JSON"); + ui.Click("Body"); + ui.Click("○ file"); + var label = ui.Find("File:"); + ui.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(label.X + 8, label.Y))); + ui.Type(path); + typing = ui.Window.BodyFileStatus; // the disk is not read while typing + step = 1; + break; + case 1 when ui.Window.BodyFileStatus.StartsWith("order.json", StringComparison.Ordinal): + found = ui.Window.BodyFileStatus; + ui.Type("x"); + step = 2; + break; + case 2 when ui.Window.BodyFileStatus.StartsWith('✗'): + missing = ui.Window.BodyFileStatus; + ui.App.InjectKey(Key.S.WithCtrl); + ui.App.RequestStop(); + return false; + } + + return true; + }); + + ui.App.Run(ui.Window); + + Assert.Equal($"Looking for {path}…", typing); + Assert.Equal("order.json · 11 B · sent as it is", found); + Assert.Equal($"✗ {path}x does not exist.", missing); + } + + [Fact] + public void A_body_file_outside_the_workspace_is_not_looked_at_until_files_from_outside_are_allowed() + { + // As Send has it: on Windows, looking at \\server\share\x signs in to that server with the user's credentials. + var secret = Path.Combine(TestFiles.NewTempDirectory(), "credentials"); + File.WriteAllText(secret, "s3cret"); + using var ui = new Harness(_directory); + string Shown(BodyMode mode) + { + ui.Window.Editor.Load(new HttpRequestSpec { Url = "https://api.example.com/upload", Body = new RequestBody { Mode = mode, Raw = "{}", FileSrc = secret } }); + return ui.Window.BodyFileStatus; + } + + var raw = Shown(BodyMode.Raw); // a raw body keeps a file path it doesn't send + var file = Shown(BodyMode.File); + ui.Runner.OutsideFilesAllowed = true; + ui.Window.Editor.RefreshBodyFile(); + + Assert.Equal("", raw); + Assert.Equal($"✗ {secret} is outside the workspace folder: it is not sent unless you allow files from outside it (Tools › Settings…).", file); + Assert.Equal("credentials · 6 B · sent as it is", ui.Window.BodyFileStatus); + } + + /// A plain-text response, as if it had just arrived. + private static TermRest.Core.Http.HttpExchange TextResponse(string body, params KeyValuePair[] headers) => + new(new TermRest.Core.Http.PreparedRequest { Method = "GET", Url = "https://api.example.com/log" }) + { + Response = new TermRest.Core.Http.ResponseSnapshot + { + StatusCode = 200, + ReasonPhrase = "OK", + ContentType = "text/plain", + Body = System.Text.Encoding.UTF8.GetBytes(body), + Headers = [new("Content-Type", "text/plain"), .. headers], + }, + }; + + private static List HistoryEntries(int count) => + [ + .. Enumerable.Range(0, count).Select(i => new TermRest.Core.History.HistoryEntry + { + Id = i.ToString(System.Globalization.CultureInfo.InvariantCulture), + Time = DateTimeOffset.Now, + Method = "GET", + Url = $"https://api.example.com/items/{i}", + Item = new System.Text.Json.Nodes.JsonObject + { + ["name"] = $"Item {i}", + ["request"] = new System.Text.Json.Nodes.JsonObject { ["method"] = "GET", ["url"] = $"https://api.example.com/items/{i}" }, + }, + Status = 200, + }), + ]; + /// What the main loop would show: draws only what changed ( redraws everything). private static string Drawn(Harness ui) { diff --git a/tests/TermRest.Tui.Tests/ResponseViewTests.cs b/tests/TermRest.Tui.Tests/ResponseViewTests.cs new file mode 100644 index 0000000..4841b97 --- /dev/null +++ b/tests/TermRest.Tui.Tests/ResponseViewTests.cs @@ -0,0 +1,281 @@ +using System.Diagnostics; +using System.Drawing; +using System.Text; +using System.Text.Json.Nodes; +using Terminal.Gui.App; +using Terminal.Gui.Drivers; +using Terminal.Gui.Testing; +using Terminal.Gui.ViewBase; +using Terminal.Gui.Views; +using TermRest.Core.History; +using TermRest.Core.Http; +using TermRest.Core.Scripting; +using TermRest.Tui.Views; +using Xunit; + +namespace TermRest.Tui.Tests; + +/// The response pane's Body tab with large bodies: cut for display, formatted in the background, copied whole. +[Collection("TUI")] +public sealed class ResponseViewTests : IDisposable +{ + private readonly IApplication _app; + private readonly Window _window = new() { Width = Dim.Fill(), Height = Dim.Fill() }; + private readonly ResponseView _view = new(); + private readonly List _notices = []; + private readonly SessionToken? _token; + + public ResponseViewTests() + { + _app = Application.Create(); + _app.Init(DriverRegistry.Names.ANSI); + _app.Driver!.SetScreenSize(100, 30); + _app.Driver.Clipboard = new FakeClipboard(); + _view.Notice += (_, notice) => _notices.Add(notice); + _window.Add(_view); + _token = _app.Begin(_window); + _app.LayoutAndDraw(forceRedraw: true); + } + + private static HttpExchange Exchange(byte[] body, string contentType = "application/json", bool truncated = false) => + new(new PreparedRequest { Method = "GET", Url = "https://api.example.com/items" }) + { + Response = new ResponseSnapshot + { + StatusCode = 200, + ReasonPhrase = "OK", + ContentType = contentType, + Body = body, + BodyTruncated = truncated, + Headers = [new("Content-Type", contentType)], + }, + }; + + /// A minified JSON array of about bytes, as APIs send it. + private static byte[] Items(int size) + { + var json = new StringBuilder("["); + for (var i = 0; json.Length < size; i++) + { + json.Append(i > 0 ? "," : "").Append("{\"id\":").Append(i).Append(",\"name\":\"Item ").Append(i).Append("\",\"tags\":[\"alpha\",\"beta\"]}"); + } + + return Encoding.UTF8.GetBytes(json.Append(']').ToString()); + } + + /// Runs the main loop's work until , for at most. + private void RunUntil(Func done, int seconds = 30) + { + var deadline = DateTime.UtcNow.AddSeconds(seconds); + while (!done() && DateTime.UtcNow < deadline) + { + _app.TimedEvents!.RunTimers(); + Thread.Sleep(10); + } + } + + /// Waits a few seconds at most for background work to come back to the main loop, and runs it. + private void RunBackgroundWork() + { + RunUntil(() => _app.TimedEvents!.Timeouts.Count > 0, seconds: 5); + RunUntil(() => _app.TimedEvents!.Timeouts.Count == 0); + } + + private void Click(string text) + { + _app.LayoutAndDraw(forceRedraw: true); + var lines = (_app.Driver!.ToString() ?? "").Split('\n'); + var y = Array.FindIndex(lines, line => line.Contains(text, StringComparison.Ordinal)); + Assert.True(y >= 0, $"'{text}' is not on screen"); + _app.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(lines[y].IndexOf(text, StringComparison.Ordinal), y))); + } + + [Fact] + public void A_large_body_is_formatted_in_the_background_shown_cut_with_a_note_and_copied_whole() + { + var body = Items(3_000_000); + var whole = BodyFormatter.Format(body, "application/json"); + + var watch = Stopwatch.StartNew(); + _view.ShowExchange(Exchange(body)); + var returned = watch.Elapsed; + var placeholder = _view.BodyText; + RunUntil(() => _view.BodyText != placeholder); + var shown = _view.BodyText; + Click("Copy"); + RunUntil(() => _notices.Count > 1); + + Assert.True(returned < TimeSpan.FromSeconds(1), $"ShowExchange took {returned}"); // formatting 3 MB took 1 to 2 s + Assert.Equal("Formatting…", placeholder); + var note = shown.LastIndexOf("\n\n… showing the first 1.0 MB of ", StringComparison.Ordinal); + Assert.True(note > ResponseView.MaxShownLength - 4096, $"cut at {note}"); + Assert.True(note <= ResponseView.MaxShownLength); + Assert.StartsWith(shown[..note], whole, StringComparison.Ordinal); + Assert.Equal('\n', whole[note]); // at the end of a line + Assert.EndsWith(": Copy and Save as… give the whole body", shown, StringComparison.Ordinal); + Assert.Equal(["Copying the response body…", "Response body copied to the clipboard."], _notices); + Assert.Equal(whole, _app.Clipboard!.GetClipboardData()); + } + + [Fact] + public void A_body_formatted_in_the_background_is_not_shown_once_another_body_replaced_it() + { + var large = Exchange(Items(2_000_000)); + + _view.ShowExchange(large); + _view.ShowExchange(Exchange("{\"ok\":true}"u8.ToArray())); + RunBackgroundWork(); + var afterAnother = _view.BodyText; + + _view.ShowExchange(large); + Click("Pretty: on"); + RunUntil(() => _view.BodyText != "Formatting…"); + RunBackgroundWork(); + var afterPrettyOff = _view.BodyText; + + Assert.Equal("{\n \"ok\": true\n}", afterAnother); + Assert.Equal(ResponseView.Shown(large.Response!, pretty: false), afterPrettyOff); + } + + [Fact] + public void A_long_body_is_cut_at_a_line_break_when_one_is_near_and_never_inside_a_character() + { + static string Shown(string text, bool truncated = false) => + ResponseView.Shown(Exchange(Encoding.UTF8.GetBytes(text), "text/plain", truncated).Response!, pretty: true); + + var lines = new string('a', ResponseView.MaxShownLength - 100) + "\r\n" + new string('b', 300); + var line = new string('a', ResponseView.MaxShownLength - 1) + "😀 and more"; + var small = "short body"; + + var cutAtLine = Shown(lines); + var cutBeforePair = Shown(line, truncated: true); + + Assert.Equal(new string('a', ResponseView.MaxShownLength - 100) + "\n\n… showing the first 1.0 MB of 1.0 MB: Copy and Save as… give the whole body", cutAtLine); + Assert.Equal(new string('a', ResponseView.MaxShownLength - 1) + "\n\n… showing the first 1.0 MB of 1.0 MB (truncated): Copy and Save as… give the whole body", cutBeforePair); + Assert.Equal(small, Shown(small)); + Assert.Equal(small + "\n\n… (truncated)", Shown(small, truncated: true)); + } + + [Fact] + public void What_scripts_wrote_is_shown_up_to_the_same_length_as_a_body() + { + // 2,000 lines of 4,000 characters (two phases' worth): about 700 MB in the editor, and a second or two to load. + var scripts = new ScriptResults(); + scripts.Logs.AddRange(Enumerable.Range(0, 2000).Select(i => new ScriptLog("test", "request 'Items'", $"{i:D4} " + new string('x', 3995)))); + var exchange = Exchange("[]"u8.ToArray()); + exchange.Scripts = scripts; + + _view.ShowExchange(exchange); + + var shown = _view.ScriptsText; + Assert.InRange(shown.Length, ResponseView.MaxShownLength - 4096, ResponseView.MaxShownLength + 100); + Assert.EndsWith(" the scripts wrote", shown, StringComparison.Ordinal); + Assert.Contains("0000 xxx", shown, StringComparison.Ordinal); + Assert.DoesNotContain("1999 xxx", shown, StringComparison.Ordinal); + } + + [Fact] + public void A_JSON_body_that_cannot_be_pretty_printed_is_shown_as_received() + { + const string Json = "{\"a\":\"\\ud800 lone surrogate\"}"; + + _view.ShowExchange(Exchange(Encoding.UTF8.GetBytes(Json))); + + Assert.Equal(Json, _view.BodyText); + } + + [Fact] + public void The_timeline_cuts_a_long_request_body_before_a_character_it_would_cut_in_two() + { + var request = new PreparedRequest + { + Method = "POST", + Url = "https://api.example.com/items", + Body = new PreparedBody { Kind = PreparedBodyKind.Text, Text = new string('a', 3999) + "😀 and more" }, + }; + var start = $"POST https://api.example.com/items\n\n{new string('a', 3999)}\n… (truncated)\n"; + + _view.ShowSending(request); + var sending = _view.TimelineText; + _view.ShowExchange(new HttpExchange(request) { ErrorMessage = "Connection refused" }); + var sent = _view.TimelineText; + Click("Timeline"); + _app.LayoutAndDraw(forceRedraw: true); + + Assert.StartsWith(start, sending, StringComparison.Ordinal); + Assert.StartsWith(start, sent, StringComparison.Ordinal); + Assert.Contains("POST https://api.example.com/items", _app.Driver!.ToString(), StringComparison.Ordinal); + } + + [Fact] + public void A_response_from_the_history_says_what_the_history_does_not_keep() + { + // An https request with tests and a client certificate, whose 3 MB response the history keeps the start of. + var entry = new HistoryEntry + { + Id = "cut", + Time = DateTimeOffset.Now, + Method = "GET", + Url = "https://api.example.com/items", + Item = new JsonObject { ["name"] = "Items" }, + Status = 200, + Reason = "OK", + HttpVersion = "1.1", + Size = 3 * 1024 * 1024, + ContentType = "text/plain", + BodySaved = true, + BodyTruncated = true, + ClientCertificate = "client.example.com (expires 2027-06-30, 0A1B2C3D…)", + Timing = new TimingBreakdown { Tls = TimeSpan.FromMilliseconds(35), Total = TimeSpan.FromMilliseconds(120) }, + }; + var fromHistory = entry.ToExchange("the start"u8.ToArray()); + var live = new HttpExchange(new PreparedRequest { Method = "GET", Url = entry.Url, Uri = new Uri(entry.Url) }) + { + Response = fromHistory.Response, + Timing = entry.Timing, + }; + + _view.ShowExchange(fromHistory, fromHistory: true); + var shown = (_view.StatusText, _view.BodyText, _view.TlsText, _view.ScriptsText, _view.TimelineText); + _view.ShowExchange(fromHistory); // put back, as when the next request could not be sent + var shownAgain = (_view.StatusText, _view.BodyText, _view.TlsText, _view.ScriptsText, _view.TimelineText); + _view.ShowExchange(entry.ToExchange(null), fromHistory: true); // its copy of the body is gone + var withoutBody = (_view.StatusText, _view.BodyText); + _app.Clipboard!.SetClipboardData("the user's"); + Click("Copy"); // neither copies nor saves nothing in its place + Click("Save as…"); + RunUntil(() => _notices.Count >= 2, seconds: 5); + var withoutBodyNotices = _notices.ToList(); + var clipboard = _app.Clipboard.GetClipboardData(); + _view.ShowExchange(live); + + Assert.Equal("200 OK · 120 ms · 3.0 MB · HTTP/1.1", shown.StatusText); + Assert.Equal("the start\n\n… (truncated)", shown.BodyText); + Assert.Equal("TLS details are not kept in the history.", shown.TlsText); + Assert.Equal("Script results are not kept in the history.", shown.ScriptsText); + Assert.Contains("\nAuth: (not recorded)\nClient certificate: client.example.com (expires 2027-06-30, 0A1B2C3D…)\nSSL verification: (not recorded) · Redirects: (not recorded)\n", + shown.TimelineText, StringComparison.Ordinal); + Assert.Equal(shown, shownAgain); + Assert.Equal(("200 OK · 120 ms · 3.0 MB · HTTP/1.1", "(response body not kept in the history)"), withoutBody); + Assert.Equal(["The history kept no copy of this response body.", "The history kept no copy of this response body."], withoutBodyNotices); + Assert.Equal("the user's", clipboard); + + // A response just received says what it has. + Assert.Equal("200 OK · 120 ms · 9 B · HTTP/1.1", _view.StatusText); + Assert.Equal("the start\n\n… (truncated)", _view.BodyText); + Assert.Equal("No TLS session was established.", _view.TlsText); + Assert.StartsWith("No scripts ran for this request.", _view.ScriptsText, StringComparison.Ordinal); + Assert.Contains("\nAuth: No auth\nClient certificate: none\nSSL verification: on · Redirects: follow\n", _view.TimelineText, StringComparison.Ordinal); + } + + public void Dispose() + { + if (_token is not null) + { + _app.End(_token); + } + + _window.Dispose(); + _app.Dispose(); + } +} diff --git a/tests/TermRest.Tui.Tests/ScriptsDialogTests.cs b/tests/TermRest.Tui.Tests/ScriptsDialogTests.cs new file mode 100644 index 0000000..5b6b702 --- /dev/null +++ b/tests/TermRest.Tui.Tests/ScriptsDialogTests.cs @@ -0,0 +1,125 @@ +using System.Drawing; +using Terminal.Gui.App; +using Terminal.Gui.Drivers; +using Terminal.Gui.Input; +using Terminal.Gui.Testing; +using TermRest.Core.Scripting; +using TermRest.Core.Tests.Infrastructure; +using TermRest.Core.Workspace; +using TermRest.Tui.Dialogs; +using Xunit; + +namespace TermRest.Tui.Tests; + +/// Tools › Scripts, driven headlessly through Terminal.Gui's ANSI driver as a user would. +[Collection("TUI")] +public sealed class ScriptsDialogTests +{ + [Fact] + public void A_runtime_chosen_with_browse_in_the_workspace_folder_is_that_file_not_a_command_on_path() + { + var directory = TestFiles.NewTempDirectory(); + var settings = TestFiles.NewTempDirectory(); + var name = "python-" + Guid.NewGuid().ToString("N")[..8] + (OperatingSystem.IsWindows() ? ".cmd" : ""); + var runtime = Path.Combine(directory, name); + File.WriteAllText(runtime, OperatingSystem.IsWindows() ? "@echo Python 3.99.0\r\n@echo %~f0\r\n" : "#!/bin/sh\necho Python 3.99.0\necho \"$0\"\n"); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(runtime, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + + TuiApp.ConfigureKeyBindings(); + var workspace = ApiWorkspace.Open(directory); + using var runner = new RequestRunner(workspace) { RequireScriptRuntimes = false }; + using var app = Application.Create(); + app.Init(DriverRegistry.Names.ANSI); + app.Driver!.SetScreenSize(150, 45); + using var window = TuiApp.CreateWindow(workspace, runner); + string Screen() + { + app.LayoutAndDraw(forceRedraw: true); + return app.Driver!.ToString() ?? ""; + } + + void Click(string text) + { + var lines = Screen().Split('\n'); + var y = Array.FindIndex(lines, line => line.Contains(text, StringComparison.Ordinal)); + Assert.True(y >= 0, $"'{text}' is not on screen:\n{string.Join('\n', lines)}"); + app.InjectSequence(InputInjectionExtensions.LeftButtonClick(new Point(lines[y].IndexOf(text, StringComparison.Ordinal), y))); + } + + // The file picker opens in the workspace's folder, where the user picks the file: types its name, presses Enter. + var checkedRuntime = ""; + (Func Ready, Action Act)[] steps = + [ + (screen => screen.Contains("Stop scripts", StringComparison.Ordinal), _ => Click("Browse…")), + (screen => screen.Contains("Choose Python", StringComparison.Ordinal), _ => + { + app.InjectKey(Key.End); + foreach (var c in name) + { + app.InjectKey(new Key(c)); + } + + app.InjectKey(Key.Enter); + }), + (screen => screen.Contains("✓ ", StringComparison.Ordinal) || screen.Contains("✗ ", StringComparison.Ordinal), screen => + { + checkedRuntime = screen; + Click("► Save ◄"); + }), + ]; + var deadline = DateTime.UtcNow.AddSeconds(30); + + // Each step waits for its screen, then acts; the next one is scheduled first, as an action that opens a dialog returns + // only once that is closed. + void Next(int index) + { + if (index < steps.Length) + { + app.AddTimeout(TimeSpan.FromMilliseconds(50), () => + { + var screen = Screen(); + if (app.TopRunnable is { StopRequested: true } || !steps[index].Ready(screen)) + { + return DateTime.UtcNow < deadline; + } + + Next(index + 1); + steps[index].Act(screen); + return false; + }); + } + } + + // After 30 s, whatever is open is closed, so that the test fails instead of hanging. + var done = false; + app.AddTimeout(TimeSpan.FromSeconds(1), () => + { + if (!done && DateTime.UtcNow > deadline) + { + app.RequestStop(); + } + + return !done; + }); + app.AddTimeout(TimeSpan.FromMilliseconds(100), () => + { + Next(0); + ScriptsDialog.ShowRuntimes(app, workspace, runner, settings); + done = true; + app.RequestStop(); + return false; + }); + + app.Run(window); + + // The file was checked (no Python on PATH is 3.99.0), and is what scripts run. + var chosen = "." + Path.DirectorySeparatorChar + name; + Assert.True(checkedRuntime.Contains("✓ Python 3.99.0 · ", StringComparison.Ordinal), checkedRuntime); + Assert.Contains(chosen, checkedRuntime, StringComparison.Ordinal); + Assert.Equal(chosen, UserSettings.Load(settings).GetScriptRuntime(ScriptLanguage.Python, workspace.RootPath)); + Assert.Equal(runtime, runner.PythonInterpreter); + } +} diff --git a/tests/TermRest.Tui.Tests/SyntaxTests.cs b/tests/TermRest.Tui.Tests/SyntaxTests.cs index d7b42d3..959142b 100644 --- a/tests/TermRest.Tui.Tests/SyntaxTests.cs +++ b/tests/TermRest.Tui.Tests/SyntaxTests.cs @@ -60,6 +60,7 @@ class Greeter(Base): [InlineData("return /^\\d+$/.test(s);", "«K return» «S /^\\d+$/».«F test»(s);")] [InlineData("class Client extends Base { static items = new Map(); }", "«K class» «T Client» «K extends» «T Base» { «K static» items = «K new» «T Map»(); }")] [InlineData("if (typeof x === 'string' || x.default.delete(1) === undefined) {}", "«K if» («K typeof» x === «S 'string'» || x.default.«F delete»(«N 1») === «N undefined») {}")] + [InlineData("const s = `a${`b${1}`}`;", "«K const» s = «S `a${`b${»«N 1»«S }`}`»;")] public void JavaScript(string line, string expected) => Assert.Equal(expected, Colored(ScriptLanguage.JavaScript, line)); [Fact] @@ -163,6 +164,52 @@ public void PowerShell_here_strings_strings_and_comments_go_on_over_lines() """); } + [Theory] + [InlineData(ScriptLanguage.JavaScript, "`${")] + [InlineData(ScriptLanguage.Python, "f\"{")] + [InlineData(ScriptLanguage.CSharp, "$\"{")] + [InlineData(ScriptLanguage.PowerShell, "\"$(")] + public void Interpolations_nested_on_a_long_line_do_not_run_out_of_stack(string language, string opening) + { + var line = string.Concat(Enumerable.Repeat(opening, 30_000)); + var kinds = new SyntaxKind[line.Length]; + + var state = SyntaxLexer.For(language)!.Lex(line, kinds, LexState.Code); + + Assert.Equal((LexMode.String, SyntaxKind.String), (state.Mode, kinds[0])); + } + + [Fact] + public void Regular_expressions_that_never_close_on_a_long_line_stay_quick() + { + var line = string.Concat(Enumerable.Repeat("(/[", 30_000)) + "x = /ab/"; + var kinds = new SyntaxKind[line.Length]; + var clock = System.Diagnostics.Stopwatch.StartNew(); + + SyntaxLexer.For(ScriptLanguage.JavaScript)!.Lex(line, kinds, LexState.Code); + + Assert.True(clock.Elapsed < TimeSpan.FromSeconds(1), $"took {clock.Elapsed}"); + } + + [Theory] + [InlineData(ScriptLanguage.PowerShell, "[a ", 60_000)] // [types] that never close (6.5 s before) + [InlineData(ScriptLanguage.PowerShell, "${", 400_000)] // ${names} that never close + [InlineData(ScriptLanguage.CSharp, "$", 90_000)] // $ and @ that lead to no string (7 s before) + [InlineData(ScriptLanguage.CSharp, "@", 90_000)] + [InlineData(ScriptLanguage.CSharp, "'\\", 90_000)] // 'characters' that never close + [InlineData(ScriptLanguage.Python, "'''", 60_000)] // closing quotes counted to the end of the line + [InlineData(ScriptLanguage.Python, "\"", 180_000)] + public void Scans_that_could_go_to_the_end_of_a_long_line_each_time_stay_quick(string language, string piece, int times) + { + var line = string.Concat(Enumerable.Repeat(piece, times)); + var kinds = new SyntaxKind[line.Length]; + var clock = System.Diagnostics.Stopwatch.StartNew(); + + SyntaxLexer.For(language)!.Lex(line, kinds, LexState.Code); + + Assert.True(clock.Elapsed < TimeSpan.FromSeconds(1), $"took {clock.Elapsed}"); // a few ms + } + private static void AssertColored(string language, string script, string expected) => Assert.Equal(expected.ReplaceLineEndings("\n"), Colored(language, script.ReplaceLineEndings("\n"))); diff --git a/tests/TermRest.Tui.Tests/TextAreaTests.cs b/tests/TermRest.Tui.Tests/TextAreaTests.cs new file mode 100644 index 0000000..3551dba --- /dev/null +++ b/tests/TermRest.Tui.Tests/TextAreaTests.cs @@ -0,0 +1,509 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Drawing; +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Text; +using Terminal.Gui.App; +using Terminal.Gui.Drivers; +using Terminal.Gui.Input; +using Terminal.Gui.Testing; +using Terminal.Gui.ViewBase; +using Terminal.Gui.Views; +using TermRest.Tui.Views; +using Xunit; + +namespace TermRest.Tui.Tests; + +#pragma warning disable CS0618 // TextView: TextArea is compared with the Terminal.Gui view it draws and edits like. + +/// The text editor/viewer: drawn and edited as Terminal.Gui's TextView, without its costs on large texts. +[Collection("TUI")] +public sealed class TextAreaTests +{ + /// A pretty-printed JSON array of about characters, one property a line. + private static string Json(int size) + { + var text = new StringBuilder("[\n"); + for (var i = 0; text.Length < size; i++) + { + text.Append(CultureInfo.InvariantCulture, $" {{\n \"id\": {i},\n \"name\": \"Item {i}\",\n \"tags\": [\"alpha\", \"beta\"],\n") + .Append(CultureInfo.InvariantCulture, $" \"active\": {(i % 2 == 0 ? "true" : "false")}\n }},\n"); + } + + return text.Append(" {}\n]").ToString(); + } + + /// A headless application showing one view in a window. + private sealed class Screen : IDisposable + { + private readonly Window _window = new() { Width = Dim.Fill(), Height = Dim.Fill() }; + private SessionToken? _token; + + public Screen(int width = 60, int height = 16) + { + App = Application.Create(); + App.Init(DriverRegistry.Names.ANSI); + App.Driver!.SetScreenSize(width, height); + App.Driver.Clipboard = new FakeClipboard(); + } + + public IApplication App { get; } + + public T Show(T view, string text) + where T : TextView + { + _window.Add(view); + _token = App.Begin(_window); + if (view is TextArea area) + { + area.SetText(text); + } + else + { + view.Text = text; + } + + view.SetFocus(); + App.LayoutAndDraw(forceRedraw: true); + return view; + } + + /// What the view shows, with each cell's colors, after a full redraw. + public string Cells(View view) + { + App.LayoutAndDraw(forceRedraw: true); + var contents = App.Driver!.Contents!; + var frame = view.FrameToScreen(); + var cells = new StringBuilder(); + for (var y = frame.Top; y < frame.Bottom; y++) + { + for (var x = frame.Left; x < frame.Right; x++) + { + cells.Append(contents[y, x].Grapheme).Append(contents[y, x].Attribute).Append('|'); + } + + cells.Append('\n'); + } + + return cells.Append(view.Cursor.Position).ToString(); + } + + public void Key(Key key) => App.InjectKey(key); + + public void Mouse(View view, MouseFlags flags, int x = 3, int y = 3) => + App.InjectMouse(new Mouse { ScreenPosition = view.ViewportToScreen(new Point(x, y)), Flags = flags }); + + public void Dispose() + { + if (_token is not null) + { + App.End(_token); + } + + _window.Dispose(); + App.Dispose(); + } + } + + private static TextView Configure(TextView view, bool readOnly, bool wrap) + { + view.X = 1; + view.Y = 1; + view.Width = 40; + view.Height = 10; + view.ReadOnly = readOnly; + view.WordWrap = wrap; + view.ScrollBars = true; + return view; + } + + public static TheoryData Views => new() + { + { "top", false, false }, + { "top", true, false }, + { "middle", true, false }, + { "end", false, false }, + { "selection", false, false }, + { "selection", true, true }, + { "wide", true, false }, + { "wide", false, true }, + { "scrolled right", true, false }, + { "scrolled far right", true, false }, + { "scrolled far right", false, false }, + { "overwrite", false, false }, + }; + + [Theory] + [MemberData(nameof(Views))] + public void Draws_what_Terminal_Gui_s_text_view_draws(string what, bool readOnly, bool wrap) + { + var text = what switch + { + "wide" or "scrolled right" => string.Concat(Enumerable.Repeat("名前: 東京タワー 🎉👍🏽 é x\ty\t\tz 漢字漢字 end\n\tleading tab ab\tc " + new string('w', 50) + "\n", 20)), + "scrolled far right" => string.Concat(Enumerable.Repeat("short\n\t名前 🎉\n\n" + new string('w', 300) + " end\n", 5)), + _ => Json(30_000), + }; + void Arrange(TextView view) + { + switch (what) + { + case "middle": + view.ScrollTo(new Point(0, 150)); + break; + case "end": + view.MoveEnd(); + break; + case "selection": + view.InsertionPoint = new Point(9, 6); + view.SelectionStartRow = 2; + view.SelectionStartColumn = 4; + break; + case "scrolled right": + view.ScrollTo(new Point(9, 3)); + break; + case "scrolled far right": + view.InsertionPoint = new Point(304, 3); // the end of a long line: the other lines end far left of the view + Assert.True(view.Viewport.X > 260, $"scrolled to {view.Viewport.X}"); + break; + case "overwrite": + view.InsertionPoint = new Point(5, 2); + view.Used = false; + break; + } + } + + string Draw(TextView view) + { + using var screen = new Screen(); + screen.Show(Configure(view, readOnly, wrap), text); + Arrange(view); + return screen.Cells(view); + } + + var expected = Draw(new TextView()); + var drawn = Draw(new TextArea()); + + Assert.Equal(expected, drawn); + } + + [Fact] + public void Redrawing_a_large_text_takes_no_longer_than_a_small_one() + { + using var screen = new Screen(120, 40); + screen.Show(new TextArea { ReadOnly = true }, Json(1_000_000)); + var watch = Stopwatch.StartNew(); + for (var i = 0; i < 3; i++) + { + screen.App.LayoutAndDraw(forceRedraw: true); + } + + watch.Stop(); + var shown = screen.App.Driver!.ToString(); + + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(1.5), $"3 redraws took {watch.Elapsed}"); // ~0.05 s; 12 s when every line below was drawn too + Assert.Contains("\"name\": \"Item 0\",", shown, StringComparison.Ordinal); + } + + [Fact] + public void Redrawing_a_view_scrolled_to_the_end_of_a_very_long_line_is_quick() + { + // A pretty-printed response holding one long string: at its end, the view is far right of where the other lines end. + var json = new StringBuilder("{\n \"data\": \"").Append('x', 1_000_000).Append("\",\n"); + for (var i = 0; i < 60; i++) + { + json.Append(CultureInfo.InvariantCulture, $" \"key {i}\": {i},\n"); + } + + using var screen = new Screen(120, 40); + var area = screen.Show(new TextArea { ReadOnly = true }, json.Append(" \"end\": true\n}").ToString()); + area.InsertionPoint = new Point(0, 1); + screen.Key(Key.End); + var watch = Stopwatch.StartNew(); + screen.App.LayoutAndDraw(forceRedraw: true); + watch.Stop(); + + Assert.True(area.Viewport.X > 999_000, $"scrolled to {area.Viewport.X}"); + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(4), $"a redraw took {watch.Elapsed}"); // ~0.3 s; 11 s when the short lines were cleared from where they end + } + + [Fact] + public void A_space_typed_with_Shift_held_is_typed() + { + using var screen = new Screen(); + var area = screen.Show(new TextArea(), ""); + + screen.Key(Key.A.WithShift); + screen.Key(Key.Space.WithShift); + screen.Key(Key.B); + + Assert.Equal("A b", area.GetText()); + } + + [Fact] + public void Text_that_comes_with_no_key_is_typed_as_Terminal_Gui_s_text_view_types_it() + { + // As a kitty-protocol terminal sends text that has no key of its own (from an IME, or Option+a on a Mac): CSI 0;;text u. + const string Input = "\u001b[0;;229ub\u001b[0;;123u\u001b[0;;34ua\u001b[0;;34u:1\u001b[0;;125u"; + static string Typed(TextView view) + { + using var screen = new Screen(); + screen.Show(view, ""); + using var input = new AnsiInputProcessor(new ConcurrentQueue(Input)); + input.KeyDown += (_, key) => screen.App.Keyboard.RaiseKeyDownEvent(key); + input.ProcessQueue(); + return view.Text; + } + + var typed = Typed(new TextView { Width = Dim.Fill(), Height = Dim.Fill() }); + + Assert.Equal("åb{\"a\":1}", typed); + Assert.Equal(typed, Typed(new TextArea())); + } + + [Fact] + public void Half_of_a_character_set_or_pasted_shows_as_a_replacement_character() + { + using var screen = new Screen(); + var area = screen.Show(new TextArea(), "cut in two: \uD83D\n\uDE00 and 😀 whole, \uD83D\uD83D twice"); + var set = area.GetText(); + var shown = screen.App.Driver!.ToString(); + area.MoveEnd(); + screen.App.RaisePasteEvent(" pasted \uDE00"); + + Assert.Equal("cut in two: \uFFFD\n\uFFFD and 😀 whole, \uFFFD\uFFFD twice", set); + Assert.Contains("cut in two: \uFFFD", shown, StringComparison.Ordinal); + Assert.Equal(set + " pasted \uFFFD", area.GetText()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Cutting_with_nothing_selected_cuts_nothing(bool readOnly) + { + const string Short = "L0\nL1\nL2\nL3\nL4\nL5\nL6\nL7\nL8\nL9"; + var text = string.Join('\n', Enumerable.Range(0, 200).Select(i => $"L{i}")); + using var screen = new Screen(); + var area = screen.Show(new TextArea { ReadOnly = readOnly }, text); + screen.App.Clipboard!.SetClipboardData("kept"); + + // TextView's cut takes the text from where the last selection started (the start of the text when there was none) to + // the cursor, and fails partway when that start is past the end of a shorter text set since. + area.InsertionPoint = new Point(1, 4); + screen.Key(Key.X.WithCtrl); + Assert.Equal(text, area.GetText()); + area.InsertionPoint = new Point(0, 150); + screen.Key(Key.CursorDown.WithShift); + screen.Key(Key.CursorDown); + area.SetText(Short); + area.InsertionPoint = new Point(1, 4); + screen.Key(Key.X.WithCtrl); + + Assert.Equal(Short, area.GetText()); + Assert.Equal("kept", screen.App.Clipboard.GetClipboardData()); + } + + [Fact] + public void A_cut_the_clipboard_refuses_leaves_the_text_as_it_was() + { + using var screen = new Screen(); + var area = screen.Show(new TextArea(), "L0\nL1\nL2\nL3\nL4"); + var clipboard = new FakeClipboard { FakeException = new System.ComponentModel.Win32Exception(5, "Access is denied.") }; + area.InsertionPoint = new Point(0, 1); + screen.Key(Key.CursorDown.WithShift); + screen.Key(Key.CursorDown.WithShift); + screen.App.Driver!.Clipboard = clipboard; + + _ = Record.Exception(() => screen.Key(Key.X.WithCtrl)); // another program holds the clipboard + + Assert.Equal("L0\nL1\nL2\nL3\nL4", area.GetText()); + } + + [Fact] + public void A_paste_from_the_terminal_inserts_the_text_pasted_after_a_copy_of_the_same_text() + { + using var screen = new Screen(); + var area = screen.Show(new TextArea(), "alpha\nbeta\ngamma"); + + // Copied twice without a selection (its line), then pasted by the terminal (a bracketed paste, not Ctrl+V). + area.InsertionPoint = new Point(0, 1); + screen.Key(Key.C.WithCtrl); + screen.Key(Key.C.WithCtrl); + area.InsertionPoint = new Point(2, 2); + screen.App.RaisePasteEvent("beta"); + Assert.Equal("alpha\nbeta\ngabetamma", area.GetText()); + + // Copied without a selection, then selected and cut: the paste brings it back. + area.SetText("foo bar\nzzz"); + screen.Key(Key.C.WithCtrl); + screen.Key(Key.End.WithShift); + screen.Key(Key.X.WithCtrl); + screen.App.RaisePasteEvent("foo bar"); + Assert.Equal("foo bar\nzzz", area.GetText()); + } + + [Theory] + [InlineData("Ctrl+Z")] + [InlineData("Ctrl+Backspace")] + [InlineData("Ctrl+Shift+Backspace")] + [InlineData("Ctrl+K")] + public void Edits_that_shorten_the_text_end_the_selection(string edit) + { + using var screen = new Screen(); + var area = screen.Show(new TextArea(), "hello worl"); + area.InsertionPoint = new Point(10, 0); + screen.Key(Key.D); // something to undo + for (var i = 0; i < 3; i++) + { + screen.Key(Key.CursorLeft.WithShift); + } + + screen.Key(edit switch + { + "Ctrl+Z" => Key.Z.WithCtrl, + "Ctrl+Backspace" => Key.Backspace.WithCtrl, + "Ctrl+Shift+Backspace" => Key.Backspace.WithCtrl.WithShift, + _ => Key.K.WithCtrl, + }); + + // The selection's start would be past what is left of the text, and the next keys would fail on it. + Assert.False(area.IsSelecting); + Assert.Null(Record.Exception(() => + { + screen.Key(Key.C.WithCtrl); + screen.Key(Key.X); + screen.Key(Key.Backspace); + screen.Key(Key.Delete); + })); + } + + [Fact] + public void Copying_a_large_selection_and_the_keys_clicks_drags_and_wheel_steps_after_it_are_quick() + { + var text = Json(600_000); + using var screen = new Screen(120, 40); + var area = screen.Show(new TextArea { ReadOnly = true }, text); + var steps = new List<(string Step, TimeSpan Took)>(); + void Step(string step, Action act) + { + var watch = Stopwatch.StartNew(); + act(); + screen.App.LayoutAndDraw(); + steps.Add((step, watch.Elapsed)); + } + + Step("Ctrl+A", () => screen.Key(Key.A.WithCtrl)); + Step("Ctrl+C", () => screen.Key(Key.C.WithCtrl)); + var copied = screen.App.Clipboard!.GetClipboardData(); + Step("Shift+Up", () => screen.Key(Key.CursorUp.WithShift)); + var extended = (area.SelectionStartRow, area.SelectionStartColumn, area.CurrentRow); + Step("wheel", () => screen.Mouse(area, MouseFlags.WheeledDown)); + Step("letter", () => screen.Key(Key.X)); + var selected = area.IsSelecting; + Step("click", () => screen.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(area.ViewportToScreen(new Point(5, 5))))); + var clickEnded = !area.IsSelecting; + + // Dragging to the bottom edge selects to the end of the text. + screen.Key(Key.Home.WithCtrl); + var bottom = area.Viewport.Height - 1; + Step("press", () => screen.Mouse(area, MouseFlags.LeftButtonPressed, 5, 1)); + Step("drag to the bottom", () => screen.Mouse(area, MouseFlags.LeftButtonPressed | MouseFlags.PositionReport, 5, bottom)); + Step("drag on", () => screen.Mouse(area, MouseFlags.LeftButtonPressed | MouseFlags.PositionReport, 6, bottom)); + screen.Mouse(area, MouseFlags.LeftButtonReleased, 6, bottom); + + Assert.Equal(text.ReplaceLineEndings(Environment.NewLine), copied); + Assert.Equal((0, 0, area.Lines - 2), extended); + Assert.True(selected); + Assert.True(clickEnded); + Assert.Equal((true, 1, area.Lines - 1), (area.IsSelecting, area.SelectionStartRow, area.CurrentRow)); + Assert.All(steps, step => Assert.True(step.Took < TimeSpan.FromSeconds(1), $"{step.Step} took {step.Took}")); // ~0.05 s each; 2 to 17 s each before + } + + public static TheoryData Sequences => new() + { + { "forward cut, undo, redo", false, false }, + { "backward cut, undo", false, false }, + { "copy a line, then a selection, paste", false, false }, + { "copy, paste twice", false, false }, + { "copy, up, down", false, false }, + { "copy all", true, true }, + { "copy part", true, true }, + { "cut", true, false }, + { "wheel, letter, click", true, false }, + { "toggled selection, click", false, false }, + }; + + [Theory] + [MemberData(nameof(Sequences))] + public void Copies_cuts_and_pastes_as_Terminal_Gui_s_text_view_does(string sequence, bool readOnly, bool wrap) + { + var text = string.Join('\n', Enumerable.Range(0, 40).Select(i => i % 5 == 2 ? "short" : $"line {i}: the quick brown fox jumps over the lazy dog {i}")); + IEnumerable> Steps() + { + static Action Press(Key key, int times = 1) => (screen, _) => + { + for (var i = 0; i < times; i++) + { + screen.Key(key); + } + }; + + static Action At(int column, int row) => (_, view) => view.InsertionPoint = new Point(column, row); + + // TextView pastes the cells it copied when the text pasted is the text it copied, as on Linux (no CR for the + // paste to drop); those cells become lines of the text, which a second paste then reuses as changed (a + // Terminal.Gui 2.5 bug). TextArea's copy leaves that text empty, so its paste reads the text pasted: the + // TextView compared does the same. + static Action Paste() => (_, view) => + { + if (view is not TextArea) + { + CopiedText(view) = null; + } + + view.InvokeCommand(Command.Paste); + }; + + return sequence switch + { + "forward cut, undo, redo" => [At(5, 3), Press(Key.CursorDown.WithShift, 3), Press(Key.CursorRight.WithShift, 4), Press(Key.X.WithCtrl), Press(Key.Z.WithCtrl), Press(Key.Y.WithCtrl)], + "backward cut, undo" => [At(9, 12), Press(Key.CursorUp.WithShift, 4), Press(Key.X.WithCtrl), Press(Key.Z.WithCtrl)], + "copy a line, then a selection, paste" => [At(3, 4), Press(Key.C.WithCtrl), At(1, 6), Press(Key.CursorRight.WithShift, 5), Press(Key.C.WithCtrl), At(2, 9), Paste()], + "copy, paste twice" => [At(1, 6), Press(Key.CursorDown.WithShift, 3), Press(Key.C.WithCtrl), At(2, 20), Paste(), Paste(), Press(Key.Z.WithCtrl)], + "copy, up, down" => [At(30, 0), Press(Key.CursorDown.WithShift, 2), Press(Key.C.WithCtrl), Press(Key.CursorDown), Press(Key.CursorDown)], + "copy all" => [Press(Key.A.WithCtrl), Press(Key.C.WithCtrl)], + "copy part" => [At(3, 4), Press(Key.CursorDown.WithShift, 5), Press(Key.CursorRight.WithShift, 7), Press(Key.C.WithCtrl)], + "cut" => [At(3, 4), Press(Key.CursorDown.WithShift, 2), Press(Key.X.WithCtrl), Press(Key.CursorDown)], + "wheel, letter, click" => [Press(Key.A.WithCtrl), (screen, view) => screen.Mouse(view, MouseFlags.WheeledDown), Press(Key.Q), + (screen, view) => screen.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(view.ViewportToScreen(new Point(4, 2)))), Press(Key.C.WithCtrl)], + _ => [At(2, 1), Press(Key.Space.WithCtrl), Press(Key.CursorDown, 2), + (screen, view) => screen.App.InjectSequence(InputInjectionExtensions.LeftButtonClick(view.ViewportToScreen(new Point(5, 6)))), Press(Key.C.WithCtrl)], + }; + } + + string Play(TextView view) + { + using var screen = new Screen(); + screen.Show(Configure(view, readOnly, wrap), text); + var states = new StringBuilder(); + foreach (var step in Steps()) + { + step(screen, view); + screen.App.LayoutAndDraw(); + + // Where words wrap, TextView's copy may move a position from the start of a row to the end of the one above. + var where = wrap ? "" : $"{view.InsertionPoint} ({view.SelectionStartColumn},{view.SelectionStartRow}) {view.Viewport}"; + states.Append(CultureInfo.InvariantCulture, $"{view.Text} | {view.IsSelecting} {where} | {screen.App.Clipboard!.GetClipboardData()}\n"); + } + + return states.ToString(); + } + + Assert.Equal(Play(new TextView()), Play(new TextArea())); + } + + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_copiedText")] + private static extern ref string? CopiedText(TextView view); +} + +#pragma warning restore CS0618 diff --git a/tests/TermRest.Tui.Tests/ThemeTests.cs b/tests/TermRest.Tui.Tests/ThemeTests.cs index 1a3e358..43b9036 100644 --- a/tests/TermRest.Tui.Tests/ThemeTests.cs +++ b/tests/TermRest.Tui.Tests/ThemeTests.cs @@ -117,9 +117,109 @@ public void A_copy_of_a_theme_looks_the_same_until_it_is_edited() Assert.Equal("Dark", copy.TerminalGuiTheme); Assert.Equal(Path.Combine(directory, "My Dark-2.json"), ThemeCatalog.WriteCopy(BuiltIn("Dark"), "My Dark", directory)); + // Named for every OS (a workspace's themes are shared through Git): no | or ?, and no two names differing in case. + Assert.Equal(Path.Combine(directory, "my dark-3.json"), ThemeCatalog.WriteCopy(BuiltIn("Dark"), "my dark", directory)); + Assert.Equal(Path.Combine(directory, "Dark - contrast-.json"), ThemeCatalog.WriteCopy(BuiltIn("Dark"), "Dark | contrast?", directory)); + File.WriteAllText(path, System.Text.RegularExpressions.Regex.Replace(File.ReadAllText(path), "\"selection\": \"[^\"]*\"", "\"selection\": \"#004080\"")); var edited = ThemeCatalog.Find(ThemeCatalog.Load(null, errors, _userDirectory), "My Dark")!; Assert.Equal(Color.Parse("#004080"), edited.Schemes["Base"].Focus.Background); + + // A copy of a built-in theme starts from it and lists its palette colors by name or #RRGGBB, and nothing else. + Assert.All(ThemeCatalog.BuiltIn, theme => + { + var file = ThemeFile.CopyOf(theme, "Copy"); + Assert.Equal((theme.Name, false), (file.Base, file.Schemes is not null)); + Assert.Equal(ThemePalette.Keys.Select(k => k.Get(theme.Palette).ToString()), file.Palette!.Values); + }); + } + + [Fact] + public void A_copy_of_a_custom_theme_looks_the_same_without_the_theme_files_it_builds_on() + { + // A production theme like the README's, shared in a workspace's .termrest/themes; a theme built on it, which keeps its + // scheme roles; and one built on a Terminal.Gui theme. + var workspace = TestFiles.NewTempDirectory(); + var shared = ThemeCatalog.WorkspaceThemesDirectory(workspace); + Directory.CreateDirectory(shared); + File.WriteAllText(Path.Combine(shared, "Production.json"), """ + { + "name": "Production", + "base": "Nord", + "palette": { "bar": "#5c0000", "barText": "White", "selection": "DarkRed" }, + "schemes": { "Base": { "Focus": "white on #8b0000 bold" }, "Success": { "Normal": "on #102030" } } + } + """); + File.WriteAllText(Path.Combine(shared, "Staging.json"), """ + { "name": "Staging", "base": "Production", "palette": { "get": "Lime" }, "schemes": { "Menu": { "HotNormal": "None on none none" } } } + """); + File.WriteAllText(Path.Combine(shared, "Night.json"), """ + { "name": "Night", "base": "Dark", "schemes": { "Dialog": { "Normal": "Yellow on #102030 italic" }, "Warning": { "Disabled": "Orange" } } } + """); + var errors = new List(); + var themes = ThemeCatalog.Load(workspace, errors, _userDirectory); + var elsewhere = TestFiles.NewTempDirectory(); // the configuration folder of someone without that workspace + string[] names = ["Production", "Staging", "Night"]; + var paths = names.Select(n => ThemeCatalog.WriteCopy(ThemeCatalog.Find(themes, n)!, $"My {n}", UserSettings.ThemesDirectory(elsewhere))).ToList(); + + var copies = ThemeCatalog.Load(TestFiles.NewTempDirectory(), errors, elsewhere); + + Assert.Empty(errors); + foreach (var name in names) + { + var (source, copy) = (ThemeCatalog.Find(themes, name)!, ThemeCatalog.Find(copies, $"My {name}")!); + Assert.Equal((source.Palette, source.TerminalGuiTheme), (copy.Palette, copy.TerminalGuiTheme)); + Assert.Equal(source.Schemes.Keys.Order(), copy.Schemes.Keys.Order()); + Assert.All(source.Schemes, s => Assert.Equal(s.Value, copy.Schemes[s.Key])); + } + + // The roles the theme sets stay as they are; the others still follow its palette. + File.WriteAllText(paths[0], System.Text.RegularExpressions.Regex.Replace(File.ReadAllText(paths[0]), "\"selection\": \"[^\"]*\"", "\"selection\": \"#004080\"")); + var edited = ThemeCatalog.Find(ThemeCatalog.Load(null, errors, elsewhere), "My Production")!; + Assert.Empty(errors); + Assert.Equal(A("White", "#8b0000", TextStyle.Bold), edited.Schemes["Base"].Focus); + Assert.Equal(Color.Parse("#004080"), edited.Schemes["Menu"].Focus.Background); + } + + [Fact] + public void Roles_a_theme_sets_stay_as_set_whatever_their_order_in_the_file() + { + // Terminal.Gui derives the roles a scheme doesn't set from others: Focus from Normal, Highlight and ReadOnly from Editable. + var workspace = TestFiles.NewTempDirectory(); + var shared = ThemeCatalog.WorkspaceThemesDirectory(workspace); + Directory.CreateDirectory(shared); + File.WriteAllText(Path.Combine(shared, "Order.json"), """ + { "name": "Order", "schemes": { "Base": { "Highlight": "Red on Blue none", "ReadOnly": "Yellow on Blue none", "Focus": "Black on White none", "Editable": "White on Black none", "Normal": "Gray on Black none" } } } + """); + var errors = new List(); + + var scheme = ThemeCatalog.Find(ThemeCatalog.Load(workspace, errors, _userDirectory), "Order")!.Schemes["Base"]; + + Assert.Empty(errors); + Assert.Equal( + (A("Red", "Blue", TextStyle.None), A("Yellow", "Blue", TextStyle.None), A("Black", "White", TextStyle.None), A("White", "Black", TextStyle.None), A("Gray", "Black", TextStyle.None)), + (scheme.Highlight, scheme.ReadOnly, scheme.Focus, scheme.Editable, scheme.Normal)); + } + + [Fact] + public void A_theme_keeps_the_status_roles_its_base_sets_until_it_changes_that_status_color() + { + var workspace = TestFiles.NewTempDirectory(); + var shared = ThemeCatalog.WorkspaceThemesDirectory(workspace); + Directory.CreateDirectory(shared); + File.WriteAllText(Path.Combine(shared, "Production.json"), """ + { "name": "Production", "base": "Nord", "schemes": { "Success": { "Normal": "Lime on #102030 bold" }, "Warning": { "Normal": "Gold on #102030 bold" } } } + """); + File.WriteAllText(Path.Combine(shared, "Staging.json"), """{ "name": "Staging", "base": "Production", "palette": { "warning": "#ffa500" } }"""); + var errors = new List(); + + var themes = ThemeCatalog.Load(workspace, errors, _userDirectory); + + Assert.Empty(errors); + var (production, staging) = (ThemeCatalog.Find(themes, "Production")!, ThemeCatalog.Find(themes, "Staging")!); + Assert.Equal(A("Lime", "#102030", TextStyle.Bold), staging.Schemes[ThemeCatalog.SuccessScheme].Normal); + Assert.Equal(production.Schemes[ThemeCatalog.SuccessScheme], staging.Schemes[ThemeCatalog.SuccessScheme]); + Assert.Equal(new Attribute(Color.Parse("#ffa500"), staging.Palette.Background, TextStyle.Bold), staging.Schemes[ThemeCatalog.WarningScheme].Normal); } [Fact] @@ -180,6 +280,29 @@ public void Problems_in_theme_files_are_reported_and_the_rest_still_works() Assert.Equal(ThemeCatalog.BuiltIn.Count + 1, themes.Count); } + [Fact] + public void Out_of_range_colors_and_nulls_in_theme_files_are_reported_too() + { + WriteTheme("odd.json", """ + { + "name": "Odd", + "palette": { "bar": "rgb(256,0,0)", "accent": "Yellow" }, + "schemes": { "Menu": null, "Base": { "Focus": null, "Normal": "White on rgb(0,0,999)", "HotFocus": "White on Blue" } } + } + """); + var errors = new List(); + + var odd = ThemeCatalog.Find(ThemeCatalog.Load(null, errors, _userDirectory), "Odd")!; + + Assert.Equal(4, errors.Count); + Assert.StartsWith("odd.json: palette color bar: 'rgb(256,0,0)' is not a color", errors[0], StringComparison.Ordinal); + Assert.StartsWith("odd.json: Menu: no roles given", errors[1], StringComparison.Ordinal); + Assert.StartsWith("odd.json: Base.Focus: empty", errors[2], StringComparison.Ordinal); + Assert.Equal("odd.json: Base.Normal: 'rgb(0,0,999)' is not a color", errors[3]); + Assert.Equal(Color.Parse("Yellow"), odd.Palette.Accent); + Assert.Equal((Color.Parse("White"), Color.Parse("Blue")), (odd.Schemes["Base"].HotFocus.Foreground, odd.Schemes["Base"].HotFocus.Background)); + } + [Fact] public void Custom_themes_can_build_on_each_other_and_replace_built_in_ones() { @@ -200,6 +323,40 @@ public void Custom_themes_can_build_on_each_other_and_replace_built_in_ones() Assert.Single(themes, t => t.Name == "Dark"); } + [Fact(Timeout = 10_000)] + public async Task Several_theme_files_can_replace_the_theme_they_start_from() + { + // As after copying Default as a custom theme named Default twice, and once more into the workspace. + WriteTheme("Default.json", """{ "name": "Default", "base": "Default", "palette": { "accent": "Orange" } }"""); + WriteTheme("Default-2.json", """{ "name": "Default", "base": "Default", "palette": { "bar": "#5c0000" } }"""); + var workspaceRoot = TestFiles.NewTempDirectory(); + Directory.CreateDirectory(ThemeCatalog.WorkspaceThemesDirectory(workspaceRoot)); + var workspaceTheme = Path.Combine(ThemeCatalog.WorkspaceThemesDirectory(workspaceRoot), "Default.json"); + File.WriteAllText(workspaceTheme, """{ "name": "Default", "base": "Default", "palette": { "get": "Cyan" } }"""); + var errors = new List(); + + var themes = await Task.Run(() => ThemeCatalog.Load(workspaceRoot, errors, _userDirectory), TestContext.Current.CancellationToken); + + Assert.Empty(errors); + var theme = Assert.Single(themes, t => t.Name == ThemeCatalog.DefaultName); + Assert.Equal(workspaceTheme, theme.FilePath); + Assert.Equal((Color.Parse("Orange"), Color.Parse("#5c0000"), Color.Parse("Cyan")), (theme.Palette.Accent, theme.Palette.Bar, theme.Palette.Get)); // each starts from the one before + } + + [Fact(Timeout = 10_000)] + public async Task A_missing_base_is_reported_for_its_file_and_themes_based_on_that_theme_still_build_on_it() + { + WriteTheme("a-child.json", """{ "name": "Child", "base": "Default", "palette": { "accent": "Orange" } }"""); + WriteTheme("default.json", """{ "name": "Default", "base": "Defualt", "palette": { "background": "#101010" } }"""); + var errors = new List(); + + var themes = await Task.Run(() => ThemeCatalog.Load(null, errors, _userDirectory), TestContext.Current.CancellationToken); + + Assert.Equal(["default.json: base theme 'Defualt' was not found; using Default"], errors); + var child = ThemeCatalog.Find(themes, "Child")!; + Assert.Equal((Color.Parse("#101010"), Color.Parse("Orange")), (child.Palette.Background, child.Palette.Accent)); + } + [Fact] public void The_theme_comes_from_the_command_line_environment_workspace_or_user() { @@ -246,6 +403,21 @@ public void The_chosen_theme_is_saved_for_the_user_or_the_workspace() Assert.Null(UserSettings.Load(_userDirectory).Theme); } + [Fact] + public void User_settings_that_cannot_be_read_are_reported_and_not_saved_over() + { + var workspace = ApiWorkspace.Open(TestFiles.NewTempDirectory()); + Directory.CreateDirectory(_userDirectory); + var path = Path.Combine(_userDirectory, "settings.json"); + File.WriteAllText(path, "{ \"theme\": "); + + TuiApp.ApplyTheme(workspace, userDirectory: _userDirectory); + + Assert.Contains(workspace.LoadErrors, e => e.StartsWith(path, StringComparison.Ordinal)); + Assert.Throws(() => Dialogs.ThemeDialog.Save(workspace, BuiltIn("Nord"), workspaceOnly: false, _userDirectory)); + Assert.Equal("{ \"theme\": ", File.ReadAllText(path)); + } + [Theory] [InlineData("white on blue", "White", "Blue", TextStyle.Italic)] [InlineData("#112233 on rgb(1,2,3) bold underline", "#112233", "#010203", TextStyle.Bold | TextStyle.Underline)] @@ -263,5 +435,19 @@ public void Attributes_are_written_as_colors_and_styles(string text, string fore Assert.Equal(A(foreground, background, style), attribute); } + [Theory] + [InlineData("White", "DarkRed", TextStyle.Bold)] + [InlineData("None", "None", TextStyle.None)] + [InlineData("#123456", "None", TextStyle.Italic | TextStyle.Underline | TextStyle.Strikethrough)] + [InlineData("#80FF0000", "#00000000", TextStyle.Faint)] // partly transparent + public void Attributes_are_written_so_that_they_read_back_the_same(string foreground, string background, TextStyle style) + { + var written = A(foreground, background, style); + var fallback = A("Gray", "Black", TextStyle.Blink | TextStyle.Reverse); + + Assert.True(ThemeFile.TryParseAttribute(ThemeFile.FormatAttribute(written), fallback, out var attribute, out var problem), problem); + Assert.Equal(written, attribute); + } + public void Dispose() => ThemeCatalog.Apply(BuiltIn(ThemeCatalog.DefaultName)); } diff --git a/tests/TermRest.Tui.Tests/TimerResolutionTests.cs b/tests/TermRest.Tui.Tests/TimerResolutionTests.cs index 456ba2f..2bfc339 100644 --- a/tests/TermRest.Tui.Tests/TimerResolutionTests.cs +++ b/tests/TermRest.Tui.Tests/TimerResolutionTests.cs @@ -13,14 +13,22 @@ public void Finer_timer_resolution_is_requested_while_the_lease_is_held() { if (OperatingSystem.IsWindows()) { - // With Windows' default 15.6 ms timer tick, ten 1 ms sleeps take about 156 ms. - var clock = Stopwatch.StartNew(); - for (var i = 0; i < 10; i++) + // With Windows' default 15.6 ms timer tick, ten 1 ms sleeps take at least 140 ms (each waits for the next + // tick), every time; with 1 ms resolution about 15 ms. The best of ten tries, below 120 ms, so that a busy + // machine (tests and builds running in parallel) does not fail it, while the default tick still does. + var fastest = long.MaxValue; + for (var attempt = 0; attempt < 10 && fastest >= 120; attempt++) { - Thread.Sleep(1); + var clock = Stopwatch.StartNew(); + for (var i = 0; i < 10; i++) + { + Thread.Sleep(1); + } + + fastest = Math.Min(fastest, clock.ElapsedMilliseconds); } - Assert.True(clock.ElapsedMilliseconds < 100, $"10 × Sleep(1) took {clock.ElapsedMilliseconds} ms"); + Assert.True(fastest < 120, $"10 × Sleep(1) took {fastest} ms"); } } finally diff --git a/tests/TermRest.Tui.Tests/UiTests.cs b/tests/TermRest.Tui.Tests/UiTests.cs new file mode 100644 index 0000000..88fc04a --- /dev/null +++ b/tests/TermRest.Tui.Tests/UiTests.cs @@ -0,0 +1,16 @@ +using TermRest.Tui.Dialogs; +using Xunit; + +namespace TermRest.Tui.Tests; + +/// Helpers shared by the dialogs. +public sealed class UiTests +{ + [Fact] + public void A_line_wrapped_where_it_has_no_space_is_not_cut_inside_a_character() + { + var line = new string('a', 39) + "😀" + new string('b', 30); + + Assert.Equal([new string('a', 39), " 😀" + new string('b', 30)], Ui.Wrap(line, 40).ToArray()); + } +}