Skeleton, REST core, variables and JSON editor (M0–M2)

- knock-core: YAML collection format with unknown-field round trip,
  variable resolution across scopes with secrets and dynamic values,
  HTTP engine with manual redirects, cookie jar and large-body spill,
  basic/bearer/API key auth with debug output, assertions and extracts
- Tauri app: collection commands, file watcher, SQLite history,
  keyring-backed secrets
- Svelte UI: sidebar tree, tabs, request editor, response viewer,
  JSON form/code editor with schema hints, environments, settings
This commit is contained in:
2026-11-27 16:42:31 +01:00
commit f6484f4dc8
127 changed files with 22909 additions and 0 deletions
+184
View File
@@ -0,0 +1,184 @@
//! Auth is never a black box: every auth type returns an [`AuthDebug`] that
//! says what was computed, what was attached and where it came from.
mod simple;
use crate::model::{Auth, AuthConfig};
use crate::prepare::{EffectiveAuth, Prepared};
use crate::vars::Resolver;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StepStatus {
Ok,
Error,
Skipped,
Pending,
Warning,
}
/// One HTTP exchange made as part of an auth flow, in full.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Exchange {
pub method: String,
pub url: String,
pub request_headers: Vec<(String, String)>,
pub request_body: String,
pub status: Option<u16>,
pub response_headers: Vec<(String, String)>,
pub response_body: String,
pub curl: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Step {
pub id: String,
pub title: String,
pub status: StepStatus,
pub at: chrono::DateTime<chrono::Utc>,
pub duration_ms: f64,
/// One line shown next to the title.
pub summary: String,
/// What went wrong and what to do about it.
pub hint: Option<String>,
pub exchange: Option<Exchange>,
/// Free-form structured data (parsed URL params, decoded token, …).
pub data: serde_json::Value,
}
impl Step {
pub fn new(id: &str, title: &str, status: StepStatus, summary: impl Into<String>) -> Self {
Self {
id: id.into(),
title: title.into(),
status,
at: chrono::Utc::now(),
duration_ms: 0.0,
summary: summary.into(),
hint: None,
exchange: None,
data: serde_json::Value::Null,
}
}
pub fn hint(mut self, h: impl Into<String>) -> Self {
self.hint = Some(h.into());
self
}
pub fn data(mut self, d: serde_json::Value) -> Self {
self.data = d;
self
}
pub fn took(mut self, since: std::time::Instant) -> Self {
self.duration_ms = since.elapsed().as_secs_f64() * 1000.0;
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Sent {
/// header, query, cookie or body
pub location: String,
pub name: String,
pub value: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuthDebug {
pub kind: String,
pub origin: Option<String>,
pub source: Option<String>,
pub steps: Vec<Step>,
pub sent: Vec<Sent>,
pub warnings: Vec<String>,
/// Id of the OAuth flow log entry, if a flow ran.
pub flow_id: Option<String>,
}
impl AuthDebug {
pub fn failed(&self) -> bool {
self.steps.iter().any(|s| s.status == StepStatus::Error)
}
}
/// Hooks for auth types that need more than the request itself (OAuth token
/// store and browser, signing keys from the keyring, …). Implemented by the
/// app and the CLI.
#[allow(async_fn_in_trait)]
pub trait AuthHost: Send + Sync {
/// Returns an access token for an OAuth2 config, refreshing or logging in
/// as needed, plus the steps it took.
fn oauth2_token(
&self,
cfg: &AuthConfig,
resolver: &Resolver,
force_refresh: bool,
) -> futures_util::future::BoxFuture<'_, OauthResult>;
}
#[derive(Debug, Clone, Default)]
pub struct OauthResult {
pub token: Option<String>,
pub steps: Vec<Step>,
pub flow_id: Option<String>,
pub warnings: Vec<String>,
}
/// Attaches the effective auth to a prepared request. Errors are reported as
/// failed steps inside the returned debug info, not as `Err`, so the UI can
/// show where it broke.
pub async fn apply(
eff: &EffectiveAuth,
p: &mut Prepared,
resolver: &Resolver,
host: Option<&dyn AuthHost>,
force_refresh: bool,
) -> AuthDebug {
let mut dbg = AuthDebug {
origin: Some(format!("{:?}", eff.origin).to_lowercase()),
source: Some(eff.source.clone()),
..Default::default()
};
let cfg = match &eff.auth {
Auth::Inherit | Auth::None => {
dbg.kind = "none".into();
return dbg;
}
Auth::Config(c) => c,
};
dbg.kind = cfg.kind.clone();
let res = |key: &str| -> (String, Vec<String>) {
let r = resolver.resolve(cfg.str(key).unwrap_or_default());
(r.value, r.missing)
};
match cfg.kind.as_str() {
"basic" => simple::basic(cfg, p, &res, &mut dbg),
"bearer" => simple::bearer(cfg, p, &res, &mut dbg),
"apikey" => simple::apikey(cfg, p, &res, &mut dbg),
"oauth2" | "oidc" => {
let Some(host) = host else {
dbg.steps.push(Step::new("token", "Get token", StepStatus::Error, "OAuth is not available here"));
return dbg;
};
let out = host.oauth2_token(cfg, resolver, force_refresh).await;
dbg.steps.extend(out.steps);
dbg.warnings.extend(out.warnings);
dbg.flow_id = out.flow_id;
if let Some(token) = out.token {
simple::attach_token(cfg, p, &token, &mut dbg);
}
}
other => {
dbg.steps.push(Step::new(
"apply",
"Apply auth",
StepStatus::Error,
format!("auth type '{other}' is not supported"),
));
}
}
for s in &dbg.sent {
resolver.note_secret(&s.value);
}
dbg
}
+102
View File
@@ -0,0 +1,102 @@
use super::{AuthDebug, Sent, Step, StepStatus};
use crate::model::AuthConfig;
use crate::prepare::Prepared;
use base64::Engine;
type Res<'a> = dyn Fn(&str) -> (String, Vec<String>) + 'a;
fn check(dbg: &mut AuthDebug, field: &str, value: &str, missing: &[String]) {
if !missing.is_empty() {
dbg.warnings.push(format!(
"{field}: variable {} is not defined, sent as literal text",
missing.iter().map(|m| format!("{{{{{m}}}}}")).collect::<Vec<_>>().join(", ")
));
} else if value.is_empty() {
dbg.warnings.push(format!("{field} resolved to an empty value"));
}
}
pub(super) fn basic(cfg: &AuthConfig, p: &mut Prepared, res: &Res<'_>, dbg: &mut AuthDebug) {
let (user, m1) = res("username");
let (pass, m2) = res("password");
check(dbg, "username", &user, &m1);
check(dbg, "password", &pass, &m2);
let _ = cfg;
let encoded = base64::engine::general_purpose::STANDARD.encode(format!("{user}:{pass}"));
let value = format!("Basic {encoded}");
p.set_header("Authorization", &value);
dbg.steps.push(
Step::new("encode", "Encode credentials", StepStatus::Ok, format!("base64(\"{user}:•••\")"))
.data(serde_json::json!({ "username": user, "encoded": encoded })),
);
dbg.sent.push(Sent { location: "header".into(), name: "Authorization".into(), value });
}
pub(super) fn bearer(cfg: &AuthConfig, p: &mut Prepared, res: &Res<'_>, dbg: &mut AuthDebug) {
let (token, m) = res("token");
check(dbg, "token", &token, &m);
let prefix = cfg.str("prefix").unwrap_or("Bearer");
let value = if prefix.is_empty() { token.clone() } else { format!("{prefix} {token}") };
p.set_header("Authorization", &value);
dbg.steps.push(Step::new("attach", "Attach token", StepStatus::Ok, format!("Authorization: {prefix} …")));
dbg.sent.push(Sent { location: "header".into(), name: "Authorization".into(), value });
}
pub(super) fn apikey(cfg: &AuthConfig, p: &mut Prepared, res: &Res<'_>, dbg: &mut AuthDebug) {
let (key, m1) = res("key");
let (value, m2) = res("value");
check(dbg, "key", &key, &m1);
check(dbg, "value", &value, &m2);
let location = cfg.str("in").unwrap_or("header").to_string();
match location.as_str() {
"query" => {
if let Err(e) = p.add_query(&key, &value) {
dbg.steps.push(Step::new("attach", "Attach key", StepStatus::Error, e.to_string()));
return;
}
}
"cookie" => {
let existing = p.header("Cookie").map(str::to_string);
let c = format!("{key}={value}");
p.set_header("Cookie", existing.map(|e| format!("{e}; {c}")).unwrap_or(c));
}
_ => p.set_header(&key, &value),
}
dbg.steps.push(Step::new("attach", "Attach key", StepStatus::Ok, format!("{key} as {location}")));
dbg.sent.push(Sent { location, name: key, value });
}
/// Attaches an OAuth token the way the config asks for (header, query or body
/// field; access or id token is chosen by the host).
pub(crate) fn attach_token(cfg: &AuthConfig, p: &mut Prepared, token: &str, dbg: &mut AuthDebug) {
let place = cfg.str("token_placement").unwrap_or("header");
let name = cfg.str("token_name").filter(|s| !s.is_empty());
match place {
"query" => {
let n = name.unwrap_or("access_token");
if let Err(e) = p.add_query(n, token) {
dbg.steps.push(Step::new("attach", "Attach token", StepStatus::Error, e.to_string()));
return;
}
dbg.sent.push(Sent { location: "query".into(), name: n.into(), value: token.into() });
}
"body" => {
let n = name.unwrap_or("access_token");
let mut body = String::from_utf8_lossy(p.body_bytes()).into_owned();
if !body.is_empty() {
body.push('&');
}
body.push_str(&url::form_urlencoded::Serializer::new(String::new()).append_pair(n, token).finish());
p.body = crate::prepare::PreparedBody::Bytes { preview: body.clone(), data: body.into_bytes() };
dbg.sent.push(Sent { location: "body".into(), name: n.into(), value: token.into() });
}
_ => {
let prefix = cfg.str("token_prefix").unwrap_or("Bearer");
let header = name.unwrap_or("Authorization");
let value = if prefix.is_empty() { token.to_string() } else { format!("{prefix} {token}") };
p.set_header(header, &value);
dbg.sent.push(Sent { location: "header".into(), name: header.into(), value });
}
}
dbg.steps.push(Step::new("attach", "Attach token to request", StepStatus::Ok, format!("as {place}")));
}
+263
View File
@@ -0,0 +1,263 @@
//! Declarative assertions and extract rules.
use crate::http::Response;
use crate::model::*;
use serde::Serialize;
use serde_json::Value;
#[derive(Debug, Clone, Serialize)]
pub struct AssertResult {
pub index: usize,
pub label: String,
pub passed: bool,
pub expected: String,
pub actual: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct Extracted {
pub var: String,
pub value: Option<String>,
pub persist: bool,
pub error: Option<String>,
}
pub fn json_path(doc: &Value, path: &str) -> Result<Vec<Value>, String> {
let path = path.trim();
let path = if path.starts_with('$') { path.to_string() } else { format!("$.{path}") };
let p = serde_json_path::JsonPath::parse(&path).map_err(|e| format!("invalid JSONPath: {e}"))?;
Ok(p.query(doc).all().into_iter().cloned().collect())
}
fn target_value(rule: &AssertRule, resp: &Response) -> (Option<Value>, String) {
let path = rule.path.clone().unwrap_or_default();
match rule.on {
AssertTarget::Status => (Some(Value::from(resp.status)), "status".into()),
AssertTarget::Time => (
Some(Value::from((resp.timings.total_ms).round() as u64)),
"response time (ms)".into(),
),
AssertTarget::Size => (Some(Value::from(resp.size)), "body size (bytes)".into()),
AssertTarget::Body => (Some(Value::String(resp.text())), "body".into()),
AssertTarget::Header => (
resp.header(&path).map(|v| Value::String(v.to_string())),
format!("header {path}"),
),
AssertTarget::Json => {
let label = format!("json {path}");
let Some(doc) = resp.json() else { return (None, label) };
match json_path(&doc, &path) {
Ok(mut v) if v.len() == 1 => (v.pop(), label),
Ok(v) if v.is_empty() => (None, label),
Ok(v) => (Some(Value::Array(v)), label),
Err(_) => (None, label),
}
}
}
}
fn show(v: &Option<Value>) -> String {
match v {
None => "(missing)".into(),
Some(Value::String(s)) => {
if s.chars().count() > 200 {
format!("\"{}…\"", s.chars().take(200).collect::<String>())
} else {
format!("\"{s}\"")
}
}
Some(v) => v.to_string(),
}
}
/// Loose equality: `201` equals `"201"`, so YAML authors need not care about quoting.
fn loose_eq(a: &Value, b: &Value) -> bool {
if a == b {
return true;
}
match (a, b) {
(Value::String(s), other) | (other, Value::String(s)) if !other.is_string() => {
let o = match other {
Value::Null => "null".to_string(),
v => v.to_string(),
};
*s == o
}
(Value::Number(x), Value::Number(y)) => x.as_f64() == y.as_f64(),
_ => false,
}
}
fn type_name(v: &Value) -> &'static str {
match v {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
fn as_number(v: &Value) -> Option<f64> {
match v {
Value::Number(n) => n.as_f64(),
Value::String(s) => s.trim().parse().ok(),
_ => None,
}
}
pub fn run_asserts(rules: &[AssertRule], resp: &Response) -> Vec<AssertResult> {
let mut out = Vec::new();
for (index, rule) in rules.iter().enumerate().filter(|(_, r)| r.enabled) {
let (actual, label) = target_value(rule, resp);
let mut push = |op: &str, expected: String, passed: bool| {
out.push(AssertResult {
index,
label: format!("{label} {op}"),
passed,
expected,
actual: show(&actual),
})
};
if let Some(e) = &rule.equals {
push("equals", e.to_string(), actual.as_ref().is_some_and(|a| loose_eq(a, e)));
}
if let Some(e) = &rule.not_equals {
push("not equals", e.to_string(), !actual.as_ref().is_some_and(|a| loose_eq(a, e)));
}
if let Some(e) = &rule.contains {
let ok = match (&actual, e) {
(Some(Value::String(a)), Value::String(s)) => a.contains(s.as_str()),
(Some(Value::String(a)), other) => a.contains(&other.to_string()),
(Some(Value::Array(a)), e) => a.iter().any(|x| loose_eq(x, e)),
(Some(Value::Object(o)), Value::String(k)) => o.contains_key(k),
_ => false,
};
push("contains", e.to_string(), ok);
}
if let Some(e) = rule.exists {
push(if e { "exists" } else { "does not exist" }, e.to_string(), actual.is_some() == e);
}
if let Some(t) = &rule.type_is {
let ok = actual.as_ref().is_some_and(|a| {
type_name(a) == t || (t == "integer" && a.as_i64().is_some())
});
push("type", t.clone(), ok);
}
if let Some(re) = &rule.matches {
let ok = match regex::Regex::new(re) {
Ok(r) => actual.as_ref().is_some_and(|a| match a {
Value::String(s) => r.is_match(s),
v => r.is_match(&v.to_string()),
}),
Err(_) => false,
};
push("matches", format!("/{re}/"), ok);
}
if let Some(n) = rule.gt {
push(">", n.to_string(), actual.as_ref().and_then(as_number).is_some_and(|a| a > n));
}
if let Some(n) = rule.lt {
push("<", n.to_string(), actual.as_ref().and_then(as_number).is_some_and(|a| a < n));
}
}
out
}
pub fn run_extracts(rules: &[ExtractRule], resp: &Response) -> Vec<Extracted> {
rules
.iter()
.filter(|r| r.enabled && !r.var.is_empty())
.map(|r| {
let (value, error) = match extract_one(r, resp) {
Ok(v) => (v, None),
Err(e) => (None, Some(e)),
};
Extracted { var: r.var.clone(), value, persist: r.persist, error }
})
.collect()
}
fn extract_one(r: &ExtractRule, resp: &Response) -> Result<Option<String>, String> {
Ok(match r.from {
ExtractSource::Status => Some(resp.status.to_string()),
ExtractSource::Header => resp.header(&r.path).map(str::to_string),
ExtractSource::Cookie => resp.cookies.iter().find(|c| c.name == r.path).map(|c| c.value.clone()),
ExtractSource::Regex => {
let re = regex::Regex::new(&r.path).map_err(|e| format!("invalid regex: {e}"))?;
let text = resp.text();
re.captures(&text)
.map(|c| c.get(1).or_else(|| c.get(0)).unwrap().as_str().to_string())
}
ExtractSource::Json => {
let doc = resp.json().ok_or("response body is not JSON")?;
let mut v = json_path(&doc, &r.path)?;
match v.len() {
0 => None,
1 => Some(scalar_to_string(&v.pop().unwrap())),
_ => Some(Value::Array(v).to_string()),
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::Timings;
fn resp(body: &str) -> Response {
Response {
status: 201,
status_text: "Created".into(),
http_version: "1.1".into(),
url: "http://x".into(),
headers: vec![("Content-Type".into(), "application/json".into())],
cookies: vec![],
size: body.len() as u64,
header_size: 0,
content_type: Some("application/json".into()),
timings: Timings { total_ms: 12.0, ..Default::default() },
redirects: vec![],
remote_addr: None,
body_file: None,
body: body.as_bytes().to_vec(),
}
}
#[test]
fn asserts() {
let r = resp(r#"{"id": 7, "tags": ["a","b"], "name": "Ann"}"#);
let rules: Vec<AssertRule> = serde_yaml_ng::from_str(
r#"
- { on: status, equals: 201 }
- { on: json, path: $.id, equals: "7", type: number }
- { on: json, path: tags, contains: b }
- { on: json, path: $.missing, exists: false }
- { on: header, path: content-type, matches: "json$" }
- { on: time, lt: 1000 }
- { on: status, equals: 200 }
"#,
)
.unwrap();
let res = run_asserts(&rules, &r);
let failed: Vec<_> = res.iter().filter(|r| !r.passed).collect();
assert_eq!(failed.len(), 1, "{res:#?}");
assert_eq!(failed[0].index, 6);
}
#[test]
fn extracts() {
let r = resp(r#"{"data": {"id": "abc"}}"#);
let rules = vec![
ExtractRule { var: "id".into(), from: ExtractSource::Json, path: "$.data.id".into(), enabled: true, persist: false },
ExtractRule { var: "ct".into(), from: ExtractSource::Header, path: "content-type".into(), enabled: true, persist: false },
ExtractRule { var: "re".into(), from: ExtractSource::Regex, path: r#""id": "(\w+)""#.into(), enabled: true, persist: false },
];
let out = run_extracts(&rules, &r);
assert_eq!(out[0].value.as_deref(), Some("abc"));
assert_eq!(out[1].value.as_deref(), Some("application/json"));
assert_eq!(out[2].value.as_deref(), Some("abc"));
}
}
+766
View File
@@ -0,0 +1,766 @@
//! A collection is a directory of YAML files. Ids are paths relative to the
//! collection root, always with forward slashes.
use crate::model::*;
use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Component, Path, PathBuf};
pub const MANIFEST: &str = "knock.yaml";
pub const FOLDER_META: &str = "folder.yaml";
pub const ENV_DIR: &str = "environments";
#[derive(Debug, Clone, Serialize)]
pub struct Collection {
pub root: PathBuf,
pub manifest: Manifest,
pub tree: FolderNode,
pub environments: Vec<EnvEntry>,
/// Files that failed to parse, with the error. They stay on disk untouched.
pub problems: Vec<Problem>,
}
#[derive(Debug, Clone, Serialize)]
pub struct Problem {
pub path: String,
pub message: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct EnvEntry {
pub id: String,
pub name: String,
pub color: Option<String>,
pub protected: bool,
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "node", rename_all = "lowercase")]
pub enum Node {
Folder(FolderNode),
Request(RequestHead),
}
impl Node {
pub fn id(&self) -> &str {
match self {
Node::Folder(f) => &f.id,
Node::Request(r) => &r.id,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct FolderNode {
/// "" for the collection root.
pub id: String,
pub name: String,
pub children: Vec<Node>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RequestHead {
#[serde(default)]
pub id: String,
#[serde(default)]
pub name: String,
#[serde(rename = "type", default)]
pub kind: RequestKind,
#[serde(default)]
pub method: Option<String>,
}
impl Collection {
pub fn open(root: impl AsRef<Path>) -> Result<Self> {
let root = root.as_ref().canonicalize().with_context(|| {
format!("collection folder {} not found", root.as_ref().display())
})?;
let manifest_path = root.join(MANIFEST);
let mut manifest: Manifest = read_yaml(&manifest_path)
.with_context(|| format!("{} is not a knock collection", root.display()))?;
if manifest.version > FORMAT_VERSION {
bail!(
"collection format v{} is newer than this knock (v{FORMAT_VERSION}); update knock",
manifest.version
);
}
if manifest.id.is_empty() {
manifest.id = uuid::Uuid::new_v4().to_string();
write_yaml(&manifest_path, &manifest)?;
}
let mut problems = Vec::new();
let tree = load_folder(&root, "", &manifest.name, &manifest.order, &mut problems)?;
let environments = load_env_list(&root)?;
Ok(Self {
root,
manifest,
tree,
environments,
problems,
})
}
/// Creates a new collection in an empty (or not yet existing) folder.
pub fn create(root: impl AsRef<Path>, name: &str) -> Result<Self> {
let root = root.as_ref();
fs::create_dir_all(root.join(ENV_DIR))?;
if root.join(MANIFEST).exists() {
bail!("{} already contains a collection", root.display());
}
let manifest = Manifest {
version: FORMAT_VERSION,
name: name.to_string(),
id: uuid::Uuid::new_v4().to_string(),
..Default::default()
};
write_yaml(&root.join(MANIFEST), &manifest)?;
let env = Environment {
vars: [(
"baseUrl".to_string(),
EnvVar {
value: "http://localhost:8080".into(),
secret: false,
description: None,
},
)]
.into_iter()
.collect(),
..Default::default()
};
write_yaml(&root.join(ENV_DIR).join("local.yaml"), &env)?;
ensure_gitignore(root)?;
Self::open(root)
}
pub fn reload(&mut self) -> Result<()> {
*self = Self::open(&self.root)?;
Ok(())
}
pub fn abs(&self, id: &str) -> Result<PathBuf> {
resolve_inside(&self.root, id)
}
// ------------------------------------------------------------ reading
pub fn request(&self, id: &str) -> Result<Request> {
read_yaml(&self.abs(id)?)
}
pub fn folder_meta(&self, id: &str) -> Result<FolderMeta> {
let p = self.abs(id)?.join(FOLDER_META);
if p.exists() {
read_yaml(&p)
} else {
Ok(FolderMeta::default())
}
}
pub fn environment(&self, id: &str) -> Result<Environment> {
read_yaml(&self.root.join(ENV_DIR).join(format!("{id}.yaml")))
}
pub fn secrets_file(&self, env: &str) -> Result<SecretsFile> {
let p = self.root.join(ENV_DIR).join(format!("{env}.secrets.yaml"));
if p.exists() {
read_yaml(&p)
} else {
Ok(SecretsFile::default())
}
}
/// Folder chain from the root down to the folder that contains `id`,
/// root first. Used for auth, header and variable inheritance.
pub fn ancestors(&self, id: &str) -> Result<Vec<(String, FolderMeta)>> {
let mut out = Vec::new();
let parts: Vec<&str> = id.split('/').collect();
let mut cur = String::new();
for part in &parts[..parts.len().saturating_sub(1)] {
if !cur.is_empty() {
cur.push('/');
}
cur.push_str(part);
out.push((cur.clone(), self.folder_meta(&cur)?));
}
Ok(out)
}
pub fn find(&self, id: &str) -> Option<&Node> {
fn walk<'a>(f: &'a FolderNode, id: &str) -> Option<&'a Node> {
for c in &f.children {
if c.id() == id {
return Some(c);
}
if let Node::Folder(sub) = c {
if id.starts_with(&format!("{}/", sub.id)) {
return walk(sub, id);
}
}
}
None
}
walk(&self.tree, id)
}
/// All request ids below `folder` ("" = whole collection) in sidebar order.
pub fn requests_in(&self, folder: &str) -> Vec<String> {
fn walk(f: &FolderNode, out: &mut Vec<String>) {
for c in &f.children {
match c {
Node::Request(r) => out.push(r.id.clone()),
Node::Folder(sub) => walk(sub, out),
}
}
}
let mut out = Vec::new();
if folder.is_empty() {
walk(&self.tree, &mut out);
} else if let Some(Node::Folder(f)) = self.find(folder) {
walk(f, &mut out);
} else if let Some(Node::Request(r)) = self.find(folder) {
out.push(r.id.clone());
}
out
}
// ------------------------------------------------------------ writing
pub fn save_request(&self, id: &str, req: &Request) -> Result<()> {
write_yaml(&self.abs(id)?, req)
}
pub fn save_folder_meta(&self, id: &str, meta: &FolderMeta) -> Result<()> {
if id.is_empty() {
bail!("the collection root has no folder.yaml; edit the manifest instead");
}
write_yaml(&self.abs(id)?.join(FOLDER_META), meta)
}
pub fn save_manifest(&self, m: &Manifest) -> Result<()> {
write_yaml(&self.root.join(MANIFEST), m)
}
pub fn save_environment(&self, id: &str, env: &Environment) -> Result<()> {
check_slug(id)?;
write_yaml(&self.root.join(ENV_DIR).join(format!("{id}.yaml")), env)
}
pub fn save_secrets_file(&self, env: &str, s: &SecretsFile) -> Result<()> {
check_slug(env)?;
ensure_gitignore(&self.root)?;
write_yaml(&self.root.join(ENV_DIR).join(format!("{env}.secrets.yaml")), s)
}
pub fn delete_environment(&self, id: &str) -> Result<()> {
check_slug(id)?;
let dir = self.root.join(ENV_DIR);
fs::remove_file(dir.join(format!("{id}.yaml")))?;
let _ = fs::remove_file(dir.join(format!("{id}.secrets.yaml")));
Ok(())
}
/// Creates a request file in `folder` and returns its id.
pub fn create_request(&self, folder: &str, req: &Request) -> Result<String> {
let dir = self.abs(folder)?;
let suffix = match req.kind {
RequestKind::Ws => ".ws.yaml",
RequestKind::Graphql => ".gql.yaml",
RequestKind::Http => ".yaml",
};
let file = unique_name(&dir, &slugify(&req.name), suffix);
let id = join_id(folder, &file);
self.save_request(&id, req)?;
self.append_order(folder, &file)?;
Ok(id)
}
pub fn create_folder(&self, parent: &str, name: &str) -> Result<String> {
let dir = self.abs(parent)?;
let slug = unique_name(&dir, &slugify(name), "");
fs::create_dir_all(dir.join(&slug))?;
let id = join_id(parent, &slug);
let meta = FolderMeta {
name: Some(name.to_string()),
..Default::default()
};
self.save_folder_meta(&id, &meta)?;
self.append_order(parent, &slug)?;
Ok(id)
}
/// Renames the display name and the file or folder on disk. Returns the new id.
pub fn rename(&self, id: &str, new_name: &str) -> Result<String> {
let path = self.abs(id)?;
let (parent, old_file) = split_id(id);
let new_file;
if path.is_dir() {
let mut meta = self.folder_meta(id)?;
meta.name = Some(new_name.to_string());
self.save_folder_meta(id, &meta)?;
new_file = unique_name(&self.abs(parent)?, &slugify(new_name), "");
} else {
let mut req = self.request(id)?;
req.name = new_name.to_string();
self.save_request(id, &req)?;
let suffix = request_suffix(old_file);
let base = slugify(new_name);
if format!("{base}{suffix}") == old_file {
return Ok(id.to_string());
}
new_file = unique_name(&self.abs(parent)?, &base, suffix);
}
if new_file == old_file {
return Ok(id.to_string());
}
fs::rename(&path, self.abs(parent)?.join(&new_file))?;
self.replace_in_order(parent, old_file, &new_file)?;
Ok(join_id(parent, &new_file))
}
pub fn duplicate(&self, id: &str) -> Result<String> {
let mut req = self.request(id)?;
req.name = format!("{} copy", req.name);
let (parent, _) = split_id(id);
let dir = self.abs(parent)?;
let suffix = request_suffix(split_id(id).1);
let file = unique_name(&dir, &slugify(&req.name), suffix);
let new_id = join_id(parent, &file);
self.save_request(&new_id, &req)?;
self.insert_order_after(parent, split_id(id).1, &file)?;
Ok(new_id)
}
pub fn delete(&self, id: &str) -> Result<()> {
if id.is_empty() {
bail!("refusing to delete the collection root");
}
let path = self.abs(id)?;
if path.is_dir() {
fs::remove_dir_all(&path)?;
} else {
fs::remove_file(&path)?;
}
let (parent, file) = split_id(id);
self.remove_from_order(parent, file)
}
/// Moves a node into `target_folder` at `index` (None = end). Also used to
/// reorder within the same folder.
pub fn move_node(&self, id: &str, target_folder: &str, index: Option<usize>) -> Result<String> {
let (parent, file) = split_id(id);
if target_folder == id || target_folder.starts_with(&format!("{id}/")) {
bail!("cannot move a folder into itself");
}
let new_file = if parent == target_folder {
file.to_string()
} else {
let dir = self.abs(target_folder)?;
let new_file = if dir.join(file).exists() {
let suffix = request_suffix(file);
let base = file.strip_suffix(suffix).unwrap_or(file);
unique_name(&dir, base, suffix)
} else {
file.to_string()
};
fs::rename(self.abs(id)?, dir.join(&new_file))?;
self.remove_from_order(parent, file)?;
new_file
};
let mut order = self.effective_order(target_folder)?;
order.retain(|f| f != &new_file);
let at = index.unwrap_or(order.len()).min(order.len());
order.insert(at, new_file.clone());
self.set_order(target_folder, order)?;
Ok(join_id(target_folder, &new_file))
}
// ------------------------------------------------------------ ordering
/// Order as it is on disk right now, so earlier writes in the same
/// operation are taken into account.
fn effective_order(&self, folder: &str) -> Result<Vec<String>> {
let dir = self.abs(folder)?;
let stored = if folder.is_empty() {
read_yaml::<Manifest>(&self.root.join(MANIFEST))?.order
} else {
self.folder_meta(folder)?.order
};
let entries = list_entries(&dir)?;
Ok(apply_order(&stored, entries))
}
fn set_order(&self, folder: &str, order: Vec<String>) -> Result<()> {
if folder.is_empty() {
let mut m: Manifest = read_yaml(&self.root.join(MANIFEST))?;
m.order = order;
self.save_manifest(&m)
} else {
let mut meta = self.folder_meta(folder)?;
meta.order = order;
self.save_folder_meta(folder, &meta)
}
}
fn append_order(&self, folder: &str, file: &str) -> Result<()> {
let mut order = self.effective_order(folder)?;
if !order.iter().any(|f| f == file) {
order.push(file.to_string());
}
self.set_order(folder, order)
}
fn insert_order_after(&self, folder: &str, after: &str, file: &str) -> Result<()> {
let mut order = self.effective_order(folder)?;
order.retain(|f| f != file);
let at = order.iter().position(|f| f == after).map(|i| i + 1).unwrap_or(order.len());
order.insert(at, file.to_string());
self.set_order(folder, order)
}
fn replace_in_order(&self, folder: &str, old: &str, new: &str) -> Result<()> {
let stored = if folder.is_empty() {
read_yaml::<Manifest>(&self.root.join(MANIFEST))?.order
} else {
self.folder_meta(folder)?.order
};
if stored.is_empty() {
return Ok(());
}
let order = stored
.into_iter()
.map(|f| if f == old { new.to_string() } else { f })
.collect();
self.set_order(folder, order)
}
fn remove_from_order(&self, folder: &str, file: &str) -> Result<()> {
let stored = if folder.is_empty() {
read_yaml::<Manifest>(&self.root.join(MANIFEST))?.order
} else {
let p = self.abs(folder)?.join(FOLDER_META);
if !p.exists() {
return Ok(());
}
self.folder_meta(folder)?.order
};
if !stored.iter().any(|f| f == file) {
return Ok(());
}
self.set_order(folder, stored.into_iter().filter(|f| f != file).collect())
}
}
// ---------------------------------------------------------------- loading
fn load_folder(
root: &Path,
id: &str,
name: &str,
order: &[String],
problems: &mut Vec<Problem>,
) -> Result<FolderNode> {
let dir = if id.is_empty() { root.to_path_buf() } else { root.join(id) };
let entries = list_entries(&dir)?;
let ordered = apply_order(order, entries);
let mut children = Vec::with_capacity(ordered.len());
for file in ordered {
let child_id = join_id(id, &file);
let path = dir.join(&file);
if path.is_dir() {
let meta: FolderMeta = match path.join(FOLDER_META) {
p if p.exists() => match read_yaml(&p) {
Ok(m) => m,
Err(e) => {
problems.push(Problem {
path: format!("{child_id}/{FOLDER_META}"),
message: format!("{e:#}"),
});
FolderMeta::default()
}
},
_ => FolderMeta::default(),
};
let fname = meta.name.clone().unwrap_or_else(|| file.clone());
children.push(Node::Folder(load_folder(
root, &child_id, &fname, &meta.order, problems,
)?));
} else {
match read_yaml::<RequestHead>(&path) {
Ok(mut head) => {
head.id = child_id;
if head.name.is_empty() {
head.name = file.trim_end_matches(".yaml").to_string();
}
children.push(Node::Request(head));
}
Err(e) => problems.push(Problem {
path: child_id,
message: format!("{e:#}"),
}),
}
}
}
Ok(FolderNode {
id: id.to_string(),
name: name.to_string(),
children,
})
}
/// Request files and sub folders of a directory, unordered.
fn list_entries(dir: &Path) -> Result<Vec<String>> {
let mut out = Vec::new();
for e in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
let e = e?;
let name = e.file_name().to_string_lossy().to_string();
if name.starts_with('.') {
continue;
}
let ft = e.file_type()?;
if ft.is_dir() {
if name == ENV_DIR || name == "node_modules" || name == "target" {
continue;
}
out.push(name);
} else if (name.ends_with(".yaml") || name.ends_with(".yml"))
&& name != MANIFEST
&& name != FOLDER_META
{
out.push(name);
}
}
Ok(out)
}
/// Stored order first (skipping entries that no longer exist), then the rest
/// sorted by name.
fn apply_order(stored: &[String], mut entries: Vec<String>) -> Vec<String> {
let mut out = Vec::with_capacity(entries.len());
for s in stored {
if let Some(i) = entries.iter().position(|e| e == s) {
out.push(entries.swap_remove(i));
}
}
entries.sort_by_key(|a| a.to_lowercase());
out.extend(entries);
out
}
fn load_env_list(root: &Path) -> Result<Vec<EnvEntry>> {
let dir = root.join(ENV_DIR);
let mut out = Vec::new();
if !dir.exists() {
return Ok(out);
}
for e in fs::read_dir(&dir)? {
let e = e?;
let name = e.file_name().to_string_lossy().to_string();
let Some(id) = name.strip_suffix(".yaml") else { continue };
if id.ends_with(".secrets") {
continue;
}
let env: Environment = read_yaml(&e.path()).unwrap_or_default();
out.push(EnvEntry {
id: id.to_string(),
name: env.name.unwrap_or_else(|| id.to_string()),
color: env.color,
protected: env.protected,
});
}
out.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
Ok(out)
}
// ---------------------------------------------------------------- helpers
pub fn read_yaml<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T> {
let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
serde_yaml_ng::from_str(&text).with_context(|| format!("parsing {}", path.display()))
}
/// Writes atomically (temp file + rename) so a crash never leaves half a file
/// and file watchers see one change.
pub fn write_yaml<T: Serialize>(path: &Path, value: &T) -> Result<()> {
let text = serde_yaml_ng::to_string(value)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
if fs::read_to_string(path).ok().as_deref() == Some(text.as_str()) {
return Ok(());
}
let tmp = path.with_extension("yaml.tmp");
fs::write(&tmp, text)?;
fs::rename(&tmp, path)?;
Ok(())
}
fn ensure_gitignore(root: &Path) -> Result<()> {
let p = root.join(".gitignore");
let line = "*.secrets.yaml";
let cur = fs::read_to_string(&p).unwrap_or_default();
if !cur.lines().any(|l| l.trim() == line) {
let mut next = cur;
if !next.is_empty() && !next.ends_with('\n') {
next.push('\n');
}
next.push_str(line);
next.push('\n');
fs::write(&p, next)?;
}
Ok(())
}
/// Joins `id` onto `root` and refuses anything that would leave it.
pub fn resolve_inside(root: &Path, id: &str) -> Result<PathBuf> {
let rel = Path::new(id);
for c in rel.components() {
match c {
Component::Normal(_) | Component::CurDir => {}
_ => return Err(anyhow!("invalid path '{id}'")),
}
}
Ok(root.join(rel))
}
fn check_slug(s: &str) -> Result<()> {
if s.is_empty() || s.contains(['/', '\\']) || s.starts_with('.') {
bail!("invalid name '{s}'");
}
Ok(())
}
pub fn join_id(parent: &str, file: &str) -> String {
if parent.is_empty() {
file.to_string()
} else {
format!("{parent}/{file}")
}
}
pub fn split_id(id: &str) -> (&str, &str) {
match id.rfind('/') {
Some(i) => (&id[..i], &id[i + 1..]),
None => ("", id),
}
}
fn request_suffix(file: &str) -> &'static str {
if file.ends_with(".ws.yaml") {
".ws.yaml"
} else if file.ends_with(".gql.yaml") {
".gql.yaml"
} else if file.ends_with(".yml") {
".yml"
} else {
".yaml"
}
}
pub fn slugify(name: &str) -> String {
let mut out = String::new();
let mut dash = false;
for ch in name.trim().chars() {
let c = match ch {
'ä' | 'Ä' => Some("ae"),
'ö' | 'Ö' => Some("oe"),
'ü' | 'Ü' => Some("ue"),
'ß' => Some("ss"),
_ => None,
};
if let Some(rep) = c {
out.push_str(rep);
dash = false;
} else if ch.is_ascii_alphanumeric() {
out.push(ch.to_ascii_lowercase());
dash = false;
} else if !dash && !out.is_empty() {
out.push('-');
dash = true;
}
}
let out = out.trim_end_matches('-').to_string();
if out.is_empty() {
"untitled".into()
} else {
out
}
}
fn unique_name(dir: &Path, base: &str, suffix: &str) -> String {
let first = format!("{base}{suffix}");
if !dir.join(&first).exists() {
return first;
}
(2..)
.map(|n| format!("{base}-{n}{suffix}"))
.find(|n| !dir.join(n).exists())
.unwrap()
}
#[cfg(test)]
mod tests {
use super::*;
fn tmp() -> PathBuf {
let p = std::env::temp_dir().join(format!("knock-test-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&p).unwrap();
p
}
#[test]
fn create_load_and_order() {
let dir = tmp();
let c = Collection::create(&dir, "My API").unwrap();
assert!(fs::read_to_string(dir.join(".gitignore")).unwrap().contains("*.secrets.yaml"));
let users = c.create_folder("", "Users").unwrap();
let mut r = Request::default();
r.name = "List users".into();
let a = c.create_request(&users, &r).unwrap();
r.name = "Create user".into();
let b = c.create_request(&users, &r).unwrap();
assert_eq!(a, "users/list-users.yaml");
let c = Collection::open(&dir).unwrap();
assert_eq!(c.requests_in("users"), vec![a.clone(), b.clone()]);
assert_eq!(c.environments[0].id, "local");
// move b before a
c.move_node(&b, "users", Some(0)).unwrap();
let c = Collection::open(&dir).unwrap();
assert_eq!(c.requests_in(""), vec![b.clone(), a.clone()]);
let renamed = c.rename(&a, "All users").unwrap();
assert_eq!(renamed, "users/all-users.yaml");
let c = Collection::open(&dir).unwrap();
assert_eq!(c.requests_in(""), vec![b.clone(), renamed.clone()]);
let dup = c.duplicate(&b).unwrap();
let c = Collection::open(&dir).unwrap();
assert_eq!(c.requests_in(""), vec![b.clone(), dup.clone(), renamed.clone()]);
let moved = c.move_node(&dup, "", None).unwrap();
let c = Collection::open(&dir).unwrap();
assert_eq!(c.requests_in(""), vec![b.clone(), renamed.clone(), moved.clone()]);
c.delete(&moved).unwrap();
let c = Collection::open(&dir).unwrap();
assert_eq!(c.requests_in("").len(), 2);
assert!(c.move_node("users", "users", None).is_err());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn rejects_escaping_paths() {
let root = Path::new("/tmp/x");
assert!(resolve_inside(root, "../etc/passwd").is_err());
assert!(resolve_inside(root, "/etc/passwd").is_err());
assert!(resolve_inside(root, "a/b.yaml").is_ok());
}
#[test]
fn slugs() {
assert_eq!(slugify("Create user"), "create-user");
assert_eq!(slugify(" Größe / Übersicht!! "), "groesse-uebersicht");
assert_eq!(slugify("///"), "untitled");
}
}
+492
View File
@@ -0,0 +1,492 @@
//! The HTTP engine. Redirects are followed by hand so every hop is visible,
//! cookies are kept in a per-collection jar we can show and edit.
use crate::model::{HttpVersion, ProxyMode};
use crate::prepare::{Prepared, PreparedBody};
use anyhow::{anyhow, Context, Result};
use cookie_store::CookieStore;
use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::Write;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
/// Bodies above this size go to a file instead of memory.
pub const MEMORY_LIMIT: usize = 50 * 1024 * 1024;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Timings {
/// Time until the response headers arrived, summed over all hops.
pub ttfb_ms: f64,
pub download_ms: f64,
pub total_ms: f64,
pub redirect_ms: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Hop {
pub method: String,
pub url: String,
pub status: u16,
pub location: String,
pub headers: Vec<(String, String)>,
pub ms: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CookieInfo {
pub name: String,
pub value: String,
pub domain: String,
pub path: String,
pub expires: Option<String>,
pub secure: bool,
pub http_only: bool,
pub same_site: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Response {
pub status: u16,
pub status_text: String,
pub http_version: String,
pub url: String,
pub headers: Vec<(String, String)>,
/// Cookies set by this response (all hops).
pub cookies: Vec<CookieInfo>,
pub size: u64,
pub header_size: u64,
pub content_type: Option<String>,
pub timings: Timings,
pub redirects: Vec<Hop>,
pub remote_addr: Option<String>,
/// Set when the body was larger than [`MEMORY_LIMIT`] and went to disk.
pub body_file: Option<PathBuf>,
#[serde(skip)]
pub body: Vec<u8>,
}
impl Response {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
pub fn json(&self) -> Option<serde_json::Value> {
serde_json::from_slice(&self.body).ok()
}
}
#[derive(Debug, Clone, Default)]
pub struct TransportOptions {
pub proxy_mode: ProxyMode,
pub proxy_url: Option<String>,
pub no_proxy: Option<String>,
pub ca_bundle: Option<PathBuf>,
/// PEM with certificate and key, presented to the request's host.
pub identity_pem: Option<Vec<u8>>,
}
#[derive(Hash, PartialEq, Eq, Clone)]
struct ClientKey {
verify: bool,
version: u8,
proxy: String,
ca: Option<PathBuf>,
identity: Option<u64>,
}
pub struct Engine {
clients: Mutex<HashMap<ClientKey, reqwest::Client>>,
jars: Mutex<HashMap<String, Arc<Mutex<CookieStore>>>>,
spill_dir: PathBuf,
}
impl Engine {
pub fn new(spill_dir: PathBuf) -> Self {
Self {
clients: Mutex::default(),
jars: Mutex::default(),
spill_dir,
}
}
pub fn jar(&self, collection: &str) -> Arc<Mutex<CookieStore>> {
self.jars
.lock()
.unwrap()
.entry(collection.to_string())
.or_insert_with(|| Arc::new(Mutex::new(CookieStore::default())))
.clone()
}
pub fn load_jar(&self, collection: &str, json: &str) {
#[allow(deprecated)]
if let Ok(store) = CookieStore::load_json(json.as_bytes()) {
*self.jar(collection).lock().unwrap() = store;
}
}
pub fn save_jar(&self, collection: &str) -> String {
let jar = self.jar(collection);
let store = jar.lock().unwrap();
let mut buf = Vec::new();
#[allow(deprecated)]
let _ = store.save_json(&mut buf);
String::from_utf8(buf).unwrap_or_default()
}
pub fn cookies(&self, collection: &str) -> Vec<CookieInfo> {
let jar = self.jar(collection);
let store = jar.lock().unwrap();
store.iter_unexpired().map(cookie_info).collect()
}
pub fn delete_cookie(&self, collection: &str, domain: &str, path: &str, name: &str) {
let jar = self.jar(collection);
jar.lock().unwrap().remove(domain, path, name);
}
pub fn clear_cookies(&self, collection: &str) {
self.jar(collection).lock().unwrap().clear();
}
fn client(&self, p: &Prepared, t: &TransportOptions) -> Result<reqwest::Client> {
let version = match p.settings.http_version {
HttpVersion::Auto => 0,
HttpVersion::Http1 => 1,
HttpVersion::Http2 => 2,
};
let key = ClientKey {
verify: p.settings.verify_tls,
version,
proxy: format!("{:?}|{:?}|{:?}", t.proxy_mode, t.proxy_url, t.no_proxy),
ca: t.ca_bundle.clone(),
identity: t.identity_pem.as_ref().map(|b| {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
b.hash(&mut h);
h.finish()
}),
};
if let Some(c) = self.clients.lock().unwrap().get(&key) {
return Ok(c.clone());
}
let mut b = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.user_agent(concat!("knock/", env!("CARGO_PKG_VERSION")))
.tls_danger_accept_invalid_certs(!p.settings.verify_tls)
.connect_timeout(Duration::from_secs(30));
b = match version {
1 => b.http1_only(),
2 => b.http2_prior_knowledge(),
_ => b,
};
b = match t.proxy_mode {
ProxyMode::System => b,
ProxyMode::None => b.no_proxy(),
ProxyMode::Custom => {
let url = t.proxy_url.as_deref().ok_or_else(|| anyhow!("custom proxy has no URL"))?;
let mut proxy = reqwest::Proxy::all(url).context("invalid proxy URL")?;
if let Some(np) = &t.no_proxy {
proxy = proxy.no_proxy(reqwest::NoProxy::from_string(np));
}
b.proxy(proxy)
}
};
if let Some(ca) = &t.ca_bundle {
let pem = std::fs::read(ca).with_context(|| format!("reading CA bundle {}", ca.display()))?;
for cert in reqwest::Certificate::from_pem_bundle(&pem).context("CA bundle is not valid PEM")? {
b = b.tls_certs_merge([cert]);
}
}
if let Some(pem) = &t.identity_pem {
b = b.identity(reqwest::Identity::from_pem(pem).context("client certificate is not valid PEM")?);
}
let client = b.build()?;
self.clients.lock().unwrap().insert(key, client.clone());
Ok(client)
}
/// Sends a prepared request, following redirects according to its settings.
pub async fn send(
&self,
p: &Prepared,
transport: &TransportOptions,
jar_id: Option<&str>,
) -> Result<Response> {
let client = self.client(p, transport)?;
let jar = jar_id.filter(|_| p.settings.cookies).map(|id| self.jar(id));
let started = Instant::now();
let mut method = p.method.clone();
let mut url = url::Url::parse(&p.url)?;
let mut headers = p.headers.clone();
let mut body = Some(p.body.clone());
let mut hops = Vec::new();
let mut cookies = Vec::new();
let mut ttfb = 0.0;
let original_origin = url.origin();
loop {
let hop_start = Instant::now();
let m = reqwest::Method::from_bytes(method.as_bytes())
.map_err(|_| anyhow!("invalid method '{method}'"))?;
let mut rb = client
.request(m, url.clone())
.timeout(Duration::from_millis(p.settings.timeout_ms.max(1)));
let mut cookie_header: Option<String> = None;
for (k, v) in &headers {
if k.eq_ignore_ascii_case("cookie") {
cookie_header = Some(match cookie_header {
Some(c) => format!("{c}; {v}"),
None => v.clone(),
});
} else {
rb = rb.header(k, v);
}
}
if let Some(jar) = &jar {
let store = jar.lock().unwrap();
let from_jar: Vec<String> = store
.get_request_values(&url)
.map(|(n, v)| format!("{n}={v}"))
.collect();
if !from_jar.is_empty() {
let jar_str = from_jar.join("; ");
cookie_header = Some(match cookie_header {
Some(c) => format!("{c}; {jar_str}"),
None => jar_str,
});
}
}
if let Some(c) = cookie_header {
rb = rb.header("Cookie", c);
}
rb = match body.as_ref() {
Some(PreparedBody::Bytes { data, .. }) => rb.body(data.clone()),
Some(PreparedBody::Multipart { parts }) => rb.multipart(build_multipart(parts).await?),
_ => rb,
};
let resp = rb.send().await.map_err(describe_error)?;
ttfb += hop_start.elapsed().as_secs_f64() * 1000.0;
let status = resp.status();
let resp_headers: Vec<(String, String)> = resp
.headers()
.iter()
.map(|(k, v)| (k.to_string(), String::from_utf8_lossy(v.as_bytes()).into_owned()))
.collect();
let set_cookies: Vec<&str> = resp_headers
.iter()
.filter(|(k, _)| k.eq_ignore_ascii_case("set-cookie"))
.map(|(_, v)| v.as_str())
.collect();
for sc in &set_cookies {
if let Ok(c) = cookie_store::RawCookie::parse(sc.to_string()) {
cookies.push(raw_cookie_info(&c, &url));
}
}
if let Some(jar) = &jar {
let parsed = set_cookies
.iter()
.filter_map(|s| cookie_store::RawCookie::parse(s.to_string()).ok());
jar.lock().unwrap().store_response_cookies(parsed, &url);
}
let location = resp
.headers()
.get(reqwest::header::LOCATION)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
if status.is_redirection()
&& p.settings.follow_redirects
&& location.is_some()
&& (hops.len() as u32) < p.settings.max_redirects
{
let loc = location.unwrap();
let next = url.join(&loc).with_context(|| format!("bad Location header '{loc}'"))?;
hops.push(Hop {
method: method.clone(),
url: url.to_string(),
status: status.as_u16(),
location: next.to_string(),
headers: resp_headers,
ms: hop_start.elapsed().as_secs_f64() * 1000.0,
});
let code = status.as_u16();
if code == 303 || ((code == 301 || code == 302) && method == "POST") {
if method != "HEAD" {
method = "GET".into();
}
body = None;
headers.retain(|(k, _)| {
!k.eq_ignore_ascii_case("content-type") && !k.eq_ignore_ascii_case("content-length")
});
}
if next.origin() != original_origin {
// Same rule as curl: credentials never follow to another host.
headers.retain(|(k, _)| {
!k.eq_ignore_ascii_case("authorization") && !k.eq_ignore_ascii_case("cookie")
});
}
url = next;
// Drain so the connection can be reused.
let _ = resp.bytes().await;
continue;
}
let redirect_ms: f64 = hops.iter().map(|h| h.ms).sum();
let http_version = format!("{:?}", resp.version()).replace("HTTP/", "");
let remote_addr = resp.remote_addr().map(|a| a.to_string());
let final_url = resp.url().to_string();
let content_type = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.map(str::to_string);
let header_size: u64 = resp_headers.iter().map(|(k, v)| (k.len() + v.len() + 4) as u64).sum();
let status_text = status.canonical_reason().unwrap_or("").to_string();
let dl_start = Instant::now();
let (body, body_file, size) = self.read_body(resp).await?;
let download_ms = dl_start.elapsed().as_secs_f64() * 1000.0;
return Ok(Response {
status: status.as_u16(),
status_text,
http_version,
url: final_url,
headers: resp_headers,
cookies,
size,
header_size,
content_type,
timings: Timings {
ttfb_ms: ttfb,
download_ms,
total_ms: started.elapsed().as_secs_f64() * 1000.0,
redirect_ms,
},
redirects: hops,
remote_addr,
body_file,
body,
});
}
}
async fn read_body(&self, resp: reqwest::Response) -> Result<(Vec<u8>, Option<PathBuf>, u64)> {
let mut stream = resp.bytes_stream();
let mut buf: Vec<u8> = Vec::new();
let mut file: Option<(std::fs::File, PathBuf)> = None;
let mut size = 0u64;
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(describe_error)?;
size += chunk.len() as u64;
if let Some((f, _)) = file.as_mut() {
f.write_all(&chunk)?;
continue;
}
if buf.len() + chunk.len() > MEMORY_LIMIT {
std::fs::create_dir_all(&self.spill_dir)?;
let path = self.spill_dir.join(format!("response-{}.bin", uuid::Uuid::new_v4()));
let mut f = std::fs::File::create(&path)?;
f.write_all(&buf)?;
f.write_all(&chunk)?;
// Keep the first MB in memory for the preview.
buf.truncate(1024 * 1024);
file = Some((f, path));
continue;
}
buf.extend_from_slice(&chunk);
}
Ok((buf, file.map(|(_, p)| p), size))
}
}
async fn build_multipart(parts: &[crate::prepare::PreparedPart]) -> Result<reqwest::multipart::Form> {
let mut form = reqwest::multipart::Form::new();
for p in parts {
let part = if let Some(path) = &p.file {
let data = tokio::fs::read(path)
.await
.with_context(|| format!("reading {}", path.display()))?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
reqwest::multipart::Part::bytes(data).file_name(name)
} else {
reqwest::multipart::Part::text(p.value.clone().unwrap_or_default())
};
let part = match &p.content_type {
Some(ct) => part.mime_str(ct)?,
None => part,
};
form = form.part(p.name.clone(), part);
}
Ok(form)
}
/// reqwest errors hide the interesting part in the source chain.
fn describe_error(e: reqwest::Error) -> anyhow::Error {
let mut msg = if e.is_timeout() {
"request timed out".to_string()
} else if e.is_connect() {
"could not connect".to_string()
} else {
"request failed".to_string()
};
let mut src: Option<&dyn std::error::Error> = std::error::Error::source(&e);
let mut seen = Vec::new();
while let Some(s) = src {
let t = s.to_string();
if !seen.contains(&t) {
msg.push_str(": ");
msg.push_str(&t);
seen.push(t);
}
src = s.source();
}
anyhow!(msg)
}
fn cookie_info(c: &cookie_store::Cookie<'_>) -> CookieInfo {
CookieInfo {
name: c.name().to_string(),
value: c.value().to_string(),
domain: match &c.domain {
cookie_store::CookieDomain::HostOnly(d) | cookie_store::CookieDomain::Suffix(d) => d.clone(),
_ => String::new(),
},
path: String::from(c.path.as_ref()),
expires: match c.expires {
cookie_store::CookieExpiration::AtUtc(t) => Some(t.to_string()),
_ => None,
},
secure: c.secure().unwrap_or(false),
http_only: c.http_only().unwrap_or(false),
same_site: c.same_site().map(|s| s.to_string()),
}
}
fn raw_cookie_info(c: &cookie_store::RawCookie<'_>, url: &url::Url) -> CookieInfo {
CookieInfo {
name: c.name().to_string(),
value: c.value().to_string(),
domain: c.domain().map(str::to_string).unwrap_or_else(|| url.host_str().unwrap_or("").to_string()),
path: c.path().unwrap_or("/").to_string(),
expires: c
.expires_datetime()
.map(|t| t.to_string())
.or_else(|| c.max_age().map(|a| format!("max-age {}s", a.whole_seconds()))),
secure: c.secure().unwrap_or(false),
http_only: c.http_only().unwrap_or(false),
same_site: c.same_site().map(|s| s.to_string()),
}
}
+11
View File
@@ -0,0 +1,11 @@
pub mod auth;
pub mod checks;
pub mod collection;
pub mod http;
pub mod model;
pub mod prepare;
pub mod run;
pub mod secrets;
pub mod vars;
pub use collection::Collection;
+693
View File
@@ -0,0 +1,693 @@
//! On-disk data model. Every struct keeps unknown keys in `extra` so a file
//! written by a newer knock survives a round trip through an older one.
use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_yaml_ng::Value as Yaml;
pub type Extra = IndexMap<String, Yaml>;
pub const FORMAT_VERSION: u32 = 1;
fn is_true(b: &bool) -> bool {
*b
}
fn is_false(b: &bool) -> bool {
!*b
}
fn yes() -> bool {
true
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct KeyValue {
pub name: String,
#[serde(default)]
pub value: String,
#[serde(default = "yes", skip_serializing_if = "is_true")]
pub enabled: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(flatten)]
pub extra: Extra,
}
impl KeyValue {
pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
Self {
name: name.into(),
value: value.into(),
enabled: true,
..Default::default()
}
}
}
// ---------------------------------------------------------------- manifest
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Manifest {
#[serde(default = "format_version")]
pub version: u32,
pub name: String,
/// Stable id used to key secrets and tokens in the keyring.
#[serde(default)]
pub id: String,
#[serde(default, skip_serializing_if = "Auth::is_none_or_inherit")]
pub auth: Auth,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub headers: Vec<KeyValue>,
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
pub vars: IndexMap<String, String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub order: Vec<String>,
#[serde(default, skip_serializing_if = "CollectionSettings::is_default")]
pub settings: CollectionSettings,
#[serde(flatten)]
pub extra: Extra,
}
fn format_version() -> u32 {
FORMAT_VERSION
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct CollectionSettings {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub proxy: Option<ProxySettings>,
/// Extra CA bundle (PEM) trusted for every request in this collection.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ca_bundle: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub client_certs: Vec<ClientCert>,
#[serde(default = "yes", skip_serializing_if = "is_true")]
pub cookies: bool,
#[serde(flatten)]
pub extra: Extra,
}
impl CollectionSettings {
fn is_default(&self) -> bool {
self.proxy.is_none()
&& self.ca_bundle.is_none()
&& self.client_certs.is_empty()
&& self.cookies
&& self.extra.is_empty()
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ProxySettings {
/// `system` honours HTTP(S)_PROXY / NO_PROXY, `none` disables, `custom` uses `url`.
#[serde(default)]
pub mode: ProxyMode,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub no_proxy: Option<String>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProxyMode {
#[default]
System,
None,
Custom,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ClientCert {
/// Host (optionally with port) the certificate is presented to.
pub host: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cert: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pkcs12: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub passphrase: Option<String>,
}
// ---------------------------------------------------------------- folder
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FolderMeta {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub order: Vec<String>,
#[serde(default, skip_serializing_if = "Auth::is_inherit")]
pub auth: Auth,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub headers: Vec<KeyValue>,
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
pub vars: IndexMap<String, String>,
#[serde(flatten)]
pub extra: Extra,
}
// ---------------------------------------------------------------- request
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RequestKind {
#[default]
Http,
Graphql,
Ws,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
pub name: String,
#[serde(rename = "type", default)]
pub kind: RequestKind,
#[serde(default = "default_method", skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
#[serde(default)]
pub url: String,
#[serde(default, skip_serializing_if = "Params::is_empty")]
pub params: Params,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub headers: Vec<KeyValue>,
#[serde(default)]
pub auth: Auth,
#[serde(default, skip_serializing_if = "Body::is_none")]
pub body: Body,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub graphql: Option<GraphqlSpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ws: Option<WsSpec>,
#[serde(default, skip_serializing_if = "IndexMap::is_empty")]
pub vars: IndexMap<String, String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extract: Vec<ExtractRule>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub assert: Vec<AssertRule>,
#[serde(default, skip_serializing_if = "RequestSettings::is_default")]
pub settings: RequestSettings,
/// JSON Schema (inline or `$ref` to a file / OpenAPI pointer) describing the body.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub docs: Option<String>,
#[serde(flatten)]
pub extra: Extra,
}
fn default_method() -> Option<String> {
Some("GET".into())
}
impl Default for Request {
fn default() -> Self {
Self {
name: "New request".into(),
kind: RequestKind::Http,
method: default_method(),
url: String::new(),
params: Params::default(),
headers: Vec::new(),
auth: Auth::Inherit,
body: Body::default(),
graphql: None,
ws: None,
vars: IndexMap::new(),
extract: Vec::new(),
assert: Vec::new(),
settings: RequestSettings::default(),
schema: None,
docs: None,
extra: Extra::new(),
}
}
}
impl Request {
pub fn method(&self) -> &str {
self.method.as_deref().unwrap_or("GET")
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Params {
#[serde(default)]
pub query: Vec<KeyValue>,
#[serde(default)]
pub path: IndexMap<String, String>,
}
impl Params {
fn is_empty(&self) -> bool {
self.query.is_empty() && self.path.is_empty()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum BodyType {
#[default]
None,
Json,
Raw,
#[serde(rename = "form")]
FormUrlencoded,
Multipart,
Binary,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Body {
#[serde(rename = "type", default)]
pub kind: BodyType,
/// Text content for json and raw bodies.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub content: String,
/// Content type for raw bodies, e.g. `application/xml`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
/// Comments are allowed and stripped before sending.
#[serde(default, skip_serializing_if = "is_false")]
pub jsonc: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub form: Vec<KeyValue>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub multipart: Vec<MultipartPart>,
/// File path for binary bodies, relative to the collection root.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<String>,
}
impl Body {
fn is_none(&self) -> bool {
self.kind == BodyType::None && self.content.is_empty()
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct MultipartPart {
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub value: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
#[serde(default = "yes", skip_serializing_if = "is_true")]
pub enabled: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct GraphqlSpec {
#[serde(default)]
pub query: String,
/// JSON text, edited with the same JSON editor as bodies.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub variables: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub operation_name: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct WsSpec {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub subprotocols: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub messages: Vec<WsSavedMessage>,
#[serde(default, skip_serializing_if = "is_false")]
pub auto_reconnect: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct WsSavedMessage {
pub name: String,
#[serde(default)]
pub format: WsFormat,
#[serde(default)]
pub content: String,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WsFormat {
#[default]
Text,
Json,
Hex,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum HttpVersion {
#[default]
#[serde(rename = "auto")]
Auto,
#[serde(rename = "1.1")]
Http1,
#[serde(rename = "2")]
Http2,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RequestSettings {
#[serde(default = "default_timeout")]
pub timeout_ms: u64,
#[serde(default = "yes")]
pub follow_redirects: bool,
#[serde(default = "default_max_redirects")]
pub max_redirects: u32,
#[serde(default = "yes")]
pub verify_tls: bool,
#[serde(default)]
pub http_version: HttpVersion,
#[serde(default = "yes")]
pub cookies: bool,
/// Retry once after a 401 when an OAuth token could be refreshed.
#[serde(default = "yes")]
pub retry_on_401: bool,
}
fn default_timeout() -> u64 {
30_000
}
fn default_max_redirects() -> u32 {
10
}
impl Default for RequestSettings {
fn default() -> Self {
Self {
timeout_ms: default_timeout(),
follow_redirects: true,
max_redirects: default_max_redirects(),
verify_tls: true,
http_version: HttpVersion::Auto,
cookies: true,
retry_on_401: true,
}
}
}
impl RequestSettings {
fn is_default(&self) -> bool {
*self == Self::default()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExtractSource {
#[default]
Json,
Header,
Cookie,
Regex,
Status,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ExtractRule {
pub var: String,
#[serde(default)]
pub from: ExtractSource,
/// JSONPath, header name, cookie name or regex, depending on `from`.
#[serde(default)]
pub path: String,
#[serde(default = "yes", skip_serializing_if = "is_true")]
pub enabled: bool,
/// Keep the value after the session ends.
#[serde(default, skip_serializing_if = "is_false")]
pub persist: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AssertTarget {
#[default]
Status,
Header,
Time,
Json,
Size,
Body,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AssertRule {
pub on: AssertTarget,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub equals: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_equals: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub contains: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exists: Option<bool>,
#[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
pub type_is: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub matches: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gt: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lt: Option<f64>,
#[serde(default = "yes", skip_serializing_if = "is_true")]
pub enabled: bool,
}
// ---------------------------------------------------------------- auth
/// Auth is `inherit`, `none`, or a map with a `type` key. The map form keeps
/// its fields loosely typed so the UI can round-trip anything it does not know.
#[derive(Debug, Clone, Default, PartialEq)]
pub enum Auth {
#[default]
Inherit,
None,
Config(AuthConfig),
}
impl Auth {
pub fn is_inherit(&self) -> bool {
matches!(self, Auth::Inherit)
}
pub fn is_none_or_inherit(&self) -> bool {
matches!(self, Auth::Inherit | Auth::None)
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AuthConfig {
#[serde(rename = "type")]
pub kind: String,
#[serde(flatten)]
pub fields: IndexMap<String, serde_json::Value>,
}
impl AuthConfig {
pub fn str(&self, key: &str) -> Option<&str> {
self.fields.get(key).and_then(|v| v.as_str())
}
pub fn string(&self, key: &str) -> String {
self.str(key).unwrap_or_default().to_string()
}
pub fn bool(&self, key: &str, default: bool) -> bool {
self.fields.get(key).and_then(|v| v.as_bool()).unwrap_or(default)
}
}
impl Serialize for Auth {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Auth::Inherit => s.serialize_str("inherit"),
Auth::None => s.serialize_str("none"),
Auth::Config(c) => c.serialize(s),
}
}
}
impl<'de> Deserialize<'de> for Auth {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let v = serde_json::Value::deserialize(d)?;
match v {
serde_json::Value::Null => Ok(Auth::Inherit),
serde_json::Value::String(s) => match s.as_str() {
"inherit" => Ok(Auth::Inherit),
"none" => Ok(Auth::None),
other => Ok(Auth::Config(AuthConfig {
kind: other.to_string(),
fields: IndexMap::new(),
})),
},
serde_json::Value::Object(_) => {
let c: AuthConfig =
serde_json::from_value(v).map_err(serde::de::Error::custom)?;
match c.kind.as_str() {
"inherit" => Ok(Auth::Inherit),
"none" => Ok(Auth::None),
_ => Ok(Auth::Config(c)),
}
}
_ => Err(serde::de::Error::custom("auth must be a string or a map")),
}
}
}
// ---------------------------------------------------------------- environment
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Environment {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<String>,
/// Shows the "you are sending to prod" banner and confirms destructive methods.
#[serde(default, skip_serializing_if = "is_false")]
pub protected: bool,
#[serde(default)]
pub vars: IndexMap<String, EnvVar>,
#[serde(flatten)]
pub extra: Extra,
}
/// `key: value` or `key: { value, secret: true }`. Secret values never live
/// here; the file only marks the variable as secret.
#[derive(Debug, Clone, PartialEq)]
pub struct EnvVar {
pub value: String,
pub secret: bool,
pub description: Option<String>,
}
impl Serialize for EnvVar {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
if !self.secret && self.description.is_none() {
return s.serialize_str(&self.value);
}
let mut m = s.serialize_map(None)?;
if !self.secret {
m.serialize_entry("value", &self.value)?;
}
if self.secret {
m.serialize_entry("secret", &true)?;
}
if let Some(d) = &self.description {
m.serialize_entry("description", d)?;
}
m.end()
}
}
impl<'de> Deserialize<'de> for EnvVar {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let v = serde_json::Value::deserialize(d)?;
Ok(match v {
serde_json::Value::Object(m) => EnvVar {
value: m.get("value").map(scalar_to_string).unwrap_or_default(),
secret: m.get("secret").and_then(|v| v.as_bool()).unwrap_or(false),
description: m
.get("description")
.and_then(|v| v.as_str())
.map(str::to_string),
},
other => EnvVar {
value: scalar_to_string(&other),
secret: false,
description: None,
},
})
}
}
pub fn scalar_to_string(v: &serde_json::Value) -> String {
match v {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::Null => String::new(),
other => other.to_string(),
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SecretsFile {
#[serde(default)]
pub vars: IndexMap<String, String>,
}
#[cfg(test)]
mod tests {
use super::*;
const SAMPLE: &str = r#"
name: Create user
type: http
method: POST
url: "{{baseUrl}}/users"
params:
query: []
path: {}
headers:
- { name: Accept, value: application/json }
auth: inherit
body:
type: json
content: |
{
"name": "{{userName}}",
"roles": ["admin"]
}
extract:
- { var: userId, from: json, path: $.id }
assert:
- { on: status, equals: 201 }
futureField:
nested: true
"#;
#[test]
fn parses_spec_example_and_keeps_unknown_fields() {
let r: Request = serde_yaml_ng::from_str(SAMPLE).unwrap();
assert_eq!(r.method(), "POST");
assert_eq!(r.body.kind, BodyType::Json);
assert!(r.body.content.contains("\"roles\""));
assert_eq!(r.extract[0].path, "$.id");
assert_eq!(r.assert[0].equals, Some(serde_json::json!(201)));
assert!(r.extra.contains_key("futureField"));
let out = serde_yaml_ng::to_string(&r).unwrap();
assert!(out.contains("futureField"));
assert!(out.contains("content: |"), "body should stay a block scalar:\n{out}");
let again: Request = serde_yaml_ng::from_str(&out).unwrap();
assert_eq!(again.body, r.body);
}
#[test]
fn auth_forms() {
let a: Auth = serde_yaml_ng::from_str("none").unwrap();
assert_eq!(a, Auth::None);
let a: Auth = serde_yaml_ng::from_str("{ type: bearer, token: '{{secret.t}}' }").unwrap();
match a {
Auth::Config(c) => {
assert_eq!(c.kind, "bearer");
assert_eq!(c.str("token"), Some("{{secret.t}}"));
}
_ => panic!(),
}
}
#[test]
fn env_vars() {
let e: Environment = serde_yaml_ng::from_str(
"vars:\n baseUrl: http://x\n port: 8080\n token: { secret: true }\n",
)
.unwrap();
assert_eq!(e.vars["port"].value, "8080");
assert!(e.vars["token"].secret);
let out = serde_yaml_ng::to_string(&e).unwrap();
assert!(out.contains("baseUrl: http://x"));
assert!(out.contains("secret: true"));
}
}
+567
View File
@@ -0,0 +1,567 @@
//! Turns a stored request plus its context into a concrete, fully resolved
//! request. Nothing here touches the network.
use crate::collection::Collection;
use crate::model::*;
use crate::vars::{Layer, OauthLookup, Resolver, Scope, SecretLookup};
use anyhow::{bail, Context, Result};
use indexmap::IndexMap;
use serde::Serialize;
use std::path::PathBuf;
use std::sync::Arc;
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AuthOrigin {
Request,
Folder,
Collection,
}
#[derive(Debug, Clone, Serialize)]
pub struct EffectiveAuth {
pub auth: Auth,
pub origin: AuthOrigin,
/// Folder id or request id the auth was defined on.
pub source: String,
}
/// Everything needed to resolve and send one request of a collection.
pub struct RequestContext {
pub resolver: Resolver,
pub auth: EffectiveAuth,
/// Inherited headers, collection first, then folders, root to leaf.
pub inherited_headers: Vec<KeyValue>,
pub root: PathBuf,
pub collection_settings: CollectionSettings,
pub collection_id: String,
pub env: Option<String>,
}
pub struct ContextInput<'a> {
pub collection: &'a Collection,
pub request_id: &'a str,
pub request: &'a Request,
pub env: Option<&'a str>,
pub runtime: IndexMap<String, String>,
pub globals: IndexMap<String, String>,
pub secrets: Arc<dyn SecretLookup>,
pub oauth: Option<Arc<dyn OauthLookup>>,
}
impl RequestContext {
pub fn build(input: ContextInput<'_>) -> Result<Self> {
let c = input.collection;
let ancestors = c.ancestors(input.request_id)?;
let mut layers = vec![
Layer::new(Scope::Runtime, "runtime", input.runtime),
Layer::new(Scope::Request, input.request_id, input.request.vars.clone()),
];
for (id, meta) in ancestors.iter().rev() {
layers.push(Layer::new(Scope::Folder, format!("{id}/folder.yaml"), meta.vars.clone()));
}
if let Some(env_id) = input.env {
let env = c.environment(env_id).with_context(|| format!("environment '{env_id}'"))?;
let file = c.secrets_file(env_id).unwrap_or_default();
let mut layer = Layer::new(Scope::Environment, env_id, IndexMap::new());
for (k, v) in env.vars {
if v.secret {
layer.secret.insert(k.clone());
layer.vars.insert(k.clone(), file.vars.get(&k).cloned().unwrap_or_default());
} else {
layer.vars.insert(k, v.value);
}
}
layers.push(layer);
}
layers.push(Layer::new(Scope::Collection, "knock.yaml", c.manifest.vars.clone()));
layers.push(Layer::new(Scope::Global, "global", input.globals));
let mut resolver = Resolver::new(layers, input.secrets);
if let Some(o) = input.oauth {
resolver = resolver.with_oauth(o);
}
let auth = effective_auth(c, input.request_id, &input.request.auth, &ancestors);
let mut inherited_headers = c.manifest.headers.clone();
for (_, meta) in &ancestors {
inherited_headers.extend(meta.headers.iter().cloned());
}
Ok(Self {
resolver,
auth,
inherited_headers,
root: c.root.clone(),
collection_settings: c.manifest.settings.clone(),
collection_id: c.manifest.id.clone(),
env: input.env.map(str::to_string),
})
}
/// A context for a request that is not part of a collection (CLI one-offs,
/// pasted cURL, history replays).
pub fn standalone(request: &Request, root: PathBuf) -> Self {
Self {
resolver: Resolver::new(
vec![Layer::new(Scope::Request, "request", request.vars.clone())],
Arc::new(crate::vars::NoSecrets),
),
auth: EffectiveAuth {
auth: match &request.auth {
Auth::Inherit => Auth::None,
a => a.clone(),
},
origin: AuthOrigin::Request,
source: "request".into(),
},
inherited_headers: Vec::new(),
root,
collection_settings: CollectionSettings::default(),
collection_id: String::new(),
env: None,
}
}
}
pub fn effective_auth(
c: &Collection,
request_id: &str,
own: &Auth,
ancestors: &[(String, FolderMeta)],
) -> EffectiveAuth {
if !own.is_inherit() {
return EffectiveAuth {
auth: own.clone(),
origin: AuthOrigin::Request,
source: request_id.to_string(),
};
}
for (id, meta) in ancestors.iter().rev() {
if !meta.auth.is_inherit() {
return EffectiveAuth {
auth: meta.auth.clone(),
origin: AuthOrigin::Folder,
source: id.clone(),
};
}
}
EffectiveAuth {
auth: match &c.manifest.auth {
Auth::Inherit => Auth::None,
a => a.clone(),
},
origin: AuthOrigin::Collection,
source: "knock.yaml".into(),
}
}
// ---------------------------------------------------------------- prepared
#[derive(Debug, Clone, Serialize)]
pub struct Prepared {
pub method: String,
pub url: String,
pub headers: Vec<(String, String)>,
pub body: PreparedBody,
pub settings: RequestSettings,
/// Variables referenced but not defined anywhere.
pub missing: Vec<String>,
pub cycles: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum PreparedBody {
None,
Bytes {
#[serde(skip)]
data: Vec<u8>,
preview: String,
},
Multipart { parts: Vec<PreparedPart> },
}
#[derive(Debug, Clone, Serialize)]
pub struct PreparedPart {
pub name: String,
pub value: Option<String>,
pub file: Option<PathBuf>,
pub content_type: Option<String>,
}
impl Prepared {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.rev()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
pub fn set_header(&mut self, name: &str, value: impl Into<String>) {
self.headers.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
self.headers.push((name.to_string(), value.into()));
}
pub fn body_bytes(&self) -> &[u8] {
match &self.body {
PreparedBody::Bytes { data, .. } => data,
_ => &[],
}
}
pub fn add_query(&mut self, name: &str, value: &str) -> Result<()> {
let mut u = url::Url::parse(&self.url)?;
u.query_pairs_mut().append_pair(name, value);
self.url = u.to_string();
Ok(())
}
}
pub fn prepare(req: &Request, ctx: &RequestContext) -> Result<Prepared> {
let r = &ctx.resolver;
let mut missing = Vec::new();
let mut cycles = Vec::new();
let mut res = |s: &str| {
let x = r.resolve(s);
missing.extend(x.missing);
cycles.extend(x.cycles);
x.value
};
let method = res(req.method()).trim().to_uppercase();
if method.is_empty() {
bail!("method is empty");
}
let mut url = res(req.url.trim());
let path_params: IndexMap<String, String> =
req.params.path.iter().map(|(k, v)| (k.clone(), res(v))).collect();
url = substitute_path_params(&url, &path_params);
if !url.contains("://") {
url = format!("http://{url}");
}
let parsed = url::Url::parse(&url).with_context(|| format!("invalid URL '{url}'"))?;
url = parsed.to_string();
// Inherited headers: a deeper level replaces a shallower one by name.
// Request headers then replace inherited ones by name, but several request
// headers with the same name are all sent.
let mut headers: Vec<(String, String)> = Vec::new();
for h in ctx.inherited_headers.iter().filter(|h| h.enabled && !h.name.trim().is_empty()) {
let name = res(h.name.trim());
let value = res(&h.value);
headers.retain(|(k, _)| !k.eq_ignore_ascii_case(&name));
headers.push((name, value));
}
let own: Vec<(String, String)> = req
.headers
.iter()
.filter(|h| h.enabled && !h.name.trim().is_empty())
.map(|h| (res(h.name.trim()), res(&h.value)))
.collect();
headers.retain(|(k, _)| !own.iter().any(|(n, _)| n.eq_ignore_ascii_case(k)));
headers.extend(own);
let has = |hs: &Vec<(String, String)>, n: &str| hs.iter().any(|(k, _)| k.eq_ignore_ascii_case(n));
let body = match req.kind {
RequestKind::Graphql => {
let g = req.graphql.clone().unwrap_or_default();
let vars_text = res(&g.variables);
let variables: serde_json::Value = if vars_text.trim().is_empty() {
serde_json::Value::Null
} else {
serde_json::from_str(&strip_json_comments(&vars_text))
.context("GraphQL variables are not valid JSON")?
};
let mut payload = serde_json::json!({ "query": res(&g.query) });
if !variables.is_null() {
payload["variables"] = variables;
}
if let Some(op) = g.operation_name.filter(|s| !s.is_empty()) {
payload["operationName"] = serde_json::Value::String(op);
}
if !has(&headers, "content-type") {
headers.push(("Content-Type".into(), "application/json".into()));
}
bytes_body(serde_json::to_vec(&payload)?)
}
_ => match req.body.kind {
BodyType::None => PreparedBody::None,
BodyType::Json => {
let mut text = res(&req.body.content);
if req.body.jsonc {
text = strip_json_comments(&text);
}
if !has(&headers, "content-type") {
headers.push(("Content-Type".into(), "application/json".into()));
}
bytes_body(text.into_bytes())
}
BodyType::Raw => {
if !has(&headers, "content-type") {
let ct = req.body.content_type.clone().unwrap_or_else(|| "text/plain".into());
headers.push(("Content-Type".into(), ct));
}
bytes_body(res(&req.body.content).into_bytes())
}
BodyType::FormUrlencoded => {
let mut ser = url::form_urlencoded::Serializer::new(String::new());
for f in req.body.form.iter().filter(|f| f.enabled && !f.name.is_empty()) {
ser.append_pair(&res(&f.name), &res(&f.value));
}
if !has(&headers, "content-type") {
headers.push((
"Content-Type".into(),
"application/x-www-form-urlencoded".into(),
));
}
bytes_body(ser.finish().into_bytes())
}
BodyType::Multipart => {
// Content-Type with boundary is set by the HTTP client.
headers.retain(|(k, _)| !k.eq_ignore_ascii_case("content-type"));
PreparedBody::Multipart {
parts: req
.body
.multipart
.iter()
.filter(|p| p.enabled && !p.name.is_empty())
.map(|p| PreparedPart {
name: res(&p.name),
value: p.file.is_none().then(|| res(&p.value)),
file: p.file.as_ref().map(|f| ctx.root.join(res(f))),
content_type: p.content_type.clone(),
})
.collect(),
}
}
BodyType::Binary => {
let Some(f) = &req.body.file else { bail!("binary body has no file selected") };
let path = ctx.root.join(res(f));
let data = std::fs::read(&path)
.with_context(|| format!("reading body file {}", path.display()))?;
if !has(&headers, "content-type") {
headers.push(("Content-Type".into(), "application/octet-stream".into()));
}
PreparedBody::Bytes {
preview: format!("<{} bytes from {}>", data.len(), path.display()),
data,
}
}
},
};
missing.sort();
missing.dedup();
Ok(Prepared {
method,
url,
headers,
body,
settings: req.settings.clone(),
missing,
cycles,
})
}
fn bytes_body(data: Vec<u8>) -> PreparedBody {
let preview = match std::str::from_utf8(&data) {
Ok(s) if s.len() <= 64 * 1024 => s.to_string(),
Ok(s) => format!("{}…", &s[..s.floor_char_boundary_compat(64 * 1024)]),
Err(_) => format!("<{} bytes binary>", data.len()),
};
PreparedBody::Bytes { data, preview }
}
trait FloorBoundary {
fn floor_char_boundary_compat(&self, i: usize) -> usize;
}
impl FloorBoundary for str {
fn floor_char_boundary_compat(&self, mut i: usize) -> usize {
while i > 0 && !self.is_char_boundary(i) {
i -= 1;
}
i
}
}
/// Replaces `:name` path segments. Ports (`host:8080`) are left alone because
/// only segments after the authority are considered.
pub fn substitute_path_params(url: &str, params: &IndexMap<String, String>) -> String {
if params.is_empty() {
return url.to_string();
}
let path_start = url
.find("://")
.map(|i| i + 3)
.and_then(|i| url[i..].find('/').map(|j| i + j))
.unwrap_or(url.len());
let (head, tail) = url.split_at(path_start);
let (path, rest) = match tail.find(['?', '#']) {
Some(i) => tail.split_at(i),
None => (tail, ""),
};
let path = path
.split('/')
.map(|seg| match seg.strip_prefix(':') {
Some(name) if params.contains_key(name) => {
percent_encoding::utf8_percent_encode(&params[name], SEGMENT).to_string()
}
_ => seg.to_string(),
})
.collect::<Vec<_>>()
.join("/");
format!("{head}{path}{rest}")
}
const SEGMENT: &percent_encoding::AsciiSet = &percent_encoding::CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'<')
.add(b'>')
.add(b'?')
.add(b'`')
.add(b'{')
.add(b'}')
.add(b'/')
.add(b'%');
/// Path parameter names (`:id`) found in a URL, in order.
pub fn path_param_names(url: &str) -> Vec<String> {
let start = url
.find("://")
.map(|i| i + 3)
.and_then(|i| url[i..].find('/').map(|j| i + j))
.unwrap_or(0);
let path = &url[start..];
let path = &path[..path.find(['?', '#']).unwrap_or(path.len())];
path.split('/')
.filter_map(|s| s.strip_prefix(':'))
.filter(|s| !s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-'))
.map(str::to_string)
.collect()
}
/// Removes `//` and `/* */` comments outside strings, plus trailing commas.
pub fn strip_json_comments(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let b: Vec<char> = src.chars().collect();
let mut i = 0;
let mut in_str = false;
while i < b.len() {
let c = b[i];
if in_str {
out.push(c);
if c == '\\' && i + 1 < b.len() {
out.push(b[i + 1]);
i += 2;
continue;
}
if c == '"' {
in_str = false;
}
i += 1;
continue;
}
match c {
'"' => {
in_str = true;
out.push(c);
i += 1;
}
'/' if b.get(i + 1) == Some(&'/') => {
while i < b.len() && b[i] != '\n' {
i += 1;
}
}
'/' if b.get(i + 1) == Some(&'*') => {
i += 2;
while i + 1 < b.len() && !(b[i] == '*' && b[i + 1] == '/') {
i += 1;
}
i += 2;
}
',' => {
let mut j = i + 1;
while j < b.len() && b[j].is_whitespace() {
j += 1;
}
// Keep the comma unless the next real token closes a container.
let mut k = j;
loop {
if b.get(k) == Some(&'/') && b.get(k + 1) == Some(&'/') {
while k < b.len() && b[k] != '\n' {
k += 1;
}
} else if b.get(k) == Some(&'/') && b.get(k + 1) == Some(&'*') {
k += 2;
while k + 1 < b.len() && !(b[k] == '*' && b[k + 1] == '/') {
k += 1;
}
k += 2;
} else if b.get(k).is_some_and(|c| c.is_whitespace()) {
k += 1;
} else {
break;
}
}
if !matches!(b.get(k), Some('}') | Some(']')) {
out.push(',');
}
i += 1;
}
_ => {
out.push(c);
i += 1;
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn path_params() {
let mut p = IndexMap::new();
p.insert("id".to_string(), "a b".to_string());
assert_eq!(
substitute_path_params("http://h:8080/users/:id/x?q=:id", &p),
"http://h:8080/users/a%20b/x?q=:id"
);
assert_eq!(path_param_names("http://h:8080/u/:id/:other?x=:no"), vec!["id", "other"]);
}
#[test]
fn jsonc() {
let s = "{\n // c\n \"a\": \"http://x\", /* b */\n \"b\": [1,2,],\n}";
let v: serde_json::Value = serde_json::from_str(&strip_json_comments(s)).unwrap();
assert_eq!(v["a"], "http://x");
assert_eq!(v["b"][1], 2);
}
#[test]
fn header_override() {
let req = Request {
url: "http://x/".into(),
headers: vec![KeyValue::new("Accept", "text/plain"), KeyValue::new("X-A", "1"), KeyValue::new("X-A", "2")],
..Default::default()
};
let mut ctx = RequestContext::standalone(&req, PathBuf::from("/tmp"));
ctx.inherited_headers = vec![KeyValue::new("accept", "application/json"), KeyValue::new("X-Team", "core")];
let p = prepare(&req, &ctx).unwrap();
assert_eq!(
p.headers,
vec![
("X-Team".to_string(), "core".to_string()),
("Accept".to_string(), "text/plain".to_string()),
("X-A".to_string(), "1".to_string()),
("X-A".to_string(), "2".to_string()),
]
);
}
}
+140
View File
@@ -0,0 +1,140 @@
//! One request, start to finish: resolve, authenticate, send, check. The GUI,
//! the runner and the CLI all go through [`execute`].
use crate::auth::{self, AuthDebug, AuthHost};
use crate::checks::{run_asserts, run_extracts, AssertResult, Extracted};
use crate::http::{Engine, Response, TransportOptions};
use crate::model::*;
use crate::prepare::{prepare, Prepared, PreparedBody, RequestContext};
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub struct SentRequest {
pub method: String,
pub url: String,
pub headers: Vec<(String, String)>,
pub body: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct RunOutput {
pub request: Option<SentRequest>,
pub response: Option<Response>,
pub auth: AuthDebug,
pub asserts: Vec<AssertResult>,
pub extracted: Vec<Extracted>,
pub error: Option<String>,
pub missing: Vec<String>,
/// The request was sent a second time after refreshing an expired token.
pub retried: bool,
}
impl RunOutput {
pub fn passed(&self) -> bool {
self.error.is_none() && self.asserts.iter().all(|a| a.passed)
}
}
pub fn transport_for(ctx: &RequestContext, url: &str) -> TransportOptions {
let s = &ctx.collection_settings;
let r = &ctx.resolver;
let mut t = TransportOptions::default();
if let Some(p) = &s.proxy {
t.proxy_mode = p.mode;
t.proxy_url = p.url.as_ref().map(|u| r.apply(u));
t.no_proxy = p.no_proxy.as_ref().map(|u| r.apply(u));
}
t.ca_bundle = s.ca_bundle.as_ref().map(|p| ctx.root.join(r.apply(p)));
if let Ok(u) = url::Url::parse(url) {
let host = u.host_str().unwrap_or_default();
let with_port = format!("{host}:{}", u.port_or_known_default().unwrap_or(0));
if let Some(c) = s.client_certs.iter().find(|c| c.host == host || c.host == with_port) {
let mut pem = Vec::new();
for f in [&c.cert, &c.key].into_iter().flatten() {
if let Ok(b) = std::fs::read(ctx.root.join(r.apply(f))) {
pem.extend(b);
pem.push(b'\n');
}
}
if !pem.is_empty() {
t.identity_pem = Some(pem);
}
}
}
t
}
fn sent(p: &Prepared) -> SentRequest {
SentRequest {
method: p.method.clone(),
url: p.url.clone(),
headers: p.headers.clone(),
body: match &p.body {
PreparedBody::None => String::new(),
PreparedBody::Bytes { preview, .. } => preview.clone(),
PreparedBody::Multipart { parts } => parts
.iter()
.map(|x| match &x.file {
Some(f) => format!("{}=@{}", x.name, f.display()),
None => format!("{}={}", x.name, x.value.clone().unwrap_or_default()),
})
.collect::<Vec<_>>()
.join("\n"),
},
}
}
pub async fn execute(
engine: &Engine,
req: &Request,
ctx: &RequestContext,
host: Option<&dyn AuthHost>,
) -> RunOutput {
let mut out = RunOutput {
request: None,
response: None,
auth: AuthDebug::default(),
asserts: Vec::new(),
extracted: Vec::new(),
error: None,
missing: Vec::new(),
retried: false,
};
let base = match prepare(req, ctx) {
Ok(p) => p,
Err(e) => {
out.error = Some(format!("{e:#}"));
return out;
}
};
out.missing = base.missing.clone();
let is_oauth = matches!(&ctx.auth.auth, Auth::Config(c) if c.kind == "oauth2" || c.kind == "oidc");
let mut force_refresh = false;
loop {
let mut p = base.clone();
out.auth = auth::apply(&ctx.auth, &mut p, &ctx.resolver, host, force_refresh).await;
out.request = Some(sent(&p));
if out.auth.failed() {
out.error = Some("authentication failed, see the Auth tab".into());
return out;
}
let transport = transport_for(ctx, &p.url);
let jar = (ctx.collection_settings.cookies && !ctx.collection_id.is_empty())
.then_some(ctx.collection_id.as_str());
match engine.send(&p, &transport, jar).await {
Ok(resp) => {
if resp.status == 401 && is_oauth && !force_refresh && req.settings.retry_on_401 {
force_refresh = true;
out.retried = true;
continue;
}
out.asserts = run_asserts(&req.assert, &resp);
out.extracted = run_extracts(&req.extract, &resp);
out.response = Some(resp);
}
Err(e) => out.error = Some(format!("{e:#}")),
}
return out;
}
}
+114
View File
@@ -0,0 +1,114 @@
//! Secret values live in the OS keyring (Secret Service / KWallet on Linux)
//! or in a gitignored `<env>.secrets.yaml`. For CI, `KNOCK_SECRET_<NAME>`
//! environment variables win over both.
use crate::vars::SecretLookup;
use anyhow::Result;
use indexmap::IndexMap;
use std::collections::HashMap;
use std::sync::Mutex;
pub const SERVICE: &str = "knock";
fn account(collection: &str, env: Option<&str>, name: &str) -> String {
format!("{collection}:{}:{name}", env.unwrap_or(""))
}
pub fn env_var_name(name: &str) -> String {
let mut s = String::from("KNOCK_SECRET_");
for c in name.chars() {
s.push(if c.is_ascii_alphanumeric() { c.to_ascii_uppercase() } else { '_' });
}
s
}
pub fn keyring_get(collection: &str, env: Option<&str>, name: &str) -> Option<String> {
keyring::Entry::new(SERVICE, &account(collection, env, name))
.ok()?
.get_password()
.ok()
}
pub fn keyring_set(collection: &str, env: Option<&str>, name: &str, value: &str) -> Result<()> {
keyring::Entry::new(SERVICE, &account(collection, env, name))?.set_password(value)?;
Ok(())
}
pub fn keyring_delete(collection: &str, env: Option<&str>, name: &str) -> Result<()> {
match keyring::Entry::new(SERVICE, &account(collection, env, name))?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(e.into()),
}
}
/// Generic keyring slot for things that are not variables (tokens, passphrases).
pub fn slot_get(key: &str) -> Option<String> {
keyring::Entry::new(SERVICE, key).ok()?.get_password().ok()
}
pub fn slot_set(key: &str, value: &str) -> Result<()> {
keyring::Entry::new(SERVICE, key)?.set_password(value)?;
Ok(())
}
pub fn slot_delete(key: &str) -> Result<()> {
match keyring::Entry::new(SERVICE, key)?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(e.into()),
}
}
/// Where a secret value was found, for the UI.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SecretSource {
EnvVar,
Keyring,
File,
}
pub struct SecretStore {
pub collection: String,
pub env: Option<String>,
pub file: IndexMap<String, String>,
pub use_keyring: bool,
cache: Mutex<HashMap<String, Option<(String, SecretSource)>>>,
}
impl SecretStore {
pub fn new(collection: &str, env: Option<&str>, file: IndexMap<String, String>, use_keyring: bool) -> Self {
Self {
collection: collection.to_string(),
env: env.map(str::to_string),
file,
use_keyring,
cache: Mutex::default(),
}
}
pub fn find(&self, name: &str) -> Option<(String, SecretSource)> {
if let Some(hit) = self.cache.lock().unwrap().get(name) {
return hit.clone();
}
let found = std::env::var(env_var_name(name))
.ok()
.map(|v| (v, SecretSource::EnvVar))
.or_else(|| {
if !self.use_keyring {
return None;
}
keyring_get(&self.collection, self.env.as_deref(), name)
.or_else(|| keyring_get(&self.collection, None, name))
.map(|v| (v, SecretSource::Keyring))
})
.or_else(|| self.file.get(name).cloned().map(|v| (v, SecretSource::File)));
self.cache.lock().unwrap().insert(name.to_string(), found.clone());
found
}
}
impl SecretLookup for SecretStore {
fn secret(&self, name: &str) -> Option<String> {
self.find(name).map(|(v, _)| v)
}
}
+437
View File
@@ -0,0 +1,437 @@
//! `{{name}}` resolution. Layers are searched narrowest first; the first hit
//! wins. Values may contain variables themselves; cycles are reported.
use base64::Engine;
use indexmap::IndexMap;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Scope {
Runtime,
Request,
Folder,
Environment,
Collection,
Global,
Secret,
Dynamic,
Oauth,
}
#[derive(Debug, Clone, Serialize)]
pub struct Layer {
pub scope: Scope,
/// Where the value comes from, e.g. `users/folder.yaml` or `prod`.
pub source: String,
pub vars: IndexMap<String, String>,
/// Names in this layer whose values must be masked.
pub secret: HashSet<String>,
}
impl Layer {
pub fn new(scope: Scope, source: impl Into<String>, vars: IndexMap<String, String>) -> Self {
Self {
scope,
source: source.into(),
vars,
secret: HashSet::new(),
}
}
}
/// Looks up `{{secret.x}}` and variables flagged `secret` in an environment.
pub trait SecretLookup: Send + Sync {
fn secret(&self, name: &str) -> Option<String>;
}
/// Answers `{{oauth.<name>.<field>}}` from the token store.
pub trait OauthLookup: Send + Sync {
fn oauth_value(&self, config: &str, field: &str) -> Option<String>;
}
#[derive(Default)]
pub struct NoSecrets;
impl SecretLookup for NoSecrets {
fn secret(&self, _: &str) -> Option<String> {
None
}
}
#[derive(Debug, Clone, Serialize)]
pub struct VarInfo {
pub name: String,
pub value: Option<String>,
pub scope: Option<Scope>,
pub source: Option<String>,
pub secret: bool,
/// Set when the value could not be fully resolved (cycle or missing inner var).
pub problem: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct Resolution {
pub value: String,
pub missing: Vec<String>,
pub cycles: Vec<String>,
}
#[derive(Clone)]
pub struct Resolver {
pub layers: Vec<Layer>,
secrets: Arc<dyn SecretLookup>,
oauth: Option<Arc<dyn OauthLookup>>,
/// Secret values seen while resolving, so output can be masked.
seen_secrets: Arc<std::sync::Mutex<HashSet<String>>>,
/// Dynamic values are fixed per resolver, so `{{$uuid}}` twice in one
/// request gives the same value in URL and body.
dynamic_cache: Arc<std::sync::Mutex<HashMap<String, String>>>,
}
impl std::fmt::Debug for Resolver {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Resolver").field("layers", &self.layers).finish()
}
}
impl Default for Resolver {
fn default() -> Self {
Self::new(Vec::new(), Arc::new(NoSecrets))
}
}
const MAX_DEPTH: usize = 16;
pub const MASK: &str = "••••••";
impl Resolver {
pub fn new(layers: Vec<Layer>, secrets: Arc<dyn SecretLookup>) -> Self {
Self {
layers,
secrets,
oauth: None,
seen_secrets: Default::default(),
dynamic_cache: Default::default(),
}
}
pub fn with_oauth(mut self, o: Arc<dyn OauthLookup>) -> Self {
self.oauth = Some(o);
self
}
/// Adds a layer that wins over everything else (runtime values).
pub fn push_front(&mut self, layer: Layer) {
self.layers.insert(0, layer);
}
pub fn resolve(&self, text: &str) -> Resolution {
let mut res = Resolution::default();
let mut stack = Vec::new();
res.value = self.expand(text, &mut stack, &mut res.missing, &mut res.cycles);
res.missing.dedup();
res.cycles.dedup();
res
}
/// Resolves and drops the diagnostics. Missing variables stay as `{{name}}`.
pub fn apply(&self, text: &str) -> String {
if !text.contains("{{") {
return text.to_string();
}
self.resolve(text).value
}
pub fn info(&self, name: &str) -> VarInfo {
let mut missing = Vec::new();
let mut cycles = Vec::new();
let mut stack = Vec::new();
let found = self.lookup_raw(name);
let (value, scope, source, secret) = match found {
Some(l) => (Some(l.0), Some(l.1), Some(l.2), l.3),
None => (None, None, None, false),
};
let value = value.map(|v| self.expand(&v, &mut stack, &mut missing, &mut cycles));
let problem = if !cycles.is_empty() {
Some(format!("cycle: {}", cycles.join(", ")))
} else if !missing.is_empty() {
Some(format!("undefined: {}", missing.join(", ")))
} else {
None
};
VarInfo {
name: name.to_string(),
value,
scope,
source,
secret,
problem,
}
}
/// Every variable name visible to this resolver, for autocomplete.
pub fn names(&self) -> Vec<VarInfo> {
let mut seen = HashSet::new();
let mut out = Vec::new();
for l in &self.layers {
for k in l.vars.keys() {
if seen.insert(k.clone()) {
out.push(self.info(k));
}
}
}
out
}
/// Replaces every secret value seen so far with a mask.
pub fn mask(&self, text: &str) -> String {
let seen = self.seen_secrets.lock().unwrap();
let mut out = text.to_string();
let mut vals: Vec<&String> = seen.iter().filter(|s| s.len() >= 3).collect();
vals.sort_by_key(|s| std::cmp::Reverse(s.len()));
for v in vals {
out = out.replace(v.as_str(), MASK);
}
out
}
pub fn secret_values(&self) -> Vec<String> {
self.seen_secrets.lock().unwrap().iter().cloned().collect()
}
pub fn note_secret(&self, value: &str) {
if !value.is_empty() {
self.seen_secrets.lock().unwrap().insert(value.to_string());
}
}
fn lookup_raw(&self, name: &str) -> Option<(String, Scope, String, bool)> {
if let Some(rest) = name.strip_prefix("secret.") {
return self
.secrets
.secret(rest)
.map(|v| (v, Scope::Secret, "keyring".to_string(), true));
}
if let Some(rest) = name.strip_prefix("oauth.") {
if let (Some(o), Some((cfg, field))) = (&self.oauth, rest.split_once('.')) {
return o
.oauth_value(cfg, field)
.map(|v| (v, Scope::Oauth, format!("oauth {cfg}"), true));
}
return None;
}
for l in &self.layers {
if let Some(v) = l.vars.get(name) {
if l.secret.contains(name) {
let v = if v.is_empty() {
self.secrets.secret(name).unwrap_or_default()
} else {
v.clone()
};
return Some((v, l.scope, l.source.clone(), true));
}
return Some((v.clone(), l.scope, l.source.clone(), false));
}
}
None
}
fn expand(
&self,
text: &str,
stack: &mut Vec<String>,
missing: &mut Vec<String>,
cycles: &mut Vec<String>,
) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(start) = rest.find("{{") {
out.push_str(&rest[..start]);
let after = &rest[start + 2..];
let Some(end) = find_close(after) else {
out.push_str(&rest[start..]);
return out;
};
let inner = after[..end].trim();
let raw = &rest[start..start + 2 + end + 2];
rest = &after[end + 2..];
if inner.is_empty() {
out.push_str(raw);
continue;
}
if let Some(v) = self.dynamic(inner, stack, missing, cycles) {
out.push_str(&v);
continue;
}
if stack.iter().any(|s| s == inner) || stack.len() >= MAX_DEPTH {
cycles.push(inner.to_string());
out.push_str(raw);
continue;
}
match self.lookup_raw(inner) {
Some((v, _, _, secret)) => {
stack.push(inner.to_string());
let expanded = if v.contains("{{") {
self.expand(&v, stack, missing, cycles)
} else {
v
};
stack.pop();
if secret {
self.note_secret(&expanded);
}
out.push_str(&expanded);
}
None => {
missing.push(inner.to_string());
out.push_str(raw);
}
}
}
out.push_str(rest);
out
}
fn dynamic(
&self,
inner: &str,
stack: &mut Vec<String>,
missing: &mut Vec<String>,
cycles: &mut Vec<String>,
) -> Option<String> {
let name = inner.strip_prefix('$')?;
if let Some(arg) = name.strip_prefix("base64(").and_then(|s| s.strip_suffix(')')) {
let arg = self.expand(arg, stack, missing, cycles);
return Some(base64::engine::general_purpose::STANDARD.encode(arg));
}
let mut cache = self.dynamic_cache.lock().unwrap();
if let Some(v) = cache.get(name) {
return Some(v.clone());
}
let v = dynamic_value(name)?;
cache.insert(name.to_string(), v.clone());
Some(v)
}
}
pub const DYNAMIC_VARS: &[(&str, &str)] = &[
("$uuid", "Random UUID v4"),
("$timestamp", "Unix time in seconds"),
("$timestampMs", "Unix time in milliseconds"),
("$isoDate", "Current time, ISO 8601"),
("$randomInt", "Random integer 0..1000"),
("$randomEmail", "Random e-mail address"),
("$base64(...)", "Base64 of the argument"),
];
fn dynamic_value(name: &str) -> Option<String> {
use rand::Rng;
let now = chrono::Utc::now();
Some(match name {
"uuid" | "guid" => uuid::Uuid::new_v4().to_string(),
"timestamp" => now.timestamp().to_string(),
"timestampMs" => now.timestamp_millis().to_string(),
"isoDate" | "isoTimestamp" => now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
"randomInt" => rand::thread_rng().gen_range(0..1000).to_string(),
"randomEmail" => format!("user{}@example.com", rand::thread_rng().gen_range(1000..99999)),
_ => return None,
})
}
/// Index of the matching `}}` for text that starts right after `{{`.
fn find_close(s: &str) -> Option<usize> {
let b = s.as_bytes();
let mut depth = 0;
let mut i = 0;
while i + 1 < b.len() {
if b[i] == b'{' && b[i + 1] == b'{' {
depth += 1;
i += 2;
} else if b[i] == b'}' && b[i + 1] == b'}' {
if depth == 0 {
return Some(i);
}
depth -= 1;
i += 2;
} else {
i += 1;
}
}
None
}
/// Every `{{name}}` reference in a text, top level only.
pub fn references(text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut rest = text;
while let Some(start) = rest.find("{{") {
let after = &rest[start + 2..];
let Some(end) = find_close(after) else { break };
out.push(after[..end].trim().to_string());
rest = &after[end + 2..];
}
out
}
#[cfg(test)]
mod tests {
use super::*;
struct S;
impl SecretLookup for S {
fn secret(&self, name: &str) -> Option<String> {
(name == "pw" || name == "token").then(|| format!("s3cret-{name}"))
}
}
fn layer(scope: Scope, kv: &[(&str, &str)]) -> Layer {
Layer::new(
scope,
format!("{scope:?}"),
kv.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
)
}
#[test]
fn narrow_scope_wins_and_nesting_works() {
let r = Resolver::new(
vec![
layer(Scope::Request, &[("v", "v2")]),
layer(Scope::Environment, &[("base", "https://api"), ("v", "v1"), ("url", "{{base}}/{{v}}")]),
],
Arc::new(S),
);
let res = r.resolve("{{url}}/users?x={{missing}}");
assert_eq!(res.value, "https://api/v2/users?x={{missing}}");
assert_eq!(res.missing, vec!["missing"]);
assert_eq!(r.info("v").scope, Some(Scope::Request));
}
#[test]
fn cycles_are_reported() {
let r = Resolver::new(vec![layer(Scope::Environment, &[("a", "{{b}}"), ("b", "{{a}}")])], Arc::new(NoSecrets));
let res = r.resolve("{{a}}");
assert!(!res.cycles.is_empty());
}
#[test]
fn secrets_and_masking() {
let mut env = layer(Scope::Environment, &[("token", "")]);
env.secret.insert("token".into());
let r = Resolver::new(vec![env], Arc::new(S));
assert_eq!(r.apply("Bearer {{token}} {{secret.pw}}"), "Bearer s3cret-token s3cret-pw");
assert_eq!(r.mask("x s3cret-token y s3cret-pw"), format!("x {MASK} y {MASK}"));
}
#[test]
fn dynamic_and_base64() {
let r = Resolver::new(vec![layer(Scope::Environment, &[("u", "me")])], Arc::new(S));
let a = r.apply("{{$uuid}}");
assert_eq!(a.len(), 36);
assert_eq!(r.apply("{{$uuid}}"), a, "stable within one resolver");
assert_eq!(r.apply("{{$base64({{u}}:pw)}}"), "bWU6cHc=");
assert_eq!(references("a {{x}} b {{$base64({{y}})}}"), vec!["x", "$base64({{y}})"]);
}
}