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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20pub enum RedactionPolicy {
21 #[default]
23 All,
24 TraceOnly,
26 Off,
28}
29
30impl RedactionPolicy {
31 fn redacts_unscoped_input(self) -> bool {
42 !matches!(self, RedactionPolicy::Off)
43 }
44}
45
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
49pub enum PlainStyle {
50 #[default]
52 Readable,
53 Raw,
55}
56
57#[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 pub fn new() -> Self {
74 Self::default()
75 }
76
77 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 #[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 #[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 pub fn policy(mut self, policy: RedactionPolicy) -> Self {
110 self.policy = policy;
111 self
112 }
113
114 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 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 pub fn redact_in_place_at(&self, path: &[PathStep], value: &mut Value) {
151 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 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 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 fn scope_of<'p>(&self, path: &'p [PathStep]) -> Option<&'p [PathStep]> {
193 match self.policy {
194 RedactionPolicy::All => Some(path),
195 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 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 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 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 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 pub fn is_secret_name(&self, name: &str) -> bool {
311 RedactionContext::from_redactor(self).is_secret_key(name)
312 }
313
314 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
338pub struct OutputOptions {
339 pub redaction: Redactor,
341 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
354pub fn redacted_value(value: &Value) -> Value {
360 Redactor::new().value(value)
361}
362
363pub fn redact_argv<S: AsRef<str>>(args: &[S]) -> Vec<String> {
373 Redactor::new().argv(args)
374}
375
376pub fn redact_url_secrets(url: &str) -> String {
381 Redactor::new().url(url)
382}
383
384pub fn redact_urls_in_text(text: &str) -> String {
389 Redactor::new().urls_in_text(text)
390}
391
392pub(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 fn is_masked_key(&self, key: &str) -> bool {
429 self.is_secret_key(key) && !self.reveal_names.contains(key)
430 }
431}
432
433enum Route {
436 Masked { at_node: bool },
438 TooDeep,
440 Url,
442 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 if depth >= MAX_DEPTH {
452 return Route::TooDeep;
453 }
454 let PathStep::Field(key) = step else {
455 continue;
456 };
457 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
479pub(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 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
562fn 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 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 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 assert_eq!(at("absent_secret"), (Value::Null, true));
670 assert_eq!(at("api_token"), (json!("***"), true));
672 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 assert_eq!(at("name"), (json!("console"), false));
688 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 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 #[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 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 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 assert_eq!(
894 redactor.value(&scoped_value()),
895 json!({
896 "result": {"api_key_secret": "sk-result"},
897 "trace": {"api_key_secret": "***"}
898 })
899 );
900 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}