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
This commit is contained in:
2026-11-27 17:13:06 +01:00
parent a469697af7
commit fc253126a7
51 changed files with 8437 additions and 24 deletions
+21
View File
@@ -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"] }
+531
View File
@@ -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<String>,
/// 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<String>,
},
/// 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<String>,
#[arg(short, long, value_enum, default_value = "pretty")]
reporter: Reporter,
/// Write the report to a file instead of stdout
#[arg(short, long)]
output: Option<PathBuf>,
/// 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<String>,
},
/// 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<String>,
},
/// Walk through the token flow step by step
Debug {
path: PathBuf,
#[arg(short, long)]
env: Option<String>,
/// 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<String>,
},
}
#[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<i32> {
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<indexmap::IndexMap<String, String>> {
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<SecretStore> {
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<String>> {
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<TokenSet> {
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<String>,
}
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<String>, verbose: bool, vars: indexmap::IndexMap<String, String>) -> Result<i32> {
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<String>,
reporter: Reporter,
output: Option<PathBuf>,
bail: bool,
delay: u64,
vars: indexmap::IndexMap<String, String>,
) -> Result<i32> {
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<i32> {
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<i32> {
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)
}