From fc253126a7e00c176aab75585f666b651ccbb47c Mon Sep 17 00:00:00 2001 From: JoshiCodes <55353244+JoshiCodes@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:13:06 +0100 Subject: [PATCH] GraphQL, WebSocket, import, runner and CLI (M5, M6) plus packaging - GraphQL editor with schema introspection, cached schema, autocomplete and explorer - WebSocket: auth and subprotocols in the handshake, text/JSON/hex/file messages, saved messages, live log with filter, search and export, reconnect with backoff - Import from Postman (collections and environments), Bruno, Insomnia, OpenAPI/Swagger and cURL; imported scripts are kept as docs, never run; credentials move to the gitignored secrets file - Code snippets for cURL, fetch, Python, HTTPie, Go, PowerShell; Postman export - Runner for folders and collections with JSON and JUnit reports - knock CLI: send, run, import, auth login/debug/logout - Large JSON responses parsed off the main thread - PKGBUILDs, desktop entry with knock:// handler, CI workflow, README --- .gitea/workflows/ci.yml | 53 + Cargo.lock | 212 ++++ Cargo.toml | 2 +- README.md | 85 ++ crates/knock-cli/Cargo.toml | 21 + crates/knock-cli/src/main.rs | 531 ++++++++++ crates/knock-core/Cargo.toml | 2 + crates/knock-core/src/export/mod.rs | 7 + crates/knock-core/src/export/postman.rs | 403 ++++++++ crates/knock-core/src/export/snippet.rs | 879 ++++++++++++++++ crates/knock-core/src/import/bruno.rs | 792 ++++++++++++++ crates/knock-core/src/import/curl.rs | 811 +++++++++++++++ crates/knock-core/src/import/insomnia.rs | 446 ++++++++ crates/knock-core/src/import/mod.rs | 506 +++++++++ crates/knock-core/src/import/openapi.rs | 975 ++++++++++++++++++ crates/knock-core/src/import/postman.rs | 768 ++++++++++++++ crates/knock-core/src/lib.rs | 4 + crates/knock-core/src/prepare.rs | 4 + crates/knock-core/src/runner.rs | 310 ++++++ crates/knock-core/src/ws.rs | 135 +++ .../tests/fixtures/bruno/Health.bru | 16 + .../tests/fixtures/bruno/Search.bru | 23 + .../tests/fixtures/bruno/auth/Login.bru | 44 + .../tests/fixtures/bruno/auth/folder.bru | 4 + .../tests/fixtures/bruno/bruno.json | 6 + .../tests/fixtures/bruno/collection.bru | 19 + .../fixtures/bruno/environments/Local.bru | 4 + .../bruno/environments/Production.bru | 6 + .../fixtures/bruno/users/Create user.bru | 28 + .../tests/fixtures/bruno/users/List users.bru | 16 + .../fixtures/bruno/users/Upload avatar.bru | 17 + .../tests/fixtures/bruno/users/folder.bru | 12 + packaging/arch/knock-bin/PKGBUILD | 19 + packaging/arch/knock/PKGBUILD | 46 + packaging/linux/de.joshicodes.knock.desktop | 13 + packaging/linux/knock.desktop.hbs | 13 + src-tauri/Cargo.toml | 1 + src-tauri/src/commands.rs | 176 ++++ src-tauri/src/lib.rs | 15 + src-tauri/src/ws.rs | 209 ++++ src-tauri/tauri.conf.json | 33 +- src/lib/json/parse.worker.ts | 11 + src/lib/json/parseAsync.ts | 29 + src/lib/state/wslog.svelte.ts | 65 ++ src/lib/views/dialogs/CodeDialog.svelte | 67 +- src/lib/views/dialogs/ImportDialog.svelte | 135 ++- src/lib/views/dialogs/RunnerDialog.svelte | 146 ++- src/lib/views/response/BodyView.svelte | 33 +- .../views/settings/CollectionSettings.svelte | 15 +- src/lib/views/settings/EnvironmentView.svelte | 14 + src/lib/views/ws/WsView.svelte | 280 ++++- 51 files changed, 8437 insertions(+), 24 deletions(-) create mode 100644 .gitea/workflows/ci.yml create mode 100644 README.md create mode 100644 crates/knock-cli/Cargo.toml create mode 100644 crates/knock-cli/src/main.rs create mode 100644 crates/knock-core/src/export/mod.rs create mode 100644 crates/knock-core/src/export/postman.rs create mode 100644 crates/knock-core/src/export/snippet.rs create mode 100644 crates/knock-core/src/import/bruno.rs create mode 100644 crates/knock-core/src/import/curl.rs create mode 100644 crates/knock-core/src/import/insomnia.rs create mode 100644 crates/knock-core/src/import/mod.rs create mode 100644 crates/knock-core/src/import/openapi.rs create mode 100644 crates/knock-core/src/import/postman.rs create mode 100644 crates/knock-core/src/runner.rs create mode 100644 crates/knock-core/src/ws.rs create mode 100644 crates/knock-core/tests/fixtures/bruno/Health.bru create mode 100644 crates/knock-core/tests/fixtures/bruno/Search.bru create mode 100644 crates/knock-core/tests/fixtures/bruno/auth/Login.bru create mode 100644 crates/knock-core/tests/fixtures/bruno/auth/folder.bru create mode 100644 crates/knock-core/tests/fixtures/bruno/bruno.json create mode 100644 crates/knock-core/tests/fixtures/bruno/collection.bru create mode 100644 crates/knock-core/tests/fixtures/bruno/environments/Local.bru create mode 100644 crates/knock-core/tests/fixtures/bruno/environments/Production.bru create mode 100644 crates/knock-core/tests/fixtures/bruno/users/Create user.bru create mode 100644 crates/knock-core/tests/fixtures/bruno/users/List users.bru create mode 100644 crates/knock-core/tests/fixtures/bruno/users/Upload avatar.bru create mode 100644 crates/knock-core/tests/fixtures/bruno/users/folder.bru create mode 100644 packaging/arch/knock-bin/PKGBUILD create mode 100644 packaging/arch/knock/PKGBUILD create mode 100644 packaging/linux/de.joshicodes.knock.desktop create mode 100644 packaging/linux/knock.desktop.hbs create mode 100644 src-tauri/src/ws.rs create mode 100644 src/lib/json/parse.worker.ts create mode 100644 src/lib/json/parseAsync.ts create mode 100644 src/lib/state/wslog.svelte.ts diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..477cc2f --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,53 @@ +name: ci + +on: + push: + branches: [main] + tags: ['v*'] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + container: rust:1-bookworm + steps: + - uses: actions/checkout@v4 + - run: apt-get update && apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev librsvg2-dev libdbus-1-dev pkg-config + - run: cargo test -p knock-core --locked + + # The oldest supported Ubuntu builds the .deb, so glibc and WebKitGTK fit 22.04 and newer. + deb: + needs: test + if: startsWith(github.ref, 'refs/tags/v') + runs-on: ubuntu-latest + container: ubuntu:22.04 + steps: + - uses: actions/checkout@v4 + - run: | + apt-get update + DEBIAN_FRONTEND=noninteractive apt-get install -y curl build-essential pkg-config file \ + libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev libdbus-1-dev libssl-dev + curl -fsSL https://deb.nodesource.com/setup_22.x | bash - + apt-get install -y nodejs + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal + - run: | + . "$HOME/.cargo/env" + npm ci + cargo build --release -p knock-cli --locked + npx tauri build --bundles deb,rpm,appimage + - name: Smoke test on Ubuntu 22.04 + run: | + apt-get install -y ./target/release/bundle/deb/*.deb xvfb python3 + python3 -m http.server 18765 >/dev/null 2>&1 & + mkdir -p /tmp/c/environments + printf 'version: 1\nname: Smoke\n' > /tmp/c/knock.yaml + printf 'name: Root\nurl: http://127.0.0.1:18765/\nassert:\n - { on: status, equals: 200 }\n' > /tmp/c/root.yaml + knock run /tmp/c + timeout 10 xvfb-run -a knock-app || [ $? -eq 124 ] + - uses: actions/upload-artifact@v3 + with: + name: bundles + path: | + target/release/bundle/deb/*.deb + target/release/bundle/rpm/*.rpm + target/release/bundle/appimage/*.AppImage diff --git a/Cargo.lock b/Cargo.lock index e9a2dc7..952216c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -87,6 +87,56 @@ dependencies = [ "libc", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.105" @@ -701,6 +751,46 @@ dependencies = [ "inout 0.2.6", ] +[[package]] +name = "clap" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + [[package]] name = "cmake" version = "0.1.58" @@ -728,6 +818,12 @@ dependencies = [ "x509-cert", ] +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "combine" version = "4.6.9" @@ -2446,6 +2542,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "is-terminal" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" +dependencies = [ + "hermit-abi", + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "is-wsl" version = "0.4.0" @@ -2456,6 +2563,18 @@ dependencies = [ "once_cell", ] +[[package]] +name = "is_ci" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7655c9839580ee829dfacba1d1278c2b7883e50a277ff7541299489d6bdfdc45" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itoa" version = "1.0.19" @@ -2773,11 +2892,27 @@ dependencies = [ "tauri-plugin-opener", "tauri-plugin-single-instance", "tokio", + "tokio-tungstenite", "tracing", "url", "uuid", ] +[[package]] +name = "knock-cli" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "futures-util", + "indexmap 2.14.2", + "knock-core", + "open", + "owo-colors", + "serde_json", + "tokio", +] + [[package]] name = "knock-core" version = "0.1.0" @@ -2801,6 +2936,7 @@ dependencies = [ "regex", "reqwest", "rsa", + "rustls", "serde", "serde_json", "serde_json_path", @@ -2809,6 +2945,7 @@ dependencies = [ "sha2 0.10.9", "thiserror 2.0.21", "tokio", + "tokio-tungstenite", "tracing", "url", "uuid", @@ -3517,6 +3654,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "open" version = "5.4.5" @@ -3560,6 +3703,16 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "owo-colors" +version = "4.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c45bb4a6ae1280ec0803b1ef9d3455eb50f01efbbe1447ab020f1d54fba9d8" +dependencies = [ + "supports-color 2.1.0", + "supports-color 3.0.2", +] + [[package]] name = "p12-keystore" version = "0.4.1" @@ -5251,6 +5404,25 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "supports-color" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6398cde53adc3c4557306a96ce67b302968513830a77a95b2b17305d9719a89" +dependencies = [ + "is-terminal", + "is_ci", +] + +[[package]] +name = "supports-color" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c64fc7232dd8d2e4ac5ce4ef302b1d81e0b80d055b9d77c7c4f51f6aa4c867d6" +dependencies = [ + "is_ci", +] + [[package]] name = "swift-rs" version = "1.0.9" @@ -5903,6 +6075,22 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" +dependencies = [ + "futures-util", + "log", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.20" @@ -6122,6 +6310,24 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.10.4", + "rustls", + "rustls-pki-types", + "sha1 0.11.0", + "thiserror 2.0.21", +] + [[package]] name = "typeid" version = "1.0.3" @@ -6225,6 +6431,12 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" diff --git a/Cargo.toml b/Cargo.toml index 6df7128..15e21c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["crates/knock-core", "src-tauri"] +members = ["crates/knock-core", "crates/knock-cli", "src-tauri"] [workspace.package] version = "0.1.0" diff --git a/README.md b/README.md new file mode 100644 index 0000000..e148479 --- /dev/null +++ b/README.md @@ -0,0 +1,85 @@ +

knockknock

+ +An offline desktop API client for REST, GraphQL and WebSocket. No account, no cloud, no telemetry. Collections are folders of YAML files that live in your git repository. + +## What makes it different + +- **JSON bodies without typing brackets.** Every JSON body has a form view (keys, types, values, drag to reorder) and a code view on the same text. Switching is lossless: key order, `{{variables}}` as raw values and numbers larger than 2^53 survive. Attach a JSON Schema and the form suggests fields, marks required ones and validates while you type. +- **OAuth that shows its work.** Enter the issuer, knock runs discovery. The redirect URI sits at the top with a copy button. Log in once; knock refreshes tokens, retries once after a 401 and attaches them. When something fails, the auth debugger marks the step, shows the raw exchange, offers it as cURL and explains the provider's error in plain words. + +## Features + +- HTTP/1.1 and HTTP/2, every method, query and path parameters synced with the URL, all body types, timeouts, redirect chain, TLS options, proxies, extra CA bundles, client certificates (PEM, PKCS#12), cookie jar per collection +- Auth: Basic, Bearer, API key, Digest, JWT, AWS SigV4, OAuth 1.0a, OAuth 2.0 (authorization code + PKCE, client credentials, device code, password), OpenID Connect with ID token validation against the JWKS +- Variables in every field with scopes runtime → request → folder → environment → collection → global, hover for value and origin, dynamic values (`{{$uuid}}`, `{{$timestamp}}`, …), extract rules for chaining +- Secrets in the system keyring (Secret Service / KWallet) or a gitignored `*.secrets.yaml`, masked in history and exports +- Response viewer with JSON tree, search and JSONPath filter, previews for HTML, images and PDF, diff against the previous response, timeline, bodies up to 50 MB without freezing +- GraphQL with schema introspection, autocomplete and an explorer; WebSocket with composer, saved messages and a live log +- Assertions, a runner for folders and collections, JUnit and JSON reports +- Import from Postman, Bruno, Insomnia, OpenAPI and cURL; code snippets for cURL, fetch, Python, HTTPie, Go and PowerShell + +## Collection format + +``` +my-api/ + knock.yaml # name, collection auth, headers, variables + environments/ + local.yaml + prod.yaml + prod.secrets.yaml # gitignored + users/ + folder.yaml # folder auth, headers, variables, order + create-user.yaml +``` + +```yaml +name: Create user +type: http +method: POST +url: "{{baseUrl}}/users" +auth: inherit +body: + type: json + content: | + { + "name": "{{userName}}", + "roles": ["admin"] + } +extract: + - { var: userId, from: json, path: $.id } +assert: + - { on: status, equals: 201 } +``` + +Unknown fields are kept when knock saves a file, and changes from git or an editor are picked up live. + +## Command line + +```sh +knock send users/create-user.yaml --env local +knock run . --env staging --reporter junit --output report.xml +knock auth login users --env prod # browser login, token shared with the app +knock auth debug users --env prod --verbose +``` + +`knock run` exits with 1 when an assertion fails. In CI, secrets come from `KNOCK_SECRET_` environment variables (set `KNOCK_NO_KEYRING=1` where no keyring exists). + +## Building + +Requirements: Rust (stable), Node.js 20+, and on Linux `webkit2gtk-4.1`, `gtk3`, `libsecret`. + +```sh +npm ci +npm run tauri dev # run the app +npm run tauri build # deb, rpm, AppImage in target/release/bundle +cargo build --release -p knock-cli +cargo test -p knock-core +``` + +Arch Linux: `packaging/arch/knock` builds from source, `packaging/arch/knock-bin` repackages the release `.deb`. + +If the window stays blank on Wayland, WebKitGTK's DMA-BUF renderer is the usual cause; knock turns it off by default. Set `KNOCK_DMABUF=1` to turn it back on. + +## License + +MIT diff --git a/crates/knock-cli/Cargo.toml b/crates/knock-cli/Cargo.toml new file mode 100644 index 0000000..a85d89c --- /dev/null +++ b/crates/knock-cli/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "knock-cli" +description = "Command line runner for knock collections" +version.workspace = true +edition.workspace = true +license.workspace = true + +[[bin]] +name = "knock" +path = "src/main.rs" + +[dependencies] +knock-core.workspace = true +anyhow.workspace = true +serde_json.workspace = true +indexmap.workspace = true +tokio.workspace = true +futures-util = "0.3" +clap = { version = "4.6", features = ["derive"] } +open = "5" +owo-colors = { version = "4", features = ["supports-colors"] } diff --git a/crates/knock-cli/src/main.rs b/crates/knock-cli/src/main.rs new file mode 100644 index 0000000..48c84b1 --- /dev/null +++ b/crates/knock-cli/src/main.rs @@ -0,0 +1,531 @@ +use anyhow::{anyhow, bail, Context, Result}; +use clap::{Parser, Subcommand, ValueEnum}; +use futures_util::future::BoxFuture; +use knock_core::auth::{AuthHost, OauthResult, Step, StepStatus}; +use knock_core::collection::Collection; +use knock_core::http::Engine; +use knock_core::model::{Auth, AuthConfig}; +use knock_core::oauth::{self, config::OauthConfig, FlowHooks, TokenSet}; +use knock_core::prepare::{ContextInput, RequestContext}; +use knock_core::runner::{self, RunDeps, RunOptions}; +use knock_core::secrets::{self, SecretStore}; +use knock_core::vars::{Resolver, MASK}; +use owo_colors::{OwoColorize, Stream::Stdout}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +#[derive(Parser)] +#[command(name = "knock", version, about = "Send requests and run knock collections from the terminal")] +struct Cli { + #[command(subcommand)] + cmd: Cmd, +} + +#[derive(Subcommand)] +enum Cmd { + /// Send one request file and print the response + Send { + file: PathBuf, + #[arg(short, long)] + env: Option, + /// Print response headers too + #[arg(short, long)] + verbose: bool, + /// Set a variable, e.g. --var userId=42 (repeatable) + #[arg(long = "var", value_name = "NAME=VALUE")] + vars: Vec, + }, + /// Run every request in a folder (or the whole collection) in order + Run { + /// Collection root or a folder inside it + path: PathBuf, + #[arg(short, long)] + env: Option, + #[arg(short, long, value_enum, default_value = "pretty")] + reporter: Reporter, + /// Write the report to a file instead of stdout + #[arg(short, long)] + output: Option, + /// Stop at the first failing request + #[arg(long)] + bail: bool, + /// Pause between requests, in milliseconds + #[arg(long, default_value_t = 0)] + delay: u64, + #[arg(long = "var", value_name = "NAME=VALUE")] + vars: Vec, + }, + /// Import Postman, Bruno, Insomnia, OpenAPI or a cURL command into a new collection + Import { + /// File, Bruno folder, or "-" to read from stdin + source: PathBuf, + /// Folder for the new collection (must be empty or not exist) + dest: PathBuf, + }, + /// OAuth 2.0 / OpenID Connect helpers + Auth { + #[command(subcommand)] + cmd: AuthCmd, + }, +} + +#[derive(Subcommand)] +enum AuthCmd { + /// Log in with the browser and store the tokens (shared with the app) + Login { + /// Request, folder or collection whose OAuth settings to use + path: PathBuf, + #[arg(short, long)] + env: Option, + }, + /// Walk through the token flow step by step + Debug { + path: PathBuf, + #[arg(short, long)] + env: Option, + /// Show raw HTTP exchanges + #[arg(long)] + verbose: bool, + /// Show tokens and secrets in clear text (masked by default) + #[arg(long)] + reveal: bool, + }, + /// Forget stored tokens for this config and environment + Logout { + path: PathBuf, + #[arg(short, long)] + env: Option, + }, +} + +#[derive(Clone, Copy, ValueEnum)] +enum Reporter { + Pretty, + Json, + Junit, +} + +fn main() { + let cli = Cli::parse(); + let rt = tokio::runtime::Runtime::new().expect("tokio runtime"); + let code = match rt.block_on(dispatch(cli)) { + Ok(code) => code, + Err(e) => { + eprintln!("{} {e:#}", "error:".if_supports_color(Stdout, |t| t.red())); + 2 + } + }; + std::process::exit(code); +} + +async fn dispatch(cli: Cli) -> Result { + match cli.cmd { + Cmd::Send { file, env, verbose, vars } => send(&file, env, verbose, parse_vars(&vars)?).await, + Cmd::Run { path, env, reporter, output, bail, delay, vars } => { + run(&path, env, reporter, output, bail, delay, parse_vars(&vars)?).await + } + Cmd::Import { source, dest } => import(&source, &dest), + Cmd::Auth { cmd } => auth(cmd).await, + } +} + +fn parse_vars(v: &[String]) -> Result> { + v.iter() + .map(|s| { + s.split_once('=') + .map(|(a, b)| (a.to_string(), b.to_string())) + .ok_or_else(|| anyhow!("--var expects NAME=VALUE, got '{s}'")) + }) + .collect() +} + +/// Walks up from `path` to the folder that holds knock.yaml. Returns the +/// collection and the id of `path` inside it. +fn locate(path: &Path) -> Result<(Collection, String)> { + let abs = path.canonicalize().with_context(|| format!("{} not found", path.display()))?; + let mut dir = if abs.is_dir() { abs.clone() } else { abs.parent().map(Path::to_path_buf).unwrap_or_default() }; + loop { + if dir.join("knock.yaml").exists() { + let c = Collection::open(&dir)?; + let id = abs.strip_prefix(&c.root).unwrap_or(Path::new("")).to_string_lossy().replace('\\', "/"); + return Ok((c, id)); + } + if !dir.pop() { + bail!("{} is not inside a knock collection (no knock.yaml found above it)", path.display()); + } + } +} + +fn secrets_for(c: &Collection, env: Option<&str>) -> Arc { + let file = env.map(|e| c.secrets_file(e).unwrap_or_default()).unwrap_or_default(); + // In CI there is usually no keyring; KNOCK_SECRET_* and the secrets file still work. + let keyring = std::env::var_os("KNOCK_NO_KEYRING").is_none(); + Arc::new(SecretStore::new(&c.manifest.id, env, file.vars, keyring)) +} + +// ---------------------------------------------------------------- OAuth host + +struct CliHooks { + verbose: bool, + reveal: bool, + print: bool, +} + +impl FlowHooks for CliHooks { + fn interactive(&self) -> bool { + true + } + fn open_browser(&self, url: &str) -> Result<(), String> { + eprintln!("Opening the browser. If nothing happens, open:\n {url}\n"); + open::that(url).map_err(|e| e.to_string()) + } + fn wait_external(&self) -> BoxFuture<'static, Option> { + Box::pin(async { + eprintln!("Paste the URL you were redirected to (or the code) and press Enter:"); + tokio::task::spawn_blocking(|| { + let mut s = String::new(); + std::io::stdin().read_line(&mut s).ok().map(|_| s.trim().to_string()) + }) + .await + .ok() + .flatten() + }) + } + fn progress(&self, step: &Step) { + if self.print { + print_step(step, self.verbose, self.reveal); + } + } + fn device_prompt(&self, uri: &str, code: &str, _complete: Option<&str>) { + eprintln!("\nOpen {uri} and enter the code\n\n {}\n", code.if_supports_color(Stdout, |t| t.bold())); + } + fn load_token(&self, key: &str) -> Option { + secrets::slot_get(key).and_then(|s| serde_json::from_str(&s).ok()) + } + fn save_token(&self, key: &str, t: &TokenSet) { + if let Ok(s) = serde_json::to_string(t) { + if let Err(e) = secrets::slot_set(key, &s) { + eprintln!("warning: could not store the token in the keyring: {e:#}"); + } + } + } + fn delete_token(&self, key: &str) { + let _ = secrets::slot_delete(key); + } +} + +struct CliHost { + collection: String, + env: Option, +} + +impl AuthHost for CliHost { + fn oauth2_token(&self, cfg: &AuthConfig, resolver: &Resolver, force_refresh: bool) -> BoxFuture<'_, OauthResult> { + let oc = OauthConfig::from_auth(cfg, resolver); + let key = oc.store_key(&self.collection, self.env.as_deref()); + Box::pin(async move { + let hooks = CliHooks { verbose: false, reveal: false, print: false }; + let r = oauth::obtain(&oc, &key, &hooks, force_refresh).await; + OauthResult { token: r.token, steps: r.steps, flow_id: None, warnings: r.warnings } + }) + } +} + +fn mask(s: &str, reveal: bool) -> String { + if reveal { + return s.to_string(); + } + regex_like_mask(s) +} + +/// Masks JWTs and token-looking parameter values. +fn regex_like_mask(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for word in s.split_inclusive([' ', '&', '"', ',', '\n']) { + let trimmed = word.trim_end_matches([' ', '&', '"', ',', '\n']); + let tail = &word[trimmed.len()..]; + let masked = if trimmed.starts_with("eyJ") && trimmed.matches('.').count() == 2 { + MASK.to_string() + } else if let Some((k, _)) = trimmed.split_once('=').filter(|(k, _)| { + ["access_token", "refresh_token", "id_token", "client_secret", "code", "password", "code_verifier", "device_code"].contains(k) + }) { + format!("{k}={MASK}") + } else { + trimmed.to_string() + }; + out.push_str(&masked); + out.push_str(tail); + } + out +} + +fn print_step(s: &Step, verbose: bool, reveal: bool) { + let (mark, color): (&str, fn(&str) -> String) = match s.status { + StepStatus::Ok => ("✓", |t| t.if_supports_color(Stdout, |x| x.green()).to_string()), + StepStatus::Error => ("✗", |t| t.if_supports_color(Stdout, |x| x.red()).to_string()), + StepStatus::Skipped => ("–", |t| t.if_supports_color(Stdout, |x| x.dimmed()).to_string()), + StepStatus::Pending => ("…", |t| t.if_supports_color(Stdout, |x| x.cyan()).to_string()), + StepStatus::Warning => ("!", |t| t.if_supports_color(Stdout, |x| x.yellow()).to_string()), + }; + let ms = if s.duration_ms > 0.0 { format!(" ({:.0} ms)", s.duration_ms) } else { String::new() }; + println!("{} {} {}{}", color(mark), s.title.if_supports_color(Stdout, |t| t.bold()), mask(&s.summary, reveal), ms.if_supports_color(Stdout, |t| t.dimmed())); + if s.status == StepStatus::Error { + println!(" {}", "This is where it failed.".if_supports_color(Stdout, |t| t.red())); + } + if let Some(h) = &s.hint { + for line in mask(h, reveal).lines() { + println!(" {}", line.if_supports_color(Stdout, |t| t.dimmed())); + } + } + if verbose { + if let Some(x) = &s.exchange { + println!(" {}", "─ request".if_supports_color(Stdout, |t| t.dimmed())); + for l in mask(&x.curl, reveal).lines() { + println!(" {l}"); + } + if let Some(st) = x.status { + println!(" {} HTTP {st}", "─ response".if_supports_color(Stdout, |t| t.dimmed())); + for l in mask(&x.response_body, reveal).lines().take(40) { + println!(" {l}"); + } + } + } + } +} + +// ---------------------------------------------------------------- commands + +async fn send(file: &Path, env: Option, verbose: bool, vars: indexmap::IndexMap) -> Result { + let (c, id) = locate(file)?; + let req = c.request(&id)?; + let ctx = RequestContext::build(ContextInput { + collection: &c, + request_id: &id, + request: &req, + env: env.as_deref(), + runtime: vars, + globals: Default::default(), + secrets: secrets_for(&c, env.as_deref()), + oauth: None, + })?; + let engine = Engine::new(std::env::temp_dir().join("knock-cli")); + let host = CliHost { collection: c.manifest.id.clone(), env: env.clone() }; + let out = knock_core::run::execute(&engine, &req, &ctx, Some(&host)).await; + if let Some(e) = &out.error { + eprintln!("{} {}", "error:".if_supports_color(Stdout, |t| t.red()), ctx.resolver.mask(e)); + for s in out.auth.steps.iter().filter(|s| s.status == StepStatus::Error) { + print_step(s, false, false); + } + return Ok(1); + } + let Some(resp) = &out.response else { return Ok(1) }; + let status = format!("{} {}", resp.status, resp.status_text); + let colored = if resp.status < 300 { + status.if_supports_color(Stdout, |t| t.green()).to_string() + } else if resp.status < 400 { + status.if_supports_color(Stdout, |t| t.yellow()).to_string() + } else { + status.if_supports_color(Stdout, |t| t.red()).to_string() + }; + eprintln!("{colored} {:.0} ms {} bytes", resp.timings.total_ms, resp.size); + if verbose { + for (k, v) in &resp.headers { + eprintln!("{}: {v}", k.if_supports_color(Stdout, |t| t.cyan())); + } + eprintln!(); + } + match resp.json() { + Some(j) => println!("{}", serde_json::to_string_pretty(&j)?), + None => println!("{}", resp.text()), + } + let failed: Vec<_> = out.asserts.iter().filter(|a| !a.passed).collect(); + for a in &out.asserts { + let mark = if a.passed { "✓".if_supports_color(Stdout, |t| t.green()).to_string() } else { "✗".if_supports_color(Stdout, |t| t.red()).to_string() }; + eprintln!("{mark} {}{}", a.label, if a.passed { String::new() } else { format!(" (expected {}, got {})", a.expected, a.actual) }); + } + Ok(if failed.is_empty() { 0 } else { 1 }) +} + +async fn run( + path: &Path, + env: Option, + reporter: Reporter, + output: Option, + bail: bool, + delay: u64, + vars: indexmap::IndexMap, +) -> Result { + let (c, id) = locate(path)?; + let engine = Engine::new(std::env::temp_dir().join("knock-cli")); + let host = CliHost { collection: c.manifest.id.clone(), env: env.clone() }; + let deps = RunDeps { engine: &engine, secrets: secrets_for(&c, env.as_deref()), oauth: None, host: Some(&host) }; + let opts = RunOptions { env: env.clone(), bail, delay_ms: delay, runtime: vars, ..Default::default() }; + let pretty = matches!(reporter, Reporter::Pretty); + let report = runner::run(&c, &id, &opts, &deps, |_, _, it| { + if !pretty { + return; + } + let mark = if it.skipped { + "–".if_supports_color(Stdout, |t| t.dimmed()).to_string() + } else if it.passed { + "✓".if_supports_color(Stdout, |t| t.green()).to_string() + } else { + "✗".if_supports_color(Stdout, |t| t.red()).to_string() + }; + let status = it.status.map(|s| s.to_string()).unwrap_or_else(|| "ERR".into()); + println!("{mark} {:<7} {:<4} {:>6.0} ms {}", it.method, status, it.ms, it.name); + for a in it.asserts.iter().filter(|a| !a.passed) { + println!(" {} expected {}, got {}", a.label, a.expected, a.actual); + } + if let Some(e) = &it.error { + println!(" {}", e.if_supports_color(Stdout, |t| t.dimmed())); + } + }) + .await; + let text = match reporter { + Reporter::Pretty => format!( + "\n{} passed, {} failed, {} skipped in {:.1} s\n", + report.passed, report.failed, report.skipped, report.total_ms / 1000.0 + ), + Reporter::Json => runner::to_json(&report), + Reporter::Junit => runner::to_junit(&report), + }; + match output { + Some(p) => std::fs::write(&p, text).with_context(|| format!("writing {}", p.display()))?, + None => print!("{text}"), + } + Ok(if report.ok() { 0 } else { 1 }) +} + +/// Finds the OAuth config that applies at `path` (request, folder or collection). +fn oauth_config(path: &Path, env: Option<&str>) -> Result<(Collection, OauthConfig, String)> { + let (c, id) = locate(path)?; + let abs = c.abs(&id)?; + let (auth, req) = if abs.is_file() { + let req = c.request(&id)?; + let anc = c.ancestors(&id)?; + (knock_core::prepare::effective_auth(&c, &id, &req.auth, &anc).auth, req) + } else { + let mut auth = c.manifest.auth.clone(); + let mut cur = String::new(); + for part in id.split('/').filter(|p| !p.is_empty()) { + cur = if cur.is_empty() { part.to_string() } else { format!("{cur}/{part}") }; + let m = c.folder_meta(&cur)?; + if !m.auth.is_inherit() { + auth = m.auth; + } + } + (auth, Default::default()) + }; + let Auth::Config(cfg) = auth else { bail!("no OAuth settings apply at {}", path.display()) }; + if cfg.kind != "oauth2" && cfg.kind != "oidc" { + bail!("the auth at {} is {}, not OAuth", path.display(), cfg.kind); + } + let ctx = RequestContext::build(ContextInput { + collection: &c, + request_id: if id.is_empty() || abs.is_dir() { "__cli__.yaml" } else { &id }, + request: &req, + env, + runtime: Default::default(), + globals: Default::default(), + secrets: secrets_for(&c, env), + oauth: None, + })?; + let oc = OauthConfig::from_auth(&cfg, &ctx.resolver); + let key = oc.store_key(&c.manifest.id, env); + Ok((c, oc, key)) +} + +async fn auth(cmd: AuthCmd) -> Result { + match cmd { + AuthCmd::Login { path, env } => { + let (_, oc, key) = oauth_config(&path, env.as_deref())?; + let hooks = CliHooks { verbose: false, reveal: false, print: true }; + hooks.delete_token(&key); + let r = oauth::obtain(&oc, &key, &hooks, true).await; + Ok(if r.tokens.is_some() { + println!("\n{}", "Logged in. The app and `knock run` use this token now.".if_supports_color(Stdout, |t| t.green())); + 0 + } else { + 1 + }) + } + AuthCmd::Debug { path, env, verbose, reveal } => { + let (_, oc, key) = oauth_config(&path, env.as_deref())?; + let hooks = CliHooks { verbose, reveal, print: true }; + let r = oauth::obtain(&oc, &key, &hooks, false).await; + for w in &r.warnings { + println!("{} {w}", "!".if_supports_color(Stdout, |t| t.yellow())); + } + if let Some(t) = &r.tokens { + println!(); + println!("access token {}", mask(&t.access_token, reveal)); + if let Some(s) = t.seconds_left() { + println!("expires in {}", oauth::human(s)); + } + if let Some(claims) = oauth::idtoken::claims(&t.access_token) { + for k in ["iss", "aud", "sub", "scope", "azp"] { + if let Some(v) = claims.get(k) { + println!("{k:<13} {v}"); + } + } + } + } + Ok(if r.tokens.is_some() { 0 } else { 1 }) + } + AuthCmd::Logout { path, env } => { + let (_, _, key) = oauth_config(&path, env.as_deref())?; + secrets::slot_delete(&key)?; + println!("Token removed."); + Ok(0) + } + } +} + +fn import(source: &Path, dest: &Path) -> Result { + use knock_core::import::{self, Kind}; + let report = if source.is_dir() { + import::import_bruno(source, dest)? + } else { + let text = if source == Path::new("-") { + let mut s = String::new(); + std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?; + s + } else { + std::fs::read_to_string(source).with_context(|| format!("reading {}", source.display()))? + }; + match import::detect(&text) { + Some(Kind::PostmanCollection) => import::import_postman(&text, dest)?, + Some(Kind::Insomnia) => import::import_insomnia(&text, dest)?, + Some(Kind::Openapi) => import::import_openapi(&text, dest)?, + Some(Kind::Curl) => { + let mut req = import::parse_curl(&text)?; + let c = Collection::create(dest, "Imported")?; + let mut store = indexmap::IndexMap::new(); + import::externalize_secrets(&mut req.auth, "curl", &mut store); + if !store.is_empty() { + let mut f = c.secrets_file("local")?; + f.vars.extend(store); + c.save_secrets_file("local", &f)?; + } + c.create_request("", &req)?; + import::ImportReport { collection_root: c.root.clone(), requests: 1, ..Default::default() } + } + Some(Kind::PostmanEnvironment) => bail!("this is a Postman environment; import the collection first"), + None => bail!("unknown format; knock imports Postman, Bruno, Insomnia, OpenAPI and cURL"), + } + }; + println!( + "Imported {} requests in {} folders into {}", + report.requests, + report.folders, + report.collection_root.display() + ); + if report.scripts_skipped > 0 { + println!("{} scripts were kept in the request docs and not run.", report.scripts_skipped); + } + for w in &report.warnings { + println!("{} {w}", "!".if_supports_color(Stdout, |t| t.yellow())); + } + Ok(0) +} diff --git a/crates/knock-core/Cargo.toml b/crates/knock-core/Cargo.toml index c748e2d..bc83ace 100644 --- a/crates/knock-core/Cargo.toml +++ b/crates/knock-core/Cargo.toml @@ -36,3 +36,5 @@ hex = "0.4" jsonwebtoken = { version = "12", default-features = false, features = ["aws_lc_rs", "use_pem"] } rsa = { version = "0.9", features = ["sha1", "sha2"] } p12-keystore = "0.4" +tokio-tungstenite = { version = "0.30", features = ["rustls-tls-native-roots"] } +rustls = { version = "0.23", default-features = false, features = ["aws_lc_rs", "std"] } diff --git a/crates/knock-core/src/export/mod.rs b/crates/knock-core/src/export/mod.rs new file mode 100644 index 0000000..20de72f --- /dev/null +++ b/crates/knock-core/src/export/mod.rs @@ -0,0 +1,7 @@ +//! Code snippets for a prepared request and Postman collection export. + +pub mod postman; +pub mod snippet; + +pub use postman::export_postman; +pub use snippet::{snippet, Lang}; diff --git a/crates/knock-core/src/export/postman.rs b/crates/knock-core/src/export/postman.rs new file mode 100644 index 0000000..692126c --- /dev/null +++ b/crates/knock-core/src/export/postman.rs @@ -0,0 +1,403 @@ +//! Postman Collection v2.1 export. Variables, including `{{secret.x}}`, are +//! written as placeholders and never resolved. + +use crate::collection::{Collection, FolderNode, Node}; +use crate::model::*; +use anyhow::Result; +use serde_json::{json, Map, Value}; + +const SCHEMA: &str = "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"; + +pub fn export_postman(c: &Collection) -> Result { + let m = &c.manifest; + let mut info = json!({ + "_postman_id": m.id, + "name": m.name, + "schema": SCHEMA, + }); + if let Some(d) = m.extra.get("docs").and_then(|d| d.as_str()) { + info["description"] = Value::String(d.to_string()); + } + let mut root = Map::new(); + root.insert("info".into(), info); + root.insert("item".into(), Value::Array(items(c, &c.tree, &m.headers)?)); + if let Some(a) = auth(&m.auth) { + root.insert("auth".into(), a); + } + if !m.vars.is_empty() { + root.insert("variable".into(), variables(&m.vars)); + } + Ok(serde_json::to_string_pretty(&Value::Object(root))?) +} + +fn variables(vars: &indexmap::IndexMap) -> Value { + Value::Array(vars.iter().map(|(k, v)| json!({ "key": k, "value": v })).collect()) +} + +/// Postman has no folder headers, so inherited headers are copied into each request. +fn items(c: &Collection, folder: &FolderNode, inherited: &[KeyValue]) -> Result> { + let mut out = Vec::new(); + for child in &folder.children { + match child { + Node::Folder(f) => { + let meta = c.folder_meta(&f.id)?; + let mut headers = inherited.to_vec(); + merge_headers(&mut headers, &meta.headers); + let mut item = Map::new(); + item.insert("name".into(), Value::String(f.name.clone())); + item.insert("item".into(), Value::Array(items(c, f, &headers)?)); + if let Some(a) = auth(&meta.auth) { + item.insert("auth".into(), a); + } + if !meta.vars.is_empty() { + item.insert("variable".into(), variables(&meta.vars)); + } + if let Some(d) = meta.extra.get("docs").and_then(|d| d.as_str()) { + item.insert("description".into(), Value::String(d.to_string())); + } + out.push(Value::Object(item)); + } + Node::Request(head) => { + let req = c.request(&head.id)?; + if req.kind == RequestKind::Ws { + continue; + } + out.push(request_item(&req, inherited)); + } + } + } + Ok(out) +} + +fn merge_headers(into: &mut Vec, own: &[KeyValue]) { + for h in own { + into.retain(|x| !x.name.eq_ignore_ascii_case(&h.name)); + } + into.extend(own.iter().cloned()); +} + +fn request_item(req: &Request, inherited: &[KeyValue]) -> Value { + let mut headers = inherited.to_vec(); + merge_headers(&mut headers, &req.headers); + + let mut r = Map::new(); + r.insert("method".into(), Value::String(req.method().to_string())); + let mut header_list: Vec = headers.iter().map(kv).collect(); + + let body = match req.kind { + RequestKind::Graphql => { + let g = req.graphql.clone().unwrap_or_default(); + Some(json!({ "mode": "graphql", "graphql": { "query": g.query, "variables": g.variables } })) + } + _ => body(&req.body, &headers, &mut header_list), + }; + r.insert("header".into(), Value::Array(header_list)); + if let Some(b) = body { + r.insert("body".into(), b); + } + r.insert("url".into(), url(req)); + if let Some(a) = auth(&req.auth) { + r.insert("auth".into(), a); + } + if let Some(d) = &req.docs { + r.insert("description".into(), Value::String(d.clone())); + } + + let mut item = Map::new(); + item.insert("name".into(), Value::String(req.name.clone())); + item.insert("request".into(), Value::Object(r)); + let mut ppb = Map::new(); + if !req.settings.follow_redirects { + ppb.insert("followRedirects".into(), Value::Bool(false)); + } + if !req.settings.verify_tls { + ppb.insert("strictSSL".into(), Value::Bool(false)); + } + if req.settings.max_redirects != RequestSettings::default().max_redirects { + ppb.insert("maxRedirects".into(), json!(req.settings.max_redirects)); + } + if !ppb.is_empty() { + item.insert("protocolProfileBehavior".into(), Value::Object(ppb)); + } + item.insert("response".into(), json!([])); + Value::Object(item) +} + +fn kv(h: &KeyValue) -> Value { + let mut o = Map::new(); + o.insert("key".into(), Value::String(h.name.clone())); + o.insert("value".into(), Value::String(h.value.clone())); + if !h.enabled { + o.insert("disabled".into(), Value::Bool(true)); + } + if let Some(d) = &h.description { + o.insert("description".into(), Value::String(d.clone())); + } + Value::Object(o) +} + +fn body(b: &Body, headers: &[KeyValue], header_list: &mut Vec) -> Option { + let has_ct = headers.iter().any(|h| h.enabled && h.name.eq_ignore_ascii_case("content-type")); + match b.kind { + BodyType::None => None, + BodyType::Json => Some(json!({ + "mode": "raw", + "raw": b.content, + "options": { "raw": { "language": "json" } } + })), + BodyType::Raw => { + let ct = b.content_type.clone().unwrap_or_else(|| "text/plain".into()); + let language = if ct.contains("xml") { + "xml" + } else if ct.contains("html") { + "html" + } else if ct.contains("javascript") { + "javascript" + } else { + "text" + }; + if !has_ct && b.content_type.is_some() { + header_list.push(json!({ "key": "Content-Type", "value": ct })); + } + Some(json!({ "mode": "raw", "raw": b.content, "options": { "raw": { "language": language } } })) + } + BodyType::FormUrlencoded => Some(json!({ + "mode": "urlencoded", + "urlencoded": b.form.iter().map(kv).collect::>() + })), + BodyType::Multipart => Some(json!({ + "mode": "formdata", + "formdata": b.multipart.iter().map(|p| { + let mut o = Map::new(); + o.insert("key".into(), Value::String(p.name.clone())); + match &p.file { + Some(f) => { + o.insert("type".into(), Value::String("file".into())); + o.insert("src".into(), Value::String(f.clone())); + } + None => { + o.insert("type".into(), Value::String("text".into())); + o.insert("value".into(), Value::String(p.value.clone())); + } + } + if let Some(ct) = &p.content_type { + o.insert("contentType".into(), Value::String(ct.clone())); + } + if !p.enabled { + o.insert("disabled".into(), Value::Bool(true)); + } + Value::Object(o) + }).collect::>() + })), + BodyType::Binary => Some(json!({ "mode": "file", "file": { "src": b.file.clone().unwrap_or_default() } })), + } +} + +fn url(req: &Request) -> Value { + let raw = req.url.clone(); + let no_query = raw.split(['?', '#']).next().unwrap_or(&raw).to_string(); + let (protocol, rest) = match no_query.split_once("://") { + Some((p, r)) => (Some(p.to_string()), r.to_string()), + None => (None, no_query.clone()), + }; + let (host, path) = if let Some(after) = rest.strip_prefix("{{") { + match after.find("}}") { + Some(i) => (rest[..i + 4].to_string(), rest[i + 4..].to_string()), + None => (rest.clone(), String::new()), + } + } else { + match rest.find('/') { + Some(i) => (rest[..i].to_string(), rest[i..].to_string()), + None => (rest.clone(), String::new()), + } + }; + let (host, port) = match host.rsplit_once(':') { + Some((h, p)) if !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()) => (h.to_string(), Some(p.to_string())), + _ => (host, None), + }; + let mut o = Map::new(); + o.insert("raw".into(), Value::String(raw)); + if let Some(p) = protocol { + o.insert("protocol".into(), Value::String(p)); + } + let host_parts: Vec = if host.starts_with("{{") { + vec![Value::String(host)] + } else { + host.split('.').map(|s| Value::String(s.to_string())).collect() + }; + o.insert("host".into(), Value::Array(host_parts)); + if let Some(p) = port { + o.insert("port".into(), Value::String(p)); + } + let segments: Vec = path + .trim_start_matches('/') + .split('/') + .filter(|s| !s.is_empty()) + .map(|s| Value::String(s.to_string())) + .collect(); + if !segments.is_empty() { + o.insert("path".into(), Value::Array(segments)); + } + if !req.params.query.is_empty() { + o.insert("query".into(), Value::Array(req.params.query.iter().map(kv).collect())); + } + if !req.params.path.is_empty() { + o.insert( + "variable".into(), + Value::Array(req.params.path.iter().map(|(k, v)| json!({ "key": k, "value": v })).collect()), + ); + } + Value::Object(o) +} + +fn auth(a: &Auth) -> Option { + let cfg = match a { + Auth::Inherit => return None, + Auth::None => return Some(json!({ "type": "noauth" })), + Auth::Config(c) => c, + }; + let s = |k: &str| cfg.string(k); + let (kind, params): (&str, Vec<(&str, String)>) = match cfg.kind.as_str() { + "basic" => ("basic", vec![("username", s("username")), ("password", s("password"))]), + "digest" => ("digest", vec![("username", s("username")), ("password", s("password"))]), + "bearer" => ("bearer", vec![("token", s("token"))]), + "apikey" => { + let place = if s("in") == "query" { "query" } else { "header" }; + ("apikey", vec![("key", s("key")), ("value", s("value")), ("in", place.into())]) + } + "awsv4" => ( + "awsv4", + vec![ + ("accessKey", s("access_key")), + ("secretKey", s("secret_key")), + ("sessionToken", s("session_token")), + ("region", s("region")), + ("service", s("service")), + ], + ), + "oauth1" => ( + "oauth1", + vec![ + ("consumerKey", s("consumer_key")), + ("consumerSecret", s("consumer_secret")), + ("token", s("token")), + ("tokenSecret", s("token_secret")), + ("signatureMethod", s("signature_method")), + ], + ), + "oauth2" | "oidc" => { + let grant = match s("grant").as_str() { + "client_credentials" => "client_credentials", + "password" => "password_credentials", + _ if cfg.bool("pkce", false) => "authorization_code_with_pkce", + _ => "authorization_code", + }; + let client_auth = if s("client_auth") == "post" { "body" } else { "header" }; + ( + "oauth2", + vec![ + ("grant_type", grant.into()), + ("authUrl", s("authorize_url")), + ("accessTokenUrl", s("token_url")), + ("clientId", s("client_id")), + ("clientSecret", s("client_secret")), + ("scope", s("scopes")), + ("audience", s("audience")), + ("username", s("username")), + ("password", s("password")), + ("client_authentication", client_auth.into()), + ("headerPrefix", s("token_prefix")), + ], + ) + } + "jwt" => ( + "jwt", + vec![ + ("algorithm", s("algorithm")), + ("secret", s("secret")), + ("privateKey", s("private_key")), + ("payload", s("payload")), + ], + ), + _ => return None, + }; + let list: Vec = params + .into_iter() + .filter(|(_, v)| !v.is_empty()) + .map(|(k, v)| json!({ "key": k, "value": v, "type": "string" })) + .collect(); + let mut o = Map::new(); + o.insert("type".into(), Value::String(kind.into())); + o.insert(kind.into(), Value::Array(list)); + Some(Value::Object(o)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::import::postman::import_postman; + + fn tmp() -> std::path::PathBuf { + std::env::temp_dir().join(format!("knock-export-{}", uuid::Uuid::new_v4())) + } + + fn comparable(c: &Collection) -> Vec<(String, Value)> { + c.requests_in("") + .into_iter() + .map(|id| { + let r = c.request(&id).unwrap(); + let v = json!({ + "name": r.name, "kind": r.kind, "method": r.method, "url": r.url, "params": r.params, + "headers": r.headers, "auth": r.auth, "body": r.body, "graphql": r.graphql, + "settings": r.settings, "docs": r.docs, + }); + (id, v) + }) + .collect() + } + + #[test] + fn postman_round_trip() { + let a_dir = tmp(); + let b_dir = tmp(); + let sample = crate::import::postman::tests_sample(); + import_postman(sample, &a_dir).unwrap(); + let a = Collection::open(&a_dir).unwrap(); + let exported = export_postman(&a).unwrap(); + assert!(exported.contains("{{secret.pets_password}}")); + assert!(!exported.contains("hunter2"), "secrets must stay placeholders"); + + let rep = import_postman(&exported, &b_dir).unwrap(); + assert_eq!(rep.requests, 6); + let b = Collection::open(&b_dir).unwrap(); + assert_eq!(comparable(&a), comparable(&b)); + assert_eq!(a.manifest.vars, b.manifest.vars); + assert_eq!(a.manifest.auth, b.manifest.auth); + assert_eq!(a.folder_meta("pets").unwrap().auth, b.folder_meta("pets").unwrap().auth); + std::fs::remove_dir_all(a_dir).unwrap(); + std::fs::remove_dir_all(b_dir).unwrap(); + } + + #[test] + fn exports_urls_and_bodies() { + let req = Request { + name: "x".into(), + url: "https://api.example.com:8443/v1/users/:id?q=1".into(), + params: Params { + query: vec![KeyValue::new("q", "1"), KeyValue { enabled: false, ..KeyValue::new("off", "2") }], + path: [("id".to_string(), "7".to_string())].into_iter().collect(), + }, + body: Body { kind: BodyType::Raw, content: "".into(), content_type: Some("application/xml".into()), ..Default::default() }, + ..Default::default() + }; + let v = request_item(&req, &[]); + let u = &v["request"]["url"]; + assert_eq!(u["host"], json!(["api", "example", "com"])); + assert_eq!(u["port"], "8443"); + assert_eq!(u["path"], json!(["v1", "users", ":id"])); + assert_eq!(u["query"][1]["disabled"], true); + assert_eq!(u["variable"][0]["value"], "7"); + assert_eq!(v["request"]["body"]["options"]["raw"]["language"], "xml"); + assert_eq!(v["request"]["header"][0]["value"], "application/xml"); + } +} diff --git a/crates/knock-core/src/export/snippet.rs b/crates/knock-core/src/export/snippet.rs new file mode 100644 index 0000000..727a911 --- /dev/null +++ b/crates/knock-core/src/export/snippet.rs @@ -0,0 +1,879 @@ +//! Code snippets for a fully resolved request. + +use crate::prepare::{Prepared, PreparedBody, PreparedPart}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::fmt::Write as _; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Lang { + Curl, + Fetch, + PythonRequests, + PythonHttpx, + Httpie, + Go, + #[serde(rename = "powershell")] + PowerShell, +} + +/// Placeholder file name for bodies that are not valid UTF-8. +const BINARY_FILE: &str = "body.bin"; +const DEFAULT_TIMEOUT_MS: u64 = 30_000; + +pub fn snippet(p: &Prepared, lang: Lang) -> String { + let payload = Payload::of(p); + match lang { + Lang::Curl => curl(p, &payload), + Lang::Fetch => fetch(p, &payload), + Lang::PythonRequests => python(p, &payload, false), + Lang::PythonHttpx => python(p, &payload, true), + Lang::Httpie => httpie(p, &payload), + Lang::Go => go(p, &payload), + Lang::PowerShell => powershell(p, &payload), + } +} + +enum Payload<'a> { + None, + Json(Value, String), + Form(Vec<(String, String)>, String), + Text(String), + Binary, + Multipart(&'a [PreparedPart]), +} + +impl<'a> Payload<'a> { + fn of(p: &'a Prepared) -> Self { + match &p.body { + PreparedBody::None => Payload::None, + PreparedBody::Multipart { parts } => Payload::Multipart(parts), + PreparedBody::Bytes { data, .. } if data.is_empty() => Payload::None, + PreparedBody::Bytes { data, .. } => { + let Ok(text) = std::str::from_utf8(data) else { return Payload::Binary }; + let ct = p.header("content-type").unwrap_or("").to_ascii_lowercase(); + if ct.contains("json") { + if let Ok(v) = serde_json::from_str::(text) { + return Payload::Json(v, text.to_string()); + } + } + if ct.starts_with("application/x-www-form-urlencoded") { + let pairs = url::form_urlencoded::parse(text.as_bytes()).into_owned().collect(); + return Payload::Form(pairs, text.to_string()); + } + Payload::Text(text.to_string()) + } + } + } + + fn is_some(&self) -> bool { + !matches!(self, Payload::None) + } +} + +/// Header list with repeated names folded into one value (for languages that use maps). +fn merged_headers(p: &Prepared, skip: &[&str]) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = Vec::new(); + for (k, v) in &p.headers { + if skip.iter().any(|s| k.eq_ignore_ascii_case(s)) { + continue; + } + match out.iter_mut().find(|(n, _)| n.eq_ignore_ascii_case(k)) { + Some((_, existing)) => { + existing.push_str(if k.eq_ignore_ascii_case("cookie") { "; " } else { ", " }); + existing.push_str(v); + } + None => out.push((k.clone(), v.clone())), + } + } + out +} + +fn file_name(part: &PreparedPart) -> String { + part.file + .as_ref() + .and_then(|f| f.file_name()) + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| part.name.clone()) +} + +fn file_path(part: &PreparedPart) -> String { + part.file.as_ref().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default() +} + +/// Double-quoted string literal. JSON escaping is valid in JS, Python and Go. +fn dq(s: &str) -> String { + serde_json::to_string(s).unwrap_or_else(|_| format!("\"{s}\"")) +} + +/// POSIX shell single quoting. +fn sq(s: &str) -> String { + let safe = !s.is_empty() + && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./:=@,+%".contains(c)); + if safe { + s.to_string() + } else { + format!("'{}'", s.replace('\'', r"'\''")) + } +} + +/// Indents every line but the first. +fn indent_tail(s: &str, pad: &str) -> String { + s.lines().collect::>().join(&format!("\n{pad}")) +} + +fn shell_lines(args: Vec) -> String { + let mut out = String::new(); + for (i, a) in args.iter().enumerate() { + if i == 0 { + out.push_str(a); + } else if i == 1 { + out.push(' '); + out.push_str(a); + } else { + out.push_str(" \\\n "); + out.push_str(a); + } + } + out +} + +// ---------------------------------------------------------------- curl + +fn curl(p: &Prepared, body: &Payload) -> String { + let mut args = vec!["curl".to_string()]; + let has_body = body.is_some(); + let mut first = String::new(); + match p.method.as_str() { + "HEAD" => first.push_str("--head "), + "GET" if !has_body => {} + "POST" if has_body => {} + m => { + let _ = write!(first, "-X {} ", sq(m)); + } + } + first.push_str(&sq(&p.url)); + args.push(first); + for (k, v) in &p.headers { + args.push(if v.is_empty() { format!("-H {}", sq(&format!("{k};"))) } else { format!("-H {}", sq(&format!("{k}: {v}"))) }); + } + match body { + Payload::None => {} + Payload::Json(_, text) | Payload::Form(_, text) | Payload::Text(text) => args.push(format!("--data-raw {}", sq(text))), + Payload::Binary => args.push(format!("--data-binary @{BINARY_FILE}")), + Payload::Multipart(parts) => { + for part in parts.iter() { + if part.file.is_some() { + let path = file_path(part); + let path = if path.contains([';', ',', '"']) { + format!("\"{}\"", path.replace('\\', "\\\\").replace('"', "\\\"")) + } else { + path + }; + let mut spec = format!("{}=@{path}", part.name); + if let Some(ct) = &part.content_type { + let _ = write!(spec, ";type={ct}"); + } + args.push(format!("-F {}", sq(&spec))); + } else { + let value = part.value.clone().unwrap_or_default(); + match &part.content_type { + Some(ct) => args.push(format!( + "-F {}", + sq(&format!("{}=\"{}\";type={ct}", part.name, value.replace('\\', "\\\\").replace('"', "\\\""))) + )), + None => args.push(format!("--form-string {}", sq(&format!("{}={value}", part.name)))), + } + } + } + } + } + if p.settings.follow_redirects { + args.push("-L".into()); + } + if !p.settings.verify_tls { + args.push("-k".into()); + } + if p.settings.timeout_ms != DEFAULT_TIMEOUT_MS && p.settings.timeout_ms > 0 { + args.push(format!("--max-time {}", secs(p.settings.timeout_ms))); + } + shell_lines(args) +} + +fn secs(ms: u64) -> String { + if ms.is_multiple_of(1000) { + (ms / 1000).to_string() + } else { + format!("{:.3}", ms as f64 / 1000.0).trim_end_matches('0').to_string() + } +} + +// ---------------------------------------------------------------- fetch + +fn fetch(p: &Prepared, body: &Payload) -> String { + let mut pre = String::new(); + let mut opts: Vec = Vec::new(); + if p.method != "GET" { + opts.push(format!("method: {}", dq(&p.method))); + } + let headers = merged_headers(p, &[]); + if !headers.is_empty() { + let mut h = String::from("headers: {\n"); + for (k, v) in &headers { + let _ = writeln!(h, " {}: {},", dq(k), dq(v)); + } + h.push_str(" }"); + opts.push(h); + } + let needs_fs = matches!(body, Payload::Binary) + || matches!(body, Payload::Multipart(parts) if parts.iter().any(|x| x.file.is_some())); + match body { + Payload::None => {} + Payload::Json(v, _) => { + let pretty = serde_json::to_string_pretty(v).unwrap_or_default(); + opts.push(format!("body: JSON.stringify({})", indent_tail(&pretty, " "))); + } + Payload::Form(pairs, text) => { + let unique = pairs.iter().all(|(k, _)| pairs.iter().filter(|(n, _)| n == k).count() == 1); + if pairs.is_empty() { + opts.push(format!("body: {}", dq(text))); + } else if unique { + let fields: Vec = pairs.iter().map(|(k, v)| format!(" {}: {},", dq(k), dq(v))).collect(); + opts.push(format!("body: new URLSearchParams({{\n{}\n }})", fields.join("\n"))); + } else { + let fields: Vec = pairs.iter().map(|(k, v)| format!(" [{}, {}],", dq(k), dq(v))).collect(); + opts.push(format!("body: new URLSearchParams([\n{}\n ])", fields.join("\n"))); + } + } + Payload::Text(t) => opts.push(format!("body: {}", dq(t))), + Payload::Binary => opts.push(format!("body: await readFile({})", dq(BINARY_FILE))), + Payload::Multipart(parts) => { + pre.push_str("const form = new FormData();\n"); + for part in parts.iter() { + if part.file.is_some() { + let blob_opts = part.content_type.as_ref().map(|ct| format!(", {{ type: {} }}", dq(ct))).unwrap_or_default(); + let _ = writeln!( + pre, + "form.append({}, new Blob([await readFile({})]{blob_opts}), {});", + dq(&part.name), + dq(&file_path(part)), + dq(&file_name(part)) + ); + } else { + let _ = writeln!(pre, "form.append({}, {});", dq(&part.name), dq(part.value.as_deref().unwrap_or(""))); + } + } + pre.push('\n'); + opts.push("body: form".into()); + } + } + if !p.settings.follow_redirects { + opts.push("redirect: \"manual\"".into()); + } + if p.settings.timeout_ms > 0 { + opts.push(format!("signal: AbortSignal.timeout({})", p.settings.timeout_ms)); + } + + let mut out = String::new(); + if needs_fs { + out.push_str("import { readFile } from \"node:fs/promises\";\n\n"); + } + if !p.settings.verify_tls { + out.push_str("// TLS certificate checks are off for this request; in Node set NODE_TLS_REJECT_UNAUTHORIZED=0.\n"); + } + out.push_str(&pre); + if opts.is_empty() { + let _ = writeln!(out, "const response = await fetch({});", dq(&p.url)); + } else { + let _ = writeln!(out, "const response = await fetch({}, {{", dq(&p.url)); + for o in &opts { + let _ = writeln!(out, " {o},"); + } + out.push_str("});\n"); + } + out.push_str("\nconsole.log(response.status);\nconsole.log(await response.text());\n"); + out +} + +// ---------------------------------------------------------------- python + +/// JSON value as a Python literal. +fn py_value(v: &Value, level: usize) -> String { + let pad = " ".repeat(level + 1); + let close = " ".repeat(level); + match v { + Value::Null => "None".into(), + Value::Bool(true) => "True".into(), + Value::Bool(false) => "False".into(), + Value::Number(n) => n.to_string(), + Value::String(s) => dq(s), + Value::Array(a) if a.is_empty() => "[]".into(), + Value::Object(o) if o.is_empty() => "{}".into(), + Value::Array(a) => { + let items: Vec = a.iter().map(|x| format!("{pad}{},", py_value(x, level + 1))).collect(); + format!("[\n{}\n{close}]", items.join("\n")) + } + Value::Object(o) => { + let items: Vec = o.iter().map(|(k, x)| format!("{pad}{}: {},", dq(k), py_value(x, level + 1))).collect(); + format!("{{\n{}\n{close}}}", items.join("\n")) + } + } +} + +/// Pairs as a Python dict; repeated names become lists. +fn py_dict(pairs: &[(String, String)]) -> String { + let mut grouped: Vec<(String, Vec)> = Vec::new(); + for (k, v) in pairs { + match grouped.iter_mut().find(|(n, _)| n == k) { + Some((_, vs)) => vs.push(v.clone()), + None => grouped.push((k.clone(), vec![v.clone()])), + } + } + if grouped.is_empty() { + return "{}".into(); + } + let mut out = String::from("{\n"); + for (k, vs) in grouped { + let value = if vs.len() == 1 { + dq(&vs[0]) + } else { + format!("[{}]", vs.iter().map(|v| dq(v)).collect::>().join(", ")) + }; + let _ = writeln!(out, " {}: {value},", dq(&k)); + } + out.push('}'); + out +} + +fn python(p: &Prepared, body: &Payload, httpx: bool) -> String { + let lib = if httpx { "httpx" } else { "requests" }; + let mut out = format!("import {lib}\n\nurl = {}\n", dq(&p.url)); + let mut kwargs: Vec = Vec::new(); + + let headers = merged_headers(p, &[]); + if !headers.is_empty() { + let pairs: Vec<(String, String)> = headers; + let _ = write!(out, "\nheaders = {}\n", py_dict(&pairs)); + kwargs.push("headers=headers".into()); + } + match body { + Payload::None => {} + Payload::Json(v, _) => { + let _ = write!(out, "\npayload = {}\n", py_value(v, 0)); + kwargs.push("json=payload".into()); + } + Payload::Form(pairs, _) => { + let _ = write!(out, "\ndata = {}\n", py_dict(pairs)); + kwargs.push("data=data".into()); + } + Payload::Text(t) => { + let _ = write!(out, "\npayload = {}\n", dq(t)); + kwargs.push(if httpx { "content=payload" } else { "data=payload" }.into()); + } + Payload::Binary => { + let _ = write!(out, "\nwith open({}, \"rb\") as f:\n payload = f.read()\n", dq(BINARY_FILE)); + kwargs.push(if httpx { "content=payload" } else { "data=payload" }.into()); + } + Payload::Multipart(parts) => { + let fields: Vec<(String, String)> = parts + .iter() + .filter(|x| x.file.is_none()) + .map(|x| (x.name.clone(), x.value.clone().unwrap_or_default())) + .collect(); + if !fields.is_empty() { + let _ = write!(out, "\ndata = {}\n", py_dict(&fields)); + kwargs.push("data=data".into()); + } + let files: Vec<&PreparedPart> = parts.iter().filter(|x| x.file.is_some()).collect(); + if !files.is_empty() { + out.push_str("\nfiles = [\n"); + for f in files { + let ct = f.content_type.as_ref().map(|c| format!(", {}", dq(c))).unwrap_or_default(); + let _ = writeln!( + out, + " ({}, ({}, open({}, \"rb\"){ct})),", + dq(&f.name), + dq(&file_name(f)), + dq(&file_path(f)) + ); + } + out.push_str("]\n"); + kwargs.push("files=files".into()); + } + } + } + if !p.settings.verify_tls { + kwargs.push("verify=False".into()); + } + if httpx && p.settings.follow_redirects { + kwargs.push("follow_redirects=True".into()); + } else if !httpx && !p.settings.follow_redirects { + kwargs.push("allow_redirects=False".into()); + } + if p.settings.timeout_ms > 0 { + kwargs.push(format!("timeout={}", secs(p.settings.timeout_ms))); + } + + let m = p.method.to_ascii_lowercase(); + let shortcut = if httpx { + match m.as_str() { + "post" | "put" | "patch" => true, + "get" | "head" | "options" | "delete" => !body.is_some(), + _ => false, + } + } else { + matches!(m.as_str(), "get" | "post" | "put" | "patch" | "delete" | "head" | "options") + }; + let mut args = Vec::new(); + let call = if shortcut { + format!("{lib}.{m}") + } else { + args.push(dq(&p.method)); + format!("{lib}.request") + }; + args.push("url".into()); + args.extend(kwargs); + let one_line = format!("{call}({})", args.join(", ")); + if one_line.len() + 11 <= 88 { + let _ = writeln!(out, "\nresponse = {one_line}"); + } else { + let _ = writeln!(out, "\nresponse = {call}("); + for a in &args { + let _ = writeln!(out, " {a},"); + } + out.push_str(")\n"); + } + out.push_str("\nprint(response.status_code)\nprint(response.text)\n"); + out +} + +// ---------------------------------------------------------------- httpie + +/// Escapes HTTPie item separators in a field or header name. +fn httpie_key(k: &str) -> String { + let mut out = String::new(); + for c in k.chars() { + if matches!(c, ':' | '=' | '@' | '\\') { + out.push('\\'); + } + out.push(c); + } + out +} + +fn httpie(p: &Prepared, body: &Payload) -> String { + let mut flags = Vec::new(); + match body { + Payload::Form(..) => flags.push("--form".to_string()), + Payload::Multipart(_) => flags.push("--multipart".to_string()), + _ => {} + } + if p.settings.follow_redirects { + flags.push("--follow".into()); + } + if !p.settings.verify_tls { + flags.push("--verify=no".into()); + } + if p.settings.timeout_ms > 0 && p.settings.timeout_ms != DEFAULT_TIMEOUT_MS { + flags.push(format!("--timeout={}", secs(p.settings.timeout_ms))); + } + if let Payload::Json(Value::Array(_), text) | Payload::Json(Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_), text) = body { + flags.push(format!("--raw {}", sq(text))); + } + if let Payload::Text(t) = body { + flags.push(format!("--raw {}", sq(t))); + } + + let mut args = vec!["http".to_string()]; + let mut first = flags.join(" "); + if !first.is_empty() { + first.push(' '); + } + let _ = write!(first, "{} {}", p.method, sq(&p.url)); + args.push(first); + for (k, v) in &p.headers { + args.push(if v.is_empty() { sq(&format!("{};", httpie_key(k))) } else { sq(&format!("{}:{v}", httpie_key(k))) }); + } + match body { + Payload::Json(Value::Object(o), _) => { + for (k, v) in o { + args.push(match v { + Value::String(s) => sq(&format!("{}={s}", httpie_key(k))), + other => sq(&format!("{}:={}", httpie_key(k), other)), + }); + } + } + Payload::Form(pairs, _) => { + for (k, v) in pairs { + args.push(sq(&format!("{}={v}", httpie_key(k)))); + } + } + Payload::Multipart(parts) => { + for part in parts.iter() { + if part.file.is_some() { + let mut spec = format!("{}@{}", httpie_key(&part.name), file_path(part)); + if let Some(ct) = &part.content_type { + let _ = write!(spec, ";type={ct}"); + } + args.push(sq(&spec)); + } else { + args.push(sq(&format!("{}={}", httpie_key(&part.name), part.value.as_deref().unwrap_or("")))); + } + } + } + Payload::Binary => args.push(format!("< {BINARY_FILE}")), + _ => {} + } + shell_lines(args) +} + +// ---------------------------------------------------------------- go + +fn go_str(s: &str) -> String { + if s.contains('\n') && !s.contains('`') && !s.contains('\r') { + format!("`{s}`") + } else { + dq(s) + } +} + +const GO_PANIC: &str = "if err != nil {\n\t\tpanic(err)\n\t}"; + +fn go(p: &Prepared, body: &Payload) -> String { + let mut imports = vec!["fmt", "io", "net/http"]; + let mut pre = String::new(); + let mut body_expr = "nil".to_string(); + let mut after_req = String::new(); + match body { + Payload::None => {} + Payload::Json(v, _) => { + imports.push("strings"); + let pretty = serde_json::to_string_pretty(v).unwrap_or_default(); + let _ = writeln!(pre, "\tbody := strings.NewReader({})\n", go_str(&pretty)); + body_expr = "body".into(); + } + Payload::Form(_, text) | Payload::Text(text) => { + imports.push("strings"); + let _ = writeln!(pre, "\tbody := strings.NewReader({})\n", go_str(text)); + body_expr = "body".into(); + } + Payload::Binary => { + imports.push("os"); + let _ = writeln!(pre, "\tbody, err := os.Open({})\n\t{GO_PANIC}\n\tdefer body.Close()\n", dq(BINARY_FILE)); + body_expr = "body".into(); + } + Payload::Multipart(parts) => { + imports.extend(["bytes", "mime/multipart"]); + pre.push_str("\tvar body bytes.Buffer\n\tmw := multipart.NewWriter(&body)\n"); + for part in parts.iter() { + if part.file.is_some() { + if !imports.contains(&"os") { + imports.extend(["os", "path/filepath"]); + } + let _ = write!( + pre, + "\t{{\n\t\tf, err := os.Open({path})\n\t\tif err != nil {{\n\t\t\tpanic(err)\n\t\t}}\n\t\tpart, err := mw.CreateFormFile({name}, filepath.Base(f.Name()))\n\t\tif err != nil {{\n\t\t\tpanic(err)\n\t\t}}\n\t\tif _, err := io.Copy(part, f); err != nil {{\n\t\t\tpanic(err)\n\t\t}}\n\t\tf.Close()\n\t}}\n", + path = dq(&file_path(part)), + name = dq(&part.name), + ); + } else { + let _ = write!( + pre, + "\tif err := mw.WriteField({}, {}); err != nil {{\n\t\tpanic(err)\n\t}}\n", + dq(&part.name), + go_str(part.value.as_deref().unwrap_or("")) + ); + } + } + pre.push_str("\tif err := mw.Close(); err != nil {\n\t\tpanic(err)\n\t}\n\n"); + body_expr = "&body".into(); + after_req.push_str("\treq.Header.Set(\"Content-Type\", mw.FormDataContentType())\n"); + } + } + + let mut client_fields = Vec::new(); + if p.settings.timeout_ms > 0 { + imports.push("time"); + let t = if p.settings.timeout_ms.is_multiple_of(1000) { + format!("{} * time.Second", p.settings.timeout_ms / 1000) + } else { + format!("{} * time.Millisecond", p.settings.timeout_ms) + }; + client_fields.push(format!("Timeout: {t},")); + } + if !p.settings.verify_tls { + imports.push("crypto/tls"); + client_fields.push("Transport: &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t},".into()); + } + if !p.settings.follow_redirects { + client_fields.push( + "CheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},".into(), + ); + } + imports.sort(); + imports.dedup(); + + let mut out = String::from("package main\n\nimport (\n"); + for i in &imports { + let _ = writeln!(out, "\t\"{i}\""); + } + out.push_str(")\n\nfunc main() {\n"); + out.push_str(&pre); + let _ = writeln!(out, "\treq, err := http.NewRequest({}, {}, {body_expr})\n\t{GO_PANIC}", dq(&p.method), dq(&p.url)); + for (k, v) in &p.headers { + let _ = writeln!(out, "\treq.Header.Add({}, {})", dq(k), dq(v)); + } + out.push_str(&after_req); + out.push('\n'); + if client_fields.is_empty() { + out.push_str("\tclient := &http.Client{}\n"); + } else { + out.push_str("\tclient := &http.Client{\n"); + for f in &client_fields { + let _ = writeln!(out, "\t\t{f}"); + } + out.push_str("\t}\n"); + } + let _ = write!( + out, + "\tresp, err := client.Do(req)\n\t{GO_PANIC}\n\tdefer resp.Body.Close()\n\n\tdata, err := io.ReadAll(resp.Body)\n\t{GO_PANIC}\n\tfmt.Println(resp.Status)\n\tfmt.Println(string(data))\n}}\n" + ); + out +} + +// ---------------------------------------------------------------- powershell + +fn ps(s: &str) -> String { + format!("'{}'", s.replace('\'', "''")) +} + +/// Single-quoted here-string for multi-line text, a plain literal otherwise. +fn ps_text(s: &str) -> String { + if s.contains('\n') && !s.lines().any(|l| l.starts_with("'@")) { + format!("@'\n{s}\n'@") + } else { + ps(s) + } +} + +fn powershell(p: &Prepared, body: &Payload) -> String { + const STANDARD: &[&str] = &["Get", "Head", "Post", "Put", "Delete", "Trace", "Options", "Patch", "Merge"]; + let mut out = String::new(); + let mut params: Vec<(&str, String)> = vec![("Uri", ps(&p.url))]; + let method = STANDARD.iter().find(|m| m.eq_ignore_ascii_case(&p.method)); + match method { + Some(m) => params.push(("Method", ps(m))), + None => params.push(("CustomMethod", ps(&p.method))), + } + + let headers = merged_headers(p, &["content-type", "user-agent"]); + if !headers.is_empty() { + out.push_str("$headers = @{\n"); + for (k, v) in &headers { + let _ = writeln!(out, " {} = {}", ps(k), ps(v)); + } + out.push_str("}\n"); + params.push(("Headers", "$headers".into())); + } + if let Some(ct) = p.header("content-type") { + params.push(("ContentType", ps(ct))); + } + if let Some(ua) = p.header("user-agent") { + params.push(("UserAgent", ps(ua))); + } + match body { + Payload::None => {} + Payload::Json(_, t) | Payload::Form(_, t) | Payload::Text(t) => { + let _ = writeln!(out, "$body = {}", ps_text(t)); + params.push(("Body", "$body".into())); + } + Payload::Binary => params.push(("InFile", ps(BINARY_FILE))), + Payload::Multipart(parts) => { + out.push_str("$form = @{\n"); + for part in parts.iter() { + if part.file.is_some() { + let _ = writeln!(out, " {} = Get-Item -LiteralPath {}", ps(&part.name), ps(&file_path(part))); + } else { + let _ = writeln!(out, " {} = {}", ps(&part.name), ps(part.value.as_deref().unwrap_or(""))); + } + } + out.push_str("}\n"); + params.push(("Form", "$form".into())); + } + } + if !p.settings.follow_redirects { + params.push(("MaximumRedirection", "0".into())); + } + if !p.settings.verify_tls { + params.push(("SkipCertificateCheck", "$true".into())); + } + if p.settings.timeout_ms > 0 { + params.push(("TimeoutSec", p.settings.timeout_ms.div_ceil(1000).to_string())); + } + if !out.is_empty() { + out.push('\n'); + } + let width = params.iter().map(|(k, _)| k.len()).max().unwrap_or(0); + out.push_str("$params = @{\n"); + for (k, v) in ¶ms { + let _ = writeln!(out, " {k: Prepared { + Prepared { + method: method.into(), + url: url.into(), + headers: headers.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(), + body, + settings: RequestSettings::default(), + missing: Vec::new(), + cycles: Vec::new(), + } + } + + fn bytes(s: &str) -> PreparedBody { + PreparedBody::Bytes { data: s.as_bytes().to_vec(), preview: s.into() } + } + + fn json_post() -> Prepared { + prepared( + "POST", + "https://api.example.com/users?x=1&y=2", + &[("Content-Type", "application/json"), ("X-Note", "it's \"quoted\"")], + bytes(r#"{"name":"O'Brien","quote":"say \"hi\"","ok":true,"none":null,"n":[1,2]}"#), + ) + } + + fn multipart() -> Prepared { + prepared( + "POST", + "https://upload.example.com/files", + &[("Authorization", "Bearer abc")], + PreparedBody::Multipart { + parts: vec![ + PreparedPart { name: "title".into(), value: Some("Q3 'final'".into()), file: None, content_type: None }, + PreparedPart { + name: "file".into(), + value: None, + file: Some(PathBuf::from("/home/me/My Report.pdf")), + content_type: Some("application/pdf".into()), + }, + ], + }, + ) + } + + #[test] + fn curl_escapes_single_quotes() { + let s = snippet(&json_post(), Lang::Curl); + assert!(s.starts_with("curl 'https://api.example.com/users?x=1&y=2' \\\n"), "{s}"); + assert!(s.contains(r#"-H 'X-Note: it'\''s "quoted"'"#), "{s}"); + assert!(s.contains(r#"--data-raw '{"name":"O'\''Brien","#), "{s}"); + assert!(!s.contains("-X POST")); + + let s = snippet(&multipart(), Lang::Curl); + assert!(s.contains(r#"--form-string 'title=Q3 '\''final'\'''"#), "{s}"); + assert!(s.contains("-F 'file=@/home/me/My Report.pdf;type=application/pdf'"), "{s}"); + } + + #[test] + fn curl_method_and_flags() { + let mut p = prepared("DELETE", "https://x.example/a", &[], PreparedBody::None); + p.settings.verify_tls = false; + p.settings.follow_redirects = false; + p.settings.timeout_ms = 2500; + assert_eq!(snippet(&p, Lang::Curl), "curl -X DELETE https://x.example/a \\\n -k \\\n --max-time 2.5"); + } + + #[test] + fn fetch_json_and_multipart() { + let s = snippet(&json_post(), Lang::Fetch); + assert!(s.contains("method: \"POST\""), "{s}"); + assert!(s.contains(r#""X-Note": "it's \"quoted\"""#), "{s}"); + assert!(s.contains("body: JSON.stringify({\n \"name\": \"O'Brien\""), "{s}"); + + let s = snippet(&multipart(), Lang::Fetch); + assert!(s.starts_with("import { readFile } from \"node:fs/promises\";"), "{s}"); + assert!(s.contains( + "form.append(\"file\", new Blob([await readFile(\"/home/me/My Report.pdf\")], { type: \"application/pdf\" }), \"My Report.pdf\");" + ), "{s}"); + assert!(s.contains("body: form")); + } + + #[test] + fn python_literals() { + let s = snippet(&json_post(), Lang::PythonRequests); + assert!(s.contains(" \"ok\": True,\n \"none\": None,"), "{s}"); + assert!(s.contains("\"quote\": \"say \\\"hi\\\"\""), "{s}"); + assert!(s.contains("requests.post(url, headers=headers, json=payload, timeout=30)"), "{s}"); + + let s = snippet(&multipart(), Lang::PythonHttpx); + assert!(s.contains("data = {\n \"title\": \"Q3 'final'\",\n}"), "{s}"); + assert!(s.contains("(\"file\", (\"My Report.pdf\", open(\"/home/me/My Report.pdf\", \"rb\"), \"application/pdf\")),"), "{s}"); + assert!(s.contains("follow_redirects=True"), "{s}"); + + let form = prepared( + "PATCH", + "https://x.example/f", + &[("Content-Type", "application/x-www-form-urlencoded")], + bytes("a=1&a=2&b=x+y"), + ); + let s = snippet(&form, Lang::PythonRequests); + assert!(s.contains("\"a\": [\"1\", \"2\"],\n \"b\": \"x y\","), "{s}"); + } + + #[test] + fn httpie_items() { + let s = snippet(&json_post(), Lang::Httpie); + assert!(s.starts_with("http --follow POST 'https://api.example.com/users?x=1&y=2'"), "{s}"); + assert!(s.contains(r#"'name=O'\''Brien'"#), "{s}"); + assert!(s.contains(" ok:=true \\\n"), "{s}"); + assert!(s.contains("'n:=[1,2]'"), "{s}"); + let s = snippet(&multipart(), Lang::Httpie); + assert!(s.contains("--multipart")); + assert!(s.contains("'file@/home/me/My Report.pdf;type=application/pdf'"), "{s}"); + } + + #[test] + fn go_program() { + let s = snippet(&json_post(), Lang::Go); + assert!(s.contains("import (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)"), "{s}"); + assert!(s.contains("body := strings.NewReader(`{\n \"name\": \"O'Brien\""), "{s}"); + assert!(s.contains("req.Header.Add(\"X-Note\", \"it's \\\"quoted\\\"\")"), "{s}"); + let s = snippet(&multipart(), Lang::Go); + assert!(s.contains("\"mime/multipart\"")); + assert!(s.contains("mw.CreateFormFile(\"file\", filepath.Base(f.Name()))")); + assert!(s.contains("req.Header.Set(\"Content-Type\", mw.FormDataContentType())")); + } + + #[test] + fn powershell_splatting() { + let s = snippet(&json_post(), Lang::PowerShell); + assert!(s.contains("'X-Note' = 'it''s \"quoted\"'"), "{s}"); + assert!(s.contains("ContentType = 'application/json'"), "{s}"); + assert!(s.contains("$body = '{\"name\":\"O''Brien\""), "{s}"); + assert!(s.contains("Method = 'Post'"), "{s}"); + let s = snippet(&multipart(), Lang::PowerShell); + assert!(s.contains("'file' = Get-Item -LiteralPath '/home/me/My Report.pdf'"), "{s}"); + assert!(s.contains("Form")); + } + + #[test] + fn lang_serde_names() { + let names: Vec = [Lang::Curl, Lang::Fetch, Lang::PythonRequests, Lang::PythonHttpx, Lang::Httpie, Lang::Go, Lang::PowerShell] + .iter() + .map(|l| serde_json::to_string(l).unwrap()) + .collect(); + assert_eq!(names, ["\"curl\"", "\"fetch\"", "\"python-requests\"", "\"python-httpx\"", "\"httpie\"", "\"go\"", "\"powershell\""]); + } +} diff --git a/crates/knock-core/src/import/bruno.rs b/crates/knock-core/src/import/bruno.rs new file mode 100644 index 0000000..448c7ae --- /dev/null +++ b/crates/knock-core/src/import/bruno.rs @@ -0,0 +1,792 @@ +//! Bruno collections: a folder with `bruno.json`, `.bru` request files, +//! `folder.bru`, `collection.bru` and `environments/*.bru`. + +use super::{append_docs, looks_like_json, parse_query, pretty_json, scripts_doc, set_url, ImportReport, Writer}; +use crate::model::*; +use anyhow::{anyhow, bail, Context, Result}; +use indexmap::IndexMap; +use std::fs; +use std::path::Path; + +// ---------------------------------------------------------------- .bru parser + +#[derive(Debug, Clone, PartialEq)] +pub struct Entry { + pub key: String, + pub value: String, + pub enabled: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum BlockBody { + /// `key: value` lines. + Dict(Vec), + /// Free text with the block indentation removed. + Text(String), + /// `name [ a, b ]`. + List(Vec), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Block { + pub name: String, + pub body: BlockBody, +} + +#[derive(Debug, Default)] +pub struct BruFile { + pub blocks: Vec, +} + +impl BruFile { + pub fn block(&self, name: &str) -> Option<&BlockBody> { + self.blocks.iter().find(|b| b.name == name).map(|b| &b.body) + } + + pub fn dict(&self, name: &str) -> &[Entry] { + match self.block(name) { + Some(BlockBody::Dict(d)) | Some(BlockBody::List(d)) => d, + _ => &[], + } + } + + pub fn get(&self, block: &str, key: &str) -> Option<&str> { + self.dict(block).iter().find(|e| e.key == key && e.enabled).map(|e| e.value.as_str()) + } + + pub fn text(&self, name: &str) -> Option<&str> { + match self.block(name) { + Some(BlockBody::Text(t)) if !t.trim().is_empty() => Some(t), + _ => None, + } + } +} + +fn is_text_block(name: &str) -> bool { + name.starts_with("body:") && !matches!(name, "body:form-urlencoded" | "body:multipart-form" | "body:file") + || name.starts_with("script:") + || name == "tests" + || name == "docs" +} + +/// Parses the `.bru` block format. +pub fn parse_bru(src: &str) -> Result { + let lines: Vec<&str> = src.lines().collect(); + let mut out = BruFile::default(); + let mut i = 0; + while i < lines.len() { + let line = lines[i].trim_end(); + i += 1; + if line.trim().is_empty() { + continue; + } + if let Some(name) = line.strip_suffix('{').map(str::trim).filter(|n| !n.is_empty() && !n.contains(' ')) { + let start = i; + while i < lines.len() && lines[i].trim_end() != "}" { + i += 1; + } + if i >= lines.len() { + bail!("block `{name}` starting on line {start} is not closed with `}}`"); + } + let content = &lines[start..i]; + i += 1; + let body = if is_text_block(name) { + BlockBody::Text(dedent(content)) + } else { + BlockBody::Dict(parse_dict(content)) + }; + out.blocks.push(Block { name: name.to_string(), body }); + } else if let Some(name) = line.strip_suffix('[').map(str::trim).filter(|n| !n.is_empty()) { + let start = i; + let mut items = Vec::new(); + while i < lines.len() && lines[i].trim() != "]" { + for raw in lines[i].split(',') { + let t = raw.trim(); + if !t.is_empty() { + let (enabled, key) = match t.strip_prefix('~') { + Some(k) => (false, k), + None => (true, t), + }; + items.push(Entry { key: key.to_string(), value: String::new(), enabled }); + } + } + i += 1; + } + if i >= lines.len() { + bail!("list `{name}` starting on line {start} is not closed with `]`"); + } + i += 1; + out.blocks.push(Block { name: name.to_string(), body: BlockBody::List(items) }); + } else { + bail!("unexpected line {i}: `{}`", line.trim()); + } + } + Ok(out) +} + +fn dedent(lines: &[&str]) -> String { + let text: Vec<&str> = lines.iter().map(|l| l.strip_prefix(" ").unwrap_or(l)).collect(); + text.join("\n").trim_matches('\n').to_string() +} + +fn parse_dict(lines: &[&str]) -> Vec { + let mut out = Vec::new(); + let mut i = 0; + while i < lines.len() { + let t = lines[i].trim(); + i += 1; + if t.is_empty() { + continue; + } + let (enabled, t) = match t.strip_prefix('~') { + Some(rest) => (false, rest), + None => (true, t), + }; + let (key, value) = match t.split_once(':') { + Some((k, v)) => (k.trim(), v.trim()), + None => (t, ""), + }; + let mut value = value.to_string(); + // Multi-line values are wrapped in ''' … '''. + if value == "'''" { + let mut buf = Vec::new(); + while i < lines.len() && lines[i].trim() != "'''" { + buf.push(lines[i].strip_prefix(" ").unwrap_or(lines[i])); + i += 1; + } + i += 1; + value = buf.join("\n"); + } + out.push(Entry { key: unquote_key(key), value, enabled }); + } + out +} + +fn unquote_key(k: &str) -> String { + k.strip_prefix('"').and_then(|s| s.strip_suffix('"')).unwrap_or(k).to_string() +} + +// ---------------------------------------------------------------- import + +const METHODS: &[&str] = &["get", "post", "put", "patch", "delete", "options", "head", "connect", "trace"]; + +pub fn import_bruno(src_dir: &Path, dest: &Path) -> Result { + let manifest_path = src_dir.join("bruno.json"); + let manifest: serde_json::Value = serde_json::from_str( + &fs::read_to_string(&manifest_path) + .with_context(|| format!("{} is not a Bruno collection (bruno.json missing)", src_dir.display()))?, + ) + .context("bruno.json is not valid JSON")?; + let name = super::text(manifest.get("name")); + let ignore: Vec = manifest + .get("ignore") + .and_then(|v| v.as_array()) + .map(|a| a.iter().filter_map(|s| s.as_str().map(str::to_string)).collect()) + .unwrap_or_else(|| vec!["node_modules".into(), ".git".into()]); + + let mut w = Writer::start(dest, &name)?; + + let coll_file = src_dir.join("collection.bru"); + if coll_file.exists() { + let bru = read_bru(&coll_file)?; + let mut warnings = Vec::new(); + let auth = map_auth(&bru, &mut warnings); + let headers = kv(bru.dict("headers")); + let vars = vars_map(bru.dict("vars:pre-request")); + let (docs, scripts) = misc_docs(&bru); + w.report.scripts_skipped += scripts; + w.manifest(|m| { + m.headers = headers; + m.vars = vars; + if !docs.is_empty() { + m.extra.insert("docs".into(), docs.into()); + } + })?; + w.collection_auth(auth)?; + for msg in warnings { + w.warn(format!("collection.bru: {msg}")); + } + } + + let env_dir = src_dir.join("environments"); + if env_dir.is_dir() { + let mut has_local = false; + let mut files: Vec<_> = fs::read_dir(&env_dir)?.filter_map(|e| e.ok()).map(|e| e.path()).collect(); + files.sort(); + for p in files.iter().filter(|p| p.extension().is_some_and(|e| e == "bru")) { + let stem = p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); + let bru = read_bru(p)?; + let mut env = Environment::default(); + for e in bru.dict("vars").iter().filter(|e| e.enabled) { + env.vars.insert(e.key.clone(), EnvVar { value: e.value.clone(), secret: false, description: None }); + } + for e in bru.dict("vars:secret").iter().filter(|e| e.enabled) { + env.vars.insert(e.key.clone(), EnvVar { value: String::new(), secret: true, description: None }); + } + let id = w.environment(&stem, env, IndexMap::new())?; + has_local |= id == "local"; + } + if !files.is_empty() && !has_local { + w.remove_local_env()?; + } + if bru_secret_count(&files) > 0 { + w.warn("Bruno stores secret values outside the collection; set them again in knock's environment editor"); + } + } + + import_dir(&mut w, src_dir, src_dir, "", &ignore)?; + w.finish() +} + +fn bru_secret_count(files: &[std::path::PathBuf]) -> usize { + files + .iter() + .filter_map(|p| read_bru(p).ok()) + .map(|b| b.dict("vars:secret").len()) + .sum() +} + +fn read_bru(p: &Path) -> Result { + let text = fs::read_to_string(p).with_context(|| format!("reading {}", p.display()))?; + parse_bru(&text).with_context(|| format!("parsing {}", p.display())) +} + +enum Child { + Folder { path: std::path::PathBuf, name: String, seq: f64, meta: Option }, + Request { file: BruFile, name: String, seq: f64 }, +} + +fn import_dir(w: &mut Writer, root: &Path, dir: &Path, folder: &str, ignore: &[String]) -> Result<()> { + let mut children = Vec::new(); + for e in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? { + let e = e?; + let path = e.path(); + let fname = e.file_name().to_string_lossy().to_string(); + let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/"); + if fname.starts_with('.') || ignore.iter().any(|i| *i == fname || *i == rel) { + continue; + } + if path.is_dir() { + if dir == root && fname == "environments" { + continue; + } + let meta_path = path.join("folder.bru"); + let meta = if meta_path.exists() { Some(read_bru(&meta_path)?) } else { None }; + let name = meta.as_ref().and_then(|m| m.get("meta", "name")).map(str::to_string).unwrap_or_else(|| fname.clone()); + let seq = meta.as_ref().and_then(|m| m.get("meta", "seq")).and_then(|s| s.parse().ok()).unwrap_or(f64::MAX); + children.push(Child::Folder { path, name, seq, meta }); + } else if fname.ends_with(".bru") && fname != "folder.bru" && fname != "collection.bru" { + let file = match read_bru(&path) { + Ok(f) => f, + Err(err) => { + w.warn(format!("{rel} skipped: {err:#}")); + continue; + } + }; + let name = file.get("meta", "name").map(str::to_string).unwrap_or_else(|| fname.trim_end_matches(".bru").to_string()); + let seq = file.get("meta", "seq").and_then(|s| s.parse().ok()).unwrap_or(f64::MAX); + children.push(Child::Request { file, name, seq }); + } + } + children.sort_by(|a, b| { + let key = |c: &Child| match c { + Child::Folder { seq, name, .. } | Child::Request { seq, name, .. } => (*seq, name.to_lowercase()), + }; + let (sa, na) = key(a); + let (sb, nb) = key(b); + sa.total_cmp(&sb).then(na.cmp(&nb)) + }); + for child in children { + match child { + Child::Folder { path, name, meta, .. } => { + let id = w.folder(folder, &name)?; + if let Some(bru) = meta { + let mut warnings = Vec::new(); + let auth = map_auth(&bru, &mut warnings); + let headers = kv(bru.dict("headers")); + let vars = vars_map(bru.dict("vars:pre-request")); + let (docs, scripts) = misc_docs(&bru); + w.report.scripts_skipped += scripts; + w.folder_meta(&id, |m| { + m.auth = auth; + m.headers = headers; + m.vars = vars; + if !docs.is_empty() { + m.extra.insert("docs".into(), docs.into()); + } + })?; + for msg in warnings { + w.warn(format!("{name}: {msg}")); + } + } + import_dir(w, root, &path, &id, ignore)?; + } + Child::Request { file, name, .. } => { + let mut warnings = Vec::new(); + let mut scripts = 0; + match map_request(&file, &name, &mut warnings, &mut scripts) { + Ok(req) => { + w.report.scripts_skipped += scripts; + w.request(folder, req)?; + } + Err(e) => w.warn(format!("{name} skipped: {e:#}")), + } + for msg in warnings { + w.warn(format!("{name}: {msg}")); + } + } + } + } + Ok(()) +} + +fn kv(entries: &[Entry]) -> Vec { + entries + .iter() + .map(|e| KeyValue { + name: e.key.clone(), + value: e.value.clone(), + enabled: e.enabled, + ..Default::default() + }) + .collect() +} + +fn vars_map(entries: &[Entry]) -> IndexMap { + entries.iter().filter(|e| e.enabled).map(|e| (e.key.clone(), e.value.clone())).collect() +} + +/// Docs plus scripts and tests rendered as markdown, and the number of scripts. +fn misc_docs(bru: &BruFile) -> (String, usize) { + let mut docs = bru.text("docs").unwrap_or_default().to_string(); + let scripts: Vec<(&str, &str, String)> = [ + ("script:pre-request", "Pre-request script"), + ("script:post-response", "Post-response script"), + ("tests", "Tests"), + ] + .into_iter() + .filter_map(|(block, label)| bru.text(block).map(|t| (label, "js", t.to_string()))) + .collect(); + if !scripts.is_empty() { + if !docs.is_empty() { + docs.push_str("\n\n"); + } + docs.push_str(&scripts_doc("Bruno", &scripts)); + } + (docs, scripts.len()) +} + +fn map_auth(bru: &BruFile, warnings: &mut Vec) -> Auth { + let mode = bru + .get("auth", "mode") + .or_else(|| METHODS.iter().find_map(|m| bru.get(m, "auth"))) + .unwrap_or("inherit"); + let g = |block: &str, key: &str| bru.get(block, key).unwrap_or("").to_string(); + match mode { + "none" => Auth::None, + "inherit" => Auth::Inherit, + "basic" => super::auth("basic", [("username", g("auth:basic", "username")), ("password", g("auth:basic", "password"))]), + "digest" => super::auth("digest", [("username", g("auth:digest", "username")), ("password", g("auth:digest", "password"))]), + "bearer" => super::auth("bearer", [("token", g("auth:bearer", "token"))]), + "apikey" => { + let place = if g("auth:apikey", "placement") == "queryparams" { "query" } else { "header" }; + super::auth("apikey", [("key", g("auth:apikey", "key")), ("value", g("auth:apikey", "value")), ("in", place.into())]) + } + "awsv4" => super::auth( + "awsv4", + [ + ("access_key", g("auth:awsv4", "accessKeyId")), + ("secret_key", g("auth:awsv4", "secretAccessKey")), + ("session_token", g("auth:awsv4", "sessionToken")), + ("region", g("auth:awsv4", "region")), + ("service", g("auth:awsv4", "service")), + ], + ), + "oauth2" => { + let o = |k: &str| g("auth:oauth2", k); + let grant = match o("grant_type").as_str() { + "client_credentials" => "client_credentials", + "password" => "password", + _ => "authorization_code", + }; + let client_auth = if o("credentials_placement") == "body" { "post" } else { "basic" }; + let mut auth = super::auth( + "oauth2", + [ + ("grant", grant.to_string()), + ("authorize_url", o("authorization_url")), + ("token_url", o("access_token_url")), + ("client_id", o("client_id")), + ("client_secret", o("client_secret")), + ("client_auth", client_auth.to_string()), + ("scopes", o("scope")), + ("username", o("username")), + ("password", o("password")), + ("token_prefix", o("token_header_prefix")), + ], + ); + if let Auth::Config(c) = &mut auth { + if o("pkce") == "true" { + c.fields.insert("pkce".into(), serde_json::Value::Bool(true)); + } + } + auth + } + other => { + warnings.push(format!("auth mode `{other}` is not supported and was left as inherit")); + Auth::Inherit + } + } +} + +fn map_request(bru: &BruFile, name: &str, warnings: &mut Vec, scripts: &mut usize) -> Result { + let method = METHODS + .iter() + .find(|m| bru.block(m).is_some()) + .ok_or_else(|| anyhow!("no method block (get, post, …) found"))?; + let url = bru.get(method, "url").unwrap_or("").to_string(); + let body_mode = bru.get(method, "body").unwrap_or("none"); + let graphql = bru.get("meta", "type") == Some("graphql"); + + let mut req = Request { + name: name.to_string(), + method: Some(method.to_uppercase()), + headers: kv(bru.dict("headers")), + vars: vars_map(bru.dict("vars:pre-request")), + ..Default::default() + }; + req.auth = map_auth(bru, warnings); + + let rows = match bru.block("params:query") { + Some(BlockBody::Dict(d)) => kv(d), + _ => parse_query(&url), + }; + set_url(&mut req, &url, rows); + for e in bru.dict("params:path") { + req.params.path.insert(e.key.clone(), e.value.clone()); + } + + if graphql || body_mode == "graphql" { + req.kind = RequestKind::Graphql; + req.graphql = Some(GraphqlSpec { + query: bru.text("body:graphql").unwrap_or("").to_string(), + variables: bru.text("body:graphql:vars").unwrap_or("").to_string(), + operation_name: None, + }); + } else { + req.body = map_body(bru, body_mode, warnings); + } + + let mut leftovers = Vec::new(); + for e in bru.dict("vars:post-response") { + match extract_rule(&e.key, &e.value) { + Some(mut r) => { + r.enabled = e.enabled; + req.extract.push(r); + } + None => leftovers.push(format!("- vars:post-response `{}: {}`", e.key, e.value)), + } + } + for e in bru.dict("assert") { + match assert_rule(&e.key, &e.value) { + Some(mut r) => { + r.enabled = e.enabled; + req.assert.push(r); + } + None => leftovers.push(format!("- assert `{}: {}`", e.key, e.value)), + } + } + + let (docs, n) = misc_docs(bru); + *scripts += n; + append_docs(&mut req, &docs); + if !leftovers.is_empty() { + append_docs( + &mut req, + &format!("## Bruno rules not converted\n\n{}", leftovers.join("\n")), + ); + } + Ok(req) +} + +fn map_body(bru: &BruFile, mode: &str, warnings: &mut Vec) -> Body { + let raw = |block: &str, ct: Option<&str>| Body { + kind: BodyType::Raw, + content: bru.text(block).unwrap_or("").to_string(), + content_type: ct.map(str::to_string), + ..Default::default() + }; + match mode { + "json" => { + let content = bru.text("body:json").unwrap_or("").to_string(); + let jsonc = !content.trim().is_empty() + && !looks_like_json(&content) + && serde_json::from_str::(&crate::prepare::strip_json_comments(&content)).is_ok(); + Body { + kind: BodyType::Json, + content: if looks_like_json(&content) { pretty_json(&content) } else { content }, + jsonc, + ..Default::default() + } + } + "text" => raw("body:text", Some("text/plain")), + "xml" => raw("body:xml", Some("application/xml")), + "sparql" => raw("body:sparql", Some("application/sparql-query")), + "formUrlEncoded" => Body { + kind: BodyType::FormUrlencoded, + form: kv(bru.dict("body:form-urlencoded")), + ..Default::default() + }, + "multipartForm" => Body { + kind: BodyType::Multipart, + multipart: bru + .dict("body:multipart-form") + .iter() + .map(|e| { + let (value, ct) = split_content_type(&e.value); + let file = file_ref(&value, warnings, &e.key); + MultipartPart { + name: e.key.clone(), + value: if file.is_some() { String::new() } else { value }, + file, + content_type: ct, + enabled: e.enabled, + } + }) + .collect(), + ..Default::default() + }, + "file" => { + let first = bru.dict("body:file").iter().find(|e| e.enabled); + let (file, ct) = first + .map(|e| { + let (v, ct) = split_content_type(&e.value); + (file_ref(&v, warnings, &e.key), ct) + }) + .unwrap_or((None, None)); + Body { + kind: BodyType::Binary, + file, + content_type: ct, + ..Default::default() + } + } + "none" | "" => Body::default(), + other => { + warnings.push(format!("body mode `{other}` is not supported")); + Body::default() + } + } +} + +/// `value @contentType(x)` → (value, x). +fn split_content_type(v: &str) -> (String, Option) { + match v.rfind("@contentType(") { + Some(i) if v.ends_with(')') => ( + v[..i].trim().to_string(), + Some(v[i + "@contentType(".len()..v.len() - 1].to_string()), + ), + _ => (v.to_string(), None), + } +} + +/// `@file(a|b)` → first path. +fn file_ref(v: &str, warnings: &mut Vec, key: &str) -> Option { + let inner = v.strip_prefix("@file(")?.strip_suffix(')')?; + let mut files = inner.split('|'); + let first = files.next().unwrap_or("").to_string(); + if files.next().is_some() { + warnings.push(format!("form field `{key}` had several files; only the first was kept")); + } + Some(first) +} + +/// `res.body.a.b` → JSONPath `$.a.b`. +fn body_path(expr: &str) -> Option { + let rest = expr.strip_prefix("res.body")?; + if rest.is_empty() { + return Some("$".into()); + } + if rest.starts_with('.') || rest.starts_with('[') { + let ok = rest.chars().all(|c| c.is_alphanumeric() || "._[]-\"'*".contains(c)); + return ok.then(|| format!("${rest}")); + } + None +} + +fn header_name(expr: &str) -> Option { + let rest = expr.strip_prefix("res.headers.").or_else(|| expr.strip_prefix("res.headers["))?; + let name = rest.trim_end_matches(']').trim_matches(['"', '\'']); + (!name.is_empty()).then(|| name.to_string()) +} + +fn extract_rule(var: &str, expr: &str) -> Option { + let expr = expr.trim(); + let (from, path) = if let Some(p) = body_path(expr) { + (ExtractSource::Json, p) + } else if let Some(h) = header_name(expr) { + (ExtractSource::Header, h) + } else if expr == "res.status" { + (ExtractSource::Status, String::new()) + } else { + return None; + }; + Some(ExtractRule { + var: var.to_string(), + from, + path, + enabled: true, + persist: false, + }) +} + +fn literal(v: &str) -> serde_json::Value { + let v = v.trim(); + serde_json::from_str(v).unwrap_or_else(|_| { + serde_json::Value::String(v.trim_matches(|c| c == '\'' || c == '"').to_string()) + }) +} + +fn assert_rule(target: &str, expr: &str) -> Option { + let target = target.trim(); + let mut rule = AssertRule { enabled: true, ..Default::default() }; + if target == "res.status" { + rule.on = AssertTarget::Status; + } else if target == "res.responseTime" { + rule.on = AssertTarget::Time; + } else if let Some(h) = header_name(target) { + rule.on = AssertTarget::Header; + rule.path = Some(h); + } else { + rule.on = AssertTarget::Json; + rule.path = Some(body_path(target)?); + } + let expr = expr.trim(); + let (op, arg) = match expr.split_once(' ') { + Some((o, a)) => (o, a.trim()), + None => (expr, ""), + }; + let num = || arg.trim().parse::().ok(); + match op { + "eq" => rule.equals = Some(literal(arg)), + "neq" => rule.not_equals = Some(literal(arg)), + "gt" => rule.gt = Some(num()?), + "lt" => rule.lt = Some(num()?), + "contains" => rule.contains = Some(literal(arg)), + "matches" => rule.matches = Some(arg.trim_matches(['"', '\'']).to_string()), + "startsWith" => rule.matches = Some(format!("^{}", regex::escape(arg.trim_matches(['"', '\''])))), + "endsWith" => rule.matches = Some(format!("{}$", regex::escape(arg.trim_matches(['"', '\''])))), + "isDefined" => rule.exists = Some(true), + "isUndefined" => rule.exists = Some(false), + "isNull" => rule.equals = Some(serde_json::Value::Null), + "isString" => rule.type_is = Some("string".into()), + "isNumber" => rule.type_is = Some("number".into()), + "isBoolean" => rule.type_is = Some("boolean".into()), + "isArray" => rule.type_is = Some("array".into()), + _ => return None, + } + // Header and status checks only support a subset. + if rule.on == AssertTarget::Status && (rule.exists.is_some() || rule.type_is.is_some()) { + return None; + } + Some(rule) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::collection::Collection; + + fn fixture() -> std::path::PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/bruno") + } + + #[test] + fn parses_blocks() { + let src = "meta {\n name: Get\n seq: 2\n}\n\nget {\n url: {{baseUrl}}/a?x=1\n}\n\nheaders {\n Accept: application/json\n ~X-Off: 1\n}\n\nbody:json {\n {\n \"a\": \"}\"\n }\n}\n\nvars:secret [\n token,\n ~old\n]\n"; + let f = parse_bru(src).unwrap(); + assert_eq!(f.get("meta", "seq"), Some("2")); + assert_eq!(f.get("get", "url"), Some("{{baseUrl}}/a?x=1")); + assert!(!f.dict("headers")[1].enabled); + assert_eq!(f.text("body:json"), Some("{\n \"a\": \"}\"\n}")); + assert_eq!(f.dict("vars:secret").len(), 2); + assert!(parse_bru("get {\n url: x\n").is_err()); + } + + #[test] + fn converts_asserts_and_extracts() { + let a = assert_rule("res.status", "eq 200").unwrap(); + assert_eq!((a.on, a.equals), (AssertTarget::Status, Some(serde_json::json!(200)))); + let a = assert_rule("res.body.id", "isDefined").unwrap(); + assert_eq!((a.path.as_deref(), a.exists), (Some("$.id"), Some(true))); + let a = assert_rule("res.headers.content-type", "contains json").unwrap(); + assert_eq!((a.on, a.path.as_deref()), (AssertTarget::Header, Some("content-type"))); + assert_eq!(a.contains, Some(serde_json::json!("json"))); + assert!(assert_rule("res.body.items", "length 3").is_none()); + let e = extract_rule("token", "res.body.token").unwrap(); + assert_eq!((e.from, e.path.as_str()), (ExtractSource::Json, "$.token")); + let e = extract_rule("first", "res.body.items[0].id").unwrap(); + assert_eq!(e.path, "$.items[0].id"); + assert!(extract_rule("x", "res.body.items.map(i => i.id)").is_none()); + } + + #[test] + fn imports_fixture_collection() { + let dir = super::super::tmp_dir(); + let rep = import_bruno(&fixture(), &dir).unwrap(); + assert_eq!(rep.requests, 6, "{rep:?}"); + assert_eq!(rep.folders, 2); + assert_eq!(rep.scripts_skipped, 3); + assert_eq!(rep.environments, vec!["local".to_string(), "production".to_string()]); + + let c = Collection::open(&dir).unwrap(); + assert_eq!(c.manifest.name, "Shop API"); + assert_eq!(c.manifest.headers[0].name, "X-Client"); + assert!(matches!(&c.manifest.auth, Auth::Config(a) if a.kind == "bearer")); + assert_eq!( + c.requests_in(""), + vec![ + "auth/login.yaml", + "users/list-users.yaml", + "users/create-user.yaml", + "users/upload-avatar.yaml", + "search.gql.yaml", + "health.yaml" + ] + ); + + let login = c.request("auth/login.yaml").unwrap(); + assert_eq!(login.auth, Auth::None); + assert_eq!(login.extract[0].var, "token"); + assert_eq!(login.extract[0].path, "$.token"); + assert_eq!(login.assert.len(), 3); + let docs = login.docs.unwrap(); + assert!(docs.contains("Imported Bruno scripts (not run)")); + assert!(docs.contains("res.body.roles: length 2")); + + let list = c.request("users/list-users.yaml").unwrap(); + assert_eq!(list.url, "{{baseUrl}}/users?page=1"); + assert_eq!(list.params.query.len(), 2); + assert!(!list.params.query[1].enabled); + + let create = c.request("users/create-user.yaml").unwrap(); + assert_eq!(create.body.kind, BodyType::Json); + assert_eq!(create.params.path["org"], "acme"); + let Auth::Config(basic) = &create.auth else { panic!() }; + assert!(basic.str("password").unwrap().starts_with("{{secret.")); + + let up = c.request("users/upload-avatar.yaml").unwrap(); + assert_eq!(up.body.multipart[0].file.as_deref(), Some("avatars/me.png")); + assert_eq!(up.body.multipart[1].value, "profile"); + + let gql = c.request("search.gql.yaml").unwrap(); + assert!(gql.graphql.unwrap().query.contains("products")); + + let prod = c.environment("production").unwrap(); + assert!(prod.vars["apiToken"].secret); + assert_eq!(prod.vars["baseUrl"].value, "https://api.shop.example.com"); + let folder = c.folder_meta("users").unwrap(); + assert_eq!(folder.vars["pageSize"], "20"); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/knock-core/src/import/curl.rs b/crates/knock-core/src/import/curl.rs new file mode 100644 index 0000000..85c9d34 --- /dev/null +++ b/crates/knock-core/src/import/curl.rs @@ -0,0 +1,811 @@ +//! `curl …` command lines (bash, zsh, cmd.exe) to a request. + +use super::{looks_like_json, parse_query, pretty_json, set_url, url_path}; +use crate::model::*; +use anyhow::{anyhow, bail, Result}; +use base64::Engine; + +/// Splits a shell command into words. Understands `'…'`, `"…"`, `$'…'`, +/// backslash escapes and line continuations (`\` and cmd.exe `^`). +pub fn split_shell(cmd: &str) -> Result> { + let cmd = if is_cmd_style(cmd) { unescape_cmd(cmd) } else { cmd.to_string() }; + let chars: Vec = cmd.chars().collect(); + let mut words = Vec::new(); + let mut cur = String::new(); + let mut in_word = false; + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + match c { + c if c.is_whitespace() => { + if in_word { + words.push(std::mem::take(&mut cur)); + in_word = false; + } + i += 1; + } + '\\' => { + match chars.get(i + 1) { + Some('\n') => i += 2, + Some('\r') if chars.get(i + 2) == Some(&'\n') => i += 3, + Some(&n) => { + cur.push(n); + in_word = true; + i += 2; + } + None => i += 1, + } + } + '\'' => { + in_word = true; + let end = chars[i + 1..] + .iter() + .position(|&ch| ch == '\'') + .ok_or_else(|| anyhow!("unterminated single quote in command"))?; + cur.extend(&chars[i + 1..i + 1 + end]); + i += end + 2; + } + '$' if chars.get(i + 1) == Some(&'\'') => { + in_word = true; + i = ansi_c_quoted(&chars, i + 2, &mut cur)?; + } + '"' => { + in_word = true; + i += 1; + loop { + let Some(&ch) = chars.get(i) else { bail!("unterminated double quote in command") }; + match ch { + '"' => { + i += 1; + break; + } + '\\' => match chars.get(i + 1) { + Some(&n @ ('"' | '\\' | '$' | '`')) => { + cur.push(n); + i += 2; + } + Some('\n') => i += 2, + _ => { + cur.push('\\'); + i += 1; + } + }, + _ => { + cur.push(ch); + i += 1; + } + } + } + } + _ => { + cur.push(c); + in_word = true; + i += 1; + } + } + } + if in_word { + words.push(cur); + } + Ok(words) +} + +/// Body of a `$'…'` word starting at `i`; returns the index after the closing quote. +fn ansi_c_quoted(chars: &[char], mut i: usize, out: &mut String) -> Result { + loop { + let Some(&ch) = chars.get(i) else { bail!("unterminated $'…' quote in command") }; + match ch { + '\'' => return Ok(i + 1), + '\\' => { + let Some(&n) = chars.get(i + 1) else { bail!("unterminated $'…' quote in command") }; + i += 2; + match n { + 'n' => out.push('\n'), + 't' => out.push('\t'), + 'r' => out.push('\r'), + 'a' => out.push('\x07'), + 'b' => out.push('\x08'), + 'e' | 'E' => out.push('\x1b'), + 'f' => out.push('\x0c'), + 'v' => out.push('\x0b'), + 'x' | 'u' | 'U' => { + let max = match n { + 'x' => 2, + 'u' => 4, + _ => 8, + }; + let hex: String = chars[i..].iter().take(max).take_while(|c| c.is_ascii_hexdigit()).collect(); + if hex.is_empty() { + out.push('\\'); + out.push(n); + } else { + i += hex.len(); + let code = u32::from_str_radix(&hex, 16).unwrap_or(0xfffd); + out.push(char::from_u32(code).unwrap_or('\u{fffd}')); + } + } + '0'..='7' => { + let oct: String = std::iter::once(n) + .chain(chars[i..].iter().copied().take(2).take_while(|c| ('0'..='7').contains(c))) + .collect(); + i += oct.len() - 1; + let code = u32::from_str_radix(&oct, 8).unwrap_or(0); + out.push(char::from_u32(code).unwrap_or('\u{fffd}')); + } + other => out.push(other), + } + } + _ => { + out.push(ch); + i += 1; + } + } + } +} + +fn is_cmd_style(cmd: &str) -> bool { + cmd.contains("^\n") || cmd.contains("^\r\n") || cmd.contains("^\"") +} + +/// cmd.exe: `^` escapes the next character and `^` + newline continues the line. +fn unescape_cmd(cmd: &str) -> String { + let mut out = String::with_capacity(cmd.len()); + let mut it = cmd.chars().peekable(); + while let Some(c) = it.next() { + if c != '^' { + out.push(c); + continue; + } + match it.next() { + Some('\r') => { + if it.peek() == Some(&'\n') { + it.next(); + } + } + Some('\n') => {} + Some(n) => out.push(n), + None => {} + } + } + out +} + +/// Long options that take a value. Everything else is treated as a flag. +const LONG_WITH_VALUE: &[&str] = &[ + "request", "header", "data", "data-raw", "data-binary", "data-ascii", "data-urlencode", "json", "form", + "form-string", "user", "cookie", "user-agent", "referer", "url", "output", "max-time", "connect-timeout", + "proxy", "proxy-user", "cert", "key", "cacert", "capath", "cookie-jar", "write-out", "retry", "max-redirs", + "oauth2-bearer", "aws-sigv4", "resolve", "connect-to", "range", "upload-file", "unix-socket", "config", + "interface", "local-port", "limit-rate", "pass", "key-type", "cert-type", "ciphers", "dump-header", + "trace", "trace-ascii", "stderr", "retry-delay", "retry-max-time", "expect100-timeout", "time-cond", + "request-target", "preproxy", "noproxy", "variable", "url-query", "header-file", "proto", "proto-redir", +]; + +fn short_takes_value(c: char) -> bool { + matches!(c, 'X' | 'H' | 'd' | 'u' | 'b' | 'A' | 'e' | 'F' | 'o' | 'm' | 'w' | 'x' | 'T' | 'E' | 'r' | 'c' | 'K' | 'U' | 'Y' | 'y' | 'z' | 'C' | 'D' | 'P' | 'Q' | 't') +} + +fn short_to_long(c: char) -> Option<&'static str> { + Some(match c { + 'X' => "request", + 'H' => "header", + 'd' => "data", + 'u' => "user", + 'b' => "cookie", + 'A' => "user-agent", + 'e' => "referer", + 'F' => "form", + 'm' => "max-time", + 'T' => "upload-file", + 'G' => "get", + 'I' => "head", + 'k' => "insecure", + 'L' => "location", + _ => return None, + }) +} + +enum DataPart { + /// Sent as is (already in wire form). + Text(String), + /// `@file` for -d / --data-binary. + File { path: String, binary: bool }, +} + +#[derive(Default)] +struct Parsed { + method: Option, + url: Option, + headers: Vec, + data: Vec, + json: bool, + form: Vec, + user: Option, + digest: bool, + get: bool, + head: bool, + upload: Option, + bearer: Option, + sigv4: Option, + settings: RequestSettings, + notes: Vec, +} + +/// Parses a cURL command into a request. Credentials stay literal; call +/// [`super::externalize_secrets`] before saving the request into a collection. +pub fn parse_curl(cmd: &str) -> Result { + let words = split_shell(cmd.trim())?; + let mut it = words.into_iter().peekable(); + match it.next() { + Some(w) if is_curl_word(&w) => {} + Some(w) => bail!("expected a curl command, found '{w}'"), + None => bail!("the command is empty"), + } + let mut p = Parsed::default(); + let mut only_urls = false; + while let Some(w) = it.next() { + if only_urls || !w.starts_with('-') || w == "-" { + set_url_once(&mut p, w)?; + continue; + } + if w == "--" { + only_urls = true; + continue; + } + if let Some(long) = w.strip_prefix("--") { + let (name, inline) = match long.split_once('=') { + Some((n, v)) if LONG_WITH_VALUE.contains(&n) => (n.to_string(), Some(v.to_string())), + _ => (long.to_string(), None), + }; + let value = if LONG_WITH_VALUE.contains(&name.as_str()) { + match inline { + Some(v) => Some(v), + None => Some(it.next().ok_or_else(|| anyhow!("option --{name} needs a value"))?), + } + } else { + None + }; + apply(&mut p, &name, value)?; + continue; + } + // Short options, possibly combined (`-sSL`) or with an attached value (`-XPOST`). + let flags: Vec = w[1..].chars().collect(); + let mut j = 0; + while j < flags.len() { + let c = flags[j]; + if short_takes_value(c) { + let rest: String = flags[j + 1..].iter().collect(); + let value = if rest.is_empty() { + it.next().ok_or_else(|| anyhow!("option -{c} needs a value"))? + } else { + rest + }; + if let Some(long) = short_to_long(c) { + apply(&mut p, long, Some(value))?; + } + break; + } + if let Some(long) = short_to_long(c) { + apply(&mut p, long, None)?; + } + j += 1; + } + } + build(p) +} + +fn is_curl_word(w: &str) -> bool { + let base = w.rsplit(['/', '\\']).next().unwrap_or(w).to_ascii_lowercase(); + base == "curl" || base == "curl.exe" +} + +fn set_url_once(p: &mut Parsed, url: String) -> Result<()> { + if p.url.is_none() { + p.url = Some(url); + } else { + p.notes.push(format!("Additional URL ignored: {url}")); + } + Ok(()) +} + +fn apply(p: &mut Parsed, name: &str, value: Option) -> Result<()> { + let v = value.unwrap_or_default(); + match name { + "request" => p.method = Some(v.to_uppercase()), + "url" => set_url_once(p, v)?, + "header" => { + if let Some(file) = v.strip_prefix('@') { + p.notes.push(format!("Headers from file `{file}` were not imported.")); + } else if let Some((n, val)) = v.split_once(':') { + let val = val.trim(); + // `Name:` with no value removes a header in curl. + if !val.is_empty() { + p.headers.push(KeyValue::new(n.trim(), val)); + } + } else if let Some(n) = v.strip_suffix(';') { + p.headers.push(KeyValue::new(n.trim(), "")); + } + } + "data" | "data-ascii" | "data-binary" => { + if let Some(path) = v.strip_prefix('@') { + p.data.push(DataPart::File { + path: path.to_string(), + binary: name == "data-binary", + }); + } else { + let text = if name == "data-binary" { v } else { v.replace(['\r', '\n'], "") }; + p.data.push(DataPart::Text(text)); + } + } + "data-raw" => p.data.push(DataPart::Text(v)), + "json" => { + p.json = true; + if let Some(path) = v.strip_prefix('@') { + p.data.push(DataPart::File { path: path.to_string(), binary: true }); + } else { + p.data.push(DataPart::Text(v)); + } + } + "data-urlencode" => p.data.push(urlencode_part(&v, &mut p.notes)), + "form" | "form-string" => p.form.push(form_part(&v, name == "form-string", &mut p.notes)?), + "user" => p.user = Some(v), + "digest" => p.digest = true, + "basic" => p.digest = false, + "cookie" => { + if v.contains('=') { + p.headers.push(KeyValue::new("Cookie", v)); + } else { + p.notes.push(format!("Cookies from file `{v}` were not imported.")); + } + } + "user-agent" => p.headers.push(KeyValue::new("User-Agent", v)), + "referer" => p.headers.push(KeyValue::new("Referer", v.trim_end_matches(";auto"))), + "get" => p.get = true, + "head" => p.head = true, + "insecure" => p.settings.verify_tls = false, + "location" | "location-trusted" => p.settings.follow_redirects = true, + "max-redirs" => { + if let Ok(n) = v.trim().parse::() { + p.settings.max_redirects = n.clamp(0, u32::MAX as i64) as u32; + } + } + "max-time" => { + if let Ok(secs) = v.trim().parse::() { + if secs > 0.0 { + p.settings.timeout_ms = (secs * 1000.0) as u64; + } + } + } + "http1.1" | "http1.0" => p.settings.http_version = HttpVersion::Http1, + "http2" | "http2-prior-knowledge" => p.settings.http_version = HttpVersion::Http2, + "upload-file" => p.upload = Some(v), + "oauth2-bearer" => p.bearer = Some(v), + "aws-sigv4" => p.sigv4 = Some(v), + "url-query" => p.notes.push(format!("--url-query `{v}` was not imported.")), + _ => {} + } + Ok(()) +} + +/// `--data-urlencode` forms: `content`, `=content`, `name=content`, `@file`, `name@file`. +fn urlencode_part(v: &str, notes: &mut Vec) -> DataPart { + let enc = |s: &str| url::form_urlencoded::byte_serialize(s.as_bytes()).collect::(); + if let Some((name, content)) = v.split_once('=') { + return DataPart::Text(if name.is_empty() { enc(content) } else { format!("{name}={}", enc(content)) }); + } + if let Some((name, file)) = v.split_once('@') { + notes.push(format!("`--data-urlencode {v}` reads `{file}` when curl runs; the file was not imported.")); + return DataPart::Text(if name.is_empty() { String::new() } else { format!("{name}=") }); + } + DataPart::Text(enc(v)) +} + +fn form_part(v: &str, literal: bool, notes: &mut Vec) -> Result { + let (name, rest) = v + .split_once('=') + .ok_or_else(|| anyhow!("form field '{v}' must look like name=value"))?; + let mut part = MultipartPart { + name: name.to_string(), + enabled: true, + ..Default::default() + }; + if literal { + part.value = rest.to_string(); + return Ok(part); + } + let (main, opts) = split_form_options(rest); + for opt in opts { + if let Some(t) = opt.strip_prefix("type=") { + part.content_type = Some(t.to_string()); + } else if let Some(f) = opt.strip_prefix("filename=") { + notes.push(format!("Form field `{name}` used filename `{f}`; the file's own name is sent instead.")); + } + } + if let Some(path) = main.strip_prefix('@') { + part.file = Some(path.to_string()); + } else if let Some(path) = main.strip_prefix('<') { + part.file = Some(path.to_string()); + notes.push(format!("Form field `{name}` read its text from `{path}`; it is sent as a file part.")); + } else { + part.value = main; + } + Ok(part) +} + +/// Splits `value;type=x;filename=y`, honouring a quoted value. +fn split_form_options(s: &str) -> (String, Vec) { + let (main, rest) = if let Some(q) = s.strip_prefix('"') { + match q.find('"') { + Some(end) => (q[..end].to_string(), &q[end + 1..]), + None => (q.to_string(), ""), + } + } else { + match s.find(";type=").or_else(|| s.find(";filename=")).or_else(|| s.find(";headers=")) { + Some(i) => (s[..i].to_string(), &s[i..]), + None => (s.to_string(), ""), + } + }; + let opts = rest.split(';').map(str::trim).filter(|o| !o.is_empty()).map(str::to_string).collect(); + (main, opts) +} + +fn build(p: Parsed) -> Result { + let url = p.url.clone().ok_or_else(|| anyhow!("the curl command has no URL"))?; + let mut req = Request { + headers: p.headers, + settings: p.settings, + auth: Auth::None, + ..Default::default() + }; + let mut notes = p.notes; + + // Body + let has_data = !p.data.is_empty(); + let mut query_extra = Vec::new(); + if !p.form.is_empty() { + req.body = Body { + kind: BodyType::Multipart, + multipart: p.form, + ..Default::default() + }; + drop_header(&mut req.headers, "content-type", |v| v.to_ascii_lowercase().starts_with("multipart/form-data")); + } else if has_data && p.get { + for d in &p.data { + match d { + DataPart::Text(t) => query_extra.extend(parse_query(&format!("?{t}"))), + DataPart::File { path, .. } => notes.push(format!("Query data from file `{path}` was not imported.")), + } + } + } else if has_data { + if p.json { + add_default_header(&mut req.headers, "Content-Type", "application/json"); + add_default_header(&mut req.headers, "Accept", "application/json"); + } + req.body = data_body(&p.data, &mut req.headers, &mut notes); + } else if let Some(file) = &p.upload { + req.body = Body { + kind: BodyType::Binary, + file: Some(file.clone()), + ..Default::default() + }; + } + + // Method + let method = p.method.clone().unwrap_or_else(|| { + if p.head { + "HEAD".into() + } else if p.upload.is_some() && !has_data && req.body.kind == BodyType::Binary { + "PUT".into() + } else if (has_data && !p.get) || !req.body.multipart.is_empty() { + "POST".into() + } else { + "GET".into() + } + }); + req.method = Some(method.clone()); + + // Auth + if let Some(user) = &p.user { + let (u, pw) = user.split_once(':').unwrap_or((user.as_str(), "")); + if let Some(sig) = &p.sigv4 { + // aws:amz:region:service + let parts: Vec<&str> = sig.split(':').collect(); + req.auth = super::auth( + "awsv4", + [ + ("access_key", u.to_string()), + ("secret_key", pw.to_string()), + ("region", parts.get(2).unwrap_or(&"").to_string()), + ("service", parts.get(3).unwrap_or(&"").to_string()), + ], + ); + } else { + let kind = if p.digest { "digest" } else { "basic" }; + req.auth = super::auth(kind, [("username", u.to_string()), ("password", pw.to_string())]); + } + } else if let Some(token) = &p.bearer { + req.auth = super::auth("bearer", [("token", token.clone())]); + } + if let Some(i) = req.headers.iter().position(|h| h.name.eq_ignore_ascii_case("authorization")) { + if matches!(req.auth, Auth::None) { + if let Some(a) = auth_from_header(&req.headers[i].value) { + req.auth = a; + req.headers.remove(i); + } + } + } + + // URL and query + let mut rows = parse_query(&url); + rows.extend(query_extra); + set_url(&mut req, &url, rows); + req.name = format!("{method} {}", url_path(&req.url)); + + if !notes.is_empty() { + let list: Vec = notes.iter().map(|n| format!("- {n}")).collect(); + req.docs = Some(format!("Imported from cURL:\n\n{}", list.join("\n"))); + } + Ok(req) +} + +fn data_body(data: &[DataPart], headers: &mut Vec, notes: &mut Vec) -> Body { + if let [DataPart::File { path, binary }] = data { + notes.push(if *binary { + format!("The body is read from `{path}`.") + } else { + format!("The body is read from `{path}`; curl -d strips line breaks from it, knock sends the file as is.") + }); + let ct = header_value(headers, "content-type"); + drop_header(headers, "content-type", |_| true); + return Body { + kind: BodyType::Binary, + file: Some(path.clone()), + content_type: ct, + ..Default::default() + }; + } + let mut text = String::new(); + for d in data { + if !text.is_empty() { + text.push('&'); + } + match d { + DataPart::Text(t) => text.push_str(t), + DataPart::File { path, .. } => { + notes.push(format!("Body part `@{path}` reads a file when curl runs; it was kept as text.")); + text.push('@'); + text.push_str(path); + } + } + } + let ct = header_value(headers, "content-type").map(|c| c.to_ascii_lowercase()); + let is_json_ct = ct.as_deref().is_some_and(|c| c.contains("json")); + let is_form_ct = ct.as_deref().is_some_and(|c| c.starts_with("application/x-www-form-urlencoded")); + if is_json_ct || (ct.is_none() && looks_like_json(&text)) { + drop_header(headers, "content-type", |v| v.eq_ignore_ascii_case("application/json")); + return Body { + kind: BodyType::Json, + content: pretty_json(&text), + ..Default::default() + }; + } + if is_form_ct || (ct.is_none() && looks_like_form(&text)) { + drop_header(headers, "content-type", |_| is_form_ct); + return Body { + kind: BodyType::FormUrlencoded, + form: parse_query(&format!("?{text}")), + ..Default::default() + }; + } + let content_type = header_value(headers, "content-type").or_else(|| Some("application/x-www-form-urlencoded".into())); + drop_header(headers, "content-type", |_| true); + Body { + kind: BodyType::Raw, + content: text, + content_type, + ..Default::default() + } +} + +fn looks_like_form(s: &str) -> bool { + !s.is_empty() + && !s.contains(['\n', ' ', '{', '<']) + && s.split('&').all(|pair| match pair.split_once('=') { + Some((n, _)) => !n.is_empty(), + None => !pair.is_empty(), + }) +} + +fn header_value(headers: &[KeyValue], name: &str) -> Option { + headers.iter().rev().find(|h| h.name.eq_ignore_ascii_case(name)).map(|h| h.value.clone()) +} + +fn drop_header(headers: &mut Vec, name: &str, when: impl Fn(&str) -> bool) { + headers.retain(|h| !(h.name.eq_ignore_ascii_case(name) && when(&h.value))); +} + +fn add_default_header(headers: &mut Vec, name: &str, value: &str) { + if !headers.iter().any(|h| h.name.eq_ignore_ascii_case(name)) { + headers.push(KeyValue::new(name, value)); + } +} + +/// `Bearer x` and `Basic base64(user:pass)` become auth configs. +pub(crate) fn auth_from_header(value: &str) -> Option { + let (scheme, rest) = value.trim().split_once(' ')?; + let rest = rest.trim(); + if scheme.eq_ignore_ascii_case("bearer") && !rest.is_empty() { + return Some(super::auth("bearer", [("token", rest.to_string())])); + } + if scheme.eq_ignore_ascii_case("basic") { + let raw = base64::engine::general_purpose::STANDARD.decode(rest).ok()?; + let s = String::from_utf8(raw).ok()?; + let (u, p) = s.split_once(':').unwrap_or((s.as_str(), "")); + return Some(super::auth("basic", [("username", u.to_string()), ("password", p.to_string())])); + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cfg(a: &Auth) -> &AuthConfig { + match a { + Auth::Config(c) => c, + other => panic!("expected auth config, got {other:?}"), + } + } + + fn header<'a>(r: &'a Request, n: &str) -> Option<&'a str> { + r.headers.iter().find(|h| h.name.eq_ignore_ascii_case(n)).map(|h| h.value.as_str()) + } + + #[test] + fn chrome_bash_copy() { + let cmd = r#"curl 'https://api.example.com/v1/users?page=2&sort=name' \ + -H 'accept: application/json, text/plain, */*' \ + -H 'accept-language: de-DE,de;q=0.9,en;q=0.8' \ + -H 'authorization: Bearer eyJhbGciOiJIUzI1NiJ9.e30.abc' \ + -H 'cache-control: no-cache' \ + -H 'origin: https://app.example.com' \ + -H 'referer: https://app.example.com/' \ + -H 'sec-ch-ua: "Chromium";v="124", "Google Chrome";v="124"' \ + -H 'sec-fetch-mode: cors' \ + -H 'user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' \ + --compressed"#; + let r = parse_curl(cmd).unwrap(); + assert_eq!(r.method(), "GET"); + assert_eq!(r.name, "GET /v1/users"); + assert_eq!(r.url, "https://api.example.com/v1/users?page=2&sort=name"); + assert_eq!(r.params.query.len(), 2); + assert_eq!(r.params.query[1].value, "name"); + assert_eq!(cfg(&r.auth).str("token"), Some("eyJhbGciOiJIUzI1NiJ9.e30.abc")); + assert!(header(&r, "authorization").is_none()); + assert_eq!(header(&r, "sec-ch-ua"), Some(r#""Chromium";v="124", "Google Chrome";v="124""#)); + assert_eq!(r.headers.len(), 8); + } + + #[test] + fn chrome_ansi_c_quoted_json_post() { + let cmd = "curl 'https://api.example.com/graphql' \\\n -H 'content-type: application/json' \\\n --data-raw $'{\"query\":\"query { me { name } }\",\"note\":\"it\\'s \\u00e4\\\\n\"}'"; + let r = parse_curl(cmd).unwrap(); + assert_eq!(r.method(), "POST"); + assert_eq!(r.body.kind, BodyType::Json); + let v: serde_json::Value = serde_json::from_str(&r.body.content).unwrap(); + assert_eq!(v["note"], "it's ä\n"); + assert!(r.body.content.contains("\n \"query\""), "pretty printed: {}", r.body.content); + assert!(header(&r, "content-type").is_none()); + } + + #[test] + fn firefox_copy() { + let cmd = r#"curl 'https://shop.example.org/cart/add' -X POST -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:126.0) Gecko/20100101 Firefox/126.0' -H 'Accept: */*' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'Cookie: session=abc123; theme=dark' -H 'Connection: keep-alive' --data-raw 'product_id=42&qty=3¬e=gift+wrap%21'"#; + let r = parse_curl(cmd).unwrap(); + assert_eq!(r.method(), "POST"); + assert_eq!(r.body.kind, BodyType::FormUrlencoded); + assert_eq!(r.body.form.len(), 3); + assert_eq!(r.body.form[2].value, "gift wrap!"); + assert!(header(&r, "content-type").is_none()); + assert_eq!(header(&r, "cookie"), Some("session=abc123; theme=dark")); + } + + #[test] + fn multipart_upload() { + let cmd = r#"curl -X POST https://upload.example.com/files \ + -F "title=Quarterly report" \ + -F 'file=@/home/me/report.pdf;type=application/pdf' \ + -F meta='{"a":1}' \ + -H "X-Trace: 1""#; + let r = parse_curl(cmd).unwrap(); + assert_eq!(r.body.kind, BodyType::Multipart); + let parts = &r.body.multipart; + assert_eq!(parts.len(), 3); + assert_eq!(parts[0].value, "Quarterly report"); + assert_eq!(parts[1].file.as_deref(), Some("/home/me/report.pdf")); + assert_eq!(parts[1].content_type.as_deref(), Some("application/pdf")); + assert_eq!(parts[2].value, r#"{"a":1}"#); + } + + #[test] + fn basic_user_and_flags() { + let r = parse_curl("curl -sSLk -u admin:s3cr:et https://intranet.local:8443/status --max-time 5").unwrap(); + let c = cfg(&r.auth); + assert_eq!(c.kind, "basic"); + assert_eq!(c.str("username"), Some("admin")); + assert_eq!(c.str("password"), Some("s3cr:et")); + assert!(!r.settings.verify_tls); + assert!(r.settings.follow_redirects); + assert_eq!(r.settings.timeout_ms, 5000); + assert_eq!(r.name, "GET /status"); + } + + #[test] + fn json_flag() { + let r = parse_curl(r#"curl --json '{"name":"knock","tags":["a","b"]}' https://api.example.com/items"#).unwrap(); + assert_eq!(r.method(), "POST"); + assert_eq!(r.body.kind, BodyType::Json); + assert!(r.body.content.contains("\"tags\": [")); + assert_eq!(header(&r, "accept"), Some("application/json")); + } + + #[test] + fn basic_header_and_get_data() { + let r = parse_curl( + "curl -G https://api.example.com/search -d q=rust+lang --data-urlencode 'filter=a b&c' -H 'Authorization: Basic dXNlcjpwYXNz'", + ) + .unwrap(); + assert_eq!(r.method(), "GET"); + assert_eq!(r.body.kind, BodyType::None); + assert_eq!(r.params.query.len(), 2); + assert_eq!(r.params.query[0].value, "rust lang"); + assert_eq!(r.params.query[1].value, "a b&c"); + assert_eq!(r.url, "https://api.example.com/search?q=rust%20lang&filter=a%20b%26c"); + let c = cfg(&r.auth); + assert_eq!((c.str("username"), c.str("password")), (Some("user"), Some("pass"))); + } + + #[test] + fn windows_cmd_copy() { + let cmd = "curl ^\"https://api.example.com/v1/orders^\" ^\r\n -H ^\"accept: application/json^\" ^\r\n -H ^\"content-type: application/json^\" ^\r\n --data-raw ^\"^{^\\^\"id^\\^\":7^}^\""; + let r = parse_curl(cmd).unwrap(); + assert_eq!(r.url, "https://api.example.com/v1/orders"); + assert_eq!(r.method(), "POST"); + assert_eq!(r.body.kind, BodyType::Json); + assert!(r.body.content.contains("\"id\": 7")); + } + + #[test] + fn multiple_data_joined_and_raw_text() { + let r = parse_curl("curl https://x.example/a -d a=1 -d b=2").unwrap(); + assert_eq!(r.body.kind, BodyType::FormUrlencoded); + assert_eq!(r.body.form.len(), 2); + + let r = parse_curl("curl -X PUT https://x.example/a -H 'Content-Type: text/xml' -d '1'").unwrap(); + assert_eq!(r.method(), "PUT"); + assert_eq!(r.body.kind, BodyType::Raw); + assert_eq!(r.body.content_type.as_deref(), Some("text/xml")); + assert_eq!(r.body.content, "1"); + } + + #[test] + fn head_cookie_agent_referer_and_file_body() { + let r = parse_curl("curl -I --url https://x.example/ -b 'a=1' -A 'knock/1' -e https://ref.example").unwrap(); + assert_eq!(r.method(), "HEAD"); + assert_eq!(header(&r, "cookie"), Some("a=1")); + assert_eq!(header(&r, "user-agent"), Some("knock/1")); + assert_eq!(header(&r, "referer"), Some("https://ref.example")); + + let r = parse_curl("curl https://x.example/up --data-binary @payload.json -H 'Content-Type: application/json'").unwrap(); + assert_eq!(r.body.kind, BodyType::Binary); + assert_eq!(r.body.file.as_deref(), Some("payload.json")); + assert!(r.docs.unwrap().contains("payload.json")); + } + + #[test] + fn errors_are_clear() { + assert!(parse_curl("wget https://x").unwrap_err().to_string().contains("expected a curl command")); + assert!(parse_curl("curl -H 'a: b'").unwrap_err().to_string().contains("no URL")); + assert!(parse_curl("curl 'https://x").unwrap_err().to_string().contains("unterminated")); + } +} diff --git a/crates/knock-core/src/import/insomnia.rs b/crates/knock-core/src/import/insomnia.rs new file mode 100644 index 0000000..54fb905 --- /dev/null +++ b/crates/knock-core/src/import/insomnia.rs @@ -0,0 +1,446 @@ +//! Insomnia v4 exports (`_type: export`, `__export_format: 4`). + +use super::{looks_like_json, parse_query, pretty_json, set_url, text, ImportReport, Writer}; +use crate::model::*; +use anyhow::{anyhow, Context, Result}; +use indexmap::IndexMap; +use regex::Regex; +use serde_json::Value; +use std::path::Path; +use std::sync::OnceLock; + +/// `{{ _.name }}` → `{{name}}`. +pub fn convert_vars(s: &str) -> String { + static RE: OnceLock = OnceLock::new(); + let re = RE.get_or_init(|| Regex::new(r"\{\{\s*_\.([^\s}]+)\s*\}\}").expect("valid regex")); + re.replace_all(s, "{{$1}}").into_owned() +} + +pub fn import_insomnia(json: &str, dest: &Path) -> Result { + let root: Value = serde_json::from_str(json).context("the file is not valid JSON")?; + let resources = root + .get("resources") + .and_then(Value::as_array) + .ok_or_else(|| anyhow!("not an Insomnia export: the `resources` list is missing"))?; + let kind = |r: &Value| r.get("_type").and_then(Value::as_str).unwrap_or("").to_string(); + let workspaces: Vec<&Value> = resources.iter().filter(|r| kind(r) == "workspace").collect(); + if workspaces.is_empty() { + return Err(anyhow!("the Insomnia export contains no workspace")); + } + let name = if workspaces.len() == 1 { text(workspaces[0].get("name")) } else { "Insomnia".to_string() }; + let mut w = Writer::start(dest, &name)?; + let mut templates = 0usize; + + // Children by parent id, sorted like the Insomnia sidebar. + let mut children: IndexMap> = IndexMap::new(); + for r in resources { + children.entry(text(r.get("parentId"))).or_default().push(r); + } + for list in children.values_mut() { + list.sort_by(|a, b| { + let k = |r: &Value| r.get("metaSortKey").and_then(Value::as_f64).unwrap_or(0.0); + k(a).total_cmp(&k(b)) + }); + } + + // Environments: the base environment becomes collection variables, + // sub environments become knock environments. + let mut coll_vars = IndexMap::new(); + let mut env_count = 0; + let mut has_local = false; + for ws in &workspaces { + let ws_id = text(ws.get("_id")); + for base in children.get(&ws_id).into_iter().flatten().filter(|r| kind(r) == "environment") { + flatten("", base.get("data").unwrap_or(&Value::Null), &mut coll_vars); + for sub in children.get(&text(base.get("_id"))).into_iter().flatten().filter(|r| kind(r) == "environment") { + let mut vars = IndexMap::new(); + flatten("", sub.get("data").unwrap_or(&Value::Null), &mut vars); + let env = Environment { + color: sub.get("color").and_then(Value::as_str).map(str::to_string), + vars: vars + .into_iter() + .map(|(k, v)| (k, EnvVar { value: v, secret: false, description: None })) + .collect(), + ..Default::default() + }; + let id = w.environment(&text(sub.get("name")), env, IndexMap::new())?; + has_local |= id == "local"; + env_count += 1; + } + } + } + if !has_local { + if env_count > 0 { + w.remove_local_env()?; + } else { + w.reset_local_env(IndexMap::new())?; + } + } + let coll_vars: IndexMap = coll_vars.into_iter().map(|(k, v)| (k, convert_vars(&v))).collect(); + w.manifest(|m| m.vars = coll_vars)?; + + let mut skipped: IndexMap = IndexMap::new(); + for ws in &workspaces { + let folder = if workspaces.len() == 1 { String::new() } else { w.folder("", &text(ws.get("name")))? }; + walk(&mut w, &children, &text(ws.get("_id")), &folder, &mut skipped, &mut templates)?; + } + for (k, n) in skipped { + w.warn(format!("{n} Insomnia resource(s) of type `{k}` were not imported")); + } + if templates > 0 { + w.warn(format!( + "{templates} value(s) use Insomnia template tags ({{% … %}}); they were kept as text and need to be replaced" + )); + } + w.finish() +} + +fn flatten(prefix: &str, v: &Value, out: &mut IndexMap) { + match v { + Value::Object(m) => { + for (k, v) in m { + let key = if prefix.is_empty() { k.clone() } else { format!("{prefix}.{k}") }; + flatten(&key, v, out); + } + } + Value::Null if prefix.is_empty() => {} + other => { + out.insert(prefix.to_string(), scalar_to_string(other)); + } + } +} + +fn walk( + w: &mut Writer, + children: &IndexMap>, + parent: &str, + folder: &str, + skipped: &mut IndexMap, + templates: &mut usize, +) -> Result<()> { + for r in children.get(parent).into_iter().flatten() { + let ty = r.get("_type").and_then(Value::as_str).unwrap_or(""); + match ty { + "request_group" => { + let id = w.folder(folder, &text(r.get("name")))?; + let mut vars = IndexMap::new(); + flatten("", r.get("environment").unwrap_or(&Value::Null), &mut vars); + let mut warnings = Vec::new(); + let auth = map_auth(r.get("authentication"), &mut warnings); + let headers = rows(r.get("headers"), templates); + let docs = text(r.get("description")); + w.folder_meta(&id, |m| { + m.vars = vars.into_iter().map(|(k, v)| (k, convert_vars(&v))).collect(); + m.auth = auth; + m.headers = headers; + if !docs.trim().is_empty() { + m.extra.insert("docs".into(), docs.into()); + } + })?; + for msg in warnings { + w.warn(msg); + } + walk(w, children, &text(r.get("_id")), &id, skipped, templates)?; + } + "request" => { + let mut warnings = Vec::new(); + let req = map_request(r, &mut warnings, templates); + for msg in warnings { + w.warn(format!("{}: {msg}", req.name)); + } + w.request(folder, req)?; + } + "environment" | "workspace" | "cookie_jar" => {} + other => *skipped.entry(other.to_string()).or_default() += 1, + } + } + Ok(()) +} + +fn conv(s: String, templates: &mut usize) -> String { + if s.contains("{%") { + *templates += 1; + } + convert_vars(&s) +} + +fn rows(v: Option<&Value>, templates: &mut usize) -> Vec { + v.and_then(Value::as_array) + .into_iter() + .flatten() + .map(|p| KeyValue { + name: conv(text(p.get("name")), templates), + value: conv(text(p.get("value")), templates), + enabled: p.get("disabled").and_then(Value::as_bool) != Some(true), + description: p.get("description").and_then(Value::as_str).filter(|d| !d.is_empty()).map(str::to_string), + ..Default::default() + }) + .filter(|kv| !kv.name.is_empty() || !kv.value.is_empty()) + .collect() +} + +fn map_request(r: &Value, warnings: &mut Vec, templates: &mut usize) -> Request { + let mut req = Request { + name: text(r.get("name")), + method: Some(r.get("method").and_then(Value::as_str).unwrap_or("GET").to_uppercase()), + headers: rows(r.get("headers"), templates), + ..Default::default() + }; + let url = conv(text(r.get("url")), templates); + let mut query = parse_query(&url); + query.extend(rows(r.get("parameters"), templates)); + set_url(&mut req, &url, query); + for p in r.get("pathParameters").and_then(Value::as_array).into_iter().flatten() { + req.params.path.insert(text(p.get("name")), conv(text(p.get("value")), templates)); + } + req.auth = map_auth(r.get("authentication"), warnings); + if let Some(b) = r.get("body").filter(|b| b.as_object().is_some_and(|o| !o.is_empty())) { + map_body(&mut req, b, templates); + } + match r.get("settingFollowRedirects").and_then(Value::as_str) { + Some("off") => req.settings.follow_redirects = false, + Some("on") => req.settings.follow_redirects = true, + _ => {} + } + let docs = text(r.get("description")); + if !docs.trim().is_empty() { + req.docs = Some(docs); + } + req +} + +fn map_body(req: &mut Request, b: &Value, templates: &mut usize) { + let mime = text(b.get("mimeType")).to_ascii_lowercase(); + let content = conv(text(b.get("text")), templates); + if mime.contains("graphql") { + let parsed: Value = serde_json::from_str(&content).unwrap_or(Value::Null); + let variables = match parsed.get("variables") { + Some(Value::String(s)) => s.clone(), + Some(v @ Value::Object(_)) => serde_json::to_string_pretty(v).unwrap_or_default(), + _ => String::new(), + }; + req.kind = RequestKind::Graphql; + req.graphql = Some(GraphqlSpec { + query: text(parsed.get("query")), + variables, + operation_name: parsed.get("operationName").and_then(Value::as_str).map(str::to_string), + }); + drop_content_type(req); + return; + } + if mime.starts_with("application/x-www-form-urlencoded") { + req.body = Body { kind: BodyType::FormUrlencoded, form: rows(b.get("params"), templates), ..Default::default() }; + drop_content_type(req); + return; + } + if mime.starts_with("multipart/") { + let parts = b + .get("params") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|p| { + let is_file = p.get("type").and_then(Value::as_str) == Some("file"); + MultipartPart { + name: conv(text(p.get("name")), templates), + value: if is_file { String::new() } else { conv(text(p.get("value")), templates) }, + file: is_file.then(|| text(p.get("fileName"))), + content_type: None, + enabled: p.get("disabled").and_then(Value::as_bool) != Some(true), + } + }) + .collect(); + req.body = Body { kind: BodyType::Multipart, multipart: parts, ..Default::default() }; + drop_content_type(req); + return; + } + if let Some(file) = b.get("fileName").and_then(Value::as_str).filter(|f| !f.is_empty()) { + req.body = Body { kind: BodyType::Binary, file: Some(file.to_string()), ..Default::default() }; + return; + } + if content.is_empty() { + return; + } + if mime.contains("json") || (mime.is_empty() && looks_like_json(&content)) { + req.body = Body { kind: BodyType::Json, content: pretty_json(&content), ..Default::default() }; + req.headers + .retain(|h| !(h.name.eq_ignore_ascii_case("content-type") && h.value.eq_ignore_ascii_case("application/json"))); + } else { + req.body = Body { + kind: BodyType::Raw, + content, + content_type: (!mime.is_empty()).then_some(mime), + ..Default::default() + }; + } +} + +fn drop_content_type(req: &mut Request) { + req.headers.retain(|h| !h.name.eq_ignore_ascii_case("content-type")); +} + +fn map_auth(v: Option<&Value>, warnings: &mut Vec) -> Auth { + let Some(a) = v.and_then(Value::as_object).filter(|o| !o.is_empty()) else { return Auth::Inherit }; + if a.get("disabled").and_then(Value::as_bool) == Some(true) { + return Auth::None; + } + let g = |k: &str| convert_vars(&text(a.get(k))); + match a.get("type").and_then(Value::as_str).unwrap_or("") { + "none" => Auth::None, + "basic" => super::auth("basic", [("username", g("username")), ("password", g("password"))]), + "digest" => super::auth("digest", [("username", g("username")), ("password", g("password"))]), + "bearer" => super::auth("bearer", [("token", g("token")), ("prefix", g("prefix"))]), + "apikey" => { + let place = match g("addTo").as_str() { + "queryParams" => "query", + "cookie" => "cookie", + _ => "header", + }; + super::auth("apikey", [("key", g("key")), ("value", g("value")), ("in", place.into())]) + } + "iam" => super::auth( + "awsv4", + [ + ("access_key", g("accessKeyId")), + ("secret_key", g("secretAccessKey")), + ("session_token", g("sessionToken")), + ("region", g("region")), + ("service", g("service")), + ], + ), + "oauth1" => super::auth( + "oauth1", + [ + ("consumer_key", g("consumerKey")), + ("consumer_secret", g("consumerSecret")), + ("token", g("tokenKey")), + ("token_secret", g("tokenSecret")), + ("signature_method", g("signatureMethod")), + ], + ), + "oauth2" => { + let grant = match g("grantType").as_str() { + "client_credentials" => "client_credentials", + "password" => "password", + "implicit" => { + warnings.push("OAuth 2 implicit grant is not supported; imported as authorization code".into()); + "authorization_code" + } + _ => "authorization_code", + }; + let in_body = a.get("credentialsInBody").and_then(Value::as_bool) == Some(true); + let mut auth = super::auth( + "oauth2", + [ + ("grant", grant.to_string()), + ("authorize_url", g("authorizationUrl")), + ("token_url", g("accessTokenUrl")), + ("client_id", g("clientId")), + ("client_secret", g("clientSecret")), + ("client_auth", if in_body { "post" } else { "basic" }.to_string()), + ("scopes", g("scope")), + ("audience", g("audience")), + ("username", g("username")), + ("password", g("password")), + ("token_prefix", g("tokenPrefix")), + ], + ); + if let Auth::Config(c) = &mut auth { + if a.get("usePkce").and_then(Value::as_bool) == Some(true) { + c.fields.insert("pkce".into(), Value::Bool(true)); + } + } + auth + } + other => { + warnings.push(format!("auth type `{other}` is not supported and was left as inherit")); + Auth::Inherit + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::collection::Collection; + + const EXPORT: &str = r##"{ + "_type": "export", + "__export_format": 4, + "__export_source": "insomnia.desktop.app:v2023.5.8", + "resources": [ + { "_id": "wrk_1", "_type": "workspace", "parentId": null, "name": "Billing" }, + { "_id": "env_base", "_type": "environment", "parentId": "wrk_1", "name": "Base Environment", + "data": { "base_url": "https://billing.example.com", "api": { "version": "v2" } } }, + { "_id": "env_dev", "_type": "environment", "parentId": "env_base", "name": "Dev", "color": "#7d69cb", + "data": { "base_url": "http://localhost:9000" } }, + { "_id": "fld_1", "_type": "request_group", "parentId": "wrk_1", "name": "Invoices", "metaSortKey": -10, + "environment": { "limit": 50 }, + "authentication": { "type": "bearer", "token": "{{ _.token }}" } }, + { "_id": "req_2", "_type": "request", "parentId": "fld_1", "name": "Create invoice", "metaSortKey": 2, + "method": "POST", "url": "{{ _.base_url }}/{{ _.api.version }}/invoices", + "headers": [ { "name": "Content-Type", "value": "application/json" }, { "name": "X-Old", "value": "1", "disabled": true } ], + "body": { "mimeType": "application/json", "text": "{\"amount\": {{ _.amount }}, \"currency\": \"EUR\"}" }, + "authentication": {} }, + { "_id": "req_1", "_type": "request", "parentId": "fld_1", "name": "List invoices", "metaSortKey": 1, + "method": "GET", "url": "{{ _.base_url }}/invoices", + "parameters": [ { "name": "limit", "value": "{{ _.limit }}" }, { "name": "status", "value": "open", "disabled": true } ], + "authentication": {} }, + { "_id": "req_3", "_type": "request", "parentId": "wrk_1", "name": "Token", "metaSortKey": 5, + "method": "POST", "url": "{{ _.base_url }}/oauth/token", + "body": { "mimeType": "application/x-www-form-urlencoded", "params": [ { "name": "grant_type", "value": "client_credentials" } ] }, + "authentication": { "type": "basic", "username": "client", "password": "s3cret" } }, + { "_id": "req_4", "_type": "request", "parentId": "wrk_1", "name": "Stamp", "metaSortKey": 6, + "method": "GET", "url": "{{ _.base_url }}/time?ts={% now 'millis', '' %}", "authentication": { "type": "none" } }, + { "_id": "ws_1", "_type": "websocket_request", "parentId": "wrk_1", "name": "Live" } + ] +}"##; + + #[test] + fn converts_template_vars() { + assert_eq!(convert_vars("{{ _.base_url }}/a/{{_.x}}"), "{{base_url}}/a/{{x}}"); + assert_eq!(convert_vars("{{ plain }}"), "{{ plain }}"); + } + + #[test] + fn imports_export() { + let dir = super::super::tmp_dir(); + let rep = import_insomnia(EXPORT, &dir).unwrap(); + assert_eq!(rep.requests, 4); + assert_eq!(rep.folders, 1); + assert_eq!(rep.environments, vec!["dev".to_string()]); + assert!(rep.warnings.iter().any(|w| w.contains("websocket_request"))); + assert!(rep.warnings.iter().any(|w| w.contains("template tags"))); + + let c = Collection::open(&dir).unwrap(); + assert_eq!(c.manifest.name, "Billing"); + assert_eq!(c.manifest.vars["api.version"], "v2"); + assert_eq!(c.environment("dev").unwrap().vars["base_url"].value, "http://localhost:9000"); + assert_eq!( + c.requests_in(""), + vec!["invoices/list-invoices.yaml", "invoices/create-invoice.yaml", "token.yaml", "stamp.yaml"] + ); + let meta = c.folder_meta("invoices").unwrap(); + assert_eq!(meta.vars["limit"], "50"); + let Auth::Config(a) = &meta.auth else { panic!() }; + assert_eq!(a.str("token"), Some("{{token}}")); + + let list = c.request("invoices/list-invoices.yaml").unwrap(); + assert_eq!(list.url, "{{base_url}}/invoices?limit={{limit}}"); + assert!(!list.params.query[1].enabled); + assert_eq!(list.auth, Auth::Inherit); + + let create = c.request("invoices/create-invoice.yaml").unwrap(); + assert_eq!(create.url, "{{base_url}}/{{api.version}}/invoices"); + assert_eq!(create.body.kind, BodyType::Json); + assert_eq!(create.body.content, "{\"amount\": {{amount}}, \"currency\": \"EUR\"}"); + assert_eq!(create.headers.len(), 1); + + let token = c.request("token.yaml").unwrap(); + assert_eq!(token.body.form[0].value, "client_credentials"); + let Auth::Config(b) = &token.auth else { panic!() }; + assert_eq!(b.str("password"), Some("{{secret.token_password}}")); + assert_eq!(c.secrets_file("dev").unwrap().vars["token_password"], "s3cret"); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/knock-core/src/import/mod.rs b/crates/knock-core/src/import/mod.rs new file mode 100644 index 0000000..f32f0f0 --- /dev/null +++ b/crates/knock-core/src/import/mod.rs @@ -0,0 +1,506 @@ +//! Importers that turn other tools' formats into knock collections. +//! +//! Every importer writes through [`Collection`] so files, order and the +//! `.gitignore` look exactly like a collection created in the app. Literal +//! credentials found in auth configs are moved into the secrets files of the +//! imported environments and replaced by `{{secret.name}}` references. + +pub mod bruno; +pub mod curl; +pub mod insomnia; +pub mod openapi; +pub mod postman; + +use crate::collection::{read_yaml, slugify, Collection, ENV_DIR, MANIFEST}; +use crate::model::*; +use anyhow::{bail, Context, Result}; +use indexmap::IndexMap; +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +pub use bruno::import_bruno; +pub use curl::parse_curl; +pub use insomnia::import_insomnia; +pub use openapi::import_openapi; +pub use postman::{import_postman, import_postman_environment}; + +#[derive(Debug, Clone, Default, Serialize)] +pub struct ImportReport { + pub collection_root: PathBuf, + pub requests: usize, + pub folders: usize, + pub environments: Vec, + pub scripts_skipped: usize, + pub warnings: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Kind { + Curl, + PostmanCollection, + PostmanEnvironment, + Insomnia, + Openapi, +} + +/// Guesses the format of pasted or opened text. +pub fn detect(text: &str) -> Option { + let t = text.trim_start(); + let lower = t.get(..10).unwrap_or(t).to_ascii_lowercase(); + if lower.starts_with("curl ") || lower.starts_with("curl.exe ") || lower.starts_with("curl\t") { + return Some(Kind::Curl); + } + let v: serde_json::Value = if t.starts_with('{') { + serde_json::from_str(t).ok()? + } else { + serde_yaml_ng::from_str(t).ok()? + }; + let o = v.as_object()?; + if o.contains_key("openapi") || o.contains_key("swagger") { + return Some(Kind::Openapi); + } + if o.get("_type").and_then(|v| v.as_str()) == Some("export") + && o.get("resources").is_some_and(|r| r.is_array()) + { + return Some(Kind::Insomnia); + } + if let Some(info) = o.get("info").and_then(|i| i.as_object()) { + let schema = info.get("schema").and_then(|s| s.as_str()).unwrap_or(""); + if schema.contains("getpostman.com") || info.contains_key("_postman_id") || o.get("item").is_some_and(|i| i.is_array()) { + return Some(Kind::PostmanCollection); + } + } + if o.get("values").is_some_and(|v| v.is_array()) + && (o.contains_key("_postman_variable_scope") || o.contains_key("name")) + { + return Some(Kind::PostmanEnvironment); + } + None +} + +// ---------------------------------------------------------------- writer + +/// Accumulates an import into a fresh collection. +pub(crate) struct Writer { + pub c: Collection, + pub report: ImportReport, + /// Credentials pulled out of auth configs, name -> value. + secrets: IndexMap, +} + +impl Writer { + pub fn start(dest: &Path, name: &str) -> Result { + if dest.exists() { + if !dest.is_dir() { + bail!("{} exists and is not a folder", dest.display()); + } + let mut entries = std::fs::read_dir(dest).with_context(|| format!("reading {}", dest.display()))?; + if entries.next().is_some() { + bail!("{} is not empty; choose an empty folder for the imported collection", dest.display()); + } + } + let name = if name.trim().is_empty() { "Imported collection" } else { name.trim() }; + let c = Collection::create(dest, name)?; + let report = ImportReport { + collection_root: c.root.clone(), + ..Default::default() + }; + Ok(Self { + c, + report, + secrets: IndexMap::new(), + }) + } + + pub fn warn(&mut self, msg: impl Into) { + self.report.warnings.push(msg.into()); + } + + pub fn manifest(&self, f: impl FnOnce(&mut Manifest)) -> Result<()> { + let mut m: Manifest = read_yaml(&self.c.root.join(MANIFEST))?; + f(&mut m); + self.c.save_manifest(&m) + } + + pub fn collection_auth(&mut self, mut auth: Auth) -> Result<()> { + let prefix = self.c.manifest.name.clone(); + self.secure(&mut auth, &prefix); + self.manifest(|m| m.auth = auth) + } + + pub fn folder(&mut self, parent: &str, name: &str) -> Result { + let id = self.c.create_folder(parent, if name.trim().is_empty() { "Folder" } else { name })?; + self.report.folders += 1; + Ok(id) + } + + pub fn folder_meta(&mut self, id: &str, f: impl FnOnce(&mut FolderMeta)) -> Result<()> { + let mut meta = self.c.folder_meta(id)?; + f(&mut meta); + let prefix = meta.name.clone().unwrap_or_else(|| id.to_string()); + self.secure(&mut meta.auth, &prefix); + self.c.save_folder_meta(id, &meta) + } + + pub fn request(&mut self, folder: &str, mut req: Request) -> Result { + if req.name.trim().is_empty() { + req.name = "Untitled request".into(); + } + let prefix = req.name.clone(); + self.secure(&mut req.auth, &prefix); + let id = self.c.create_request(folder, &req)?; + self.report.requests += 1; + Ok(id) + } + + /// Writes an environment; `secrets` go to its gitignored secrets file. + pub fn environment(&mut self, name: &str, mut env: Environment, secrets: IndexMap) -> Result { + let id = slugify(name); + if env.name.is_none() && id != name { + env.name = Some(name.to_string()); + } + for k in secrets.keys() { + env.vars.entry(k.clone()).or_insert(EnvVar { + value: String::new(), + secret: true, + description: None, + }); + } + for (k, v) in env.vars.iter_mut() { + if secrets.contains_key(k) { + v.secret = true; + v.value.clear(); + } + } + self.c.save_environment(&id, &env)?; + if !secrets.is_empty() { + self.c.save_secrets_file(&id, &SecretsFile { vars: secrets })?; + } + Ok(id) + } + + fn secure(&mut self, auth: &mut Auth, prefix: &str) { + let before = self.secrets.len(); + externalize_secrets(auth, prefix, &mut self.secrets); + if self.secrets.len() > before && before == 0 { + self.report.warnings.push( + "credentials found in auth settings were moved to the environments' secrets files (gitignored)".into(), + ); + } + } + + pub fn finish(mut self) -> Result { + let c = Collection::open(&self.c.root)?; + for env in &c.environments { + if !self.secrets.is_empty() { + let mut file = c.secrets_file(&env.id)?; + for (k, v) in &self.secrets { + file.vars.entry(k.clone()).or_insert_with(|| v.clone()); + } + c.save_secrets_file(&env.id, &file)?; + } + self.report.environments.push(env.id.clone()); + } + if self.secrets.is_empty() { + return Ok(self.report); + } + if c.environments.is_empty() { + let id = "local"; + c.save_environment(id, &Environment::default())?; + c.save_secrets_file(id, &SecretsFile { vars: self.secrets.clone() })?; + self.report.environments.push(id.into()); + } + Ok(self.report) + } + + /// Replaces the default `local` environment written by `Collection::create`. + pub fn reset_local_env(&self, vars: IndexMap) -> Result<()> { + let env = Environment { + vars: vars + .into_iter() + .map(|(k, v)| (k, EnvVar { value: v, secret: false, description: None })) + .collect(), + ..Default::default() + }; + self.c.save_environment("local", &env) + } + + pub fn remove_local_env(&self) -> Result<()> { + let p = self.c.root.join(ENV_DIR).join("local.yaml"); + if p.exists() { + std::fs::remove_file(p)?; + } + Ok(()) + } +} + +/// Auth fields that hold credentials, per auth type. +fn secret_fields(kind: &str) -> &'static [&'static str] { + match kind { + "basic" | "digest" => &["password"], + "bearer" => &["token"], + "apikey" => &["value"], + "oauth2" | "oidc" => &["client_secret", "password"], + "awsv4" => &["secret_key", "session_token"], + "oauth1" => &["consumer_secret", "token_secret"], + "jwt" => &["secret", "private_key"], + _ => &["password", "secret", "client_secret", "token"], + } +} + +/// Moves literal credentials of `auth` into `store` and replaces them by +/// `{{secret.name}}`. Values that already use variables are left alone. +/// Equal values share one secret name. +pub fn externalize_secrets(auth: &mut Auth, prefix: &str, store: &mut IndexMap) { + let Auth::Config(cfg) = auth else { return }; + let base = secret_base(prefix); + for field in secret_fields(&cfg.kind) { + let Some(serde_json::Value::String(v)) = cfg.fields.get(*field) else { continue }; + if v.is_empty() || v.contains("{{") { + continue; + } + let v = v.clone(); + let name = match store.iter().find(|(_, val)| **val == v) { + Some((k, _)) => k.clone(), + None => { + let first = format!("{base}_{field}"); + let name = if store.contains_key(&first) { + (2..).map(|n| format!("{first}_{n}")).find(|n| !store.contains_key(n)).unwrap_or(first) + } else { + first + }; + store.insert(name.clone(), v); + name + } + }; + cfg.fields + .insert(field.to_string(), serde_json::Value::String(format!("{{{{secret.{name}}}}}"))); + } +} + +fn secret_base(prefix: &str) -> String { + let s = slugify(prefix).replace('-', "_"); + if s == "untitled" { + "imported".into() + } else { + s + } +} + +// ---------------------------------------------------------------- shared helpers + +pub(crate) fn auth(kind: &str, fields: impl IntoIterator) -> Auth { + Auth::Config(AuthConfig { + kind: kind.to_string(), + fields: fields + .into_iter() + .filter(|(_, v)| !v.is_empty()) + .map(|(k, v)| (k.to_string(), serde_json::Value::String(v))) + .collect(), + }) +} + +pub(crate) fn append_docs(req: &mut Request, text: &str) { + if text.trim().is_empty() { + return; + } + match &mut req.docs { + Some(d) if !d.trim().is_empty() => { + d.push_str("\n\n"); + d.push_str(text.trim_end()); + } + _ => req.docs = Some(text.trim_end().to_string()), + } +} + +/// Markdown block with skipped scripts. `scripts` is (label, language, source). +pub(crate) fn scripts_doc(tool: &str, scripts: &[(&str, &str, String)]) -> String { + let mut out = format!("## Imported {tool} scripts (not run)\n"); + for (label, lang, src) in scripts { + out.push_str(&format!("\n### {label}\n\n```{lang}\n{}\n```\n", src.trim_end())); + } + out +} + +pub(crate) fn looks_like_json(s: &str) -> bool { + let t = s.trim(); + (t.starts_with('{') || t.starts_with('[')) && serde_json::from_str::(t).is_ok() +} + +/// Pretty-prints JSON text; leaves it unchanged if it does not parse (e.g. because of `{{vars}}`). +pub(crate) fn pretty_json(s: &str) -> String { + match serde_json::from_str::(s.trim()) { + Ok(v) => serde_json::to_string_pretty(&v).unwrap_or_else(|_| s.to_string()), + Err(_) => s.to_string(), + } +} + +/// Splits `?a=1&b` off a URL, decoding names and values but keeping `{{vars}}`. +pub(crate) fn parse_query(url: &str) -> Vec { + let Some(q) = url.find('?') else { return Vec::new() }; + let mut qs = &url[q + 1..]; + if let Some(h) = qs.find('#') { + qs = &qs[..h]; + } + if qs.is_empty() { + return Vec::new(); + } + qs.split('&') + .map(|pair| { + let (n, v) = pair.split_once('=').unwrap_or((pair, "")); + KeyValue::new(decode(n), decode(v)) + }) + .collect() +} + +fn decode(s: &str) -> String { + let s = s.replace('+', " "); + percent_encoding::percent_decode_str(&s) + .decode_utf8() + .map(|c| c.into_owned()) + .unwrap_or(s) +} + +const QUERY_PART: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC + .remove(b'-') + .remove(b'_') + .remove(b'.') + .remove(b'!') + .remove(b'~') + .remove(b'*') + .remove(b'\'') + .remove(b'(') + .remove(b')') + .remove(b'/') + .remove(b':') + .remove(b','); + +/// Encodes a query name or value, leaving `{{vars}}` readable. +pub(crate) fn encode_part(s: &str) -> String { + let mut out = String::new(); + let mut rest = s; + while let Some(start) = rest.find("{{") { + let Some(end) = rest[start..].find("}}") else { break }; + out.push_str(&percent_encoding::utf8_percent_encode(&rest[..start], QUERY_PART).to_string()); + out.push_str(&rest[start..start + end + 2]); + rest = &rest[start + end + 2..]; + } + out.push_str(&percent_encoding::utf8_percent_encode(rest, QUERY_PART).to_string()); + out +} + +/// Rewrites the query of `url` from the enabled rows, like the URL bar does. +pub(crate) fn with_query(url: &str, rows: &[KeyValue]) -> String { + let (no_hash, hash) = match url.find('#') { + Some(i) => url.split_at(i), + None => (url, ""), + }; + let base = no_hash.split('?').next().unwrap_or(no_hash); + let enabled: Vec<&KeyValue> = rows.iter().filter(|r| r.enabled && (!r.name.is_empty() || !r.value.is_empty())).collect(); + if enabled.is_empty() { + return format!("{base}{hash}"); + } + let qs = enabled + .iter() + .map(|r| { + if r.value.is_empty() && !r.name.contains('=') { + encode_part(&r.name) + } else { + format!("{}={}", encode_part(&r.name), encode_part(&r.value)) + } + }) + .collect::>() + .join("&"); + format!("{base}?{qs}{hash}") +} + +/// Sets url and params.query consistently: enabled rows end up in the URL, +/// disabled ones only in the table. +pub(crate) fn set_url(req: &mut Request, url: &str, rows: Vec) { + req.url = with_query(url, &rows); + req.params.query = rows; + for name in crate::prepare::path_param_names(&req.url) { + req.params.path.entry(name).or_default(); + } +} + +/// Last path segments of a URL for request names, e.g. `/users/:id`. +pub(crate) fn url_path(url: &str) -> String { + let no_q = url.split(['?', '#']).next().unwrap_or(url); + let after_scheme = match no_q.find("://") { + Some(i) => &no_q[i + 3..], + None => no_q, + }; + let path = if let Some(rest) = after_scheme.strip_prefix("{{") { + rest.find("}}").map(|i| &rest[i + 2..]).unwrap_or("") + } else { + after_scheme.find('/').map(|i| &after_scheme[i..]).unwrap_or("") + }; + if path.is_empty() { + "/".into() + } else { + path.to_string() + } +} + +/// Reads a JSON number, bool or string as text. +pub(crate) fn text(v: Option<&serde_json::Value>) -> String { + v.map(scalar_to_string).unwrap_or_default() +} + +#[cfg(test)] +pub(crate) fn tmp_dir() -> PathBuf { + std::env::temp_dir().join(format!("knock-import-{}", uuid::Uuid::new_v4())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detects_formats() { + assert_eq!(detect("curl https://x"), Some(Kind::Curl)); + assert_eq!(detect(" CURL -X POST https://x"), Some(Kind::Curl)); + assert_eq!( + detect(r#"{"info":{"name":"a","schema":"https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},"item":[]}"#), + Some(Kind::PostmanCollection) + ); + assert_eq!( + detect(r#"{"name":"dev","values":[],"_postman_variable_scope":"environment"}"#), + Some(Kind::PostmanEnvironment) + ); + assert_eq!(detect(r#"{"_type":"export","__export_format":4,"resources":[]}"#), Some(Kind::Insomnia)); + assert_eq!(detect("openapi: 3.0.0\ninfo: {title: x}\npaths: {}\n"), Some(Kind::Openapi)); + assert_eq!(detect(r#"{"swagger":"2.0","paths":{}}"#), Some(Kind::Openapi)); + assert_eq!(detect("hello"), None); + } + + #[test] + fn query_helpers() { + let mut rows = parse_query("http://x/a?q=hello%20world&tag={{t}}&flag"); + assert_eq!(rows[0].value, "hello world"); + assert_eq!(rows[1].value, "{{t}}"); + rows.push(KeyValue { enabled: false, ..KeyValue::new("off", "1") }); + assert_eq!(with_query("http://x/a?old=1", &rows), "http://x/a?q=hello%20world&tag={{t}}&flag"); + assert_eq!(url_path("{{baseUrl}}/users/:id?x=1"), "/users/:id"); + assert_eq!(url_path("https://api.example.com"), "/"); + } + + #[test] + fn secrets_are_externalized_and_shared() { + let mut store = IndexMap::new(); + let mut a = auth("basic", [("username", "bob".into()), ("password", "hunter2".into())]); + externalize_secrets(&mut a, "My API", &mut store); + let mut b = auth("bearer", [("token", "{{token}}".into())]); + externalize_secrets(&mut b, "x", &mut store); + let mut c = auth("digest", [("username", "bob".into()), ("password", "hunter2".into())]); + externalize_secrets(&mut c, "other", &mut store); + assert_eq!(store.len(), 1); + assert_eq!(store["my_api_password"], "hunter2"); + let Auth::Config(cfg) = c else { panic!() }; + assert_eq!(cfg.str("password"), Some("{{secret.my_api_password}}")); + let Auth::Config(cfg) = b else { panic!() }; + assert_eq!(cfg.str("token"), Some("{{token}}")); + } +} diff --git a/crates/knock-core/src/import/openapi.rs b/crates/knock-core/src/import/openapi.rs new file mode 100644 index 0000000..a7355de --- /dev/null +++ b/crates/knock-core/src/import/openapi.rs @@ -0,0 +1,975 @@ +//! OpenAPI 3.x and Swagger 2.0 (JSON or YAML) to a collection. + +use super::{set_url, ImportReport, Writer}; +use crate::collection::slugify; +use crate::model::*; +use anyhow::{anyhow, bail, Context, Result}; +use indexmap::IndexMap; +use serde_json::{json, Map, Value}; +use std::path::Path; + +const MAX_DEPTH: usize = 8; +/// Inlining counts every JSON nesting level, so it gets more room. +const INLINE_DEPTH: usize = 40; +const METHODS: &[&str] = &["get", "put", "post", "delete", "options", "head", "patch", "trace"]; + +pub fn import_openapi(text: &str, dest: &Path) -> Result { + let yaml: serde_yaml_ng::Value = serde_yaml_ng::from_str(text).context("the file is neither valid JSON nor YAML")?; + let doc = yaml_to_json(yaml); + let spec = Spec::new(&doc)?; + + let title = doc.pointer("/info/title").and_then(Value::as_str).unwrap_or("Imported API"); + let mut w = Writer::start(dest, title)?; + let mut warnings = Vec::new(); + + // Environments from servers. + let servers = spec.servers(); + let base = servers.first().map(|(_, u)| u.clone()).unwrap_or_else(|| "http://localhost".into()); + w.reset_local_env([("baseUrl".to_string(), base)].into_iter().collect())?; + for (i, (label, url)) in servers.iter().enumerate().skip(1) { + let name = if label.is_empty() { format!("server {}", i + 1) } else { label.clone() }; + let env = Environment { + vars: [("baseUrl".to_string(), EnvVar { value: url.clone(), secret: false, description: None })] + .into_iter() + .collect(), + ..Default::default() + }; + if slugify(&name) == "local" { + continue; + } + w.environment(&name, env, IndexMap::new())?; + } + + // Collection auth and docs. + let schemes = spec.security_schemes(); + let global_scheme = doc + .get("security") + .and_then(first_requirement) + .or_else(|| schemes.keys().next().cloned()); + let coll_auth = global_scheme + .as_deref() + .and_then(|n| schemes.get(n).map(|s| spec.map_scheme(n, s, &mut warnings))) + .unwrap_or(Auth::None); + let docs = doc.pointer("/info/description").and_then(Value::as_str).unwrap_or("").to_string(); + w.manifest(|m| { + if !docs.trim().is_empty() { + m.extra.insert("docs".into(), docs.into()); + } + })?; + w.collection_auth(coll_auth)?; + + // Operations grouped by first tag, in the order of the top-level `tags` list. + let mut groups: IndexMap> = IndexMap::new(); + for t in doc.get("tags").and_then(Value::as_array).into_iter().flatten() { + if let Some(n) = t.get("name").and_then(Value::as_str) { + groups.insert(n.to_string(), Vec::new()); + } + } + let mut root_ops = Vec::new(); + let paths = doc.get("paths").and_then(Value::as_object).cloned().unwrap_or_default(); + for (path, item) in &paths { + let item = spec.resolve(item); + let shared = item.get("parameters").and_then(Value::as_array).cloned().unwrap_or_default(); + for method in METHODS { + let Some(op) = item.get(*method) else { continue }; + let mut req = spec.operation(path, method, op, &shared, &mut warnings); + match op.get("security").and_then(Value::as_array) { + Some(list) if list.is_empty() => req.auth = Auth::None, + Some(list) => { + let wanted = list.first().and_then(|r| r.as_object()).and_then(|o| o.keys().next().cloned()); + if wanted.is_some() && wanted != global_scheme { + if let Some(s) = wanted.as_deref().and_then(|n| schemes.get(n).map(|s| (n, s))) { + req.auth = spec.map_scheme(s.0, s.1, &mut warnings); + } + } + } + None => {} + } + match op.get("tags").and_then(Value::as_array).and_then(|t| t.first()).and_then(Value::as_str) { + Some(tag) => groups.entry(tag.to_string()).or_default().push(req), + None => root_ops.push(req), + } + } + } + for (tag, reqs) in groups { + if reqs.is_empty() { + continue; + } + let id = w.folder("", &tag)?; + for r in reqs { + w.request(&id, r)?; + } + } + for r in root_ops { + w.request("", r)?; + } + warnings.sort(); + warnings.dedup(); + for msg in warnings { + w.warn(msg); + } + w.finish() +} + +fn first_requirement(v: &Value) -> Option { + v.as_array()?.iter().find_map(|r| r.as_object()?.keys().next().cloned()) +} + +/// YAML allows non-string keys (`200:`); JSON does not. +fn yaml_to_json(v: serde_yaml_ng::Value) -> Value { + use serde_yaml_ng::Value as Y; + match v { + Y::Null => Value::Null, + Y::Bool(b) => Value::Bool(b), + Y::Number(n) => { + if let Some(i) = n.as_i64() { + Value::from(i) + } else if let Some(u) = n.as_u64() { + Value::from(u) + } else { + n.as_f64().and_then(serde_json::Number::from_f64).map(Value::Number).unwrap_or(Value::Null) + } + } + Y::String(s) => Value::String(s), + Y::Sequence(s) => Value::Array(s.into_iter().map(yaml_to_json).collect()), + Y::Mapping(m) => Value::Object( + m.into_iter() + .map(|(k, v)| { + let key = match k { + Y::String(s) => s, + Y::Number(n) => n.to_string(), + Y::Bool(b) => b.to_string(), + other => serde_yaml_ng::to_string(&other).unwrap_or_default().trim().to_string(), + }; + (key, yaml_to_json(v)) + }) + .collect(), + ), + Y::Tagged(t) => yaml_to_json(t.value), + } +} + +struct Spec<'a> { + doc: &'a Value, + v3: bool, +} + +impl<'a> Spec<'a> { + fn new(doc: &'a Value) -> Result { + if let Some(v) = doc.get("openapi") { + let v = super::text(Some(v)); + if !v.starts_with('3') { + bail!("OpenAPI version {v} is not supported (3.x and Swagger 2.0 are)"); + } + Ok(Self { doc, v3: true }) + } else if let Some(v) = doc.get("swagger") { + let v = super::text(Some(v)); + if !v.starts_with('2') { + bail!("Swagger version {v} is not supported"); + } + Ok(Self { doc, v3: false }) + } else { + Err(anyhow!("not an OpenAPI document: neither `openapi` nor `swagger` is set")) + } + } + + /// Follows local `$ref`s. Unknown or external refs resolve to the input. + fn resolve(&self, mut v: &'a Value) -> &'a Value { + for _ in 0..32 { + let Some(r) = v.get("$ref").and_then(Value::as_str) else { return v }; + match r.strip_prefix('#').and_then(|p| self.doc.pointer(p)) { + Some(t) => v = t, + None => return v, + } + } + v + } + + fn servers(&self) -> Vec<(String, String)> { + if self.v3 { + let mut out = Vec::new(); + for s in self.doc.get("servers").and_then(Value::as_array).into_iter().flatten() { + let mut url = super::text(s.get("url")); + if let Some(vars) = s.get("variables").and_then(Value::as_object) { + for (k, v) in vars { + url = url.replace(&format!("{{{k}}}"), &super::text(v.get("default"))); + } + } + if url.starts_with('/') || url.is_empty() { + url = format!("http://localhost{url}"); + } + out.push((super::text(s.get("description")), url.trim_end_matches('/').to_string())); + } + out + } else { + let host = self.doc.get("host").and_then(Value::as_str).unwrap_or("localhost"); + let base = self.doc.get("basePath").and_then(Value::as_str).unwrap_or(""); + let schemes: Vec<&str> = self + .doc + .get("schemes") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + let scheme = if schemes.contains(&"https") { "https" } else { schemes.first().copied().unwrap_or("http") }; + vec![(String::new(), format!("{scheme}://{host}{base}").trim_end_matches('/').to_string())] + } + } + + fn security_schemes(&self) -> Map { + let p = if self.v3 { "/components/securitySchemes" } else { "/securityDefinitions" }; + self.doc + .pointer(p) + .and_then(Value::as_object) + .map(|m| m.iter().map(|(k, v)| (k.clone(), self.resolve(v).clone())).collect()) + .unwrap_or_default() + } + + fn map_scheme(&self, name: &str, s: &Value, warnings: &mut Vec) -> Auth { + let t = s.get("type").and_then(Value::as_str).unwrap_or(""); + let secret = |field: &str| format!("{{{{secret.{}}}}}", slugify(&format!("{name} {field}")).replace('-', "_")); + match t { + "http" => match s.get("scheme").and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() { + Some("basic") => super::auth("basic", [("username", "{{username}}".into()), ("password", secret("password"))]), + Some("bearer") => super::auth("bearer", [("token", secret("token"))]), + Some("digest") => super::auth("digest", [("username", "{{username}}".into()), ("password", secret("password"))]), + other => { + warnings.push(format!("security scheme `{name}` (http {}) is not supported", other.unwrap_or("?"))); + Auth::None + } + }, + "basic" => super::auth("basic", [("username", "{{username}}".into()), ("password", secret("password"))]), + "apiKey" => { + let place = match s.get("in").and_then(Value::as_str) { + Some("query") => "query", + Some("cookie") => "cookie", + _ => "header", + }; + super::auth("apikey", [("key", super::text(s.get("name"))), ("value", secret("key")), ("in", place.into())]) + } + "oauth2" => { + let (grant, flow) = if self.v3 { + let flows = s.get("flows").and_then(Value::as_object).cloned().unwrap_or_default(); + let pick = ["authorizationCode", "clientCredentials", "password", "implicit"] + .into_iter() + .find_map(|f| flows.get(f).map(|v| (f, v.clone()))); + match pick { + Some((f, v)) => (f.to_string(), v), + None => return Auth::None, + } + } else { + (super::text(s.get("flow")), s.clone()) + }; + let grant = match grant.as_str() { + "clientCredentials" | "application" => "client_credentials", + "password" => "password", + "implicit" => { + warnings.push(format!("security scheme `{name}` uses the implicit flow; imported as authorization code")); + "authorization_code" + } + _ => "authorization_code", + }; + let scopes = flow + .get("scopes") + .and_then(Value::as_object) + .map(|m| m.keys().cloned().collect::>().join(" ")) + .unwrap_or_default(); + super::auth( + "oauth2", + [ + ("grant", grant.to_string()), + ("authorize_url", super::text(flow.get("authorizationUrl"))), + ("token_url", super::text(flow.get("tokenUrl"))), + ("client_id", "{{clientId}}".to_string()), + ("client_secret", secret("client_secret")), + ("client_auth", "basic".to_string()), + ("scopes", scopes), + ], + ) + } + "openIdConnect" => { + let url = super::text(s.get("openIdConnectUrl")); + let issuer = url.trim_end_matches("/.well-known/openid-configuration").to_string(); + super::auth( + "oauth2", + [ + ("grant", "authorization_code".to_string()), + ("issuer", issuer), + ("client_id", "{{clientId}}".to_string()), + ("client_secret", secret("client_secret")), + ("client_auth", "basic".to_string()), + ("scopes", "openid".to_string()), + ], + ) + } + other => { + warnings.push(format!("security scheme `{name}` of type `{other}` is not supported")); + Auth::None + } + } + } + + fn operation(&self, path: &str, method: &str, op: &Value, shared: &[Value], warnings: &mut Vec) -> Request { + let summary = op.get("summary").and_then(Value::as_str).filter(|s| !s.trim().is_empty()); + let op_id = op.get("operationId").and_then(Value::as_str).filter(|s| !s.trim().is_empty()); + let name = summary + .or(op_id) + .map(str::to_string) + .unwrap_or_else(|| format!("{} {path}", method.to_uppercase())); + + let mut req = Request { + name: name.trim().to_string(), + method: Some(method.to_uppercase()), + ..Default::default() + }; + + // Path-level parameters, overridden by operation ones with the same name and location. + let mut params: Vec = Vec::new(); + for p in shared.iter().chain(op.get("parameters").and_then(Value::as_array).into_iter().flatten()) { + let p = self.resolve(p).clone(); + let key = (super::text(p.get("name")), super::text(p.get("in"))); + params.retain(|q| (super::text(q.get("name")), super::text(q.get("in"))) != key); + params.push(p); + } + + let url = format!("{{{{baseUrl}}}}{}", convert_path(path)); + let mut query = Vec::new(); + let mut path_vals = IndexMap::new(); + let mut cookies = Vec::new(); + let mut form_params = Vec::new(); + let mut body_param = None; + for p in ¶ms { + let pname = super::text(p.get("name")); + let required = p.get("required").and_then(Value::as_bool).unwrap_or(false); + let value = self.param_example(p); + let description = p.get("description").and_then(Value::as_str).map(str::to_string); + let row = KeyValue { + name: pname.clone(), + value: value.clone(), + enabled: required, + description, + ..Default::default() + }; + match p.get("in").and_then(Value::as_str).unwrap_or("") { + "query" => query.push(row), + "path" => { + path_vals.insert(pname, value); + } + "header" => { + if !["accept", "content-type", "authorization"].contains(&pname.to_ascii_lowercase().as_str()) { + req.headers.push(row); + } + } + "cookie" => cookies.push(format!("{pname}={value}")), + "body" => body_param = Some(p.clone()), + "formData" => form_params.push(p.clone()), + _ => {} + } + } + if !cookies.is_empty() { + req.headers.push(KeyValue::new("Cookie", cookies.join("; "))); + } + set_url(&mut req, &url, query); + for (k, v) in path_vals { + req.params.path.insert(k, v); + } + + if self.v3 { + if let Some(rb) = op.get("requestBody") { + self.request_body_v3(&mut req, self.resolve(rb), warnings); + } + } else { + let consumes = op + .get("consumes") + .or_else(|| self.doc.get("consumes")) + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect::>()) + .unwrap_or_default(); + if let Some(bp) = body_param { + if let Some(schema) = bp.get("schema") { + let ct = consumes.first().cloned().unwrap_or_else(|| "application/json".into()); + self.schema_body(&mut req, &ct, schema, None); + } + } else if !form_params.is_empty() { + let multipart = consumes.iter().any(|c| c.contains("multipart")) + || form_params.iter().any(|p| p.get("type").and_then(Value::as_str) == Some("file")); + if multipart { + req.body = Body { + kind: BodyType::Multipart, + multipart: form_params + .iter() + .map(|p| { + let is_file = p.get("type").and_then(Value::as_str) == Some("file"); + MultipartPart { + name: super::text(p.get("name")), + value: if is_file { String::new() } else { self.param_example(p) }, + file: is_file.then(String::new), + content_type: None, + enabled: true, + } + }) + .collect(), + ..Default::default() + }; + } else { + req.body = Body { + kind: BodyType::FormUrlencoded, + form: form_params + .iter() + .map(|p| KeyValue { + name: super::text(p.get("name")), + value: self.param_example(p), + enabled: p.get("required").and_then(Value::as_bool).unwrap_or(false), + ..Default::default() + }) + .collect(), + ..Default::default() + }; + } + } + } + + let mut docs = Vec::new(); + if op.get("deprecated").and_then(Value::as_bool) == Some(true) { + docs.push("**Deprecated.**".to_string()); + } + if let Some(d) = op.get("description").and_then(Value::as_str).filter(|d| !d.trim().is_empty()) { + docs.push(d.trim().to_string()); + } + if summary.is_some() { + if let Some(id) = op_id { + docs.push(format!("Operation id: `{id}`")); + } + } + if !docs.is_empty() { + req.docs = Some(docs.join("\n\n")); + } + req + } + + fn request_body_v3(&self, req: &mut Request, rb: &Value, warnings: &mut Vec) { + let Some(content) = rb.get("content").and_then(Value::as_object) else { return }; + let pick = content + .keys() + .find(|k| is_json(k)) + .or_else(|| content.keys().find(|k| k.starts_with("application/x-www-form-urlencoded"))) + .or_else(|| content.keys().find(|k| k.starts_with("multipart/"))) + .or_else(|| content.keys().next()) + .cloned(); + let Some(ct) = pick else { return }; + let media = &content[&ct]; + let example = media + .get("example") + .cloned() + .or_else(|| { + media + .get("examples") + .and_then(Value::as_object) + .and_then(|m| m.values().next()) + .map(|e| self.resolve(e)) + .and_then(|e| e.get("value").cloned()) + }); + match media.get("schema") { + Some(schema) => self.schema_body(req, &ct, schema, example), + None => { + if let Some(ex) = example { + self.schema_body(req, &ct, &json!({}), Some(ex)); + } else if !is_json(&ct) { + warnings.push(format!("{}: request body `{ct}` has no schema", req.name)); + } + } + } + } + + /// Fills the body from a schema (or an explicit example) for a content type. + fn schema_body(&self, req: &mut Request, ct: &str, schema: &Value, example: Option) { + let ex = example.unwrap_or_else(|| self.example(schema, 0, &mut Vec::new())); + if is_json(ct) { + req.body = Body { + kind: BodyType::Json, + content: serde_json::to_string_pretty(&ex).unwrap_or_default(), + ..Default::default() + }; + req.schema = Some(self.inline(schema, 0, &mut Vec::new())); + if ct != "application/json" { + req.headers.push(KeyValue::new("Content-Type", ct)); + } + return; + } + let props = self.properties(schema); + if ct.starts_with("application/x-www-form-urlencoded") { + req.body = Body { + kind: BodyType::FormUrlencoded, + form: props + .iter() + .map(|(k, s)| KeyValue::new(k, scalar(&ex.get(k).cloned().unwrap_or_else(|| self.example(s, 1, &mut Vec::new()))))) + .collect(), + ..Default::default() + }; + } else if ct.starts_with("multipart/") { + req.body = Body { + kind: BodyType::Multipart, + multipart: props + .iter() + .map(|(k, s)| { + let s = self.resolve(s); + let binary = matches!(s.get("format").and_then(Value::as_str), Some("binary" | "byte")) + || s.get("contentMediaType").is_some(); + MultipartPart { + name: k.clone(), + value: if binary { String::new() } else { scalar(&ex.get(k).cloned().unwrap_or_else(|| self.example(s, 1, &mut Vec::new()))) }, + file: binary.then(String::new), + content_type: None, + enabled: true, + } + }) + .collect(), + ..Default::default() + }; + } else if ct == "application/octet-stream" || ct.starts_with("image/") || ct.starts_with("video/") || ct.starts_with("audio/") { + req.body = Body { + kind: BodyType::Binary, + content_type: Some(ct.to_string()), + ..Default::default() + }; + } else { + req.body = Body { + kind: BodyType::Raw, + content: match &ex { + Value::String(s) => s.clone(), + Value::Null => String::new(), + other => other.to_string(), + }, + content_type: Some(ct.to_string()), + ..Default::default() + }; + } + } + + /// Properties of an object schema, following `$ref` and `allOf`. + fn properties(&self, schema: &Value) -> Vec<(String, Value)> { + let s = self.resolve(schema); + let mut out: Vec<(String, Value)> = Vec::new(); + if let Some(all) = s.get("allOf").and_then(Value::as_array) { + for sub in all { + for (k, v) in self.properties(sub) { + out.retain(|(n, _)| *n != k); + out.push((k, v)); + } + } + } + if let Some(p) = s.get("properties").and_then(Value::as_object) { + for (k, v) in p { + out.retain(|(n, _)| n != k); + out.push((k.clone(), v.clone())); + } + } + out + } + + fn param_example(&self, p: &Value) -> String { + if let Some(e) = p.get("example") { + return scalar(e); + } + if let Some(e) = p.get("examples").and_then(Value::as_object).and_then(|m| m.values().next()) { + if let Some(v) = self.resolve(e).get("value") { + return scalar(v); + } + } + let schema = p.get("schema").unwrap_or(p); + let s = self.resolve(schema); + for key in ["example", "default"] { + if let Some(v) = s.get(key) { + return scalar(v); + } + } + if let Some(v) = s.get("enum").and_then(Value::as_array).and_then(|a| a.first()) { + return scalar(v); + } + String::new() + } + + /// Example value for a schema: examples > example > default > enum[0] > type default. + fn example(&self, schema: &Value, depth: usize, stack: &mut Vec) -> Value { + if depth > MAX_DEPTH { + return Value::Null; + } + let ref_name = schema.get("$ref").and_then(Value::as_str).map(str::to_string); + if let Some(r) = &ref_name { + if stack.contains(r) { + return Value::Null; + } + stack.push(r.clone()); + } + let s = self.resolve(schema); + let out = self.example_inner(s, depth, stack); + if ref_name.is_some() { + stack.pop(); + } + out + } + + fn example_inner(&self, s: &Value, depth: usize, stack: &mut Vec) -> Value { + if let Some(v) = s.get("examples").and_then(Value::as_array).and_then(|a| a.first()) { + return v.clone(); + } + for key in ["example", "default", "const"] { + if let Some(v) = s.get(key) { + return v.clone(); + } + } + if let Some(v) = s.get("enum").and_then(Value::as_array).and_then(|a| a.first()) { + return v.clone(); + } + if let Some(all) = s.get("allOf").and_then(Value::as_array) { + let mut merged = Map::new(); + let mut other = None; + for sub in all { + match self.example(sub, depth + 1, stack) { + Value::Object(m) => merged.extend(m), + Value::Null => {} + v => other = Some(v), + } + } + if let Some(p) = s.get("properties").and_then(Value::as_object) { + for (k, v) in p { + merged.insert(k.clone(), self.example(v, depth + 1, stack)); + } + } + return if merged.is_empty() { other.unwrap_or(Value::Null) } else { Value::Object(merged) }; + } + for key in ["oneOf", "anyOf"] { + if let Some(first) = s.get(key).and_then(Value::as_array).and_then(|a| a.first()) { + return self.example(first, depth + 1, stack); + } + } + let ty = match s.get("type") { + Some(Value::String(t)) => t.clone(), + Some(Value::Array(ts)) => ts.iter().filter_map(Value::as_str).find(|t| *t != "null").unwrap_or("null").to_string(), + _ if s.get("properties").is_some() => "object".into(), + _ if s.get("items").is_some() => "array".into(), + _ => String::new(), + }; + match ty.as_str() { + "object" => { + let mut m = Map::new(); + if let Some(p) = s.get("properties").and_then(Value::as_object) { + for (k, v) in p { + let resolved = self.resolve(v); + if resolved.get("readOnly").and_then(Value::as_bool) == Some(true) { + continue; + } + m.insert(k.clone(), self.example(v, depth + 1, stack)); + } + } + Value::Object(m) + } + "array" => match s.get("items") { + Some(items) => match self.example(items, depth + 1, stack) { + Value::Null => json!([]), + v => json!([v]), + }, + None => json!([]), + }, + "string" => Value::String( + match s.get("format").and_then(Value::as_str).unwrap_or("") { + "date-time" => "2024-01-01T00:00:00Z", + "date" => "2024-01-01", + "time" => "00:00:00", + "email" => "user@example.com", + "uuid" => "00000000-0000-0000-0000-000000000000", + "uri" | "url" => "https://example.com", + "hostname" => "example.com", + "ipv4" => "192.0.2.1", + "ipv6" => "2001:db8::1", + "binary" | "byte" | "password" => "", + _ => "string", + } + .to_string(), + ), + "integer" => json!(0), + "number" => json!(0.0), + "boolean" => json!(false), + _ => Value::Null, + } + } + + /// Copy of a schema with local `$ref`s inlined, depth-limited and cycle-safe. + fn inline(&self, schema: &Value, depth: usize, stack: &mut Vec) -> Value { + if depth > INLINE_DEPTH { + return json!({}); + } + match schema { + Value::Object(m) => { + if let Some(r) = m.get("$ref").and_then(Value::as_str) { + if stack.iter().any(|s| s == r) { + return json!({}); + } + let target = self.resolve(schema); + if std::ptr::eq(target, schema) { + return schema.clone(); + } + stack.push(r.to_string()); + let out = self.inline(target, depth + 1, stack); + stack.pop(); + return out; + } + Value::Object(m.iter().map(|(k, v)| (k.clone(), self.inline(v, depth + 1, stack))).collect()) + } + Value::Array(a) => Value::Array(a.iter().map(|v| self.inline(v, depth, stack)).collect()), + other => other.clone(), + } + } +} + +fn is_json(ct: &str) -> bool { + let ct = ct.to_ascii_lowercase(); + ct.starts_with("application/json") || ct.contains("+json") +} + +fn scalar(v: &Value) -> String { + match v { + Value::Array(a) => a.iter().map(scalar).collect::>().join(","), + Value::Object(_) => v.to_string(), + other => scalar_to_string(other), + } +} + +/// `/users/{id}` → `/users/:id`. +fn convert_path(path: &str) -> String { + path.split('/') + .map(|seg| match seg.strip_prefix('{').and_then(|s| s.strip_suffix('}')) { + Some(name) => format!(":{name}"), + None => seg.to_string(), + }) + .collect::>() + .join("/") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::collection::Collection; + + const PETSTORE: &str = r##" +openapi: 3.0.3 +info: + title: Petstore + description: Sample pet store. + version: 1.0.0 +servers: + - url: https://{region}.petstore.example.com/v1 + description: Production + variables: + region: { default: eu } + - url: http://localhost:3000/v1 + description: Dev box +tags: + - name: pets + - name: store +security: + - bearerAuth: [] +paths: + /pets: + get: + tags: [pets] + summary: List pets + operationId: listPets + parameters: + - { name: limit, in: query, required: true, schema: { type: integer, example: 20 } } + - { name: status, in: query, schema: { type: string, enum: [available, sold] } } + - { name: X-Request-Id, in: header, schema: { type: string, format: uuid } } + responses: + 200: { description: ok } + post: + tags: [pets] + operationId: createPet + requestBody: + required: true + content: + application/json: + schema: { $ref: '#/components/schemas/NewPet' } + responses: + 201: { description: created } + /pets/{petId}: + parameters: + - { name: petId, in: path, required: true, schema: { type: string }, example: "p-1" } + get: + tags: [pets] + summary: Get pet + responses: + 200: { description: ok } + delete: + tags: [pets] + security: [] + responses: + 204: { description: gone } + /store/upload: + post: + tags: [store] + summary: Upload photo + security: + - apiKey: [] + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + caption: { type: string, default: hello } + photo: { type: string, format: binary } + responses: + 200: { description: ok } + /health: + get: + responses: + 200: { description: ok } +components: + securitySchemes: + bearerAuth: { type: http, scheme: bearer } + apiKey: { type: apiKey, in: header, name: X-API-Key } + schemas: + Pet: + allOf: + - $ref: '#/components/schemas/NewPet' + - type: object + properties: + id: { type: integer, readOnly: true } + NewPet: + type: object + required: [name] + properties: + name: { type: string, example: Rex } + tag: { type: string } + born: { type: string, format: date } + owner: { $ref: '#/components/schemas/Owner' } + friends: + type: array + items: { $ref: '#/components/schemas/Pet' } + Owner: + type: object + properties: + email: { type: string, format: email } + pet: { $ref: '#/components/schemas/Pet' } +"##; + + #[test] + fn imports_openapi3() { + let dir = super::super::tmp_dir(); + let rep = import_openapi(PETSTORE, &dir).unwrap(); + assert_eq!(rep.requests, 6, "{rep:?}"); + assert_eq!(rep.folders, 2); + let c = Collection::open(&dir).unwrap(); + assert_eq!(c.manifest.name, "Petstore"); + assert_eq!(c.environment("local").unwrap().vars["baseUrl"].value, "https://eu.petstore.example.com/v1"); + assert_eq!(c.environment("dev-box").unwrap().vars["baseUrl"].value, "http://localhost:3000/v1"); + let Auth::Config(a) = &c.manifest.auth else { panic!() }; + assert_eq!((a.kind.as_str(), a.str("token")), ("bearer", Some("{{secret.bearerauth_token}}"))); + + assert_eq!( + c.requests_in(""), + vec![ + "pets/list-pets.yaml", + "pets/createpet.yaml", + "pets/get-pet.yaml", + "pets/delete-pets-petid.yaml", + "store/upload-photo.yaml", + "get-health.yaml" + ] + ); + let list = c.request("pets/list-pets.yaml").unwrap(); + assert_eq!(list.url, "{{baseUrl}}/pets?limit=20"); + assert_eq!(list.params.query[1].value, "available"); + assert!(!list.params.query[1].enabled); + assert_eq!(list.headers[0].name, "X-Request-Id"); + + let create = c.request("pets/createpet.yaml").unwrap(); + assert_eq!(create.body.kind, BodyType::Json); + let body: Value = serde_json::from_str(&create.body.content).unwrap(); + assert_eq!(body["name"], "Rex"); + assert_eq!(body["born"], "2024-01-01"); + assert_eq!(body["owner"]["email"], "user@example.com"); + assert!(body["friends"][0].get("id").is_none(), "readOnly skipped"); + let schema = create.schema.unwrap(); + assert_eq!(schema["properties"]["owner"]["properties"]["email"]["format"], "email"); + assert!(!schema.to_string().contains("$ref")); + + let get = c.request("pets/get-pet.yaml").unwrap(); + assert_eq!(get.url, "{{baseUrl}}/pets/:petId"); + assert_eq!(get.params.path["petId"], "p-1"); + + let del = c.request("pets/delete-pets-petid.yaml").unwrap(); + assert_eq!(del.auth, Auth::None); + + let up = c.request("store/upload-photo.yaml").unwrap(); + assert_eq!(up.body.kind, BodyType::Multipart); + assert_eq!(up.body.multipart[0].value, "hello"); + assert_eq!(up.body.multipart[1].file.as_deref(), Some("")); + let Auth::Config(k) = &up.auth else { panic!() }; + assert_eq!((k.kind.as_str(), k.str("key")), ("apikey", Some("X-API-Key"))); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn imports_swagger2_json() { + let doc = r##"{ + "swagger": "2.0", + "info": { "title": "Legacy", "version": "1" }, + "host": "legacy.example.com", + "basePath": "/api", + "schemes": ["http", "https"], + "securityDefinitions": { + "oauth": { "type": "oauth2", "flow": "accessCode", "authorizationUrl": "https://auth.example.com/authorize", + "tokenUrl": "https://auth.example.com/token", "scopes": { "read": "r", "write": "w" } } + }, + "paths": { + "/items/{id}": { + "put": { + "operationId": "updateItem", + "parameters": [ + { "name": "id", "in": "path", "required": true, "type": "integer" }, + { "name": "body", "in": "body", "schema": { "$ref": "#/definitions/Item" } } + ], + "responses": { "200": { "description": "ok" } } + } + }, + "/login": { + "post": { + "consumes": ["application/x-www-form-urlencoded"], + "parameters": [ + { "name": "user", "in": "formData", "type": "string", "required": true }, + { "name": "pass", "in": "formData", "type": "string", "required": true } + ], + "responses": { "200": { "description": "ok" } } + } + } + }, + "definitions": { + "Item": { "type": "object", "properties": { "title": { "type": "string" }, "qty": { "type": "integer", "default": 1 } } } + } + }"##; + let dir = super::super::tmp_dir(); + let rep = import_openapi(doc, &dir).unwrap(); + assert_eq!(rep.requests, 2); + let c = Collection::open(&dir).unwrap(); + assert_eq!(c.environment("local").unwrap().vars["baseUrl"].value, "https://legacy.example.com/api"); + let Auth::Config(a) = &c.manifest.auth else { panic!() }; + assert_eq!(a.str("grant"), Some("authorization_code")); + assert_eq!(a.str("scopes"), Some("read write")); + assert_eq!(a.str("token_url"), Some("https://auth.example.com/token")); + let put = c.request("updateitem.yaml").unwrap(); + assert_eq!(put.url, "{{baseUrl}}/items/:id"); + let body: Value = serde_json::from_str(&put.body.content).unwrap(); + assert_eq!(body, json!({ "title": "string", "qty": 1 })); + let login = c.request("post-login.yaml").unwrap(); + assert_eq!(login.body.kind, BodyType::FormUrlencoded); + assert_eq!(login.body.form.len(), 2); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn rejects_other_documents() { + let dir = super::super::tmp_dir(); + assert!(import_openapi("foo: bar", &dir).unwrap_err().to_string().contains("not an OpenAPI document")); + assert!(import_openapi("{", &dir).is_err()); + } +} diff --git a/crates/knock-core/src/import/postman.rs b/crates/knock-core/src/import/postman.rs new file mode 100644 index 0000000..f133a14 --- /dev/null +++ b/crates/knock-core/src/import/postman.rs @@ -0,0 +1,768 @@ +//! Postman Collection v2.0 / v2.1 and Postman environments. + +use super::{append_docs, looks_like_json, parse_query, pretty_json, scripts_doc, set_url, text, ImportReport, Writer}; +use crate::collection::{slugify, Collection, ENV_DIR}; +use crate::model::*; +use anyhow::{anyhow, bail, Context, Result}; +use indexmap::IndexMap; +use serde_json::{Map, Value}; +use std::path::Path; + +pub fn import_postman(json: &str, dest: &Path) -> Result { + let root: Value = serde_json::from_str(json).context("the file is not valid JSON")?; + let info = root + .get("info") + .and_then(Value::as_object) + .ok_or_else(|| anyhow!("not a Postman collection: the `info` object is missing"))?; + let items = root + .get("item") + .and_then(Value::as_array) + .ok_or_else(|| anyhow!("not a Postman collection: the `item` list is missing"))?; + let name = text(info.get("name")); + let mut w = Writer::start(dest, &name)?; + + let vars = variables(root.get("variable")); + let docs = description(info.get("description")); + let scripts = events(root.get("event")); + w.report.scripts_skipped += scripts.len(); + let mut warnings = Vec::new(); + let auth = map_auth(root.get("auth"), &mut warnings); + let mut extra_docs = docs.unwrap_or_default(); + if !scripts.is_empty() { + append(&mut extra_docs, &scripts_doc("Postman", &scripts)); + } + w.manifest(|m| { + m.vars = vars; + if !extra_docs.is_empty() { + m.extra.insert("docs".into(), extra_docs.into()); + } + })?; + w.collection_auth(auth)?; + // Postman collections usually carry their own variables; drop the default baseUrl. + w.reset_local_env(IndexMap::new())?; + for wmsg in warnings { + w.warn(wmsg); + } + + let mut examples = 0; + walk(&mut w, "", items, &mut examples)?; + if examples > 0 { + w.warn(format!("{examples} saved example response(s) were not imported")); + } + w.finish() +} + +fn walk(w: &mut Writer, folder: &str, items: &[Value], examples: &mut usize) -> Result<()> { + for item in items { + let name = text(item.get("name")); + if let Some(children) = item.get("item").and_then(Value::as_array) { + let id = w.folder(folder, &name)?; + let mut warnings = Vec::new(); + let auth = map_auth(item.get("auth"), &mut warnings); + let vars = variables(item.get("variable")); + let mut docs = description(item.get("description")).unwrap_or_default(); + let scripts = events(item.get("event")); + w.report.scripts_skipped += scripts.len(); + if !scripts.is_empty() { + append(&mut docs, &scripts_doc("Postman", &scripts)); + } + w.folder_meta(&id, |m| { + m.auth = auth; + m.vars = vars; + if !docs.is_empty() { + m.extra.insert("docs".into(), docs.into()); + } + })?; + for msg in warnings { + w.warn(format!("{name}: {msg}")); + } + walk(w, &id, children, examples)?; + } else if let Some(r) = item.get("request") { + let mut warnings = Vec::new(); + let mut req = map_request(&name, r, &mut warnings); + if let Some(d) = description(item.get("description")) { + append_docs(&mut req, &d); + } + let scripts = events(item.get("event")); + if !scripts.is_empty() { + w.report.scripts_skipped += scripts.len(); + append_docs(&mut req, &scripts_doc("Postman", &scripts)); + } + if let Some(ppb) = item.get("protocolProfileBehavior").and_then(Value::as_object) { + if ppb.get("followRedirects").and_then(Value::as_bool) == Some(false) { + req.settings.follow_redirects = false; + } + if ppb.get("strictSSL").and_then(Value::as_bool) == Some(false) { + req.settings.verify_tls = false; + } + if let Some(n) = ppb.get("maxRedirects").and_then(Value::as_u64) { + req.settings.max_redirects = n.min(u32::MAX as u64) as u32; + } + } + *examples += item.get("response").and_then(Value::as_array).map_or(0, Vec::len); + for msg in warnings { + w.warn(format!("{}: {msg}", req.name)); + } + w.request(folder, req)?; + } + } + Ok(()) +} + +fn append(s: &mut String, more: &str) { + if !s.is_empty() { + s.push_str("\n\n"); + } + s.push_str(more); +} + +fn description(v: Option<&Value>) -> Option { + let s = match v? { + Value::String(s) => s.clone(), + Value::Object(o) => text(o.get("content")), + _ => return None, + }; + (!s.trim().is_empty()).then_some(s) +} + +fn variables(v: Option<&Value>) -> IndexMap { + let mut out = IndexMap::new(); + for var in v.and_then(Value::as_array).into_iter().flatten() { + if var.get("disabled").and_then(Value::as_bool) == Some(true) { + continue; + } + let key = text(var.get("key").or_else(|| var.get("id"))); + if !key.is_empty() { + out.insert(key, text(var.get("value"))); + } + } + out +} + +/// Script sources as (label, language, code). +fn events(v: Option<&Value>) -> Vec<(&'static str, &'static str, String)> { + let mut out = Vec::new(); + for ev in v.and_then(Value::as_array).into_iter().flatten() { + let label = match ev.get("listen").and_then(Value::as_str) { + Some("prerequest") => "Pre-request", + Some("test") => "Tests", + _ => "Script", + }; + let Some(script) = ev.get("script") else { continue }; + let code = match script.get("exec") { + Some(Value::Array(lines)) => lines.iter().map(|l| text(Some(l))).collect::>().join("\n"), + Some(Value::String(s)) => s.clone(), + _ => String::new(), + }; + if !code.trim().is_empty() { + out.push((label, "js", code)); + } + } + out +} + +/// Postman auth params as a map, for both the v2.1 list form and the v2.0 object form. +fn auth_params(a: &Value, kind: &str) -> Map { + match a.get(kind) { + Some(Value::Array(list)) => list + .iter() + .filter_map(|p| Some((p.get("key")?.as_str()?.to_string(), p.get("value").cloned().unwrap_or(Value::Null)))) + .collect(), + Some(Value::Object(o)) => o.clone(), + _ => Map::new(), + } +} + +pub(crate) fn map_auth(v: Option<&Value>, warnings: &mut Vec) -> Auth { + let Some(a) = v.filter(|a| a.is_object()) else { return Auth::Inherit }; + let kind = a.get("type").and_then(Value::as_str).unwrap_or("inherit"); + let p = auth_params(a, kind); + let g = |k: &str| text(p.get(k)); + match kind { + "noauth" => Auth::None, + "inherit" => Auth::Inherit, + "basic" => super::auth("basic", [("username", g("username")), ("password", g("password"))]), + "digest" => super::auth("digest", [("username", g("username")), ("password", g("password"))]), + "bearer" => super::auth("bearer", [("token", g("token"))]), + "apikey" => { + let place = match g("in").as_str() { + "query" => "query", + _ => "header", + }; + super::auth("apikey", [("key", g("key")), ("value", g("value")), ("in", place.to_string())]) + } + "awsv4" => super::auth( + "awsv4", + [ + ("access_key", g("accessKey")), + ("secret_key", g("secretKey")), + ("session_token", g("sessionToken")), + ("region", g("region")), + ("service", g("service")), + ], + ), + "oauth1" => super::auth( + "oauth1", + [ + ("consumer_key", g("consumerKey")), + ("consumer_secret", g("consumerSecret")), + ("token", g("token")), + ("token_secret", g("tokenSecret")), + ("signature_method", g("signatureMethod")), + ], + ), + "oauth2" => { + let grant = match g("grant_type").as_str() { + "client_credentials" => "client_credentials", + "password_credentials" => "password", + "implicit" => { + warnings.push("OAuth 2 implicit grant is not supported; imported as authorization code".into()); + "authorization_code" + } + _ => "authorization_code", + }; + let client_auth = match g("client_authentication").as_str() { + "body" => "post", + _ => "basic", + }; + let prefix = g("headerPrefix"); + let mut auth = super::auth( + "oauth2", + [ + ("grant", grant.to_string()), + ("authorize_url", g("authUrl")), + ("token_url", g("accessTokenUrl")), + ("client_id", g("clientId")), + ("client_secret", g("clientSecret")), + ("client_auth", client_auth.to_string()), + ("scopes", g("scope")), + ("audience", g("audience")), + ("username", g("username")), + ("password", g("password")), + ("token_prefix", prefix), + ], + ); + if let Auth::Config(c) = &mut auth { + if g("grant_type") == "authorization_code_with_pkce" { + c.fields.insert("pkce".into(), Value::Bool(true)); + } + } + if !g("accessToken").is_empty() { + warnings.push("a stored OAuth 2 access token was not imported; fetch a new one in knock".into()); + } + auth + } + "jwt" => super::auth( + "jwt", + [ + ("algorithm", g("algorithm")), + ("secret", g("secret")), + ("private_key", g("privateKey")), + ("payload", g("payload")), + ], + ), + other => { + warnings.push(format!("auth type `{other}` is not supported and was left as inherit")); + Auth::Inherit + } + } +} + +fn map_request(name: &str, r: &Value, warnings: &mut Vec) -> Request { + let mut req = Request { + name: name.to_string(), + ..Default::default() + }; + // v2.0 allows the request to be a plain URL string. + if let Value::String(url) = r { + set_url(&mut req, url, parse_query(url)); + return req; + } + req.method = Some(r.get("method").and_then(Value::as_str).unwrap_or("GET").to_uppercase()); + map_url(&mut req, r.get("url")); + req.headers = headers(r.get("header")); + req.auth = map_auth(r.get("auth"), warnings); + if let Some(d) = description(r.get("description")) { + append_docs(&mut req, &d); + } + if let Some(b) = r.get("body").filter(|b| b.get("disabled").and_then(Value::as_bool) != Some(true)) { + map_body(&mut req, b, warnings); + } + req +} + +fn map_url(req: &mut Request, v: Option<&Value>) { + let Some(v) = v else { return }; + let (base, rows, path_vars) = match v { + Value::String(s) => (s.clone(), parse_query(s), Vec::new()), + Value::Object(o) => { + let raw = text(o.get("raw")); + let base = if !raw.is_empty() { + raw.clone() + } else { + let mut s = String::new(); + if let Some(p) = o.get("protocol").and_then(Value::as_str) { + s.push_str(p); + s.push_str("://"); + } + s.push_str(&join_parts(o.get("host"), ".")); + if let Some(port) = o.get("port") { + s.push(':'); + s.push_str(&text(Some(port))); + } + let path = join_parts(o.get("path"), "/"); + if !path.is_empty() { + if !path.starts_with('/') { + s.push('/'); + } + s.push_str(&path); + } + s + }; + let rows = match o.get("query").and_then(Value::as_array) { + Some(q) => q + .iter() + .map(|p| KeyValue { + name: text(p.get("key")), + value: text(p.get("value")), + enabled: p.get("disabled").and_then(Value::as_bool) != Some(true), + description: description(p.get("description")), + ..Default::default() + }) + .collect(), + None => parse_query(&raw), + }; + let vars = o + .get("variable") + .and_then(Value::as_array) + .map(|vs| vs.iter().map(|v| (text(v.get("key").or_else(|| v.get("id"))), text(v.get("value")))).collect()) + .unwrap_or_default(); + (base, rows, vars) + } + _ => return, + }; + set_url(req, &base, rows); + for (k, v) in path_vars { + if !k.is_empty() { + req.params.path.insert(k, v); + } + } +} + +fn join_parts(v: Option<&Value>, sep: &str) -> String { + match v { + Some(Value::Array(a)) => a + .iter() + .map(|p| match p { + Value::Object(o) => text(o.get("value")), + other => text(Some(other)), + }) + .collect::>() + .join(sep), + Some(other) => text(Some(other)), + None => String::new(), + } +} + +fn headers(v: Option<&Value>) -> Vec { + match v { + Some(Value::Array(list)) => list + .iter() + .map(|h| KeyValue { + name: text(h.get("key")), + value: text(h.get("value")), + enabled: h.get("disabled").and_then(Value::as_bool) != Some(true), + description: description(h.get("description")), + ..Default::default() + }) + .filter(|h| !h.name.is_empty()) + .collect(), + Some(Value::String(s)) => s + .lines() + .filter_map(|l| l.split_once(':')) + .map(|(k, v)| KeyValue::new(k.trim(), v.trim())) + .collect(), + _ => Vec::new(), + } +} + +fn kv_rows(v: Option<&Value>) -> Vec { + v.and_then(Value::as_array) + .into_iter() + .flatten() + .map(|p| KeyValue { + name: text(p.get("key")), + value: text(p.get("value")), + enabled: p.get("disabled").and_then(Value::as_bool) != Some(true), + description: description(p.get("description")), + ..Default::default() + }) + .collect() +} + +fn map_body(req: &mut Request, b: &Value, warnings: &mut Vec) { + let mode = b.get("mode").and_then(Value::as_str).unwrap_or(""); + match mode { + "raw" => { + let content = text(b.get("raw")); + if content.is_empty() { + return; + } + let lang = b + .pointer("/options/raw/language") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(); + let ct = req + .headers + .iter() + .find(|h| h.enabled && h.name.eq_ignore_ascii_case("content-type")) + .map(|h| h.value.to_ascii_lowercase()); + let json = lang == "json" + || ct.as_deref().is_some_and(|c| c.contains("json")) + || (lang.is_empty() && ct.is_none() && looks_like_json(&content)); + if json { + let parses = serde_json::from_str::(&content).is_ok(); + let jsonc = !parses + && serde_json::from_str::(&crate::prepare::strip_json_comments(&content)).is_ok(); + req.body = Body { + kind: BodyType::Json, + content: if parses { pretty_json(&content) } else { content }, + jsonc, + ..Default::default() + }; + req.headers + .retain(|h| !(h.name.eq_ignore_ascii_case("content-type") && h.value.eq_ignore_ascii_case("application/json"))); + } else { + let content_type = match lang.as_str() { + "xml" => Some("application/xml"), + "html" => Some("text/html"), + "javascript" => Some("application/javascript"), + "graphql" => Some("application/graphql"), + "text" => Some("text/plain"), + _ => None, + }; + req.body = Body { + kind: BodyType::Raw, + content, + content_type: content_type.map(str::to_string), + ..Default::default() + }; + } + } + "urlencoded" => { + req.body = Body { + kind: BodyType::FormUrlencoded, + form: kv_rows(b.get("urlencoded")), + ..Default::default() + }; + } + "formdata" => { + let parts = b + .get("formdata") + .and_then(Value::as_array) + .into_iter() + .flatten() + .map(|p| { + let is_file = p.get("type").and_then(Value::as_str) == Some("file"); + let file = if is_file { + match p.get("src") { + Some(Value::String(s)) => Some(s.clone()), + Some(Value::Array(a)) => { + if a.len() > 1 { + warnings.push(format!("form field `{}` had several files; only the first was kept", text(p.get("key")))); + } + a.first().map(|s| text(Some(s))) + } + _ => Some(String::new()), + } + } else { + None + }; + MultipartPart { + name: text(p.get("key")), + value: if is_file { String::new() } else { text(p.get("value")) }, + file, + content_type: p.get("contentType").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string), + enabled: p.get("disabled").and_then(Value::as_bool) != Some(true), + } + }) + .collect(); + req.body = Body { + kind: BodyType::Multipart, + multipart: parts, + ..Default::default() + }; + } + "file" => { + let src = b.pointer("/file/src").map(|v| text(Some(v))).unwrap_or_default(); + req.body = Body { + kind: BodyType::Binary, + file: (!src.is_empty()).then_some(src), + ..Default::default() + }; + } + "graphql" => { + let g = b.get("graphql"); + let vars = g.and_then(|g| g.get("variables")); + let variables = match vars { + Some(Value::String(s)) => s.clone(), + Some(v @ Value::Object(_)) => serde_json::to_string_pretty(v).unwrap_or_default(), + _ => String::new(), + }; + req.kind = RequestKind::Graphql; + req.graphql = Some(GraphqlSpec { + query: text(g.and_then(|g| g.get("query"))), + variables, + operation_name: None, + }); + } + "" => {} + other => warnings.push(format!("body mode `{other}` is not supported")), + } +} + +/// Imports a Postman environment into an existing collection. Secret values +/// go to `.secrets.yaml`, never into the environment file. +pub fn import_postman_environment(json: &str, dest_collection_root: &Path) -> Result { + let v: Value = serde_json::from_str(json).context("the file is not valid JSON")?; + let values = v + .get("values") + .and_then(Value::as_array) + .ok_or_else(|| anyhow!("not a Postman environment: the `values` list is missing"))?; + let name = text(v.get("name")); + let name = if name.trim().is_empty() { "Imported".to_string() } else { name }; + let c = Collection::open(dest_collection_root)?; + + let base = slugify(&name); + let dir = c.root.join(ENV_DIR); + let id = std::iter::once(base.clone()) + .chain((2..).map(|n| format!("{base}-{n}"))) + .find(|id| !dir.join(format!("{id}.yaml")).exists()) + .unwrap_or(base); + + let mut env = Environment { + name: Some(name), + ..Default::default() + }; + let mut secrets = IndexMap::new(); + for item in values { + if item.get("enabled").and_then(Value::as_bool) == Some(false) { + continue; + } + let key = text(item.get("key")); + if key.is_empty() { + continue; + } + let value = text(item.get("value")); + let secret = item.get("type").and_then(Value::as_str) == Some("secret"); + if secret { + secrets.insert(key.clone(), value); + env.vars.insert(key, EnvVar { value: String::new(), secret: true, description: None }); + } else { + env.vars.insert(key, EnvVar { value, secret: false, description: None }); + } + } + if env.vars.is_empty() && !values.is_empty() { + bail!("the environment has no enabled variables"); + } + c.save_environment(&id, &env)?; + if !secrets.is_empty() { + c.save_secrets_file(&id, &SecretsFile { vars: secrets })?; + } + Ok(id) +} + +#[cfg(test)] +pub(crate) fn tests_sample() -> &'static str { + tests::SAMPLE +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::collection::Collection; + + pub(crate) const SAMPLE: &str = r#"{ + "info": { + "_postman_id": "1f0c", + "name": "Pet Store", + "description": "Demo API", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "auth": { "type": "bearer", "bearer": [ { "key": "token", "value": "{{token}}", "type": "string" } ] }, + "variable": [ { "key": "baseUrl", "value": "https://petstore.example.com/v2" } ], + "event": [ { "listen": "prerequest", "script": { "type": "text/javascript", "exec": ["console.log('collection')"] } } ], + "item": [ + { + "name": "Pets", + "auth": { "type": "basic", "basic": [ { "key": "username", "value": "admin" }, { "key": "password", "value": "hunter2" } ] }, + "item": [ + { + "name": "Get pet", + "event": [ + { "listen": "test", "script": { "exec": ["pm.test('ok', () => pm.response.to.have.status(200));"] } } + ], + "request": { + "method": "GET", + "header": [ { "key": "Accept", "value": "application/json" }, { "key": "X-Debug", "value": "1", "disabled": true } ], + "url": { + "raw": "{{baseUrl}}/pets/:petId?expand=owner", + "host": ["{{baseUrl}}"], + "path": ["pets", ":petId"], + "query": [ { "key": "expand", "value": "owner" }, { "key": "verbose", "value": "true", "disabled": true } ], + "variable": [ { "key": "petId", "value": "42" } ] + } + }, + "response": [ { "name": "200" } ] + }, + { + "name": "Nested", + "item": [ + { + "name": "Create pet", + "request": { + "method": "POST", + "header": [ { "key": "Content-Type", "value": "application/json" } ], + "body": { "mode": "raw", "raw": "{\"name\":\"Rex\",\"tags\":[\"dog\"]}", "options": { "raw": { "language": "json" } } }, + "url": "{{baseUrl}}/pets" + } + } + ] + } + ] + }, + { + "name": "Upload", + "request": { + "method": "POST", + "auth": { "type": "noauth" }, + "body": { "mode": "formdata", "formdata": [ + { "key": "file", "type": "file", "src": "/tmp/cat.png" }, + { "key": "caption", "value": "cute", "type": "text" }, + { "key": "old", "value": "x", "type": "text", "disabled": true } + ] }, + "url": { "raw": "https://upload.example.com/u", "protocol": "https", "host": ["upload","example","com"], "path": ["u"] } + } + }, + { + "name": "Login", + "request": { + "method": "POST", + "body": { "mode": "urlencoded", "urlencoded": [ { "key": "user", "value": "me" }, { "key": "pw", "value": "{{pw}}" } ] }, + "url": "{{baseUrl}}/login" + } + }, + { + "name": "Search", + "request": { + "method": "POST", + "body": { "mode": "graphql", "graphql": { "query": "query { pets { id } }", "variables": "{\"n\": 1}" } }, + "url": "{{baseUrl}}/graphql" + } + }, + { + "name": "Signed", + "request": { + "method": "GET", + "auth": { "type": "awsv4", "awsv4": { "accessKey": "AKIA", "secretKey": "abc", "region": "eu-central-1", "service": "s3" } }, + "url": "https://s3.example.com/bucket" + } + } + ] +}"#; + + #[test] + fn imports_collection() { + let dir = super::super::tmp_dir(); + let rep = import_postman(SAMPLE, &dir).unwrap(); + assert_eq!(rep.requests, 6); + assert_eq!(rep.folders, 2); + assert_eq!(rep.scripts_skipped, 2); + assert!(rep.warnings.iter().any(|w| w.contains("example"))); + let c = Collection::open(&dir).unwrap(); + assert_eq!(c.manifest.vars["baseUrl"], "https://petstore.example.com/v2"); + assert!(matches!(&c.manifest.auth, Auth::Config(a) if a.kind == "bearer")); + + let ids = c.requests_in(""); + assert_eq!( + ids, + vec![ + "pets/get-pet.yaml", + "pets/nested/create-pet.yaml", + "upload.yaml", + "login.yaml", + "search.gql.yaml", + "signed.yaml" + ] + ); + let folder = c.folder_meta("pets").unwrap(); + let Auth::Config(fa) = &folder.auth else { panic!() }; + assert_eq!(fa.str("password"), Some("{{secret.pets_password}}")); + let secrets = c.secrets_file("local").unwrap(); + assert_eq!(secrets.vars["pets_password"], "hunter2"); + + let get = c.request("pets/get-pet.yaml").unwrap(); + assert_eq!(get.url, "{{baseUrl}}/pets/:petId?expand=owner"); + assert_eq!(get.params.path["petId"], "42"); + assert_eq!(get.params.query.len(), 2); + assert!(!get.params.query[1].enabled); + assert!(!get.headers[1].enabled); + assert!(get.docs.unwrap().contains("Imported Postman scripts (not run)")); + + let create = c.request("pets/nested/create-pet.yaml").unwrap(); + assert_eq!(create.body.kind, BodyType::Json); + assert!(create.body.content.contains("\"name\": \"Rex\"")); + + let up = c.request("upload.yaml").unwrap(); + assert_eq!(up.auth, Auth::None); + assert_eq!(up.body.multipart[0].file.as_deref(), Some("/tmp/cat.png")); + assert!(!up.body.multipart[2].enabled); + + let login = c.request("login.yaml").unwrap(); + assert_eq!(login.body.kind, BodyType::FormUrlencoded); + assert_eq!(login.body.form[1].value, "{{pw}}"); + + let gql = c.request("search.gql.yaml").unwrap(); + assert_eq!(gql.kind, RequestKind::Graphql); + assert_eq!(gql.graphql.unwrap().variables, "{\"n\": 1}"); + + let signed = c.request("signed.yaml").unwrap(); + let Auth::Config(sa) = &signed.auth else { panic!() }; + assert_eq!(sa.str("region"), Some("eu-central-1")); + assert!(sa.str("secret_key").unwrap().starts_with("{{secret.")); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn imports_environment_with_secrets() { + let dir = super::super::tmp_dir(); + Collection::create(&dir, "x").unwrap(); + let env = r#"{"name":"Staging","values":[ + {"key":"baseUrl","value":"https://staging.example.com","type":"default","enabled":true}, + {"key":"apiKey","value":"sk_live_123","type":"secret","enabled":true}, + {"key":"off","value":"1","enabled":false} + ],"_postman_variable_scope":"environment"}"#; + let id = import_postman_environment(env, &dir).unwrap(); + assert_eq!(id, "staging"); + let file = std::fs::read_to_string(dir.join("environments/staging.yaml")).unwrap(); + assert!(!file.contains("sk_live_123")); + let c = Collection::open(&dir).unwrap(); + let e = c.environment("staging").unwrap(); + assert!(e.vars["apiKey"].secret); + assert!(!e.vars.contains_key("off")); + assert_eq!(c.secrets_file("staging").unwrap().vars["apiKey"], "sk_live_123"); + assert_eq!(import_postman_environment(env, &dir).unwrap(), "staging-2"); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn rejects_non_empty_destination() { + let dir = super::super::tmp_dir(); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("x.txt"), "x").unwrap(); + let err = import_postman(SAMPLE, &dir).unwrap_err().to_string(); + assert!(err.contains("not empty"), "{err}"); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/crates/knock-core/src/lib.rs b/crates/knock-core/src/lib.rs index 2936969..9df6c07 100644 --- a/crates/knock-core/src/lib.rs +++ b/crates/knock-core/src/lib.rs @@ -1,12 +1,16 @@ pub mod auth; pub mod checks; pub mod collection; +pub mod export; pub mod http; +pub mod import; pub mod model; pub mod oauth; pub mod prepare; pub mod run; +pub mod runner; pub mod secrets; pub mod vars; +pub mod ws; pub use collection::Collection; diff --git a/crates/knock-core/src/prepare.rs b/crates/knock-core/src/prepare.rs index 27bd09f..e78f9da 100644 --- a/crates/knock-core/src/prepare.rs +++ b/crates/knock-core/src/prepare.rs @@ -235,6 +235,10 @@ pub fn prepare(req: &Request, ctx: &RequestContext) -> Result { } let mut url = res(req.url.trim()); + if let Some(start) = url.find("{{") { + let name = url[start + 2..].split("}}").next().unwrap_or("").trim().to_string(); + bail!("the URL uses {{{{{name}}}}}, which is not defined in any scope. Pick an environment or define the variable"); + } let path_params: IndexMap = req.params.path.iter().map(|(k, v)| (k.clone(), res(v))).collect(); url = substitute_path_params(&url, &path_params); diff --git a/crates/knock-core/src/runner.rs b/crates/knock-core/src/runner.rs new file mode 100644 index 0000000..be04518 --- /dev/null +++ b/crates/knock-core/src/runner.rs @@ -0,0 +1,310 @@ +//! Runs a folder or a whole collection in sidebar order. Values extracted by +//! one request are visible to the next, as in the GUI. + +use crate::auth::AuthHost; +use crate::checks::AssertResult; +use crate::collection::Collection; +use crate::http::Engine; +use crate::model::RequestKind; +use crate::prepare::{ContextInput, RequestContext}; +use crate::run::execute; +use crate::vars::{OauthLookup, SecretLookup}; +use indexmap::IndexMap; +use serde::Serialize; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +#[derive(Debug, Clone, Default)] +pub struct RunOptions { + pub env: Option, + pub bail: bool, + pub delay_ms: u64, + pub globals: IndexMap, + pub runtime: IndexMap, +} + +#[derive(Debug, Clone, Serialize)] +pub struct RunItem { + pub id: String, + pub name: String, + pub method: String, + pub url: String, + pub status: Option, + pub ms: f64, + pub passed: bool, + pub skipped: bool, + pub asserts: Vec, + pub error: Option, +} + +#[derive(Debug, Clone, Serialize)] +pub struct RunReport { + pub collection: String, + pub folder: String, + pub env: Option, + pub started_at: String, + pub total_ms: f64, + pub passed: usize, + pub failed: usize, + pub skipped: usize, + pub items: Vec, + /// Runtime variables at the end of the run. + pub runtime: IndexMap, +} + +impl RunReport { + pub fn ok(&self) -> bool { + self.failed == 0 + } +} + +pub struct RunDeps<'a> { + pub engine: &'a Engine, + pub secrets: Arc, + pub oauth: Option>, + pub host: Option<&'a dyn AuthHost>, +} + +pub async fn run( + c: &Collection, + folder: &str, + opts: &RunOptions, + deps: &RunDeps<'_>, + mut progress: impl FnMut(usize, usize, &RunItem), +) -> RunReport { + let ids = c.requests_in(folder); + let started = Instant::now(); + let mut runtime = opts.runtime.clone(); + let mut items = Vec::with_capacity(ids.len()); + let mut stop = false; + for (i, id) in ids.iter().enumerate() { + let item = if stop { + skipped(id, "skipped after an earlier failure") + } else { + run_one(c, id, opts, deps, &mut runtime).await + }; + if !item.passed && !item.skipped && opts.bail { + stop = true; + } + progress(i + 1, ids.len(), &item); + items.push(item); + if opts.delay_ms > 0 && i + 1 < ids.len() && !stop { + tokio::time::sleep(Duration::from_millis(opts.delay_ms)).await; + } + } + let passed = items.iter().filter(|x| x.passed).count(); + let skipped_n = items.iter().filter(|x| x.skipped).count(); + RunReport { + collection: c.manifest.name.clone(), + folder: folder.to_string(), + env: opts.env.clone(), + started_at: chrono::Utc::now().to_rfc3339(), + total_ms: started.elapsed().as_secs_f64() * 1000.0, + passed, + failed: items.len() - passed - skipped_n, + skipped: skipped_n, + items, + runtime, + } +} + +fn skipped(id: &str, why: &str) -> RunItem { + RunItem { + id: id.into(), + name: id.into(), + method: String::new(), + url: String::new(), + status: None, + ms: 0.0, + passed: false, + skipped: true, + asserts: vec![], + error: Some(why.into()), + } +} + +pub async fn run_one( + c: &Collection, + id: &str, + opts: &RunOptions, + deps: &RunDeps<'_>, + runtime: &mut IndexMap, +) -> RunItem { + let req = match c.request(id) { + Ok(r) => r, + Err(e) => { + let mut it = skipped(id, &format!("{e:#}")); + it.skipped = false; + return it; + } + }; + if req.kind == RequestKind::Ws { + let mut it = skipped(id, "WebSocket requests are not part of runs"); + it.name = req.name; + return it; + } + let ctx = match RequestContext::build(ContextInput { + collection: c, + request_id: id, + request: &req, + env: opts.env.as_deref(), + runtime: runtime.clone(), + globals: opts.globals.clone(), + secrets: deps.secrets.clone(), + oauth: deps.oauth.clone(), + }) { + Ok(ctx) => ctx, + Err(e) => { + let mut it = skipped(id, &format!("{e:#}")); + it.skipped = false; + it.name = req.name; + return it; + } + }; + let out = execute(deps.engine, &req, &ctx, deps.host).await; + for x in &out.extracted { + if let Some(v) = &x.value { + runtime.insert(x.var.clone(), v.clone()); + } + } + let mask = |s: &str| ctx.resolver.mask(s); + RunItem { + id: id.into(), + name: req.name.clone(), + method: out.request.as_ref().map(|r| r.method.clone()).unwrap_or_else(|| req.method().to_string()), + url: out.request.as_ref().map(|r| mask(&r.url)).unwrap_or_else(|| req.url.clone()), + status: out.response.as_ref().map(|r| r.status), + ms: out.response.as_ref().map(|r| r.timings.total_ms).unwrap_or(0.0), + passed: out.passed(), + skipped: false, + asserts: out.asserts.clone(), + error: out.error.as_deref().map(mask), + } +} + +// ---------------------------------------------------------------- reporters + +pub fn to_json(r: &RunReport) -> String { + let mut v = serde_json::to_value(r).unwrap_or_default(); + // Runtime values may hold tokens; reports only list the names. + if let Some(m) = v.get_mut("runtime").and_then(|x| x.as_object_mut()) { + for val in m.values_mut() { + *val = serde_json::Value::String("••••••".into()); + } + } + serde_json::to_string_pretty(&v).unwrap_or_default() +} + +fn xml(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +pub fn to_junit(r: &RunReport) -> String { + let mut out = String::from("\n"); + out.push_str(&format!( + "\n", + xml(&r.collection), + r.items.len(), + r.failed, + r.skipped, + r.total_ms / 1000.0 + )); + out.push_str(&format!( + " \n", + xml(if r.folder.is_empty() { &r.collection } else { &r.folder }), + r.items.len(), + r.failed, + r.skipped, + r.total_ms / 1000.0, + r.started_at + )); + for it in &r.items { + out.push_str(&format!( + " \n", + xml(&it.id), + xml(&it.method), + xml(&it.name), + it.ms / 1000.0 + )); + if it.skipped { + out.push_str(&format!(" \n", xml(it.error.as_deref().unwrap_or("")))); + } else if let Some(e) = &it.error { + out.push_str(&format!(" \n", xml(e))); + } + for a in it.asserts.iter().filter(|a| !a.passed) { + out.push_str(&format!( + " expected {}, got {}\n", + xml(&a.label), + xml(&a.expected), + xml(&a.actual) + )); + } + out.push_str(" \n"); + } + out.push_str(" \n\n"); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::*; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + #[tokio::test] + async fn runs_folder_and_chains_extracts() { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { + loop { + let (mut s, _) = l.accept().await.unwrap(); + tokio::spawn(async move { + let mut b = vec![0; 8192]; + let n = s.read(&mut b).await.unwrap_or(0); + let req = String::from_utf8_lossy(&b[..n]).to_string(); + let body = if req.starts_with("POST /login") { + r#"{"token":"abc"}"#.to_string() + } else if req.contains("authorization: Bearer abc") || req.contains("Authorization: Bearer abc") { + r#"{"ok":true}"#.to_string() + } else { + r#"{"ok":false}"#.to_string() + }; + let _ = s + .write_all(format!("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()) + .await; + }); + } + }); + let dir = std::env::temp_dir().join(format!("knock-run-{}", uuid::Uuid::new_v4())); + let c = Collection::create(&dir, "Run").unwrap(); + let mut env = c.environment("local").unwrap(); + env.vars.insert("baseUrl".into(), EnvVar { value: format!("http://{addr}"), secret: false, description: None }); + c.save_environment("local", &env).unwrap(); + let login = Request { + name: "Login".into(), + method: Some("POST".into()), + url: "{{baseUrl}}/login".into(), + extract: vec![ExtractRule { var: "token".into(), from: ExtractSource::Json, path: "$.token".into(), enabled: true, persist: false }], + ..Default::default() + }; + let me = Request { + name: "Me".into(), + url: "{{baseUrl}}/me".into(), + headers: vec![KeyValue::new("Authorization", "Bearer {{token}}")], + assert: vec![AssertRule { on: AssertTarget::Json, path: Some("$.ok".into()), equals: Some(serde_json::json!(true)), enabled: true, ..Default::default() }], + ..Default::default() + }; + c.create_request("", &login).unwrap(); + c.create_request("", &me).unwrap(); + let c = Collection::open(&dir).unwrap(); + let engine = Engine::new(dir.join(".spill")); + let deps = RunDeps { engine: &engine, secrets: Arc::new(crate::vars::NoSecrets), oauth: None, host: None }; + let opts = RunOptions { env: Some("local".into()), ..Default::default() }; + let report = run(&c, "", &opts, &deps, |_, _, _| {}).await; + assert_eq!(report.passed, 2, "{report:#?}"); + let junit = to_junit(&report); + assert!(junit.contains("tests=\"2\" failures=\"0\"")); + assert!(to_json(&report).contains("\"token\": \"••••••\"")); + std::fs::remove_dir_all(dir).ok(); + } +} diff --git a/crates/knock-core/src/ws.rs b/crates/knock-core/src/ws.rs new file mode 100644 index 0000000..2fc1079 --- /dev/null +++ b/crates/knock-core/src/ws.rs @@ -0,0 +1,135 @@ +//! WebSocket connect: same URL, headers and auth handling as HTTP, so an +//! OAuth token travels in the handshake like it would on a request. + +use crate::prepare::Prepared; +use anyhow::{anyhow, Context, Result}; +use serde::Serialize; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::http::HeaderValue; +use tokio_tungstenite::{MaybeTlsStream, WebSocketStream}; + +pub type Socket = WebSocketStream>; + +#[derive(Debug, Clone, Serialize)] +pub struct Handshake { + pub url: String, + pub status: u16, + pub request_headers: Vec<(String, String)>, + pub response_headers: Vec<(String, String)>, + pub protocol: Option, + pub ms: f64, +} + +pub async fn connect(p: &Prepared, subprotocols: &[String]) -> Result<(Socket, Handshake)> { + // Several crates bring rustls; pick the provider once so wss:// does not panic. + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let url = p.url.replacen("http://", "ws://", 1).replacen("https://", "wss://", 1); + if !url.starts_with("ws://") && !url.starts_with("wss://") { + return Err(anyhow!("WebSocket URLs start with ws:// or wss://")); + } + let mut req = url.as_str().into_client_request().context("invalid WebSocket URL")?; + for (k, v) in &p.headers { + let name: tokio_tungstenite::tungstenite::http::HeaderName = k.parse().with_context(|| format!("invalid header name {k}"))?; + req.headers_mut().append(name, HeaderValue::from_str(v).with_context(|| format!("invalid value for header {k}"))?); + } + if !subprotocols.is_empty() { + req.headers_mut().insert("Sec-WebSocket-Protocol", HeaderValue::from_str(&subprotocols.join(", "))?); + } + let request_headers = req + .headers() + .iter() + .map(|(k, v)| (k.to_string(), String::from_utf8_lossy(v.as_bytes()).into_owned())) + .collect(); + let started = std::time::Instant::now(); + let (sock, resp) = tokio::time::timeout( + std::time::Duration::from_millis(p.settings.timeout_ms.max(1)), + tokio_tungstenite::connect_async(req), + ) + .await + .map_err(|_| anyhow!("handshake timed out"))? + .map_err(|e| match e { + tokio_tungstenite::tungstenite::Error::Http(r) => anyhow!( + "the server answered the handshake with HTTP {}{}", + r.status(), + r.body().as_ref().map(|b| format!(": {}", String::from_utf8_lossy(b))).unwrap_or_default() + ), + other => anyhow!("{other}"), + })?; + let response_headers: Vec<(String, String)> = resp + .headers() + .iter() + .map(|(k, v)| (k.to_string(), String::from_utf8_lossy(v.as_bytes()).into_owned())) + .collect(); + let protocol = resp + .headers() + .get("sec-websocket-protocol") + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + Ok(( + sock, + Handshake { + url, + status: resp.status().as_u16(), + request_headers, + response_headers, + protocol, + ms: started.elapsed().as_secs_f64() * 1000.0, + }, + )) +} + +/// Parses "0a ff 10" or "0aff10" into bytes. +pub fn parse_hex(s: &str) -> Result> { + let clean: String = s.chars().filter(|c| !c.is_whitespace() && *c != ':').collect(); + if clean.len() % 2 != 0 { + return Err(anyhow!("hex needs an even number of digits")); + } + (0..clean.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&clean[i..i + 2], 16).map_err(|_| anyhow!("'{}' is not hex", &clean[i..i + 2]))) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use futures_util::{SinkExt, StreamExt}; + use tokio_tungstenite::tungstenite::Message; + + #[tokio::test] + async fn echo_with_header_and_subprotocol() { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { + let (s, _) = l.accept().await.unwrap(); + let cb = |req: &tokio_tungstenite::tungstenite::handshake::server::Request, + mut resp: tokio_tungstenite::tungstenite::handshake::server::Response| { + assert_eq!(req.headers().get("authorization").unwrap(), "Bearer t"); + resp.headers_mut().insert("sec-websocket-protocol", HeaderValue::from_static("chat")); + Ok(resp) + }; + let mut ws = tokio_tungstenite::accept_hdr_async(s, cb).await.unwrap(); + while let Some(Ok(m)) = ws.next().await { + if m.is_text() || m.is_binary() { + ws.send(m).await.unwrap(); + } + } + }); + let p = Prepared { + method: "GET".into(), + url: format!("http://{addr}/"), + headers: vec![("Authorization".into(), "Bearer t".into())], + body: crate::prepare::PreparedBody::None, + settings: Default::default(), + missing: vec![], + cycles: vec![], + }; + let (mut sock, hs) = connect(&p, &["chat".into()]).await.unwrap(); + assert_eq!(hs.status, 101); + assert_eq!(hs.protocol.as_deref(), Some("chat")); + sock.send(Message::Text("hi".into())).await.unwrap(); + let m = sock.next().await.unwrap().unwrap(); + assert_eq!(m.into_text().unwrap().as_str(), "hi"); + assert_eq!(parse_hex("0a ff").unwrap(), vec![10, 255]); + } +} diff --git a/crates/knock-core/tests/fixtures/bruno/Health.bru b/crates/knock-core/tests/fixtures/bruno/Health.bru new file mode 100644 index 0000000..a05b8e7 --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/Health.bru @@ -0,0 +1,16 @@ +meta { + name: Health + type: http + seq: 4 +} + +get { + url: {{baseUrl}}/health + body: none + auth: none +} + +assert { + res.status: eq 200 + res.responseTime: lt 500 +} diff --git a/crates/knock-core/tests/fixtures/bruno/Search.bru b/crates/knock-core/tests/fixtures/bruno/Search.bru new file mode 100644 index 0000000..5477f9f --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/Search.bru @@ -0,0 +1,23 @@ +meta { + name: Search + type: graphql + seq: 3 +} + +post { + url: {{baseUrl}}/graphql + body: graphql + auth: inherit +} + +body:graphql { + query Search($q: String!) { + products(query: $q) { id name } + } +} + +body:graphql:vars { + { + "q": "chair" + } +} diff --git a/crates/knock-core/tests/fixtures/bruno/auth/Login.bru b/crates/knock-core/tests/fixtures/bruno/auth/Login.bru new file mode 100644 index 0000000..c98a242 --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/auth/Login.bru @@ -0,0 +1,44 @@ +meta { + name: Login + type: http + seq: 1 +} + +post { + url: {{baseUrl}}/auth/login + body: json + auth: none +} + +headers { + Accept: application/json +} + +body:json { + { + "email": "{{email}}", + "password": "{{password}}" + } +} + +vars:post-response { + token: res.body.token + ~refresh: res.body.refresh_token +} + +assert { + res.status: eq 200 + res.body.token: isDefined + res.headers.content-type: contains json + res.body.roles: length 2 +} + +script:post-response { + bru.setVar("loggedInAt", Date.now()); +} + +tests { + test("returns a token", function() { + expect(res.getBody().token).to.be.a("string"); + }); +} diff --git a/crates/knock-core/tests/fixtures/bruno/auth/folder.bru b/crates/knock-core/tests/fixtures/bruno/auth/folder.bru new file mode 100644 index 0000000..d310afd --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/auth/folder.bru @@ -0,0 +1,4 @@ +meta { + name: auth + seq: 1 +} diff --git a/crates/knock-core/tests/fixtures/bruno/bruno.json b/crates/knock-core/tests/fixtures/bruno/bruno.json new file mode 100644 index 0000000..d53570f --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/bruno.json @@ -0,0 +1,6 @@ +{ + "version": "1", + "name": "Shop API", + "type": "collection", + "ignore": ["node_modules", ".git"] +} diff --git a/crates/knock-core/tests/fixtures/bruno/collection.bru b/crates/knock-core/tests/fixtures/bruno/collection.bru new file mode 100644 index 0000000..7372b12 --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/collection.bru @@ -0,0 +1,19 @@ +headers { + X-Client: knock-fixture +} + +auth { + mode: bearer +} + +auth:bearer { + token: {{apiToken}} +} + +script:pre-request { + req.setHeader("X-Request-Id", Date.now().toString()); +} + +docs { + Internal shop API used by the storefront. +} diff --git a/crates/knock-core/tests/fixtures/bruno/environments/Local.bru b/crates/knock-core/tests/fixtures/bruno/environments/Local.bru new file mode 100644 index 0000000..5913e77 --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/environments/Local.bru @@ -0,0 +1,4 @@ +vars { + baseUrl: http://localhost:4000 + ~debugUser: alice +} diff --git a/crates/knock-core/tests/fixtures/bruno/environments/Production.bru b/crates/knock-core/tests/fixtures/bruno/environments/Production.bru new file mode 100644 index 0000000..210d655 --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/environments/Production.bru @@ -0,0 +1,6 @@ +vars { + baseUrl: https://api.shop.example.com +} +vars:secret [ + apiToken +] diff --git a/crates/knock-core/tests/fixtures/bruno/users/Create user.bru b/crates/knock-core/tests/fixtures/bruno/users/Create user.bru new file mode 100644 index 0000000..0a0d7c0 --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/users/Create user.bru @@ -0,0 +1,28 @@ +meta { + name: Create user + type: http + seq: 2 +} + +post { + url: {{baseUrl}}/orgs/:org/users + body: json + auth: basic +} + +params:path { + org: acme +} + +auth:basic { + username: admin + password: correct-horse +} + +body:json { + {"name": "Ada", "roles": ["admin"]} +} + +docs { + Creates a user in the given organisation. +} diff --git a/crates/knock-core/tests/fixtures/bruno/users/List users.bru b/crates/knock-core/tests/fixtures/bruno/users/List users.bru new file mode 100644 index 0000000..ab88ae7 --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/users/List users.bru @@ -0,0 +1,16 @@ +meta { + name: List users + type: http + seq: 1 +} + +get { + url: {{baseUrl}}/users?page=1 + body: none + auth: inherit +} + +params:query { + page: 1 + ~size: {{pageSize}} +} diff --git a/crates/knock-core/tests/fixtures/bruno/users/Upload avatar.bru b/crates/knock-core/tests/fixtures/bruno/users/Upload avatar.bru new file mode 100644 index 0000000..76946e2 --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/users/Upload avatar.bru @@ -0,0 +1,17 @@ +meta { + name: Upload avatar + type: http + seq: 3 +} + +put { + url: {{baseUrl}}/users/me/avatar + body: multipartForm + auth: inherit +} + +body:multipart-form { + file: @file(avatars/me.png) + kind: profile + ~note: old +} diff --git a/crates/knock-core/tests/fixtures/bruno/users/folder.bru b/crates/knock-core/tests/fixtures/bruno/users/folder.bru new file mode 100644 index 0000000..0c9d93c --- /dev/null +++ b/crates/knock-core/tests/fixtures/bruno/users/folder.bru @@ -0,0 +1,12 @@ +meta { + name: users + seq: 2 +} + +headers { + Accept: application/json +} + +vars:pre-request { + pageSize: 20 +} diff --git a/packaging/arch/knock-bin/PKGBUILD b/packaging/arch/knock-bin/PKGBUILD new file mode 100644 index 0000000..303fe5d --- /dev/null +++ b/packaging/arch/knock-bin/PKGBUILD @@ -0,0 +1,19 @@ +# Maintainer: Joshua +pkgname=knock-bin +pkgver=0.1.0 +pkgrel=1 +pkgdesc="Offline desktop API client for REST, GraphQL and WebSocket with plain-file collections (binary release)" +arch=('x86_64') +url="https://git.joshicodes.de/JoshiCodes/knock" +license=('MIT') +depends=('webkit2gtk-4.1' 'gtk3' 'libsecret' 'hicolor-icon-theme') +optdepends=('kwallet: store secrets in KWallet' 'gnome-keyring: store secrets in GNOME Keyring') +provides=('knock') +conflicts=('knock') +source=("knock_${pkgver}_amd64.deb::$url/releases/download/v$pkgver/knock_${pkgver}_amd64.deb") +sha256sums=('SKIP') + +package() { + bsdtar -xf data.tar.* -C "$pkgdir" + install -Dm644 "$pkgdir/usr/share/doc/knock/copyright" "$pkgdir/usr/share/licenses/$pkgname/LICENSE" 2>/dev/null || true +} diff --git a/packaging/arch/knock/PKGBUILD b/packaging/arch/knock/PKGBUILD new file mode 100644 index 0000000..4b49382 --- /dev/null +++ b/packaging/arch/knock/PKGBUILD @@ -0,0 +1,46 @@ +# Maintainer: Joshua +pkgname=knock +pkgver=0.1.0 +pkgrel=1 +pkgdesc="Offline desktop API client for REST, GraphQL and WebSocket with plain-file collections" +arch=('x86_64') +url="https://git.joshicodes.de/JoshiCodes/knock" +license=('MIT') +depends=('webkit2gtk-4.1' 'gtk3' 'libsecret' 'hicolor-icon-theme') +makedepends=('rust' 'cargo' 'nodejs' 'npm' 'git') +optdepends=('kwallet: store secrets in KWallet' 'gnome-keyring: store secrets in GNOME Keyring') +conflicts=('knock-bin') +source=("$pkgname-$pkgver.tar.gz::$url/archive/v$pkgver.tar.gz") +sha256sums=('SKIP') + +prepare() { + cd "$pkgname" + export RUSTUP_TOOLCHAIN=stable + cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')" + npm ci +} + +build() { + cd "$pkgname" + export RUSTUP_TOOLCHAIN=stable + npm run build + cargo build --frozen --release -p knock-app -p knock-cli +} + +check() { + cd "$pkgname" + cargo test --frozen --release -p knock-core +} + +package() { + cd "$pkgname" + install -Dm755 target/release/knock-app "$pkgdir/usr/bin/knock-app" + install -Dm755 target/release/knock "$pkgdir/usr/bin/knock" + install -Dm644 packaging/linux/de.joshicodes.knock.desktop "$pkgdir/usr/share/applications/de.joshicodes.knock.desktop" + install -Dm644 logo/knock-app-icon.svg "$pkgdir/usr/share/icons/hicolor/scalable/apps/knock.svg" + for s in 32 128; do + install -Dm644 "src-tauri/icons/${s}x${s}.png" "$pkgdir/usr/share/icons/hicolor/${s}x${s}/apps/knock.png" + done + install -Dm644 src-tauri/icons/128x128@2x.png "$pkgdir/usr/share/icons/hicolor/256x256/apps/knock.png" + install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE" +} diff --git a/packaging/linux/de.joshicodes.knock.desktop b/packaging/linux/de.joshicodes.knock.desktop new file mode 100644 index 0000000..7e1d932 --- /dev/null +++ b/packaging/linux/de.joshicodes.knock.desktop @@ -0,0 +1,13 @@ +[Desktop Entry] +Type=Application +Name=knock +GenericName=API Client +Comment=Send HTTP, GraphQL and WebSocket requests +Exec=knock-app %u +Icon=knock +Terminal=false +Categories=Development;Network; +Keywords=api;http;rest;graphql;websocket;oauth;postman;bruno; +MimeType=x-scheme-handler/knock; +StartupWMClass=knock-app +StartupNotify=true diff --git a/packaging/linux/knock.desktop.hbs b/packaging/linux/knock.desktop.hbs new file mode 100644 index 0000000..0eb9e74 --- /dev/null +++ b/packaging/linux/knock.desktop.hbs @@ -0,0 +1,13 @@ +[Desktop Entry] +Type=Application +Name={{name}} +GenericName=API Client +Comment=Send HTTP, GraphQL and WebSocket requests +Exec={{exec}} %u +Icon={{icon}} +Terminal=false +Categories=Development;Network; +Keywords=api;http;rest;graphql;websocket;oauth;postman;bruno; +MimeType=x-scheme-handler/knock; +StartupWMClass={{exec}} +StartupNotify=true diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 6ab21cb..728949d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -35,3 +35,4 @@ rusqlite = { version = "0.37", features = ["bundled"] } notify = "8" futures-util = "0.3" regex = "1" +tokio-tungstenite = "0.30" diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index b7a8d9b..916e75e 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -621,3 +621,179 @@ pub fn path_params(url: String) -> Vec { pub fn app_version() -> String { env!("CARGO_PKG_VERSION").to_string() } + +#[tauri::command] +pub fn write_text_file(path: String, text: String) -> Res<()> { + std::fs::write(&path, text).map_err(err) +} + +#[derive(Serialize)] +pub struct RunResult { + pub report: knock_core::runner::RunReport, + pub json: String, + pub junit: String, +} + +#[tauri::command] +pub async fn runner_run( + app: AppHandle, + col: String, + folder: String, + env: Option, + bail: bool, + delay_ms: u64, +) -> Res { + use tauri::Emitter; + let state = app.state::(); + let c = state.collection(&col).map_err(errx)?; + let file = env.as_deref().map(|e| c.secrets_file(e).unwrap_or_default()).unwrap_or_default(); + let secrets = Arc::new(SecretStore::new(&c.manifest.id, env.as_deref(), file.vars, true)); + let oauth = Arc::new(crate::oauth::TokenLookup::new(&app, &c, env.as_deref())); + let host = crate::oauth::Host::new(app.clone(), Some(col.clone()), env.clone()); + let engine = state.engine.clone(); + let opts = knock_core::runner::RunOptions { + env: env.clone(), + bail, + delay_ms, + globals: db::globals_load(&state.db.lock().unwrap()).unwrap_or_default(), + runtime: state.runtime_vars(&col), + }; + let deps = knock_core::runner::RunDeps { engine: &engine, secrets, oauth: Some(oauth), host: Some(&host) }; + let report = knock_core::runner::run(&c, &folder, &opts, &deps, |done, total, item| { + let _ = app.emit("run-progress", (done, total, item)); + }) + .await; + for (k, v) in &report.runtime { + state.set_runtime(&col, k, Some(v.clone()), false); + } + let json = state.engine.save_jar(&col); + let _ = db::jar_save(&state.db.lock().unwrap(), &col, &json); + Ok(RunResult { json: knock_core::runner::to_json(&report), junit: knock_core::runner::to_junit(&report), report }) +} + +// ---------------------------------------------------------------- import / export + +use knock_core::import::{self as importer, ImportReport, Kind as ImportKind}; + +#[tauri::command] +pub fn import_curl(text: String) -> Res { + importer::parse_curl(&text).map_err(errx) +} + +#[tauri::command] +pub fn import_detect(text: String) -> Option { + importer::detect(&text) +} + +/// Imports a file or folder (Bruno) into a new collection at `dest` and opens it. +#[tauri::command] +pub fn import_source(app: AppHandle, state: State<'_, AppState>, source: String, dest: String) -> Res<(ImportReport, CollectionView)> { + let src = PathBuf::from(&source); + let dest_path = PathBuf::from(&dest); + let report = if src.is_dir() { + if !src.join("bruno.json").exists() { + return Err("this folder is not a Bruno collection (no bruno.json)".into()); + } + importer::import_bruno(&src, &dest_path).map_err(errx)? + } else { + let text = std::fs::read_to_string(&src).map_err(|e| format!("{source}: {e}"))?; + import_text_into(&text, &dest_path)? + }; + let c = Collection::open(&report.collection_root).map_err(errx)?; + let view = register(&app, &state, c)?; + Ok((report, view)) +} + +#[tauri::command] +pub fn import_text(app: AppHandle, state: State<'_, AppState>, text: String, dest: String) -> Res<(ImportReport, CollectionView)> { + let report = import_text_into(&text, &PathBuf::from(&dest))?; + let c = Collection::open(&report.collection_root).map_err(errx)?; + let view = register(&app, &state, c)?; + Ok((report, view)) +} + +fn import_text_into(text: &str, dest: &std::path::Path) -> Res { + match importer::detect(text) { + Some(ImportKind::PostmanCollection) => importer::import_postman(text, dest).map_err(errx), + Some(ImportKind::Insomnia) => importer::import_insomnia(text, dest).map_err(errx), + Some(ImportKind::Openapi) => importer::import_openapi(text, dest).map_err(errx), + Some(ImportKind::Curl) => { + let mut req = importer::parse_curl(text).map_err(errx)?; + let name = dest.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "Imported".into()); + let c = Collection::create(dest, &name).map_err(errx)?; + // Credentials from the command go to the gitignored secrets file, not the request. + let mut store = IndexMap::new(); + importer::externalize_secrets(&mut req.auth, "curl", &mut store); + if !store.is_empty() { + let mut f = c.secrets_file("local").unwrap_or_default(); + f.vars.extend(store); + c.save_secrets_file("local", &f).map_err(errx)?; + } + c.create_request("", &req).map_err(errx)?; + Ok(ImportReport { collection_root: c.root.clone(), requests: 1, ..Default::default() }) + } + Some(ImportKind::PostmanEnvironment) => Err("this is a Postman environment. Open the collection first, then import the environment from its Environments tab".into()), + None => Err("could not recognise the format. knock imports Postman, Bruno, Insomnia, OpenAPI/Swagger and cURL".into()), + } +} + +#[tauri::command] +pub fn import_environment(state: State<'_, AppState>, col: String, source: String) -> Res { + let text = std::fs::read_to_string(&source).map_err(|e| format!("{source}: {e}"))?; + let root = state.with_collection(&col, |c| Ok(c.root.clone())).map_err(errx)?; + importer::import_postman_environment(&text, &root).map_err(errx)?; + after_edit(&state, &col) +} + +#[tauri::command] +pub fn export_postman(state: State<'_, AppState>, col: String, path: String) -> Res<()> { + let json = state.with_collection(&col, knock_core::export::export_postman).map_err(errx)?; + std::fs::write(&path, json).map_err(err) +} + +/// Code for the request. `resolve` fills in variables (secrets stay masked); +/// otherwise `{{placeholders}}` are kept as written. +#[tauri::command] +pub async fn code_snippet(app: AppHandle, args: ScopeArgs, lang: knock_core::export::Lang, resolve: bool) -> Res { + use knock_core::prepare::{Prepared, PreparedBody}; + let state = app.state::(); + let p = if resolve { + let ctx = build_context(&app, &state, &args).map_err(errx)?; + let mut p = knock_core::prepare::prepare(&args.request, &ctx).map_err(errx)?; + // Stored tokens only; generating code never starts a login. + let host = crate::oauth::Host::preview(app.clone(), args.col.clone(), args.env.clone()); + knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false, &ctx.root).await; + let mask = |s: &str| ctx.resolver.mask(s); + p.url = mask(&p.url); + p.headers = p.headers.into_iter().map(|(k, v)| (k, mask(&v))).collect(); + if let PreparedBody::Bytes { data, preview } = &p.body { + let text = mask(&String::from_utf8_lossy(data)); + p.body = PreparedBody::Bytes { data: text.clone().into_bytes(), preview: preview.clone() }; + } + p + } else { + let r = &args.request; + let body = match r.body.kind { + BodyType::None => PreparedBody::None, + BodyType::FormUrlencoded => { + let s = r.body.form.iter().filter(|f| f.enabled).map(|f| format!("{}={}", f.name, f.value)).collect::>().join("&"); + PreparedBody::Bytes { preview: s.clone(), data: s.into_bytes() } + } + _ => PreparedBody::Bytes { preview: r.body.content.clone(), data: r.body.content.clone().into_bytes() }, + }; + let mut headers: Vec<(String, String)> = r.headers.iter().filter(|h| h.enabled).map(|h| (h.name.clone(), h.value.clone())).collect(); + if r.body.kind == BodyType::Json && !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) { + headers.push(("Content-Type".into(), "application/json".into())); + } + Prepared { + method: r.method().to_string(), + url: r.url.clone(), + headers, + body, + settings: r.settings.clone(), + missing: vec![], + cycles: vec![], + } + }; + Ok(knock_core::export::snippet(&p, lang)) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 2522e6b..5dc1474 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,6 +3,7 @@ mod db; mod oauth; mod state; mod watch; +mod ws; use tauri::Manager; @@ -22,6 +23,7 @@ pub fn run() { let dir = app.path().app_data_dir()?; app.manage(state::AppState::new(dir)?); app.manage(oauth::OauthState::default()); + app.manage(ws::WsState::default()); Ok(()) }) .invoke_handler(tauri::generate_handler![ @@ -67,11 +69,24 @@ pub fn run() { commands::setting_set, commands::path_params, commands::app_version, + commands::write_text_file, + commands::runner_run, + commands::import_curl, + commands::import_detect, + commands::import_source, + commands::import_text, + commands::import_environment, + commands::export_postman, + commands::code_snippet, oauth::oauth_status, oauth::oauth_run, oauth::oauth_callback, oauth::oauth_deep_link, oauth::oauth_cancel, + ws::ws_connect, + ws::ws_send, + ws::ws_ping, + ws::ws_close, ]) .run(tauri::generate_context!()) .expect("error while running knock"); diff --git a/src-tauri/src/ws.rs b/src-tauri/src/ws.rs new file mode 100644 index 0000000..3478bfe --- /dev/null +++ b/src-tauri/src/ws.rs @@ -0,0 +1,209 @@ +//! WebSocket sessions, one per tab. Frames are pushed to the UI as events. + +use crate::commands::{build_context, ScopeArgs}; +use crate::state::AppState; +use futures_util::{SinkExt, StreamExt}; +use knock_core::model::WsFormat; +use knock_core::prepare::prepare; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::Duration; +use tauri::{AppHandle, Emitter, Manager}; +use tokio::sync::mpsc; +use tokio_tungstenite::tungstenite::{Bytes, Message}; + +#[derive(Default)] +pub struct WsState { + sessions: Mutex>>, +} + +enum Cmd { + Send(Message), + Close, +} + +#[derive(Clone, Serialize)] +struct WsEvent { + tab: String, + at: i64, + /// open, text, binary, ping, pong, close, error, status + kind: &'static str, + /// in, out, sys + dir: &'static str, + data: String, + size: usize, +} + +fn emit(app: &AppHandle, tab: &str, kind: &'static str, dir: &'static str, data: String, size: usize) { + let _ = app.emit( + "ws-event", + WsEvent { tab: tab.into(), at: chrono::Utc::now().timestamp_millis(), kind, dir, data, size }, + ); +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect::>().join(" ") +} + +#[derive(Deserialize)] +pub struct WsArgs { + #[serde(flatten)] + pub scope: ScopeArgs, + pub tab: String, +} + +#[tauri::command] +pub async fn ws_connect(app: AppHandle, args: WsArgs) -> Result<(), String> { + ws_close(app.clone(), args.tab.clone()); + let (tx, rx) = mpsc::unbounded_channel(); + app.state::().sessions.lock().unwrap().insert(args.tab.clone(), tx); + let reconnect = args.scope.request.ws.as_ref().is_some_and(|w| w.auto_reconnect); + tauri::async_runtime::spawn(run(app, args, rx, reconnect)); + Ok(()) +} + +async fn run(app: AppHandle, args: WsArgs, mut rx: mpsc::UnboundedReceiver, reconnect: bool) { + let tab = args.tab.clone(); + let mut attempt = 0u32; + loop { + match session(&app, &args, &mut rx).await { + Ok(true) => return, // closed by the user + Ok(false) => emit(&app, &tab, "close", "sys", "connection closed by the server".into(), 0), + Err(e) => emit(&app, &tab, "error", "sys", e, 0), + } + let still_open = app.state::().sessions.lock().unwrap().contains_key(&tab); + if !reconnect || !still_open { + app.state::().sessions.lock().unwrap().remove(&tab); + emit(&app, &tab, "status", "sys", "disconnected".into(), 0); + return; + } + attempt += 1; + let wait = Duration::from_secs((1u64 << attempt.min(5)).min(30)); + emit(&app, &tab, "status", "sys", format!("reconnecting in {} s (attempt {attempt})", wait.as_secs()), 0); + tokio::select! { + _ = tokio::time::sleep(wait) => {} + cmd = rx.recv() => { + if matches!(cmd, None | Some(Cmd::Close)) { + emit(&app, &tab, "status", "sys", "disconnected".into(), 0); + return; + } + } + } + } +} + +/// Ok(true) when the user closed it, Ok(false) when the server did. +async fn session(app: &AppHandle, args: &WsArgs, rx: &mut mpsc::UnboundedReceiver) -> Result { + let tab = &args.tab; + let state = app.state::(); + let ctx = build_context(app, &state, &args.scope).map_err(|e| format!("{e:#}"))?; + let mut p = prepare(&args.scope.request, &ctx).map_err(|e| format!("{e:#}"))?; + let host = crate::oauth::Host::new(app.clone(), args.scope.col.clone(), args.scope.env.clone()); + let auth = knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false, &ctx.root).await; + if auth.failed() { + let _ = app.emit("ws-auth", (tab.clone(), &auth)); + return Err("authentication failed, see the Auth tab".into()); + } + let protocols = args.scope.request.ws.as_ref().map(|w| w.subprotocols.clone()).unwrap_or_default(); + emit(app, tab, "status", "sys", format!("connecting to {}", p.url), 0); + let (sock, hs) = knock_core::ws::connect(&p, &protocols).await.map_err(|e| format!("{e:#}"))?; + let _ = app.emit("ws-handshake", (tab.clone(), &hs, &auth)); + emit(app, tab, "open", "sys", format!("connected in {:.0} ms{}", hs.ms, hs.protocol.as_ref().map(|p| format!(", protocol {p}")).unwrap_or_default()), 0); + + let (mut write, mut read) = sock.split(); + loop { + tokio::select! { + cmd = rx.recv() => match cmd { + Some(Cmd::Send(m)) => { + let (kind, data, size) = describe(&m); + if let Err(e) = write.send(m).await { + return Err(format!("send failed: {e}")); + } + emit(app, tab, kind, "out", data, size); + } + Some(Cmd::Close) | None => { + let _ = write.send(Message::Close(None)).await; + emit(app, tab, "close", "sys", "closed".into(), 0); + return Ok(true); + } + }, + msg = read.next() => match msg { + Some(Ok(Message::Close(frame))) => { + let why = frame.map(|f| format!("code {} {}", u16::from(f.code), f.reason)).unwrap_or_default(); + emit(app, tab, "close", "in", why, 0); + return Ok(false); + } + Some(Ok(m)) => { + let (kind, data, size) = describe(&m); + emit(app, tab, kind, "in", data, size); + } + Some(Err(e)) => return Err(e.to_string()), + None => return Ok(false), + } + } + } +} + +fn describe(m: &Message) -> (&'static str, String, usize) { + match m { + Message::Text(t) => ("text", t.to_string(), t.len()), + Message::Binary(b) => ("binary", hex(b), b.len()), + Message::Ping(b) => ("ping", hex(b), b.len()), + Message::Pong(b) => ("pong", hex(b), b.len()), + Message::Close(_) => ("close", String::new(), 0), + Message::Frame(_) => ("binary", String::new(), 0), + } +} + +#[tauri::command] +pub fn ws_send( + app: AppHandle, + tab: String, + format: WsFormat, + content: String, + file: Option, + scope: Option, +) -> Result<(), String> { + // Messages may use {{variables}} like any other field. + let content = match &scope { + Some(s) => { + let state = app.state::(); + let ctx = build_context(&app, &state, s).map_err(|e| format!("{e:#}"))?; + let text = ctx.resolver.apply(&content); + if format == WsFormat::Json { + knock_core::prepare::strip_json_comments(&text) + } else { + text + } + } + None => content, + }; + let msg = if let Some(f) = file { + Message::Binary(Bytes::from(std::fs::read(&f).map_err(|e| format!("{f}: {e}"))?)) + } else { + match format { + WsFormat::Hex => Message::Binary(Bytes::from(knock_core::ws::parse_hex(&content).map_err(|e| e.to_string())?)), + _ => Message::Text(content.into()), + } + }; + let state = app.state::(); + let sessions = state.sessions.lock().unwrap(); + let tx = sessions.get(&tab).ok_or("not connected")?; + tx.send(Cmd::Send(msg)).map_err(|_| "not connected".to_string()) +} + +#[tauri::command] +pub fn ws_ping(app: AppHandle, tab: String) -> Result<(), String> { + let state = app.state::(); + let sessions = state.sessions.lock().unwrap(); + let tx = sessions.get(&tab).ok_or("not connected")?; + tx.send(Cmd::Send(Message::Ping(Bytes::from_static(b"knock")))).map_err(|_| "not connected".to_string()) +} + +#[tauri::command] +pub fn ws_close(app: AppHandle, tab: String) { + if let Some(tx) = app.state::().sessions.lock().unwrap().remove(&tab) { + let _ = tx.send(Cmd::Close); + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index b23cd45..c264fb2 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -30,12 +30,20 @@ }, "plugins": { "deep-link": { - "desktop": { "schemes": ["knock"] } + "desktop": { + "schemes": [ + "knock" + ] + } } }, "bundle": { "active": true, - "targets": ["deb", "rpm", "appimage"], + "targets": [ + "deb", + "rpm", + "appimage" + ], "category": "DeveloperTool", "shortDescription": "API client for REST, GraphQL and WebSocket", "longDescription": "knock is an offline desktop API client that stores collections as plain YAML files.", @@ -48,8 +56,25 @@ "icons/icon.ico" ], "linux": { - "deb": { "depends": ["libwebkit2gtk-4.1-0", "libgtk-3-0"] }, - "rpm": { "depends": ["webkit2gtk4.1"] } + "deb": { + "depends": [ + "libwebkit2gtk-4.1-0", + "libgtk-3-0" + ], + "desktopTemplate": "../packaging/linux/knock.desktop.hbs", + "files": { + "/usr/bin/knock": "../target/release/knock" + } + }, + "rpm": { + "depends": [ + "webkit2gtk4.1" + ], + "desktopTemplate": "../packaging/linux/knock.desktop.hbs", + "files": { + "/usr/bin/knock": "../target/release/knock" + } + } } } } diff --git a/src/lib/json/parse.worker.ts b/src/lib/json/parse.worker.ts new file mode 100644 index 0000000..d7d950f --- /dev/null +++ b/src/lib/json/parse.worker.ts @@ -0,0 +1,11 @@ +import { parse, serialize } from './ast'; + +self.onmessage = (e: MessageEvent<{ id: number; text: string }>) => { + const { id, text } = e.data; + try { + const tree = parse(text); + (self as unknown as Worker).postMessage({ id, tree, pretty: serialize(tree, ' ') }); + } catch (err) { + (self as unknown as Worker).postMessage({ id, error: String((err as Error).message) }); + } +}; diff --git a/src/lib/json/parseAsync.ts b/src/lib/json/parseAsync.ts new file mode 100644 index 0000000..4667f52 --- /dev/null +++ b/src/lib/json/parseAsync.ts @@ -0,0 +1,29 @@ +import type { JNode } from './ast'; +import { parse, serialize } from './ast'; + +let worker: Worker | null = null; +let seq = 0; +const pending = new Map void>(); + +/** Parses large JSON off the main thread so a 50 MB body does not freeze the UI. */ +export function parseJson(text: string): Promise<{ tree: JNode | null; pretty: string; error?: string }> { + if (text.length < 512 * 1024) { + try { + const tree = parse(text); + return Promise.resolve({ tree, pretty: serialize(tree, ' ') }); + } catch (e) { + return Promise.resolve({ tree: null, pretty: text, error: String((e as Error).message) }); + } + } + worker ??= new Worker(new URL('./parse.worker.ts', import.meta.url), { type: 'module' }); + worker.onmessage = (e) => { + const cb = pending.get(e.data.id); + pending.delete(e.data.id); + cb?.(e.data); + }; + const id = ++seq; + return new Promise((resolve) => { + pending.set(id, (r) => resolve({ tree: r.tree ?? null, pretty: r.pretty ?? text, error: r.error })); + worker!.postMessage({ id, text }); + }); +} diff --git a/src/lib/state/wslog.svelte.ts b/src/lib/state/wslog.svelte.ts new file mode 100644 index 0000000..8ff3662 --- /dev/null +++ b/src/lib/state/wslog.svelte.ts @@ -0,0 +1,65 @@ +import { listen } from '@tauri-apps/api/event'; +import type { AuthDebug } from '$lib/types'; + +export interface WsEvent { + tab: string; + at: number; + kind: 'open' | 'text' | 'binary' | 'ping' | 'pong' | 'close' | 'error' | 'status'; + dir: 'in' | 'out' | 'sys'; + data: string; + size: number; + id: number; +} + +export interface Handshake { + url: string; + status: number; + request_headers: [string, string][]; + response_headers: [string, string][]; + protocol: string | null; + ms: number; +} + +const MAX = 5000; +let seq = 0; + +class WsLogs { + events = $state>({}); + connected = $state>({}); + connecting = $state>({}); + handshake = $state>({}); + authFailure = $state>({}); + + constructor() { + listen>('ws-event', (e) => { + const ev = { ...e.payload, id: ++seq }; + const list = (this.events[ev.tab] ??= []); + list.push(ev); + if (list.length > MAX) list.splice(0, list.length - MAX); + if (ev.kind === 'open') { + this.connected[ev.tab] = true; + this.connecting[ev.tab] = false; + } + if (ev.kind === 'error' || (ev.kind === 'status' && ev.data === 'disconnected') || (ev.kind === 'close' && ev.dir !== 'out')) { + this.connected[ev.tab] = false; + if (ev.kind !== 'close' || ev.data === 'closed') this.connecting[ev.tab] = false; + } + if (ev.kind === 'status' && ev.data.startsWith('reconnecting')) this.connecting[ev.tab] = true; + if (ev.kind === 'error') this.connecting[ev.tab] = false; + }); + listen<[string, Handshake, AuthDebug]>('ws-handshake', (e) => { + const [tab, hs, auth] = e.payload; + this.handshake[tab] = { hs, auth }; + delete this.authFailure[tab]; + }); + listen<[string, AuthDebug]>('ws-auth', (e) => { + this.authFailure[e.payload[0]] = e.payload[1]; + }); + } + + clear(tab: string) { + this.events[tab] = []; + } +} + +export const wsLogs = new WsLogs(); diff --git a/src/lib/views/dialogs/CodeDialog.svelte b/src/lib/views/dialogs/CodeDialog.svelte index aed6617..da8005d 100644 --- a/src/lib/views/dialogs/CodeDialog.svelte +++ b/src/lib/views/dialogs/CodeDialog.svelte @@ -1,4 +1,67 @@ + + +
+
+ {#each LANGS as [id, label]} + + {/each} + + Fill in variables +
+ {#if error}

{error}

{/if} +
+ {#key `${lang}`}{/key} +
+

Secret values are masked; replace them before running the code. Auth that is computed per request (OAuth, signatures) is shown with the values of this moment.

+
+ {#snippet footer()} +
+ + +
+ {/snippet} +
diff --git a/src/lib/views/dialogs/ImportDialog.svelte b/src/lib/views/dialogs/ImportDialog.svelte index aed6617..9dccf82 100644 --- a/src/lib/views/dialogs/ImportDialog.svelte +++ b/src/lib/views/dialogs/ImportDialog.svelte @@ -1,4 +1,135 @@ + + + {#if report} +
+

+ Imported {report.requests} requests in {report.folders} folders{report.environments.length ? ` and ${report.environments.length} environments` : ''}. +

+

{report.collection_root}

+ {#if report.scripts_skipped} + + knock never runs imported scripts. Their code is kept in the Docs tab of each request so you can turn them into assertions or extract rules. + + {/if} + {#if report.warnings.length} +
+ {#each report.warnings as w}

{w}

{/each} +
+ {/if} +
+ {:else} +
+
+ + + {#if source}{source}{/if} +
+ {#if !source} + + {#snippet children(attrs)} +