Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/sourceorigin-standard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions crates/sourceorigin-standard/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ pub(crate) struct Config {
pub(crate) no_json_macro: Vec<Listed>,
/// The modules that own HTTP paths, such as `my_app::routes`.
pub(crate) route_modules: Vec<Listed>,
/// The field names `tracing` events and spans never record, such as
/// `token`.
pub(crate) denied_fields: Vec<Listed>,
/// The `[comments]` table.
pub(crate) comments: Comments,
}
Expand Down Expand Up @@ -229,6 +232,7 @@ struct File {
unsafe_modules: Vec<Spanned<String>>,
no_json_macro: Vec<Spanned<String>>,
route_modules: Vec<Spanned<String>>,
denied_fields: Vec<Spanned<String>>,
comments: Comments,
}

Expand Down Expand Up @@ -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,
})
}
Expand Down
6 changes: 6 additions & 0 deletions crates/sourceorigin-standard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod source;
mod test_code;
#[cfg(test)]
mod tests;
mod tracing_fields;
mod unsafe_modules;
mod walk;
mod workspace_lints;
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions crates/sourceorigin-standard/src/rules/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
46 changes: 46 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/tracing_fields.rs
Original file line number Diff line number Diff line change
@@ -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::<String>::new()
);
}
118 changes: 118 additions & 0 deletions crates/sourceorigin-standard/src/rules/tracing_fields.rs
Original file line number Diff line number Diff line change
@@ -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<Finding>,
}

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<TokenTree> = 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<String> {
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<Finding> {
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
}
}