use std::any::Any;
use std::backtrace::Backtrace;
use std::io::Write;
use std::panic::{Location, PanicHookInfo};
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use crate::redact::{self, SecretRegistry};
pub fn install_redacting_hook() {
std::panic::set_hook(Box::new(hook));
}
fn hook(info: &PanicHookInfo<'_>) {
let report = redact::with_process_secrets(|secrets| report(info.location(), info.payload(), secrets))
.unwrap_or_else(|| withheld(info.location()));
let mut stderr = std::io::stderr().lock();
let _ = stderr.write_all(report.as_bytes());
match backtrace_style() {
SHORT => {
let _ = writeln!(stderr, "stack backtrace:\n{}", Backtrace::force_capture());
}
FULL => {
let _ = writeln!(stderr, "stack backtrace:\n{:#}", Backtrace::force_capture());
}
_ => {
if FIRST_PANIC.swap(false, Ordering::Relaxed) {
let _ = writeln!(stderr, "note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace");
}
}
}
let _ = stderr.flush();
}
static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
const UNREAD: u8 = 0;
const OFF: u8 = 1;
const SHORT: u8 = 2;
const FULL: u8 = 3;
fn backtrace_style() -> u8 {
static STYLE: AtomicU8 = AtomicU8::new(UNREAD);
let style = STYLE.load(Ordering::Relaxed);
if style != UNREAD {
return style;
}
let style = match std::env::var_os("RUST_BACKTRACE") {
None => OFF,
Some(value) if value == "0" => OFF,
Some(value) if value == "full" => FULL,
Some(_) => SHORT,
};
STYLE.store(style, Ordering::Relaxed);
style
}
fn report(location: Option<&Location<'_>>, payload: &(dyn Any + Send), secrets: &SecretRegistry) -> String {
let message = redact::scrub(secrets, &redact::panic_text(payload));
format!("{}:\n{message}\n", heading(location))
}
fn withheld(location: Option<&Location<'_>>) -> String {
format!("{}:\n[message withheld: the secrets to redact it with could not be read]\n", heading(location))
}
fn heading(location: Option<&Location<'_>>) -> String {
match location {
Some(at) => format!("panicked at {at}"),
None => "panicked".to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
const SECRET: &str = "report-token-4471";
fn registry() -> SecretRegistry {
let mut secrets = SecretRegistry::default();
secrets.register(SECRET.to_owned());
secrets
}
#[test]
fn a_report_carries_the_message_redacted_at_its_location() {
let payload: Box<dyn Any + Send> = Box::new(format!("connecting with {SECRET} to postgres://app:pw@db/main"));
let report = report(Some(Location::caller()), &*payload, ®istry());
assert!(!report.contains(SECRET) && !report.contains("app:pw"), "{report}");
assert!(report.contains("connecting with [redacted] to postgres://[redacted]@db/main"), "{report}");
assert!(report.starts_with(&format!("panicked at {}:", file!())), "{report}");
}
#[test]
fn a_payload_that_is_no_string_is_named_as_such() {
let payload: Box<dyn Any + Send> = Box::new(7u32);
let report = report(None, &*payload, ®istry());
assert_eq!(report, "panicked:\na panic whose payload is not a string\n");
}
#[test]
fn a_registry_whose_lock_is_held_is_withheld_and_never_waited_on() {
redact::record_for_process(&[SECRET.to_owned()]);
let held = redact::hold_process_lock_for_test();
let read = redact::with_process_secrets(|secrets| secrets.texts.len());
drop(held);
assert_eq!(read, None, "the read did not see the lock held");
let after = redact::with_process_secrets(|secrets| secrets.texts.contains(&SECRET.to_owned()));
assert_eq!(after, Some(true), "the recorded secret, once the lock is released");
}
}