use std::any::Any;
use std::error::Error;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, PoisonError, RwLock};
use crate::timer::BoxError;
pub struct Redacted {
inner: BoxError,
text: String,
}
impl Redacted {
pub fn downcast_ref<E: Error + 'static>(&self) -> Option<&E> {
self.inner.downcast_ref::<E>()
}
pub fn into_inner(self) -> BoxError {
self.inner
}
pub(crate) fn from_parts(inner: BoxError, text: String) -> Self {
Redacted { inner, text }
}
}
impl fmt::Display for Redacted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
impl fmt::Debug for Redacted {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
impl Error for Redacted {
fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct Secret<T> {
value: T,
}
impl<T> Secret<T> {
pub fn new(value: T) -> Self {
Secret { value }
}
pub fn expose(&self) -> &T {
&self.value
}
pub fn into_inner(self) -> T {
self.value
}
}
impl<T: Hash> Hash for Secret<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.value.hash(state);
}
}
impl<T> fmt::Debug for Secret<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Secret([redacted])")
}
}
impl<T> fmt::Display for Secret<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
impl From<String> for Secret<String> {
fn from(value: String) -> Self {
Secret::new(value)
}
}
impl From<&str> for Secret<String> {
fn from(value: &str) -> Self {
Secret::new(value.to_owned())
}
}
#[derive(Clone, Default)]
pub(crate) struct SecretRegistry {
pub(crate) texts: Vec<String>,
}
impl SecretRegistry {
pub(crate) fn register(&mut self, text: String) {
if !text.is_empty() && !self.texts.contains(&text) {
self.texts.push(text);
}
}
pub(crate) fn register_if_secret(&mut self, value: &dyn Any) {
let secret = value
.downcast_ref::<Secret<String>>()
.or_else(|| value.downcast_ref::<Arc<Secret<String>>>().map(|s| &**s));
if let Some(secret) = secret {
self.register(secret.expose().clone());
}
}
fn replace(&self, text: &str) -> String {
let mut secrets: Vec<&str> = self.texts.iter().map(String::as_str).filter(|s| !s.is_empty()).collect();
if secrets.is_empty() {
return text.to_owned();
}
secrets.sort_by(|a, b| b.len().cmp(&a.len()));
let mut out = String::with_capacity(text.len());
let mut rest = text;
'scan: while !rest.is_empty() {
for secret in &secrets {
if let Some(after) = rest.strip_prefix(*secret) {
out.push_str(MARKER);
rest = after;
continue 'scan;
}
}
let mut chars = rest.chars();
if let Some(c) = chars.next() {
out.push(c);
}
rest = chars.as_str();
}
out
}
}
#[derive(Clone, Default)]
pub(crate) struct Redactor(Arc<RwLock<Arc<SecretRegistry>>>);
impl Redactor {
pub(crate) fn set(&self, secrets: &SecretRegistry) {
*self.0.write().unwrap_or_else(PoisonError::into_inner) = Arc::new(secrets.clone());
}
pub(crate) fn panic(&self, payload: Box<dyn Any + Send>) -> Redacted {
let secrets = Arc::clone(&*self.0.read().unwrap_or_else(PoisonError::into_inner));
redact_panic(&secrets, payload)
}
}
const MARKER: &str = "[redacted]";
pub(crate) fn redact(secrets: &SecretRegistry, error: BoxError) -> Redacted {
let text = scrub(secrets, &chain_text(&*error));
Redacted::from_parts(error, text)
}
pub(crate) fn redact_as(secrets: &SecretRegistry, error: BoxError, text: String) -> Redacted {
Redacted::from_parts(error, scrub(secrets, &text))
}
pub(crate) fn redact_panic(secrets: &SecretRegistry, payload: Box<dyn Any + Send>) -> Redacted {
let message = if let Some(s) = payload.downcast_ref::<&'static str>() {
(*s).to_owned()
} else if let Some(s) = payload.downcast_ref::<String>() {
s.clone()
} else {
"a panic whose payload is not a string".to_owned()
};
let text = scrub(secrets, &message);
Redacted::from_parts(Box::new(PanicMessage(message)), text)
}
pub(crate) fn strip_userinfo(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(at) = rest.find("://") {
let (head, tail) = rest.split_at(at + "://".len());
out.push_str(head);
let end = tail
.find(|c: char| matches!(c, '/' | '?' | '#' | '"' | '\'' | '`' | '<' | '>') || c.is_whitespace())
.unwrap_or(tail.len());
let (authority, after) = tail.split_at(end);
match authority.rfind('@') {
Some(i) => {
out.push_str(MARKER);
out.push_str(&authority[i..]);
}
None => out.push_str(authority),
}
rest = after;
}
out.push_str(rest);
out
}
fn scrub(secrets: &SecretRegistry, text: &str) -> String {
strip_userinfo(&secrets.replace(text))
}
const MAX_CHAIN: usize = 32;
fn chain_text(error: &(dyn Error + 'static)) -> String {
let mut text = error.to_string();
let mut next = error.source();
let mut links = 0;
while let Some(cause) = next {
if links == MAX_CHAIN {
break;
}
let message = cause.to_string();
if !message.is_empty() && !text.contains(&message) {
text.push_str(": ");
text.push_str(&message);
}
next = cause.source();
links += 1;
}
text
}
#[derive(Debug)]
struct PanicMessage(String);
impl fmt::Display for PanicMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl Error for PanicMessage {}