Skip to main content

agent_first_data/
redaction.rs

1mod url;
2pub(crate) use url::valid_url_field;
3
4use self::url::{redact_url_field_value, redact_url_in_str, redact_urls_in_text_with_context};
5use crate::document::PathStep;
6use serde_json::Value;
7use std::collections::HashSet;
8
9// ═══════════════════════════════════════════
10// Public API: Output Formatters
11// ═══════════════════════════════════════════
12
13/// Which fields a [`Redactor`] scrubs. The default is [`RedactionPolicy::All`].
14///
15/// The policy selects a *scope* inside a structured value. A command line
16/// ([`Redactor::argv`]) and a bare URL string ([`Redactor::url`]) have no
17/// `result`/`trace` split to scope to, so on those two paths `TraceOnly`
18/// redacts in full like `All`, and only [`RedactionPolicy::Off`] turns
19/// redaction off.
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum RedactionPolicy {
22    /// Redact every secret field anywhere in the value (the default).
23    #[default]
24    All,
25    /// Redact only inside the top-level `trace` object.
26    TraceOnly,
27    /// Do not redact anything.
28    Off,
29}
30
31impl RedactionPolicy {
32    /// Whether this policy redacts an input that carries no scope of its own —
33    /// a command line or a single URL string, as opposed to a JSON value with a
34    /// `trace` object to narrow to.
35    ///
36    /// `TraceOnly` narrows *where* redaction applies within a value; it does not
37    /// weaken redaction. A standalone argv or URL has no non-`trace` half to
38    /// leave alone — and both are diagnostic material by construction, the very
39    /// thing `TraceOnly` scrubs — so `TraceOnly` redacts them in full, exactly
40    /// like `All`. Only `Off`, the caller explicitly asking for raw output,
41    /// disables redaction, and it does so on all three paths alike.
42    fn redacts_unscoped_input(self) -> bool {
43        !matches!(self, RedactionPolicy::Off)
44    }
45}
46
47/// Rendering style for plain (logfmt) output only. JSON and YAML are always
48/// structure-preserving and ignore this.
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub enum PlainStyle {
51    /// Human-readable AFDATA rendering: strip suffixes and format values.
52    #[default]
53    Readable,
54    /// Schema-preserving rendering: keep keys and values unchanged after redaction.
55    Raw,
56}
57
58/// Configurable redaction builder for secrets and legacy field names.
59///
60/// `Redactor` encapsulates redaction policy, custom secret field names, and
61/// exact legacy URL field names.
62/// Build with [`Redactor::new()`], configure via builder methods, then pass to
63/// redaction functions like [`redacted_value`] or [`redact_url_secrets`].
64#[derive(Clone, Debug, Default, PartialEq, Eq)]
65pub struct Redactor {
66    policy: RedactionPolicy,
67    secret_names: Vec<String>,
68    url_names: Vec<String>,
69    reveal_names: Vec<String>,
70}
71
72impl Redactor {
73    /// Create a new default redactor (full redaction, no custom secret names).
74    pub fn new() -> Self {
75        Self::default()
76    }
77
78    /// Set custom field names to treat as secrets in addition to `_secret` suffixes.
79    ///
80    /// Matching is exact field-name equality at any nesting level. The same
81    /// list also matches URL query-parameter names inside `_url` fields.
82    /// Builder style: returns `self`.
83    pub fn secret_names<I: IntoIterator<Item = S>, S: Into<String>>(mut self, names: I) -> Self {
84        self.secret_names = names.into_iter().map(|s| s.into()).collect();
85        self
86    }
87
88    /// Set exact legacy field names whose values should receive URL-aware
89    /// redaction in addition to `_url`/`_URL` suffixed fields.
90    ///
91    /// A matching string is handled like an `_url` value. Arrays and nested
92    /// collections recursively apply that treatment to every string leaf.
93    /// Matching is exact and does not normalize case, whitespace, or spelling.
94    #[must_use]
95    pub fn url_names<I: IntoIterator<Item = S>, S: Into<String>>(mut self, names: I) -> Self {
96        self.url_names = names.into_iter().map(Into::into).collect();
97        self
98    }
99
100    /// Reveal exactly these structured field names at any depth. Other secrets
101    /// remain masked; URL parameters and argv never use this exception.
102    #[must_use]
103    pub fn reveal_names<I: IntoIterator<Item = S>, S: Into<String>>(mut self, names: I) -> Self {
104        self.reveal_names = names.into_iter().map(Into::into).collect();
105        self
106    }
107
108    /// Set the redaction policy (default: full redaction).
109    /// Builder style: returns `self`.
110    pub fn policy(mut self, policy: RedactionPolicy) -> Self {
111        self.policy = policy;
112        self
113    }
114
115    /// Redact a JSON value copy using this redactor's policy and secret names.
116    ///
117    /// Clones `value` first; for a large payload you already own and can
118    /// mutate, prefer [`Redactor::redact_in_place`] to avoid the copy.
119    pub fn value(&self, value: &Value) -> Value {
120        let mut v = value.clone();
121        self.redact_in_place(&mut v);
122        v
123    }
124
125    /// Redact `value` as the node found at `path` inside a larger value: the
126    /// result is exactly what that node looks like in [`Redactor::value`] of
127    /// the whole.
128    ///
129    /// Taking a node out of its document drops the names above it, and those
130    /// names are what redaction reads. So `path` carries them back: an object
131    /// key on it that is secret (by `_secret` suffix or `secret_names`, and not
132    /// in `reveal_names`) masks the node whole — to `***`, except that a node
133    /// which is itself the secret field and is `null` stays `null`, as it does
134    /// in the whole. A key on it that is a URL field (`_url` suffix or
135    /// `url_names`) scrubs credentials from every string the node holds. The
136    /// policy scopes the same way too: under [`RedactionPolicy::TraceOnly`]
137    /// only a path into the top-level `trace` object is redacted.
138    ///
139    /// `path` is the structural route — [`PathStep::Field`] for each object key,
140    /// [`PathStep::Element`] for each array element — as
141    /// [`document::locate`](crate::document::locate) returns it. An
142    /// identifier that selected an element is not a key on the route, so it
143    /// never makes the element secret; the element's own keys still do.
144    pub fn value_at(&self, path: &[PathStep], value: &Value) -> Value {
145        let mut v = value.clone();
146        self.redact_in_place_at(path, &mut v);
147        v
148    }
149
150    /// [`Redactor::value_at`] without the copy.
151    pub fn redact_in_place_at(&self, path: &[PathStep], value: &mut Value) {
152        // The empty route is the whole value, which the policy scopes itself.
153        if path.is_empty() {
154            return self.redact_in_place(value);
155        }
156        let context = RedactionContext::from_redactor(self);
157        let Some(scope) = self.scope_of(path, &context) else {
158            return;
159        };
160        match judge_route(scope, &context) {
161            Route::Masked { at_node } => {
162                // The null exemption belongs to the secret field itself. A node
163                // below one was inside a value the whole render hides.
164                if !(at_node && value.is_null()) {
165                    *value = Value::String(REDACTED_MARKER.into());
166                }
167            }
168            Route::TooDeep => *value = Value::String(MAX_DEPTH_MARKER.into()),
169            Route::Url => redact_url_value_depth(value, &context, scope.len()),
170            Route::Plain => redact_secrets_with_context_depth(value, &context, scope.len()),
171        }
172    }
173
174    /// Whether the node at `path` is secret by name: some object key on the
175    /// route is secret and not revealed, within the policy's scope. This is
176    /// the gate for a caller about to print the raw node rather than its
177    /// redacted form. A URL field on the route does not count: whether its
178    /// strings carry a credential is a question about the value, which
179    /// [`Redactor::value_at`] answers.
180    pub fn is_secret_path(&self, path: &[PathStep]) -> bool {
181        let context = RedactionContext::from_redactor(self);
182        let Some(scope) = self.scope_of(path, &context) else {
183            return false;
184        };
185        scope.iter().any(|step| match step {
186            PathStep::Field(key) => context.is_masked_key(key),
187            PathStep::Element => false,
188        })
189    }
190
191    /// The part of `path` this redactor's policy judges, measured from the
192    /// root its walk starts at; `None` when the policy leaves the node alone.
193    fn scope_of<'p>(
194        &self,
195        path: &'p [PathStep],
196        context: &RedactionContext,
197    ) -> Option<&'p [PathStep]> {
198        match self.policy {
199            RedactionPolicy::All => Some(path),
200            // The whole render walks `trace` as its own root, so its route
201            // starts below that key.
202            RedactionPolicy::TraceOnly => match path.split_first() {
203                Some((PathStep::Field(key), rest)) if key == "trace" => {
204                    Some(if context.is_masked_key(key) {
205                        path
206                    } else {
207                        rest
208                    })
209                }
210                _ => None,
211            },
212            RedactionPolicy::Off => None,
213        }
214    }
215
216    /// Redact secret components of a URL string using this redactor's settings.
217    ///
218    /// A query parameter is redacted iff its (form-decoded) name ends in
219    /// `_secret`/`_SECRET` or matches an exact entry in `secret_names`. A
220    /// fragment written in the same `k=v&k=v` shape — how an OAuth implicit-flow
221    /// response carries its token — is redacted by that same rule; any other
222    /// fragment passes through byte-for-byte. The userinfo password
223    /// (`scheme://user:pass@host`) is always redacted as a structural rule.
224    /// Only the secret spans are replaced with `***`; every other byte is
225    /// preserved. A string that is not a single, whitespace-free,
226    /// scheme-prefixed URL (including a URL embedded in surrounding prose) is
227    /// returned unchanged.
228    ///
229    /// A URL is unscoped input: `RedactionPolicy::Off` returns it unchanged,
230    /// every other policy redacts it in full.
231    pub fn url(&self, url: &str) -> String {
232        if !self.policy.redacts_unscoped_input() {
233            return url.to_string();
234        }
235        let context = RedactionContext::from_redactor(self);
236        redact_url_in_str(url, &context).unwrap_or_else(|| url.to_string())
237    }
238
239    /// Redact complete scheme-prefixed URLs embedded in prose.
240    ///
241    /// This is deliberately explicit and independent from structured field
242    /// redaction. It recognizes URL spans only; it never scans surrounding text
243    /// for secret-looking names or values.
244    pub fn urls_in_text(&self, text: &str) -> String {
245        if !self.policy.redacts_unscoped_input() {
246            return text.to_string();
247        }
248        let context = RedactionContext::from_redactor(self);
249        redact_urls_in_text_with_context(text, &context)
250    }
251
252    /// Redact `value` in place, using this redactor's policy and secret names.
253    ///
254    /// The zero-copy counterpart of [`Redactor::value`] — use it on a large
255    /// payload you already own to avoid cloning.
256    pub fn redact_in_place(&self, value: &mut Value) {
257        let context = RedactionContext::from_redactor(self);
258        apply_redaction_policy_with_context(value, self.policy, &context);
259    }
260
261    /// Redact secret *values* out of a command line, using this redactor's
262    /// policy and secret names.
263    ///
264    /// A long flag whose name is secret by AFDATA naming (`--api-key-secret`,
265    /// or an exact `secret_names` entry) has its value replaced by `***`, in
266    /// both `--flag=value` and `--flag value` spellings. Everything else is
267    /// preserved byte-for-byte.
268    ///
269    /// Free text is deliberately never scanned: a bare `api_key_secret=sk-live`
270    /// positional, or a secret-looking token after a non-secret flag, is left
271    /// alone. AFDATA decides sensitivity from the *field name*, and argv is no
272    /// exception — rename the flag rather than pattern-matching values. A flag
273    /// with no value (end of argv, or followed by another flag) is likewise
274    /// left inspectable.
275    ///
276    /// Only long (`--`) flags are recognized, matching the convention's
277    /// long-flags-only rule.
278    ///
279    /// A command line is unscoped input: `RedactionPolicy::Off` returns `args`
280    /// unchanged, every other policy redacts in full.
281    pub fn argv<S: AsRef<str>>(&self, args: &[S]) -> Vec<String> {
282        if !self.policy.redacts_unscoped_input() {
283            return args.iter().map(|arg| arg.as_ref().to_string()).collect();
284        }
285        let context = RedactionContext::from_redactor(self);
286        let mut out = Vec::with_capacity(args.len());
287        let mut redact_next = false;
288        for arg in args {
289            let arg = arg.as_ref();
290            if redact_next {
291                redact_next = false;
292                if !arg.starts_with("--") {
293                    out.push(REDACTED_MARKER.to_string());
294                    continue;
295                }
296            }
297            if let Some(rest) = arg.strip_prefix("--") {
298                if let Some((name, _)) = rest.split_once('=') {
299                    if is_secret_flag_name(name, &context) {
300                        out.push(format!("--{name}={REDACTED_MARKER}"));
301                        continue;
302                    }
303                } else if is_secret_flag_name(rest, &context) {
304                    redact_next = true;
305                }
306            }
307            out.push(arg.to_string());
308        }
309        out
310    }
311
312    /// True when `name` would be treated as a secret field name by this
313    /// redactor: an exact `_secret`/`_SECRET` suffix, or an exact match
314    /// against a configured `secret_names` entry.
315    ///
316    /// This judges one name. A value taken out of a document is judged by its
317    /// whole route instead — a secret ancestor hides it as surely as a secret
318    /// leaf, and an identifier that selected an array element is not a name at
319    /// all — so use [`Redactor::is_secret_path`] and [`Redactor::value_at`]
320    /// there rather than testing the path's last segment with this.
321    pub fn is_secret_name(&self, name: &str) -> bool {
322        RedactionContext::from_redactor(self).is_secret_key(name)
323    }
324
325    /// True when `name` receives URL-aware structured-field redaction: an
326    /// exact `_url`/`_URL` suffix or an exact configured `url_names` entry.
327    ///
328    /// The counterpart to [`Redactor::is_secret_name`], with the same caveat:
329    /// for a value taken out of a document, [`Redactor::value_at`] applies the
330    /// URL scrubbing its route calls for.
331    pub fn is_url_name(&self, name: &str) -> bool {
332        RedactionContext::from_redactor(self).is_url_key(name)
333    }
334}
335
336impl From<RedactionPolicy> for Redactor {
337    fn from(policy: RedactionPolicy) -> Self {
338        Self {
339            policy,
340            secret_names: Vec::new(),
341            url_names: Vec::new(),
342            reveal_names: Vec::new(),
343        }
344    }
345}
346
347/// Output options combining redaction and rendering style.
348#[derive(Clone, Debug, Default, PartialEq, Eq)]
349pub struct OutputOptions {
350    /// Redactor applied before rendering.
351    pub redaction: Redactor,
352    /// Rendering style for plain output only.
353    pub style: PlainStyle,
354}
355
356impl From<RedactionPolicy> for OutputOptions {
357    fn from(policy: RedactionPolicy) -> Self {
358        Self {
359            redaction: Redactor::from(policy),
360            style: PlainStyle::default(),
361        }
362    }
363}
364
365// ═══════════════════════════════════════════
366// Public API: Redaction & Utility
367// ═══════════════════════════════════════════
368
369/// Return a JSON value copy with default `_secret` redaction applied.
370pub fn redacted_value(value: &Value) -> Value {
371    Redactor::new().value(value)
372}
373
374/// Redact secret values out of a command line, using default options.
375///
376/// Returns `args` with the value of every `_secret`-suffixed long flag replaced
377/// by `***`, covering both `--flag=value` and `--flag value`. Use
378/// [`Redactor::argv`] for custom `secret_names` or a non-default policy.
379///
380/// Intended for CLIs that record their own invocation — startup diagnostics,
381/// audit trails, crash reports — where writing argv verbatim would put a
382/// credential in the log.
383pub fn redact_argv<S: AsRef<str>>(args: &[S]) -> Vec<String> {
384    Redactor::new().argv(args)
385}
386
387/// Redact secret components of a single URL string, using default options.
388///
389/// Returns `url` with its userinfo password and any `_secret`-suffixed query
390/// parameter values replaced by `***`.
391pub fn redact_url_secrets(url: &str) -> String {
392    Redactor::new().url(url)
393}
394
395/// Redact complete scheme-prefixed URLs embedded in prose, using default
396/// secret-name rules.
397///
398/// This helper is opt-in. Ordinary structured redaction never scans prose.
399pub fn redact_urls_in_text(text: &str) -> String {
400    Redactor::new().urls_in_text(text)
401}
402
403// ═══════════════════════════════════════════
404// Secret Redaction
405// ═══════════════════════════════════════════
406
407/// The scalar every redacted span, value, and subtree is replaced with. Also
408/// the signal plain rendering reads to tell a hidden field from a live one.
409pub(crate) const REDACTED_MARKER: &str = "***";
410
411#[derive(Default)]
412pub(crate) struct RedactionContext {
413    secret_names: HashSet<String>,
414    url_names: HashSet<String>,
415    reveal_names: HashSet<String>,
416}
417
418impl RedactionContext {
419    fn from_redactor(redactor: &Redactor) -> Self {
420        let secret_names = redactor.secret_names.iter().cloned().collect();
421        let url_names = redactor.url_names.iter().cloned().collect();
422        Self {
423            secret_names,
424            url_names,
425            reveal_names: redactor.reveal_names.iter().cloned().collect(),
426        }
427    }
428
429    fn is_secret_key(&self, key: &str) -> bool {
430        key_has_secret_suffix(key) || self.secret_names.contains(key)
431    }
432
433    fn is_url_key(&self, key: &str) -> bool {
434        key_has_url_suffix(key) || self.url_names.contains(key)
435    }
436
437    /// A field whose value the structured walk replaces: secret, and not one
438    /// of the names the caller chose to reveal.
439    fn is_masked_key(&self, key: &str) -> bool {
440        self.is_secret_key(key) && !self.reveal_names.contains(key)
441    }
442}
443
444/// How the structured walk treats the node at the end of a route, decided by
445/// the keys above it exactly as the walk itself decides on its way down.
446enum Route {
447    /// A masked key is on the route; `at_node` when it is the route's last step.
448    Masked { at_node: bool },
449    /// The walk's depth bound is reached before the route ends.
450    TooDeep,
451    /// A URL field is on the route, so the node is walked in URL mode.
452    Url,
453    /// Nothing above the node changes how it is walked.
454    Plain,
455}
456
457fn judge_route(route: &[PathStep], context: &RedactionContext) -> Route {
458    let mut in_url = false;
459    for (depth, step) in route.iter().enumerate() {
460        // The step from a node at this depth to its child is taken while the
461        // walk is at that node, which it never reaches past the bound.
462        if depth >= MAX_DEPTH {
463            return Route::TooDeep;
464        }
465        let PathStep::Field(key) = step else {
466            continue;
467        };
468        // Same order as the walk: a masked key wins over a URL key, and a URL
469        // field's subtree stays in URL mode while still masking secret keys.
470        if context.is_masked_key(key) {
471            return Route::Masked {
472                at_node: depth + 1 == route.len(),
473            };
474        }
475        if context.is_url_key(key) {
476            in_url = true;
477        }
478    }
479    if in_url { Route::Url } else { Route::Plain }
480}
481
482fn key_has_secret_suffix(key: &str) -> bool {
483    key.ends_with("_secret") || key.ends_with("_SECRET")
484}
485
486fn key_has_url_suffix(key: &str) -> bool {
487    key.ends_with("_url") || key.ends_with("_URL")
488}
489
490/// Whether a long flag's name is secret, normalizing the kebab-case flag
491/// spelling to the snake_case field spelling the convention is defined in.
492///
493/// Ungated: core argv redaction relies on it.
494pub(crate) fn is_secret_flag_name(flag_name: &str, context: &RedactionContext) -> bool {
495    let normalized = flag_name.replace('-', "_");
496    context.is_secret_key(&normalized) || context.is_secret_key(flag_name)
497}
498
499const MAX_DEPTH: usize = 256;
500const MAX_DEPTH_MARKER: &str = "<afdata:max-depth>";
501
502fn redact_secrets_with_context(value: &mut Value, context: &RedactionContext) {
503    redact_secrets_with_context_depth(value, context, 0);
504}
505
506fn redact_secrets_with_context_depth(value: &mut Value, context: &RedactionContext, depth: usize) {
507    if depth >= MAX_DEPTH {
508        *value = Value::String(MAX_DEPTH_MARKER.into());
509        return;
510    }
511    match value {
512        Value::Object(map) => {
513            let keys: Vec<String> = map.keys().cloned().collect();
514            for key in keys {
515                if context.is_masked_key(&key) {
516                    // A null secret is an *absent* secret. Masking it would
517                    // manufacture the appearance of a configured credential:
518                    // readers cannot tell `"***"`-because-set from
519                    // `"***"`-because-null, so a tool showing its own config
520                    // would report every unset secret as configured. Redaction
521                    // hides a value that exists; it does not invent one.
522                    if !map.get(&key).is_some_and(Value::is_null) {
523                        map.insert(key, Value::String(REDACTED_MARKER.into()));
524                    }
525                } else if context.is_url_key(&key) {
526                    if let Some(v) = map.get_mut(&key) {
527                        redact_url_value_depth(v, context, depth + 1);
528                    }
529                } else if let Some(v) = map.get_mut(&key) {
530                    redact_secrets_with_context_depth(v, context, depth + 1);
531                }
532            }
533        }
534        Value::Array(arr) => {
535            for v in arr {
536                redact_secrets_with_context_depth(v, context, depth + 1);
537            }
538        }
539        _ => {}
540    }
541}
542
543fn redact_url_value_depth(value: &mut Value, context: &RedactionContext, depth: usize) {
544    if depth >= MAX_DEPTH {
545        *value = Value::String(MAX_DEPTH_MARKER.into());
546        return;
547    }
548    match value {
549        Value::String(text) => {
550            *text = redact_url_field_value(text, context);
551        }
552        Value::Array(values) => {
553            for value in values {
554                redact_url_value_depth(value, context, depth + 1);
555            }
556        }
557        Value::Object(values) => {
558            let keys = values.keys().cloned().collect::<Vec<_>>();
559            for key in keys {
560                if context.is_masked_key(&key) {
561                    if !values.get(&key).is_some_and(Value::is_null) {
562                        values.insert(key, Value::String(REDACTED_MARKER.into()));
563                    }
564                } else if let Some(value) = values.get_mut(&key) {
565                    redact_url_value_depth(value, context, depth + 1);
566                }
567            }
568        }
569        _ => {}
570    }
571}
572
573/// Redact secret components of a single URL string, returning `Some(redacted)`
574/// when `s` is a processable URL, or `None` when it is not (so callers can keep
575/// the original). Only secret spans change; all other bytes are preserved.
576fn apply_redaction_policy_with_context(
577    value: &mut Value,
578    redaction_policy: RedactionPolicy,
579    context: &RedactionContext,
580) {
581    match redaction_policy {
582        RedactionPolicy::All => redact_secrets_with_context(value, context),
583        RedactionPolicy::TraceOnly => {
584            if let Value::Object(map) = value
585                && let Some(trace) = map.get_mut("trace")
586            {
587                if context.is_masked_key("trace") {
588                    if !trace.is_null() {
589                        *trace = Value::String(REDACTED_MARKER.into());
590                    }
591                } else {
592                    redact_secrets_with_context(trace, context);
593                }
594            }
595        }
596        RedactionPolicy::Off => {}
597    }
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603    use serde_json::json;
604
605    // ── A node out of its document keeps its route ──────────
606
607    fn routed_document() -> Value {
608        json!({
609            "name": "console",
610            "endpoint_url": "https://reviewer:pw@h/?token_secret=t&page=2",
611            "mirror_url": [
612                "https://u:pw@a/",
613                {"nested": "https://u:pw@b/", "key_secret": "k", "plain": "mailto:x@y.z"}
614            ],
615            "vault_secret": {"inner": {"leaf": "x"}, "list": [1, 2], "gone": null},
616            "absent_secret": null,
617            "api_token": "configured-name",
618            "servers": [
619                {"name": "api_secret", "port": 1, "password_secret": "p", "hook_url": "https://u:pw@d/"}
620            ],
621            "trace": {"session_secret": "s", "callback_url": "https://u:pw@c/", "step": 3},
622            "shown_secret": "visible"
623        })
624    }
625
626    fn compare_nodes(redactor: &Redactor, raw: &Value, shown: &Value, route: &mut Vec<PathStep>) {
627        assert_eq!(redactor.value_at(route, raw), *shown, "{route:?}");
628        match raw {
629            Value::Object(map) => {
630                for (key, child) in map {
631                    route.push(PathStep::Field(key.clone()));
632                    compare_nodes(redactor, child, shown.get(key).unwrap_or(shown), route);
633                    route.pop();
634                }
635            }
636            Value::Array(items) => {
637                for (index, child) in items.iter().enumerate() {
638                    route.push(PathStep::Element);
639                    compare_nodes(redactor, child, shown.get(index).unwrap_or(shown), route);
640                    route.pop();
641                }
642            }
643            _ => {}
644        }
645    }
646
647    #[test]
648    fn a_routed_node_equals_the_same_node_in_the_redacted_whole() {
649        let document = routed_document();
650        for policy in [
651            RedactionPolicy::All,
652            RedactionPolicy::TraceOnly,
653            RedactionPolicy::Off,
654        ] {
655            let redactor = Redactor::new()
656                .policy(policy)
657                .secret_names(["api_token"])
658                .reveal_names(["shown_secret"]);
659            let whole = redactor.value(&document);
660            compare_nodes(&redactor, &document, &whole, &mut Vec::new());
661        }
662    }
663
664    #[test]
665    fn a_route_carries_secret_ancestors_url_fields_and_absent_secrets() {
666        let document = routed_document();
667        let redactor = Redactor::new().secret_names(["api_token"]);
668        let at = |path: &str| {
669            let document = crate::document::Value::from(document.clone());
670            let node =
671                crate::document::locate(&document, path, crate::document::Addressing::INDEX_ONLY)
672                    .unwrap();
673            let value = Value::try_from(node.value).unwrap();
674            (
675                redactor.value_at(&node.steps, &value),
676                redactor.is_secret_path(&node.steps),
677            )
678        };
679        let key = |name: &str| PathStep::Field(name.to_string());
680
681        // A child beneath a secret ancestor is hidden, even a null one.
682        assert_eq!(at("vault_secret.inner.leaf"), (json!("***"), true));
683        assert_eq!(at("vault_secret.list.0"), (json!("***"), true));
684        assert_eq!(at("vault_secret.gone"), (json!("***"), true));
685        // The secret field itself stays null when it is null.
686        assert_eq!(at("absent_secret"), (Value::Null, true));
687        // A configured exact name counts like the suffix.
688        assert_eq!(at("api_token"), (json!("***"), true));
689        // A URL field scrubs the selected string, and each element of a
690        // URL collection, without hiding the readable parts.
691        assert_eq!(
692            at("endpoint_url"),
693            (
694                json!("https://reviewer:***@h/?token_secret=***&page=2"),
695                false
696            )
697        );
698        assert_eq!(at("mirror_url.0"), (json!("https://u:***@a/"), false));
699        assert_eq!(
700            at("mirror_url.1.nested"),
701            (json!("https://u:***@b/"), false)
702        );
703        // A plain field is itself.
704        assert_eq!(at("name"), (json!("console"), false));
705        // Revealing a name lifts exactly that name.
706        let revealing = Redactor::new().reveal_names(["shown_secret"]);
707        assert_eq!(
708            revealing.value_at(&[key("shown_secret")], &json!("visible")),
709            json!("visible")
710        );
711        assert!(!revealing.is_secret_path(&[key("shown_secret")]));
712    }
713
714    #[test]
715    fn an_identifier_that_selects_an_element_is_data_not_a_field_name() {
716        use crate::document::{self, Addressing, KeyedList};
717        let source = document::Value::from(routed_document());
718        let lists = [KeyedList {
719            prefix: "servers",
720            slug_field: "name",
721        }];
722        let located =
723            document::locate(&source, "servers.api_secret", Addressing::keyed(&lists)).unwrap();
724        assert_eq!(
725            located.steps,
726            vec![PathStep::Field("servers".to_string()), PathStep::Element]
727        );
728        let redactor = Redactor::new();
729        assert!(!redactor.is_secret_path(&located.steps));
730        let element = Value::try_from(located.value).unwrap();
731        // The element's own keys still count.
732        assert_eq!(
733            redactor.value_at(&located.steps, &element),
734            json!({"name": "api_secret", "port": 1, "password_secret": "***", "hook_url": "https://u:***@d/"})
735        );
736
737        let located = document::locate(
738            &source,
739            "servers.api_secret.password_secret",
740            Addressing::keyed(&lists),
741        )
742        .unwrap();
743        assert!(redactor.is_secret_path(&located.steps));
744    }
745
746    #[test]
747    fn trace_only_judges_a_route_from_inside_trace() {
748        let redactor = Redactor::new().policy(RedactionPolicy::TraceOnly);
749        let key = |name: &str| PathStep::Field(name.to_string());
750        assert!(redactor.is_secret_path(&[key("trace"), key("session_secret")]));
751        assert!(!redactor.is_secret_path(&[key("result"), key("session_secret")]));
752        assert_eq!(
753            redactor.value_at(&[key("trace")], &json!({"session_secret": "s"})),
754            json!({"session_secret": "***"})
755        );
756        assert_eq!(
757            redactor.value_at(&[key("result"), key("session_secret")], &json!("s")),
758            json!("s")
759        );
760    }
761
762    #[test]
763    fn a_route_past_the_depth_bound_is_cut_like_the_whole() {
764        let mut document = json!("leaf");
765        for _ in 0..(MAX_DEPTH + 4) {
766            document = json!({ "k": document });
767        }
768        let redactor = Redactor::new();
769        let whole = redactor.value(&document);
770        compare_nodes(&redactor, &document, &whole, &mut Vec::new());
771    }
772
773    // ── URL fragments carry secrets too ──────────
774
775    #[test]
776    fn url_fragment_params_redacted_like_query_params() {
777        assert_eq!(
778            redact_url_secrets("https://h/p?token_secret=QUERYLEAK#token_secret=FRAGLEAK"),
779            "https://h/p?token_secret=***#token_secret=***"
780        );
781    }
782
783    #[test]
784    fn url_fragment_params_redacted_without_a_query() {
785        // The OAuth implicit-flow shape: the credential exists only after '#'.
786        assert_eq!(
787            redact_url_secrets("https://h/cb#access_token_secret=abc&state=xyz"),
788            "https://h/cb#access_token_secret=***&state=xyz"
789        );
790    }
791
792    #[test]
793    fn url_fragment_without_params_is_preserved() {
794        for url in [
795            "https://h/p?a=1#section",
796            "https://h/p#",
797            "https://h/p#a/b?c",
798        ] {
799            assert_eq!(redact_url_secrets(url), url);
800        }
801    }
802
803    #[test]
804    fn url_fragment_honors_secret_names() {
805        let redactor = Redactor::new().secret_names(vec!["token".to_string()]);
806        assert_eq!(
807            redactor.url("https://h/cb#token=abc&page=2"),
808            "https://h/cb#token=***&page=2"
809        );
810    }
811
812    #[test]
813    fn url_names_are_exact_and_recurse_through_collections() {
814        let redactor = Redactor::new().secret_names(["token"]).url_names([
815            "url",
816            "relays",
817            "synapse_selector",
818        ]);
819        let input = json!({
820            "url": "https://u:pw@h/?token=one",
821            "URL": "https://u:visible@h/?token=two",
822            "relays": [
823                "wss://relay.example/?token=three",
824                {"nested": "https://u:pw@nested.example/"}
825            ],
826            "synapse_selector": "user:pass@host/db",
827            "other": "https://u:visible@h/?token=four"
828        });
829
830        assert_eq!(
831            redactor.value(&input),
832            json!({
833                "url": "https://u:***@h/?token=***",
834                "URL": "https://u:visible@h/?token=two",
835                "relays": [
836                    "wss://relay.example/?token=***",
837                    {"nested": "https://u:***@nested.example/"}
838                ],
839                "synapse_selector": "***",
840                "other": "https://u:visible@h/?token=four"
841            })
842        );
843        assert!(redactor.is_url_name("url"));
844        assert!(!redactor.is_url_name("URL"));
845    }
846
847    #[test]
848    fn prose_url_redaction_is_explicit_and_preserves_punctuation() {
849        let message = "connect (https://u:pw@h/?token_secret=one), then wss://h/?token_secret=two. bare user:pw@h stays";
850        assert_eq!(
851            redact_urls_in_text(message),
852            "connect (https://u:***@h/?token_secret=***), then wss://h/?token_secret=***. bare user:pw@h stays"
853        );
854        assert_eq!(
855            redacted_value(&json!({"message": message})),
856            json!({"message": message})
857        );
858    }
859
860    #[test]
861    fn prose_url_redaction_honors_policy_and_secret_names() {
862        let text = "see https://h/?token=abc";
863        assert_eq!(
864            Redactor::new().secret_names(["token"]).urls_in_text(text),
865            "see https://h/?token=***"
866        );
867        assert_eq!(
868            Redactor::new()
869                .policy(RedactionPolicy::Off)
870                .secret_names(["token"])
871                .urls_in_text(text),
872            text
873        );
874    }
875
876    // ── One policy meaning across value, argv, url ──────────
877
878    fn scoped_value() -> Value {
879        json!({
880            "result": {"api_key_secret": "sk-result"},
881            "trace": {"api_key_secret": "sk-trace"}
882        })
883    }
884
885    fn argv() -> Vec<String> {
886        vec!["tool".to_string(), "--api-key-secret=sk-live".to_string()]
887    }
888
889    #[test]
890    fn all_policy_redacts_every_path() {
891        let redactor = Redactor::new().policy(RedactionPolicy::All);
892        assert_eq!(
893            redactor.value(&scoped_value()),
894            json!({
895                "result": {"api_key_secret": "***"},
896                "trace": {"api_key_secret": "***"}
897            })
898        );
899        assert_eq!(redactor.argv(&argv()), vec!["tool", "--api-key-secret=***"]);
900        assert_eq!(
901            redactor.url("https://u:pw@h/cb?token_secret=abc"),
902            "https://u:***@h/cb?token_secret=***"
903        );
904    }
905
906    #[test]
907    fn trace_only_scopes_a_value_but_redacts_argv_and_url_in_full() {
908        let redactor = Redactor::new().policy(RedactionPolicy::TraceOnly);
909        // Scoped input: only the `trace` half is scrubbed.
910        assert_eq!(
911            redactor.value(&scoped_value()),
912            json!({
913                "result": {"api_key_secret": "sk-result"},
914                "trace": {"api_key_secret": "***"}
915            })
916        );
917        // Unscoped input: a command line and a bare URL have no non-`trace`
918        // half to leave alone, so they are redacted like `All`.
919        assert_eq!(redactor.argv(&argv()), vec!["tool", "--api-key-secret=***"]);
920        assert_eq!(
921            redactor.url("https://u:pw@h/cb?token_secret=abc"),
922            "https://u:***@h/cb?token_secret=***"
923        );
924    }
925
926    #[test]
927    fn off_policy_disables_every_path() {
928        let redactor = Redactor::new().policy(RedactionPolicy::Off);
929        assert_eq!(redactor.value(&scoped_value()), scoped_value());
930        assert_eq!(redactor.argv(&argv()), argv());
931        assert_eq!(
932            redactor.url("https://u:pw@h/cb?token_secret=abc"),
933            "https://u:pw@h/cb?token_secret=abc"
934        );
935    }
936}