Skip to main content

aidaemon_core/
redaction.rs

1//! Secret redaction at the kernel boundary.
2//!
3//! Every value registered in the agent's [`RedactionScope`] (by default the
4//! process-wide one, where [`register_secret`] puts a value and
5//! `aidaemon_secrets` registers each secret it hands out) and everything a
6//! hook's [`Redact`] recognizes (the policies crate's `Redactor`: credential
7//! shapes and literals) is replaced with `[REDACTED:...]` in what leaves the
8//! kernel:
9//!
10//! - every model request (the whole transcript, after `before_model` hooks);
11//! - every event, before sinks and the store see it;
12//! - receipts: arguments, details and reason;
13//! - the interruption put to the owner (call arguments, reason, request);
14//! - the transcript and receipts in the saved and returned [`crate::RunState`],
15//!   and the run's final text.
16//!
17//! What it does not cover: the exact arguments of a call that has not run
18//! yet (a paused call in `RunState::pending`, a batch in flight) stay as the
19//! model sent them so the call can run; a secret shorter than
20//! [`MIN_SECRET_CHARS`] (refused, since redacting it would garble ordinary
21//! text); encodings of a secret (hex, base64) or a secret split across
22//! streamed text deltas.
23
24use std::borrow::Cow;
25use std::sync::{Arc, OnceLock, RwLock};
26
27/// Secrets shorter than this are refused: redacting every `abc` would
28/// destroy output without protecting anything.
29pub const MIN_SECRET_CHARS: usize = 6;
30
31/// A secret too short to redact safely.
32#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
33#[error(
34    "a secret of {chars} characters is too short to redact (the minimum is {MIN_SECRET_CHARS}); \
35     it will appear as is wherever it is used"
36)]
37pub struct SecretTooShort {
38    pub chars: usize,
39}
40
41/// A set of registered secrets: what an agent's runs redact, beside its
42/// hooks' [`Redact`]ers.
43///
44/// [`RedactionScope::process`] is the process-wide set, every agent's
45/// default ([`crate::AgentBuilder::redaction_scope`]) and the daemon's: a
46/// value registered there is hidden from every run in the process and is
47/// never removed. [`RedactionScope::isolated`] is a set of its own, for an
48/// agent (or a test) whose secrets must not reach other agents' runs, and
49/// whose runs must not depend on what other code registered. Give the same
50/// scope to everything that registers for that agent: its secret store and
51/// its `Redactor` hook. Cheap to clone; clones share the set.
52#[derive(Clone)]
53pub struct RedactionScope {
54    secrets: Arc<RwLock<Vec<String>>>,
55}
56
57impl RedactionScope {
58    /// The process-wide set.
59    pub fn process() -> Self {
60        static PROCESS: OnceLock<RedactionScope> = OnceLock::new();
61        PROCESS.get_or_init(Self::isolated).clone()
62    }
63
64    /// A new, empty set shared with no one but its clones.
65    pub fn isolated() -> Self {
66        Self {
67            secrets: Arc::default(),
68        }
69    }
70
71    /// Whether this is the process-wide set.
72    pub fn is_process(&self) -> bool {
73        Arc::ptr_eq(&self.secrets, &Self::process().secrets)
74    }
75
76    /// Redact `value` from everything this scope's runs send out. Errors
77    /// (and registers nothing) for a value under [`MIN_SECRET_CHARS`].
78    pub fn register(&self, value: &str) -> Result<(), SecretTooShort> {
79        let chars = value.chars().count();
80        if chars < MIN_SECRET_CHARS {
81            return Err(SecretTooShort { chars });
82        }
83        let mut secrets = self
84            .secrets
85            .write()
86            .unwrap_or_else(std::sync::PoisonError::into_inner);
87        if !secrets.iter().any(|known| known == value) {
88            secrets.push(value.to_string());
89            // Longest first, so a secret that contains another is fully hidden.
90            secrets.sort_by_key(|s| std::cmp::Reverse(s.len()));
91        }
92        Ok(())
93    }
94
95    /// `text` with every secret in this scope replaced by
96    /// `[REDACTED:secret]`.
97    pub fn redact<'a>(&self, text: &'a str) -> Cow<'a, str> {
98        let secrets = self
99            .secrets
100            .read()
101            .unwrap_or_else(std::sync::PoisonError::into_inner);
102        let mut out = Cow::Borrowed(text);
103        for secret in secrets.iter() {
104            if out.contains(secret.as_str()) {
105                out = Cow::Owned(out.replace(secret.as_str(), "[REDACTED:secret]"));
106            }
107        }
108        out
109    }
110
111    /// How many secrets are registered.
112    pub fn len(&self) -> usize {
113        self.secrets
114            .read()
115            .unwrap_or_else(std::sync::PoisonError::into_inner)
116            .len()
117    }
118
119    pub fn is_empty(&self) -> bool {
120        self.len() == 0
121    }
122}
123
124/// The process-wide set, as for an agent that names none.
125impl Default for RedactionScope {
126    fn default() -> Self {
127        Self::process()
128    }
129}
130
131/// Never the values: which set it is and how many it holds.
132impl std::fmt::Debug for RedactionScope {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        f.debug_struct("RedactionScope")
135            .field("process", &self.is_process())
136            .field("secrets", &self.len())
137            .finish()
138    }
139}
140
141/// Register `value` in the process-wide scope
142/// ([`RedactionScope::process`]), which every agent uses unless it is given
143/// another. Errors (and registers nothing) for a value under
144/// [`MIN_SECRET_CHARS`].
145pub fn register_secret(value: &str) -> Result<(), SecretTooShort> {
146    RedactionScope::process().register(value)
147}
148
149/// `text` with every secret registered in the process-wide scope replaced
150/// by `[REDACTED:secret]`.
151pub fn redact_registered(text: &str) -> Cow<'_, str> {
152    RedactionScope::process().redact(text)
153}
154
155/// Something that hides secrets in text. A hook offers one through
156/// [`crate::Hook::redactor`], and the kernel applies it at the boundary.
157pub trait Redact: Send + Sync {
158    fn redact(&self, text: &str) -> String;
159}
160
161/// The kernel's one redaction pass: the agent's [`RedactionScope`], then
162/// every hook's [`Redact`].
163pub(crate) struct Scrubber<'a> {
164    pub scope: &'a RedactionScope,
165    pub hooks: &'a [std::sync::Arc<dyn crate::Hook>],
166}
167
168impl Scrubber<'_> {
169    /// `text` redacted, or `None` when nothing changed.
170    fn changed(&self, text: &str) -> Option<String> {
171        let mut out = match self.scope.redact(text) {
172            Cow::Borrowed(_) => None,
173            Cow::Owned(owned) => Some(owned),
174        };
175        for hook in self.hooks {
176            if let Some(redactor) = hook.redactor() {
177                let current = out.as_deref().unwrap_or(text);
178                let redacted = redactor.redact(current);
179                if redacted != current {
180                    out = Some(redacted);
181                }
182            }
183        }
184        out
185    }
186
187    pub fn text(&self, text: &mut String) {
188        if let Some(redacted) = self.changed(text) {
189            *text = redacted;
190        }
191    }
192
193    /// Redact every string in `value`. Returns whether anything changed.
194    pub fn value(&self, value: &mut serde_json::Value) -> bool {
195        use serde_json::Value;
196        match value {
197            Value::String(text) => match self.changed(text) {
198                Some(redacted) => {
199                    *text = redacted;
200                    true
201                }
202                None => false,
203            },
204            Value::Array(items) => items
205                .iter_mut()
206                .fold(false, |changed, item| self.value(item) | changed),
207            Value::Object(map) => map
208                .values_mut()
209                .fold(false, |changed, item| self.value(item) | changed),
210            _ => false,
211        }
212    }
213
214    /// A message's text and its tool calls' arguments (not its images).
215    pub fn message(&self, message: &mut crate::Message) {
216        self.text(&mut message.content);
217        for call in &mut message.tool_calls {
218            self.value(&mut call.arguments);
219        }
220        if let Some(reasoning) = &mut message.reasoning {
221            self.text(reasoning);
222        }
223    }
224
225    pub fn receipt(&self, receipt: &mut crate::Receipt) {
226        self.value(&mut receipt.arguments);
227        self.value(&mut receipt.details);
228        if let Some(reason) = &mut receipt.reason {
229            self.text(reason);
230        }
231    }
232
233    /// Any serializable value, through its JSON form.
234    pub fn json<T>(&self, item: &mut T)
235    where
236        T: serde::Serialize + serde::de::DeserializeOwned,
237    {
238        let Ok(mut value) = serde_json::to_value(&*item) else {
239            return;
240        };
241        if self.value(&mut value)
242            && let Ok(redacted) = serde_json::from_value(value)
243        {
244            *item = redacted;
245        }
246    }
247}