//! Scan shipping Rust diagnostics, including nested format calls and implicit captures. use proc_macro2::{TokenStream, TokenTree}; use quote::ToTokens; use std::{ collections::{BTreeMap, BTreeSet, HashSet}, path::Path, }; use syn::{ spanned::Spanned, visit::{self, Visit}, }; fn sensitive(name: &str) -> bool { if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { return false; } let lower = name.to_ascii_lowercase(); lower.split('_').any(|word| { matches!( word, "token" | "secret" | "password" | "bearer" | "sealed" | "credential" | "credentials" ) }) || matches!( lower.as_str(), "key" | "keys" | "digits" | "join_code" | "relay_id" | "relay_identifier" | "relay_token" ) || lower.ends_with("_key") } fn captures(value: &str) -> Vec<&str> { let mut names = vec![]; let mut remaining = value; while let Some(at) = remaining.find('{') { remaining = &remaining[at + 1..]; if let Some(rest) = remaining.strip_prefix('{') { remaining = rest; continue; } let end = remaining .find(['}', ':', '.', '[']) .unwrap_or(remaining.len()); names.push(&remaining[..end]); } names } fn names(tokens: TokenStream, found: &mut BTreeSet) { for token in tokens { match token { TokenTree::Ident(id) if sensitive(&id.to_string()) => { found.insert(id.to_string()); } TokenTree::Group(group) => names(group.stream(), found), TokenTree::Literal(lit) => { // Rust format's implicit captures are arguments too. A literal // sentence merely mentioning a token is not a capture. if let Ok(syn::Lit::Str(value)) = syn::parse_str::(&lit.to_string()) { for name in captures(&value.value()) { if sensitive(name) { found.insert(name.into()); } } } } _ => {} } } } // Follow local aliases of credential values. Broad ambiguous names such as // `key` remain scan hits, but do not taint every schema-column alias. fn credential_source(name: &str) -> bool { let lower = name.to_ascii_lowercase(); !name.starts_with(char::is_uppercase) && !name.chars().all(|c| !c.is_alphabetic() || c.is_uppercase()) && !lower.ends_with("_id") && !lower.ends_with("_name") && !lower.ends_with("_path") && !lower.ends_with("_file") && !matches!( lower.as_str(), "key" | "keys" | "digits" | "token_id" | "secret_id" ) && sensitive(name) } // Ambiguous `key` names still propagate when copied, encoded or read as a // field. Metadata operations remain conservative hits at their diagnostic. fn copied_sources(expr: &syn::Expr, found: &mut BTreeSet) { let copies = match expr { syn::Expr::Path(_) | syn::Expr::Field(_) | syn::Expr::Index(_) | syn::Expr::Unary(_) => { true } syn::Expr::Reference(reference) => { copied_sources(&reference.expr, found); false } syn::Expr::Paren(paren) => { copied_sources(&paren.expr, found); false } syn::Expr::MethodCall(call) => matches!( call.method.to_string().as_str(), "clone" | "to_string" | "to_vec" | "as_ref" | "as_bytes" | "as_slice" | "expose" | "encode" | "digest" ), syn::Expr::Call(call) => { matches!(call.func.as_ref(), syn::Expr::Path(path) if path.path.segments.last().is_some_and(|s| matches!(s.ident.to_string().as_str(), "encode" | "digest" | "base64url" | "base64url_encode"))) } syn::Expr::Macro(mac) => mac .mac .path .segments .last() .is_some_and(|s| s.ident == "format" || s.ident == "format_args"), _ => false, }; if copies { names(expr.to_token_stream(), found); } } fn selector_names(tokens: TokenStream, found: &mut BTreeSet) { for token in tokens { match token { TokenTree::Group(group) => selector_names(group.stream(), found), TokenTree::Literal(lit) => { if let Ok(syn::Lit::Str(value)) = syn::parse_str::(&lit.to_string()) { let value = value.value(); let selector = value .trim_start_matches('/') .rsplit('/') .next() .unwrap_or(""); if credential_source(selector) { found.insert(selector.into()); } } } _ => {} } } } fn alias_names( tokens: TokenStream, aliases: &BTreeMap>, found: &mut BTreeSet, ) { for token in tokens { match token { TokenTree::Ident(id) => { if let Some(sources) = aliases.get(&id.to_string()) { for source in sources { found.insert(format!("{}<-{}", id, source)); } } } TokenTree::Group(group) => alias_names(group.stream(), aliases, found), TokenTree::Literal(lit) => { if let Ok(syn::Lit::Str(value)) = syn::parse_str::(&lit.to_string()) { for name in captures(&value.value()) { if let Some(sources) = aliases.get(name) { for source in sources { found.insert(format!("{name}<-{source}")); } } } } } _ => {} } } } struct Scan { aliases: BTreeMap>, hits: Vec<(usize, String, String, String)>, } impl Scan { fn arguments(&mut self, span: proc_macro2::Span, kind: &str, tokens: TokenStream) { let mut args = BTreeSet::new(); names(tokens.clone(), &mut args); alias_names(tokens.clone(), &self.aliases, &mut args); for arg in args { self.hits .push((span.start().line, kind.into(), arg, tokens.to_string())); } } } impl<'ast> Visit<'ast> for Scan { fn visit_item_fn(&mut self, item: &'ast syn::ItemFn) { let old = std::mem::take(&mut self.aliases); visit::visit_item_fn(self, item); self.aliases = old; } fn visit_impl_item_fn(&mut self, item: &'ast syn::ImplItemFn) { let old = std::mem::take(&mut self.aliases); visit::visit_impl_item_fn(self, item); self.aliases = old; } fn visit_local(&mut self, local: &'ast syn::Local) { if let (syn::Pat::Ident(binding), Some(init)) = (&local.pat, &local.init) { let mut sources = BTreeSet::new(); names(init.expr.to_token_stream(), &mut sources); selector_names(init.expr.to_token_stream(), &mut sources); sources.retain(|name| credential_source(name)); copied_sources(&init.expr, &mut sources); alias_names(init.expr.to_token_stream(), &self.aliases, &mut sources); self.aliases.remove(&binding.ident.to_string()); if !sources.is_empty() { self.aliases.insert(binding.ident.to_string(), sources); } } visit::visit_local(self, local); } fn visit_block(&mut self, block: &'ast syn::Block) { let old = self.aliases.clone(); visit::visit_block(self, block); self.aliases = old; } fn visit_expr_struct(&mut self, expr: &'ast syn::ExprStruct) { if expr.path.segments.iter().any(|s| { s.ident.to_string().ends_with("Error") || s.ident.to_string().ends_with("Refusal") }) { self.arguments( expr.path.span(), "error-message", expr.fields.to_token_stream(), ); } visit::visit_expr_struct(self, expr); } fn visit_expr_assign(&mut self, expr: &'ast syn::ExprAssign) { if let syn::Expr::Path(binding) = expr.left.as_ref() { if let Some(name) = binding.path.get_ident() { let mut sources = BTreeSet::new(); names(expr.right.to_token_stream(), &mut sources); selector_names(expr.right.to_token_stream(), &mut sources); sources.retain(|name| credential_source(name)); copied_sources(&expr.right, &mut sources); alias_names(expr.right.to_token_stream(), &self.aliases, &mut sources); self.aliases.remove(&name.to_string()); if !sources.is_empty() { self.aliases.insert(name.to_string(), sources); } } } visit::visit_expr_assign(self, expr); } fn visit_expr_call(&mut self, call: &'ast syn::ExprCall) { if let syn::Expr::Path(path) = call.func.as_ref() { let segments: Vec<_> = path .path .segments .iter() .map(|s| s.ident.to_string()) .collect(); if segments .iter() .any(|s| s.ends_with("Error") || s.ends_with("Refusal")) || segments.last().is_some_and(|s| { matches!( s.as_str(), "log" | "trace" | "debug" | "info" | "warn" | "error" | "print" | "println" | "eprintln" ) }) { self.arguments(call.span(), "error-message", call.args.to_token_stream()); } } visit::visit_expr_call(self, call); } fn visit_expr_method_call(&mut self, call: &'ast syn::ExprMethodCall) { if matches!( call.method.to_string().as_str(), "context" | "with_context" | "expect" | "log" | "say" | "trace" | "debug" | "info" | "warn" | "error" | "print" | "println" | "eprintln" | "write_fmt" ) { self.arguments( call.method.span(), "error-message", call.args.to_token_stream(), ); } visit::visit_expr_method_call(self, call); } fn visit_attribute(&mut self, attr: &'ast syn::Attribute) { if attr.path().is_ident("error") { self.arguments( attr.path().segments[0].ident.span(), "error-message", attr.meta.to_token_stream(), ); } visit::visit_attribute(self, attr); } fn visit_item_mod(&mut self, item: &'ast syn::ItemMod) { if item.attrs.iter().any(|a| { a.path().is_ident("cfg") && a.meta.to_token_stream().to_string() == "cfg (test)" }) { return; } visit::visit_item_mod(self, item); } fn visit_macro(&mut self, mac: &'ast syn::Macro) { let kind = mac.path.segments.last().unwrap().ident.to_string(); if matches!( kind.as_str(), "trace" | "event" | "span" | "debug" | "info" | "warn" | "error" | "log" | "format" | "format_args" | "print" | "println" | "eprint" | "eprintln" | "write" | "writeln" | "anyhow" | "bail" | "ensure" ) { self.arguments( mac.path.segments.last().unwrap().ident.span(), &kind, mac.tokens.clone(), ); nested(mac.tokens.clone(), self); } else { // Macro input is opaque to syn. Walk nested macro invocations so a // format inside json!, select! or a generated handler still counts. nested(mac.tokens.clone(), self); } } } fn nested(tokens: TokenStream, scan: &mut Scan) { let tokens: Vec<_> = tokens.into_iter().collect(); for window in tokens.windows(3) { if let [TokenTree::Ident(name), TokenTree::Punct(bang), TokenTree::Group(body)] = window { if bang.as_char() == '!' { let mac: syn::Macro = syn::parse2(quote::quote!(#name ! #body)).unwrap(); scan.visit_macro(&mac); } } } for token in tokens { if let TokenTree::Group(group) = token { nested(group.stream(), scan); } } } fn scan(text: &str) -> Vec<(usize, String, String, String)> { let file = syn::parse_file(text).expect("shipping Rust must parse"); let mut scan = Scan { aliases: BTreeMap::new(), hits: vec![], }; scan.visit_file(&file); scan.hits.sort(); scan.hits.dedup(); scan.hits } struct Hit { file: String, line: usize, kind: String, argument: String, expression: String, } #[derive(serde::Deserialize)] struct Allowed { file: String, kind: String, arguments: Vec, expression: String, reason: String, } fn permitted(hit: &Hit, allow: &Allowed) -> bool { hit.file == allow.file && hit.kind == allow.kind && hit.expression == allow.expression && allow.arguments.contains(&hit.argument) } fn walk(dir: &Path, root: &Path, hits: &mut Vec) { let mut paths: Vec<_> = std::fs::read_dir(dir) .unwrap() .map(|e| e.unwrap().path()) .collect(); paths.sort(); for path in paths { if path.is_dir() { walk(&path, root, hits); } else if path.extension().is_some_and(|s| s == "rs") && !path .file_name() .unwrap() .to_string_lossy() .ends_with("_tests.rs") && path.file_name().unwrap() != "tests.rs" { let relative = path.strip_prefix(root).unwrap().to_string_lossy(); for (line, kind, arg, tokens) in scan(&std::fs::read_to_string(&path).unwrap()) { hits.push(Hit { file: relative.to_string(), line, kind, argument: arg, expression: tokens, }); } } } } /// RULE: A credential never passes through a log, a note, a chat or an agent's context. #[test] fn shipping_diagnostics_never_format_credentials() { let manifest = cotton_store::manifest_dir(); let root = manifest.parent().unwrap(); let mut hits = vec![]; for entry in std::fs::read_dir(root).unwrap() { let src = entry.unwrap().path().join("src"); if src.is_dir() { walk(&src, root, &mut hits); } } // Exceptions match the exact expression AND each source/alias argument, // never a whole file or a variable name. New value sources need a new // honest sentence; wrapping a transport expression in a log is a new hit. let mut allowed: Vec = serde_json::from_str(include_str!( "fixtures/credential_diagnostics_allowlist.json" )) .unwrap(); for allow in &mut allowed { allow.expression = allow .expression .parse::() .expect("an exception expression must be Rust tokens") .to_string(); } let mut seen = HashSet::new(); let mut refused = vec![]; let mut unlisted: Vec = vec![]; for hit in &hits { if let Some((index, _)) = allowed .iter() .enumerate() .find(|(_, allow)| permitted(hit, allow)) { seen.insert((index, hit.argument.clone())); } else { refused.push(format!( "{}:{}: {} argument {}", hit.file, hit.line, hit.kind, hit.argument )); unlisted.push(serde_json::json!({ "file": hit.file, "line": hit.line, "kind": hit.kind, "arguments": [hit.argument], "expression": hit.expression, })); } } // CREDENTIAL_DIAG_DUMP= writes each refused hit with its expression, to read // and, where it is honestly no credential, to add to the allowlist with its reason. if let Ok(path) = std::env::var("CREDENTIAL_DIAG_DUMP") { std::fs::write(&path, serde_json::to_string_pretty(&unlisted).unwrap()).unwrap(); // And each exception argument nothing matched any more, to take out. let stale: Vec = allowed.iter().enumerate().flat_map(|(index, allow)| { allow.arguments.iter().filter(|argument| !seen.contains(&(index, (*argument).clone()))).map(move |argument| serde_json::json!({ "index": index, "file": allow.file, "argument": argument })).collect::>() }).collect(); std::fs::write(format!("{path}.stale"), serde_json::to_string_pretty(&stale).unwrap()).unwrap(); } assert!( refused.is_empty(), "credential-shaped diagnostic arguments (names only):\n{}", refused.join("\n") ); for (index, allow) in allowed.iter().enumerate() { assert!( allow.reason.ends_with('.') && allow.reason.contains(' '), "{}: exception needs the sentence that makes it honest", allow.file ); for argument in &allow.arguments { assert!( seen.contains(&(index, argument.clone())), "{}: remove a stale {} exception for {}", allow.file, allow.kind, argument ); } } } /// RULE: A credential never passes through a log, a note, a chat or an agent's context. #[test] fn catches_multiline_fields_nested_formats_and_implicit_captures() { for text in [ "fn f() { tracing::info!(\n secret = %value, \"ok\"); }", "fn f() { eprintln!(\"{token}\"); }", "fn f() { anyhow!(\"{}\", credentials.secret); }", "fn f() { json!({\"x\": format!(\"{relay_id}\")}); }", "fn f() { let payload = secret.to_string(); println!(\"{payload}\"); }", "fn f() { let payload = body[\"password\"].clone(); let copied = payload; warn!(\"{copied}\"); }", "fn f() { let mut payload = String::new(); payload = bearer; error!(\"{payload}\"); }", "fn f() { result.context(password); }", "fn f() { events.log(secret); }", "fn f() { let payload = key.clone(); info!(\"{payload}\"); }", "fn f() { let payload = hex::encode(key); warn!(\"{payload}\"); }", "fn f() { tracing::event!(Level::INFO, bearer = %value); }", "fn f() { return HttpError::new(401, secret); }", "fn f() { return HttpError { message: secret }; }", "#[derive(Error)] #[error(\"{password}\")] struct E { password: String }", ] { assert!(!scan(text).is_empty(), "diagnostic scanner missed a credential argument"); } for safe in [ "fn f() { println!(\"token revoked\"); }", "fn f() { println!(\"{{token}}\"); }", "fn f() { let payload = secret.clone(); { let payload = \"safe\"; println!(\"{payload}\"); } }", ] { assert!(scan(safe).is_empty(), "scanner treated safe text or a shadowed binding as a credential"); } } /// RULE: A credential never passes through a log, a note, a chat or an agent's context. #[test] fn a_transport_exception_cannot_allow_a_log_or_a_new_source() { let allowed = Allowed { file: "fixture.rs".into(), kind: "format".into(), expression: "\"Bearer {token}\"".into(), arguments: vec!["token".into()], reason: "This builds an outbound authorization header on the private protocol path.".into(), }; let hit = Hit { file: "fixture.rs".into(), line: 1, kind: "format".into(), argument: "token".into(), expression: allowed.expression.clone(), }; assert!(permitted(&hit, &allowed)); assert!(!permitted( &Hit { kind: "println".into(), ..hit }, &allowed )); assert!(!permitted( &Hit { file: "fixture.rs".into(), line: 1, kind: "format".into(), argument: "token<-secret".into(), expression: allowed.expression.clone() }, &allowed )); }