From 58499cb79196684358bdec0e689ff7a390c9b6f8 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 21:45:06 +0100 Subject: [PATCH] feat: tracing-fields keeps the fields standard.toml denies out of telemetry When denied-fields lists names, no tracing event or span macro outside tests records a field whose name, or a dotted part of it, is one of them. --- crates/sourceorigin-standard/README.md | 5 + .../sourceorigin-standard/src/config/mod.rs | 5 + crates/sourceorigin-standard/src/rules/mod.rs | 6 + .../src/rules/tests/mod.rs | 1 + .../src/rules/tests/tracing_fields.rs | 46 +++++++ .../src/rules/tracing_fields.rs | 118 ++++++++++++++++++ 6 files changed, 181 insertions(+) create mode 100644 crates/sourceorigin-standard/src/rules/tests/tracing_fields.rs create mode 100644 crates/sourceorigin-standard/src/rules/tracing_fields.rs diff --git a/crates/sourceorigin-standard/README.md b/crates/sourceorigin-standard/README.md index 213682a..95f25d3 100644 --- a/crates/sourceorigin-standard/README.md +++ b/crates/sourceorigin-standard/README.md @@ -43,6 +43,7 @@ A repository adopts the standard in four steps: - `no-json-macro`: Code outside tests, in the crates `standard.toml`'s `no-json-macro` lists, invokes no `json!`: it serializes structs. Each name there is a workspace crate. - `route-literals`: When `standard.toml`'s `route-modules` lists modules, such as `my_app::routes`, code outside them, tests and examples passes no string literal starting with `/` to `Router::route`, `route_service`, `nest` or `nest_service`, or to a `Redirect` constructor: it uses the paths those modules name. Each listed module is a file of a library or binary. - `duplicate-items`: No function body outside test code with at least 50 tokens repeats another, token for token once identifiers are renamed in the order they appear. +- `tracing-fields`: Outside tests, no `tracing` event or span macro (`info!`, `info_span!`, `event!`, …) records a field whose name, or a dotted part of it, `standard.toml`'s `denied-fields` lists, such as `token` or `http.user_agent`. Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and @@ -75,6 +76,10 @@ no-json-macro = ["my_protocol"] # elsewhere passes them no `/…` literal. Unset, paths aren't checked. route-modules = ["my_app::routes"] +# The field names `tracing` events and spans outside tests never record, as +# a name or a dotted part of one. Unset, fields aren't checked. +denied-fields = ["token", "secret", "cookie", "user_agent", "ip"] + [comments] # The most lines of prose an item's or module's docs may span, code blocks # and a crate root's `//!` docs aside. diff --git a/crates/sourceorigin-standard/src/config/mod.rs b/crates/sourceorigin-standard/src/config/mod.rs index 20e5cc8..99cf2ab 100644 --- a/crates/sourceorigin-standard/src/config/mod.rs +++ b/crates/sourceorigin-standard/src/config/mod.rs @@ -78,6 +78,9 @@ pub(crate) struct Config { pub(crate) no_json_macro: Vec, /// The modules that own HTTP paths, such as `my_app::routes`. pub(crate) route_modules: Vec, + /// The field names `tracing` events and spans never record, such as + /// `token`. + pub(crate) denied_fields: Vec, /// The `[comments]` table. pub(crate) comments: Comments, } @@ -229,6 +232,7 @@ struct File { unsafe_modules: Vec>, no_json_macro: Vec>, route_modules: Vec>, + denied_fields: Vec>, comments: Comments, } @@ -359,6 +363,7 @@ impl Config { unsafe_modules: listed(file.unsafe_modules), no_json_macro: listed(file.no_json_macro), route_modules: listed(file.route_modules), + denied_fields: listed(file.denied_fields), comments: file.comments, }) } diff --git a/crates/sourceorigin-standard/src/rules/mod.rs b/crates/sourceorigin-standard/src/rules/mod.rs index cde9f98..fc682e5 100644 --- a/crates/sourceorigin-standard/src/rules/mod.rs +++ b/crates/sourceorigin-standard/src/rules/mod.rs @@ -22,6 +22,7 @@ mod source; mod test_code; #[cfg(test)] mod tests; +mod tracing_fields; mod unsafe_modules; mod walk; mod workspace_lints; @@ -154,6 +155,11 @@ rules! { /// another, token for token once identifiers are renamed in the order /// they appear. DuplicateItems = "duplicate-items" => duplicate_items, + /// Outside tests, no `tracing` event or span macro (`info!`, + /// `info_span!`, `event!`, …) records a field whose name, or a dotted + /// part of it, `standard.toml`'s `denied-fields` lists, such as `token` + /// or `http.user_agent`. + TracingFields = "tracing-fields" => tracing_fields, } /// Why the rules couldn't be checked. diff --git a/crates/sourceorigin-standard/src/rules/tests/mod.rs b/crates/sourceorigin-standard/src/rules/tests/mod.rs index ef6e1b3..d14dfb4 100644 --- a/crates/sourceorigin-standard/src/rules/tests/mod.rs +++ b/crates/sourceorigin-standard/src/rules/tests/mod.rs @@ -13,6 +13,7 @@ mod inline_tests; mod no_json_macro; mod report; mod route_literals; +mod tracing_fields; mod unsafe_modules; mod workspace_lints; diff --git a/crates/sourceorigin-standard/src/rules/tests/tracing_fields.rs b/crates/sourceorigin-standard/src/rules/tests/tracing_fields.rs new file mode 100644 index 0000000..8212066 --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/tests/tracing_fields.rs @@ -0,0 +1,46 @@ +use super::{Fixture, INHERITS}; +use crate::rules::Rule; + +/// Events and spans, recording denied fields on lines 2, 3 and 6. +const LIB: &str = r#"fn serve(token: &str, request: &Request) { + tracing::info!(token = %token, "signed in"); + info!(?request.path, "request"); + tracing::debug!("token {}", token); + let _span = info_span!("handle", user = %request.user); + warn!(target: "audit", %token); +} +#[test] +fn logs() { + info!(token = 1); +} +"#; + +#[test] +fn events_and_spans_record_no_denied_field() { + let fixture = Fixture::new(); + fixture + .add_crate("core", INHERITS) + .write("crates/core/src/lib.rs", LIB) + .write("standard.toml", "denied-fields = [\"token\", \"path\"]\n"); + let message = |line: usize, macro_name: &str, field: &str, denied: &str| { + format!( + "crates/core/src/lib.rs:{line}: `{macro_name}!` records the field `{field}`, and \ + telemetry never holds a `{denied}` (`denied-fields` in standard.toml): leave it \ + out (tracing-fields)" + ) + }; + assert_eq!( + fixture.violations(Rule::TracingFields), + [ + message(2, "info", "token", "token"), + message(3, "info", "request.path", "path"), + message(6, "warn", "token", "token"), + ] + ); + + fixture.write("standard.toml", ""); + assert_eq!( + fixture.violations(Rule::TracingFields), + Vec::::new() + ); +} diff --git a/crates/sourceorigin-standard/src/rules/tracing_fields.rs b/crates/sourceorigin-standard/src/rules/tracing_fields.rs new file mode 100644 index 0000000..93f646e --- /dev/null +++ b/crates/sourceorigin-standard/src/rules/tracing_fields.rs @@ -0,0 +1,118 @@ +//! `tracing-fields`: telemetry never records the fields `standard.toml` +//! denies. + +use std::path::Path; + +use proc_macro2::{Spacing, TokenTree}; + +use super::walk::{Inspect, Scope, Walk}; +use super::{Finding, Repository}; +use crate::config::{self, Listed}; + +/// The `tracing` macros that record fields. +const MACROS: &[&str] = &[ + "trace", + "debug", + "info", + "warn", + "error", + "event", + "span", + "trace_span", + "debug_span", + "info_span", + "warn_span", + "error_span", +]; + +/// The denied fields outside test code that one file's events and spans +/// record. +struct Fields<'a> { + path: &'a Path, + denied: &'a [Listed], + findings: Vec, +} + +impl Inspect for Fields<'_> { + fn macro_call(&mut self, call: &syn::Macro, scope: Scope) { + let Some(last) = call.path.segments.last() else { + return; + }; + if scope.test || !MACROS.contains(&last.ident.to_string().as_str()) { + return; + } + let tokens: Vec = call.tokens.clone().into_iter().collect(); + for argument in + tokens.split(|token| matches!(token, TokenTree::Punct(punct) if punct.as_char() == ',')) + { + let Some(name) = Self::field(argument) else { + if matches!(argument.first(), Some(TokenTree::Literal(_))) { + break; + } + continue; + }; + let denied = name + .split('.') + .find(|part| self.denied.iter().any(|entry| entry.value == *part)); + if let Some(denied) = denied { + self.findings.push(Finding { + path: self.path.to_owned(), + line: last.ident.span().start().line, + message: format!( + "`{}!` records the field `{name}`, and telemetry never holds a \ + `{denied}` (`denied-fields` in {}): leave it out", + last.ident, + config::PATH + ), + }); + } + } + } +} + +impl Fields<'_> { + /// The name of the field `argument` records, such as `http.path` for + /// `http.path = %path` or `token` for `?token`; `None` for the message + /// and its format arguments, and for `target:`, `parent:` or `name:`. + fn field(argument: &[TokenTree]) -> Option { + let mut name = String::new(); + let mut tokens = argument.iter().skip_while(|token| { + matches!(token, TokenTree::Punct(punct) if matches!(punct.as_char(), '%' | '?')) + }); + for token in tokens.by_ref() { + match token { + TokenTree::Ident(ident) => name.push_str(&ident.to_string()), + TokenTree::Punct(punct) if punct.as_char() == '.' => name.push('.'), + TokenTree::Punct(punct) + if punct.as_char() == '=' && punct.spacing() == Spacing::Alone => + { + return (!name.is_empty()).then_some(name); + } + TokenTree::Group(_) | TokenTree::Literal(_) | TokenTree::Punct(_) => return None, + } + } + (!name.is_empty()).then_some(name) + } +} + +impl Repository { + /// Each field outside test code a `tracing` event or span records whose + /// name, or a dotted part of it, `denied-fields` lists. + pub(super) fn tracing_fields(&self) -> Vec { + let denied = &self.config.denied_fields; + if denied.is_empty() { + return Vec::new(); + } + let mut findings = Vec::new(); + for source in self.sources.iter().filter(|source| !source.generated) { + let mut fields = Fields { + path: &source.path, + denied, + findings: Vec::new(), + }; + Walk::file(source, self.modules.is_test(&source.path), &mut fields); + findings.extend(fields.findings); + } + findings + } +}