Import Bruno's YAML collections; fix defaults of on-by-default switches

- Bruno OpenCollection format (opencollection.yml, folder.yml, .yml
  requests, environments): folders and order, requests, bodies, auth
  including OAuth 2.0, settings, docs; scripts and other rules kept in
  Docs; a note when Bruno's hosted callback URI was used
- bruno.json is optional for .bru collections; picking a folder that
  holds several collections names them
- Collection variables that look like credentials (cookie, session,
  token, secret, password, api key) move to the secrets file and keep
  working under their name
- KeyValue, CollectionSettings, MultipartPart, ExtractRule and
  AssertRule default to enabled like the file format; new collections
  no longer start with the cookie jar turned off
This commit is contained in:
2026-11-27 21:44:33 +01:00
parent d96f9939a0
commit a73490e5d4
8 changed files with 793 additions and 19 deletions
+1 -1
View File
@@ -485,7 +485,7 @@ async fn auth(cmd: AuthCmd) -> Result<i32> {
fn import(source: &Path, dest: &Path) -> Result<i32> {
use knock_core::import::{self, Kind};
let report = if source.is_dir() {
import::import_bruno(source, dest)?
import::import_folder(source, dest)?
} else {
let text = if source == Path::new("-") {
let mut s = String::new();
+11 -8
View File
@@ -1,4 +1,4 @@
//! Bruno collections: a folder with `bruno.json`, `.bru` request files,
//! Bruno collections in the `.bru` format: `bruno.json` (optional), `.bru` request files,
//! `folder.bru`, `collection.bru` and `environments/*.bru`.
use super::{append_docs, looks_like_json, parse_query, pretty_json, scripts_doc, set_url, ImportReport, Writer};
@@ -171,13 +171,16 @@ fn unquote_key(k: &str) -> String {
const METHODS: &[&str] = &["get", "post", "put", "patch", "delete", "options", "head", "connect", "trace"];
pub fn import_bruno(src_dir: &Path, dest: &Path) -> Result<ImportReport> {
// bruno.json is optional: collections copied without it still have their .bru files.
let manifest_path = src_dir.join("bruno.json");
let manifest: serde_json::Value = serde_json::from_str(
&fs::read_to_string(&manifest_path)
.with_context(|| format!("{} is not a Bruno collection (bruno.json missing)", src_dir.display()))?,
)
.context("bruno.json is not valid JSON")?;
let name = super::text(manifest.get("name"));
let manifest: serde_json::Value = if manifest_path.is_file() {
serde_json::from_str(&fs::read_to_string(&manifest_path)?).context("bruno.json is not valid JSON")?
} else {
serde_json::Value::Null
};
let name = Some(super::text(manifest.get("name")))
.filter(|n| !n.is_empty())
.unwrap_or_else(|| src_dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default());
let ignore: Vec<String> = manifest
.get("ignore")
.and_then(|v| v.as_array())
@@ -192,7 +195,7 @@ pub fn import_bruno(src_dir: &Path, dest: &Path) -> Result<ImportReport> {
let mut warnings = Vec::new();
let auth = map_auth(&bru, &mut warnings);
let headers = kv(bru.dict("headers"));
let vars = vars_map(bru.dict("vars:pre-request"));
let vars = w.protect_vars(vars_map(bru.dict("vars:pre-request")));
let (docs, scripts) = misc_docs(&bru);
w.report.scripts_skipped += scripts;
w.manifest(|m| {
+1
View File
@@ -77,6 +77,7 @@ pub fn import_insomnia(json: &str, dest: &Path) -> Result<ImportReport> {
}
}
let coll_vars: IndexMap<String, String> = coll_vars.into_iter().map(|(k, v)| (k, convert_vars(&v))).collect();
let coll_vars = w.protect_vars(coll_vars);
w.manifest(|m| m.vars = coll_vars)?;
let mut skipped: IndexMap<String, usize> = IndexMap::new();
+88 -1
View File
@@ -9,6 +9,7 @@ pub mod bruno;
pub mod curl;
pub mod insomnia;
pub mod openapi;
pub mod opencollection;
pub mod postman;
use crate::collection::{read_yaml, slugify, Collection, ENV_DIR, MANIFEST};
@@ -22,6 +23,7 @@ pub use bruno::import_bruno;
pub use curl::parse_curl;
pub use insomnia::import_insomnia;
pub use openapi::import_openapi;
pub use opencollection::import_opencollection;
pub use postman::{import_postman, import_postman_environment};
#[derive(Debug, Clone, Default, Serialize)]
@@ -87,6 +89,7 @@ pub(crate) struct Writer {
pub report: ImportReport,
/// Credentials pulled out of auth configs, name -> value.
secrets: IndexMap<String, String>,
auth_secrets_noted: bool,
}
impl Writer {
@@ -110,6 +113,7 @@ impl Writer {
c,
report,
secrets: IndexMap::new(),
auth_secrets_noted: false,
})
}
@@ -180,10 +184,38 @@ impl Writer {
Ok(id)
}
/// Collection variables whose names point to credentials (cookies,
/// sessions, tokens, keys, passwords) keep their name, but their value
/// moves to the gitignored secrets file and the variable points there.
pub fn protect_vars(&mut self, vars: IndexMap<String, String>) -> IndexMap<String, String> {
let mut moved = Vec::new();
let out = vars
.into_iter()
.map(|(k, v)| {
if sensitive_name(&k) && !v.is_empty() && !v.contains("{{") {
self.secrets.insert(k.clone(), v);
moved.push(k.clone());
let reference = format!("{{{{secret.{k}}}}}");
(k, reference)
} else {
(k, v)
}
})
.collect();
if !moved.is_empty() {
self.report.warnings.push(format!(
"variables that look like credentials ({}) were moved to the secrets file; requests use them as before",
moved.join(", ")
));
}
out
}
fn secure(&mut self, auth: &mut Auth, prefix: &str) {
let before = self.secrets.len();
externalize_secrets(auth, prefix, &mut self.secrets);
if self.secrets.len() > before && before == 0 {
if self.secrets.len() > before && !self.auth_secrets_noted {
self.auth_secrets_noted = true;
self.report.warnings.push(
"credentials found in auth settings were moved to the environments' secrets files (gitignored)".into(),
);
@@ -235,6 +267,14 @@ impl Writer {
}
}
/// Variable names that usually hold credentials.
pub(crate) fn sensitive_name(name: &str) -> bool {
let n = name.to_ascii_lowercase().replace(['-', '.'], "_");
["secret", "password", "passwd", "token", "cookie", "session", "apikey", "api_key", "private_key", "credential"]
.iter()
.any(|w| n.contains(w))
}
/// Auth fields that hold credentials, per auth type.
fn secret_fields(kind: &str) -> &'static [&'static str] {
match kind {
@@ -504,3 +544,50 @@ mod tests {
assert_eq!(cfg.str("token"), Some("{{token}}"));
}
}
fn has_bru_files(dir: &Path, depth: u32) -> bool {
let Ok(rd) = std::fs::read_dir(dir) else { return false };
rd.filter_map(|e| e.ok()).any(|e| {
let p = e.path();
if p.is_dir() {
depth > 0 && !e.file_name().to_string_lossy().starts_with('.') && has_bru_files(&p, depth - 1)
} else {
p.extension().is_some_and(|x| x == "bru")
}
})
}
fn is_bruno_dir(dir: &Path) -> bool {
opencollection::is_opencollection(dir) || dir.join("bruno.json").is_file() || has_bru_files(dir, 3)
}
/// Imports a collection folder: Bruno's YAML format (opencollection.yml) or
/// the classic `.bru` format, with or without bruno.json.
pub fn import_folder(src: &Path, dest: &Path) -> Result<ImportReport> {
if opencollection::is_opencollection(src) {
return import_opencollection(src, dest);
}
if src.join("bruno.json").is_file() || has_bru_files(src, 3) {
return import_bruno(src, dest);
}
// A folder that holds several collections (Bruno's workspace folder).
let inner: Vec<String> = std::fs::read_dir(src)
.map(|rd| {
rd.filter_map(|e| e.ok())
.filter(|e| e.path().is_dir() && is_bruno_dir(&e.path()))
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default();
if !inner.is_empty() {
bail!(
"{} holds several collections ({}). Choose one of those folders",
src.display(),
inner.join(", ")
);
}
bail!(
"{} is not a Bruno collection: no opencollection.yml, bruno.json or .bru files found",
src.display()
)
}
@@ -0,0 +1,620 @@
//! Bruno's YAML format (OpenCollection): `opencollection.yml`, `folder.yml`
//! per folder, one `.yml` per request and `environments/*.yml`.
use super::{append_docs, looks_like_json, parse_query, pretty_json, scripts_doc, set_url, ImportReport, Writer};
use crate::model::*;
use anyhow::{Context, Result};
use indexmap::IndexMap;
use serde_yaml_ng::Value;
use std::fs;
use std::path::Path;
pub const MANIFEST: &str = "opencollection.yml";
/// True when `dir` is an OpenCollection folder.
pub fn is_opencollection(dir: &Path) -> bool {
dir.join(MANIFEST).is_file() || dir.join("opencollection.yaml").is_file()
}
fn read(p: &Path) -> Result<Value> {
let text = fs::read_to_string(p).with_context(|| format!("reading {}", p.display()))?;
serde_yaml_ng::from_str(&text).with_context(|| format!("parsing {}", p.display()))
}
fn s(v: &Value, path: &[&str]) -> String {
let mut cur = v;
for k in path {
match cur.get(*k) {
Some(n) => cur = n,
None => return String::new(),
}
}
match cur {
Value::String(x) => x.clone(),
Value::Number(n) => n.to_string(),
Value::Bool(b) => b.to_string(),
_ => String::new(),
}
}
fn get<'a>(v: &'a Value, path: &[&str]) -> Option<&'a Value> {
let mut cur = v;
for k in path {
cur = cur.get(*k)?;
}
Some(cur)
}
/// `[{ name, value, enabled|disabled }]` as key/value rows.
fn rows(v: Option<&Value>) -> Vec<KeyValue> {
let Some(Value::Sequence(items)) = v else { return Vec::new() };
items
.iter()
.filter_map(|i| {
let name = s(i, &["name"]);
if name.is_empty() {
return None;
}
let disabled = i.get("disabled").and_then(|d| d.as_bool()).unwrap_or(false)
|| i.get("enabled").and_then(|d| d.as_bool()) == Some(false);
let mut kv = KeyValue::new(name, s(i, &["value"]));
if disabled {
kv.enabled = false;
}
let d = s(i, &["description"]);
if !d.is_empty() {
kv.description = Some(d);
}
Some(kv)
})
.collect()
}
fn vars(v: Option<&Value>) -> IndexMap<String, String> {
rows(v).into_iter().filter(|r| r.enabled).map(|r| (r.name, r.value)).collect()
}
fn auth(v: Option<&Value>, warnings: &mut Vec<String>) -> Auth {
let Some(a) = v else { return Auth::Inherit };
if let Value::String(mode) = a {
return match mode.as_str() {
"none" => Auth::None,
_ => Auth::Inherit,
};
}
let g = |k: &[&str]| s(a, k);
match g(&["type"]).as_str() {
"none" => Auth::None,
"inherit" | "" => Auth::Inherit,
"basic" => super::auth("basic", [("username", g(&["username"])), ("password", g(&["password"]))]),
"digest" => super::auth("digest", [("username", g(&["username"])), ("password", g(&["password"]))]),
"bearer" => super::auth("bearer", [("token", g(&["token"]))]),
"apikey" | "api-key" => {
let place = match g(&["placement"]).as_str() {
"query" | "queryparams" => "query",
_ => "header",
};
super::auth("apikey", [("key", g(&["key"])), ("value", g(&["value"])), ("in", place.into())])
}
"awsv4" | "aws-sigv4" => super::auth(
"awsv4",
[
("access_key", g(&["accessKeyId"])),
("secret_key", g(&["secretAccessKey"])),
("session_token", g(&["sessionToken"])),
("region", g(&["region"])),
("service", g(&["service"])),
],
),
"oauth2" => {
let flow = g(&["flow"]);
let grant = match flow.as_str() {
"client_credentials" => "client_credentials",
"password" => "password",
"implicit" => {
warnings.push("the implicit flow was mapped to authorization code with PKCE".into());
"authorization_code"
}
_ => "authorization_code",
};
let client_auth = match g(&["credentials", "placement"]).as_str() {
"body" | "request_body" => "post",
_ => "basic",
};
let source = g(&["tokenConfig", "source"]);
let prefix = g(&["tokenConfig", "placement", "header"]);
let query = g(&["tokenConfig", "placement", "query"]);
let mut fields: Vec<(&'static str, String)> = vec![
("grant", grant.to_string()),
("authorize_url", g(&["authorizationUrl"])),
("token_url", g(&["accessTokenUrl"])),
("client_id", g(&["credentials", "clientId"])),
("client_secret", g(&["credentials", "clientSecret"])),
("client_auth", client_auth.to_string()),
("scopes", g(&["scope"])),
("username", g(&["username"])),
("password", g(&["password"])),
];
if source == "id_token" {
fields.push(("token_use", "id_token".into()));
}
if !query.is_empty() {
fields.push(("token_placement", "query".into()));
fields.push(("token_name", query));
} else if !prefix.is_empty() && prefix != "Bearer" {
fields.push(("token_prefix", prefix));
}
let mut a2 = super::auth("oauth2", fields);
if let Auth::Config(c) = &mut a2 {
// An explicit `pkce: false` / `enabled: false` turns it off; knock uses PKCE otherwise.
let off = matches!(get(a, &["pkce"]), Some(Value::Bool(false)))
|| get(a, &["pkce", "enabled"]).and_then(|v| v.as_bool()) == Some(false);
if off {
c.fields.insert("pkce".into(), serde_json::Value::Bool(false));
}
}
let callback = g(&["callbackUrl"]);
if !callback.is_empty() {
warnings.push(format!(
"Bruno used the redirect URI {callback}; knock listens on http://127.0.0.1:53127/callback by default. Register that at the provider, or change it in the OAuth settings"
));
}
a2
}
other => {
warnings.push(format!("auth type `{other}` is not supported and was left as inherit"));
Auth::Inherit
}
}
}
fn body(http: &Value, warnings: &mut Vec<String>) -> (Body, Option<GraphqlSpec>) {
let Some(b) = http.get("body") else { return (Body::default(), None) };
let kind = s(b, &["type"]);
let data = b.get("data");
let text = || data.and_then(|d| d.as_str()).unwrap_or("").to_string();
match kind.as_str() {
"json" => {
let t = text();
let content = if looks_like_json(&t) { pretty_json(&t) } else { t };
(Body { kind: BodyType::Json, content, ..Default::default() }, None)
}
"text" => (Body { kind: BodyType::Raw, content: text(), content_type: Some("text/plain".into()), ..Default::default() }, None),
"xml" => (Body { kind: BodyType::Raw, content: text(), content_type: Some("application/xml".into()), ..Default::default() }, None),
"sparql" => (Body { kind: BodyType::Raw, content: text(), content_type: Some("application/sparql-query".into()), ..Default::default() }, None),
"form-urlencoded" | "formUrlEncoded" => (Body { kind: BodyType::FormUrlencoded, form: rows(data), ..Default::default() }, None),
"multipart-form" | "multipartForm" => {
let parts = match data {
Some(Value::Sequence(items)) => items
.iter()
.filter_map(|i| {
let name = s(i, &["name"]);
if name.is_empty() {
return None;
}
let is_file = s(i, &["type"]) == "file";
let value = match i.get("value") {
Some(Value::Sequence(v)) => v.first().and_then(|x| x.as_str()).unwrap_or("").to_string(),
_ => s(i, &["value"]),
};
let ct = s(i, &["contentType"]);
Some(MultipartPart {
name,
value: if is_file { String::new() } else { value.clone() },
file: is_file.then_some(value),
content_type: (!ct.is_empty()).then_some(ct),
enabled: i.get("disabled").and_then(|d| d.as_bool()) != Some(true),
})
})
.collect(),
_ => Vec::new(),
};
(Body { kind: BodyType::Multipart, multipart: parts, ..Default::default() }, None)
}
"graphql" => {
let (query, variables) = match data {
Some(Value::Mapping(_)) => (s(data.unwrap(), &["query"]), s(data.unwrap(), &["variables"])),
_ => (text(), String::new()),
};
(Body::default(), Some(GraphqlSpec { query, variables, operation_name: None }))
}
"file" | "binary" => {
warnings.push("binary file bodies point to paths outside the collection; pick the file again".into());
(Body { kind: BodyType::Binary, ..Default::default() }, None)
}
"" | "none" => (Body::default(), None),
other => {
warnings.push(format!("body type `{other}` was not converted"));
(Body::default(), None)
}
}
}
const KNOWN_KEYS: &[&str] = &["info", "http", "graphql", "settings", "docs"];
fn request(doc: &Value, name: &str, warnings: &mut Vec<String>, scripts: &mut usize) -> Request {
let http = doc.get("http").or_else(|| doc.get("graphql")).cloned().unwrap_or(Value::Null);
let is_gql = s(doc, &["info", "type"]) == "graphql" || doc.get("graphql").is_some();
let method = s(&http, &["method"]);
let url = s(&http, &["url"]);
let mut req = Request {
name: name.to_string(),
method: Some(if method.is_empty() { "GET".into() } else { method.to_uppercase() }),
headers: rows(http.get("headers")),
auth: auth(http.get("auth"), warnings),
..Default::default()
};
let mut query = Vec::new();
if let Some(Value::Sequence(params)) = http.get("params") {
for p in params {
let row = rows(Some(&Value::Sequence(vec![p.clone()])));
if s(p, &["type"]) == "path" {
if let Some(r) = row.first() {
req.params.path.insert(r.name.clone(), r.value.clone());
}
} else {
query.extend(row);
}
}
}
if query.is_empty() {
query = parse_query(&url);
}
set_url(&mut req, &url, query);
let (b, gql) = body(&http, warnings);
req.body = b;
if is_gql || gql.is_some() {
req.kind = RequestKind::Graphql;
req.method = Some("POST".into());
req.graphql = Some(gql.unwrap_or_default());
}
if let Some(st) = doc.get("settings") {
let n = |k: &str| st.get(k).and_then(|v| v.as_u64());
if let Some(t) = n("timeout").filter(|t| *t > 0) {
req.settings.timeout_ms = t;
}
if let Some(f) = st.get("followRedirects").and_then(|v| v.as_bool()) {
req.settings.follow_redirects = f;
}
if let Some(m) = n("maxRedirects") {
req.settings.max_redirects = m as u32;
}
}
let docs = s(doc, &["docs"]);
if !docs.is_empty() {
req.docs = Some(docs);
}
// Scripts, tests, assertions and anything newer stay readable in Docs.
let mut leftovers: Vec<(&str, &str, String)> = Vec::new();
if let Value::Mapping(m) = doc {
for (k, v) in m {
let key = k.as_str().unwrap_or("");
if KNOWN_KEYS.contains(&key) {
continue;
}
if key.contains("script") || key == "tests" {
*scripts += 1;
}
leftovers.push(("yaml", key, serde_yaml_ng::to_string(v).unwrap_or_default()));
}
}
for extra in ["scripts", "assertions", "variables", "tests"] {
if let Some(v) = http.get(extra) {
if extra == "scripts" || extra == "tests" {
*scripts += 1;
}
leftovers.push(("yaml", extra, serde_yaml_ng::to_string(v).unwrap_or_default()));
}
}
if !leftovers.is_empty() {
append_docs(&mut req, &scripts_doc("Bruno (not converted)", &leftovers));
}
req
}
enum Child {
Folder { path: std::path::PathBuf, name: String, seq: f64, meta: Option<Value> },
Request { doc: Value, name: String, seq: f64 },
}
fn seq(doc: &Value) -> f64 {
get(doc, &["info", "seq"]).and_then(|v| v.as_f64()).unwrap_or(f64::MAX)
}
fn import_dir(w: &mut Writer, root: &Path, dir: &Path, folder: &str, ignore: &[String]) -> Result<()> {
let mut children = Vec::new();
for e in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
let e = e?;
let path = e.path();
let fname = e.file_name().to_string_lossy().to_string();
let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
if fname.starts_with('.') || ignore.iter().any(|i| *i == fname || *i == rel) {
continue;
}
if path.is_dir() {
if dir == root && fname == "environments" {
continue;
}
let meta_path = ["folder.yml", "folder.yaml"].iter().map(|f| path.join(f)).find(|p| p.is_file());
let meta = match meta_path {
Some(p) => Some(read(&p)?),
None => None,
};
let name = meta.as_ref().map(|m| s(m, &["info", "name"])).filter(|n| !n.is_empty()).unwrap_or_else(|| fname.clone());
let sq = meta.as_ref().map(seq).unwrap_or(f64::MAX);
children.push(Child::Folder { path, name, seq: sq, meta });
} else if (fname.ends_with(".yml") || fname.ends_with(".yaml"))
&& !matches!(fname.as_str(), "folder.yml" | "folder.yaml" | MANIFEST | "opencollection.yaml")
{
let doc = match read(&path) {
Ok(d) => d,
Err(err) => {
w.warn(format!("{rel} skipped: {err:#}"));
continue;
}
};
let stem = fname.trim_end_matches(".yml").trim_end_matches(".yaml").to_string();
let name = Some(s(&doc, &["info", "name"])).filter(|n| !n.is_empty()).unwrap_or(stem);
let sq = seq(&doc);
children.push(Child::Request { doc, name, seq: sq });
}
}
children.sort_by(|a, b| {
let key = |c: &Child| match c {
Child::Folder { seq, name, .. } | Child::Request { seq, name, .. } => (*seq, name.to_lowercase()),
};
let (sa, na) = key(a);
let (sb, nb) = key(b);
sa.total_cmp(&sb).then(na.cmp(&nb))
});
for child in children {
match child {
Child::Folder { path, name, meta, .. } => {
let id = w.folder(folder, &name)?;
if let Some(m) = meta {
let mut warnings = Vec::new();
let r = m.get("request").cloned().unwrap_or(Value::Null);
let a = auth(r.get("auth"), &mut warnings);
let headers = rows(r.get("headers"));
let v = vars(r.get("variables"));
let docs = s(&m, &["docs"]);
w.folder_meta(&id, |fm| {
fm.auth = a;
fm.headers = headers;
fm.vars = v;
if !docs.is_empty() {
fm.extra.insert("docs".into(), docs.into());
}
})?;
for msg in warnings {
w.warn(format!("{name}: {msg}"));
}
}
import_dir(w, root, &path, &id, ignore)?;
}
Child::Request { doc, name, .. } => {
let mut warnings = Vec::new();
let mut scripts = 0;
let req = request(&doc, &name, &mut warnings, &mut scripts);
w.report.scripts_skipped += scripts;
w.request(folder, req)?;
for msg in warnings {
w.warn(format!("{name}: {msg}"));
}
}
}
}
Ok(())
}
pub fn import_opencollection(src_dir: &Path, dest: &Path) -> Result<ImportReport> {
let manifest_path = [MANIFEST, "opencollection.yaml"].iter().map(|f| src_dir.join(f)).find(|p| p.is_file());
let manifest = read(&manifest_path.context("opencollection.yml not found")?)?;
let name = Some(s(&manifest, &["info", "name"]))
.filter(|n| !n.is_empty())
.unwrap_or_else(|| src_dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default());
let ignore: Vec<String> = match get(&manifest, &["extensions", "bruno", "ignore"]) {
Some(Value::Sequence(v)) => v.iter().filter_map(|x| x.as_str().map(str::to_string)).collect(),
_ => vec!["node_modules".into(), ".git".into()],
};
let mut w = Writer::start(dest, &name)?;
let r = manifest.get("request").cloned().unwrap_or(Value::Null);
let mut warnings = Vec::new();
let col_auth = auth(r.get("auth"), &mut warnings);
let headers = rows(r.get("headers"));
let col_vars = vars(r.get("variables"));
let col_vars = w.protect_vars(col_vars);
let docs = s(&manifest, &["docs"]);
w.manifest(|m| {
m.headers = headers;
m.vars = col_vars;
if !docs.is_empty() {
m.extra.insert("docs".into(), docs.into());
}
})?;
w.collection_auth(col_auth)?;
for msg in warnings {
w.warn(format!("collection: {msg}"));
}
if let Some(proxy) = get(&manifest, &["config", "proxy"]) {
let inherit = proxy.get("inherit").and_then(|v| v.as_bool()).unwrap_or(true);
let host = s(proxy, &["config", "hostname"]);
if !inherit && !host.is_empty() {
let url = format!("{}://{}:{}", s(proxy, &["config", "protocol"]), host, s(proxy, &["config", "port"]));
w.manifest(|m| {
m.settings.proxy = Some(ProxySettings { mode: ProxyMode::Custom, url: Some(url), no_proxy: None });
})?;
}
}
let env_dir = src_dir.join("environments");
let mut env_files: Vec<_> = if env_dir.is_dir() {
fs::read_dir(&env_dir)?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "yml" || e == "yaml"))
.collect()
} else {
Vec::new()
};
env_files.sort();
let mut has_local = false;
let mut secret_vars = 0;
for p in &env_files {
let doc = read(p)?;
let stem = p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();
let env_name = Some(s(&doc, &["name"])).filter(|n| !n.is_empty()).unwrap_or(stem);
let mut env = Environment::default();
let mut secrets = IndexMap::new();
if let Some(Value::Sequence(items)) = doc.get("variables") {
for i in items {
let n = s(i, &["name"]);
if n.is_empty() || i.get("enabled").and_then(|v| v.as_bool()) == Some(false) {
continue;
}
let secret = i.get("secret").and_then(|v| v.as_bool()).unwrap_or(false);
let value = s(i, &["value"]);
if secret {
secret_vars += 1;
if !value.is_empty() {
secrets.insert(n.clone(), value);
}
env.vars.insert(n, EnvVar { value: String::new(), secret: true, description: None });
} else {
env.vars.insert(n, EnvVar { value, secret: false, description: None });
}
}
}
let id = w.environment(&env_name, env, secrets)?;
has_local |= id == "local";
}
if !env_files.is_empty() && !has_local {
w.remove_local_env()?;
}
if secret_vars > 0 {
w.warn("secret environment variables without a stored value need to be set again in knock's environment editor");
}
import_dir(&mut w, src_dir, src_dir, "", &ignore)?;
w.finish()
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture() -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("knock-oc-src-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(d.join("Auth")).unwrap();
fs::create_dir_all(d.join("environments")).unwrap();
fs::write(
d.join(MANIFEST),
r#"opencollection: 1.0.0
info:
name: Demo
request:
headers:
- name: X-Client
value: knock
auth:
type: oauth2
flow: authorization_code
authorizationUrl: "{{BASE}}/realms/default/oauth2/authorize"
accessTokenUrl: "{{BASE}}/realms/default/oauth2/token"
callbackUrl: https://oauth.usebruno.com/callback
credentials:
clientId: test
clientSecret: s3cr3t
placement: basic_auth_header
scope: openid profile email
pkce: {}
tokenConfig:
source: access_token
placement:
header: Bearer
variables:
- name: BASE
value: http://localhost:5173
- name: AUTH_COOKIE
value: sid=abc123
"#,
)
.unwrap();
fs::write(d.join("Auth/folder.yml"), "info:\n name: Auth\n type: folder\n seq: 2\nrequest:\n auth: inherit\n").unwrap();
fs::write(
d.join("Auth/Login.yml"),
r#"info:
name: Login
type: http
seq: 1
http:
method: POST
url: "{{BASE}}/api/login?remember=1"
headers:
- name: Origin
value: "{{BASE}}"
body:
type: json
data: |-
{"username": "alice"}
settings:
timeout: 0
followRedirects: true
maxRedirects: 5
scripts:
postResponse: bru.setVar("x", 1)
"#,
)
.unwrap();
fs::write(d.join("Health.yml"), "info:\n name: Health\n type: http\n seq: 1\nhttp:\n method: GET\n url: \"{{BASE}}/health\"\ndocs: Is it up?\n").unwrap();
fs::write(
d.join("environments/Local.yml"),
"name: Local\nvariables:\n - name: BASE\n value: http://localhost:5173\n - name: token\n value: abc\n secret: true\n",
)
.unwrap();
d
}
#[test]
fn imports_opencollection() {
let src = fixture();
let dest = std::env::temp_dir().join(format!("knock-oc-dst-{}", uuid::Uuid::new_v4()));
let report = import_opencollection(&src, &dest).unwrap();
assert_eq!(report.requests, 2);
assert_eq!(report.folders, 1);
assert_eq!(report.scripts_skipped, 1);
assert!(report.warnings.iter().any(|w| w.contains("127.0.0.1:53127")), "{:?}", report.warnings);
let c = crate::Collection::open(&dest).unwrap();
assert_eq!(c.manifest.name, "Demo");
assert_eq!(c.manifest.vars["BASE"], "http://localhost:5173");
assert_eq!(c.manifest.vars["AUTH_COOKIE"], "{{secret.AUTH_COOKIE}}");
assert_eq!(c.secrets_file("local").unwrap().vars["AUTH_COOKIE"], "sid=abc123");
let Auth::Config(a) = &c.manifest.auth else { panic!("collection auth") };
assert_eq!(a.kind, "oauth2");
assert_eq!(a.str("client_id"), Some("test"));
assert!(a.str("client_secret").unwrap().starts_with("{{secret."), "secret must not stay in knock.yaml");
assert_eq!(c.requests_in(""), vec!["health.yaml".to_string(), "auth/login.yaml".to_string()]);
let login = c.request("auth/login.yaml").unwrap();
assert_eq!(login.method(), "POST");
assert_eq!(login.body.kind, BodyType::Json);
assert!(login.body.content.contains("\"username\": \"alice\""));
assert_eq!(login.params.query[0].name, "remember");
assert!(login.docs.unwrap().contains("bru.setVar"));
assert!(login.auth.is_inherit());
let env = c.environment("local").unwrap();
assert!(env.vars["token"].secret);
assert_eq!(c.secrets_file("local").unwrap().vars["token"], "abc");
fs::remove_dir_all(src).ok();
fs::remove_dir_all(dest).ok();
}
}
+1
View File
@@ -31,6 +31,7 @@ pub fn import_postman(json: &str, dest: &Path) -> Result<ImportReport> {
if !scripts.is_empty() {
append(&mut extra_docs, &scripts_doc("Postman", &scripts));
}
let vars = w.protect_vars(vars);
w.manifest(|m| {
m.vars = vars;
if !extra_docs.is_empty() {
+70 -5
View File
@@ -19,7 +19,7 @@ fn yes() -> bool {
true
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct KeyValue {
pub name: String,
#[serde(default)]
@@ -32,6 +32,13 @@ pub struct KeyValue {
pub extra: Extra,
}
// Same defaults as the file format: switches that are on unless written.
impl Default for KeyValue {
fn default() -> Self {
Self { name: String::new(), value: String::new(), enabled: true, description: None, extra: Extra::new() }
}
}
impl KeyValue {
pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
Self {
@@ -71,7 +78,7 @@ fn format_version() -> u32 {
FORMAT_VERSION
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CollectionSettings {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub proxy: Option<ProxySettings>,
@@ -86,6 +93,13 @@ pub struct CollectionSettings {
pub extra: Extra,
}
// Same defaults as the file format: switches that are on unless written.
impl Default for CollectionSettings {
fn default() -> Self {
Self { proxy: None, ca_bundle: None, client_certs: Vec::new(), cookies: true, extra: Extra::new() }
}
}
impl CollectionSettings {
fn is_default(&self) -> bool {
self.proxy.is_none()
@@ -286,7 +300,7 @@ impl Body {
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MultipartPart {
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
@@ -299,6 +313,13 @@ pub struct MultipartPart {
pub enabled: bool,
}
// Same defaults as the file format: switches that are on unless written.
impl Default for MultipartPart {
fn default() -> Self {
Self { name: String::new(), value: String::new(), file: None, content_type: None, enabled: true }
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct GraphqlSpec {
#[serde(default)]
@@ -406,7 +427,7 @@ pub enum ExtractSource {
Status,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExtractRule {
pub var: String,
#[serde(default)]
@@ -421,6 +442,13 @@ pub struct ExtractRule {
pub persist: bool,
}
// Same defaults as the file format: switches that are on unless written.
impl Default for ExtractRule {
fn default() -> Self {
Self { var: String::new(), from: ExtractSource::default(), path: String::new(), enabled: true, persist: false }
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AssertTarget {
@@ -433,7 +461,7 @@ pub enum AssertTarget {
Body,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssertRule {
pub on: AssertTarget,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -458,6 +486,25 @@ pub struct AssertRule {
pub enabled: bool,
}
// Same defaults as the file format: switches that are on unless written.
impl Default for AssertRule {
fn default() -> Self {
Self {
on: AssertTarget::default(),
path: None,
equals: None,
not_equals: None,
contains: None,
exists: None,
type_is: None,
matches: None,
gt: None,
lt: None,
enabled: true,
}
}
}
// ---------------------------------------------------------------- auth
/// Auth is `inherit`, `none`, or a map with a `type` key. The map form keeps
@@ -678,6 +725,24 @@ futureField:
}
}
#[test]
fn rust_defaults_match_file_defaults() {
let kv: KeyValue = serde_yaml_ng::from_str("name: a").unwrap();
assert_eq!(KeyValue { name: "a".into(), ..Default::default() }, kv);
let cs: CollectionSettings = serde_yaml_ng::from_str("{}").unwrap();
assert_eq!(CollectionSettings::default(), cs);
assert!(CollectionSettings::default().cookies);
let mp: MultipartPart = serde_yaml_ng::from_str("name: f").unwrap();
assert_eq!(MultipartPart { name: "f".into(), ..Default::default() }, mp);
let ex: ExtractRule = serde_yaml_ng::from_str("var: x").unwrap();
assert_eq!(ExtractRule { var: "x".into(), ..Default::default() }, ex);
let ar: AssertRule = serde_yaml_ng::from_str("on: status").unwrap();
assert_eq!(AssertRule::default(), ar);
// A fresh manifest writes no settings block at all.
let out = serde_yaml_ng::to_string(&Manifest { name: "x".into(), ..Default::default() }).unwrap();
assert!(!out.contains("settings"), "{out}");
}
#[test]
fn env_vars() {
let e: Environment = serde_yaml_ng::from_str(