use std::borrow::Cow;
use std::sync::{Arc, OnceLock, RwLock};
pub const MIN_SECRET_CHARS: usize = 6;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
"a secret of {chars} characters is too short to redact (the minimum is {MIN_SECRET_CHARS}); \
it will appear as is wherever it is used"
)]
pub struct SecretTooShort {
pub chars: usize,
}
#[derive(Clone)]
pub struct RedactionScope {
secrets: Arc<RwLock<Vec<String>>>,
}
impl RedactionScope {
pub fn process() -> Self {
static PROCESS: OnceLock<RedactionScope> = OnceLock::new();
PROCESS.get_or_init(Self::isolated).clone()
}
pub fn isolated() -> Self {
Self {
secrets: Arc::default(),
}
}
pub fn is_process(&self) -> bool {
Arc::ptr_eq(&self.secrets, &Self::process().secrets)
}
pub fn register(&self, value: &str) -> Result<(), SecretTooShort> {
let chars = value.chars().count();
if chars < MIN_SECRET_CHARS {
return Err(SecretTooShort { chars });
}
let mut secrets = self
.secrets
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !secrets.iter().any(|known| known == value) {
secrets.push(value.to_string());
secrets.sort_by_key(|s| std::cmp::Reverse(s.len()));
}
Ok(())
}
pub fn redact<'a>(&self, text: &'a str) -> Cow<'a, str> {
let secrets = self
.secrets
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let mut out = Cow::Borrowed(text);
for secret in secrets.iter() {
if out.contains(secret.as_str()) {
out = Cow::Owned(out.replace(secret.as_str(), "[REDACTED:secret]"));
}
}
out
}
pub fn len(&self) -> usize {
self.secrets
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl Default for RedactionScope {
fn default() -> Self {
Self::process()
}
}
impl std::fmt::Debug for RedactionScope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RedactionScope")
.field("process", &self.is_process())
.field("secrets", &self.len())
.finish()
}
}
pub fn register_secret(value: &str) -> Result<(), SecretTooShort> {
RedactionScope::process().register(value)
}
pub fn redact_registered(text: &str) -> Cow<'_, str> {
RedactionScope::process().redact(text)
}
pub trait Redact: Send + Sync {
fn redact(&self, text: &str) -> String;
}
pub(crate) struct Scrubber<'a> {
pub scope: &'a RedactionScope,
pub hooks: &'a [std::sync::Arc<dyn crate::Hook>],
}
impl Scrubber<'_> {
fn changed(&self, text: &str) -> Option<String> {
let mut out = match self.scope.redact(text) {
Cow::Borrowed(_) => None,
Cow::Owned(owned) => Some(owned),
};
for hook in self.hooks {
if let Some(redactor) = hook.redactor() {
let current = out.as_deref().unwrap_or(text);
let redacted = redactor.redact(current);
if redacted != current {
out = Some(redacted);
}
}
}
out
}
pub fn text(&self, text: &mut String) {
if let Some(redacted) = self.changed(text) {
*text = redacted;
}
}
pub fn value(&self, value: &mut serde_json::Value) -> bool {
use serde_json::Value;
match value {
Value::String(text) => match self.changed(text) {
Some(redacted) => {
*text = redacted;
true
}
None => false,
},
Value::Array(items) => items
.iter_mut()
.fold(false, |changed, item| self.value(item) | changed),
Value::Object(map) => map
.values_mut()
.fold(false, |changed, item| self.value(item) | changed),
_ => false,
}
}
pub fn message(&self, message: &mut crate::Message) {
self.text(&mut message.content);
for call in &mut message.tool_calls {
self.value(&mut call.arguments);
}
if let Some(reasoning) = &mut message.reasoning {
self.text(reasoning);
}
}
pub fn receipt(&self, receipt: &mut crate::Receipt) {
self.value(&mut receipt.arguments);
self.value(&mut receipt.details);
if let Some(reason) = &mut receipt.reason {
self.text(reason);
}
}
pub fn json<T>(&self, item: &mut T)
where
T: serde::Serialize + serde::de::DeserializeOwned,
{
let Ok(mut value) = serde_json::to_value(&*item) else {
return;
};
if self.value(&mut value)
&& let Ok(redacted) = serde_json::from_value(value)
{
*item = redacted;
}
}
}