Skip to main content

agent_first_data/
redaction.rs

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