Skip to main content

ulo/
panic.rs

1//! The process's panic hook. Rust runs the installed hook for every panic, on the panicking thread,
2//! before the unwinding reaches any `catch_unwind`, so what ulo redacts in a caught panic reaches
3//! its reports and never what the hook already printed; the default hook prints the raw message.
4//! [`install_redacting_hook`] replaces it with one that prints the message redacted. ulo never
5//! installs it: the hook is the process's, and a library replacing it would replace the
6//! application's own.
7
8use std::any::Any;
9use std::backtrace::Backtrace;
10use std::io::Write;
11use std::panic::{Location, PanicHookInfo};
12use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
13
14use crate::redact::{self, SecretRegistry};
15
16/// Replaces the process's panic hook with one that prints each panic's message after the redaction
17/// ulo applies to a panic it catches: every secret the process's apps registered replaced by
18/// `[redacted]`, and the userinfo of anything shaped like a URL stripped. For an application to
19/// call at the start of `main`, before anything can panic.
20///
21/// The secrets are those of every graph an app took in this process, at `wire` and at each `load`,
22/// an app since dropped included, and every text [`collect_secrets`] collected, so the hook can be
23/// installed before the app is wired. A panic before anything is recorded, such as one while a
24/// configuration loads outside `collect_secrets`, is printed with the userinfo strip alone.
25///
26/// The hook writes to stderr `panicked at <file>:<line>:<column>:` and the redacted message, then
27/// the backtrace when `RUST_BACKTRACE` enables one, every frame under `full`, or, after the first
28/// panic only, the note the default hook writes naming `RUST_BACKTRACE`. `RUST_LIB_BACKTRACE`
29/// leaves it unchanged, as it leaves the default hook. The thread's name is left out: reading it panics
30/// once the thread's local data is gone, and a panic inside a panic hook aborts the process. For
31/// the same reason nothing in the hook unwraps, a failed write to stderr is ignored, and the
32/// secrets are read without waiting on their lock: a read that finds a writer in it on every one
33/// of a bounded number of tries prints
34/// `[message withheld: the secrets to redact it with could not be read]` in place of the message.
35///
36/// The hook it replaces is not called, whether the default, the application's own or a library's.
37/// A hook reads the message from the `PanicHookInfo` it is given, which nothing outside the
38/// standard library builds with another message, so calling the previous hook would print the
39/// raw message beside the redacted one. An application with a hook of its own, a crash reporter
40/// say, installs that hook instead of this one, and ulo redacts nothing it prints. Calling this
41/// again installs the same hook again.
42///
43/// # Panics
44///
45/// When called from a panicking thread, as [`std::panic::set_hook`] does.
46///
47/// ```
48/// ulo::panic::install_redacting_hook();
49/// // Wire, connect and serve the app: a panic anywhere in the process now prints redacted.
50/// let caught = std::panic::catch_unwind(|| panic!("connecting to postgres://app:hunter2@db/main"));
51/// assert!(caught.is_err());
52/// // stderr: panicked at <file>:<line>:<column>:
53/// //         connecting to postgres://[redacted]@db/main
54/// ```
55///
56/// [`collect_secrets`]: crate::secrets::collect_secrets
57pub fn install_redacting_hook() {
58    std::panic::set_hook(Box::new(hook));
59}
60
61fn hook(info: &PanicHookInfo<'_>) {
62    let report = redact::with_process_secrets(|secrets| report(info.location(), info.payload(), secrets))
63        .unwrap_or_else(|| withheld(info.location()));
64    let mut stderr = std::io::stderr().lock();
65    let _ = stderr.write_all(report.as_bytes());
66    match backtrace_style() {
67        SHORT => {
68            let _ = writeln!(stderr, "stack backtrace:\n{}", Backtrace::force_capture());
69        }
70        FULL => {
71            let _ = writeln!(stderr, "stack backtrace:\n{:#}", Backtrace::force_capture());
72        }
73        _ => {
74            if FIRST_PANIC.swap(false, Ordering::Relaxed) {
75                let _ = writeln!(stderr, "note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace");
76            }
77        }
78    }
79    let _ = stderr.flush();
80}
81
82/// Cleared by the first panic the hook prints, which alone carries the backtrace note.
83static FIRST_PANIC: AtomicBool = AtomicBool::new(true);
84
85const UNREAD: u8 = 0;
86const OFF: u8 = 1;
87const SHORT: u8 = 2;
88const FULL: u8 = 3;
89
90/// `RUST_BACKTRACE` as the default hook reads it, read once: unset or `0` prints no backtrace,
91/// `full` every frame, any other value the short form. `RUST_LIB_BACKTRACE` is not read:
92/// `Backtrace::capture` reads it ahead of `RUST_BACKTRACE`, and it configures the backtraces
93/// errors capture, not a panic's.
94fn backtrace_style() -> u8 {
95    static STYLE: AtomicU8 = AtomicU8::new(UNREAD);
96    let style = STYLE.load(Ordering::Relaxed);
97    if style != UNREAD {
98        return style;
99    }
100    let style = match std::env::var_os("RUST_BACKTRACE") {
101        None => OFF,
102        Some(value) if value == "0" => OFF,
103        Some(value) if value == "full" => FULL,
104        Some(_) => SHORT,
105    };
106    STYLE.store(style, Ordering::Relaxed);
107    style
108}
109
110/// What the hook prints for a panic at `location` carrying `payload`, its message redacted with
111/// `secrets` by the function a caught panic's message passes through.
112fn report(location: Option<&Location<'_>>, payload: &(dyn Any + Send), secrets: &SecretRegistry) -> String {
113    let message = redact::scrub(secrets, &redact::panic_text(payload));
114    format!("{}:\n{message}\n", heading(location))
115}
116
117/// What the hook prints when the secrets could not be read.
118fn withheld(location: Option<&Location<'_>>) -> String {
119    format!("{}:\n[message withheld: the secrets to redact it with could not be read]\n", heading(location))
120}
121
122fn heading(location: Option<&Location<'_>>) -> String {
123    match location {
124        Some(at) => format!("panicked at {at}"),
125        None => "panicked".to_owned(),
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    const SECRET: &str = "report-token-4471";
134
135    fn registry() -> SecretRegistry {
136        let mut secrets = SecretRegistry::default();
137        secrets.register(SECRET.to_owned());
138        secrets
139    }
140
141    /// The report replaces a registered secret and a url's userinfo, keeps the rest of the message
142    /// and names the location.
143    #[test]
144    fn a_report_carries_the_message_redacted_at_its_location() {
145        let payload: Box<dyn Any + Send> = Box::new(format!("connecting with {SECRET} to postgres://app:pw@db/main"));
146        let report = report(Some(Location::caller()), &*payload, &registry());
147        assert!(!report.contains(SECRET) && !report.contains("app:pw"), "{report}");
148        assert!(report.contains("connecting with [redacted] to postgres://[redacted]@db/main"), "{report}");
149        assert!(report.starts_with(&format!("panicked at {}:", file!())), "{report}");
150    }
151
152    /// A payload that is no string is reported by the text a caught panic's carries.
153    #[test]
154    fn a_payload_that_is_no_string_is_named_as_such() {
155        let payload: Box<dyn Any + Send> = Box::new(7u32);
156        let report = report(None, &*payload, &registry());
157        assert_eq!(report, "panicked:\na panic whose payload is not a string\n");
158    }
159
160    /// A writer holding the registry's lock on the panicking thread, which the swap never does,
161    /// leaves the hook's read refused rather than waiting: the message is withheld, and the read
162    /// returns.
163    #[test]
164    fn a_registry_whose_lock_is_held_is_withheld_and_never_waited_on() {
165        redact::record_for_process(&[SECRET.to_owned()]);
166        let held = redact::hold_process_lock_for_test();
167        let read = redact::with_process_secrets(|secrets| secrets.texts.len());
168        drop(held);
169        assert_eq!(read, None, "the read did not see the lock held");
170        let after = redact::with_process_secrets(|secrets| secrets.texts.contains(&SECRET.to_owned()));
171        assert_eq!(after, Some(true), "the recorded secret, once the lock is released");
172    }
173}