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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum RedactionPolicy {
22 #[default]
24 All,
25 TraceOnly,
27 Off,
29}
30
31impl RedactionPolicy {
32 fn redacts_unscoped_input(self) -> bool {
43 !matches!(self, RedactionPolicy::Off)
44 }
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub enum PlainStyle {
51 #[default]
53 Readable,
54 Raw,
56}
57
58#[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 pub fn new() -> Self {
75 Self::default()
76 }
77
78 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 #[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 #[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 pub fn policy(mut self, policy: RedactionPolicy) -> Self {
111 self.policy = policy;
112 self
113 }
114
115 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 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 pub fn redact_in_place_at(&self, path: &[PathStep], value: &mut Value) {
152 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 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 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 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 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 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 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 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 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 pub fn is_secret_name(&self, name: &str) -> bool {
322 RedactionContext::from_redactor(self).is_secret_key(name)
323 }
324
325 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
349pub struct OutputOptions {
350 pub redaction: Redactor,
352 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
365pub fn redacted_value(value: &Value) -> Value {
371 Redactor::new().value(value)
372}
373
374pub fn redact_argv<S: AsRef<str>>(args: &[S]) -> Vec<String> {
384 Redactor::new().argv(args)
385}
386
387pub fn redact_url_secrets(url: &str) -> String {
392 Redactor::new().url(url)
393}
394
395pub fn redact_urls_in_text(text: &str) -> String {
400 Redactor::new().urls_in_text(text)
401}
402
403pub(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 fn is_masked_key(&self, key: &str) -> bool {
440 self.is_secret_key(key) && !self.reveal_names.contains(key)
441 }
442}
443
444enum Route {
447 Masked { at_node: bool },
449 TooDeep,
451 Url,
453 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 if depth >= MAX_DEPTH {
463 return Route::TooDeep;
464 }
465 let PathStep::Field(key) = step else {
466 continue;
467 };
468 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
490pub(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 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
573fn 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 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 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 assert_eq!(at("absent_secret"), (Value::Null, true));
687 assert_eq!(at("api_token"), (json!("***"), true));
689 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 assert_eq!(at("name"), (json!("console"), false));
705 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 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 #[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 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 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 assert_eq!(
911 redactor.value(&scoped_value()),
912 json!({
913 "result": {"api_key_secret": "sk-result"},
914 "trace": {"api_key_secret": "***"}
915 })
916 );
917 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}