Skip to content
237 changes: 230 additions & 7 deletions apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,7 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen
let pictures = ask_pictures(args)?;
eprintln!("[{} · {}]", cfg.provider, cfg.model);
let yes = args.iter().any(|a| a == "--yes");
let trace_key = cfg.key.clone();
let mut a = Agent::new(cfg, s);
a.set_skills(rustgis_assistant::skills::installed());
let mut shown = 0;
Expand All @@ -678,13 +679,8 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen
let send = |req: &rustgis_assistant::HttpRequest| {
let r = transport(req);
if let Some(path) = &trace {
let resp = match &r {
Ok(r) => format!("HTTP {}\n{}", r.status, String::from_utf8_lossy(&r.body)),
Err(e) => e.to_string(),
};
let entry = format!("> {} {}\n{}\n< {resp}\n\n", req.method, req.url, req.body.as_deref().unwrap_or(""));
let written = std::fs::OpenOptions::new().create(true).append(true).open(path).and_then(|mut f| f.write_all(entry.as_bytes()));
if let Err(e) = written {
let entry = format_trace_entry(req, &r, &trace_key);
if let Err(e) = append_trace(path, &entry) {
eprintln!("rustgis-cli: {}: {e}", path.display());
}
}
Expand All @@ -707,6 +703,110 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen
Ok(())
}

/// Scrubs active service login values and the assistant's own API key (raw and JSON-escaped)
/// from trace text.
fn mask_trace_secrets(text: &str, key: &str) -> String {
let mut scrubbed = rustgis_engine::render::rustgis_tiles::logins::scrub(text);
if !key.is_empty() {
scrubbed = scrubbed.replace(key, "[redacted]");
if let Ok(quoted) = serde_json::to_string(key)
&& let Some(escaped) = quoted.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
&& escaped != key
{
scrubbed = scrubbed.replace(escaped, "[redacted]");
}
}
scrubbed
}

/// Recursively redacts decoded JSON string values and object keys (bounded to `depth`) so
/// JSON-escaped active credentials and API keys (for example containing `\` or `"`) match before
/// re-serialization.
fn scrub_json_value(value: &mut Value, key: &str, depth: usize) {
if depth == 0 {
*value = Value::String("[redacted]".into());
return;
}
match value {
Value::String(s) => {
*s = mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(s), key);
}
Value::Array(items) => {
for item in items {
scrub_json_value(item, key, depth - 1);
}
}
Value::Object(map) => {
let entries = std::mem::take(map);
for (k, mut v) in entries {
let sensitive = rustgis_engine::data::address::log_sensitive(&k);
Comment thread
giswqs marked this conversation as resolved.
Resolved
let k = mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(&k), key);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if sensitive {
v = Value::String("[redacted]".into());
} else {
scrub_json_value(&mut v, key, depth - 1);
}
map.insert(k, v);
}
}
_ => {}
}
}

/// Scrubs a request or response body for `--trace`: decodes JSON payloads (whole bodies and SSE
/// `data:` lines) so escaped credentials match active logins and the API key, while keeping raw
/// redaction for non-JSON text.
fn scrub_trace_body(body: &str, key: &str) -> String {
Comment thread
giswqs marked this conversation as resolved.
Resolved
const MAX_JSON_DEPTH: usize = 64;
let decoded = if let Ok(mut value) = serde_json::from_str::<Value>(body) {
scrub_json_value(&mut value, key, MAX_JSON_DEPTH);
serde_json::to_string(&value).unwrap_or_else(|_| body.to_string())
} else if body.lines().any(|line| line.starts_with("data:")) {
body.lines()
.map(|line| {
if let Some(rest) = line.strip_prefix("data:")
&& let Ok(mut value) = serde_json::from_str::<Value>(rest.trim())
{
scrub_json_value(&mut value, key, MAX_JSON_DEPTH);
if let Ok(serialized) = serde_json::to_string(&value) {
return format!("data: {serialized}");
}
}
line.to_string()
})
.collect::<Vec<_>>()
.join("\n")
} else {
body.to_string()
};
mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(&decoded), key)
}

/// Formats a `--trace` entry for an assistant request and its response, redacting URL
/// credentials, secret fields, active service logins, and the configured API key.
fn format_trace_entry<E: std::fmt::Display>(
req: &rustgis_assistant::HttpRequest,
resp: &Result<rustgis_assistant::HttpResponse, E>,
key: &str,
) -> String {
let url = mask_trace_secrets(&rustgis_engine::sources::redact(&req.url), key);
let body = scrub_trace_body(req.body.as_deref().unwrap_or(""), key);
let answer = match resp {
Ok(r) => format!("HTTP {}\n{}", r.status, scrub_trace_body(&String::from_utf8_lossy(&r.body), key)),
Err(e) => mask_trace_secrets(&rustgis_engine::data::diagnostics::redact(&e.to_string()), key),
};
format!("> {} {url}\n{body}\n< {answer}\n\n", req.method)
}

/// Appends `entry` to the `--trace` file, restricting new files to owner-only permissions on Unix.
fn append_trace(path: &std::path::Path, entry: &str) -> std::io::Result<()> {
let mut options = std::fs::OpenOptions::new();
options.create(true).append(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
options.open(path)?.write_all(entry.as_bytes())
}

/// `--attach [PORT]` as `mcp` takes it: the port that follows when it isn't another flag, else
/// the app's default.
fn attach_port(args: &[String]) -> Result<Option<u16>, String> {
Expand Down Expand Up @@ -1483,4 +1583,127 @@ mod tests {
}
assert!(store.accounts().is_empty(), "asked for {:?}", store.accounts());
}

#[test]
fn trace_entry_scrubs_secrets_and_urls() {
let origin = "https://trace-login.example.test";
let binding = rustgis_engine::render::rustgis_tiles::logins::activate(
origin,
"trace",
rustgis_engine::render::rustgis_tiles::logins::Method::Header("X-Key".into()),
"active-login-secret-999",
false,
)
.unwrap();
let req = rustgis_assistant::HttpRequest {
method: "POST",
url: "https://user:urlpw@api.example.test/v1/chat?key=sk-test-key-12345&model=m".into(),
headers: Vec::new(),
body: Some(r#"{"prompt":"check postgres://dbu:dbpw@db.example/gis and sk-test-key-12345 and active-login-secret-999"}"#.into()),
};
let resp: Result<_, &str> = Ok(rustgis_assistant::HttpResponse {
status: 400,
headers: Vec::new(),
body: br#"{"error":"invalid key sk-test-key-12345 at https://u:respw@api.example.test?token=resptok"}"#.to_vec(),
});
let entry = format_trace_entry(&req, &resp, "sk-test-key-12345");
let err_entry = format_trace_entry(
&req,
&Err("failed calling https://u:errpw@api.example.test?api_key=errkey with sk-test-key-12345 and active-login-secret-999"),
"sk-test-key-12345",
);
assert!(rustgis_engine::render::rustgis_tiles::logins::deactivate(&binding));
for secret in ["urlpw", "sk-test-key-12345", "dbpw", "respw", "resptok", "active-login-secret-999"] {
assert!(!entry.contains(secret), "leaked {secret} in: {entry}");
}
assert!(entry.contains("HTTP 400") && entry.contains("\"prompt\""), "{entry}");
for secret in ["urlpw", "sk-test-key-12345", "errpw", "errkey", "active-login-secret-999"] {
assert!(!err_entry.contains(secret), "leaked {secret} in: {err_entry}");
}

// JSON-escaped credentials containing backslashes and double quotes are redacted in JSON bodies.
let slash_secret = r"login\slash-secret-42";
let quote_secret = r#"login"quote-secret-42"#;
let escaped_key = r#"sk\key"escape-42"#;
let b_slash = rustgis_engine::render::rustgis_tiles::logins::activate(
"https://trace-slash.example.test",
"slash",
rustgis_engine::render::rustgis_tiles::logins::Method::Header("X-Key".into()),
slash_secret,
false,
)
.unwrap();
let b_quote = rustgis_engine::render::rustgis_tiles::logins::activate(
"https://trace-quote.example.test",
"quote",
rustgis_engine::render::rustgis_tiles::logins::Method::Header("X-Key".into()),
quote_secret,
false,
)
.unwrap();
let req_json = rustgis_assistant::HttpRequest {
method: "POST",
url: "https://api.example.test/v1/chat".into(),
headers: Vec::new(),
body: Some(json!({"prompt": format!("req {slash_secret} {quote_secret} {escaped_key}")}).to_string()),
};
let resp_json: Result<_, &str> = Ok(rustgis_assistant::HttpResponse {
status: 200,
headers: Vec::new(),
body: json!({"output": format!("resp {slash_secret} {quote_secret} {escaped_key}")}).to_string().into_bytes(),
});
let json_entry = format_trace_entry(&req_json, &resp_json, escaped_key);
let plain_resp: Result<_, &str> = Ok(rustgis_assistant::HttpResponse {
status: 200,
headers: Vec::new(),
body: format!("plain {slash_secret} {quote_secret} {escaped_key}").into_bytes(),
});
let plain_entry = format_trace_entry(&req_json, &plain_resp, escaped_key);
assert!(rustgis_engine::render::rustgis_tiles::logins::deactivate(&b_slash));
assert!(rustgis_engine::render::rustgis_tiles::logins::deactivate(&b_quote));
for leaked in
[slash_secret, r"login\\slash-secret-42", quote_secret, r#"login\"quote-secret-42"#, escaped_key, r#"sk\\key\"escape-42"#]
{
assert!(!json_entry.contains(leaked), "leaked {leaked} in JSON trace: {json_entry}");
assert!(!plain_entry.contains(leaked), "leaked {leaked} in plain trace: {plain_entry}");
}

// An active login whose value equals a sensitive field name must not bypass value redaction.
let b_field = rustgis_engine::render::rustgis_tiles::logins::activate(
"https://trace-field.example.test",
"field",
rustgis_engine::render::rustgis_tiles::logins::Method::Header("X-Key".into()),
"password",
false,
)
.unwrap();
let req_sensitive = rustgis_assistant::HttpRequest {
method: "POST",
url: "https://api.example.test/v1/chat".into(),
headers: Vec::new(),
body: Some(json!({"password": "my-db-secret", "prompt": "safe"}).to_string()),
};
let resp_sensitive: Result<_, &str> = Ok(rustgis_assistant::HttpResponse {
status: 200,
headers: Vec::new(),
body: json!({"password": "my-resp-secret", "output": "ok"}).to_string().into_bytes(),
});
let sensitive_entry = format_trace_entry(&req_sensitive, &resp_sensitive, "");
assert!(rustgis_engine::render::rustgis_tiles::logins::deactivate(&b_field));
assert!(!sensitive_entry.contains("my-db-secret"), "leaked request secret in: {sensitive_entry}");
assert!(!sensitive_entry.contains("my-resp-secret"), "leaked response secret in: {sensitive_entry}");
assert!(sensitive_entry.contains("\"prompt\":\"safe\""), "{sensitive_entry}");
}

#[cfg(unix)]
#[test]
fn trace_file_uses_private_permissions() {
use std::os::unix::fs::PermissionsExt;
let path = std::env::temp_dir().join(format!("rustgis-cli-trace-mode-{}.txt", std::process::id()));
let _ = std::fs::remove_file(&path);
append_trace(&path, "entry\n").unwrap();
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
let _ = std::fs::remove_file(&path);
assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
}
}
10 changes: 3 additions & 7 deletions crates/data/src/source/msconn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,7 @@ pub fn split_password(s: &str) -> Option<(String, Option<String>)> {
return None;
}
let (mut public, password) = super::myconn::split_userinfo_password(s.trim())?;
let password = password.or_else(|| {
let (_, query) = public.split_once('?')?;
query.split('&').find_map(|kv| {
let (key, value) = kv.split_once('=')?;
(key.eq_ignore_ascii_case("pwd") || key.eq_ignore_ascii_case("passwd")).then(|| super::pgconn::percent_decode(value))
})
});
let password = password.or_else(|| super::myconn::query_password_alias(&public));
super::credentials::redact_query(&mut public);
Some((public, password))
}
Expand Down Expand Up @@ -59,6 +53,8 @@ mod tests {
("pwd=ignored&password=chosen", "chosen"),
("passwd=ignored&pass=chosen", "chosen"),
("pwd=&passwd=second", ""),
("pw%64=encoded-pwd", "encoded-pwd"),
("pass%77d=encoded-passwd", "encoded-passwd"),
] {
let (public, password) = split_password(&format!("mssql://sa@h/gis?{query}&encrypt=strict")).unwrap();
assert_eq!(password.as_deref(), Some(expected), "{query}");
Expand Down
50 changes: 48 additions & 2 deletions crates/data/src/source/myconn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,20 @@ pub fn split_password(s: &str) -> Option<(String, Option<String>)> {
if !is_address(t) {
return None;
}
split_userinfo_password(t)
let (mut public, password) = split_userinfo_password(t)?;
let password = password.or_else(|| query_password_alias(&public));
super::credentials::redact_query(&mut public);
Comment thread
giswqs marked this conversation as resolved.
Resolved
Some((public, password))
}

/// Extracts the first `pwd` or `passwd` query alias (percent-decoded) when neither user-info nor
/// `password`/`pass` supplied a password.
pub(super) fn query_password_alias(public: &str) -> Option<String> {
let (_, query) = public.split_once('?')?;
query.split('&').find_map(|kv| {
let (key, value) = kv.split_once('=')?;
matches!(crate::address::normalized_name(key).as_deref(), Some("pwd" | "passwd")).then(|| super::pgconn::percent_decode(value))
})
}

/// Removes user-info and query passwords without restricting the address's scheme.
Expand Down Expand Up @@ -64,7 +77,7 @@ fn query_without_password(s: &str) -> (String, Option<String>) {
let mut kept = Vec::new();
for kv in query.split('&').filter(|kv| !kv.is_empty()) {
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
if k.eq_ignore_ascii_case("password") || k.eq_ignore_ascii_case("pass") {
if matches!(crate::address::normalized_name(k).as_deref(), Some("password" | "pass")) {
password = Some(super::pgconn::percent_decode(v));
} else {
kept.push(kv);
Expand Down Expand Up @@ -113,4 +126,37 @@ mod tests {
assert_eq!(database_name("mysql://h"), None);
assert_eq!(database_name("mysql://h/"), None);
}

#[test]
fn encoded_password_and_secret_query_params_are_stripped() {
let s = |a: &str| split_password(a).unwrap_or_else(|| panic!("{a}"));
assert_eq!(
s("mysql://me@h/gis?pass%77ord=sec%26ret&ssl-mode=REQUIRED"),
("mysql://me@h/gis?ssl-mode=REQUIRED".into(), Some("sec&ret".into()))
);
assert_eq!(
s("mariadb://me@h/gis?pa%73s=pw123&ssl-mode=REQUIRED"),
("mariadb://me@h/gis?ssl-mode=REQUIRED".into(), Some("pw123".into()))
);
for (query, expected) in [
("pwd=sec%26ret", "sec&ret"),
("passwd=pw123", "pw123"),
("pw%64=enc-pwd", "enc-pwd"),
("pass%77d=enc-passwd", "enc-passwd"),
("pwd=ignored&password=chosen", "chosen"),
] {
assert_eq!(
s(&format!("mysql://me@h/gis?{query}&ssl-mode=REQUIRED")),
("mysql://me@h/gis?ssl-mode=REQUIRED".into(), Some(expected.into())),
"{query}"
);
}
for key in ["token", "access_token", "client_secret", "api_key"] {
assert_eq!(
s(&format!("mysql://me@h/gis?{key}=secret&ssl-mode=REQUIRED")),
("mysql://me@h/gis?ssl-mode=REQUIRED".into(), None),
"{key}"
);
}
}
}
Loading
Loading